_id
stringlengths 64
64
| repository
stringlengths 6
84
| name
stringlengths 4
110
| content
stringlengths 0
248k
| license
null | download_url
stringlengths 89
454
| language
stringclasses 7
values | comments
stringlengths 0
74.6k
| code
stringlengths 0
248k
|
---|---|---|---|---|---|---|---|---|
63ea7735814d1c1328dd29d4a4e984cd277ab37a3ed4cd2af36850ec4768fe57
|
sealchain-project/sealchain
|
Context.hs
|
# LANGUAGE ExistentialQuantification #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS -fno-warn-unused-top-binds #-} -- for lenses
-- | Runtime context of node.
module Pos.Context.Context
( HasNodeContext(..)
, HasSscContext(..)
, NodeContext (..)
, NodeParams(..)
, BaseParams(..)
, TxpGlobalSettings
, StartTime(..)
, BlockRetrievalQueueTag
, BlockRetrievalQueue
, ConnectedPeers(..)
) where
import Universum
import Control.Lens (lens, makeLensesWith)
import Data.Time.Clock (UTCTime)
import Pos.Chain.Block (HasSlogContext (..), HasSlogGState (..),
LastKnownHeader, LastKnownHeaderTag, SlogContext (..))
import Pos.Chain.Ssc (HasSscContext (..), SscContext)
import Pos.Communication.Types (NodeId)
import Pos.Core (HasPrimaryKey (..), Timestamp)
import Pos.Core.Reporting (HasMisbehaviorMetrics (..),
MisbehaviorMetrics (..))
import Pos.DB.Lrc (LrcContext)
import Pos.DB.Txp.Settings (TxpGlobalSettings)
import Pos.DB.Update (UpdateContext)
import Pos.Infra.DHT.Real.Param (KademliaParams)
import Pos.Infra.Network.Types (NetworkConfig (..))
import Pos.Infra.Recovery.Types (RecoveryHeader, RecoveryHeaderTag)
import Pos.Infra.Shutdown (HasShutdownContext (..),
ShutdownContext (..))
import Pos.Infra.Slotting (HasSlottingVar (..),
SimpleSlottingStateVar)
import Pos.Infra.Slotting.Types (SlottingData)
import Pos.Infra.StateLock (StateLock, StateLockMetrics)
import Pos.Infra.Util.JsonLog.Events (MemPoolModifyReason (..))
import Pos.Launcher.Param (BaseParams (..), NodeParams (..))
import Pos.Network.Block.RetrievalQueue (BlockRetrievalQueue,
BlockRetrievalQueueTag)
import Pos.Util.Lens (postfixLFields)
import Pos.Util.UserSecret (HasUserSecret (..), UserSecret)
import Pos.Util.Util (HasLens (..))
import Pos.Util.Wlog (LoggerConfig)
----------------------------------------------------------------------------
NodeContext
----------------------------------------------------------------------------
newtype ConnectedPeers = ConnectedPeers { unConnectedPeers :: TVar (Set NodeId) }
newtype StartTime = StartTime { unStartTime :: UTCTime }
data SscContextTag
| NodeContext contains runtime context of node .
data NodeContext = NodeContext
{ ncSscContext :: !SscContext
^ Context needed for Shared Seed Computation ( SSC ) .
, ncUpdateContext :: !UpdateContext
-- ^ Context needed for the update system
, ncLrcContext :: !LrcContext
-- ^ Context needed for LRC
, ncSlottingVar :: !(Timestamp, TVar SlottingData)
-- ^ Data necessary for 'MonadSlotsData'.
, ncSlottingContext :: !SimpleSlottingStateVar
-- ^ Context needed for Slotting.
, ncShutdownContext :: !ShutdownContext
-- ^ Context needed for Shutdown
, ncSlogContext :: !SlogContext
^ Context needed for Slog .
, ncStateLock :: !StateLock
-- ^ A lock which manages access to shared resources.
-- Stored hash is a hash of last applied block.
, ncStateLockMetrics :: !(StateLockMetrics MemPoolModifyReason)
^ A set of callbacks for ' StateLock ' .
, ncUserSecret :: !(TVar UserSecret)
-- ^ Secret keys (and path to file) which are used to send transactions
, ncBlockRetrievalQueue :: !BlockRetrievalQueue
-- ^ Concurrent queue that holds block headers that are to be
-- downloaded.
, ncRecoveryHeader :: !RecoveryHeader
-- ^ In case of recovery mode this variable holds the latest header hash
-- we know about, and the node we're talking to, so we can do chained
-- block requests. Invariant: this mvar is full iff we're in recovery mode
-- and downloading blocks. Every time we get block that's more
-- difficult than this one, we overwrite. Every time we process some
-- blocks and fail or see that we've downloaded this header, we clean
-- mvar.
, ncLastKnownHeader :: !LastKnownHeader
-- ^ Header of last known block, generated by network (announcement of
-- which reached us). Should be use only for informational purposes
-- (status in Daedalus). It's easy to falsify this value.
, ncLoggerConfig :: !LoggerConfig
-- ^ Logger config, as taken/read from CLI.
, ncNodeParams :: !NodeParams
-- ^ Params node is launched with
, ncStartTime :: !StartTime
^ Time when node was started ( ' NodeContext ' initialized ) .
, ncTxpGlobalSettings :: !TxpGlobalSettings
^ Settings for global Txp .
, ncConnectedPeers :: !ConnectedPeers
-- ^ Set of peers that we're connected to.
, ncNetworkConfig :: !(NetworkConfig KademliaParams)
, ncMisbehaviorMetrics :: Maybe MisbehaviorMetrics
}
makeLensesWith postfixLFields ''NodeContext
class HasNodeContext ctx where
nodeContext :: Lens' ctx NodeContext
instance HasNodeContext NodeContext where
nodeContext = identity
instance HasSscContext NodeContext where
sscContext = ncSscContext_L
instance HasSlottingVar NodeContext where
slottingTimestamp = ncSlottingVar_L . _1
slottingVar = ncSlottingVar_L . _2
instance HasSlogContext NodeContext where
slogContext = ncSlogContext_L
instance HasSlogGState NodeContext where
slogGState = ncSlogContext_L . slogGState
instance HasLens SimpleSlottingStateVar NodeContext SimpleSlottingStateVar where
lensOf = ncSlottingContext_L
instance HasLens StateLock NodeContext StateLock where
lensOf = ncStateLock_L
instance HasLens (StateLockMetrics MemPoolModifyReason) NodeContext (StateLockMetrics MemPoolModifyReason) where
lensOf = ncStateLockMetrics_L
instance HasLens LastKnownHeaderTag NodeContext LastKnownHeader where
lensOf = ncLastKnownHeader_L
instance HasShutdownContext NodeContext where
shutdownContext = ncShutdownContext_L
instance HasLens UpdateContext NodeContext UpdateContext where
lensOf = ncUpdateContext_L
instance HasUserSecret NodeContext where
userSecret = ncUserSecret_L
instance HasLens RecoveryHeaderTag NodeContext RecoveryHeader where
lensOf = ncRecoveryHeader_L
instance HasLens ConnectedPeers NodeContext ConnectedPeers where
lensOf = ncConnectedPeers_L
instance HasLens BlockRetrievalQueueTag NodeContext BlockRetrievalQueue where
lensOf = ncBlockRetrievalQueue_L
instance HasLens StartTime NodeContext StartTime where
lensOf = ncStartTime_L
instance HasLens LrcContext NodeContext LrcContext where
lensOf = ncLrcContext_L
instance HasLens TxpGlobalSettings NodeContext TxpGlobalSettings where
lensOf = ncTxpGlobalSettings_L
instance {-# OVERLAPPABLE #-}
HasLens tag NodeParams r =>
HasLens tag NodeContext r
where
lensOf = ncNodeParams_L . lensOf @tag
instance HasPrimaryKey NodeContext where
primaryKey = ncNodeParams_L . primaryKey
instance HasMisbehaviorMetrics NodeContext where
misbehaviorMetrics = lens getter (flip setter)
where
getter nc = nc ^. ncMisbehaviorMetrics_L
setter mm = set ncMisbehaviorMetrics_L mm
instance HasLens (NetworkConfig KademliaParams) NodeContext (NetworkConfig KademliaParams) where
lensOf = ncNetworkConfig_L
| null |
https://raw.githubusercontent.com/sealchain-project/sealchain/e97b4bac865fb147979cb14723a12c716a62e51e/lib/src/Pos/Context/Context.hs
|
haskell
|
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# OPTIONS -fno-warn-unused-top-binds #
for lenses
| Runtime context of node.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
^ Context needed for the update system
^ Context needed for LRC
^ Data necessary for 'MonadSlotsData'.
^ Context needed for Slotting.
^ Context needed for Shutdown
^ A lock which manages access to shared resources.
Stored hash is a hash of last applied block.
^ Secret keys (and path to file) which are used to send transactions
^ Concurrent queue that holds block headers that are to be
downloaded.
^ In case of recovery mode this variable holds the latest header hash
we know about, and the node we're talking to, so we can do chained
block requests. Invariant: this mvar is full iff we're in recovery mode
and downloading blocks. Every time we get block that's more
difficult than this one, we overwrite. Every time we process some
blocks and fail or see that we've downloaded this header, we clean
mvar.
^ Header of last known block, generated by network (announcement of
which reached us). Should be use only for informational purposes
(status in Daedalus). It's easy to falsify this value.
^ Logger config, as taken/read from CLI.
^ Params node is launched with
^ Set of peers that we're connected to.
# OVERLAPPABLE #
|
# LANGUAGE ExistentialQuantification #
module Pos.Context.Context
( HasNodeContext(..)
, HasSscContext(..)
, NodeContext (..)
, NodeParams(..)
, BaseParams(..)
, TxpGlobalSettings
, StartTime(..)
, BlockRetrievalQueueTag
, BlockRetrievalQueue
, ConnectedPeers(..)
) where
import Universum
import Control.Lens (lens, makeLensesWith)
import Data.Time.Clock (UTCTime)
import Pos.Chain.Block (HasSlogContext (..), HasSlogGState (..),
LastKnownHeader, LastKnownHeaderTag, SlogContext (..))
import Pos.Chain.Ssc (HasSscContext (..), SscContext)
import Pos.Communication.Types (NodeId)
import Pos.Core (HasPrimaryKey (..), Timestamp)
import Pos.Core.Reporting (HasMisbehaviorMetrics (..),
MisbehaviorMetrics (..))
import Pos.DB.Lrc (LrcContext)
import Pos.DB.Txp.Settings (TxpGlobalSettings)
import Pos.DB.Update (UpdateContext)
import Pos.Infra.DHT.Real.Param (KademliaParams)
import Pos.Infra.Network.Types (NetworkConfig (..))
import Pos.Infra.Recovery.Types (RecoveryHeader, RecoveryHeaderTag)
import Pos.Infra.Shutdown (HasShutdownContext (..),
ShutdownContext (..))
import Pos.Infra.Slotting (HasSlottingVar (..),
SimpleSlottingStateVar)
import Pos.Infra.Slotting.Types (SlottingData)
import Pos.Infra.StateLock (StateLock, StateLockMetrics)
import Pos.Infra.Util.JsonLog.Events (MemPoolModifyReason (..))
import Pos.Launcher.Param (BaseParams (..), NodeParams (..))
import Pos.Network.Block.RetrievalQueue (BlockRetrievalQueue,
BlockRetrievalQueueTag)
import Pos.Util.Lens (postfixLFields)
import Pos.Util.UserSecret (HasUserSecret (..), UserSecret)
import Pos.Util.Util (HasLens (..))
import Pos.Util.Wlog (LoggerConfig)
NodeContext
newtype ConnectedPeers = ConnectedPeers { unConnectedPeers :: TVar (Set NodeId) }
newtype StartTime = StartTime { unStartTime :: UTCTime }
data SscContextTag
| NodeContext contains runtime context of node .
data NodeContext = NodeContext
{ ncSscContext :: !SscContext
^ Context needed for Shared Seed Computation ( SSC ) .
, ncUpdateContext :: !UpdateContext
, ncLrcContext :: !LrcContext
, ncSlottingVar :: !(Timestamp, TVar SlottingData)
, ncSlottingContext :: !SimpleSlottingStateVar
, ncShutdownContext :: !ShutdownContext
, ncSlogContext :: !SlogContext
^ Context needed for Slog .
, ncStateLock :: !StateLock
, ncStateLockMetrics :: !(StateLockMetrics MemPoolModifyReason)
^ A set of callbacks for ' StateLock ' .
, ncUserSecret :: !(TVar UserSecret)
, ncBlockRetrievalQueue :: !BlockRetrievalQueue
, ncRecoveryHeader :: !RecoveryHeader
, ncLastKnownHeader :: !LastKnownHeader
, ncLoggerConfig :: !LoggerConfig
, ncNodeParams :: !NodeParams
, ncStartTime :: !StartTime
^ Time when node was started ( ' NodeContext ' initialized ) .
, ncTxpGlobalSettings :: !TxpGlobalSettings
^ Settings for global Txp .
, ncConnectedPeers :: !ConnectedPeers
, ncNetworkConfig :: !(NetworkConfig KademliaParams)
, ncMisbehaviorMetrics :: Maybe MisbehaviorMetrics
}
makeLensesWith postfixLFields ''NodeContext
class HasNodeContext ctx where
nodeContext :: Lens' ctx NodeContext
instance HasNodeContext NodeContext where
nodeContext = identity
instance HasSscContext NodeContext where
sscContext = ncSscContext_L
instance HasSlottingVar NodeContext where
slottingTimestamp = ncSlottingVar_L . _1
slottingVar = ncSlottingVar_L . _2
instance HasSlogContext NodeContext where
slogContext = ncSlogContext_L
instance HasSlogGState NodeContext where
slogGState = ncSlogContext_L . slogGState
instance HasLens SimpleSlottingStateVar NodeContext SimpleSlottingStateVar where
lensOf = ncSlottingContext_L
instance HasLens StateLock NodeContext StateLock where
lensOf = ncStateLock_L
instance HasLens (StateLockMetrics MemPoolModifyReason) NodeContext (StateLockMetrics MemPoolModifyReason) where
lensOf = ncStateLockMetrics_L
instance HasLens LastKnownHeaderTag NodeContext LastKnownHeader where
lensOf = ncLastKnownHeader_L
instance HasShutdownContext NodeContext where
shutdownContext = ncShutdownContext_L
instance HasLens UpdateContext NodeContext UpdateContext where
lensOf = ncUpdateContext_L
instance HasUserSecret NodeContext where
userSecret = ncUserSecret_L
instance HasLens RecoveryHeaderTag NodeContext RecoveryHeader where
lensOf = ncRecoveryHeader_L
instance HasLens ConnectedPeers NodeContext ConnectedPeers where
lensOf = ncConnectedPeers_L
instance HasLens BlockRetrievalQueueTag NodeContext BlockRetrievalQueue where
lensOf = ncBlockRetrievalQueue_L
instance HasLens StartTime NodeContext StartTime where
lensOf = ncStartTime_L
instance HasLens LrcContext NodeContext LrcContext where
lensOf = ncLrcContext_L
instance HasLens TxpGlobalSettings NodeContext TxpGlobalSettings where
lensOf = ncTxpGlobalSettings_L
HasLens tag NodeParams r =>
HasLens tag NodeContext r
where
lensOf = ncNodeParams_L . lensOf @tag
instance HasPrimaryKey NodeContext where
primaryKey = ncNodeParams_L . primaryKey
instance HasMisbehaviorMetrics NodeContext where
misbehaviorMetrics = lens getter (flip setter)
where
getter nc = nc ^. ncMisbehaviorMetrics_L
setter mm = set ncMisbehaviorMetrics_L mm
instance HasLens (NetworkConfig KademliaParams) NodeContext (NetworkConfig KademliaParams) where
lensOf = ncNetworkConfig_L
|
b63a7b44a0fe0e98044f24d33c5528261e4507ad6370ccc3d31175527490715a
|
clojure-interop/aws-api
|
AbstractAWSWAF.clj
|
(ns com.amazonaws.services.waf.AbstractAWSWAF
"Abstract implementation of AWSWAF. Convenient method forms pass through to the corresponding overload that
takes a request object, which throws an UnsupportedOperationException."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.waf AbstractAWSWAF]))
(defn delete-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRuleGroupRequest`
returns: Result of the DeleteRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRuleGroupResult`"
(^com.amazonaws.services.waf.model.DeleteRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRuleGroupRequest request]
(-> this (.deleteRuleGroup request))))
(defn get-rate-based-rule-managed-keys
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRateBasedRuleManagedKeysRequest`
returns: Result of the GetRateBasedRuleManagedKeys operation returned by the service. - `com.amazonaws.services.waf.model.GetRateBasedRuleManagedKeysResult`"
(^com.amazonaws.services.waf.model.GetRateBasedRuleManagedKeysResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRateBasedRuleManagedKeysRequest request]
(-> this (.getRateBasedRuleManagedKeys request))))
(defn get-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRuleRequest`
returns: Result of the GetRule operation returned by the service. - `com.amazonaws.services.waf.model.GetRuleResult`"
(^com.amazonaws.services.waf.model.GetRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRuleRequest request]
(-> this (.getRule request))))
(defn list-tags-for-resource
"request - `com.amazonaws.services.waf.model.ListTagsForResourceRequest`
returns: Result of the ListTagsForResource operation returned by the service. - `com.amazonaws.services.waf.model.ListTagsForResourceResult`"
(^com.amazonaws.services.waf.model.ListTagsForResourceResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListTagsForResourceRequest request]
(-> this (.listTagsForResource request))))
(defn update-sql-injection-match-set
"Description copied from interface: AWSWAF
request - A request to update a SqlInjectionMatchSet. - `com.amazonaws.services.waf.model.UpdateSqlInjectionMatchSetRequest`
returns: Result of the UpdateSqlInjectionMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateSqlInjectionMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateSqlInjectionMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateSqlInjectionMatchSetRequest request]
(-> this (.updateSqlInjectionMatchSet request))))
(defn get-logging-configuration
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetLoggingConfigurationRequest`
returns: Result of the GetLoggingConfiguration operation returned by the service. - `com.amazonaws.services.waf.model.GetLoggingConfigurationResult`"
(^com.amazonaws.services.waf.model.GetLoggingConfigurationResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetLoggingConfigurationRequest request]
(-> this (.getLoggingConfiguration request))))
(defn set-region
"Description copied from interface: AWSWAF
region - The region this client will communicate with. See Region.getRegion(com.amazonaws.regions.Regions) for accessing a given region. Must not be null and must be a region where the service is available. - `com.amazonaws.regions.Region`"
([^AbstractAWSWAF this ^com.amazonaws.regions.Region region]
(-> this (.setRegion region))))
(defn delete-byte-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteByteMatchSetRequest`
returns: Result of the DeleteByteMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteByteMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteByteMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteByteMatchSetRequest request]
(-> this (.deleteByteMatchSet request))))
(defn delete-permission-policy
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeletePermissionPolicyRequest`
returns: Result of the DeletePermissionPolicy operation returned by the service. - `com.amazonaws.services.waf.model.DeletePermissionPolicyResult`"
(^com.amazonaws.services.waf.model.DeletePermissionPolicyResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeletePermissionPolicyRequest request]
(-> this (.deletePermissionPolicy request))))
(defn create-regex-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRegexMatchSetRequest`
returns: Result of the CreateRegexMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateRegexMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateRegexMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRegexMatchSetRequest request]
(-> this (.createRegexMatchSet request))))
(defn list-ip-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListIPSetsRequest`
returns: Result of the ListIPSets operation returned by the service. - `com.amazonaws.services.waf.model.ListIPSetsResult`"
(^com.amazonaws.services.waf.model.ListIPSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListIPSetsRequest request]
(-> this (.listIPSets request))))
(defn list-regex-pattern-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRegexPatternSetsRequest`
returns: Result of the ListRegexPatternSets operation returned by the service. - `com.amazonaws.services.waf.model.ListRegexPatternSetsResult`"
(^com.amazonaws.services.waf.model.ListRegexPatternSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRegexPatternSetsRequest request]
(-> this (.listRegexPatternSets request))))
(defn delete-regex-pattern-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRegexPatternSetRequest`
returns: Result of the DeleteRegexPatternSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRegexPatternSetResult`"
(^com.amazonaws.services.waf.model.DeleteRegexPatternSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRegexPatternSetRequest request]
(-> this (.deleteRegexPatternSet request))))
(defn list-web-ac-ls
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListWebACLsRequest`
returns: Result of the ListWebACLs operation returned by the service. - `com.amazonaws.services.waf.model.ListWebACLsResult`"
(^com.amazonaws.services.waf.model.ListWebACLsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListWebACLsRequest request]
(-> this (.listWebACLs request))))
(defn get-regex-pattern-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRegexPatternSetRequest`
returns: Result of the GetRegexPatternSet operation returned by the service. - `com.amazonaws.services.waf.model.GetRegexPatternSetResult`"
(^com.amazonaws.services.waf.model.GetRegexPatternSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRegexPatternSetRequest request]
(-> this (.getRegexPatternSet request))))
(defn update-size-constraint-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateSizeConstraintSetRequest`
returns: Result of the UpdateSizeConstraintSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateSizeConstraintSetResult`"
(^com.amazonaws.services.waf.model.UpdateSizeConstraintSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateSizeConstraintSetRequest request]
(-> this (.updateSizeConstraintSet request))))
(defn create-sql-injection-match-set
"Description copied from interface: AWSWAF
request - A request to create a SqlInjectionMatchSet. - `com.amazonaws.services.waf.model.CreateSqlInjectionMatchSetRequest`
returns: Result of the CreateSqlInjectionMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateSqlInjectionMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateSqlInjectionMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateSqlInjectionMatchSetRequest request]
(-> this (.createSqlInjectionMatchSet request))))
(defn delete-sql-injection-match-set
"Description copied from interface: AWSWAF
request - A request to delete a SqlInjectionMatchSet from AWS WAF. - `com.amazonaws.services.waf.model.DeleteSqlInjectionMatchSetRequest`
returns: Result of the DeleteSqlInjectionMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteSqlInjectionMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteSqlInjectionMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteSqlInjectionMatchSetRequest request]
(-> this (.deleteSqlInjectionMatchSet request))))
(defn get-size-constraint-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetSizeConstraintSetRequest`
returns: Result of the GetSizeConstraintSet operation returned by the service. - `com.amazonaws.services.waf.model.GetSizeConstraintSetResult`"
(^com.amazonaws.services.waf.model.GetSizeConstraintSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetSizeConstraintSetRequest request]
(-> this (.getSizeConstraintSet request))))
(defn delete-xss-match-set
"Description copied from interface: AWSWAF
request - A request to delete an XssMatchSet from AWS WAF. - `com.amazonaws.services.waf.model.DeleteXssMatchSetRequest`
returns: Result of the DeleteXssMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteXssMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteXssMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteXssMatchSetRequest request]
(-> this (.deleteXssMatchSet request))))
(defn create-geo-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateGeoMatchSetRequest`
returns: Result of the CreateGeoMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateGeoMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateGeoMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateGeoMatchSetRequest request]
(-> this (.createGeoMatchSet request))))
(defn untag-resource
"request - `com.amazonaws.services.waf.model.UntagResourceRequest`
returns: Result of the UntagResource operation returned by the service. - `com.amazonaws.services.waf.model.UntagResourceResult`"
(^com.amazonaws.services.waf.model.UntagResourceResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UntagResourceRequest request]
(-> this (.untagResource request))))
(defn update-ip-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateIPSetRequest`
returns: Result of the UpdateIPSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateIPSetResult`"
(^com.amazonaws.services.waf.model.UpdateIPSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateIPSetRequest request]
(-> this (.updateIPSet request))))
(defn update-web-acl
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateWebACLRequest`
returns: Result of the UpdateWebACL operation returned by the service. - `com.amazonaws.services.waf.model.UpdateWebACLResult`"
(^com.amazonaws.services.waf.model.UpdateWebACLResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateWebACLRequest request]
(-> this (.updateWebACL request))))
(defn update-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRuleGroupRequest`
returns: Result of the UpdateRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRuleGroupResult`"
(^com.amazonaws.services.waf.model.UpdateRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRuleGroupRequest request]
(-> this (.updateRuleGroup request))))
(defn delete-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRuleRequest`
returns: Result of the DeleteRule operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRuleResult`"
(^com.amazonaws.services.waf.model.DeleteRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRuleRequest request]
(-> this (.deleteRule request))))
(defn delete-regex-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRegexMatchSetRequest`
returns: Result of the DeleteRegexMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRegexMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteRegexMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRegexMatchSetRequest request]
(-> this (.deleteRegexMatchSet request))))
(defn update-xss-match-set
"Description copied from interface: AWSWAF
request - A request to update an XssMatchSet. - `com.amazonaws.services.waf.model.UpdateXssMatchSetRequest`
returns: Result of the UpdateXssMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateXssMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateXssMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateXssMatchSetRequest request]
(-> this (.updateXssMatchSet request))))
(defn delete-geo-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteGeoMatchSetRequest`
returns: Result of the DeleteGeoMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteGeoMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteGeoMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteGeoMatchSetRequest request]
(-> this (.deleteGeoMatchSet request))))
(defn update-regex-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRegexMatchSetRequest`
returns: Result of the UpdateRegexMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRegexMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateRegexMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRegexMatchSetRequest request]
(-> this (.updateRegexMatchSet request))))
(defn get-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRuleGroupRequest`
returns: Result of the GetRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.GetRuleGroupResult`"
(^com.amazonaws.services.waf.model.GetRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRuleGroupRequest request]
(-> this (.getRuleGroup request))))
(defn create-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRuleGroupRequest`
returns: Result of the CreateRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.CreateRuleGroupResult`"
(^com.amazonaws.services.waf.model.CreateRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRuleGroupRequest request]
(-> this (.createRuleGroup request))))
(defn get-change-token-status
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetChangeTokenStatusRequest`
returns: Result of the GetChangeTokenStatus operation returned by the service. - `com.amazonaws.services.waf.model.GetChangeTokenStatusResult`"
(^com.amazonaws.services.waf.model.GetChangeTokenStatusResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetChangeTokenStatusRequest request]
(-> this (.getChangeTokenStatus request))))
(defn get-regex-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRegexMatchSetRequest`
returns: Result of the GetRegexMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetRegexMatchSetResult`"
(^com.amazonaws.services.waf.model.GetRegexMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRegexMatchSetRequest request]
(-> this (.getRegexMatchSet request))))
(defn create-byte-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateByteMatchSetRequest`
returns: Result of the CreateByteMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateByteMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateByteMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateByteMatchSetRequest request]
(-> this (.createByteMatchSet request))))
(defn list-size-constraint-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListSizeConstraintSetsRequest`
returns: Result of the ListSizeConstraintSets operation returned by the service. - `com.amazonaws.services.waf.model.ListSizeConstraintSetsResult`"
(^com.amazonaws.services.waf.model.ListSizeConstraintSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListSizeConstraintSetsRequest request]
(-> this (.listSizeConstraintSets request))))
(defn shutdown
"Description copied from interface: AWSWAF"
([^AbstractAWSWAF this]
(-> this (.shutdown))))
(defn update-byte-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateByteMatchSetRequest`
returns: Result of the UpdateByteMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateByteMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateByteMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateByteMatchSetRequest request]
(-> this (.updateByteMatchSet request))))
(defn list-geo-match-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListGeoMatchSetsRequest`
returns: Result of the ListGeoMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListGeoMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListGeoMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListGeoMatchSetsRequest request]
(-> this (.listGeoMatchSets request))))
(defn get-change-token
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetChangeTokenRequest`
returns: Result of the GetChangeToken operation returned by the service. - `com.amazonaws.services.waf.model.GetChangeTokenResult`"
(^com.amazonaws.services.waf.model.GetChangeTokenResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetChangeTokenRequest request]
(-> this (.getChangeToken request))))
(defn delete-size-constraint-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteSizeConstraintSetRequest`
returns: Result of the DeleteSizeConstraintSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteSizeConstraintSetResult`"
(^com.amazonaws.services.waf.model.DeleteSizeConstraintSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteSizeConstraintSetRequest request]
(-> this (.deleteSizeConstraintSet request))))
(defn get-sql-injection-match-set
"Description copied from interface: AWSWAF
request - A request to get a SqlInjectionMatchSet. - `com.amazonaws.services.waf.model.GetSqlInjectionMatchSetRequest`
returns: Result of the GetSqlInjectionMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetSqlInjectionMatchSetResult`"
(^com.amazonaws.services.waf.model.GetSqlInjectionMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetSqlInjectionMatchSetRequest request]
(-> this (.getSqlInjectionMatchSet request))))
(defn list-subscribed-rule-groups
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListSubscribedRuleGroupsRequest`
returns: Result of the ListSubscribedRuleGroups operation returned by the service. - `com.amazonaws.services.waf.model.ListSubscribedRuleGroupsResult`"
(^com.amazonaws.services.waf.model.ListSubscribedRuleGroupsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListSubscribedRuleGroupsRequest request]
(-> this (.listSubscribedRuleGroups request))))
(defn list-rule-groups
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRuleGroupsRequest`
returns: Result of the ListRuleGroups operation returned by the service. - `com.amazonaws.services.waf.model.ListRuleGroupsResult`"
(^com.amazonaws.services.waf.model.ListRuleGroupsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRuleGroupsRequest request]
(-> this (.listRuleGroups request))))
(defn create-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRuleRequest`
returns: Result of the CreateRule operation returned by the service. - `com.amazonaws.services.waf.model.CreateRuleResult`"
(^com.amazonaws.services.waf.model.CreateRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRuleRequest request]
(-> this (.createRule request))))
(defn get-xss-match-set
"Description copied from interface: AWSWAF
request - A request to get an XssMatchSet. - `com.amazonaws.services.waf.model.GetXssMatchSetRequest`
returns: Result of the GetXssMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetXssMatchSetResult`"
(^com.amazonaws.services.waf.model.GetXssMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetXssMatchSetRequest request]
(-> this (.getXssMatchSet request))))
(defn set-endpoint
"Description copied from interface: AWSWAF
endpoint - The endpoint (ex: \"waf.amazonaws.com/\") or a full URL, including the protocol (ex: \"/\") of the region specific AWS endpoint this client will communicate with. - `java.lang.String`"
([^AbstractAWSWAF this ^java.lang.String endpoint]
(-> this (.setEndpoint endpoint))))
(defn update-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRuleRequest`
returns: Result of the UpdateRule operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRuleResult`"
(^com.amazonaws.services.waf.model.UpdateRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRuleRequest request]
(-> this (.updateRule request))))
(defn delete-web-acl
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteWebACLRequest`
returns: Result of the DeleteWebACL operation returned by the service. - `com.amazonaws.services.waf.model.DeleteWebACLResult`"
(^com.amazonaws.services.waf.model.DeleteWebACLResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteWebACLRequest request]
(-> this (.deleteWebACL request))))
(defn update-regex-pattern-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRegexPatternSetRequest`
returns: Result of the UpdateRegexPatternSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRegexPatternSetResult`"
(^com.amazonaws.services.waf.model.UpdateRegexPatternSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRegexPatternSetRequest request]
(-> this (.updateRegexPatternSet request))))
(defn list-rate-based-rules
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRateBasedRulesRequest`
returns: Result of the ListRateBasedRules operation returned by the service. - `com.amazonaws.services.waf.model.ListRateBasedRulesResult`"
(^com.amazonaws.services.waf.model.ListRateBasedRulesResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRateBasedRulesRequest request]
(-> this (.listRateBasedRules request))))
(defn update-rate-based-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRateBasedRuleRequest`
returns: Result of the UpdateRateBasedRule operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRateBasedRuleResult`"
(^com.amazonaws.services.waf.model.UpdateRateBasedRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRateBasedRuleRequest request]
(-> this (.updateRateBasedRule request))))
(defn put-permission-policy
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.PutPermissionPolicyRequest`
returns: Result of the PutPermissionPolicy operation returned by the service. - `com.amazonaws.services.waf.model.PutPermissionPolicyResult`"
(^com.amazonaws.services.waf.model.PutPermissionPolicyResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.PutPermissionPolicyRequest request]
(-> this (.putPermissionPolicy request))))
(defn delete-rate-based-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRateBasedRuleRequest`
returns: Result of the DeleteRateBasedRule operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRateBasedRuleResult`"
(^com.amazonaws.services.waf.model.DeleteRateBasedRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRateBasedRuleRequest request]
(-> this (.deleteRateBasedRule request))))
(defn list-sql-injection-match-sets
"Description copied from interface: AWSWAF
request - A request to list the SqlInjectionMatchSet objects created by the current AWS account. - `com.amazonaws.services.waf.model.ListSqlInjectionMatchSetsRequest`
returns: Result of the ListSqlInjectionMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListSqlInjectionMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListSqlInjectionMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListSqlInjectionMatchSetsRequest request]
(-> this (.listSqlInjectionMatchSets request))))
(defn get-geo-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetGeoMatchSetRequest`
returns: Result of the GetGeoMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetGeoMatchSetResult`"
(^com.amazonaws.services.waf.model.GetGeoMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetGeoMatchSetRequest request]
(-> this (.getGeoMatchSet request))))
(defn get-ip-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetIPSetRequest`
returns: Result of the GetIPSet operation returned by the service. - `com.amazonaws.services.waf.model.GetIPSetResult`"
(^com.amazonaws.services.waf.model.GetIPSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetIPSetRequest request]
(-> this (.getIPSet request))))
(defn get-rate-based-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRateBasedRuleRequest`
returns: Result of the GetRateBasedRule operation returned by the service. - `com.amazonaws.services.waf.model.GetRateBasedRuleResult`"
(^com.amazonaws.services.waf.model.GetRateBasedRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRateBasedRuleRequest request]
(-> this (.getRateBasedRule request))))
(defn put-logging-configuration
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.PutLoggingConfigurationRequest`
returns: Result of the PutLoggingConfiguration operation returned by the service. - `com.amazonaws.services.waf.model.PutLoggingConfigurationResult`"
(^com.amazonaws.services.waf.model.PutLoggingConfigurationResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.PutLoggingConfigurationRequest request]
(-> this (.putLoggingConfiguration request))))
(defn list-activated-rules-in-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListActivatedRulesInRuleGroupRequest`
returns: Result of the ListActivatedRulesInRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.ListActivatedRulesInRuleGroupResult`"
(^com.amazonaws.services.waf.model.ListActivatedRulesInRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListActivatedRulesInRuleGroupRequest request]
(-> this (.listActivatedRulesInRuleGroup request))))
(defn delete-logging-configuration
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteLoggingConfigurationRequest`
returns: Result of the DeleteLoggingConfiguration operation returned by the service. - `com.amazonaws.services.waf.model.DeleteLoggingConfigurationResult`"
(^com.amazonaws.services.waf.model.DeleteLoggingConfigurationResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteLoggingConfigurationRequest request]
(-> this (.deleteLoggingConfiguration request))))
(defn list-byte-match-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListByteMatchSetsRequest`
returns: Result of the ListByteMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListByteMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListByteMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListByteMatchSetsRequest request]
(-> this (.listByteMatchSets request))))
(defn get-sampled-requests
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetSampledRequestsRequest`
returns: Result of the GetSampledRequests operation returned by the service. - `com.amazonaws.services.waf.model.GetSampledRequestsResult`"
(^com.amazonaws.services.waf.model.GetSampledRequestsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetSampledRequestsRequest request]
(-> this (.getSampledRequests request))))
(defn list-xss-match-sets
"Description copied from interface: AWSWAF
request - A request to list the XssMatchSet objects created by the current AWS account. - `com.amazonaws.services.waf.model.ListXssMatchSetsRequest`
returns: Result of the ListXssMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListXssMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListXssMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListXssMatchSetsRequest request]
(-> this (.listXssMatchSets request))))
(defn list-regex-match-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRegexMatchSetsRequest`
returns: Result of the ListRegexMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListRegexMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListRegexMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRegexMatchSetsRequest request]
(-> this (.listRegexMatchSets request))))
(defn get-cached-response-metadata
"Description copied from interface: AWSWAF
request - The originally executed request. - `com.amazonaws.AmazonWebServiceRequest`
returns: The response metadata for the specified request, or null if none is available. - `com.amazonaws.ResponseMetadata`"
(^com.amazonaws.ResponseMetadata [^AbstractAWSWAF this ^com.amazonaws.AmazonWebServiceRequest request]
(-> this (.getCachedResponseMetadata request))))
(defn get-web-acl
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetWebACLRequest`
returns: Result of the GetWebACL operation returned by the service. - `com.amazonaws.services.waf.model.GetWebACLResult`"
(^com.amazonaws.services.waf.model.GetWebACLResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetWebACLRequest request]
(-> this (.getWebACL request))))
(defn get-permission-policy
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetPermissionPolicyRequest`
returns: Result of the GetPermissionPolicy operation returned by the service. - `com.amazonaws.services.waf.model.GetPermissionPolicyResult`"
(^com.amazonaws.services.waf.model.GetPermissionPolicyResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetPermissionPolicyRequest request]
(-> this (.getPermissionPolicy request))))
(defn create-xss-match-set
"Description copied from interface: AWSWAF
request - A request to create an XssMatchSet. - `com.amazonaws.services.waf.model.CreateXssMatchSetRequest`
returns: Result of the CreateXssMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateXssMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateXssMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateXssMatchSetRequest request]
(-> this (.createXssMatchSet request))))
(defn create-regex-pattern-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRegexPatternSetRequest`
returns: Result of the CreateRegexPatternSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateRegexPatternSetResult`"
(^com.amazonaws.services.waf.model.CreateRegexPatternSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRegexPatternSetRequest request]
(-> this (.createRegexPatternSet request))))
(defn list-rules
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRulesRequest`
returns: Result of the ListRules operation returned by the service. - `com.amazonaws.services.waf.model.ListRulesResult`"
(^com.amazonaws.services.waf.model.ListRulesResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRulesRequest request]
(-> this (.listRules request))))
(defn create-ip-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateIPSetRequest`
returns: Result of the CreateIPSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateIPSetResult`"
(^com.amazonaws.services.waf.model.CreateIPSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateIPSetRequest request]
(-> this (.createIPSet request))))
(defn tag-resource
"request - `com.amazonaws.services.waf.model.TagResourceRequest`
returns: Result of the TagResource operation returned by the service. - `com.amazonaws.services.waf.model.TagResourceResult`"
(^com.amazonaws.services.waf.model.TagResourceResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.TagResourceRequest request]
(-> this (.tagResource request))))
(defn create-size-constraint-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateSizeConstraintSetRequest`
returns: Result of the CreateSizeConstraintSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateSizeConstraintSetResult`"
(^com.amazonaws.services.waf.model.CreateSizeConstraintSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateSizeConstraintSetRequest request]
(-> this (.createSizeConstraintSet request))))
(defn update-geo-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateGeoMatchSetRequest`
returns: Result of the UpdateGeoMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateGeoMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateGeoMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateGeoMatchSetRequest request]
(-> this (.updateGeoMatchSet request))))
(defn list-logging-configurations
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListLoggingConfigurationsRequest`
returns: Result of the ListLoggingConfigurations operation returned by the service. - `com.amazonaws.services.waf.model.ListLoggingConfigurationsResult`"
(^com.amazonaws.services.waf.model.ListLoggingConfigurationsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListLoggingConfigurationsRequest request]
(-> this (.listLoggingConfigurations request))))
(defn create-web-acl
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateWebACLRequest`
returns: Result of the CreateWebACL operation returned by the service. - `com.amazonaws.services.waf.model.CreateWebACLResult`"
(^com.amazonaws.services.waf.model.CreateWebACLResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateWebACLRequest request]
(-> this (.createWebACL request))))
(defn get-byte-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetByteMatchSetRequest`
returns: Result of the GetByteMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetByteMatchSetResult`"
(^com.amazonaws.services.waf.model.GetByteMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetByteMatchSetRequest request]
(-> this (.getByteMatchSet request))))
(defn delete-ip-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteIPSetRequest`
returns: Result of the DeleteIPSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteIPSetResult`"
(^com.amazonaws.services.waf.model.DeleteIPSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteIPSetRequest request]
(-> this (.deleteIPSet request))))
(defn create-rate-based-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRateBasedRuleRequest`
returns: Result of the CreateRateBasedRule operation returned by the service. - `com.amazonaws.services.waf.model.CreateRateBasedRuleResult`"
(^com.amazonaws.services.waf.model.CreateRateBasedRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRateBasedRuleRequest request]
(-> this (.createRateBasedRule request))))
| null |
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.waf/src/com/amazonaws/services/waf/AbstractAWSWAF.clj
|
clojure
|
(ns com.amazonaws.services.waf.AbstractAWSWAF
"Abstract implementation of AWSWAF. Convenient method forms pass through to the corresponding overload that
takes a request object, which throws an UnsupportedOperationException."
(:refer-clojure :only [require comment defn ->])
(:import [com.amazonaws.services.waf AbstractAWSWAF]))
(defn delete-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRuleGroupRequest`
returns: Result of the DeleteRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRuleGroupResult`"
(^com.amazonaws.services.waf.model.DeleteRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRuleGroupRequest request]
(-> this (.deleteRuleGroup request))))
(defn get-rate-based-rule-managed-keys
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRateBasedRuleManagedKeysRequest`
returns: Result of the GetRateBasedRuleManagedKeys operation returned by the service. - `com.amazonaws.services.waf.model.GetRateBasedRuleManagedKeysResult`"
(^com.amazonaws.services.waf.model.GetRateBasedRuleManagedKeysResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRateBasedRuleManagedKeysRequest request]
(-> this (.getRateBasedRuleManagedKeys request))))
(defn get-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRuleRequest`
returns: Result of the GetRule operation returned by the service. - `com.amazonaws.services.waf.model.GetRuleResult`"
(^com.amazonaws.services.waf.model.GetRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRuleRequest request]
(-> this (.getRule request))))
(defn list-tags-for-resource
"request - `com.amazonaws.services.waf.model.ListTagsForResourceRequest`
returns: Result of the ListTagsForResource operation returned by the service. - `com.amazonaws.services.waf.model.ListTagsForResourceResult`"
(^com.amazonaws.services.waf.model.ListTagsForResourceResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListTagsForResourceRequest request]
(-> this (.listTagsForResource request))))
(defn update-sql-injection-match-set
"Description copied from interface: AWSWAF
request - A request to update a SqlInjectionMatchSet. - `com.amazonaws.services.waf.model.UpdateSqlInjectionMatchSetRequest`
returns: Result of the UpdateSqlInjectionMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateSqlInjectionMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateSqlInjectionMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateSqlInjectionMatchSetRequest request]
(-> this (.updateSqlInjectionMatchSet request))))
(defn get-logging-configuration
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetLoggingConfigurationRequest`
returns: Result of the GetLoggingConfiguration operation returned by the service. - `com.amazonaws.services.waf.model.GetLoggingConfigurationResult`"
(^com.amazonaws.services.waf.model.GetLoggingConfigurationResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetLoggingConfigurationRequest request]
(-> this (.getLoggingConfiguration request))))
(defn set-region
"Description copied from interface: AWSWAF
region - The region this client will communicate with. See Region.getRegion(com.amazonaws.regions.Regions) for accessing a given region. Must not be null and must be a region where the service is available. - `com.amazonaws.regions.Region`"
([^AbstractAWSWAF this ^com.amazonaws.regions.Region region]
(-> this (.setRegion region))))
(defn delete-byte-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteByteMatchSetRequest`
returns: Result of the DeleteByteMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteByteMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteByteMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteByteMatchSetRequest request]
(-> this (.deleteByteMatchSet request))))
(defn delete-permission-policy
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeletePermissionPolicyRequest`
returns: Result of the DeletePermissionPolicy operation returned by the service. - `com.amazonaws.services.waf.model.DeletePermissionPolicyResult`"
(^com.amazonaws.services.waf.model.DeletePermissionPolicyResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeletePermissionPolicyRequest request]
(-> this (.deletePermissionPolicy request))))
(defn create-regex-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRegexMatchSetRequest`
returns: Result of the CreateRegexMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateRegexMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateRegexMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRegexMatchSetRequest request]
(-> this (.createRegexMatchSet request))))
(defn list-ip-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListIPSetsRequest`
returns: Result of the ListIPSets operation returned by the service. - `com.amazonaws.services.waf.model.ListIPSetsResult`"
(^com.amazonaws.services.waf.model.ListIPSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListIPSetsRequest request]
(-> this (.listIPSets request))))
(defn list-regex-pattern-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRegexPatternSetsRequest`
returns: Result of the ListRegexPatternSets operation returned by the service. - `com.amazonaws.services.waf.model.ListRegexPatternSetsResult`"
(^com.amazonaws.services.waf.model.ListRegexPatternSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRegexPatternSetsRequest request]
(-> this (.listRegexPatternSets request))))
(defn delete-regex-pattern-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRegexPatternSetRequest`
returns: Result of the DeleteRegexPatternSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRegexPatternSetResult`"
(^com.amazonaws.services.waf.model.DeleteRegexPatternSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRegexPatternSetRequest request]
(-> this (.deleteRegexPatternSet request))))
(defn list-web-ac-ls
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListWebACLsRequest`
returns: Result of the ListWebACLs operation returned by the service. - `com.amazonaws.services.waf.model.ListWebACLsResult`"
(^com.amazonaws.services.waf.model.ListWebACLsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListWebACLsRequest request]
(-> this (.listWebACLs request))))
(defn get-regex-pattern-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRegexPatternSetRequest`
returns: Result of the GetRegexPatternSet operation returned by the service. - `com.amazonaws.services.waf.model.GetRegexPatternSetResult`"
(^com.amazonaws.services.waf.model.GetRegexPatternSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRegexPatternSetRequest request]
(-> this (.getRegexPatternSet request))))
(defn update-size-constraint-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateSizeConstraintSetRequest`
returns: Result of the UpdateSizeConstraintSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateSizeConstraintSetResult`"
(^com.amazonaws.services.waf.model.UpdateSizeConstraintSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateSizeConstraintSetRequest request]
(-> this (.updateSizeConstraintSet request))))
(defn create-sql-injection-match-set
"Description copied from interface: AWSWAF
request - A request to create a SqlInjectionMatchSet. - `com.amazonaws.services.waf.model.CreateSqlInjectionMatchSetRequest`
returns: Result of the CreateSqlInjectionMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateSqlInjectionMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateSqlInjectionMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateSqlInjectionMatchSetRequest request]
(-> this (.createSqlInjectionMatchSet request))))
(defn delete-sql-injection-match-set
"Description copied from interface: AWSWAF
request - A request to delete a SqlInjectionMatchSet from AWS WAF. - `com.amazonaws.services.waf.model.DeleteSqlInjectionMatchSetRequest`
returns: Result of the DeleteSqlInjectionMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteSqlInjectionMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteSqlInjectionMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteSqlInjectionMatchSetRequest request]
(-> this (.deleteSqlInjectionMatchSet request))))
(defn get-size-constraint-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetSizeConstraintSetRequest`
returns: Result of the GetSizeConstraintSet operation returned by the service. - `com.amazonaws.services.waf.model.GetSizeConstraintSetResult`"
(^com.amazonaws.services.waf.model.GetSizeConstraintSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetSizeConstraintSetRequest request]
(-> this (.getSizeConstraintSet request))))
(defn delete-xss-match-set
"Description copied from interface: AWSWAF
request - A request to delete an XssMatchSet from AWS WAF. - `com.amazonaws.services.waf.model.DeleteXssMatchSetRequest`
returns: Result of the DeleteXssMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteXssMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteXssMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteXssMatchSetRequest request]
(-> this (.deleteXssMatchSet request))))
(defn create-geo-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateGeoMatchSetRequest`
returns: Result of the CreateGeoMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateGeoMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateGeoMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateGeoMatchSetRequest request]
(-> this (.createGeoMatchSet request))))
(defn untag-resource
"request - `com.amazonaws.services.waf.model.UntagResourceRequest`
returns: Result of the UntagResource operation returned by the service. - `com.amazonaws.services.waf.model.UntagResourceResult`"
(^com.amazonaws.services.waf.model.UntagResourceResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UntagResourceRequest request]
(-> this (.untagResource request))))
(defn update-ip-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateIPSetRequest`
returns: Result of the UpdateIPSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateIPSetResult`"
(^com.amazonaws.services.waf.model.UpdateIPSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateIPSetRequest request]
(-> this (.updateIPSet request))))
(defn update-web-acl
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateWebACLRequest`
returns: Result of the UpdateWebACL operation returned by the service. - `com.amazonaws.services.waf.model.UpdateWebACLResult`"
(^com.amazonaws.services.waf.model.UpdateWebACLResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateWebACLRequest request]
(-> this (.updateWebACL request))))
(defn update-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRuleGroupRequest`
returns: Result of the UpdateRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRuleGroupResult`"
(^com.amazonaws.services.waf.model.UpdateRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRuleGroupRequest request]
(-> this (.updateRuleGroup request))))
(defn delete-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRuleRequest`
returns: Result of the DeleteRule operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRuleResult`"
(^com.amazonaws.services.waf.model.DeleteRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRuleRequest request]
(-> this (.deleteRule request))))
(defn delete-regex-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRegexMatchSetRequest`
returns: Result of the DeleteRegexMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRegexMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteRegexMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRegexMatchSetRequest request]
(-> this (.deleteRegexMatchSet request))))
(defn update-xss-match-set
"Description copied from interface: AWSWAF
request - A request to update an XssMatchSet. - `com.amazonaws.services.waf.model.UpdateXssMatchSetRequest`
returns: Result of the UpdateXssMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateXssMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateXssMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateXssMatchSetRequest request]
(-> this (.updateXssMatchSet request))))
(defn delete-geo-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteGeoMatchSetRequest`
returns: Result of the DeleteGeoMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteGeoMatchSetResult`"
(^com.amazonaws.services.waf.model.DeleteGeoMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteGeoMatchSetRequest request]
(-> this (.deleteGeoMatchSet request))))
(defn update-regex-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRegexMatchSetRequest`
returns: Result of the UpdateRegexMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRegexMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateRegexMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRegexMatchSetRequest request]
(-> this (.updateRegexMatchSet request))))
(defn get-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRuleGroupRequest`
returns: Result of the GetRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.GetRuleGroupResult`"
(^com.amazonaws.services.waf.model.GetRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRuleGroupRequest request]
(-> this (.getRuleGroup request))))
(defn create-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRuleGroupRequest`
returns: Result of the CreateRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.CreateRuleGroupResult`"
(^com.amazonaws.services.waf.model.CreateRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRuleGroupRequest request]
(-> this (.createRuleGroup request))))
(defn get-change-token-status
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetChangeTokenStatusRequest`
returns: Result of the GetChangeTokenStatus operation returned by the service. - `com.amazonaws.services.waf.model.GetChangeTokenStatusResult`"
(^com.amazonaws.services.waf.model.GetChangeTokenStatusResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetChangeTokenStatusRequest request]
(-> this (.getChangeTokenStatus request))))
(defn get-regex-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRegexMatchSetRequest`
returns: Result of the GetRegexMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetRegexMatchSetResult`"
(^com.amazonaws.services.waf.model.GetRegexMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRegexMatchSetRequest request]
(-> this (.getRegexMatchSet request))))
(defn create-byte-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateByteMatchSetRequest`
returns: Result of the CreateByteMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateByteMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateByteMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateByteMatchSetRequest request]
(-> this (.createByteMatchSet request))))
(defn list-size-constraint-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListSizeConstraintSetsRequest`
returns: Result of the ListSizeConstraintSets operation returned by the service. - `com.amazonaws.services.waf.model.ListSizeConstraintSetsResult`"
(^com.amazonaws.services.waf.model.ListSizeConstraintSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListSizeConstraintSetsRequest request]
(-> this (.listSizeConstraintSets request))))
(defn shutdown
"Description copied from interface: AWSWAF"
([^AbstractAWSWAF this]
(-> this (.shutdown))))
(defn update-byte-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateByteMatchSetRequest`
returns: Result of the UpdateByteMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateByteMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateByteMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateByteMatchSetRequest request]
(-> this (.updateByteMatchSet request))))
(defn list-geo-match-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListGeoMatchSetsRequest`
returns: Result of the ListGeoMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListGeoMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListGeoMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListGeoMatchSetsRequest request]
(-> this (.listGeoMatchSets request))))
(defn get-change-token
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetChangeTokenRequest`
returns: Result of the GetChangeToken operation returned by the service. - `com.amazonaws.services.waf.model.GetChangeTokenResult`"
(^com.amazonaws.services.waf.model.GetChangeTokenResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetChangeTokenRequest request]
(-> this (.getChangeToken request))))
(defn delete-size-constraint-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteSizeConstraintSetRequest`
returns: Result of the DeleteSizeConstraintSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteSizeConstraintSetResult`"
(^com.amazonaws.services.waf.model.DeleteSizeConstraintSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteSizeConstraintSetRequest request]
(-> this (.deleteSizeConstraintSet request))))
(defn get-sql-injection-match-set
"Description copied from interface: AWSWAF
request - A request to get a SqlInjectionMatchSet. - `com.amazonaws.services.waf.model.GetSqlInjectionMatchSetRequest`
returns: Result of the GetSqlInjectionMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetSqlInjectionMatchSetResult`"
(^com.amazonaws.services.waf.model.GetSqlInjectionMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetSqlInjectionMatchSetRequest request]
(-> this (.getSqlInjectionMatchSet request))))
(defn list-subscribed-rule-groups
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListSubscribedRuleGroupsRequest`
returns: Result of the ListSubscribedRuleGroups operation returned by the service. - `com.amazonaws.services.waf.model.ListSubscribedRuleGroupsResult`"
(^com.amazonaws.services.waf.model.ListSubscribedRuleGroupsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListSubscribedRuleGroupsRequest request]
(-> this (.listSubscribedRuleGroups request))))
(defn list-rule-groups
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRuleGroupsRequest`
returns: Result of the ListRuleGroups operation returned by the service. - `com.amazonaws.services.waf.model.ListRuleGroupsResult`"
(^com.amazonaws.services.waf.model.ListRuleGroupsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRuleGroupsRequest request]
(-> this (.listRuleGroups request))))
(defn create-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRuleRequest`
returns: Result of the CreateRule operation returned by the service. - `com.amazonaws.services.waf.model.CreateRuleResult`"
(^com.amazonaws.services.waf.model.CreateRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRuleRequest request]
(-> this (.createRule request))))
(defn get-xss-match-set
"Description copied from interface: AWSWAF
request - A request to get an XssMatchSet. - `com.amazonaws.services.waf.model.GetXssMatchSetRequest`
returns: Result of the GetXssMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetXssMatchSetResult`"
(^com.amazonaws.services.waf.model.GetXssMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetXssMatchSetRequest request]
(-> this (.getXssMatchSet request))))
(defn set-endpoint
"Description copied from interface: AWSWAF
endpoint - The endpoint (ex: \"waf.amazonaws.com/\") or a full URL, including the protocol (ex: \"/\") of the region specific AWS endpoint this client will communicate with. - `java.lang.String`"
([^AbstractAWSWAF this ^java.lang.String endpoint]
(-> this (.setEndpoint endpoint))))
(defn update-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRuleRequest`
returns: Result of the UpdateRule operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRuleResult`"
(^com.amazonaws.services.waf.model.UpdateRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRuleRequest request]
(-> this (.updateRule request))))
(defn delete-web-acl
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteWebACLRequest`
returns: Result of the DeleteWebACL operation returned by the service. - `com.amazonaws.services.waf.model.DeleteWebACLResult`"
(^com.amazonaws.services.waf.model.DeleteWebACLResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteWebACLRequest request]
(-> this (.deleteWebACL request))))
(defn update-regex-pattern-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRegexPatternSetRequest`
returns: Result of the UpdateRegexPatternSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRegexPatternSetResult`"
(^com.amazonaws.services.waf.model.UpdateRegexPatternSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRegexPatternSetRequest request]
(-> this (.updateRegexPatternSet request))))
(defn list-rate-based-rules
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRateBasedRulesRequest`
returns: Result of the ListRateBasedRules operation returned by the service. - `com.amazonaws.services.waf.model.ListRateBasedRulesResult`"
(^com.amazonaws.services.waf.model.ListRateBasedRulesResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRateBasedRulesRequest request]
(-> this (.listRateBasedRules request))))
(defn update-rate-based-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateRateBasedRuleRequest`
returns: Result of the UpdateRateBasedRule operation returned by the service. - `com.amazonaws.services.waf.model.UpdateRateBasedRuleResult`"
(^com.amazonaws.services.waf.model.UpdateRateBasedRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateRateBasedRuleRequest request]
(-> this (.updateRateBasedRule request))))
(defn put-permission-policy
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.PutPermissionPolicyRequest`
returns: Result of the PutPermissionPolicy operation returned by the service. - `com.amazonaws.services.waf.model.PutPermissionPolicyResult`"
(^com.amazonaws.services.waf.model.PutPermissionPolicyResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.PutPermissionPolicyRequest request]
(-> this (.putPermissionPolicy request))))
(defn delete-rate-based-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteRateBasedRuleRequest`
returns: Result of the DeleteRateBasedRule operation returned by the service. - `com.amazonaws.services.waf.model.DeleteRateBasedRuleResult`"
(^com.amazonaws.services.waf.model.DeleteRateBasedRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteRateBasedRuleRequest request]
(-> this (.deleteRateBasedRule request))))
(defn list-sql-injection-match-sets
"Description copied from interface: AWSWAF
request - A request to list the SqlInjectionMatchSet objects created by the current AWS account. - `com.amazonaws.services.waf.model.ListSqlInjectionMatchSetsRequest`
returns: Result of the ListSqlInjectionMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListSqlInjectionMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListSqlInjectionMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListSqlInjectionMatchSetsRequest request]
(-> this (.listSqlInjectionMatchSets request))))
(defn get-geo-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetGeoMatchSetRequest`
returns: Result of the GetGeoMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetGeoMatchSetResult`"
(^com.amazonaws.services.waf.model.GetGeoMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetGeoMatchSetRequest request]
(-> this (.getGeoMatchSet request))))
(defn get-ip-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetIPSetRequest`
returns: Result of the GetIPSet operation returned by the service. - `com.amazonaws.services.waf.model.GetIPSetResult`"
(^com.amazonaws.services.waf.model.GetIPSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetIPSetRequest request]
(-> this (.getIPSet request))))
(defn get-rate-based-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetRateBasedRuleRequest`
returns: Result of the GetRateBasedRule operation returned by the service. - `com.amazonaws.services.waf.model.GetRateBasedRuleResult`"
(^com.amazonaws.services.waf.model.GetRateBasedRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetRateBasedRuleRequest request]
(-> this (.getRateBasedRule request))))
(defn put-logging-configuration
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.PutLoggingConfigurationRequest`
returns: Result of the PutLoggingConfiguration operation returned by the service. - `com.amazonaws.services.waf.model.PutLoggingConfigurationResult`"
(^com.amazonaws.services.waf.model.PutLoggingConfigurationResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.PutLoggingConfigurationRequest request]
(-> this (.putLoggingConfiguration request))))
(defn list-activated-rules-in-rule-group
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListActivatedRulesInRuleGroupRequest`
returns: Result of the ListActivatedRulesInRuleGroup operation returned by the service. - `com.amazonaws.services.waf.model.ListActivatedRulesInRuleGroupResult`"
(^com.amazonaws.services.waf.model.ListActivatedRulesInRuleGroupResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListActivatedRulesInRuleGroupRequest request]
(-> this (.listActivatedRulesInRuleGroup request))))
(defn delete-logging-configuration
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteLoggingConfigurationRequest`
returns: Result of the DeleteLoggingConfiguration operation returned by the service. - `com.amazonaws.services.waf.model.DeleteLoggingConfigurationResult`"
(^com.amazonaws.services.waf.model.DeleteLoggingConfigurationResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteLoggingConfigurationRequest request]
(-> this (.deleteLoggingConfiguration request))))
(defn list-byte-match-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListByteMatchSetsRequest`
returns: Result of the ListByteMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListByteMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListByteMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListByteMatchSetsRequest request]
(-> this (.listByteMatchSets request))))
(defn get-sampled-requests
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetSampledRequestsRequest`
returns: Result of the GetSampledRequests operation returned by the service. - `com.amazonaws.services.waf.model.GetSampledRequestsResult`"
(^com.amazonaws.services.waf.model.GetSampledRequestsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetSampledRequestsRequest request]
(-> this (.getSampledRequests request))))
(defn list-xss-match-sets
"Description copied from interface: AWSWAF
request - A request to list the XssMatchSet objects created by the current AWS account. - `com.amazonaws.services.waf.model.ListXssMatchSetsRequest`
returns: Result of the ListXssMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListXssMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListXssMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListXssMatchSetsRequest request]
(-> this (.listXssMatchSets request))))
(defn list-regex-match-sets
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRegexMatchSetsRequest`
returns: Result of the ListRegexMatchSets operation returned by the service. - `com.amazonaws.services.waf.model.ListRegexMatchSetsResult`"
(^com.amazonaws.services.waf.model.ListRegexMatchSetsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRegexMatchSetsRequest request]
(-> this (.listRegexMatchSets request))))
(defn get-cached-response-metadata
"Description copied from interface: AWSWAF
request - The originally executed request. - `com.amazonaws.AmazonWebServiceRequest`
returns: The response metadata for the specified request, or null if none is available. - `com.amazonaws.ResponseMetadata`"
(^com.amazonaws.ResponseMetadata [^AbstractAWSWAF this ^com.amazonaws.AmazonWebServiceRequest request]
(-> this (.getCachedResponseMetadata request))))
(defn get-web-acl
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetWebACLRequest`
returns: Result of the GetWebACL operation returned by the service. - `com.amazonaws.services.waf.model.GetWebACLResult`"
(^com.amazonaws.services.waf.model.GetWebACLResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetWebACLRequest request]
(-> this (.getWebACL request))))
(defn get-permission-policy
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetPermissionPolicyRequest`
returns: Result of the GetPermissionPolicy operation returned by the service. - `com.amazonaws.services.waf.model.GetPermissionPolicyResult`"
(^com.amazonaws.services.waf.model.GetPermissionPolicyResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetPermissionPolicyRequest request]
(-> this (.getPermissionPolicy request))))
(defn create-xss-match-set
"Description copied from interface: AWSWAF
request - A request to create an XssMatchSet. - `com.amazonaws.services.waf.model.CreateXssMatchSetRequest`
returns: Result of the CreateXssMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateXssMatchSetResult`"
(^com.amazonaws.services.waf.model.CreateXssMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateXssMatchSetRequest request]
(-> this (.createXssMatchSet request))))
(defn create-regex-pattern-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRegexPatternSetRequest`
returns: Result of the CreateRegexPatternSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateRegexPatternSetResult`"
(^com.amazonaws.services.waf.model.CreateRegexPatternSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRegexPatternSetRequest request]
(-> this (.createRegexPatternSet request))))
(defn list-rules
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListRulesRequest`
returns: Result of the ListRules operation returned by the service. - `com.amazonaws.services.waf.model.ListRulesResult`"
(^com.amazonaws.services.waf.model.ListRulesResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListRulesRequest request]
(-> this (.listRules request))))
(defn create-ip-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateIPSetRequest`
returns: Result of the CreateIPSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateIPSetResult`"
(^com.amazonaws.services.waf.model.CreateIPSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateIPSetRequest request]
(-> this (.createIPSet request))))
(defn tag-resource
"request - `com.amazonaws.services.waf.model.TagResourceRequest`
returns: Result of the TagResource operation returned by the service. - `com.amazonaws.services.waf.model.TagResourceResult`"
(^com.amazonaws.services.waf.model.TagResourceResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.TagResourceRequest request]
(-> this (.tagResource request))))
(defn create-size-constraint-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateSizeConstraintSetRequest`
returns: Result of the CreateSizeConstraintSet operation returned by the service. - `com.amazonaws.services.waf.model.CreateSizeConstraintSetResult`"
(^com.amazonaws.services.waf.model.CreateSizeConstraintSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateSizeConstraintSetRequest request]
(-> this (.createSizeConstraintSet request))))
(defn update-geo-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.UpdateGeoMatchSetRequest`
returns: Result of the UpdateGeoMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.UpdateGeoMatchSetResult`"
(^com.amazonaws.services.waf.model.UpdateGeoMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.UpdateGeoMatchSetRequest request]
(-> this (.updateGeoMatchSet request))))
(defn list-logging-configurations
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.ListLoggingConfigurationsRequest`
returns: Result of the ListLoggingConfigurations operation returned by the service. - `com.amazonaws.services.waf.model.ListLoggingConfigurationsResult`"
(^com.amazonaws.services.waf.model.ListLoggingConfigurationsResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.ListLoggingConfigurationsRequest request]
(-> this (.listLoggingConfigurations request))))
(defn create-web-acl
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateWebACLRequest`
returns: Result of the CreateWebACL operation returned by the service. - `com.amazonaws.services.waf.model.CreateWebACLResult`"
(^com.amazonaws.services.waf.model.CreateWebACLResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateWebACLRequest request]
(-> this (.createWebACL request))))
(defn get-byte-match-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.GetByteMatchSetRequest`
returns: Result of the GetByteMatchSet operation returned by the service. - `com.amazonaws.services.waf.model.GetByteMatchSetResult`"
(^com.amazonaws.services.waf.model.GetByteMatchSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.GetByteMatchSetRequest request]
(-> this (.getByteMatchSet request))))
(defn delete-ip-set
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.DeleteIPSetRequest`
returns: Result of the DeleteIPSet operation returned by the service. - `com.amazonaws.services.waf.model.DeleteIPSetResult`"
(^com.amazonaws.services.waf.model.DeleteIPSetResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.DeleteIPSetRequest request]
(-> this (.deleteIPSet request))))
(defn create-rate-based-rule
"Description copied from interface: AWSWAF
request - `com.amazonaws.services.waf.model.CreateRateBasedRuleRequest`
returns: Result of the CreateRateBasedRule operation returned by the service. - `com.amazonaws.services.waf.model.CreateRateBasedRuleResult`"
(^com.amazonaws.services.waf.model.CreateRateBasedRuleResult [^AbstractAWSWAF this ^com.amazonaws.services.waf.model.CreateRateBasedRuleRequest request]
(-> this (.createRateBasedRule request))))
|
|
a2ef12bc00a8c71fa51df889404724c17c7fae73460969d637affe7e0f271d82
|
rowangithub/DOrder
|
parser.mli
|
type token =
| AMPERAMPER
| AMPERSAND
| AND
| AS
| ASSERT
| BACKQUOTE
| BANG
| BAR
| BARBAR
| BARRBRACKET
| BEGIN
| CHAR of (char)
| CLASS
| COLON
| COLONCOLON
| COLONEQUAL
| COLONGREATER
| COMMA
| CONSTRAINT
| DO
| DONE
| DOT
| DOTDOT
| DOWNTO
| ELSE
| END
| EOF
| EQUAL
| EXCEPTION
| EXTERNAL
| FALSE
| FLOAT of (string)
| FOR
| FUN
| FUNCTION
| FUNCTOR
| GREATER
| GREATERRBRACE
| GREATERRBRACKET
| IF
| IN
| INCLUDE
| INFIXOP0 of (string)
| INFIXOP1 of (string)
| INFIXOP2 of (string)
| INFIXOP3 of (string)
| INFIXOP4 of (string)
| INHERIT
| INITIALIZER
| INT of (int)
| INT32 of (int32)
| INT64 of (int64)
| LABEL of (string)
| LAZY
| LBRACE
| LBRACELESS
| LBRACKET
| LBRACKETBAR
| LBRACKETLESS
| LBRACKETGREATER
| LESS
| LESSMINUS
| LET
| LIDENT of (string)
| LPAREN
| MATCH
| METHOD
| MINUS
| MINUSDOT
| MINUSGREATER
| MODULE
| MUTABLE
| NATIVEINT of (nativeint)
| NEW
| OBJECT
| OF
| OPEN
| OPTLABEL of (string)
| OR
| PLUS
| PLUSDOT
| PREFIXOP of (string)
| PRIVATE
| QUALIF
| SINGLE_QUALIF
| PREDICATE
| FORALL
| REACH
| LINK
| QUESTION
| QUESTIONQUESTION
| QUOTE
| RBRACE
| RBRACKET
| REC
| RPAREN
| SEMI
| SEMISEMI
| SHARP
| SIG
| STAR
| STRING of (string)
| STRUCT
| THEN
| TILDE
| TO
| TRUE
| TRY
| TYPE
| UIDENT of (string)
| UNDERSCORE
| VAL
| VIRTUAL
| WHEN
| WHILE
| WITH
val implementation :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.structure
val interface :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.signature
val toplevel_phrase :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.toplevel_phrase
val use_file :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.toplevel_phrase list
val qualifiers :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.qualifier_declaration list
val qualifier_patterns :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.qualifier_declaration list
val liquid_interface :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.penv
| null |
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/parsing/parser.mli
|
ocaml
|
type token =
| AMPERAMPER
| AMPERSAND
| AND
| AS
| ASSERT
| BACKQUOTE
| BANG
| BAR
| BARBAR
| BARRBRACKET
| BEGIN
| CHAR of (char)
| CLASS
| COLON
| COLONCOLON
| COLONEQUAL
| COLONGREATER
| COMMA
| CONSTRAINT
| DO
| DONE
| DOT
| DOTDOT
| DOWNTO
| ELSE
| END
| EOF
| EQUAL
| EXCEPTION
| EXTERNAL
| FALSE
| FLOAT of (string)
| FOR
| FUN
| FUNCTION
| FUNCTOR
| GREATER
| GREATERRBRACE
| GREATERRBRACKET
| IF
| IN
| INCLUDE
| INFIXOP0 of (string)
| INFIXOP1 of (string)
| INFIXOP2 of (string)
| INFIXOP3 of (string)
| INFIXOP4 of (string)
| INHERIT
| INITIALIZER
| INT of (int)
| INT32 of (int32)
| INT64 of (int64)
| LABEL of (string)
| LAZY
| LBRACE
| LBRACELESS
| LBRACKET
| LBRACKETBAR
| LBRACKETLESS
| LBRACKETGREATER
| LESS
| LESSMINUS
| LET
| LIDENT of (string)
| LPAREN
| MATCH
| METHOD
| MINUS
| MINUSDOT
| MINUSGREATER
| MODULE
| MUTABLE
| NATIVEINT of (nativeint)
| NEW
| OBJECT
| OF
| OPEN
| OPTLABEL of (string)
| OR
| PLUS
| PLUSDOT
| PREFIXOP of (string)
| PRIVATE
| QUALIF
| SINGLE_QUALIF
| PREDICATE
| FORALL
| REACH
| LINK
| QUESTION
| QUESTIONQUESTION
| QUOTE
| RBRACE
| RBRACKET
| REC
| RPAREN
| SEMI
| SEMISEMI
| SHARP
| SIG
| STAR
| STRING of (string)
| STRUCT
| THEN
| TILDE
| TO
| TRUE
| TRY
| TYPE
| UIDENT of (string)
| UNDERSCORE
| VAL
| VIRTUAL
| WHEN
| WHILE
| WITH
val implementation :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.structure
val interface :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.signature
val toplevel_phrase :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.toplevel_phrase
val use_file :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.toplevel_phrase list
val qualifiers :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.qualifier_declaration list
val qualifier_patterns :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.qualifier_declaration list
val liquid_interface :
(Lexing.lexbuf -> token) -> Lexing.lexbuf -> Parsetree.penv
|
|
bff123c9c77bedc26bdead603e31c3ece4d385337355e25ca59d352de8a6c1eb
|
marijnh/Postmodern
|
test-return-types.lisp
|
-*- Mode : LISP ; Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : POSTMODERN - TESTS ; -*-
(in-package :postmodern-tests)
(def-suite :postmodern-return-types
:description "Return types"
:in :postmodern)
(in-suite :postmodern-return-types)
(defun return-types-fixture ()
(when (table-exists-p 'test-data)
(query (:drop-table :if-exists 'test-data :cascade)))
(execute (:create-table test-data ((id :type integer :primary-key t)
(int4 :type integer)
(text :type (or text db-null))
(jsonb :type (or jsonb db-null))
(timestamp-without-time-zone
:type (or timestamp-without-time-zone
db-null))
(timestamp-with-time-zone
:type (or timestamp-with-time-zone db-null))
(timestamptz :type (or timestamptz db-null))
(timestamp :type (or timestamp db-null))
(time :type (or time db-null))
(date :type (or date db-null))
(interval :type (or interval db-null)))))
(query (:insert-rows-into 'test-data
:columns 'id 'int4 'text 'jsonb 'timestamp-without-time-zone
'timestamp-with-time-zone 'timestamptz 'timestamp 'time 'date 'interval
:values '((1 2147483645 "text one" "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}"
"2020-12-30 13:30:54" "2019-12-30 13:30:54" "2018-12-30 13:30:54"
"2017-12-30 13:30:54"
"14:31:54" "2016-12-30" "2 hours 10 minutes")
(2 0 "text two" "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"
"1920-12-30 13:30:54" "1919-12-30 13:30:54" "1918-12-30 13:30:54"
"1917-12-30 13:30:54"
"14:32:54" "1916-12-30" "3 months 2 hours 10 minutes")
(3 3 "text three" "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}"
"1980-12-30 13:30:54" "1981-12-30 13:30:54" "1982-12-30 13:30:54"
"1983-12-30 13:30:54"
"14:33:54" "1983-12-30" "5 years 3 months 2 hours 10 minutes")))))
(defmacro with-return-types-fixture (&body body)
`(progn
(return-types-fixture)
(unwind-protect (progn ,@body)
(execute (:drop-table :if-exists 'test-data :cascade)))))
(test return-types-json
(with-test-connection
(with-return-types-fixture
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)))
'((1
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}")
(2
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"))))
(is (equal (query (:select 'jsonb :from 'test-data :where (:= 'id 3)) :single)
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}"))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :list)
'(3
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}")))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :lists)
'((1
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}")
(2
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :alist)
'((:ID . 3)
(:JSONB
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}"))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :str-alist)
'(("id" . 3)
("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}"))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :alists)
'(((:ID . 1)
(:JSONB
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}"))
((:ID . 2)
(:JSONB
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}")))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :str-alists)
'((("id" . 1)
("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}"))
(("id" . 2)
("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}")))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :plist)
'(:ID 3 :JSONB
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}")))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :plists)
'((:ID 1 :JSONB
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}")
(:ID 2 :JSONB
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"))))
(is (typep (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :array-hash) 'vector))
(is (typep (aref (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :array-hash) 1) 'hash-table))
(let ((val (alexandria:hash-table-alist
(aref
(query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :array-hash)
1))))
(is (or
(equal val
'(("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}")
("id" . 2)))
(equal val
'(("id" . 2)
("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"))))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :json-strs)
'("{\"id\":1,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Greece\\\", \\\"description\\\": \\\"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\\\", \\\"granularity\\\": \\\"year\\\"}\"}"
"{\"id\":2,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Egypt\\\", \\\"description\\\": \\\"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\\\", \\\"granularity\\\": \\\"year\\\"}\"}")))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :json-str)
"{\"id\":3,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Egypt\\\", \\\"description\\\": \\\"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\\\", \\\"granularity\\\": \\\"year\\\"}\"}"))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :json-array-str)
"[{\"id\":1,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Greece\\\", \\\"description\\\": \\\"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\\\", \\\"granularity\\\": \\\"year\\\"}\"}, {\"id\":2,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Egypt\\\", \\\"description\\\": \\\"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\\\", \\\"granularity\\\": \\\"year\\\"}\"}]")))))
(test return-types
(with-test-connection
(with-return-types-fixture
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :none)
nil))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)))
'((1 2147483645 "text one") (2 0 "text two"))))
(is (equal (query (:select 'text :from 'test-data :where (:= 'id 3)) :single)
"text three"))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :list)
'(3 3 "text three")))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :lists)
'((1 2147483645 "text one") (2 0 "text two"))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :alist)
'((:ID . 3) (:INT4 . 3) (:TEXT . "text three"))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :str-alist)
'(("id" . 3) ("int4" . 3) ("text" . "text three"))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :alists)
'(((:ID . 1) (:INT4 . 2147483645) (:TEXT . "text one"))
((:ID . 2) (:INT4 . 0) (:TEXT . "text two")))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :str-alists)
'((("id" . 1) ("int4" . 2147483645) ("text" . "text one"))
(("id" . 2) ("int4" . 0) ("text" . "text two")))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :plist)
'(:ID 3 :INT4 3 :TEXT "text three")))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :plists)
'((:ID 1 :INT4 2147483645 :TEXT "text one")
(:ID 2 :INT4 0 :TEXT "text two"))))
(is (equalp (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 3)) :vectors)
#(#(1 2147483645 "text one") #(2 0 "text two"))))
(is (equalp (query (:select 'id :from 'test-data) :vectors)
#(#(1) #(2) #(3))))
(is (equalp (query (:select 'id 'int4 'text :from 'test-data) :vectors)
#(#(1 2147483645 "text one") #(2 0 "text two") #(3 3 "text three"))))
(is (equalp (aref (query (:select 'id 'int4 'text :from 'test-data) :vectors) 1)
#(2 0 "text two")))
(let ((val (alexandria:hash-table-alist
(aref
(query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :array-hash)
1))))
(is (equal (assoc "text" val :test 'equal)
'("text" . "text two"))))
(is (equal (query (:select 'id :from 'test-data
:where (:< 'id 3)) :column)
'(1 2)))
(is (equal (query (:select 'id :from 'test-data
:where (:= 'id 3)) :column)
'(3)))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :json-strs)
'("{\"id\":1,\"int4\":2147483645,\"text\":\"text one\"}"
"{\"id\":2,\"int4\":0,\"text\":\"text two\"}")))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :json-str)
"{\"id\":3,\"int4\":3,\"text\":\"text three\"}"))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :json-array-str)
"[{\"id\":1,\"int4\":2147483645,\"text\":\"text one\"}, {\"id\":2,\"int4\":0,\"text\":\"text two\"}]")))))
(test empty-return-types
(with-test-connection
(with-return-types-fixture
(is (equalp (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:vectors)
#()))
(is (equalp (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:array-hash)
#()))
(is (equalp (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:json-array-str)
"[]"))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:json-strs))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:alists))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:alist))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:plists))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:plist))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1)))))))
(test return-type-types
(with-test-connection
(with-return-types-fixture
(is (typep (query (:select 'id 'int4 'text :from 'test-data) :vectors)
'vector))
(is (typep (aref (query (:select 'id 'int4 'text :from 'test-data) :vectors)
1)
'vector))
(is (typep (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1)) :vectors)
'vector))
(is (typep (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :array-hash)
'vector))
(is (typep (aref (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :array-hash) 1)
'hash-table))
(is (typep (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1)) :array-hash)
'array)))))
| null |
https://raw.githubusercontent.com/marijnh/Postmodern/d54e494000e1915a7046e8d825cb635555957e85/postmodern/tests/test-return-types.lisp
|
lisp
|
Syntax : Ansi - Common - Lisp ; Base : 10 ; Package : POSTMODERN - TESTS ; -*-
|
(in-package :postmodern-tests)
(def-suite :postmodern-return-types
:description "Return types"
:in :postmodern)
(in-suite :postmodern-return-types)
(defun return-types-fixture ()
(when (table-exists-p 'test-data)
(query (:drop-table :if-exists 'test-data :cascade)))
(execute (:create-table test-data ((id :type integer :primary-key t)
(int4 :type integer)
(text :type (or text db-null))
(jsonb :type (or jsonb db-null))
(timestamp-without-time-zone
:type (or timestamp-without-time-zone
db-null))
(timestamp-with-time-zone
:type (or timestamp-with-time-zone db-null))
(timestamptz :type (or timestamptz db-null))
(timestamp :type (or timestamp db-null))
(time :type (or time db-null))
(date :type (or date db-null))
(interval :type (or interval db-null)))))
(query (:insert-rows-into 'test-data
:columns 'id 'int4 'text 'jsonb 'timestamp-without-time-zone
'timestamp-with-time-zone 'timestamptz 'timestamp 'time 'date 'interval
:values '((1 2147483645 "text one" "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}"
"2020-12-30 13:30:54" "2019-12-30 13:30:54" "2018-12-30 13:30:54"
"2017-12-30 13:30:54"
"14:31:54" "2016-12-30" "2 hours 10 minutes")
(2 0 "text two" "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"
"1920-12-30 13:30:54" "1919-12-30 13:30:54" "1918-12-30 13:30:54"
"1917-12-30 13:30:54"
"14:32:54" "1916-12-30" "3 months 2 hours 10 minutes")
(3 3 "text three" "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}"
"1980-12-30 13:30:54" "1981-12-30 13:30:54" "1982-12-30 13:30:54"
"1983-12-30 13:30:54"
"14:33:54" "1983-12-30" "5 years 3 months 2 hours 10 minutes")))))
(defmacro with-return-types-fixture (&body body)
`(progn
(return-types-fixture)
(unwind-protect (progn ,@body)
(execute (:drop-table :if-exists 'test-data :cascade)))))
(test return-types-json
(with-test-connection
(with-return-types-fixture
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)))
'((1
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}")
(2
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"))))
(is (equal (query (:select 'jsonb :from 'test-data :where (:= 'id 3)) :single)
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}"))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :list)
'(3
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}")))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :lists)
'((1
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}")
(2
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :alist)
'((:ID . 3)
(:JSONB
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}"))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :str-alist)
'(("id" . 3)
("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}"))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :alists)
'(((:ID . 1)
(:JSONB
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}"))
((:ID . 2)
(:JSONB
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}")))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :str-alists)
'((("id" . 1)
("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}"))
(("id" . 2)
("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}")))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :plist)
'(:ID 3 :JSONB
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\", \"granularity\": \"year\"}")))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :plists)
'((:ID 1 :JSONB
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Greece\", \"description\": \"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\", \"granularity\": \"year\"}")
(:ID 2 :JSONB
"{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"))))
(is (typep (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :array-hash) 'vector))
(is (typep (aref (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :array-hash) 1) 'hash-table))
(let ((val (alexandria:hash-table-alist
(aref
(query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :array-hash)
1))))
(is (or
(equal val
'(("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}")
("id" . 2)))
(equal val
'(("id" . 2)
("jsonb"
. "{\"date\": \"-300\", \"lang\": \"en\", \"category1\": \"By place\", \"category2\": \"Egypt\", \"description\": \"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\", \"granularity\": \"year\"}"))))))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :json-strs)
'("{\"id\":1,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Greece\\\", \\\"description\\\": \\\"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\\\", \\\"granularity\\\": \\\"year\\\"}\"}"
"{\"id\":2,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Egypt\\\", \\\"description\\\": \\\"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\\\", \\\"granularity\\\": \\\"year\\\"}\"}")))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:= 'id 3)) :json-str)
"{\"id\":3,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Egypt\\\", \\\"description\\\": \\\"Ptolemy concludes an alliance with King Lysimachus of Thrace and gives him his daughter Arsinoe II in marriage.\\\", \\\"granularity\\\": \\\"year\\\"}\"}"))
(is (equal (query (:select 'id 'jsonb :from 'test-data
:where (:< 'id 3)) :json-array-str)
"[{\"id\":1,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Greece\\\", \\\"description\\\": \\\"Pilgrims travel to the healing temples of Asclepieion to be cured of their ills. After a ritual purification the followers bring offerings or sacrifices.\\\", \\\"granularity\\\": \\\"year\\\"}\"}, {\"id\":2,\"jsonb\":\"{\\\"date\\\": \\\"-300\\\", \\\"lang\\\": \\\"en\\\", \\\"category1\\\": \\\"By place\\\", \\\"category2\\\": \\\"Egypt\\\", \\\"description\\\": \\\"Pyrrhus, the King of Epirus, is taken as a hostage to Egypt after the Battle of Ipsus and makes a diplomatic marriage with the princess Antigone, daughter of Ptolemy and Berenice.\\\", \\\"granularity\\\": \\\"year\\\"}\"}]")))))
(test return-types
(with-test-connection
(with-return-types-fixture
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :none)
nil))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)))
'((1 2147483645 "text one") (2 0 "text two"))))
(is (equal (query (:select 'text :from 'test-data :where (:= 'id 3)) :single)
"text three"))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :list)
'(3 3 "text three")))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :lists)
'((1 2147483645 "text one") (2 0 "text two"))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :alist)
'((:ID . 3) (:INT4 . 3) (:TEXT . "text three"))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :str-alist)
'(("id" . 3) ("int4" . 3) ("text" . "text three"))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :alists)
'(((:ID . 1) (:INT4 . 2147483645) (:TEXT . "text one"))
((:ID . 2) (:INT4 . 0) (:TEXT . "text two")))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :str-alists)
'((("id" . 1) ("int4" . 2147483645) ("text" . "text one"))
(("id" . 2) ("int4" . 0) ("text" . "text two")))))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :plist)
'(:ID 3 :INT4 3 :TEXT "text three")))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :plists)
'((:ID 1 :INT4 2147483645 :TEXT "text one")
(:ID 2 :INT4 0 :TEXT "text two"))))
(is (equalp (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 3)) :vectors)
#(#(1 2147483645 "text one") #(2 0 "text two"))))
(is (equalp (query (:select 'id :from 'test-data) :vectors)
#(#(1) #(2) #(3))))
(is (equalp (query (:select 'id 'int4 'text :from 'test-data) :vectors)
#(#(1 2147483645 "text one") #(2 0 "text two") #(3 3 "text three"))))
(is (equalp (aref (query (:select 'id 'int4 'text :from 'test-data) :vectors) 1)
#(2 0 "text two")))
(let ((val (alexandria:hash-table-alist
(aref
(query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :array-hash)
1))))
(is (equal (assoc "text" val :test 'equal)
'("text" . "text two"))))
(is (equal (query (:select 'id :from 'test-data
:where (:< 'id 3)) :column)
'(1 2)))
(is (equal (query (:select 'id :from 'test-data
:where (:= 'id 3)) :column)
'(3)))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :json-strs)
'("{\"id\":1,\"int4\":2147483645,\"text\":\"text one\"}"
"{\"id\":2,\"int4\":0,\"text\":\"text two\"}")))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:= 'id 3)) :json-str)
"{\"id\":3,\"int4\":3,\"text\":\"text three\"}"))
(is (equal (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :json-array-str)
"[{\"id\":1,\"int4\":2147483645,\"text\":\"text one\"}, {\"id\":2,\"int4\":0,\"text\":\"text two\"}]")))))
(test empty-return-types
(with-test-connection
(with-return-types-fixture
(is (equalp (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:vectors)
#()))
(is (equalp (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:array-hash)
#()))
(is (equalp (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:json-array-str)
"[]"))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:json-strs))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:alists))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:alist))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:plists))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1))
:plist))
(is-false (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1)))))))
(test return-type-types
(with-test-connection
(with-return-types-fixture
(is (typep (query (:select 'id 'int4 'text :from 'test-data) :vectors)
'vector))
(is (typep (aref (query (:select 'id 'int4 'text :from 'test-data) :vectors)
1)
'vector))
(is (typep (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1)) :vectors)
'vector))
(is (typep (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :array-hash)
'vector))
(is (typep (aref (query (:select 'id 'int4 'text :from 'test-data
:where (:< 'id 3)) :array-hash) 1)
'hash-table))
(is (typep (query (:select 'id 'int4 'text :from 'test-data :where (:< 'id 1)) :array-hash)
'array)))))
|
4409019e26d07744151f60b5f029c7f931776533aba7a597e9a5b6f079cc0776
|
tweag/asterius
|
ByteString.hs
|
module Asterius.ByteString
( byteStringFromJSUint8Array,
byteStringToJSUint8Array,
unsafeByteStringToJSUint8Array,
lazyByteStringToJSUint8Array,
)
where
import Asterius.Magic
import Asterius.Types
import Control.Exception
import qualified Data.ByteString as BS
import Data.ByteString.Internal (ByteString, fromForeignPtr)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Internal as LBS
import Data.ByteString.Unsafe (unsafeUseAsCStringLen)
import Data.Int
import Foreign.Ptr
# INLINEABLE byteStringFromJSUint8Array #
byteStringFromJSUint8Array :: JSUint8Array -> ByteString
byteStringFromJSUint8Array buf =
accursedUnutterablePerformIO $ do
fp <- fromJSUint8Array buf
len <- lengthOfJSUint8Array buf
evaluate $ fromForeignPtr fp 0 len
# INLINEABLE byteStringToJSUint8Array #
byteStringToJSUint8Array :: ByteString -> JSUint8Array
byteStringToJSUint8Array bs =
accursedUnutterablePerformIO
$ unsafeUseAsCStringLen bs
$ uncurry toJSUint8Array
{-# INLINEABLE unsafeByteStringToJSUint8Array #-}
unsafeByteStringToJSUint8Array :: ByteString -> JSUint8Array
unsafeByteStringToJSUint8Array bs =
accursedUnutterablePerformIO
$ unsafeUseAsCStringLen bs
$ uncurry unsafeToJSUint8Array
{-# INLINEABLE lazyByteStringToJSUint8Array #-}
lazyByteStringToJSUint8Array :: LBS.ByteString -> JSUint8Array
lazyByteStringToJSUint8Array lbs =
accursedUnutterablePerformIO $ do
r <- js_newUint8Array $ LBS.length lbs
let w _ LBS.Empty = pure ()
w i (LBS.Chunk c cs) =
unsafeUseAsCStringLen c (uncurry $ js_chunk_save r i)
*> w (i + BS.length c) cs
in w 0 lbs
pure r
foreign import javascript unsafe "new Uint8Array($1)"
js_newUint8Array ::
Int64 -> IO JSUint8Array
foreign import javascript unsafe "$1.subarray($2).set(__asterius_jsffi.exposeMemory($3, $4))"
js_chunk_save ::
JSUint8Array -> Int -> Ptr a -> Int -> IO ()
| null |
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/ghc-toolkit/boot-libs/asterius-prelude/src/Asterius/ByteString.hs
|
haskell
|
# INLINEABLE unsafeByteStringToJSUint8Array #
# INLINEABLE lazyByteStringToJSUint8Array #
|
module Asterius.ByteString
( byteStringFromJSUint8Array,
byteStringToJSUint8Array,
unsafeByteStringToJSUint8Array,
lazyByteStringToJSUint8Array,
)
where
import Asterius.Magic
import Asterius.Types
import Control.Exception
import qualified Data.ByteString as BS
import Data.ByteString.Internal (ByteString, fromForeignPtr)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Internal as LBS
import Data.ByteString.Unsafe (unsafeUseAsCStringLen)
import Data.Int
import Foreign.Ptr
# INLINEABLE byteStringFromJSUint8Array #
byteStringFromJSUint8Array :: JSUint8Array -> ByteString
byteStringFromJSUint8Array buf =
accursedUnutterablePerformIO $ do
fp <- fromJSUint8Array buf
len <- lengthOfJSUint8Array buf
evaluate $ fromForeignPtr fp 0 len
# INLINEABLE byteStringToJSUint8Array #
byteStringToJSUint8Array :: ByteString -> JSUint8Array
byteStringToJSUint8Array bs =
accursedUnutterablePerformIO
$ unsafeUseAsCStringLen bs
$ uncurry toJSUint8Array
unsafeByteStringToJSUint8Array :: ByteString -> JSUint8Array
unsafeByteStringToJSUint8Array bs =
accursedUnutterablePerformIO
$ unsafeUseAsCStringLen bs
$ uncurry unsafeToJSUint8Array
lazyByteStringToJSUint8Array :: LBS.ByteString -> JSUint8Array
lazyByteStringToJSUint8Array lbs =
accursedUnutterablePerformIO $ do
r <- js_newUint8Array $ LBS.length lbs
let w _ LBS.Empty = pure ()
w i (LBS.Chunk c cs) =
unsafeUseAsCStringLen c (uncurry $ js_chunk_save r i)
*> w (i + BS.length c) cs
in w 0 lbs
pure r
foreign import javascript unsafe "new Uint8Array($1)"
js_newUint8Array ::
Int64 -> IO JSUint8Array
foreign import javascript unsafe "$1.subarray($2).set(__asterius_jsffi.exposeMemory($3, $4))"
js_chunk_save ::
JSUint8Array -> Int -> Ptr a -> Int -> IO ()
|
c65b3f379312b939615abd80a0d70ce150b3340e0fc2667a6fa39ac7b6004419
|
emina/rosette
|
synthesize.rkt
|
#lang rosette
(require rackunit rackunit/text-ui rosette/lib/roseunit)
(define-symbolic a b c boolean?)
(define-symbolic xi yi zi integer?)
(define-symbolic xr yr zr real?)
(define-symbolic xb yb zb (bitvector 4))
(define basic-tests
(test-suite+ "Basic synthesis tests."
(current-bitwidth #f)
(check-unsat (synthesize #:forall '() #:guarantee (assert #f)))
(check-unsat (synthesize #:forall '() #:guarantee (begin (assume #f) (assert #f))))
(check-equal?
(model (check-sat (synthesize #:forall a #:guarantee (begin (assume a) (assert (&& a b))))))
(hash b #t))
(check-unsat (synthesize #:forall xb #:guarantee (assert (bvslt xb (bvadd xb yb)))))
(parameterize ([current-bitwidth 4])
(check-unsat (synthesize #:forall xi #:guarantee (assert (< xi (+ xi yi))))))
(check-true
(evaluate (> yi 0) (synthesize #:forall xi #:guarantee (assert (< xi (+ xi yi))))))
(check-true
(evaluate (> yr 0) (synthesize #:forall xr #:guarantee (assert (< xr (+ xr yr))))))
(check-true
(evaluate (> yr 0) (synthesize #:forall xi #:guarantee (assert (< xi (+ xi yr))))))
(check-true
(evaluate (>= yi 0) (synthesize #:forall xi #:guarantee (begin (assume (> xi 0)) (assert (>= xi yi))))))
))
(module+ test
(time (run-tests basic-tests)))
| null |
https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/test/query/synthesize.rkt
|
racket
|
#lang rosette
(require rackunit rackunit/text-ui rosette/lib/roseunit)
(define-symbolic a b c boolean?)
(define-symbolic xi yi zi integer?)
(define-symbolic xr yr zr real?)
(define-symbolic xb yb zb (bitvector 4))
(define basic-tests
(test-suite+ "Basic synthesis tests."
(current-bitwidth #f)
(check-unsat (synthesize #:forall '() #:guarantee (assert #f)))
(check-unsat (synthesize #:forall '() #:guarantee (begin (assume #f) (assert #f))))
(check-equal?
(model (check-sat (synthesize #:forall a #:guarantee (begin (assume a) (assert (&& a b))))))
(hash b #t))
(check-unsat (synthesize #:forall xb #:guarantee (assert (bvslt xb (bvadd xb yb)))))
(parameterize ([current-bitwidth 4])
(check-unsat (synthesize #:forall xi #:guarantee (assert (< xi (+ xi yi))))))
(check-true
(evaluate (> yi 0) (synthesize #:forall xi #:guarantee (assert (< xi (+ xi yi))))))
(check-true
(evaluate (> yr 0) (synthesize #:forall xr #:guarantee (assert (< xr (+ xr yr))))))
(check-true
(evaluate (> yr 0) (synthesize #:forall xi #:guarantee (assert (< xi (+ xi yr))))))
(check-true
(evaluate (>= yi 0) (synthesize #:forall xi #:guarantee (begin (assume (> xi 0)) (assert (>= xi yi))))))
))
(module+ test
(time (run-tests basic-tests)))
|
|
3ac0d290f3255ee2368703c74964594fd881a9f23b0871bfd44258b9f2331119
|
ktakashi/sagittarius-scheme
|
rsa.scm
|
-*- mode : scheme ; coding : utf-8 ; -*-
;;;
;;; sagittarius/crypto/signatures/rsa.scm - RSA signature
;;;
Copyright ( c ) 2022 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
#!nounbound
(library (sagittarius crypto signatures rsa)
(export *signature:rsa*
make-signer-state signer-state->signature
make-verifier-state verifier-state-verify-message
mgf-1
pkcs1-emsa-pss-encode pkcs1-emsa-pss-verify
pkcs1-emsa-v1.5-encode pkcs1-emsa-v1.5-verify
)
(import (rnrs)
(clos user)
(sagittarius crypto asn1)
(sagittarius crypto signatures types)
(sagittarius crypto ciphers asymmetric)
(sagittarius crypto keys)
(sagittarius crypto digests)
(sagittarius crypto random)
(sagittarius crypto secure)
(util bytevector))
(define *signature:rsa* *key:rsa*)
(define-class <rsa-signer-state> (<digest-signature-state> <signer-state>)
((encoder :init-keyword :encoder :reader rsa-signer-state-encoder)))
(define-class <rsa-verifier-state> (<digest-signature-state> <verifier-state>)
((verifier :init-keyword :verifier :reader rsa-verifier-state-verifier)))
;; Those who are very lazy..
(define-method make-signer-state ((m (eql *scheme:rsa*)) . args)
(apply make-signer-state *signature:rsa* args))
(define-method make-signer-state ((m (eql *signature:rsa*))
(key <rsa-private-key>)
:key (encoder pkcs1-emsa-pss-encode)
(digest *digest:sha-256*)
:allow-other-keys opts)
(make <rsa-signer-state> :encoder (apply encoder opts)
:key key :digest digest))
(define-method signer-state->signature ((state <rsa-signer-state>))
(let ((cipher (make-asymmetric-cipher *scheme:rsa*
:encoding (lambda ignore (values #f #f))))
(encoder (rsa-signer-state-encoder state))
(key (signature-state-key state))
(signing-message (digest-signature-state-signing-message! state)))
(asymmetric-cipher-init! cipher key)
(asymmetric-cipher-encrypt-bytevector
cipher (encoder (digest-signature-state-digest state)
(rsa-private-key-modulus key) signing-message))))
(define-method make-verifier-state ((m (eql *scheme:rsa*)) . opts)
(apply make-verifier-state *signature:rsa* opts))
(define-method make-verifier-state ((m (eql *signature:rsa*))
(key <rsa-public-key>)
:key (verifier pkcs1-emsa-pss-verify)
(digest *digest:sha-256*)
:allow-other-keys opts)
(make <rsa-verifier-state> :verifier (apply verifier opts)
:key key :digest digest))
(define-method verifier-state-verify-message ((state <rsa-verifier-state>)
(signature <bytevector>))
(let ((cipher (make-asymmetric-cipher *scheme:rsa*
:encoding (lambda ignore (values #f #f))))
(verifier (rsa-verifier-state-verifier state))
(key (signature-state-key state))
(signing-message (digest-signature-state-signing-message! state)))
(asymmetric-cipher-init! cipher key)
(let ((EM (asymmetric-cipher-decrypt-bytevector cipher signature)))
(verifier (digest-signature-state-digest state)
(rsa-public-key-modulus key) signing-message EM))))
EMSA PSS ENCODE
(define default-prng (secure-random-generator *prng:chacha20*))
(define (default-salt digest)
(random-generator-read-random-bytes default-prng
(digest-descriptor-digest-size digest)))
(define (pkcs1-emsa-pss-encode
:key (given-salt :salt #f)
(mgf mgf-1)
(given-mgf-digest :mgf-digest #f)
:allow-other-keys)
(lambda (digest modulus m)
(define digest-size (digest-descriptor-digest-size digest))
(define md (make-message-digest digest))
(define salt (or given-salt (default-salt digest)))
(define salt-len (bytevector-length salt))
(define mgf-digest (or given-mgf-digest digest))
(define em-bits (- (bitwise-length modulus) 1))
(define em-len (div (+ em-bits 7) 8))
(when (< em-len (+ digest-size salt-len 2))
(assertion-violation 'pkcs1-emsa-pss-encode
"Intended encoded message length too short"))
(let ((m-dash (make-bytevector (+ digest-size salt-len 8) 0)))
M ' = ( 0x)00 00 00 00 00 00 00 00 || mHash || salt
(bytevector-copy! m 0 m-dash 8 digest-size)
(bytevector-copy! salt 0 m-dash (+ 8 digest-size) salt-len)
(let* ((H (digest-message md m-dash))
(PS-len (- em-len salt-len digest-size 2))
(PS (make-bytevector PS-len 0))
(DB (make-bytevector (+ PS-len salt-len 1) #x01)))
(bytevector-copy! PS 0 DB 0 PS-len)
(bytevector-copy! salt 0 DB (+ PS-len 1) salt-len)
(let* ((db-mask (mgf H (- em-len digest-size 1) mgf-digest))
(masked-db (bytevector-xor DB db-mask))
(bit-mask (bitwise-arithmetic-shift-right
#xFF (- (* em-len 8) em-bits))))
(bytevector-u8-set! masked-db 0
(bitwise-and (bytevector-u8-ref masked-db 0)
bit-mask))
(let* ((m-len (bytevector-length masked-db))
(h-len (bytevector-length H))
(EM (make-bytevector (+ m-len h-len 1) #xBC)))
(bytevector-copy! masked-db 0 EM 0 m-len)
(bytevector-copy! H 0 EM m-len h-len)
EM))))))
(define (pkcs1-emsa-pss-verify
:key (given-salt-len :salt-length #f)
(mgf mgf-1)
(given-mgf-digest :mgf-digest #f)
:allow-other-keys)
(lambda (digest modulus m EM)
(define digest-size (digest-descriptor-digest-size digest))
(define md (make-message-digest digest))
(define salt-len (or given-salt-len
(digest-descriptor-digest-size digest)))
(define mgf-digest (or given-mgf-digest digest))
(define (check-zero bv limit)
(let loop ((i 0) (ok? #t))
(if (= i limit)
ok?
(loop (+ i 1) (and (zero? (bytevector-u8-ref bv i)) ok?)))))
(define em-bits (- (bitwise-length modulus) 1))
(define em-len (div (+ em-bits 7) 8))
;; we do entire step here to prevent oracle attack
(let* ((mask-length (- em-len digest-size 1))
(masked-db (make-bytevector mask-length 0))
(H (make-bytevector digest-size 0))
(bit-mask (bitwise-arithmetic-shift-right
#xFF (- (* 8 em-len) em-bits))))
(bytevector-copy! EM 0 masked-db 0 mask-length)
(bytevector-copy! EM mask-length H 0 digest-size)
(let* ((db-mask (mgf H mask-length mgf-digest))
;; we need masked-db to check at the last step
(DB (bytevector-xor masked-db db-mask))
(limit2 (- em-len digest-size salt-len 2)))
(bytevector-u8-set! DB 0
(bitwise-and (bytevector-u8-ref DB 0) bit-mask))
(let ((check0 (check-zero DB limit2))
(check1 (= #x01 (bytevector-u8-ref DB limit2)))
(m-dash (make-bytevector (+ 8 digest-size salt-len) 0)))
(bytevector-copy! m 0 m-dash 8 digest-size)
(bytevector-copy! DB (- (bytevector-length DB) salt-len)
m-dash (+ 8 digest-size) salt-len)
(let ((h-dash (digest-message md m-dash)))
longest , do it first
(not (< em-len (+ digest-size salt-len 2)))
(= #xBC (bytevector-u8-ref EM (- (bytevector-length EM) 1)))
(zero? (bitwise-and (bytevector-u8-ref masked-db 0)
(bitwise-not bit-mask)))
check0
check1)))))))
(define ((pkcs1-emsa-v1.5-encode . ignore) digest modulus m
:optional (no-null? #f))
(define oid (digest-descriptor-oid digest))
(let* ((em-len (div (+ (bitwise-length modulus) 7) 8))
(asn1 (der-sequence
(make-der-sequence
(filter values (list
(oid-string->der-object-identifier oid)
(and (not no-null?) (make-der-null)))))
(bytevector->der-octet-string m)))
(T (asn1-encodable->bytevector asn1))
(t-len (bytevector-length T)))
(when (< em-len (+ t-len 11))
(error 'pkcs1-emsa-v1.5-encode
"Intended encoded message length too short"))
(let* ((PS-len (- em-len t-len 3))
Initialize with PS value
(EM (make-bytevector (+ PS-len 3 t-len) #xFF)))
(bytevector-u8-set! EM 0 #x00)
(bytevector-u8-set! EM 1 #x01)
(bytevector-u8-set! EM (+ PS-len 2) #x00)
(bytevector-copy! T 0 EM (+ PS-len 3) t-len)
EM)))
(define (pkcs1-emsa-v1.5-verify . opts)
(define encode (pkcs1-emsa-v1.5-encode))
(lambda (digest modulus m S)
(or (let ((EM (encode digest modulus m)))
(safe-bytevector=? EM S))
(let ((EM (encode digest modulus m #t)))
(safe-bytevector=? EM S)))))
)
| null |
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/8d3be98032133507b87d6c0466d60f982ebf9b15/ext/crypto/sagittarius/crypto/signatures/rsa.scm
|
scheme
|
coding : utf-8 ; -*-
sagittarius/crypto/signatures/rsa.scm - RSA signature
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Those who are very lazy..
we do entire step here to prevent oracle attack
we need masked-db to check at the last step
|
Copyright ( c ) 2022 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
#!nounbound
(library (sagittarius crypto signatures rsa)
(export *signature:rsa*
make-signer-state signer-state->signature
make-verifier-state verifier-state-verify-message
mgf-1
pkcs1-emsa-pss-encode pkcs1-emsa-pss-verify
pkcs1-emsa-v1.5-encode pkcs1-emsa-v1.5-verify
)
(import (rnrs)
(clos user)
(sagittarius crypto asn1)
(sagittarius crypto signatures types)
(sagittarius crypto ciphers asymmetric)
(sagittarius crypto keys)
(sagittarius crypto digests)
(sagittarius crypto random)
(sagittarius crypto secure)
(util bytevector))
(define *signature:rsa* *key:rsa*)
(define-class <rsa-signer-state> (<digest-signature-state> <signer-state>)
((encoder :init-keyword :encoder :reader rsa-signer-state-encoder)))
(define-class <rsa-verifier-state> (<digest-signature-state> <verifier-state>)
((verifier :init-keyword :verifier :reader rsa-verifier-state-verifier)))
(define-method make-signer-state ((m (eql *scheme:rsa*)) . args)
(apply make-signer-state *signature:rsa* args))
(define-method make-signer-state ((m (eql *signature:rsa*))
(key <rsa-private-key>)
:key (encoder pkcs1-emsa-pss-encode)
(digest *digest:sha-256*)
:allow-other-keys opts)
(make <rsa-signer-state> :encoder (apply encoder opts)
:key key :digest digest))
(define-method signer-state->signature ((state <rsa-signer-state>))
(let ((cipher (make-asymmetric-cipher *scheme:rsa*
:encoding (lambda ignore (values #f #f))))
(encoder (rsa-signer-state-encoder state))
(key (signature-state-key state))
(signing-message (digest-signature-state-signing-message! state)))
(asymmetric-cipher-init! cipher key)
(asymmetric-cipher-encrypt-bytevector
cipher (encoder (digest-signature-state-digest state)
(rsa-private-key-modulus key) signing-message))))
(define-method make-verifier-state ((m (eql *scheme:rsa*)) . opts)
(apply make-verifier-state *signature:rsa* opts))
(define-method make-verifier-state ((m (eql *signature:rsa*))
(key <rsa-public-key>)
:key (verifier pkcs1-emsa-pss-verify)
(digest *digest:sha-256*)
:allow-other-keys opts)
(make <rsa-verifier-state> :verifier (apply verifier opts)
:key key :digest digest))
(define-method verifier-state-verify-message ((state <rsa-verifier-state>)
(signature <bytevector>))
(let ((cipher (make-asymmetric-cipher *scheme:rsa*
:encoding (lambda ignore (values #f #f))))
(verifier (rsa-verifier-state-verifier state))
(key (signature-state-key state))
(signing-message (digest-signature-state-signing-message! state)))
(asymmetric-cipher-init! cipher key)
(let ((EM (asymmetric-cipher-decrypt-bytevector cipher signature)))
(verifier (digest-signature-state-digest state)
(rsa-public-key-modulus key) signing-message EM))))
EMSA PSS ENCODE
(define default-prng (secure-random-generator *prng:chacha20*))
(define (default-salt digest)
(random-generator-read-random-bytes default-prng
(digest-descriptor-digest-size digest)))
(define (pkcs1-emsa-pss-encode
:key (given-salt :salt #f)
(mgf mgf-1)
(given-mgf-digest :mgf-digest #f)
:allow-other-keys)
(lambda (digest modulus m)
(define digest-size (digest-descriptor-digest-size digest))
(define md (make-message-digest digest))
(define salt (or given-salt (default-salt digest)))
(define salt-len (bytevector-length salt))
(define mgf-digest (or given-mgf-digest digest))
(define em-bits (- (bitwise-length modulus) 1))
(define em-len (div (+ em-bits 7) 8))
(when (< em-len (+ digest-size salt-len 2))
(assertion-violation 'pkcs1-emsa-pss-encode
"Intended encoded message length too short"))
(let ((m-dash (make-bytevector (+ digest-size salt-len 8) 0)))
M ' = ( 0x)00 00 00 00 00 00 00 00 || mHash || salt
(bytevector-copy! m 0 m-dash 8 digest-size)
(bytevector-copy! salt 0 m-dash (+ 8 digest-size) salt-len)
(let* ((H (digest-message md m-dash))
(PS-len (- em-len salt-len digest-size 2))
(PS (make-bytevector PS-len 0))
(DB (make-bytevector (+ PS-len salt-len 1) #x01)))
(bytevector-copy! PS 0 DB 0 PS-len)
(bytevector-copy! salt 0 DB (+ PS-len 1) salt-len)
(let* ((db-mask (mgf H (- em-len digest-size 1) mgf-digest))
(masked-db (bytevector-xor DB db-mask))
(bit-mask (bitwise-arithmetic-shift-right
#xFF (- (* em-len 8) em-bits))))
(bytevector-u8-set! masked-db 0
(bitwise-and (bytevector-u8-ref masked-db 0)
bit-mask))
(let* ((m-len (bytevector-length masked-db))
(h-len (bytevector-length H))
(EM (make-bytevector (+ m-len h-len 1) #xBC)))
(bytevector-copy! masked-db 0 EM 0 m-len)
(bytevector-copy! H 0 EM m-len h-len)
EM))))))
(define (pkcs1-emsa-pss-verify
:key (given-salt-len :salt-length #f)
(mgf mgf-1)
(given-mgf-digest :mgf-digest #f)
:allow-other-keys)
(lambda (digest modulus m EM)
(define digest-size (digest-descriptor-digest-size digest))
(define md (make-message-digest digest))
(define salt-len (or given-salt-len
(digest-descriptor-digest-size digest)))
(define mgf-digest (or given-mgf-digest digest))
(define (check-zero bv limit)
(let loop ((i 0) (ok? #t))
(if (= i limit)
ok?
(loop (+ i 1) (and (zero? (bytevector-u8-ref bv i)) ok?)))))
(define em-bits (- (bitwise-length modulus) 1))
(define em-len (div (+ em-bits 7) 8))
(let* ((mask-length (- em-len digest-size 1))
(masked-db (make-bytevector mask-length 0))
(H (make-bytevector digest-size 0))
(bit-mask (bitwise-arithmetic-shift-right
#xFF (- (* 8 em-len) em-bits))))
(bytevector-copy! EM 0 masked-db 0 mask-length)
(bytevector-copy! EM mask-length H 0 digest-size)
(let* ((db-mask (mgf H mask-length mgf-digest))
(DB (bytevector-xor masked-db db-mask))
(limit2 (- em-len digest-size salt-len 2)))
(bytevector-u8-set! DB 0
(bitwise-and (bytevector-u8-ref DB 0) bit-mask))
(let ((check0 (check-zero DB limit2))
(check1 (= #x01 (bytevector-u8-ref DB limit2)))
(m-dash (make-bytevector (+ 8 digest-size salt-len) 0)))
(bytevector-copy! m 0 m-dash 8 digest-size)
(bytevector-copy! DB (- (bytevector-length DB) salt-len)
m-dash (+ 8 digest-size) salt-len)
(let ((h-dash (digest-message md m-dash)))
longest , do it first
(not (< em-len (+ digest-size salt-len 2)))
(= #xBC (bytevector-u8-ref EM (- (bytevector-length EM) 1)))
(zero? (bitwise-and (bytevector-u8-ref masked-db 0)
(bitwise-not bit-mask)))
check0
check1)))))))
(define ((pkcs1-emsa-v1.5-encode . ignore) digest modulus m
:optional (no-null? #f))
(define oid (digest-descriptor-oid digest))
(let* ((em-len (div (+ (bitwise-length modulus) 7) 8))
(asn1 (der-sequence
(make-der-sequence
(filter values (list
(oid-string->der-object-identifier oid)
(and (not no-null?) (make-der-null)))))
(bytevector->der-octet-string m)))
(T (asn1-encodable->bytevector asn1))
(t-len (bytevector-length T)))
(when (< em-len (+ t-len 11))
(error 'pkcs1-emsa-v1.5-encode
"Intended encoded message length too short"))
(let* ((PS-len (- em-len t-len 3))
Initialize with PS value
(EM (make-bytevector (+ PS-len 3 t-len) #xFF)))
(bytevector-u8-set! EM 0 #x00)
(bytevector-u8-set! EM 1 #x01)
(bytevector-u8-set! EM (+ PS-len 2) #x00)
(bytevector-copy! T 0 EM (+ PS-len 3) t-len)
EM)))
(define (pkcs1-emsa-v1.5-verify . opts)
(define encode (pkcs1-emsa-v1.5-encode))
(lambda (digest modulus m S)
(or (let ((EM (encode digest modulus m)))
(safe-bytevector=? EM S))
(let ((EM (encode digest modulus m #t)))
(safe-bytevector=? EM S)))))
)
|
0e7af8e4e6413bf342ba3e8b293ea4b51700263a77902b9974f79e835c689cbf
|
nwf/dyna
|
TTerm.hs
|
---------------------------------------------------------------------------
-- | Very, very basic (Trivial, even) representation of terms.
--
-- XXX This isn't going to be sufficient when we start doing more
-- complicated things, but it suffices for now?
-- Header material {{{
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE KindSignatures #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}
module Dyna.Term.TTerm (
-- * Annotations
Annotation(..),
-- * Term Base Cases
TBase(..), TBaseSkolem(..),
-- * Terms
TermF(..), {- DTermV, -} DVar, DFunct, DFunctAr, {- DTerm, -}
-- * Rules
DRule ( .. ) ,
-- * Convenience re-export
UTerm ( .. )
) where
import qualified Data.ByteString as B
import qualified Data.Data as D
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import qualified Text.PrettyPrint.Free as PP
This is needed to work with ghc 7.4 and bytestring 0.9.2.1
import qualified Data.ByteString.Char8()
------------------------------------------------------------------------}}}
-- Term Base Cases {{{
data TBaseSkolem = TSBool | TSNumeric | TSString
deriving (Eq,Ord,Show)
-- | Term base cases.
data TBase = TBool !Bool
| TNumeric !(Either Integer Double)
| TString !B.ByteString
deriving (D.Data,D.Typeable,Eq,Ord,Show)
instance PP.Pretty TBase where
pretty ( TBool x ) = PP.pretty x
pretty (TBool True) = "true"
pretty (TBool False) = "false"
pretty (TNumeric (Left x)) = PP.pretty x
pretty (TNumeric (Right x)) = PP.pretty x
pretty (TString s) = PP.text $ show s
------------------------------------------------------------------------}}}
-- Terms {{{
data Annotation t = AnnType t
deriving (D.Data,D.Typeable,Eq,F.Foldable,Functor,Ord,Show,T.Traversable)
data TermF a t = TFunctor !a ![t]
| TBase !TBase
deriving (Eq,F.Foldable,Functor,Ord,Show,T.Traversable)
type DFunct = B.ByteString
type DFunctAr = (DFunct,Int)
type DVar = B.ByteString
------------------------------------------------------------------------}}}
-- Instances {{{
instance ( Eq a ) = > ( TermF a ) where
( TFunctor a as ) ( TFunctor b bs ) | a = = b
& & length as = = length bs
= Just ( TFunctor a ( zipWith ( \aa ba - > Right ( aa , ba ) ) as bs ) )
zipMatch _ _ = Nothing
instance (Eq a) => Unifiable (TermF a) where
zipMatch (TFunctor a as) (TFunctor b bs) | a == b
&& length as == length bs
= Just (TFunctor a (zipWith (\aa ba -> Right (aa,ba)) as bs))
zipMatch _ _ = Nothing
-}
------------------------------------------------------------------------}}}
-- Rules {{{
type DAgg = B.ByteString
data DRule = Rule ! DTerm ! DAgg ! [ DTerm ] ! DTerm
deriving ( Show )
data DRule = Rule !DTerm !DAgg ![DTerm] !DTerm
deriving (Show)
-}
------------------------------------------------------------------------}}}
| null |
https://raw.githubusercontent.com/nwf/dyna/74bdc852b906b902b53ca07dab0c8e0639ace8ba/src/Dyna/Term/TTerm.hs
|
haskell
|
-------------------------------------------------------------------------
| Very, very basic (Trivial, even) representation of terms.
XXX This isn't going to be sufficient when we start doing more
complicated things, but it suffices for now?
Header material {{{
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveTraversable #
# LANGUAGE OverloadedStrings #
# LANGUAGE Rank2Types #
* Annotations
* Term Base Cases
* Terms
DTermV,
DTerm,
* Rules
* Convenience re-export
----------------------------------------------------------------------}}}
Term Base Cases {{{
| Term base cases.
----------------------------------------------------------------------}}}
Terms {{{
----------------------------------------------------------------------}}}
Instances {{{
----------------------------------------------------------------------}}}
Rules {{{
----------------------------------------------------------------------}}}
|
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleContexts #
# LANGUAGE KindSignatures #
module Dyna.Term.TTerm (
Annotation(..),
TBase(..), TBaseSkolem(..),
DRule ( .. ) ,
UTerm ( .. )
) where
import qualified Data.ByteString as B
import qualified Data.Data as D
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import qualified Text.PrettyPrint.Free as PP
This is needed to work with ghc 7.4 and bytestring 0.9.2.1
import qualified Data.ByteString.Char8()
data TBaseSkolem = TSBool | TSNumeric | TSString
deriving (Eq,Ord,Show)
data TBase = TBool !Bool
| TNumeric !(Either Integer Double)
| TString !B.ByteString
deriving (D.Data,D.Typeable,Eq,Ord,Show)
instance PP.Pretty TBase where
pretty ( TBool x ) = PP.pretty x
pretty (TBool True) = "true"
pretty (TBool False) = "false"
pretty (TNumeric (Left x)) = PP.pretty x
pretty (TNumeric (Right x)) = PP.pretty x
pretty (TString s) = PP.text $ show s
data Annotation t = AnnType t
deriving (D.Data,D.Typeable,Eq,F.Foldable,Functor,Ord,Show,T.Traversable)
data TermF a t = TFunctor !a ![t]
| TBase !TBase
deriving (Eq,F.Foldable,Functor,Ord,Show,T.Traversable)
type DFunct = B.ByteString
type DFunctAr = (DFunct,Int)
type DVar = B.ByteString
instance ( Eq a ) = > ( TermF a ) where
( TFunctor a as ) ( TFunctor b bs ) | a = = b
& & length as = = length bs
= Just ( TFunctor a ( zipWith ( \aa ba - > Right ( aa , ba ) ) as bs ) )
zipMatch _ _ = Nothing
instance (Eq a) => Unifiable (TermF a) where
zipMatch (TFunctor a as) (TFunctor b bs) | a == b
&& length as == length bs
= Just (TFunctor a (zipWith (\aa ba -> Right (aa,ba)) as bs))
zipMatch _ _ = Nothing
-}
type DAgg = B.ByteString
data DRule = Rule ! DTerm ! DAgg ! [ DTerm ] ! DTerm
deriving ( Show )
data DRule = Rule !DTerm !DAgg ![DTerm] !DTerm
deriving (Show)
-}
|
161c8dae39cdf1d4c25396f7c825a8ff893966139c1b3edd5cead3a47e26eabb
|
agda/agda-ocaml
|
Instances.hs
|
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
# OPTIONS_GHC -fno - warn - orphans #
module Agda.Compiler.Malfunction.Instances where
import Agda.Syntax.Common
import qualified Agda.Syntax.Concrete as C
import qualified Agda.Syntax.Fixity as F
import Agda.Syntax.Literal
import Agda.Syntax.Notation
import Agda.Syntax.Position
import Agda.Syntax.Treeless
import Agda.Utils.FileName
import Data.Data
import Data.Graph
deriving instance Data F.Fixity'
deriving instance Data F.PrecedenceLevel
deriving instance Data F.Associativity
deriving instance Data MetaId
deriving instance Data NameId
deriving instance Data C.NamePart
deriving instance Data C.Name
deriving instance Data Hiding
deriving instance Data Big
deriving instance Data Relevance
deriving instance Data Origin
deriving instance Data ArgInfo
deriving instance Data (Ranged RawName)
deriving instance Data (Named_ Int)
deriving instance Data (NamedArg Int)
deriving instance Data GenPart
deriving instance Data F.Fixity
deriving instance Data AbsolutePath
deriving instance Data (Position' ())
deriving instance Data (Interval' ())
deriving instance Data Range
deriving instance Data TError
deriving instance Data CaseType
deriving instance Data ModuleName
deriving instance Data Name
deriving instance Data TAlt
deriving instance Data Literal
deriving instance Data TPrim
deriving instance Data QName
deriving instance Data TTerm
deriving instance Typeable TTerm
deriving instance Show vertex => Show (SCC vertex)
| null |
https://raw.githubusercontent.com/agda/agda-ocaml/e38b699870ba638221828b07b12948d70a1bdaec/src/full/Agda/Compiler/Malfunction/Instances.hs
|
haskell
|
# LANGUAGE DeriveDataTypeable #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeSynonymInstances #
|
# LANGUAGE FlexibleInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Agda.Compiler.Malfunction.Instances where
import Agda.Syntax.Common
import qualified Agda.Syntax.Concrete as C
import qualified Agda.Syntax.Fixity as F
import Agda.Syntax.Literal
import Agda.Syntax.Notation
import Agda.Syntax.Position
import Agda.Syntax.Treeless
import Agda.Utils.FileName
import Data.Data
import Data.Graph
deriving instance Data F.Fixity'
deriving instance Data F.PrecedenceLevel
deriving instance Data F.Associativity
deriving instance Data MetaId
deriving instance Data NameId
deriving instance Data C.NamePart
deriving instance Data C.Name
deriving instance Data Hiding
deriving instance Data Big
deriving instance Data Relevance
deriving instance Data Origin
deriving instance Data ArgInfo
deriving instance Data (Ranged RawName)
deriving instance Data (Named_ Int)
deriving instance Data (NamedArg Int)
deriving instance Data GenPart
deriving instance Data F.Fixity
deriving instance Data AbsolutePath
deriving instance Data (Position' ())
deriving instance Data (Interval' ())
deriving instance Data Range
deriving instance Data TError
deriving instance Data CaseType
deriving instance Data ModuleName
deriving instance Data Name
deriving instance Data TAlt
deriving instance Data Literal
deriving instance Data TPrim
deriving instance Data QName
deriving instance Data TTerm
deriving instance Typeable TTerm
deriving instance Show vertex => Show (SCC vertex)
|
2f0ca87b8b09a71f66274e8135040d14c843beca001e3f850677c034dae91440
|
tjknoth/resyn
|
Synthesizer.hs
|
-- | Top-level synthesizer interface
module Synquid.Synthesis.Synthesizer (
synthesize
) where
import Synquid.Util
import Synquid.Logic
import Synquid.Type hiding (set)
import Synquid.Program
import Synquid.Z3
import Synquid.Resolver
import Synquid.Synthesis.TypeChecker
import Synquid.Synthesis.Util
import Synquid.Solver.Monad
import Synquid.Solver.HornClause
import Synquid.Solver.TypeConstraint
import Synquid.Solver.Types
import Synquid.Solver.Resource (getAnnotationStyle, getPolynomialDomain)
import Data.List
import Control.Monad
import Control.Lens
import qualified Data.Set as Set
import qualified Data.Map as Map
type HornSolver = FixPointSolver Z3State
-- | 'synthesize' @templGenParam consGenParams solverParams env typ templ cq tq@ : synthesize a program that has a type @typ@
in the typing environment @env@ and follows template @templ@ ,
-- using conditional qualifiers @cquals@ and type qualifiers @tquals@,
-- with parameters for template generation, constraint generation, and constraint solving @templGenParam@ @consGenParams@ @solverParams@ respectively
synthesize :: ExplorerParams -> HornSolverParams -> Goal -> [Formula] -> [Formula] -> Maybe PersistentTState -> IO (Either ErrorMessage [(RProgram, TypingState)])
synthesize explorerParams solverParams goal cquals tquals mpts =
evalZ3State $ evalFixPointSolver reconstruction solverParams
where
-- | Stream of programs that satisfy the specification or type error
reconstruction :: HornSolver (Either ErrorMessage [(RProgram, TypingState)])
reconstruction = let
allSchema = gSpec goal : Map.elems (allSymbols (gEnvironment goal))
rdom = getAnnotationStyle (fmap _resourcePreds (gEnvironment goal ^. datatypes)) allSchema
pdom = getPolynomialDomain (fmap _resourcePreds (gEnvironment goal ^. datatypes)) (gSpec goal)
adj = set rSolverDomain rdom . set polynomialDomain pdom
typingParams = TypingParams {
_condQualsGen = condQuals,
_matchQualsGen = matchQuals,
_typeQualsGen = typeQuals,
_predQualsGen = predQuals,
_tcSolverSplitMeasures = _splitMeasures explorerParams,
_tcSolverLogLevel = _explorerLogLevel explorerParams,
_resourceArgs = adj (_explorerResourceArgs explorerParams)
}
in reconstruct explorerParams typingParams mpts goal
-- | Qualifier generator for conditionals
condQuals :: Environment -> [Formula] -> QSpace
condQuals env vars = toSpace Nothing $ concat $
map (instantiateCondQualifier False env vars) cquals ++ map (extractCondFromType env vars) (components ++ allArgTypes syntGoal)
-- | Qualifier generator for match scrutinees
matchQuals :: Environment -> [Formula] -> QSpace
matchQuals env vars = toSpace (Just 1) $ concatMap (extractMatchQGen env vars) (Map.toList $ gEnvironment goal ^. datatypes)
-- | Qualifier generator for types
typeQuals :: Environment -> Formula -> [Formula] -> QSpace
typeQuals env val vars = toSpace Nothing $ concat $
[ extractQGenFromType False env val vars syntGoal,
extractQGenFromType True env val vars syntGoal] -- extract from spec: both positive and negative
++ map (instantiateTypeQualifier env val vars) tquals -- extract from given qualifiers
++ map (extractQGenFromType False env val vars) components -- extract from components: only negative
-- ++ map (extractQGenFromType True env val vars) components -- extract from components: also positive for now
-- | Qualifier generator for bound predicates
predQuals :: Environment -> [Formula] -> [Formula] -> QSpace
predQuals env params vars = toSpace Nothing $
concatMap (extractPredQGenFromType True env params vars) (syntGoal : components) ++
if null params -- Parameter-less predicate: also include conditional qualifiers
then concatMap (instantiateCondQualifier False env vars) cquals ++ concatMap (extractCondFromType env vars) (components ++ allArgTypes syntGoal)
else []
components = componentsIn $ gEnvironment goal
componentsIn = map toMonotype . Map.elems . allSymbols
syntGoal = toMonotype $ gSpec goal
Qualifier Generators
-- | 'instantiateTypeQualifier ' @qual@: qualifier generator that treats free variables of @qual@ except _v as parameters
instantiateTypeQualifier :: Environment -> Formula -> [Formula] -> Formula -> [Formula]
instantiateTypeQualifier _ _ _ (BoolLit True) = []
instantiateTypeQualifier env actualVal actualVars qual =
let (formalVals, formalVars) = partition (\v -> varName v == valueVarName) . Set.toList . varsOf $ qual in
if length formalVals == 1
then allSubstitutions env qual formalVars actualVars formalVals [actualVal]
else []
-- | 'instantiateCondQualifier' @qual@: qualifier generator that treats free variables of @qual@ as parameters
instantiateCondQualifier :: Bool -> Environment -> [Formula] -> Formula -> [Formula]
instantiateCondQualifier allowDtEq env vars qual =
let f = if allowDtEq then const True else not . isDataEq in -- TODO: disallowing datatype equality in conditionals, this is a bit of a hack
filter f $ allSubstitutions env qual (Set.toList . varsOf $ qual) vars [] []
isDataEq (Binary op e1 _)
| op == Eq || op == Neq = isData (sortOf e1)
| otherwise = False
isDataEq _ = False
| ' extractMatchQGen ' @(dtName , dtDef)@ : qualifier generator that generates qualifiers of the form x = = ctor , for all scalar constructors ctor of datatype
extractMatchQGen :: Environment -> [Formula] -> (Id, DatatypeDef) -> [Formula]
extractMatchQGen env vars (dtName, DatatypeDef tParams _ _ ctors _ _) = concatMap extractForCtor ctors
where
-- Extract formulas x == @ctor@ for each x in @vars@
extractForCtor ctor = case toMonotype $ allSymbols env Map.! ctor of
ScalarT baseT fml _ ->
let fml' = sortSubstituteFml sortInst fml in
allSubstitutions env fml' [Var (sortSubstitute sortInst $ toSort baseT) valueVarName] vars [] []
_ -> []
sortInst = Map.fromList $ zip tParams (map VarS distinctTypeVars)
| ' extractQGenFromType ' @positive t@ : qualifier generator that extracts all conjuncts from refinements of @t@ and treats their free variables as parameters ;
extracts from positively or negatively occurring refinements depending on @positive@
extractQGenFromType :: Bool -> Environment -> Formula -> [Formula] -> RType -> [Formula]
extractQGenFromType positive env val vars t = extractQGenFromType' positive t
where
sortInst = Map.fromList $ zip (Set.toList $ typeVarsOf t) (map VarS distinctTypeVars)
extractQGenFromType' :: Bool -> RType -> [Formula]
extractQGenFromType' False (ScalarT _ _ _) = []
extractQGenFromType' True (ScalarT baseT fml pot) =
let
Datatype : extract from tArgs and
extractFromBase (DatatypeT dtName tArgs pArgs) =
let (DatatypeDef _ pParams _ _ _ _) = (env ^. datatypes) Map.! dtName
in concatMap (extractQGenFromType' True) tArgs ++ concat (zipWith extractQGenFromPred pParams pArgs)
-- Otherwise: no formulas
extractFromBase _ = []
fmls = Set.toList $ conjunctsOf (sortSubstituteFml sortInst fml) -- `Set.union` conjunctsOf (sortSubstituteFml sortInst pot)
in concatMap (instantiateTypeQualifier env val vars) fmls ++ extractFromBase baseT
extractQGenFromType' False (FunctionT _ tArg tRes _) = extractQGenFromType' True tArg ++ extractQGenFromType' False tRes
extractQGenFromType' True (FunctionT _ tArg tRes _) = extractQGenFromType' True tRes
-- Extract type qualifiers from a predicate argument of a datatype:
-- if the predicate has parameters, turn it into a type qualifier where the last parameter is replaced with _v
extractQGenFromPred (PredSig _ argSorts _) fml =
if null argSorts
then []
else let
lastSort = last argSorts
lastParam = deBrujns !! (length argSorts - 1)
fmls = Set.toList $ conjunctsOf $ sortSubstituteFml sortInst $ substitute (Map.singleton lastParam (Var lastSort valueVarName)) fml
in concatMap (instantiateTypeQualifier env val vars) fmls
| Extract conditional qualifiers from the types of Boolean functions
extractCondFromType :: Environment -> [Formula] -> RType -> [Formula]
extractCondFromType env vars t@(FunctionT _ tArg _ _) = case lastType t of
ScalarT BoolT (Binary Eq (Var BoolS v) fml) _ | v == valueVarName ->
let
sortInst = Map.fromList $ zip (Set.toList $ typeVarsOf t) (map VarS distinctTypeVars)
fml' = sortSubstituteFml sortInst fml
in filter (not . isDataEq) $ allSubstitutions env fml' (Set.toList . varsOf $ fml') vars [] []
_ -> []
extractCondFromType _ _ _ = []
extractPredQGenFromQual : : Bool - > Environment - > [ Formula ] - > [ Formula ] - > Formula - > [ Formula ]
extractPredQGenFromQual useAllArgs env actualParams actualVars fml =
if null actualParams
then [ ]
else let
( formalVals , formalVars ) = partition ( \v - > varName v = = valueVarName ) . Set.toList . varsOf $ fml
fmls = Set.toList $ conjunctsOf fml
extractFromConjunct c =
( init actualParams + + actualVars ) formalVals [ last actualParams ]
in concatMap extractFromConjunct where
filterAllArgs = if useAllArgs
then filter ( \q - > Set.fromList actualParams ` Set.isSubsetOf ` varsOf q ) -- Only take the qualifiers that use all predicate parameters
else i d
extractPredQGenFromQual :: Bool -> Environment -> [Formula] -> [Formula] -> Formula -> [Formula]
extractPredQGenFromQual useAllArgs env actualParams actualVars fml =
if null actualParams
then []
else let
(formalVals, formalVars) = partition (\v -> varName v == valueVarName) . Set.toList . varsOf $ fml
fmls = Set.toList $ conjunctsOf fml
extractFromConjunct c =
filterAllArgs $ allSubstitutions env c formalVars (init actualParams ++ actualVars) formalVals [last actualParams]
in concatMap extractFromConjunct fmls
where
filterAllArgs = if useAllArgs
then filter (\q -> Set.fromList actualParams `Set.isSubsetOf` varsOf q) -- Only take the qualifiers that use all predicate parameters
else id
-}
extractPredQGenFromType :: Bool -> Environment -> [Formula] -> [Formula] -> RType -> [Formula]
extractPredQGenFromType useAllArgs env actualParams actualVars t = extractPredQGenFromType' t
where
sortInst = Map.fromList $ zip (Set.toList $ typeVarsOf t) (map VarS distinctTypeVars)
isParam (Var _ name) = take 1 name == dontCare
isParam _ = False
filterAllArgs = if useAllArgs
then filter (\q -> Set.fromList actualParams `Set.isSubsetOf` varsOf q) -- Only take the qualifiers that use all predicate parameters
else id
-- Extract predicate qualifiers from a type refinement:
-- only allow replacing _v with the last parameter of the refinement
extractFromRefinement fml = if null actualParams
then []
else let
fml' = sortSubstituteFml sortInst fml
(formalVals, formalVars) = partition (\v -> varName v == valueVarName) . Set.toList . varsOf $ fml'
fmls = Set.toList $ conjunctsOf fml'
extractFromConjunct c =
filterAllArgs $ allSubstitutions env c formalVars (init actualParams ++ actualVars) formalVals [last actualParams]
in concatMap extractFromConjunct fmls
extractPredQGenFromType' :: RType -> [Formula]
extractPredQGenFromType' (ScalarT (DatatypeT dtName tArgs pArgs) fml pot) =
let extractFromPArg pArg =
let
pArg' = sortSubstituteFml sortInst pArg
(_, formalVars) = partition isParam (Set.toList $ varsOf pArg')
atoms = Set.toList $ ( atomsOf ' ` Set.union ` conjunctsOf pArg ' ) -- Uncomment this to enable disjunctive qualifiers
atoms = Set.toList $ atomsOf pArg'
extractFromAtom atom =
filterAllArgs $ allSubstitutions env atom formalVars (actualVars ++ actualParams) [] []
in concatMap extractFromAtom atoms -- Substitute the variables, but leave predicate parameters unchanged (optimization)
in extractFromRefinement fml {-++ extractFromRefinement pot-} ++ concatMap extractFromPArg pArgs ++ concatMap extractPredQGenFromType' tArgs
extractPredQGenFromType' (ScalarT _ fml pot) = extractFromRefinement fml -- ++ extractFromRefinement pot
extractPredQGenFromType' (FunctionT _ tArg tRes _) = extractPredQGenFromType' tArg ++ extractPredQGenFromType' tRes
-- | 'allSubstitutions' @env qual nonsubstActuals formals actuals@:
-- all well-typed substitutions of @actuals@ for @formals@ in a qualifier @qual@
allRawSubstitutions :: Environment -> Formula -> [Formula] -> [Formula] -> [Formula] -> [Formula] -> [Formula]
allRawSubstitutions _ (BoolLit True) _ _ _ _ = []
allRawSubstitutions env qual formals actuals fixedFormals fixedActuals = do
let tvs = Set.fromList (env ^. boundTypeVars)
case unifySorts tvs (map sortOf fixedFormals) (map sortOf fixedActuals) of
Left _ -> []
Right fixedSortSubst -> do
let fixedSubst = Map.fromList $ zip (map varName fixedFormals) fixedActuals
let qual' = substitute fixedSubst qual
(sortSubst, subst, _) <- foldM (go tvs) (fixedSortSubst, Map.empty, actuals) formals
return $ substitute subst $ sortSubstituteFml sortSubst qual'
where
go tvs (sortSubst, subst, actuals) formal = do
let formal' = sortSubstituteFml sortSubst formal
actual <- actuals
case unifySorts tvs [sortOf formal'] [sortOf actual] of
Left _ -> mzero
Right sortSubst' -> return (sortSubst `Map.union` sortSubst', Map.insert (varName formal) actual subst, delete actual actuals)
allSubstitutions :: Environment -> Formula -> [Formula] -> [Formula] -> [Formula] -> [Formula] -> [Formula]
allSubstitutions env qual formals actuals fixedFormals fixedActuals = do
qual' <- allRawSubstitutions env qual formals actuals fixedFormals fixedActuals
case resolveRefinement env qual' of
Left _ -> [] -- Variable sort mismatch
Right resolved -> return resolved
| null |
https://raw.githubusercontent.com/tjknoth/resyn/54ff304c635f26b4b498b82be267923a65e0662d/src/Synquid/Synthesis/Synthesizer.hs
|
haskell
|
| Top-level synthesizer interface
| 'synthesize' @templGenParam consGenParams solverParams env typ templ cq tq@ : synthesize a program that has a type @typ@
using conditional qualifiers @cquals@ and type qualifiers @tquals@,
with parameters for template generation, constraint generation, and constraint solving @templGenParam@ @consGenParams@ @solverParams@ respectively
| Stream of programs that satisfy the specification or type error
| Qualifier generator for conditionals
| Qualifier generator for match scrutinees
| Qualifier generator for types
extract from spec: both positive and negative
extract from given qualifiers
extract from components: only negative
++ map (extractQGenFromType True env val vars) components -- extract from components: also positive for now
| Qualifier generator for bound predicates
Parameter-less predicate: also include conditional qualifiers
| 'instantiateTypeQualifier ' @qual@: qualifier generator that treats free variables of @qual@ except _v as parameters
| 'instantiateCondQualifier' @qual@: qualifier generator that treats free variables of @qual@ as parameters
TODO: disallowing datatype equality in conditionals, this is a bit of a hack
Extract formulas x == @ctor@ for each x in @vars@
Otherwise: no formulas
`Set.union` conjunctsOf (sortSubstituteFml sortInst pot)
Extract type qualifiers from a predicate argument of a datatype:
if the predicate has parameters, turn it into a type qualifier where the last parameter is replaced with _v
Only take the qualifiers that use all predicate parameters
Only take the qualifiers that use all predicate parameters
Only take the qualifiers that use all predicate parameters
Extract predicate qualifiers from a type refinement:
only allow replacing _v with the last parameter of the refinement
Uncomment this to enable disjunctive qualifiers
Substitute the variables, but leave predicate parameters unchanged (optimization)
++ extractFromRefinement pot
++ extractFromRefinement pot
| 'allSubstitutions' @env qual nonsubstActuals formals actuals@:
all well-typed substitutions of @actuals@ for @formals@ in a qualifier @qual@
Variable sort mismatch
|
module Synquid.Synthesis.Synthesizer (
synthesize
) where
import Synquid.Util
import Synquid.Logic
import Synquid.Type hiding (set)
import Synquid.Program
import Synquid.Z3
import Synquid.Resolver
import Synquid.Synthesis.TypeChecker
import Synquid.Synthesis.Util
import Synquid.Solver.Monad
import Synquid.Solver.HornClause
import Synquid.Solver.TypeConstraint
import Synquid.Solver.Types
import Synquid.Solver.Resource (getAnnotationStyle, getPolynomialDomain)
import Data.List
import Control.Monad
import Control.Lens
import qualified Data.Set as Set
import qualified Data.Map as Map
type HornSolver = FixPointSolver Z3State
in the typing environment @env@ and follows template @templ@ ,
synthesize :: ExplorerParams -> HornSolverParams -> Goal -> [Formula] -> [Formula] -> Maybe PersistentTState -> IO (Either ErrorMessage [(RProgram, TypingState)])
synthesize explorerParams solverParams goal cquals tquals mpts =
evalZ3State $ evalFixPointSolver reconstruction solverParams
where
reconstruction :: HornSolver (Either ErrorMessage [(RProgram, TypingState)])
reconstruction = let
allSchema = gSpec goal : Map.elems (allSymbols (gEnvironment goal))
rdom = getAnnotationStyle (fmap _resourcePreds (gEnvironment goal ^. datatypes)) allSchema
pdom = getPolynomialDomain (fmap _resourcePreds (gEnvironment goal ^. datatypes)) (gSpec goal)
adj = set rSolverDomain rdom . set polynomialDomain pdom
typingParams = TypingParams {
_condQualsGen = condQuals,
_matchQualsGen = matchQuals,
_typeQualsGen = typeQuals,
_predQualsGen = predQuals,
_tcSolverSplitMeasures = _splitMeasures explorerParams,
_tcSolverLogLevel = _explorerLogLevel explorerParams,
_resourceArgs = adj (_explorerResourceArgs explorerParams)
}
in reconstruct explorerParams typingParams mpts goal
condQuals :: Environment -> [Formula] -> QSpace
condQuals env vars = toSpace Nothing $ concat $
map (instantiateCondQualifier False env vars) cquals ++ map (extractCondFromType env vars) (components ++ allArgTypes syntGoal)
matchQuals :: Environment -> [Formula] -> QSpace
matchQuals env vars = toSpace (Just 1) $ concatMap (extractMatchQGen env vars) (Map.toList $ gEnvironment goal ^. datatypes)
typeQuals :: Environment -> Formula -> [Formula] -> QSpace
typeQuals env val vars = toSpace Nothing $ concat $
[ extractQGenFromType False env val vars syntGoal,
predQuals :: Environment -> [Formula] -> [Formula] -> QSpace
predQuals env params vars = toSpace Nothing $
concatMap (extractPredQGenFromType True env params vars) (syntGoal : components) ++
then concatMap (instantiateCondQualifier False env vars) cquals ++ concatMap (extractCondFromType env vars) (components ++ allArgTypes syntGoal)
else []
components = componentsIn $ gEnvironment goal
componentsIn = map toMonotype . Map.elems . allSymbols
syntGoal = toMonotype $ gSpec goal
Qualifier Generators
instantiateTypeQualifier :: Environment -> Formula -> [Formula] -> Formula -> [Formula]
instantiateTypeQualifier _ _ _ (BoolLit True) = []
instantiateTypeQualifier env actualVal actualVars qual =
let (formalVals, formalVars) = partition (\v -> varName v == valueVarName) . Set.toList . varsOf $ qual in
if length formalVals == 1
then allSubstitutions env qual formalVars actualVars formalVals [actualVal]
else []
instantiateCondQualifier :: Bool -> Environment -> [Formula] -> Formula -> [Formula]
instantiateCondQualifier allowDtEq env vars qual =
filter f $ allSubstitutions env qual (Set.toList . varsOf $ qual) vars [] []
isDataEq (Binary op e1 _)
| op == Eq || op == Neq = isData (sortOf e1)
| otherwise = False
isDataEq _ = False
| ' extractMatchQGen ' @(dtName , dtDef)@ : qualifier generator that generates qualifiers of the form x = = ctor , for all scalar constructors ctor of datatype
extractMatchQGen :: Environment -> [Formula] -> (Id, DatatypeDef) -> [Formula]
extractMatchQGen env vars (dtName, DatatypeDef tParams _ _ ctors _ _) = concatMap extractForCtor ctors
where
extractForCtor ctor = case toMonotype $ allSymbols env Map.! ctor of
ScalarT baseT fml _ ->
let fml' = sortSubstituteFml sortInst fml in
allSubstitutions env fml' [Var (sortSubstitute sortInst $ toSort baseT) valueVarName] vars [] []
_ -> []
sortInst = Map.fromList $ zip tParams (map VarS distinctTypeVars)
| ' extractQGenFromType ' @positive t@ : qualifier generator that extracts all conjuncts from refinements of @t@ and treats their free variables as parameters ;
extracts from positively or negatively occurring refinements depending on @positive@
extractQGenFromType :: Bool -> Environment -> Formula -> [Formula] -> RType -> [Formula]
extractQGenFromType positive env val vars t = extractQGenFromType' positive t
where
sortInst = Map.fromList $ zip (Set.toList $ typeVarsOf t) (map VarS distinctTypeVars)
extractQGenFromType' :: Bool -> RType -> [Formula]
extractQGenFromType' False (ScalarT _ _ _) = []
extractQGenFromType' True (ScalarT baseT fml pot) =
let
Datatype : extract from tArgs and
extractFromBase (DatatypeT dtName tArgs pArgs) =
let (DatatypeDef _ pParams _ _ _ _) = (env ^. datatypes) Map.! dtName
in concatMap (extractQGenFromType' True) tArgs ++ concat (zipWith extractQGenFromPred pParams pArgs)
extractFromBase _ = []
in concatMap (instantiateTypeQualifier env val vars) fmls ++ extractFromBase baseT
extractQGenFromType' False (FunctionT _ tArg tRes _) = extractQGenFromType' True tArg ++ extractQGenFromType' False tRes
extractQGenFromType' True (FunctionT _ tArg tRes _) = extractQGenFromType' True tRes
extractQGenFromPred (PredSig _ argSorts _) fml =
if null argSorts
then []
else let
lastSort = last argSorts
lastParam = deBrujns !! (length argSorts - 1)
fmls = Set.toList $ conjunctsOf $ sortSubstituteFml sortInst $ substitute (Map.singleton lastParam (Var lastSort valueVarName)) fml
in concatMap (instantiateTypeQualifier env val vars) fmls
| Extract conditional qualifiers from the types of Boolean functions
extractCondFromType :: Environment -> [Formula] -> RType -> [Formula]
extractCondFromType env vars t@(FunctionT _ tArg _ _) = case lastType t of
ScalarT BoolT (Binary Eq (Var BoolS v) fml) _ | v == valueVarName ->
let
sortInst = Map.fromList $ zip (Set.toList $ typeVarsOf t) (map VarS distinctTypeVars)
fml' = sortSubstituteFml sortInst fml
in filter (not . isDataEq) $ allSubstitutions env fml' (Set.toList . varsOf $ fml') vars [] []
_ -> []
extractCondFromType _ _ _ = []
extractPredQGenFromQual : : Bool - > Environment - > [ Formula ] - > [ Formula ] - > Formula - > [ Formula ]
extractPredQGenFromQual useAllArgs env actualParams actualVars fml =
if null actualParams
then [ ]
else let
( formalVals , formalVars ) = partition ( \v - > varName v = = valueVarName ) . Set.toList . varsOf $ fml
fmls = Set.toList $ conjunctsOf fml
extractFromConjunct c =
( init actualParams + + actualVars ) formalVals [ last actualParams ]
in concatMap extractFromConjunct where
filterAllArgs = if useAllArgs
else i d
extractPredQGenFromQual :: Bool -> Environment -> [Formula] -> [Formula] -> Formula -> [Formula]
extractPredQGenFromQual useAllArgs env actualParams actualVars fml =
if null actualParams
then []
else let
(formalVals, formalVars) = partition (\v -> varName v == valueVarName) . Set.toList . varsOf $ fml
fmls = Set.toList $ conjunctsOf fml
extractFromConjunct c =
filterAllArgs $ allSubstitutions env c formalVars (init actualParams ++ actualVars) formalVals [last actualParams]
in concatMap extractFromConjunct fmls
where
filterAllArgs = if useAllArgs
else id
-}
extractPredQGenFromType :: Bool -> Environment -> [Formula] -> [Formula] -> RType -> [Formula]
extractPredQGenFromType useAllArgs env actualParams actualVars t = extractPredQGenFromType' t
where
sortInst = Map.fromList $ zip (Set.toList $ typeVarsOf t) (map VarS distinctTypeVars)
isParam (Var _ name) = take 1 name == dontCare
isParam _ = False
filterAllArgs = if useAllArgs
else id
extractFromRefinement fml = if null actualParams
then []
else let
fml' = sortSubstituteFml sortInst fml
(formalVals, formalVars) = partition (\v -> varName v == valueVarName) . Set.toList . varsOf $ fml'
fmls = Set.toList $ conjunctsOf fml'
extractFromConjunct c =
filterAllArgs $ allSubstitutions env c formalVars (init actualParams ++ actualVars) formalVals [last actualParams]
in concatMap extractFromConjunct fmls
extractPredQGenFromType' :: RType -> [Formula]
extractPredQGenFromType' (ScalarT (DatatypeT dtName tArgs pArgs) fml pot) =
let extractFromPArg pArg =
let
pArg' = sortSubstituteFml sortInst pArg
(_, formalVars) = partition isParam (Set.toList $ varsOf pArg')
atoms = Set.toList $ atomsOf pArg'
extractFromAtom atom =
filterAllArgs $ allSubstitutions env atom formalVars (actualVars ++ actualParams) [] []
extractPredQGenFromType' (FunctionT _ tArg tRes _) = extractPredQGenFromType' tArg ++ extractPredQGenFromType' tRes
allRawSubstitutions :: Environment -> Formula -> [Formula] -> [Formula] -> [Formula] -> [Formula] -> [Formula]
allRawSubstitutions _ (BoolLit True) _ _ _ _ = []
allRawSubstitutions env qual formals actuals fixedFormals fixedActuals = do
let tvs = Set.fromList (env ^. boundTypeVars)
case unifySorts tvs (map sortOf fixedFormals) (map sortOf fixedActuals) of
Left _ -> []
Right fixedSortSubst -> do
let fixedSubst = Map.fromList $ zip (map varName fixedFormals) fixedActuals
let qual' = substitute fixedSubst qual
(sortSubst, subst, _) <- foldM (go tvs) (fixedSortSubst, Map.empty, actuals) formals
return $ substitute subst $ sortSubstituteFml sortSubst qual'
where
go tvs (sortSubst, subst, actuals) formal = do
let formal' = sortSubstituteFml sortSubst formal
actual <- actuals
case unifySorts tvs [sortOf formal'] [sortOf actual] of
Left _ -> mzero
Right sortSubst' -> return (sortSubst `Map.union` sortSubst', Map.insert (varName formal) actual subst, delete actual actuals)
allSubstitutions :: Environment -> Formula -> [Formula] -> [Formula] -> [Formula] -> [Formula] -> [Formula]
allSubstitutions env qual formals actuals fixedFormals fixedActuals = do
qual' <- allRawSubstitutions env qual formals actuals fixedFormals fixedActuals
case resolveRefinement env qual' of
Right resolved -> return resolved
|
657995892c8345551e178ecb4e7bf99fda48832f757b23d16951df67d6ee205b
|
exercism/clojurescript
|
example.cljs
|
(ns isbn-verifier)
(defn- error-checker-fn
"Check the ISBN data structure against any invalidate status and if it is, do not call the function.
Some kinda high order fail-safe function. For Forward-Reading, look at Railway oriented programming."
[f {validation :validation :as isbn}]
(if validation
(f isbn)
isbn))
(defn- init-isbn10-d
"Takes ISBN-10 string and initialize the structure of the exercise logic."
[isbn10]
{:isbn isbn10 :validation true})
(defn- isbn10-count-validation*
"Check the ISBN10 character count against any invalid string.
If there is any invalid situation, set the :validation flag `false`"
[isbn]
(if (or
(-> isbn :isbn count (< 9))
(-> isbn :isbn count (> 13)))
(assoc-in isbn [:validation] false)
isbn))
(def isbn10-count-validation
"ISBN10 count function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-count-validation*))
(defn- isbn10-X-validator*
"Takes ISBN structure and check the last character of it.
If it is `X` character:
- Set the calculated total value with summed with ten.
If not:
- Do not change anything."
[{isbn :isbn :as isbn10}]
(if (-> isbn last (= \X))
(update-in isbn10 [:calculated-tot] + 10)
isbn10))
(def isbn10-X-validator
"ISBN10 X validator function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-X-validator*))
(defn- isbn10-number-sequences*
"Generate ISBN10 number sequence for the calculation."
[{isbn :isbn :as isbn10}]
(assoc-in isbn10 [:isbn10-sequence] (vec (map int (re-seq #"\d" isbn)))))
(def isbn10-number-sequences
"ISBN10 number sequence function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-number-sequences*))
(defn- isbn10-calculate-value*
"ISBN10 calculate the desired value and assoc it to the structure."
[{isbn-sq :isbn10-sequence :as isbn10}]
(let [middle-calc (reverse (range 1 11))
calculated-formula (map * isbn-sq middle-calc)
final-calculation (reduce + calculated-formula)]
(-> isbn10
(assoc-in [:calculated-tot] final-calculation))))
(def isbn10-calculate-value
"ISBN10 calculate value function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-calculate-value*))
(defn- isbn10-calculated-validation*
"ISBN10 calculate final validation result based on the calculated total value."
[{ct :calculated-tot :as isbn10}]
(if (zero? (mod ct 11))
isbn10
(assoc-in isbn10 [:validation] false)))
(def isbn10-calculated-validation
"ISBN10 calculate final validation function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-calculated-validation*))
(defn- isbn10-validate
"A simple value extractor from the ISBN structure."
[{validation :validation}]
validation)
(defn isbn?
"isbn? is the final and composed function with all our simple and tiny logics on data."
[isbn]
(-> isbn
init-isbn10-d
isbn10-count-validation
isbn10-number-sequences
isbn10-calculate-value
isbn10-X-validator
isbn10-calculated-validation
isbn10-validate))
| null |
https://raw.githubusercontent.com/exercism/clojurescript/7700a33e17a798f6320aad01fb59a637bd21e12b/exercises/practice/isbn-verifier/.meta/src/example.cljs
|
clojure
|
(ns isbn-verifier)
(defn- error-checker-fn
"Check the ISBN data structure against any invalidate status and if it is, do not call the function.
Some kinda high order fail-safe function. For Forward-Reading, look at Railway oriented programming."
[f {validation :validation :as isbn}]
(if validation
(f isbn)
isbn))
(defn- init-isbn10-d
"Takes ISBN-10 string and initialize the structure of the exercise logic."
[isbn10]
{:isbn isbn10 :validation true})
(defn- isbn10-count-validation*
"Check the ISBN10 character count against any invalid string.
If there is any invalid situation, set the :validation flag `false`"
[isbn]
(if (or
(-> isbn :isbn count (< 9))
(-> isbn :isbn count (> 13)))
(assoc-in isbn [:validation] false)
isbn))
(def isbn10-count-validation
"ISBN10 count function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-count-validation*))
(defn- isbn10-X-validator*
"Takes ISBN structure and check the last character of it.
If it is `X` character:
- Set the calculated total value with summed with ten.
If not:
- Do not change anything."
[{isbn :isbn :as isbn10}]
(if (-> isbn last (= \X))
(update-in isbn10 [:calculated-tot] + 10)
isbn10))
(def isbn10-X-validator
"ISBN10 X validator function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-X-validator*))
(defn- isbn10-number-sequences*
"Generate ISBN10 number sequence for the calculation."
[{isbn :isbn :as isbn10}]
(assoc-in isbn10 [:isbn10-sequence] (vec (map int (re-seq #"\d" isbn)))))
(def isbn10-number-sequences
"ISBN10 number sequence function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-number-sequences*))
(defn- isbn10-calculate-value*
"ISBN10 calculate the desired value and assoc it to the structure."
[{isbn-sq :isbn10-sequence :as isbn10}]
(let [middle-calc (reverse (range 1 11))
calculated-formula (map * isbn-sq middle-calc)
final-calculation (reduce + calculated-formula)]
(-> isbn10
(assoc-in [:calculated-tot] final-calculation))))
(def isbn10-calculate-value
"ISBN10 calculate value function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-calculate-value*))
(defn- isbn10-calculated-validation*
"ISBN10 calculate final validation result based on the calculated total value."
[{ct :calculated-tot :as isbn10}]
(if (zero? (mod ct 11))
isbn10
(assoc-in isbn10 [:validation] false)))
(def isbn10-calculated-validation
"ISBN10 calculate final validation function combined with fail-safe function wrapper."
(partial error-checker-fn isbn10-calculated-validation*))
(defn- isbn10-validate
"A simple value extractor from the ISBN structure."
[{validation :validation}]
validation)
(defn isbn?
"isbn? is the final and composed function with all our simple and tiny logics on data."
[isbn]
(-> isbn
init-isbn10-d
isbn10-count-validation
isbn10-number-sequences
isbn10-calculate-value
isbn10-X-validator
isbn10-calculated-validation
isbn10-validate))
|
|
9338c82c9c878ee1897b67392c5006641bb623a3434d56bc2f4f3f4ac32fb75f
|
jixiuf/helloerlang
|
mochiweb_test_sup.erl
|
@author Mochi Media < >
@copyright 2010 Mochi Media < >
%% @doc Supervisor for the mochiweb_test application.
-module(mochiweb_test_sup).
-author("Mochi Media <>").
-behaviour(supervisor).
%% External exports
-export([start_link/0, upgrade/0]).
%% supervisor callbacks
-export([init/1]).
( ) - > ServerRet
%% @doc API for starting the supervisor.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@spec upgrade ( ) - > ok
%% @doc Add processes if necessary.
upgrade() ->
{ok, {_, Specs}} = init([]),
Old = sets:from_list(
[Name || {Name, _, _, _} <- supervisor:which_children(?MODULE)]),
New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]),
Kill = sets:subtract(Old, New),
sets:fold(fun (Id, ok) ->
supervisor:terminate_child(?MODULE, Id),
supervisor:delete_child(?MODULE, Id),
ok
end, ok, Kill),
[supervisor:start_child(?MODULE, Spec) || Spec <- Specs],
ok.
@spec init ( [ ] ) - > SupervisorTree
%% @doc supervisor callback.
init([]) ->
Web = web_specs(mochiweb_test_web, 8080),
Processes = [Web],
Strategy = {one_for_one, 10, 10},
{ok,
{Strategy, lists:flatten(Processes)}}.
web_specs(Mod, Port) ->
WebConfig = [{ip, {0,0,0,0}},
{port, Port},
{docroot, mochiweb_test_deps:local_path(["priv", "www"])}],
{Mod,
{Mod, start, [WebConfig]},
permanent, 5000, worker, dynamic}.
| null |
https://raw.githubusercontent.com/jixiuf/helloerlang/3960eb4237b026f98edf35d6064539259a816d58/mochiweb_test/src/mochiweb_test_sup.erl
|
erlang
|
@doc Supervisor for the mochiweb_test application.
External exports
supervisor callbacks
@doc API for starting the supervisor.
@doc Add processes if necessary.
@doc supervisor callback.
|
@author Mochi Media < >
@copyright 2010 Mochi Media < >
-module(mochiweb_test_sup).
-author("Mochi Media <>").
-behaviour(supervisor).
-export([start_link/0, upgrade/0]).
-export([init/1]).
( ) - > ServerRet
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@spec upgrade ( ) - > ok
upgrade() ->
{ok, {_, Specs}} = init([]),
Old = sets:from_list(
[Name || {Name, _, _, _} <- supervisor:which_children(?MODULE)]),
New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]),
Kill = sets:subtract(Old, New),
sets:fold(fun (Id, ok) ->
supervisor:terminate_child(?MODULE, Id),
supervisor:delete_child(?MODULE, Id),
ok
end, ok, Kill),
[supervisor:start_child(?MODULE, Spec) || Spec <- Specs],
ok.
@spec init ( [ ] ) - > SupervisorTree
init([]) ->
Web = web_specs(mochiweb_test_web, 8080),
Processes = [Web],
Strategy = {one_for_one, 10, 10},
{ok,
{Strategy, lists:flatten(Processes)}}.
web_specs(Mod, Port) ->
WebConfig = [{ip, {0,0,0,0}},
{port, Port},
{docroot, mochiweb_test_deps:local_path(["priv", "www"])}],
{Mod,
{Mod, start, [WebConfig]},
permanent, 5000, worker, dynamic}.
|
63b265ad3d9114415ee50aacdd4bd4cb0bbd6cae35e8e75eb2a2b0a2a7c9322f
|
kelamg/HtDP2e-workthrough
|
ex475.rkt
|
The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex475) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(require 2htdp/abstraction)
; A Node is a Symbol.
A DestinationNode is a Node
A Neighbors is a [ List - of DestinationNode ]
A is a [ List - of [ List - of Node Neighbours ] ]
; A Path is a [List-of Node].
; interpretation The list of nodes specifies a sequence
of immediate neighbors that leads from the first
; Node on the list to the last one.
(define sample-graph
'((A (B E))
(B (E F))
(C (D))
(D ())
(E (C F))
(F (D G))
(G ())))
(define G sample-graph)
(define cyclic-graph
'((A (B E))
(B (E F))
(C (B D))
(D ())
(E (C F))
(F (D))
(G ())))
Node Node Graph - > [ Maybe Path ]
; finds a path from origination to destination in G
; if there is no path, the function produces #false
(check-expect (find-path 'C 'D G)
'(C D))
(check-member-of (find-path 'E 'D G)
'(E F D) '(E C D))
(check-expect (find-path 'C 'G G)
#false)
(define (find-path origination destination G)
(local ((define (find-path origination destination)
(cond
[(symbol=? origination destination) (list destination)]
[else
(local ((define next (neighbors origination G))
(define candidate
(find-path/list next destination)))
(cond
[(boolean? candidate) #false]
[else (cons origination candidate)]))]))
; [List-of Node] Node -> [Maybe Path]
; finds a path from some node on lo-originations to
; destination; otherwise, it produces #false
(define (find-path/list lo-Os D)
(for/or ([node lo-Os])
(local ((define candidate (find-path node D)))
(if (boolean? candidate) #false candidate)))))
(find-path origination destination)))
;; Node Graph -> Neighbours
produces the nodes to which one edge exists from node n
(check-expect (neighbors 'A G) '(B E))
(check-expect (neighbors 'G G) '())
(check-error (neighbors 'Z G))
(define (neighbors n g)
(local ((define found (assq n g)))
(if (false? found) (error "node does not exist") (second found))))
;; Graph -> Boolean
;; produces #true if there is a path between any pair of nodes
(define all-have-paths
'((A (B))
(B (E))
(E (A))))
(check-expect (test-on-all-nodes G) #false)
(check-expect (test-on-all-nodes all-have-paths) #true)
(define (test-on-all-nodes g)
(local ((define all-nodes (map first g))
(define all-pairs
(for*/list ([i all-nodes] [j all-nodes])
(list i j))))
(for/and ([pair all-pairs])
(cons? (find-path (first pair) (second pair) g)))))
| null |
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Generative-Recursion/ex475.rkt
|
racket
|
about the language level of this file in a form that our tools can easily process.
A Node is a Symbol.
A Path is a [List-of Node].
interpretation The list of nodes specifies a sequence
Node on the list to the last one.
finds a path from origination to destination in G
if there is no path, the function produces #false
[List-of Node] Node -> [Maybe Path]
finds a path from some node on lo-originations to
destination; otherwise, it produces #false
Node Graph -> Neighbours
Graph -> Boolean
produces #true if there is a path between any pair of nodes
|
The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex475) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(require 2htdp/abstraction)
A DestinationNode is a Node
A Neighbors is a [ List - of DestinationNode ]
A is a [ List - of [ List - of Node Neighbours ] ]
of immediate neighbors that leads from the first
(define sample-graph
'((A (B E))
(B (E F))
(C (D))
(D ())
(E (C F))
(F (D G))
(G ())))
(define G sample-graph)
(define cyclic-graph
'((A (B E))
(B (E F))
(C (B D))
(D ())
(E (C F))
(F (D))
(G ())))
Node Node Graph - > [ Maybe Path ]
(check-expect (find-path 'C 'D G)
'(C D))
(check-member-of (find-path 'E 'D G)
'(E F D) '(E C D))
(check-expect (find-path 'C 'G G)
#false)
(define (find-path origination destination G)
(local ((define (find-path origination destination)
(cond
[(symbol=? origination destination) (list destination)]
[else
(local ((define next (neighbors origination G))
(define candidate
(find-path/list next destination)))
(cond
[(boolean? candidate) #false]
[else (cons origination candidate)]))]))
(define (find-path/list lo-Os D)
(for/or ([node lo-Os])
(local ((define candidate (find-path node D)))
(if (boolean? candidate) #false candidate)))))
(find-path origination destination)))
produces the nodes to which one edge exists from node n
(check-expect (neighbors 'A G) '(B E))
(check-expect (neighbors 'G G) '())
(check-error (neighbors 'Z G))
(define (neighbors n g)
(local ((define found (assq n g)))
(if (false? found) (error "node does not exist") (second found))))
(define all-have-paths
'((A (B))
(B (E))
(E (A))))
(check-expect (test-on-all-nodes G) #false)
(check-expect (test-on-all-nodes all-have-paths) #true)
(define (test-on-all-nodes g)
(local ((define all-nodes (map first g))
(define all-pairs
(for*/list ([i all-nodes] [j all-nodes])
(list i j))))
(for/and ([pair all-pairs])
(cons? (find-path (first pair) (second pair) g)))))
|
2a9096c557b527078f263ad9f968459fd65073690aabc33b7355acb3224585ad
|
footprintanalytics/footprint-web
|
name_test.clj
|
(ns metabase.sync.analyze.classifiers.name-test
(:require [clojure.test :refer :all]
[metabase.models.field :refer [Field]]
[metabase.models.interface :as mi]
[metabase.models.table :as table :refer [Table]]
[metabase.sync.analyze.classifiers.name :as classifiers.name]
[metabase.test :as mt]
[toucan.db :as db]))
(deftest semantic-type-for-name-and-base-type-test
(doseq [[input expected] {["id" :type/Integer] :type/PK
;; other pattern matches based on type/regex (remember, base_type matters in matching!)
["rating" :type/Integer] :type/Score
["rating" :type/Boolean] nil
["country" :type/Text] :type/Country
["country" :type/Integer] nil}]
(testing (pr-str (cons 'semantic-type-for-name-and-base-type input))
(is (= expected
(apply #'classifiers.name/semantic-type-for-name-and-base-type input))))))
(deftest infer-entity-type-test
(testing "name matches"
(let [classify (fn [table-name] (-> (mi/instance Table {:name table-name})
classifiers.name/infer-entity-type
:entity_type))]
(testing "matches simple"
(is (= :entity/TransactionTable (classify "MY_ORDERS"))))
(testing "matches prefix"
(is (= :entity/ProductTable (classify "productcatalogue"))))
(testing "doesn't match in the middle"
(is (= :entity/GenericTable (classify "myproductcatalogue"))))
(testing "defaults to generic table"
(is (= :entity/GenericTable (classify "foo"))))))
(testing "When using field info"
(testing "doesn't infer on PK/FK semantic_types"
(mt/with-temp* [Table [{table-id :id}]
Field [{field-id :id} {:table_id table-id
:semantic_type :type/FK
:name "City"
:base_type :type/Text}]]
(is (nil? (-> (db/select-one Field :id field-id) (classifiers.name/infer-and-assoc-semantic-type nil) :semantic_type)))))
(testing "but does infer on non-PK/FK fields"
(mt/with-temp* [Table [{table-id :id}]
Field [{field-id :id} {:table_id table-id
:semantic_type :type/Category
:name "City"
:base_type :type/Text}]]
(-> (db/select-one Field :id field-id) (classifiers.name/infer-and-assoc-semantic-type nil) :semantic_type)))))
(deftest infer-semantic-type-test
(let [infer (fn infer [column-name & [base-type]]
(classifiers.name/infer-semantic-type
{:name column-name, :base_type (or base-type :type/Text)}))]
(testing "standard checks"
;; not exhausting but a place for edge cases in the future
(are [expected info] (= expected (apply infer info))
:type/Name ["first_name"]
:type/Name ["name"]
:type/Quantity ["quantity" :type/Integer]))
(testing "name and type matches"
(testing "matches \"updated at\" style columns"
(let [classify (fn [table-name table-type] (-> (mi/instance Table {:name table-name :base_type table-type})
classifiers.name/infer-semantic-type))]
(doseq [[col-type expected] [[:type/Date :type/UpdatedDate]
[:type/DateTime :type/UpdatedTimestamp]
[:type/Time :type/UpdatedTime]]]
(doseq [column-name ["updated_at" "updated" "updated-at"]]
(is (= expected (classify column-name col-type))))))))
(testing "Doesn't mark state columns (#2735)"
(doseq [column-name ["state" "order_state" "state_of_order"]]
(is (not= :type/State (infer column-name)))))))
| null |
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/test/metabase/sync/analyze/classifiers/name_test.clj
|
clojure
|
other pattern matches based on type/regex (remember, base_type matters in matching!)
not exhausting but a place for edge cases in the future
|
(ns metabase.sync.analyze.classifiers.name-test
(:require [clojure.test :refer :all]
[metabase.models.field :refer [Field]]
[metabase.models.interface :as mi]
[metabase.models.table :as table :refer [Table]]
[metabase.sync.analyze.classifiers.name :as classifiers.name]
[metabase.test :as mt]
[toucan.db :as db]))
(deftest semantic-type-for-name-and-base-type-test
(doseq [[input expected] {["id" :type/Integer] :type/PK
["rating" :type/Integer] :type/Score
["rating" :type/Boolean] nil
["country" :type/Text] :type/Country
["country" :type/Integer] nil}]
(testing (pr-str (cons 'semantic-type-for-name-and-base-type input))
(is (= expected
(apply #'classifiers.name/semantic-type-for-name-and-base-type input))))))
(deftest infer-entity-type-test
(testing "name matches"
(let [classify (fn [table-name] (-> (mi/instance Table {:name table-name})
classifiers.name/infer-entity-type
:entity_type))]
(testing "matches simple"
(is (= :entity/TransactionTable (classify "MY_ORDERS"))))
(testing "matches prefix"
(is (= :entity/ProductTable (classify "productcatalogue"))))
(testing "doesn't match in the middle"
(is (= :entity/GenericTable (classify "myproductcatalogue"))))
(testing "defaults to generic table"
(is (= :entity/GenericTable (classify "foo"))))))
(testing "When using field info"
(testing "doesn't infer on PK/FK semantic_types"
(mt/with-temp* [Table [{table-id :id}]
Field [{field-id :id} {:table_id table-id
:semantic_type :type/FK
:name "City"
:base_type :type/Text}]]
(is (nil? (-> (db/select-one Field :id field-id) (classifiers.name/infer-and-assoc-semantic-type nil) :semantic_type)))))
(testing "but does infer on non-PK/FK fields"
(mt/with-temp* [Table [{table-id :id}]
Field [{field-id :id} {:table_id table-id
:semantic_type :type/Category
:name "City"
:base_type :type/Text}]]
(-> (db/select-one Field :id field-id) (classifiers.name/infer-and-assoc-semantic-type nil) :semantic_type)))))
(deftest infer-semantic-type-test
(let [infer (fn infer [column-name & [base-type]]
(classifiers.name/infer-semantic-type
{:name column-name, :base_type (or base-type :type/Text)}))]
(testing "standard checks"
(are [expected info] (= expected (apply infer info))
:type/Name ["first_name"]
:type/Name ["name"]
:type/Quantity ["quantity" :type/Integer]))
(testing "name and type matches"
(testing "matches \"updated at\" style columns"
(let [classify (fn [table-name table-type] (-> (mi/instance Table {:name table-name :base_type table-type})
classifiers.name/infer-semantic-type))]
(doseq [[col-type expected] [[:type/Date :type/UpdatedDate]
[:type/DateTime :type/UpdatedTimestamp]
[:type/Time :type/UpdatedTime]]]
(doseq [column-name ["updated_at" "updated" "updated-at"]]
(is (= expected (classify column-name col-type))))))))
(testing "Doesn't mark state columns (#2735)"
(doseq [column-name ["state" "order_state" "state_of_order"]]
(is (not= :type/State (infer column-name)))))))
|
a79f389fead32a9052a4f18bf3d6ab550cbb0ae9c661bd61a24bb0eff7889a0c
|
theobat/massalia
|
MorpheusTypes.hs
|
# OPTIONS_GHC -fno - warn - orphans #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE DerivingVia #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
-- |
Module : . MorpheusTypes
Description : A reexport of the handy functions and types from " " .
And their orphan instances for GQLType
module Massalia.MorpheusTypes
(
module Data.Morpheus.Types,
module Data.Morpheus.Types.GQLScalar
)
where
import qualified Data.Aeson as JSON
import Data.Morpheus.Types.GQLScalar ( EncodeScalar(encodeScalar), DecodeScalar(decodeScalar) )
import Data.Morpheus.Types (GQLType(description), KIND)
import Data.Morpheus.Kind (SCALAR)
import qualified Data.Morpheus.Types as GQLT
import Massalia.Utils (UTCTime,
EmailAddress, LocalTime, ZonedTime, ZonedTimeEq, UUID, Day,
SimpleRange, Inclusivity (..),
emailToByteString, emailValidate, stringToText, uuidFromText, uuidToText
)
import Massalia.Auth (JWTEncodedString(JWTEncodedString))
import Protolude
instance EncodeScalar UUID where
encodeScalar = GQLT.String . uuidToText
instance DecodeScalar UUID where
decodeScalar (GQLT.String x) = case uuidFromText x of
Nothing -> Left $ "The given value = " <> x <> " is not a correct UUID"
Just iid -> pure iid
decodeScalar _ = Left "The given value is not a string"
instance GQLType UUID where
type KIND UUID = SCALAR
instance EncodeScalar UTCTime where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar UTCTime where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "UTCTime can only be String"
instance GQLType UTCTime where
type KIND UTCTime = SCALAR
instance EncodeScalar LocalTime where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar LocalTime where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "LocalTime can only be String"
instance GQLType LocalTime where
type KIND LocalTime = SCALAR
instance EncodeScalar ZonedTime where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar ZonedTime where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "ZonedTime can only be String"
instance GQLType ZonedTime where
type KIND ZonedTime = SCALAR
instance EncodeScalar ZonedTimeEq where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar ZonedTimeEq where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "ZonedTimeEq can only be String"
instance GQLType ZonedTimeEq where
type KIND ZonedTimeEq = SCALAR
instance EncodeScalar Day where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar Day where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "Day can only be String"
instance GQLType Day where
type KIND Day = SCALAR
instance EncodeScalar EmailAddress where
encodeScalar = GQLT.String . (decodeUtf8 . emailToByteString)
instance DecodeScalar EmailAddress where
decodeScalar (GQLT.String x) = first stringToText $ emailValidate $ encodeUtf8 x
decodeScalar _ = Left "EmailAddress can only be String"
instance GQLType EmailAddress where
type KIND EmailAddress = SCALAR
instance EncodeScalar JWTEncodedString where
encodeScalar (JWTEncodedString val) = GQLT.String val
instance DecodeScalar JWTEncodedString where
decodeScalar (GQLT.String x) = pure $ JWTEncodedString x
decodeScalar _ = Left "JWTEncodedString can only be String"
instance GQLType JWTEncodedString where
type KIND JWTEncodedString = SCALAR
instance EncodeScalar Void where
encodeScalar _ = panic "Impossible, trying to serialize void"
instance DecodeScalar Void where
decodeScalar _ = Left "Impossible, trying to parse to void (that is, this field should be null or undefined)"
instance GQLType Void where
type KIND Void = SCALAR
instance (Typeable a, GQLType a) => GQLType (SimpleRange a) where
description = const $ Just ("A simple range structure for filtering in postgres, it's ultimately translated as a PostgresRange" :: Text)
instance EncodeScalar Inclusivity where
encodeScalar x = case x of
II -> GQLT.String "[]"
IE -> GQLT.String "[)"
EI -> GQLT.String "(]"
EE -> GQLT.String "()"
instance DecodeScalar Inclusivity where
decodeScalar (GQLT.String x) = case x of
"[]" -> Right II
"[)" -> Right IE
"(]" -> Right EI
"()" -> Right EE
_ -> Left $ "cannot parse range inclusivity = " <> x
decodeScalar _ = Left "Inclusivity can only be a String"
instance GQLType Inclusivity where
type KIND Inclusivity = SCALAR
| null |
https://raw.githubusercontent.com/theobat/massalia/25129187add0e3724deeb9cb473f2145b09c51dc/src/Massalia/MorpheusTypes.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
|
|
# OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE DerivingVia #
# LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
Module : . MorpheusTypes
Description : A reexport of the handy functions and types from " " .
And their orphan instances for GQLType
module Massalia.MorpheusTypes
(
module Data.Morpheus.Types,
module Data.Morpheus.Types.GQLScalar
)
where
import qualified Data.Aeson as JSON
import Data.Morpheus.Types.GQLScalar ( EncodeScalar(encodeScalar), DecodeScalar(decodeScalar) )
import Data.Morpheus.Types (GQLType(description), KIND)
import Data.Morpheus.Kind (SCALAR)
import qualified Data.Morpheus.Types as GQLT
import Massalia.Utils (UTCTime,
EmailAddress, LocalTime, ZonedTime, ZonedTimeEq, UUID, Day,
SimpleRange, Inclusivity (..),
emailToByteString, emailValidate, stringToText, uuidFromText, uuidToText
)
import Massalia.Auth (JWTEncodedString(JWTEncodedString))
import Protolude
instance EncodeScalar UUID where
encodeScalar = GQLT.String . uuidToText
instance DecodeScalar UUID where
decodeScalar (GQLT.String x) = case uuidFromText x of
Nothing -> Left $ "The given value = " <> x <> " is not a correct UUID"
Just iid -> pure iid
decodeScalar _ = Left "The given value is not a string"
instance GQLType UUID where
type KIND UUID = SCALAR
instance EncodeScalar UTCTime where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar UTCTime where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "UTCTime can only be String"
instance GQLType UTCTime where
type KIND UTCTime = SCALAR
instance EncodeScalar LocalTime where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar LocalTime where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "LocalTime can only be String"
instance GQLType LocalTime where
type KIND LocalTime = SCALAR
instance EncodeScalar ZonedTime where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar ZonedTime where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "ZonedTime can only be String"
instance GQLType ZonedTime where
type KIND ZonedTime = SCALAR
instance EncodeScalar ZonedTimeEq where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar ZonedTimeEq where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "ZonedTimeEq can only be String"
instance GQLType ZonedTimeEq where
type KIND ZonedTimeEq = SCALAR
instance EncodeScalar Day where
encodeScalar = GQLT.String . (fromMaybe "" . JSON.decode . JSON.encode)
instance DecodeScalar Day where
decodeScalar (GQLT.String x) = first stringToText $ JSON.eitherDecode $ JSON.encode x
decodeScalar _ = Left "Day can only be String"
instance GQLType Day where
type KIND Day = SCALAR
instance EncodeScalar EmailAddress where
encodeScalar = GQLT.String . (decodeUtf8 . emailToByteString)
instance DecodeScalar EmailAddress where
decodeScalar (GQLT.String x) = first stringToText $ emailValidate $ encodeUtf8 x
decodeScalar _ = Left "EmailAddress can only be String"
instance GQLType EmailAddress where
type KIND EmailAddress = SCALAR
instance EncodeScalar JWTEncodedString where
encodeScalar (JWTEncodedString val) = GQLT.String val
instance DecodeScalar JWTEncodedString where
decodeScalar (GQLT.String x) = pure $ JWTEncodedString x
decodeScalar _ = Left "JWTEncodedString can only be String"
instance GQLType JWTEncodedString where
type KIND JWTEncodedString = SCALAR
instance EncodeScalar Void where
encodeScalar _ = panic "Impossible, trying to serialize void"
instance DecodeScalar Void where
decodeScalar _ = Left "Impossible, trying to parse to void (that is, this field should be null or undefined)"
instance GQLType Void where
type KIND Void = SCALAR
instance (Typeable a, GQLType a) => GQLType (SimpleRange a) where
description = const $ Just ("A simple range structure for filtering in postgres, it's ultimately translated as a PostgresRange" :: Text)
instance EncodeScalar Inclusivity where
encodeScalar x = case x of
II -> GQLT.String "[]"
IE -> GQLT.String "[)"
EI -> GQLT.String "(]"
EE -> GQLT.String "()"
instance DecodeScalar Inclusivity where
decodeScalar (GQLT.String x) = case x of
"[]" -> Right II
"[)" -> Right IE
"(]" -> Right EI
"()" -> Right EE
_ -> Left $ "cannot parse range inclusivity = " <> x
decodeScalar _ = Left "Inclusivity can only be a String"
instance GQLType Inclusivity where
type KIND Inclusivity = SCALAR
|
15c680e905b951631cdc33a12fd88a3fb28af1027b1207ffb974ddd2c97be1d3
|
nuvla/api-server
|
infrastructure_service_template_test.clj
|
(ns sixsq.nuvla.server.resources.infrastructure-service-template-test
(:require
[clojure.test :refer [deftest use-fixtures]]
[peridot.core :refer [content-type header request session]]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.infrastructure-service-template :as tpl]
[sixsq.nuvla.server.resources.infrastructure-service-template-generic :as tpl-generic]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.util.metadata-test-utils :as mdtu]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context tpl/resource-type))
(deftest check-metadata
(mdtu/check-metadata-exists "infrastructure-service-template-generic"))
(deftest ensure-templates-exist
(doseq [subtype [tpl-generic/method]]
(let [session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon")
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")
tpl (str tpl/resource-type "/" subtype)
resource-uri (str p/service-context tpl)]
;; anonymous access to template must fail
(-> session-anon
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; admin and user access must succeed
(doseq [session [session-admin session-user]]
(-> session
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 200))))))
(deftest bad-methods
(let [resource-uri (str p/service-context tpl/resource-type "/" tpl-generic/method)]
(ltu/verify-405-status [[base-uri :post]
[base-uri :delete]
[resource-uri :put]
[resource-uri :post]
[resource-uri :delete]])))
| null |
https://raw.githubusercontent.com/nuvla/api-server/272c1b8f7a5cd306d01464cf801d6174df146f71/code/test/sixsq/nuvla/server/resources/infrastructure_service_template_test.clj
|
clojure
|
anonymous access to template must fail
admin and user access must succeed
|
(ns sixsq.nuvla.server.resources.infrastructure-service-template-test
(:require
[clojure.test :refer [deftest use-fixtures]]
[peridot.core :refer [content-type header request session]]
[sixsq.nuvla.server.app.params :as p]
[sixsq.nuvla.server.middleware.authn-info :refer [authn-info-header]]
[sixsq.nuvla.server.resources.infrastructure-service-template :as tpl]
[sixsq.nuvla.server.resources.infrastructure-service-template-generic :as tpl-generic]
[sixsq.nuvla.server.resources.lifecycle-test-utils :as ltu]
[sixsq.nuvla.server.util.metadata-test-utils :as mdtu]))
(use-fixtures :once ltu/with-test-server-fixture)
(def base-uri (str p/service-context tpl/resource-type))
(deftest check-metadata
(mdtu/check-metadata-exists "infrastructure-service-template-generic"))
(deftest ensure-templates-exist
(doseq [subtype [tpl-generic/method]]
(let [session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "group/nuvla-admin group/nuvla-admin group/nuvla-user group/nuvla-anon")
session-user (header session authn-info-header "user/jane user/jane group/nuvla-user group/nuvla-anon")
session-anon (header session authn-info-header "user/unknown user/unknown group/nuvla-anon")
tpl (str tpl/resource-type "/" subtype)
resource-uri (str p/service-context tpl)]
(-> session-anon
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 403))
(doseq [session [session-admin session-user]]
(-> session
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 200))))))
(deftest bad-methods
(let [resource-uri (str p/service-context tpl/resource-type "/" tpl-generic/method)]
(ltu/verify-405-status [[base-uri :post]
[base-uri :delete]
[resource-uri :put]
[resource-uri :post]
[resource-uri :delete]])))
|
ebdd741d611d2207cd414dec238bebe4c272608423cacb7cacc7e7b015aff2e9
|
albertoruiz/easyVision
|
stand1.hs
|
import Vision.GUI
import Image
main = runIt win
win = standalone (Size 100 400) "click to change" x0 updts [] sh
where
x0 = 7
sh = text (Point 0 0) . show
updts = [(key (MouseButton LeftButton), \_droi _pt -> (+1)) ]
| null |
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/tour/stand1.hs
|
haskell
|
import Vision.GUI
import Image
main = runIt win
win = standalone (Size 100 400) "click to change" x0 updts [] sh
where
x0 = 7
sh = text (Point 0 0) . show
updts = [(key (MouseButton LeftButton), \_droi _pt -> (+1)) ]
|
|
6e91a1a0e6922f34bc64092dc3c0b971b8a52b8a26315887248616b121d9b590
|
pjotrp/guix
|
ssh.scm
|
;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 , 2015 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU 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.
;;;
;;; GNU Guix 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 GNU . If not , see < / > .
(define-module (gnu services ssh)
#:use-module (guix gexp)
#:use-module (guix records)
#:use-module (gnu services)
#:use-module (gnu services dmd)
#:use-module (gnu system pam)
#:use-module (gnu packages lsh)
#:use-module (srfi srfi-26)
#:export (lsh-service))
;;; Commentary:
;;;
;;; This module implements secure shell (SSH) services.
;;;
;;; Code:
;; TODO: Export.
(define-record-type* <lsh-configuration>
lsh-configuration make-lsh-configuration
lsh-configuration?
(lsh lsh-configuration-lsh
(default lsh))
(daemonic? lsh-configuration-daemonic?)
(host-key lsh-configuration-host-key)
(interfaces lsh-configuration-interfaces)
(port-number lsh-configuration-port-number)
(allow-empty-passwords? lsh-configuration-allow-empty-passwords?)
(root-login? lsh-configuration-root-login?)
(syslog-output? lsh-configuration-syslog-output?)
(pid-file? lsh-configuration-pid-file?)
(pid-file lsh-configuration-pid-file)
(x11-forwarding? lsh-configuration-x11-forwarding?)
(tcp/ip-forwarding? lsh-configuration-tcp/ip-forwarding?)
(password-authentication? lsh-configuration-password-authentication?)
(public-key-authentication? lsh-configuration-public-key-authentication?)
(initialize? lsh-configuration-initialize?))
(define %yarrow-seed
"/var/spool/lsh/yarrow-seed-file")
(define (lsh-initialization lsh host-key)
"Return the gexp to initialize the LSH service for HOST-KEY."
#~(begin
(unless (file-exists? #$%yarrow-seed)
(system* (string-append #$lsh "/bin/lsh-make-seed")
"--sloppy" "-o" #$%yarrow-seed))
(unless (file-exists? #$host-key)
(mkdir-p (dirname #$host-key))
(format #t "creating SSH host key '~a'...~%" #$host-key)
;; FIXME: We're just doing a simple pipeline, but 'system' cannot be
used yet because /bin / sh might be dangling ; factorize this somehow .
(let* ((in+out (pipe))
(keygen (primitive-fork)))
(case keygen
((0)
(close-port (car in+out))
(close-fdes 1)
(dup2 (fileno (cdr in+out)) 1)
(execl (string-append #$lsh "/bin/lsh-keygen")
"lsh-keygen" "--server"))
(else
(let ((write-key (primitive-fork)))
(case write-key
((0)
(close-port (cdr in+out))
(close-fdes 0)
(dup2 (fileno (car in+out)) 0)
(execl (string-append #$lsh "/bin/lsh-writekey")
"lsh-writekey" "--server" "-o" #$host-key))
(else
(close-port (car in+out))
(close-port (cdr in+out))
(waitpid keygen)
(waitpid write-key))))))))))
(define (lsh-activation config)
"Return the activation gexp for CONFIG."
#~(begin
(use-modules (guix build utils))
(mkdir-p "/var/spool/lsh")
#$(if (lsh-configuration-initialize? config)
(lsh-initialization (lsh-configuration-lsh config)
(lsh-configuration-host-key config))
#t)))
(define (lsh-dmd-service config)
"Return a <dmd-service> for lsh with CONFIG."
(define lsh (lsh-configuration-lsh config))
(define pid-file (lsh-configuration-pid-file config))
(define pid-file? (lsh-configuration-pid-file? config))
(define daemonic? (lsh-configuration-daemonic? config))
(define interfaces (lsh-configuration-interfaces config))
(define lsh-command
(append
(cons #~(string-append #$lsh "/sbin/lshd")
(if daemonic?
(let ((syslog (if (lsh-configuration-syslog-output? config)
'()
(list "--no-syslog"))))
(cons "--daemonic"
(if pid-file?
(cons #~(string-append "--pid-file=" #$pid-file)
syslog)
(cons "--no-pid-file" syslog))))
(if pid-file?
(list #~(string-append "--pid-file=" #$pid-file))
'())))
(cons* #~(string-append "--host-key="
#$(lsh-configuration-host-key config))
#~(string-append "--password-helper=" #$lsh "/sbin/lsh-pam-checkpw")
#~(string-append "--subsystems=sftp=" #$lsh "/sbin/sftp-server")
"-p" (number->string (lsh-configuration-port-number config))
(if (lsh-configuration-password-authentication? config)
"--password" "--no-password")
(if (lsh-configuration-public-key-authentication? config)
"--publickey" "--no-publickey")
(if (lsh-configuration-root-login? config)
"--root-login" "--no-root-login")
(if (lsh-configuration-x11-forwarding? config)
"--x11-forward" "--no-x11-forward")
(if (lsh-configuration-tcp/ip-forwarding? config)
"--tcpip-forward" "--no-tcpip-forward")
(if (null? interfaces)
'()
(map (cut string-append "--interface=" <>)
interfaces)))))
(define requires
(if (and daemonic? (lsh-configuration-syslog-output? config))
'(networking syslogd)
'(networking)))
(list (dmd-service
(documentation "GNU lsh SSH server")
(provision '(ssh-daemon))
(requirement requires)
(start #~(make-forkexec-constructor (list #$@lsh-command)))
(stop #~(make-kill-destructor)))))
(define (lsh-pam-services config)
"Return a list of <pam-services> for lshd with CONFIG."
(list (unix-pam-service
"lshd"
#:allow-empty-passwords?
(lsh-configuration-allow-empty-passwords? config))))
(define lsh-service-type
(service-type (name 'lsh)
(extensions
(list (service-extension dmd-root-service-type
lsh-dmd-service)
(service-extension pam-root-service-type
lsh-pam-services)
(service-extension activation-service-type
lsh-activation)))))
(define* (lsh-service #:key
(lsh lsh)
(daemonic? #t)
(host-key "/etc/lsh/host-key")
(interfaces '())
(port-number 22)
(allow-empty-passwords? #f)
(root-login? #f)
(syslog-output? #t)
(pid-file? #f)
(pid-file "/var/run/lshd.pid")
(x11-forwarding? #t)
(tcp/ip-forwarding? #t)
(password-authentication? #t)
(public-key-authentication? #t)
(initialize? #t))
"Run the @command{lshd} program from @var{lsh} to listen on port @var{port-number}.
@var{host-key} must designate a file containing the host key, and readable
only by root.
When @var{daemonic?} is true, @command{lshd} will detach from the
controlling terminal and log its output to syslogd, unless one sets
@var{syslog-output?} to false. Obviously, it also makes lsh-service
depend on existence of syslogd service. When @var{pid-file?} is true,
@command{lshd} writes its PID to the file called @var{pid-file}.
When @var{initialize?} is true, automatically create the seed and host key
upon service activation if they do not exist yet. This may take long and
require interaction.
When @var{initialize?} is false, it is up to the user to initialize the
randomness generator (@pxref{lsh-make-seed,,, lsh, LSH Manual}), and to create
a key pair with the private key stored in file @var{host-key} (@pxref{lshd
basics,,, lsh, LSH Manual}).
When @var{interfaces} is empty, lshd listens for connections on all the
network interfaces; otherwise, @var{interfaces} must be a list of host names
or addresses.
@var{allow-empty-passwords?} specifies whether to accept log-ins with empty
passwords, and @var{root-login?} specifies whether to accept log-ins as
root.
The other options should be self-descriptive."
(service lsh-service-type
(lsh-configuration (lsh lsh) (daemonic? daemonic?)
(host-key host-key) (interfaces interfaces)
(port-number port-number)
(allow-empty-passwords? allow-empty-passwords?)
(root-login? root-login?)
(syslog-output? syslog-output?)
(pid-file? pid-file?) (pid-file pid-file)
(x11-forwarding? x11-forwarding?)
(tcp/ip-forwarding? tcp/ip-forwarding?)
(password-authentication?
password-authentication?)
(public-key-authentication?
public-key-authentication?)
(initialize? initialize?))))
;;; ssh.scm ends here
| null |
https://raw.githubusercontent.com/pjotrp/guix/96250294012c2f1520b67f12ea80bfd6b98075a2/gnu/services/ssh.scm
|
scheme
|
GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix 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.
Commentary:
This module implements secure shell (SSH) services.
Code:
TODO: Export.
FIXME: We're just doing a simple pipeline, but 'system' cannot be
factorize this somehow .
otherwise, @var{interfaces} must be a list of host names
ssh.scm ends here
|
Copyright © 2014 , 2015 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu services ssh)
#:use-module (guix gexp)
#:use-module (guix records)
#:use-module (gnu services)
#:use-module (gnu services dmd)
#:use-module (gnu system pam)
#:use-module (gnu packages lsh)
#:use-module (srfi srfi-26)
#:export (lsh-service))
(define-record-type* <lsh-configuration>
lsh-configuration make-lsh-configuration
lsh-configuration?
(lsh lsh-configuration-lsh
(default lsh))
(daemonic? lsh-configuration-daemonic?)
(host-key lsh-configuration-host-key)
(interfaces lsh-configuration-interfaces)
(port-number lsh-configuration-port-number)
(allow-empty-passwords? lsh-configuration-allow-empty-passwords?)
(root-login? lsh-configuration-root-login?)
(syslog-output? lsh-configuration-syslog-output?)
(pid-file? lsh-configuration-pid-file?)
(pid-file lsh-configuration-pid-file)
(x11-forwarding? lsh-configuration-x11-forwarding?)
(tcp/ip-forwarding? lsh-configuration-tcp/ip-forwarding?)
(password-authentication? lsh-configuration-password-authentication?)
(public-key-authentication? lsh-configuration-public-key-authentication?)
(initialize? lsh-configuration-initialize?))
(define %yarrow-seed
"/var/spool/lsh/yarrow-seed-file")
(define (lsh-initialization lsh host-key)
"Return the gexp to initialize the LSH service for HOST-KEY."
#~(begin
(unless (file-exists? #$%yarrow-seed)
(system* (string-append #$lsh "/bin/lsh-make-seed")
"--sloppy" "-o" #$%yarrow-seed))
(unless (file-exists? #$host-key)
(mkdir-p (dirname #$host-key))
(format #t "creating SSH host key '~a'...~%" #$host-key)
(let* ((in+out (pipe))
(keygen (primitive-fork)))
(case keygen
((0)
(close-port (car in+out))
(close-fdes 1)
(dup2 (fileno (cdr in+out)) 1)
(execl (string-append #$lsh "/bin/lsh-keygen")
"lsh-keygen" "--server"))
(else
(let ((write-key (primitive-fork)))
(case write-key
((0)
(close-port (cdr in+out))
(close-fdes 0)
(dup2 (fileno (car in+out)) 0)
(execl (string-append #$lsh "/bin/lsh-writekey")
"lsh-writekey" "--server" "-o" #$host-key))
(else
(close-port (car in+out))
(close-port (cdr in+out))
(waitpid keygen)
(waitpid write-key))))))))))
(define (lsh-activation config)
"Return the activation gexp for CONFIG."
#~(begin
(use-modules (guix build utils))
(mkdir-p "/var/spool/lsh")
#$(if (lsh-configuration-initialize? config)
(lsh-initialization (lsh-configuration-lsh config)
(lsh-configuration-host-key config))
#t)))
(define (lsh-dmd-service config)
"Return a <dmd-service> for lsh with CONFIG."
(define lsh (lsh-configuration-lsh config))
(define pid-file (lsh-configuration-pid-file config))
(define pid-file? (lsh-configuration-pid-file? config))
(define daemonic? (lsh-configuration-daemonic? config))
(define interfaces (lsh-configuration-interfaces config))
(define lsh-command
(append
(cons #~(string-append #$lsh "/sbin/lshd")
(if daemonic?
(let ((syslog (if (lsh-configuration-syslog-output? config)
'()
(list "--no-syslog"))))
(cons "--daemonic"
(if pid-file?
(cons #~(string-append "--pid-file=" #$pid-file)
syslog)
(cons "--no-pid-file" syslog))))
(if pid-file?
(list #~(string-append "--pid-file=" #$pid-file))
'())))
(cons* #~(string-append "--host-key="
#$(lsh-configuration-host-key config))
#~(string-append "--password-helper=" #$lsh "/sbin/lsh-pam-checkpw")
#~(string-append "--subsystems=sftp=" #$lsh "/sbin/sftp-server")
"-p" (number->string (lsh-configuration-port-number config))
(if (lsh-configuration-password-authentication? config)
"--password" "--no-password")
(if (lsh-configuration-public-key-authentication? config)
"--publickey" "--no-publickey")
(if (lsh-configuration-root-login? config)
"--root-login" "--no-root-login")
(if (lsh-configuration-x11-forwarding? config)
"--x11-forward" "--no-x11-forward")
(if (lsh-configuration-tcp/ip-forwarding? config)
"--tcpip-forward" "--no-tcpip-forward")
(if (null? interfaces)
'()
(map (cut string-append "--interface=" <>)
interfaces)))))
(define requires
(if (and daemonic? (lsh-configuration-syslog-output? config))
'(networking syslogd)
'(networking)))
(list (dmd-service
(documentation "GNU lsh SSH server")
(provision '(ssh-daemon))
(requirement requires)
(start #~(make-forkexec-constructor (list #$@lsh-command)))
(stop #~(make-kill-destructor)))))
(define (lsh-pam-services config)
"Return a list of <pam-services> for lshd with CONFIG."
(list (unix-pam-service
"lshd"
#:allow-empty-passwords?
(lsh-configuration-allow-empty-passwords? config))))
(define lsh-service-type
(service-type (name 'lsh)
(extensions
(list (service-extension dmd-root-service-type
lsh-dmd-service)
(service-extension pam-root-service-type
lsh-pam-services)
(service-extension activation-service-type
lsh-activation)))))
(define* (lsh-service #:key
(lsh lsh)
(daemonic? #t)
(host-key "/etc/lsh/host-key")
(interfaces '())
(port-number 22)
(allow-empty-passwords? #f)
(root-login? #f)
(syslog-output? #t)
(pid-file? #f)
(pid-file "/var/run/lshd.pid")
(x11-forwarding? #t)
(tcp/ip-forwarding? #t)
(password-authentication? #t)
(public-key-authentication? #t)
(initialize? #t))
"Run the @command{lshd} program from @var{lsh} to listen on port @var{port-number}.
@var{host-key} must designate a file containing the host key, and readable
only by root.
When @var{daemonic?} is true, @command{lshd} will detach from the
controlling terminal and log its output to syslogd, unless one sets
@var{syslog-output?} to false. Obviously, it also makes lsh-service
depend on existence of syslogd service. When @var{pid-file?} is true,
@command{lshd} writes its PID to the file called @var{pid-file}.
When @var{initialize?} is true, automatically create the seed and host key
upon service activation if they do not exist yet. This may take long and
require interaction.
When @var{initialize?} is false, it is up to the user to initialize the
randomness generator (@pxref{lsh-make-seed,,, lsh, LSH Manual}), and to create
a key pair with the private key stored in file @var{host-key} (@pxref{lshd
basics,,, lsh, LSH Manual}).
When @var{interfaces} is empty, lshd listens for connections on all the
or addresses.
@var{allow-empty-passwords?} specifies whether to accept log-ins with empty
passwords, and @var{root-login?} specifies whether to accept log-ins as
root.
The other options should be self-descriptive."
(service lsh-service-type
(lsh-configuration (lsh lsh) (daemonic? daemonic?)
(host-key host-key) (interfaces interfaces)
(port-number port-number)
(allow-empty-passwords? allow-empty-passwords?)
(root-login? root-login?)
(syslog-output? syslog-output?)
(pid-file? pid-file?) (pid-file pid-file)
(x11-forwarding? x11-forwarding?)
(tcp/ip-forwarding? tcp/ip-forwarding?)
(password-authentication?
password-authentication?)
(public-key-authentication?
public-key-authentication?)
(initialize? initialize?))))
|
0410e0f0efcc29e6a99ea4245499a15734c7dd905598c01a72e246b0e02f0614
|
jonaprieto/online-atps
|
Yaml.hs
|
-- | Yaml.hs module process .online-atps files.
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE UnicodeSyntax #
module OnlineATPs.Utils.Yaml
( module YAP -- #hide
, (.:.)
, (.?.)
, (.@.)
, hypen
, loadYAML
, lower
, underscore
, upper
) where
import Control.Applicative ( (<|>) )
import Data.Aeson as YAP ( withObject )
import Data.Aeson.Types as YAP ( camelTo2 )
import qualified Data.Text as T
import Data.Yaml as YAP
import Data.Yaml.Include as YamlInclude
-- | This function 'underscore' translate a field string from
CamelCase to its version using underscores .
underscore ∷ T.Text → T.Text
underscore field = T.pack $ camelTo2 '_' $ T.unpack field
-- | This function 'underscore' translate a field string from
CamelCase to its version using hypens .
hypen ∷ T.Text → T.Text
hypen field = T.pack $ camelTo2 '-' $T.unpack field
-- | This function 'lower' transforms the text to lower case.
lower ∷ T.Text → T.Text
lower = T.toLower
-- | This function 'upper' transforms the text to upper case.
upper ∷ T.Text → T.Text
upper = T.toUpper
-- | This function '.?.' checks if the JSON data has a field trying
-- with all variants of the string for the field, that includes using
CamelCase , underscores or hypens to replace white spaces , upper case
-- and lower case.
(.?.) :: FromJSON a => Object → T.Text → Parser (Maybe a)
x .?. field = x .:? field
<|> x .:? underscore field
<|> x .:? hypen field
<|> x .:? lower field
<|> x .:? upper field
-- | This function '.:.' extracts from the JSON the field trying
-- with all variants of the string for the field, that includes using
CamelCase , underscores or hypens to replace white spaces , upper case
-- and lower case.
(.:.) :: FromJSON a => Object → T.Text → Parser a
x .:. field = x .: field
<|> x .: underscore field
<|> x .: hypen field
<|> x .: lower field
<|> x .: upper field
-- | This function '.@.' parses a JSON data and extracts a specific field.
(.@.) ∷ FromJSON a ⇒ [Object] → T.Text → Parser a
[] .@. _ = fail "failed. Expected at least one key-value"
[x] .@. field = x .:. field
(x:xs) .@. field = do
value ← x .?. field
maybe (xs .@. field) return value
| Decode a Yaml structured file .
loadYAML ∷ FilePath → IO (Maybe Object)
loadYAML path = do
decoded ← YamlInclude.decodeFileEither path
case decoded of
Right o → return $ Just o
Left msg → do
print msg
return Nothing
| null |
https://raw.githubusercontent.com/jonaprieto/online-atps/be0faf1f750ec4a4973feb20af3646ddd47ca70d/src/OnlineATPs/Utils/Yaml.hs
|
haskell
|
| Yaml.hs module process .online-atps files.
# LANGUAGE OverloadedStrings #
#hide
| This function 'underscore' translate a field string from
| This function 'underscore' translate a field string from
| This function 'lower' transforms the text to lower case.
| This function 'upper' transforms the text to upper case.
| This function '.?.' checks if the JSON data has a field trying
with all variants of the string for the field, that includes using
and lower case.
| This function '.:.' extracts from the JSON the field trying
with all variants of the string for the field, that includes using
and lower case.
| This function '.@.' parses a JSON data and extracts a specific field.
|
# LANGUAGE UnicodeSyntax #
module OnlineATPs.Utils.Yaml
, (.:.)
, (.?.)
, (.@.)
, hypen
, loadYAML
, lower
, underscore
, upper
) where
import Control.Applicative ( (<|>) )
import Data.Aeson as YAP ( withObject )
import Data.Aeson.Types as YAP ( camelTo2 )
import qualified Data.Text as T
import Data.Yaml as YAP
import Data.Yaml.Include as YamlInclude
CamelCase to its version using underscores .
underscore ∷ T.Text → T.Text
underscore field = T.pack $ camelTo2 '_' $ T.unpack field
CamelCase to its version using hypens .
hypen ∷ T.Text → T.Text
hypen field = T.pack $ camelTo2 '-' $T.unpack field
lower ∷ T.Text → T.Text
lower = T.toLower
upper ∷ T.Text → T.Text
upper = T.toUpper
CamelCase , underscores or hypens to replace white spaces , upper case
(.?.) :: FromJSON a => Object → T.Text → Parser (Maybe a)
x .?. field = x .:? field
<|> x .:? underscore field
<|> x .:? hypen field
<|> x .:? lower field
<|> x .:? upper field
CamelCase , underscores or hypens to replace white spaces , upper case
(.:.) :: FromJSON a => Object → T.Text → Parser a
x .:. field = x .: field
<|> x .: underscore field
<|> x .: hypen field
<|> x .: lower field
<|> x .: upper field
(.@.) ∷ FromJSON a ⇒ [Object] → T.Text → Parser a
[] .@. _ = fail "failed. Expected at least one key-value"
[x] .@. field = x .:. field
(x:xs) .@. field = do
value ← x .?. field
maybe (xs .@. field) return value
| Decode a Yaml structured file .
loadYAML ∷ FilePath → IO (Maybe Object)
loadYAML path = do
decoded ← YamlInclude.decodeFileEither path
case decoded of
Right o → return $ Just o
Left msg → do
print msg
return Nothing
|
3ffbcc9ed90690324f936bca0b0e0668fd2804144c022ed754d5a64ce3a02b7c
|
hopbit/sonic-pi-snippets
|
panie_janie.sps
|
# key: panie janie
# point_line: 0
# point_index: 0
# --
# WRUG 20 -----------------------------------------
# Panie Janie!
use_bpm 140
notes = (
# Panie Janie! x2
[:f4, 1, :g4, 1, :a4, 1, :f4, 1] * 2 +
# Rano wstań x2
[:a4, 1, :bb4, 1, :c5, 2] * 2 +
# Wszystkie dzwony biją! x2
[:c5, 0.5, :d5, 0.5, :c5, 0.5, :bb4, 0.5, :a4, 1, :f4, 1] * 2 +
# Bim, bam, bom! x2
[:f4, 1, :c4, 1, :f4, 2] * 2
).ring
4.times do |c|
sleep 8 * c
live_loop c.to_s.to_sym do
play notes.tick
sleep notes.tick
end
end
| null |
https://raw.githubusercontent.com/hopbit/sonic-pi-snippets/2232854ac9587fc2f9f684ba04d7476e2dbaa288/tunes/panie_janie.sps
|
scheme
|
# key: panie janie
# point_line: 0
# point_index: 0
# --
# WRUG 20 -----------------------------------------
# Panie Janie!
use_bpm 140
notes = (
# Panie Janie! x2
[:f4, 1, :g4, 1, :a4, 1, :f4, 1] * 2 +
# Rano wstań x2
[:a4, 1, :bb4, 1, :c5, 2] * 2 +
# Wszystkie dzwony biją! x2
[:c5, 0.5, :d5, 0.5, :c5, 0.5, :bb4, 0.5, :a4, 1, :f4, 1] * 2 +
# Bim, bam, bom! x2
[:f4, 1, :c4, 1, :f4, 2] * 2
).ring
4.times do |c|
sleep 8 * c
live_loop c.to_s.to_sym do
play notes.tick
sleep notes.tick
end
end
|
|
1a9a4804ac22620f805b2c790f86b74b8ba48da10bf4b34ab94a8597fb0af6b1
|
mario-goulart/spock
|
srfi-25.scm
|
srfi-25.scm - array library
(define array:array-tag (list 'array))
(define (array:make vec ind shp) (vector array:array-tag vec ind shp))
(define (array:array? x) (and (vector? x) (eq? (vector-ref x 0) array:array-tag)))
(define (array:vector a) (vector-ref a 1))
(define (array:index a) (vector-ref a 2))
(define (array:shape a) (vector-ref a 3))
;;; array
1997 - 2001
;;; --- Intro ---
This interface to arrays is based on array.scm of
1993 ( earlier version in the Internet Repository and another
;;; version in SLIB). This is a complete rewrite, to be consistent
;;; with the rest of Scheme and to make arrays independent of lists.
Some modifications are due to discussion in srfi-25 mailing list .
;;; (array? obj)
;;; (make-array shape [obj]) changed arguments
;;; (shape bound ...) new
;;; (array shape obj ...) new
;;; (array-rank array) changed name back
;;; (array-start array dimension) new
;;; (array-end array dimension) new
;;; (array-ref array k ...)
;;; (array-ref array index) new variant
;;; (array-set! array k ... obj) changed argument order
;;; (array-set! array index obj) new variant
;;; (share-array array shape proc) changed arguments
;;; All other variables in this file have names in "array:".
;;; Should there be a way to make arrays with initial values mapped
;;; from indices? Sure. The current "initial object" is lame.
;;;
;;; Removed (array-shape array) from here. There is a new version
in arlib though .
;;; --- Representation type dependencies ---
;;; The mapping from array indices to the index to the underlying vector
is whatever array : optimize returns . The file " opt " provides three
;;; representations:
;;;
;;; mbda) mapping is a procedure that allows an optional argument
tter ) mapping is two procedures that takes exactly the indices
;;; ctor) mapping is a vector of a constant term and coefficients
;;;
Choose one in " opt " to make the optimizer . Then choose the matching
;;; implementation of array-ref and array-set!.
;;;
;;; These should be made macros to inline them. Or have a good compiler
;;; and plant the package as a module.
1 . Pick an optimizer .
2 . Pick matching index representation .
3 . Pick a record implementation ; as - procedure is generic ; syntax inlines .
3 . This file is otherwise portable .
--- ( R4RS and multiple values ) ---
;;; (array? obj)
;;; returns #t if `obj' is an array and #t or #f otherwise.
(define (array? obj)
(array:array? obj))
(define-syntax check-array
(syntax-rules ()
((_ x loc)
(let ((var x))
(or (##core#check (array:array? var))
(##sys#signal-hook #:type-error loc (##core#immutable '"bad argument type - not an array") var) ) ) ) ) )
;;; (make-array shape)
;;; (make-array shape obj)
;;; makes array of `shape' with each cell containing `obj' initially.
(define (make-array shape . rest)
(or (##core#check (array:good-shape? shape))
(##sys#signal-hook #:type-error 'make-array "bad argument type - not a valid shape" shape))
(apply array:make-array shape rest))
(define (array:make-array shape . rest)
(let ((size (array:size shape)))
(array:make
(if (pair? rest)
(apply (lambda (o) (make-vector size o)) rest)
(make-vector size))
(if (= size 0)
(array:optimize-empty
(vector-ref (array:shape shape) 1))
(array:optimize
(array:make-index shape)
(vector-ref (array:shape shape) 1)))
(array:shape->vector shape))))
;;; (shape bound ...)
;;; makes a shape. Bounds must be an even number of exact, pairwise
;;; non-decreasing integers. Note that any such array can be a shape.
(define (shape . bounds)
(let ((v (list->vector bounds)))
(or (##core#check (even? (vector-length v)))
(##sys#error 'shape "uneven number of bounds" bounds) )
(let ((shp (array:make
v
(if (pair? bounds)
(array:shape-index)
(array:empty-shape-index))
(vector 0 (quotient (vector-length v) 2)
0 2))))
(or (##core#check (array:good-shape? shp))
(##sys#signal-hook #:type-error 'shape "bounds are not pairwise non-decreasing exact integers" bounds) )
shp)))
;;; (array shape obj ...)
;;; is analogous to `vector'.
(define (array shape . elts)
(or (##core#check (array:good-shape? shape))
(##sys#signal-hook #:type-error 'array "bad argument type - not a valid shape" shape) )
(let ((size (array:size shape)))
(let ((vector (list->vector elts)))
(or (##core#check (= (vector-length vector) size))
(##sys#error 'array "bad number of elements" shape elts) )
(array:make
vector
(if (= size 0)
(array:optimize-empty
(vector-ref (array:shape shape) 1))
(array:optimize
(array:make-index shape)
(vector-ref (array:shape shape) 1)))
(array:shape->vector shape)))))
;;; (array-rank array)
;;; returns the number of dimensions of `array'.
(define (array-rank array)
(check-array array 'array-rank)
(quotient (vector-length (array:shape array)) 2))
;;; (array-start array k)
returns the lower bound index of array along dimension is
;;; the least valid index along that dimension if the dimension is not
;;; empty.
(define (array-start array d)
(check-array array 'array-start)
(vector-ref (array:shape array) (+ d d)))
;;; (array-end array k)
returns the upper bound index of array along dimension is
;;; not a valid index. If the dimension is empty, this is the same as
;;; the lower bound along it.
(define (array-end array d)
(check-array array 'array-end)
(vector-ref (array:shape array) (+ d d 1)))
;;; (share-array array shape proc)
;;; makes an array that shares elements of `array' at shape `shape'.
;;; The arguments to `proc' are indices of the result. The values of
;;; `proc' are indices of `array'.
;;; Todo: in the error message, should recognise the mapping and show it.
(define (share-array array subshape f)
(check-array array 'share-array)
(or (##core#check (array:good-shape? subshape))
(##sys#signal-hook #:type-error 'share-array "not a shape" subshape) )
(let ((subsize (array:size subshape)))
(or (##core#check (array:good-share? subshape subsize f (array:shape array)))
(##sys#error 'share-array "subshape does not map into supershape" subshape shape) )
(let ((g (array:index array)))
(array:make
(array:vector array)
(if (= subsize 0)
(array:optimize-empty
(vector-ref (array:shape subshape) 1))
(array:optimize
(lambda ks
(call-with-values
(lambda () (apply f ks))
(lambda ks (array:vector-index g ks))))
(vector-ref (array:shape subshape) 1)))
(array:shape->vector subshape)))))
;;; --- Hrmph ---
;;; (array:share/index! ...)
;;; reuses a user supplied index object when recognising the
;;; mapping. The mind balks at the very nasty side effect that
;;; exposes the implementation. So this is not in the spec.
;;; But letting index objects in at all creates a pressure
;;; to go the whole hog. Arf.
;;; Use array:optimize-empty for an empty array to get a
;;; clearly invalid vector index.
;;; Surely it's perverse to use an actor for index here? But
;;; the possibility is provided for completeness.
(define (array:share/index! array subshape proc index)
(array:make
(array:vector array)
(if (= (array:size subshape) 0)
(array:optimize-empty
(quotient (vector-length (array:shape array)) 2))
((if (vector? index)
array:optimize/vector
array:optimize/actor)
(lambda (subindex)
(let ((superindex (proc subindex)))
(if (vector? superindex)
(array:index/vector
(quotient (vector-length (array:shape array)) 2)
(array:index array)
superindex)
(array:index/array
(quotient (vector-length (array:shape array)) 2)
(array:index array)
(array:vector superindex)
(array:index superindex)))))
index))
(array:shape->vector subshape)))
(define (array:optimize/vector f v)
(let ((r (vector-length v)))
(do ((k 0 (+ k 1)))
((= k r))
(vector-set! v k 0))
(let ((n0 (f v))
(cs (make-vector (+ r 1)))
(apply (array:applier-to-vector (+ r 1))))
(vector-set! cs 0 n0)
(let wok ((k 0))
(if (< k r)
(let ((k1 (+ k 1)))
(vector-set! v k 1)
(let ((nk (- (f v) n0)))
(vector-set! v k 0)
(vector-set! cs k1 nk)
(wok k1)))))
(apply (array:maker r) cs))))
(define (array:optimize/actor f a)
(let ((r (array-end a 0))
(v (array:vector a))
(i (array:index a)))
(do ((k 0 (+ k 1)))
((= k r))
(vector-set! v (array:actor-index i k) 0))
(let ((n0 (f a))
(cs (make-vector (+ r 1)))
(apply (array:applier-to-vector (+ r 1))))
(vector-set! cs 0 n0)
(let wok ((k 0))
(if (< k r)
(let ((k1 (+ k 1))
(t (array:actor-index i k)))
(vector-set! v t 1)
(let ((nk (- (f a) n0)))
(vector-set! v t 0)
(vector-set! cs k1 nk)
(wok k1)))))
(apply (array:maker r) cs))))
;;; --- Internals ---
(define (array:shape->vector shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(let ((vec (make-vector (* rnk 2))))
(do ((k 0 (+ k 1)))
((= k rnk)
vec)
(vector-set! vec (+ k k)
(vector-ref shv (array:shape-vector-index idx k 0)))
(vector-set! vec (+ k k 1)
(vector-ref shv (array:shape-vector-index idx k 1)))))))
;;; (array:size shape)
;;; returns the number of elements in arrays of shape `shape'.
(define (array:size shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(do ((k 0 (+ k 1))
(s 1 (* s
(- (vector-ref shv (array:shape-vector-index idx k 1))
(vector-ref shv (array:shape-vector-index idx k 0))))))
((= k rnk) s))))
;;; (array:make-index shape)
;;; returns an index function for arrays of shape `shape'. This is a
;;; runtime composition of several variable arity procedures, to be
;;; passed to array:optimize for recognition as an affine function of
;;; as many variables as there are dimensions in arrays of this shape.
(define (array:make-index shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(do ((f (lambda () 0)
(lambda (k . ks)
(+ (* s (- k (vector-ref
shv
(array:shape-vector-index idx (- j 1) 0))))
(apply f ks))))
(s 1 (* s (- (vector-ref
shv
(array:shape-vector-index idx (- j 1) 1))
(vector-ref
shv
(array:shape-vector-index idx (- j 1) 0)))))
(j rnk (- j 1)))
((= j 0)
f))))
;;; --- Error checking ---
;;; (array:good-shape? shape)
;;; returns true if `shape' is an array of the right shape and its
;;; elements are exact integers that pairwise bound intervals `[lo..hi)´.
(define (array:good-shape? shape)
(and (array:array? shape)
(let ((u (array:shape shape))
(v (array:vector shape))
(x (array:index shape)))
(and (= (vector-length u) 4)
(= (vector-ref u 0) 0)
(= (vector-ref u 2) 0)
(= (vector-ref u 3) 2))
(let ((p (vector-ref u 1)))
(do ((k 0 (+ k 1))
(true #t (let ((lo (vector-ref
v
(array:shape-vector-index x k 0)))
(hi (vector-ref
v
(array:shape-vector-index x k 1))))
(and true
(integer? lo)
(exact? lo)
(integer? hi)
(exact? hi)
(<= lo hi)))))
((= k p) true))))))
( array : good - share ? subv subsize mapping )
;;; returns true if the extreme indices in the subshape vector map
;;; into the bounds in the supershape vector.
;;; If some interval in `subv' is empty, then `subv' is empty and its
;;; image under `f' is empty and it is trivially alright. One must
;;; not call `f', though.
(define (array:good-share? subshape subsize f super)
(or (zero? subsize)
(letrec
((sub (array:vector subshape))
(dex (array:index subshape))
(ck (lambda (k ks)
(if (zero? k)
(call-with-values
(lambda () (apply f ks))
(lambda qs (array:good-indices? qs super)))
(and (ck (- k 1)
(cons (vector-ref
sub
(array:shape-vector-index
dex
(- k 1)
0))
ks))
(ck (- k 1)
(cons (- (vector-ref
sub
(array:shape-vector-index
dex
(- k 1)
1))
1)
ks)))))))
(let ((rnk (vector-ref (array:shape subshape) 1)))
(or (array:unchecked-share-depth? rnk)
(ck rnk '()))))))
Check good - share on 10 dimensions at most . The trouble is ,
;;; the cost of this check is exponential in the number of dimensions.
(define (array:unchecked-share-depth? rank)
(if (> rank 10)
(begin
(display `(warning: unchecked depth in share:
,rank subdimensions))
(newline)
#t)
#f))
;;; (array:check-indices caller indices shape-vector)
;;; (array:check-indices.o caller indices shape-vector)
;;; (array:check-index-vector caller index-vector shape-vector)
;;; return if the index is in bounds, else signal error.
;;;
;;; Shape-vector is the internal representation, with
b and e for dimension k at 2k and 2k + 1 .
(define (array:check-indices who ks shv)
(or (array:good-indices? ks shv)
(##sys#signal-hook #:bounds-error (array:not-in who ks shv))))
(define (array:check-indices.o who ks shv)
(or (array:good-indices.o? ks shv)
(##sys#signal-hook #:bounds-error (array:not-in who (reverse (cdr (reverse ks))) shv))))
(define (array:check-index-vector who ks shv)
(or (array:good-index-vector? ks shv)
(##sys#signal-hook #:bounds-error (array:not-in who (vector->list ks) shv))))
(define (array:check-index-actor who ks shv)
(let ((shape (array:shape ks)))
(or (and (= (vector-length shape) 2)
(= (vector-ref shape 0) 0))
(##sys#signal-hook #:type-error "not an actor"))
(or (array:good-index-actor?
(vector-ref shape 1)
(array:vector ks)
(array:index ks)
shv)
(array:not-in who (do ((k (vector-ref shape 1) (- k 1))
(m '() (cons (vector-ref
(array:vector ks)
(array:actor-index
(array:index ks)
(- k 1)))
m)))
((= k 0) m))
shv))))
(define (array:good-indices? ks shv)
(let ((d2 (vector-length shv)))
(do ((kp ks (if (pair? kp)
(cdr kp)))
(k 0 (+ k 2))
(true #t (and true (pair? kp)
(array:good-index? (car kp) shv k))))
((= k d2)
(and true (null? kp))))))
(define (array:good-indices.o? ks.o shv)
(let ((d2 (vector-length shv)))
(do ((kp ks.o (if (pair? kp)
(cdr kp)))
(k 0 (+ k 2))
(true #t (and true (pair? kp)
(array:good-index? (car kp) shv k))))
((= k d2)
(and true (pair? kp) (null? (cdr kp)))))))
(define (array:good-index-vector? ks shv)
(let ((r2 (vector-length shv)))
(and (= (* 2 (vector-length ks)) r2)
(do ((j 0 (+ j 1))
(k 0 (+ k 2))
(true #t (and true
(array:good-index? (vector-ref ks j) shv k))))
((= k r2) true)))))
(define (array:good-index-actor? r v i shv)
(and (= (* 2 r) (vector-length shv))
(do ((j 0 (+ j 1))
(k 0 (+ k 2))
(true #t (and true
(array:good-index? (vector-ref
v
(array:actor-index i j))
shv
k))))
((= j r) true))))
;;; (array:good-index? index shape-vector 2d)
returns true if index is within bounds for dimension 2d/2 .
(define (array:good-index? w shv k)
(and (integer? w)
(exact? w)
(<= (vector-ref shv k) w)
(< w (vector-ref shv (+ k 1)))))
(define (array:not-in who ks shv)
(##sys#signal-hook #:bounds-error (string-append who ": index not in bounds") ks shv) )
(begin
(define (array:coefficients f n0 vs vp)
(case vp
((()) '())
(else
(set-car! vp 1)
(let ((n (- (apply f vs) n0)))
(set-car! vp 0)
(cons n (array:coefficients f n0 vs (cdr vp)))))))
(define (array:vector-index x ks)
(do ((sum 0 (+ sum (* (vector-ref x k) (car ks))))
(ks ks (cdr ks))
(k 0 (+ k 1)))
((null? ks) (+ sum (vector-ref x k)))))
(define (array:shape-index) '#(2 1 0))
(define (array:empty-shape-index) '#(0 0 -1))
(define (array:shape-vector-index x r k)
(+
(* (vector-ref x 0) r)
(* (vector-ref x 1) k)
(vector-ref x 2)))
(define (array:actor-index x k)
(+ (* (vector-ref x 0) k) (vector-ref x 1)))
(define (array:0 n0) (vector n0))
(define (array:1 n0 n1) (vector n1 n0))
(define (array:2 n0 n1 n2) (vector n1 n2 n0))
(define (array:3 n0 n1 n2 n3) (vector n1 n2 n3 n0))
(define (array:n n0 n1 n2 n3 n4 . ns)
(apply vector n1 n2 n3 n4 (append ns (list n0))))
(define (array:maker r)
(case r
((0) array:0)
((1) array:1)
((2) array:2)
((3) array:3)
(else array:n)))
(define array:indexer/vector
(let ((em
(vector
(lambda (x i) (+ (vector-ref x 0)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(vector-ref x 1)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(vector-ref x 2)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(vector-ref x 3)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(vector-ref x 4)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(vector-ref x 5)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(vector-ref x 6)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(vector-ref x 7)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(vector-ref x 8)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(* (vector-ref x 8) (vector-ref i 8))
(vector-ref x 9)))))
(it
(lambda (w)
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(* (vector-ref x 8) (vector-ref i 8))
(* (vector-ref x 9) (vector-ref i 9))
(do ((xi
0
(+
(* (vector-ref x u) (vector-ref i u))
xi))
(u (- w 1) (- u 1)))
((< u 10) xi))
(vector-ref x w))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:indexer/array
(let ((em
(vector
(lambda (x v i) (+ (vector-ref x 0)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(vector-ref x 1)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(vector-ref x 2)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(vector-ref x 3)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(vector-ref x 4)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(vector-ref x 5)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(vector-ref x 6)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(vector-ref x 7)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(vector-ref x 8)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(*
(vector-ref x 8)
(vector-ref v (array:actor-index i 8)))
(vector-ref x 9)))))
(it
(lambda (w)
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(*
(vector-ref x 8)
(vector-ref v (array:actor-index i 8)))
(*
(vector-ref x 9)
(vector-ref v (array:actor-index i 9)))
(do ((xi
0
(+
(*
(vector-ref x u)
(vector-ref
v
(array:actor-index i u)))
xi))
(u (- w 1) (- u 1)))
((< u 10) xi))
(vector-ref x w))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-vector
(let ((em
(vector
(lambda (p v) (p))
(lambda (p v) (p (vector-ref v 0)))
(lambda (p v)
(p (vector-ref v 0) (vector-ref v 1)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)
(vector-ref v 8)))))
(it
(lambda (r)
(lambda (p v)
(apply
p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)
(vector-ref v 8)
(vector-ref v 9)
(do ((k r (- k 1))
(r
'()
(cons (vector-ref v (- k 1)) r)))
((= k 10) r)))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-actor
(let ((em
(vector
(lambda (p a) (p))
(lambda (p a) (p (array-ref a 0)))
(lambda (p a)
(p (array-ref a 0) (array-ref a 1)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)
(array-ref a 8)))))
(it
(lambda (r)
(lambda (p a)
(apply
a
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)
(array-ref a 8)
(array-ref a 9)
(do ((k r (- k 1))
(r '() (cons (array-ref a (- k 1)) r)))
((= k 10) r)))))))
(lambda (r)
"These are high level, hiding implementation at call site."
(if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-backing-vector
(let ((em
(vector
(lambda (p ai av) (p))
(lambda (p ai av)
(p (vector-ref av (array:actor-index ai 0))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))
(vector-ref av (array:actor-index ai 8))))))
(it
(lambda (r)
(lambda (p ai av)
(apply
p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))
(vector-ref av (array:actor-index ai 8))
(vector-ref av (array:actor-index ai 9))
(do ((k r (- k 1))
(r
'()
(cons
(vector-ref
av
(array:actor-index ai (- k 1)))
r)))
((= k 10) r)))))))
(lambda (r)
"These are low level, exposing implementation at call site."
(if (< r 10) (vector-ref em r) (it r)))))
(define (array:index/vector r x v)
((array:indexer/vector r) x v))
(define (array:index/array r x av ai)
((array:indexer/array r) x av ai))
(define (array:apply-to-actor r p a)
((array:applier-to-actor r) p a))
(define (array:apply-to-vector r p v)
((array:applier-to-vector r) p v))
(define (array:optimize f r)
(case r
((0) (let ((n0 (f))) (array:0 n0)))
((1) (let ((n0 (f 0))) (array:1 n0 (- (f 1) n0))))
((2)
(let ((n0 (f 0 0)))
(array:2 n0 (- (f 1 0) n0) (- (f 0 1) n0))))
((3)
(let ((n0 (f 0 0 0)))
(array:3
n0
(- (f 1 0 0) n0)
(- (f 0 1 0) n0)
(- (f 0 0 1) n0))))
(else
(let ((v
(do ((k 0 (+ k 1)) (v '() (cons 0 v)))
((= k r) v))))
(let ((n0 (apply f v)))
(apply
array:n
n0
(array:coefficients f n0 v v)))))))
(define (array:optimize-empty r)
(let ((x (make-vector (+ r 1) 0)))
(vector-set! x r -1)
x)))
(define (array-ref a . xs)
(or (##core#check (array:array? a))
(##sys#signal-hook #:type-error 'array-ref "not an array" a))
(let ((shape (array:shape a)))
(##core#check
(if (null? xs)
(array:check-indices "array-ref" xs shape)
(let ((x (car xs)))
(if (vector? x)
(array:check-index-vector "array-ref" x shape)
(if (integer? x)
(array:check-indices "array-ref" xs shape)
(if (array:array? x)
(array:check-index-actor "array-ref" x shape)
(##sys#signal-hook #:type-error 'array-ref "not an index object" x)))))))
(vector-ref
(array:vector a)
(if (null? xs)
(vector-ref (array:index a) 0)
(let ((x (car xs)))
(if (vector? x)
(array:index/vector
(quotient (vector-length shape) 2)
(array:index a)
x)
(if (integer? x)
(array:vector-index (array:index a) xs)
(if (##core#check (array:array? x))
(array:index/array
(quotient (vector-length shape) 2)
(array:index a)
(array:vector x)
(array:index x))
(##sys#signal-hook #:type-error 'array-ref "bad index object" x)))))))))
(define (array-set! a x . xs)
(or (##core#check (array:array? a))
(##sys#signal-hook #:type-error 'array-set! "not an array" a))
(let ((shape (array:shape a)))
(##core#check
(if (null? xs)
(array:check-indices "array-set!" '() shape)
(if (vector? x)
(array:check-index-vector "array-set!" x shape)
(if (integer? x)
(array:check-indices.o "array-set!" (cons x xs) shape)
(if (array:array? x)
(array:check-index-actor "array-set!" x shape)
(##sys#signal-hook #:type-error 'array-set! "not an index object" x))))))
(if (null? xs)
(vector-set! (array:vector a) (vector-ref (array:index a) 0) x)
(if (vector? x)
(vector-set! (array:vector a)
(array:index/vector
(quotient (vector-length shape) 2)
(array:index a)
x)
(car xs))
(if (integer? x)
(let ((v (array:vector a))
(i (array:index a))
(r (quotient (vector-length shape) 2)))
(do ((sum (* (vector-ref i 0) x)
(+ sum (* (vector-ref i k) (car ks))))
(ks xs (cdr ks))
(k 1 (+ k 1)))
((= k r)
(vector-set! v (+ sum (vector-ref i k)) (car ks)))))
(if (##core#check (array:array? x))
(vector-set! (array:vector a)
(array:index/array
(quotient (vector-length shape) 2)
(array:index a)
(array:vector x)
(array:index x))
(car xs))
(##sys#signal-hook
#:type-error 'array-set!
"bad index object: "
x)))))))
(define (array:make-locative a x weak?)
(or (##core#check (array:array? a))
(##sys#signal-hook #:type-error 'array:make-locative "not an array"))
(let ((shape (array:shape a)))
(##core#check
(if (vector? x)
(array:check-index-vector "array:make-locative" x shape)
(if (integer? x)
(array:check-indices.o "array:make-locative" (list x) shape)
(if (array:array? x)
(array:check-index-actor "array:make-locative" x shape)
(##sys#signal-hook #:type-error 'array:make-locative "not an index object" x)))))
(if (vector? x)
(##core#inline_allocate
("C_a_i_make_locative" 5)
0
(array:vector a)
(array:index/vector
(quotient (vector-length shape) 2)
(array:index a)
x)
weak?)
(if (##core#check (array:array? x))
(##core#inline_allocate
("C_a_i_make_locative" 5)
0
(array:vector a)
(array:index/array
(quotient (vector-length shape) 2)
(array:index a)
(array:vector x)
(array:index x))
weak?)
(##sys#signal-hook #:type-error 'array:make-locative "bad index object: " x)))))
| null |
https://raw.githubusercontent.com/mario-goulart/spock/b88f08f8bc689babc433ad8288559ce5c28c52d5/tests/srfi-25.scm
|
scheme
|
array
--- Intro ---
version in SLIB). This is a complete rewrite, to be consistent
with the rest of Scheme and to make arrays independent of lists.
(array? obj)
(make-array shape [obj]) changed arguments
(shape bound ...) new
(array shape obj ...) new
(array-rank array) changed name back
(array-start array dimension) new
(array-end array dimension) new
(array-ref array k ...)
(array-ref array index) new variant
(array-set! array k ... obj) changed argument order
(array-set! array index obj) new variant
(share-array array shape proc) changed arguments
All other variables in this file have names in "array:".
Should there be a way to make arrays with initial values mapped
from indices? Sure. The current "initial object" is lame.
Removed (array-shape array) from here. There is a new version
--- Representation type dependencies ---
The mapping from array indices to the index to the underlying vector
representations:
mbda) mapping is a procedure that allows an optional argument
ctor) mapping is a vector of a constant term and coefficients
implementation of array-ref and array-set!.
These should be made macros to inline them. Or have a good compiler
and plant the package as a module.
as - procedure is generic ; syntax inlines .
(array? obj)
returns #t if `obj' is an array and #t or #f otherwise.
(make-array shape)
(make-array shape obj)
makes array of `shape' with each cell containing `obj' initially.
(shape bound ...)
makes a shape. Bounds must be an even number of exact, pairwise
non-decreasing integers. Note that any such array can be a shape.
(array shape obj ...)
is analogous to `vector'.
(array-rank array)
returns the number of dimensions of `array'.
(array-start array k)
the least valid index along that dimension if the dimension is not
empty.
(array-end array k)
not a valid index. If the dimension is empty, this is the same as
the lower bound along it.
(share-array array shape proc)
makes an array that shares elements of `array' at shape `shape'.
The arguments to `proc' are indices of the result. The values of
`proc' are indices of `array'.
Todo: in the error message, should recognise the mapping and show it.
--- Hrmph ---
(array:share/index! ...)
reuses a user supplied index object when recognising the
mapping. The mind balks at the very nasty side effect that
exposes the implementation. So this is not in the spec.
But letting index objects in at all creates a pressure
to go the whole hog. Arf.
Use array:optimize-empty for an empty array to get a
clearly invalid vector index.
Surely it's perverse to use an actor for index here? But
the possibility is provided for completeness.
--- Internals ---
(array:size shape)
returns the number of elements in arrays of shape `shape'.
(array:make-index shape)
returns an index function for arrays of shape `shape'. This is a
runtime composition of several variable arity procedures, to be
passed to array:optimize for recognition as an affine function of
as many variables as there are dimensions in arrays of this shape.
--- Error checking ---
(array:good-shape? shape)
returns true if `shape' is an array of the right shape and its
elements are exact integers that pairwise bound intervals `[lo..hi)´.
returns true if the extreme indices in the subshape vector map
into the bounds in the supershape vector.
If some interval in `subv' is empty, then `subv' is empty and its
image under `f' is empty and it is trivially alright. One must
not call `f', though.
the cost of this check is exponential in the number of dimensions.
(array:check-indices caller indices shape-vector)
(array:check-indices.o caller indices shape-vector)
(array:check-index-vector caller index-vector shape-vector)
return if the index is in bounds, else signal error.
Shape-vector is the internal representation, with
(array:good-index? index shape-vector 2d)
|
srfi-25.scm - array library
(define array:array-tag (list 'array))
(define (array:make vec ind shp) (vector array:array-tag vec ind shp))
(define (array:array? x) (and (vector? x) (eq? (vector-ref x 0) array:array-tag)))
(define (array:vector a) (vector-ref a 1))
(define (array:index a) (vector-ref a 2))
(define (array:shape a) (vector-ref a 3))
1997 - 2001
This interface to arrays is based on array.scm of
1993 ( earlier version in the Internet Repository and another
Some modifications are due to discussion in srfi-25 mailing list .
in arlib though .
is whatever array : optimize returns . The file " opt " provides three
tter ) mapping is two procedures that takes exactly the indices
Choose one in " opt " to make the optimizer . Then choose the matching
1 . Pick an optimizer .
2 . Pick matching index representation .
3 . This file is otherwise portable .
--- ( R4RS and multiple values ) ---
(define (array? obj)
(array:array? obj))
(define-syntax check-array
(syntax-rules ()
((_ x loc)
(let ((var x))
(or (##core#check (array:array? var))
(##sys#signal-hook #:type-error loc (##core#immutable '"bad argument type - not an array") var) ) ) ) ) )
(define (make-array shape . rest)
(or (##core#check (array:good-shape? shape))
(##sys#signal-hook #:type-error 'make-array "bad argument type - not a valid shape" shape))
(apply array:make-array shape rest))
(define (array:make-array shape . rest)
(let ((size (array:size shape)))
(array:make
(if (pair? rest)
(apply (lambda (o) (make-vector size o)) rest)
(make-vector size))
(if (= size 0)
(array:optimize-empty
(vector-ref (array:shape shape) 1))
(array:optimize
(array:make-index shape)
(vector-ref (array:shape shape) 1)))
(array:shape->vector shape))))
(define (shape . bounds)
(let ((v (list->vector bounds)))
(or (##core#check (even? (vector-length v)))
(##sys#error 'shape "uneven number of bounds" bounds) )
(let ((shp (array:make
v
(if (pair? bounds)
(array:shape-index)
(array:empty-shape-index))
(vector 0 (quotient (vector-length v) 2)
0 2))))
(or (##core#check (array:good-shape? shp))
(##sys#signal-hook #:type-error 'shape "bounds are not pairwise non-decreasing exact integers" bounds) )
shp)))
(define (array shape . elts)
(or (##core#check (array:good-shape? shape))
(##sys#signal-hook #:type-error 'array "bad argument type - not a valid shape" shape) )
(let ((size (array:size shape)))
(let ((vector (list->vector elts)))
(or (##core#check (= (vector-length vector) size))
(##sys#error 'array "bad number of elements" shape elts) )
(array:make
vector
(if (= size 0)
(array:optimize-empty
(vector-ref (array:shape shape) 1))
(array:optimize
(array:make-index shape)
(vector-ref (array:shape shape) 1)))
(array:shape->vector shape)))))
(define (array-rank array)
(check-array array 'array-rank)
(quotient (vector-length (array:shape array)) 2))
returns the lower bound index of array along dimension is
(define (array-start array d)
(check-array array 'array-start)
(vector-ref (array:shape array) (+ d d)))
returns the upper bound index of array along dimension is
(define (array-end array d)
(check-array array 'array-end)
(vector-ref (array:shape array) (+ d d 1)))
(define (share-array array subshape f)
(check-array array 'share-array)
(or (##core#check (array:good-shape? subshape))
(##sys#signal-hook #:type-error 'share-array "not a shape" subshape) )
(let ((subsize (array:size subshape)))
(or (##core#check (array:good-share? subshape subsize f (array:shape array)))
(##sys#error 'share-array "subshape does not map into supershape" subshape shape) )
(let ((g (array:index array)))
(array:make
(array:vector array)
(if (= subsize 0)
(array:optimize-empty
(vector-ref (array:shape subshape) 1))
(array:optimize
(lambda ks
(call-with-values
(lambda () (apply f ks))
(lambda ks (array:vector-index g ks))))
(vector-ref (array:shape subshape) 1)))
(array:shape->vector subshape)))))
(define (array:share/index! array subshape proc index)
(array:make
(array:vector array)
(if (= (array:size subshape) 0)
(array:optimize-empty
(quotient (vector-length (array:shape array)) 2))
((if (vector? index)
array:optimize/vector
array:optimize/actor)
(lambda (subindex)
(let ((superindex (proc subindex)))
(if (vector? superindex)
(array:index/vector
(quotient (vector-length (array:shape array)) 2)
(array:index array)
superindex)
(array:index/array
(quotient (vector-length (array:shape array)) 2)
(array:index array)
(array:vector superindex)
(array:index superindex)))))
index))
(array:shape->vector subshape)))
(define (array:optimize/vector f v)
(let ((r (vector-length v)))
(do ((k 0 (+ k 1)))
((= k r))
(vector-set! v k 0))
(let ((n0 (f v))
(cs (make-vector (+ r 1)))
(apply (array:applier-to-vector (+ r 1))))
(vector-set! cs 0 n0)
(let wok ((k 0))
(if (< k r)
(let ((k1 (+ k 1)))
(vector-set! v k 1)
(let ((nk (- (f v) n0)))
(vector-set! v k 0)
(vector-set! cs k1 nk)
(wok k1)))))
(apply (array:maker r) cs))))
(define (array:optimize/actor f a)
(let ((r (array-end a 0))
(v (array:vector a))
(i (array:index a)))
(do ((k 0 (+ k 1)))
((= k r))
(vector-set! v (array:actor-index i k) 0))
(let ((n0 (f a))
(cs (make-vector (+ r 1)))
(apply (array:applier-to-vector (+ r 1))))
(vector-set! cs 0 n0)
(let wok ((k 0))
(if (< k r)
(let ((k1 (+ k 1))
(t (array:actor-index i k)))
(vector-set! v t 1)
(let ((nk (- (f a) n0)))
(vector-set! v t 0)
(vector-set! cs k1 nk)
(wok k1)))))
(apply (array:maker r) cs))))
(define (array:shape->vector shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(let ((vec (make-vector (* rnk 2))))
(do ((k 0 (+ k 1)))
((= k rnk)
vec)
(vector-set! vec (+ k k)
(vector-ref shv (array:shape-vector-index idx k 0)))
(vector-set! vec (+ k k 1)
(vector-ref shv (array:shape-vector-index idx k 1)))))))
(define (array:size shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(do ((k 0 (+ k 1))
(s 1 (* s
(- (vector-ref shv (array:shape-vector-index idx k 1))
(vector-ref shv (array:shape-vector-index idx k 0))))))
((= k rnk) s))))
(define (array:make-index shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(do ((f (lambda () 0)
(lambda (k . ks)
(+ (* s (- k (vector-ref
shv
(array:shape-vector-index idx (- j 1) 0))))
(apply f ks))))
(s 1 (* s (- (vector-ref
shv
(array:shape-vector-index idx (- j 1) 1))
(vector-ref
shv
(array:shape-vector-index idx (- j 1) 0)))))
(j rnk (- j 1)))
((= j 0)
f))))
(define (array:good-shape? shape)
(and (array:array? shape)
(let ((u (array:shape shape))
(v (array:vector shape))
(x (array:index shape)))
(and (= (vector-length u) 4)
(= (vector-ref u 0) 0)
(= (vector-ref u 2) 0)
(= (vector-ref u 3) 2))
(let ((p (vector-ref u 1)))
(do ((k 0 (+ k 1))
(true #t (let ((lo (vector-ref
v
(array:shape-vector-index x k 0)))
(hi (vector-ref
v
(array:shape-vector-index x k 1))))
(and true
(integer? lo)
(exact? lo)
(integer? hi)
(exact? hi)
(<= lo hi)))))
((= k p) true))))))
( array : good - share ? subv subsize mapping )
(define (array:good-share? subshape subsize f super)
(or (zero? subsize)
(letrec
((sub (array:vector subshape))
(dex (array:index subshape))
(ck (lambda (k ks)
(if (zero? k)
(call-with-values
(lambda () (apply f ks))
(lambda qs (array:good-indices? qs super)))
(and (ck (- k 1)
(cons (vector-ref
sub
(array:shape-vector-index
dex
(- k 1)
0))
ks))
(ck (- k 1)
(cons (- (vector-ref
sub
(array:shape-vector-index
dex
(- k 1)
1))
1)
ks)))))))
(let ((rnk (vector-ref (array:shape subshape) 1)))
(or (array:unchecked-share-depth? rnk)
(ck rnk '()))))))
Check good - share on 10 dimensions at most . The trouble is ,
(define (array:unchecked-share-depth? rank)
(if (> rank 10)
(begin
(display `(warning: unchecked depth in share:
,rank subdimensions))
(newline)
#t)
#f))
b and e for dimension k at 2k and 2k + 1 .
(define (array:check-indices who ks shv)
(or (array:good-indices? ks shv)
(##sys#signal-hook #:bounds-error (array:not-in who ks shv))))
(define (array:check-indices.o who ks shv)
(or (array:good-indices.o? ks shv)
(##sys#signal-hook #:bounds-error (array:not-in who (reverse (cdr (reverse ks))) shv))))
(define (array:check-index-vector who ks shv)
(or (array:good-index-vector? ks shv)
(##sys#signal-hook #:bounds-error (array:not-in who (vector->list ks) shv))))
(define (array:check-index-actor who ks shv)
(let ((shape (array:shape ks)))
(or (and (= (vector-length shape) 2)
(= (vector-ref shape 0) 0))
(##sys#signal-hook #:type-error "not an actor"))
(or (array:good-index-actor?
(vector-ref shape 1)
(array:vector ks)
(array:index ks)
shv)
(array:not-in who (do ((k (vector-ref shape 1) (- k 1))
(m '() (cons (vector-ref
(array:vector ks)
(array:actor-index
(array:index ks)
(- k 1)))
m)))
((= k 0) m))
shv))))
(define (array:good-indices? ks shv)
(let ((d2 (vector-length shv)))
(do ((kp ks (if (pair? kp)
(cdr kp)))
(k 0 (+ k 2))
(true #t (and true (pair? kp)
(array:good-index? (car kp) shv k))))
((= k d2)
(and true (null? kp))))))
(define (array:good-indices.o? ks.o shv)
(let ((d2 (vector-length shv)))
(do ((kp ks.o (if (pair? kp)
(cdr kp)))
(k 0 (+ k 2))
(true #t (and true (pair? kp)
(array:good-index? (car kp) shv k))))
((= k d2)
(and true (pair? kp) (null? (cdr kp)))))))
(define (array:good-index-vector? ks shv)
(let ((r2 (vector-length shv)))
(and (= (* 2 (vector-length ks)) r2)
(do ((j 0 (+ j 1))
(k 0 (+ k 2))
(true #t (and true
(array:good-index? (vector-ref ks j) shv k))))
((= k r2) true)))))
(define (array:good-index-actor? r v i shv)
(and (= (* 2 r) (vector-length shv))
(do ((j 0 (+ j 1))
(k 0 (+ k 2))
(true #t (and true
(array:good-index? (vector-ref
v
(array:actor-index i j))
shv
k))))
((= j r) true))))
returns true if index is within bounds for dimension 2d/2 .
(define (array:good-index? w shv k)
(and (integer? w)
(exact? w)
(<= (vector-ref shv k) w)
(< w (vector-ref shv (+ k 1)))))
(define (array:not-in who ks shv)
(##sys#signal-hook #:bounds-error (string-append who ": index not in bounds") ks shv) )
(begin
(define (array:coefficients f n0 vs vp)
(case vp
((()) '())
(else
(set-car! vp 1)
(let ((n (- (apply f vs) n0)))
(set-car! vp 0)
(cons n (array:coefficients f n0 vs (cdr vp)))))))
(define (array:vector-index x ks)
(do ((sum 0 (+ sum (* (vector-ref x k) (car ks))))
(ks ks (cdr ks))
(k 0 (+ k 1)))
((null? ks) (+ sum (vector-ref x k)))))
(define (array:shape-index) '#(2 1 0))
(define (array:empty-shape-index) '#(0 0 -1))
(define (array:shape-vector-index x r k)
(+
(* (vector-ref x 0) r)
(* (vector-ref x 1) k)
(vector-ref x 2)))
(define (array:actor-index x k)
(+ (* (vector-ref x 0) k) (vector-ref x 1)))
(define (array:0 n0) (vector n0))
(define (array:1 n0 n1) (vector n1 n0))
(define (array:2 n0 n1 n2) (vector n1 n2 n0))
(define (array:3 n0 n1 n2 n3) (vector n1 n2 n3 n0))
(define (array:n n0 n1 n2 n3 n4 . ns)
(apply vector n1 n2 n3 n4 (append ns (list n0))))
(define (array:maker r)
(case r
((0) array:0)
((1) array:1)
((2) array:2)
((3) array:3)
(else array:n)))
(define array:indexer/vector
(let ((em
(vector
(lambda (x i) (+ (vector-ref x 0)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(vector-ref x 1)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(vector-ref x 2)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(vector-ref x 3)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(vector-ref x 4)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(vector-ref x 5)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(vector-ref x 6)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(vector-ref x 7)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(vector-ref x 8)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(* (vector-ref x 8) (vector-ref i 8))
(vector-ref x 9)))))
(it
(lambda (w)
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(* (vector-ref x 8) (vector-ref i 8))
(* (vector-ref x 9) (vector-ref i 9))
(do ((xi
0
(+
(* (vector-ref x u) (vector-ref i u))
xi))
(u (- w 1) (- u 1)))
((< u 10) xi))
(vector-ref x w))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:indexer/array
(let ((em
(vector
(lambda (x v i) (+ (vector-ref x 0)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(vector-ref x 1)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(vector-ref x 2)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(vector-ref x 3)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(vector-ref x 4)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(vector-ref x 5)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(vector-ref x 6)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(vector-ref x 7)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(vector-ref x 8)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(*
(vector-ref x 8)
(vector-ref v (array:actor-index i 8)))
(vector-ref x 9)))))
(it
(lambda (w)
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(*
(vector-ref x 8)
(vector-ref v (array:actor-index i 8)))
(*
(vector-ref x 9)
(vector-ref v (array:actor-index i 9)))
(do ((xi
0
(+
(*
(vector-ref x u)
(vector-ref
v
(array:actor-index i u)))
xi))
(u (- w 1) (- u 1)))
((< u 10) xi))
(vector-ref x w))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-vector
(let ((em
(vector
(lambda (p v) (p))
(lambda (p v) (p (vector-ref v 0)))
(lambda (p v)
(p (vector-ref v 0) (vector-ref v 1)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)
(vector-ref v 8)))))
(it
(lambda (r)
(lambda (p v)
(apply
p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)
(vector-ref v 8)
(vector-ref v 9)
(do ((k r (- k 1))
(r
'()
(cons (vector-ref v (- k 1)) r)))
((= k 10) r)))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-actor
(let ((em
(vector
(lambda (p a) (p))
(lambda (p a) (p (array-ref a 0)))
(lambda (p a)
(p (array-ref a 0) (array-ref a 1)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)
(array-ref a 8)))))
(it
(lambda (r)
(lambda (p a)
(apply
a
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)
(array-ref a 8)
(array-ref a 9)
(do ((k r (- k 1))
(r '() (cons (array-ref a (- k 1)) r)))
((= k 10) r)))))))
(lambda (r)
"These are high level, hiding implementation at call site."
(if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-backing-vector
(let ((em
(vector
(lambda (p ai av) (p))
(lambda (p ai av)
(p (vector-ref av (array:actor-index ai 0))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))
(vector-ref av (array:actor-index ai 8))))))
(it
(lambda (r)
(lambda (p ai av)
(apply
p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))
(vector-ref av (array:actor-index ai 8))
(vector-ref av (array:actor-index ai 9))
(do ((k r (- k 1))
(r
'()
(cons
(vector-ref
av
(array:actor-index ai (- k 1)))
r)))
((= k 10) r)))))))
(lambda (r)
"These are low level, exposing implementation at call site."
(if (< r 10) (vector-ref em r) (it r)))))
(define (array:index/vector r x v)
((array:indexer/vector r) x v))
(define (array:index/array r x av ai)
((array:indexer/array r) x av ai))
(define (array:apply-to-actor r p a)
((array:applier-to-actor r) p a))
(define (array:apply-to-vector r p v)
((array:applier-to-vector r) p v))
(define (array:optimize f r)
(case r
((0) (let ((n0 (f))) (array:0 n0)))
((1) (let ((n0 (f 0))) (array:1 n0 (- (f 1) n0))))
((2)
(let ((n0 (f 0 0)))
(array:2 n0 (- (f 1 0) n0) (- (f 0 1) n0))))
((3)
(let ((n0 (f 0 0 0)))
(array:3
n0
(- (f 1 0 0) n0)
(- (f 0 1 0) n0)
(- (f 0 0 1) n0))))
(else
(let ((v
(do ((k 0 (+ k 1)) (v '() (cons 0 v)))
((= k r) v))))
(let ((n0 (apply f v)))
(apply
array:n
n0
(array:coefficients f n0 v v)))))))
(define (array:optimize-empty r)
(let ((x (make-vector (+ r 1) 0)))
(vector-set! x r -1)
x)))
(define (array-ref a . xs)
(or (##core#check (array:array? a))
(##sys#signal-hook #:type-error 'array-ref "not an array" a))
(let ((shape (array:shape a)))
(##core#check
(if (null? xs)
(array:check-indices "array-ref" xs shape)
(let ((x (car xs)))
(if (vector? x)
(array:check-index-vector "array-ref" x shape)
(if (integer? x)
(array:check-indices "array-ref" xs shape)
(if (array:array? x)
(array:check-index-actor "array-ref" x shape)
(##sys#signal-hook #:type-error 'array-ref "not an index object" x)))))))
(vector-ref
(array:vector a)
(if (null? xs)
(vector-ref (array:index a) 0)
(let ((x (car xs)))
(if (vector? x)
(array:index/vector
(quotient (vector-length shape) 2)
(array:index a)
x)
(if (integer? x)
(array:vector-index (array:index a) xs)
(if (##core#check (array:array? x))
(array:index/array
(quotient (vector-length shape) 2)
(array:index a)
(array:vector x)
(array:index x))
(##sys#signal-hook #:type-error 'array-ref "bad index object" x)))))))))
(define (array-set! a x . xs)
(or (##core#check (array:array? a))
(##sys#signal-hook #:type-error 'array-set! "not an array" a))
(let ((shape (array:shape a)))
(##core#check
(if (null? xs)
(array:check-indices "array-set!" '() shape)
(if (vector? x)
(array:check-index-vector "array-set!" x shape)
(if (integer? x)
(array:check-indices.o "array-set!" (cons x xs) shape)
(if (array:array? x)
(array:check-index-actor "array-set!" x shape)
(##sys#signal-hook #:type-error 'array-set! "not an index object" x))))))
(if (null? xs)
(vector-set! (array:vector a) (vector-ref (array:index a) 0) x)
(if (vector? x)
(vector-set! (array:vector a)
(array:index/vector
(quotient (vector-length shape) 2)
(array:index a)
x)
(car xs))
(if (integer? x)
(let ((v (array:vector a))
(i (array:index a))
(r (quotient (vector-length shape) 2)))
(do ((sum (* (vector-ref i 0) x)
(+ sum (* (vector-ref i k) (car ks))))
(ks xs (cdr ks))
(k 1 (+ k 1)))
((= k r)
(vector-set! v (+ sum (vector-ref i k)) (car ks)))))
(if (##core#check (array:array? x))
(vector-set! (array:vector a)
(array:index/array
(quotient (vector-length shape) 2)
(array:index a)
(array:vector x)
(array:index x))
(car xs))
(##sys#signal-hook
#:type-error 'array-set!
"bad index object: "
x)))))))
(define (array:make-locative a x weak?)
(or (##core#check (array:array? a))
(##sys#signal-hook #:type-error 'array:make-locative "not an array"))
(let ((shape (array:shape a)))
(##core#check
(if (vector? x)
(array:check-index-vector "array:make-locative" x shape)
(if (integer? x)
(array:check-indices.o "array:make-locative" (list x) shape)
(if (array:array? x)
(array:check-index-actor "array:make-locative" x shape)
(##sys#signal-hook #:type-error 'array:make-locative "not an index object" x)))))
(if (vector? x)
(##core#inline_allocate
("C_a_i_make_locative" 5)
0
(array:vector a)
(array:index/vector
(quotient (vector-length shape) 2)
(array:index a)
x)
weak?)
(if (##core#check (array:array? x))
(##core#inline_allocate
("C_a_i_make_locative" 5)
0
(array:vector a)
(array:index/array
(quotient (vector-length shape) 2)
(array:index a)
(array:vector x)
(array:index x))
weak?)
(##sys#signal-hook #:type-error 'array:make-locative "bad index object: " x)))))
|
ebaf53ea8fec25b2e2ca4341878021d27941c90b740b33af652c88451e8555bc
|
lambdamikel/DLMAPS
|
strategy.lisp
|
;;; -*- Mode: LISP; Syntax: Common-Lisp; Package: PROVER -*-
(in-package :PROVER)
;;;
;;;
;;;
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro with-strategy ((strat) &body body)
`(let ((*strategy* ,strat))
(establish-context-for *strategy*
#'(lambda ()
,@body))))
(defpersistentclass strategy ())
(defpersistentclass trace-strategy (strategy))
(defpersistentclass abox-saturation-strategy (strategy))
;;;
;;;
;;;
(defmethod establish-context-for ((strategy strategy) fn)
(funcall fn))
(defmethod establish-context-for ((strategy abox-saturation-strategy) fn)
(let ((*maintain-unexpanded-or-concepts1-heap-p* t)
(*combined-some-all-rule-p* nil)
(*maintain-active-nodes-p* t)
)
(funcall fn)))
(defmethod establish-context-for ((strategy trace-strategy) fn)
(let ((*maintain-active-nodes-p* t))
(funcall fn)))
;;;
;;;
;;;
(defconstant +strategy+ (make-instance 'strategy))
(defconstant +trace-strategy+ (make-instance 'trace-strategy))
(defconstant +abox-saturation-strategy+ (make-instance 'abox-saturation-strategy))
)
| null |
https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/prover/strategy.lisp
|
lisp
|
-*- Mode: LISP; Syntax: Common-Lisp; Package: PROVER -*-
|
(in-package :PROVER)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro with-strategy ((strat) &body body)
`(let ((*strategy* ,strat))
(establish-context-for *strategy*
#'(lambda ()
,@body))))
(defpersistentclass strategy ())
(defpersistentclass trace-strategy (strategy))
(defpersistentclass abox-saturation-strategy (strategy))
(defmethod establish-context-for ((strategy strategy) fn)
(funcall fn))
(defmethod establish-context-for ((strategy abox-saturation-strategy) fn)
(let ((*maintain-unexpanded-or-concepts1-heap-p* t)
(*combined-some-all-rule-p* nil)
(*maintain-active-nodes-p* t)
)
(funcall fn)))
(defmethod establish-context-for ((strategy trace-strategy) fn)
(let ((*maintain-active-nodes-p* t))
(funcall fn)))
(defconstant +strategy+ (make-instance 'strategy))
(defconstant +trace-strategy+ (make-instance 'trace-strategy))
(defconstant +abox-saturation-strategy+ (make-instance 'abox-saturation-strategy))
)
|
250c2295f7902566c7bf524fe260ae80c9708c3910ed83c26d2cc023fb69f806
|
quil-lang/magicl
|
lapack-bindings.lisp
|
;;;; lapack-bindings.lisp
;;;;
Author :
(in-package #:magicl-lapack)
(macrolet ((def-all-lapack ()
"Define the lapack bindings for all lapack types"
`(progn
,@(loop :for type :in '(single-float double-float (complex single-float) (complex double-float))
:for real-type :in (list nil nil 'single-float 'double-float)
:for matrix-class :in '(matrix/single-float matrix/double-float matrix/complex-single-float matrix/complex-double-float)
:for vector-class :in '(vector/single-float vector/double-float vector/complex-single-float vector/complex-double-float)
:for prefix :in '("s" "d" "c" "z")
:append
(labels ((generate-routine-symbol (package routine)
(find-symbol (format nil "%~:@(~A~A~)" prefix routine) package))
(blas-routine (routine)
(generate-routine-symbol 'magicl.blas-cffi routine))
(lapack-routine (routine)
(generate-routine-symbol 'magicl.lapack-cffi routine)))
(let ((complex (not (null real-type))))
(list
(generate-lapack-mult-for-type
matrix-class vector-class type
(blas-routine "gemm") (blas-routine "gemv"))
(generate-lapack-lu-for-type
matrix-class type (lapack-routine "getrf"))
(generate-lapack-lu-solve-for-type
matrix-class type (lapack-routine "getrs"))
(generate-lapack-inv-for-type
matrix-class type
(lapack-routine "getrf") (lapack-routine "getri"))
(generate-lapack-svd-for-type
matrix-class type
(lapack-routine "gesvd")
real-type)
(generate-lapack-eig-for-type
matrix-class type
(lapack-routine "geev")
real-type)
(generate-lapack-ql-qr-rq-lq-for-type
matrix-class type
(lapack-routine "geqlf") (lapack-routine "geqrf")
(lapack-routine "gerqf") (lapack-routine "gelqf")
(lapack-routine (if complex "ungql" "orgql"))
(lapack-routine (if complex "ungqr" "orgqr"))
(lapack-routine (if complex "ungrq" "orgrq"))
(lapack-routine (if complex "unglq" "orglq")))
(when complex
(generate-lapack-hermitian-eig-for-type
matrix-class type
(lapack-routine "heev")
real-type)))))))))
(def-all-lapack))
| null |
https://raw.githubusercontent.com/quil-lang/magicl/9541b63b3913b2722ac9ed6463cce5cef13b3edc/src/extensions/lapack/lapack-bindings.lisp
|
lisp
|
lapack-bindings.lisp
|
Author :
(in-package #:magicl-lapack)
(macrolet ((def-all-lapack ()
"Define the lapack bindings for all lapack types"
`(progn
,@(loop :for type :in '(single-float double-float (complex single-float) (complex double-float))
:for real-type :in (list nil nil 'single-float 'double-float)
:for matrix-class :in '(matrix/single-float matrix/double-float matrix/complex-single-float matrix/complex-double-float)
:for vector-class :in '(vector/single-float vector/double-float vector/complex-single-float vector/complex-double-float)
:for prefix :in '("s" "d" "c" "z")
:append
(labels ((generate-routine-symbol (package routine)
(find-symbol (format nil "%~:@(~A~A~)" prefix routine) package))
(blas-routine (routine)
(generate-routine-symbol 'magicl.blas-cffi routine))
(lapack-routine (routine)
(generate-routine-symbol 'magicl.lapack-cffi routine)))
(let ((complex (not (null real-type))))
(list
(generate-lapack-mult-for-type
matrix-class vector-class type
(blas-routine "gemm") (blas-routine "gemv"))
(generate-lapack-lu-for-type
matrix-class type (lapack-routine "getrf"))
(generate-lapack-lu-solve-for-type
matrix-class type (lapack-routine "getrs"))
(generate-lapack-inv-for-type
matrix-class type
(lapack-routine "getrf") (lapack-routine "getri"))
(generate-lapack-svd-for-type
matrix-class type
(lapack-routine "gesvd")
real-type)
(generate-lapack-eig-for-type
matrix-class type
(lapack-routine "geev")
real-type)
(generate-lapack-ql-qr-rq-lq-for-type
matrix-class type
(lapack-routine "geqlf") (lapack-routine "geqrf")
(lapack-routine "gerqf") (lapack-routine "gelqf")
(lapack-routine (if complex "ungql" "orgql"))
(lapack-routine (if complex "ungqr" "orgqr"))
(lapack-routine (if complex "ungrq" "orgrq"))
(lapack-routine (if complex "unglq" "orglq")))
(when complex
(generate-lapack-hermitian-eig-for-type
matrix-class type
(lapack-routine "heev")
real-type)))))))))
(def-all-lapack))
|
b8fded2e07d4db6f895ac2c3e2ea9d3b06a6783431a3b20abc5073023d8f7a87
|
puffnfresh/sonic2
|
Player.hs
|
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
module Game.Sega.Sonic.Player (
Player(..)
, HasPlayer(..)
, Statuses(..)
, MdAir(..)
, MdRoll(..)
, HasPosition(..)
, PlayerRoutine(..)
, mdAir
, mdRoll
, playerRoutine
, playerVelocity
, playerRadius
, playerTopSpeed
, playerAcceleration
, playerDeceleration
, playerInertia
, playerAngle
, initialStatuses
, isJumping
, statuses
, resetOnFloor
, jump
, moveRight
, moveLeft
, settle
, traction
, normalTopSpeed
, normalAcceleration
, normalDeceleration
, underWaterTopSpeed
, underWaterAcceleration
, underWaterDeceleration
, pixels
, objectMove
, objectMoveAndFall
) where
import Control.Lens
import Control.Monad.Reader (MonadReader)
import Control.Monad.State
import Data.Bits
import Data.Halves (finiteBitHalves)
import Data.Int
import Data.Word (Word8)
import Foreign.C.Types
import Game.Sega.Sonic.Sine
import Game.Sega.Sonic.Types
import SDL
import Debug.Trace
data Player
= Player (V2 CInt) (V2 Int16) (V2 CInt) Int16 Int16 Int16 Int16 Word8 Statuses
deriving (Eq, Ord, Show)
class HasPlayer a where
player :: Lens' a Player
instance HasPlayer Player where
player =
id
data Statuses
= Statuses MdAir MdRoll
deriving (Eq, Ord, Show)
initialStatuses :: Statuses
initialStatuses =
Statuses MdAirOff MdRollOff
mdAir :: Lens' Statuses MdAir
mdAir =
lens f g
where
f (Statuses a _) =
a
g (Statuses _ b) a =
Statuses a b
mdRoll :: Lens' Statuses MdRoll
mdRoll =
lens f g
where
f (Statuses _ b) =
b
g (Statuses a _) b =
Statuses a b
isJumping :: Statuses -> Bool
isJumping s =
s ^. mdAir == MdAirOn && s ^. mdRoll == MdRollOn
data PlayerRoutine
= MdNormal
| MdAir
| MdRoll
| MdJump
deriving Show
playerRoutine :: Statuses -> PlayerRoutine
playerRoutine (Statuses MdAirOff MdRollOff) =
MdNormal
playerRoutine (Statuses MdAirOff MdRollOn) =
MdRoll
playerRoutine (Statuses MdAirOn MdRollOff) =
MdAir
playerRoutine (Statuses MdAirOn MdRollOn) =
MdJump
data MdAir
= MdAirOn
| MdAirOff
deriving (Eq, Ord, Show)
data MdRoll
= MdRollOn
| MdRollOff
deriving (Eq, Ord, Show)
instance HasPosition Player where
position =
lens y z
where
y (Player a _ _ _ _ _ _ _ _) =
a
z (Player _ b c d e f g h i) a =
Player a b c d e f g h i
playerVelocity :: Lens' Player (V2 Int16)
playerVelocity =
lens y z
where
y (Player _ b _ _ _ _ _ _ _) =
b
z (Player a _ c d e f g h i) b =
Player a b c d e f g h i
playerRadius :: Lens' Player (V2 CInt)
playerRadius =
lens y z
where
y (Player _ _ c _ _ _ _ _ _) =
c
z (Player a b _ d e f g h i) c =
Player a b c d e f g h i
playerTopSpeed :: Lens' Player Int16
playerTopSpeed =
lens y z
where
y (Player _ _ _ d _ _ _ _ _) =
d
z (Player a b c _ e f g h i) d =
Player a b c d e f g h i
playerAcceleration :: Lens' Player Int16
playerAcceleration =
lens y z
where
y (Player _ _ _ _ e _ _ _ _) =
e
z (Player a b c d _ f g h i) e =
Player a b c d e f g h i
playerDeceleration :: Lens' Player Int16
playerDeceleration =
lens y z
where
y (Player _ _ _ _ _ f _ _ _) =
f
z (Player a b c d e _ g h i) f =
Player a b c d e f g h i
playerInertia :: Lens' Player Int16
playerInertia =
lens y z
where
y (Player _ _ _ _ _ _ g _ _) =
g
z (Player a b c d e f _ h i) g =
Player a b c d e f g h i
playerAngle :: Lens' Player Word8
playerAngle =
lens y z
where
y (Player _ _ _ _ _ _ _ h _) =
h
z (Player a b c d e f g _ i) h =
Player a b c d e f g h i
statuses :: Lens' Player Statuses
statuses =
lens y z
where
y (Player _ _ _ _ _ _ _ _ i) =
i
z (Player a b c d e f g h _) i =
Player a b c d e f g h i
moveRight :: (MonadState Player m) => m ()
moveRight = do
acceleration <- use playerAcceleration
playerInertia += acceleration
topSpeed <- use playerTopSpeed
i <- use playerInertia
unless (i < topSpeed) $ do
playerInertia -= acceleration
i' <- use playerInertia
when (i' >= topSpeed) $
playerInertia .= topSpeed
moveLeft :: (MonadState Player m) => m ()
moveLeft = do
acceleration <- use playerAcceleration
playerInertia -= acceleration
topSpeed <- use playerTopSpeed
i <- use playerInertia
unless (i > -topSpeed) $ do
playerInertia += acceleration
i' <- use playerInertia
when (i' <= -topSpeed) $
playerInertia .= -topSpeed
settle :: (MonadState Player m) => m ()
settle = do
i <- use playerInertia
if i > 0
then settleRight
else settleLeft
settleRight :: (MonadState Player m) => m ()
settleRight = do
playerInertia %= \i -> max 0 (i - 0xC)
settleLeft :: (MonadState Player m) => m ()
settleLeft = do
playerInertia %= \i -> min 0 (i + 0xC)
traction :: (HasPlayer s, MonadState s m) => m ()
traction = do
-- let
-- angle =
-- 0
-- cosine =
256
-- sine =
-- 0
inertia <- use (player . playerInertia)
-- let
-- x =
( inertia * cosine ) ` shiftR ` 8
-- y =
( inertia * sine ) ` shiftR ` 8
-- v =
-- V2 (fromIntegral x) (fromIntegral y)
-- playerVelocity .= v
player . playerVelocity .= V2 (fromIntegral inertia) 0
cIntHalves :: Iso' CInt (Int16, Int16)
cIntHalves =
finiteBitHalves
pixels :: Lens' (V2 CInt) (V2 Int16)
pixels =
lens f g
where
f (V2 a b) =
V2 (a ^. cIntHalves . _1) (b ^. cIntHalves . _1)
g (V2 a b) (V2 x y) =
V2 (a & cIntHalves . _1 .~ x) (b & cIntHalves . _1 .~ y)
jump :: (HasSineData a, MonadReader a m, MonadState Player m) => m ()
jump = do
angle' <- use playerAngle
(sine, cosine) <- calcSine (angle' - 0x40)
let
jumpSpeed :: Int32
jumpSpeed =
0x680
x :: Int16
x =
fromIntegral $ (jumpSpeed * fromIntegral cosine) `shiftR` 8
y :: Int16
y =
fromIntegral $ (jumpSpeed * fromIntegral sine) `shiftR` 8
statuses . mdAir .= MdAirOn
statuses . mdRoll .= MdRollOn
playerVelocity . _x += x
playerVelocity . _y += y
objectMoveAndFall :: (MonadState Player m) => m ()
objectMoveAndFall = do
velocity <- use playerVelocity
playerVelocity . _y += 0x38
position += ((`shiftL` 8) . fromIntegral <$> velocity)
objectMove :: (MonadState Player m) => m ()
objectMove = do
velocity <- use playerVelocity
position += ((`shiftL` 8) . fromIntegral <$> velocity)
resetOnFloor :: (HasPlayer s, MonadState s m) => m ()
resetOnFloor = do
player . statuses . mdAir .= MdAirOff
player . statuses . mdRoll .= MdRollOff
normalTopSpeed :: Int16
normalTopSpeed =
0x600
normalAcceleration :: Int16
normalAcceleration =
0xC
normalDeceleration :: Int16
normalDeceleration =
0x80
underWaterTopSpeed :: Int16
underWaterTopSpeed =
0x300
underWaterAcceleration :: Int16
underWaterAcceleration =
0x6
underWaterDeceleration :: Int16
underWaterDeceleration =
0x40
| null |
https://raw.githubusercontent.com/puffnfresh/sonic2/0abc3e109a847582c2e16edb13e83e611419fc8a/src/Game/Sega/Sonic/Player.hs
|
haskell
|
# LANGUAGE FlexibleContexts #
let
angle =
0
cosine =
sine =
0
let
x =
y =
v =
V2 (fromIntegral x) (fromIntegral y)
playerVelocity .= v
|
# LANGUAGE MultiParamTypeClasses #
module Game.Sega.Sonic.Player (
Player(..)
, HasPlayer(..)
, Statuses(..)
, MdAir(..)
, MdRoll(..)
, HasPosition(..)
, PlayerRoutine(..)
, mdAir
, mdRoll
, playerRoutine
, playerVelocity
, playerRadius
, playerTopSpeed
, playerAcceleration
, playerDeceleration
, playerInertia
, playerAngle
, initialStatuses
, isJumping
, statuses
, resetOnFloor
, jump
, moveRight
, moveLeft
, settle
, traction
, normalTopSpeed
, normalAcceleration
, normalDeceleration
, underWaterTopSpeed
, underWaterAcceleration
, underWaterDeceleration
, pixels
, objectMove
, objectMoveAndFall
) where
import Control.Lens
import Control.Monad.Reader (MonadReader)
import Control.Monad.State
import Data.Bits
import Data.Halves (finiteBitHalves)
import Data.Int
import Data.Word (Word8)
import Foreign.C.Types
import Game.Sega.Sonic.Sine
import Game.Sega.Sonic.Types
import SDL
import Debug.Trace
data Player
= Player (V2 CInt) (V2 Int16) (V2 CInt) Int16 Int16 Int16 Int16 Word8 Statuses
deriving (Eq, Ord, Show)
class HasPlayer a where
player :: Lens' a Player
instance HasPlayer Player where
player =
id
data Statuses
= Statuses MdAir MdRoll
deriving (Eq, Ord, Show)
initialStatuses :: Statuses
initialStatuses =
Statuses MdAirOff MdRollOff
mdAir :: Lens' Statuses MdAir
mdAir =
lens f g
where
f (Statuses a _) =
a
g (Statuses _ b) a =
Statuses a b
mdRoll :: Lens' Statuses MdRoll
mdRoll =
lens f g
where
f (Statuses _ b) =
b
g (Statuses a _) b =
Statuses a b
isJumping :: Statuses -> Bool
isJumping s =
s ^. mdAir == MdAirOn && s ^. mdRoll == MdRollOn
data PlayerRoutine
= MdNormal
| MdAir
| MdRoll
| MdJump
deriving Show
playerRoutine :: Statuses -> PlayerRoutine
playerRoutine (Statuses MdAirOff MdRollOff) =
MdNormal
playerRoutine (Statuses MdAirOff MdRollOn) =
MdRoll
playerRoutine (Statuses MdAirOn MdRollOff) =
MdAir
playerRoutine (Statuses MdAirOn MdRollOn) =
MdJump
data MdAir
= MdAirOn
| MdAirOff
deriving (Eq, Ord, Show)
data MdRoll
= MdRollOn
| MdRollOff
deriving (Eq, Ord, Show)
instance HasPosition Player where
position =
lens y z
where
y (Player a _ _ _ _ _ _ _ _) =
a
z (Player _ b c d e f g h i) a =
Player a b c d e f g h i
playerVelocity :: Lens' Player (V2 Int16)
playerVelocity =
lens y z
where
y (Player _ b _ _ _ _ _ _ _) =
b
z (Player a _ c d e f g h i) b =
Player a b c d e f g h i
playerRadius :: Lens' Player (V2 CInt)
playerRadius =
lens y z
where
y (Player _ _ c _ _ _ _ _ _) =
c
z (Player a b _ d e f g h i) c =
Player a b c d e f g h i
playerTopSpeed :: Lens' Player Int16
playerTopSpeed =
lens y z
where
y (Player _ _ _ d _ _ _ _ _) =
d
z (Player a b c _ e f g h i) d =
Player a b c d e f g h i
playerAcceleration :: Lens' Player Int16
playerAcceleration =
lens y z
where
y (Player _ _ _ _ e _ _ _ _) =
e
z (Player a b c d _ f g h i) e =
Player a b c d e f g h i
playerDeceleration :: Lens' Player Int16
playerDeceleration =
lens y z
where
y (Player _ _ _ _ _ f _ _ _) =
f
z (Player a b c d e _ g h i) f =
Player a b c d e f g h i
playerInertia :: Lens' Player Int16
playerInertia =
lens y z
where
y (Player _ _ _ _ _ _ g _ _) =
g
z (Player a b c d e f _ h i) g =
Player a b c d e f g h i
playerAngle :: Lens' Player Word8
playerAngle =
lens y z
where
y (Player _ _ _ _ _ _ _ h _) =
h
z (Player a b c d e f g _ i) h =
Player a b c d e f g h i
statuses :: Lens' Player Statuses
statuses =
lens y z
where
y (Player _ _ _ _ _ _ _ _ i) =
i
z (Player a b c d e f g h _) i =
Player a b c d e f g h i
moveRight :: (MonadState Player m) => m ()
moveRight = do
acceleration <- use playerAcceleration
playerInertia += acceleration
topSpeed <- use playerTopSpeed
i <- use playerInertia
unless (i < topSpeed) $ do
playerInertia -= acceleration
i' <- use playerInertia
when (i' >= topSpeed) $
playerInertia .= topSpeed
moveLeft :: (MonadState Player m) => m ()
moveLeft = do
acceleration <- use playerAcceleration
playerInertia -= acceleration
topSpeed <- use playerTopSpeed
i <- use playerInertia
unless (i > -topSpeed) $ do
playerInertia += acceleration
i' <- use playerInertia
when (i' <= -topSpeed) $
playerInertia .= -topSpeed
settle :: (MonadState Player m) => m ()
settle = do
i <- use playerInertia
if i > 0
then settleRight
else settleLeft
settleRight :: (MonadState Player m) => m ()
settleRight = do
playerInertia %= \i -> max 0 (i - 0xC)
settleLeft :: (MonadState Player m) => m ()
settleLeft = do
playerInertia %= \i -> min 0 (i + 0xC)
traction :: (HasPlayer s, MonadState s m) => m ()
traction = do
256
inertia <- use (player . playerInertia)
( inertia * cosine ) ` shiftR ` 8
( inertia * sine ) ` shiftR ` 8
player . playerVelocity .= V2 (fromIntegral inertia) 0
cIntHalves :: Iso' CInt (Int16, Int16)
cIntHalves =
finiteBitHalves
pixels :: Lens' (V2 CInt) (V2 Int16)
pixels =
lens f g
where
f (V2 a b) =
V2 (a ^. cIntHalves . _1) (b ^. cIntHalves . _1)
g (V2 a b) (V2 x y) =
V2 (a & cIntHalves . _1 .~ x) (b & cIntHalves . _1 .~ y)
jump :: (HasSineData a, MonadReader a m, MonadState Player m) => m ()
jump = do
angle' <- use playerAngle
(sine, cosine) <- calcSine (angle' - 0x40)
let
jumpSpeed :: Int32
jumpSpeed =
0x680
x :: Int16
x =
fromIntegral $ (jumpSpeed * fromIntegral cosine) `shiftR` 8
y :: Int16
y =
fromIntegral $ (jumpSpeed * fromIntegral sine) `shiftR` 8
statuses . mdAir .= MdAirOn
statuses . mdRoll .= MdRollOn
playerVelocity . _x += x
playerVelocity . _y += y
objectMoveAndFall :: (MonadState Player m) => m ()
objectMoveAndFall = do
velocity <- use playerVelocity
playerVelocity . _y += 0x38
position += ((`shiftL` 8) . fromIntegral <$> velocity)
objectMove :: (MonadState Player m) => m ()
objectMove = do
velocity <- use playerVelocity
position += ((`shiftL` 8) . fromIntegral <$> velocity)
resetOnFloor :: (HasPlayer s, MonadState s m) => m ()
resetOnFloor = do
player . statuses . mdAir .= MdAirOff
player . statuses . mdRoll .= MdRollOff
normalTopSpeed :: Int16
normalTopSpeed =
0x600
normalAcceleration :: Int16
normalAcceleration =
0xC
normalDeceleration :: Int16
normalDeceleration =
0x80
underWaterTopSpeed :: Int16
underWaterTopSpeed =
0x300
underWaterAcceleration :: Int16
underWaterAcceleration =
0x6
underWaterDeceleration :: Int16
underWaterDeceleration =
0x40
|
7c1a20d8caf290446df745e191941c441feb5e17ca0a446a9f847efe1b1b962a
|
icfpcontest2021/icfpcontest2021.github.io
|
Polygon.hs
|
module BrainWall.Polygon
( Polygon
, unPolygon
, mkPolygon
, polygonSimplify
, polygonVertices
, polygonEdges
, polygonCorners
, polygonSplitEdge
, clockwise
) where
import BrainWall.Polygon.Internal
| null |
https://raw.githubusercontent.com/icfpcontest2021/icfpcontest2021.github.io/fb23fea2a8ecec7740017d3dda78d921c1df5a26/toolchain/lib/BrainWall/Polygon.hs
|
haskell
|
module BrainWall.Polygon
( Polygon
, unPolygon
, mkPolygon
, polygonSimplify
, polygonVertices
, polygonEdges
, polygonCorners
, polygonSplitEdge
, clockwise
) where
import BrainWall.Polygon.Internal
|
|
30f3c610805e4554773d49d092a6e3e494ee9304d01fbcf33a4d9f900dde7476
|
cstar/ejabberd-old
|
ejabberd_rdbms.erl
|
%%%----------------------------------------------------------------------
%%% File : ejabberd_rdbms.erl
Author : < >
%%% Purpose : Manage the start of the database modules when needed
Created : 31 Jan 2003 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2010 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%----------------------------------------------------------------------
-module(ejabberd_rdbms).
-author('').
-export([start/0]).
-include("ejabberd.hrl").
start() ->
Check if ejabberd has been compiled with ODBC
case catch ejabberd_odbc_sup:module_info() of
{'EXIT',{undef,_}} ->
?INFO_MSG("ejabberd has not been compiled with relational database support. Skipping database startup.", []);
_ ->
If compiled with ODBC , start ODBC on the needed host
start_hosts()
end.
Start relationnal DB module on the nodes where it is needed
start_hosts() ->
lists:foreach(
fun(Host) ->
case needs_odbc(Host) of
true -> start_odbc(Host);
false -> ok
end
end, ?MYHOSTS).
Start the ODBC module on the given host
start_odbc(Host) ->
Supervisor_name = gen_mod:get_module_proc(Host, ejabberd_odbc_sup),
ChildSpec =
{Supervisor_name,
{ejabberd_odbc_sup, start_link, [Host]},
transient,
infinity,
supervisor,
[ejabberd_odbc_sup]},
case supervisor:start_child(ejabberd_sup, ChildSpec) of
{ok, _PID} ->
ok;
_Error ->
?ERROR_MSG("Start of supervisor ~p failed:~n~p~nRetrying...~n", [Supervisor_name, _Error]),
start_odbc(Host)
end.
Returns true if we have configured odbc_server for the given host
needs_odbc(Host) ->
LHost = jlib:nameprep(Host),
case ejabberd_config:get_local_option({odbc_server, LHost}) of
undefined ->
false;
_ -> true
end.
| null |
https://raw.githubusercontent.com/cstar/ejabberd-old/559f8b6b0a935710fe93e9afacb4270d6d6ea00f/src/ejabberd_rdbms.erl
|
erlang
|
----------------------------------------------------------------------
File : ejabberd_rdbms.erl
Purpose : Manage the start of the database modules when needed
This program is free software; you can redistribute it and/or
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.
along with this program; if not, write to the Free Software
----------------------------------------------------------------------
|
Author : < >
Created : 31 Jan 2003 by < >
ejabberd , Copyright ( C ) 2002 - 2010 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(ejabberd_rdbms).
-author('').
-export([start/0]).
-include("ejabberd.hrl").
start() ->
Check if ejabberd has been compiled with ODBC
case catch ejabberd_odbc_sup:module_info() of
{'EXIT',{undef,_}} ->
?INFO_MSG("ejabberd has not been compiled with relational database support. Skipping database startup.", []);
_ ->
If compiled with ODBC , start ODBC on the needed host
start_hosts()
end.
Start relationnal DB module on the nodes where it is needed
start_hosts() ->
lists:foreach(
fun(Host) ->
case needs_odbc(Host) of
true -> start_odbc(Host);
false -> ok
end
end, ?MYHOSTS).
Start the ODBC module on the given host
start_odbc(Host) ->
Supervisor_name = gen_mod:get_module_proc(Host, ejabberd_odbc_sup),
ChildSpec =
{Supervisor_name,
{ejabberd_odbc_sup, start_link, [Host]},
transient,
infinity,
supervisor,
[ejabberd_odbc_sup]},
case supervisor:start_child(ejabberd_sup, ChildSpec) of
{ok, _PID} ->
ok;
_Error ->
?ERROR_MSG("Start of supervisor ~p failed:~n~p~nRetrying...~n", [Supervisor_name, _Error]),
start_odbc(Host)
end.
Returns true if we have configured odbc_server for the given host
needs_odbc(Host) ->
LHost = jlib:nameprep(Host),
case ejabberd_config:get_local_option({odbc_server, LHost}) of
undefined ->
false;
_ -> true
end.
|
bf0cf3f1e43a931b2f3d1946b136ceb793b8bd322d16e01e42ab73de86e60e73
|
blynn/compiler
|
party.hs
|
-- Modules.
module Main where
import Base
import Map
import Ast
import RTS
import Typer
import Kiselyov
import System
hide_prelude_here' = hide_prelude_here'
dumpWith dumper s = case untangle s of
Left err -> err
Right tab -> foldr ($) [] $ map (\(name, mod) -> ("module "++) . (name++) . ('\n':) . (foldr (.) id $ dumper mod)) $ toAscList tab
dumpLambs (typed, _) = map (\(s, (_, t)) -> (s++) . (" = "++) . shows t . ('\n':)) $ toAscList typed
dumpTypes (typed, _) = map (\(s, (q, _)) -> (s++) . (" :: "++) . shows q . ('\n':)) $ toAscList typed
dumpCombs (typed, _) = go <$> optiComb (lambsList typed) where
go (s, t) = (s++) . (" = "++) . shows t . (";\n"++)
main = getArgs >>= \case
"comb":_ -> interact $ dumpWith dumpCombs
"lamb":_ -> interact $ dumpWith dumpLambs
"type":_ -> interact $ dumpWith dumpTypes
_ -> interact \s -> either id id $ untangle s >>= compile
| null |
https://raw.githubusercontent.com/blynn/compiler/b9fe455ad4ee4fbabe77f2f5c3c9aaa53cffa85b/inn/party.hs
|
haskell
|
Modules.
|
module Main where
import Base
import Map
import Ast
import RTS
import Typer
import Kiselyov
import System
hide_prelude_here' = hide_prelude_here'
dumpWith dumper s = case untangle s of
Left err -> err
Right tab -> foldr ($) [] $ map (\(name, mod) -> ("module "++) . (name++) . ('\n':) . (foldr (.) id $ dumper mod)) $ toAscList tab
dumpLambs (typed, _) = map (\(s, (_, t)) -> (s++) . (" = "++) . shows t . ('\n':)) $ toAscList typed
dumpTypes (typed, _) = map (\(s, (q, _)) -> (s++) . (" :: "++) . shows q . ('\n':)) $ toAscList typed
dumpCombs (typed, _) = go <$> optiComb (lambsList typed) where
go (s, t) = (s++) . (" = "++) . shows t . (";\n"++)
main = getArgs >>= \case
"comb":_ -> interact $ dumpWith dumpCombs
"lamb":_ -> interact $ dumpWith dumpLambs
"type":_ -> interact $ dumpWith dumpTypes
_ -> interact \s -> either id id $ untangle s >>= compile
|
db3f680e76fa6798aca2bc6d9e002e7e38602971495734529aeeeef769359013
|
wedesoft/aiscm
|
virtual_arrays.scm
|
(use-modules (oop goops) (aiscm core))
(define f (jit (list (rgb <int>) (llvmarray <int> 1)) +))
(f (rgb 1 2 3) (arr <int> 4 5 6))
# < multiarray < int<32,signed>,1 > > :
( ( rgb 5 6 7 ) ( rgb 6 7 8) ( rgb 7 8 9 ) )
| null |
https://raw.githubusercontent.com/wedesoft/aiscm/2c3db8d00cad6e042150714ada85da19cf4338ad/tests/integration/virtual_arrays.scm
|
scheme
|
(use-modules (oop goops) (aiscm core))
(define f (jit (list (rgb <int>) (llvmarray <int> 1)) +))
(f (rgb 1 2 3) (arr <int> 4 5 6))
# < multiarray < int<32,signed>,1 > > :
( ( rgb 5 6 7 ) ( rgb 6 7 8) ( rgb 7 8 9 ) )
|
|
01c5ff8d564e8fe2d1fe3e8759e1b80192d575eb7592f60adc19a8acee76122e
|
rems-project/cerberus
|
pp_prelude.mli
|
module P = PPrint
val (!^): string -> P.document
val (^^): P.document -> P.document -> P.document
val (^/^): P.document -> P.document -> P.document
val (^//^): P.document -> P.document -> P.document
val (^^^): P.document -> P.document -> P.document
val comma_list: ('a -> P.document) -> 'a list -> P.document
val semi_list: ('a -> P.document) -> 'a list -> P.document
val with_grouped_arg: P.document -> P.document -> P.document
val with_grouped_args: ?sep:P.document -> P.document -> P.document list -> P.document
| null |
https://raw.githubusercontent.com/rems-project/cerberus/dbfab2643ce6cedb54d2a52cbcb3673e03bfd161/util/pp_prelude.mli
|
ocaml
|
module P = PPrint
val (!^): string -> P.document
val (^^): P.document -> P.document -> P.document
val (^/^): P.document -> P.document -> P.document
val (^//^): P.document -> P.document -> P.document
val (^^^): P.document -> P.document -> P.document
val comma_list: ('a -> P.document) -> 'a list -> P.document
val semi_list: ('a -> P.document) -> 'a list -> P.document
val with_grouped_arg: P.document -> P.document -> P.document
val with_grouped_args: ?sep:P.document -> P.document -> P.document list -> P.document
|
|
55a758c7bf0717253e906b91f7bff144daf281ad7c6617d34961d3b2e2d381ea
|
MedeaMelana/Magic
|
Engine.hs
|
# LANGUAGE TypeOperators #
# LANGUAGE TupleSections #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE GADTs #-}
# LANGUAGE DataKinds #
module Magic.Engine (newWorld, fullGame, Engine(..)) where
import Magic.Core
import Magic.Events hiding (executeEffect, executeEffects)
import qualified Magic.IdList as IdList
import Magic.Labels
import Magic.ObjectTypes
import Magic.Predicates
import Magic.Target
import Magic.Types
import Magic.Utils
import Magic.Engine.Types
import Magic.Engine.Events
import Magic.Some
import Control.Applicative ((<$>), (<*>))
import Control.Category ((.))
import Control.Monad (forever, forM_, when, void, liftM, unless)
import Control.Monad.Trans (lift)
import Control.Monad.Writer (tell, execWriterT)
import Data.Boolean ((&&*))
import Data.Label (get, set, modify)
import Data.Label.Monadic (gets, (=:), (=.), asks)
import Data.List (nub, intersect, delete)
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import qualified Data.MultiSet as MultiSet
import qualified Data.Text as Text
import Data.Text (Text)
import Data.Traversable (for)
import Prelude hiding (round, (.))
newWorld :: [Deck] -> World
newWorld decks = World
{ _players = ps
, _activePlayer = head playerIds
, _activeStep = BeginningPhase UntapStep
, _time = 0
, _turnStructure = ts
, _exile = IdList.empty
, _battlefield = IdList.empty
, _stack = IdList.empty
, _command = IdList.empty
, _turnHistory = []
}
where
ps = IdList.fromListWithId (\i deck -> newPlayer i deck) decks
playerIds = IdList.ids ps
ts = case playerIds of
103.7a . In a two - player game , the player who plays first skips the draw step of his or her first turn .
[p1, p2] -> (p1, removeFirst (== BeginningPhase DrawStep) turnSteps)
: cycle [(p2, turnSteps), (p1, turnSteps)]
_ -> cycle (map (, turnSteps) playerIds)
removeFirst :: (a -> Bool) -> [a] -> [a]
removeFirst notOk xs =
case break notOk xs of
(as, _ : bs) -> as ++ bs
_ -> xs
turnSteps :: [Step]
turnSteps =
[ BeginningPhase UntapStep
, BeginningPhase UpkeepStep
, BeginningPhase DrawStep
, MainPhase
, CombatPhase BeginningOfCombatStep
, CombatPhase DeclareAttackersStep
, CombatPhase DeclareBlockersStep
, CombatPhase CombatDamageStep
, CombatPhase EndOfCombatStep
, MainPhase
, EndPhase EndOfTurnStep
, EndPhase CleanupStep
]
newPlayer :: PlayerRef -> Deck -> Player
newPlayer i deck = Player
{ _life = 20
, _manaPool = mempty
, _prestack = []
, _library = IdList.fromList [ CardObject (instantiateCard card i)
| card <- deck ]
, _hand = IdList.empty
, _graveyard = IdList.empty
, _maximumHandSize = Just 7
, _failedCardDraw = False
}
drawOpeningHands :: [PlayerRef] -> Int -> Engine ()
drawOpeningHands [] _ =
return ()
drawOpeningHands playerIds 0 =
void $ executeEffects TurnBasedActions (map (Will . ShuffleLibrary) playerIds)
drawOpeningHands playerIds handSize = do
mulliganingPlayers <- do
forM_ playerIds $ \playerId -> do
_ <- undrawHand TurnBasedActions playerId
_ <- executeEffect TurnBasedActions (Will (ShuffleLibrary playerId))
executeEffects TurnBasedActions (replicate handSize (Will (DrawCard playerId)))
for playerIds $ \playerId -> do
keepHand <- askQuestion playerId AskKeepHand
if keepHand
then return Nothing
else return (Just playerId)
drawOpeningHands (catMaybes mulliganingPlayers) (handSize - 1)
undrawHand :: EventSource -> PlayerRef -> Engine [Event]
undrawHand source p = do
idxs <- IdList.toList <$> gets (hand . player p)
executeEffects source [ WillMoveObject (Just (Some (Hand p), i)) (Library p) x | (i, x) <- idxs ]
fullGame :: Engine ()
fullGame = do
ps <- IdList.ids <$> gets players
drawOpeningHands ps 7
forever $ do
players =.* set manaPool mempty
(step, newTurn) <- nextStep
when newTurn (turnHistory =: [])
raise TurnBasedActions [DidBeginStep step]
executeStep step
raise TurnBasedActions [WillEndStep step]
-- | Moves to the next step. Returns the new step, and whether a new turn has begun.
nextStep :: Engine (Step, Bool)
nextStep = do
structure <- gets turnStructure
case structure of
(rp, s : ss) : ts -> do
turnStructure =: if null ss then ts else (rp, ss) : ts
activePlayer =: rp
activeStep =: s
return (s, null ss)
-- Execution of steps
executeStep :: Step -> Engine ()
executeStep (BeginningPhase UntapStep) = do
TODO [ 502.1 ] phasing
[ 502.2 ] untap permanents
rp <- gets activePlayer
ios <- (IdList.filter (\perm@Permanent {} -> isControlledBy rp (get objectPart perm))) <$> gets battlefield
_ <- executeEffects TurnBasedActions (map (\(i, _) -> Will (UntapPermanent (Battlefield, i))) ios)
return ()
executeStep (BeginningPhase UpkeepStep) = do
TODO [ 503.1 ] handle triggers
[ 503.2 ]
offerPriority
executeStep (BeginningPhase DrawStep) = do
[ 504.1 ]
ap <- gets activePlayer
_ <- executeEffect TurnBasedActions (Will (DrawCard ap))
TODO [ 504.2 ] handle triggers
[ 504.3 ]
offerPriority
executeStep MainPhase = do
TODO [ 505.4 ] handle triggers
[ 505.5 ]
offerPriority
executeStep (CombatPhase BeginningOfCombatStep) = do
offerPriority
executeStep (CombatPhase DeclareAttackersStep) = do
[ 508.1a ] declare attackers
-- [508.1b] declare which player or planeswalker each attacker attacks
-- TODO Offer attacking planeswalkers
-- TODO Check summoning sickness
ap <- gets activePlayer
let canAttack perm =
(isControlledBy ap &&* hasTypes creatureType) (get objectPart perm)
&& get tapStatus perm == Untapped
possibleAttackerRefs <- map (\(i,_) -> (Battlefield, i)) . filter (canAttack . snd) . IdList.toList <$> view (asks battlefield)
attackablePlayerRefs <- (filter (/= ap) . IdList.ids) <$> gets players
attacks <- askQuestion ap (AskAttackers possibleAttackerRefs (map PlayerRef attackablePlayerRefs))
-- TODO [508.1c] check attacking restrictions
-- TODO [508.1d] check attacking requirements
TODO [ 508.1e ] declare banding
-- [508.1f] tap attackers
forM_ attacks $ \(Attack rAttacker _rAttackee) -> do
keywords <- view (asks (staticKeywordAbilities . objectPart . object rAttacker))
unless (elem Vigilance keywords) $
tapStatus . object rAttacker =: Tapped
TODO [ 508.1 g ] determine costs
-- TODO [508.1h] allow mana abilities
TODO [ 508.1i ] pay costs
[ 508.1j ] mark creatures as attacking
forM_ attacks $ \(Attack rAttacker rAttackee) ->
attacking . object rAttacker =: Just rAttackee
[ 508.2 ] handle triggers
raise TurnBasedActions [DidDeclareAttackers ap attacks]
offerPriority
TODO [ 508.6 ] potentially skip declare blockers and combat damage steps
return ()
executeStep (CombatPhase DeclareBlockersStep) = do
TODO [ 509.1a ] declare blockers
TODO [ 509.1b ] check blocking restrictions
-- TODO [509.1c] check blocking requirements
TODO [ 509.1d ] determine costs
TODO [ 509.1e ] allow mana abilities
TODO [ 509.1f ] pay costs
TODO [ 509.1 g ] mark creatures as blocking
TODO [ 509.1h ] mark creatures as blocked
TODO [ 509.2 ] declare attackers ' damage assignment order
TODO [ 509.3 ] declare blockers ' damage assignment order
TODO [ 509.4 ] handle triggers
offerPriority
TODO [ 509.6 ] determine new attackers ' damage assignment order
TODO [ 509.7 ] determine new blockers ' damage assignment order
return ()
executeStep (CombatPhase CombatDamageStep) = do
TODO [ 510.1 ] assign combat damage
TODO [ 510.2 ] deal damage
TODO [ 510.3 ] handle triggers
effectses <- view $ do
permanents <- IdList.toList <$> asks battlefield
for permanents $ \(r, permanent) -> do
let attackingObject = _permanentObject permanent
let Just (power, _) = _pt attackingObject
case _attacking permanent of
Nothing -> return []
Just (PlayerRef p) -> return [Will (DamagePlayer attackingObject p power True True)]
Just (ObjectRef (Some Battlefield, i)) -> return [Will (DamageObject attackingObject (Battlefield, i) power True True)]
_ <- executeEffects TurnBasedActions (concat effectses)
offerPriority
TODO [ 510.5 ] possibly introduce extra combat damage step for first / double strike
return ()
executeStep (CombatPhase EndOfCombatStep) = do
TODO [ 511.1 ] handle triggers
[ 511.2 ]
offerPriority
[ 511.3 ] remove creatures from combat
battlefield =.* set attacking Nothing
executeStep (EndPhase EndOfTurnStep) = do
TODO [ 513.1 ] handle triggers
[ 513.2 ]
offerPriority
executeStep (EndPhase CleanupStep) = do
TODO [ 514.1 ] discard excess cards
[ 514.2 ] remove damage from permanents
battlefield =.* set damage 0
[ 514.2 ] Remove effects that last until end of turn
battlefield =.* modify (temporaryEffects . objectPart)
(filter (\tle -> temporaryDuration tle /= UntilEndOfTurn))
shouldOfferPriority <- executeSBAsAndProcessPrestacks
when shouldOfferPriority offerPriority
offerPriority :: Engine ()
offerPriority = gets activePlayer >>= fullRoundStartingWith
where
fullRoundStartingWith p = do
_ <- executeSBAsAndProcessPrestacks
mAction <- playersStartingWith p >>= partialRound
case mAction of
Just (initiatingPlayer, action) -> do
executePriorityAction initiatingPlayer action
fullRoundStartingWith initiatingPlayer
Nothing -> do
st <- gets stack
case IdList.head st of
Nothing -> return ()
Just (i, _) -> do
resolve (Stack, i)
offerPriority
partialRound ((p, _):ps) = do
actions <- collectPriorityActions p
mAction <- askQuestion p (AskPriorityAction actions)
case mAction of
Just action -> return (Just (p, action))
Nothing -> partialRound ps
partialRound [] = return Nothing
-- | Repeatedly checks and execute state-based effects and asks players to put triggered abilities
on the stack , until everything has been processed . Returns whether any SBAs have been taken or
-- whether any abilities have been put on the stack.
executeSBAsAndProcessPrestacks :: Engine Bool
executeSBAsAndProcessPrestacks = untilFalse ((||) <$> checkSBAs <*> processPrestacks)
-- | Repeatedly checks and executes state-based effects until no more actions need to be taken.
-- Returns whether any actions were taken at all.
checkSBAs :: Engine Bool
checkSBAs = untilFalse $ (not . null) <$> checkSBAsOnce
where
checkSBAsOnce = collectSBAs >>= executeEffects StateBasedActions
| Ask players to put pending items on the stack in APNAP order . [ 405.3 ]
-- Returns whether anything was put on the stack as a result.
processPrestacks :: Engine Bool
processPrestacks = do
ips <- apnap
liftM or $ for ips $ \(i,p) -> do
let pending = get prestack p
when (not (null pending)) $ do
index <- askQuestion i (AskPickTrigger (map fst pending))
let (lki, program) = pending !! index
executeMagic (StackTrigger lki) program
prestack . player i =. deleteAtIndex index
return (not (null pending))
untilFalse :: Monad m => m Bool -> m Bool
untilFalse p = do
b <- p
if b
then untilFalse p >> return True
else return False
-- | Collects and returns all applicable state-based actions (without executing them).
collectSBAs :: Engine [OneShotEffect]
collectSBAs = view $ execWriterT $ do
checkPlayers
checkBattlefield
-- TODO [704.5d]
-- TODO [704.5e]
TODO [ 704.5u ]
-- TODO [704.5v]
TODO [ 704.5w ]
where
checkPlayers = do
-- [704.5a]
-- [704.5b]
-- TODO [704.5c]
TODO [ 704.5 t ]
ips <- IdList.toList <$> lift (asks players)
forM_ ips $ \(i,p) -> do
when (get life p <= 0 || get failedCardDraw p) $
tell [Will (LoseGame i)]
checkBattlefield = do
ios <- IdList.toList <$> lift (asks battlefield)
forM_ ios $ \(i, Permanent o _ dam deatht _ _) -> do
-- Check creatures
when (hasTypes creatureType o) $ do
-- [704.5f]
let hasNonPositiveToughness = maybe False (<= 0) (fmap snd (get pt o))
when hasNonPositiveToughness $ tell [willMoveToGraveyard (Battlefield, i) o]
[ 704.5 g ]
[ 704.5h ]
let hasLethalDamage =
case get pt o of
Just (_, t) -> t > 0 && dam >= t
_ -> False
when (hasLethalDamage || deatht) $
tell [Will (DestroyPermanent (Battlefield, i) True)]
[ 704.5i ]
when (hasTypes planeswalkerType o && countCountersOfType Loyalty o == 0) $
tell [willMoveToGraveyard (Battlefield, i) o]
TODO [ 704.5j ]
-- TODO [704.5k]
TODO [ 704.5 m ]
-- TODO [704.5n]
TODO [ 704.5p ]
-- TODO [704.5q]
-- TODO [704.5r]
TODO [ 704.5s ]
resolve :: ObjectRef TyStackItem -> Engine ()
resolve r@(Stack, i) = do
stackItem <- gets (object r)
case stackItem of
StackItem o item -> do
let (_, Just mkEffects) = evaluateTargetList item
let eventSource = ResolutionOf r
executeMagic eventSource (mkEffects r (get controller o))
-- if the object is now still on the stack, move it to the appropriate zone
if (hasTypes instantType o || hasTypes sorceryType o)
then void $ executeEffect eventSource $
WillMoveObject (Just (Some Stack, i)) (Graveyard (get controller o)) (CardObject o)
else if hasPermanentType o
then void $ executeEffect eventSource $
WillMoveObject (Just (Some Stack, i)) Battlefield (Permanent o Untapped 0 False Nothing Nothing)
else void $ executeEffect eventSource $ Will $ CeaseToExist (Some Stack, i)
collectPriorityActions :: PlayerRef -> Engine [PriorityAction]
collectPriorityActions p = do
as <- map ActivateAbility <$> collectAvailableActivatedAbilities (const True) p
plays <- map PlayCard <$> collectPlayableCards p
return (as <> plays)
collectAvailableActivatedAbilities :: (ActivatedAbility -> Bool) -> PlayerRef -> Engine [ActivatedAbilityRef]
collectAvailableActivatedAbilities predicate p = do
objects <- view allObjects
execWriterT $ do
for objects $ \(r,o) -> do
for (zip [0..] (get activatedAbilities o)) $ \(i, ability) -> do
ok <- lift (shouldOfferActivation (abilityActivation ability) r p)
payCostsOk <- lift (canPayTapCost (tapCost ability) r p)
when (predicate ability && ok && payCostsOk) (tell [(r, i)])
collectPlayableCards :: PlayerRef -> Engine [ObjectRef TyCard]
collectPlayableCards p = do
objects <- view allCards
execWriterT $ do
forM_ objects $ \(r,o) -> do
case get play o of
Just playAbility -> do
ok <- lift (shouldOfferActivation playAbility (someObjectRef r) p)
when ok (tell [r])
Nothing -> return ()
shouldOfferActivation :: Activation -> Contextual (Engine Bool)
shouldOfferActivation activation rSource you =
view ((timing &&* available) activation rSource you)
activate :: EventSource -> Activation -> Contextual (Engine ())
activate source activation rSource rActivator = do
--case manaCost activation of
Just mc - > offerManaAbilitiesToPay source
-- Nothing -> return ()
executeMagic source (effect activation rSource rActivator)
executePriorityAction :: PlayerRef -> PriorityAction -> Engine ()
executePriorityAction p a = do
case a of
PlayCard r -> do
maybeAbility <- gets (play . objectPart . object r)
case maybeAbility of
Just ability ->
activate (PriorityActionExecution a) ability (someObjectRef r) p
ActivateAbility (r, i) -> do
abilities <- gets (activatedAbilities . objectBase r)
let ab = abilities !! i
let eventSource = PriorityActionExecution a
payTapCost eventSource (tapCost ab) r p
activate eventSource (abilityActivation ab) r p
offerManaAbilitiesToPay :: EventSource -> PlayerRef -> ManaCost -> Engine ()
offerManaAbilitiesToPay _ _ cost | MultiSet.null cost = return ()
offerManaAbilitiesToPay source p cost = do
amas <- map ActivateManaAbility <$>
collectAvailableActivatedAbilities ((== ManaAb) . abilityType) p
pool <- gets (manaPool . player p)
let pms =
if MultiSet.member GenericCost cost
then
There is at least 1 generic mana to pay .
-- Offer all colors in the mana pool to spend.
map PayManaFromManaPool (MultiSet.distinctElems pool)
else
-- Cost has no generic component.
-- Only offer colors in the mana pool that occur in the cost.
[ PayManaFromManaPool manaEl
| ManaElCost manaEl <- MultiSet.distinctElems cost
, manaEl `MultiSet.member` pool
]
action <- askQuestion p (AskManaAbility cost (amas <> pms))
case action of
PayManaFromManaPool manaEl -> do
_ <- executeEffect source $
Will (SpendFromManaPool p (MultiSet.singleton manaEl))
let restCost =
-- Pay a colored cost element if possible;
-- otherwise pay a generic element.
if ManaElCost manaEl `elem` cost
then MultiSet.delete (ManaElCost manaEl) cost
else MultiSet.delete GenericCost cost
offerManaAbilitiesToPay source p restCost
ActivateManaAbility (r, i) -> do
abilities <- gets (activatedAbilities . objectBase r)
activate source (abilityActivation (abilities !! i)) r p
offerManaAbilitiesToPay source p cost
canPayTapCost :: TapCost -> Contextual (Engine Bool)
canPayTapCost NoTapCost _ _ = return True
canPayTapCost TapCost (Some Battlefield, i) _ =
(== Untapped) <$> gets (tapStatus . object (Battlefield, i))
canPayTapCost TapCost _ _ = return False
payTapCost :: EventSource -> TapCost -> Contextual (Engine ())
payTapCost _ NoTapCost _ _ = return ()
payTapCost source TapCost (Some Battlefield, i) _ =
void (executeEffect source (Will (TapPermanent (Battlefield, i))))
payTapCost _ _ _ _ = return ()
-- | Returns player IDs in APNAP order (active player, non-active player).
apnap :: Engine [(PlayerRef, Player)]
apnap = gets activePlayer >>= playersStartingWith
playersStartingWith :: PlayerRef -> Engine [(PlayerRef, Player)]
playersStartingWith p = do
(ps, qs) <- break ((== p) . fst) . IdList.toList <$> gets players
return (qs ++ ps)
| null |
https://raw.githubusercontent.com/MedeaMelana/Magic/7bd87e4e1d54a7c5e5f81661196cafb87682c62a/Magic/src/Magic/Engine.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
# LANGUAGE DoAndIfThenElse #
# LANGUAGE GADTs #
| Moves to the next step. Returns the new step, and whether a new turn has begun.
Execution of steps
[508.1b] declare which player or planeswalker each attacker attacks
TODO Offer attacking planeswalkers
TODO Check summoning sickness
TODO [508.1c] check attacking restrictions
TODO [508.1d] check attacking requirements
[508.1f] tap attackers
TODO [508.1h] allow mana abilities
TODO [509.1c] check blocking requirements
| Repeatedly checks and execute state-based effects and asks players to put triggered abilities
whether any abilities have been put on the stack.
| Repeatedly checks and executes state-based effects until no more actions need to be taken.
Returns whether any actions were taken at all.
Returns whether anything was put on the stack as a result.
| Collects and returns all applicable state-based actions (without executing them).
TODO [704.5d]
TODO [704.5e]
TODO [704.5v]
[704.5a]
[704.5b]
TODO [704.5c]
Check creatures
[704.5f]
TODO [704.5k]
TODO [704.5n]
TODO [704.5q]
TODO [704.5r]
if the object is now still on the stack, move it to the appropriate zone
case manaCost activation of
Nothing -> return ()
Offer all colors in the mana pool to spend.
Cost has no generic component.
Only offer colors in the mana pool that occur in the cost.
Pay a colored cost element if possible;
otherwise pay a generic element.
| Returns player IDs in APNAP order (active player, non-active player).
|
# LANGUAGE TypeOperators #
# LANGUAGE TupleSections #
# LANGUAGE DataKinds #
module Magic.Engine (newWorld, fullGame, Engine(..)) where
import Magic.Core
import Magic.Events hiding (executeEffect, executeEffects)
import qualified Magic.IdList as IdList
import Magic.Labels
import Magic.ObjectTypes
import Magic.Predicates
import Magic.Target
import Magic.Types
import Magic.Utils
import Magic.Engine.Types
import Magic.Engine.Events
import Magic.Some
import Control.Applicative ((<$>), (<*>))
import Control.Category ((.))
import Control.Monad (forever, forM_, when, void, liftM, unless)
import Control.Monad.Trans (lift)
import Control.Monad.Writer (tell, execWriterT)
import Data.Boolean ((&&*))
import Data.Label (get, set, modify)
import Data.Label.Monadic (gets, (=:), (=.), asks)
import Data.List (nub, intersect, delete)
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import qualified Data.MultiSet as MultiSet
import qualified Data.Text as Text
import Data.Text (Text)
import Data.Traversable (for)
import Prelude hiding (round, (.))
newWorld :: [Deck] -> World
newWorld decks = World
{ _players = ps
, _activePlayer = head playerIds
, _activeStep = BeginningPhase UntapStep
, _time = 0
, _turnStructure = ts
, _exile = IdList.empty
, _battlefield = IdList.empty
, _stack = IdList.empty
, _command = IdList.empty
, _turnHistory = []
}
where
ps = IdList.fromListWithId (\i deck -> newPlayer i deck) decks
playerIds = IdList.ids ps
ts = case playerIds of
103.7a . In a two - player game , the player who plays first skips the draw step of his or her first turn .
[p1, p2] -> (p1, removeFirst (== BeginningPhase DrawStep) turnSteps)
: cycle [(p2, turnSteps), (p1, turnSteps)]
_ -> cycle (map (, turnSteps) playerIds)
removeFirst :: (a -> Bool) -> [a] -> [a]
removeFirst notOk xs =
case break notOk xs of
(as, _ : bs) -> as ++ bs
_ -> xs
turnSteps :: [Step]
turnSteps =
[ BeginningPhase UntapStep
, BeginningPhase UpkeepStep
, BeginningPhase DrawStep
, MainPhase
, CombatPhase BeginningOfCombatStep
, CombatPhase DeclareAttackersStep
, CombatPhase DeclareBlockersStep
, CombatPhase CombatDamageStep
, CombatPhase EndOfCombatStep
, MainPhase
, EndPhase EndOfTurnStep
, EndPhase CleanupStep
]
newPlayer :: PlayerRef -> Deck -> Player
newPlayer i deck = Player
{ _life = 20
, _manaPool = mempty
, _prestack = []
, _library = IdList.fromList [ CardObject (instantiateCard card i)
| card <- deck ]
, _hand = IdList.empty
, _graveyard = IdList.empty
, _maximumHandSize = Just 7
, _failedCardDraw = False
}
drawOpeningHands :: [PlayerRef] -> Int -> Engine ()
drawOpeningHands [] _ =
return ()
drawOpeningHands playerIds 0 =
void $ executeEffects TurnBasedActions (map (Will . ShuffleLibrary) playerIds)
drawOpeningHands playerIds handSize = do
mulliganingPlayers <- do
forM_ playerIds $ \playerId -> do
_ <- undrawHand TurnBasedActions playerId
_ <- executeEffect TurnBasedActions (Will (ShuffleLibrary playerId))
executeEffects TurnBasedActions (replicate handSize (Will (DrawCard playerId)))
for playerIds $ \playerId -> do
keepHand <- askQuestion playerId AskKeepHand
if keepHand
then return Nothing
else return (Just playerId)
drawOpeningHands (catMaybes mulliganingPlayers) (handSize - 1)
undrawHand :: EventSource -> PlayerRef -> Engine [Event]
undrawHand source p = do
idxs <- IdList.toList <$> gets (hand . player p)
executeEffects source [ WillMoveObject (Just (Some (Hand p), i)) (Library p) x | (i, x) <- idxs ]
fullGame :: Engine ()
fullGame = do
ps <- IdList.ids <$> gets players
drawOpeningHands ps 7
forever $ do
players =.* set manaPool mempty
(step, newTurn) <- nextStep
when newTurn (turnHistory =: [])
raise TurnBasedActions [DidBeginStep step]
executeStep step
raise TurnBasedActions [WillEndStep step]
nextStep :: Engine (Step, Bool)
nextStep = do
structure <- gets turnStructure
case structure of
(rp, s : ss) : ts -> do
turnStructure =: if null ss then ts else (rp, ss) : ts
activePlayer =: rp
activeStep =: s
return (s, null ss)
executeStep :: Step -> Engine ()
executeStep (BeginningPhase UntapStep) = do
TODO [ 502.1 ] phasing
[ 502.2 ] untap permanents
rp <- gets activePlayer
ios <- (IdList.filter (\perm@Permanent {} -> isControlledBy rp (get objectPart perm))) <$> gets battlefield
_ <- executeEffects TurnBasedActions (map (\(i, _) -> Will (UntapPermanent (Battlefield, i))) ios)
return ()
executeStep (BeginningPhase UpkeepStep) = do
TODO [ 503.1 ] handle triggers
[ 503.2 ]
offerPriority
executeStep (BeginningPhase DrawStep) = do
[ 504.1 ]
ap <- gets activePlayer
_ <- executeEffect TurnBasedActions (Will (DrawCard ap))
TODO [ 504.2 ] handle triggers
[ 504.3 ]
offerPriority
executeStep MainPhase = do
TODO [ 505.4 ] handle triggers
[ 505.5 ]
offerPriority
executeStep (CombatPhase BeginningOfCombatStep) = do
offerPriority
executeStep (CombatPhase DeclareAttackersStep) = do
[ 508.1a ] declare attackers
ap <- gets activePlayer
let canAttack perm =
(isControlledBy ap &&* hasTypes creatureType) (get objectPart perm)
&& get tapStatus perm == Untapped
possibleAttackerRefs <- map (\(i,_) -> (Battlefield, i)) . filter (canAttack . snd) . IdList.toList <$> view (asks battlefield)
attackablePlayerRefs <- (filter (/= ap) . IdList.ids) <$> gets players
attacks <- askQuestion ap (AskAttackers possibleAttackerRefs (map PlayerRef attackablePlayerRefs))
TODO [ 508.1e ] declare banding
forM_ attacks $ \(Attack rAttacker _rAttackee) -> do
keywords <- view (asks (staticKeywordAbilities . objectPart . object rAttacker))
unless (elem Vigilance keywords) $
tapStatus . object rAttacker =: Tapped
TODO [ 508.1 g ] determine costs
TODO [ 508.1i ] pay costs
[ 508.1j ] mark creatures as attacking
forM_ attacks $ \(Attack rAttacker rAttackee) ->
attacking . object rAttacker =: Just rAttackee
[ 508.2 ] handle triggers
raise TurnBasedActions [DidDeclareAttackers ap attacks]
offerPriority
TODO [ 508.6 ] potentially skip declare blockers and combat damage steps
return ()
executeStep (CombatPhase DeclareBlockersStep) = do
TODO [ 509.1a ] declare blockers
TODO [ 509.1b ] check blocking restrictions
TODO [ 509.1d ] determine costs
TODO [ 509.1e ] allow mana abilities
TODO [ 509.1f ] pay costs
TODO [ 509.1 g ] mark creatures as blocking
TODO [ 509.1h ] mark creatures as blocked
TODO [ 509.2 ] declare attackers ' damage assignment order
TODO [ 509.3 ] declare blockers ' damage assignment order
TODO [ 509.4 ] handle triggers
offerPriority
TODO [ 509.6 ] determine new attackers ' damage assignment order
TODO [ 509.7 ] determine new blockers ' damage assignment order
return ()
executeStep (CombatPhase CombatDamageStep) = do
TODO [ 510.1 ] assign combat damage
TODO [ 510.2 ] deal damage
TODO [ 510.3 ] handle triggers
effectses <- view $ do
permanents <- IdList.toList <$> asks battlefield
for permanents $ \(r, permanent) -> do
let attackingObject = _permanentObject permanent
let Just (power, _) = _pt attackingObject
case _attacking permanent of
Nothing -> return []
Just (PlayerRef p) -> return [Will (DamagePlayer attackingObject p power True True)]
Just (ObjectRef (Some Battlefield, i)) -> return [Will (DamageObject attackingObject (Battlefield, i) power True True)]
_ <- executeEffects TurnBasedActions (concat effectses)
offerPriority
TODO [ 510.5 ] possibly introduce extra combat damage step for first / double strike
return ()
executeStep (CombatPhase EndOfCombatStep) = do
TODO [ 511.1 ] handle triggers
[ 511.2 ]
offerPriority
[ 511.3 ] remove creatures from combat
battlefield =.* set attacking Nothing
executeStep (EndPhase EndOfTurnStep) = do
TODO [ 513.1 ] handle triggers
[ 513.2 ]
offerPriority
executeStep (EndPhase CleanupStep) = do
TODO [ 514.1 ] discard excess cards
[ 514.2 ] remove damage from permanents
battlefield =.* set damage 0
[ 514.2 ] Remove effects that last until end of turn
battlefield =.* modify (temporaryEffects . objectPart)
(filter (\tle -> temporaryDuration tle /= UntilEndOfTurn))
shouldOfferPriority <- executeSBAsAndProcessPrestacks
when shouldOfferPriority offerPriority
offerPriority :: Engine ()
offerPriority = gets activePlayer >>= fullRoundStartingWith
where
fullRoundStartingWith p = do
_ <- executeSBAsAndProcessPrestacks
mAction <- playersStartingWith p >>= partialRound
case mAction of
Just (initiatingPlayer, action) -> do
executePriorityAction initiatingPlayer action
fullRoundStartingWith initiatingPlayer
Nothing -> do
st <- gets stack
case IdList.head st of
Nothing -> return ()
Just (i, _) -> do
resolve (Stack, i)
offerPriority
partialRound ((p, _):ps) = do
actions <- collectPriorityActions p
mAction <- askQuestion p (AskPriorityAction actions)
case mAction of
Just action -> return (Just (p, action))
Nothing -> partialRound ps
partialRound [] = return Nothing
on the stack , until everything has been processed . Returns whether any SBAs have been taken or
executeSBAsAndProcessPrestacks :: Engine Bool
executeSBAsAndProcessPrestacks = untilFalse ((||) <$> checkSBAs <*> processPrestacks)
checkSBAs :: Engine Bool
checkSBAs = untilFalse $ (not . null) <$> checkSBAsOnce
where
checkSBAsOnce = collectSBAs >>= executeEffects StateBasedActions
| Ask players to put pending items on the stack in APNAP order . [ 405.3 ]
processPrestacks :: Engine Bool
processPrestacks = do
ips <- apnap
liftM or $ for ips $ \(i,p) -> do
let pending = get prestack p
when (not (null pending)) $ do
index <- askQuestion i (AskPickTrigger (map fst pending))
let (lki, program) = pending !! index
executeMagic (StackTrigger lki) program
prestack . player i =. deleteAtIndex index
return (not (null pending))
untilFalse :: Monad m => m Bool -> m Bool
untilFalse p = do
b <- p
if b
then untilFalse p >> return True
else return False
collectSBAs :: Engine [OneShotEffect]
collectSBAs = view $ execWriterT $ do
checkPlayers
checkBattlefield
TODO [ 704.5u ]
TODO [ 704.5w ]
where
checkPlayers = do
TODO [ 704.5 t ]
ips <- IdList.toList <$> lift (asks players)
forM_ ips $ \(i,p) -> do
when (get life p <= 0 || get failedCardDraw p) $
tell [Will (LoseGame i)]
checkBattlefield = do
ios <- IdList.toList <$> lift (asks battlefield)
forM_ ios $ \(i, Permanent o _ dam deatht _ _) -> do
when (hasTypes creatureType o) $ do
let hasNonPositiveToughness = maybe False (<= 0) (fmap snd (get pt o))
when hasNonPositiveToughness $ tell [willMoveToGraveyard (Battlefield, i) o]
[ 704.5 g ]
[ 704.5h ]
let hasLethalDamage =
case get pt o of
Just (_, t) -> t > 0 && dam >= t
_ -> False
when (hasLethalDamage || deatht) $
tell [Will (DestroyPermanent (Battlefield, i) True)]
[ 704.5i ]
when (hasTypes planeswalkerType o && countCountersOfType Loyalty o == 0) $
tell [willMoveToGraveyard (Battlefield, i) o]
TODO [ 704.5j ]
TODO [ 704.5 m ]
TODO [ 704.5p ]
TODO [ 704.5s ]
resolve :: ObjectRef TyStackItem -> Engine ()
resolve r@(Stack, i) = do
stackItem <- gets (object r)
case stackItem of
StackItem o item -> do
let (_, Just mkEffects) = evaluateTargetList item
let eventSource = ResolutionOf r
executeMagic eventSource (mkEffects r (get controller o))
if (hasTypes instantType o || hasTypes sorceryType o)
then void $ executeEffect eventSource $
WillMoveObject (Just (Some Stack, i)) (Graveyard (get controller o)) (CardObject o)
else if hasPermanentType o
then void $ executeEffect eventSource $
WillMoveObject (Just (Some Stack, i)) Battlefield (Permanent o Untapped 0 False Nothing Nothing)
else void $ executeEffect eventSource $ Will $ CeaseToExist (Some Stack, i)
collectPriorityActions :: PlayerRef -> Engine [PriorityAction]
collectPriorityActions p = do
as <- map ActivateAbility <$> collectAvailableActivatedAbilities (const True) p
plays <- map PlayCard <$> collectPlayableCards p
return (as <> plays)
collectAvailableActivatedAbilities :: (ActivatedAbility -> Bool) -> PlayerRef -> Engine [ActivatedAbilityRef]
collectAvailableActivatedAbilities predicate p = do
objects <- view allObjects
execWriterT $ do
for objects $ \(r,o) -> do
for (zip [0..] (get activatedAbilities o)) $ \(i, ability) -> do
ok <- lift (shouldOfferActivation (abilityActivation ability) r p)
payCostsOk <- lift (canPayTapCost (tapCost ability) r p)
when (predicate ability && ok && payCostsOk) (tell [(r, i)])
collectPlayableCards :: PlayerRef -> Engine [ObjectRef TyCard]
collectPlayableCards p = do
objects <- view allCards
execWriterT $ do
forM_ objects $ \(r,o) -> do
case get play o of
Just playAbility -> do
ok <- lift (shouldOfferActivation playAbility (someObjectRef r) p)
when ok (tell [r])
Nothing -> return ()
shouldOfferActivation :: Activation -> Contextual (Engine Bool)
shouldOfferActivation activation rSource you =
view ((timing &&* available) activation rSource you)
activate :: EventSource -> Activation -> Contextual (Engine ())
activate source activation rSource rActivator = do
Just mc - > offerManaAbilitiesToPay source
executeMagic source (effect activation rSource rActivator)
executePriorityAction :: PlayerRef -> PriorityAction -> Engine ()
executePriorityAction p a = do
case a of
PlayCard r -> do
maybeAbility <- gets (play . objectPart . object r)
case maybeAbility of
Just ability ->
activate (PriorityActionExecution a) ability (someObjectRef r) p
ActivateAbility (r, i) -> do
abilities <- gets (activatedAbilities . objectBase r)
let ab = abilities !! i
let eventSource = PriorityActionExecution a
payTapCost eventSource (tapCost ab) r p
activate eventSource (abilityActivation ab) r p
offerManaAbilitiesToPay :: EventSource -> PlayerRef -> ManaCost -> Engine ()
offerManaAbilitiesToPay _ _ cost | MultiSet.null cost = return ()
offerManaAbilitiesToPay source p cost = do
amas <- map ActivateManaAbility <$>
collectAvailableActivatedAbilities ((== ManaAb) . abilityType) p
pool <- gets (manaPool . player p)
let pms =
if MultiSet.member GenericCost cost
then
There is at least 1 generic mana to pay .
map PayManaFromManaPool (MultiSet.distinctElems pool)
else
[ PayManaFromManaPool manaEl
| ManaElCost manaEl <- MultiSet.distinctElems cost
, manaEl `MultiSet.member` pool
]
action <- askQuestion p (AskManaAbility cost (amas <> pms))
case action of
PayManaFromManaPool manaEl -> do
_ <- executeEffect source $
Will (SpendFromManaPool p (MultiSet.singleton manaEl))
let restCost =
if ManaElCost manaEl `elem` cost
then MultiSet.delete (ManaElCost manaEl) cost
else MultiSet.delete GenericCost cost
offerManaAbilitiesToPay source p restCost
ActivateManaAbility (r, i) -> do
abilities <- gets (activatedAbilities . objectBase r)
activate source (abilityActivation (abilities !! i)) r p
offerManaAbilitiesToPay source p cost
canPayTapCost :: TapCost -> Contextual (Engine Bool)
canPayTapCost NoTapCost _ _ = return True
canPayTapCost TapCost (Some Battlefield, i) _ =
(== Untapped) <$> gets (tapStatus . object (Battlefield, i))
canPayTapCost TapCost _ _ = return False
payTapCost :: EventSource -> TapCost -> Contextual (Engine ())
payTapCost _ NoTapCost _ _ = return ()
payTapCost source TapCost (Some Battlefield, i) _ =
void (executeEffect source (Will (TapPermanent (Battlefield, i))))
payTapCost _ _ _ _ = return ()
apnap :: Engine [(PlayerRef, Player)]
apnap = gets activePlayer >>= playersStartingWith
playersStartingWith :: PlayerRef -> Engine [(PlayerRef, Player)]
playersStartingWith p = do
(ps, qs) <- break ((== p) . fst) . IdList.toList <$> gets players
return (qs ++ ps)
|
a16d00e3c7eae41b408bf21601c2278f69874ac44a7fe055071000ae9a92ca85
|
xapi-project/xcp-rrd
|
rrd_unix.ml
|
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
* RRD Unix module
* This module provides Unix tools for dealing with RRDs
* RRD Unix module
* This module provides Unix tools for dealing with RRDs
*)
(**
* @group Performance Monitoring
*)
let finally = Xapi_stdext_pervasives.Pervasiveext.finally
let with_out_channel_output fd f =
let oc = Unix.out_channel_of_descr fd in
finally
(fun () ->
let output = Xmlm.make_output (`Channel oc) in
f output
)
(fun () -> flush oc)
let xml_to_fd rrd fd = with_out_channel_output fd (Rrd.xml_to_output rrd)
let json_to_fd rrd fd =
let payload = Rrd.json_to_string rrd |> Bytes.unsafe_of_string in
let len = Bytes.length payload in
Unix.write fd payload 0 len |> ignore
let to_fd ?(json = false) rrd fd =
(if json then json_to_fd else xml_to_fd) rrd fd
| null |
https://raw.githubusercontent.com/xapi-project/xcp-rrd/496ed07c4989be7a86087c4778350b53a937b8a1/unix/rrd_unix.ml
|
ocaml
|
*
* @group Performance Monitoring
|
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
* RRD Unix module
* This module provides Unix tools for dealing with RRDs
* RRD Unix module
* This module provides Unix tools for dealing with RRDs
*)
let finally = Xapi_stdext_pervasives.Pervasiveext.finally
let with_out_channel_output fd f =
let oc = Unix.out_channel_of_descr fd in
finally
(fun () ->
let output = Xmlm.make_output (`Channel oc) in
f output
)
(fun () -> flush oc)
let xml_to_fd rrd fd = with_out_channel_output fd (Rrd.xml_to_output rrd)
let json_to_fd rrd fd =
let payload = Rrd.json_to_string rrd |> Bytes.unsafe_of_string in
let len = Bytes.length payload in
Unix.write fd payload 0 len |> ignore
let to_fd ?(json = false) rrd fd =
(if json then json_to_fd else xml_to_fd) rrd fd
|
95dad40138c0562d13436873470e147f6b242c6890e04bf42a0f3948d77a7333
|
serokell/qtah
|
Internal.hs
|
This file is part of Qtah .
--
Copyright 2015 - 2018 The Qtah Authors .
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
--
You should have received a copy of the GNU Lesser General Public License
-- along with this program. If not, see </>.
module Graphics.UI.Qtah.Generator.Interface.Internal (modules) where
import qualified Graphics.UI.Qtah.Generator.Interface.Internal.Callback as Callback
import qualified Graphics.UI.Qtah.Generator.Interface.Internal.EventListener as EventListener
import qualified Graphics.UI.Qtah.Generator.Interface.Internal.Listener as Listener
import qualified Graphics.UI.Qtah.Generator.Interface.Internal.SceneEventListener as SceneEventListener
import Graphics.UI.Qtah.Generator.Module (AModule)
{-# ANN module "HLint: ignore Use camelCase" #-}
modules :: [AModule]
modules =
[ Callback.aModule
, EventListener.aModule
, Listener.aModule
, SceneEventListener.aModule
]
| null |
https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Internal.hs
|
haskell
|
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
(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
along with this program. If not, see </>.
# ANN module "HLint: ignore Use camelCase" #
|
This file is part of Qtah .
Copyright 2015 - 2018 The Qtah Authors .
the Free Software Foundation , either version 3 of the License , or
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
module Graphics.UI.Qtah.Generator.Interface.Internal (modules) where
import qualified Graphics.UI.Qtah.Generator.Interface.Internal.Callback as Callback
import qualified Graphics.UI.Qtah.Generator.Interface.Internal.EventListener as EventListener
import qualified Graphics.UI.Qtah.Generator.Interface.Internal.Listener as Listener
import qualified Graphics.UI.Qtah.Generator.Interface.Internal.SceneEventListener as SceneEventListener
import Graphics.UI.Qtah.Generator.Module (AModule)
modules :: [AModule]
modules =
[ Callback.aModule
, EventListener.aModule
, Listener.aModule
, SceneEventListener.aModule
]
|
1c9a8d1e2bff82473a61773fb72bd7493590cb99adbb658494cca54ea91de7a6
|
shirok/Gauche
|
96.scm
|
;;;
SRFI-96 is not really meant to be ' use'-ed ; it basically defines
;;; required adaptor to support slib. We have it in slib.scm.
;;;
(define-module srfi.96 (extend slib))
| null |
https://raw.githubusercontent.com/shirok/Gauche/e606bfe5a94b100d5807bca9c2bb95df94f60aa6/lib/srfi/96.scm
|
scheme
|
it basically defines
required adaptor to support slib. We have it in slib.scm.
|
(define-module srfi.96 (extend slib))
|
abe7635863fea499dce5cfe2ce2133b96f7859335ef5834f2be4606a923b5be6
|
ocaml-ppx/ocamlformat
|
parsetree.mli
|
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Abstract syntax tree produced by parsing
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
*)
open Asttypes
type constant =
| Pconst_integer of string * char option
* Integer constants such as [ 3 ] [ 3l ] [ 3L ] [ 3n ] .
Suffixes [ [ g - z][G - Z ] ] are accepted by the parser .
Suffixes except [ ' l ' ] , [ ' L ' ] and [ ' n ' ] are rejected by the typechecker
Suffixes [[g-z][G-Z]] are accepted by the parser.
Suffixes except ['l'], ['L'] and ['n'] are rejected by the typechecker
*)
| Pconst_char of char (** Character such as ['c']. *)
| Pconst_string of string * Location.t * string option
* Constant string such as [ " constant " ] or
[ { } ] .
The location span the content of the string , without the delimiters .
[{delim|other constant|delim}].
The location span the content of the string, without the delimiters.
*)
| Pconst_float of string * char option
* Float constant such as [ 3.4 ] , [ 2e5 ] or [ 1.4e-4 ] .
Suffixes [ g - z][G - Z ] are accepted by the parser .
Suffixes are rejected by the typechecker .
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes are rejected by the typechecker.
*)
type location_stack = Location.t list
* { 1 Extension points }
type attribute = {
attr_name : string loc;
attr_payload : payload;
attr_loc : Location.t;
}
(** Attributes such as [[\@id ARG]] and [[\@\@id ARG]].
Metadata containers passed around within the AST.
The compiler ignores unknown attributes.
*)
and extension = string loc * payload
(** Extension points such as [[%id ARG] and [%%id ARG]].
Sub-language placeholder -- rejected by the typechecker.
*)
and attributes = attribute list
and payload =
| PStr of structure
* [: SIG ] in an attribute or an extension point
| PTyp of core_type (** [: T] in an attribute or an extension point *)
| PPat of pattern * expression option
(** [? P] or [? P when E], in an attribute or an extension point *)
* { 1 Core language }
* { 2 Type expressions }
and core_type =
{
ptyp_desc: core_type_desc;
ptyp_loc: Location.t;
ptyp_loc_stack: location_stack;
ptyp_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and core_type_desc =
| Ptyp_any (** [_] *)
| Ptyp_var of string (** A type variable such as ['a] *)
| Ptyp_arrow of arg_label * core_type * core_type
(** [Ptyp_arrow(lbl, T1, T2)] represents:
- [T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Nolabel}[Nolabel]},
- [~l:T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Labelled}[Labelled]},
- [?l:T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Optional}[Optional]}.
*)
| Ptyp_tuple of core_type list
* [ Ptyp_tuple([T1 ; ... ; Tn ] ) ]
represents a product type [ T1 * ... * Tn ] .
Invariant : [ n > = 2 ] .
represents a product type [T1 * ... * Tn].
Invariant: [n >= 2].
*)
| Ptyp_constr of Longident.t loc * core_type list
(** [Ptyp_constr(lident, l)] represents:
- [tconstr] when [l=[]],
- [T tconstr] when [l=[T]],
- [(T1, ..., Tn) tconstr] when [l=[T1 ; ... ; Tn]].
*)
| Ptyp_object of object_field list * closed_flag
(** [Ptyp_object([ l1:T1; ...; ln:Tn ], flag)] represents:
- [< l1:T1; ...; ln:Tn >] when [flag] is
{{!Asttypes.closed_flag.Closed}[Closed]},
- [< l1:T1; ...; ln:Tn; .. >] when [flag] is
{{!Asttypes.closed_flag.Open}[Open]}.
*)
| Ptyp_class of Longident.t loc * core_type list
(** [Ptyp_class(tconstr, l)] represents:
- [#tconstr] when [l=[]],
- [T #tconstr] when [l=[T]],
- [(T1, ..., Tn) #tconstr] when [l=[T1 ; ... ; Tn]].
*)
| Ptyp_alias of core_type * string (** [T as 'a]. *)
| Ptyp_variant of row_field list * closed_flag * label list option
(** [Ptyp_variant([`A;`B], flag, labels)] represents:
- [[ `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [None],
- [[> `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Open}[Open]},
and [labels] is [None],
- [[< `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [Some []],
- [[< `A|`B > `X `Y ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [Some ["X";"Y"]].
*)
| Ptyp_poly of string loc list * core_type
* [ ' a1 ... ' an . T ]
Can only appear in the following context :
- As the { ! core_type } of a
{ { ! pattern_desc . Ppat_constraint}[Ppat_constraint ] } node corresponding
to a constraint on a let - binding :
{ [ let x : ' a1 ... ' an . T = e ... ] }
- Under { { ! class_field_kind . Cfk_virtual}[Cfk_virtual ] } for methods
( not values ) .
- As the { ! core_type } of a
{ { ! class_type_field_desc . ] } node .
- As the { ! core_type } of a { { ! expression_desc . Pexp_poly}[Pexp_poly ] }
node .
- As the { { ! label_declaration.pld_type}[pld_type ] } field of a
{ ! label_declaration } .
- As a { ! core_type } of a { { ! core_type_desc . Ptyp_object}[Ptyp_object ] }
node .
- As the { { ! value_description.pval_type}[pval_type ] } field of a
{ ! value_description } .
Can only appear in the following context:
- As the {!core_type} of a
{{!pattern_desc.Ppat_constraint}[Ppat_constraint]} node corresponding
to a constraint on a let-binding:
{[let x : 'a1 ... 'an. T = e ...]}
- Under {{!class_field_kind.Cfk_virtual}[Cfk_virtual]} for methods
(not values).
- As the {!core_type} of a
{{!class_type_field_desc.Pctf_method}[Pctf_method]} node.
- As the {!core_type} of a {{!expression_desc.Pexp_poly}[Pexp_poly]}
node.
- As the {{!label_declaration.pld_type}[pld_type]} field of a
{!label_declaration}.
- As a {!core_type} of a {{!core_type_desc.Ptyp_object}[Ptyp_object]}
node.
- As the {{!value_description.pval_type}[pval_type]} field of a
{!value_description}.
*)
| Ptyp_package of package_type (** [(module S)]. *)
| Ptyp_extension of extension (** [[%id]]. *)
and package_type = Longident.t loc * (Longident.t loc * core_type) list
* As { ! package_type } typed values :
- [ ( S , [ ] ) ] represents [ ( module S ) ] ,
- [ ( S , [ ( t1 , T1 ) ; ... ; ( tn , Tn ) ] ) ]
represents [ ( module S with type t1 = T1 and ... and tn = Tn ) ] .
- [(S, [])] represents [(module S)],
- [(S, [(t1, T1) ; ... ; (tn, Tn)])]
represents [(module S with type t1 = T1 and ... and tn = Tn)].
*)
and row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
and row_field_desc =
| Rtag of label loc * bool * core_type list
* [ , b , l ) ] represents :
- [ ` A ] when [ b ] is [ true ] and [ l ] is [ [ ] ] ,
- [ ` A of T ] when [ b ] is [ false ] and [ l ] is [ [ T ] ] ,
- [ ` A of T1 & .. & Tn ] when [ b ] is [ false ] and [ l ] is [ [ T1; ... Tn ] ] ,
- [ ` A of & T1 & .. & Tn ] when [ b ] is [ true ] and [ l ] is [ [ T1; ... Tn ] ] .
- The [ bool ] field is true if the tag contains a
constant ( empty ) constructor .
- [ & ] occurs when several types are used for the same constructor
( see 4.2 in the manual )
- [`A] when [b] is [true] and [l] is [[]],
- [`A of T] when [b] is [false] and [l] is [[T]],
- [`A of T1 & .. & Tn] when [b] is [false] and [l] is [[T1;...Tn]],
- [`A of & T1 & .. & Tn] when [b] is [true] and [l] is [[T1;...Tn]].
- The [bool] field is true if the tag contains a
constant (empty) constructor.
- [&] occurs when several types are used for the same constructor
(see 4.2 in the manual)
*)
| Rinherit of core_type (** [[ | t ]] *)
and object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
and object_field_desc =
| Otag of label loc * core_type
| Oinherit of core_type
(** {2 Patterns} *)
and pattern =
{
ppat_desc: pattern_desc;
ppat_loc: Location.t;
ppat_loc_stack: location_stack;
ppat_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and pattern_desc =
| Ppat_any (** The pattern [_]. *)
| Ppat_var of string loc (** A variable pattern such as [x] *)
| Ppat_alias of pattern * string loc
(** An alias pattern such as [P as 'a] *)
| Ppat_constant of constant
* Patterns such as [ 1 ] , [ ' a ' ] , [ " true " ] , [ 1.0 ] , [ 1l ] , [ 1L ] , [ 1n ]
| Ppat_interval of constant * constant
(** Patterns such as ['a'..'z'].
Other forms of interval are recognized by the parser
but rejected by the type-checker. *)
| Ppat_tuple of pattern list
* Patterns [ ( P1 , ... , Pn ) ] .
Invariant : [ n > = 2 ]
Invariant: [n >= 2]
*)
| Ppat_construct of Longident.t loc * (string loc list * pattern) option
(** [Ppat_construct(C, args)] represents:
- [C] when [args] is [None],
- [C P] when [args] is [Some ([], P)]
- [C (P1, ..., Pn)] when [args] is
[Some ([], Ppat_tuple [P1; ...; Pn])]
- [C (type a b) P] when [args] is [Some ([a; b], P)]
*)
| Ppat_variant of label * pattern option
(** [Ppat_variant(`A, pat)] represents:
- [`A] when [pat] is [None],
- [`A P] when [pat] is [Some P]
*)
| Ppat_record of (Longident.t loc * pattern) list * closed_flag
* [ Ppat_record([(l1 , P1 ) ; ... ; ( ln , Pn ) ] , flag ) ] represents :
- [ { l1 = P1 ; ... ; ln = Pn } ]
when [ flag ] is { { ! Asttypes.closed_flag . Closed}[Closed ] }
- [ { l1 = P1 ; ... ; ln = Pn ; _ } ]
when [ flag ] is { { ! Asttypes.closed_flag . Open}[Open ] }
Invariant : [ n > 0 ]
- [{ l1=P1; ...; ln=Pn }]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]}
- [{ l1=P1; ...; ln=Pn; _}]
when [flag] is {{!Asttypes.closed_flag.Open}[Open]}
Invariant: [n > 0]
*)
| Ppat_array of pattern list (** Pattern [[| P1; ...; Pn |]] *)
| Ppat_or of pattern * pattern (** Pattern [P1 | P2] *)
| Ppat_constraint of pattern * core_type (** Pattern [(P : T)] *)
| Ppat_type of Longident.t loc (** Pattern [#tconst] *)
| Ppat_lazy of pattern (** Pattern [lazy P] *)
| Ppat_unpack of string option loc
(** [Ppat_unpack(s)] represents:
- [(module P)] when [s] is [Some "P"]
- [(module _)] when [s] is [None]
Note: [(module P : S)] is represented as
[Ppat_constraint(Ppat_unpack(Some "P"), Ptyp_package S)]
*)
| Ppat_exception of pattern (** Pattern [exception P] *)
| Ppat_extension of extension (** Pattern [[%id]] *)
| Ppat_open of Longident.t loc * pattern (** Pattern [M.(P)] *)
* { 2 Value expressions }
and expression =
{
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_loc_stack: location_stack;
pexp_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and expression_desc =
| Pexp_ident of Longident.t loc
* Identifiers such as [ x ] and [ ]
*)
| Pexp_constant of constant
* Expressions constant such as [ 1 ] , [ ' a ' ] , [ " true " ] , [ 1.0 ] , [ 1l ] ,
[ 1L ] , [ 1n ]
[1L], [1n] *)
| Pexp_let of rec_flag * value_binding list * expression
(** [Pexp_let(flag, [(P1,E1) ; ... ; (Pn,En)], E)] represents:
- [let P1 = E1 and ... and Pn = EN in E]
when [flag] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN in E]
when [flag] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
*)
| Pexp_function of case list (** [function P1 -> E1 | ... | Pn -> En] *)
| Pexp_fun of arg_label * expression option * pattern * expression
* [ Pexp_fun(lbl , exp0 , P , E1 ) ] represents :
- [ fun P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Nolabel}[Nolabel ] }
and [ exp0 ] is [ None ]
- [ fun ~l :P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Labelled}[Labelled l ] }
and [ exp0 ] is [ None ]
- [ fun ? l :P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ None ]
- [ fun ? l:(P = E0 ) - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ Some E0 ]
Notes :
- If [ E0 ] is provided , only
{ { ! Asttypes.arg_label . Optional}[Optional ] } is allowed .
- [ fun P1 P2 .. Pn - > E1 ] is represented as nested
{ { ! expression_desc . Pexp_fun}[Pexp_fun ] } .
- [ let f P = E ] is represented using
{ { ! expression_desc . Pexp_fun}[Pexp_fun ] } .
- [fun P -> E1]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]}
and [exp0] is [None]
- [fun ~l:P -> E1]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]}
and [exp0] is [None]
- [fun ?l:P -> E1]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [None]
- [fun ?l:(P = E0) -> E1]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [Some E0]
Notes:
- If [E0] is provided, only
{{!Asttypes.arg_label.Optional}[Optional]} is allowed.
- [fun P1 P2 .. Pn -> E1] is represented as nested
{{!expression_desc.Pexp_fun}[Pexp_fun]}.
- [let f P = E] is represented using
{{!expression_desc.Pexp_fun}[Pexp_fun]}.
*)
| Pexp_apply of expression * (arg_label * expression) list
(** [Pexp_apply(E0, [(l1, E1) ; ... ; (ln, En)])]
represents [E0 ~l1:E1 ... ~ln:En]
[li] can be
{{!Asttypes.arg_label.Nolabel}[Nolabel]} (non labeled argument),
{{!Asttypes.arg_label.Labelled}[Labelled]} (labelled arguments) or
{{!Asttypes.arg_label.Optional}[Optional]} (optional argument).
Invariant: [n > 0]
*)
| Pexp_match of expression * case list
* [ match E0 with P1 - > E1 | ... | Pn - > En ]
| Pexp_try of expression * case list
* [ try E0 with P1 - > E1 | ... | Pn - > En ]
| Pexp_tuple of expression list
* Expressions [ ( E1 , ... , En ) ]
Invariant : [ n > = 2 ]
Invariant: [n >= 2]
*)
| Pexp_construct of Longident.t loc * expression option
(** [Pexp_construct(C, exp)] represents:
- [C] when [exp] is [None],
- [C E] when [exp] is [Some E],
- [C (E1, ..., En)] when [exp] is [Some (Pexp_tuple[E1;...;En])]
*)
| Pexp_variant of label * expression option
* [ Pexp_variant(`A , exp ) ] represents
- [ ` A ] when [ exp ] is [ None ]
- [ ` A E ] when [ exp ] is [ Some E ]
- [`A] when [exp] is [None]
- [`A E] when [exp] is [Some E]
*)
| Pexp_record of (Longident.t loc * expression) list * expression option
* [ Pexp_record([(l1,P1 ) ; ... ; ( ln , Pn ) ] , exp0 ) ] represents
- [ { l1 = P1 ; ... ; ln = Pn } ] when [ exp0 ] is [ None ]
- [ { E0 with l1 = P1 ; ... ; ln = Pn } ] when [ exp0 ] is [ Some E0 ]
Invariant : [ n > 0 ]
- [{ l1=P1; ...; ln=Pn }] when [exp0] is [None]
- [{ E0 with l1=P1; ...; ln=Pn }] when [exp0] is [Some E0]
Invariant: [n > 0]
*)
| Pexp_field of expression * Longident.t loc (** [E.l] *)
| Pexp_setfield of expression * Longident.t loc * expression
(** [E1.l <- E2] *)
| Pexp_array of expression list (** [[| E1; ...; En |]] *)
| Pexp_ifthenelse of expression * expression * expression option
(** [if E1 then E2 else E3] *)
| Pexp_sequence of expression * expression (** [E1; E2] *)
| Pexp_while of expression * expression (** [while E1 do E2 done] *)
| Pexp_for of pattern * expression * expression * direction_flag * expression
* [ Pexp_for(i , E1 , E2 , direction , E3 ) ] represents :
- [ for i = E1 to E2 do E3 done ]
when [ direction ] is { { ! Asttypes.direction_flag . Upto}[Upto ] }
- [ for i = E1 downto E2 do E3 done ]
when [ direction ] is { { ! Asttypes.direction_flag . Downto}[Downto ] }
- [for i = E1 to E2 do E3 done]
when [direction] is {{!Asttypes.direction_flag.Upto}[Upto]}
- [for i = E1 downto E2 do E3 done]
when [direction] is {{!Asttypes.direction_flag.Downto}[Downto]}
*)
| Pexp_constraint of expression * core_type (** [(E : T)] *)
| Pexp_coerce of expression * core_type option * core_type
* [ , from , T ) ] represents
- [ ( E :> T ) ] when [ from ] is [ None ] ,
- [ ( E : T0 :> T ) ] when [ from ] is [ Some T0 ] .
- [(E :> T)] when [from] is [None],
- [(E : T0 :> T)] when [from] is [Some T0].
*)
| Pexp_send of expression * label loc (** [E # m] *)
| Pexp_new of Longident.t loc (** [new M.c] *)
| Pexp_setinstvar of label loc * expression (** [x <- 2] *)
| Pexp_override of (label loc * expression) list
(** [{< x1 = E1; ...; xn = En >}] *)
| Pexp_letmodule of string option loc * module_expr * expression
(** [let module M = ME in E] *)
| Pexp_letexception of extension_constructor * expression
(** [let exception C in E] *)
| Pexp_assert of expression
(** [assert E].
Note: [assert false] is treated in a special way by the
type-checker. *)
| Pexp_lazy of expression (** [lazy E] *)
| Pexp_poly of expression * core_type option
(** Used for method bodies.
Can only be used as the expression under
{{!class_field_kind.Cfk_concrete}[Cfk_concrete]} for methods (not
values). *)
| Pexp_object of class_structure (** [object ... end] *)
| Pexp_newtype of string loc * expression (** [fun (type t) -> E] *)
| Pexp_pack of module_expr
(** [(module ME)].
[(module ME : S)] is represented as
[Pexp_constraint(Pexp_pack ME, Ptyp_package S)] *)
| Pexp_open of open_declaration * expression
(** - [M.(E)]
- [let open M in E]
- [let open! M in E] *)
| Pexp_letop of letop
(** - [let* P = E0 in E1]
- [let* P0 = E00 and* P1 = E01 in E1] *)
| Pexp_extension of extension (** [[%id]] *)
| Pexp_unreachable (** [.] *)
| Pexp_hole (** [_] *)
and case =
{
pc_lhs: pattern;
pc_guard: expression option;
pc_rhs: expression;
}
(** Values of type {!case} represents [(P -> E)] or [(P when E0 -> E)] *)
and letop =
{
let_ : binding_op;
ands : binding_op list;
body : expression;
}
and binding_op =
{
pbop_op : string loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
* { 2 Value descriptions }
and value_description =
{
pval_name: string loc;
pval_type: core_type;
pval_prim: string list;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pval_loc: Location.t;
}
(** Values of type {!value_description} represents:
- [val x: T],
when {{!value_description.pval_prim}[pval_prim]} is [[]]
- [external x: T = "s1" ... "sn"]
when {{!value_description.pval_prim}[pval_prim]} is [["s1";..."sn"]]
*)
* { 2 Type declarations }
and type_declaration =
{
ptype_name: string loc;
ptype_params: (core_type * (variance * injectivity)) list;
(** [('a1,...'an) t] *)
ptype_cstrs: (core_type * core_type * Location.t) list;
* [ ... constraint T1 = T1 ' ... constraint ]
ptype_kind: type_kind;
ptype_private: private_flag; (** for [= private ...] *)
ptype_manifest: core_type option; (** represents [= T] *)
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
ptype_loc: Location.t;
}
*
Here are type declarations and their representation ,
for various { { ! type_declaration.ptype_kind}[ptype_kind ] }
and { { ! ] } values :
- [ type t ] when [ type_kind ] is { { ! type_kind . Ptype_abstract}[Ptype_abstract ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 ]
when [ type_kind ] is { { ! type_kind . Ptype_abstract}[Ptype_abstract ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = C of T | ... ]
when [ type_kind ] is { { ! type_kind . Ptype_variant}[Ptype_variant ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 = C of T | ... ]
when [ type_kind ] is { { ! type_kind . Ptype_variant}[Ptype_variant ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = { l : T ; ... } ]
when [ type_kind ] is { { ! type_kind . Ptype_record}[Ptype_record ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 = { l : T ; ... } ]
when [ type_kind ] is { { ! type_kind . Ptype_record}[Ptype_record ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = .. ]
when [ type_kind ] is { { ! type_kind . Ptype_open}[Ptype_open ] } ,
and [ manifest ] is [ None ] .
Here are type declarations and their representation,
for various {{!type_declaration.ptype_kind}[ptype_kind]}
and {{!type_declaration.ptype_manifest}[ptype_manifest]} values:
- [type t] when [type_kind] is {{!type_kind.Ptype_abstract}[Ptype_abstract]},
and [manifest] is [None],
- [type t = T0]
when [type_kind] is {{!type_kind.Ptype_abstract}[Ptype_abstract]},
and [manifest] is [Some T0],
- [type t = C of T | ...]
when [type_kind] is {{!type_kind.Ptype_variant}[Ptype_variant]},
and [manifest] is [None],
- [type t = T0 = C of T | ...]
when [type_kind] is {{!type_kind.Ptype_variant}[Ptype_variant]},
and [manifest] is [Some T0],
- [type t = {l: T; ...}]
when [type_kind] is {{!type_kind.Ptype_record}[Ptype_record]},
and [manifest] is [None],
- [type t = T0 = {l : T; ...}]
when [type_kind] is {{!type_kind.Ptype_record}[Ptype_record]},
and [manifest] is [Some T0],
- [type t = ..]
when [type_kind] is {{!type_kind.Ptype_open}[Ptype_open]},
and [manifest] is [None].
*)
and type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_record of label_declaration list (** Invariant: non-empty list *)
| Ptype_open
and label_declaration =
{
pld_name: string loc;
pld_mutable: mutable_flag;
pld_type: core_type;
pld_loc: Location.t;
pld_attributes: attributes; (** [l : T [\@id1] [\@id2]] *)
}
(**
- [{ ...; l: T; ... }]
when {{!label_declaration.pld_mutable}[pld_mutable]}
is {{!Asttypes.mutable_flag.Immutable}[Immutable]},
- [{ ...; mutable l: T; ... }]
when {{!label_declaration.pld_mutable}[pld_mutable]}
is {{!Asttypes.mutable_flag.Mutable}[Mutable]}.
Note: [T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]}.
*)
and constructor_declaration =
{
pcd_name: string loc;
pcd_vars: string loc list;
pcd_args: constructor_arguments;
pcd_res: core_type option;
pcd_loc: Location.t;
pcd_attributes: attributes; (** [C of ... [\@id1] [\@id2]] *)
}
and constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
(** Values of type {!constructor_declaration}
represents the constructor arguments of:
- [C of T1 * ... * Tn] when [res = None],
and [args = Pcstr_tuple [T1; ... ; Tn]],
- [C: T0] when [res = Some T0],
and [args = Pcstr_tuple []],
- [C: T1 * ... * Tn -> T0] when [res = Some T0],
and [args = Pcstr_tuple [T1; ... ; Tn]],
- [C of {...}] when [res = None],
and [args = Pcstr_record [...]],
- [C: {...} -> T0] when [res = Some T0],
and [args = Pcstr_record [...]].
*)
and type_extension =
{
ptyext_path: Longident.t loc;
ptyext_params: (core_type * (variance * injectivity)) list;
ptyext_constructors: extension_constructor list;
ptyext_private: private_flag;
ptyext_loc: Location.t;
* ... [ \@\@id1 ] [ \@\@id2 ]
}
(**
Definition of new extensions constructors for the extensive sum type [t]
([type t += ...]).
*)
and extension_constructor =
{
pext_name: string loc;
pext_kind: extension_constructor_kind;
pext_loc: Location.t;
pext_attributes: attributes; (** [C of ... [\@id1] [\@id2]] *)
}
and type_exception =
{
ptyexn_constructor : extension_constructor;
ptyexn_loc : Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
(** Definition of a new exception ([exception E]). *)
and extension_constructor_kind =
| Pext_decl of string loc list * constructor_arguments * core_type option
* [ Pext_decl(existentials , , t_opt ) ]
describes a new extension constructor . It can be :
- [ C of T1 * ... * Tn ] when :
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ None ] } . }
- [ C : T0 ] when
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
- [ C : T1 * ... * Tn - > T0 ] when
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
- [ C : ' a ... . T1 * ... * Tn - > T0 ] when
{ ul { - [ existentials ] is [ [ ' a ; ... ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
describes a new extension constructor. It can be:
- [C of T1 * ... * Tn] when:
{ul {- [existentials] is [[]],}
{- [c_args] is [[T1; ...; Tn]],}
{- [t_opt] is [None]}.}
- [C: T0] when
{ul {- [existentials] is [[]],}
{- [c_args] is [[]],}
{- [t_opt] is [Some T0].}}
- [C: T1 * ... * Tn -> T0] when
{ul {- [existentials] is [[]],}
{- [c_args] is [[T1; ...; Tn]],}
{- [t_opt] is [Some T0].}}
- [C: 'a... . T1 * ... * Tn -> T0] when
{ul {- [existentials] is [['a;...]],}
{- [c_args] is [[T1; ... ; Tn]],}
{- [t_opt] is [Some T0].}}
*)
| Pext_rebind of Longident.t loc
(** [Pext_rebind(D)] re-export the constructor [D] with the new name [C] *)
(** {1 Class language} *)
* { 2 Type expressions for the class language }
and class_type =
{
pcty_desc: class_type_desc;
pcty_loc: Location.t;
pcty_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and class_type_desc =
| Pcty_constr of Longident.t loc * core_type list
(** - [c]
- [['a1, ..., 'an] c] *)
| Pcty_signature of class_signature (** [object ... end] *)
| Pcty_arrow of arg_label * core_type * class_type
(** [Pcty_arrow(lbl, T, CT)] represents:
- [T -> CT]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]},
- [~l:T -> CT]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]},
- [?l:T -> CT]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}.
*)
| Pcty_extension of extension (** [%id] *)
| Pcty_open of open_description * class_type (** [let open M in CT] *)
and class_signature =
{
pcsig_self: core_type;
pcsig_fields: class_type_field list;
}
(** Values of type [class_signature] represents:
- [object('selfpat) ... end]
- [object ... end] when {{!class_signature.pcsig_self}[pcsig_self]}
is {{!core_type_desc.Ptyp_any}[Ptyp_any]}
*)
and class_type_field =
{
pctf_desc: class_type_field_desc;
pctf_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_type_field_desc =
| Pctf_inherit of class_type (** [inherit CT] *)
| Pctf_val of (label loc * mutable_flag * virtual_flag * core_type)
* [ x : T ]
| Pctf_method of (label loc * private_flag * virtual_flag * core_type)
(** [method x: T]
Note: [T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]}.
*)
| Pctf_constraint of (core_type * core_type) (** [constraint T1 = T2] *)
| Pctf_attribute of attribute (** [[\@\@\@id]] *)
| Pctf_extension of extension (** [[%%id]] *)
and 'a class_infos =
{
pci_virt: virtual_flag;
pci_params: (core_type * (variance * injectivity)) list;
pci_name: string loc;
pci_expr: 'a;
pci_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
(** Values of type [class_expr class_infos] represents:
- [class c = ...]
- [class ['a1,...,'an] c = ...]
- [class virtual c = ...]
They are also used for "class type" declaration.
*)
and class_description = class_type class_infos
and class_type_declaration = class_type class_infos
* { 2 Value expressions for the class language }
and class_expr =
{
pcl_desc: class_expr_desc;
pcl_loc: Location.t;
pcl_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and class_expr_desc =
| Pcl_constr of Longident.t loc * core_type list
(** [c] and [['a1, ..., 'an] c] *)
| Pcl_structure of class_structure (** [object ... end] *)
| Pcl_fun of arg_label * expression option * pattern * class_expr
* [ Pcl_fun(lbl , exp0 , P , CE ) ] represents :
- [ fun P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Nolabel}[Nolabel ] }
and [ exp0 ] is [ None ] ,
- [ fun ~l :P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Labelled}[Labelled l ] }
and [ exp0 ] is [ None ] ,
- [ fun ? l :P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ None ] ,
- [ fun ? l:(P = E0 ) - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ Some E0 ] .
- [fun P -> CE]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]}
and [exp0] is [None],
- [fun ~l:P -> CE]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]}
and [exp0] is [None],
- [fun ?l:P -> CE]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [None],
- [fun ?l:(P = E0) -> CE]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [Some E0].
*)
| Pcl_apply of class_expr * (arg_label * expression) list
* [ Pcl_apply(CE , [ ( ) ; ... ; ( ln , En ) ] ) ]
represents [ CE ~l1 : E1 ... ~ln : En ] .
[ li ] can be empty ( non labeled argument ) or start with [ ? ]
( optional argument ) .
Invariant : [ n > 0 ]
represents [CE ~l1:E1 ... ~ln:En].
[li] can be empty (non labeled argument) or start with [?]
(optional argument).
Invariant: [n > 0]
*)
| Pcl_let of rec_flag * value_binding list * class_expr
(** [Pcl_let(rec, [(P1, E1); ... ; (Pn, En)], CE)] represents:
- [let P1 = E1 and ... and Pn = EN in CE]
when [rec] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN in CE]
when [rec] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
*)
| Pcl_constraint of class_expr * class_type (** [(CE : CT)] *)
| Pcl_extension of extension (** [[%id]] *)
| Pcl_open of open_description * class_expr (** [let open M in CE] *)
and class_structure =
{
pcstr_self: pattern;
pcstr_fields: class_field list;
}
(** Values of type {!class_structure} represents:
- [object(selfpat) ... end]
- [object ... end] when {{!class_structure.pcstr_self}[pcstr_self]}
is {{!pattern_desc.Ppat_any}[Ppat_any]}
*)
and class_field =
{
pcf_desc: class_field_desc;
pcf_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_field_desc =
| Pcf_inherit of override_flag * class_expr * string loc option
* [ Pcf_inherit(flag , CE , s ) ] represents :
- [ inherit CE ]
when [ flag ] is { { ! . Fresh}[Fresh ] }
and [ s ] is [ None ] ,
- [ inherit CE as x ]
when [ flag ] is { { ! . Fresh}[Fresh ] }
and [ s ] is [ Some x ] ,
- [ inherit ! CE ]
when [ flag ] is { { ! . Override}[Override ] }
and [ s ] is [ None ] ,
- [ inherit ! CE as x ]
when [ flag ] is { { ! . Override}[Override ] }
and [ s ] is [ Some x ]
- [inherit CE]
when [flag] is {{!Asttypes.override_flag.Fresh}[Fresh]}
and [s] is [None],
- [inherit CE as x]
when [flag] is {{!Asttypes.override_flag.Fresh}[Fresh]}
and [s] is [Some x],
- [inherit! CE]
when [flag] is {{!Asttypes.override_flag.Override}[Override]}
and [s] is [None],
- [inherit! CE as x]
when [flag] is {{!Asttypes.override_flag.Override}[Override]}
and [s] is [Some x]
*)
| Pcf_val of (label loc * mutable_flag * class_field_kind)
(** [Pcf_val(x,flag, kind)] represents:
- [val x = E]
when [flag] is {{!Asttypes.mutable_flag.Immutable}[Immutable]}
and [kind] is {{!class_field_kind.Cfk_concrete}[Cfk_concrete(Fresh, E)]}
- [val virtual x: T]
when [flag] is {{!Asttypes.mutable_flag.Immutable}[Immutable]}
and [kind] is {{!class_field_kind.Cfk_virtual}[Cfk_virtual(T)]}
- [val mutable x = E]
when [flag] is {{!Asttypes.mutable_flag.Mutable}[Mutable]}
and [kind] is {{!class_field_kind.Cfk_concrete}[Cfk_concrete(Fresh, E)]}
- [val mutable virtual x: T]
when [flag] is {{!Asttypes.mutable_flag.Mutable}[Mutable]}
and [kind] is {{!class_field_kind.Cfk_virtual}[Cfk_virtual(T)]}
*)
| Pcf_method of (label loc * private_flag * class_field_kind)
(** - [method x = E]
([E] can be a {{!expression_desc.Pexp_poly}[Pexp_poly]})
- [method virtual x: T]
([T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]})
*)
| Pcf_constraint of (core_type * core_type) (** [constraint T1 = T2] *)
| Pcf_initializer of expression (** [initializer E] *)
| Pcf_attribute of attribute (** [[\@\@\@id]] *)
| Pcf_extension of extension (** [[%%id]] *)
and class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of override_flag * expression
and class_declaration = class_expr class_infos
(** {1 Module language} *)
* { 2 Type expressions for the module language }
and module_type =
{
pmty_desc: module_type_desc;
pmty_loc: Location.t;
pmty_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and module_type_desc =
| Pmty_ident of Longident.t loc (** [Pmty_ident(S)] represents [S] *)
| Pmty_signature of signature (** [sig ... end] *)
| Pmty_functor of functor_parameter * module_type
* [ functor(X : ) - > MT2 ]
| Pmty_with of module_type * with_constraint list (** [MT with ...] *)
| Pmty_typeof of module_expr (** [module type of ME] *)
| Pmty_extension of extension (** [[%id]] *)
| Pmty_alias of Longident.t loc (** [(module M)] *)
and functor_parameter =
| Unit (** [()] *)
| Named of string option loc * module_type
* [ Named(name , ) ] represents :
- [ ( X : MT ) ] when [ name ] is [ Some X ] ,
- [ ( _ : MT ) ] when [ name ] is [ None ]
- [(X : MT)] when [name] is [Some X],
- [(_ : MT)] when [name] is [None] *)
and signature = signature_item list
and signature_item =
{
psig_desc: signature_item_desc;
psig_loc: Location.t;
}
and signature_item_desc =
| Psig_value of value_description
(** - [val x: T]
- [external x: T = "s1" ... "sn"]
*)
| Psig_type of rec_flag * type_declaration list
* [ type t1 = ... and ... and = ... ]
| Psig_typesubst of type_declaration list
(** [type t1 := ... and ... and tn := ...] *)
| Psig_typext of type_extension (** [type t1 += ...] *)
| Psig_exception of type_exception (** [exception C of T] *)
| Psig_module of module_declaration (** [module X = M] and [module X : MT] *)
| Psig_modsubst of module_substitution (** [module X := M] *)
| Psig_recmodule of module_declaration list
* [ module rec X1 : and ... and Xn : MTn ]
| Psig_modtype of module_type_declaration
(** [module type S = MT] and [module type S] *)
| Psig_modtypesubst of module_type_declaration
(** [module type S := ...] *)
| Psig_open of open_description (** [open X] *)
| Psig_include of include_description (** [include MT] *)
| Psig_class of class_description list
(** [class c1 : ... and ... and cn : ...] *)
| Psig_class_type of class_type_declaration list
(** [class type ct1 = ... and ... and ctn = ...] *)
| Psig_attribute of attribute (** [[\@\@\@id]] *)
| Psig_extension of extension * attributes (** [[%%id]] *)
and module_declaration =
{
pmd_name: string option loc;
pmd_type: module_type;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pmd_loc: Location.t;
}
(** Values of type [module_declaration] represents [S : MT] *)
and module_substitution =
{
pms_name: string loc;
pms_manifest: Longident.t loc;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pms_loc: Location.t;
}
(** Values of type [module_substitution] represents [S := M] *)
and module_type_declaration =
{
pmtd_name: string loc;
pmtd_type: module_type option;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pmtd_loc: Location.t;
}
(** Values of type [module_type_declaration] represents:
- [S = MT],
- [S] for abstract module type declaration,
when {{!module_type_declaration.pmtd_type}[pmtd_type]} is [None].
*)
and 'a open_infos =
{
popen_expr: 'a;
popen_override: override_flag;
popen_loc: Location.t;
popen_attributes: attributes;
}
* Values of type [ ' a open_infos ] represents :
- [ open ! X ] when { { ! open_infos.popen_override}[popen_override ] }
is { { ! . Override}[Override ] }
( silences the " used identifier shadowing " warning )
- [ open X ] when { { ! open_infos.popen_override}[popen_override ] }
is { { ! . Fresh}[Fresh ] }
- [open! X] when {{!open_infos.popen_override}[popen_override]}
is {{!Asttypes.override_flag.Override}[Override]}
(silences the "used identifier shadowing" warning)
- [open X] when {{!open_infos.popen_override}[popen_override]}
is {{!Asttypes.override_flag.Fresh}[Fresh]}
*)
and open_description = Longident.t loc open_infos
(** Values of type [open_description] represents:
- [open M.N]
- [open M(N).O] *)
and open_declaration = module_expr open_infos
(** Values of type [open_declaration] represents:
- [open M.N]
- [open M(N).O]
- [open struct ... end] *)
and 'a include_infos =
{
pincl_mod: 'a;
pincl_loc: Location.t;
pincl_attributes: attributes;
}
and include_description = module_type include_infos
(** Values of type [include_description] represents [include MT] *)
and include_declaration = module_expr include_infos
(** Values of type [include_declaration] represents [include ME] *)
and with_constraint =
| Pwith_type of Longident.t loc * type_declaration
(** [with type X.t = ...]
Note: the last component of the longident must match
the name of the type_declaration. *)
| Pwith_module of Longident.t loc * Longident.t loc
(** [with module X.Y = Z] *)
| Pwith_modtype of Longident.t loc * module_type
(** [with module type X.Y = Z] *)
| Pwith_modtypesubst of Longident.t loc * module_type
(** [with module type X.Y := sig end] *)
| Pwith_typesubst of Longident.t loc * type_declaration
(** [with type X.t := ..., same format as [Pwith_type]] *)
| Pwith_modsubst of Longident.t loc * Longident.t loc
(** [with module X.Y := Z] *)
* { 2 Value expressions for the module language }
and module_expr =
{
pmod_desc: module_expr_desc;
pmod_loc: Location.t;
pmod_attributes: attributes; (** [... [\@id1] [\@id2]] *)
}
and module_expr_desc =
| Pmod_ident of Longident.t loc (** [X] *)
| Pmod_structure of structure (** [struct ... end] *)
| Pmod_functor of functor_parameter * module_expr
* [ functor(X : ) - > ME ]
* [ ) ]
| Pmod_constraint of module_expr * module_type (** [(ME : MT)] *)
| Pmod_unpack of expression (** [(val E)] *)
| Pmod_extension of extension (** [[%id]] *)
| Pmod_hole (** [_] *)
and structure = structure_item list
and structure_item =
{
pstr_desc: structure_item_desc;
pstr_loc: Location.t;
}
and structure_item_desc =
| Pstr_eval of expression * attributes (** [E] *)
| Pstr_value of rec_flag * value_binding list
* [ Pstr_value(rec , [ ( P1 , E1 ; ... ; ( Pn , En ) ) ] ) ] represents :
- [ let P1 = E1 and ... and Pn = EN ]
when [ rec ] is { { ! Asttypes.rec_flag . Nonrecursive}[Nonrecursive ] } ,
- [ let rec P1 = E1 and ... and Pn = EN ]
when [ rec ] is { { ! Asttypes.rec_flag . Recursive}[Recursive ] } .
- [let P1 = E1 and ... and Pn = EN]
when [rec] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN ]
when [rec] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
*)
| Pstr_primitive of value_description
(** - [val x: T]
- [external x: T = "s1" ... "sn" ]*)
| Pstr_type of rec_flag * type_declaration list
(** [type t1 = ... and ... and tn = ...] *)
| Pstr_typext of type_extension (** [type t1 += ...] *)
| Pstr_exception of type_exception
(** - [exception C of T]
- [exception C = M.X] *)
| Pstr_module of module_binding (** [module X = ME] *)
| Pstr_recmodule of module_binding list
(** [module rec X1 = ME1 and ... and Xn = MEn] *)
| Pstr_modtype of module_type_declaration (** [module type S = MT] *)
| Pstr_open of open_declaration (** [open X] *)
| Pstr_class of class_declaration list
(** [class c1 = ... and ... and cn = ...] *)
| Pstr_class_type of class_type_declaration list
(** [class type ct1 = ... and ... and ctn = ...] *)
| Pstr_include of include_declaration (** [include ME] *)
| Pstr_attribute of attribute (** [[\@\@\@id]] *)
| Pstr_extension of extension * attributes (** [[%%id]] *)
and value_binding =
{
pvb_pat: pattern;
pvb_expr: expression;
pvb_attributes: attributes;
pvb_loc: Location.t;
}
and module_binding =
{
pmb_name: string option loc;
pmb_expr: module_expr;
pmb_attributes: attributes;
pmb_loc: Location.t;
}
(** Values of type [module_binding] represents [module X = ME] *)
* { 1 Toplevel }
* { 2 Toplevel phrases }
type toplevel_phrase =
| Ptop_def of structure
| Ptop_dir of toplevel_directive (** [#use], [#load] ... *)
and toplevel_directive =
{
pdir_name: string loc;
pdir_arg: directive_argument option;
pdir_loc: Location.t;
}
and directive_argument =
{
pdira_desc: directive_argument_desc;
pdira_loc: Location.t;
}
and directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
| null |
https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/c490e5b7c4b5f5e5848a5cbdb1e669588dfeaae3/vendor/parser-standard/parsetree.mli
|
ocaml
|
************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Abstract syntax tree produced by parsing
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
* Character such as ['c'].
* Attributes such as [[\@id ARG]] and [[\@\@id ARG]].
Metadata containers passed around within the AST.
The compiler ignores unknown attributes.
* Extension points such as [[%id ARG] and [%%id ARG]].
Sub-language placeholder -- rejected by the typechecker.
* [: T] in an attribute or an extension point
* [? P] or [? P when E], in an attribute or an extension point
* [... [\@id1] [\@id2]]
* [_]
* A type variable such as ['a]
* [Ptyp_arrow(lbl, T1, T2)] represents:
- [T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Nolabel}[Nolabel]},
- [~l:T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Labelled}[Labelled]},
- [?l:T1 -> T2] when [lbl] is
{{!Asttypes.arg_label.Optional}[Optional]}.
* [Ptyp_constr(lident, l)] represents:
- [tconstr] when [l=[]],
- [T tconstr] when [l=[T]],
- [(T1, ..., Tn) tconstr] when [l=[T1 ; ... ; Tn]].
* [Ptyp_object([ l1:T1; ...; ln:Tn ], flag)] represents:
- [< l1:T1; ...; ln:Tn >] when [flag] is
{{!Asttypes.closed_flag.Closed}[Closed]},
- [< l1:T1; ...; ln:Tn; .. >] when [flag] is
{{!Asttypes.closed_flag.Open}[Open]}.
* [Ptyp_class(tconstr, l)] represents:
- [#tconstr] when [l=[]],
- [T #tconstr] when [l=[T]],
- [(T1, ..., Tn) #tconstr] when [l=[T1 ; ... ; Tn]].
* [T as 'a].
* [Ptyp_variant([`A;`B], flag, labels)] represents:
- [[ `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [None],
- [[> `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Open}[Open]},
and [labels] is [None],
- [[< `A|`B ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [Some []],
- [[< `A|`B > `X `Y ]]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]},
and [labels] is [Some ["X";"Y"]].
* [(module S)].
* [[%id]].
* [[ | t ]]
* {2 Patterns}
* [... [\@id1] [\@id2]]
* The pattern [_].
* A variable pattern such as [x]
* An alias pattern such as [P as 'a]
* Patterns such as ['a'..'z'].
Other forms of interval are recognized by the parser
but rejected by the type-checker.
* [Ppat_construct(C, args)] represents:
- [C] when [args] is [None],
- [C P] when [args] is [Some ([], P)]
- [C (P1, ..., Pn)] when [args] is
[Some ([], Ppat_tuple [P1; ...; Pn])]
- [C (type a b) P] when [args] is [Some ([a; b], P)]
* [Ppat_variant(`A, pat)] represents:
- [`A] when [pat] is [None],
- [`A P] when [pat] is [Some P]
* Pattern [[| P1; ...; Pn |]]
* Pattern [P1 | P2]
* Pattern [(P : T)]
* Pattern [#tconst]
* Pattern [lazy P]
* [Ppat_unpack(s)] represents:
- [(module P)] when [s] is [Some "P"]
- [(module _)] when [s] is [None]
Note: [(module P : S)] is represented as
[Ppat_constraint(Ppat_unpack(Some "P"), Ptyp_package S)]
* Pattern [exception P]
* Pattern [[%id]]
* Pattern [M.(P)]
* [... [\@id1] [\@id2]]
* [Pexp_let(flag, [(P1,E1) ; ... ; (Pn,En)], E)] represents:
- [let P1 = E1 and ... and Pn = EN in E]
when [flag] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN in E]
when [flag] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
* [function P1 -> E1 | ... | Pn -> En]
* [Pexp_apply(E0, [(l1, E1) ; ... ; (ln, En)])]
represents [E0 ~l1:E1 ... ~ln:En]
[li] can be
{{!Asttypes.arg_label.Nolabel}[Nolabel]} (non labeled argument),
{{!Asttypes.arg_label.Labelled}[Labelled]} (labelled arguments) or
{{!Asttypes.arg_label.Optional}[Optional]} (optional argument).
Invariant: [n > 0]
* [Pexp_construct(C, exp)] represents:
- [C] when [exp] is [None],
- [C E] when [exp] is [Some E],
- [C (E1, ..., En)] when [exp] is [Some (Pexp_tuple[E1;...;En])]
* [E.l]
* [E1.l <- E2]
* [[| E1; ...; En |]]
* [if E1 then E2 else E3]
* [E1; E2]
* [while E1 do E2 done]
* [(E : T)]
* [E # m]
* [new M.c]
* [x <- 2]
* [{< x1 = E1; ...; xn = En >}]
* [let module M = ME in E]
* [let exception C in E]
* [assert E].
Note: [assert false] is treated in a special way by the
type-checker.
* [lazy E]
* Used for method bodies.
Can only be used as the expression under
{{!class_field_kind.Cfk_concrete}[Cfk_concrete]} for methods (not
values).
* [object ... end]
* [fun (type t) -> E]
* [(module ME)].
[(module ME : S)] is represented as
[Pexp_constraint(Pexp_pack ME, Ptyp_package S)]
* - [M.(E)]
- [let open M in E]
- [let open! M in E]
* - [let* P = E0 in E1]
- [let* P0 = E00 and* P1 = E01 in E1]
* [[%id]]
* [.]
* [_]
* Values of type {!case} represents [(P -> E)] or [(P when E0 -> E)]
* Values of type {!value_description} represents:
- [val x: T],
when {{!value_description.pval_prim}[pval_prim]} is [[]]
- [external x: T = "s1" ... "sn"]
when {{!value_description.pval_prim}[pval_prim]} is [["s1";..."sn"]]
* [('a1,...'an) t]
* for [= private ...]
* represents [= T]
* Invariant: non-empty list
* [l : T [\@id1] [\@id2]]
*
- [{ ...; l: T; ... }]
when {{!label_declaration.pld_mutable}[pld_mutable]}
is {{!Asttypes.mutable_flag.Immutable}[Immutable]},
- [{ ...; mutable l: T; ... }]
when {{!label_declaration.pld_mutable}[pld_mutable]}
is {{!Asttypes.mutable_flag.Mutable}[Mutable]}.
Note: [T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]}.
* [C of ... [\@id1] [\@id2]]
* Values of type {!constructor_declaration}
represents the constructor arguments of:
- [C of T1 * ... * Tn] when [res = None],
and [args = Pcstr_tuple [T1; ... ; Tn]],
- [C: T0] when [res = Some T0],
and [args = Pcstr_tuple []],
- [C: T1 * ... * Tn -> T0] when [res = Some T0],
and [args = Pcstr_tuple [T1; ... ; Tn]],
- [C of {...}] when [res = None],
and [args = Pcstr_record [...]],
- [C: {...} -> T0] when [res = Some T0],
and [args = Pcstr_record [...]].
*
Definition of new extensions constructors for the extensive sum type [t]
([type t += ...]).
* [C of ... [\@id1] [\@id2]]
* Definition of a new exception ([exception E]).
* [Pext_rebind(D)] re-export the constructor [D] with the new name [C]
* {1 Class language}
* [... [\@id1] [\@id2]]
* - [c]
- [['a1, ..., 'an] c]
* [object ... end]
* [Pcty_arrow(lbl, T, CT)] represents:
- [T -> CT]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]},
- [~l:T -> CT]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]},
- [?l:T -> CT]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}.
* [%id]
* [let open M in CT]
* Values of type [class_signature] represents:
- [object('selfpat) ... end]
- [object ... end] when {{!class_signature.pcsig_self}[pcsig_self]}
is {{!core_type_desc.Ptyp_any}[Ptyp_any]}
* [inherit CT]
* [method x: T]
Note: [T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]}.
* [constraint T1 = T2]
* [[\@\@\@id]]
* [[%%id]]
* Values of type [class_expr class_infos] represents:
- [class c = ...]
- [class ['a1,...,'an] c = ...]
- [class virtual c = ...]
They are also used for "class type" declaration.
* [... [\@id1] [\@id2]]
* [c] and [['a1, ..., 'an] c]
* [object ... end]
* [Pcl_let(rec, [(P1, E1); ... ; (Pn, En)], CE)] represents:
- [let P1 = E1 and ... and Pn = EN in CE]
when [rec] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN in CE]
when [rec] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
* [(CE : CT)]
* [[%id]]
* [let open M in CE]
* Values of type {!class_structure} represents:
- [object(selfpat) ... end]
- [object ... end] when {{!class_structure.pcstr_self}[pcstr_self]}
is {{!pattern_desc.Ppat_any}[Ppat_any]}
* [Pcf_val(x,flag, kind)] represents:
- [val x = E]
when [flag] is {{!Asttypes.mutable_flag.Immutable}[Immutable]}
and [kind] is {{!class_field_kind.Cfk_concrete}[Cfk_concrete(Fresh, E)]}
- [val virtual x: T]
when [flag] is {{!Asttypes.mutable_flag.Immutable}[Immutable]}
and [kind] is {{!class_field_kind.Cfk_virtual}[Cfk_virtual(T)]}
- [val mutable x = E]
when [flag] is {{!Asttypes.mutable_flag.Mutable}[Mutable]}
and [kind] is {{!class_field_kind.Cfk_concrete}[Cfk_concrete(Fresh, E)]}
- [val mutable virtual x: T]
when [flag] is {{!Asttypes.mutable_flag.Mutable}[Mutable]}
and [kind] is {{!class_field_kind.Cfk_virtual}[Cfk_virtual(T)]}
* - [method x = E]
([E] can be a {{!expression_desc.Pexp_poly}[Pexp_poly]})
- [method virtual x: T]
([T] can be a {{!core_type_desc.Ptyp_poly}[Ptyp_poly]})
* [constraint T1 = T2]
* [initializer E]
* [[\@\@\@id]]
* [[%%id]]
* {1 Module language}
* [... [\@id1] [\@id2]]
* [Pmty_ident(S)] represents [S]
* [sig ... end]
* [MT with ...]
* [module type of ME]
* [[%id]]
* [(module M)]
* [()]
* - [val x: T]
- [external x: T = "s1" ... "sn"]
* [type t1 := ... and ... and tn := ...]
* [type t1 += ...]
* [exception C of T]
* [module X = M] and [module X : MT]
* [module X := M]
* [module type S = MT] and [module type S]
* [module type S := ...]
* [open X]
* [include MT]
* [class c1 : ... and ... and cn : ...]
* [class type ct1 = ... and ... and ctn = ...]
* [[\@\@\@id]]
* [[%%id]]
* Values of type [module_declaration] represents [S : MT]
* Values of type [module_substitution] represents [S := M]
* Values of type [module_type_declaration] represents:
- [S = MT],
- [S] for abstract module type declaration,
when {{!module_type_declaration.pmtd_type}[pmtd_type]} is [None].
* Values of type [open_description] represents:
- [open M.N]
- [open M(N).O]
* Values of type [open_declaration] represents:
- [open M.N]
- [open M(N).O]
- [open struct ... end]
* Values of type [include_description] represents [include MT]
* Values of type [include_declaration] represents [include ME]
* [with type X.t = ...]
Note: the last component of the longident must match
the name of the type_declaration.
* [with module X.Y = Z]
* [with module type X.Y = Z]
* [with module type X.Y := sig end]
* [with type X.t := ..., same format as [Pwith_type]]
* [with module X.Y := Z]
* [... [\@id1] [\@id2]]
* [X]
* [struct ... end]
* [(ME : MT)]
* [(val E)]
* [[%id]]
* [_]
* [E]
* - [val x: T]
- [external x: T = "s1" ... "sn" ]
* [type t1 = ... and ... and tn = ...]
* [type t1 += ...]
* - [exception C of T]
- [exception C = M.X]
* [module X = ME]
* [module rec X1 = ME1 and ... and Xn = MEn]
* [module type S = MT]
* [open X]
* [class c1 = ... and ... and cn = ...]
* [class type ct1 = ... and ... and ctn = ...]
* [include ME]
* [[\@\@\@id]]
* [[%%id]]
* Values of type [module_binding] represents [module X = ME]
* [#use], [#load] ...
|
, projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Asttypes
type constant =
| Pconst_integer of string * char option
* Integer constants such as [ 3 ] [ 3l ] [ 3L ] [ 3n ] .
Suffixes [ [ g - z][G - Z ] ] are accepted by the parser .
Suffixes except [ ' l ' ] , [ ' L ' ] and [ ' n ' ] are rejected by the typechecker
Suffixes [[g-z][G-Z]] are accepted by the parser.
Suffixes except ['l'], ['L'] and ['n'] are rejected by the typechecker
*)
| Pconst_string of string * Location.t * string option
* Constant string such as [ " constant " ] or
[ { } ] .
The location span the content of the string , without the delimiters .
[{delim|other constant|delim}].
The location span the content of the string, without the delimiters.
*)
| Pconst_float of string * char option
* Float constant such as [ 3.4 ] , [ 2e5 ] or [ 1.4e-4 ] .
Suffixes [ g - z][G - Z ] are accepted by the parser .
Suffixes are rejected by the typechecker .
Suffixes [g-z][G-Z] are accepted by the parser.
Suffixes are rejected by the typechecker.
*)
type location_stack = Location.t list
* { 1 Extension points }
type attribute = {
attr_name : string loc;
attr_payload : payload;
attr_loc : Location.t;
}
and extension = string loc * payload
and attributes = attribute list
and payload =
| PStr of structure
* [: SIG ] in an attribute or an extension point
| PPat of pattern * expression option
* { 1 Core language }
* { 2 Type expressions }
and core_type =
{
ptyp_desc: core_type_desc;
ptyp_loc: Location.t;
ptyp_loc_stack: location_stack;
}
and core_type_desc =
| Ptyp_arrow of arg_label * core_type * core_type
| Ptyp_tuple of core_type list
* [ Ptyp_tuple([T1 ; ... ; Tn ] ) ]
represents a product type [ T1 * ... * Tn ] .
Invariant : [ n > = 2 ] .
represents a product type [T1 * ... * Tn].
Invariant: [n >= 2].
*)
| Ptyp_constr of Longident.t loc * core_type list
| Ptyp_object of object_field list * closed_flag
| Ptyp_class of Longident.t loc * core_type list
| Ptyp_variant of row_field list * closed_flag * label list option
| Ptyp_poly of string loc list * core_type
* [ ' a1 ... ' an . T ]
Can only appear in the following context :
- As the { ! core_type } of a
{ { ! pattern_desc . Ppat_constraint}[Ppat_constraint ] } node corresponding
to a constraint on a let - binding :
{ [ let x : ' a1 ... ' an . T = e ... ] }
- Under { { ! class_field_kind . Cfk_virtual}[Cfk_virtual ] } for methods
( not values ) .
- As the { ! core_type } of a
{ { ! class_type_field_desc . ] } node .
- As the { ! core_type } of a { { ! expression_desc . Pexp_poly}[Pexp_poly ] }
node .
- As the { { ! label_declaration.pld_type}[pld_type ] } field of a
{ ! label_declaration } .
- As a { ! core_type } of a { { ! core_type_desc . Ptyp_object}[Ptyp_object ] }
node .
- As the { { ! value_description.pval_type}[pval_type ] } field of a
{ ! value_description } .
Can only appear in the following context:
- As the {!core_type} of a
{{!pattern_desc.Ppat_constraint}[Ppat_constraint]} node corresponding
to a constraint on a let-binding:
{[let x : 'a1 ... 'an. T = e ...]}
- Under {{!class_field_kind.Cfk_virtual}[Cfk_virtual]} for methods
(not values).
- As the {!core_type} of a
{{!class_type_field_desc.Pctf_method}[Pctf_method]} node.
- As the {!core_type} of a {{!expression_desc.Pexp_poly}[Pexp_poly]}
node.
- As the {{!label_declaration.pld_type}[pld_type]} field of a
{!label_declaration}.
- As a {!core_type} of a {{!core_type_desc.Ptyp_object}[Ptyp_object]}
node.
- As the {{!value_description.pval_type}[pval_type]} field of a
{!value_description}.
*)
and package_type = Longident.t loc * (Longident.t loc * core_type) list
* As { ! package_type } typed values :
- [ ( S , [ ] ) ] represents [ ( module S ) ] ,
- [ ( S , [ ( t1 , T1 ) ; ... ; ( tn , Tn ) ] ) ]
represents [ ( module S with type t1 = T1 and ... and tn = Tn ) ] .
- [(S, [])] represents [(module S)],
- [(S, [(t1, T1) ; ... ; (tn, Tn)])]
represents [(module S with type t1 = T1 and ... and tn = Tn)].
*)
and row_field = {
prf_desc : row_field_desc;
prf_loc : Location.t;
prf_attributes : attributes;
}
and row_field_desc =
| Rtag of label loc * bool * core_type list
* [ , b , l ) ] represents :
- [ ` A ] when [ b ] is [ true ] and [ l ] is [ [ ] ] ,
- [ ` A of T ] when [ b ] is [ false ] and [ l ] is [ [ T ] ] ,
- [ ` A of T1 & .. & Tn ] when [ b ] is [ false ] and [ l ] is [ [ T1; ... Tn ] ] ,
- [ ` A of & T1 & .. & Tn ] when [ b ] is [ true ] and [ l ] is [ [ T1; ... Tn ] ] .
- The [ bool ] field is true if the tag contains a
constant ( empty ) constructor .
- [ & ] occurs when several types are used for the same constructor
( see 4.2 in the manual )
- [`A] when [b] is [true] and [l] is [[]],
- [`A of T] when [b] is [false] and [l] is [[T]],
- [`A of T1 & .. & Tn] when [b] is [false] and [l] is [[T1;...Tn]],
- [`A of & T1 & .. & Tn] when [b] is [true] and [l] is [[T1;...Tn]].
- The [bool] field is true if the tag contains a
constant (empty) constructor.
- [&] occurs when several types are used for the same constructor
(see 4.2 in the manual)
*)
and object_field = {
pof_desc : object_field_desc;
pof_loc : Location.t;
pof_attributes : attributes;
}
and object_field_desc =
| Otag of label loc * core_type
| Oinherit of core_type
and pattern =
{
ppat_desc: pattern_desc;
ppat_loc: Location.t;
ppat_loc_stack: location_stack;
}
and pattern_desc =
| Ppat_alias of pattern * string loc
| Ppat_constant of constant
* Patterns such as [ 1 ] , [ ' a ' ] , [ " true " ] , [ 1.0 ] , [ 1l ] , [ 1L ] , [ 1n ]
| Ppat_interval of constant * constant
| Ppat_tuple of pattern list
* Patterns [ ( P1 , ... , Pn ) ] .
Invariant : [ n > = 2 ]
Invariant: [n >= 2]
*)
| Ppat_construct of Longident.t loc * (string loc list * pattern) option
| Ppat_variant of label * pattern option
| Ppat_record of (Longident.t loc * pattern) list * closed_flag
* [ Ppat_record([(l1 , P1 ) ; ... ; ( ln , Pn ) ] , flag ) ] represents :
- [ { l1 = P1 ; ... ; ln = Pn } ]
when [ flag ] is { { ! Asttypes.closed_flag . Closed}[Closed ] }
- [ { l1 = P1 ; ... ; ln = Pn ; _ } ]
when [ flag ] is { { ! Asttypes.closed_flag . Open}[Open ] }
Invariant : [ n > 0 ]
- [{ l1=P1; ...; ln=Pn }]
when [flag] is {{!Asttypes.closed_flag.Closed}[Closed]}
- [{ l1=P1; ...; ln=Pn; _}]
when [flag] is {{!Asttypes.closed_flag.Open}[Open]}
Invariant: [n > 0]
*)
| Ppat_unpack of string option loc
* { 2 Value expressions }
and expression =
{
pexp_desc: expression_desc;
pexp_loc: Location.t;
pexp_loc_stack: location_stack;
}
and expression_desc =
| Pexp_ident of Longident.t loc
* Identifiers such as [ x ] and [ ]
*)
| Pexp_constant of constant
* Expressions constant such as [ 1 ] , [ ' a ' ] , [ " true " ] , [ 1.0 ] , [ 1l ] ,
[ 1L ] , [ 1n ]
[1L], [1n] *)
| Pexp_let of rec_flag * value_binding list * expression
| Pexp_fun of arg_label * expression option * pattern * expression
* [ Pexp_fun(lbl , exp0 , P , E1 ) ] represents :
- [ fun P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Nolabel}[Nolabel ] }
and [ exp0 ] is [ None ]
- [ fun ~l :P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Labelled}[Labelled l ] }
and [ exp0 ] is [ None ]
- [ fun ? l :P - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ None ]
- [ fun ? l:(P = E0 ) - > E1 ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ Some E0 ]
Notes :
- If [ E0 ] is provided , only
{ { ! Asttypes.arg_label . Optional}[Optional ] } is allowed .
- [ fun P1 P2 .. Pn - > E1 ] is represented as nested
{ { ! expression_desc . Pexp_fun}[Pexp_fun ] } .
- [ let f P = E ] is represented using
{ { ! expression_desc . Pexp_fun}[Pexp_fun ] } .
- [fun P -> E1]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]}
and [exp0] is [None]
- [fun ~l:P -> E1]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]}
and [exp0] is [None]
- [fun ?l:P -> E1]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [None]
- [fun ?l:(P = E0) -> E1]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [Some E0]
Notes:
- If [E0] is provided, only
{{!Asttypes.arg_label.Optional}[Optional]} is allowed.
- [fun P1 P2 .. Pn -> E1] is represented as nested
{{!expression_desc.Pexp_fun}[Pexp_fun]}.
- [let f P = E] is represented using
{{!expression_desc.Pexp_fun}[Pexp_fun]}.
*)
| Pexp_apply of expression * (arg_label * expression) list
| Pexp_match of expression * case list
* [ match E0 with P1 - > E1 | ... | Pn - > En ]
| Pexp_try of expression * case list
* [ try E0 with P1 - > E1 | ... | Pn - > En ]
| Pexp_tuple of expression list
* Expressions [ ( E1 , ... , En ) ]
Invariant : [ n > = 2 ]
Invariant: [n >= 2]
*)
| Pexp_construct of Longident.t loc * expression option
| Pexp_variant of label * expression option
* [ Pexp_variant(`A , exp ) ] represents
- [ ` A ] when [ exp ] is [ None ]
- [ ` A E ] when [ exp ] is [ Some E ]
- [`A] when [exp] is [None]
- [`A E] when [exp] is [Some E]
*)
| Pexp_record of (Longident.t loc * expression) list * expression option
* [ Pexp_record([(l1,P1 ) ; ... ; ( ln , Pn ) ] , exp0 ) ] represents
- [ { l1 = P1 ; ... ; ln = Pn } ] when [ exp0 ] is [ None ]
- [ { E0 with l1 = P1 ; ... ; ln = Pn } ] when [ exp0 ] is [ Some E0 ]
Invariant : [ n > 0 ]
- [{ l1=P1; ...; ln=Pn }] when [exp0] is [None]
- [{ E0 with l1=P1; ...; ln=Pn }] when [exp0] is [Some E0]
Invariant: [n > 0]
*)
| Pexp_setfield of expression * Longident.t loc * expression
| Pexp_ifthenelse of expression * expression * expression option
| Pexp_for of pattern * expression * expression * direction_flag * expression
* [ Pexp_for(i , E1 , E2 , direction , E3 ) ] represents :
- [ for i = E1 to E2 do E3 done ]
when [ direction ] is { { ! Asttypes.direction_flag . Upto}[Upto ] }
- [ for i = E1 downto E2 do E3 done ]
when [ direction ] is { { ! Asttypes.direction_flag . Downto}[Downto ] }
- [for i = E1 to E2 do E3 done]
when [direction] is {{!Asttypes.direction_flag.Upto}[Upto]}
- [for i = E1 downto E2 do E3 done]
when [direction] is {{!Asttypes.direction_flag.Downto}[Downto]}
*)
| Pexp_coerce of expression * core_type option * core_type
* [ , from , T ) ] represents
- [ ( E :> T ) ] when [ from ] is [ None ] ,
- [ ( E : T0 :> T ) ] when [ from ] is [ Some T0 ] .
- [(E :> T)] when [from] is [None],
- [(E : T0 :> T)] when [from] is [Some T0].
*)
| Pexp_override of (label loc * expression) list
| Pexp_letmodule of string option loc * module_expr * expression
| Pexp_letexception of extension_constructor * expression
| Pexp_assert of expression
| Pexp_poly of expression * core_type option
| Pexp_pack of module_expr
| Pexp_open of open_declaration * expression
| Pexp_letop of letop
and case =
{
pc_lhs: pattern;
pc_guard: expression option;
pc_rhs: expression;
}
and letop =
{
let_ : binding_op;
ands : binding_op list;
body : expression;
}
and binding_op =
{
pbop_op : string loc;
pbop_pat : pattern;
pbop_exp : expression;
pbop_loc : Location.t;
}
* { 2 Value descriptions }
and value_description =
{
pval_name: string loc;
pval_type: core_type;
pval_prim: string list;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pval_loc: Location.t;
}
* { 2 Type declarations }
and type_declaration =
{
ptype_name: string loc;
ptype_params: (core_type * (variance * injectivity)) list;
ptype_cstrs: (core_type * core_type * Location.t) list;
* [ ... constraint T1 = T1 ' ... constraint ]
ptype_kind: type_kind;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
ptype_loc: Location.t;
}
*
Here are type declarations and their representation ,
for various { { ! type_declaration.ptype_kind}[ptype_kind ] }
and { { ! ] } values :
- [ type t ] when [ type_kind ] is { { ! type_kind . Ptype_abstract}[Ptype_abstract ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 ]
when [ type_kind ] is { { ! type_kind . Ptype_abstract}[Ptype_abstract ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = C of T | ... ]
when [ type_kind ] is { { ! type_kind . Ptype_variant}[Ptype_variant ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 = C of T | ... ]
when [ type_kind ] is { { ! type_kind . Ptype_variant}[Ptype_variant ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = { l : T ; ... } ]
when [ type_kind ] is { { ! type_kind . Ptype_record}[Ptype_record ] } ,
and [ manifest ] is [ None ] ,
- [ type t = T0 = { l : T ; ... } ]
when [ type_kind ] is { { ! type_kind . Ptype_record}[Ptype_record ] } ,
and [ manifest ] is [ Some T0 ] ,
- [ type t = .. ]
when [ type_kind ] is { { ! type_kind . Ptype_open}[Ptype_open ] } ,
and [ manifest ] is [ None ] .
Here are type declarations and their representation,
for various {{!type_declaration.ptype_kind}[ptype_kind]}
and {{!type_declaration.ptype_manifest}[ptype_manifest]} values:
- [type t] when [type_kind] is {{!type_kind.Ptype_abstract}[Ptype_abstract]},
and [manifest] is [None],
- [type t = T0]
when [type_kind] is {{!type_kind.Ptype_abstract}[Ptype_abstract]},
and [manifest] is [Some T0],
- [type t = C of T | ...]
when [type_kind] is {{!type_kind.Ptype_variant}[Ptype_variant]},
and [manifest] is [None],
- [type t = T0 = C of T | ...]
when [type_kind] is {{!type_kind.Ptype_variant}[Ptype_variant]},
and [manifest] is [Some T0],
- [type t = {l: T; ...}]
when [type_kind] is {{!type_kind.Ptype_record}[Ptype_record]},
and [manifest] is [None],
- [type t = T0 = {l : T; ...}]
when [type_kind] is {{!type_kind.Ptype_record}[Ptype_record]},
and [manifest] is [Some T0],
- [type t = ..]
when [type_kind] is {{!type_kind.Ptype_open}[Ptype_open]},
and [manifest] is [None].
*)
and type_kind =
| Ptype_abstract
| Ptype_variant of constructor_declaration list
| Ptype_open
and label_declaration =
{
pld_name: string loc;
pld_mutable: mutable_flag;
pld_type: core_type;
pld_loc: Location.t;
}
and constructor_declaration =
{
pcd_name: string loc;
pcd_vars: string loc list;
pcd_args: constructor_arguments;
pcd_res: core_type option;
pcd_loc: Location.t;
}
and constructor_arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label_declaration list
and type_extension =
{
ptyext_path: Longident.t loc;
ptyext_params: (core_type * (variance * injectivity)) list;
ptyext_constructors: extension_constructor list;
ptyext_private: private_flag;
ptyext_loc: Location.t;
* ... [ \@\@id1 ] [ \@\@id2 ]
}
and extension_constructor =
{
pext_name: string loc;
pext_kind: extension_constructor_kind;
pext_loc: Location.t;
}
and type_exception =
{
ptyexn_constructor : extension_constructor;
ptyexn_loc : Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and extension_constructor_kind =
| Pext_decl of string loc list * constructor_arguments * core_type option
* [ Pext_decl(existentials , , t_opt ) ]
describes a new extension constructor . It can be :
- [ C of T1 * ... * Tn ] when :
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ None ] } . }
- [ C : T0 ] when
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
- [ C : T1 * ... * Tn - > T0 ] when
{ ul { - [ existentials ] is [ [ ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
- [ C : ' a ... . T1 * ... * Tn - > T0 ] when
{ ul { - [ existentials ] is [ [ ' a ; ... ] ] , }
{ - [ c_args ] is [ [ T1 ; ... ; Tn ] ] , }
{ - [ t_opt ] is [ Some T0 ] . } }
describes a new extension constructor. It can be:
- [C of T1 * ... * Tn] when:
{ul {- [existentials] is [[]],}
{- [c_args] is [[T1; ...; Tn]],}
{- [t_opt] is [None]}.}
- [C: T0] when
{ul {- [existentials] is [[]],}
{- [c_args] is [[]],}
{- [t_opt] is [Some T0].}}
- [C: T1 * ... * Tn -> T0] when
{ul {- [existentials] is [[]],}
{- [c_args] is [[T1; ...; Tn]],}
{- [t_opt] is [Some T0].}}
- [C: 'a... . T1 * ... * Tn -> T0] when
{ul {- [existentials] is [['a;...]],}
{- [c_args] is [[T1; ... ; Tn]],}
{- [t_opt] is [Some T0].}}
*)
| Pext_rebind of Longident.t loc
* { 2 Type expressions for the class language }
and class_type =
{
pcty_desc: class_type_desc;
pcty_loc: Location.t;
}
and class_type_desc =
| Pcty_constr of Longident.t loc * core_type list
| Pcty_arrow of arg_label * core_type * class_type
and class_signature =
{
pcsig_self: core_type;
pcsig_fields: class_type_field list;
}
and class_type_field =
{
pctf_desc: class_type_field_desc;
pctf_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_type_field_desc =
| Pctf_val of (label loc * mutable_flag * virtual_flag * core_type)
* [ x : T ]
| Pctf_method of (label loc * private_flag * virtual_flag * core_type)
and 'a class_infos =
{
pci_virt: virtual_flag;
pci_params: (core_type * (variance * injectivity)) list;
pci_name: string loc;
pci_expr: 'a;
pci_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_description = class_type class_infos
and class_type_declaration = class_type class_infos
* { 2 Value expressions for the class language }
and class_expr =
{
pcl_desc: class_expr_desc;
pcl_loc: Location.t;
}
and class_expr_desc =
| Pcl_constr of Longident.t loc * core_type list
| Pcl_fun of arg_label * expression option * pattern * class_expr
* [ Pcl_fun(lbl , exp0 , P , CE ) ] represents :
- [ fun P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Nolabel}[Nolabel ] }
and [ exp0 ] is [ None ] ,
- [ fun ~l :P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Labelled}[Labelled l ] }
and [ exp0 ] is [ None ] ,
- [ fun ? l :P - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ None ] ,
- [ fun ? l:(P = E0 ) - > CE ]
when [ lbl ] is { { ! Asttypes.arg_label . Optional}[Optional l ] }
and [ exp0 ] is [ Some E0 ] .
- [fun P -> CE]
when [lbl] is {{!Asttypes.arg_label.Nolabel}[Nolabel]}
and [exp0] is [None],
- [fun ~l:P -> CE]
when [lbl] is {{!Asttypes.arg_label.Labelled}[Labelled l]}
and [exp0] is [None],
- [fun ?l:P -> CE]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [None],
- [fun ?l:(P = E0) -> CE]
when [lbl] is {{!Asttypes.arg_label.Optional}[Optional l]}
and [exp0] is [Some E0].
*)
| Pcl_apply of class_expr * (arg_label * expression) list
* [ Pcl_apply(CE , [ ( ) ; ... ; ( ln , En ) ] ) ]
represents [ CE ~l1 : E1 ... ~ln : En ] .
[ li ] can be empty ( non labeled argument ) or start with [ ? ]
( optional argument ) .
Invariant : [ n > 0 ]
represents [CE ~l1:E1 ... ~ln:En].
[li] can be empty (non labeled argument) or start with [?]
(optional argument).
Invariant: [n > 0]
*)
| Pcl_let of rec_flag * value_binding list * class_expr
and class_structure =
{
pcstr_self: pattern;
pcstr_fields: class_field list;
}
and class_field =
{
pcf_desc: class_field_desc;
pcf_loc: Location.t;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
}
and class_field_desc =
| Pcf_inherit of override_flag * class_expr * string loc option
* [ Pcf_inherit(flag , CE , s ) ] represents :
- [ inherit CE ]
when [ flag ] is { { ! . Fresh}[Fresh ] }
and [ s ] is [ None ] ,
- [ inherit CE as x ]
when [ flag ] is { { ! . Fresh}[Fresh ] }
and [ s ] is [ Some x ] ,
- [ inherit ! CE ]
when [ flag ] is { { ! . Override}[Override ] }
and [ s ] is [ None ] ,
- [ inherit ! CE as x ]
when [ flag ] is { { ! . Override}[Override ] }
and [ s ] is [ Some x ]
- [inherit CE]
when [flag] is {{!Asttypes.override_flag.Fresh}[Fresh]}
and [s] is [None],
- [inherit CE as x]
when [flag] is {{!Asttypes.override_flag.Fresh}[Fresh]}
and [s] is [Some x],
- [inherit! CE]
when [flag] is {{!Asttypes.override_flag.Override}[Override]}
and [s] is [None],
- [inherit! CE as x]
when [flag] is {{!Asttypes.override_flag.Override}[Override]}
and [s] is [Some x]
*)
| Pcf_val of (label loc * mutable_flag * class_field_kind)
| Pcf_method of (label loc * private_flag * class_field_kind)
and class_field_kind =
| Cfk_virtual of core_type
| Cfk_concrete of override_flag * expression
and class_declaration = class_expr class_infos
* { 2 Type expressions for the module language }
and module_type =
{
pmty_desc: module_type_desc;
pmty_loc: Location.t;
}
and module_type_desc =
| Pmty_functor of functor_parameter * module_type
* [ functor(X : ) - > MT2 ]
and functor_parameter =
| Named of string option loc * module_type
* [ Named(name , ) ] represents :
- [ ( X : MT ) ] when [ name ] is [ Some X ] ,
- [ ( _ : MT ) ] when [ name ] is [ None ]
- [(X : MT)] when [name] is [Some X],
- [(_ : MT)] when [name] is [None] *)
and signature = signature_item list
and signature_item =
{
psig_desc: signature_item_desc;
psig_loc: Location.t;
}
and signature_item_desc =
| Psig_value of value_description
| Psig_type of rec_flag * type_declaration list
* [ type t1 = ... and ... and = ... ]
| Psig_typesubst of type_declaration list
| Psig_recmodule of module_declaration list
* [ module rec X1 : and ... and Xn : MTn ]
| Psig_modtype of module_type_declaration
| Psig_modtypesubst of module_type_declaration
| Psig_class of class_description list
| Psig_class_type of class_type_declaration list
and module_declaration =
{
pmd_name: string option loc;
pmd_type: module_type;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pmd_loc: Location.t;
}
and module_substitution =
{
pms_name: string loc;
pms_manifest: Longident.t loc;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pms_loc: Location.t;
}
and module_type_declaration =
{
pmtd_name: string loc;
pmtd_type: module_type option;
* [ ... [ \@\@id1 ] [ \@\@id2 ] ]
pmtd_loc: Location.t;
}
and 'a open_infos =
{
popen_expr: 'a;
popen_override: override_flag;
popen_loc: Location.t;
popen_attributes: attributes;
}
* Values of type [ ' a open_infos ] represents :
- [ open ! X ] when { { ! open_infos.popen_override}[popen_override ] }
is { { ! . Override}[Override ] }
( silences the " used identifier shadowing " warning )
- [ open X ] when { { ! open_infos.popen_override}[popen_override ] }
is { { ! . Fresh}[Fresh ] }
- [open! X] when {{!open_infos.popen_override}[popen_override]}
is {{!Asttypes.override_flag.Override}[Override]}
(silences the "used identifier shadowing" warning)
- [open X] when {{!open_infos.popen_override}[popen_override]}
is {{!Asttypes.override_flag.Fresh}[Fresh]}
*)
and open_description = Longident.t loc open_infos
and open_declaration = module_expr open_infos
and 'a include_infos =
{
pincl_mod: 'a;
pincl_loc: Location.t;
pincl_attributes: attributes;
}
and include_description = module_type include_infos
and include_declaration = module_expr include_infos
and with_constraint =
| Pwith_type of Longident.t loc * type_declaration
| Pwith_module of Longident.t loc * Longident.t loc
| Pwith_modtype of Longident.t loc * module_type
| Pwith_modtypesubst of Longident.t loc * module_type
| Pwith_typesubst of Longident.t loc * type_declaration
| Pwith_modsubst of Longident.t loc * Longident.t loc
* { 2 Value expressions for the module language }
and module_expr =
{
pmod_desc: module_expr_desc;
pmod_loc: Location.t;
}
and module_expr_desc =
| Pmod_functor of functor_parameter * module_expr
* [ functor(X : ) - > ME ]
* [ ) ]
and structure = structure_item list
and structure_item =
{
pstr_desc: structure_item_desc;
pstr_loc: Location.t;
}
and structure_item_desc =
| Pstr_value of rec_flag * value_binding list
* [ Pstr_value(rec , [ ( P1 , E1 ; ... ; ( Pn , En ) ) ] ) ] represents :
- [ let P1 = E1 and ... and Pn = EN ]
when [ rec ] is { { ! Asttypes.rec_flag . Nonrecursive}[Nonrecursive ] } ,
- [ let rec P1 = E1 and ... and Pn = EN ]
when [ rec ] is { { ! Asttypes.rec_flag . Recursive}[Recursive ] } .
- [let P1 = E1 and ... and Pn = EN]
when [rec] is {{!Asttypes.rec_flag.Nonrecursive}[Nonrecursive]},
- [let rec P1 = E1 and ... and Pn = EN ]
when [rec] is {{!Asttypes.rec_flag.Recursive}[Recursive]}.
*)
| Pstr_primitive of value_description
| Pstr_type of rec_flag * type_declaration list
| Pstr_exception of type_exception
| Pstr_recmodule of module_binding list
| Pstr_class of class_declaration list
| Pstr_class_type of class_type_declaration list
and value_binding =
{
pvb_pat: pattern;
pvb_expr: expression;
pvb_attributes: attributes;
pvb_loc: Location.t;
}
and module_binding =
{
pmb_name: string option loc;
pmb_expr: module_expr;
pmb_attributes: attributes;
pmb_loc: Location.t;
}
* { 1 Toplevel }
* { 2 Toplevel phrases }
type toplevel_phrase =
| Ptop_def of structure
and toplevel_directive =
{
pdir_name: string loc;
pdir_arg: directive_argument option;
pdir_loc: Location.t;
}
and directive_argument =
{
pdira_desc: directive_argument_desc;
pdira_loc: Location.t;
}
and directive_argument_desc =
| Pdir_string of string
| Pdir_int of string * char option
| Pdir_ident of Longident.t
| Pdir_bool of bool
|
30f91c7f4542a6d53b9b5e790aa2cd2aca9f83969209ead62b9aa9b139e6929e
|
spell-music/amsterdam
|
Decay.hs
|
| This instrument is derived from Risset 's Linear and Exponential Decay Experiments .
The object of the comparison here are two types of decay and four different durations :
middle ( 2 sec ) , long ( 4 sec ) , short ( 1 sec ) and shorter ( .5 sec ) .
Linear decay seems to occur slowly at first and then suddenly disappears ;
exponential decay is more even and gives a resonance impression .
To avoid cutoff during exponential decay , one has to ensure that the amplitude controlling
function decays to a final value not smaller than the inverse of the maximum amplitude .
When the absolute amplitude becomes smaller than 1 , the sound is lost in the quantizing noise .
For instance , if the maximum amplitude is 8000 , one should have a function
decaying to 2(**-13)=1/8192 . ( Risset 1969 : # 300 )
The object of the comparison here are two types of decay and four different durations:
middle (2 sec), long (4 sec), short (1 sec) and shorter (.5 sec).
Linear decay seems to occur slowly at first and then suddenly disappears;
exponential decay is more even and gives a resonance impression.
To avoid cutoff during exponential decay, one has to ensure that the amplitude controlling
function decays to a final value not smaller than the inverse of the maximum amplitude.
When the absolute amplitude becomes smaller than 1, the sound is lost in the quantizing noise.
For instance, if the maximum amplitude is 8000, one should have a function
decaying to 2(**-13)=1/8192. (Risset 1969: #300)
-}
module Decay where
import Csound
instr :: (D, D, Tab, Tab) -> Sig
instr (amp, cps, wave, env) = once env * oscili (sig amp) (sig cps) wave
envelopes = [
elins [1, 0],
guardPoint $ eexps [8192, 1]]
waves = fmap sines [
[1, 0.5, 0.3, 0.2, 0.15, 0.12],
[1, 0.2, 0.05]]
durs = [2, 4, 1, 0.5]
amp = 0.5
cps = 440
res = sco instr $ line [ delay 1 $ d *| temp (amp, cps, w, e) | w <- waves, d <- durs, e <- envelopes ]
main = dac $ runMix res
| null |
https://raw.githubusercontent.com/spell-music/amsterdam/ab491022c7826c74eab557ecd11794268f5a5ae0/01-basic-instruments/Decay.hs
|
haskell
|
| This instrument is derived from Risset 's Linear and Exponential Decay Experiments .
The object of the comparison here are two types of decay and four different durations :
middle ( 2 sec ) , long ( 4 sec ) , short ( 1 sec ) and shorter ( .5 sec ) .
Linear decay seems to occur slowly at first and then suddenly disappears ;
exponential decay is more even and gives a resonance impression .
To avoid cutoff during exponential decay , one has to ensure that the amplitude controlling
function decays to a final value not smaller than the inverse of the maximum amplitude .
When the absolute amplitude becomes smaller than 1 , the sound is lost in the quantizing noise .
For instance , if the maximum amplitude is 8000 , one should have a function
decaying to 2(**-13)=1/8192 . ( Risset 1969 : # 300 )
The object of the comparison here are two types of decay and four different durations:
middle (2 sec), long (4 sec), short (1 sec) and shorter (.5 sec).
Linear decay seems to occur slowly at first and then suddenly disappears;
exponential decay is more even and gives a resonance impression.
To avoid cutoff during exponential decay, one has to ensure that the amplitude controlling
function decays to a final value not smaller than the inverse of the maximum amplitude.
When the absolute amplitude becomes smaller than 1, the sound is lost in the quantizing noise.
For instance, if the maximum amplitude is 8000, one should have a function
decaying to 2(**-13)=1/8192. (Risset 1969: #300)
-}
module Decay where
import Csound
instr :: (D, D, Tab, Tab) -> Sig
instr (amp, cps, wave, env) = once env * oscili (sig amp) (sig cps) wave
envelopes = [
elins [1, 0],
guardPoint $ eexps [8192, 1]]
waves = fmap sines [
[1, 0.5, 0.3, 0.2, 0.15, 0.12],
[1, 0.2, 0.05]]
durs = [2, 4, 1, 0.5]
amp = 0.5
cps = 440
res = sco instr $ line [ delay 1 $ d *| temp (amp, cps, w, e) | w <- waves, d <- durs, e <- envelopes ]
main = dac $ runMix res
|
|
5e30bbdc6faca48d9843f3d51e5e3e07d5cd335adf084f30ed8ea17a735e3a72
|
ekmett/intern
|
IntSet.hs
|
# LANGUAGE MagicHash , TypeFamilies , FlexibleInstances , BangPatterns , CPP #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Interned.IntSet
Copyright : ( c ) 2002
( c ) 2011
-- License : BSD-style
-- Maintainer :
-- Stability : provisional
Portability : non - portable ( TypeFamilies , MagicHash )
--
-- An efficient implementation of integer sets.
--
-- Since many function names (but not the type name) clash with
" Prelude " names , this module is usually imported @qualified@ , e.g.
--
> import Data . IntSet ( )
> import qualified Data . IntSet as
--
-- The implementation is based on /big-endian patricia trees/. This data
-- structure performs especially well on binary operations like 'union'
-- and 'intersection'. However, my benchmarks show that it is also
-- (much) faster on insertions and deletions when compared to a generic
-- size-balanced set implementation (see "Data.Set").
--
* and , \"/Fast Maps/\ " ,
Workshop on ML , September 1998 , pages 77 - 86 ,
-- <>
--
* , -- Practical Algorithm To Retrieve
Information Coded In Alphanumeric/\ " , Journal of the ACM , 15(4 ) ,
October 1968 , pages 514 - 534 .
--
Many operations have a worst - case complexity of /O(min(n , W))/.
-- This means that the operation can become linear in the number of
-- elements with a maximum of /W/ -- the number of bits in an 'Int'
( 32 or 64 ) .
--
-- Unlike the reference implementation in Data.IntSet, Data.Interned.IntSet
uses hash consing to ensure that there is only ever one copy of any given
IntSet in memory . This is enabled by the normal form of the PATRICIA trie .
--
-- This can mean a drastic reduction in the memory footprint of a program
-- in exchange for much more costly set manipulation.
--
-----------------------------------------------------------------------------
module Data.Interned.IntSet (
-- * Set type
instance Eq , Show
, identity
-- * Operators
, (\\)
-- * Query
, null
, size
, member
, notMember
, isSubsetOf
, isProperSubsetOf
-- * Construction
, empty
, singleton
, insert
, delete
-- * Combine
, union, unions
, difference
, intersection
-- * Filter
, filter
, partition
, split
, splitMember
*
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, maxView
, minView
-- * Map
, map
-- * Fold
, fold
-- * Conversion
-- ** List
, elems
, toList
, fromList
-- ** Ordered list
, toAscList
, fromAscList
, fromDistinctAscList
-- * Debugging
, showTree
, showTreeWith
) where
import Prelude hiding (lookup,filter,foldr,foldl,null,map)
import qualified Data.List as List
import Data.Maybe (fromMaybe)
import Data.Interned.Internal
import Data.Bits
import Data.Hashable
import Text.Read
import GHC.Exts ( Word(..), Int(..), shiftRL# )
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (Monoid(..))
#endif
#if MIN_VERSION_base(4,9,0) && !(MIN_VERSION_base(4,11,0))
import Data.Semigroup (Semigroup(..))
#endif
import Data . Typeable
import Data . Data ( Data ( .. ) , mkNoRepType )
This comment teaches CPP correct behaviour
A " " is a natural machine word ( an unsigned Int )
type Nat = Word
natFromInt :: Int -> Nat
natFromInt i = fromIntegral i
intFromNat :: Nat -> Int
intFromNat w = fromIntegral w
shiftRL :: Nat -> Int -> Nat
shiftRL (W# x) (I# i) = W# (shiftRL# x i)
-------------------------------------------------------------------
Operators
-------------------------------------------------------------------
Operators
--------------------------------------------------------------------}
-- | /O(n+m)/. See 'difference'.
(\\) :: IntSet -> IntSet -> IntSet
m1 \\ m2 = difference m1 m2
{--------------------------------------------------------------------
Types
--------------------------------------------------------------------}
-- | A set of integers.
data IntSet
= Nil
| Tip {-# UNPACK #-} !Id {-# UNPACK #-} !Int
| Bin {-# UNPACK #-} !Id {-# UNPACK #-} !Int {-# UNPACK #-} !Prefix {-# UNPACK #-} !Mask !IntSet !IntSet
Invariant : Nil is never found as a child of .
Invariant : The Mask is a power of 2 . It is the largest bit position at which
two elements of the set differ .
-- Invariant: Prefix is the common high-order bits that all elements share to
-- the left of the Mask bit.
Invariant : In prefix mask left right , left consists of the elements that
-- don't have the mask bit set; right is all the elements that do.
data UninternedIntSet
= UNil
| UTip !Int
| UBin {-# UNPACK #-} !Prefix {-# UNPACK #-} !Mask !IntSet !IntSet
tip :: Int -> IntSet
tip n = intern (UTip n)
{--------------------------------------------------------------------
@bin@ assures that we never have empty trees within a tree.
--------------------------------------------------------------------}
bin :: Prefix -> Mask -> IntSet -> IntSet -> IntSet
bin _ _ l Nil = l
bin _ _ Nil r = r
bin p m l r = intern (UBin p m l r)
bin_ :: Prefix -> Mask -> IntSet -> IntSet -> IntSet
bin_ p m l r = intern (UBin p m l r)
-- | A unique integer ID associated with each interned set.
identity :: IntSet -> Id
identity Nil = 0
identity (Tip i _) = i
identity (Bin i _ _ _ _ _) = i
instance Interned IntSet where
type Uninterned IntSet = UninternedIntSet
data Description IntSet
= DNil
| DTip {-# UNPACK #-} !Int
| DBin {-# UNPACK #-} !Prefix {-# UNPACK #-} !Mask {-# UNPACK #-} !Id {-# UNPACK #-} !Id
deriving Eq
describe UNil = DNil
describe (UTip j) = DTip j
describe (UBin p m l r) = DBin p m (identity l) (identity r)
cacheWidth _ = 16384 -- a huge cache width!
seedIdentity _ = 1
identify _ UNil = Nil
identify i (UTip j) = Tip i j
identify i (UBin p m l r) = Bin i (size l + size r) p m l r
cache = intSetCache
instance Hashable (Description IntSet) where
hashWithSalt s DNil = s `hashWithSalt` (0 :: Int)
hashWithSalt s (DTip n) = s `hashWithSalt` (1 :: Int) `hashWithSalt` n
hashWithSalt s (DBin p m l r) = s `hashWithSalt` (2 :: Int) `hashWithSalt` p `hashWithSalt` m `hashWithSalt` l `hashWithSalt` r
intSetCache :: Cache IntSet
intSetCache = mkCache
# NOINLINE intSetCache #
instance Uninternable IntSet where
unintern Nil = UNil
unintern (Tip _ j) = UTip j
unintern (Bin _ _ p m l r) = UBin p m l r
type Prefix = Int
type Mask = Int
#if MIN_VERSION_base(4,9,0)
instance Semigroup IntSet where
(<>) = union
#endif
instance Monoid IntSet where
mempty = empty
#if !(MIN_VERSION_base(4,11,0))
mappend = union
#endif
mconcat = unions
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | /O(1)/. Is the set empty?
null :: IntSet -> Bool
null Nil = True
null _ = False
-- | /O(1)/. Cardinality of the set.
size :: IntSet -> Int
size t
= case t of
Bin _ s _ _ _ _ -> s
Tip _ _ -> 1
Nil -> 0
-- | /O(min(n,W))/. Is the value a member of the set?
member :: Int -> IntSet -> Bool
member x t
= case t of
Bin _ _ p m l r
| nomatch x p m -> False
| zero x m -> member x l
| otherwise -> member x r
Tip _ y -> (x==y)
Nil -> False
-- | /O(min(n,W))/. Is the element not in the set?
notMember :: Int -> IntSet -> Bool
notMember k = not . member k
-- 'lookup' is used by 'intersection' for left-biasing
lookup :: Int -> IntSet -> Maybe Int
lookup k t
= let nk = natFromInt k in seq nk (lookupN nk t)
lookupN :: Nat -> IntSet -> Maybe Int
lookupN k t
= case t of
Bin _ _ _ m l r
| zeroN k (natFromInt m) -> lookupN k l
| otherwise -> lookupN k r
Tip _ kx
| (k == natFromInt kx) -> Just kx
| otherwise -> Nothing
Nil -> Nothing
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | /O(1)/. The empty set.
empty :: IntSet
empty = Nil
| /O(1)/. A set of one element .
singleton :: Int -> IntSet
singleton x = tip x
{--------------------------------------------------------------------
Insert
--------------------------------------------------------------------}
-- | /O(min(n,W))/. Add a value to the set. When the value is already
-- an element of the set, it is replaced by the new one, ie. 'insert'
-- is left-biased.
insert :: Int -> IntSet -> IntSet
insert x t
= case t of
Bin _ _ p m l r
| nomatch x p m -> join x (tip x) p t
| zero x m -> bin_ p m (insert x l) r
| otherwise -> bin_ p m l (insert x r)
Tip _ y
| x==y -> tip x
| otherwise -> join x (tip x) y t
Nil -> tip x
-- right-biased insertion, used by 'union'
insertR :: Int -> IntSet -> IntSet
insertR x t
= case t of
Bin _ _ p m l r
| nomatch x p m -> join x (tip x) p t
| zero x m -> bin_ p m (insert x l) r
| otherwise -> bin_ p m l (insert x r)
Tip _ y
| x==y -> t
| otherwise -> join x (tip x) y t
Nil -> tip x
-- | /O(min(n,W))/. Delete a value in the set. Returns the
-- original set when the value was not present.
delete :: Int -> IntSet -> IntSet
delete x t
= case t of
Bin _ _ p m l r
| nomatch x p m -> t
| zero x m -> bin p m (delete x l) r
| otherwise -> bin p m l (delete x r)
Tip _ y
| x==y -> Nil
| otherwise -> t
Nil -> Nil
{--------------------------------------------------------------------
Union
--------------------------------------------------------------------}
-- | The union of a list of sets.
unions :: [IntSet] -> IntSet
unions xs = foldlStrict union empty xs
| /O(n+m)/. The union of two sets .
union :: IntSet -> IntSet -> IntSet
union t1@(Bin _ _ p1 m1 l1 r1) t2@(Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = union1
| shorter m2 m1 = union2
| p1 == p2 = bin_ p1 m1 (union l1 l2) (union r1 r2)
| otherwise = join p1 t1 p2 t2
where
union1 | nomatch p2 p1 m1 = join p1 t1 p2 t2
| zero p2 m1 = bin_ p1 m1 (union l1 t2) r1
| otherwise = bin_ p1 m1 l1 (union r1 t2)
union2 | nomatch p1 p2 m2 = join p1 t1 p2 t2
| zero p1 m2 = bin_ p2 m2 (union t1 l2) r2
| otherwise = bin_ p2 m2 l2 (union t1 r2)
union (Tip _ x) t = insert x t
union t (Tip _ x) = insertR x t -- right bias
union Nil t = t
union t Nil = t
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
| /O(n+m)/. Difference between two sets .
difference :: IntSet -> IntSet -> IntSet
difference t1@(Bin _ _ p1 m1 l1 r1) t2@(Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = difference1
| shorter m2 m1 = difference2
| p1 == p2 = bin p1 m1 (difference l1 l2) (difference r1 r2)
| otherwise = t1
where
difference1 | nomatch p2 p1 m1 = t1
| zero p2 m1 = bin p1 m1 (difference l1 t2) r1
| otherwise = bin p1 m1 l1 (difference r1 t2)
difference2 | nomatch p1 p2 m2 = t1
| zero p1 m2 = difference t1 l2
| otherwise = difference t1 r2
difference t1@(Tip _ x) t2
| member x t2 = Nil
| otherwise = t1
difference Nil _ = Nil
difference t (Tip _ x) = delete x t
difference t Nil = t
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
| /O(n+m)/. The intersection of two sets .
intersection :: IntSet -> IntSet -> IntSet
intersection t1@(Bin _ _ p1 m1 l1 r1) t2@(Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = intersection1
| shorter m2 m1 = intersection2
| p1 == p2 = bin p1 m1 (intersection l1 l2) (intersection r1 r2)
| otherwise = Nil
where
intersection1 | nomatch p2 p1 m1 = Nil
| zero p2 m1 = intersection l1 t2
| otherwise = intersection r1 t2
intersection2 | nomatch p1 p2 m2 = Nil
| zero p1 m2 = intersection t1 l2
| otherwise = intersection t1 r2
intersection t1@(Tip _ x) t2
| member x t2 = t1
| otherwise = Nil
intersection t (Tip _ x)
= case lookup x t of
Just y -> tip y
Nothing -> Nil
intersection Nil _ = Nil
intersection _ Nil = Nil
{--------------------------------------------------------------------
Subset
--------------------------------------------------------------------}
| /O(n+m)/. Is this a proper subset ? ( ie . a subset but not equal ) .
isProperSubsetOf :: IntSet -> IntSet -> Bool
isProperSubsetOf t1 t2
= case subsetCmp t1 t2 of
LT -> True
_ -> False
subsetCmp :: IntSet -> IntSet -> Ordering
subsetCmp t1@(Bin _ _ p1 m1 l1 r1) (Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = GT
| shorter m2 m1 = case subsetCmpLt of
GT -> GT
_ -> LT
| p1 == p2 = subsetCmpEq
| otherwise = GT -- disjoint
where
subsetCmpLt | nomatch p1 p2 m2 = GT
| zero p1 m2 = subsetCmp t1 l2
| otherwise = subsetCmp t1 r2
subsetCmpEq = case (subsetCmp l1 l2, subsetCmp r1 r2) of
(GT,_ ) -> GT
(_ ,GT) -> GT
(EQ,EQ) -> EQ
_ -> LT
subsetCmp (Bin _ _ _ _ _ _) _ = GT
subsetCmp (Tip _ x) (Tip _ y)
| x==y = EQ
| otherwise = GT -- disjoint
subsetCmp (Tip _ x) t
| member x t = LT
| otherwise = GT -- disjoint
subsetCmp Nil Nil = EQ
subsetCmp Nil _ = LT
| /O(n+m)/. Is this a subset ?
@(s1 ` isSubsetOf ` tells whether @s1@ is a subset of @s2@.
isSubsetOf :: IntSet -> IntSet -> Bool
isSubsetOf t1@(Bin _ _ p1 m1 l1 r1) (Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = False
| shorter m2 m1 = match p1 p2 m2 && (if zero p1 m2 then isSubsetOf t1 l2
else isSubsetOf t1 r2)
| otherwise = (p1==p2) && isSubsetOf l1 l2 && isSubsetOf r1 r2
isSubsetOf (Bin _ _ _ _ _ _) _ = False
isSubsetOf (Tip _ x) t = member x t
isSubsetOf Nil _ = True
{--------------------------------------------------------------------
Filter
--------------------------------------------------------------------}
-- | /O(n)/. Filter all elements that satisfy some predicate.
filter :: (Int -> Bool) -> IntSet -> IntSet
filter predicate t
= case t of
Bin _ _ p m l r
-> bin p m (filter predicate l) (filter predicate r)
Tip _ x
| predicate x -> t
| otherwise -> Nil
Nil -> Nil
-- | /O(n)/. partition the set according to some predicate.
partition :: (Int -> Bool) -> IntSet -> (IntSet,IntSet)
partition predicate t
= case t of
Bin _ _ p m l r
-> let (l1,l2) = partition predicate l
(r1,r2) = partition predicate r
in (bin p m l1 r1, bin p m l2 r2)
Tip _ x
| predicate x -> (t,Nil)
| otherwise -> (Nil,t)
Nil -> (Nil,Nil)
-- | /O(min(n,W))/. The expression (@'split' x set@) is a pair @(set1,set2)@
where @set1@ comprises the elements of @set@ less than @x@ and @set2@
comprises the elements of @set@ greater than @x@.
--
> split 3 ( fromList [ 1 .. 5 ] ) = = ( fromList [ 1,2 ] , fromList [ 4,5 ] )
split :: Int -> IntSet -> (IntSet,IntSet)
split x t
= case t of
Bin _ _ _ m l r
| m < 0 -> if x >= 0 then let (lt,gt) = split' x l in (union r lt, gt)
else let (lt,gt) = split' x r in (lt, union gt l)
-- handle negative numbers.
| otherwise -> split' x t
Tip _ y
| x>y -> (t,Nil)
| x<y -> (Nil,t)
| otherwise -> (Nil,Nil)
Nil -> (Nil, Nil)
split' :: Int -> IntSet -> (IntSet,IntSet)
split' x t
= case t of
Bin _ _ p m l r
| match x p m -> if zero x m then let (lt,gt) = split' x l in (lt,union gt r)
else let (lt,gt) = split' x r in (union l lt,gt)
| otherwise -> if x < p then (Nil, t)
else (t, Nil)
Tip _ y
| x>y -> (t,Nil)
| x<y -> (Nil,t)
| otherwise -> (Nil,Nil)
Nil -> (Nil,Nil)
-- | /O(min(n,W))/. Performs a 'split' but also returns whether the pivot
-- element was found in the original set.
splitMember :: Int -> IntSet -> (IntSet,Bool,IntSet)
splitMember x t
= case t of
Bin _ _ _ m l r
| m < 0 -> if x >= 0 then let (lt,found,gt) = splitMember' x l in (union r lt, found, gt)
else let (lt,found,gt) = splitMember' x r in (lt, found, union gt l)
-- handle negative numbers.
| otherwise -> splitMember' x t
Tip _ y
| x>y -> (t,False,Nil)
| x<y -> (Nil,False,t)
| otherwise -> (Nil,True,Nil)
Nil -> (Nil,False,Nil)
splitMember' :: Int -> IntSet -> (IntSet,Bool,IntSet)
splitMember' x t
= case t of
Bin _ _ p m l r
| match x p m -> if zero x m then let (lt,found,gt) = splitMember x l in (lt,found,union gt r)
else let (lt,found,gt) = splitMember x r in (union l lt,found,gt)
| otherwise -> if x < p then (Nil, False, t)
else (t, False, Nil)
Tip _ y
| x>y -> (t,False,Nil)
| x<y -> (Nil,False,t)
| otherwise -> (Nil,True,Nil)
Nil -> (Nil,False,Nil)
---------------------------------------------------------------------
Min /
---------------------------------------------------------------------
Min/Max
----------------------------------------------------------------------}
-- | /O(min(n,W))/. Retrieves the maximal key of the set, and the set
-- stripped of that element, or 'Nothing' if passed an empty set.
maxView :: IntSet -> Maybe (Int, IntSet)
maxView t
= case t of
Bin _ _ p m l r | m < 0 -> let (result,t') = maxViewUnsigned l in Just (result, bin p m t' r)
Bin _ _ p m l r -> let (result,t') = maxViewUnsigned r in Just (result, bin p m l t')
Tip _ y -> Just (y,Nil)
Nil -> Nothing
maxViewUnsigned :: IntSet -> (Int, IntSet)
maxViewUnsigned t
= case t of
Bin _ _ p m l r -> let (result,t') = maxViewUnsigned r in (result, bin p m l t')
Tip _ y -> (y, Nil)
Nil -> error "maxViewUnsigned Nil"
-- | /O(min(n,W))/. Retrieves the minimal key of the set, and the set
-- stripped of that element, or 'Nothing' if passed an empty set.
minView :: IntSet -> Maybe (Int, IntSet)
minView t
= case t of
Bin _ _ p m l r | m < 0 -> let (result,t') = minViewUnsigned r in Just (result, bin p m l t')
Bin _ _ p m l r -> let (result,t') = minViewUnsigned l in Just (result, bin p m t' r)
Tip _ y -> Just (y, Nil)
Nil -> Nothing
minViewUnsigned :: IntSet -> (Int, IntSet)
minViewUnsigned t
= case t of
Bin _ _ p m l r -> let (result,t') = minViewUnsigned l in (result, bin p m t' r)
Tip _ y -> (y, Nil)
Nil -> error "minViewUnsigned Nil"
-- | /O(min(n,W))/. Delete and find the minimal element.
--
-- > deleteFindMin set = (findMin set, deleteMin set)
deleteFindMin :: IntSet -> (Int, IntSet)
deleteFindMin = fromMaybe (error "deleteFindMin: empty set has no minimal element") . minView
-- | /O(min(n,W))/. Delete and find the maximal element.
--
> set = ( set , deleteMax set )
deleteFindMax :: IntSet -> (Int, IntSet)
deleteFindMax = fromMaybe (error "deleteFindMax: empty set has no maximal element") . maxView
-- | /O(min(n,W))/. The minimal element of the set.
findMin :: IntSet -> Int
findMin Nil = error "findMin: empty set has no minimal element"
findMin (Tip _ x) = x
findMin (Bin _ _ _ m l r)
| m < 0 = find r
| otherwise = find l
where find (Tip _ x) = x
find (Bin _ _ _ _ l' _) = find l'
find Nil = error "findMin Nil"
-- | /O(min(n,W))/. The maximal element of a set.
findMax :: IntSet -> Int
findMax Nil = error "findMax: empty set has no maximal element"
findMax (Tip _ x) = x
findMax (Bin _ _ _ m l r)
| m < 0 = find l
| otherwise = find r
where find (Tip _ x) = x
find (Bin _ _ _ _ _ r') = find r'
find Nil = error "findMax Nil"
-- | /O(min(n,W))/. Delete the minimal element.
deleteMin :: IntSet -> IntSet
deleteMin = maybe (error "deleteMin: empty set has no minimal element") snd . minView
-- | /O(min(n,W))/. Delete the maximal element.
deleteMax :: IntSet -> IntSet
deleteMax = maybe (error "deleteMax: empty set has no maximal element") snd . maxView
{----------------------------------------------------------------------
Map
----------------------------------------------------------------------}
-- | /O(n*min(n,W))/.
@'map ' f s@ is the set obtained by applying @f@ to each element of @s@.
--
-- It's worth noting that the size of the result may be smaller if,
for some @(x , y)@ , @x \/= y & & f x = = f y@
map :: (Int->Int) -> IntSet -> IntSet
map f = fromList . List.map f . toList
-------------------------------------------------------------------
Fold
-------------------------------------------------------------------
Fold
--------------------------------------------------------------------}
-- | /O(n)/. Fold over the elements of a set in an unspecified order.
--
> sum set = = fold ( + ) 0 set
> elems set = = fold ( :) [ ] set
fold :: (Int -> b -> b) -> b -> IntSet -> b
fold f z t
= case t of
Bin _ _ 0 m l r | m < 0 -> foldr f (foldr f z l) r
-- put negative numbers before.
Bin _ _ _ _ _ _ -> foldr f z t
Tip _ x -> f x z
Nil -> z
foldr :: (Int -> b -> b) -> b -> IntSet -> b
foldr f z t
= case t of
Bin _ _ _ _ l r -> foldr f (foldr f z r) l
Tip _ x -> f x z
Nil -> z
{--------------------------------------------------------------------
List variations
--------------------------------------------------------------------}
-- | /O(n)/. The elements of a set. (For sets, this is equivalent to toList)
elems :: IntSet -> [Int]
elems s = toList s
{--------------------------------------------------------------------
Lists
--------------------------------------------------------------------}
-- | /O(n)/. Convert the set to a list of elements.
toList :: IntSet -> [Int]
toList t = fold (:) [] t
-- | /O(n)/. Convert the set to an ascending list of elements.
toAscList :: IntSet -> [Int]
toAscList t = toList t
| /O(n*min(n , W))/. Create a set from a list of integers .
fromList :: [Int] -> IntSet
fromList xs = foldlStrict ins empty xs
where
ins t x = insert x t
-- | /O(n)/. Build a set from an ascending list of elements.
/The precondition ( input list is ascending ) is not checked./
fromAscList :: [Int] -> IntSet
fromAscList [] = Nil
fromAscList (x0 : xs0) = fromDistinctAscList (combineEq x0 xs0)
where
combineEq x' [] = [x']
combineEq x' (x:xs)
| x==x' = combineEq x' xs
| otherwise = x' : combineEq x xs
-- | /O(n)/. Build a set from an ascending list of distinct elements.
/The precondition ( input list is strictly ascending ) is not checked./
fromDistinctAscList :: [Int] -> IntSet
fromDistinctAscList [] = Nil
fromDistinctAscList (z0 : zs0) = work z0 zs0 Nada
where
work x [] stk = finish x (tip x) stk
work x (z:zs) stk = reduce z zs (branchMask z x) x (tip x) stk
reduce z zs _ px tx Nada = work z zs (Push px tx Nada)
reduce z zs m px tx stk@(Push py ty stk') =
let mxy = branchMask px py
pxy = mask px mxy
in if shorter m mxy
then reduce z zs m pxy (bin_ pxy mxy ty tx) stk'
else work z zs (Push px tx stk)
finish _ t Nada = t
finish px tx (Push py ty stk) = finish p (join py ty px tx) stk
where m = branchMask px py
p = mask px m
data Stack = Push {-# UNPACK #-} !Prefix !IntSet !Stack | Nada
{--------------------------------------------------------------------
Debugging
--------------------------------------------------------------------}
-- | /O(n)/. Show the tree that implements the set. The tree is shown
-- in a compressed, hanging format.
showTree :: IntSet -> String
showTree s
= showTreeWith True False s
| /O(n)/. The expression ( @'showTreeWith ' hang wide map@ ) shows
the tree that implements the set . If @hang@ is
' True ' , a /hanging/ tree is shown otherwise a rotated tree is shown . If
@wide@ is ' True ' , an extra wide version is shown .
the tree that implements the set. If @hang@ is
'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
@wide@ is 'True', an extra wide version is shown.
-}
showTreeWith :: Bool -> Bool -> IntSet -> String
showTreeWith hang wide t
| hang = (showsTreeHang wide [] t) ""
| otherwise = (showsTree wide [] [] t) ""
showsTree :: Bool -> [String] -> [String] -> IntSet -> ShowS
showsTree wide lbars rbars t
= case t of
Bin _ _ p m l r
-> showsTree wide (withBar rbars) (withEmpty rbars) r .
showWide wide rbars .
showsBars lbars . showString (showBin p m) . showString "\n" .
showWide wide lbars .
showsTree wide (withEmpty lbars) (withBar lbars) l
Tip _ x
-> showsBars lbars . showString " " . shows x . showString "\n"
Nil -> showsBars lbars . showString "|\n"
showsTreeHang :: Bool -> [String] -> IntSet -> ShowS
showsTreeHang wide bars t
= case t of
Bin _ _ p m l r
-> showsBars bars . showString (showBin p m) . showString "\n" .
showWide wide bars .
showsTreeHang wide (withBar bars) l .
showWide wide bars .
showsTreeHang wide (withEmpty bars) r
Tip _ x
-> showsBars bars . showString " " . shows x . showString "\n"
Nil -> showsBars bars . showString "|\n"
showBin :: Prefix -> Mask -> String
showBin _ _
= "*" -- ++ show (p,m)
showWide :: Bool -> [String] -> String -> String
showWide wide bars
| wide = showString (concat (reverse bars)) . showString "|\n"
| otherwise = id
showsBars :: [String] -> ShowS
showsBars bars
= case bars of
[] -> id
_ -> showString (concat (reverse (tail bars))) . showString node
node :: String
node = "+--"
withBar, withEmpty :: [String] -> [String]
withBar bars = "| ":bars
withEmpty bars = " ":bars
-------------------------------------------------------------------
Eq
-------------------------------------------------------------------
Eq
--------------------------------------------------------------------}
-- /O(1)/
instance Eq IntSet where
Nil == Nil = True
Tip i _ == Tip j _ = i == j
Bin i _ _ _ _ _ == Bin j _ _ _ _ _ = i == j
_ == _ = False
{--------------------------------------------------------------------
Ord
NB: this ordering is not the ordering implied by the elements
but is usable for comparison
--------------------------------------------------------------------}
instance Ord IntSet where
Nil `compare` Nil = EQ
Nil `compare` Tip _ _ = LT
Nil `compare` Bin _ _ _ _ _ _ = LT
Tip _ _ `compare` Nil = GT
Tip i _ `compare` Tip j _ = compare i j
Tip i _ `compare` Bin j _ _ _ _ _ = compare i j
Bin _ _ _ _ _ _ `compare` Nil = GT
Bin i _ _ _ _ _ `compare` Tip j _ = compare i j
Bin i _ _ _ _ _ `compare` Bin j _ _ _ _ _ = compare i j
-- compare s1 s2 = compare (toAscList s1) (toAscList s2)
{--------------------------------------------------------------------
Show
--------------------------------------------------------------------}
instance Show IntSet where
showsPrec p xs = showParen (p > 10) $
showString "fromList " . shows (toList xs)
-------------------------------------------------------------------
Hashable
-------------------------------------------------------------------
Hashable
--------------------------------------------------------------------}
instance Hashable IntSet where
hashWithSalt s x = hashWithSalt s $ identity x
{--------------------------------------------------------------------
Read
--------------------------------------------------------------------}
instance Read IntSet where
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
{--------------------------------------------------------------------
Helpers
--------------------------------------------------------------------}
{--------------------------------------------------------------------
Join
--------------------------------------------------------------------}
join :: Prefix -> IntSet -> Prefix -> IntSet -> IntSet
join p1 t1 p2 t2
| zero p1 m = bin_ p m t1 t2
| otherwise = bin_ p m t2 t1
where
m = branchMask p1 p2
p = mask p1 m
-------------------------------------------------------------------
Endian independent bit twiddling
-------------------------------------------------------------------
Endian independent bit twiddling
--------------------------------------------------------------------}
zero :: Int -> Mask -> Bool
zero i m
= (natFromInt i) .&. (natFromInt m) == 0
nomatch,match :: Int -> Prefix -> Mask -> Bool
nomatch i p m
= (mask i m) /= p
match i p m
= (mask i m) == p
Suppose a is largest such that 2^a divides 2*m .
-- Then mask i m is i with the low a bits zeroed out.
mask :: Int -> Mask -> Prefix
mask i m
= maskW (natFromInt i) (natFromInt m)
zeroN :: Nat -> Nat -> Bool
zeroN i m = (i .&. m) == 0
{--------------------------------------------------------------------
Big endian operations
--------------------------------------------------------------------}
maskW :: Nat -> Nat -> Prefix
maskW i m
= intFromNat (i .&. (complement (m-1) `xor` m))
shorter :: Mask -> Mask -> Bool
shorter m1 m2
= (natFromInt m1) > (natFromInt m2)
branchMask :: Prefix -> Prefix -> Mask
branchMask p1 p2
= intFromNat (highestBitMask (natFromInt p1 `xor` natFromInt p2))
---------------------------------------------------------------------
Finding the highest bit ( mask ) in a word [ x ] can be done efficiently in
three ways :
* convert to a floating point value and the mantissa tells us the
[ log2(x ) ] that corresponds with the highest bit position . The mantissa
is retrieved either via the standard C function [ frexp ] or by some bit
twiddling on IEEE compatible numbers ( float ) . Note that one needs to
use at least [ double ] precision for an accurate mantissa of 32 bit
numbers .
* use bit twiddling , a logarithmic sequence of bitwise or 's and shifts ( bit ) .
* use processor specific assembler instruction ( asm ) .
The most portable way would be [ bit ] , but is it efficient enough ?
I have measured the cycle counts of the different methods on an AMD
Athlon - XP 1800 ( ~ Pentium III 1.8Ghz ) using the RDTSC instruction :
highestBitMask : method cycles
--------------
frexp 200
float 33
bit 11
asm 12
highestBit : method cycles
--------------
frexp 195
float 33
bit 11
asm 11
Wow , the bit twiddling is on today 's RISC like machines even faster
than a single CISC instruction ( BSR ) !
---------------------------------------------------------------------
Finding the highest bit (mask) in a word [x] can be done efficiently in
three ways:
* convert to a floating point value and the mantissa tells us the
[log2(x)] that corresponds with the highest bit position. The mantissa
is retrieved either via the standard C function [frexp] or by some bit
twiddling on IEEE compatible numbers (float). Note that one needs to
use at least [double] precision for an accurate mantissa of 32 bit
numbers.
* use bit twiddling, a logarithmic sequence of bitwise or's and shifts (bit).
* use processor specific assembler instruction (asm).
The most portable way would be [bit], but is it efficient enough?
I have measured the cycle counts of the different methods on an AMD
Athlon-XP 1800 (~ Pentium III 1.8Ghz) using the RDTSC instruction:
highestBitMask: method cycles
--------------
frexp 200
float 33
bit 11
asm 12
highestBit: method cycles
--------------
frexp 195
float 33
bit 11
asm 11
Wow, the bit twiddling is on today's RISC like machines even faster
than a single CISC instruction (BSR)!
----------------------------------------------------------------------}
---------------------------------------------------------------------
[ highestBitMask ] returns a word where only the highest bit is set .
It is found by first setting all bits in lower positions than the
highest bit and than taking an exclusive or with the original value .
Although the function may look expensive , GHC compiles this into
excellent C code that subsequently compiled into highly efficient
machine code . The algorithm is derived from FXT library .
---------------------------------------------------------------------
[highestBitMask] returns a word where only the highest bit is set.
It is found by first setting all bits in lower positions than the
highest bit and than taking an exclusive or with the original value.
Although the function may look expensive, GHC compiles this into
excellent C code that subsequently compiled into highly efficient
machine code. The algorithm is derived from Jorg Arndt's FXT library.
----------------------------------------------------------------------}
highestBitMask :: Nat -> Nat
highestBitMask x0
= case (x0 .|. shiftRL x0 1) of
x1 -> case (x1 .|. shiftRL x1 2) of
x2 -> case (x2 .|. shiftRL x2 4) of
x3 -> case (x3 .|. shiftRL x3 8) of
x4 -> case (x4 .|. shiftRL x4 16) of
for 64 bit platforms
x6 -> (x6 `xor` (shiftRL x6 1))
-------------------------------------------------------------------
Utilities
-------------------------------------------------------------------
Utilities
--------------------------------------------------------------------}
foldlStrict :: (a -> b -> a) -> a -> [b] -> a
foldlStrict f z xs
= case xs of
[] -> z
(x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
| null |
https://raw.githubusercontent.com/ekmett/intern/1c78fbec0d46f27307092ce08019d76c22eee1b4/Data/Interned/IntSet.hs
|
haskell
|
---------------------------------------------------------------------------
|
Module : Data.Interned.IntSet
License : BSD-style
Maintainer :
Stability : provisional
An efficient implementation of integer sets.
Since many function names (but not the type name) clash with
The implementation is based on /big-endian patricia trees/. This data
structure performs especially well on binary operations like 'union'
and 'intersection'. However, my benchmarks show that it is also
(much) faster on insertions and deletions when compared to a generic
size-balanced set implementation (see "Data.Set").
<>
Practical Algorithm To Retrieve
This means that the operation can become linear in the number of
elements with a maximum of /W/ -- the number of bits in an 'Int'
Unlike the reference implementation in Data.IntSet, Data.Interned.IntSet
This can mean a drastic reduction in the memory footprint of a program
in exchange for much more costly set manipulation.
---------------------------------------------------------------------------
* Set type
* Operators
* Query
* Construction
* Combine
* Filter
* Map
* Fold
* Conversion
** List
** Ordered list
* Debugging
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
| /O(n+m)/. See 'difference'.
-------------------------------------------------------------------
Types
-------------------------------------------------------------------
| A set of integers.
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
Invariant: Prefix is the common high-order bits that all elements share to
the left of the Mask bit.
don't have the mask bit set; right is all the elements that do.
# UNPACK #
# UNPACK #
-------------------------------------------------------------------
@bin@ assures that we never have empty trees within a tree.
-------------------------------------------------------------------
| A unique integer ID associated with each interned set.
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
a huge cache width!
-------------------------------------------------------------------
Query
-------------------------------------------------------------------
| /O(1)/. Is the set empty?
| /O(1)/. Cardinality of the set.
| /O(min(n,W))/. Is the value a member of the set?
| /O(min(n,W))/. Is the element not in the set?
'lookup' is used by 'intersection' for left-biasing
-------------------------------------------------------------------
Construction
-------------------------------------------------------------------
| /O(1)/. The empty set.
-------------------------------------------------------------------
Insert
-------------------------------------------------------------------
| /O(min(n,W))/. Add a value to the set. When the value is already
an element of the set, it is replaced by the new one, ie. 'insert'
is left-biased.
right-biased insertion, used by 'union'
| /O(min(n,W))/. Delete a value in the set. Returns the
original set when the value was not present.
-------------------------------------------------------------------
Union
-------------------------------------------------------------------
| The union of a list of sets.
right bias
-------------------------------------------------------------------
Difference
-------------------------------------------------------------------
-------------------------------------------------------------------
Intersection
-------------------------------------------------------------------
-------------------------------------------------------------------
Subset
-------------------------------------------------------------------
disjoint
disjoint
disjoint
-------------------------------------------------------------------
Filter
-------------------------------------------------------------------
| /O(n)/. Filter all elements that satisfy some predicate.
| /O(n)/. partition the set according to some predicate.
| /O(min(n,W))/. The expression (@'split' x set@) is a pair @(set1,set2)@
handle negative numbers.
| /O(min(n,W))/. Performs a 'split' but also returns whether the pivot
element was found in the original set.
handle negative numbers.
-------------------------------------------------------------------
-------------------------------------------------------------------
--------------------------------------------------------------------}
| /O(min(n,W))/. Retrieves the maximal key of the set, and the set
stripped of that element, or 'Nothing' if passed an empty set.
| /O(min(n,W))/. Retrieves the minimal key of the set, and the set
stripped of that element, or 'Nothing' if passed an empty set.
| /O(min(n,W))/. Delete and find the minimal element.
> deleteFindMin set = (findMin set, deleteMin set)
| /O(min(n,W))/. Delete and find the maximal element.
| /O(min(n,W))/. The minimal element of the set.
| /O(min(n,W))/. The maximal element of a set.
| /O(min(n,W))/. Delete the minimal element.
| /O(min(n,W))/. Delete the maximal element.
---------------------------------------------------------------------
Map
---------------------------------------------------------------------
| /O(n*min(n,W))/.
It's worth noting that the size of the result may be smaller if,
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
| /O(n)/. Fold over the elements of a set in an unspecified order.
put negative numbers before.
-------------------------------------------------------------------
List variations
-------------------------------------------------------------------
| /O(n)/. The elements of a set. (For sets, this is equivalent to toList)
-------------------------------------------------------------------
Lists
-------------------------------------------------------------------
| /O(n)/. Convert the set to a list of elements.
| /O(n)/. Convert the set to an ascending list of elements.
| /O(n)/. Build a set from an ascending list of elements.
| /O(n)/. Build a set from an ascending list of distinct elements.
# UNPACK #
-------------------------------------------------------------------
Debugging
-------------------------------------------------------------------
| /O(n)/. Show the tree that implements the set. The tree is shown
in a compressed, hanging format.
++ show (p,m)
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
/O(1)/
-------------------------------------------------------------------
Ord
NB: this ordering is not the ordering implied by the elements
but is usable for comparison
-------------------------------------------------------------------
compare s1 s2 = compare (toAscList s1) (toAscList s2)
-------------------------------------------------------------------
Show
-------------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
-------------------------------------------------------------------
Read
-------------------------------------------------------------------
-------------------------------------------------------------------
Helpers
-------------------------------------------------------------------
-------------------------------------------------------------------
Join
-------------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
Then mask i m is i with the low a bits zeroed out.
-------------------------------------------------------------------
Big endian operations
-------------------------------------------------------------------
-------------------------------------------------------------------
------------
------------
-------------------------------------------------------------------
------------
------------
--------------------------------------------------------------------}
-------------------------------------------------------------------
-------------------------------------------------------------------
--------------------------------------------------------------------}
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
|
# LANGUAGE MagicHash , TypeFamilies , FlexibleInstances , BangPatterns , CPP #
Copyright : ( c ) 2002
( c ) 2011
Portability : non - portable ( TypeFamilies , MagicHash )
" Prelude " names , this module is usually imported @qualified@ , e.g.
> import Data . IntSet ( )
> import qualified Data . IntSet as
* and , \"/Fast Maps/\ " ,
Workshop on ML , September 1998 , pages 77 - 86 ,
Information Coded In Alphanumeric/\ " , Journal of the ACM , 15(4 ) ,
October 1968 , pages 514 - 534 .
Many operations have a worst - case complexity of /O(min(n , W))/.
( 32 or 64 ) .
uses hash consing to ensure that there is only ever one copy of any given
IntSet in memory . This is enabled by the normal form of the PATRICIA trie .
module Data.Interned.IntSet (
instance Eq , Show
, identity
, (\\)
, null
, size
, member
, notMember
, isSubsetOf
, isProperSubsetOf
, empty
, singleton
, insert
, delete
, union, unions
, difference
, intersection
, filter
, partition
, split
, splitMember
*
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, maxView
, minView
, map
, fold
, elems
, toList
, fromList
, toAscList
, fromAscList
, fromDistinctAscList
, showTree
, showTreeWith
) where
import Prelude hiding (lookup,filter,foldr,foldl,null,map)
import qualified Data.List as List
import Data.Maybe (fromMaybe)
import Data.Interned.Internal
import Data.Bits
import Data.Hashable
import Text.Read
import GHC.Exts ( Word(..), Int(..), shiftRL# )
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (Monoid(..))
#endif
#if MIN_VERSION_base(4,9,0) && !(MIN_VERSION_base(4,11,0))
import Data.Semigroup (Semigroup(..))
#endif
import Data . Typeable
import Data . Data ( Data ( .. ) , mkNoRepType )
This comment teaches CPP correct behaviour
A " " is a natural machine word ( an unsigned Int )
type Nat = Word
natFromInt :: Int -> Nat
natFromInt i = fromIntegral i
intFromNat :: Nat -> Int
intFromNat w = fromIntegral w
shiftRL :: Nat -> Int -> Nat
shiftRL (W# x) (I# i) = W# (shiftRL# x i)
Operators
Operators
(\\) :: IntSet -> IntSet -> IntSet
m1 \\ m2 = difference m1 m2
data IntSet
= Nil
Invariant : Nil is never found as a child of .
Invariant : The Mask is a power of 2 . It is the largest bit position at which
two elements of the set differ .
Invariant : In prefix mask left right , left consists of the elements that
data UninternedIntSet
= UNil
| UTip !Int
tip :: Int -> IntSet
tip n = intern (UTip n)
bin :: Prefix -> Mask -> IntSet -> IntSet -> IntSet
bin _ _ l Nil = l
bin _ _ Nil r = r
bin p m l r = intern (UBin p m l r)
bin_ :: Prefix -> Mask -> IntSet -> IntSet -> IntSet
bin_ p m l r = intern (UBin p m l r)
identity :: IntSet -> Id
identity Nil = 0
identity (Tip i _) = i
identity (Bin i _ _ _ _ _) = i
instance Interned IntSet where
type Uninterned IntSet = UninternedIntSet
data Description IntSet
= DNil
deriving Eq
describe UNil = DNil
describe (UTip j) = DTip j
describe (UBin p m l r) = DBin p m (identity l) (identity r)
seedIdentity _ = 1
identify _ UNil = Nil
identify i (UTip j) = Tip i j
identify i (UBin p m l r) = Bin i (size l + size r) p m l r
cache = intSetCache
instance Hashable (Description IntSet) where
hashWithSalt s DNil = s `hashWithSalt` (0 :: Int)
hashWithSalt s (DTip n) = s `hashWithSalt` (1 :: Int) `hashWithSalt` n
hashWithSalt s (DBin p m l r) = s `hashWithSalt` (2 :: Int) `hashWithSalt` p `hashWithSalt` m `hashWithSalt` l `hashWithSalt` r
intSetCache :: Cache IntSet
intSetCache = mkCache
# NOINLINE intSetCache #
instance Uninternable IntSet where
unintern Nil = UNil
unintern (Tip _ j) = UTip j
unintern (Bin _ _ p m l r) = UBin p m l r
type Prefix = Int
type Mask = Int
#if MIN_VERSION_base(4,9,0)
instance Semigroup IntSet where
(<>) = union
#endif
instance Monoid IntSet where
mempty = empty
#if !(MIN_VERSION_base(4,11,0))
mappend = union
#endif
mconcat = unions
null :: IntSet -> Bool
null Nil = True
null _ = False
size :: IntSet -> Int
size t
= case t of
Bin _ s _ _ _ _ -> s
Tip _ _ -> 1
Nil -> 0
member :: Int -> IntSet -> Bool
member x t
= case t of
Bin _ _ p m l r
| nomatch x p m -> False
| zero x m -> member x l
| otherwise -> member x r
Tip _ y -> (x==y)
Nil -> False
notMember :: Int -> IntSet -> Bool
notMember k = not . member k
lookup :: Int -> IntSet -> Maybe Int
lookup k t
= let nk = natFromInt k in seq nk (lookupN nk t)
lookupN :: Nat -> IntSet -> Maybe Int
lookupN k t
= case t of
Bin _ _ _ m l r
| zeroN k (natFromInt m) -> lookupN k l
| otherwise -> lookupN k r
Tip _ kx
| (k == natFromInt kx) -> Just kx
| otherwise -> Nothing
Nil -> Nothing
empty :: IntSet
empty = Nil
| /O(1)/. A set of one element .
singleton :: Int -> IntSet
singleton x = tip x
insert :: Int -> IntSet -> IntSet
insert x t
= case t of
Bin _ _ p m l r
| nomatch x p m -> join x (tip x) p t
| zero x m -> bin_ p m (insert x l) r
| otherwise -> bin_ p m l (insert x r)
Tip _ y
| x==y -> tip x
| otherwise -> join x (tip x) y t
Nil -> tip x
insertR :: Int -> IntSet -> IntSet
insertR x t
= case t of
Bin _ _ p m l r
| nomatch x p m -> join x (tip x) p t
| zero x m -> bin_ p m (insert x l) r
| otherwise -> bin_ p m l (insert x r)
Tip _ y
| x==y -> t
| otherwise -> join x (tip x) y t
Nil -> tip x
delete :: Int -> IntSet -> IntSet
delete x t
= case t of
Bin _ _ p m l r
| nomatch x p m -> t
| zero x m -> bin p m (delete x l) r
| otherwise -> bin p m l (delete x r)
Tip _ y
| x==y -> Nil
| otherwise -> t
Nil -> Nil
unions :: [IntSet] -> IntSet
unions xs = foldlStrict union empty xs
| /O(n+m)/. The union of two sets .
union :: IntSet -> IntSet -> IntSet
union t1@(Bin _ _ p1 m1 l1 r1) t2@(Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = union1
| shorter m2 m1 = union2
| p1 == p2 = bin_ p1 m1 (union l1 l2) (union r1 r2)
| otherwise = join p1 t1 p2 t2
where
union1 | nomatch p2 p1 m1 = join p1 t1 p2 t2
| zero p2 m1 = bin_ p1 m1 (union l1 t2) r1
| otherwise = bin_ p1 m1 l1 (union r1 t2)
union2 | nomatch p1 p2 m2 = join p1 t1 p2 t2
| zero p1 m2 = bin_ p2 m2 (union t1 l2) r2
| otherwise = bin_ p2 m2 l2 (union t1 r2)
union (Tip _ x) t = insert x t
union Nil t = t
union t Nil = t
| /O(n+m)/. Difference between two sets .
difference :: IntSet -> IntSet -> IntSet
difference t1@(Bin _ _ p1 m1 l1 r1) t2@(Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = difference1
| shorter m2 m1 = difference2
| p1 == p2 = bin p1 m1 (difference l1 l2) (difference r1 r2)
| otherwise = t1
where
difference1 | nomatch p2 p1 m1 = t1
| zero p2 m1 = bin p1 m1 (difference l1 t2) r1
| otherwise = bin p1 m1 l1 (difference r1 t2)
difference2 | nomatch p1 p2 m2 = t1
| zero p1 m2 = difference t1 l2
| otherwise = difference t1 r2
difference t1@(Tip _ x) t2
| member x t2 = Nil
| otherwise = t1
difference Nil _ = Nil
difference t (Tip _ x) = delete x t
difference t Nil = t
| /O(n+m)/. The intersection of two sets .
intersection :: IntSet -> IntSet -> IntSet
intersection t1@(Bin _ _ p1 m1 l1 r1) t2@(Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = intersection1
| shorter m2 m1 = intersection2
| p1 == p2 = bin p1 m1 (intersection l1 l2) (intersection r1 r2)
| otherwise = Nil
where
intersection1 | nomatch p2 p1 m1 = Nil
| zero p2 m1 = intersection l1 t2
| otherwise = intersection r1 t2
intersection2 | nomatch p1 p2 m2 = Nil
| zero p1 m2 = intersection t1 l2
| otherwise = intersection t1 r2
intersection t1@(Tip _ x) t2
| member x t2 = t1
| otherwise = Nil
intersection t (Tip _ x)
= case lookup x t of
Just y -> tip y
Nothing -> Nil
intersection Nil _ = Nil
intersection _ Nil = Nil
| /O(n+m)/. Is this a proper subset ? ( ie . a subset but not equal ) .
isProperSubsetOf :: IntSet -> IntSet -> Bool
isProperSubsetOf t1 t2
= case subsetCmp t1 t2 of
LT -> True
_ -> False
subsetCmp :: IntSet -> IntSet -> Ordering
subsetCmp t1@(Bin _ _ p1 m1 l1 r1) (Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = GT
| shorter m2 m1 = case subsetCmpLt of
GT -> GT
_ -> LT
| p1 == p2 = subsetCmpEq
where
subsetCmpLt | nomatch p1 p2 m2 = GT
| zero p1 m2 = subsetCmp t1 l2
| otherwise = subsetCmp t1 r2
subsetCmpEq = case (subsetCmp l1 l2, subsetCmp r1 r2) of
(GT,_ ) -> GT
(_ ,GT) -> GT
(EQ,EQ) -> EQ
_ -> LT
subsetCmp (Bin _ _ _ _ _ _) _ = GT
subsetCmp (Tip _ x) (Tip _ y)
| x==y = EQ
subsetCmp (Tip _ x) t
| member x t = LT
subsetCmp Nil Nil = EQ
subsetCmp Nil _ = LT
| /O(n+m)/. Is this a subset ?
@(s1 ` isSubsetOf ` tells whether @s1@ is a subset of @s2@.
isSubsetOf :: IntSet -> IntSet -> Bool
isSubsetOf t1@(Bin _ _ p1 m1 l1 r1) (Bin _ _ p2 m2 l2 r2)
| shorter m1 m2 = False
| shorter m2 m1 = match p1 p2 m2 && (if zero p1 m2 then isSubsetOf t1 l2
else isSubsetOf t1 r2)
| otherwise = (p1==p2) && isSubsetOf l1 l2 && isSubsetOf r1 r2
isSubsetOf (Bin _ _ _ _ _ _) _ = False
isSubsetOf (Tip _ x) t = member x t
isSubsetOf Nil _ = True
filter :: (Int -> Bool) -> IntSet -> IntSet
filter predicate t
= case t of
Bin _ _ p m l r
-> bin p m (filter predicate l) (filter predicate r)
Tip _ x
| predicate x -> t
| otherwise -> Nil
Nil -> Nil
partition :: (Int -> Bool) -> IntSet -> (IntSet,IntSet)
partition predicate t
= case t of
Bin _ _ p m l r
-> let (l1,l2) = partition predicate l
(r1,r2) = partition predicate r
in (bin p m l1 r1, bin p m l2 r2)
Tip _ x
| predicate x -> (t,Nil)
| otherwise -> (Nil,t)
Nil -> (Nil,Nil)
where @set1@ comprises the elements of @set@ less than @x@ and @set2@
comprises the elements of @set@ greater than @x@.
> split 3 ( fromList [ 1 .. 5 ] ) = = ( fromList [ 1,2 ] , fromList [ 4,5 ] )
split :: Int -> IntSet -> (IntSet,IntSet)
split x t
= case t of
Bin _ _ _ m l r
| m < 0 -> if x >= 0 then let (lt,gt) = split' x l in (union r lt, gt)
else let (lt,gt) = split' x r in (lt, union gt l)
| otherwise -> split' x t
Tip _ y
| x>y -> (t,Nil)
| x<y -> (Nil,t)
| otherwise -> (Nil,Nil)
Nil -> (Nil, Nil)
split' :: Int -> IntSet -> (IntSet,IntSet)
split' x t
= case t of
Bin _ _ p m l r
| match x p m -> if zero x m then let (lt,gt) = split' x l in (lt,union gt r)
else let (lt,gt) = split' x r in (union l lt,gt)
| otherwise -> if x < p then (Nil, t)
else (t, Nil)
Tip _ y
| x>y -> (t,Nil)
| x<y -> (Nil,t)
| otherwise -> (Nil,Nil)
Nil -> (Nil,Nil)
splitMember :: Int -> IntSet -> (IntSet,Bool,IntSet)
splitMember x t
= case t of
Bin _ _ _ m l r
| m < 0 -> if x >= 0 then let (lt,found,gt) = splitMember' x l in (union r lt, found, gt)
else let (lt,found,gt) = splitMember' x r in (lt, found, union gt l)
| otherwise -> splitMember' x t
Tip _ y
| x>y -> (t,False,Nil)
| x<y -> (Nil,False,t)
| otherwise -> (Nil,True,Nil)
Nil -> (Nil,False,Nil)
splitMember' :: Int -> IntSet -> (IntSet,Bool,IntSet)
splitMember' x t
= case t of
Bin _ _ p m l r
| match x p m -> if zero x m then let (lt,found,gt) = splitMember x l in (lt,found,union gt r)
else let (lt,found,gt) = splitMember x r in (union l lt,found,gt)
| otherwise -> if x < p then (Nil, False, t)
else (t, False, Nil)
Tip _ y
| x>y -> (t,False,Nil)
| x<y -> (Nil,False,t)
| otherwise -> (Nil,True,Nil)
Nil -> (Nil,False,Nil)
Min /
Min/Max
maxView :: IntSet -> Maybe (Int, IntSet)
maxView t
= case t of
Bin _ _ p m l r | m < 0 -> let (result,t') = maxViewUnsigned l in Just (result, bin p m t' r)
Bin _ _ p m l r -> let (result,t') = maxViewUnsigned r in Just (result, bin p m l t')
Tip _ y -> Just (y,Nil)
Nil -> Nothing
maxViewUnsigned :: IntSet -> (Int, IntSet)
maxViewUnsigned t
= case t of
Bin _ _ p m l r -> let (result,t') = maxViewUnsigned r in (result, bin p m l t')
Tip _ y -> (y, Nil)
Nil -> error "maxViewUnsigned Nil"
minView :: IntSet -> Maybe (Int, IntSet)
minView t
= case t of
Bin _ _ p m l r | m < 0 -> let (result,t') = minViewUnsigned r in Just (result, bin p m l t')
Bin _ _ p m l r -> let (result,t') = minViewUnsigned l in Just (result, bin p m t' r)
Tip _ y -> Just (y, Nil)
Nil -> Nothing
minViewUnsigned :: IntSet -> (Int, IntSet)
minViewUnsigned t
= case t of
Bin _ _ p m l r -> let (result,t') = minViewUnsigned l in (result, bin p m t' r)
Tip _ y -> (y, Nil)
Nil -> error "minViewUnsigned Nil"
deleteFindMin :: IntSet -> (Int, IntSet)
deleteFindMin = fromMaybe (error "deleteFindMin: empty set has no minimal element") . minView
> set = ( set , deleteMax set )
deleteFindMax :: IntSet -> (Int, IntSet)
deleteFindMax = fromMaybe (error "deleteFindMax: empty set has no maximal element") . maxView
findMin :: IntSet -> Int
findMin Nil = error "findMin: empty set has no minimal element"
findMin (Tip _ x) = x
findMin (Bin _ _ _ m l r)
| m < 0 = find r
| otherwise = find l
where find (Tip _ x) = x
find (Bin _ _ _ _ l' _) = find l'
find Nil = error "findMin Nil"
findMax :: IntSet -> Int
findMax Nil = error "findMax: empty set has no maximal element"
findMax (Tip _ x) = x
findMax (Bin _ _ _ m l r)
| m < 0 = find l
| otherwise = find r
where find (Tip _ x) = x
find (Bin _ _ _ _ _ r') = find r'
find Nil = error "findMax Nil"
deleteMin :: IntSet -> IntSet
deleteMin = maybe (error "deleteMin: empty set has no minimal element") snd . minView
deleteMax :: IntSet -> IntSet
deleteMax = maybe (error "deleteMax: empty set has no maximal element") snd . maxView
@'map ' f s@ is the set obtained by applying @f@ to each element of @s@.
for some @(x , y)@ , @x \/= y & & f x = = f y@
map :: (Int->Int) -> IntSet -> IntSet
map f = fromList . List.map f . toList
Fold
Fold
> sum set = = fold ( + ) 0 set
> elems set = = fold ( :) [ ] set
fold :: (Int -> b -> b) -> b -> IntSet -> b
fold f z t
= case t of
Bin _ _ 0 m l r | m < 0 -> foldr f (foldr f z l) r
Bin _ _ _ _ _ _ -> foldr f z t
Tip _ x -> f x z
Nil -> z
foldr :: (Int -> b -> b) -> b -> IntSet -> b
foldr f z t
= case t of
Bin _ _ _ _ l r -> foldr f (foldr f z r) l
Tip _ x -> f x z
Nil -> z
elems :: IntSet -> [Int]
elems s = toList s
toList :: IntSet -> [Int]
toList t = fold (:) [] t
toAscList :: IntSet -> [Int]
toAscList t = toList t
| /O(n*min(n , W))/. Create a set from a list of integers .
fromList :: [Int] -> IntSet
fromList xs = foldlStrict ins empty xs
where
ins t x = insert x t
/The precondition ( input list is ascending ) is not checked./
fromAscList :: [Int] -> IntSet
fromAscList [] = Nil
fromAscList (x0 : xs0) = fromDistinctAscList (combineEq x0 xs0)
where
combineEq x' [] = [x']
combineEq x' (x:xs)
| x==x' = combineEq x' xs
| otherwise = x' : combineEq x xs
/The precondition ( input list is strictly ascending ) is not checked./
fromDistinctAscList :: [Int] -> IntSet
fromDistinctAscList [] = Nil
fromDistinctAscList (z0 : zs0) = work z0 zs0 Nada
where
work x [] stk = finish x (tip x) stk
work x (z:zs) stk = reduce z zs (branchMask z x) x (tip x) stk
reduce z zs _ px tx Nada = work z zs (Push px tx Nada)
reduce z zs m px tx stk@(Push py ty stk') =
let mxy = branchMask px py
pxy = mask px mxy
in if shorter m mxy
then reduce z zs m pxy (bin_ pxy mxy ty tx) stk'
else work z zs (Push px tx stk)
finish _ t Nada = t
finish px tx (Push py ty stk) = finish p (join py ty px tx) stk
where m = branchMask px py
p = mask px m
showTree :: IntSet -> String
showTree s
= showTreeWith True False s
| /O(n)/. The expression ( @'showTreeWith ' hang wide map@ ) shows
the tree that implements the set . If @hang@ is
' True ' , a /hanging/ tree is shown otherwise a rotated tree is shown . If
@wide@ is ' True ' , an extra wide version is shown .
the tree that implements the set. If @hang@ is
'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
@wide@ is 'True', an extra wide version is shown.
-}
showTreeWith :: Bool -> Bool -> IntSet -> String
showTreeWith hang wide t
| hang = (showsTreeHang wide [] t) ""
| otherwise = (showsTree wide [] [] t) ""
showsTree :: Bool -> [String] -> [String] -> IntSet -> ShowS
showsTree wide lbars rbars t
= case t of
Bin _ _ p m l r
-> showsTree wide (withBar rbars) (withEmpty rbars) r .
showWide wide rbars .
showsBars lbars . showString (showBin p m) . showString "\n" .
showWide wide lbars .
showsTree wide (withEmpty lbars) (withBar lbars) l
Tip _ x
-> showsBars lbars . showString " " . shows x . showString "\n"
Nil -> showsBars lbars . showString "|\n"
showsTreeHang :: Bool -> [String] -> IntSet -> ShowS
showsTreeHang wide bars t
= case t of
Bin _ _ p m l r
-> showsBars bars . showString (showBin p m) . showString "\n" .
showWide wide bars .
showsTreeHang wide (withBar bars) l .
showWide wide bars .
showsTreeHang wide (withEmpty bars) r
Tip _ x
-> showsBars bars . showString " " . shows x . showString "\n"
Nil -> showsBars bars . showString "|\n"
showBin :: Prefix -> Mask -> String
showBin _ _
showWide :: Bool -> [String] -> String -> String
showWide wide bars
| wide = showString (concat (reverse bars)) . showString "|\n"
| otherwise = id
showsBars :: [String] -> ShowS
showsBars bars
= case bars of
[] -> id
_ -> showString (concat (reverse (tail bars))) . showString node
node :: String
node = "+--"
withBar, withEmpty :: [String] -> [String]
withBar bars = "| ":bars
withEmpty bars = " ":bars
Eq
Eq
instance Eq IntSet where
Nil == Nil = True
Tip i _ == Tip j _ = i == j
Bin i _ _ _ _ _ == Bin j _ _ _ _ _ = i == j
_ == _ = False
instance Ord IntSet where
Nil `compare` Nil = EQ
Nil `compare` Tip _ _ = LT
Nil `compare` Bin _ _ _ _ _ _ = LT
Tip _ _ `compare` Nil = GT
Tip i _ `compare` Tip j _ = compare i j
Tip i _ `compare` Bin j _ _ _ _ _ = compare i j
Bin _ _ _ _ _ _ `compare` Nil = GT
Bin i _ _ _ _ _ `compare` Tip j _ = compare i j
Bin i _ _ _ _ _ `compare` Bin j _ _ _ _ _ = compare i j
instance Show IntSet where
showsPrec p xs = showParen (p > 10) $
showString "fromList " . shows (toList xs)
Hashable
Hashable
instance Hashable IntSet where
hashWithSalt s x = hashWithSalt s $ identity x
instance Read IntSet where
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
join :: Prefix -> IntSet -> Prefix -> IntSet -> IntSet
join p1 t1 p2 t2
| zero p1 m = bin_ p m t1 t2
| otherwise = bin_ p m t2 t1
where
m = branchMask p1 p2
p = mask p1 m
Endian independent bit twiddling
Endian independent bit twiddling
zero :: Int -> Mask -> Bool
zero i m
= (natFromInt i) .&. (natFromInt m) == 0
nomatch,match :: Int -> Prefix -> Mask -> Bool
nomatch i p m
= (mask i m) /= p
match i p m
= (mask i m) == p
Suppose a is largest such that 2^a divides 2*m .
mask :: Int -> Mask -> Prefix
mask i m
= maskW (natFromInt i) (natFromInt m)
zeroN :: Nat -> Nat -> Bool
zeroN i m = (i .&. m) == 0
maskW :: Nat -> Nat -> Prefix
maskW i m
= intFromNat (i .&. (complement (m-1) `xor` m))
shorter :: Mask -> Mask -> Bool
shorter m1 m2
= (natFromInt m1) > (natFromInt m2)
branchMask :: Prefix -> Prefix -> Mask
branchMask p1 p2
= intFromNat (highestBitMask (natFromInt p1 `xor` natFromInt p2))
Finding the highest bit ( mask ) in a word [ x ] can be done efficiently in
three ways :
* convert to a floating point value and the mantissa tells us the
[ log2(x ) ] that corresponds with the highest bit position . The mantissa
is retrieved either via the standard C function [ frexp ] or by some bit
twiddling on IEEE compatible numbers ( float ) . Note that one needs to
use at least [ double ] precision for an accurate mantissa of 32 bit
numbers .
* use bit twiddling , a logarithmic sequence of bitwise or 's and shifts ( bit ) .
* use processor specific assembler instruction ( asm ) .
The most portable way would be [ bit ] , but is it efficient enough ?
I have measured the cycle counts of the different methods on an AMD
Athlon - XP 1800 ( ~ Pentium III 1.8Ghz ) using the RDTSC instruction :
highestBitMask : method cycles
frexp 200
float 33
bit 11
asm 12
highestBit : method cycles
frexp 195
float 33
bit 11
asm 11
Wow , the bit twiddling is on today 's RISC like machines even faster
than a single CISC instruction ( BSR ) !
Finding the highest bit (mask) in a word [x] can be done efficiently in
three ways:
* convert to a floating point value and the mantissa tells us the
[log2(x)] that corresponds with the highest bit position. The mantissa
is retrieved either via the standard C function [frexp] or by some bit
twiddling on IEEE compatible numbers (float). Note that one needs to
use at least [double] precision for an accurate mantissa of 32 bit
numbers.
* use bit twiddling, a logarithmic sequence of bitwise or's and shifts (bit).
* use processor specific assembler instruction (asm).
The most portable way would be [bit], but is it efficient enough?
I have measured the cycle counts of the different methods on an AMD
Athlon-XP 1800 (~ Pentium III 1.8Ghz) using the RDTSC instruction:
highestBitMask: method cycles
frexp 200
float 33
bit 11
asm 12
highestBit: method cycles
frexp 195
float 33
bit 11
asm 11
Wow, the bit twiddling is on today's RISC like machines even faster
than a single CISC instruction (BSR)!
[ highestBitMask ] returns a word where only the highest bit is set .
It is found by first setting all bits in lower positions than the
highest bit and than taking an exclusive or with the original value .
Although the function may look expensive , GHC compiles this into
excellent C code that subsequently compiled into highly efficient
machine code . The algorithm is derived from FXT library .
[highestBitMask] returns a word where only the highest bit is set.
It is found by first setting all bits in lower positions than the
highest bit and than taking an exclusive or with the original value.
Although the function may look expensive, GHC compiles this into
excellent C code that subsequently compiled into highly efficient
machine code. The algorithm is derived from Jorg Arndt's FXT library.
highestBitMask :: Nat -> Nat
highestBitMask x0
= case (x0 .|. shiftRL x0 1) of
x1 -> case (x1 .|. shiftRL x1 2) of
x2 -> case (x2 .|. shiftRL x2 4) of
x3 -> case (x3 .|. shiftRL x3 8) of
x4 -> case (x4 .|. shiftRL x4 16) of
for 64 bit platforms
x6 -> (x6 `xor` (shiftRL x6 1))
Utilities
Utilities
foldlStrict :: (a -> b -> a) -> a -> [b] -> a
foldlStrict f z xs
= case xs of
[] -> z
(x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
|
e526945a4b3f87e09cace99f38d3ece774dd113024427a13b389c8021c2b0151
|
vyorkin/tiger
|
trace.ml
|
open Core_kernel
module S = Symbol
module L = Location
module T = Type
type target =
| Stdout
| File of string
[@@deriving eq, show]
type source =
| Symbol of target list
| Semant of target list
[@@deriving eq, show]
(* Note that in the [logs] lib terminology "source" defines a
named unit of logging whose reporting level can be set independently *)
module Symbol = struct
let src = Logs.Src.create "tig.symbol" ~doc:"Symbol table"
let trace op name sym =
Logs.debug ~src (fun m ->
m ~header:"symbol" "%s %s: %s" op name (S.to_string sym))
let bind name sym = trace "<==" name sym
let look name sym = trace "==>" name sym
end
module Semant = struct
open Syntax
open Syntax.Printer
let src = Logs.Src.create "tig.semant" ~doc:"Semantic analysis"
let trace f = Logs.debug ~src (fun m -> f (m ~header:"semant"))
let trace_tr name expr = trace @@ fun m -> m ">>> %s: %s" name expr
let trans_prog _ =
trace (fun m -> m "trans_prog")
let trans_ty typ =
trace_tr "trans_ty" (print_ty typ)
let tr_expr expr =
trace_tr "tr_expr" (print_expr expr.L.value)
let tr_var var =
trace_tr "tr_var" (print_var var.L.value)
let tr_simple_var sym =
trace_tr "tr_simple_var" (print_simple_var sym)
let tr_field_var var field =
trace_tr "tr_field_var" (print_field_var var field)
let tr_subscript_var var sub =
trace_tr "tr_subscript_var" (print_subscript_var var sub)
let tr_call f args =
trace_tr "tr_call" (print_call f args)
let tr_op l r op =
trace_tr "tr_op" (print_op l r op)
let tr_record ty_name vfields =
trace_tr "tr_record" (print_record ty_name vfields)
let tr_record_field name expr ty =
trace_tr "tr_record_field" (print_record_field name expr (Some ty))
let tr_seq exprs =
trace_tr "tr_seq" (print_seq exprs)
let tr_assign var expr =
trace_tr "tr_assign" (print_assign var expr)
let tr_cond cond t f =
trace_tr "tr_cond" (print_cond cond t f)
let tr_while cond body =
trace_tr "tr_while" (print_while cond body)
let tr_for var lo hi body =
trace_tr "tr_for" (print_for var lo hi body)
let tr_break br loop =
let mark = match loop with
| Some _ -> "inside"
| None -> "outside"
in
trace @@ fun m -> m ">>> tr_break (%s): %s"
mark (print_break br)
let tr_let decs body =
trace_tr "tr_let" (print_let decs body)
let tr_array typ size init =
trace_tr "tr_array" (print_array typ size init)
let trans_decs decs =
trace @@ fun m -> m ">>> trans_decs:\n%s" (print_decs decs)
let trans_type_decs tys =
trace @@ fun m -> m ">>> trans_type_decs:\n%s" (print_type_decs tys)
let trans_fun_decs fs =
trace @@ fun m -> m ">>> trans_fun:\n%s" (print_fun_decs fs)
let trans_fun_head fun_dec =
trace_tr "trans_fun_head" (print_fun_dec fun_dec)
let trans_var_dec var =
trace_tr "trans_var_dec" (print_var_dec var)
let ret_ty ty =
trace @@ T.(fun m -> m "<-- %s (%s)" (to_string ty) (to_string (~! ty)))
let assert_ty ty expr =
trace @@ fun m -> m "!!! (ty) %s : %s" (print_expr expr.L.value) (T.to_string ty)
let assert_comparison expr l r =
trace @@ fun m -> m "!!! (comparsion) %s : %s (%s)"
(print_expr l.L.value)
(print_expr r.L.value)
(print_expr expr.L.value)
let assert_op l r =
trace @@ fun m -> m "!!! (op) %s : int && %s : int"
(print_expr l.L.value)
(print_expr r.L.value)
let assert_fun_body fun_dec result =
trace @@ fun m -> m "!!! (fun body) %s : %s"
(print_fun_dec fun_dec)
(T.to_string result)
let assert_init var init_ty =
trace @@ fun m -> m "!!! (init) %s : %s"
(print_var_dec var)
(T.to_string init_ty)
end
(* TODO: Report only enabled sources *)
let mk_reporter cfg =
let open Config in
let report src level ~over k msgf =
let app = Format.std_formatter in
let dst = Format.err_formatter in
let k _ = over (); k () in
msgf @@ fun ?header ?tags fmt ->
[ ppf ] is our pretty - printing formatter
see #Most-general-pretty-printing-using-fprintf for deatils
see #Most-general-pretty-printing-using-fprintf for deatils *)
let ppf = if level = Logs.App then app else dst in
Format.kfprintf k ppf ("%a@[" ^^ fmt ^^ "@]@.") Logs_fmt.pp_header (level, header)
in
{ Logs.report = report }
| null |
https://raw.githubusercontent.com/vyorkin/tiger/54dd179c1cd291df42f7894abce3ee9064e18def/chapter5/lib/trace.ml
|
ocaml
|
Note that in the [logs] lib terminology "source" defines a
named unit of logging whose reporting level can be set independently
TODO: Report only enabled sources
|
open Core_kernel
module S = Symbol
module L = Location
module T = Type
type target =
| Stdout
| File of string
[@@deriving eq, show]
type source =
| Symbol of target list
| Semant of target list
[@@deriving eq, show]
module Symbol = struct
let src = Logs.Src.create "tig.symbol" ~doc:"Symbol table"
let trace op name sym =
Logs.debug ~src (fun m ->
m ~header:"symbol" "%s %s: %s" op name (S.to_string sym))
let bind name sym = trace "<==" name sym
let look name sym = trace "==>" name sym
end
module Semant = struct
open Syntax
open Syntax.Printer
let src = Logs.Src.create "tig.semant" ~doc:"Semantic analysis"
let trace f = Logs.debug ~src (fun m -> f (m ~header:"semant"))
let trace_tr name expr = trace @@ fun m -> m ">>> %s: %s" name expr
let trans_prog _ =
trace (fun m -> m "trans_prog")
let trans_ty typ =
trace_tr "trans_ty" (print_ty typ)
let tr_expr expr =
trace_tr "tr_expr" (print_expr expr.L.value)
let tr_var var =
trace_tr "tr_var" (print_var var.L.value)
let tr_simple_var sym =
trace_tr "tr_simple_var" (print_simple_var sym)
let tr_field_var var field =
trace_tr "tr_field_var" (print_field_var var field)
let tr_subscript_var var sub =
trace_tr "tr_subscript_var" (print_subscript_var var sub)
let tr_call f args =
trace_tr "tr_call" (print_call f args)
let tr_op l r op =
trace_tr "tr_op" (print_op l r op)
let tr_record ty_name vfields =
trace_tr "tr_record" (print_record ty_name vfields)
let tr_record_field name expr ty =
trace_tr "tr_record_field" (print_record_field name expr (Some ty))
let tr_seq exprs =
trace_tr "tr_seq" (print_seq exprs)
let tr_assign var expr =
trace_tr "tr_assign" (print_assign var expr)
let tr_cond cond t f =
trace_tr "tr_cond" (print_cond cond t f)
let tr_while cond body =
trace_tr "tr_while" (print_while cond body)
let tr_for var lo hi body =
trace_tr "tr_for" (print_for var lo hi body)
let tr_break br loop =
let mark = match loop with
| Some _ -> "inside"
| None -> "outside"
in
trace @@ fun m -> m ">>> tr_break (%s): %s"
mark (print_break br)
let tr_let decs body =
trace_tr "tr_let" (print_let decs body)
let tr_array typ size init =
trace_tr "tr_array" (print_array typ size init)
let trans_decs decs =
trace @@ fun m -> m ">>> trans_decs:\n%s" (print_decs decs)
let trans_type_decs tys =
trace @@ fun m -> m ">>> trans_type_decs:\n%s" (print_type_decs tys)
let trans_fun_decs fs =
trace @@ fun m -> m ">>> trans_fun:\n%s" (print_fun_decs fs)
let trans_fun_head fun_dec =
trace_tr "trans_fun_head" (print_fun_dec fun_dec)
let trans_var_dec var =
trace_tr "trans_var_dec" (print_var_dec var)
let ret_ty ty =
trace @@ T.(fun m -> m "<-- %s (%s)" (to_string ty) (to_string (~! ty)))
let assert_ty ty expr =
trace @@ fun m -> m "!!! (ty) %s : %s" (print_expr expr.L.value) (T.to_string ty)
let assert_comparison expr l r =
trace @@ fun m -> m "!!! (comparsion) %s : %s (%s)"
(print_expr l.L.value)
(print_expr r.L.value)
(print_expr expr.L.value)
let assert_op l r =
trace @@ fun m -> m "!!! (op) %s : int && %s : int"
(print_expr l.L.value)
(print_expr r.L.value)
let assert_fun_body fun_dec result =
trace @@ fun m -> m "!!! (fun body) %s : %s"
(print_fun_dec fun_dec)
(T.to_string result)
let assert_init var init_ty =
trace @@ fun m -> m "!!! (init) %s : %s"
(print_var_dec var)
(T.to_string init_ty)
end
let mk_reporter cfg =
let open Config in
let report src level ~over k msgf =
let app = Format.std_formatter in
let dst = Format.err_formatter in
let k _ = over (); k () in
msgf @@ fun ?header ?tags fmt ->
[ ppf ] is our pretty - printing formatter
see #Most-general-pretty-printing-using-fprintf for deatils
see #Most-general-pretty-printing-using-fprintf for deatils *)
let ppf = if level = Logs.App then app else dst in
Format.kfprintf k ppf ("%a@[" ^^ fmt ^^ "@]@.") Logs_fmt.pp_header (level, header)
in
{ Logs.report = report }
|
a2ffb76e99eb16d1795e4ce3986e3aaa0303de4668710f2725b7c6a485030dae
|
NorfairKing/intray
|
Persistence.hs
|
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
# OPTIONS_GHC -fno - warn - orphans #
module Intray.Web.Server.Persistence where
import Database.Persist.Sql
import Servant.Auth.Client (Token (..))
deriving instance PersistField Token
deriving instance PersistFieldSql Token
| null |
https://raw.githubusercontent.com/NorfairKing/intray/f8ed32c79d8b3159a4c82cd8cc5c5aeeb92c2c90/intray-web-server/src/Intray/Web/Server/Persistence.hs
|
haskell
|
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
# OPTIONS_GHC -fno - warn - orphans #
module Intray.Web.Server.Persistence where
import Database.Persist.Sql
import Servant.Auth.Client (Token (..))
deriving instance PersistField Token
deriving instance PersistFieldSql Token
|
|
5f297a5422df8e7ebc16830c4dca02663ce3dc55cb9b250e4418d2e99d40041f
|
igarnier/ocaml-geth
|
rpc.ml
|
open CCFun
open Geth
open Types
let debug_flag = ref false
let switch_debug () = debug_flag := not !debug_flag
let print_debug s =
if !debug_flag then Lwt_log.debug_f "Ocaml_geth.Rpc: %s" s
else Lwt.return_unit
let rpc_call url method_name (params : Yojson.Safe.t) =
let json : Yojson.Safe.t =
`Assoc
[ ("jsonrpc", `String "2.0"); ("method", `String method_name);
TODO : this sould be a UID
in
let data = Yojson.Safe.to_string json in
let headers = Cohttp.Header.of_list [("Content-type", "application/json")] in
let body = Cohttp_lwt.Body.of_string data in
print_debug (Printf.sprintf "Rpc.call: raw request =\n%s\n" data) ;%lwt
let%lwt _resp, body = Cohttp_lwt_unix.Client.post url ~headers ~body in
match body with
| `Empty -> Lwt.fail_with "Ocaml_geth.Rpc.rpc_call: error, empty reply"
| `Strings _ls -> Lwt.fail_with "Ocaml_geth.Rpc.rpc_call: error, string list"
| `String _s -> Lwt.fail_with "Ocaml_geth.Rpc.rpc_call: error, string"
| `Stream stream -> (
let%lwt ls = Lwt_stream.to_list stream in
match ls with
| [] -> Lwt.fail_with "Ocaml_geth.Rpc.rpc_call: error, empty reply"
| [reply] ->
print_debug
(Printf.sprintf "Ocaml_geth.Rpc.call: raw reply =\n%s\n" reply) ;%lwt
Lwt.return (Yojson.Safe.from_string reply)
| _ ->
Lwt.fail_with
"Ocaml_geth.Rpc.rpc_call: error, cannot interpret multi-part reply"
)
let req = new Http_client.post_raw url data in
* req#set_req_header " Content - type " " application / json " ;
* let pipeline = new Http_client.pipeline in
* let errormsg = ref None in
* pipeline#add_with_callback req @@
* ( fun call - > match call#response_status with
* | ` Ok - > ( )
* | ` Bad_request - >
* let response_body =
* > Json.drop_assoc
* | > List.assoc " message "
* | > Json.drop_string
* in
* errormsg : = Some ( " Bad_request : " ^ response_body )
* | _ - >
* let msg =
* " Response status text : " ^
* ( call#response_status_text ) ^ " \n " ^
* " Response vody : \n " ^
* ( call#response_body#value )
* in
* errormsg : = Some msg
* ) ;
* pipeline#run ( ) ;
* match ! with
* | None - >
* let ( ans : string ) = req#get_resp_body ( ) in
* print_debug ans;%lwt
* Lwt.return ( Json.from_string ans )
* | Some error - >
* Lwt.fail_with error
* req#set_req_header "Content-type" "application/json";
* let pipeline = new Http_client.pipeline in
* let errormsg = ref None in
* pipeline#add_with_callback req @@
* (fun call -> match call#response_status with
* | `Ok -> ()
* | `Bad_request ->
* let response_body =
* Json.from_string call#response_body#value
* |> Json.drop_assoc
* |> List.assoc "message"
* |> Json.drop_string
* in
* errormsg := Some ("Bad_request:" ^ response_body)
* | _ ->
* let msg =
* "Response status text: \n" ^
* (call#response_status_text) ^ "\n" ^
* "Response vody: \n" ^
* (call#response_body#value)
* in
* errormsg := Some msg
* );
* pipeline#run ();
* match !errormsg with
* | None ->
* let (ans: string) = req#get_resp_body () in
* print_debug ans;%lwt
* Lwt.return (Json.from_string ans)
* | Some error ->
* Lwt.fail_with error *)
let rpc_call url method_name ( params : ) =
* let open Yojson . Safe in
* let : =
* ` Assoc [ ( " jsonrpc " , ` String " 2.0 " ) ;
* ( " method " , ` String method_name ) ;
* ( " params " , params ) ;
* ( " i d " , ` Int 0 ) ; ( \ * TODO : this sould be a UID * \ )
* ]
* in
* let data = Yojson . Safe.to_string json in
* print_debug ( Printf.sprintf " Rpc.call : raw request = \n%s\n " data);%lwt
* let req = new Http_client.post_raw url data in
* req#set_req_header " Content - type " " application / json " ;
* let pipeline = new Http_client.pipeline in
* let errormsg = ref None in
* pipeline#add_with_callback req @@
* ( fun call - > match call#response_status with
* | ` Ok - > ( )
* | ` Bad_request - >
* let response_body =
* > Json.drop_assoc
* | > List.assoc " message "
* | > Json.drop_string
* in
* errormsg : = Some ( " Bad_request : " ^ response_body )
* | _ - >
* let msg =
* " Response status text : " ^
* ( call#response_status_text ) ^ " \n " ^
* " Response vody : \n " ^
* ( call#response_body#value )
* in
* errormsg : = Some msg
* ) ;
* pipeline#run ( ) ;
* match ! with
* | None - >
* let ( ans : string ) = req#get_resp_body ( ) in
* print_debug ans;%lwt
* Lwt.return ( Json.from_string ans )
* | Some error - >
* Lwt.fail_with error
* let open Yojson.Safe in
* let json : Json.json =
* `Assoc [ ("jsonrpc", `String "2.0");
* ("method", `String method_name);
* ("params", params);
* ("id", `Int 0); (\* TODO: this sould be a UID *\)
* ]
* in
* let data = Yojson.Safe.to_string json in
* print_debug (Printf.sprintf "Rpc.call: raw request =\n%s\n" data);%lwt
* let req = new Http_client.post_raw url data in
* req#set_req_header "Content-type" "application/json";
* let pipeline = new Http_client.pipeline in
* let errormsg = ref None in
* pipeline#add_with_callback req @@
* (fun call -> match call#response_status with
* | `Ok -> ()
* | `Bad_request ->
* let response_body =
* Json.from_string call#response_body#value
* |> Json.drop_assoc
* |> List.assoc "message"
* |> Json.drop_string
* in
* errormsg := Some ("Bad_request:" ^ response_body)
* | _ ->
* let msg =
* "Response status text: \n" ^
* (call#response_status_text) ^ "\n" ^
* "Response vody: \n" ^
* (call#response_body#value)
* in
* errormsg := Some msg
* );
* pipeline#run ();
* match !errormsg with
* | None ->
* let (ans: string) = req#get_resp_body () in
* print_debug ans;%lwt
* Lwt.return (Json.from_string ans)
* | Some error ->
* Lwt.fail_with error *)
-RPC#json-rpc-api-reference
module Get = Json.GetExn
(* module Net = struct
* let version ~url = rpc_call url "net_version" `Null
* let listening ~url = rpc_call url "net_listening" `Null
* let peer_count ~url = rpc_call url "net_peerCount" `Null
* end *)
let ( |>> ) promise pure = Lwt.bind promise (fun x -> Lwt.return (pure x))
module Eth = struct
type time = [`block of int | `latest | `earliest | `pending]
let time_to_json (at_time : time) =
match at_time with
| `block i ->
let s = Printf.sprintf "0x%x" i in
`String s
| `latest -> `String "latest"
| `earliest -> `String "earliest"
| `pending -> `String "pending"
let protocol_version url =
rpc_call url "eth_protocolVersion" `Null |>> Get.int_as_string
let syncing url = rpc_call url "eth_syncing" `Null |>> Get.bool
let coinbase url =
rpc_call url "eth_coinbase" `Null |>> Address.of_0x % Get.string
let mining url = rpc_call url "eth_mining" `Null |>> Get.bool
let hashrate url = rpc_call url "eth_hashrate" `Null |>> Get.bigint_as_string
let gas_price url = rpc_call url "eth_gasPrice" `Null |>> Get.bigint_as_string
let accounts url =
rpc_call url "eth_accounts" `Null
|>> Get.string_list |>> List.map Address.of_0x
let block_number url =
rpc_call url "eth_blockNumber" `Null |>> Get.int_as_string
let get_balance url ~address ~(at_time : time) =
let time = time_to_json at_time in
let params = `List [`String (Address.show address); time] in
rpc_call url "eth_getBalance" params |>> Get.bigint_as_string
let get_storage_at url ~address ~position ~(at_time : time) =
let time = time_to_json at_time in
let params =
`List
[`String (Address.show address); `String (Z.to_string position); time]
in
rpc_call url "eth_getStorageAt" params |>> Get.string
let get_transaction_count url ~address ~(at_time : time) =
let time = time_to_json at_time in
let params = `List [`String (Address.show address); time] in
rpc_call url "eth_getTransactionCount" params |>> Get.int
let get_transaction_count_by_hash url ~block_hash =
let args = `List [`String (Hash256.show block_hash)] in
rpc_call url "eth_getTransactionCountByHash" args |>> Get.int
let get_transaction_count_by_number url ~(at_time : time) =
let args = `List [time_to_json at_time] in
rpc_call url "eth_getTransactionCountByNumber" args |>> Get.int
(* eth_getUncleCountByBlockHash, eth_getUncleCountByBlockNumber *)
let get_code url ~address ~(at_time : time) =
let params = `List [`String (Address.show address); time_to_json at_time] in
rpc_call url "eth_getCode" params |>> Get.string
(* TODO: it would be nice to parse it back to bytecode *)
let get_block_by_hash url ~block_hash =
let params = `List [`String (Hash256.show block_hash)] in
rpc_call url "eth_getBlockByHash" params |>> Get.result |>> assert false
let get_block_by_number url ~at_time =
let params = `List [time_to_json at_time; `Bool true] in
rpc_call url "eth_getBlockByNumber" params |>> Get.result |>> assert false
let sign url ~address ~message =
rpc_call url "eth_sign"
(`List [`String (Address.show address); `String message])
|>> Get.string
let send_transaction url ~transaction =
let args = `List [Tx.to_json transaction] in
rpc_call url "eth_sendTransaction" args |>> Get.string |>> Hash256.of_0x
let send_raw_transaction url ~data =
let args = `List [`String data] in
rpc_call url "eth_sendRawTransaction" args |>> Get.string |>> Hash256.of_0x
let call url ~transaction ~(at_time : time) =
rpc_call url "eth_call"
(`List [Tx.to_json transaction; time_to_json at_time])
|>> Get.string
let estimate_gas url ~transaction =
try%lwt
rpc_call url "eth_estimateGas" (`List [Tx.to_json transaction])
|>> Get.bigint_as_string
with exn ->
let msg = "estimate_gas: error" in
Lwt.fail_with @@ msg ^ "/" ^ Printexc.to_string exn
(* getBlockByHash/byNumber, etc *)
getTransactionReceipt
let get_transaction_receipt url ~transaction_hash =
rpc_call url "eth_getTransactionReceipt"
(`List [`String (Hash256.show transaction_hash)])
|>> Get.result |>> Tx.receipt_from_json
let send_transaction_and_get_receipt url ~transaction =
let%lwt hash = send_transaction url ~transaction in
let rec loop () =
match%lwt get_transaction_receipt url ~transaction_hash:hash with
| None ->
Lwt_log.debug "send_transaction_and_get_receipt: waiting ..." ;%lwt
Lwt_unix.sleep 1.0 ;%lwt
loop ()
| Some receipt -> Lwt.return receipt
| exception exn ->
Lwt_log.debug
"send_transaction_and_get_receipt: error in get_transaction_receipt\n" ;%lwt
Lwt.fail exn in
loop ()
let send_contract_and_get_receipt_auto url ~src ~data ? value ( ) =
* let open Tx in
* let tx =
* {
* src ;
* dst = None ;
* gas = None ;
* gas_price = None ;
* value ;
* data = Bitstr . Hex.to_string data ;
* nonce = None
* }
* in
* let gas = estimate_gas url ~transaction : tx in
* let = { tx with gas = Some gas } in
* send_transaction_and_get_receipt url ~transaction : tx
* let open Tx in
* let tx =
* {
* src;
* dst = None;
* gas = None;
* gas_price = None;
* value;
* data = Bitstr.Hex.to_string data;
* nonce = None
* }
* in
* let gas = estimate_gas url ~transaction:tx in
* let tx = { tx with gas = Some gas } in
* send_transaction_and_get_receipt url ~transaction:tx *)
let send_contract_and_get_receipt url ~src ~data ?gas ?value () =
let open Tx in
let tx =
{src; dst= None; gas= None; gas_price= None; value; data; nonce= None}
in
let%lwt tx =
match gas with
| None ->
let%lwt gas = estimate_gas url ~transaction:tx in
Lwt.return {tx with gas= Some gas}
| Some _ -> Lwt.return {tx with gas} in
send_transaction_and_get_receipt url ~transaction:tx
end
module EthLwt =
* struct
*
* let send_transaction_and_get_receipt url ~transaction =
* let%lwt hash = Eth.send_transaction url ~transaction in
* let rec loop ( ) =
* match%lwt Eth.get_transaction_receipt url ~transaction_hash : hash with
* | None - >
* Lwt_unix.sleep 2.0;%lwt
* loop ( )
* | Some receipt - >
* Lwt.return receipt
* | exception err - >
* Lwt_io.eprintf " send_transaction_and_get_receipt : error in get_transaction_receipt\n";%lwt
* Lwt.fail err
* in
* loop ( )
*
* ( \ * let send_contract_and_get_receipt_auto url ~src ~data ? value ( ) =
* * let open Tx in
* * let tx =
* * {
* * src ;
* * dst = None ;
* * gas = None ;
* * gas_price = None ;
* * value ;
* * data = Bitstr . Hex.to_string data ;
* * nonce = None
* * }
* * in
* * let gas = Eth.estimate_gas url ~transaction : tx in
* * let = { tx with gas = Some gas } in
* * send_transaction_and_get_receipt url ~transaction : tx * \ )
*
* let send_contract_and_get_receipt url ~src ~data ? gas ? value ( ) =
* let open Tx in
* let =
* {
* src ;
* dst = None ;
* gas = None ;
* gas_price = None ;
* value ;
* data = Bitstr . Hex.to_string data ;
* nonce = None
* }
* in
* let =
* match gas with
* | None - >
* let%lwt gas = Eth.estimate_gas url ~transaction : tx in
* Lwt.return { tx with gas = Some gas }
* | Some _ - >
* Lwt.return { tx with gas }
* in
* send_transaction_and_get_receipt url ~transaction : tx
*
* end
* struct
*
* let send_transaction_and_get_receipt url ~transaction =
* let%lwt hash = Eth.send_transaction url ~transaction in
* let rec loop () =
* match%lwt Eth.get_transaction_receipt url ~transaction_hash:hash with
* | None ->
* Lwt_unix.sleep 2.0;%lwt
* loop ()
* | Some receipt ->
* Lwt.return receipt
* | exception err ->
* Lwt_io.eprintf "send_transaction_and_get_receipt: error in get_transaction_receipt\n";%lwt
* Lwt.fail err
* in
* loop ()
*
* (\* let send_contract_and_get_receipt_auto url ~src ~data ?value () =
* * let open Tx in
* * let tx =
* * {
* * src;
* * dst = None;
* * gas = None;
* * gas_price = None;
* * value;
* * data = Bitstr.Hex.to_string data;
* * nonce = None
* * }
* * in
* * let gas = Eth.estimate_gas url ~transaction:tx in
* * let tx = { tx with gas = Some gas } in
* * send_transaction_and_get_receipt url ~transaction:tx *\)
*
* let send_contract_and_get_receipt url ~src ~data ?gas ?value () =
* let open Tx in
* let tx =
* {
* src;
* dst = None;
* gas = None;
* gas_price = None;
* value;
* data = Bitstr.Hex.to_string data;
* nonce = None
* }
* in
* let tx =
* match gas with
* | None ->
* let%lwt gas = Eth.estimate_gas url ~transaction:tx in
* Lwt.return { tx with gas = Some gas }
* | Some _ ->
* Lwt.return { tx with gas }
* in
* send_transaction_and_get_receipt url ~transaction:tx
*
* end *)
module Personal = struct
let send_transaction url ~src ~dst ~value ~src_pwd =
(* let value = Bitstr.(hex_to_string (hex_of_bigint value)) in *)
let args =
`List
[ `Assoc
[ ("from", `String (Address.show src));
("to", `String (Address.show dst)); ("value", Json.zhex value) ];
`String src_pwd ] in
rpc_call url "personal_sendTransaction" args
|>> Get.string |>> Hash256.of_0x
let new_account url ~passphrase =
let args = `List [`String passphrase] in
rpc_call url "personal_newAccount" args |>> Get.string |>> Address.of_0x
let unlock_account url ~account ~passphrase ~unlock_duration =
let args =
`List
[ `String (Address.show account); `String passphrase;
`Int unlock_duration ] in
rpc_call url "personal_unlockAccount" args |>> Get.bool
end
module Miner = struct
let set_gas_price url ~gas_price =
rpc_call url "miner_setGasPrice" (`List [Json.zhex gas_price]) |>> Get.bool
let start url ~thread_count =
let args = `Int thread_count in
rpc_call url "miner_start" (`List [args]) |>> Get.null
let stop url = rpc_call url "miner_stop" `Null |>> ignore
let set_ether_base url ~address =
let args = `List [`String (Address.show address)] in
rpc_call url "miner_setEtherbase" args |>> Get.bool
end
module Admin = struct
let add_peer url ~peer_url =
rpc_call url "admin_addPeer" (`List [`String peer_url]) |>> Get.bool
let datadir url = rpc_call url "admin_datadir" `Null |>> Get.string
let node_info url =
rpc_call url "admin_nodeInfo" `Null
|>> Get.result |>> Types.node_info_from_json
let peers url =
rpc_call url "admin_peers" `Null
|>> Get.result |>> Types.peer_info_from_json
end
module Debug = struct
let dump_block url ~block_number =
let bnum = Printf.sprintf "0x%x" block_number in
rpc_call url "debug_dumpBlock" (`List [`String bnum])
|>> Get.result |>> Types.block_from_json
end
| null |
https://raw.githubusercontent.com/igarnier/ocaml-geth/e87ca9f86f79190aff108a14aaae6e925aed5641/lib_lwt/rpc.ml
|
ocaml
|
module Net = struct
* let version ~url = rpc_call url "net_version" `Null
* let listening ~url = rpc_call url "net_listening" `Null
* let peer_count ~url = rpc_call url "net_peerCount" `Null
* end
eth_getUncleCountByBlockHash, eth_getUncleCountByBlockNumber
TODO: it would be nice to parse it back to bytecode
getBlockByHash/byNumber, etc
let value = Bitstr.(hex_to_string (hex_of_bigint value)) in
|
open CCFun
open Geth
open Types
let debug_flag = ref false
let switch_debug () = debug_flag := not !debug_flag
let print_debug s =
if !debug_flag then Lwt_log.debug_f "Ocaml_geth.Rpc: %s" s
else Lwt.return_unit
let rpc_call url method_name (params : Yojson.Safe.t) =
let json : Yojson.Safe.t =
`Assoc
[ ("jsonrpc", `String "2.0"); ("method", `String method_name);
TODO : this sould be a UID
in
let data = Yojson.Safe.to_string json in
let headers = Cohttp.Header.of_list [("Content-type", "application/json")] in
let body = Cohttp_lwt.Body.of_string data in
print_debug (Printf.sprintf "Rpc.call: raw request =\n%s\n" data) ;%lwt
let%lwt _resp, body = Cohttp_lwt_unix.Client.post url ~headers ~body in
match body with
| `Empty -> Lwt.fail_with "Ocaml_geth.Rpc.rpc_call: error, empty reply"
| `Strings _ls -> Lwt.fail_with "Ocaml_geth.Rpc.rpc_call: error, string list"
| `String _s -> Lwt.fail_with "Ocaml_geth.Rpc.rpc_call: error, string"
| `Stream stream -> (
let%lwt ls = Lwt_stream.to_list stream in
match ls with
| [] -> Lwt.fail_with "Ocaml_geth.Rpc.rpc_call: error, empty reply"
| [reply] ->
print_debug
(Printf.sprintf "Ocaml_geth.Rpc.call: raw reply =\n%s\n" reply) ;%lwt
Lwt.return (Yojson.Safe.from_string reply)
| _ ->
Lwt.fail_with
"Ocaml_geth.Rpc.rpc_call: error, cannot interpret multi-part reply"
)
let req = new Http_client.post_raw url data in
* req#set_req_header " Content - type " " application / json " ;
* let pipeline = new Http_client.pipeline in
* let errormsg = ref None in
* pipeline#add_with_callback req @@
* ( fun call - > match call#response_status with
* | ` Ok - > ( )
* | ` Bad_request - >
* let response_body =
* > Json.drop_assoc
* | > List.assoc " message "
* | > Json.drop_string
* in
* errormsg : = Some ( " Bad_request : " ^ response_body )
* | _ - >
* let msg =
* " Response status text : " ^
* ( call#response_status_text ) ^ " \n " ^
* " Response vody : \n " ^
* ( call#response_body#value )
* in
* errormsg : = Some msg
* ) ;
* pipeline#run ( ) ;
* match ! with
* | None - >
* let ( ans : string ) = req#get_resp_body ( ) in
* print_debug ans;%lwt
* Lwt.return ( Json.from_string ans )
* | Some error - >
* Lwt.fail_with error
* req#set_req_header "Content-type" "application/json";
* let pipeline = new Http_client.pipeline in
* let errormsg = ref None in
* pipeline#add_with_callback req @@
* (fun call -> match call#response_status with
* | `Ok -> ()
* | `Bad_request ->
* let response_body =
* Json.from_string call#response_body#value
* |> Json.drop_assoc
* |> List.assoc "message"
* |> Json.drop_string
* in
* errormsg := Some ("Bad_request:" ^ response_body)
* | _ ->
* let msg =
* "Response status text: \n" ^
* (call#response_status_text) ^ "\n" ^
* "Response vody: \n" ^
* (call#response_body#value)
* in
* errormsg := Some msg
* );
* pipeline#run ();
* match !errormsg with
* | None ->
* let (ans: string) = req#get_resp_body () in
* print_debug ans;%lwt
* Lwt.return (Json.from_string ans)
* | Some error ->
* Lwt.fail_with error *)
let rpc_call url method_name ( params : ) =
* let open Yojson . Safe in
* let : =
* ` Assoc [ ( " jsonrpc " , ` String " 2.0 " ) ;
* ( " method " , ` String method_name ) ;
* ( " params " , params ) ;
* ( " i d " , ` Int 0 ) ; ( \ * TODO : this sould be a UID * \ )
* ]
* in
* let data = Yojson . Safe.to_string json in
* print_debug ( Printf.sprintf " Rpc.call : raw request = \n%s\n " data);%lwt
* let req = new Http_client.post_raw url data in
* req#set_req_header " Content - type " " application / json " ;
* let pipeline = new Http_client.pipeline in
* let errormsg = ref None in
* pipeline#add_with_callback req @@
* ( fun call - > match call#response_status with
* | ` Ok - > ( )
* | ` Bad_request - >
* let response_body =
* > Json.drop_assoc
* | > List.assoc " message "
* | > Json.drop_string
* in
* errormsg : = Some ( " Bad_request : " ^ response_body )
* | _ - >
* let msg =
* " Response status text : " ^
* ( call#response_status_text ) ^ " \n " ^
* " Response vody : \n " ^
* ( call#response_body#value )
* in
* errormsg : = Some msg
* ) ;
* pipeline#run ( ) ;
* match ! with
* | None - >
* let ( ans : string ) = req#get_resp_body ( ) in
* print_debug ans;%lwt
* Lwt.return ( Json.from_string ans )
* | Some error - >
* Lwt.fail_with error
* let open Yojson.Safe in
* let json : Json.json =
* `Assoc [ ("jsonrpc", `String "2.0");
* ("method", `String method_name);
* ("params", params);
* ("id", `Int 0); (\* TODO: this sould be a UID *\)
* ]
* in
* let data = Yojson.Safe.to_string json in
* print_debug (Printf.sprintf "Rpc.call: raw request =\n%s\n" data);%lwt
* let req = new Http_client.post_raw url data in
* req#set_req_header "Content-type" "application/json";
* let pipeline = new Http_client.pipeline in
* let errormsg = ref None in
* pipeline#add_with_callback req @@
* (fun call -> match call#response_status with
* | `Ok -> ()
* | `Bad_request ->
* let response_body =
* Json.from_string call#response_body#value
* |> Json.drop_assoc
* |> List.assoc "message"
* |> Json.drop_string
* in
* errormsg := Some ("Bad_request:" ^ response_body)
* | _ ->
* let msg =
* "Response status text: \n" ^
* (call#response_status_text) ^ "\n" ^
* "Response vody: \n" ^
* (call#response_body#value)
* in
* errormsg := Some msg
* );
* pipeline#run ();
* match !errormsg with
* | None ->
* let (ans: string) = req#get_resp_body () in
* print_debug ans;%lwt
* Lwt.return (Json.from_string ans)
* | Some error ->
* Lwt.fail_with error *)
-RPC#json-rpc-api-reference
module Get = Json.GetExn
let ( |>> ) promise pure = Lwt.bind promise (fun x -> Lwt.return (pure x))
module Eth = struct
type time = [`block of int | `latest | `earliest | `pending]
let time_to_json (at_time : time) =
match at_time with
| `block i ->
let s = Printf.sprintf "0x%x" i in
`String s
| `latest -> `String "latest"
| `earliest -> `String "earliest"
| `pending -> `String "pending"
let protocol_version url =
rpc_call url "eth_protocolVersion" `Null |>> Get.int_as_string
let syncing url = rpc_call url "eth_syncing" `Null |>> Get.bool
let coinbase url =
rpc_call url "eth_coinbase" `Null |>> Address.of_0x % Get.string
let mining url = rpc_call url "eth_mining" `Null |>> Get.bool
let hashrate url = rpc_call url "eth_hashrate" `Null |>> Get.bigint_as_string
let gas_price url = rpc_call url "eth_gasPrice" `Null |>> Get.bigint_as_string
let accounts url =
rpc_call url "eth_accounts" `Null
|>> Get.string_list |>> List.map Address.of_0x
let block_number url =
rpc_call url "eth_blockNumber" `Null |>> Get.int_as_string
let get_balance url ~address ~(at_time : time) =
let time = time_to_json at_time in
let params = `List [`String (Address.show address); time] in
rpc_call url "eth_getBalance" params |>> Get.bigint_as_string
let get_storage_at url ~address ~position ~(at_time : time) =
let time = time_to_json at_time in
let params =
`List
[`String (Address.show address); `String (Z.to_string position); time]
in
rpc_call url "eth_getStorageAt" params |>> Get.string
let get_transaction_count url ~address ~(at_time : time) =
let time = time_to_json at_time in
let params = `List [`String (Address.show address); time] in
rpc_call url "eth_getTransactionCount" params |>> Get.int
let get_transaction_count_by_hash url ~block_hash =
let args = `List [`String (Hash256.show block_hash)] in
rpc_call url "eth_getTransactionCountByHash" args |>> Get.int
let get_transaction_count_by_number url ~(at_time : time) =
let args = `List [time_to_json at_time] in
rpc_call url "eth_getTransactionCountByNumber" args |>> Get.int
let get_code url ~address ~(at_time : time) =
let params = `List [`String (Address.show address); time_to_json at_time] in
rpc_call url "eth_getCode" params |>> Get.string
let get_block_by_hash url ~block_hash =
let params = `List [`String (Hash256.show block_hash)] in
rpc_call url "eth_getBlockByHash" params |>> Get.result |>> assert false
let get_block_by_number url ~at_time =
let params = `List [time_to_json at_time; `Bool true] in
rpc_call url "eth_getBlockByNumber" params |>> Get.result |>> assert false
let sign url ~address ~message =
rpc_call url "eth_sign"
(`List [`String (Address.show address); `String message])
|>> Get.string
let send_transaction url ~transaction =
let args = `List [Tx.to_json transaction] in
rpc_call url "eth_sendTransaction" args |>> Get.string |>> Hash256.of_0x
let send_raw_transaction url ~data =
let args = `List [`String data] in
rpc_call url "eth_sendRawTransaction" args |>> Get.string |>> Hash256.of_0x
let call url ~transaction ~(at_time : time) =
rpc_call url "eth_call"
(`List [Tx.to_json transaction; time_to_json at_time])
|>> Get.string
let estimate_gas url ~transaction =
try%lwt
rpc_call url "eth_estimateGas" (`List [Tx.to_json transaction])
|>> Get.bigint_as_string
with exn ->
let msg = "estimate_gas: error" in
Lwt.fail_with @@ msg ^ "/" ^ Printexc.to_string exn
getTransactionReceipt
let get_transaction_receipt url ~transaction_hash =
rpc_call url "eth_getTransactionReceipt"
(`List [`String (Hash256.show transaction_hash)])
|>> Get.result |>> Tx.receipt_from_json
let send_transaction_and_get_receipt url ~transaction =
let%lwt hash = send_transaction url ~transaction in
let rec loop () =
match%lwt get_transaction_receipt url ~transaction_hash:hash with
| None ->
Lwt_log.debug "send_transaction_and_get_receipt: waiting ..." ;%lwt
Lwt_unix.sleep 1.0 ;%lwt
loop ()
| Some receipt -> Lwt.return receipt
| exception exn ->
Lwt_log.debug
"send_transaction_and_get_receipt: error in get_transaction_receipt\n" ;%lwt
Lwt.fail exn in
loop ()
let send_contract_and_get_receipt_auto url ~src ~data ? value ( ) =
* let open Tx in
* let tx =
* {
* src ;
* dst = None ;
* gas = None ;
* gas_price = None ;
* value ;
* data = Bitstr . Hex.to_string data ;
* nonce = None
* }
* in
* let gas = estimate_gas url ~transaction : tx in
* let = { tx with gas = Some gas } in
* send_transaction_and_get_receipt url ~transaction : tx
* let open Tx in
* let tx =
* {
* src;
* dst = None;
* gas = None;
* gas_price = None;
* value;
* data = Bitstr.Hex.to_string data;
* nonce = None
* }
* in
* let gas = estimate_gas url ~transaction:tx in
* let tx = { tx with gas = Some gas } in
* send_transaction_and_get_receipt url ~transaction:tx *)
let send_contract_and_get_receipt url ~src ~data ?gas ?value () =
let open Tx in
let tx =
{src; dst= None; gas= None; gas_price= None; value; data; nonce= None}
in
let%lwt tx =
match gas with
| None ->
let%lwt gas = estimate_gas url ~transaction:tx in
Lwt.return {tx with gas= Some gas}
| Some _ -> Lwt.return {tx with gas} in
send_transaction_and_get_receipt url ~transaction:tx
end
module EthLwt =
* struct
*
* let send_transaction_and_get_receipt url ~transaction =
* let%lwt hash = Eth.send_transaction url ~transaction in
* let rec loop ( ) =
* match%lwt Eth.get_transaction_receipt url ~transaction_hash : hash with
* | None - >
* Lwt_unix.sleep 2.0;%lwt
* loop ( )
* | Some receipt - >
* Lwt.return receipt
* | exception err - >
* Lwt_io.eprintf " send_transaction_and_get_receipt : error in get_transaction_receipt\n";%lwt
* Lwt.fail err
* in
* loop ( )
*
* ( \ * let send_contract_and_get_receipt_auto url ~src ~data ? value ( ) =
* * let open Tx in
* * let tx =
* * {
* * src ;
* * dst = None ;
* * gas = None ;
* * gas_price = None ;
* * value ;
* * data = Bitstr . Hex.to_string data ;
* * nonce = None
* * }
* * in
* * let gas = Eth.estimate_gas url ~transaction : tx in
* * let = { tx with gas = Some gas } in
* * send_transaction_and_get_receipt url ~transaction : tx * \ )
*
* let send_contract_and_get_receipt url ~src ~data ? gas ? value ( ) =
* let open Tx in
* let =
* {
* src ;
* dst = None ;
* gas = None ;
* gas_price = None ;
* value ;
* data = Bitstr . Hex.to_string data ;
* nonce = None
* }
* in
* let =
* match gas with
* | None - >
* let%lwt gas = Eth.estimate_gas url ~transaction : tx in
* Lwt.return { tx with gas = Some gas }
* | Some _ - >
* Lwt.return { tx with gas }
* in
* send_transaction_and_get_receipt url ~transaction : tx
*
* end
* struct
*
* let send_transaction_and_get_receipt url ~transaction =
* let%lwt hash = Eth.send_transaction url ~transaction in
* let rec loop () =
* match%lwt Eth.get_transaction_receipt url ~transaction_hash:hash with
* | None ->
* Lwt_unix.sleep 2.0;%lwt
* loop ()
* | Some receipt ->
* Lwt.return receipt
* | exception err ->
* Lwt_io.eprintf "send_transaction_and_get_receipt: error in get_transaction_receipt\n";%lwt
* Lwt.fail err
* in
* loop ()
*
* (\* let send_contract_and_get_receipt_auto url ~src ~data ?value () =
* * let open Tx in
* * let tx =
* * {
* * src;
* * dst = None;
* * gas = None;
* * gas_price = None;
* * value;
* * data = Bitstr.Hex.to_string data;
* * nonce = None
* * }
* * in
* * let gas = Eth.estimate_gas url ~transaction:tx in
* * let tx = { tx with gas = Some gas } in
* * send_transaction_and_get_receipt url ~transaction:tx *\)
*
* let send_contract_and_get_receipt url ~src ~data ?gas ?value () =
* let open Tx in
* let tx =
* {
* src;
* dst = None;
* gas = None;
* gas_price = None;
* value;
* data = Bitstr.Hex.to_string data;
* nonce = None
* }
* in
* let tx =
* match gas with
* | None ->
* let%lwt gas = Eth.estimate_gas url ~transaction:tx in
* Lwt.return { tx with gas = Some gas }
* | Some _ ->
* Lwt.return { tx with gas }
* in
* send_transaction_and_get_receipt url ~transaction:tx
*
* end *)
module Personal = struct
let send_transaction url ~src ~dst ~value ~src_pwd =
let args =
`List
[ `Assoc
[ ("from", `String (Address.show src));
("to", `String (Address.show dst)); ("value", Json.zhex value) ];
`String src_pwd ] in
rpc_call url "personal_sendTransaction" args
|>> Get.string |>> Hash256.of_0x
let new_account url ~passphrase =
let args = `List [`String passphrase] in
rpc_call url "personal_newAccount" args |>> Get.string |>> Address.of_0x
let unlock_account url ~account ~passphrase ~unlock_duration =
let args =
`List
[ `String (Address.show account); `String passphrase;
`Int unlock_duration ] in
rpc_call url "personal_unlockAccount" args |>> Get.bool
end
module Miner = struct
let set_gas_price url ~gas_price =
rpc_call url "miner_setGasPrice" (`List [Json.zhex gas_price]) |>> Get.bool
let start url ~thread_count =
let args = `Int thread_count in
rpc_call url "miner_start" (`List [args]) |>> Get.null
let stop url = rpc_call url "miner_stop" `Null |>> ignore
let set_ether_base url ~address =
let args = `List [`String (Address.show address)] in
rpc_call url "miner_setEtherbase" args |>> Get.bool
end
module Admin = struct
let add_peer url ~peer_url =
rpc_call url "admin_addPeer" (`List [`String peer_url]) |>> Get.bool
let datadir url = rpc_call url "admin_datadir" `Null |>> Get.string
let node_info url =
rpc_call url "admin_nodeInfo" `Null
|>> Get.result |>> Types.node_info_from_json
let peers url =
rpc_call url "admin_peers" `Null
|>> Get.result |>> Types.peer_info_from_json
end
module Debug = struct
let dump_block url ~block_number =
let bnum = Printf.sprintf "0x%x" block_number in
rpc_call url "debug_dumpBlock" (`List [`String bnum])
|>> Get.result |>> Types.block_from_json
end
|
948605c2bf500cd7dfdce7632ba3494e4f5b0cafd91439f23422002d5357bde2
|
johnwhitington/ocamli
|
tinyexternal.mli
|
val to_ocaml_value : Tinyocaml.t -> 'a
val of_ocaml_value : Tinyocaml.env -> 'a -> string -> Tinyocaml.t
type untyped_ocaml_value =
UInt of int
| UBlock of int * untyped_ocaml_value array
| UString of string
| UDouble of float
| UDoubleArray of float array
val untyped_of_ocaml_value : 'a -> untyped_ocaml_value
| null |
https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/tinyexternal.mli
|
ocaml
|
val to_ocaml_value : Tinyocaml.t -> 'a
val of_ocaml_value : Tinyocaml.env -> 'a -> string -> Tinyocaml.t
type untyped_ocaml_value =
UInt of int
| UBlock of int * untyped_ocaml_value array
| UString of string
| UDouble of float
| UDoubleArray of float array
val untyped_of_ocaml_value : 'a -> untyped_ocaml_value
|
|
59afa8ed71e492cc6aaf60e61f78bbf03fdf655b3015e6a433f1807afa3d3aa6
|
cram2/cram
|
package.lisp
|
;;;
Copyright ( c ) 2017 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
2;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of the Institute for Artificial Intelligence/
;;; Universitaet Bremen nor the names of its contributors may be used to
;;; endorse or promote products derived from this software without
;;; specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
;;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;;; POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage cram-common-failures
(:nicknames #:common-fail)
(:use #:cpl)
(:export
;; common
#:low-level-failure
#:actionlib-action-timed-out
#:high-level-failure
;; high-level
#:navigation-high-level-failure
#:navigation-goal-in-collision
#:navigation-failure-pose-stamped
#:looking-high-level-failure
#:object-unreachable
#:object-unreachable-object
#:manipulation-goal-in-collision
#:object-unfetchable
#:object-unfetchable-object
#:object-undeliverable
#:object-undeliverable-object
#:object-nowhere-to-be-found
#:object-nowhere-to-be-found-object
#:environment-manipulation-impossible
#:environment-unreachable
;; manipulation
#:manipulation-low-level-failure
#:gripper-low-level-failure
#:gripper-failure-action
#:gripper-closed-completely
#:gripper-goal-not-reached
#:manipulation-goal-not-reached
#:manipulation-pose-unreachable
;; navigation
#:navigation-low-level-failure
#:navigation-failure-location
#:navigation-pose-unreachable
#:navigation-goal-not-reached
;; perception
#:perception-low-level-failure
#:perception-object-not-found
#:object-not-found-object
ptu
#:ptu-low-level-failure
#:ptu-goal-unreachable
#:ptu-goal-not-reached
;; torso
#:torso-low-level-failure
#:torso-goal-unreachable
#:torso-goal-not-reached))
| null |
https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_common/cram_common_failures/src/package.lisp
|
lisp
|
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Universitaet Bremen nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
common
high-level
manipulation
navigation
perception
torso
|
Copyright ( c ) 2017 , < >
* Neither the name of the Institute for Artificial Intelligence/
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :cl-user)
(defpackage cram-common-failures
(:nicknames #:common-fail)
(:use #:cpl)
(:export
#:low-level-failure
#:actionlib-action-timed-out
#:high-level-failure
#:navigation-high-level-failure
#:navigation-goal-in-collision
#:navigation-failure-pose-stamped
#:looking-high-level-failure
#:object-unreachable
#:object-unreachable-object
#:manipulation-goal-in-collision
#:object-unfetchable
#:object-unfetchable-object
#:object-undeliverable
#:object-undeliverable-object
#:object-nowhere-to-be-found
#:object-nowhere-to-be-found-object
#:environment-manipulation-impossible
#:environment-unreachable
#:manipulation-low-level-failure
#:gripper-low-level-failure
#:gripper-failure-action
#:gripper-closed-completely
#:gripper-goal-not-reached
#:manipulation-goal-not-reached
#:manipulation-pose-unreachable
#:navigation-low-level-failure
#:navigation-failure-location
#:navigation-pose-unreachable
#:navigation-goal-not-reached
#:perception-low-level-failure
#:perception-object-not-found
#:object-not-found-object
ptu
#:ptu-low-level-failure
#:ptu-goal-unreachable
#:ptu-goal-not-reached
#:torso-low-level-failure
#:torso-goal-unreachable
#:torso-goal-not-reached))
|
18344f1c3293a0dadfc6a83573979df02bad7913b16fdec6949fe388c63ffdee
|
ocaml-multicore/parafuzz
|
minor_major_force.ml
|
(* TEST
ocamlopt_flags += " -O3 "
*)
(*
- create a record with a mutable field that has a lazy value in it
- force a minor_gc to make sure that record is on the heap
- update the lazy value to be a minor heap value
- force the lazy value to be a forward to an item in the minor heap
- call minor_gc and watch it fail the assert which makes sure that all remembered set items have been forwarded
*)
type test_record = {
mutable lzy_str: string Lazy.t;
mutable lzy_int: int Lazy.t;
}
let is_shared x = Obj.is_shared (Obj.repr x)
let glbl_int = ref 0
let glbl_string = ref "init"
let get_random_int () =
Random.int 256
let get_random_string () =
Printf.sprintf "%f" (Random.float 1.)
let get_lazy_status fmt_str x =
if Lazy.is_val x then
Printf.sprintf fmt_str (Lazy.force x)
else
"<not forced>"
let get_lazy_int_status x = get_lazy_status "%d" x
let get_lazy_string_status x = get_lazy_status "%s" x
let dump_record_status x =
Printf.printf "x.lzy_string=%s [shared=%b]\n" (get_lazy_string_status x.lzy_str) (is_shared x.lzy_str);
Printf.printf "x.lzy_int=%s [shared=%b]\n" (get_lazy_int_status x.lzy_int) (is_shared x.lzy_int)
let force_lazy_vals x =
let v = Lazy.force x.lzy_str in
Printf.printf "forcing x.lzy_str [%s] %b %d\n%!" v (is_shared x.lzy_str) (Obj.tag (Obj.repr x.lzy_str));
let v = Lazy.force x.lzy_int in
Printf.printf "forcing x.lzy_int [%d] %b %d\n%!" v (is_shared x.lzy_int) (Obj.tag (Obj.repr x.lzy_int))
let do_minor_gc () =
Printf.printf "Gc.minor ()\n%!";
Gc.minor ()
let () =
Random.init 34;
let x = {
lzy_str = lazy (glbl_string := get_random_string (); !glbl_string);
lzy_int = lazy (glbl_int := get_random_int (); !glbl_int);
} in
do_minor_gc ();
(* x should now be on the heap *)
dump_record_status x;
Printf.printf "x is setup on major heap\n\n%!";
Printf.printf "updating fields in x\n\n%!";
x.lzy_str <- lazy (glbl_string := get_random_string (); !glbl_string);
x.lzy_int <- lazy (glbl_int := get_random_int (); !glbl_int);
dump_record_status x;
force_lazy_vals x;
dump_record_status x;
do_minor_gc ();
dump_record_status x
| null |
https://raw.githubusercontent.com/ocaml-multicore/parafuzz/6a92906f1ba03287ffcb433063bded831a644fd5/testsuite/tests/lazy/minor_major_force.ml
|
ocaml
|
TEST
ocamlopt_flags += " -O3 "
- create a record with a mutable field that has a lazy value in it
- force a minor_gc to make sure that record is on the heap
- update the lazy value to be a minor heap value
- force the lazy value to be a forward to an item in the minor heap
- call minor_gc and watch it fail the assert which makes sure that all remembered set items have been forwarded
x should now be on the heap
|
type test_record = {
mutable lzy_str: string Lazy.t;
mutable lzy_int: int Lazy.t;
}
let is_shared x = Obj.is_shared (Obj.repr x)
let glbl_int = ref 0
let glbl_string = ref "init"
let get_random_int () =
Random.int 256
let get_random_string () =
Printf.sprintf "%f" (Random.float 1.)
let get_lazy_status fmt_str x =
if Lazy.is_val x then
Printf.sprintf fmt_str (Lazy.force x)
else
"<not forced>"
let get_lazy_int_status x = get_lazy_status "%d" x
let get_lazy_string_status x = get_lazy_status "%s" x
let dump_record_status x =
Printf.printf "x.lzy_string=%s [shared=%b]\n" (get_lazy_string_status x.lzy_str) (is_shared x.lzy_str);
Printf.printf "x.lzy_int=%s [shared=%b]\n" (get_lazy_int_status x.lzy_int) (is_shared x.lzy_int)
let force_lazy_vals x =
let v = Lazy.force x.lzy_str in
Printf.printf "forcing x.lzy_str [%s] %b %d\n%!" v (is_shared x.lzy_str) (Obj.tag (Obj.repr x.lzy_str));
let v = Lazy.force x.lzy_int in
Printf.printf "forcing x.lzy_int [%d] %b %d\n%!" v (is_shared x.lzy_int) (Obj.tag (Obj.repr x.lzy_int))
let do_minor_gc () =
Printf.printf "Gc.minor ()\n%!";
Gc.minor ()
let () =
Random.init 34;
let x = {
lzy_str = lazy (glbl_string := get_random_string (); !glbl_string);
lzy_int = lazy (glbl_int := get_random_int (); !glbl_int);
} in
do_minor_gc ();
dump_record_status x;
Printf.printf "x is setup on major heap\n\n%!";
Printf.printf "updating fields in x\n\n%!";
x.lzy_str <- lazy (glbl_string := get_random_string (); !glbl_string);
x.lzy_int <- lazy (glbl_int := get_random_int (); !glbl_int);
dump_record_status x;
force_lazy_vals x;
dump_record_status x;
do_minor_gc ();
dump_record_status x
|
04722fff0acf1bcdac70a9b023c6178f5a036c190dbbfcb3153054e6f4e70b78
|
multunus/dashboard-clj
|
project.clj
|
(defproject com.multunus/dashboard-clj "0.1.0-SNAPSHOT"
:description "Library to create dashboards"
:url "-clj"
:license {:name "MIT LICENSE"
:url ""}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.8.40" :scope "provided"]
[ring "1.4.0"]
[ring/ring-defaults "0.2.0"]
[bk/ring-gzip "0.1.1"]
[ring.middleware.logger "0.5.0"]
[compojure "1.5.0"]
[environ "1.0.2"]
[http-kit "2.1.19"]
[com.stuartsierra/component "0.3.1"]
[org.immutant/scheduling "2.1.3"]
[reagent "0.6.0-alpha"]
[com.taoensso/sente "1.8.1"]
[re-frame "0.7.0"]
[cljsjs/react-grid-layout "0.12.4-0"]]
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:plugins [[lein-cljsbuild "1.1.1"]
[lein-environ "1.0.1"]]
:min-lein-version "2.6.1"
:source-paths ["src/clj" "src/cljs"]
:test-paths ["test/clj"]
:clean-targets ^{:protect false} [:target-path :compile-path "resources/public/js"]
:uberjar-name "dashboard-clj.jar"
:repl-options {:init-ns user}
:env { :http-port 10555}
:cljsbuild {:builds
{:app
{:source-paths ["src/cljs"]
:figwheel true
:compiler {:main dashboard-clj.core
:asset-path "js/compiled/out"
:output-to "resources/public/js/compiled/dashboard_clj.js"
:output-dir "resources/public/js/compiled/out"
:source-map-timestamp true}}}}
:figwheel {
:css-dirs ["resources/public/css"] ;; watch and update CSS
:server-logfile "log/figwheel.log"}
:doo {:build "test"}
:profiles {:dev
{:source-paths ["dev"]
:dependencies [[figwheel "0.5.2"]
[figwheel-sidecar "0.5.2"]
[com.cemerick/piggieback "0.2.1"]
[org.clojure/tools.nrepl "0.2.12"]]
:plugins [[lein-figwheel "0.5.2"]
[lein-doo "0.1.6"]]
:cljsbuild {:builds
{:test
{:source-paths ["src/cljs" "test/cljs"]
:compiler
{:output-to "resources/public/js/compiled/testable.js"
:main dashboard-clj.test-runner
:optimizations :none}}}}}
:uberjar
{:source-paths ^:replace ["src/clj"]
:hooks [leiningen.cljsbuild]
:omit-source true
:aot :all
:cljsbuild {:builds
{:app
{:source-paths ^:replace ["src/cljs"]
:jar true
:compiler
{:optimizations :advanced
:pretty-print false}}}}}})
| null |
https://raw.githubusercontent.com/multunus/dashboard-clj/14ec30d6eb4a2fdbaadfec52beb572f250b0c781/project.clj
|
clojure
|
watch and update CSS
|
(defproject com.multunus/dashboard-clj "0.1.0-SNAPSHOT"
:description "Library to create dashboards"
:url "-clj"
:license {:name "MIT LICENSE"
:url ""}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.8.40" :scope "provided"]
[ring "1.4.0"]
[ring/ring-defaults "0.2.0"]
[bk/ring-gzip "0.1.1"]
[ring.middleware.logger "0.5.0"]
[compojure "1.5.0"]
[environ "1.0.2"]
[http-kit "2.1.19"]
[com.stuartsierra/component "0.3.1"]
[org.immutant/scheduling "2.1.3"]
[reagent "0.6.0-alpha"]
[com.taoensso/sente "1.8.1"]
[re-frame "0.7.0"]
[cljsjs/react-grid-layout "0.12.4-0"]]
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:plugins [[lein-cljsbuild "1.1.1"]
[lein-environ "1.0.1"]]
:min-lein-version "2.6.1"
:source-paths ["src/clj" "src/cljs"]
:test-paths ["test/clj"]
:clean-targets ^{:protect false} [:target-path :compile-path "resources/public/js"]
:uberjar-name "dashboard-clj.jar"
:repl-options {:init-ns user}
:env { :http-port 10555}
:cljsbuild {:builds
{:app
{:source-paths ["src/cljs"]
:figwheel true
:compiler {:main dashboard-clj.core
:asset-path "js/compiled/out"
:output-to "resources/public/js/compiled/dashboard_clj.js"
:output-dir "resources/public/js/compiled/out"
:source-map-timestamp true}}}}
:figwheel {
:server-logfile "log/figwheel.log"}
:doo {:build "test"}
:profiles {:dev
{:source-paths ["dev"]
:dependencies [[figwheel "0.5.2"]
[figwheel-sidecar "0.5.2"]
[com.cemerick/piggieback "0.2.1"]
[org.clojure/tools.nrepl "0.2.12"]]
:plugins [[lein-figwheel "0.5.2"]
[lein-doo "0.1.6"]]
:cljsbuild {:builds
{:test
{:source-paths ["src/cljs" "test/cljs"]
:compiler
{:output-to "resources/public/js/compiled/testable.js"
:main dashboard-clj.test-runner
:optimizations :none}}}}}
:uberjar
{:source-paths ^:replace ["src/clj"]
:hooks [leiningen.cljsbuild]
:omit-source true
:aot :all
:cljsbuild {:builds
{:app
{:source-paths ^:replace ["src/cljs"]
:jar true
:compiler
{:optimizations :advanced
:pretty-print false}}}}}})
|
18f6a1cff8771bc5a42a7e088e424495a9aaac1e3027bf34b252166e018020ca
|
kronkltd/jiksnu
|
webfinger_test.clj
|
(ns jiksnu.modules.core.model.webfinger-test
(:require [clj-factory.core :refer [factory fseq]]
[ciste.model :as cm]
[hiccup.core :as hiccup]
[jiksnu.modules.core.model.webfinger :refer :all]
[jiksnu.namespace :as ns]
[jiksnu.test-helper :as th]
[midje.sweet :refer :all]))
(defn mock-xrd-with-username
[username]
(cm/string->document
(hiccup/html
[:XRD {:xmlns ns/xrd}
[:Link
[:Property {:type ""}
username]]])))
(defn mock-xrd-with-subject
[subject]
(cm/string->document
(hiccup/html
[:XRD {:xmlns ns/xrd}
[:Subject subject]])))
(th/module-test ["jiksnu.modules.core"])
(facts "#'jiksnu.modules.core.model.webfinger/get-username-from-atom-property"
(fact "when the property has an identifier"
(let [username (fseq :username)
user-meta (mock-xrd-with-username username)]
(get-username-from-atom-property user-meta) => username)))
(facts "#'jiksnu.modules.core.model.webfinger/get-links"
(fact "When it has links"
(let [xrd (cm/string->document
(hiccup/html
[:XRD
[:Link {:ref ns/updates-from
:xmlns ns/xrd
:type "application/atom+xml"
:href ""}]]))]
(get-links xrd) => (contains [(contains {:type "application/atom+xml"})]))))
(facts "#'jiksnu.modules.core.model.webfinger/get-identifiers"
(let [subject "acct:"
xrd (mock-xrd-with-subject subject)]
(get-identifiers xrd) => (contains subject)))
(facts "#'jiksnu.modules.core.model.webfinger/get-username-from-identifiers"
(let [subject "acct:"
xrd (mock-xrd-with-subject subject)]
(get-username-from-identifiers xrd) => "foo"))
(facts "#'jiksnu.modules.core.model.webfinger/get-username-from-xrd"
(let [username (fseq :username)
domain (fseq :domain)
subject (format "acct:%s@%s" username domain)
user-meta (mock-xrd-with-subject subject)]
(fact "when the usermeta has an identifier"
(get-username-from-xrd user-meta) => username
(provided
(get-username-from-identifiers user-meta) => username
(get-username-from-atom-property user-meta) => nil :times 0))
(fact "when the usermeta does not have an identifier"
(fact "and the atom link has an identifier"
(let [user-meta (cm/string->document
(hiccup/html
[:XRD
[:Link {:ref ns/updates-from
:type "application/atom+xml"
:href ""}]]))]
(get-username-from-xrd user-meta) => .username.
(provided
(get-username-from-identifiers user-meta) => nil
(get-username-from-atom-property user-meta) => .username.)))
(fact "and the atom link does not have an identifier"
(let [user-meta (cm/string->document
(hiccup/html
[:XRD
[:Link {:ref ns/updates-from
:type "application/atom+xml"
:href ""}]]))]
(get-username-from-xrd user-meta) => nil
(provided
(get-username-from-identifiers user-meta) => nil
(get-username-from-atom-property user-meta) => nil))))))
| null |
https://raw.githubusercontent.com/kronkltd/jiksnu/8c91e9b1fddcc0224b028e573f7c3ca2f227e516/test/jiksnu/modules/core/model/webfinger_test.clj
|
clojure
|
(ns jiksnu.modules.core.model.webfinger-test
(:require [clj-factory.core :refer [factory fseq]]
[ciste.model :as cm]
[hiccup.core :as hiccup]
[jiksnu.modules.core.model.webfinger :refer :all]
[jiksnu.namespace :as ns]
[jiksnu.test-helper :as th]
[midje.sweet :refer :all]))
(defn mock-xrd-with-username
[username]
(cm/string->document
(hiccup/html
[:XRD {:xmlns ns/xrd}
[:Link
[:Property {:type ""}
username]]])))
(defn mock-xrd-with-subject
[subject]
(cm/string->document
(hiccup/html
[:XRD {:xmlns ns/xrd}
[:Subject subject]])))
(th/module-test ["jiksnu.modules.core"])
(facts "#'jiksnu.modules.core.model.webfinger/get-username-from-atom-property"
(fact "when the property has an identifier"
(let [username (fseq :username)
user-meta (mock-xrd-with-username username)]
(get-username-from-atom-property user-meta) => username)))
(facts "#'jiksnu.modules.core.model.webfinger/get-links"
(fact "When it has links"
(let [xrd (cm/string->document
(hiccup/html
[:XRD
[:Link {:ref ns/updates-from
:xmlns ns/xrd
:type "application/atom+xml"
:href ""}]]))]
(get-links xrd) => (contains [(contains {:type "application/atom+xml"})]))))
(facts "#'jiksnu.modules.core.model.webfinger/get-identifiers"
(let [subject "acct:"
xrd (mock-xrd-with-subject subject)]
(get-identifiers xrd) => (contains subject)))
(facts "#'jiksnu.modules.core.model.webfinger/get-username-from-identifiers"
(let [subject "acct:"
xrd (mock-xrd-with-subject subject)]
(get-username-from-identifiers xrd) => "foo"))
(facts "#'jiksnu.modules.core.model.webfinger/get-username-from-xrd"
(let [username (fseq :username)
domain (fseq :domain)
subject (format "acct:%s@%s" username domain)
user-meta (mock-xrd-with-subject subject)]
(fact "when the usermeta has an identifier"
(get-username-from-xrd user-meta) => username
(provided
(get-username-from-identifiers user-meta) => username
(get-username-from-atom-property user-meta) => nil :times 0))
(fact "when the usermeta does not have an identifier"
(fact "and the atom link has an identifier"
(let [user-meta (cm/string->document
(hiccup/html
[:XRD
[:Link {:ref ns/updates-from
:type "application/atom+xml"
:href ""}]]))]
(get-username-from-xrd user-meta) => .username.
(provided
(get-username-from-identifiers user-meta) => nil
(get-username-from-atom-property user-meta) => .username.)))
(fact "and the atom link does not have an identifier"
(let [user-meta (cm/string->document
(hiccup/html
[:XRD
[:Link {:ref ns/updates-from
:type "application/atom+xml"
:href ""}]]))]
(get-username-from-xrd user-meta) => nil
(provided
(get-username-from-identifiers user-meta) => nil
(get-username-from-atom-property user-meta) => nil))))))
|
|
d036d93deb7a908214bee2f7496ddfca06874e3c940794076a92bcc6fd2bc6ba
|
ekmett/succinct-binary
|
Put.hs
|
{-# language DeriveFunctor #-}
{-# language DefaultSignatures #-}
{-# language FlexibleContexts #-}
# language BangPatterns #
# language EmptyCase #
# language GADTs #
# language TypeOperators #
# language RankNTypes #
# language TypeApplications #
{-# language ScopedTypeVariables #-}
# options_ghc -funbox - strict - fields #
module Data.Binary.Succinct.Put {- .Internal -}
( Put(..)
-- guts
, meta, metas, paren, parens, content
, State(..)
, W(..)
, Result(..)
, put8
, Puttable(..)
, putN
, putN_
, gput
) where
import Data.Bits
import Data.ByteString.Lazy as Lazy
import Data.ByteString.Builder as Builder
import Data.Int
import Data.Proxy
import Data.Semigroup
import Data.Void
import Data.Word
import qualified GHC.Generics as G
import Data.Functor.Compose as F
import Data.Functor.Product as F
import Data.Functor.Sum as F
import qualified Generics.SOP as SOP
import qualified Generics.SOP.GGP as SOP
import Data.Binary.Succinct.Size
data State = State !Int !Word8 !Int !Word8
data W = W !Builder !Builder !Builder !Word64
instance Semigroup W where
W a b c m <> W d e f n = W (a <> d) (b <> e) (c <> f) (m + n)
instance Monoid W where
mempty = W mempty mempty mempty 0
mappend = (<>)
data Result = Result {-# UNPACK #-} !State {-# UNPACK #-} !W
newtype Put = Put { runPut :: State -> Result }
instance Semigroup Put where
f <> g = Put $ \s -> case runPut f s of
Result s' m -> case runPut g s' of
Result s'' n -> Result s'' (m <> n)
instance Monoid Put where
mempty = Put $ \s -> Result s mempty
push :: Bool -> Int -> Word8 -> (Builder, Int, Word8)
push v i b
| i == 7 = (Builder.word8 b', 0, 0)
| otherwise = (mempty, i + 1, b')
where b' = if v then setBit b i else b
# INLINE push #
meta :: Bool -> Put
meta v = Put $ \(State i b j c) -> case push v i b of
(m,i',b') -> Result (State i' b' j c) (W m mempty mempty 1)
paren :: Bool -> Put
paren v = Put $ \(State i b j c) -> case push v j c of
(s,j',c') -> case push True i b of
(m, i', b') -> Result (State i' b' j' c') (W m s mempty 1)
parens :: Put -> Put
parens p = paren True <> p <> paren False
push a run of 0s into the meta buffer
metas :: Int -> Put
metas k
| k <= 0 = mempty
| otherwise = Put $ \(State i b j c) -> case divMod (i + k) 8 of
(0,r) -> Result (State r b j c) $ W mempty mempty mempty (fromIntegral k)
(q,r) -> Result (State r 0 j c) $
W (Builder.word8 b <> stimesMonoid (q-1) (Builder.word8 0))
mempty
mempty
(fromIntegral k)
content :: Builder -> Put
content m = Put $ \s -> Result s (W mempty mempty m 0)
put8 :: Word8 -> Put
put8 x = meta False <> content (word8 x)
putN :: Int -> Builder -> Put
putN i w = metas i <> content w
putN_ :: Builder -> Put
putN_ w = putN (fromIntegral $ Lazy.length bs) (Builder.lazyByteString bs) where
bs = Builder.toLazyByteString w
--------------------------------------------------------------------------------
-- * Puttable
--------------------------------------------------------------------------------
class Sized a => Puttable a where
put :: a -> Put
default put :: (G.Generic a, SOP.GFrom a, SOP.All2 Puttable (SOP.GCode a)) => a -> Put
put = gput
gput :: (G.Generic a, SOP.GFrom a, SOP.All2 Puttable (SOP.GCode a)) => a -> Put
gput xs0 = case SOP.lengthSList sop of
1 -> case sop of
SOP.Z xs -> products xs
_ -> error "the impossible happened"
_ -> sums 0 sop
where
SOP.SOP sop = SOP.gfrom xs0
sums :: SOP.All2 Puttable xss => Word8 -> SOP.NS (SOP.NP SOP.I) xss -> Put
sums !acc (SOP.Z xs) = put8 acc <> products xs
sums acc (SOP.S xss) = sums (acc + 1) xss
products :: SOP.All Puttable xs => SOP.NP SOP.I xs -> Put
products SOP.Nil = mempty
products (SOP.I x SOP.:* xs) = products1 x xs
-- the last field is written without parens
products1 :: (Puttable x, SOP.All Puttable xs) => x -> SOP.NP SOP.I xs -> Put
products1 x SOP.Nil = put x
products1 x (SOP.I y SOP.:* ys) = putWithParens x <> products1 y ys
putWithParens :: forall a. Puttable a => a -> Put
putWithParens = case size @a of
Variable -> parens . put
_ -> put
instance Puttable Void where
put = absurd
instance Puttable Word64 where
put = putN 8 . Builder.word64LE
instance Puttable Word32 where
put = putN 4 . Builder.word32LE
instance Puttable Word16 where
put = putN 2 . Builder.word16LE
instance Puttable Word8 where
put = putN 1 . Builder.word8
instance Puttable Int64 where
put = putN 8 . Builder.int64LE
instance Puttable Int32 where
put = putN 4 . Builder.int32LE
instance Puttable Int16 where
put = putN 2 . Builder.int16LE
instance Puttable Int8 where
put = putN 1 . Builder.int8
instance Puttable Char where
put = put . (fromIntegral . fromEnum :: Char -> Word32)
instance Puttable ()
instance Puttable (Proxy a)
instance Puttable a => Puttable (Maybe a)
instance Puttable a => Puttable [a]
instance (Puttable a, Puttable b) => Puttable (a, b)
instance (Puttable a, Puttable b) => Puttable (Either a b)
instance Puttable (f (g a)) => Puttable (Compose f g a)
instance (Puttable (f a), Puttable (g a)) => Puttable (F.Product f g a)
instance (Puttable (f a), Puttable (g a)) => Puttable (F.Sum f g a)
| null |
https://raw.githubusercontent.com/ekmett/succinct-binary/c8731ba6617e83ab416faffde95a118c4a3eef38/src/Data/Binary/Succinct/Put.hs
|
haskell
|
# language DeriveFunctor #
# language DefaultSignatures #
# language FlexibleContexts #
# language ScopedTypeVariables #
.Internal
guts
# UNPACK #
# UNPACK #
------------------------------------------------------------------------------
* Puttable
------------------------------------------------------------------------------
the last field is written without parens
|
# language BangPatterns #
# language EmptyCase #
# language GADTs #
# language TypeOperators #
# language RankNTypes #
# language TypeApplications #
# options_ghc -funbox - strict - fields #
( Put(..)
, meta, metas, paren, parens, content
, State(..)
, W(..)
, Result(..)
, put8
, Puttable(..)
, putN
, putN_
, gput
) where
import Data.Bits
import Data.ByteString.Lazy as Lazy
import Data.ByteString.Builder as Builder
import Data.Int
import Data.Proxy
import Data.Semigroup
import Data.Void
import Data.Word
import qualified GHC.Generics as G
import Data.Functor.Compose as F
import Data.Functor.Product as F
import Data.Functor.Sum as F
import qualified Generics.SOP as SOP
import qualified Generics.SOP.GGP as SOP
import Data.Binary.Succinct.Size
data State = State !Int !Word8 !Int !Word8
data W = W !Builder !Builder !Builder !Word64
instance Semigroup W where
W a b c m <> W d e f n = W (a <> d) (b <> e) (c <> f) (m + n)
instance Monoid W where
mempty = W mempty mempty mempty 0
mappend = (<>)
newtype Put = Put { runPut :: State -> Result }
instance Semigroup Put where
f <> g = Put $ \s -> case runPut f s of
Result s' m -> case runPut g s' of
Result s'' n -> Result s'' (m <> n)
instance Monoid Put where
mempty = Put $ \s -> Result s mempty
push :: Bool -> Int -> Word8 -> (Builder, Int, Word8)
push v i b
| i == 7 = (Builder.word8 b', 0, 0)
| otherwise = (mempty, i + 1, b')
where b' = if v then setBit b i else b
# INLINE push #
meta :: Bool -> Put
meta v = Put $ \(State i b j c) -> case push v i b of
(m,i',b') -> Result (State i' b' j c) (W m mempty mempty 1)
paren :: Bool -> Put
paren v = Put $ \(State i b j c) -> case push v j c of
(s,j',c') -> case push True i b of
(m, i', b') -> Result (State i' b' j' c') (W m s mempty 1)
parens :: Put -> Put
parens p = paren True <> p <> paren False
push a run of 0s into the meta buffer
metas :: Int -> Put
metas k
| k <= 0 = mempty
| otherwise = Put $ \(State i b j c) -> case divMod (i + k) 8 of
(0,r) -> Result (State r b j c) $ W mempty mempty mempty (fromIntegral k)
(q,r) -> Result (State r 0 j c) $
W (Builder.word8 b <> stimesMonoid (q-1) (Builder.word8 0))
mempty
mempty
(fromIntegral k)
content :: Builder -> Put
content m = Put $ \s -> Result s (W mempty mempty m 0)
put8 :: Word8 -> Put
put8 x = meta False <> content (word8 x)
putN :: Int -> Builder -> Put
putN i w = metas i <> content w
putN_ :: Builder -> Put
putN_ w = putN (fromIntegral $ Lazy.length bs) (Builder.lazyByteString bs) where
bs = Builder.toLazyByteString w
class Sized a => Puttable a where
put :: a -> Put
default put :: (G.Generic a, SOP.GFrom a, SOP.All2 Puttable (SOP.GCode a)) => a -> Put
put = gput
gput :: (G.Generic a, SOP.GFrom a, SOP.All2 Puttable (SOP.GCode a)) => a -> Put
gput xs0 = case SOP.lengthSList sop of
1 -> case sop of
SOP.Z xs -> products xs
_ -> error "the impossible happened"
_ -> sums 0 sop
where
SOP.SOP sop = SOP.gfrom xs0
sums :: SOP.All2 Puttable xss => Word8 -> SOP.NS (SOP.NP SOP.I) xss -> Put
sums !acc (SOP.Z xs) = put8 acc <> products xs
sums acc (SOP.S xss) = sums (acc + 1) xss
products :: SOP.All Puttable xs => SOP.NP SOP.I xs -> Put
products SOP.Nil = mempty
products (SOP.I x SOP.:* xs) = products1 x xs
products1 :: (Puttable x, SOP.All Puttable xs) => x -> SOP.NP SOP.I xs -> Put
products1 x SOP.Nil = put x
products1 x (SOP.I y SOP.:* ys) = putWithParens x <> products1 y ys
putWithParens :: forall a. Puttable a => a -> Put
putWithParens = case size @a of
Variable -> parens . put
_ -> put
instance Puttable Void where
put = absurd
instance Puttable Word64 where
put = putN 8 . Builder.word64LE
instance Puttable Word32 where
put = putN 4 . Builder.word32LE
instance Puttable Word16 where
put = putN 2 . Builder.word16LE
instance Puttable Word8 where
put = putN 1 . Builder.word8
instance Puttable Int64 where
put = putN 8 . Builder.int64LE
instance Puttable Int32 where
put = putN 4 . Builder.int32LE
instance Puttable Int16 where
put = putN 2 . Builder.int16LE
instance Puttable Int8 where
put = putN 1 . Builder.int8
instance Puttable Char where
put = put . (fromIntegral . fromEnum :: Char -> Word32)
instance Puttable ()
instance Puttable (Proxy a)
instance Puttable a => Puttable (Maybe a)
instance Puttable a => Puttable [a]
instance (Puttable a, Puttable b) => Puttable (a, b)
instance (Puttable a, Puttable b) => Puttable (Either a b)
instance Puttable (f (g a)) => Puttable (Compose f g a)
instance (Puttable (f a), Puttable (g a)) => Puttable (F.Product f g a)
instance (Puttable (f a), Puttable (g a)) => Puttable (F.Sum f g a)
|
1324fe8136c07e26044292ba004e3a2742cbaf8127a3c53c9f987cf3a8e0fabb
|
valderman/haste-compiler
|
Gregorian.hs
|
{-# OPTIONS -fno-warn-orphans #-}
-- #hide
module Data.Time.Calendar.Gregorian
(
-- * Gregorian calendar
toGregorian,fromGregorian,fromGregorianValid,showGregorian,gregorianMonthLength,
-- calendrical arithmetic
e.g. " one month after March 31st "
addGregorianMonthsClip,addGregorianMonthsRollOver,
addGregorianYearsClip,addGregorianYearsRollOver,
re - exported from OrdinalDate
isLeapYear
) where
import Data.Time.Calendar.MonthDay
import Data.Time.Calendar.OrdinalDate
import Data.Time.Calendar.Days
import Data.Time.Calendar.Private
| convert to proleptic calendar . First element of result is year , second month number ( 1 - 12 ) , third day ( 1 - 31 ) .
toGregorian :: Day -> (Integer,Int,Int)
toGregorian date = (year,month,day) where
(year,yd) = toOrdinalDate date
(month,day) = dayOfYearToMonthAndDay (isLeapYear year) yd
| convert from proleptic calendar . First argument is year , second month number ( 1 - 12 ) , third day ( 1 - 31 ) .
Invalid values will be clipped to the correct range , month first , then day .
fromGregorian :: Integer -> Int -> Int -> Day
fromGregorian year month day = fromOrdinalDate year (monthAndDayToDayOfYear (isLeapYear year) month day)
| convert from proleptic calendar . First argument is year , second month number ( 1 - 12 ) , third day ( 1 - 31 ) .
Invalid values will return Nothing
fromGregorianValid :: Integer -> Int -> Int -> Maybe Day
fromGregorianValid year month day = do
doy <- monthAndDayToDayOfYearValid (isLeapYear year) month day
fromOrdinalDateValid year doy
| show in ISO 8601 format ( yyyy - mm - dd )
showGregorian :: Day -> String
showGregorian date = (show4 (Just '0') y) ++ "-" ++ (show2 (Just '0') m) ++ "-" ++ (show2 (Just '0') d) where
(y,m,d) = toGregorian date
| The number of days in a given month according to the proleptic calendar . First argument is year , second is month .
gregorianMonthLength :: Integer -> Int -> Int
gregorianMonthLength year = monthLength (isLeapYear year)
rolloverMonths :: (Integer,Integer) -> (Integer,Int)
rolloverMonths (y,m) = (y + (div (m - 1) 12),fromIntegral (mod (m - 1) 12) + 1)
addGregorianMonths :: Integer -> Day -> (Integer,Int,Int)
addGregorianMonths n day = (y',m',d) where
(y,m,d) = toGregorian day
(y',m') = rolloverMonths (y,fromIntegral m + n)
| Add months , with days past the last day of the month clipped to the last day .
For instance , 2005 - 01 - 30 + 1 month = 2005 - 02 - 28 .
addGregorianMonthsClip :: Integer -> Day -> Day
addGregorianMonthsClip n day = fromGregorian y m d where
(y,m,d) = addGregorianMonths n day
| Add months , with days past the last day of the month rolling over to the next month .
For instance , 2005 - 01 - 30 + 1 month = 2005 - 03 - 02 .
addGregorianMonthsRollOver :: Integer -> Day -> Day
addGregorianMonthsRollOver n day = addDays (fromIntegral d - 1) (fromGregorian y m 1) where
(y,m,d) = addGregorianMonths n day
| Add years , matching month and day , with Feb 29th clipped to Feb 28th if necessary .
For instance , 2004 - 02 - 29 + 2 years = 2006 - 02 - 28 .
addGregorianYearsClip :: Integer -> Day -> Day
addGregorianYearsClip n = addGregorianMonthsClip (n * 12)
| Add years , matching month and day , with Feb 29th rolled over to Mar 1st if necessary .
For instance , 2004 - 02 - 29 + 2 years = 2006 - 03 - 01 .
addGregorianYearsRollOver :: Integer -> Day -> Day
addGregorianYearsRollOver n = addGregorianMonthsRollOver (n * 12)
-- orphan instance
instance Show Day where
show = showGregorian
| null |
https://raw.githubusercontent.com/valderman/haste-compiler/47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8/libraries/time/lib/Data/Time/Calendar/Gregorian.hs
|
haskell
|
# OPTIONS -fno-warn-orphans #
#hide
* Gregorian calendar
calendrical arithmetic
orphan instance
|
module Data.Time.Calendar.Gregorian
(
toGregorian,fromGregorian,fromGregorianValid,showGregorian,gregorianMonthLength,
e.g. " one month after March 31st "
addGregorianMonthsClip,addGregorianMonthsRollOver,
addGregorianYearsClip,addGregorianYearsRollOver,
re - exported from OrdinalDate
isLeapYear
) where
import Data.Time.Calendar.MonthDay
import Data.Time.Calendar.OrdinalDate
import Data.Time.Calendar.Days
import Data.Time.Calendar.Private
| convert to proleptic calendar . First element of result is year , second month number ( 1 - 12 ) , third day ( 1 - 31 ) .
toGregorian :: Day -> (Integer,Int,Int)
toGregorian date = (year,month,day) where
(year,yd) = toOrdinalDate date
(month,day) = dayOfYearToMonthAndDay (isLeapYear year) yd
| convert from proleptic calendar . First argument is year , second month number ( 1 - 12 ) , third day ( 1 - 31 ) .
Invalid values will be clipped to the correct range , month first , then day .
fromGregorian :: Integer -> Int -> Int -> Day
fromGregorian year month day = fromOrdinalDate year (monthAndDayToDayOfYear (isLeapYear year) month day)
| convert from proleptic calendar . First argument is year , second month number ( 1 - 12 ) , third day ( 1 - 31 ) .
Invalid values will return Nothing
fromGregorianValid :: Integer -> Int -> Int -> Maybe Day
fromGregorianValid year month day = do
doy <- monthAndDayToDayOfYearValid (isLeapYear year) month day
fromOrdinalDateValid year doy
| show in ISO 8601 format ( yyyy - mm - dd )
showGregorian :: Day -> String
showGregorian date = (show4 (Just '0') y) ++ "-" ++ (show2 (Just '0') m) ++ "-" ++ (show2 (Just '0') d) where
(y,m,d) = toGregorian date
| The number of days in a given month according to the proleptic calendar . First argument is year , second is month .
gregorianMonthLength :: Integer -> Int -> Int
gregorianMonthLength year = monthLength (isLeapYear year)
rolloverMonths :: (Integer,Integer) -> (Integer,Int)
rolloverMonths (y,m) = (y + (div (m - 1) 12),fromIntegral (mod (m - 1) 12) + 1)
addGregorianMonths :: Integer -> Day -> (Integer,Int,Int)
addGregorianMonths n day = (y',m',d) where
(y,m,d) = toGregorian day
(y',m') = rolloverMonths (y,fromIntegral m + n)
| Add months , with days past the last day of the month clipped to the last day .
For instance , 2005 - 01 - 30 + 1 month = 2005 - 02 - 28 .
addGregorianMonthsClip :: Integer -> Day -> Day
addGregorianMonthsClip n day = fromGregorian y m d where
(y,m,d) = addGregorianMonths n day
| Add months , with days past the last day of the month rolling over to the next month .
For instance , 2005 - 01 - 30 + 1 month = 2005 - 03 - 02 .
addGregorianMonthsRollOver :: Integer -> Day -> Day
addGregorianMonthsRollOver n day = addDays (fromIntegral d - 1) (fromGregorian y m 1) where
(y,m,d) = addGregorianMonths n day
| Add years , matching month and day , with Feb 29th clipped to Feb 28th if necessary .
For instance , 2004 - 02 - 29 + 2 years = 2006 - 02 - 28 .
addGregorianYearsClip :: Integer -> Day -> Day
addGregorianYearsClip n = addGregorianMonthsClip (n * 12)
| Add years , matching month and day , with Feb 29th rolled over to Mar 1st if necessary .
For instance , 2004 - 02 - 29 + 2 years = 2006 - 03 - 01 .
addGregorianYearsRollOver :: Integer -> Day -> Day
addGregorianYearsRollOver n = addGregorianMonthsRollOver (n * 12)
instance Show Day where
show = showGregorian
|
cdcbadcbbc5f52bb015e42abce5b0c00197a4aff07ee404dca078c55960dfd69
|
Apress/practical-ocaml
|
ch_04.ml
|
let a = 5;;
let b = 10;;
a + b;;
let myfunc () = 1 + 1;;
myfunc ();;
let myfunc = (fun () -> 1 + 1);;
myfunc ();;
let myfunc x y =
let someval = x + y in
Printf.printf "Hello internal value: %i\n" someval;;
myfunc 10 20;;
let errorprone x = try
while !x < 10 do
incr x
done
with _ -> "Failed";;
let errorprone x = try
while !x < 10 do
incr x
done
with _ -> ();;
let mismatching (x:int) (y: float) = x + (int_of_string y);;
let bigger f x y = f x y;;
bigger (>) 10 20;;
bigger (<) 10 20;;
bigger < 10 20;;
let add_one = (+) 1;;
add_one 10;;
(fun x y -> x * y);;
[1;2;3;4;5];;
List.sort compare [4;5;6;2;4;2;0];;
List.nth [0;1;2;3;4] 3;;
List.nth [0;1;2;3;4] 0;;
List.sort (fun x y -> if x = y then
-1
else if x < y then
1
else
0) [1;4;9;3;2;1];;
List.sort compare [1;4;9;3;2;1];;
Scanf.sscanf "hello world" "%s %s" (fun x y -> Printf.printf "%s %s\n" y x);;
(fun x -> 10);;
(fun x -> 10 + x) 30;;
Printf.printf "%s\n";;
let funclist = [Printf.printf "%s\n"];;
(List.nth funclist 0) "hello world";;
List.fold_left (+) 0 [1;2;3;4;5];;
let sum = List.fold_left (+) 0;;
sum [1;2;3;4;5;6];;
let f x y = x + y;;
let m = [f];;
(List.hd m) == f;;
let b = f;;
b == f;;
let c x y = x + y;;
c == f;;
let compose m y = y m;;
compose (fun x -> x 3.14159) (fun m n o -> (m n) o);;
let b = compose (fun x -> x 3.14159) (fun m n o -> (m n) o);;
b 3.123;;
b (fun n m o -> o);;
(b (fun n m o -> o)) "hi" "there";;
let add_one = (+) 1;;
val add_one : int -> int = <fun
# add_one 10;;
- : int = 11
(Meter 3) %* (Mile 1);;
(Foot 12) %- (Foot 3);;
let rec fib n = if (n < 2) then
1
else
(fib (n - 1)) + (fib (n - 2));;
fib 6;;
let explode_string x =
let strlen = String.length x in
let rec es i acc =
if (i < strlen) then
es (i+1) (x.[i] :: acc)
else
List.rev acc
in
es 0 [];;
let collapse_string x =
let buf = Buffer.create (List.length x) in
let rec cs i = match i with
[] -> Buffer.contents buf
| h :: t -> Buffer.add_char buf h;cs t
in
cs x;;
let wrong_recursive lst acc = match lst with
[] -> acc
| h :: t -> wrong_recursive t ((String.length h) :: acc);;
let rec wrong_recursive lst acc = match lst with
[] -> acc
| h :: t -> wrong_recursive t ((String.length h) :: acc);;
let rec scan_input scan_buf acc_buf = try
Scanf.bscanf scan_buf "%c" (fun x ->
Buffer.add_char acc_buf x);
scan_input scan_buf acc_buf
with End_of_file -> Buffer.contents acc_buf;;
let myfunc x = match x with
n,m,z -> (n+m,z+. 4.);;
myfunc (1,2,3.);;
myfunc 1;;
let myfunc (n,m,z) = (n+m,z+. 0.4);;
let myfunc x = match x with
n,m,z -> n+m+z
| n,m,_ -> n+m;;
let myfunc x = match x with
n,m,_ -> n+m;;
let myfunc (n,m,z) = n+m;;
let rec lispy x acc = match x with
[] -> acc
| head :: tail -> lispy tail (acc + head);;
lispy [1;2;3;4;5] 0;;
let b x y = match x with
0 -> (let q = x in match y with
0 -> 1
| _ -> q)
| 1 -> y
| _ -> x * y;;
b 0 3;;
b 0 0;;
(Foot 0) %%+ (Mile 3);;
(Foot 3) %%+(Mile 3);;
let add_some_labeled ~x ~y = x + y;;
add_some_labeled 10 20;;
add_some_labeled ~x:10 30;;
add_some_labeled ~x:10 ~y:10;;
let increment ?(by = 1) v = v + by;;
increment 10;;
increment ~by:30 10;;
increment 30 10;;
| null |
https://raw.githubusercontent.com/Apress/practical-ocaml/c0f1e36283eb0e495ff8db7f2a88cadbf1a3d49e/Chapter04/ch_04.ml
|
ocaml
|
let a = 5;;
let b = 10;;
a + b;;
let myfunc () = 1 + 1;;
myfunc ();;
let myfunc = (fun () -> 1 + 1);;
myfunc ();;
let myfunc x y =
let someval = x + y in
Printf.printf "Hello internal value: %i\n" someval;;
myfunc 10 20;;
let errorprone x = try
while !x < 10 do
incr x
done
with _ -> "Failed";;
let errorprone x = try
while !x < 10 do
incr x
done
with _ -> ();;
let mismatching (x:int) (y: float) = x + (int_of_string y);;
let bigger f x y = f x y;;
bigger (>) 10 20;;
bigger (<) 10 20;;
bigger < 10 20;;
let add_one = (+) 1;;
add_one 10;;
(fun x y -> x * y);;
[1;2;3;4;5];;
List.sort compare [4;5;6;2;4;2;0];;
List.nth [0;1;2;3;4] 3;;
List.nth [0;1;2;3;4] 0;;
List.sort (fun x y -> if x = y then
-1
else if x < y then
1
else
0) [1;4;9;3;2;1];;
List.sort compare [1;4;9;3;2;1];;
Scanf.sscanf "hello world" "%s %s" (fun x y -> Printf.printf "%s %s\n" y x);;
(fun x -> 10);;
(fun x -> 10 + x) 30;;
Printf.printf "%s\n";;
let funclist = [Printf.printf "%s\n"];;
(List.nth funclist 0) "hello world";;
List.fold_left (+) 0 [1;2;3;4;5];;
let sum = List.fold_left (+) 0;;
sum [1;2;3;4;5;6];;
let f x y = x + y;;
let m = [f];;
(List.hd m) == f;;
let b = f;;
b == f;;
let c x y = x + y;;
c == f;;
let compose m y = y m;;
compose (fun x -> x 3.14159) (fun m n o -> (m n) o);;
let b = compose (fun x -> x 3.14159) (fun m n o -> (m n) o);;
b 3.123;;
b (fun n m o -> o);;
(b (fun n m o -> o)) "hi" "there";;
let add_one = (+) 1;;
val add_one : int -> int = <fun
# add_one 10;;
- : int = 11
(Meter 3) %* (Mile 1);;
(Foot 12) %- (Foot 3);;
let rec fib n = if (n < 2) then
1
else
(fib (n - 1)) + (fib (n - 2));;
fib 6;;
let explode_string x =
let strlen = String.length x in
let rec es i acc =
if (i < strlen) then
es (i+1) (x.[i] :: acc)
else
List.rev acc
in
es 0 [];;
let collapse_string x =
let buf = Buffer.create (List.length x) in
let rec cs i = match i with
[] -> Buffer.contents buf
| h :: t -> Buffer.add_char buf h;cs t
in
cs x;;
let wrong_recursive lst acc = match lst with
[] -> acc
| h :: t -> wrong_recursive t ((String.length h) :: acc);;
let rec wrong_recursive lst acc = match lst with
[] -> acc
| h :: t -> wrong_recursive t ((String.length h) :: acc);;
let rec scan_input scan_buf acc_buf = try
Scanf.bscanf scan_buf "%c" (fun x ->
Buffer.add_char acc_buf x);
scan_input scan_buf acc_buf
with End_of_file -> Buffer.contents acc_buf;;
let myfunc x = match x with
n,m,z -> (n+m,z+. 4.);;
myfunc (1,2,3.);;
myfunc 1;;
let myfunc (n,m,z) = (n+m,z+. 0.4);;
let myfunc x = match x with
n,m,z -> n+m+z
| n,m,_ -> n+m;;
let myfunc x = match x with
n,m,_ -> n+m;;
let myfunc (n,m,z) = n+m;;
let rec lispy x acc = match x with
[] -> acc
| head :: tail -> lispy tail (acc + head);;
lispy [1;2;3;4;5] 0;;
let b x y = match x with
0 -> (let q = x in match y with
0 -> 1
| _ -> q)
| 1 -> y
| _ -> x * y;;
b 0 3;;
b 0 0;;
(Foot 0) %%+ (Mile 3);;
(Foot 3) %%+(Mile 3);;
let add_some_labeled ~x ~y = x + y;;
add_some_labeled 10 20;;
add_some_labeled ~x:10 30;;
add_some_labeled ~x:10 ~y:10;;
let increment ?(by = 1) v = v + by;;
increment 10;;
increment ~by:30 10;;
increment 30 10;;
|
|
a25e0a67d0c5050cbf5ca24f27f927cc313520b9b4d29bad64eb3a68a1bcd835
|
camfort/fortran-src
|
ParserUtils.hs
|
# LANGUAGE CPP #
{-| Utils for various parsers (beyond token level).
We can sometimes work around there being free-form and fixed-form versions of
the @LexAction@ monad by requesting the underlying instances instances. We place
such utilities that match that form here.
-}
module Language.Fortran.Parser.ParserUtils where
import Language.Fortran.AST
import Language.Fortran.AST.Literal.Real
import Language.Fortran.AST.Literal.Complex
import Language.Fortran.Util.Position
#if !MIN_VERSION_base(4,13,0)
Control . Monad . Fail import is redundant since GHC 8.8.1
import Control.Monad.Fail ( MonadFail )
#endif
$ complex - lit - parsing
Parsing complex literal parts unambiguously is a pain , so instead , we parse any
expression , then case on it to determine if it 's valid for a complex literal
part -- and if so , push it into a ' ComplexPart ' constructor . This may cause
unexpected behaviour if more bracketing / tuple rules are added !
Parsing complex literal parts unambiguously is a pain, so instead, we parse any
expression, then case on it to determine if it's valid for a complex literal
part -- and if so, push it into a 'ComplexPart' constructor. This may cause
unexpected behaviour if more bracketing/tuple rules are added!
-}
-- | Try to validate an expression as a COMPLEX literal part.
--
-- $complex-lit-parsing
exprToComplexLitPart :: MonadFail m => Expression a -> m (ComplexPart a)
exprToComplexLitPart e =
case e' of
ExpValue a ss val ->
case val of
ValReal r mkp ->
let r' = r { realLitSignificand = sign <> realLitSignificand r }
in return $ ComplexPartReal a ss r' mkp
ValInteger i mkp -> return $ ComplexPartInt a ss (sign<>i) mkp
ValVariable var -> return $ ComplexPartNamed a ss var
_ -> fail $ "Invalid COMPLEX literal @ " <> show ss
_ -> fail $ "Invalid COMPLEX literal @ " <> show (getSpan e')
where
(sign, e') = case e of ExpUnary _ _ Minus e'' -> ("-", e'')
ExpUnary _ _ Plus e'' -> ("", e'')
_ -> ("", e)
-- | Helper for forming COMPLEX literals.
complexLit
:: MonadFail m => SrcSpan -> Expression A0 -> Expression A0
-> m (Expression A0)
complexLit ss e1 e2 = do
compReal <- exprToComplexLitPart e1
compImag <- exprToComplexLitPart e2
return $ ExpValue () ss $ ValComplex $ ComplexLit () ss compReal compImag
| null |
https://raw.githubusercontent.com/camfort/fortran-src/9a333f0b01abf830ab269fa021555be263e0ccaa/src/Language/Fortran/Parser/ParserUtils.hs
|
haskell
|
| Utils for various parsers (beyond token level).
We can sometimes work around there being free-form and fixed-form versions of
the @LexAction@ monad by requesting the underlying instances instances. We place
such utilities that match that form here.
and if so , push it into a ' ComplexPart ' constructor . This may cause
and if so, push it into a 'ComplexPart' constructor. This may cause
| Try to validate an expression as a COMPLEX literal part.
$complex-lit-parsing
| Helper for forming COMPLEX literals.
|
# LANGUAGE CPP #
module Language.Fortran.Parser.ParserUtils where
import Language.Fortran.AST
import Language.Fortran.AST.Literal.Real
import Language.Fortran.AST.Literal.Complex
import Language.Fortran.Util.Position
#if !MIN_VERSION_base(4,13,0)
Control . Monad . Fail import is redundant since GHC 8.8.1
import Control.Monad.Fail ( MonadFail )
#endif
$ complex - lit - parsing
Parsing complex literal parts unambiguously is a pain , so instead , we parse any
expression , then case on it to determine if it 's valid for a complex literal
unexpected behaviour if more bracketing / tuple rules are added !
Parsing complex literal parts unambiguously is a pain, so instead, we parse any
expression, then case on it to determine if it's valid for a complex literal
unexpected behaviour if more bracketing/tuple rules are added!
-}
exprToComplexLitPart :: MonadFail m => Expression a -> m (ComplexPart a)
exprToComplexLitPart e =
case e' of
ExpValue a ss val ->
case val of
ValReal r mkp ->
let r' = r { realLitSignificand = sign <> realLitSignificand r }
in return $ ComplexPartReal a ss r' mkp
ValInteger i mkp -> return $ ComplexPartInt a ss (sign<>i) mkp
ValVariable var -> return $ ComplexPartNamed a ss var
_ -> fail $ "Invalid COMPLEX literal @ " <> show ss
_ -> fail $ "Invalid COMPLEX literal @ " <> show (getSpan e')
where
(sign, e') = case e of ExpUnary _ _ Minus e'' -> ("-", e'')
ExpUnary _ _ Plus e'' -> ("", e'')
_ -> ("", e)
complexLit
:: MonadFail m => SrcSpan -> Expression A0 -> Expression A0
-> m (Expression A0)
complexLit ss e1 e2 = do
compReal <- exprToComplexLitPart e1
compImag <- exprToComplexLitPart e2
return $ ExpValue () ss $ ValComplex $ ComplexLit () ss compReal compImag
|
8ada5f34efdd0957b7a9e2dd881396a4fd78dcf3cefb9d0975705d553abdbe56
|
hiratara/Haskell-Nyumon-Sample
|
chap02-samples-2-5-sample3.hs
|
-- sample3.hs
main :: IO ()
main = do
putStrLn "Hello, world!"
putStrLn "from first hs file."
| null |
https://raw.githubusercontent.com/hiratara/Haskell-Nyumon-Sample/ac52b741e3b96722f6fc104cfa84078e39f7a241/chap02-samples/chap02-samples-2-5-sample3.hs
|
haskell
|
sample3.hs
|
main :: IO ()
main = do
putStrLn "Hello, world!"
putStrLn "from first hs file."
|
ea5cec5902dfc8d3dcf6fee63d682be8e013f15b61afcc7b69043e8a8fafddf7
|
cirodrig/triolet
|
LocalCPSAnn.hs
|
| Annotated IR used for the local continuation - passing transformation .
The LCPS transformation reorganizes local functions in a way that
increases the number of functions that can be translated to local
procedures , which execute more efficiently than hoisted functions .
To perform the transformation , @let@-expressions must be labeled .
This module defines the labeled IR and insertion / removal of labels .
The LCPS transformation is described in the paper
\"Optimizing Nested Loops Using Local CPS Conversion\ " by ,
in Proc . Higher - Order and Symbolic Computation 15 , p. 161 - 180 , 2002 .
The LCPS transformation reorganizes local functions in a way that
increases the number of functions that can be translated to local
procedures, which execute more efficiently than hoisted functions.
To perform the transformation, @let@-expressions must be labeled.
This module defines the labeled IR and insertion/removal of labels.
The LCPS transformation is described in the paper
\"Optimizing Nested Loops Using Local CPS Conversion\" by John Reppy,
in Proc. Higher-Order and Symbolic Computation 15, p. 161-180, 2002.
-}
# LANGUAGE GeneralizedNewtypeDeriving , FlexibleInstances #
module LowLevel.Closure.LocalCPSAnn
(LStm(..), GroupLabel, GroupLabel, LAlt, LFunDef, LFun,
labelFunction,
pprLStm,
pprLFunDef,
unAnnotate,
unAnnotateDef
)
where
import Prelude hiding(mapM)
import Control.Applicative hiding(empty)
import Control.Monad hiding(mapM, forM, join)
import Control.Monad.Reader
import Data.Traversable
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IntSet
import Data.Maybe
import Text.PrettyPrint.HughesPJ
import Common.Error
import Common.Identifier
import Common.Supply
import LowLevel.CodeTypes
import LowLevel.FreshVar
import LowLevel.Print
import LowLevel.Syntax
import Globals
-------------------------------------------------------------------------------
-- | A LCPS Statement. This is like 'Stm' except that let-expressions are
-- annotated with a variable. The variable stands for the body of the
-- let-expression; if the body is turned into a function, then that variable
-- becomes the function's name.
data LStm =
LetLCPS [ParamVar] Atom !Var LStm
| LetrecLCPS !(Group LFunDef) !(Ident GroupLabel) LStm
| SwitchLCPS Val [LAlt]
| ReturnLCPS Atom
| ThrowLCPS Val
-- | This uninhabited data type is used as the ID type for definition groups.
data GroupLabel
type LAlt = (Lit, LStm)
type LFunDef = Def LFun
type LFun = FunBase LStm
newtype Ann a = Ann (ReaderT (IdentSupply Var, IdentSupply GroupLabel) IO a)
deriving(Functor, Applicative, Monad)
instance Supplies Ann (Ident Var) where
fresh = Ann $ ReaderT $ \(supply, _) -> supplyValue supply
instance Supplies Ann (Ident GroupLabel) where
fresh = Ann $ ReaderT $ \(_, supply) -> supplyValue supply
annotateStm :: Stm -> Ann LStm
annotateStm statement =
case statement
of LetE params rhs body -> do
v <- newAnonymousVar (PrimType OwnedType)
body' <- annotateStm body
return $ LetLCPS params rhs v body'
LetrecE defs body ->
LetrecLCPS <$> traverse annotateFunDef defs <*> fresh <*> annotateStm body
SwitchE scr alts ->
SwitchLCPS scr <$> traverse do_alt alts
ReturnE atom -> pure $ ReturnLCPS atom
ThrowE val -> pure $ ThrowLCPS val
where
do_alt (k, stm) = (,) k <$> annotateStm stm
annotateFun :: Fun -> Ann LFun
annotateFun f = changeFunBodyM annotateStm f
annotateFunDef :: FunDef -> Ann LFunDef
annotateFunDef (Def v f) = Def v <$> annotateFun f
labelFunction :: IdentSupply Var -> Fun -> IO (LFun, Ident GroupLabel)
labelFunction var_supply f = do
group_supply <- newIdentSupply
lfun <- runReaderT (case annotateFun f of Ann x -> x) (var_supply, group_supply)
max_group_id <- supplyValue group_supply
return (lfun, max_group_id)
unAnnotate :: LStm -> Stm
unAnnotate statement =
case statement
of LetLCPS params rhs _ body -> LetE params rhs (unAnnotate body)
LetrecLCPS defs _ body -> LetrecE (fmap do_def defs) (unAnnotate body)
SwitchLCPS scr alts -> SwitchE scr (map do_alt alts)
ReturnLCPS atom -> ReturnE atom
ThrowLCPS val -> ThrowE val
where
do_def (Def v f) = Def v (unAnnotateFun f)
do_alt (k, stm) = (k, unAnnotate stm)
unAnnotateFun :: LFun -> Fun
unAnnotateFun = changeFunBody unAnnotate
unAnnotateDef :: Def LFun -> Def Fun
unAnnotateDef (Def v f) = Def v (unAnnotateFun f)
-------------------------------------------------------------------------------
pprLStm :: LStm -> Doc
pprLStm stmt = pprLabeledLStm empty stmt
-- | Pretty-print a statement, preceded by a label. This code is a modified
-- version of 'pprStm'.
pprLabeledLStm :: Doc -> LStm -> Doc
pprLabeledLStm label stmt =
case stmt
of LetLCPS [] atom v body ->
label <+> text "[] <-" <+> pprAtom atom $$
pprLabeledLStm (pprVar v <+> text ":") body
LetLCPS vars atom v body ->
let binder = sep $ punctuate (text ",") $ map pprVarLong vars
rhs = pprAtom atom
in hang (label <+> binder <+> text "<-") 8 rhs $$
pprLabeledLStm (pprVar v <+> text ":") body
LetrecLCPS defs lab body ->
label <+> text "let<" <> text (show lab) <> text ">" <+> pprGroup pprLFunDef defs $$
pprLStm body
SwitchLCPS val alts ->
label <+> text "switch" <> parens (pprVal val) $$
nest 2 (vcat $ map print_alt alts)
ReturnLCPS atom -> label <+> pprAtom atom
ThrowLCPS val -> label <+> text "throw" <+> pprVal val
where
print_alt (lit, body) = hang (pprLit lit <> text ":") 6 (pprLStm body)
-- | Pretty-print a function definition. This code is a modified
-- version of 'pprFunDef'.
pprLFunDef :: Def LFun -> Doc
pprLFunDef (Def v f) =
let intro = case funConvention f
of JoinCall -> text "label"
ClosureCall -> text "function"
PrimCall -> text "procedure"
uses = case funUses f
of ZeroUses -> text "[0]"
OneUse -> text "[1]"
ManyUses -> empty
inl = if funInlineRequest f then text "INLINE" else empty
param_doc = map pprVarLong $ funParams f
ret_doc = map pprValueType $ funReturnTypes f
leader = pprVar v <> pprFunSignature param_doc ret_doc
local_doc = if funFrameSize f == 0
then empty
else text "frame size:" <+> text (show $ funFrameSize f)
in intro <+> uses <+> inl <+> leader <+> text "=" $$
nest 4 local_doc $$
nest 4 (pprLStm (funBody f))
| null |
https://raw.githubusercontent.com/cirodrig/triolet/e515a1dc0d6b3e546320eac7b71fb36cea5b53d0/src/program/LowLevel/Closure/LocalCPSAnn.hs
|
haskell
|
-----------------------------------------------------------------------------
| A LCPS Statement. This is like 'Stm' except that let-expressions are
annotated with a variable. The variable stands for the body of the
let-expression; if the body is turned into a function, then that variable
becomes the function's name.
| This uninhabited data type is used as the ID type for definition groups.
-----------------------------------------------------------------------------
| Pretty-print a statement, preceded by a label. This code is a modified
version of 'pprStm'.
| Pretty-print a function definition. This code is a modified
version of 'pprFunDef'.
|
| Annotated IR used for the local continuation - passing transformation .
The LCPS transformation reorganizes local functions in a way that
increases the number of functions that can be translated to local
procedures , which execute more efficiently than hoisted functions .
To perform the transformation , @let@-expressions must be labeled .
This module defines the labeled IR and insertion / removal of labels .
The LCPS transformation is described in the paper
\"Optimizing Nested Loops Using Local CPS Conversion\ " by ,
in Proc . Higher - Order and Symbolic Computation 15 , p. 161 - 180 , 2002 .
The LCPS transformation reorganizes local functions in a way that
increases the number of functions that can be translated to local
procedures, which execute more efficiently than hoisted functions.
To perform the transformation, @let@-expressions must be labeled.
This module defines the labeled IR and insertion/removal of labels.
The LCPS transformation is described in the paper
\"Optimizing Nested Loops Using Local CPS Conversion\" by John Reppy,
in Proc. Higher-Order and Symbolic Computation 15, p. 161-180, 2002.
-}
# LANGUAGE GeneralizedNewtypeDeriving , FlexibleInstances #
module LowLevel.Closure.LocalCPSAnn
(LStm(..), GroupLabel, GroupLabel, LAlt, LFunDef, LFun,
labelFunction,
pprLStm,
pprLFunDef,
unAnnotate,
unAnnotateDef
)
where
import Prelude hiding(mapM)
import Control.Applicative hiding(empty)
import Control.Monad hiding(mapM, forM, join)
import Control.Monad.Reader
import Data.Traversable
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IntSet
import Data.Maybe
import Text.PrettyPrint.HughesPJ
import Common.Error
import Common.Identifier
import Common.Supply
import LowLevel.CodeTypes
import LowLevel.FreshVar
import LowLevel.Print
import LowLevel.Syntax
import Globals
data LStm =
LetLCPS [ParamVar] Atom !Var LStm
| LetrecLCPS !(Group LFunDef) !(Ident GroupLabel) LStm
| SwitchLCPS Val [LAlt]
| ReturnLCPS Atom
| ThrowLCPS Val
data GroupLabel
type LAlt = (Lit, LStm)
type LFunDef = Def LFun
type LFun = FunBase LStm
newtype Ann a = Ann (ReaderT (IdentSupply Var, IdentSupply GroupLabel) IO a)
deriving(Functor, Applicative, Monad)
instance Supplies Ann (Ident Var) where
fresh = Ann $ ReaderT $ \(supply, _) -> supplyValue supply
instance Supplies Ann (Ident GroupLabel) where
fresh = Ann $ ReaderT $ \(_, supply) -> supplyValue supply
annotateStm :: Stm -> Ann LStm
annotateStm statement =
case statement
of LetE params rhs body -> do
v <- newAnonymousVar (PrimType OwnedType)
body' <- annotateStm body
return $ LetLCPS params rhs v body'
LetrecE defs body ->
LetrecLCPS <$> traverse annotateFunDef defs <*> fresh <*> annotateStm body
SwitchE scr alts ->
SwitchLCPS scr <$> traverse do_alt alts
ReturnE atom -> pure $ ReturnLCPS atom
ThrowE val -> pure $ ThrowLCPS val
where
do_alt (k, stm) = (,) k <$> annotateStm stm
annotateFun :: Fun -> Ann LFun
annotateFun f = changeFunBodyM annotateStm f
annotateFunDef :: FunDef -> Ann LFunDef
annotateFunDef (Def v f) = Def v <$> annotateFun f
labelFunction :: IdentSupply Var -> Fun -> IO (LFun, Ident GroupLabel)
labelFunction var_supply f = do
group_supply <- newIdentSupply
lfun <- runReaderT (case annotateFun f of Ann x -> x) (var_supply, group_supply)
max_group_id <- supplyValue group_supply
return (lfun, max_group_id)
unAnnotate :: LStm -> Stm
unAnnotate statement =
case statement
of LetLCPS params rhs _ body -> LetE params rhs (unAnnotate body)
LetrecLCPS defs _ body -> LetrecE (fmap do_def defs) (unAnnotate body)
SwitchLCPS scr alts -> SwitchE scr (map do_alt alts)
ReturnLCPS atom -> ReturnE atom
ThrowLCPS val -> ThrowE val
where
do_def (Def v f) = Def v (unAnnotateFun f)
do_alt (k, stm) = (k, unAnnotate stm)
unAnnotateFun :: LFun -> Fun
unAnnotateFun = changeFunBody unAnnotate
unAnnotateDef :: Def LFun -> Def Fun
unAnnotateDef (Def v f) = Def v (unAnnotateFun f)
pprLStm :: LStm -> Doc
pprLStm stmt = pprLabeledLStm empty stmt
pprLabeledLStm :: Doc -> LStm -> Doc
pprLabeledLStm label stmt =
case stmt
of LetLCPS [] atom v body ->
label <+> text "[] <-" <+> pprAtom atom $$
pprLabeledLStm (pprVar v <+> text ":") body
LetLCPS vars atom v body ->
let binder = sep $ punctuate (text ",") $ map pprVarLong vars
rhs = pprAtom atom
in hang (label <+> binder <+> text "<-") 8 rhs $$
pprLabeledLStm (pprVar v <+> text ":") body
LetrecLCPS defs lab body ->
label <+> text "let<" <> text (show lab) <> text ">" <+> pprGroup pprLFunDef defs $$
pprLStm body
SwitchLCPS val alts ->
label <+> text "switch" <> parens (pprVal val) $$
nest 2 (vcat $ map print_alt alts)
ReturnLCPS atom -> label <+> pprAtom atom
ThrowLCPS val -> label <+> text "throw" <+> pprVal val
where
print_alt (lit, body) = hang (pprLit lit <> text ":") 6 (pprLStm body)
pprLFunDef :: Def LFun -> Doc
pprLFunDef (Def v f) =
let intro = case funConvention f
of JoinCall -> text "label"
ClosureCall -> text "function"
PrimCall -> text "procedure"
uses = case funUses f
of ZeroUses -> text "[0]"
OneUse -> text "[1]"
ManyUses -> empty
inl = if funInlineRequest f then text "INLINE" else empty
param_doc = map pprVarLong $ funParams f
ret_doc = map pprValueType $ funReturnTypes f
leader = pprVar v <> pprFunSignature param_doc ret_doc
local_doc = if funFrameSize f == 0
then empty
else text "frame size:" <+> text (show $ funFrameSize f)
in intro <+> uses <+> inl <+> leader <+> text "=" $$
nest 4 local_doc $$
nest 4 (pprLStm (funBody f))
|
f474782a92dd457123a29fec792db7519d7fefebce329eb8a477296e3ef01f8b
|
psandeepunni/cowboy-automatic-route-dispatcher
|
cards_access_policy.erl
|
-module(cards_access_policy).
-callback execute(Req)
-> {ok, Req, list()}
| {error, Req, list()}
when Req::cowboy_req:req().
| null |
https://raw.githubusercontent.com/psandeepunni/cowboy-automatic-route-dispatcher/f72560f847d00de0bf88b52a26a15fed24cef890/src/cards_access_policy.erl
|
erlang
|
-module(cards_access_policy).
-callback execute(Req)
-> {ok, Req, list()}
| {error, Req, list()}
when Req::cowboy_req:req().
|
|
33b04f30c05248c0c10fd82059c9f08d45f9b9d4a93897a1be92af98692f51c5
|
mauke/data-default
|
Class.hs
|
Copyright ( c ) 2013
All rights reserved .
Redistribution and use in source and binary forms , with or without modification ,
are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright notice , this
list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
* Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY LUKAS MAI AND CONTRIBUTORS " AS IS " AND ANY
EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2013 Lukas Mai
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY LUKAS MAI AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
# LANGUAGE CPP #
#define HAVE_GHC_GENERICS (__GLASGOW_HASKELL__ >= 704)
#if HAVE_GHC_GENERICS
# LANGUAGE DefaultSignatures , TypeOperators , FlexibleContexts #
#endif
module Data.Default.Class (
-- | This module defines a class for types with a default value.
-- It also defines 'Default' instances for the types 'Int', 'Int8',
' Int16 ' , ' Int32 ' , ' Int64 ' , ' Word ' , ' Word8 ' , ' Word16 ' , ' ' , ' Word64 ' ,
' Integer ' , ' Float ' , ' Double ' , ' Ratio ' , ' Complex ' , ' CShort ' , ' CUShort ' ,
' CInt ' , ' CUInt ' , ' ' , ' ' , ' ' , ' ' , ' CPtrdiff ' ,
' CSize ' , ' CSigAtomic ' , ' CIntPtr ' , ' CUIntPtr ' , ' ' , ' ' ,
' CClock ' , ' CTime ' , ' CUSeconds ' , ' ' , ' CFloat ' , ' CDouble ' , ' ( - > ) ' ,
-- 'IO', 'Maybe', '()', '[]', 'Ordering', 'Any', 'All', 'Last', 'First', 'Sum',
-- 'Product', 'Endo', 'Dual', and tuples.
Default(..)
) where
import Data.Int
import Data.Word
import Data.Monoid
import Data.Ratio
import Data.Complex
import Foreign.C.Types
#if HAVE_GHC_GENERICS
import GHC.Generics
class GDefault f where
gdef :: f a
instance GDefault U1 where
gdef = U1
instance (Default a) => GDefault (K1 i a) where
gdef = K1 def
instance (GDefault a, GDefault b) => GDefault (a :*: b) where
gdef = gdef :*: gdef
instance (GDefault a) => GDefault (M1 i c a) where
gdef = M1 gdef
#endif
-- | A class for types with a default value.
class Default a where
-- | The default value for this type.
def :: a
#if HAVE_GHC_GENERICS
default def :: (Generic a, GDefault (Rep a)) => a
def = to gdef
#endif
instance Default Int where def = 0
instance Default Int8 where def = 0
instance Default Int16 where def = 0
instance Default Int32 where def = 0
instance Default Int64 where def = 0
instance Default Word where def = 0
instance Default Word8 where def = 0
instance Default Word16 where def = 0
instance Default Word32 where def = 0
instance Default Word64 where def = 0
instance Default Integer where def = 0
instance Default Float where def = 0
instance Default Double where def = 0
instance (Integral a) => Default (Ratio a) where def = 0
instance (Default a, RealFloat a) => Default (Complex a) where def = def :+ def
instance Default CShort where def = 0
instance Default CUShort where def = 0
instance Default CInt where def = 0
instance Default CUInt where def = 0
instance Default CLong where def = 0
instance Default CULong where def = 0
instance Default CLLong where def = 0
instance Default CULLong where def = 0
instance Default CPtrdiff where def = 0
instance Default CSize where def = 0
instance Default CSigAtomic where def = 0
instance Default CIntPtr where def = 0
instance Default CUIntPtr where def = 0
instance Default CIntMax where def = 0
instance Default CUIntMax where def = 0
instance Default CClock where def = 0
instance Default CTime where def = 0
#if MIN_VERSION_base(4, 4, 0)
instance Default CUSeconds where def = 0
instance Default CSUSeconds where def = 0
#endif
instance Default CFloat where def = 0
instance Default CDouble where def = 0
instance (Default r) => Default (e -> r) where def = const def
instance (Default a) => Default (IO a) where def = return def
instance Default (Maybe a) where def = Nothing
instance Default () where def = mempty
instance Default [a] where def = mempty
instance Default Ordering where def = mempty
instance Default Any where def = mempty
instance Default All where def = mempty
instance Default (Last a) where def = mempty
instance Default (First a) where def = mempty
instance (Num a) => Default (Sum a) where def = mempty
instance (Num a) => Default (Product a) where def = mempty
instance Default (Endo a) where def = mempty
instance (Default a) => Default (Dual a) where def = Dual def
instance (Default a, Default b) => Default (a, b) where def = (def, def)
instance (Default a, Default b, Default c) => Default (a, b, c) where def = (def, def, def)
instance (Default a, Default b, Default c, Default d) => Default (a, b, c, d) where def = (def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e) => Default (a, b, c, d, e) where def = (def, def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e, Default f) => Default (a, b, c, d, e, f) where def = (def, def, def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e, Default f, Default g) => Default (a, b, c, d, e, f, g) where def = (def, def, def, def, def, def, def)
| null |
https://raw.githubusercontent.com/mauke/data-default/b1a08788ca3d6a714319726e3768cf93df92458e/data-default-class/Data/Default/Class.hs
|
haskell
|
| This module defines a class for types with a default value.
It also defines 'Default' instances for the types 'Int', 'Int8',
'IO', 'Maybe', '()', '[]', 'Ordering', 'Any', 'All', 'Last', 'First', 'Sum',
'Product', 'Endo', 'Dual', and tuples.
| A class for types with a default value.
| The default value for this type.
|
Copyright ( c ) 2013
All rights reserved .
Redistribution and use in source and binary forms , with or without modification ,
are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright notice , this
list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright notice ,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution .
* Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY LUKAS MAI AND CONTRIBUTORS " AS IS " AND ANY
EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2013 Lukas Mai
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY LUKAS MAI AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
# LANGUAGE CPP #
#define HAVE_GHC_GENERICS (__GLASGOW_HASKELL__ >= 704)
#if HAVE_GHC_GENERICS
# LANGUAGE DefaultSignatures , TypeOperators , FlexibleContexts #
#endif
module Data.Default.Class (
' Int16 ' , ' Int32 ' , ' Int64 ' , ' Word ' , ' Word8 ' , ' Word16 ' , ' ' , ' Word64 ' ,
' Integer ' , ' Float ' , ' Double ' , ' Ratio ' , ' Complex ' , ' CShort ' , ' CUShort ' ,
' CInt ' , ' CUInt ' , ' ' , ' ' , ' ' , ' ' , ' CPtrdiff ' ,
' CSize ' , ' CSigAtomic ' , ' CIntPtr ' , ' CUIntPtr ' , ' ' , ' ' ,
' CClock ' , ' CTime ' , ' CUSeconds ' , ' ' , ' CFloat ' , ' CDouble ' , ' ( - > ) ' ,
Default(..)
) where
import Data.Int
import Data.Word
import Data.Monoid
import Data.Ratio
import Data.Complex
import Foreign.C.Types
#if HAVE_GHC_GENERICS
import GHC.Generics
class GDefault f where
gdef :: f a
instance GDefault U1 where
gdef = U1
instance (Default a) => GDefault (K1 i a) where
gdef = K1 def
instance (GDefault a, GDefault b) => GDefault (a :*: b) where
gdef = gdef :*: gdef
instance (GDefault a) => GDefault (M1 i c a) where
gdef = M1 gdef
#endif
class Default a where
def :: a
#if HAVE_GHC_GENERICS
default def :: (Generic a, GDefault (Rep a)) => a
def = to gdef
#endif
instance Default Int where def = 0
instance Default Int8 where def = 0
instance Default Int16 where def = 0
instance Default Int32 where def = 0
instance Default Int64 where def = 0
instance Default Word where def = 0
instance Default Word8 where def = 0
instance Default Word16 where def = 0
instance Default Word32 where def = 0
instance Default Word64 where def = 0
instance Default Integer where def = 0
instance Default Float where def = 0
instance Default Double where def = 0
instance (Integral a) => Default (Ratio a) where def = 0
instance (Default a, RealFloat a) => Default (Complex a) where def = def :+ def
instance Default CShort where def = 0
instance Default CUShort where def = 0
instance Default CInt where def = 0
instance Default CUInt where def = 0
instance Default CLong where def = 0
instance Default CULong where def = 0
instance Default CLLong where def = 0
instance Default CULLong where def = 0
instance Default CPtrdiff where def = 0
instance Default CSize where def = 0
instance Default CSigAtomic where def = 0
instance Default CIntPtr where def = 0
instance Default CUIntPtr where def = 0
instance Default CIntMax where def = 0
instance Default CUIntMax where def = 0
instance Default CClock where def = 0
instance Default CTime where def = 0
#if MIN_VERSION_base(4, 4, 0)
instance Default CUSeconds where def = 0
instance Default CSUSeconds where def = 0
#endif
instance Default CFloat where def = 0
instance Default CDouble where def = 0
instance (Default r) => Default (e -> r) where def = const def
instance (Default a) => Default (IO a) where def = return def
instance Default (Maybe a) where def = Nothing
instance Default () where def = mempty
instance Default [a] where def = mempty
instance Default Ordering where def = mempty
instance Default Any where def = mempty
instance Default All where def = mempty
instance Default (Last a) where def = mempty
instance Default (First a) where def = mempty
instance (Num a) => Default (Sum a) where def = mempty
instance (Num a) => Default (Product a) where def = mempty
instance Default (Endo a) where def = mempty
instance (Default a) => Default (Dual a) where def = Dual def
instance (Default a, Default b) => Default (a, b) where def = (def, def)
instance (Default a, Default b, Default c) => Default (a, b, c) where def = (def, def, def)
instance (Default a, Default b, Default c, Default d) => Default (a, b, c, d) where def = (def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e) => Default (a, b, c, d, e) where def = (def, def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e, Default f) => Default (a, b, c, d, e, f) where def = (def, def, def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e, Default f, Default g) => Default (a, b, c, d, e, f, g) where def = (def, def, def, def, def, def, def)
|
602cca1862a8c3926cd380962b91e93d0ee25498d2b8b6d2af429570b09a32fc
|
typedclojure/typedclojure
|
register_malli_extensions.cljc
|
;; this namespace is implicitly loaded via `src/typedclojure_config.cljc` by the type checker
(ns typed-example.register-malli-extensions
(:require [typed.malli.schema-to-type :refer [register-malli->type-extension]]))
(register-malli->type-extension :typed-example.malli-extensible/over [m opts]
Do whatever you want to convert the schema to Typed Clojure syntax .
;; Mostly, you'd just want to return a type.
;; More involved ideas include guessing the type by generating values until `:pred` succeeds.
;; If the type is different based on platform, use impl/impl-case to dispatch (used here
;; just for illustration purposes).
#?(:clj `t/AnyInteger
:cljs `t/AnyInteger))
| null |
https://raw.githubusercontent.com/typedclojure/typedclojure/d57fa8d7aba7e035071c0ce3093d08997f51697d/example-projects/malli-type-providers/src/typed_example/register_malli_extensions.cljc
|
clojure
|
this namespace is implicitly loaded via `src/typedclojure_config.cljc` by the type checker
Mostly, you'd just want to return a type.
More involved ideas include guessing the type by generating values until `:pred` succeeds.
If the type is different based on platform, use impl/impl-case to dispatch (used here
just for illustration purposes).
|
(ns typed-example.register-malli-extensions
(:require [typed.malli.schema-to-type :refer [register-malli->type-extension]]))
(register-malli->type-extension :typed-example.malli-extensible/over [m opts]
Do whatever you want to convert the schema to Typed Clojure syntax .
#?(:clj `t/AnyInteger
:cljs `t/AnyInteger))
|
8fab30ae90dc92d6258f5bddbd5252bccc2dd88fb6f882436802360b319512f4
|
TyGuS/hoogle_plus
|
CodeFormer.hs
|
# LANGUAGE FlexibleContexts #
module HooglePlus.CodeFormer(
generateProgram
, FormerState(..)
, CodePieces
) where
import Types.Common
import Types.Encoder
import Types.Abstract
import Synquid.Util
import Control.Monad.State
import Data.Set (Set)
import qualified Data.Set as Set
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.List
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Maybe
import Data.List.Split
type Code = String
type CodePieces = Set Code
data FormerState = FormerState {
typedTerms :: HashMap AbstractSkeleton CodePieces,
allSignatures :: [FunctionCode]
}
type CodeFormer = StateT FormerState IO
withParen :: Code -> Code
withParen c = "(" ++ c ++ ")"
applyFunction :: FunctionCode -> CodeFormer CodePieces
applyFunction func = do
args <- generateArgs [""] (funParams func)
let res = Set.fromList $ map (\a -> withParen $ fname ++ a) args
-- update typedTerms
st <- get
let tterms = typedTerms st
let newTerms = HashMap.insertWith Set.union (head (funReturn func)) res tterms
put $ st { typedTerms = newTerms }
return res
where
fname = funName func
generateArgs codeSoFar [] = return codeSoFar
generateArgs codeSoFar (tArg:tArgs) = do
args <- generateArg tArg
let partialApplication = [f ++ " " ++ a | f <- codeSoFar, a <- args]
case partialApplication of
[] -> return []
codePieces -> generateArgs codePieces tArgs
generateArg tArg = do
tterms <- gets typedTerms
return $ Set.toList $ HashMap.lookupDefault Set.empty tArg tterms
-- | generate the program from the signatures appeared in selected transitions
-- these signatures are sorted by their timestamps,
-- i.e. they may only use symbols appearing before them
generateProgram :: [FunctionCode] -- signatures used to generate program
-> [AbstractSkeleton] -- argument types in the query
-> [Id] -- argument names
-> [AbstractSkeleton] -- return types
-> Bool -- relevancy toggle
-> CodeFormer CodePieces
generateProgram signatures inputs argNames rets disrel = do
-- prepare scalar variables
st <- get
put $ st { allSignatures = signatures }
mapM_ (uncurry addTypedArg) $ zip inputs argNames
mapM_ applyFunction signatures
termLib <- gets typedTerms
let codePieces = map (\ret -> HashMap.lookupDefault Set.empty ret termLib) rets
let vars = []
return $ Set.filter (includeAllSymbols vars . splitOneOf " ()") (Set.unions codePieces)
where
addTypedArg input argName = do
st <- get
let tterms = typedTerms st
let newTerms = HashMap.insertWith Set.union input (Set.singleton argName) tterms
put $ st { typedTerms = newTerms }
includeAllSymbols vars code =
let fold_fn f (b, c) = if b && f `elem` c then (True, f `delete` c) else (False, c)
base = (True, code)
funcNames = map funName signatures
(res, c) = foldr fold_fn base (funcNames ++ if disrel then [] else argNames)
in res
| null |
https://raw.githubusercontent.com/TyGuS/hoogle_plus/d02a1466d98f872e78ddb2fb612cb67d4bd0ca18/src/HooglePlus/CodeFormer.hs
|
haskell
|
update typedTerms
| generate the program from the signatures appeared in selected transitions
these signatures are sorted by their timestamps,
i.e. they may only use symbols appearing before them
signatures used to generate program
argument types in the query
argument names
return types
relevancy toggle
prepare scalar variables
|
# LANGUAGE FlexibleContexts #
module HooglePlus.CodeFormer(
generateProgram
, FormerState(..)
, CodePieces
) where
import Types.Common
import Types.Encoder
import Types.Abstract
import Synquid.Util
import Control.Monad.State
import Data.Set (Set)
import qualified Data.Set as Set
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.List
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Maybe
import Data.List.Split
type Code = String
type CodePieces = Set Code
data FormerState = FormerState {
typedTerms :: HashMap AbstractSkeleton CodePieces,
allSignatures :: [FunctionCode]
}
type CodeFormer = StateT FormerState IO
withParen :: Code -> Code
withParen c = "(" ++ c ++ ")"
applyFunction :: FunctionCode -> CodeFormer CodePieces
applyFunction func = do
args <- generateArgs [""] (funParams func)
let res = Set.fromList $ map (\a -> withParen $ fname ++ a) args
st <- get
let tterms = typedTerms st
let newTerms = HashMap.insertWith Set.union (head (funReturn func)) res tterms
put $ st { typedTerms = newTerms }
return res
where
fname = funName func
generateArgs codeSoFar [] = return codeSoFar
generateArgs codeSoFar (tArg:tArgs) = do
args <- generateArg tArg
let partialApplication = [f ++ " " ++ a | f <- codeSoFar, a <- args]
case partialApplication of
[] -> return []
codePieces -> generateArgs codePieces tArgs
generateArg tArg = do
tterms <- gets typedTerms
return $ Set.toList $ HashMap.lookupDefault Set.empty tArg tterms
-> CodeFormer CodePieces
generateProgram signatures inputs argNames rets disrel = do
st <- get
put $ st { allSignatures = signatures }
mapM_ (uncurry addTypedArg) $ zip inputs argNames
mapM_ applyFunction signatures
termLib <- gets typedTerms
let codePieces = map (\ret -> HashMap.lookupDefault Set.empty ret termLib) rets
let vars = []
return $ Set.filter (includeAllSymbols vars . splitOneOf " ()") (Set.unions codePieces)
where
addTypedArg input argName = do
st <- get
let tterms = typedTerms st
let newTerms = HashMap.insertWith Set.union input (Set.singleton argName) tterms
put $ st { typedTerms = newTerms }
includeAllSymbols vars code =
let fold_fn f (b, c) = if b && f `elem` c then (True, f `delete` c) else (False, c)
base = (True, code)
funcNames = map funName signatures
(res, c) = foldr fold_fn base (funcNames ++ if disrel then [] else argNames)
in res
|
3bd1436500e1be195b61706545017f4fefc823ea8bfb06cf6a364c3d50d35e36
|
ucsd-progsys/nate
|
opterrors.ml
|
(***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : opterrors.ml , v 1.19 2006/04/16 23:28:21 doligez Exp $
(* WARNING: if you change something in this file, you must look at
errors.ml to see if you need to make the same changes there.
*)
open Format
(* Report an error *)
let report_error ppf exn =
let report ppf = function
| Lexer.Error(err, l) ->
Location.print ppf l;
Lexer.report_error ppf err
| Syntaxerr.Error err ->
Syntaxerr.report_error ppf err
| Pparse.Error ->
fprintf ppf "Preprocessor error"
| Env.Error err ->
Env.report_error ppf err
| Ctype.Tags(l, l') -> fprintf ppf
"In this program,@ variant constructors@ `%s and `%s@ \
have the same hash value.@ Change one of them." l l'
| Typecore.Error(loc, err) ->
Location.print ppf loc; Typecore.report_error ppf err
| Typetexp.Error(loc, err) ->
Location.print ppf loc; Typetexp.report_error ppf err
| Typedecl.Error(loc, err) ->
Location.print ppf loc; Typedecl.report_error ppf err
| Typeclass.Error(loc, err) ->
Location.print ppf loc; Typeclass.report_error ppf err
| Includemod.Error err ->
Includemod.report_error ppf err
| Typemod.Error(loc, err) ->
Location.print ppf loc; Typemod.report_error ppf err
| Translcore.Error(loc, err) ->
Location.print ppf loc; Translcore.report_error ppf err
| Translclass.Error(loc, err) ->
Location.print ppf loc; Translclass.report_error ppf err
| Translmod.Error(loc, err) ->
Location.print ppf loc; Translmod.report_error ppf err
| Compilenv.Error code ->
Compilenv.report_error ppf code
| Asmgen.Error code ->
Asmgen.report_error ppf code
| Asmlink.Error code ->
Asmlink.report_error ppf code
| Asmlibrarian.Error code ->
Asmlibrarian.report_error ppf code
| Asmpackager.Error code ->
Asmpackager.report_error ppf code
| Sys_error msg ->
fprintf ppf "I/O error: %s" msg
| Warnings.Errors (n) ->
fprintf ppf "@.Error: error-enabled warnings (%d occurrences)" n
| x -> fprintf ppf "@]"; raise x in
fprintf ppf "@[%a@]@." report exn
| null |
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/driver/opterrors.ml
|
ocaml
|
*********************************************************************
Objective Caml
*********************************************************************
WARNING: if you change something in this file, you must look at
errors.ml to see if you need to make the same changes there.
Report an error
|
, projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : opterrors.ml , v 1.19 2006/04/16 23:28:21 doligez Exp $
open Format
let report_error ppf exn =
let report ppf = function
| Lexer.Error(err, l) ->
Location.print ppf l;
Lexer.report_error ppf err
| Syntaxerr.Error err ->
Syntaxerr.report_error ppf err
| Pparse.Error ->
fprintf ppf "Preprocessor error"
| Env.Error err ->
Env.report_error ppf err
| Ctype.Tags(l, l') -> fprintf ppf
"In this program,@ variant constructors@ `%s and `%s@ \
have the same hash value.@ Change one of them." l l'
| Typecore.Error(loc, err) ->
Location.print ppf loc; Typecore.report_error ppf err
| Typetexp.Error(loc, err) ->
Location.print ppf loc; Typetexp.report_error ppf err
| Typedecl.Error(loc, err) ->
Location.print ppf loc; Typedecl.report_error ppf err
| Typeclass.Error(loc, err) ->
Location.print ppf loc; Typeclass.report_error ppf err
| Includemod.Error err ->
Includemod.report_error ppf err
| Typemod.Error(loc, err) ->
Location.print ppf loc; Typemod.report_error ppf err
| Translcore.Error(loc, err) ->
Location.print ppf loc; Translcore.report_error ppf err
| Translclass.Error(loc, err) ->
Location.print ppf loc; Translclass.report_error ppf err
| Translmod.Error(loc, err) ->
Location.print ppf loc; Translmod.report_error ppf err
| Compilenv.Error code ->
Compilenv.report_error ppf code
| Asmgen.Error code ->
Asmgen.report_error ppf code
| Asmlink.Error code ->
Asmlink.report_error ppf code
| Asmlibrarian.Error code ->
Asmlibrarian.report_error ppf code
| Asmpackager.Error code ->
Asmpackager.report_error ppf code
| Sys_error msg ->
fprintf ppf "I/O error: %s" msg
| Warnings.Errors (n) ->
fprintf ppf "@.Error: error-enabled warnings (%d occurrences)" n
| x -> fprintf ppf "@]"; raise x in
fprintf ppf "@[%a@]@." report exn
|
cc16e8a1b8657a0dc1f73ce46b871a715e519c682a7f9df0e604f348267774d0
|
agda/agda
|
Monad.hs
|
# LANGUAGE NondecreasingIndentation #
{-| The scope monad with operations.
-}
module Agda.Syntax.Scope.Monad where
import Prelude hiding (null)
import Control.Arrow ((***))
import Control.Monad
import Control.Monad.Except
import Control.Monad.State
import Data.Either ( partitionEithers )
import Data.Foldable (all, traverse_)
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable hiding (for)
import Agda.Interaction.Options
import Agda.Interaction.Options.Warnings
import Agda.Syntax.Common
import Agda.Syntax.Position
import Agda.Syntax.Fixity
import Agda.Syntax.Notation
import Agda.Syntax.Abstract.Name as A
import qualified Agda.Syntax.Abstract as A
import Agda.Syntax.Abstract (ScopeCopyInfo(..))
import Agda.Syntax.Concrete as C
import Agda.Syntax.Concrete.Fixity
import Agda.Syntax.Concrete.Definitions ( DeclarationWarning(..) ,DeclarationWarning'(..) )
-- TODO: move the relevant warnings out of there
import Agda.Syntax.Scope.Base as A
import Agda.TypeChecking.Monad.Base
import Agda.TypeChecking.Monad.Builtin ( HasBuiltins , getBuiltinName' , builtinSet , builtinProp , builtinSetOmega, builtinSSetOmega )
import Agda.TypeChecking.Monad.Debug
import Agda.TypeChecking.Monad.State
import Agda.TypeChecking.Monad.Trace
import Agda.TypeChecking.Positivity.Occurrence (Occurrence)
import Agda.TypeChecking.Warnings ( warning, warning' )
import qualified Agda.Utils.AssocList as AssocList
import Agda.Utils.CallStack ( CallStack, HasCallStack, withCallerCallStack )
import Agda.Utils.Functor
import Agda.Utils.Lens
import Agda.Utils.List
import Agda.Utils.List1 (List1, pattern (:|), nonEmpty, toList)
import Agda.Utils.List2 (List2(List2), toList)
import qualified Agda.Utils.List1 as List1
import qualified Agda.Utils.List2 as List2
import Agda.Utils.Maybe
import Agda.Utils.Monad
import Agda.Utils.Null
import Agda.Utils.Pretty
import Agda.Utils.Singleton
import Agda.Utils.Suffix as C
import Agda.Utils.Impossible
---------------------------------------------------------------------------
-- * The scope checking monad
---------------------------------------------------------------------------
-- | To simplify interaction between scope checking and type checking (in
-- particular when chasing imports), we use the same monad.
type ScopeM = TCM
-- Debugging
printLocals :: Int -> String -> ScopeM ()
printLocals v s = verboseS "scope.top" v $ do
locals <- getLocalVars
reportSLn "scope.top" v $ s ++ " " ++ prettyShow locals
scopeWarning' :: CallStack -> DeclarationWarning' -> ScopeM ()
scopeWarning' loc = warning' loc . NicifierIssue . DeclarationWarning loc
scopeWarning :: HasCallStack => DeclarationWarning' -> ScopeM ()
scopeWarning = withCallerCallStack scopeWarning'
---------------------------------------------------------------------------
-- * General operations
---------------------------------------------------------------------------
isDatatypeModule :: ReadTCState m => A.ModuleName -> m (Maybe DataOrRecordModule)
isDatatypeModule m = do
scopeDatatypeModule . Map.findWithDefault __IMPOSSIBLE__ m <$> useScope scopeModules
getCurrentModule :: ReadTCState m => m A.ModuleName
getCurrentModule = setRange noRange <$> useScope scopeCurrent
setCurrentModule :: MonadTCState m => A.ModuleName -> m ()
setCurrentModule m = modifyScope $ set scopeCurrent m
withCurrentModule :: (ReadTCState m, MonadTCState m) => A.ModuleName -> m a -> m a
withCurrentModule new action = do
old <- getCurrentModule
setCurrentModule new
x <- action
setCurrentModule old
return x
withCurrentModule' :: (MonadTrans t, Monad (t ScopeM)) => A.ModuleName -> t ScopeM a -> t ScopeM a
withCurrentModule' new action = do
old <- lift getCurrentModule
lift $ setCurrentModule new
x <- action
lift $ setCurrentModule old
return x
getNamedScope :: A.ModuleName -> ScopeM Scope
getNamedScope m = do
scope <- getScope
case Map.lookup m (scope ^. scopeModules) of
Just s -> return s
Nothing -> do
reportSLn "" 0 $ "ERROR: In scope\n" ++ prettyShow scope ++ "\nNO SUCH SCOPE " ++ prettyShow m
__IMPOSSIBLE__
getCurrentScope :: ScopeM Scope
getCurrentScope = getNamedScope =<< getCurrentModule
-- | Create a new module with an empty scope.
-- If the module is not new (e.g. duplicate @import@),
-- don't erase its contents.
-- (@Just@ if it is a datatype or record module.)
createModule :: Maybe DataOrRecordModule -> A.ModuleName -> ScopeM ()
createModule b m = do
reportSLn "scope.createModule" 10 $ "createModule " ++ prettyShow m
s <- getCurrentScope
let parents = scopeName s : scopeParents s
sm = emptyScope { scopeName = m
, scopeParents = parents
, scopeDatatypeModule = b }
, 2015 - 07 - 02 : internal error if module is not new .
Ulf , 2016 - 02 - 15 : It 's not new if multiple imports ( # 1770 ) .
, 2020 - 05 - 18 , issue # 3933 :
-- If it is not new (but apparently did not clash),
-- we do not erase its contents for reasons of monotonicity.
modifyScopes $ Map.insertWith mergeScope m sm
-- | Apply a function to the scope map.
modifyScopes :: (Map A.ModuleName Scope -> Map A.ModuleName Scope) -> ScopeM ()
modifyScopes = modifyScope . over scopeModules
-- | Apply a function to the given scope.
modifyNamedScope :: A.ModuleName -> (Scope -> Scope) -> ScopeM ()
modifyNamedScope m f = modifyScopes $ Map.adjust f m
setNamedScope :: A.ModuleName -> Scope -> ScopeM ()
setNamedScope m s = modifyNamedScope m $ const s
-- | Apply a monadic function to the top scope.
modifyNamedScopeM :: A.ModuleName -> (Scope -> ScopeM (a, Scope)) -> ScopeM a
modifyNamedScopeM m f = do
(a, s) <- f =<< getNamedScope m
setNamedScope m s
return a
-- | Apply a function to the current scope.
modifyCurrentScope :: (Scope -> Scope) -> ScopeM ()
modifyCurrentScope f = getCurrentModule >>= (`modifyNamedScope` f)
modifyCurrentScopeM :: (Scope -> ScopeM (a, Scope)) -> ScopeM a
modifyCurrentScopeM f = getCurrentModule >>= (`modifyNamedScopeM` f)
-- | Apply a function to the public or private name space.
modifyCurrentNameSpace :: NameSpaceId -> (NameSpace -> NameSpace) -> ScopeM ()
modifyCurrentNameSpace acc f = modifyCurrentScope $ updateScopeNameSpaces $
AssocList.updateAt acc f
setContextPrecedence :: PrecedenceStack -> ScopeM ()
setContextPrecedence = modifyScope_ . set scopePrecedence
withContextPrecedence :: ReadTCState m => Precedence -> m a -> m a
withContextPrecedence p =
locallyTCState (stScope . scopePrecedence) $ pushPrecedence p
getLocalVars :: ReadTCState m => m LocalVars
getLocalVars = useScope scopeLocals
modifyLocalVars :: (LocalVars -> LocalVars) -> ScopeM ()
modifyLocalVars = modifyScope_ . updateScopeLocals
setLocalVars :: LocalVars -> ScopeM ()
setLocalVars vars = modifyLocalVars $ const vars
-- | Run a computation without changing the local variables.
withLocalVars :: ScopeM a -> ScopeM a
withLocalVars = bracket_ getLocalVars setLocalVars
-- | Run a computation outside some number of local variables and add them back afterwards. This
-- lets you bind variables in the middle of the context and is used when binding generalizable
variables ( # 3735 ) .
outsideLocalVars :: Int -> ScopeM a -> ScopeM a
outsideLocalVars n m = do
inner <- take n <$> getLocalVars
modifyLocalVars (drop n)
x <- m
modifyLocalVars (inner ++)
return x
-- | Check that the newly added variable have unique names.
withCheckNoShadowing :: ScopeM a -> ScopeM a
withCheckNoShadowing = bracket_ getLocalVars $ \ lvarsOld ->
checkNoShadowing lvarsOld =<< getLocalVars
checkNoShadowing :: LocalVars -- ^ Old local scope
-> LocalVars -- ^ New local scope
-> ScopeM ()
checkNoShadowing old new = do
opts <- pragmaOptions
when (ShadowingInTelescope_ `Set.member`
(optWarningMode opts ^. warningSet)) $ do
LocalVars is currnently an AssocList so the difference between
two local scope is the left part of the new one .
let diff = dropEnd (length old) new
-- Filter out the underscores.
let newNames = filter (not . isNoName) $ AssocList.keys diff
-- Associate each name to its occurrences.
let nameOccs1 :: [(C.Name, List1 Range)]
nameOccs1 = Map.toList $ Map.fromListWith (<>) $ map pairWithRange newNames
Warn if we have two or more occurrences of the same name .
let nameOccs2 :: [(C.Name, List2 Range)]
nameOccs2 = mapMaybe (traverseF List2.fromList1Maybe) nameOccs1
caseList nameOccs2 (return ()) $ \ c conflicts -> do
scopeWarning $ ShadowingInTelescope $ c :| conflicts
where
pairWithRange :: C.Name -> (C.Name, List1 Range)
pairWithRange n = (n, singleton $ getRange n)
getVarsToBind :: ScopeM LocalVars
getVarsToBind = useScope scopeVarsToBind
addVarToBind :: C.Name -> LocalVar -> ScopeM ()
addVarToBind x y = modifyScope_ $ updateVarsToBind $ AssocList.insert x y
-- | After collecting some variable names in the scopeVarsToBind,
-- bind them all simultaneously.
bindVarsToBind :: ScopeM ()
bindVarsToBind = do
vars <- getVarsToBind
modifyLocalVars (vars++)
printLocals 10 "bound variables:"
modifyScope_ $ setVarsToBind []
annotateDecls :: ReadTCState m => m [A.Declaration] -> m A.Declaration
annotateDecls m = do
ds <- m
s <- getScope
return $ A.ScopedDecl s ds
annotateExpr :: ReadTCState m => m A.Expr -> m A.Expr
annotateExpr m = do
e <- m
s <- getScope
return $ A.ScopedExpr s e
---------------------------------------------------------------------------
-- * Names
---------------------------------------------------------------------------
-- | Create a fresh abstract name from a concrete name.
--
-- This function is used when we translate a concrete name
-- in a binder. The 'Range' of the concrete name is
-- saved as the 'nameBindingSite' of the abstract name.
freshAbstractName :: Fixity' -> C.Name -> ScopeM A.Name
freshAbstractName fx x = do
i <- fresh
return $ A.Name
{ nameId = i
, nameConcrete = x
, nameCanonical = x
, nameBindingSite = getRange x
, nameFixity = fx
, nameIsRecordName = False
}
-- | @freshAbstractName_ = freshAbstractName noFixity'@
freshAbstractName_ :: C.Name -> ScopeM A.Name
freshAbstractName_ = freshAbstractName noFixity'
-- | Create a fresh abstract qualified name.
freshAbstractQName :: Fixity' -> C.Name -> ScopeM A.QName
freshAbstractQName fx x = do
y <- freshAbstractName fx x
m <- getCurrentModule
return $ A.qualify m y
freshAbstractQName' :: C.Name -> ScopeM A.QName
freshAbstractQName' x = do
fx <- getConcreteFixity x
freshAbstractQName fx x
-- | Create a concrete name that is not yet in scope.
| NOTE : See @chooseName@ in @Agda . Syntax . Translation . AbstractToConcrete@ for similar logic .
-- | NOTE: See @withName@ in @Agda.Syntax.Translation.ReflectedToAbstract@ for similar logic.
freshConcreteName :: Range -> Int -> String -> ScopeM C.Name
freshConcreteName r i s = do
let cname = C.Name r C.NotInScope $ singleton $ Id $ stringToRawName $ s ++ show i
resolveName (C.QName cname) >>= \case
UnknownName -> return cname
_ -> freshConcreteName r (i+1) s
---------------------------------------------------------------------------
-- * Resolving names
---------------------------------------------------------------------------
-- | Look up the abstract name referred to by a given concrete name.
resolveName :: C.QName -> ScopeM ResolvedName
resolveName = resolveName' allKindsOfNames Nothing
-- | Look up the abstract name corresponding to a concrete name of
-- a certain kind and/or from a given set of names.
-- Sometimes we know already that we are dealing with a constructor
-- or pattern synonym (e.g. when we have parsed a pattern).
-- Then, we can ignore conflicting definitions of that name
of a different kind . ( See issue 822 . )
resolveName' ::
KindsOfNames -> Maybe (Set A.Name) -> C.QName -> ScopeM ResolvedName
resolveName' kinds names x = runExceptT (tryResolveName kinds names x) >>= \case
Left reason -> do
reportS "scope.resolve" 60 $ unlines $
"resolveName': ambiguous name" :
map (show . qnameName) (toList $ ambiguousNamesInReason reason)
setCurrentRange x $ typeError $ AmbiguousName x reason
Right x' -> return x'
tryResolveName
:: forall m. (ReadTCState m, HasBuiltins m, MonadError AmbiguousNameReason m)
=> KindsOfNames -- ^ Restrict search to these kinds of names.
-> Maybe (Set A.Name) -- ^ Unless 'Nothing', restrict search to match any of these names.
-> C.QName -- ^ Name to be resolved
-> m ResolvedName -- ^ If illegally ambiguous, throw error with the ambiguous name.
tryResolveName kinds names x = do
scope <- getScope
let vars = AssocList.mapKeysMonotonic C.QName $ scope ^. scopeLocals
case lookup x vars of
-- Case: we have a local variable x, but is (perhaps) shadowed by some imports ys.
Just var@(LocalVar y b ys) ->
-- We may ignore the imports filtered out by the @names@ filter.
case nonEmpty $ filterNames id ys of
Nothing -> return $ VarName y{ nameConcrete = unqualify x } b
Just ys' -> throwError $ AmbiguousLocalVar var ys'
-- Case: we do not have a local variable x.
Nothing -> do
-- Consider only names that are in the given set of names and
are of one of the given kinds
let filtKind = filter $ (`elemKindsOfNames` kinds) . anameKind . fst
possibleNames z = filtKind $ filterNames fst $ scopeLookup' z scope
-- If the name has a suffix, also consider the possibility that
the base name is in scope ( e.g. the builtin sorts ` Set ` and ` Prop ` ) .
canHaveSuffix <- canHaveSuffixTest
let (xsuffix, xbase) = (C.lensQNameName . nameSuffix) (,Nothing) x
possibleBaseNames = filter (canHaveSuffix . anameName . fst) $ possibleNames xbase
suffixedNames = (,) <$> fromConcreteSuffix xsuffix <*> nonEmpty possibleBaseNames
case (nonEmpty $ possibleNames x) of
Just ds | let ks = fmap (isConName . anameKind . fst) ds
, all isJust ks
, isNothing suffixedNames ->
return $ ConstructorName (Set.fromList $ List1.catMaybes ks) $ fmap (upd . fst) ds
Just ds | all ((FldName ==) . anameKind . fst) ds , isNothing suffixedNames ->
return $ FieldName $ fmap (upd . fst) ds
Just ds | all ((PatternSynName ==) . anameKind . fst) ds , isNothing suffixedNames ->
return $ PatternSynResName $ fmap (upd . fst) ds
Just ((d, a) :| ds) -> case (suffixedNames, ds) of
(Nothing, []) ->
return $ DefinedName a (upd d) A.NoSuffix
(Nothing, (d',_) : ds') ->
throwError $ AmbiguousDeclName $ List2 d d' $ map fst ds'
(Just (_, ss), _) ->
throwError $ AmbiguousDeclName $ List2.append (d :| map fst ds) (fmap fst ss)
Nothing -> case suffixedNames of
Nothing -> return UnknownName
Just (suffix , (d, a) :| []) -> return $ DefinedName a (upd d) suffix
Just (suffix , (d1,_) :| (d2,_) : sds) ->
throwError $ AmbiguousDeclName $ List2 d1 d2 $ map fst sds
where
-- @names@ intended semantics: a filter on names.
-- @Nothing@: don't filter out anything.
@Just : filter by membership in @ns@.
filterNames :: forall a. (a -> AbstractName) -> [a] -> [a]
filterNames = case names of
Nothing -> \ f -> id
Just ns -> \ f -> filter $ (`Set.member` ns) . A.qnameName . anameName . f
-- lambda-dropped style by intention
upd d = updateConcreteName d $ unqualify x
updateConcreteName :: AbstractName -> C.Name -> AbstractName
updateConcreteName d@(AbsName { anameName = A.QName qm qn }) x =
d { anameName = A.QName (setRange (getRange x) qm) (qn { nameConcrete = x }) }
fromConcreteSuffix = \case
Nothing -> Nothing
Just C.Prime{} -> Nothing
Just (C.Index i) -> Just $ A.Suffix i
Just (C.Subscript i) -> Just $ A.Suffix i
-- | Test if a given abstract name can appear with a suffix. Currently
only true for the names of builtin sorts @Set@ and @Prop@.
canHaveSuffixTest :: HasBuiltins m => m (A.QName -> Bool)
canHaveSuffixTest = do
builtinSet <- getBuiltinName' builtinSet
builtinProp <- getBuiltinName' builtinProp
builtinSetOmega <- getBuiltinName' builtinSetOmega
builtinSSetOmega <- getBuiltinName' builtinSSetOmega
return $ \x -> Just x `elem` [builtinSet, builtinProp, builtinSetOmega, builtinSSetOmega]
-- | Look up a module in the scope.
resolveModule :: C.QName -> ScopeM AbstractModule
resolveModule x = do
ms <- scopeLookup x <$> getScope
caseMaybe (nonEmpty ms) (typeError $ NoSuchModule x) $ \ case
AbsModule m why :| [] -> return $ AbsModule (m `withRangeOf` x) why
ms -> typeError $ AmbiguousModule x (fmap amodName ms)
-- | Get the fixity of a not yet bound name.
getConcreteFixity :: C.Name -> ScopeM Fixity'
getConcreteFixity x = Map.findWithDefault noFixity' x <$> useScope scopeFixities
-- | Get the polarities of a not yet bound name.
getConcretePolarity :: C.Name -> ScopeM (Maybe [Occurrence])
getConcretePolarity x = Map.lookup x <$> useScope scopePolarities
instance MonadFixityError ScopeM where
throwMultipleFixityDecls xs = case xs of
(x, _) : _ -> setCurrentRange (getRange x) $ typeError $ MultipleFixityDecls xs
[] -> __IMPOSSIBLE__
throwMultiplePolarityPragmas xs = case xs of
x : _ -> setCurrentRange (getRange x) $ typeError $ MultiplePolarityPragmas xs
[] -> __IMPOSSIBLE__
warnUnknownNamesInFixityDecl = scopeWarning . UnknownNamesInFixityDecl
warnUnknownNamesInPolarityPragmas = scopeWarning . UnknownNamesInPolarityPragmas
warnUnknownFixityInMixfixDecl = scopeWarning . UnknownFixityInMixfixDecl
warnPolarityPragmasButNotPostulates = scopeWarning . PolarityPragmasButNotPostulates
-- | Collect the fixity/syntax declarations and polarity pragmas from the list
-- of declarations and store them in the scope.
computeFixitiesAndPolarities :: DoWarn -> [C.Declaration] -> ScopeM a -> ScopeM a
computeFixitiesAndPolarities warn ds cont = do
fp <- fixitiesAndPolarities warn ds
, 2019 - 08 - 16 :
-- Since changing fixities and polarities does not affect the name sets,
-- we do not need to invoke @modifyScope@ here
-- (which does @recomputeInverseScopeMaps@).
-- A simple @locallyScope@ is sufficient.
locallyScope scopeFixitiesAndPolarities (const fp) cont
-- | Get the notation of a name. The name is assumed to be in scope.
getNotation
:: C.QName
-> Set A.Name
^ The name must correspond to one of the names in this set .
-> ScopeM NewNotation
getNotation x ns = do
r <- resolveName' allKindsOfNames (Just ns) x
case r of
VarName y _ -> return $ namesToNotation x y
DefinedName _ d _ -> return $ notation d
FieldName ds -> return $ oneNotation ds
ConstructorName _ ds-> return $ oneNotation ds
PatternSynResName n -> return $ oneNotation n
UnknownName -> __IMPOSSIBLE__
where
notation = namesToNotation x . qnameName . anameName
oneNotation ds =
case mergeNotations $ map notation $ List1.toList ds of
[n] -> n
_ -> __IMPOSSIBLE__
---------------------------------------------------------------------------
-- * Binding names
---------------------------------------------------------------------------
-- | Bind a variable.
bindVariable
^ , @Π@ , , ... ?
-> C.Name -- ^ Concrete name.
-> A.Name -- ^ Abstract name.
-> ScopeM ()
bindVariable b x y = modifyLocalVars $ AssocList.insert x $ LocalVar y b []
-- | Temporarily unbind a variable. Used for non-recursive lets.
unbindVariable :: C.Name -> ScopeM a -> ScopeM a
unbindVariable x = bracket_ (getLocalVars <* modifyLocalVars (AssocList.delete x)) (modifyLocalVars . const)
-- | Bind a defined name. Must not shadow anything.
bindName :: Access -> KindOfName -> C.Name -> A.QName -> ScopeM ()
bindName acc kind x y = bindName' acc kind NoMetadata x y
bindName' :: Access -> KindOfName -> NameMetadata -> C.Name -> A.QName -> ScopeM ()
bindName' acc kind meta x y = whenJustM (bindName'' acc kind meta x y) typeError
-- | Bind a name. Returns the 'TypeError' if exists, but does not throw it.
bindName'' :: Access -> KindOfName -> NameMetadata -> C.Name -> A.QName -> ScopeM (Maybe TypeError)
bindName'' acc kind meta x y = do
when (isNoName x) $ modifyScopes $ Map.map $ removeNameFromScope PrivateNS x
r <- resolveName (C.QName x)
let y' :: Either TypeError AbstractName
y' = case r of
-- Binding an anonymous declaration always succeeds.
In case it 's not the first one , we simply remove the one that came before
_ | isNoName x -> success
DefinedName _ d _ -> clash $ anameName d
VarName z _ -> clash $ A.qualify_ z
FieldName ds -> ambiguous (== FldName) ds
ConstructorName i ds-> ambiguous (isJust . isConName) ds
PatternSynResName n -> ambiguous (== PatternSynName) n
UnknownName -> success
let ns = if isNoName x then PrivateNS else localNameSpace acc
traverse_ (modifyCurrentScope . addNameToScope ns x) y'
pure $ either Just (const Nothing) y'
where
success = Right $ AbsName y kind Defined meta
clash n = Left $ ClashingDefinition (C.QName x) n Nothing
ambiguous f ds =
if f kind && all (f . anameKind) ds
then success else clash $ anameName (List1.head ds)
-- | Rebind a name. Use with care!
Ulf , 2014 - 06 - 29 : Currently used to rebind the name defined by an
-- unquoteDecl, which is a 'QuotableName' in the body, but a 'DefinedName'
-- later on.
rebindName :: Access -> KindOfName -> C.Name -> A.QName -> ScopeM ()
rebindName acc kind x y = do
if kind == ConName
then modifyCurrentScope $
mapScopeNS (localNameSpace acc)
(Map.update (toList <.> nonEmpty . (filter ((==) ConName . anameKind))) x)
id
id
else modifyCurrentScope $ removeNameFromScope (localNameSpace acc) x
bindName acc kind x y
-- | Bind a module name.
bindModule :: Access -> C.Name -> A.ModuleName -> ScopeM ()
bindModule acc x m = modifyCurrentScope $
addModuleToScope (localNameSpace acc) x (AbsModule m Defined)
-- | Bind a qualified module name. Adds it to the imports field of the scope.
bindQModule :: Access -> C.QName -> A.ModuleName -> ScopeM ()
bindQModule acc q m = modifyCurrentScope $ \s ->
s { scopeImports = Map.insert q m (scopeImports s) }
---------------------------------------------------------------------------
-- * Module manipulation operations
---------------------------------------------------------------------------
-- | Clear the scope of any no names.
stripNoNames :: ScopeM ()
stripNoNames = modifyScopes $ Map.map $ mapScope_ stripN stripN id
where
stripN = Map.filterWithKey $ const . not . isNoName
type WSM = StateT ScopeMemo ScopeM
data ScopeMemo = ScopeMemo
{ memoNames :: A.Ren A.QName
, memoModules :: Map ModuleName (ModuleName, Bool)
^ : did we copy recursively ? We need to track this because we do n't
-- copy recursively when creating new modules for reexported functions
( issue1985 ) , but we might need to copy recursively later .
}
memoToScopeInfo :: ScopeMemo -> ScopeCopyInfo
memoToScopeInfo (ScopeMemo names mods) =
ScopeCopyInfo { renNames = names
, renModules = Map.map (pure . fst) mods }
-- | Create a new scope with the given name from an old scope. Renames
-- public names in the old scope to match the new name and returns the
-- renamings.
copyScope :: C.QName -> A.ModuleName -> Scope -> ScopeM (Scope, ScopeCopyInfo)
copyScope oldc new0 s = (inScopeBecause (Applied oldc) *** memoToScopeInfo) <$> runStateT (copy new0 s) (ScopeMemo mempty mempty)
where
copy :: A.ModuleName -> Scope -> WSM Scope
copy new s = do
lift $ reportSLn "scope.copy" 20 $ "Copying scope " ++ prettyShow old ++ " to " ++ prettyShow new
lift $ reportSLn "scope.copy" 50 $ prettyShow s
s0 <- lift $ getNamedScope new
-- Delete private names, then copy names and modules. Recompute inScope
-- set rather than trying to copy it.
s' <- recomputeInScopeSets <$> mapScopeM_ copyD copyM return (setNameSpace PrivateNS emptyNameSpace s)
-- Fix name and parent.
return $ s' { scopeName = scopeName s0
, scopeParents = scopeParents s0
}
where
rnew = getRange new
new' = killRange new
newL = A.mnameToList new'
old = scopeName s
copyD :: NamesInScope -> WSM NamesInScope
copyD = traverse $ mapM $ onName renName
copyM :: ModulesInScope -> WSM ModulesInScope
copyM = traverse $ mapM $ lensAmodName renMod
onName :: (A.QName -> WSM A.QName) -> AbstractName -> WSM AbstractName
onName f d =
case anameKind d of
PatternSynName -> return d -- Pattern synonyms are simply aliased, not renamed
_ -> lensAnameName f d
-- Adding to memo structure.
addName x y = modify $ \ i -> i { memoNames = Map.insertWith (<>) x (pure y) (memoNames i) }
addMod x y rec = modify $ \ i -> i { memoModules = Map.insert x (y, rec) (memoModules i) }
-- Querying the memo structure.
NB : : Defined but not used
findMod x = gets (Map.lookup x . memoModules)
refresh :: A.Name -> WSM A.Name
refresh x = do
i <- lift fresh
return $ x { A.nameId = i }
Change a binding M.x - > old . M'.y to M.x - > new . M'.y
renName :: A.QName -> WSM A.QName
renName x = do
Issue 1985 : For re - exported names we ca n't use new ' as the
-- module, since it has the wrong telescope. Example:
--
module M1 ( A : Set ) where
module M2 ( B : Set ) where
-- postulate X : Set
module M3 ( C : Set ) where
module M4 ( D E : Set ) where
open M2 public
--
-- module M = M1.M3 A C
--
Here we ca n't copy M1.M2.X to M.M4.X since we need
X : ( B : Set ) → Set , but M.M4 has telescope ( D E : Set ) . Thus , we
-- would break the invariant that all functions in a module share the
module telescope . Instead we copy M1.M2.X to M.M2.X for a fresh
module M2 that gets the right telescope .
m <- if x `isInModule` old
then return new'
else renMod' False (qnameModule x)
-- Don't copy recursively here, we only know that the
-- current name x should be copied.
-- Generate a fresh name for the target.
, 2015 - 08 - 11 Issue 1619 :
-- Names copied by a module macro should get the module macro's
-- range as declaration range
-- (maybe rather the one of the open statement).
-- For now, we just set their range
to the new module name 's one , which fixes issue 1619 .
y <- setRange rnew . A.qualify m <$> refresh (qnameName x)
lift $ reportSLn "scope.copy" 50 $ " Copying " ++ prettyShow x ++ " to " ++ prettyShow y
addName x y
return y
Change a binding M.x - > old . M'.y to M.x - > new . M'.y
renMod :: A.ModuleName -> WSM A.ModuleName
renMod = renMod' True
renMod' rec x = do
, issue 1607 :
-- If we have already copied this module, return the copy.
z <- findMod x
case z of
Just (y, False) | rec -> y <$ copyRec x y
Just (y, _) -> return y
Nothing -> do
Ulf ( issue 1985 ): If copying a reexported module we put it at the
-- top-level, to make sure we don't mess up the invariant that all
-- (abstract) names M.f share the argument telescope of M.
let newM = if x `isLtChildModuleOf` old then newL else mnameToList new0
y <- do
Andreas , Jesper , 2015 - 07 - 02 : Issue 1597
-- Don't blindly drop a prefix of length of the old qualifier.
-- If things are imported by open public they do not have the old qualifier
-- as prefix. Those need just to be linked, not copied.
-- return $ A.mnameFromList $ (newL ++) $ drop (size old) $ A.mnameToList x
( ( A.mnameToList old ) ( A.mnameToList x ) ) ( return x ) $ \ suffix - > do
return $ A.mnameFromList $ newL + + suffix
Ulf , 2016 - 02 - 22 : # 1726
-- We still need to copy modules from 'open public'. Same as in renName.
y <- refresh $ lastWithDefault __IMPOSSIBLE__ $ A.mnameToList x
return $ A.mnameFromList $ newM ++ [y]
Andreas , Jesper , 2015 - 07 - 02 : Issue 1597
-- Don't copy a module over itself, it will just be emptied of its contents.
if (x == y) then return x else do
lift $ reportSLn "scope.copy" 50 $ " Copying module " ++ prettyShow x ++ " to " ++ prettyShow y
addMod x y rec
lift $ createModule Nothing y
-- We need to copy the contents of included modules recursively (only when 'rec')
when rec $ copyRec x y
return y
where
copyRec x y = do
s0 <- lift $ getNamedScope x
s <- withCurrentModule' y $ copy y s0
lift $ modifyNamedScope y (const s)
---------------------------------------------------------------------------
-- * Import directives
---------------------------------------------------------------------------
-- | Warn about useless fixity declarations in @renaming@ directives.
for the sake of error reporting .
checkNoFixityInRenamingModule :: [C.Renaming] -> ScopeM ()
checkNoFixityInRenamingModule ren = do
whenJust (nonEmpty $ mapMaybe rangeOfUselessInfix ren) $ \ rs -> do
setCurrentRange rs $ do
warning $ FixityInRenamingModule rs
where
rangeOfUselessInfix :: C.Renaming -> Maybe Range
rangeOfUselessInfix = \case
Renaming ImportedModule{} _ mfx _ -> getRange <$> mfx
_ -> Nothing
-- Moved here carefully from Parser.y to preserve the archaeological artefact
dating from Oct 2005 ( 5ba14b647b9bd175733f9563e744176425c39126 ) .
-- | Check that an import directive doesn't contain repeated names.
verifyImportDirective :: [C.ImportedName] -> C.HidingDirective -> C.RenamingDirective -> ScopeM ()
verifyImportDirective usn hdn ren =
case filter ((>1) . length)
$ List.group
$ List.sort xs
of
[] -> return ()
yss -> setCurrentRange yss $ genericError $
"Repeated name" ++ s ++ " in import directive: " ++
concat (List.intersperse ", " $ map (prettyShow . head) yss)
where
s = case yss of
[_] -> ""
_ -> "s"
where
xs = usn ++ hdn ++ map renFrom ren
-- | Apply an import directive and check that all the names mentioned actually
-- exist.
--
for the sake of error reporting .
applyImportDirectiveM
:: C.QName -- ^ Name of the scope, only for error reporting.
-> C.ImportDirective -- ^ Description of how scope is to be modified.
-> Scope -- ^ Input scope.
-> ScopeM (A.ImportDirective, Scope) -- ^ Scope-checked description, output scope.
applyImportDirectiveM m (ImportDirective rng usn' hdn' ren' public) scope0 = do
-- Module names do not come with fixities, thus, we should complain if the
user has supplied fixity annotations to @renaming module@ clauses .
checkNoFixityInRenamingModule ren'
, 2020 - 06 - 06 , issue # 4707
-- Duplicates in @using@ directive are dropped with a warning.
usingList <- discardDuplicatesInUsing usn'
-- The following check was originally performed by the parser.
-- The Great Ulf Himself added the check back in the dawn of time
-- (5ba14b647b9bd175733f9563e744176425c39126)
when Agda 2 was n't even believed to exist yet .
verifyImportDirective usingList hdn' ren'
-- We start by checking that all of the names talked about in the import
-- directive do exist. If some do not then we remove them and raise a warning.
let (missingExports, namesA) = checkExist $ usingList ++ hdn' ++ map renFrom ren'
unless (null missingExports) $ setCurrentRange rng $ do
reportSLn "scope.import.apply" 20 $ "non existing names: " ++ prettyShow missingExports
warning $ ModuleDoesntExport m (Map.keys namesInScope) (Map.keys modulesInScope) missingExports
-- We can now define a cleaned-up version of the import directive.
# 3997 , efficient lookup in missingExports
remove missingExports from usn '
let hdn = filter notMissing hdn' -- remove missingExports from hdn'
and from ren '
let dir = ImportDirective rng (mapUsing (const usn) usn') hdn ren public
-- Convenient shorthands for defined names and names brought into scope:
let names = map renFrom ren ++ hdn ++ usn
let definedNames = map renTo ren
let targetNames = usn ++ definedNames
-- Efficient test of (`elem` names):
let inNames = (names `hasElem`)
-- Efficient test of whether a module import should be added to the import
-- of a definition (like a data or record definition).
let extra x = inNames (ImportedName x)
&& notMissing (ImportedModule x)
&& (not . inNames $ ImportedModule x)
The last test implies that @hiding ( module M)@ prevents @module M@
-- from entering the @using@ list in @addExtraModule@.
dir' <- sanityCheck (not . inNames) $ addExtraModules extra dir
-- Check for duplicate imports in a single import directive.
-- @dup@ : To be imported names that are mentioned more than once.
unlessNull (allDuplicates targetNames) $ \ dup ->
typeError $ DuplicateImports m dup
-- Apply the import directive.
let (scope', (nameClashes, moduleClashes)) = applyImportDirective_ dir' scope
, 2019 - 11 - 08 , issue # 4154 , report clashes
-- introduced by the @renaming@.
unless (null nameClashes) $
warning $ ClashesViaRenaming NameNotModule $ Set.toList nameClashes
unless (null moduleClashes) $
warning $ ClashesViaRenaming ModuleNotName $ Set.toList moduleClashes
-- Look up the defined names in the new scope.
let namesInScope' = (allNamesInScope scope' :: ThingsInScope AbstractName)
let modulesInScope' = (allNamesInScope scope' :: ThingsInScope AbstractModule)
let look x = headWithDefault __IMPOSSIBLE__ . Map.findWithDefault __IMPOSSIBLE__ x
-- We set the ranges to the ranges of the concrete names in order to get
-- highlighting for the names in the import directive.
let definedA = for definedNames $ \case
ImportedName x -> ImportedName . (x,) . setRange (getRange x) . anameName $ look x namesInScope'
ImportedModule x -> ImportedModule . (x,) . setRange (getRange x) . amodName $ look x modulesInScope'
let adir = mapImportDir namesA definedA dir
TODO Issue 1714 :
where
, 2020 - 06 - 23 , issue # 4773 , fixing regression in 2.5.1 .
-- Import directive may not mention private things.
-- ```agda
-- module M where private X = Set
-- module N = M using (X)
-- ```
-- Further, modules (N) need not copy private things (X) from other
-- modules (M) ever, since they cannot legally referred to
-- (neither through qualification (N.X) nor open N).
-- Thus, we can unconditionally remove private definitions
-- before we apply the import directive.
scope = restrictPrivate scope0
-- Return names in the @using@ directive, discarding duplicates.
Monadic for the sake of throwing warnings .
discardDuplicatesInUsing :: C.Using -> ScopeM [C.ImportedName]
discardDuplicatesInUsing = \case
UseEverything -> return []
Using xs -> do
let (ys, dups) = nubAndDuplicatesOn id xs
List1.unlessNull dups $ warning . DuplicateUsing
return ys
-- If both @using@ and @hiding@ directive are present,
-- the hiding directive may only contain modules whose twins are mentioned.
Monadic for the sake of error reporting .
sanityCheck notMentioned = \case
dir@(ImportDirective{ using = Using{}, hiding = ys }) -> do
let useless = \case
ImportedName{} -> True
ImportedModule y -> notMentioned (ImportedName y)
unlessNull (filter useless ys) $ warning . UselessHiding
-- We can empty @hiding@ now, since there is an explicit @using@ directive
-- and @hiding@ served its purpose to prevent modules to enter the @Using@ list.
return dir{ hiding = [] }
dir -> return dir
addExtraModules :: (C.Name -> Bool) -> C.ImportDirective -> C.ImportDirective
addExtraModules extra dir =
dir{ using = mapUsing (concatMap addExtra) $ using dir
, hiding = concatMap addExtra $ hiding dir
, impRenaming = concatMap extraRenaming $ impRenaming dir
}
where
addExtra f@(ImportedName y) | extra y = [f, ImportedModule y]
addExtra m = [m]
extraRenaming = \case
r@(Renaming (ImportedName y) (ImportedName z) _fixity rng) | extra y ->
[ r , Renaming (ImportedModule y) (ImportedModule z) Nothing rng ]
r -> [r]
-- Names and modules (abstract) in scope before the import.
namesInScope = (allNamesInScope scope :: ThingsInScope AbstractName)
modulesInScope = (allNamesInScope scope :: ThingsInScope AbstractModule)
concreteNamesInScope = (Map.keys namesInScope ++ Map.keys modulesInScope :: [C.Name])
AST versions of the concrete names passed as an argument .
We get back a pair consisting of a list of missing exports first ,
and a list of successful imports second .
checkExist :: [ImportedName] -> ([ImportedName], [ImportedName' (C.Name, A.QName) (C.Name, A.ModuleName)])
checkExist xs = partitionEithers $ for xs $ \ name -> case name of
ImportedName x -> ImportedName . (x,) . setRange (getRange x) . anameName <$> resolve name x namesInScope
ImportedModule x -> ImportedModule . (x,) . setRange (getRange x) . amodName <$> resolve name x modulesInScope
where resolve :: Ord a => err -> a -> Map a [b] -> Either err b
resolve err x m = maybe (Left err) (Right . head) $ Map.lookup x m
-- | Translation of @ImportDirective@.
mapImportDir
:: (Ord n1, Ord m1)
=> [ImportedName' (n1,n2) (m1,m2)] -- ^ Translation of imported names.
-> [ImportedName' (n1,n2) (m1,m2)] -- ^ Translation of names defined by this import.
-> ImportDirective' n1 m1
-> ImportDirective' n2 m2
mapImportDir src0 tgt0 (ImportDirective r u h ren open) =
ImportDirective r
(mapUsing (map (lookupImportedName src)) u)
(map (lookupImportedName src) h)
(map (mapRenaming src tgt) ren)
open
where
src = importedNameMapFromList src0
tgt = importedNameMapFromList tgt0
| A finite map for @ImportedName@s .
data ImportedNameMap n1 n2 m1 m2 = ImportedNameMap
{ inameMap :: Map n1 n2
, imoduleMap :: Map m1 m2
}
| Create a ' ImportedNameMap ' .
importedNameMapFromList
:: (Ord n1, Ord m1)
=> [ImportedName' (n1,n2) (m1,m2)]
-> ImportedNameMap n1 n2 m1 m2
importedNameMapFromList = foldr (flip add) $ ImportedNameMap Map.empty Map.empty
where
add (ImportedNameMap nm mm) = \case
ImportedName (x,y) -> ImportedNameMap (Map.insert x y nm) mm
ImportedModule (x,y) -> ImportedNameMap nm (Map.insert x y mm)
| Apply a ' ImportedNameMap ' .
lookupImportedName
:: (Ord n1, Ord m1)
=> ImportedNameMap n1 n2 m1 m2
-> ImportedName' n1 m1
-> ImportedName' n2 m2
lookupImportedName (ImportedNameMap nm mm) = \case
ImportedName x -> ImportedName $ Map.findWithDefault __IMPOSSIBLE__ x nm
ImportedModule x -> ImportedModule $ Map.findWithDefault __IMPOSSIBLE__ x mm
-- | Translation of @Renaming@.
mapRenaming
:: (Ord n1, Ord m1)
=> ImportedNameMap n1 n2 m1 m2 -- ^ Translation of 'renFrom' names and module names.
-> ImportedNameMap n1 n2 m1 m2 -- ^ Translation of 'rento' names and module names.
^ Renaming before translation ( 1 ) .
^ Renaming after translation ( 2 ) .
mapRenaming src tgt (Renaming from to fixity r) =
Renaming (lookupImportedName src from) (lookupImportedName tgt to) fixity r
---------------------------------------------------------------------------
-- * Opening a module
---------------------------------------------------------------------------
data OpenKind = LetOpenModule | TopOpenModule
noGeneralizedVarsIfLetOpen :: OpenKind -> Scope -> Scope
noGeneralizedVarsIfLetOpen TopOpenModule = id
noGeneralizedVarsIfLetOpen LetOpenModule = disallowGeneralizedVars
-- | Open a module.
openModule_ :: OpenKind -> C.QName -> C.ImportDirective -> ScopeM A.ImportDirective
openModule_ kind cm dir = openModule kind Nothing cm dir
-- | Open a module, possibly given an already resolved module name.
openModule :: OpenKind -> Maybe A.ModuleName -> C.QName -> C.ImportDirective -> ScopeM A.ImportDirective
openModule kind mam cm dir = do
current <- getCurrentModule
m <- caseMaybe mam (amodName <$> resolveModule cm) return
let acc | Nothing <- publicOpen dir = PrivateNS
| m `isLtChildModuleOf` current = PublicNS
| otherwise = ImportedNS
-- Get the scope exported by module to be opened.
(adir, s') <- applyImportDirectiveM cm dir . inScopeBecause (Opened cm) .
noGeneralizedVarsIfLetOpen kind =<< getNamedScope m
let s = setScopeAccess acc s'
let ns = scopeNameSpace acc s
modifyCurrentScope (`mergeScope` s)
, 2018 - 06 - 03 , issue # 3057 :
-- If we simply check for ambiguous exported identifiers _after_
-- importing the new identifiers into the current scope, we also
-- catch the case of importing an ambiguous identifier.
checkForClashes
-- Importing names might shadow existing locals.
verboseS "scope.locals" 10 $ do
locals <- mapMaybe (\ (c,x) -> c <$ notShadowedLocal x) <$> getLocalVars
let newdefs = Map.keys $ nsNames ns
shadowed = locals `List.intersect` newdefs
reportSLn "scope.locals" 10 $ "opening module shadows the following locals vars: " ++ prettyShow shadowed
, 2014 - 09 - 03 , issue 1266 : shadow local variables by imported defs .
modifyLocalVars $ AssocList.mapWithKey $ \ c x ->
case Map.lookup c $ nsNames ns of
Nothing -> x
Just ys -> shadowLocal ys x
return adir
where
-- Only checks for clashes that would lead to the same
-- name being exported twice from the module.
checkForClashes = when (isJust $ publicOpen dir) $ do
exported <- allThingsInScope . restrictPrivate <$> (getNamedScope =<< getCurrentModule)
Get all exported concrete names that are mapped to at least 2 abstract names
let defClashes = filter (\ (_c, as) -> length as >= 2) $ Map.toList $ nsNames exported
modClashes = filter (\ (_c, as) -> length as >= 2) $ Map.toList $ nsModules exported
-- No ambiguity if concrete identifier is only mapped to
-- constructor names or only to projection names or only to pattern synonyms.
defClash (_, qs) = not $ or
[ all (isJust . isConName) ks
, all (== FldName) ks
, all (== PatternSynName) ks
]
where ks = map anameKind qs
We report the first clashing exported identifier .
unlessNull (filter defClash defClashes) $
\ ((x, q:_) : _) -> typeError $ ClashingDefinition (C.QName x) (anameName q) Nothing
unlessNull modClashes $ \ ((_, ms) : _) -> do
caseMaybe (last2 ms) __IMPOSSIBLE__ $ \ (m0, m1) -> do
typeError $ ClashingModule (amodName m0) (amodName m1)
| null |
https://raw.githubusercontent.com/agda/agda/bf1a531d6a579c7b8016179b361920d3d0c69458/src/full/Agda/Syntax/Scope/Monad.hs
|
haskell
|
| The scope monad with operations.
TODO: move the relevant warnings out of there
-------------------------------------------------------------------------
* The scope checking monad
-------------------------------------------------------------------------
| To simplify interaction between scope checking and type checking (in
particular when chasing imports), we use the same monad.
Debugging
-------------------------------------------------------------------------
* General operations
-------------------------------------------------------------------------
| Create a new module with an empty scope.
If the module is not new (e.g. duplicate @import@),
don't erase its contents.
(@Just@ if it is a datatype or record module.)
If it is not new (but apparently did not clash),
we do not erase its contents for reasons of monotonicity.
| Apply a function to the scope map.
| Apply a function to the given scope.
| Apply a monadic function to the top scope.
| Apply a function to the current scope.
| Apply a function to the public or private name space.
| Run a computation without changing the local variables.
| Run a computation outside some number of local variables and add them back afterwards. This
lets you bind variables in the middle of the context and is used when binding generalizable
| Check that the newly added variable have unique names.
^ Old local scope
^ New local scope
Filter out the underscores.
Associate each name to its occurrences.
| After collecting some variable names in the scopeVarsToBind,
bind them all simultaneously.
-------------------------------------------------------------------------
* Names
-------------------------------------------------------------------------
| Create a fresh abstract name from a concrete name.
This function is used when we translate a concrete name
in a binder. The 'Range' of the concrete name is
saved as the 'nameBindingSite' of the abstract name.
| @freshAbstractName_ = freshAbstractName noFixity'@
| Create a fresh abstract qualified name.
| Create a concrete name that is not yet in scope.
| NOTE: See @withName@ in @Agda.Syntax.Translation.ReflectedToAbstract@ for similar logic.
-------------------------------------------------------------------------
* Resolving names
-------------------------------------------------------------------------
| Look up the abstract name referred to by a given concrete name.
| Look up the abstract name corresponding to a concrete name of
a certain kind and/or from a given set of names.
Sometimes we know already that we are dealing with a constructor
or pattern synonym (e.g. when we have parsed a pattern).
Then, we can ignore conflicting definitions of that name
^ Restrict search to these kinds of names.
^ Unless 'Nothing', restrict search to match any of these names.
^ Name to be resolved
^ If illegally ambiguous, throw error with the ambiguous name.
Case: we have a local variable x, but is (perhaps) shadowed by some imports ys.
We may ignore the imports filtered out by the @names@ filter.
Case: we do not have a local variable x.
Consider only names that are in the given set of names and
If the name has a suffix, also consider the possibility that
@names@ intended semantics: a filter on names.
@Nothing@: don't filter out anything.
lambda-dropped style by intention
| Test if a given abstract name can appear with a suffix. Currently
| Look up a module in the scope.
| Get the fixity of a not yet bound name.
| Get the polarities of a not yet bound name.
| Collect the fixity/syntax declarations and polarity pragmas from the list
of declarations and store them in the scope.
Since changing fixities and polarities does not affect the name sets,
we do not need to invoke @modifyScope@ here
(which does @recomputeInverseScopeMaps@).
A simple @locallyScope@ is sufficient.
| Get the notation of a name. The name is assumed to be in scope.
-------------------------------------------------------------------------
* Binding names
-------------------------------------------------------------------------
| Bind a variable.
^ Concrete name.
^ Abstract name.
| Temporarily unbind a variable. Used for non-recursive lets.
| Bind a defined name. Must not shadow anything.
| Bind a name. Returns the 'TypeError' if exists, but does not throw it.
Binding an anonymous declaration always succeeds.
| Rebind a name. Use with care!
unquoteDecl, which is a 'QuotableName' in the body, but a 'DefinedName'
later on.
| Bind a module name.
| Bind a qualified module name. Adds it to the imports field of the scope.
-------------------------------------------------------------------------
* Module manipulation operations
-------------------------------------------------------------------------
| Clear the scope of any no names.
copy recursively when creating new modules for reexported functions
| Create a new scope with the given name from an old scope. Renames
public names in the old scope to match the new name and returns the
renamings.
Delete private names, then copy names and modules. Recompute inScope
set rather than trying to copy it.
Fix name and parent.
Pattern synonyms are simply aliased, not renamed
Adding to memo structure.
Querying the memo structure.
module, since it has the wrong telescope. Example:
postulate X : Set
module M = M1.M3 A C
would break the invariant that all functions in a module share the
Don't copy recursively here, we only know that the
current name x should be copied.
Generate a fresh name for the target.
Names copied by a module macro should get the module macro's
range as declaration range
(maybe rather the one of the open statement).
For now, we just set their range
If we have already copied this module, return the copy.
top-level, to make sure we don't mess up the invariant that all
(abstract) names M.f share the argument telescope of M.
Don't blindly drop a prefix of length of the old qualifier.
If things are imported by open public they do not have the old qualifier
as prefix. Those need just to be linked, not copied.
return $ A.mnameFromList $ (newL ++) $ drop (size old) $ A.mnameToList x
We still need to copy modules from 'open public'. Same as in renName.
Don't copy a module over itself, it will just be emptied of its contents.
We need to copy the contents of included modules recursively (only when 'rec')
-------------------------------------------------------------------------
* Import directives
-------------------------------------------------------------------------
| Warn about useless fixity declarations in @renaming@ directives.
Moved here carefully from Parser.y to preserve the archaeological artefact
| Check that an import directive doesn't contain repeated names.
| Apply an import directive and check that all the names mentioned actually
exist.
^ Name of the scope, only for error reporting.
^ Description of how scope is to be modified.
^ Input scope.
^ Scope-checked description, output scope.
Module names do not come with fixities, thus, we should complain if the
Duplicates in @using@ directive are dropped with a warning.
The following check was originally performed by the parser.
The Great Ulf Himself added the check back in the dawn of time
(5ba14b647b9bd175733f9563e744176425c39126)
We start by checking that all of the names talked about in the import
directive do exist. If some do not then we remove them and raise a warning.
We can now define a cleaned-up version of the import directive.
remove missingExports from hdn'
Convenient shorthands for defined names and names brought into scope:
Efficient test of (`elem` names):
Efficient test of whether a module import should be added to the import
of a definition (like a data or record definition).
from entering the @using@ list in @addExtraModule@.
Check for duplicate imports in a single import directive.
@dup@ : To be imported names that are mentioned more than once.
Apply the import directive.
introduced by the @renaming@.
Look up the defined names in the new scope.
We set the ranges to the ranges of the concrete names in order to get
highlighting for the names in the import directive.
Import directive may not mention private things.
```agda
module M where private X = Set
module N = M using (X)
```
Further, modules (N) need not copy private things (X) from other
modules (M) ever, since they cannot legally referred to
(neither through qualification (N.X) nor open N).
Thus, we can unconditionally remove private definitions
before we apply the import directive.
Return names in the @using@ directive, discarding duplicates.
If both @using@ and @hiding@ directive are present,
the hiding directive may only contain modules whose twins are mentioned.
We can empty @hiding@ now, since there is an explicit @using@ directive
and @hiding@ served its purpose to prevent modules to enter the @Using@ list.
Names and modules (abstract) in scope before the import.
| Translation of @ImportDirective@.
^ Translation of imported names.
^ Translation of names defined by this import.
| Translation of @Renaming@.
^ Translation of 'renFrom' names and module names.
^ Translation of 'rento' names and module names.
-------------------------------------------------------------------------
* Opening a module
-------------------------------------------------------------------------
| Open a module.
| Open a module, possibly given an already resolved module name.
Get the scope exported by module to be opened.
If we simply check for ambiguous exported identifiers _after_
importing the new identifiers into the current scope, we also
catch the case of importing an ambiguous identifier.
Importing names might shadow existing locals.
Only checks for clashes that would lead to the same
name being exported twice from the module.
No ambiguity if concrete identifier is only mapped to
constructor names or only to projection names or only to pattern synonyms.
|
# LANGUAGE NondecreasingIndentation #
module Agda.Syntax.Scope.Monad where
import Prelude hiding (null)
import Control.Arrow ((***))
import Control.Monad
import Control.Monad.Except
import Control.Monad.State
import Data.Either ( partitionEithers )
import Data.Foldable (all, traverse_)
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable hiding (for)
import Agda.Interaction.Options
import Agda.Interaction.Options.Warnings
import Agda.Syntax.Common
import Agda.Syntax.Position
import Agda.Syntax.Fixity
import Agda.Syntax.Notation
import Agda.Syntax.Abstract.Name as A
import qualified Agda.Syntax.Abstract as A
import Agda.Syntax.Abstract (ScopeCopyInfo(..))
import Agda.Syntax.Concrete as C
import Agda.Syntax.Concrete.Fixity
import Agda.Syntax.Concrete.Definitions ( DeclarationWarning(..) ,DeclarationWarning'(..) )
import Agda.Syntax.Scope.Base as A
import Agda.TypeChecking.Monad.Base
import Agda.TypeChecking.Monad.Builtin ( HasBuiltins , getBuiltinName' , builtinSet , builtinProp , builtinSetOmega, builtinSSetOmega )
import Agda.TypeChecking.Monad.Debug
import Agda.TypeChecking.Monad.State
import Agda.TypeChecking.Monad.Trace
import Agda.TypeChecking.Positivity.Occurrence (Occurrence)
import Agda.TypeChecking.Warnings ( warning, warning' )
import qualified Agda.Utils.AssocList as AssocList
import Agda.Utils.CallStack ( CallStack, HasCallStack, withCallerCallStack )
import Agda.Utils.Functor
import Agda.Utils.Lens
import Agda.Utils.List
import Agda.Utils.List1 (List1, pattern (:|), nonEmpty, toList)
import Agda.Utils.List2 (List2(List2), toList)
import qualified Agda.Utils.List1 as List1
import qualified Agda.Utils.List2 as List2
import Agda.Utils.Maybe
import Agda.Utils.Monad
import Agda.Utils.Null
import Agda.Utils.Pretty
import Agda.Utils.Singleton
import Agda.Utils.Suffix as C
import Agda.Utils.Impossible
type ScopeM = TCM
printLocals :: Int -> String -> ScopeM ()
printLocals v s = verboseS "scope.top" v $ do
locals <- getLocalVars
reportSLn "scope.top" v $ s ++ " " ++ prettyShow locals
scopeWarning' :: CallStack -> DeclarationWarning' -> ScopeM ()
scopeWarning' loc = warning' loc . NicifierIssue . DeclarationWarning loc
scopeWarning :: HasCallStack => DeclarationWarning' -> ScopeM ()
scopeWarning = withCallerCallStack scopeWarning'
isDatatypeModule :: ReadTCState m => A.ModuleName -> m (Maybe DataOrRecordModule)
isDatatypeModule m = do
scopeDatatypeModule . Map.findWithDefault __IMPOSSIBLE__ m <$> useScope scopeModules
getCurrentModule :: ReadTCState m => m A.ModuleName
getCurrentModule = setRange noRange <$> useScope scopeCurrent
setCurrentModule :: MonadTCState m => A.ModuleName -> m ()
setCurrentModule m = modifyScope $ set scopeCurrent m
withCurrentModule :: (ReadTCState m, MonadTCState m) => A.ModuleName -> m a -> m a
withCurrentModule new action = do
old <- getCurrentModule
setCurrentModule new
x <- action
setCurrentModule old
return x
withCurrentModule' :: (MonadTrans t, Monad (t ScopeM)) => A.ModuleName -> t ScopeM a -> t ScopeM a
withCurrentModule' new action = do
old <- lift getCurrentModule
lift $ setCurrentModule new
x <- action
lift $ setCurrentModule old
return x
getNamedScope :: A.ModuleName -> ScopeM Scope
getNamedScope m = do
scope <- getScope
case Map.lookup m (scope ^. scopeModules) of
Just s -> return s
Nothing -> do
reportSLn "" 0 $ "ERROR: In scope\n" ++ prettyShow scope ++ "\nNO SUCH SCOPE " ++ prettyShow m
__IMPOSSIBLE__
getCurrentScope :: ScopeM Scope
getCurrentScope = getNamedScope =<< getCurrentModule
createModule :: Maybe DataOrRecordModule -> A.ModuleName -> ScopeM ()
createModule b m = do
reportSLn "scope.createModule" 10 $ "createModule " ++ prettyShow m
s <- getCurrentScope
let parents = scopeName s : scopeParents s
sm = emptyScope { scopeName = m
, scopeParents = parents
, scopeDatatypeModule = b }
, 2015 - 07 - 02 : internal error if module is not new .
Ulf , 2016 - 02 - 15 : It 's not new if multiple imports ( # 1770 ) .
, 2020 - 05 - 18 , issue # 3933 :
modifyScopes $ Map.insertWith mergeScope m sm
modifyScopes :: (Map A.ModuleName Scope -> Map A.ModuleName Scope) -> ScopeM ()
modifyScopes = modifyScope . over scopeModules
modifyNamedScope :: A.ModuleName -> (Scope -> Scope) -> ScopeM ()
modifyNamedScope m f = modifyScopes $ Map.adjust f m
setNamedScope :: A.ModuleName -> Scope -> ScopeM ()
setNamedScope m s = modifyNamedScope m $ const s
modifyNamedScopeM :: A.ModuleName -> (Scope -> ScopeM (a, Scope)) -> ScopeM a
modifyNamedScopeM m f = do
(a, s) <- f =<< getNamedScope m
setNamedScope m s
return a
modifyCurrentScope :: (Scope -> Scope) -> ScopeM ()
modifyCurrentScope f = getCurrentModule >>= (`modifyNamedScope` f)
modifyCurrentScopeM :: (Scope -> ScopeM (a, Scope)) -> ScopeM a
modifyCurrentScopeM f = getCurrentModule >>= (`modifyNamedScopeM` f)
modifyCurrentNameSpace :: NameSpaceId -> (NameSpace -> NameSpace) -> ScopeM ()
modifyCurrentNameSpace acc f = modifyCurrentScope $ updateScopeNameSpaces $
AssocList.updateAt acc f
setContextPrecedence :: PrecedenceStack -> ScopeM ()
setContextPrecedence = modifyScope_ . set scopePrecedence
withContextPrecedence :: ReadTCState m => Precedence -> m a -> m a
withContextPrecedence p =
locallyTCState (stScope . scopePrecedence) $ pushPrecedence p
getLocalVars :: ReadTCState m => m LocalVars
getLocalVars = useScope scopeLocals
modifyLocalVars :: (LocalVars -> LocalVars) -> ScopeM ()
modifyLocalVars = modifyScope_ . updateScopeLocals
setLocalVars :: LocalVars -> ScopeM ()
setLocalVars vars = modifyLocalVars $ const vars
withLocalVars :: ScopeM a -> ScopeM a
withLocalVars = bracket_ getLocalVars setLocalVars
variables ( # 3735 ) .
outsideLocalVars :: Int -> ScopeM a -> ScopeM a
outsideLocalVars n m = do
inner <- take n <$> getLocalVars
modifyLocalVars (drop n)
x <- m
modifyLocalVars (inner ++)
return x
withCheckNoShadowing :: ScopeM a -> ScopeM a
withCheckNoShadowing = bracket_ getLocalVars $ \ lvarsOld ->
checkNoShadowing lvarsOld =<< getLocalVars
-> ScopeM ()
checkNoShadowing old new = do
opts <- pragmaOptions
when (ShadowingInTelescope_ `Set.member`
(optWarningMode opts ^. warningSet)) $ do
LocalVars is currnently an AssocList so the difference between
two local scope is the left part of the new one .
let diff = dropEnd (length old) new
let newNames = filter (not . isNoName) $ AssocList.keys diff
let nameOccs1 :: [(C.Name, List1 Range)]
nameOccs1 = Map.toList $ Map.fromListWith (<>) $ map pairWithRange newNames
Warn if we have two or more occurrences of the same name .
let nameOccs2 :: [(C.Name, List2 Range)]
nameOccs2 = mapMaybe (traverseF List2.fromList1Maybe) nameOccs1
caseList nameOccs2 (return ()) $ \ c conflicts -> do
scopeWarning $ ShadowingInTelescope $ c :| conflicts
where
pairWithRange :: C.Name -> (C.Name, List1 Range)
pairWithRange n = (n, singleton $ getRange n)
getVarsToBind :: ScopeM LocalVars
getVarsToBind = useScope scopeVarsToBind
addVarToBind :: C.Name -> LocalVar -> ScopeM ()
addVarToBind x y = modifyScope_ $ updateVarsToBind $ AssocList.insert x y
bindVarsToBind :: ScopeM ()
bindVarsToBind = do
vars <- getVarsToBind
modifyLocalVars (vars++)
printLocals 10 "bound variables:"
modifyScope_ $ setVarsToBind []
annotateDecls :: ReadTCState m => m [A.Declaration] -> m A.Declaration
annotateDecls m = do
ds <- m
s <- getScope
return $ A.ScopedDecl s ds
annotateExpr :: ReadTCState m => m A.Expr -> m A.Expr
annotateExpr m = do
e <- m
s <- getScope
return $ A.ScopedExpr s e
freshAbstractName :: Fixity' -> C.Name -> ScopeM A.Name
freshAbstractName fx x = do
i <- fresh
return $ A.Name
{ nameId = i
, nameConcrete = x
, nameCanonical = x
, nameBindingSite = getRange x
, nameFixity = fx
, nameIsRecordName = False
}
freshAbstractName_ :: C.Name -> ScopeM A.Name
freshAbstractName_ = freshAbstractName noFixity'
freshAbstractQName :: Fixity' -> C.Name -> ScopeM A.QName
freshAbstractQName fx x = do
y <- freshAbstractName fx x
m <- getCurrentModule
return $ A.qualify m y
freshAbstractQName' :: C.Name -> ScopeM A.QName
freshAbstractQName' x = do
fx <- getConcreteFixity x
freshAbstractQName fx x
| NOTE : See @chooseName@ in @Agda . Syntax . Translation . AbstractToConcrete@ for similar logic .
freshConcreteName :: Range -> Int -> String -> ScopeM C.Name
freshConcreteName r i s = do
let cname = C.Name r C.NotInScope $ singleton $ Id $ stringToRawName $ s ++ show i
resolveName (C.QName cname) >>= \case
UnknownName -> return cname
_ -> freshConcreteName r (i+1) s
resolveName :: C.QName -> ScopeM ResolvedName
resolveName = resolveName' allKindsOfNames Nothing
of a different kind . ( See issue 822 . )
resolveName' ::
KindsOfNames -> Maybe (Set A.Name) -> C.QName -> ScopeM ResolvedName
resolveName' kinds names x = runExceptT (tryResolveName kinds names x) >>= \case
Left reason -> do
reportS "scope.resolve" 60 $ unlines $
"resolveName': ambiguous name" :
map (show . qnameName) (toList $ ambiguousNamesInReason reason)
setCurrentRange x $ typeError $ AmbiguousName x reason
Right x' -> return x'
tryResolveName
:: forall m. (ReadTCState m, HasBuiltins m, MonadError AmbiguousNameReason m)
tryResolveName kinds names x = do
scope <- getScope
let vars = AssocList.mapKeysMonotonic C.QName $ scope ^. scopeLocals
case lookup x vars of
Just var@(LocalVar y b ys) ->
case nonEmpty $ filterNames id ys of
Nothing -> return $ VarName y{ nameConcrete = unqualify x } b
Just ys' -> throwError $ AmbiguousLocalVar var ys'
Nothing -> do
are of one of the given kinds
let filtKind = filter $ (`elemKindsOfNames` kinds) . anameKind . fst
possibleNames z = filtKind $ filterNames fst $ scopeLookup' z scope
the base name is in scope ( e.g. the builtin sorts ` Set ` and ` Prop ` ) .
canHaveSuffix <- canHaveSuffixTest
let (xsuffix, xbase) = (C.lensQNameName . nameSuffix) (,Nothing) x
possibleBaseNames = filter (canHaveSuffix . anameName . fst) $ possibleNames xbase
suffixedNames = (,) <$> fromConcreteSuffix xsuffix <*> nonEmpty possibleBaseNames
case (nonEmpty $ possibleNames x) of
Just ds | let ks = fmap (isConName . anameKind . fst) ds
, all isJust ks
, isNothing suffixedNames ->
return $ ConstructorName (Set.fromList $ List1.catMaybes ks) $ fmap (upd . fst) ds
Just ds | all ((FldName ==) . anameKind . fst) ds , isNothing suffixedNames ->
return $ FieldName $ fmap (upd . fst) ds
Just ds | all ((PatternSynName ==) . anameKind . fst) ds , isNothing suffixedNames ->
return $ PatternSynResName $ fmap (upd . fst) ds
Just ((d, a) :| ds) -> case (suffixedNames, ds) of
(Nothing, []) ->
return $ DefinedName a (upd d) A.NoSuffix
(Nothing, (d',_) : ds') ->
throwError $ AmbiguousDeclName $ List2 d d' $ map fst ds'
(Just (_, ss), _) ->
throwError $ AmbiguousDeclName $ List2.append (d :| map fst ds) (fmap fst ss)
Nothing -> case suffixedNames of
Nothing -> return UnknownName
Just (suffix , (d, a) :| []) -> return $ DefinedName a (upd d) suffix
Just (suffix , (d1,_) :| (d2,_) : sds) ->
throwError $ AmbiguousDeclName $ List2 d1 d2 $ map fst sds
where
@Just : filter by membership in @ns@.
filterNames :: forall a. (a -> AbstractName) -> [a] -> [a]
filterNames = case names of
Nothing -> \ f -> id
Just ns -> \ f -> filter $ (`Set.member` ns) . A.qnameName . anameName . f
upd d = updateConcreteName d $ unqualify x
updateConcreteName :: AbstractName -> C.Name -> AbstractName
updateConcreteName d@(AbsName { anameName = A.QName qm qn }) x =
d { anameName = A.QName (setRange (getRange x) qm) (qn { nameConcrete = x }) }
fromConcreteSuffix = \case
Nothing -> Nothing
Just C.Prime{} -> Nothing
Just (C.Index i) -> Just $ A.Suffix i
Just (C.Subscript i) -> Just $ A.Suffix i
only true for the names of builtin sorts @Set@ and @Prop@.
canHaveSuffixTest :: HasBuiltins m => m (A.QName -> Bool)
canHaveSuffixTest = do
builtinSet <- getBuiltinName' builtinSet
builtinProp <- getBuiltinName' builtinProp
builtinSetOmega <- getBuiltinName' builtinSetOmega
builtinSSetOmega <- getBuiltinName' builtinSSetOmega
return $ \x -> Just x `elem` [builtinSet, builtinProp, builtinSetOmega, builtinSSetOmega]
resolveModule :: C.QName -> ScopeM AbstractModule
resolveModule x = do
ms <- scopeLookup x <$> getScope
caseMaybe (nonEmpty ms) (typeError $ NoSuchModule x) $ \ case
AbsModule m why :| [] -> return $ AbsModule (m `withRangeOf` x) why
ms -> typeError $ AmbiguousModule x (fmap amodName ms)
getConcreteFixity :: C.Name -> ScopeM Fixity'
getConcreteFixity x = Map.findWithDefault noFixity' x <$> useScope scopeFixities
getConcretePolarity :: C.Name -> ScopeM (Maybe [Occurrence])
getConcretePolarity x = Map.lookup x <$> useScope scopePolarities
instance MonadFixityError ScopeM where
throwMultipleFixityDecls xs = case xs of
(x, _) : _ -> setCurrentRange (getRange x) $ typeError $ MultipleFixityDecls xs
[] -> __IMPOSSIBLE__
throwMultiplePolarityPragmas xs = case xs of
x : _ -> setCurrentRange (getRange x) $ typeError $ MultiplePolarityPragmas xs
[] -> __IMPOSSIBLE__
warnUnknownNamesInFixityDecl = scopeWarning . UnknownNamesInFixityDecl
warnUnknownNamesInPolarityPragmas = scopeWarning . UnknownNamesInPolarityPragmas
warnUnknownFixityInMixfixDecl = scopeWarning . UnknownFixityInMixfixDecl
warnPolarityPragmasButNotPostulates = scopeWarning . PolarityPragmasButNotPostulates
computeFixitiesAndPolarities :: DoWarn -> [C.Declaration] -> ScopeM a -> ScopeM a
computeFixitiesAndPolarities warn ds cont = do
fp <- fixitiesAndPolarities warn ds
, 2019 - 08 - 16 :
locallyScope scopeFixitiesAndPolarities (const fp) cont
getNotation
:: C.QName
-> Set A.Name
^ The name must correspond to one of the names in this set .
-> ScopeM NewNotation
getNotation x ns = do
r <- resolveName' allKindsOfNames (Just ns) x
case r of
VarName y _ -> return $ namesToNotation x y
DefinedName _ d _ -> return $ notation d
FieldName ds -> return $ oneNotation ds
ConstructorName _ ds-> return $ oneNotation ds
PatternSynResName n -> return $ oneNotation n
UnknownName -> __IMPOSSIBLE__
where
notation = namesToNotation x . qnameName . anameName
oneNotation ds =
case mergeNotations $ map notation $ List1.toList ds of
[n] -> n
_ -> __IMPOSSIBLE__
bindVariable
^ , @Π@ , , ... ?
-> ScopeM ()
bindVariable b x y = modifyLocalVars $ AssocList.insert x $ LocalVar y b []
unbindVariable :: C.Name -> ScopeM a -> ScopeM a
unbindVariable x = bracket_ (getLocalVars <* modifyLocalVars (AssocList.delete x)) (modifyLocalVars . const)
bindName :: Access -> KindOfName -> C.Name -> A.QName -> ScopeM ()
bindName acc kind x y = bindName' acc kind NoMetadata x y
bindName' :: Access -> KindOfName -> NameMetadata -> C.Name -> A.QName -> ScopeM ()
bindName' acc kind meta x y = whenJustM (bindName'' acc kind meta x y) typeError
bindName'' :: Access -> KindOfName -> NameMetadata -> C.Name -> A.QName -> ScopeM (Maybe TypeError)
bindName'' acc kind meta x y = do
when (isNoName x) $ modifyScopes $ Map.map $ removeNameFromScope PrivateNS x
r <- resolveName (C.QName x)
let y' :: Either TypeError AbstractName
y' = case r of
In case it 's not the first one , we simply remove the one that came before
_ | isNoName x -> success
DefinedName _ d _ -> clash $ anameName d
VarName z _ -> clash $ A.qualify_ z
FieldName ds -> ambiguous (== FldName) ds
ConstructorName i ds-> ambiguous (isJust . isConName) ds
PatternSynResName n -> ambiguous (== PatternSynName) n
UnknownName -> success
let ns = if isNoName x then PrivateNS else localNameSpace acc
traverse_ (modifyCurrentScope . addNameToScope ns x) y'
pure $ either Just (const Nothing) y'
where
success = Right $ AbsName y kind Defined meta
clash n = Left $ ClashingDefinition (C.QName x) n Nothing
ambiguous f ds =
if f kind && all (f . anameKind) ds
then success else clash $ anameName (List1.head ds)
Ulf , 2014 - 06 - 29 : Currently used to rebind the name defined by an
rebindName :: Access -> KindOfName -> C.Name -> A.QName -> ScopeM ()
rebindName acc kind x y = do
if kind == ConName
then modifyCurrentScope $
mapScopeNS (localNameSpace acc)
(Map.update (toList <.> nonEmpty . (filter ((==) ConName . anameKind))) x)
id
id
else modifyCurrentScope $ removeNameFromScope (localNameSpace acc) x
bindName acc kind x y
bindModule :: Access -> C.Name -> A.ModuleName -> ScopeM ()
bindModule acc x m = modifyCurrentScope $
addModuleToScope (localNameSpace acc) x (AbsModule m Defined)
bindQModule :: Access -> C.QName -> A.ModuleName -> ScopeM ()
bindQModule acc q m = modifyCurrentScope $ \s ->
s { scopeImports = Map.insert q m (scopeImports s) }
stripNoNames :: ScopeM ()
stripNoNames = modifyScopes $ Map.map $ mapScope_ stripN stripN id
where
stripN = Map.filterWithKey $ const . not . isNoName
type WSM = StateT ScopeMemo ScopeM
data ScopeMemo = ScopeMemo
{ memoNames :: A.Ren A.QName
, memoModules :: Map ModuleName (ModuleName, Bool)
^ : did we copy recursively ? We need to track this because we do n't
( issue1985 ) , but we might need to copy recursively later .
}
memoToScopeInfo :: ScopeMemo -> ScopeCopyInfo
memoToScopeInfo (ScopeMemo names mods) =
ScopeCopyInfo { renNames = names
, renModules = Map.map (pure . fst) mods }
copyScope :: C.QName -> A.ModuleName -> Scope -> ScopeM (Scope, ScopeCopyInfo)
copyScope oldc new0 s = (inScopeBecause (Applied oldc) *** memoToScopeInfo) <$> runStateT (copy new0 s) (ScopeMemo mempty mempty)
where
copy :: A.ModuleName -> Scope -> WSM Scope
copy new s = do
lift $ reportSLn "scope.copy" 20 $ "Copying scope " ++ prettyShow old ++ " to " ++ prettyShow new
lift $ reportSLn "scope.copy" 50 $ prettyShow s
s0 <- lift $ getNamedScope new
s' <- recomputeInScopeSets <$> mapScopeM_ copyD copyM return (setNameSpace PrivateNS emptyNameSpace s)
return $ s' { scopeName = scopeName s0
, scopeParents = scopeParents s0
}
where
rnew = getRange new
new' = killRange new
newL = A.mnameToList new'
old = scopeName s
copyD :: NamesInScope -> WSM NamesInScope
copyD = traverse $ mapM $ onName renName
copyM :: ModulesInScope -> WSM ModulesInScope
copyM = traverse $ mapM $ lensAmodName renMod
onName :: (A.QName -> WSM A.QName) -> AbstractName -> WSM AbstractName
onName f d =
case anameKind d of
_ -> lensAnameName f d
addName x y = modify $ \ i -> i { memoNames = Map.insertWith (<>) x (pure y) (memoNames i) }
addMod x y rec = modify $ \ i -> i { memoModules = Map.insert x (y, rec) (memoModules i) }
NB : : Defined but not used
findMod x = gets (Map.lookup x . memoModules)
refresh :: A.Name -> WSM A.Name
refresh x = do
i <- lift fresh
return $ x { A.nameId = i }
Change a binding M.x - > old . M'.y to M.x - > new . M'.y
renName :: A.QName -> WSM A.QName
renName x = do
Issue 1985 : For re - exported names we ca n't use new ' as the
module M1 ( A : Set ) where
module M2 ( B : Set ) where
module M3 ( C : Set ) where
module M4 ( D E : Set ) where
open M2 public
Here we ca n't copy M1.M2.X to M.M4.X since we need
X : ( B : Set ) → Set , but M.M4 has telescope ( D E : Set ) . Thus , we
module telescope . Instead we copy M1.M2.X to M.M2.X for a fresh
module M2 that gets the right telescope .
m <- if x `isInModule` old
then return new'
else renMod' False (qnameModule x)
, 2015 - 08 - 11 Issue 1619 :
to the new module name 's one , which fixes issue 1619 .
y <- setRange rnew . A.qualify m <$> refresh (qnameName x)
lift $ reportSLn "scope.copy" 50 $ " Copying " ++ prettyShow x ++ " to " ++ prettyShow y
addName x y
return y
Change a binding M.x - > old . M'.y to M.x - > new . M'.y
renMod :: A.ModuleName -> WSM A.ModuleName
renMod = renMod' True
renMod' rec x = do
, issue 1607 :
z <- findMod x
case z of
Just (y, False) | rec -> y <$ copyRec x y
Just (y, _) -> return y
Nothing -> do
Ulf ( issue 1985 ): If copying a reexported module we put it at the
let newM = if x `isLtChildModuleOf` old then newL else mnameToList new0
y <- do
Andreas , Jesper , 2015 - 07 - 02 : Issue 1597
( ( A.mnameToList old ) ( A.mnameToList x ) ) ( return x ) $ \ suffix - > do
return $ A.mnameFromList $ newL + + suffix
Ulf , 2016 - 02 - 22 : # 1726
y <- refresh $ lastWithDefault __IMPOSSIBLE__ $ A.mnameToList x
return $ A.mnameFromList $ newM ++ [y]
Andreas , Jesper , 2015 - 07 - 02 : Issue 1597
if (x == y) then return x else do
lift $ reportSLn "scope.copy" 50 $ " Copying module " ++ prettyShow x ++ " to " ++ prettyShow y
addMod x y rec
lift $ createModule Nothing y
when rec $ copyRec x y
return y
where
copyRec x y = do
s0 <- lift $ getNamedScope x
s <- withCurrentModule' y $ copy y s0
lift $ modifyNamedScope y (const s)
for the sake of error reporting .
checkNoFixityInRenamingModule :: [C.Renaming] -> ScopeM ()
checkNoFixityInRenamingModule ren = do
whenJust (nonEmpty $ mapMaybe rangeOfUselessInfix ren) $ \ rs -> do
setCurrentRange rs $ do
warning $ FixityInRenamingModule rs
where
rangeOfUselessInfix :: C.Renaming -> Maybe Range
rangeOfUselessInfix = \case
Renaming ImportedModule{} _ mfx _ -> getRange <$> mfx
_ -> Nothing
dating from Oct 2005 ( 5ba14b647b9bd175733f9563e744176425c39126 ) .
verifyImportDirective :: [C.ImportedName] -> C.HidingDirective -> C.RenamingDirective -> ScopeM ()
verifyImportDirective usn hdn ren =
case filter ((>1) . length)
$ List.group
$ List.sort xs
of
[] -> return ()
yss -> setCurrentRange yss $ genericError $
"Repeated name" ++ s ++ " in import directive: " ++
concat (List.intersperse ", " $ map (prettyShow . head) yss)
where
s = case yss of
[_] -> ""
_ -> "s"
where
xs = usn ++ hdn ++ map renFrom ren
for the sake of error reporting .
applyImportDirectiveM
applyImportDirectiveM m (ImportDirective rng usn' hdn' ren' public) scope0 = do
user has supplied fixity annotations to @renaming module@ clauses .
checkNoFixityInRenamingModule ren'
, 2020 - 06 - 06 , issue # 4707
usingList <- discardDuplicatesInUsing usn'
when Agda 2 was n't even believed to exist yet .
verifyImportDirective usingList hdn' ren'
let (missingExports, namesA) = checkExist $ usingList ++ hdn' ++ map renFrom ren'
unless (null missingExports) $ setCurrentRange rng $ do
reportSLn "scope.import.apply" 20 $ "non existing names: " ++ prettyShow missingExports
warning $ ModuleDoesntExport m (Map.keys namesInScope) (Map.keys modulesInScope) missingExports
# 3997 , efficient lookup in missingExports
remove missingExports from usn '
and from ren '
let dir = ImportDirective rng (mapUsing (const usn) usn') hdn ren public
let names = map renFrom ren ++ hdn ++ usn
let definedNames = map renTo ren
let targetNames = usn ++ definedNames
let inNames = (names `hasElem`)
let extra x = inNames (ImportedName x)
&& notMissing (ImportedModule x)
&& (not . inNames $ ImportedModule x)
The last test implies that @hiding ( module M)@ prevents @module M@
dir' <- sanityCheck (not . inNames) $ addExtraModules extra dir
unlessNull (allDuplicates targetNames) $ \ dup ->
typeError $ DuplicateImports m dup
let (scope', (nameClashes, moduleClashes)) = applyImportDirective_ dir' scope
, 2019 - 11 - 08 , issue # 4154 , report clashes
unless (null nameClashes) $
warning $ ClashesViaRenaming NameNotModule $ Set.toList nameClashes
unless (null moduleClashes) $
warning $ ClashesViaRenaming ModuleNotName $ Set.toList moduleClashes
let namesInScope' = (allNamesInScope scope' :: ThingsInScope AbstractName)
let modulesInScope' = (allNamesInScope scope' :: ThingsInScope AbstractModule)
let look x = headWithDefault __IMPOSSIBLE__ . Map.findWithDefault __IMPOSSIBLE__ x
let definedA = for definedNames $ \case
ImportedName x -> ImportedName . (x,) . setRange (getRange x) . anameName $ look x namesInScope'
ImportedModule x -> ImportedModule . (x,) . setRange (getRange x) . amodName $ look x modulesInScope'
let adir = mapImportDir namesA definedA dir
TODO Issue 1714 :
where
, 2020 - 06 - 23 , issue # 4773 , fixing regression in 2.5.1 .
scope = restrictPrivate scope0
Monadic for the sake of throwing warnings .
discardDuplicatesInUsing :: C.Using -> ScopeM [C.ImportedName]
discardDuplicatesInUsing = \case
UseEverything -> return []
Using xs -> do
let (ys, dups) = nubAndDuplicatesOn id xs
List1.unlessNull dups $ warning . DuplicateUsing
return ys
Monadic for the sake of error reporting .
sanityCheck notMentioned = \case
dir@(ImportDirective{ using = Using{}, hiding = ys }) -> do
let useless = \case
ImportedName{} -> True
ImportedModule y -> notMentioned (ImportedName y)
unlessNull (filter useless ys) $ warning . UselessHiding
return dir{ hiding = [] }
dir -> return dir
addExtraModules :: (C.Name -> Bool) -> C.ImportDirective -> C.ImportDirective
addExtraModules extra dir =
dir{ using = mapUsing (concatMap addExtra) $ using dir
, hiding = concatMap addExtra $ hiding dir
, impRenaming = concatMap extraRenaming $ impRenaming dir
}
where
addExtra f@(ImportedName y) | extra y = [f, ImportedModule y]
addExtra m = [m]
extraRenaming = \case
r@(Renaming (ImportedName y) (ImportedName z) _fixity rng) | extra y ->
[ r , Renaming (ImportedModule y) (ImportedModule z) Nothing rng ]
r -> [r]
namesInScope = (allNamesInScope scope :: ThingsInScope AbstractName)
modulesInScope = (allNamesInScope scope :: ThingsInScope AbstractModule)
concreteNamesInScope = (Map.keys namesInScope ++ Map.keys modulesInScope :: [C.Name])
AST versions of the concrete names passed as an argument .
We get back a pair consisting of a list of missing exports first ,
and a list of successful imports second .
checkExist :: [ImportedName] -> ([ImportedName], [ImportedName' (C.Name, A.QName) (C.Name, A.ModuleName)])
checkExist xs = partitionEithers $ for xs $ \ name -> case name of
ImportedName x -> ImportedName . (x,) . setRange (getRange x) . anameName <$> resolve name x namesInScope
ImportedModule x -> ImportedModule . (x,) . setRange (getRange x) . amodName <$> resolve name x modulesInScope
where resolve :: Ord a => err -> a -> Map a [b] -> Either err b
resolve err x m = maybe (Left err) (Right . head) $ Map.lookup x m
mapImportDir
:: (Ord n1, Ord m1)
-> ImportDirective' n1 m1
-> ImportDirective' n2 m2
mapImportDir src0 tgt0 (ImportDirective r u h ren open) =
ImportDirective r
(mapUsing (map (lookupImportedName src)) u)
(map (lookupImportedName src) h)
(map (mapRenaming src tgt) ren)
open
where
src = importedNameMapFromList src0
tgt = importedNameMapFromList tgt0
| A finite map for @ImportedName@s .
data ImportedNameMap n1 n2 m1 m2 = ImportedNameMap
{ inameMap :: Map n1 n2
, imoduleMap :: Map m1 m2
}
| Create a ' ImportedNameMap ' .
importedNameMapFromList
:: (Ord n1, Ord m1)
=> [ImportedName' (n1,n2) (m1,m2)]
-> ImportedNameMap n1 n2 m1 m2
importedNameMapFromList = foldr (flip add) $ ImportedNameMap Map.empty Map.empty
where
add (ImportedNameMap nm mm) = \case
ImportedName (x,y) -> ImportedNameMap (Map.insert x y nm) mm
ImportedModule (x,y) -> ImportedNameMap nm (Map.insert x y mm)
| Apply a ' ImportedNameMap ' .
lookupImportedName
:: (Ord n1, Ord m1)
=> ImportedNameMap n1 n2 m1 m2
-> ImportedName' n1 m1
-> ImportedName' n2 m2
lookupImportedName (ImportedNameMap nm mm) = \case
ImportedName x -> ImportedName $ Map.findWithDefault __IMPOSSIBLE__ x nm
ImportedModule x -> ImportedModule $ Map.findWithDefault __IMPOSSIBLE__ x mm
mapRenaming
:: (Ord n1, Ord m1)
^ Renaming before translation ( 1 ) .
^ Renaming after translation ( 2 ) .
mapRenaming src tgt (Renaming from to fixity r) =
Renaming (lookupImportedName src from) (lookupImportedName tgt to) fixity r
data OpenKind = LetOpenModule | TopOpenModule
noGeneralizedVarsIfLetOpen :: OpenKind -> Scope -> Scope
noGeneralizedVarsIfLetOpen TopOpenModule = id
noGeneralizedVarsIfLetOpen LetOpenModule = disallowGeneralizedVars
openModule_ :: OpenKind -> C.QName -> C.ImportDirective -> ScopeM A.ImportDirective
openModule_ kind cm dir = openModule kind Nothing cm dir
openModule :: OpenKind -> Maybe A.ModuleName -> C.QName -> C.ImportDirective -> ScopeM A.ImportDirective
openModule kind mam cm dir = do
current <- getCurrentModule
m <- caseMaybe mam (amodName <$> resolveModule cm) return
let acc | Nothing <- publicOpen dir = PrivateNS
| m `isLtChildModuleOf` current = PublicNS
| otherwise = ImportedNS
(adir, s') <- applyImportDirectiveM cm dir . inScopeBecause (Opened cm) .
noGeneralizedVarsIfLetOpen kind =<< getNamedScope m
let s = setScopeAccess acc s'
let ns = scopeNameSpace acc s
modifyCurrentScope (`mergeScope` s)
, 2018 - 06 - 03 , issue # 3057 :
checkForClashes
verboseS "scope.locals" 10 $ do
locals <- mapMaybe (\ (c,x) -> c <$ notShadowedLocal x) <$> getLocalVars
let newdefs = Map.keys $ nsNames ns
shadowed = locals `List.intersect` newdefs
reportSLn "scope.locals" 10 $ "opening module shadows the following locals vars: " ++ prettyShow shadowed
, 2014 - 09 - 03 , issue 1266 : shadow local variables by imported defs .
modifyLocalVars $ AssocList.mapWithKey $ \ c x ->
case Map.lookup c $ nsNames ns of
Nothing -> x
Just ys -> shadowLocal ys x
return adir
where
checkForClashes = when (isJust $ publicOpen dir) $ do
exported <- allThingsInScope . restrictPrivate <$> (getNamedScope =<< getCurrentModule)
Get all exported concrete names that are mapped to at least 2 abstract names
let defClashes = filter (\ (_c, as) -> length as >= 2) $ Map.toList $ nsNames exported
modClashes = filter (\ (_c, as) -> length as >= 2) $ Map.toList $ nsModules exported
defClash (_, qs) = not $ or
[ all (isJust . isConName) ks
, all (== FldName) ks
, all (== PatternSynName) ks
]
where ks = map anameKind qs
We report the first clashing exported identifier .
unlessNull (filter defClash defClashes) $
\ ((x, q:_) : _) -> typeError $ ClashingDefinition (C.QName x) (anameName q) Nothing
unlessNull modClashes $ \ ((_, ms) : _) -> do
caseMaybe (last2 ms) __IMPOSSIBLE__ $ \ (m0, m1) -> do
typeError $ ClashingModule (amodName m0) (amodName m1)
|
8c0cf66b1f74f4e77c35a09e49d0bf312ecd163ab84bfe0503cb7ddd1b7e9bb5
|
ocaml-community/calendar
|
time_Zone.ml
|
(**************************************************************************)
(* *)
(* This file is part of Calendar. *)
(* *)
Copyright ( C ) 2003 - 2011
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License version 2.1 as published by the
Free Software Foundation , with a special linking exception ( usual
(* for Objective Caml libraries). *)
(* *)
(* It 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 *)
(* *)
See the GNU Lesser General Public Licence version 2.1 for more
(* details (enclosed in the file LGPL). *)
(* *)
(* The special linking exception is detailled in the enclosed file *)
(* LICENSE. *)
(**************************************************************************)
type t =
| UTC
| Local
| UTC_Plus of int
let tz = ref UTC
let out_of_bounds x = x < - 12 || x > 11
let in_bounds x = not (out_of_bounds x)
let make_in_bounds x =
let y = x mod 24 in
if y < -12 then y + 24
else if y > 11 then y - 24
else y
let gap_gmt_local =
let t = Unix.time () in
(Unix.localtime t).Unix.tm_hour - (Unix.gmtime t).Unix.tm_hour
let current () = !tz
let change = function
| _ as t -> tz := t
let gap t1 t2 =
let aux t1 t2 =
assert (t1 < t2);
match t1, t2 with
| UTC, Local -> gap_gmt_local
| UTC, UTC_Plus x -> x
| Local, UTC_Plus x -> x - gap_gmt_local
| UTC_Plus x, UTC_Plus y -> y - x
| _ -> assert false
in
let res =
if t1 = t2 then 0
else if t1 < t2 then aux t1 t2
else - aux t2 t1
in
make_in_bounds res
let from_gmt () = gap UTC (current ())
let to_gmt () = gap (current ()) UTC
let is_dst () =
current () = Local && (Unix.localtime (Unix.time ())).Unix.tm_isdst
let hour_of_dst () = if is_dst () then 1 else 0
let on f tz x =
let old = current () in
change tz;
try
let res = f x in
change old;
res
with exn ->
change old;
raise exn
| null |
https://raw.githubusercontent.com/ocaml-community/calendar/f119658010cc9045e1866eddadc4a776adbcc146/src/time_Zone.ml
|
ocaml
|
************************************************************************
This file is part of Calendar.
you can redistribute it and/or modify it under the terms of the GNU
for Objective Caml libraries).
It 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
details (enclosed in the file LGPL).
The special linking exception is detailled in the enclosed file
LICENSE.
************************************************************************
|
Copyright ( C ) 2003 - 2011
Lesser General Public License version 2.1 as published by the
Free Software Foundation , with a special linking exception ( usual
See the GNU Lesser General Public Licence version 2.1 for more
type t =
| UTC
| Local
| UTC_Plus of int
let tz = ref UTC
let out_of_bounds x = x < - 12 || x > 11
let in_bounds x = not (out_of_bounds x)
let make_in_bounds x =
let y = x mod 24 in
if y < -12 then y + 24
else if y > 11 then y - 24
else y
let gap_gmt_local =
let t = Unix.time () in
(Unix.localtime t).Unix.tm_hour - (Unix.gmtime t).Unix.tm_hour
let current () = !tz
let change = function
| _ as t -> tz := t
let gap t1 t2 =
let aux t1 t2 =
assert (t1 < t2);
match t1, t2 with
| UTC, Local -> gap_gmt_local
| UTC, UTC_Plus x -> x
| Local, UTC_Plus x -> x - gap_gmt_local
| UTC_Plus x, UTC_Plus y -> y - x
| _ -> assert false
in
let res =
if t1 = t2 then 0
else if t1 < t2 then aux t1 t2
else - aux t2 t1
in
make_in_bounds res
let from_gmt () = gap UTC (current ())
let to_gmt () = gap (current ()) UTC
let is_dst () =
current () = Local && (Unix.localtime (Unix.time ())).Unix.tm_isdst
let hour_of_dst () = if is_dst () then 1 else 0
let on f tz x =
let old = current () in
change tz;
try
let res = f x in
change old;
res
with exn ->
change old;
raise exn
|
b3a72d54cc012e5759035c071b3fe3d620ff4cd4c20c8c8b4589d67d3808b6e3
|
alasconnect/azure-demo
|
App.hs
|
# LANGUAGE FlexibleContexts #
module App where
--------------------------------------------------------------------------------
import Control.Lens
import Control.Monad (unless)
import Data.Pool
import Data.Proxy
import Data.Text (pack, unpack)
import Dhall
import Database.Beam.Postgres
import Network.Wai
import qualified Network.Wai.Handler.Warp as W
import Servant
--------------------------------------------------------------------------------
import Api
import Opts
import Routes
import Types
--------------------------------------------------------------------------------
Standard Servant setup
totalApi :: Proxy Routes
totalApi = Proxy
-- We defer running our code in a particular monad transformer stack
-- until later at the API level. Until then it is simply in a Servant Handler.
app :: AppContext -> Application
app ctx = serve totalApi (api ctx)
run :: OptConfig -> IO ()
run o = do
Parse configuration file
a <- input auto (pack (optConfigFile o))
-- Check the configuration file for sanity without running the app.
-- This is useful for double checking against a built binary in a CI server
-- without actually starting the process.
unless (optConfigCheck o) $ do
-- Generate database connection pool
p <- mkPool a
putStrLn ("Running server on port " ++ show (view appPort a))
-- Run webserver
W.run (fromIntegral (view appPort a)) (app (AppContext p a))
where
mkPool a = do
let i = ConnectInfo
(unpack (view dbHost a))
(fromIntegral (view dbPort a))
(unpack (view dbUser a))
(unpack (view dbPass a))
(unpack (view dbName a))
createPool (connect i) close
(fromIntegral (view poolStripes a))
(fromIntegral (view poolKillTime a))
(fromIntegral (view poolCount a))
| null |
https://raw.githubusercontent.com/alasconnect/azure-demo/5d16db775ccf3b753f4ef078bad8e9437b844d76/backend/src/App.hs
|
haskell
|
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
We defer running our code in a particular monad transformer stack
until later at the API level. Until then it is simply in a Servant Handler.
Check the configuration file for sanity without running the app.
This is useful for double checking against a built binary in a CI server
without actually starting the process.
Generate database connection pool
Run webserver
|
# LANGUAGE FlexibleContexts #
module App where
import Control.Lens
import Control.Monad (unless)
import Data.Pool
import Data.Proxy
import Data.Text (pack, unpack)
import Dhall
import Database.Beam.Postgres
import Network.Wai
import qualified Network.Wai.Handler.Warp as W
import Servant
import Api
import Opts
import Routes
import Types
Standard Servant setup
totalApi :: Proxy Routes
totalApi = Proxy
app :: AppContext -> Application
app ctx = serve totalApi (api ctx)
run :: OptConfig -> IO ()
run o = do
Parse configuration file
a <- input auto (pack (optConfigFile o))
unless (optConfigCheck o) $ do
p <- mkPool a
putStrLn ("Running server on port " ++ show (view appPort a))
W.run (fromIntegral (view appPort a)) (app (AppContext p a))
where
mkPool a = do
let i = ConnectInfo
(unpack (view dbHost a))
(fromIntegral (view dbPort a))
(unpack (view dbUser a))
(unpack (view dbPass a))
(unpack (view dbName a))
createPool (connect i) close
(fromIntegral (view poolStripes a))
(fromIntegral (view poolKillTime a))
(fromIntegral (view poolCount a))
|
73ae4743a6ffec61b4e274115a25403760f9d5f6b22603e909b5eb53ada05169
|
zadean/xqerl
|
prod_Annotation_SUITE.erl
|
-module('prod_Annotation_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['annotation-1'/1]).
-export(['annotation-2'/1]).
-export(['annotation-3'/1]).
-export(['annotation-4'/1]).
-export(['annotation-5'/1]).
-export(['annotation-6'/1]).
-export(['annotation-7'/1]).
-export(['annotation-8'/1]).
-export(['annotation-9'/1]).
-export(['annotation-10'/1]).
-export(['annotation-11'/1]).
-export(['annotation-12'/1]).
-export(['annotation-13'/1]).
-export(['annotation-14'/1]).
-export(['annotation-15'/1]).
-export(['annotation-16'/1]).
-export(['annotation-17'/1]).
-export(['annotation-18'/1]).
-export(['annotation-19'/1]).
-export(['annotation-20'/1]).
-export(['annotation-21'/1]).
-export(['annotation-22'/1]).
-export(['annotation-23'/1]).
-export(['annotation-24'/1]).
-export(['annotation-25'/1]).
-export(['annotation-26'/1]).
-export(['annotation-27'/1]).
-export(['annotation-28'/1]).
-export(['annotation-29'/1]).
-export(['annotation-30'/1]).
-export(['annotation-31'/1]).
-export(['annotation-32'/1]).
-export(['annotation-33'/1]).
-export(['annotation-34'/1]).
-export(['annotation-35'/1]).
-export(['annotation-36'/1]).
-export(['annotation-37'/1]).
-export(['annotation-38'/1]).
-export(['annotation-assertion-1'/1]).
-export(['annotation-assertion-2'/1]).
-export(['annotation-assertion-3'/1]).
-export(['annotation-assertion-4'/1]).
-export(['annotation-assertion-5'/1]).
-export(['annotation-assertion-6'/1]).
-export(['annotation-assertion-7'/1]).
-export(['annotation-assertion-8'/1]).
-export(['annotation-assertion-9'/1]).
-export(['annotation-assertion-10'/1]).
-export(['annotation-assertion-11'/1]).
-export(['annotation-assertion-12'/1]).
-export(['annotation-assertion-13'/1]).
-export(['annotation-assertion-14'/1]).
-export(['annotation-assertion-15'/1]).
-export(['annotation-assertion-16'/1]).
-export(['annotation-assertion-17'/1]).
-export(['annotation-assertion-18'/1]).
-export(['annotation-assertion-19'/1]).
-export(['annotation-assertion-20'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "prod"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0},
{group, group_1},
{group, group_2}
].
groups() ->
[
{group_0, [parallel], [
'annotation-1',
'annotation-2',
'annotation-3',
'annotation-4',
'annotation-5',
'annotation-6',
'annotation-7',
'annotation-8',
'annotation-9',
'annotation-10',
'annotation-11',
'annotation-12',
'annotation-13',
'annotation-14',
'annotation-15',
'annotation-16',
'annotation-17',
'annotation-18',
'annotation-19',
'annotation-20',
'annotation-21',
'annotation-22',
'annotation-23'
]},
{group_1, [parallel], [
'annotation-24',
'annotation-25',
'annotation-26',
'annotation-27',
'annotation-28',
'annotation-29',
'annotation-30',
'annotation-31',
'annotation-32',
'annotation-33',
'annotation-34',
'annotation-35',
'annotation-36',
'annotation-37',
'annotation-38',
'annotation-assertion-1',
'annotation-assertion-2',
'annotation-assertion-3',
'annotation-assertion-4',
'annotation-assertion-5',
'annotation-assertion-6',
'annotation-assertion-7',
'annotation-assertion-8',
'annotation-assertion-9'
]},
{group_2, [parallel], [
'annotation-assertion-10',
'annotation-assertion-11',
'annotation-assertion-12',
'annotation-assertion-13',
'annotation-assertion-14',
'annotation-assertion-15',
'annotation-assertion-16',
'annotation-assertion-17',
'annotation-assertion-18',
'annotation-assertion-19',
'annotation-assertion-20'
]}
].
'annotation-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" declare %eg:sequential function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-1.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" declare %eg:sequential variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-2.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" %eg:sequential function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-3.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace java = \"\";\n"
"\n"
" declare %java:variable(\"java.lang.Integer.MAX_VALUE\") variable $max := 0;\n"
"\n"
" declare %java:method(\"java.lang.Math.sin\") function local:sin($arg) { 0 }; \n"
"\n"
" local:sin($max)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-4.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:integer(1234) variable $foo := 0;\n"
"\n"
" declare %eg:integer(1234) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-5.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:integer(12.34) variable $foo := 0;\n"
"\n"
" declare %eg:integer(12.34) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-6.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:integer(12e34) variable $foo := 0;\n"
"\n"
" declare %eg:integer(12e34) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-7.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:integer(1+2) function local:foo() { 0 }; \n"
"\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-8.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:many(12e34,\"abc\",1234) variable $foo := 0;\n"
"\n"
" declare %eg:many(\"xyz\", 987, 12.3) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-9.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{}bar variable $foo := 0;\n"
"\n"
" declare %Q{}bar function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-10.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-11'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:one %eg:two %eg:three variable $foo := 0;\n"
"\n"
" declare %eg:one %eg:two %eg:three function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-11.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-12'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:one%eg:two%eg:three(1)%eg:four variable $foo := 0;\n"
"\n"
" declare %eg:one%eg:two%eg:three(1)%eg:four function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-12.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-13'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare \n"
" %eg:one\n"
" %eg:two\n"
" (: Lorem ipsum dolor sit amet. :)\n"
" %eg:three(1)\n"
" %Q{}four\n"
" variable $foo := 0;\n"
"\n"
" declare \n"
" %eg:one\n"
" %eg:two\n"
" (: Lorem ipsum dolor sit amet. :)\n"
" %eg:three(1)\n"
" %Q{}four\n"
" function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-13.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-14'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:one(1, 2, 3) %eg:two(\"a\", \"b\") %eg:three(1.234) variable $foo := 0;\n"
"\n"
" declare %eg:one(1, 2, 3) %eg:two(\"a\", \"b\") %eg:three(1.234) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-14.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-15'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %xml:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-15.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-16'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-16.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-17'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %xs:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-17.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-18'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-18.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-19'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %xsi:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-19.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-20'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{-instance}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-20.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-21'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %fn:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-21.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-22'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{-functions}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-22.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-23'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-23.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-24'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace math = \"-functions/math\";\n"
" declare %math:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-24.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-25'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{-functions/math}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-25.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-26'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace opts = \"\";\n"
" declare %opts:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-26.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-27'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-27.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-28'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare default function namespace \"\";\n"
" declare %x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-28.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-29'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %local:x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-29.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-30'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" %eg:sequential(\"abc\", 3) function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-30.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-31'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" % Q{}sequential(\"abc\", 3) function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-31.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-32'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" %eg:sequential(\"abc\", 3) %eg:memo-function function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-32.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-33'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" %eg:sequential(true()) function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-33.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-34'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare default function namespace \"\";\n"
" declare %private function lt() as item()*{\n"
" ()\n"
" };\n"
" ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-34.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-35'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace array = \"-functions/array\";\n"
" declare %array:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-35.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-36'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace map = \"-functions/map\";\n"
" declare %map:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-36.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-37'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace a = \"\";\n"
" declare %a:translucent(\"true\") %a:translucent(\"false\") function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-37.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-38'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace a = \"\";\n"
" declare %a:translucent(\"true\") %a:translucent(\"false\") variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-38.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(\"foo\") function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(1234) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(12.34) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(12e34) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-5.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(\"abc\", 12e34, 567) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-6.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %Q{}x function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-7.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %Q{}x function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-8.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x %eg:y%eg:z %eg:w(1) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-9.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x function(xs:integer) as xs:string\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-10.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-11'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %xml:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-11.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-12'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %Q{}x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-12.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-13'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %xs:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-13.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-14'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %Q{}x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-14.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-15'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %xsi:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-15.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-16'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %fn:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-16.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-17'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace math = \"-functions/math\";\n"
" () instance of %math:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-17.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-18'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace opts = \"\";\n"
" () instance of %opts:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-18.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-19'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(1) %eg:x(2) function(xs:integer) as xs:string\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-19.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-20'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" declare %public function local:three() as xs:integer {3};\n"
" local:three#0 instance of %public %private function(xs:integer) as xs:integer\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-20.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| null |
https://raw.githubusercontent.com/zadean/xqerl/1a94833e996435495922346010ce918b4b0717f2/test/prod/prod_Annotation_SUITE.erl
|
erlang
|
-module('prod_Annotation_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['annotation-1'/1]).
-export(['annotation-2'/1]).
-export(['annotation-3'/1]).
-export(['annotation-4'/1]).
-export(['annotation-5'/1]).
-export(['annotation-6'/1]).
-export(['annotation-7'/1]).
-export(['annotation-8'/1]).
-export(['annotation-9'/1]).
-export(['annotation-10'/1]).
-export(['annotation-11'/1]).
-export(['annotation-12'/1]).
-export(['annotation-13'/1]).
-export(['annotation-14'/1]).
-export(['annotation-15'/1]).
-export(['annotation-16'/1]).
-export(['annotation-17'/1]).
-export(['annotation-18'/1]).
-export(['annotation-19'/1]).
-export(['annotation-20'/1]).
-export(['annotation-21'/1]).
-export(['annotation-22'/1]).
-export(['annotation-23'/1]).
-export(['annotation-24'/1]).
-export(['annotation-25'/1]).
-export(['annotation-26'/1]).
-export(['annotation-27'/1]).
-export(['annotation-28'/1]).
-export(['annotation-29'/1]).
-export(['annotation-30'/1]).
-export(['annotation-31'/1]).
-export(['annotation-32'/1]).
-export(['annotation-33'/1]).
-export(['annotation-34'/1]).
-export(['annotation-35'/1]).
-export(['annotation-36'/1]).
-export(['annotation-37'/1]).
-export(['annotation-38'/1]).
-export(['annotation-assertion-1'/1]).
-export(['annotation-assertion-2'/1]).
-export(['annotation-assertion-3'/1]).
-export(['annotation-assertion-4'/1]).
-export(['annotation-assertion-5'/1]).
-export(['annotation-assertion-6'/1]).
-export(['annotation-assertion-7'/1]).
-export(['annotation-assertion-8'/1]).
-export(['annotation-assertion-9'/1]).
-export(['annotation-assertion-10'/1]).
-export(['annotation-assertion-11'/1]).
-export(['annotation-assertion-12'/1]).
-export(['annotation-assertion-13'/1]).
-export(['annotation-assertion-14'/1]).
-export(['annotation-assertion-15'/1]).
-export(['annotation-assertion-16'/1]).
-export(['annotation-assertion-17'/1]).
-export(['annotation-assertion-18'/1]).
-export(['annotation-assertion-19'/1]).
-export(['annotation-assertion-20'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "prod"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0},
{group, group_1},
{group, group_2}
].
groups() ->
[
{group_0, [parallel], [
'annotation-1',
'annotation-2',
'annotation-3',
'annotation-4',
'annotation-5',
'annotation-6',
'annotation-7',
'annotation-8',
'annotation-9',
'annotation-10',
'annotation-11',
'annotation-12',
'annotation-13',
'annotation-14',
'annotation-15',
'annotation-16',
'annotation-17',
'annotation-18',
'annotation-19',
'annotation-20',
'annotation-21',
'annotation-22',
'annotation-23'
]},
{group_1, [parallel], [
'annotation-24',
'annotation-25',
'annotation-26',
'annotation-27',
'annotation-28',
'annotation-29',
'annotation-30',
'annotation-31',
'annotation-32',
'annotation-33',
'annotation-34',
'annotation-35',
'annotation-36',
'annotation-37',
'annotation-38',
'annotation-assertion-1',
'annotation-assertion-2',
'annotation-assertion-3',
'annotation-assertion-4',
'annotation-assertion-5',
'annotation-assertion-6',
'annotation-assertion-7',
'annotation-assertion-8',
'annotation-assertion-9'
]},
{group_2, [parallel], [
'annotation-assertion-10',
'annotation-assertion-11',
'annotation-assertion-12',
'annotation-assertion-13',
'annotation-assertion-14',
'annotation-assertion-15',
'annotation-assertion-16',
'annotation-assertion-17',
'annotation-assertion-18',
'annotation-assertion-19',
'annotation-assertion-20'
]}
].
'annotation-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" declare %eg:sequential function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-1.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" declare %eg:sequential variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-2.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" %eg:sequential function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-3.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace java = \"\";\n"
"\n"
" declare %java:variable(\"java.lang.Integer.MAX_VALUE\") variable $max := 0;\n"
"\n"
" declare %java:method(\"java.lang.Math.sin\") function local:sin($arg) { 0 }; \n"
"\n"
" local:sin($max)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-4.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:integer(1234) variable $foo := 0;\n"
"\n"
" declare %eg:integer(1234) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-5.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:integer(12.34) variable $foo := 0;\n"
"\n"
" declare %eg:integer(12.34) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-6.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:integer(12e34) variable $foo := 0;\n"
"\n"
" declare %eg:integer(12e34) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-7.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:integer(1+2) function local:foo() { 0 }; \n"
"\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-8.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:many(12e34,\"abc\",1234) variable $foo := 0;\n"
"\n"
" declare %eg:many(\"xyz\", 987, 12.3) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-9.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{}bar variable $foo := 0;\n"
"\n"
" declare %Q{}bar function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-10.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-11'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:one %eg:two %eg:three variable $foo := 0;\n"
"\n"
" declare %eg:one %eg:two %eg:three function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-11.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-12'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:one%eg:two%eg:three(1)%eg:four variable $foo := 0;\n"
"\n"
" declare %eg:one%eg:two%eg:three(1)%eg:four function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-12.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-13'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare \n"
" %eg:one\n"
" %eg:two\n"
" (: Lorem ipsum dolor sit amet. :)\n"
" %eg:three(1)\n"
" %Q{}four\n"
" variable $foo := 0;\n"
"\n"
" declare \n"
" %eg:one\n"
" %eg:two\n"
" (: Lorem ipsum dolor sit amet. :)\n"
" %eg:three(1)\n"
" %Q{}four\n"
" function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-13.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-14'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
"\n"
" declare %eg:one(1, 2, 3) %eg:two(\"a\", \"b\") %eg:three(1.234) variable $foo := 0;\n"
"\n"
" declare %eg:one(1, 2, 3) %eg:two(\"a\", \"b\") %eg:three(1.234) function local:foo($arg) { $arg }; \n"
"\n"
" local:foo($foo)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-14.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "0") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-15'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %xml:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-15.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-16'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-16.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-17'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %xs:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-17.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-18'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-18.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-19'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %xsi:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-19.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-20'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{-instance}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-20.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-21'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %fn:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-21.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-22'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{-functions}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-22.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-23'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-23.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-24'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace math = \"-functions/math\";\n"
" declare %math:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-24.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-25'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{-functions/math}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-25.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-26'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace opts = \"\";\n"
" declare %opts:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-26.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-27'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %Q{}x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-27.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-28'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare default function namespace \"\";\n"
" declare %x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-28.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-29'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare %local:x variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-29.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-30'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" %eg:sequential(\"abc\", 3) function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-30.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-31'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" % Q{}sequential(\"abc\", 3) function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-31.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-32'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" %eg:sequential(\"abc\", 3) %eg:memo-function function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-32.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-33'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" %eg:sequential(true()) function () { \"bar\" } ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-33.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0003") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0003 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-34'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare default function namespace \"\";\n"
" declare %private function lt() as item()*{\n"
" ()\n"
" };\n"
" ()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-34.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-35'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace array = \"-functions/array\";\n"
" declare %array:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-35.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-36'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace map = \"-functions/map\";\n"
" declare %map:x function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-36.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-37'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace a = \"\";\n"
" declare %a:translucent(\"true\") %a:translucent(\"false\") function local:foo() {\n"
" \"bar\"\n"
" };\n"
" local:foo()\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-37.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-38'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace a = \"\";\n"
" declare %a:translucent(\"true\") %a:translucent(\"false\") variable $foo := \"bar\";\n"
" $foo\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "annotation-38.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_eq(Res, "\"bar\"") of
true -> {comment, "Equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(\"foo\") function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(1234) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(12.34) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(12e34) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-5.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(\"abc\", 12e34, 567) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-6.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %Q{}x function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-7.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %Q{}x function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-8.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x %eg:y%eg:z %eg:w(1) function(*)\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-9.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x function(xs:integer) as xs:string\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-10.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-11'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %xml:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-11.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-12'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %Q{}x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-12.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-13'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %xs:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-13.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-14'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %Q{}x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-14.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-15'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %xsi:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-15.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-16'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" () instance of %fn:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-16.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-17'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace math = \"-functions/math\";\n"
" () instance of %math:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-17.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-18'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace opts = \"\";\n"
" () instance of %opts:x function(*) \n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-18.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XQST0045") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XQST0045 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-19'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" () instance of %eg:x(1) %eg:x(2) function(xs:integer) as xs:string\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-19.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'annotation-assertion-20'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" declare namespace eg = \"\";\n"
" declare %public function local:three() as xs:integer {3};\n"
" local:three#0 instance of %public %private function(xs:integer) as xs:integer\n"
" ",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "annotation-assertion-20.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
|
|
7ce1a21d8ee9a79a4974f77adabc0b8728f05c4ed08f95deaeb7efa2907c313e
|
awakesecurity/proto3-wire
|
Types.hs
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveLift #-}
# LANGUAGE GeneralizedNewtypeDeriving #
Copyright 2016 Awake Networks
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2016 Awake Networks
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
-- | This module defines types which are shared by the encoding and decoding
-- modules.
module Proto3.Wire.Types
( -- * Message Structure
FieldNumber(..)
, fieldNumber
, WireType(..)
) where
import Control.DeepSeq ( NFData )
import Data.Data ( Data )
import Data.Hashable ( Hashable )
import Data.Word ( Word64 )
import GHC.Generics ( Generic )
import Language.Haskell.TH.Syntax ( Lift )
import Test.QuickCheck ( Arbitrary(..), choose )
-- | A 'FieldNumber' identifies a field inside a protobufs message.
--
-- This library makes no attempt to generate these automatically, or even make
-- sure that field numbers are provided in increasing order. Such things are
-- left to other, higher-level libraries.
newtype FieldNumber = FieldNumber
{ getFieldNumber :: Word64 }
deriving (Bounded, Data, Enum, Eq, Generic, Hashable, Lift, NFData, Num, Ord)
instance Show FieldNumber where
show (FieldNumber n) = show n
instance Arbitrary FieldNumber where
arbitrary = FieldNumber <$> choose (1, 536870911)
| Create a ' FieldNumber ' given the ( one - based ) integer which would label
-- the field in the corresponding .proto file.
fieldNumber :: Word64 -> FieldNumber
fieldNumber = FieldNumber
| The ( non - deprecated ) wire types identified by the Protocol
-- Buffers specification.
data WireType
= Varint
| Fixed32
| Fixed64
| LengthDelimited
deriving (Bounded, Data, Enum, Eq, Generic, Lift, Ord, Show)
| null |
https://raw.githubusercontent.com/awakesecurity/proto3-wire/5ffc23c39345e075ae118af789c28d4febb58544/src/Proto3/Wire/Types.hs
|
haskell
|
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveGeneric #
# LANGUAGE DeriveLift #
| This module defines types which are shared by the encoding and decoding
modules.
* Message Structure
| A 'FieldNumber' identifies a field inside a protobufs message.
This library makes no attempt to generate these automatically, or even make
sure that field numbers are provided in increasing order. Such things are
left to other, higher-level libraries.
the field in the corresponding .proto file.
Buffers specification.
|
# LANGUAGE GeneralizedNewtypeDeriving #
Copyright 2016 Awake Networks
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2016 Awake Networks
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Proto3.Wire.Types
FieldNumber(..)
, fieldNumber
, WireType(..)
) where
import Control.DeepSeq ( NFData )
import Data.Data ( Data )
import Data.Hashable ( Hashable )
import Data.Word ( Word64 )
import GHC.Generics ( Generic )
import Language.Haskell.TH.Syntax ( Lift )
import Test.QuickCheck ( Arbitrary(..), choose )
newtype FieldNumber = FieldNumber
{ getFieldNumber :: Word64 }
deriving (Bounded, Data, Enum, Eq, Generic, Hashable, Lift, NFData, Num, Ord)
instance Show FieldNumber where
show (FieldNumber n) = show n
instance Arbitrary FieldNumber where
arbitrary = FieldNumber <$> choose (1, 536870911)
| Create a ' FieldNumber ' given the ( one - based ) integer which would label
fieldNumber :: Word64 -> FieldNumber
fieldNumber = FieldNumber
| The ( non - deprecated ) wire types identified by the Protocol
data WireType
= Varint
| Fixed32
| Fixed64
| LengthDelimited
deriving (Bounded, Data, Enum, Eq, Generic, Lift, Ord, Show)
|
8309b17f17868cfd823eb5ac8a0f0116b4134e184772d00087774831e4a93d5e
|
janestreet/bonsai
|
var.mli
|
open! Core
open! Import
(* $MDX part-begin=var_module_signature *)
type 'a t
(** Creates a var with an initial value. *)
val create : 'a -> 'a t
(** Runs a function over the current value and updates it to the result. *)
val update : 'a t -> f:('a -> 'a) -> unit
(** Change the current value. *)
val set : 'a t -> 'a -> unit
(** Retrieve the current value. *)
val get : 'a t -> 'a
(** Get a value that tracks the current value, for use in a computation. *)
val value : 'a t -> 'a Value.t
(* $MDX part-end *)
| null |
https://raw.githubusercontent.com/janestreet/bonsai/33e9a58fc55ec12095959dc5ef4fd681021c1083/src/var.mli
|
ocaml
|
$MDX part-begin=var_module_signature
* Creates a var with an initial value.
* Runs a function over the current value and updates it to the result.
* Change the current value.
* Retrieve the current value.
* Get a value that tracks the current value, for use in a computation.
$MDX part-end
|
open! Core
open! Import
type 'a t
val create : 'a -> 'a t
val update : 'a t -> f:('a -> 'a) -> unit
val set : 'a t -> 'a -> unit
val get : 'a t -> 'a
val value : 'a t -> 'a Value.t
|
e1d6e6af7fb35c8ef7abcf1ebc3c7d3a9eb8c75ae60d0abbadd810126842b3b7
|
MaskRay/OJHaskell
|
34.hs
|
import Data.Char
factorial = scanl (*) 1 [1..9]
main = print . sum $ [x | x <- [10..999999], (sum . map (product . enumFromTo 1 . digitToInt) . show $ x) == x]
| null |
https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/Project%20Euler/34.hs
|
haskell
|
import Data.Char
factorial = scanl (*) 1 [1..9]
main = print . sum $ [x | x <- [10..999999], (sum . map (product . enumFromTo 1 . digitToInt) . show $ x) == x]
|
|
ab0e4894465db2d458c1dcb3514f77e9b8ecf7b9eeec3bee12f96dceb265a5ce
|
fpco/wai-middleware-auth
|
OAuth2.hs
|
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
module Network.Wai.Middleware.Auth.OAuth2
( OAuth2(..)
, oAuth2Parser
, URIParseException(..)
, parseAbsoluteURI
, getAccessToken
) where
import Control.Monad.Catch
import Data.Aeson.TH (defaultOptions,
deriveJSON,
fieldLabelModifier)
import Data.Functor ((<&>))
import Data.Int (Int64)
import Data.Proxy (Proxy (..))
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Foreign.C.Types (CTime (..))
import Network.HTTP.Client.TLS (getGlobalManager)
import qualified Network.OAuth.OAuth2 as OA2
import Network.Wai (Request)
import Network.Wai.Auth.Internal (decodeToken, encodeToken,
oauth2Login,
refreshTokens)
import Network.Wai.Auth.Tools (toLowerUnderscore)
import qualified Network.Wai.Middleware.Auth as MA
import Network.Wai.Middleware.Auth.Provider
import System.PosixCompat.Time (epochTime)
import qualified URI.ByteString as U
| General authentication ` Provider ` .
data OAuth2 = OAuth2
{ oa2ClientId :: T.Text
, oa2ClientSecret :: T.Text
, oa2AuthorizeEndpoint :: T.Text
, oa2AccessTokenEndpoint :: T.Text
, oa2Scope :: Maybe [T.Text]
, oa2ProviderInfo :: ProviderInfo
}
-- | Used for validating proper url structure. Can be thrown by
-- `parseAbsoluteURI` and consequently by `handleLogin` for `OAuth2` `Provider`
-- instance.
--
-- @since 0.1.2.0
data URIParseException = URIParseException U.URIParseError deriving Show
instance Exception URIParseException
| Parse absolute URI and throw ` URIParseException ` in case it is malformed
--
-- @since 0.1.2.0
parseAbsoluteURI :: MonadThrow m => T.Text -> m U.URI
parseAbsoluteURI urlTxt = do
case U.parseURI U.strictURIParserOptions (encodeUtf8 urlTxt) of
Left err -> throwM $ URIParseException err
Right url -> return url
getClientId :: T.Text -> T.Text
getClientId = id
getClientSecret :: T.Text -> T.Text
getClientSecret = id
$(deriveJSON defaultOptions { fieldLabelModifier = toLowerUnderscore . drop 3} ''OAuth2)
-- | Aeson parser for `OAuth2` provider.
--
@since 0.1.0
oAuth2Parser :: ProviderParser
oAuth2Parser = mkProviderParser (Proxy :: Proxy OAuth2)
instance AuthProvider OAuth2 where
getProviderName _ = "oauth2"
getProviderInfo = oa2ProviderInfo
handleLogin oa2@OAuth2 {..} req suffix renderUrl onSuccess onFailure = do
authEndpointURI <- parseAbsoluteURI oa2AuthorizeEndpoint
accessTokenEndpointURI <- parseAbsoluteURI oa2AccessTokenEndpoint
callbackURI <- parseAbsoluteURI $ renderUrl (ProviderUrl ["complete"]) []
let oauth2 =
OA2.OAuth2
{ oauthClientId = getClientId oa2ClientId
, oauthClientSecret = Just $ getClientSecret oa2ClientSecret
, oauthOAuthorizeEndpoint = authEndpointURI
, oauthAccessTokenEndpoint = accessTokenEndpointURI
, oauthCallback = Just callbackURI
}
man <- getGlobalManager
oauth2Login
oauth2
man
oa2Scope
(getProviderName oa2)
req
suffix
onSuccess
onFailure
refreshLoginState OAuth2 {..} req user = do
authEndpointURI <- parseAbsoluteURI oa2AuthorizeEndpoint
accessTokenEndpointURI <- parseAbsoluteURI oa2AccessTokenEndpoint
let loginState = authLoginState user
case decodeToken loginState of
Left _ -> pure Nothing
Right tokens -> do
CTime now <- epochTime
if tokenExpired user now tokens then do
let oauth2 =
OA2.OAuth2
{ oauthClientId = getClientId oa2ClientId
, oauthClientSecret = Just (getClientSecret oa2ClientSecret)
, oauthOAuthorizeEndpoint = authEndpointURI
, oauthAccessTokenEndpoint = accessTokenEndpointURI
-- Setting callback endpoint to `Nothing` below is a lie.
-- We do have a callback endpoint but in this context
-- don't have access to the function that can render it.
-- We get away with this because the callback endpoint is
-- not needed for obtaining a refresh token, the only
-- way we use the config here constructed.
, oauthCallback = Nothing
}
man <- getGlobalManager
rRes <- refreshTokens tokens man oauth2
pure (rRes <&> \newTokens -> (req, user {
authLoginState = encodeToken newTokens,
authLoginTime = fromIntegral now
}))
else
pure (Just (req, user))
tokenExpired :: AuthUser -> Int64 -> OA2.OAuth2Token -> Bool
tokenExpired user now tokens =
case OA2.expiresIn tokens of
Nothing -> False
Just expiresIn -> authLoginTime user + (fromIntegral expiresIn) < now
| Get the @AccessToken@ for the current user .
--
-- If called on a @Request@ behind the middleware, should always return a
-- @Just@ value.
--
@since 0.2.0.0
getAccessToken :: Request -> Maybe OA2.OAuth2Token
getAccessToken req = do
user <- MA.getAuthUser req
either (const Nothing) Just $ decodeToken (authLoginState user)
| null |
https://raw.githubusercontent.com/fpco/wai-middleware-auth/0ae5ebb7f0cc3255927a81b78c0d4f5ed66befd0/src/Network/Wai/Middleware/Auth/OAuth2.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
| Used for validating proper url structure. Can be thrown by
`parseAbsoluteURI` and consequently by `handleLogin` for `OAuth2` `Provider`
instance.
@since 0.1.2.0
@since 0.1.2.0
| Aeson parser for `OAuth2` provider.
Setting callback endpoint to `Nothing` below is a lie.
We do have a callback endpoint but in this context
don't have access to the function that can render it.
We get away with this because the callback endpoint is
not needed for obtaining a refresh token, the only
way we use the config here constructed.
If called on a @Request@ behind the middleware, should always return a
@Just@ value.
|
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
module Network.Wai.Middleware.Auth.OAuth2
( OAuth2(..)
, oAuth2Parser
, URIParseException(..)
, parseAbsoluteURI
, getAccessToken
) where
import Control.Monad.Catch
import Data.Aeson.TH (defaultOptions,
deriveJSON,
fieldLabelModifier)
import Data.Functor ((<&>))
import Data.Int (Int64)
import Data.Proxy (Proxy (..))
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Foreign.C.Types (CTime (..))
import Network.HTTP.Client.TLS (getGlobalManager)
import qualified Network.OAuth.OAuth2 as OA2
import Network.Wai (Request)
import Network.Wai.Auth.Internal (decodeToken, encodeToken,
oauth2Login,
refreshTokens)
import Network.Wai.Auth.Tools (toLowerUnderscore)
import qualified Network.Wai.Middleware.Auth as MA
import Network.Wai.Middleware.Auth.Provider
import System.PosixCompat.Time (epochTime)
import qualified URI.ByteString as U
| General authentication ` Provider ` .
data OAuth2 = OAuth2
{ oa2ClientId :: T.Text
, oa2ClientSecret :: T.Text
, oa2AuthorizeEndpoint :: T.Text
, oa2AccessTokenEndpoint :: T.Text
, oa2Scope :: Maybe [T.Text]
, oa2ProviderInfo :: ProviderInfo
}
data URIParseException = URIParseException U.URIParseError deriving Show
instance Exception URIParseException
| Parse absolute URI and throw ` URIParseException ` in case it is malformed
parseAbsoluteURI :: MonadThrow m => T.Text -> m U.URI
parseAbsoluteURI urlTxt = do
case U.parseURI U.strictURIParserOptions (encodeUtf8 urlTxt) of
Left err -> throwM $ URIParseException err
Right url -> return url
getClientId :: T.Text -> T.Text
getClientId = id
getClientSecret :: T.Text -> T.Text
getClientSecret = id
$(deriveJSON defaultOptions { fieldLabelModifier = toLowerUnderscore . drop 3} ''OAuth2)
@since 0.1.0
oAuth2Parser :: ProviderParser
oAuth2Parser = mkProviderParser (Proxy :: Proxy OAuth2)
instance AuthProvider OAuth2 where
getProviderName _ = "oauth2"
getProviderInfo = oa2ProviderInfo
handleLogin oa2@OAuth2 {..} req suffix renderUrl onSuccess onFailure = do
authEndpointURI <- parseAbsoluteURI oa2AuthorizeEndpoint
accessTokenEndpointURI <- parseAbsoluteURI oa2AccessTokenEndpoint
callbackURI <- parseAbsoluteURI $ renderUrl (ProviderUrl ["complete"]) []
let oauth2 =
OA2.OAuth2
{ oauthClientId = getClientId oa2ClientId
, oauthClientSecret = Just $ getClientSecret oa2ClientSecret
, oauthOAuthorizeEndpoint = authEndpointURI
, oauthAccessTokenEndpoint = accessTokenEndpointURI
, oauthCallback = Just callbackURI
}
man <- getGlobalManager
oauth2Login
oauth2
man
oa2Scope
(getProviderName oa2)
req
suffix
onSuccess
onFailure
refreshLoginState OAuth2 {..} req user = do
authEndpointURI <- parseAbsoluteURI oa2AuthorizeEndpoint
accessTokenEndpointURI <- parseAbsoluteURI oa2AccessTokenEndpoint
let loginState = authLoginState user
case decodeToken loginState of
Left _ -> pure Nothing
Right tokens -> do
CTime now <- epochTime
if tokenExpired user now tokens then do
let oauth2 =
OA2.OAuth2
{ oauthClientId = getClientId oa2ClientId
, oauthClientSecret = Just (getClientSecret oa2ClientSecret)
, oauthOAuthorizeEndpoint = authEndpointURI
, oauthAccessTokenEndpoint = accessTokenEndpointURI
, oauthCallback = Nothing
}
man <- getGlobalManager
rRes <- refreshTokens tokens man oauth2
pure (rRes <&> \newTokens -> (req, user {
authLoginState = encodeToken newTokens,
authLoginTime = fromIntegral now
}))
else
pure (Just (req, user))
tokenExpired :: AuthUser -> Int64 -> OA2.OAuth2Token -> Bool
tokenExpired user now tokens =
case OA2.expiresIn tokens of
Nothing -> False
Just expiresIn -> authLoginTime user + (fromIntegral expiresIn) < now
| Get the @AccessToken@ for the current user .
@since 0.2.0.0
getAccessToken :: Request -> Maybe OA2.OAuth2Token
getAccessToken req = do
user <- MA.getAuthUser req
either (const Nothing) Just $ decodeToken (authLoginState user)
|
0e7865cb3015986953c3a1e89c009e4bf49f34372be482fd48382fc8cb1498a9
|
clojure/core.typed
|
tc_equiv.clj
|
Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns clojure.core.typed.checker.jvm.tc-equiv
(:require [clojure.core.typed.checker.type-rep :as r]
[clojure.core.typed.checker.type-ctors :as c]
[clojure.core.typed.checker.filter-rep :as fl]
[clojure.core.typed.checker.filter-ops :as fo]
[clojure.core.typed.checker.check-below :as below]
[clojure.math.combinatorics :as comb]
[clojure.core.typed.current-impl :as impl]))
(defn equivable [t]
{:pre [(r/Type? t)]
:post [((some-fn nil? r/Type?) %)]}
(or (when (r/Value? t)
(when ((some-fn string? number? symbol? keyword? nil? true? false? class?) (:val t))
t))
(impl/impl-case
:clojure nil
; (if (= undefined a)
; .. ; a :- nil
; .. ; a :- (Not nil))
; (if (= null a)
; .. ; a :- nil
; .. ; a :- (Not nil))
:cljs (when ((some-fn r/JSNull? r/JSUndefined?) t)
(r/-val nil)))))
(defn identicalable [branch t]
{:pre [(#{:then :else} branch)
(r/Type? t)]
:post [((some-fn nil? r/Type?) %)]}
(or (when (r/Value? t)
(let [v (:val t)]
(case branch
:then (when ((some-fn number? symbol? keyword? nil? true? false? class?) v)
t)
:else (or (when ((some-fn true? false?) v)
t)
(when (nil? v)
(impl/impl-case
:clojure t
when ( identical ? ( - form ... nil ) a ) is false , we ca n't
say ` a ` is non - nil ( either arg could be JSUndefined or JSNull ) .
:cljs nil))))))
(impl/impl-case
:clojure nil
:cljs (when ((some-fn r/JSNull? r/JSUndefined?) t)
t))))
[ Any TCResult * - > ]
(defn tc-equiv [comparator vs expected]
{:pre [(every? r/TCResult? vs)
((some-fn nil? r/TCResult?) expected)]
:post [(r/TCResult? %)]}
(assert (seq vs))
(let [[then-equivable else-equivable]
(case comparator
:= [equivable equivable]
:identical? [#(identicalable :then %)
#(identicalable :else %)])
; TODO sequence behaviour is subtle
; conservative for now
vs-combinations (comb/combinations vs 2)
;_ (prn (count vs-combinations))
then-filter (apply fo/-and (apply concat
(for [[{t1 :t fl1 :fl o1 :o}
{t2 :t fl2 :fl o2 :o}] vs-combinations]
(concat
(when-some [t1 (then-equivable t1)]
[(fo/-filter-at t1 o2)])
(when-some [t2 (then-equivable t2)]
[(fo/-filter-at t2 o1)])))))
;_ (prn "then" then-filter)
else-filter (apply fo/-or
(if-let [fs (seq (apply concat
(for [[{t1 :t fl1 :fl o1 :o}
{t2 :t fl2 :fl o2 :o}] vs-combinations]
(concat
(when-some [t1 (else-equivable t1)]
;(prn "else t1" t1 o2 (fo/-not-filter-at t1 o2))
[(fo/-not-filter-at t1 o2)])
(when-some [t2 (else-equivable t2)]
;(prn "else t2" t2 o1 (fo/-not-filter-at t2 o1))
[(fo/-not-filter-at t2 o1)])))))]
fs
ensure we do n't simplify to ff if we have more than one
argument to = ( 1 arg is always a true value )
(when (< 1 (count vs))
[fl/-top])))
;_ (prn "else" else-filter)
]
(below/maybe-check-below
(r/ret (apply c/Un (concat (when (not= then-filter fl/-bot)
[r/-true])
(when (not= else-filter fl/-bot)
[r/-false])))
(fo/-FS then-filter else-filter))
expected)))
| null |
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/src/clojure/core/typed/checker/jvm/tc_equiv.clj
|
clojure
|
The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
(if (= undefined a)
.. ; a :- nil
.. ; a :- (Not nil))
(if (= null a)
.. ; a :- nil
.. ; a :- (Not nil))
TODO sequence behaviour is subtle
conservative for now
_ (prn (count vs-combinations))
_ (prn "then" then-filter)
(prn "else t1" t1 o2 (fo/-not-filter-at t1 o2))
(prn "else t2" t2 o1 (fo/-not-filter-at t2 o1))
_ (prn "else" else-filter)
|
Copyright ( c ) , contributors .
(ns clojure.core.typed.checker.jvm.tc-equiv
(:require [clojure.core.typed.checker.type-rep :as r]
[clojure.core.typed.checker.type-ctors :as c]
[clojure.core.typed.checker.filter-rep :as fl]
[clojure.core.typed.checker.filter-ops :as fo]
[clojure.core.typed.checker.check-below :as below]
[clojure.math.combinatorics :as comb]
[clojure.core.typed.current-impl :as impl]))
(defn equivable [t]
{:pre [(r/Type? t)]
:post [((some-fn nil? r/Type?) %)]}
(or (when (r/Value? t)
(when ((some-fn string? number? symbol? keyword? nil? true? false? class?) (:val t))
t))
(impl/impl-case
:clojure nil
:cljs (when ((some-fn r/JSNull? r/JSUndefined?) t)
(r/-val nil)))))
(defn identicalable [branch t]
{:pre [(#{:then :else} branch)
(r/Type? t)]
:post [((some-fn nil? r/Type?) %)]}
(or (when (r/Value? t)
(let [v (:val t)]
(case branch
:then (when ((some-fn number? symbol? keyword? nil? true? false? class?) v)
t)
:else (or (when ((some-fn true? false?) v)
t)
(when (nil? v)
(impl/impl-case
:clojure t
when ( identical ? ( - form ... nil ) a ) is false , we ca n't
say ` a ` is non - nil ( either arg could be JSUndefined or JSNull ) .
:cljs nil))))))
(impl/impl-case
:clojure nil
:cljs (when ((some-fn r/JSNull? r/JSUndefined?) t)
t))))
[ Any TCResult * - > ]
(defn tc-equiv [comparator vs expected]
{:pre [(every? r/TCResult? vs)
((some-fn nil? r/TCResult?) expected)]
:post [(r/TCResult? %)]}
(assert (seq vs))
(let [[then-equivable else-equivable]
(case comparator
:= [equivable equivable]
:identical? [#(identicalable :then %)
#(identicalable :else %)])
vs-combinations (comb/combinations vs 2)
then-filter (apply fo/-and (apply concat
(for [[{t1 :t fl1 :fl o1 :o}
{t2 :t fl2 :fl o2 :o}] vs-combinations]
(concat
(when-some [t1 (then-equivable t1)]
[(fo/-filter-at t1 o2)])
(when-some [t2 (then-equivable t2)]
[(fo/-filter-at t2 o1)])))))
else-filter (apply fo/-or
(if-let [fs (seq (apply concat
(for [[{t1 :t fl1 :fl o1 :o}
{t2 :t fl2 :fl o2 :o}] vs-combinations]
(concat
(when-some [t1 (else-equivable t1)]
[(fo/-not-filter-at t1 o2)])
(when-some [t2 (else-equivable t2)]
[(fo/-not-filter-at t2 o1)])))))]
fs
ensure we do n't simplify to ff if we have more than one
argument to = ( 1 arg is always a true value )
(when (< 1 (count vs))
[fl/-top])))
]
(below/maybe-check-below
(r/ret (apply c/Un (concat (when (not= then-filter fl/-bot)
[r/-true])
(when (not= else-filter fl/-bot)
[r/-false])))
(fo/-FS then-filter else-filter))
expected)))
|
bab8b443b1483c79057c9cf3994913d1e5aad6bd2b1e51e991344f148cf5110b
|
borodust/claw
|
packages.lisp
|
(cl:defpackage :claw
(:use :claw.util :claw.wrapper :claw.cffi.c)
(:export #:defwrapper
#:include
#:load-wrapper
#:generate-wrapper
#:build-adapter
#:initialize-adapter))
| null |
https://raw.githubusercontent.com/borodust/claw/04dcac64a72921430997a7b9105d18493feeaf7a/src/packages.lisp
|
lisp
|
(cl:defpackage :claw
(:use :claw.util :claw.wrapper :claw.cffi.c)
(:export #:defwrapper
#:include
#:load-wrapper
#:generate-wrapper
#:build-adapter
#:initialize-adapter))
|
|
633d2ab081041a6c1b11b8de5c4692e9c19b7dfac0a7d778a3b2aa9b63e438b2
|
ocaml/merlin
|
test_use.ml
|
open Foo
| null |
https://raw.githubusercontent.com/ocaml/merlin/e576bc75f11323ec8489d2e58a701264f5a7fe0e/tests/test-dirs/no-escape.t/test_use.ml
|
ocaml
|
open Foo
|
|
a72bdf66ea633b8db81b5e8efec40a2f94e43b80fa4c7ab73504763d7469492d
|
ocaml-flambda/ocaml-jst
|
ocamlcmt.ml
|
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Fabrice Le Fessant, INRIA Saclay *)
(* *)
Copyright 2012 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
let gen_annot = ref false
let gen_ml = ref false
let print_info_arg = ref false
let target_filename = ref None
let save_cmt_info = ref false
let arg_list = Arg.align [
"-o", Arg.String (fun s -> target_filename := Some s),
"<file> Dump to file <file> (or stdout if -)";
"-annot", Arg.Set gen_annot,
" Generate the corresponding .annot file";
"-save-cmt-info", Arg.Set save_cmt_info,
" Encapsulate additional cmt information in annotations";
"-src", Arg.Set gen_ml,
" Convert .cmt or .cmti back to source code (without comments)";
"-info", Arg.Set print_info_arg, " : print information on the file";
"-args", Arg.Expand Arg.read_arg,
"<file> Read additional newline separated command line arguments \n\
\ from <file>";
"-args0", Arg.Expand Arg.read_arg0,
"<file> Read additional NUL separated command line arguments from \n\
\ <file>";
"-I", Arg.String (fun s ->
Clflags.include_dirs := s :: !Clflags.include_dirs),
"<dir> Add <dir> to the list of include directories";
]
let arg_usage =
"ocamlcmt [OPTIONS] FILE.cmt : read FILE.cmt and print related information"
let dummy_crc = String.make 32 '-'
let print_info cmt =
let oc = match !target_filename with
| None -> stdout
| Some filename -> open_out filename
in
let open Cmt_format in
Printf.fprintf oc "module name: %a\n" Compilation_unit.output cmt.cmt_modname;
begin match cmt.cmt_annots with
Packed (_, list) ->
Printf.fprintf oc "pack: %s\n" (String.concat " " list)
| Implementation _ -> Printf.fprintf oc "kind: implementation\n"
| Interface _ -> Printf.fprintf oc "kind: interface\n"
| Partial_implementation _ ->
Printf.fprintf oc "kind: implementation with errors\n"
| Partial_interface _ -> Printf.fprintf oc "kind: interface with errors\n"
end;
Printf.fprintf oc "command: %s\n"
(String.concat " " (Array.to_list cmt.cmt_args));
begin match cmt.cmt_sourcefile with
None -> ()
| Some name ->
Printf.fprintf oc "sourcefile: %s\n" name;
end;
Printf.fprintf oc "build directory: %s\n" cmt.cmt_builddir;
List.iter (Printf.fprintf oc "load path: %s\n%!") cmt.cmt_loadpath;
begin
match cmt.cmt_source_digest with
None -> ()
| Some digest ->
Printf.fprintf oc "source digest: %s\n" (Digest.to_hex digest);
end;
begin
match cmt.cmt_interface_digest with
None -> ()
| Some digest ->
Printf.fprintf oc "interface digest: %s\n" (Digest.to_hex digest);
end;
let compare_imports (name1, _crco1) (name2, _crco2) =
Compilation_unit.Name.compare name1 name2
in
let imports =
let imports =
Array.map (fun import ->
Import_info.name import, Import_info.crc_with_unit import)
cmt.cmt_imports
in
Array.sort compare_imports imports;
Array.to_list imports
in
List.iter (fun (name, crco) ->
let crc =
match crco with
None -> dummy_crc
| Some (_unit, crc) -> Digest.to_hex crc
in
Printf.fprintf oc "import: %a %s\n" Compilation_unit.Name.output name crc;
) imports;
Printf.fprintf oc "%!";
begin match !target_filename with
| None -> ()
| Some _ -> close_out oc
end;
()
let generate_ml target_filename filename cmt =
let (printer, ext) =
match cmt.Cmt_format.cmt_annots with
| Cmt_format.Implementation typedtree ->
(fun ppf -> Pprintast.structure ppf
(Untypeast.untype_structure typedtree)),
".ml"
| Cmt_format.Interface typedtree ->
(fun ppf -> Pprintast.signature ppf
(Untypeast.untype_signature typedtree)),
".mli"
| _ ->
Printf.fprintf stderr "File was generated with an error\n%!";
exit 2
in
let target_filename = match target_filename with
None -> Some (filename ^ ext)
| Some "-" -> None
| Some _ -> target_filename
in
let oc = match target_filename with
None -> None
| Some filename -> Some (open_out filename) in
let ppf = match oc with
None -> Format.std_formatter
| Some oc -> Format.formatter_of_out_channel oc in
printer ppf;
Format.pp_print_flush ppf ();
match oc with
None -> flush stdout
| Some oc -> close_out oc
(* Save cmt information as faked annotations, attached to
Location.none, on top of the .annot file. Only when -save-cmt-info is
provided to ocaml_cmt.
*)
let record_cmt_info cmt =
let location_none = {
Location.none with Location.loc_ghost = false }
in
let location_file file = {
Location.none with
Location.loc_start = {
Location.none.Location.loc_start with
Lexing.pos_fname = file }}
in
let record_info name value =
let ident = Printf.sprintf ".%s" name in
Stypes.record (Stypes.An_ident (location_none, ident,
Annot.Idef (location_file value)))
in
let open Cmt_format in
List.iter (fun dir -> record_info "include" dir) cmt.cmt_loadpath;
record_info "chdir" cmt.cmt_builddir;
(match cmt.cmt_sourcefile with
None -> () | Some file -> record_info "source" file)
let main () =
Clflags.annotations := true;
Arg.parse_expand arg_list (fun filename ->
if
Filename.check_suffix filename ".cmt" ||
Filename.check_suffix filename ".cmti"
then begin
let open Cmt_format in
Compmisc.init_path ();
let cmt = read_cmt filename in
if !gen_annot then begin
if !save_cmt_info then record_cmt_info cmt;
let target_filename =
match !target_filename with
| None -> Some (filename ^ ".annot")
| Some "-" -> None
| Some _ as x -> x
in
Envaux.reset_cache ~preserve_persistent_env:false;
List.iter Load_path.add_dir cmt.cmt_loadpath;
Cmt2annot.gen_annot target_filename
~sourcefile:cmt.cmt_sourcefile
~use_summaries:cmt.cmt_use_summaries
cmt.cmt_annots
end;
if !gen_ml then generate_ml !target_filename filename cmt;
if !print_info_arg || not (!gen_ml || !gen_annot) then print_info cmt;
end else begin
Printf.fprintf stderr
"Error: the file's extension must be .cmt or .cmti.\n%!";
Arg.usage arg_list arg_usage
end
) arg_usage
let () =
try
main ()
with x ->
Printf.eprintf "Exception in main ()\n%!";
Location.report_exception Format.err_formatter x;
Format.fprintf Format.err_formatter "@.";
exit 2
| null |
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/7e5a626e4b4e12f1e9106564e1baba4d0ef6309a/tools/ocamlcmt.ml
|
ocaml
|
************************************************************************
OCaml
Fabrice Le Fessant, INRIA Saclay
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Save cmt information as faked annotations, attached to
Location.none, on top of the .annot file. Only when -save-cmt-info is
provided to ocaml_cmt.
|
Copyright 2012 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
let gen_annot = ref false
let gen_ml = ref false
let print_info_arg = ref false
let target_filename = ref None
let save_cmt_info = ref false
let arg_list = Arg.align [
"-o", Arg.String (fun s -> target_filename := Some s),
"<file> Dump to file <file> (or stdout if -)";
"-annot", Arg.Set gen_annot,
" Generate the corresponding .annot file";
"-save-cmt-info", Arg.Set save_cmt_info,
" Encapsulate additional cmt information in annotations";
"-src", Arg.Set gen_ml,
" Convert .cmt or .cmti back to source code (without comments)";
"-info", Arg.Set print_info_arg, " : print information on the file";
"-args", Arg.Expand Arg.read_arg,
"<file> Read additional newline separated command line arguments \n\
\ from <file>";
"-args0", Arg.Expand Arg.read_arg0,
"<file> Read additional NUL separated command line arguments from \n\
\ <file>";
"-I", Arg.String (fun s ->
Clflags.include_dirs := s :: !Clflags.include_dirs),
"<dir> Add <dir> to the list of include directories";
]
let arg_usage =
"ocamlcmt [OPTIONS] FILE.cmt : read FILE.cmt and print related information"
let dummy_crc = String.make 32 '-'
let print_info cmt =
let oc = match !target_filename with
| None -> stdout
| Some filename -> open_out filename
in
let open Cmt_format in
Printf.fprintf oc "module name: %a\n" Compilation_unit.output cmt.cmt_modname;
begin match cmt.cmt_annots with
Packed (_, list) ->
Printf.fprintf oc "pack: %s\n" (String.concat " " list)
| Implementation _ -> Printf.fprintf oc "kind: implementation\n"
| Interface _ -> Printf.fprintf oc "kind: interface\n"
| Partial_implementation _ ->
Printf.fprintf oc "kind: implementation with errors\n"
| Partial_interface _ -> Printf.fprintf oc "kind: interface with errors\n"
end;
Printf.fprintf oc "command: %s\n"
(String.concat " " (Array.to_list cmt.cmt_args));
begin match cmt.cmt_sourcefile with
None -> ()
| Some name ->
Printf.fprintf oc "sourcefile: %s\n" name;
end;
Printf.fprintf oc "build directory: %s\n" cmt.cmt_builddir;
List.iter (Printf.fprintf oc "load path: %s\n%!") cmt.cmt_loadpath;
begin
match cmt.cmt_source_digest with
None -> ()
| Some digest ->
Printf.fprintf oc "source digest: %s\n" (Digest.to_hex digest);
end;
begin
match cmt.cmt_interface_digest with
None -> ()
| Some digest ->
Printf.fprintf oc "interface digest: %s\n" (Digest.to_hex digest);
end;
let compare_imports (name1, _crco1) (name2, _crco2) =
Compilation_unit.Name.compare name1 name2
in
let imports =
let imports =
Array.map (fun import ->
Import_info.name import, Import_info.crc_with_unit import)
cmt.cmt_imports
in
Array.sort compare_imports imports;
Array.to_list imports
in
List.iter (fun (name, crco) ->
let crc =
match crco with
None -> dummy_crc
| Some (_unit, crc) -> Digest.to_hex crc
in
Printf.fprintf oc "import: %a %s\n" Compilation_unit.Name.output name crc;
) imports;
Printf.fprintf oc "%!";
begin match !target_filename with
| None -> ()
| Some _ -> close_out oc
end;
()
let generate_ml target_filename filename cmt =
let (printer, ext) =
match cmt.Cmt_format.cmt_annots with
| Cmt_format.Implementation typedtree ->
(fun ppf -> Pprintast.structure ppf
(Untypeast.untype_structure typedtree)),
".ml"
| Cmt_format.Interface typedtree ->
(fun ppf -> Pprintast.signature ppf
(Untypeast.untype_signature typedtree)),
".mli"
| _ ->
Printf.fprintf stderr "File was generated with an error\n%!";
exit 2
in
let target_filename = match target_filename with
None -> Some (filename ^ ext)
| Some "-" -> None
| Some _ -> target_filename
in
let oc = match target_filename with
None -> None
| Some filename -> Some (open_out filename) in
let ppf = match oc with
None -> Format.std_formatter
| Some oc -> Format.formatter_of_out_channel oc in
printer ppf;
Format.pp_print_flush ppf ();
match oc with
None -> flush stdout
| Some oc -> close_out oc
let record_cmt_info cmt =
let location_none = {
Location.none with Location.loc_ghost = false }
in
let location_file file = {
Location.none with
Location.loc_start = {
Location.none.Location.loc_start with
Lexing.pos_fname = file }}
in
let record_info name value =
let ident = Printf.sprintf ".%s" name in
Stypes.record (Stypes.An_ident (location_none, ident,
Annot.Idef (location_file value)))
in
let open Cmt_format in
List.iter (fun dir -> record_info "include" dir) cmt.cmt_loadpath;
record_info "chdir" cmt.cmt_builddir;
(match cmt.cmt_sourcefile with
None -> () | Some file -> record_info "source" file)
let main () =
Clflags.annotations := true;
Arg.parse_expand arg_list (fun filename ->
if
Filename.check_suffix filename ".cmt" ||
Filename.check_suffix filename ".cmti"
then begin
let open Cmt_format in
Compmisc.init_path ();
let cmt = read_cmt filename in
if !gen_annot then begin
if !save_cmt_info then record_cmt_info cmt;
let target_filename =
match !target_filename with
| None -> Some (filename ^ ".annot")
| Some "-" -> None
| Some _ as x -> x
in
Envaux.reset_cache ~preserve_persistent_env:false;
List.iter Load_path.add_dir cmt.cmt_loadpath;
Cmt2annot.gen_annot target_filename
~sourcefile:cmt.cmt_sourcefile
~use_summaries:cmt.cmt_use_summaries
cmt.cmt_annots
end;
if !gen_ml then generate_ml !target_filename filename cmt;
if !print_info_arg || not (!gen_ml || !gen_annot) then print_info cmt;
end else begin
Printf.fprintf stderr
"Error: the file's extension must be .cmt or .cmti.\n%!";
Arg.usage arg_list arg_usage
end
) arg_usage
let () =
try
main ()
with x ->
Printf.eprintf "Exception in main ()\n%!";
Location.report_exception Format.err_formatter x;
Format.fprintf Format.err_formatter "@.";
exit 2
|
f20c30d14a17fa828d7af388e00051f082e0134bfae43be2da8aabc34aa2ac54
|
relevance/labrepl
|
ref_cache_test.clj
|
(ns solutions.ref-cache-test
(:use clojure.test)
(:require [solutions.ref-cache :as cache]))
(deftest test-ref-version
(let [cache (cache/create {1 2})]
(is (nil? (cache/get cache :foo)))
(is (= {:foo :bar 1 2} (cache/put cache :foo :bar)))
(is (= {:foo :zap 1 2} (cache/put cache {:foo :zap} )))
(is (= {:foo :zap 1 3} (cache/fast-put cache {1 3})))))
| null |
https://raw.githubusercontent.com/relevance/labrepl/51909dcb3eeb9f148eeae109316f7d73cc81512a/test/solutions/ref_cache_test.clj
|
clojure
|
(ns solutions.ref-cache-test
(:use clojure.test)
(:require [solutions.ref-cache :as cache]))
(deftest test-ref-version
(let [cache (cache/create {1 2})]
(is (nil? (cache/get cache :foo)))
(is (= {:foo :bar 1 2} (cache/put cache :foo :bar)))
(is (= {:foo :zap 1 2} (cache/put cache {:foo :zap} )))
(is (= {:foo :zap 1 3} (cache/fast-put cache {1 3})))))
|
|
780034e7598ff9f66e23cabb34ae9ea99c9e3c22b41a0921aedf89732ea2bcb7
|
korya/efuns
|
demo_complex.ml
|
(***********************************************************************)
(* *)
(* ____ *)
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open WX_types
let display = new WX_display.t ""
let root = new WX_root.t display 0
let appli = new WX_appli.t root
[Bindings [Key (XK.xk_q,0), (fun () -> exit 0)]]
let attributes = [Relief ReliefRaised; Foreground "red"; Background "yellow"]
let vbar = new WX_bar.v appli#container []
let adj = new WX_adjust.t ()
let panel = new WX_panel.t Vertical vbar#container adj []
let scale = new WX_scale.h vbar#container adj [Background "black"]
let cursors = [
"xc_x_cursor",XC.xc_x_cursor;
"xc_arrow",XC.xc_arrow;
"xc_based_arrow_down",XC.xc_based_arrow_down;
"xc_based_arrow_up",XC.xc_based_arrow_up;
"xc_boat",XC.xc_boat;
"xc_bogosity",XC.xc_bogosity;
"xc_bottom_left_corner",XC.xc_bottom_left_corner;
"xc_bottom_right_corner",XC.xc_bottom_right_corner;
"xc_bottom_side",XC.xc_bottom_side;
"xc_bottom_tee",XC.xc_bottom_tee;
"xc_box_spiral",XC.xc_box_spiral;
"xc_center_ptr",XC.xc_center_ptr;
"xc_circle",XC.xc_circle;
"xc_clock",XC.xc_clock;
"xc_coffee_mug",XC.xc_coffee_mug;
"xc_cross",XC.xc_cross;
"xc_cross_reverse",XC.xc_cross_reverse;
"xc_crosshair",XC.xc_crosshair;
"xc_diamond_cross",XC.xc_diamond_cross;
"xc_dot",XC.xc_dot;
"xc_dotbox",XC.xc_dotbox;
"xc_double_arrow",XC.xc_double_arrow;
"xc_draft_large",XC.xc_draft_large;
"xc_draft_small",XC.xc_draft_small;
"xc_draped_box",XC.xc_draped_box;
"xc_exchange",XC.xc_exchange;
"xc_fleur",XC.xc_fleur;
"xc_gobbler",XC.xc_gobbler;
"xc_gumby",XC.xc_gumby;
"xc_hand1",XC.xc_hand1;
"xc_hand2",XC.xc_hand2;
"xc_heart",XC.xc_heart;
"xc_icon",XC.xc_icon;
"xc_iron_cross",XC.xc_iron_cross;
"xc_left_ptr",XC.xc_left_ptr;
"xc_left_side",XC.xc_left_side;
"xc_left_tee",XC.xc_left_tee;
"xc_leftbutton",XC.xc_leftbutton;
"xc_ll_angle",XC.xc_ll_angle;
"xc_lr_angle",XC.xc_lr_angle;
"xc_man",XC.xc_man;
"xc_middlebutton",XC.xc_middlebutton;
"xc_mouse",XC.xc_mouse;
"xc_pencil",XC.xc_pencil;
"xc_pirate",XC.xc_pirate;
"xc_plus",XC.xc_plus;
"xc_question_arrow",XC.xc_question_arrow;
"xc_right_ptr",XC.xc_right_ptr;
"xc_right_side",XC.xc_right_side;
"xc_right_tee",XC.xc_right_tee;
"xc_rightbutton",XC.xc_rightbutton;
"xc_rtl_logo",XC.xc_rtl_logo;
"xc_sailboat",XC.xc_sailboat;
"xc_sb_down_arrow",XC.xc_sb_down_arrow;
"xc_sb_h_double_arrow",XC.xc_sb_h_double_arrow;
"xc_sb_left_arrow",XC.xc_sb_left_arrow;
"xc_sb_right_arrow",XC.xc_sb_right_arrow;
"xc_sb_up_arrow",XC.xc_sb_up_arrow;
"xc_sb_v_double_arrow",XC.xc_sb_v_double_arrow;
"xc_shuttle",XC.xc_shuttle;
"xc_sizing",XC.xc_sizing;
"xc_spider",XC.xc_spider;
"xc_spraycan",XC.xc_spraycan;
"xc_star",XC.xc_star;
"xc_target",XC.xc_target;
"xc_tcross",XC.xc_tcross;
"xc_top_left_arrow",XC.xc_top_left_arrow;
"xc_top_left_corner",XC.xc_top_left_corner;
"xc_top_right_corner",XC.xc_top_right_corner;
"xc_top_side",XC.xc_top_side;
"xc_top_tee",XC.xc_top_tee;
"xc_trek",XC.xc_trek;
"xc_ul_angle",XC.xc_ul_angle;
"xc_umbrella",XC.xc_umbrella;
"xc_ur_angle",XC.xc_ur_angle;
"xc_watch",XC.xc_watch;
"xc_xterm",XC.xc_xterm]
let cursors_make top =
let hbar = new WX_bar.h top#container [MaxHeight 400] in
let adx = new WX_adjust.t () in
let ady = new WX_adjust.t () in
let viewport = new WX_viewport.t hbar#container adx ady [] in
let scrollbar = new WX_scrollbar.v hbar#container ady [] in
let vbar = new WX_bar.v viewport#container [] in
hbar#container_add_s [viewport#contained; scrollbar#contained];
viewport#container_add vbar#contained;
List.iter (fun (name,curs) ->
let label = new WX_label.t vbar#container name
[Cursor (FontCursor curs);Relief ReliefRaised; ExpandX true] in
label#configure [Bindings
[EnterWindow, (fun () -> label#inverse);
LeaveWindow, (fun () -> label#normal)]];
vbar#container_add label#contained
) cursors;
top#configure [Bindings [
Key(XK.xk_Prior,0),(fun _ -> ady#page_up);
Key(XK.xk_Next,0),(fun _ -> ady#page_down);
Key(XK.xk_q,0),(fun _ -> exit 0);
]];
viewport#configure [MinHeight 500; MinWidth 100];
hbar
let viewtext parent constructor =
let hbar = new WX_bar.h parent#container [] in
let adx = new WX_adjust.t () in
let ady = new WX_adjust.t () in
let viewport = new WX_viewport.t hbar#container adx ady
[MinHeight 50; MinWidth 50;ExpandX true] in
let vscroll = new WX_scrollbar.v hbar#container ady [] in
let text = constructor viewport in
hbar#container_add_s [viewport#contained; vscroll#contained];
viewport#container_add (text#contained);
hbar#contained
let menu_desc = [|
"File", (fun _ -> Printf.printf "FILE ITEM"; print_newline ());
"Save", (fun _ -> Printf.printf "SAVE ITEM"; print_newline ());
"Print", (fun _ -> Printf.printf "PRINT ITEM"; print_newline ());
"Quit", (fun _ -> Printf.printf "QUIT ITEM"; print_newline ());
"Delete", (fun _ -> Printf.printf "DELETE ITEM"; print_newline ());
"New", (fun _ -> Printf.printf "NeW ITEM"; print_newline ());
|]
let menu = new WX_popup.t root menu_desc
let text1 = viewtext panel (fun parent ->
let hbar = new WX_bar.h parent#container [] in
let text = new WX_text.with_widgets hbar#container
[||] attributes in
let pixmap = new WX_pixmap.t text#container
("xv",FromFile "/usr/share/icons/xv.xpm") [Relief ReliefRidge]
in
let button = new WX_button.t text#container [] in
let compteur = new WX_label.t text#container "" [] in
let pixmap = new WX_pixmap.t button#container
("xv",FromFile "/usr/share/icons/xv.xpm") [Relief ReliefRidge]
in
let selector = new WX_selector.t text#container root
{ WX_selector.labels = [| "France";"Angleterre";"Allemagne" |];
WX_selector.valides = [||];
WX_selector.current = 0;
WX_selector.change_hook = []; } []
in
let ledit = new WX_ledit.t text#container "Modifier ici" [] in
let simple_text = [|
[| WX_text.RealString ([], "Bonjour") |];
[| WX_text.RealString ([], "Je suis un peu compliqué, non ?") |];
[| WX_text.RealString ([], "") |];
[| WX_text.RealString ([], "Pourtant, il suffit d'un peu") |];
[| WX_text.RealString ([], "d'habitude pour arriver à") |];
[| WX_text.RealString ([], "m'utiliser correctement") |];
[| WX_text.RealString ([], "") |];
[| WX_text.RealString ([],"Une pixmap:");WX_text.Widget [|button#contained|] |];
[| WX_text.RealString ([], "Ici, en plus, je n'utilise pas") |];
[| WX_text.RealString ([], "toutes mes capacités.") |];
[| WX_text.RealString ([], "Un selecteur:"); WX_text.Widget [|selector#contained|]|];
[| WX_text.RealString ([], "Un label editable:"); WX_text.Widget [|ledit#contained|]|];
[| WX_text.RealString ([], "Un compteur:"); WX_text.Widget [|compteur#contained|]|];
|]
in
button#set_action (fun _ ->
let (x,y) = button#root_coordinates in
menu#popup x y (Some !button_event)
);
button#container_add pixmap#contained;
button#set_wait_release false;
text#set_widgets simple_text;
let cur = cursors_make hbar in
let vbar = new WX_bar.v hbar#container [] in
let adj = new WX_adjust.t () in
adj#add_subject (fun _ ->
let v = adj#get_pos WX_adjust.v_total in
let s = string_of_int v in
compteur#set_string s
);
Array.iteri (fun i s ->
let button = new WX_radiobutton.t vbar#container adj i [ExpandX true] in
let label = new WX_label.t button#container s [ExpandX true] in
button#container_add label#contained;
vbar#container_add button#contained;
button#select
) [| "First"; "Second"; "Third";"Forth";"Fifth";"Sixth" |];
hbar#container_add_s [text#contained; cur#contained; vbar#contained];
hbar
)
let text2 = viewtext panel (fun parent ->
new WX_text.of_file parent#container
"demo_complex.ml" attributes)
let file_menu = [|
"New", (fun _ -> Printf.printf "NEW FILE"; print_newline ());
"Open", (fun _ -> Printf.printf "OPEN FILE"; print_newline ());
"Save", (fun _ -> Printf.printf "SAVE FILE"; print_newline ());
"Kill", (fun _ ->
let dialog = new WX_dialog.t root
"If you kill the buffer,
last changes will not be saved on disk.
Are you sure you want this ?"
[] in
dialog#add_button "OK" (fun _ ->
Printf.printf "KILL OK"; print_newline ();
dialog#destroy);
dialog#add_button "CANCEL" (fun _ ->
Printf.printf "KILL CANCELLED"; print_newline ();
dialog#destroy);
dialog#add_button "HELP" (fun _ ->
Printf.printf "HELP ON KILL"; print_newline (););
dialog#show;
);
"Print", (fun _ -> Printf.printf "PRINT FILE"; print_newline ());
"Quit", (fun _ -> exit 0);
|]
let edit_menu = [|
"Undo", (fun _ -> Printf.printf "UNDO EDIT"; print_newline ());
"Cut", (fun _ -> Printf.printf "CUT EDIT"; print_newline ());
"Copy", (fun _ -> Printf.printf "COPY EDIT"; print_newline ());
"Paste", (fun _ -> Printf.printf "PASTE EDIT"; print_newline ());
|]
let help_menu = [|
"About", (fun _ ->
let dialog = new WX_dialog.t root
"Some help on this demo:
The top frame is a WX_appli.t object,
which automatically creates the top bar of menus, and the
vertical bar below. This bar contains two widgets:
- a WX_panel.t, which is divided in two parts
- a WX_scale.t (in black) which controls the sizes of the
two parts of the panel (use it like a scrollbar).
In the panel, the bottom side contains a text, loaded
from a file with WX_text.file, and its scrollbar, of
class wX_scrollbar.v. Above an horizontal bar contains
a text with active widgets (a WX_pixmap.t in a WX_button.t)
and a WX_selector.t, and a vertical bar displaying all
sorts of X predefined cursors (you can use its scrollbar,
or use Prior and Next keys). To be enable displaying only
parts of some windows (in combinaison with a scrollbar for
example), the widgets are included in WX_viewport.t.
Finally, the File/Kill menu displays a simple WX_dialog.t
box with three choices.
" [] in
dialog#add_button "OK" (fun _ -> dialog#destroy);
dialog#show;
Printf.printf "ABOUT HELP"; print_newline ());
"Index", (fun _ ->
let dialog = new WX_dialog.t root
"Sorry,\nNo help available on this topic" [] in
dialog#add_button "OK" (fun _ -> dialog#destroy);
dialog#show;
Printf.printf "INDEX HELP"; print_newline ());
|]
let sep = new WX_panel.separator panel adj []
let _ =
panel#set_first text1;
panel#set_second text2;
adj#set_pos 1 2;
panel#set_step 5;
vbar#container_add_s [panel#contained; scale#contained];
appli#container_add (vbar#contained);
appli#add_menu "File" file_menu;
appli#add_menu "Edit" edit_menu;
appli#add_separator;
appli#add_menu "Help" help_menu;
appli#show;
loop ()
| null |
https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/toolkit/examples/demo_complex.ml
|
ocaml
|
*********************************************************************
____
*********************************************************************
|
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open WX_types
let display = new WX_display.t ""
let root = new WX_root.t display 0
let appli = new WX_appli.t root
[Bindings [Key (XK.xk_q,0), (fun () -> exit 0)]]
let attributes = [Relief ReliefRaised; Foreground "red"; Background "yellow"]
let vbar = new WX_bar.v appli#container []
let adj = new WX_adjust.t ()
let panel = new WX_panel.t Vertical vbar#container adj []
let scale = new WX_scale.h vbar#container adj [Background "black"]
let cursors = [
"xc_x_cursor",XC.xc_x_cursor;
"xc_arrow",XC.xc_arrow;
"xc_based_arrow_down",XC.xc_based_arrow_down;
"xc_based_arrow_up",XC.xc_based_arrow_up;
"xc_boat",XC.xc_boat;
"xc_bogosity",XC.xc_bogosity;
"xc_bottom_left_corner",XC.xc_bottom_left_corner;
"xc_bottom_right_corner",XC.xc_bottom_right_corner;
"xc_bottom_side",XC.xc_bottom_side;
"xc_bottom_tee",XC.xc_bottom_tee;
"xc_box_spiral",XC.xc_box_spiral;
"xc_center_ptr",XC.xc_center_ptr;
"xc_circle",XC.xc_circle;
"xc_clock",XC.xc_clock;
"xc_coffee_mug",XC.xc_coffee_mug;
"xc_cross",XC.xc_cross;
"xc_cross_reverse",XC.xc_cross_reverse;
"xc_crosshair",XC.xc_crosshair;
"xc_diamond_cross",XC.xc_diamond_cross;
"xc_dot",XC.xc_dot;
"xc_dotbox",XC.xc_dotbox;
"xc_double_arrow",XC.xc_double_arrow;
"xc_draft_large",XC.xc_draft_large;
"xc_draft_small",XC.xc_draft_small;
"xc_draped_box",XC.xc_draped_box;
"xc_exchange",XC.xc_exchange;
"xc_fleur",XC.xc_fleur;
"xc_gobbler",XC.xc_gobbler;
"xc_gumby",XC.xc_gumby;
"xc_hand1",XC.xc_hand1;
"xc_hand2",XC.xc_hand2;
"xc_heart",XC.xc_heart;
"xc_icon",XC.xc_icon;
"xc_iron_cross",XC.xc_iron_cross;
"xc_left_ptr",XC.xc_left_ptr;
"xc_left_side",XC.xc_left_side;
"xc_left_tee",XC.xc_left_tee;
"xc_leftbutton",XC.xc_leftbutton;
"xc_ll_angle",XC.xc_ll_angle;
"xc_lr_angle",XC.xc_lr_angle;
"xc_man",XC.xc_man;
"xc_middlebutton",XC.xc_middlebutton;
"xc_mouse",XC.xc_mouse;
"xc_pencil",XC.xc_pencil;
"xc_pirate",XC.xc_pirate;
"xc_plus",XC.xc_plus;
"xc_question_arrow",XC.xc_question_arrow;
"xc_right_ptr",XC.xc_right_ptr;
"xc_right_side",XC.xc_right_side;
"xc_right_tee",XC.xc_right_tee;
"xc_rightbutton",XC.xc_rightbutton;
"xc_rtl_logo",XC.xc_rtl_logo;
"xc_sailboat",XC.xc_sailboat;
"xc_sb_down_arrow",XC.xc_sb_down_arrow;
"xc_sb_h_double_arrow",XC.xc_sb_h_double_arrow;
"xc_sb_left_arrow",XC.xc_sb_left_arrow;
"xc_sb_right_arrow",XC.xc_sb_right_arrow;
"xc_sb_up_arrow",XC.xc_sb_up_arrow;
"xc_sb_v_double_arrow",XC.xc_sb_v_double_arrow;
"xc_shuttle",XC.xc_shuttle;
"xc_sizing",XC.xc_sizing;
"xc_spider",XC.xc_spider;
"xc_spraycan",XC.xc_spraycan;
"xc_star",XC.xc_star;
"xc_target",XC.xc_target;
"xc_tcross",XC.xc_tcross;
"xc_top_left_arrow",XC.xc_top_left_arrow;
"xc_top_left_corner",XC.xc_top_left_corner;
"xc_top_right_corner",XC.xc_top_right_corner;
"xc_top_side",XC.xc_top_side;
"xc_top_tee",XC.xc_top_tee;
"xc_trek",XC.xc_trek;
"xc_ul_angle",XC.xc_ul_angle;
"xc_umbrella",XC.xc_umbrella;
"xc_ur_angle",XC.xc_ur_angle;
"xc_watch",XC.xc_watch;
"xc_xterm",XC.xc_xterm]
let cursors_make top =
let hbar = new WX_bar.h top#container [MaxHeight 400] in
let adx = new WX_adjust.t () in
let ady = new WX_adjust.t () in
let viewport = new WX_viewport.t hbar#container adx ady [] in
let scrollbar = new WX_scrollbar.v hbar#container ady [] in
let vbar = new WX_bar.v viewport#container [] in
hbar#container_add_s [viewport#contained; scrollbar#contained];
viewport#container_add vbar#contained;
List.iter (fun (name,curs) ->
let label = new WX_label.t vbar#container name
[Cursor (FontCursor curs);Relief ReliefRaised; ExpandX true] in
label#configure [Bindings
[EnterWindow, (fun () -> label#inverse);
LeaveWindow, (fun () -> label#normal)]];
vbar#container_add label#contained
) cursors;
top#configure [Bindings [
Key(XK.xk_Prior,0),(fun _ -> ady#page_up);
Key(XK.xk_Next,0),(fun _ -> ady#page_down);
Key(XK.xk_q,0),(fun _ -> exit 0);
]];
viewport#configure [MinHeight 500; MinWidth 100];
hbar
let viewtext parent constructor =
let hbar = new WX_bar.h parent#container [] in
let adx = new WX_adjust.t () in
let ady = new WX_adjust.t () in
let viewport = new WX_viewport.t hbar#container adx ady
[MinHeight 50; MinWidth 50;ExpandX true] in
let vscroll = new WX_scrollbar.v hbar#container ady [] in
let text = constructor viewport in
hbar#container_add_s [viewport#contained; vscroll#contained];
viewport#container_add (text#contained);
hbar#contained
let menu_desc = [|
"File", (fun _ -> Printf.printf "FILE ITEM"; print_newline ());
"Save", (fun _ -> Printf.printf "SAVE ITEM"; print_newline ());
"Print", (fun _ -> Printf.printf "PRINT ITEM"; print_newline ());
"Quit", (fun _ -> Printf.printf "QUIT ITEM"; print_newline ());
"Delete", (fun _ -> Printf.printf "DELETE ITEM"; print_newline ());
"New", (fun _ -> Printf.printf "NeW ITEM"; print_newline ());
|]
let menu = new WX_popup.t root menu_desc
let text1 = viewtext panel (fun parent ->
let hbar = new WX_bar.h parent#container [] in
let text = new WX_text.with_widgets hbar#container
[||] attributes in
let pixmap = new WX_pixmap.t text#container
("xv",FromFile "/usr/share/icons/xv.xpm") [Relief ReliefRidge]
in
let button = new WX_button.t text#container [] in
let compteur = new WX_label.t text#container "" [] in
let pixmap = new WX_pixmap.t button#container
("xv",FromFile "/usr/share/icons/xv.xpm") [Relief ReliefRidge]
in
let selector = new WX_selector.t text#container root
{ WX_selector.labels = [| "France";"Angleterre";"Allemagne" |];
WX_selector.valides = [||];
WX_selector.current = 0;
WX_selector.change_hook = []; } []
in
let ledit = new WX_ledit.t text#container "Modifier ici" [] in
let simple_text = [|
[| WX_text.RealString ([], "Bonjour") |];
[| WX_text.RealString ([], "Je suis un peu compliqué, non ?") |];
[| WX_text.RealString ([], "") |];
[| WX_text.RealString ([], "Pourtant, il suffit d'un peu") |];
[| WX_text.RealString ([], "d'habitude pour arriver à") |];
[| WX_text.RealString ([], "m'utiliser correctement") |];
[| WX_text.RealString ([], "") |];
[| WX_text.RealString ([],"Une pixmap:");WX_text.Widget [|button#contained|] |];
[| WX_text.RealString ([], "Ici, en plus, je n'utilise pas") |];
[| WX_text.RealString ([], "toutes mes capacités.") |];
[| WX_text.RealString ([], "Un selecteur:"); WX_text.Widget [|selector#contained|]|];
[| WX_text.RealString ([], "Un label editable:"); WX_text.Widget [|ledit#contained|]|];
[| WX_text.RealString ([], "Un compteur:"); WX_text.Widget [|compteur#contained|]|];
|]
in
button#set_action (fun _ ->
let (x,y) = button#root_coordinates in
menu#popup x y (Some !button_event)
);
button#container_add pixmap#contained;
button#set_wait_release false;
text#set_widgets simple_text;
let cur = cursors_make hbar in
let vbar = new WX_bar.v hbar#container [] in
let adj = new WX_adjust.t () in
adj#add_subject (fun _ ->
let v = adj#get_pos WX_adjust.v_total in
let s = string_of_int v in
compteur#set_string s
);
Array.iteri (fun i s ->
let button = new WX_radiobutton.t vbar#container adj i [ExpandX true] in
let label = new WX_label.t button#container s [ExpandX true] in
button#container_add label#contained;
vbar#container_add button#contained;
button#select
) [| "First"; "Second"; "Third";"Forth";"Fifth";"Sixth" |];
hbar#container_add_s [text#contained; cur#contained; vbar#contained];
hbar
)
let text2 = viewtext panel (fun parent ->
new WX_text.of_file parent#container
"demo_complex.ml" attributes)
let file_menu = [|
"New", (fun _ -> Printf.printf "NEW FILE"; print_newline ());
"Open", (fun _ -> Printf.printf "OPEN FILE"; print_newline ());
"Save", (fun _ -> Printf.printf "SAVE FILE"; print_newline ());
"Kill", (fun _ ->
let dialog = new WX_dialog.t root
"If you kill the buffer,
last changes will not be saved on disk.
Are you sure you want this ?"
[] in
dialog#add_button "OK" (fun _ ->
Printf.printf "KILL OK"; print_newline ();
dialog#destroy);
dialog#add_button "CANCEL" (fun _ ->
Printf.printf "KILL CANCELLED"; print_newline ();
dialog#destroy);
dialog#add_button "HELP" (fun _ ->
Printf.printf "HELP ON KILL"; print_newline (););
dialog#show;
);
"Print", (fun _ -> Printf.printf "PRINT FILE"; print_newline ());
"Quit", (fun _ -> exit 0);
|]
let edit_menu = [|
"Undo", (fun _ -> Printf.printf "UNDO EDIT"; print_newline ());
"Cut", (fun _ -> Printf.printf "CUT EDIT"; print_newline ());
"Copy", (fun _ -> Printf.printf "COPY EDIT"; print_newline ());
"Paste", (fun _ -> Printf.printf "PASTE EDIT"; print_newline ());
|]
let help_menu = [|
"About", (fun _ ->
let dialog = new WX_dialog.t root
"Some help on this demo:
The top frame is a WX_appli.t object,
which automatically creates the top bar of menus, and the
vertical bar below. This bar contains two widgets:
- a WX_panel.t, which is divided in two parts
- a WX_scale.t (in black) which controls the sizes of the
two parts of the panel (use it like a scrollbar).
In the panel, the bottom side contains a text, loaded
from a file with WX_text.file, and its scrollbar, of
class wX_scrollbar.v. Above an horizontal bar contains
a text with active widgets (a WX_pixmap.t in a WX_button.t)
and a WX_selector.t, and a vertical bar displaying all
sorts of X predefined cursors (you can use its scrollbar,
or use Prior and Next keys). To be enable displaying only
parts of some windows (in combinaison with a scrollbar for
example), the widgets are included in WX_viewport.t.
Finally, the File/Kill menu displays a simple WX_dialog.t
box with three choices.
" [] in
dialog#add_button "OK" (fun _ -> dialog#destroy);
dialog#show;
Printf.printf "ABOUT HELP"; print_newline ());
"Index", (fun _ ->
let dialog = new WX_dialog.t root
"Sorry,\nNo help available on this topic" [] in
dialog#add_button "OK" (fun _ -> dialog#destroy);
dialog#show;
Printf.printf "INDEX HELP"; print_newline ());
|]
let sep = new WX_panel.separator panel adj []
let _ =
panel#set_first text1;
panel#set_second text2;
adj#set_pos 1 2;
panel#set_step 5;
vbar#container_add_s [panel#contained; scale#contained];
appli#container_add (vbar#contained);
appli#add_menu "File" file_menu;
appli#add_menu "Edit" edit_menu;
appli#add_separator;
appli#add_menu "Help" help_menu;
appli#show;
loop ()
|
b9f1a9a31b213a962a5a2b587427dfb7d11d6613c76789252d26644fb379b4d8
|
lem-project/lem
|
visual.lisp
|
(defpackage :lem-vi-mode.visual
(:use :cl
:lem
:lem-vi-mode.core)
(:export :vi-visual-end
:vi-visual-char
:vi-visual-line
:vi-visual-block
:visual-p
:visual-char-p
:visual-line-p
:visual-block-p
:apply-visual-range
:vi-visual-insert
:vi-visual-append
:vi-visual-upcase
:vi-visual-downcase))
(in-package :lem-vi-mode.visual)
(defvar *set-visual-function* nil)
(defvar *start-point* nil)
(defvar *visual-overlays* '())
(defvar *visual-keymap* (make-keymap :name '*visual-keymap* :parent *command-keymap*))
(define-key *visual-keymap* "Escape" 'vi-visual-end)
(define-key *visual-keymap* "A" 'vi-visual-append)
(define-key *visual-keymap* "I" 'vi-visual-insert)
(define-key *visual-keymap* "U" 'vi-visual-upcase)
(define-key *visual-keymap* "u" 'vi-visual-downcase)
(define-vi-state visual (:keymap *visual-keymap*
:post-command-hook 'post-command-hook)
(:disable ()
(delete-point *start-point*)
(clear-visual-overlays))
(:enable (function)
(setf *set-visual-function* function)
(setf *start-point* (copy-point (current-point)))))
(defun disable ()
(clear-visual-overlays))
(defun clear-visual-overlays ()
(mapc 'delete-overlay *visual-overlays*)
(setf *visual-overlays* '()))
(defun post-command-hook ()
(clear-visual-overlays)
(if (not (eq (current-buffer) (point-buffer *start-point*)))
(vi-visual-end)
(funcall *set-visual-function*)))
(defun visual-char ()
(with-point ((start *start-point*)
(end (current-point)))
(when (point< end start)
(rotatef start end))
(character-offset end 1)
(push (make-overlay start end 'region)
*visual-overlays*)))
(defun visual-line ()
(with-point ((start *start-point*)
(end (current-point)))
(when (point< end start) (rotatef start end))
(line-start start)
(line-end end)
(push (make-overlay start end 'region)
*visual-overlays*)))
(defun visual-block ()
(with-point ((start *start-point*)
(end (current-point)))
(when (point< end start)
(rotatef start end))
(character-offset end 1)
(let ((start-column (point-column start))
(end-column (point-column end)))
(unless (< start-column end-column)
(rotatef start-column end-column))
(apply-region-lines start end
(lambda (p)
(with-point ((s p) (e p))
(move-to-column s start-column)
(move-to-column e end-column)
(push (make-overlay s e 'region) *visual-overlays*)))))))
(define-command vi-visual-end () ()
(clear-visual-overlays)
(change-state 'command))
(define-command vi-visual-char () ()
(if (visual-char-p)
(vi-visual-end)
(progn
(change-state 'visual 'visual-char)
(message "-- VISUAL --"))))
(define-command vi-visual-line () ()
(if (visual-line-p)
(vi-visual-end)
(progn
(change-state 'visual 'visual-line)
(message "-- VISUAL LINE --"))))
(define-command vi-visual-block () ()
(if (visual-block-p)
(vi-visual-end)
(progn
(change-state 'visual 'visual-block)
(message "-- VISUAL BLOCK --"))))
(defun visual-p ()
(eq 'visual (current-state)))
(defun visual-char-p ()
(and (visual-p)
(eq *set-visual-function* 'visual-char)))
(defun visual-line-p ()
(and (visual-p)
(eq *set-visual-function* 'visual-line)))
(defun visual-block-p ()
(and (visual-p)
(eq *set-visual-function* 'visual-block)))
(defun apply-visual-range (function)
(dolist (ov (sort (copy-list *visual-overlays*) #'point< :key #'overlay-start))
(funcall function
(overlay-start ov)
(overlay-end ov))))
(defun string-without-escape ()
(concatenate 'string
(loop for key-char = (key-to-char (read-key))
while (char/= #\Escape key-char)
collect key-char)))
(define-command vi-visual-append () ()
(when (visual-block-p)
(let ((str (string-without-escape))
(max-end (apply #'max (mapcar (lambda (ov)
(point-charpos (overlay-end ov)))
*visual-overlays*))))
(apply-visual-range (lambda (start end)
(unless (point< start end)
(rotatef start end))
(let* ((space-len (- max-end (point-charpos end)))
(spaces (make-string space-len
:initial-element #\Space)))
(insert-string end (concatenate 'string
spaces
str))))))
(vi-visual-end)))
(define-command vi-visual-insert () ()
(when (visual-block-p)
(let ((str (string-without-escape)))
(apply-visual-range (lambda (start end)
(unless (point< start end)
(rotatef start end))
(insert-string start str))))
(vi-visual-end)))
(defun %visual-case (f)
(with-point ((start *start-point*)
(end (current-point)))
(apply-visual-range f)
(vi-visual-end)
(move-point (current-point) (if (point< start end)
start
end))))
(define-command vi-visual-upcase () ()
(%visual-case #'uppercase-region))
(define-command vi-visual-downcase () ()
(%visual-case #'downcase-region))
| null |
https://raw.githubusercontent.com/lem-project/lem/4f620f94a1fd3bdfb8b2364185e7db16efab57a1/modes/vi-mode/visual.lisp
|
lisp
|
(defpackage :lem-vi-mode.visual
(:use :cl
:lem
:lem-vi-mode.core)
(:export :vi-visual-end
:vi-visual-char
:vi-visual-line
:vi-visual-block
:visual-p
:visual-char-p
:visual-line-p
:visual-block-p
:apply-visual-range
:vi-visual-insert
:vi-visual-append
:vi-visual-upcase
:vi-visual-downcase))
(in-package :lem-vi-mode.visual)
(defvar *set-visual-function* nil)
(defvar *start-point* nil)
(defvar *visual-overlays* '())
(defvar *visual-keymap* (make-keymap :name '*visual-keymap* :parent *command-keymap*))
(define-key *visual-keymap* "Escape" 'vi-visual-end)
(define-key *visual-keymap* "A" 'vi-visual-append)
(define-key *visual-keymap* "I" 'vi-visual-insert)
(define-key *visual-keymap* "U" 'vi-visual-upcase)
(define-key *visual-keymap* "u" 'vi-visual-downcase)
(define-vi-state visual (:keymap *visual-keymap*
:post-command-hook 'post-command-hook)
(:disable ()
(delete-point *start-point*)
(clear-visual-overlays))
(:enable (function)
(setf *set-visual-function* function)
(setf *start-point* (copy-point (current-point)))))
(defun disable ()
(clear-visual-overlays))
(defun clear-visual-overlays ()
(mapc 'delete-overlay *visual-overlays*)
(setf *visual-overlays* '()))
(defun post-command-hook ()
(clear-visual-overlays)
(if (not (eq (current-buffer) (point-buffer *start-point*)))
(vi-visual-end)
(funcall *set-visual-function*)))
(defun visual-char ()
(with-point ((start *start-point*)
(end (current-point)))
(when (point< end start)
(rotatef start end))
(character-offset end 1)
(push (make-overlay start end 'region)
*visual-overlays*)))
(defun visual-line ()
(with-point ((start *start-point*)
(end (current-point)))
(when (point< end start) (rotatef start end))
(line-start start)
(line-end end)
(push (make-overlay start end 'region)
*visual-overlays*)))
(defun visual-block ()
(with-point ((start *start-point*)
(end (current-point)))
(when (point< end start)
(rotatef start end))
(character-offset end 1)
(let ((start-column (point-column start))
(end-column (point-column end)))
(unless (< start-column end-column)
(rotatef start-column end-column))
(apply-region-lines start end
(lambda (p)
(with-point ((s p) (e p))
(move-to-column s start-column)
(move-to-column e end-column)
(push (make-overlay s e 'region) *visual-overlays*)))))))
(define-command vi-visual-end () ()
(clear-visual-overlays)
(change-state 'command))
(define-command vi-visual-char () ()
(if (visual-char-p)
(vi-visual-end)
(progn
(change-state 'visual 'visual-char)
(message "-- VISUAL --"))))
(define-command vi-visual-line () ()
(if (visual-line-p)
(vi-visual-end)
(progn
(change-state 'visual 'visual-line)
(message "-- VISUAL LINE --"))))
(define-command vi-visual-block () ()
(if (visual-block-p)
(vi-visual-end)
(progn
(change-state 'visual 'visual-block)
(message "-- VISUAL BLOCK --"))))
(defun visual-p ()
(eq 'visual (current-state)))
(defun visual-char-p ()
(and (visual-p)
(eq *set-visual-function* 'visual-char)))
(defun visual-line-p ()
(and (visual-p)
(eq *set-visual-function* 'visual-line)))
(defun visual-block-p ()
(and (visual-p)
(eq *set-visual-function* 'visual-block)))
(defun apply-visual-range (function)
(dolist (ov (sort (copy-list *visual-overlays*) #'point< :key #'overlay-start))
(funcall function
(overlay-start ov)
(overlay-end ov))))
(defun string-without-escape ()
(concatenate 'string
(loop for key-char = (key-to-char (read-key))
while (char/= #\Escape key-char)
collect key-char)))
(define-command vi-visual-append () ()
(when (visual-block-p)
(let ((str (string-without-escape))
(max-end (apply #'max (mapcar (lambda (ov)
(point-charpos (overlay-end ov)))
*visual-overlays*))))
(apply-visual-range (lambda (start end)
(unless (point< start end)
(rotatef start end))
(let* ((space-len (- max-end (point-charpos end)))
(spaces (make-string space-len
:initial-element #\Space)))
(insert-string end (concatenate 'string
spaces
str))))))
(vi-visual-end)))
(define-command vi-visual-insert () ()
(when (visual-block-p)
(let ((str (string-without-escape)))
(apply-visual-range (lambda (start end)
(unless (point< start end)
(rotatef start end))
(insert-string start str))))
(vi-visual-end)))
(defun %visual-case (f)
(with-point ((start *start-point*)
(end (current-point)))
(apply-visual-range f)
(vi-visual-end)
(move-point (current-point) (if (point< start end)
start
end))))
(define-command vi-visual-upcase () ()
(%visual-case #'uppercase-region))
(define-command vi-visual-downcase () ()
(%visual-case #'downcase-region))
|
|
4e5ff7ee06601ec311b8be3bb2c3988f66d4848655aa2d66f53210ea52981f1d
|
headwinds/reagent-reframe-material-ui
|
protocols.cljc
|
(ns ajax.protocols)
(defprotocol AjaxImpl
"An abstraction for a javascript class that implements
Ajax calls."
(-js-ajax-request [this request handler]
"Makes an actual ajax request. All parameters except opts
are in JS format. Should return an AjaxRequest."))
(defprotocol AjaxRequest
"An abstraction for a running ajax request."
(-abort [this]
"Aborts a running ajax request, if possible."))
(defprotocol AjaxResponse
"An abstraction for an ajax response."
(-status [this]
"Returns the HTTP Status of the response as an integer.")
(-status-text [this]
"Returns the HTTP Status Text of the response as a string.")
(-get-all-headers [this]
"Returns all headers as a map.")
(-body [this]
"Returns the response body as a string or as type specified in response-format such as a blob or arraybuffer.")
(-get-response-header [this header]
"Gets the specified response header (specified by a string) as a string.")
(-was-aborted [this]
"Was the response aborted."))
(defprotocol Interceptor
"An abstraction for something that processes requests and responses."
(-process-request [this request]
"Transforms the opts")
(-process-response [this response]
"Transforms the raw response (an implementation of AjaxResponse)"))
(defrecord Response [status body status-text headers was-aborted]
AjaxResponse
(-body [this] (:body this))
(-status [this] (:status this))
(-status-text [this] (:status-text this))
(-get-all-headers [this] (:headers this))
(-get-response-header [this header] (get (:headers this) header))
(-was-aborted [this] (:was-aborted this)))
| null |
https://raw.githubusercontent.com/headwinds/reagent-reframe-material-ui/8a6fba82a026cfedca38491becac85751be9a9d4/resources/public/js/out/ajax/protocols.cljc
|
clojure
|
(ns ajax.protocols)
(defprotocol AjaxImpl
"An abstraction for a javascript class that implements
Ajax calls."
(-js-ajax-request [this request handler]
"Makes an actual ajax request. All parameters except opts
are in JS format. Should return an AjaxRequest."))
(defprotocol AjaxRequest
"An abstraction for a running ajax request."
(-abort [this]
"Aborts a running ajax request, if possible."))
(defprotocol AjaxResponse
"An abstraction for an ajax response."
(-status [this]
"Returns the HTTP Status of the response as an integer.")
(-status-text [this]
"Returns the HTTP Status Text of the response as a string.")
(-get-all-headers [this]
"Returns all headers as a map.")
(-body [this]
"Returns the response body as a string or as type specified in response-format such as a blob or arraybuffer.")
(-get-response-header [this header]
"Gets the specified response header (specified by a string) as a string.")
(-was-aborted [this]
"Was the response aborted."))
(defprotocol Interceptor
"An abstraction for something that processes requests and responses."
(-process-request [this request]
"Transforms the opts")
(-process-response [this response]
"Transforms the raw response (an implementation of AjaxResponse)"))
(defrecord Response [status body status-text headers was-aborted]
AjaxResponse
(-body [this] (:body this))
(-status [this] (:status this))
(-status-text [this] (:status-text this))
(-get-all-headers [this] (:headers this))
(-get-response-header [this header] (get (:headers this) header))
(-was-aborted [this] (:was-aborted this)))
|
|
5b9fc902ac462f42a5d022d4a5809bba1b3e17f70285cbb1ad793b51359058ae
|
anton-k/reader-pattern-servant-app
|
Api.hs
|
-- | API for the service.
-- For simplicity it is in single module, but will be split on parts
-- by methods in real project.
module Api
( Api
, SaveRequest(..)
, SaveResponse(..)
) where
import Deriving.Aeson
import Deriving.Aeson.Stock
import Servant.API
import Types
type Api = "api" :> "v1" :>
( SaveMessage
:<|> GetById
:<|> GetByTag
:<|> ToggleLog
)
type SaveMessage =
"save" :> ReqBody '[JSON] SaveRequest :> Post '[JSON] SaveResponse
--------------------------------------------------------------------------
-- save
data SaveRequest = SaveRequest
{ message :: Text
, tags :: [Tag]
}
deriving stock (Show, Generic)
deriving (FromJSON, ToJSON) via Vanilla SaveRequest
newtype SaveResponse = SaveResponse MessageId
deriving newtype (ToJSON, FromJSON, Show, Eq)
--------------------------------------------------------------------------
-- get by id
type GetById =
"get" :> "message" :> Capture "id" MessageId :> Get '[JSON] Message
--------------------------------------------------------------------------
-- get by tag
type GetByTag =
"list" :> "tag" :> Capture "tag" Tag :> Get '[JSON] [Message]
--------------------------------------------------------------------------
-- toggle log
type ToggleLog =
"toggle-logs" :> Post '[JSON] ()
| null |
https://raw.githubusercontent.com/anton-k/reader-pattern-servant-app/64fcb93cc92a6e30511e5ecf77a2bf21ada47bc2/src/Api.hs
|
haskell
|
| API for the service.
For simplicity it is in single module, but will be split on parts
by methods in real project.
------------------------------------------------------------------------
save
------------------------------------------------------------------------
get by id
------------------------------------------------------------------------
get by tag
------------------------------------------------------------------------
toggle log
|
module Api
( Api
, SaveRequest(..)
, SaveResponse(..)
) where
import Deriving.Aeson
import Deriving.Aeson.Stock
import Servant.API
import Types
type Api = "api" :> "v1" :>
( SaveMessage
:<|> GetById
:<|> GetByTag
:<|> ToggleLog
)
type SaveMessage =
"save" :> ReqBody '[JSON] SaveRequest :> Post '[JSON] SaveResponse
data SaveRequest = SaveRequest
{ message :: Text
, tags :: [Tag]
}
deriving stock (Show, Generic)
deriving (FromJSON, ToJSON) via Vanilla SaveRequest
newtype SaveResponse = SaveResponse MessageId
deriving newtype (ToJSON, FromJSON, Show, Eq)
type GetById =
"get" :> "message" :> Capture "id" MessageId :> Get '[JSON] Message
type GetByTag =
"list" :> "tag" :> Capture "tag" Tag :> Get '[JSON] [Message]
type ToggleLog =
"toggle-logs" :> Post '[JSON] ()
|
e6d2c44f0bf0c0f035f80c9234b99a2bc13c2f426921d37102c35c51a655acb2
|
sunng87/rigui
|
impl_test.clj
|
(ns rigui.impl-test
(:require [rigui.impl :refer :all]
[rigui.timer.platform :refer [*dry-run*]]
[rigui.units :refer :all]
[rigui.math :as math]
[rigui.utils :refer [now]]
[clojure.test :refer :all])
(:import [clojure.lang ExceptionInfo]))
(deftest test-level-for-target
(testing "level -1"
(is (= -1 (level-for-target 1 0 2 10)))
(is (= -1 (level-for-target -1 0 2 10))))
(testing "normal level computing"
(is (= 0 (level-for-target 5 0 1 8)))
(is (= 1 (level-for-target 10 0 1 8)))
(is (= 2 (level-for-target 70 0 1 8)))))
(deftest test-bucket-index-for-target
(is (= 5 (bucket-index-for-target 5 1 0)))
(is (= 8 (bucket-index-for-target 9 8 0)))
(is (= 16 (bucket-index-for-target 18 8 0)))
(is (= 17 (bucket-index-for-target 19 8 1))))
(deftest test-create-bucket
(let [t 1
bc 8
tw (start t bc identity 0)]
(dosync
(binding [*dry-run* true]
(create-bucket tw 2 64 0)
(create-bucket tw 2 192 0)))
(is (= 2 (count @(.buckets tw))))
(is (some? @(get @(.buckets tw) 64)))))
(deftest test-schedule-value
(binding [*dry-run* true]
(let [tw (start 1 8 identity 0)]
(schedule-value! tw :a 10 0 nil)
(schedule-value! tw :b 100 0 nil)
(schedule-value! tw :c 3 0 nil)
(schedule-value! tw :d 128 0 nil)
(is (= :a (-> tw
(.buckets)
(deref)
(get 8) ;; computed trigger time
(deref)
(first)
(.value))))
(is (= :b (-> tw
(.buckets)
(deref)
(get 64)
(deref)
(first)
(.value))))
(println (-> tw
(.buckets)
(deref)
(get 64)
(deref)
(first)))
(is (= :c (-> tw
(.buckets)
(deref)
(get 3)
(deref)
(first)
(.value))))
(is (= :d (-> tw
(.buckets)
(deref)
(get 128)
(deref)
(first)
(.value)))))))
(deftest test-cancel-task
(binding [*dry-run* true]
(let [tw (start 1 8 identity 0)
task (schedule-value! tw :a 10 0 nil)]
(cancel! task tw 0)
(is @(.cancelled? task))
(is (empty? (-> tw
(.buckets)
(deref)
(get 8)
(deref)))))))
(deftest test-stop-tw
(binding [*dry-run* true]
(let [tw (start 1 8 identity 0)]
(schedule-value! tw :a 10 0 nil)
(schedule-value! tw :b 100 0 nil)
(let [remains (stop tw)]
(await (.running tw))
(is (false? @(.running tw)))
(is (= 2 (count remains)))
(is (every? #{:a :b} remains)))
(try
(schedule-value! tw :c 10 0 nil)
(is false)
(catch ExceptionInfo e
(is (= :rigui.impl/timer-stopped (:reason (ex-data e)))))))))
| null |
https://raw.githubusercontent.com/sunng87/rigui/1c695b8259dc8dd4a527298e8dbb9e0f738e517c/test/rigui/impl_test.clj
|
clojure
|
computed trigger time
|
(ns rigui.impl-test
(:require [rigui.impl :refer :all]
[rigui.timer.platform :refer [*dry-run*]]
[rigui.units :refer :all]
[rigui.math :as math]
[rigui.utils :refer [now]]
[clojure.test :refer :all])
(:import [clojure.lang ExceptionInfo]))
(deftest test-level-for-target
(testing "level -1"
(is (= -1 (level-for-target 1 0 2 10)))
(is (= -1 (level-for-target -1 0 2 10))))
(testing "normal level computing"
(is (= 0 (level-for-target 5 0 1 8)))
(is (= 1 (level-for-target 10 0 1 8)))
(is (= 2 (level-for-target 70 0 1 8)))))
(deftest test-bucket-index-for-target
(is (= 5 (bucket-index-for-target 5 1 0)))
(is (= 8 (bucket-index-for-target 9 8 0)))
(is (= 16 (bucket-index-for-target 18 8 0)))
(is (= 17 (bucket-index-for-target 19 8 1))))
(deftest test-create-bucket
(let [t 1
bc 8
tw (start t bc identity 0)]
(dosync
(binding [*dry-run* true]
(create-bucket tw 2 64 0)
(create-bucket tw 2 192 0)))
(is (= 2 (count @(.buckets tw))))
(is (some? @(get @(.buckets tw) 64)))))
(deftest test-schedule-value
(binding [*dry-run* true]
(let [tw (start 1 8 identity 0)]
(schedule-value! tw :a 10 0 nil)
(schedule-value! tw :b 100 0 nil)
(schedule-value! tw :c 3 0 nil)
(schedule-value! tw :d 128 0 nil)
(is (= :a (-> tw
(.buckets)
(deref)
(deref)
(first)
(.value))))
(is (= :b (-> tw
(.buckets)
(deref)
(get 64)
(deref)
(first)
(.value))))
(println (-> tw
(.buckets)
(deref)
(get 64)
(deref)
(first)))
(is (= :c (-> tw
(.buckets)
(deref)
(get 3)
(deref)
(first)
(.value))))
(is (= :d (-> tw
(.buckets)
(deref)
(get 128)
(deref)
(first)
(.value)))))))
(deftest test-cancel-task
(binding [*dry-run* true]
(let [tw (start 1 8 identity 0)
task (schedule-value! tw :a 10 0 nil)]
(cancel! task tw 0)
(is @(.cancelled? task))
(is (empty? (-> tw
(.buckets)
(deref)
(get 8)
(deref)))))))
(deftest test-stop-tw
(binding [*dry-run* true]
(let [tw (start 1 8 identity 0)]
(schedule-value! tw :a 10 0 nil)
(schedule-value! tw :b 100 0 nil)
(let [remains (stop tw)]
(await (.running tw))
(is (false? @(.running tw)))
(is (= 2 (count remains)))
(is (every? #{:a :b} remains)))
(try
(schedule-value! tw :c 10 0 nil)
(is false)
(catch ExceptionInfo e
(is (= :rigui.impl/timer-stopped (:reason (ex-data e)))))))))
|
a8424592df266f0a73b05cefc625a62b3bd162d9b8441dae15b79f7e0e42faf5
|
thi-ng/geom
|
fx_pipeline.clj
|
(ns thi.ng.geom.examples.jogl.fx-pipeline
(:import
[com.jogamp.opengl GL3 GLAutoDrawable]
[com.jogamp.newt.event MouseEvent KeyEvent])
(:require
[thi.ng.math.core :as m]
[thi.ng.color.core :as col]
[thi.ng.dstruct.core :as d]
[thi.ng.geom.core :as g]
[thi.ng.geom.utils :as gu]
[thi.ng.geom.rect :as r]
[thi.ng.geom.aabb :as a]
[thi.ng.geom.vector :as v]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.quaternion :as q]
[thi.ng.geom.mesh.io :as mio]
[thi.ng.geom.gl.core :as gl]
[thi.ng.geom.gl.arcball :as arc]
[thi.ng.geom.gl.fx :as fx]
[thi.ng.geom.gl.fx.bloom :as bloom]
[thi.ng.geom.gl.glmesh :as glm]
[thi.ng.geom.gl.shaders :as sh]
[thi.ng.geom.gl.shaders.phong :as phong]
[thi.ng.geom.gl.jogl.core :as jogl]
[thi.ng.geom.gl.jogl.constants :as glc]
[thi.ng.geom.gl.jogl.buffers :as native]
[thi.ng.glsl.core :as glsl]
[clojure.pprint :refer [pprint]]
[clojure.java.io :as io]))
(def app
(atom {:mesh "assets/suzanne.stl"
:version 330}))
(defn load-mesh
"Loads STL mesh from given path and fits it into centered bounding box."
[path bounds]
(with-open [in (io/input-stream path)]
(->> #(glm/gl-mesh % #{:fnorm})
(mio/read-stl (mio/wrapped-input-stream in))
vector
(gu/fit-all-into-bounds (g/center bounds))
first)))
(defn init
[^GLAutoDrawable drawable]
(let [{:keys [mesh version]} @app
^GL3 gl (.. drawable getGL getGL3)
view-rect (gl/get-viewport-rect gl)
main-shader (sh/make-shader-from-spec gl phong/shader-spec version)
pass-shader (sh/make-shader-from-spec gl fx/shader-spec version)
fx-pipe (fx/init-pipeline gl (bloom/make-pipeline-spec 1280 720 16 version))
quad (fx/init-fx-quad gl)
img-comp (d/merge-deep
quad
{:shader (assoc-in (get-in fx-pipe [:shaders :final]) [:state :tex]
(fx/resolve-pipeline-textures fx-pipe [:src :ping]))})
img-orig (d/merge-deep
quad
{:shader (assoc-in pass-shader [:state :tex]
(fx/resolve-pipeline-textures fx-pipe :src))})
model (-> (load-mesh mesh (a/aabb 2))
(gl/as-gl-buffer-spec {})
(d/merge-deep
{:uniforms {:view (mat/look-at (v/vec3 0 0 1) (v/vec3) v/V3Y)
:lightPos [0 2 0]
:shininess 10
:wrap 0
:ambientCol [0.0 0.1 0.4 0.0]
:diffuseCol [0.1 0.6 0.8]
:specularCol [1 1 1]}
:shader main-shader})
(gl/make-buffers-in-spec gl glc/static-draw))]
(swap! app merge
{:model model
:fx-pipe fx-pipe
:img-comp img-comp
:thumbs (-> fx-pipe :passes butlast reverse vec (conj img-orig))
:arcball (arc/arcball {:init (m/normalize (q/quat 0.0 0.707 0.707 0))})})))
(defn display
[^GLAutoDrawable drawable t]
(let [^GL3 gl (.. drawable getGL getGL3)
{:keys [model arcball fx-pipe img-comp thumbs width height]} @app
src-fbo (get-in fx-pipe [:fbos :src])
view-rect (r/rect width height)
vp (-> view-rect
(gu/fit-all-into-bounds [(r/rect (:width src-fbo) (:height src-fbo))])
first
(g/center (g/centroid view-rect)))
fx-pipe (fx/update-pipeline-pass fx-pipe :final assoc :viewport vp)]
(gl/bind (:fbo src-fbo))
(doto gl
(gl/set-viewport 0 0 (:width src-fbo) (:height src-fbo))
(gl/clear-color-and-depth-buffer (col/hsva 0 0 0.3) 1)
(gl/draw-with-shader (assoc-in model [:uniforms :model] (arc/get-view arcball))))
(gl/unbind (:fbo src-fbo))
(fx/execute-pipeline gl fx-pipe)
(loop [y 0, thumbs thumbs]
(when thumbs
(gl/set-viewport gl 0 y 160 90)
(gl/draw-with-shader gl (first thumbs))
(recur (+ y 90) (next thumbs))))))
(defn key-pressed
[^KeyEvent e]
(condp = (.getKeyCode e)
KeyEvent/VK_ESCAPE (jogl/destroy-window (:window @app))
nil))
(defn resize
[_ x y w h]
(swap! app
#(-> %
(assoc-in [:model :uniforms :proj] (mat/perspective 45 (/ w h) 0.1 10))
(assoc :width w :height h)
(update :arcball arc/resize w h))))
(defn dispose [_] (jogl/stop-animator (:anim @app)))
(defn mouse-pressed [^MouseEvent e] (swap! app update :arcball arc/down (.getX e) (.getY e)))
(defn mouse-dragged [^MouseEvent e] (swap! app update :arcball arc/drag (.getX e) (.getY e)))
(defn wheel-moved [^MouseEvent e deltas] (swap! app update :arcball arc/zoom-delta (nth deltas 1)))
(defn -main
[& args]
(swap! app d/merge-deep
(jogl/gl-window
{:profile :gl3
:samples 4
:double-buffer true
:fullscreen false
:events {:init init
:display display
:dispose dispose
:resize resize
:keys {:press key-pressed}
:mouse {:press mouse-pressed
:drag mouse-dragged
:wheel wheel-moved}}}))
nil)
(-main)
| null |
https://raw.githubusercontent.com/thi-ng/geom/85783a1f87670c5821473298fa0b491bd40c3028/examples/jogl/fx_pipeline.clj
|
clojure
|
(ns thi.ng.geom.examples.jogl.fx-pipeline
(:import
[com.jogamp.opengl GL3 GLAutoDrawable]
[com.jogamp.newt.event MouseEvent KeyEvent])
(:require
[thi.ng.math.core :as m]
[thi.ng.color.core :as col]
[thi.ng.dstruct.core :as d]
[thi.ng.geom.core :as g]
[thi.ng.geom.utils :as gu]
[thi.ng.geom.rect :as r]
[thi.ng.geom.aabb :as a]
[thi.ng.geom.vector :as v]
[thi.ng.geom.matrix :as mat]
[thi.ng.geom.quaternion :as q]
[thi.ng.geom.mesh.io :as mio]
[thi.ng.geom.gl.core :as gl]
[thi.ng.geom.gl.arcball :as arc]
[thi.ng.geom.gl.fx :as fx]
[thi.ng.geom.gl.fx.bloom :as bloom]
[thi.ng.geom.gl.glmesh :as glm]
[thi.ng.geom.gl.shaders :as sh]
[thi.ng.geom.gl.shaders.phong :as phong]
[thi.ng.geom.gl.jogl.core :as jogl]
[thi.ng.geom.gl.jogl.constants :as glc]
[thi.ng.geom.gl.jogl.buffers :as native]
[thi.ng.glsl.core :as glsl]
[clojure.pprint :refer [pprint]]
[clojure.java.io :as io]))
(def app
(atom {:mesh "assets/suzanne.stl"
:version 330}))
(defn load-mesh
"Loads STL mesh from given path and fits it into centered bounding box."
[path bounds]
(with-open [in (io/input-stream path)]
(->> #(glm/gl-mesh % #{:fnorm})
(mio/read-stl (mio/wrapped-input-stream in))
vector
(gu/fit-all-into-bounds (g/center bounds))
first)))
(defn init
[^GLAutoDrawable drawable]
(let [{:keys [mesh version]} @app
^GL3 gl (.. drawable getGL getGL3)
view-rect (gl/get-viewport-rect gl)
main-shader (sh/make-shader-from-spec gl phong/shader-spec version)
pass-shader (sh/make-shader-from-spec gl fx/shader-spec version)
fx-pipe (fx/init-pipeline gl (bloom/make-pipeline-spec 1280 720 16 version))
quad (fx/init-fx-quad gl)
img-comp (d/merge-deep
quad
{:shader (assoc-in (get-in fx-pipe [:shaders :final]) [:state :tex]
(fx/resolve-pipeline-textures fx-pipe [:src :ping]))})
img-orig (d/merge-deep
quad
{:shader (assoc-in pass-shader [:state :tex]
(fx/resolve-pipeline-textures fx-pipe :src))})
model (-> (load-mesh mesh (a/aabb 2))
(gl/as-gl-buffer-spec {})
(d/merge-deep
{:uniforms {:view (mat/look-at (v/vec3 0 0 1) (v/vec3) v/V3Y)
:lightPos [0 2 0]
:shininess 10
:wrap 0
:ambientCol [0.0 0.1 0.4 0.0]
:diffuseCol [0.1 0.6 0.8]
:specularCol [1 1 1]}
:shader main-shader})
(gl/make-buffers-in-spec gl glc/static-draw))]
(swap! app merge
{:model model
:fx-pipe fx-pipe
:img-comp img-comp
:thumbs (-> fx-pipe :passes butlast reverse vec (conj img-orig))
:arcball (arc/arcball {:init (m/normalize (q/quat 0.0 0.707 0.707 0))})})))
(defn display
[^GLAutoDrawable drawable t]
(let [^GL3 gl (.. drawable getGL getGL3)
{:keys [model arcball fx-pipe img-comp thumbs width height]} @app
src-fbo (get-in fx-pipe [:fbos :src])
view-rect (r/rect width height)
vp (-> view-rect
(gu/fit-all-into-bounds [(r/rect (:width src-fbo) (:height src-fbo))])
first
(g/center (g/centroid view-rect)))
fx-pipe (fx/update-pipeline-pass fx-pipe :final assoc :viewport vp)]
(gl/bind (:fbo src-fbo))
(doto gl
(gl/set-viewport 0 0 (:width src-fbo) (:height src-fbo))
(gl/clear-color-and-depth-buffer (col/hsva 0 0 0.3) 1)
(gl/draw-with-shader (assoc-in model [:uniforms :model] (arc/get-view arcball))))
(gl/unbind (:fbo src-fbo))
(fx/execute-pipeline gl fx-pipe)
(loop [y 0, thumbs thumbs]
(when thumbs
(gl/set-viewport gl 0 y 160 90)
(gl/draw-with-shader gl (first thumbs))
(recur (+ y 90) (next thumbs))))))
(defn key-pressed
[^KeyEvent e]
(condp = (.getKeyCode e)
KeyEvent/VK_ESCAPE (jogl/destroy-window (:window @app))
nil))
(defn resize
[_ x y w h]
(swap! app
#(-> %
(assoc-in [:model :uniforms :proj] (mat/perspective 45 (/ w h) 0.1 10))
(assoc :width w :height h)
(update :arcball arc/resize w h))))
(defn dispose [_] (jogl/stop-animator (:anim @app)))
(defn mouse-pressed [^MouseEvent e] (swap! app update :arcball arc/down (.getX e) (.getY e)))
(defn mouse-dragged [^MouseEvent e] (swap! app update :arcball arc/drag (.getX e) (.getY e)))
(defn wheel-moved [^MouseEvent e deltas] (swap! app update :arcball arc/zoom-delta (nth deltas 1)))
(defn -main
[& args]
(swap! app d/merge-deep
(jogl/gl-window
{:profile :gl3
:samples 4
:double-buffer true
:fullscreen false
:events {:init init
:display display
:dispose dispose
:resize resize
:keys {:press key-pressed}
:mouse {:press mouse-pressed
:drag mouse-dragged
:wheel wheel-moved}}}))
nil)
(-main)
|
|
da0137925e264295ffc751e22ae94d75f4858e19d076665e08279909fb08b337
|
jrm-code-project/LISP-Machine
|
mouse.lisp
|
-*- Mode : LISP ; Package : ; -*-
(defobclass mouseable-rect (window-rect))
(defobclass inverting-rect (window-rect)
inverted-p)
(defobfun (invert inverting-rect) ()
(send window :draw-rectangle width height x y tv:alu-xor)
(setq inverted-p (not inverted-p)))
(defobfun (erase inverting-rect) ()
(if inverted-p (invert))
(shadowed-erase))
(defobfun (remove-frippery inverting-rect) ()
(if inverted-p (invert))
(shadowed-remove-frippery))
; Special hack for images
(defobfun (invert image-icon) ()
(send window :bitblt tv:alu-xor width height mask 0 0 x y)
(setq inverted-p (not inverted-p)))
(defobfun (invert char-icon) ()
(send window :draw-char font shape-char x y tv:alu-xor))
(defobfun (draw inverting-rect) ()
(shadowed-draw)
(setq inverted-p (not inverted-p)) ;sort of a hack
(invert))
(defobclass mouse-highlighting-rect (inverting-rect mouseable-rect))
(defobfun (mouse-in mouse-highlighting-rect) ()
(unless inverted-p (invert)))
(defobfun (mouse-out mouse-highlighting-rect) ()
(when inverted-p (invert)))
; Temp, for demo
(defobfun (mouse-click mouse-highlighting-rect) (char x y)
char
(and (point-in-region (- x (tv:sheet-left-margin-size window)) (- y (tv:sheet-top-margin-size window)))
(progn
(drag))))
(defobclass dynamic-mouseable-text-icon (dynamic-text-icon mouse-highlighting-rect))
(defobclass dynamic-mouseable-image-icon (dynamic-image-icon mouse-highlighting-rect))
(defobclass dynamic-mouseable-char-icon (dynamic-char-icon mouse-highlighting-rect))
(defobfun test (&aux ike)
(setq window (make-instance 'obie-window :edges-from :mouse :expose-p t :borders 10))
(dolist (i '("foo" "bar" "blather" "ugh" "fnord"))
(setq ike (oneof dynamic-mouseable-text-icon 'window window 'opaque-p t 'bordered-p nil 'x 0 'y 0 'font fonts:hl12b 'text i))
(send window :add-object ike t)
( ask ( draw ) )
(ask ike (drag))))
(defobfun icon-madness (&aux ike window)
(unless (boundp '*file-image*)
(load "lad:efh;icons")
(setq *file-image* (load-image "efh.icons;file")
*file-group-image* (load-image "efh.icons;double-file")
*dir-image* (load-image "efh.icons;file-folder")
*host-image* (load-image "efh.icons;lambda")))
(setq window (make-instance 'obie-window :edges-from :mouse :expose-p t :borders 10))
(dotimes (i 5)
(setq ike
(caseq i
(0 (oneof dynamic-mouseable-text-icon 'window window 'opaque-p t 'bordered-p nil 'x 0 'y 0 'font fonts:hl12b 'text "frobozz"))
(1 (oneof dynamic-mouseable-image-icon 'window window 'x 0 'y 0 'image *host-image*))
(2 (oneof dynamic-mouseable-char-icon 'window window 'x 0 'y 0 'font fonts:mouse 'shape-char #\ 'image-char #\0))
(3 (oneof dynamic-mouseable-image-icon 'window window 'x 0 'y 0 'image *file-group-image*))
(4 (oneof dynamic-mouseable-text-icon 'window window 'opaque-p t 'bordered-p nil 'x 0 'y 0 'font fonts:25fr3 'text "Icon Madness!")) ;
))
(send window :add-object ike t)
(ask ike (drag))))
tv:
(defmacro obie:with-mouse-grabbed (&rest body)
`(let ((.old.value. window-owning-mouse))
(let-globally ((who-line-mouse-grabbed-documentation nil))
(unwind-protect
(progn
(with-mouse-grabbed-internal t)
. ,body)
(setq window-owning-mouse .old.value.)
(setq mouse-reconsider t)))))
;;; Tell the mouse process to switch "modes" and wait for it to do so
; this version can be called from mouse process (no-op)
tv:
(DEFUN WITH-MOUSE-GRABBED-INTERNAL (WOM &AUX (INHIBIT-SCHEDULING-FLAG T))
(unless (eq si:current-process mouse-process)
(SETQ WINDOW-OWNING-MOUSE WOM)
(WHEN (NEQ WOM MOUSE-WINDOW)
(SETQ MOUSE-RECONSIDER T
INHIBIT-SCHEDULING-FLAG NIL )
(PROCESS-WAIT "Grab Mouse" #'(LAMBDA (WOM) (AND (NULL MOUSE-RECONSIDER)
(EQ MOUSE-WINDOW WOM)))
WOM))))
(defobfun (drag window-point) (&aux starting-mouse-buttons)
(setq starting-mouse-buttons (tv:mouse-buttons))
(tv:with-mouse-grabbed
(do-forever
(tv:mouse-wait)
(if (eql (tv:mouse-buttons) starting-mouse-buttons)
(move (- tv:mouse-x (send window :x-offset) (tv:sheet-left-margin-size window))
(- tv:mouse-y (send window :y-offset) (tv:sheet-top-margin-size window)))
(return)))))
; system version is broken
tv:
(DEFUN MOUSE-WAIT (&OPTIONAL (OLD-X MOUSE-X) (OLD-Y MOUSE-Y) (OLD-BUTTONS MOUSE-LAST-BUTTONS)
(WHOSTATE "MOUSE"))
"Wait for the mouse to move or a button transition. For processes other than MOUSE-PROCESS.
If the arguments are supplied, we wait for the mouse state to be
different from them. To avoid lossage, save the values of
MOUSE-X and MOUSE-Y and MOUSE-LAST-BUTTONS, use the saved values,
then pass the saved values to this function.
WHOSTATE is displayed in the who line while we wait."
(PROCESS-WAIT WHOSTATE
#'(LAMBDA (OLD-X OLD-Y OLD-BUTTONS)
(OR ( MOUSE-X OLD-X)
( MOUSE-Y OLD-Y)
( (tv:%lambda-mouse-buttons) OLD-BUTTONS)))
OLD-X OLD-Y OLD-BUTTONS))
| null |
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/window/sliders/mouse.lisp
|
lisp
|
Package : ; -*-
Special hack for images
sort of a hack
Temp, for demo
Tell the mouse process to switch "modes" and wait for it to do so
this version can be called from mouse process (no-op)
system version is broken
|
(defobclass mouseable-rect (window-rect))
(defobclass inverting-rect (window-rect)
inverted-p)
(defobfun (invert inverting-rect) ()
(send window :draw-rectangle width height x y tv:alu-xor)
(setq inverted-p (not inverted-p)))
(defobfun (erase inverting-rect) ()
(if inverted-p (invert))
(shadowed-erase))
(defobfun (remove-frippery inverting-rect) ()
(if inverted-p (invert))
(shadowed-remove-frippery))
(defobfun (invert image-icon) ()
(send window :bitblt tv:alu-xor width height mask 0 0 x y)
(setq inverted-p (not inverted-p)))
(defobfun (invert char-icon) ()
(send window :draw-char font shape-char x y tv:alu-xor))
(defobfun (draw inverting-rect) ()
(shadowed-draw)
(invert))
(defobclass mouse-highlighting-rect (inverting-rect mouseable-rect))
(defobfun (mouse-in mouse-highlighting-rect) ()
(unless inverted-p (invert)))
(defobfun (mouse-out mouse-highlighting-rect) ()
(when inverted-p (invert)))
(defobfun (mouse-click mouse-highlighting-rect) (char x y)
char
(and (point-in-region (- x (tv:sheet-left-margin-size window)) (- y (tv:sheet-top-margin-size window)))
(progn
(drag))))
(defobclass dynamic-mouseable-text-icon (dynamic-text-icon mouse-highlighting-rect))
(defobclass dynamic-mouseable-image-icon (dynamic-image-icon mouse-highlighting-rect))
(defobclass dynamic-mouseable-char-icon (dynamic-char-icon mouse-highlighting-rect))
(defobfun test (&aux ike)
(setq window (make-instance 'obie-window :edges-from :mouse :expose-p t :borders 10))
(dolist (i '("foo" "bar" "blather" "ugh" "fnord"))
(setq ike (oneof dynamic-mouseable-text-icon 'window window 'opaque-p t 'bordered-p nil 'x 0 'y 0 'font fonts:hl12b 'text i))
(send window :add-object ike t)
( ask ( draw ) )
(ask ike (drag))))
(defobfun icon-madness (&aux ike window)
(unless (boundp '*file-image*)
(load "lad:efh;icons")
(setq *file-image* (load-image "efh.icons;file")
*file-group-image* (load-image "efh.icons;double-file")
*dir-image* (load-image "efh.icons;file-folder")
*host-image* (load-image "efh.icons;lambda")))
(setq window (make-instance 'obie-window :edges-from :mouse :expose-p t :borders 10))
(dotimes (i 5)
(setq ike
(caseq i
(0 (oneof dynamic-mouseable-text-icon 'window window 'opaque-p t 'bordered-p nil 'x 0 'y 0 'font fonts:hl12b 'text "frobozz"))
(1 (oneof dynamic-mouseable-image-icon 'window window 'x 0 'y 0 'image *host-image*))
(2 (oneof dynamic-mouseable-char-icon 'window window 'x 0 'y 0 'font fonts:mouse 'shape-char #\ 'image-char #\0))
(3 (oneof dynamic-mouseable-image-icon 'window window 'x 0 'y 0 'image *file-group-image*))
))
(send window :add-object ike t)
(ask ike (drag))))
tv:
(defmacro obie:with-mouse-grabbed (&rest body)
`(let ((.old.value. window-owning-mouse))
(let-globally ((who-line-mouse-grabbed-documentation nil))
(unwind-protect
(progn
(with-mouse-grabbed-internal t)
. ,body)
(setq window-owning-mouse .old.value.)
(setq mouse-reconsider t)))))
tv:
(DEFUN WITH-MOUSE-GRABBED-INTERNAL (WOM &AUX (INHIBIT-SCHEDULING-FLAG T))
(unless (eq si:current-process mouse-process)
(SETQ WINDOW-OWNING-MOUSE WOM)
(WHEN (NEQ WOM MOUSE-WINDOW)
(SETQ MOUSE-RECONSIDER T
INHIBIT-SCHEDULING-FLAG NIL )
(PROCESS-WAIT "Grab Mouse" #'(LAMBDA (WOM) (AND (NULL MOUSE-RECONSIDER)
(EQ MOUSE-WINDOW WOM)))
WOM))))
(defobfun (drag window-point) (&aux starting-mouse-buttons)
(setq starting-mouse-buttons (tv:mouse-buttons))
(tv:with-mouse-grabbed
(do-forever
(tv:mouse-wait)
(if (eql (tv:mouse-buttons) starting-mouse-buttons)
(move (- tv:mouse-x (send window :x-offset) (tv:sheet-left-margin-size window))
(- tv:mouse-y (send window :y-offset) (tv:sheet-top-margin-size window)))
(return)))))
tv:
(DEFUN MOUSE-WAIT (&OPTIONAL (OLD-X MOUSE-X) (OLD-Y MOUSE-Y) (OLD-BUTTONS MOUSE-LAST-BUTTONS)
(WHOSTATE "MOUSE"))
"Wait for the mouse to move or a button transition. For processes other than MOUSE-PROCESS.
If the arguments are supplied, we wait for the mouse state to be
different from them. To avoid lossage, save the values of
MOUSE-X and MOUSE-Y and MOUSE-LAST-BUTTONS, use the saved values,
then pass the saved values to this function.
WHOSTATE is displayed in the who line while we wait."
(PROCESS-WAIT WHOSTATE
#'(LAMBDA (OLD-X OLD-Y OLD-BUTTONS)
(OR ( MOUSE-X OLD-X)
( MOUSE-Y OLD-Y)
( (tv:%lambda-mouse-buttons) OLD-BUTTONS)))
OLD-X OLD-Y OLD-BUTTONS))
|
e9b98e5f6bfdb74ca2eb56f35d094c1603f472e2f6a9c4661bc7fc87e04d05df
|
astrada/ocaml-extjs
|
ext_grid_column_Column.mli
|
* This class specifies the definition for a column i ...
{ % < p > This class specifies the definition for a column inside a < a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > . It encompasses
both the grid header configuration as well as displaying data within the grid itself . If the
< a href="#!/api / Ext.grid.column . Column - cfg - columns " rel="Ext.grid.column . Column - cfg - columns " class="docClass">columns</a > configuration is specified , this column will become a column group and can
contain other columns inside . In general , this class will not be created directly , rather
an array of column configurations will be passed to the grid:</p >
< pre class='inline - example ' > < code><a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > ' , \ {
storeId:'employeeStore ' ,
fields:['firstname ' , ' lastname ' , ' seniority ' , ' dep ' , ' hired ' ] ,
data : [
\{firstname:"Michael " , lastname:"Scott " , seniority:7 , dep:"Management " , hired:"01/10/2004"\ } ,
\{firstname:"Dwight " , lastname:"Schrute " , seniority:2 , dep:"Sales " , hired:"04/01/2004"\ } ,
" , lastname:"Halpert " , seniority:3 , dep:"Sales " , hired:"02/22/2006"\ } ,
\{firstname:"Kevin " , lastname:"Malone " , seniority:4 , dep:"Accounting " , hired:"06/10/2007"\ } ,
\{firstname:"Angela " , " , seniority:5 , dep:"Accounting " , hired:"10/21/2008"\ }
]
\ } ) ;
< a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
title : ' Column Demo ' ,
store : < a href="#!/api / Ext.data . StoreManager - method - lookup " rel="Ext.data . StoreManager - method - lookup " class="docClass">Ext.data . StoreManager.lookup</a>('employeeStore ' ) ,
columns : [
\{text : ' First Name ' , dataIndex:'firstname'\ } ,
\{text : ' Last Name ' , dataIndex:'lastname'\ } ,
\{text : ' Hired Month ' , dataIndex:'hired ' , xtype:'datecolumn ' , format:'M'\ } ,
\{text : ' Department ( Yrs ) ' , xtype:'templatecolumn ' , tpl:'\{dep\ } ( \{seniority\})'\ }
] ,
width : 400 ,
forceFit : true ,
renderTo : < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( )
\ } ) ;
< /code></pre >
< h1 > Convenience Subclasses</h1 >
< p > There are several column subclasses that provide default rendering for various data types</p >
< ul >
< li><a href="#!/api / Ext.grid.column . Action " rel="Ext.grid.column . Action " class="docClass">Ext.grid.column . > : Renders icons that can respond to click events inline</li >
< li><a href="#!/api / Ext.grid.column . Boolean " rel="Ext.grid.column . Boolean " class="docClass">Ext.grid.column . Boolean</a > : Renders for boolean values</li >
< li><a href="#!/api / Ext.grid.column . Date " rel="Ext.grid.column . Date " class="docClass">Ext.grid.column . Date</a > : Renders for date values</li >
< li><a href="#!/api / Ext.grid.column . Number " rel="Ext.grid.column . Number " class="docClass">Ext.grid.column . > : Renders for numeric values</li >
< li><a href="#!/api / Ext.grid.column . Template " rel="Ext.grid.column . Template " class="docClass">Ext.grid.column . Template</a > : Renders a value using an < a href="#!/api / Ext . XTemplate " rel="Ext . XTemplate " class="docClass">Ext . XTemplate</a > using the record data</li >
< /ul >
< h1 > Setting Sizes</h1 >
< p > The columns are laid out by a < a href="#!/api / Ext.layout.container . HBox " . HBox " class="docClass">Ext.layout.container . HBox</a > layout , so a column can either
be given an explicit width value or a flex configuration . If no width is specified the grid will
automatically the size the column to 100px . For column groups , the size is calculated by measuring
the width of the child columns , so a width option should not be specified in that case.</p >
< h1 > Header Options</h1 >
< ul >
< li><a href="#!/api / Ext.grid.column . Column - cfg - text " rel="Ext.grid.column . Column - cfg - text " class="docClass">text</a > : Sets the header text for the column</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - sortable " rel="Ext.grid.column . Column - cfg - sortable " class="docClass">sortable</a > : Specifies whether the column can be sorted by clicking the header or using the column menu</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - hideable " rel="Ext.grid.column . Column - cfg - hideable " class="docClass">hideable</a > : Specifies whether the column can be hidden using the column menu</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - menuDisabled " rel="Ext.grid.column . Column - cfg - menuDisabled " class="docClass">menuDisabled</a > : Disables the column header menu</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - draggable " rel="Ext.grid.column . Column - cfg - draggable " class="docClass">draggable</a > : Specifies whether the column header can be reordered by dragging</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - groupable " rel="Ext.grid.column . Column - cfg - groupable " class="docClass">groupable</a > : Specifies whether the grid can be grouped by the column dataIndex . See also < a href="#!/api / Ext.grid.feature . Grouping " rel="Ext.grid.feature . Grouping " class="docClass">Ext.grid.feature . Grouping</a></li >
< /ul >
< h1 > Data Options</h1 >
< ul >
< li><a href="#!/api / Ext.grid.column . Column - cfg - dataIndex " rel="Ext.grid.column . Column - cfg - dataIndex " class="docClass">dataIndex</a > : The dataIndex is the field in the underlying < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > to use as the value for the column.</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - renderer " rel="Ext.grid.column . Column - cfg - renderer " class="docClass">renderer</a > : Allows the underlying store value to be transformed before being displayed in the grid</li >
< /ul > % }
{% <p>This class specifies the definition for a column inside a <a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>. It encompasses
both the grid header configuration as well as displaying data within the grid itself. If the
<a href="#!/api/Ext.grid.column.Column-cfg-columns" rel="Ext.grid.column.Column-cfg-columns" class="docClass">columns</a> configuration is specified, this column will become a column group and can
contain other columns inside. In general, this class will not be created directly, rather
an array of column configurations will be passed to the grid:</p>
<pre class='inline-example '><code><a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Ext.data.Store</a>', \{
storeId:'employeeStore',
fields:['firstname', 'lastname', 'seniority', 'dep', 'hired'],
data:[
\{firstname:"Michael", lastname:"Scott", seniority:7, dep:"Management", hired:"01/10/2004"\},
\{firstname:"Dwight", lastname:"Schrute", seniority:2, dep:"Sales", hired:"04/01/2004"\},
\{firstname:"Jim", lastname:"Halpert", seniority:3, dep:"Sales", hired:"02/22/2006"\},
\{firstname:"Kevin", lastname:"Malone", seniority:4, dep:"Accounting", hired:"06/10/2007"\},
\{firstname:"Angela", lastname:"Martin", seniority:5, dep:"Accounting", hired:"10/21/2008"\}
]
\});
<a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
title: 'Column Demo',
store: <a href="#!/api/Ext.data.StoreManager-method-lookup" rel="Ext.data.StoreManager-method-lookup" class="docClass">Ext.data.StoreManager.lookup</a>('employeeStore'),
columns: [
\{text: 'First Name', dataIndex:'firstname'\},
\{text: 'Last Name', dataIndex:'lastname'\},
\{text: 'Hired Month', dataIndex:'hired', xtype:'datecolumn', format:'M'\},
\{text: 'Department (Yrs)', xtype:'templatecolumn', tpl:'\{dep\} (\{seniority\})'\}
],
width: 400,
forceFit: true,
renderTo: <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>()
\});
</code></pre>
<h1>Convenience Subclasses</h1>
<p>There are several column subclasses that provide default rendering for various data types</p>
<ul>
<li><a href="#!/api/Ext.grid.column.Action" rel="Ext.grid.column.Action" class="docClass">Ext.grid.column.Action</a>: Renders icons that can respond to click events inline</li>
<li><a href="#!/api/Ext.grid.column.Boolean" rel="Ext.grid.column.Boolean" class="docClass">Ext.grid.column.Boolean</a>: Renders for boolean values</li>
<li><a href="#!/api/Ext.grid.column.Date" rel="Ext.grid.column.Date" class="docClass">Ext.grid.column.Date</a>: Renders for date values</li>
<li><a href="#!/api/Ext.grid.column.Number" rel="Ext.grid.column.Number" class="docClass">Ext.grid.column.Number</a>: Renders for numeric values</li>
<li><a href="#!/api/Ext.grid.column.Template" rel="Ext.grid.column.Template" class="docClass">Ext.grid.column.Template</a>: Renders a value using an <a href="#!/api/Ext.XTemplate" rel="Ext.XTemplate" class="docClass">Ext.XTemplate</a> using the record data</li>
</ul>
<h1>Setting Sizes</h1>
<p>The columns are laid out by a <a href="#!/api/Ext.layout.container.HBox" rel="Ext.layout.container.HBox" class="docClass">Ext.layout.container.HBox</a> layout, so a column can either
be given an explicit width value or a flex configuration. If no width is specified the grid will
automatically the size the column to 100px. For column groups, the size is calculated by measuring
the width of the child columns, so a width option should not be specified in that case.</p>
<h1>Header Options</h1>
<ul>
<li><a href="#!/api/Ext.grid.column.Column-cfg-text" rel="Ext.grid.column.Column-cfg-text" class="docClass">text</a>: Sets the header text for the column</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-sortable" rel="Ext.grid.column.Column-cfg-sortable" class="docClass">sortable</a>: Specifies whether the column can be sorted by clicking the header or using the column menu</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-hideable" rel="Ext.grid.column.Column-cfg-hideable" class="docClass">hideable</a>: Specifies whether the column can be hidden using the column menu</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-menuDisabled" rel="Ext.grid.column.Column-cfg-menuDisabled" class="docClass">menuDisabled</a>: Disables the column header menu</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-draggable" rel="Ext.grid.column.Column-cfg-draggable" class="docClass">draggable</a>: Specifies whether the column header can be reordered by dragging</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-groupable" rel="Ext.grid.column.Column-cfg-groupable" class="docClass">groupable</a>: Specifies whether the grid can be grouped by the column dataIndex. See also <a href="#!/api/Ext.grid.feature.Grouping" rel="Ext.grid.feature.Grouping" class="docClass">Ext.grid.feature.Grouping</a></li>
</ul>
<h1>Data Options</h1>
<ul>
<li><a href="#!/api/Ext.grid.column.Column-cfg-dataIndex" rel="Ext.grid.column.Column-cfg-dataIndex" class="docClass">dataIndex</a>: The dataIndex is the field in the underlying <a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Ext.data.Store</a> to use as the value for the column.</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-renderer" rel="Ext.grid.column.Column-cfg-renderer" class="docClass">renderer</a>: Allows the underlying store value to be transformed before being displayed in the grid</li>
</ul> %}
*)
class type t =
object('self)
inherit Ext_grid_header_Container.t
method isColumn : bool Js.t Js.readonly_prop
* { % < p > Set in this class to identify , at runtime , instances which are not instances of the
HeaderContainer base class , but are in fact simple column > % }
Defaults to : [ true ]
HeaderContainer base class, but are in fact simple column headers.</p> %}
Defaults to: [true]
*)
method textEl : Ext_dom_Element.t Js.t Js.prop
* { % < p > Element that contains the text in column > % }
*)
method triggerEl : Ext_dom_Element.t Js.t Js.prop
* { % < p > Element that acts as button for column header dropdown > % }
*)
method afterComponentLayout : Js.number Js.t -> Js.number Js.t -> _ Js.t ->
_ Js.t -> unit Js.meth
* { % < p > private
Inform the header container about the resize</p >
< p > Called by the layout system after the Component has been laid out.</p > % }
{ b Parameters } :
{ ul { - width : [ Js.number Js.t ]
{ % < p > The width that was > % }
}
{ - height : [ Js.number Js.t ]
{ % < p > The height that was > % }
}
{ - oldWidth : [ _ Js.t ]
{ % < p > The old width , or < code > undefined</code > if this was the initial layout.</p > % }
}
{ - oldHeight : [ _ Js.t ]
{ % < p > The old height , or < code > undefined</code > if this was the initial layout.</p > % }
}
}
Inform the header container about the resize</p>
<p>Called by the layout system after the Component has been laid out.</p> %}
{b Parameters}:
{ul {- width: [Js.number Js.t]
{% <p>The width that was set</p> %}
}
{- height: [Js.number Js.t]
{% <p>The height that was set</p> %}
}
{- oldWidth: [_ Js.t]
{% <p>The old width, or <code>undefined</code> if this was the initial layout.</p> %}
}
{- oldHeight: [_ Js.t]
{% <p>The old height, or <code>undefined</code> if this was the initial layout.</p> %}
}
}
*)
method afterRender : unit Js.meth
(** {% <p>Allows addition of behavior after rendering is complete. At this stage the Component’s Element
will have been styled according to the configuration, will have had any configured CSS class
names added, and will be in the configured visibility and the configured enable state.</p> %}
*)
method autoSize : _ Js.t -> unit Js.meth
* { % < p > Sizes this Column to fit the max content width .
< em > Note that group columns shrinkwrap around the size of leaf columns . Auto sizing a group column
autosizes descendant > % }
{ b Parameters } :
{ ul { - the : [ _ Js.t ]
{ % < p > header ( or index of header ) to auto size.</p > % }
}
}
<em>Note that group columns shrinkwrap around the size of leaf columns. Auto sizing a group column
autosizes descendant leaf columns.</em></p> %}
{b Parameters}:
{ul {- the: [_ Js.t]
{% <p>header (or index of header) to auto size.</p> %}
}
}
*)
method defaultRenderer : unit Js.meth
(** {% <p>When defined this will take precedence over the <a href="#!/api/Ext.grid.column.Column-cfg-renderer" rel="Ext.grid.column.Column-cfg-renderer" class="docClass">renderer</a> config.
This is meant to be defined in subclasses that wish to supply their own renderer.</p> %}
*)
method getEditor : _ Js.t -> _ Js.t -> #Ext_form_field_Field.t Js.t Js.meth
* { % < p > Retrieves the editing field for editing associated with this header . Returns false if there is no field
associated with the Header the method will return false . If the field has not been instantiated it will be
created . Note : These methods only have an implementation if an Editing plugin has been enabled on the grid.</p > % }
{ b Parameters } :
{ ul { - record : [ _ Js.t ]
{ % < p > The < a href="#!/api / Ext.data . Model " rel="Ext.data . Model " class="docClass">Model</a > instance being edited.</p > % }
}
{ - defaultField : [ _ Js.t ]
{ % < p > An object representing a default field to be created</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_form_field_Field.t Js.t ] { % < p > field</p > % }
}
}
associated with the Header the method will return false. If the field has not been instantiated it will be
created. Note: These methods only have an implementation if an Editing plugin has been enabled on the grid.</p> %}
{b Parameters}:
{ul {- record: [_ Js.t]
{% <p>The <a href="#!/api/Ext.data.Model" rel="Ext.data.Model" class="docClass">Model</a> instance being edited.</p> %}
}
{- defaultField: [_ Js.t]
{% <p>An object representing a default field to be created</p> %}
}
}
{b Returns}:
{ul {- [#Ext_form_field_Field.t Js.t] {% <p>field</p> %}
}
}
*)
method getIndex : Js.number Js.t Js.meth
* { % < p > Returns the index of this column only if this column is a base level Column . If it
is a group column , it returns < code > false</code>.</p > % }
is a group column, it returns <code>false</code>.</p> %}
*)
method getSortParam : Js.js_string Js.t Js.meth
* { % < p > Returns the parameter to sort upon when sorting this header . By default this returns the dataIndex and will not
need to be overriden in most cases.</p > % }
need to be overriden in most cases.</p> %}
*)
method getVisibleIndex : Js.number Js.t Js.meth
* { % < p > Returns the index of this column in the list of < em > visible</em > columns only if this column is a base level Column . If it
is a group column , it returns < code > false</code>.</p > % }
is a group column, it returns <code>false</code>.</p> %}
*)
method hide_column : _ Js.t Js.optdef -> _ Js.callback Js.optdef ->
_ Js.t Js.optdef -> #Ext_Component.t Js.t Js.meth
* { % < p > Hides this Component , setting it to invisible using the configured < a href="#!/api / Ext.grid.column . Column - cfg - hideMode " rel="Ext.grid.column . Column - cfg - hideMode " class="docClass">hideMode</a>.</p > % }
{ b Parameters } :
{ ul { - animateTarget : [ _ ] ( optional )
{ % < p><strong > only valid for < a href="#!/api / Ext.grid.column . Column - cfg - floating " rel="Ext.grid.column . Column - cfg - floating " class="docClass">floating</a > Components
such as < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Window</a > s or < a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">ToolTip</a > s , or regular Components which have
been configured with < code > floating : true</code>.</strong > . The target to which the Component should animate while hiding.</p > % }
Defaults to : null
}
{ - callback : [ _ Js.callback ] ( optional )
{ % < p > A callback function to call after the Component is hidden.</p > % }
}
{ - scope : [ _ ] ( optional )
{ % < p > The scope ( < code > this</code > reference ) in which the callback is executed .
Defaults to this Component.</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_Component.t Js.t ] { % < p > this</p > % }
}
}
{b Parameters}:
{ul {- animateTarget: [_ Js.t] (optional)
{% <p><strong>only valid for <a href="#!/api/Ext.grid.column.Column-cfg-floating" rel="Ext.grid.column.Column-cfg-floating" class="docClass">floating</a> Components
such as <a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Window</a>s or <a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">ToolTip</a>s, or regular Components which have
been configured with <code>floating: true</code>.</strong>. The target to which the Component should animate while hiding.</p> %}
Defaults to: null
}
{- callback: [_ Js.callback] (optional)
{% <p>A callback function to call after the Component is hidden.</p> %}
}
{- scope: [_ Js.t] (optional)
{% <p>The scope (<code>this</code> reference) in which the callback is executed.
Defaults to this Component.</p> %}
}
}
{b Returns}:
{ul {- [#Ext_Component.t Js.t] {% <p>this</p> %}
}
}
*)
method initComponent : unit Js.meth
* { % < p > The initComponent template method is an important initialization step for a Component . It is intended to be
implemented by each subclass of < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > to provide any needed constructor logic . The
initComponent method of the class being created is called first , with each initComponent method
up the hierarchy to < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > being called thereafter . This makes it easy to implement and ,
if needed , override the constructor logic of the Component at any step in the hierarchy.</p >
< p > The initComponent method < strong > must</strong > contain a call to < a href="#!/api / Ext . Base - method - callParent " rel="Ext . Base - method - callParent " class="docClass">callParent</a > in order
to ensure that the parent class ' initComponent method is also called.</p >
< p > All config options passed to the constructor are applied to < code > this</code > before initComponent is called ,
so you can simply access them with < code > >
< p > The following example demonstrates using a dynamic string for the text of a button at the time of
instantiation of the class.</p >
< pre><code><a href="#!/api / Ext - method - define " rel="Ext - method - define " class="docClass">Ext.define</a>('DynamicButtonText ' , \ {
extend : ' < a href="#!/api / Ext.button . Button " rel="Ext.button . Button " class="docClass">Ext.button . > ' ,
initComponent : function ( ) \ {
this.text = new Date ( ) ;
this.renderTo = < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( ) ;
this.callParent ( ) ;
\ }
\ } ) ;
< a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a>(function ( ) \ {
< a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('DynamicButtonText ' ) ;
\ } ) ;
< /code></pre > % }
implemented by each subclass of <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> to provide any needed constructor logic. The
initComponent method of the class being created is called first, with each initComponent method
up the hierarchy to <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> being called thereafter. This makes it easy to implement and,
if needed, override the constructor logic of the Component at any step in the hierarchy.</p>
<p>The initComponent method <strong>must</strong> contain a call to <a href="#!/api/Ext.Base-method-callParent" rel="Ext.Base-method-callParent" class="docClass">callParent</a> in order
to ensure that the parent class' initComponent method is also called.</p>
<p>All config options passed to the constructor are applied to <code>this</code> before initComponent is called,
so you can simply access them with <code>this.someOption</code>.</p>
<p>The following example demonstrates using a dynamic string for the text of a button at the time of
instantiation of the class.</p>
<pre><code><a href="#!/api/Ext-method-define" rel="Ext-method-define" class="docClass">Ext.define</a>('DynamicButtonText', \{
extend: '<a href="#!/api/Ext.button.Button" rel="Ext.button.Button" class="docClass">Ext.button.Button</a>',
initComponent: function() \{
this.text = new Date();
this.renderTo = <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>();
this.callParent();
\}
\});
<a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(function() \{
<a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('DynamicButtonText');
\});
</code></pre> %}
*)
method initRenderData : _ Js.t Js.meth
* { % < p > Initialized the renderData to be used when rendering the renderTpl.</p > % }
{ b Returns } :
{ ul { - [ _ Js.t ]
{ % < p > Object with keys and values that are going to be applied to the renderTpl</p > % }
}
}
{b Returns}:
{ul {- [_ Js.t]
{% <p>Object with keys and values that are going to be applied to the renderTpl</p> %}
}
}
*)
method isHideable : unit Js.meth
* { % < p > Determines whether the UI should be allowed to offer an option to hide this column.</p >
< p > A column may < em > not</em > be hidden if to do so would leave the grid with no visible >
< p > This is used to determine the enabled / disabled state of header hide menu items.</p > % }
<p>A column may <em>not</em> be hidden if to do so would leave the grid with no visible columns.</p>
<p>This is used to determine the enabled/disabled state of header hide menu items.</p> %}
*)
method isLockable : unit Js.meth
* { % < p > Determines whether the UI should be allowed to offer an option to lock or unlock this column . Note
that this includes dragging a column into the opposite side of a < a href="#!/api / Ext.panel . Table - cfg - enableLocking " rel="Ext.panel . Table - cfg - enableLocking " class="docClass">lockable</a > grid.</p >
< p > A column may < em > not</em > be moved from one side to the other of a < a href="#!/api / Ext.panel . Table - cfg - enableLocking " rel="Ext.panel . Table - cfg - enableLocking " class="docClass">lockable</a > grid
if to do so would leave one side with no visible >
< p > This is used to determine the enabled / disabled state of the lock / unlock
menu item used in < a href="#!/api / Ext.panel . Table - cfg - enableLocking " rel="Ext.panel . Table - cfg - enableLocking " class="docClass">lockable</a > grids , and to determine dropppabilty when dragging a header.</p > % }
that this includes dragging a column into the opposite side of a <a href="#!/api/Ext.panel.Table-cfg-enableLocking" rel="Ext.panel.Table-cfg-enableLocking" class="docClass">lockable</a> grid.</p>
<p>A column may <em>not</em> be moved from one side to the other of a <a href="#!/api/Ext.panel.Table-cfg-enableLocking" rel="Ext.panel.Table-cfg-enableLocking" class="docClass">lockable</a> grid
if to do so would leave one side with no visible columns.</p>
<p>This is used to determine the enabled/disabled state of the lock/unlock
menu item used in <a href="#!/api/Ext.panel.Table-cfg-enableLocking" rel="Ext.panel.Table-cfg-enableLocking" class="docClass">lockable</a> grids, and to determine dropppabilty when dragging a header.</p> %}
*)
method onAdd : #Ext_Component.t Js.t -> Js.number Js.t -> unit Js.meth
* { % < p > This method is invoked after a new Component has been added . It
is passed the Component which has been added . This method may
be used to update any internal structure which may depend upon
the state of the child items.</p > % }
{ b Parameters } :
{ ul { - component : [ # Ext_Component.t Js.t ]
}
{ - position : [ Js.number Js.t ]
}
}
is passed the Component which has been added. This method may
be used to update any internal structure which may depend upon
the state of the child items.</p> %}
{b Parameters}:
{ul {- component: [#Ext_Component.t Js.t]
}
{- position: [Js.number Js.t]
}
}
*)
method onDestroy : unit Js.meth
* { % < p > Allows addition of behavior to the destroy operation .
After calling the superclass 's onDestroy , the Component will be destroyed.</p > % }
After calling the superclass's onDestroy, the Component will be destroyed.</p> %}
*)
method onRemove : #Ext_Component.t Js.t -> bool Js.t -> unit Js.meth
* { % < p > This method is invoked after a new Component has been
removed . It is passed the Component which has been
removed . This method may be used to update any internal
structure which may depend upon the state of the child items.</p > % }
{ b Parameters } :
{ ul { - component : [ # Ext_Component.t Js.t ]
}
{ - autoDestroy : [ bool Js.t ]
}
}
removed. It is passed the Component which has been
removed. This method may be used to update any internal
structure which may depend upon the state of the child items.</p> %}
{b Parameters}:
{ul {- component: [#Ext_Component.t Js.t]
}
{- autoDestroy: [bool Js.t]
}
}
*)
method setEditor : _ Js.t -> unit Js.meth
* { % < p > Sets the form field to be used for editing . Note : This method only has an implementation if an Editing plugin has
been enabled on the grid.</p > % }
{ b Parameters } :
{ ul { - field : [ _ Js.t ]
{ % < p > An object representing a field to be created . If no xtype is specified a ' textfield ' is
assumed.</p > % }
}
}
been enabled on the grid.</p> %}
{b Parameters}:
{ul {- field: [_ Js.t]
{% <p>An object representing a field to be created. If no xtype is specified a 'textfield' is
assumed.</p> %}
}
}
*)
method setText : Js.js_string Js.t -> unit Js.meth
* { % < p > Sets the header text for this > % }
{ b Parameters } :
{ ul { - text : [ Js.js_string Js.t ]
{ % < p > The header to display on this > % }
}
}
{b Parameters}:
{ul {- text: [Js.js_string Js.t]
{% <p>The header to display on this Column.</p> %}
}
}
*)
method show_column : _ Js.t Js.optdef -> _ Js.callback Js.optdef ->
_ Js.t Js.optdef -> #Ext_Component.t Js.t Js.meth
* { % < p > Shows this Component , rendering it first if < a href="#!/api / Ext.grid.column . Column - cfg - autoRender " rel="Ext.grid.column . Column - cfg - autoRender " class="docClass">autoRender</a > or < a href="#!/api / Ext.grid.column . Column - cfg - floating " rel="Ext.grid.column . Column - cfg - floating " class="docClass">floating</a > are < code > true</code>.</p >
< p > After being shown , a < a href="#!/api / Ext.grid.column . Column - cfg - floating " rel="Ext.grid.column . Column - cfg - floating " class="docClass">floating</a > Component ( such as a < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ) , is activated it and
brought to the front of its < a href="#!/api / Ext.grid.column . Column - property - zIndexManager " rel="Ext.grid.column . Column - property - zIndexManager " class="docClass">z - index stack</a>.</p > % }
{ b Parameters } :
{ ul { - animateTarget : [ _ ] ( optional )
{ % < p><strong > only valid for < a href="#!/api / Ext.grid.column . Column - cfg - floating " rel="Ext.grid.column . Column - cfg - floating " class="docClass">floating</a > Components such as < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Window</a > s or < a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">ToolTip</a > s , or regular Components which have been configured
with < code > floating : true</code>.</strong > The target from which the Component should animate from while opening.</p > % }
Defaults to : null
}
{ - callback : [ _ Js.callback ] ( optional )
{ % < p > A callback function to call after the Component is displayed .
Only necessary if animation was specified.</p > % }
}
{ - scope : [ _ ] ( optional )
{ % < p > The scope ( < code > this</code > reference ) in which the callback is executed .
Defaults to this Component.</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_Component.t Js.t ] { % < p > this</p > % }
}
}
<p>After being shown, a <a href="#!/api/Ext.grid.column.Column-cfg-floating" rel="Ext.grid.column.Column-cfg-floating" class="docClass">floating</a> Component (such as a <a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>), is activated it and
brought to the front of its <a href="#!/api/Ext.grid.column.Column-property-zIndexManager" rel="Ext.grid.column.Column-property-zIndexManager" class="docClass">z-index stack</a>.</p> %}
{b Parameters}:
{ul {- animateTarget: [_ Js.t] (optional)
{% <p><strong>only valid for <a href="#!/api/Ext.grid.column.Column-cfg-floating" rel="Ext.grid.column.Column-cfg-floating" class="docClass">floating</a> Components such as <a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Window</a>s or <a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">ToolTip</a>s, or regular Components which have been configured
with <code>floating: true</code>.</strong> The target from which the Component should animate from while opening.</p> %}
Defaults to: null
}
{- callback: [_ Js.callback] (optional)
{% <p>A callback function to call after the Component is displayed.
Only necessary if animation was specified.</p> %}
}
{- scope: [_ Js.t] (optional)
{% <p>The scope (<code>this</code> reference) in which the callback is executed.
Defaults to this Component.</p> %}
}
}
{b Returns}:
{ul {- [#Ext_Component.t Js.t] {% <p>this</p> %}
}
}
*)
end
class type configs =
object('self)
inherit Ext_grid_header_Container.configs
method align : Js.js_string Js.t Js.prop
(** {% <p>Sets the alignment of the header and rendered columns.
Possible values are: <code>'left'</code>, <code>'center'</code>, and <code>'right'</code>.</p> %}
Defaults to: ['left']
*)
method baseCls : Js.js_string Js.t Js.prop
* { % < p > The base CSS class to apply to this component 's element . This will also be prepended to elements within this
component like Panel 's body will get a class < code > x - panel - body</code > . This means that if you create a subclass of Panel , and
you want it to get all the Panels styling for the element and the body , you leave the < code > baseCls</code > < code > x - panel</code > and use
< code > componentCls</code > to add specific styling for this component.</p > % }
Defaults to : [ Ext.baseCSSPrefix + ' column - header ' ]
component like Panel's body will get a class <code>x-panel-body</code>. This means that if you create a subclass of Panel, and
you want it to get all the Panels styling for the element and the body, you leave the <code>baseCls</code> <code>x-panel</code> and use
<code>componentCls</code> to add specific styling for this component.</p> %}
Defaults to: [Ext.baseCSSPrefix + 'column-header']
*)
method columns : _ Js.t Js.js_array Js.t Js.prop
(** {% <p>An optional array of sub-column definitions. This column becomes a group, and houses the columns defined in the
<code>columns</code> config.</p>
<p>Group columns may not be sortable. But they may be hideable and moveable. And you may move headers into and out
of a group. Note that if all sub columns are dragged out of a group, the group is destroyed.</p> %}
*)
method componentLayout : _ Js.t Js.prop
* { % < p > The sizing and positioning of a Component 's internal Elements is the responsibility of the Component 's layout
manager which sizes a Component 's internal structure in response to the Component being sized.</p >
< p > Generally , developers will not use this configuration as all provided Components which need their internal
elements sizing ( Such as < a href="#!/api / Ext.form.field . Base " rel="Ext.form.field . Base " class="docClass">input fields</a > ) come with their own componentLayout managers.</p >
< p > The < a href="#!/api / Ext.layout.container . Auto " rel="Ext.layout.container . Auto " class="docClass">default layout manager</a > will be used on instances of the base < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a >
class which simply sizes the Component 's encapsulating element to the height and width specified in the
< a href="#!/api / Ext.grid.column . Column - method - setSize " rel="Ext.grid.column . Column - method - setSize " class="docClass">setSize</a > method.</p > % }
Defaults to : [ ' columncomponent ' ]
manager which sizes a Component's internal structure in response to the Component being sized.</p>
<p>Generally, developers will not use this configuration as all provided Components which need their internal
elements sizing (Such as <a href="#!/api/Ext.form.field.Base" rel="Ext.form.field.Base" class="docClass">input fields</a>) come with their own componentLayout managers.</p>
<p>The <a href="#!/api/Ext.layout.container.Auto" rel="Ext.layout.container.Auto" class="docClass">default layout manager</a> will be used on instances of the base <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a>
class which simply sizes the Component's encapsulating element to the height and width specified in the
<a href="#!/api/Ext.grid.column.Column-method-setSize" rel="Ext.grid.column.Column-method-setSize" class="docClass">setSize</a> method.</p> %}
Defaults to: ['columncomponent']
*)
method dataIndex : Js.js_string Js.t Js.prop
* { % < p > The name of the field in the grid 's < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > 's < a href="#!/api / Ext.data . Model " rel="Ext.data . Model " class="docClass">Ext.data . Model</a > definition from
which to draw the column 's value . < strong > > % }
which to draw the column's value. <strong>Required.</strong></p> %}
*)
method detachOnRemove : bool Js.t Js.prop
* { % < p > So that when removing from group headers which are then empty and then get destroyed , there 's no child >
< p > True to move any component to the < a href="#!/api / Ext - method - getDetachedBody " rel="Ext - method - getDetachedBody " class="docClass">detachedBody</a > when the component is
removed from this container . This option is only applicable when the component is not destroyed while
being removed , see < a href="#!/api / Ext.grid.column . Column - cfg - autoDestroy " rel="Ext.grid.column . Column - cfg - autoDestroy " class="docClass">autoDestroy</a > and < a href="#!/api / Ext.grid.column . Column - method - remove " rel="Ext.grid.column . Column - method - remove " class="docClass">remove</a > . If this option is set to false , the DOM
of the component will remain in the current place until it is explicitly moved.</p > % }
Defaults to : [ true ]
<p>True to move any component to the <a href="#!/api/Ext-method-getDetachedBody" rel="Ext-method-getDetachedBody" class="docClass">detachedBody</a> when the component is
removed from this container. This option is only applicable when the component is not destroyed while
being removed, see <a href="#!/api/Ext.grid.column.Column-cfg-autoDestroy" rel="Ext.grid.column.Column-cfg-autoDestroy" class="docClass">autoDestroy</a> and <a href="#!/api/Ext.grid.column.Column-method-remove" rel="Ext.grid.column.Column-method-remove" class="docClass">remove</a>. If this option is set to false, the DOM
of the component will remain in the current place until it is explicitly moved.</p> %}
Defaults to: [true]
*)
method draggable : bool Js.t Js.prop
(** {% <p>False to disable drag-drop reordering of this column.</p> %}
Defaults to: [true]
*)
method editRenderer : _ Js.callback Js.prop
* { % < p > A renderer to be used in conjunction with < a href="#!/api / Ext.grid.plugin . RowEditing " rel="Ext.grid.plugin . RowEditing " class="docClass">RowEditing</a > . This renderer is used to
display a custom value for non - editable fields.</p > % }
Defaults to : [ false ]
display a custom value for non-editable fields.</p> %}
Defaults to: [false]
*)
method editor : _ Js.t Js.prop
* { % < p > An optional xtype or config object for a < a href="#!/api / Ext.form.field . Field " rel="Ext.form.field . Field " class="docClass">Field</a > to use for editing .
Only applicable if the grid is using an < a href="#!/api / Ext.grid.plugin . Editing " rel="Ext.grid.plugin . Editing " class="docClass">Editing</a > plugin.</p > % }
Only applicable if the grid is using an <a href="#!/api/Ext.grid.plugin.Editing" rel="Ext.grid.plugin.Editing" class="docClass">Editing</a> plugin.</p> %}
*)
method emptyCellText : Js.js_string Js.t Js.prop
* { % < p > The text to diplay in empty cells ( cells with a value of < code > undefined</code > , < code , or < code>''</code>).</p >
< p > Defaults to < code>&#160;</code > aka < code>&nbsp;</code>.</p > % }
Defaults to : [ undefined ]
<p>Defaults to <code>&#160;</code> aka <code>&nbsp;</code>.</p> %}
Defaults to: [undefined]
*)
method groupable : bool Js.t Js.prop
* { % < p > If the grid uses a < a href="#!/api / Ext.grid.feature . Grouping " rel="Ext.grid.feature . Grouping " class="docClass">Ext.grid.feature . > , this option may be used to disable the header menu
item to group by the column selected . By default , the header menu group option is enabled . Set to false to
disable ( but still show ) the group option in the header menu for the column.</p > % }
item to group by the column selected. By default, the header menu group option is enabled. Set to false to
disable (but still show) the group option in the header menu for the column.</p> %}
*)
method hideable : bool Js.t Js.prop
(** {% <p>False to prevent the user from hiding this column.</p> %}
Defaults to: [true]
*)
method lockable : bool Js.t Js.prop
* { % < p > If the grid is configured with < a href="#!/api / Ext.panel . Table - cfg - enableLocking " rel="Ext.panel . Table - cfg - enableLocking " class="docClass">enableLocking</a > , or has columns which are
configured with a < a href="#!/api / Ext.grid.column . Column - cfg - locked " rel="Ext.grid.column . Column - cfg - locked " class="docClass">locked</a > value , this option may be used to disable user - driven locking or unlocking
of this column . This column will remain in the side into which its own < a href="#!/api / Ext.grid.column . Column - cfg - locked " rel="Ext.grid.column . Column - cfg - locked " class="docClass">locked</a > configuration placed it.</p > % }
configured with a <a href="#!/api/Ext.grid.column.Column-cfg-locked" rel="Ext.grid.column.Column-cfg-locked" class="docClass">locked</a> value, this option may be used to disable user-driven locking or unlocking
of this column. This column will remain in the side into which its own <a href="#!/api/Ext.grid.column.Column-cfg-locked" rel="Ext.grid.column.Column-cfg-locked" class="docClass">locked</a> configuration placed it.</p> %}
*)
method locked : bool Js.t Js.prop
* { % < p > True to lock this column in place . Implicitly enables locking on the grid .
See also < a href="#!/api / Ext.grid . Panel - cfg - enableLocking " rel="Ext.grid . Panel - cfg - enableLocking " class="docClass">Ext.grid . Panel.enableLocking</a>.</p > % }
Defaults to : [ false ]
See also <a href="#!/api/Ext.grid.Panel-cfg-enableLocking" rel="Ext.grid.Panel-cfg-enableLocking" class="docClass">Ext.grid.Panel.enableLocking</a>.</p> %}
Defaults to: [false]
*)
method menuDisabled : bool Js.t Js.prop
* { % < p > True to disable the column header menu containing sort / hide options.</p > % }
Defaults to : [ false ]
Defaults to: [false]
*)
method menuText : Js.js_string Js.t Js.prop
(** {% <p>The text to render in the column visibility selection menu for this column. If not
specified, will default to the text value.</p> %}
*)
method renderTpl : _ Js.t Js.prop
* { % < p > An < a href="#!/api / Ext . XTemplate " rel="Ext . XTemplate " class="docClass">XTemplate</a > used to create the internal structure inside this Component 's encapsulating
< a href="#!/api / Ext.grid.column . Column - method - getEl " rel="Ext.grid.column . Column - method - getEl " class="docClass">Element</a>.</p >
< p > You do not normally need to specify this . For the base classes < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > and
< a href="#!/api / Ext.container . Container " rel="Ext.container . Container " class="docClass">Ext.container . Container</a > , this defaults to < strong><code > null</code></strong > which means that they will be initially rendered
with no internal structure ; they render their < a href="#!/api / Ext.grid.column . Column - method - getEl " rel="Ext.grid.column . Column - method - getEl " class="docClass">Element</a > empty . The more specialized Ext JS and Sencha Touch
classes which use a more complex DOM structure , provide their own template definitions.</p >
< p > This is intended to allow the developer to create application - specific utility Components with customized
internal structure.</p >
< p > Upon rendering , any created child elements may be automatically imported into object properties using the
< a href="#!/api / Ext.grid.column . Column - cfg - renderSelectors " rel="Ext.grid.column . Column - cfg - renderSelectors " class="docClass">renderSelectors</a > and < a href="#!/api / Ext.grid.column . Column - cfg - childEls " rel="Ext.grid.column . Column - cfg - childEls " class="docClass">childEls</a > options.</p > % }
Defaults to : [ ' < div id="\{id\}-titleEl " \{tipMarkup\}class= " ' + Ext.baseCSSPrefix + ' column - header - inner " > ' + ' < span id="\{id\}-textEl " class= " ' + Ext.baseCSSPrefix + ' column - header - text ' + ' \{childElCls\ } " > ' + ' \{text\ } ' + ' < /span > ' + ' < tpl if="!menuDisabled " > ' + ' < div id="\{id\}-triggerEl " class= " ' + Ext.baseCSSPrefix + ' column - header - trigger ' + ' \{childElCls\}"></div > ' + ' < /tpl > ' + ' < /div > ' + ' \{%this.renderContainer(out , values)%\ } ' ]
<a href="#!/api/Ext.grid.column.Column-method-getEl" rel="Ext.grid.column.Column-method-getEl" class="docClass">Element</a>.</p>
<p>You do not normally need to specify this. For the base classes <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> and
<a href="#!/api/Ext.container.Container" rel="Ext.container.Container" class="docClass">Ext.container.Container</a>, this defaults to <strong><code>null</code></strong> which means that they will be initially rendered
with no internal structure; they render their <a href="#!/api/Ext.grid.column.Column-method-getEl" rel="Ext.grid.column.Column-method-getEl" class="docClass">Element</a> empty. The more specialized Ext JS and Sencha Touch
classes which use a more complex DOM structure, provide their own template definitions.</p>
<p>This is intended to allow the developer to create application-specific utility Components with customized
internal structure.</p>
<p>Upon rendering, any created child elements may be automatically imported into object properties using the
<a href="#!/api/Ext.grid.column.Column-cfg-renderSelectors" rel="Ext.grid.column.Column-cfg-renderSelectors" class="docClass">renderSelectors</a> and <a href="#!/api/Ext.grid.column.Column-cfg-childEls" rel="Ext.grid.column.Column-cfg-childEls" class="docClass">childEls</a> options.</p> %}
Defaults to: ['<div id="\{id\}-titleEl" \{tipMarkup\}class="' + Ext.baseCSSPrefix + 'column-header-inner">' + '<span id="\{id\}-textEl" class="' + Ext.baseCSSPrefix + 'column-header-text' + '\{childElCls\}">' + '\{text\}' + '</span>' + '<tpl if="!menuDisabled">' + '<div id="\{id\}-triggerEl" class="' + Ext.baseCSSPrefix + 'column-header-trigger' + '\{childElCls\}"></div>' + '</tpl>' + '</div>' + '\{%this.renderContainer(out,values)%\}']
*)
method renderer : _ Js.t Js.prop
* { % < p > A renderer is an ' interceptor ' method which can be used to transform data ( value , appearance , etc . )
before it is rendered . Example:</p >
< pre><code>\ {
renderer : function(value)\ {
if ( value = = = 1 ) \ {
return ' 1 person ' ;
\ }
return value + ' people ' ;
\ }
\ }
< /code></pre >
< p > Additionally a string naming an < a href="#!/api / Ext.util . Format " rel="Ext.util . Format " class="docClass">Ext.util . Format</a > method can be passed:</p >
< pre><code>\ {
renderer : ' uppercase '
\ }
< /code></pre > % }
Defaults to : [ false ]
before it is rendered. Example:</p>
<pre><code>\{
renderer: function(value)\{
if (value === 1) \{
return '1 person';
\}
return value + ' people';
\}
\}
</code></pre>
<p>Additionally a string naming an <a href="#!/api/Ext.util.Format" rel="Ext.util.Format" class="docClass">Ext.util.Format</a> method can be passed:</p>
<pre><code>\{
renderer: 'uppercase'
\}
</code></pre> %}
Defaults to: [false]
*)
method resizable_bool : bool Js.t Js.prop
* { % < p > False to prevent the column from being resizable.</p > % }
Defaults to : [ true ]
Defaults to: [true]
*)
method scope : _ Js.t Js.prop
(** {% <p>The scope to use when calling the <a href="#!/api/Ext.grid.column.Column-cfg-renderer" rel="Ext.grid.column.Column-cfg-renderer" class="docClass">renderer</a> function.</p> %}
*)
method sortable : bool Js.t Js.prop
(** {% <p>False to disable sorting of this column. Whether local/remote sorting is used is specified in
<code><a href="#!/api/Ext.data.Store-cfg-remoteSort" rel="Ext.data.Store-cfg-remoteSort" class="docClass">Ext.data.Store.remoteSort</a></code>.</p> %}
Defaults to: [true]
*)
method stateId : Js.js_string Js.t Js.prop
(** {% <p>An identifier which identifies this column uniquely within the owning grid's <a href="#!/api/Ext.grid.column.Column-cfg-stateful" rel="Ext.grid.column.Column-cfg-stateful" class="docClass">state</a>.</p>
<p>This does not have to be <em>globally</em> unique. A column's state is not saved standalone. It is encapsulated within
the owning grid's state.</p> %}
*)
method tdCls : Js.js_string Js.t Js.prop
(** {% <p>A CSS class names to apply to the table cells for this column.</p> %}
Defaults to: ['']
*)
method text : Js.js_string Js.t Js.prop
* { % < p > The header text to be used as innerHTML ( html tags are accepted ) to display in the Grid .
< strong > Note</strong > : to have a clickable header with no text displayed you can use the default of < code>&#160;</code > aka < code>&nbsp;</code>.</p > % }
Defaults to : [ ' & # 160 ; ' ]
<strong>Note</strong>: to have a clickable header with no text displayed you can use the default of <code>&#160;</code> aka <code>&nbsp;</code>.</p> %}
Defaults to: [' ']
*)
method tooltip : Js.js_string Js.t Js.prop
* { % < p > A tooltip to display for this column }
*)
method tooltipType : Js.js_string Js.t Js.prop
* { % < p > The type of < a href="#!/api / Ext.grid.column . Column - cfg - tooltip " rel="Ext.grid.column . Column - cfg - tooltip " class="docClass">tooltip</a > to use . Either ' ' for QuickTips or ' title ' for title attribute.</p > % }
Defaults to : [ " " ]
Defaults to: ["qtip"]
*)
method afterComponentLayout : ('self Js.t, Js.number Js.t -> Js.number Js.t
-> _ Js.t -> _ Js.t -> unit) Js.meth_callback Js.writeonly_prop
(** See method [t.afterComponentLayout] *)
method afterRender : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
(** See method [t.afterRender] *)
method defaultRenderer : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
(** See method [t.defaultRenderer] *)
method initComponent : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
(** See method [t.initComponent] *)
method onAdd : ('self Js.t, #Ext_Component.t Js.t -> Js.number Js.t ->
unit) Js.meth_callback Js.writeonly_prop
* See method [ ]
method onDestroy : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
(** See method [t.onDestroy] *)
method onRemove : ('self Js.t, #Ext_Component.t Js.t -> bool Js.t -> unit)
Js.meth_callback Js.writeonly_prop
(** See method [t.onRemove] *)
end
class type events =
object
inherit Ext_grid_header_Container.events
end
class type statics =
object
inherit Ext_grid_header_Container.statics
end
val of_configs : configs Js.t -> t Js.t
(** [of_configs c] casts a config object [c] to an instance of class [t] *)
val to_configs : t Js.t -> configs Js.t
(** [to_configs o] casts instance [o] of class [t] to a config object *)
| null |
https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_grid_column_Column.mli
|
ocaml
|
* {% <p>Allows addition of behavior after rendering is complete. At this stage the Component’s Element
will have been styled according to the configuration, will have had any configured CSS class
names added, and will be in the configured visibility and the configured enable state.</p> %}
* {% <p>When defined this will take precedence over the <a href="#!/api/Ext.grid.column.Column-cfg-renderer" rel="Ext.grid.column.Column-cfg-renderer" class="docClass">renderer</a> config.
This is meant to be defined in subclasses that wish to supply their own renderer.</p> %}
* {% <p>Sets the alignment of the header and rendered columns.
Possible values are: <code>'left'</code>, <code>'center'</code>, and <code>'right'</code>.</p> %}
Defaults to: ['left']
* {% <p>An optional array of sub-column definitions. This column becomes a group, and houses the columns defined in the
<code>columns</code> config.</p>
<p>Group columns may not be sortable. But they may be hideable and moveable. And you may move headers into and out
of a group. Note that if all sub columns are dragged out of a group, the group is destroyed.</p> %}
* {% <p>False to disable drag-drop reordering of this column.</p> %}
Defaults to: [true]
* {% <p>False to prevent the user from hiding this column.</p> %}
Defaults to: [true]
* {% <p>The text to render in the column visibility selection menu for this column. If not
specified, will default to the text value.</p> %}
* {% <p>The scope to use when calling the <a href="#!/api/Ext.grid.column.Column-cfg-renderer" rel="Ext.grid.column.Column-cfg-renderer" class="docClass">renderer</a> function.</p> %}
* {% <p>False to disable sorting of this column. Whether local/remote sorting is used is specified in
<code><a href="#!/api/Ext.data.Store-cfg-remoteSort" rel="Ext.data.Store-cfg-remoteSort" class="docClass">Ext.data.Store.remoteSort</a></code>.</p> %}
Defaults to: [true]
* {% <p>An identifier which identifies this column uniquely within the owning grid's <a href="#!/api/Ext.grid.column.Column-cfg-stateful" rel="Ext.grid.column.Column-cfg-stateful" class="docClass">state</a>.</p>
<p>This does not have to be <em>globally</em> unique. A column's state is not saved standalone. It is encapsulated within
the owning grid's state.</p> %}
* {% <p>A CSS class names to apply to the table cells for this column.</p> %}
Defaults to: ['']
* See method [t.afterComponentLayout]
* See method [t.afterRender]
* See method [t.defaultRenderer]
* See method [t.initComponent]
* See method [t.onDestroy]
* See method [t.onRemove]
* [of_configs c] casts a config object [c] to an instance of class [t]
* [to_configs o] casts instance [o] of class [t] to a config object
|
* This class specifies the definition for a column i ...
{ % < p > This class specifies the definition for a column inside a < a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > . It encompasses
both the grid header configuration as well as displaying data within the grid itself . If the
< a href="#!/api / Ext.grid.column . Column - cfg - columns " rel="Ext.grid.column . Column - cfg - columns " class="docClass">columns</a > configuration is specified , this column will become a column group and can
contain other columns inside . In general , this class will not be created directly , rather
an array of column configurations will be passed to the grid:</p >
< pre class='inline - example ' > < code><a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > ' , \ {
storeId:'employeeStore ' ,
fields:['firstname ' , ' lastname ' , ' seniority ' , ' dep ' , ' hired ' ] ,
data : [
\{firstname:"Michael " , lastname:"Scott " , seniority:7 , dep:"Management " , hired:"01/10/2004"\ } ,
\{firstname:"Dwight " , lastname:"Schrute " , seniority:2 , dep:"Sales " , hired:"04/01/2004"\ } ,
" , lastname:"Halpert " , seniority:3 , dep:"Sales " , hired:"02/22/2006"\ } ,
\{firstname:"Kevin " , lastname:"Malone " , seniority:4 , dep:"Accounting " , hired:"06/10/2007"\ } ,
\{firstname:"Angela " , " , seniority:5 , dep:"Accounting " , hired:"10/21/2008"\ }
]
\ } ) ;
< a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.grid . Panel " rel="Ext.grid . Panel " class="docClass">Ext.grid . Panel</a > ' , \ {
title : ' Column Demo ' ,
store : < a href="#!/api / Ext.data . StoreManager - method - lookup " rel="Ext.data . StoreManager - method - lookup " class="docClass">Ext.data . StoreManager.lookup</a>('employeeStore ' ) ,
columns : [
\{text : ' First Name ' , dataIndex:'firstname'\ } ,
\{text : ' Last Name ' , dataIndex:'lastname'\ } ,
\{text : ' Hired Month ' , dataIndex:'hired ' , xtype:'datecolumn ' , format:'M'\ } ,
\{text : ' Department ( Yrs ) ' , xtype:'templatecolumn ' , tpl:'\{dep\ } ( \{seniority\})'\ }
] ,
width : 400 ,
forceFit : true ,
renderTo : < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( )
\ } ) ;
< /code></pre >
< h1 > Convenience Subclasses</h1 >
< p > There are several column subclasses that provide default rendering for various data types</p >
< ul >
< li><a href="#!/api / Ext.grid.column . Action " rel="Ext.grid.column . Action " class="docClass">Ext.grid.column . > : Renders icons that can respond to click events inline</li >
< li><a href="#!/api / Ext.grid.column . Boolean " rel="Ext.grid.column . Boolean " class="docClass">Ext.grid.column . Boolean</a > : Renders for boolean values</li >
< li><a href="#!/api / Ext.grid.column . Date " rel="Ext.grid.column . Date " class="docClass">Ext.grid.column . Date</a > : Renders for date values</li >
< li><a href="#!/api / Ext.grid.column . Number " rel="Ext.grid.column . Number " class="docClass">Ext.grid.column . > : Renders for numeric values</li >
< li><a href="#!/api / Ext.grid.column . Template " rel="Ext.grid.column . Template " class="docClass">Ext.grid.column . Template</a > : Renders a value using an < a href="#!/api / Ext . XTemplate " rel="Ext . XTemplate " class="docClass">Ext . XTemplate</a > using the record data</li >
< /ul >
< h1 > Setting Sizes</h1 >
< p > The columns are laid out by a < a href="#!/api / Ext.layout.container . HBox " . HBox " class="docClass">Ext.layout.container . HBox</a > layout , so a column can either
be given an explicit width value or a flex configuration . If no width is specified the grid will
automatically the size the column to 100px . For column groups , the size is calculated by measuring
the width of the child columns , so a width option should not be specified in that case.</p >
< h1 > Header Options</h1 >
< ul >
< li><a href="#!/api / Ext.grid.column . Column - cfg - text " rel="Ext.grid.column . Column - cfg - text " class="docClass">text</a > : Sets the header text for the column</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - sortable " rel="Ext.grid.column . Column - cfg - sortable " class="docClass">sortable</a > : Specifies whether the column can be sorted by clicking the header or using the column menu</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - hideable " rel="Ext.grid.column . Column - cfg - hideable " class="docClass">hideable</a > : Specifies whether the column can be hidden using the column menu</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - menuDisabled " rel="Ext.grid.column . Column - cfg - menuDisabled " class="docClass">menuDisabled</a > : Disables the column header menu</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - draggable " rel="Ext.grid.column . Column - cfg - draggable " class="docClass">draggable</a > : Specifies whether the column header can be reordered by dragging</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - groupable " rel="Ext.grid.column . Column - cfg - groupable " class="docClass">groupable</a > : Specifies whether the grid can be grouped by the column dataIndex . See also < a href="#!/api / Ext.grid.feature . Grouping " rel="Ext.grid.feature . Grouping " class="docClass">Ext.grid.feature . Grouping</a></li >
< /ul >
< h1 > Data Options</h1 >
< ul >
< li><a href="#!/api / Ext.grid.column . Column - cfg - dataIndex " rel="Ext.grid.column . Column - cfg - dataIndex " class="docClass">dataIndex</a > : The dataIndex is the field in the underlying < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > to use as the value for the column.</li >
< li><a href="#!/api / Ext.grid.column . Column - cfg - renderer " rel="Ext.grid.column . Column - cfg - renderer " class="docClass">renderer</a > : Allows the underlying store value to be transformed before being displayed in the grid</li >
< /ul > % }
{% <p>This class specifies the definition for a column inside a <a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>. It encompasses
both the grid header configuration as well as displaying data within the grid itself. If the
<a href="#!/api/Ext.grid.column.Column-cfg-columns" rel="Ext.grid.column.Column-cfg-columns" class="docClass">columns</a> configuration is specified, this column will become a column group and can
contain other columns inside. In general, this class will not be created directly, rather
an array of column configurations will be passed to the grid:</p>
<pre class='inline-example '><code><a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Ext.data.Store</a>', \{
storeId:'employeeStore',
fields:['firstname', 'lastname', 'seniority', 'dep', 'hired'],
data:[
\{firstname:"Michael", lastname:"Scott", seniority:7, dep:"Management", hired:"01/10/2004"\},
\{firstname:"Dwight", lastname:"Schrute", seniority:2, dep:"Sales", hired:"04/01/2004"\},
\{firstname:"Jim", lastname:"Halpert", seniority:3, dep:"Sales", hired:"02/22/2006"\},
\{firstname:"Kevin", lastname:"Malone", seniority:4, dep:"Accounting", hired:"06/10/2007"\},
\{firstname:"Angela", lastname:"Martin", seniority:5, dep:"Accounting", hired:"10/21/2008"\}
]
\});
<a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.grid.Panel" rel="Ext.grid.Panel" class="docClass">Ext.grid.Panel</a>', \{
title: 'Column Demo',
store: <a href="#!/api/Ext.data.StoreManager-method-lookup" rel="Ext.data.StoreManager-method-lookup" class="docClass">Ext.data.StoreManager.lookup</a>('employeeStore'),
columns: [
\{text: 'First Name', dataIndex:'firstname'\},
\{text: 'Last Name', dataIndex:'lastname'\},
\{text: 'Hired Month', dataIndex:'hired', xtype:'datecolumn', format:'M'\},
\{text: 'Department (Yrs)', xtype:'templatecolumn', tpl:'\{dep\} (\{seniority\})'\}
],
width: 400,
forceFit: true,
renderTo: <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>()
\});
</code></pre>
<h1>Convenience Subclasses</h1>
<p>There are several column subclasses that provide default rendering for various data types</p>
<ul>
<li><a href="#!/api/Ext.grid.column.Action" rel="Ext.grid.column.Action" class="docClass">Ext.grid.column.Action</a>: Renders icons that can respond to click events inline</li>
<li><a href="#!/api/Ext.grid.column.Boolean" rel="Ext.grid.column.Boolean" class="docClass">Ext.grid.column.Boolean</a>: Renders for boolean values</li>
<li><a href="#!/api/Ext.grid.column.Date" rel="Ext.grid.column.Date" class="docClass">Ext.grid.column.Date</a>: Renders for date values</li>
<li><a href="#!/api/Ext.grid.column.Number" rel="Ext.grid.column.Number" class="docClass">Ext.grid.column.Number</a>: Renders for numeric values</li>
<li><a href="#!/api/Ext.grid.column.Template" rel="Ext.grid.column.Template" class="docClass">Ext.grid.column.Template</a>: Renders a value using an <a href="#!/api/Ext.XTemplate" rel="Ext.XTemplate" class="docClass">Ext.XTemplate</a> using the record data</li>
</ul>
<h1>Setting Sizes</h1>
<p>The columns are laid out by a <a href="#!/api/Ext.layout.container.HBox" rel="Ext.layout.container.HBox" class="docClass">Ext.layout.container.HBox</a> layout, so a column can either
be given an explicit width value or a flex configuration. If no width is specified the grid will
automatically the size the column to 100px. For column groups, the size is calculated by measuring
the width of the child columns, so a width option should not be specified in that case.</p>
<h1>Header Options</h1>
<ul>
<li><a href="#!/api/Ext.grid.column.Column-cfg-text" rel="Ext.grid.column.Column-cfg-text" class="docClass">text</a>: Sets the header text for the column</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-sortable" rel="Ext.grid.column.Column-cfg-sortable" class="docClass">sortable</a>: Specifies whether the column can be sorted by clicking the header or using the column menu</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-hideable" rel="Ext.grid.column.Column-cfg-hideable" class="docClass">hideable</a>: Specifies whether the column can be hidden using the column menu</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-menuDisabled" rel="Ext.grid.column.Column-cfg-menuDisabled" class="docClass">menuDisabled</a>: Disables the column header menu</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-draggable" rel="Ext.grid.column.Column-cfg-draggable" class="docClass">draggable</a>: Specifies whether the column header can be reordered by dragging</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-groupable" rel="Ext.grid.column.Column-cfg-groupable" class="docClass">groupable</a>: Specifies whether the grid can be grouped by the column dataIndex. See also <a href="#!/api/Ext.grid.feature.Grouping" rel="Ext.grid.feature.Grouping" class="docClass">Ext.grid.feature.Grouping</a></li>
</ul>
<h1>Data Options</h1>
<ul>
<li><a href="#!/api/Ext.grid.column.Column-cfg-dataIndex" rel="Ext.grid.column.Column-cfg-dataIndex" class="docClass">dataIndex</a>: The dataIndex is the field in the underlying <a href="#!/api/Ext.data.Store" rel="Ext.data.Store" class="docClass">Ext.data.Store</a> to use as the value for the column.</li>
<li><a href="#!/api/Ext.grid.column.Column-cfg-renderer" rel="Ext.grid.column.Column-cfg-renderer" class="docClass">renderer</a>: Allows the underlying store value to be transformed before being displayed in the grid</li>
</ul> %}
*)
class type t =
object('self)
inherit Ext_grid_header_Container.t
method isColumn : bool Js.t Js.readonly_prop
* { % < p > Set in this class to identify , at runtime , instances which are not instances of the
HeaderContainer base class , but are in fact simple column > % }
Defaults to : [ true ]
HeaderContainer base class, but are in fact simple column headers.</p> %}
Defaults to: [true]
*)
method textEl : Ext_dom_Element.t Js.t Js.prop
* { % < p > Element that contains the text in column > % }
*)
method triggerEl : Ext_dom_Element.t Js.t Js.prop
* { % < p > Element that acts as button for column header dropdown > % }
*)
method afterComponentLayout : Js.number Js.t -> Js.number Js.t -> _ Js.t ->
_ Js.t -> unit Js.meth
* { % < p > private
Inform the header container about the resize</p >
< p > Called by the layout system after the Component has been laid out.</p > % }
{ b Parameters } :
{ ul { - width : [ Js.number Js.t ]
{ % < p > The width that was > % }
}
{ - height : [ Js.number Js.t ]
{ % < p > The height that was > % }
}
{ - oldWidth : [ _ Js.t ]
{ % < p > The old width , or < code > undefined</code > if this was the initial layout.</p > % }
}
{ - oldHeight : [ _ Js.t ]
{ % < p > The old height , or < code > undefined</code > if this was the initial layout.</p > % }
}
}
Inform the header container about the resize</p>
<p>Called by the layout system after the Component has been laid out.</p> %}
{b Parameters}:
{ul {- width: [Js.number Js.t]
{% <p>The width that was set</p> %}
}
{- height: [Js.number Js.t]
{% <p>The height that was set</p> %}
}
{- oldWidth: [_ Js.t]
{% <p>The old width, or <code>undefined</code> if this was the initial layout.</p> %}
}
{- oldHeight: [_ Js.t]
{% <p>The old height, or <code>undefined</code> if this was the initial layout.</p> %}
}
}
*)
method afterRender : unit Js.meth
method autoSize : _ Js.t -> unit Js.meth
* { % < p > Sizes this Column to fit the max content width .
< em > Note that group columns shrinkwrap around the size of leaf columns . Auto sizing a group column
autosizes descendant > % }
{ b Parameters } :
{ ul { - the : [ _ Js.t ]
{ % < p > header ( or index of header ) to auto size.</p > % }
}
}
<em>Note that group columns shrinkwrap around the size of leaf columns. Auto sizing a group column
autosizes descendant leaf columns.</em></p> %}
{b Parameters}:
{ul {- the: [_ Js.t]
{% <p>header (or index of header) to auto size.</p> %}
}
}
*)
method defaultRenderer : unit Js.meth
method getEditor : _ Js.t -> _ Js.t -> #Ext_form_field_Field.t Js.t Js.meth
* { % < p > Retrieves the editing field for editing associated with this header . Returns false if there is no field
associated with the Header the method will return false . If the field has not been instantiated it will be
created . Note : These methods only have an implementation if an Editing plugin has been enabled on the grid.</p > % }
{ b Parameters } :
{ ul { - record : [ _ Js.t ]
{ % < p > The < a href="#!/api / Ext.data . Model " rel="Ext.data . Model " class="docClass">Model</a > instance being edited.</p > % }
}
{ - defaultField : [ _ Js.t ]
{ % < p > An object representing a default field to be created</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_form_field_Field.t Js.t ] { % < p > field</p > % }
}
}
associated with the Header the method will return false. If the field has not been instantiated it will be
created. Note: These methods only have an implementation if an Editing plugin has been enabled on the grid.</p> %}
{b Parameters}:
{ul {- record: [_ Js.t]
{% <p>The <a href="#!/api/Ext.data.Model" rel="Ext.data.Model" class="docClass">Model</a> instance being edited.</p> %}
}
{- defaultField: [_ Js.t]
{% <p>An object representing a default field to be created</p> %}
}
}
{b Returns}:
{ul {- [#Ext_form_field_Field.t Js.t] {% <p>field</p> %}
}
}
*)
method getIndex : Js.number Js.t Js.meth
* { % < p > Returns the index of this column only if this column is a base level Column . If it
is a group column , it returns < code > false</code>.</p > % }
is a group column, it returns <code>false</code>.</p> %}
*)
method getSortParam : Js.js_string Js.t Js.meth
* { % < p > Returns the parameter to sort upon when sorting this header . By default this returns the dataIndex and will not
need to be overriden in most cases.</p > % }
need to be overriden in most cases.</p> %}
*)
method getVisibleIndex : Js.number Js.t Js.meth
* { % < p > Returns the index of this column in the list of < em > visible</em > columns only if this column is a base level Column . If it
is a group column , it returns < code > false</code>.</p > % }
is a group column, it returns <code>false</code>.</p> %}
*)
method hide_column : _ Js.t Js.optdef -> _ Js.callback Js.optdef ->
_ Js.t Js.optdef -> #Ext_Component.t Js.t Js.meth
* { % < p > Hides this Component , setting it to invisible using the configured < a href="#!/api / Ext.grid.column . Column - cfg - hideMode " rel="Ext.grid.column . Column - cfg - hideMode " class="docClass">hideMode</a>.</p > % }
{ b Parameters } :
{ ul { - animateTarget : [ _ ] ( optional )
{ % < p><strong > only valid for < a href="#!/api / Ext.grid.column . Column - cfg - floating " rel="Ext.grid.column . Column - cfg - floating " class="docClass">floating</a > Components
such as < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Window</a > s or < a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">ToolTip</a > s , or regular Components which have
been configured with < code > floating : true</code>.</strong > . The target to which the Component should animate while hiding.</p > % }
Defaults to : null
}
{ - callback : [ _ Js.callback ] ( optional )
{ % < p > A callback function to call after the Component is hidden.</p > % }
}
{ - scope : [ _ ] ( optional )
{ % < p > The scope ( < code > this</code > reference ) in which the callback is executed .
Defaults to this Component.</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_Component.t Js.t ] { % < p > this</p > % }
}
}
{b Parameters}:
{ul {- animateTarget: [_ Js.t] (optional)
{% <p><strong>only valid for <a href="#!/api/Ext.grid.column.Column-cfg-floating" rel="Ext.grid.column.Column-cfg-floating" class="docClass">floating</a> Components
such as <a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Window</a>s or <a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">ToolTip</a>s, or regular Components which have
been configured with <code>floating: true</code>.</strong>. The target to which the Component should animate while hiding.</p> %}
Defaults to: null
}
{- callback: [_ Js.callback] (optional)
{% <p>A callback function to call after the Component is hidden.</p> %}
}
{- scope: [_ Js.t] (optional)
{% <p>The scope (<code>this</code> reference) in which the callback is executed.
Defaults to this Component.</p> %}
}
}
{b Returns}:
{ul {- [#Ext_Component.t Js.t] {% <p>this</p> %}
}
}
*)
method initComponent : unit Js.meth
* { % < p > The initComponent template method is an important initialization step for a Component . It is intended to be
implemented by each subclass of < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > to provide any needed constructor logic . The
initComponent method of the class being created is called first , with each initComponent method
up the hierarchy to < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > being called thereafter . This makes it easy to implement and ,
if needed , override the constructor logic of the Component at any step in the hierarchy.</p >
< p > The initComponent method < strong > must</strong > contain a call to < a href="#!/api / Ext . Base - method - callParent " rel="Ext . Base - method - callParent " class="docClass">callParent</a > in order
to ensure that the parent class ' initComponent method is also called.</p >
< p > All config options passed to the constructor are applied to < code > this</code > before initComponent is called ,
so you can simply access them with < code > >
< p > The following example demonstrates using a dynamic string for the text of a button at the time of
instantiation of the class.</p >
< pre><code><a href="#!/api / Ext - method - define " rel="Ext - method - define " class="docClass">Ext.define</a>('DynamicButtonText ' , \ {
extend : ' < a href="#!/api / Ext.button . Button " rel="Ext.button . Button " class="docClass">Ext.button . > ' ,
initComponent : function ( ) \ {
this.text = new Date ( ) ;
this.renderTo = < a href="#!/api / Ext - method - getBody " rel="Ext - method - getBody " class="docClass">Ext.getBody</a > ( ) ;
this.callParent ( ) ;
\ }
\ } ) ;
< a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a>(function ( ) \ {
< a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('DynamicButtonText ' ) ;
\ } ) ;
< /code></pre > % }
implemented by each subclass of <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> to provide any needed constructor logic. The
initComponent method of the class being created is called first, with each initComponent method
up the hierarchy to <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> being called thereafter. This makes it easy to implement and,
if needed, override the constructor logic of the Component at any step in the hierarchy.</p>
<p>The initComponent method <strong>must</strong> contain a call to <a href="#!/api/Ext.Base-method-callParent" rel="Ext.Base-method-callParent" class="docClass">callParent</a> in order
to ensure that the parent class' initComponent method is also called.</p>
<p>All config options passed to the constructor are applied to <code>this</code> before initComponent is called,
so you can simply access them with <code>this.someOption</code>.</p>
<p>The following example demonstrates using a dynamic string for the text of a button at the time of
instantiation of the class.</p>
<pre><code><a href="#!/api/Ext-method-define" rel="Ext-method-define" class="docClass">Ext.define</a>('DynamicButtonText', \{
extend: '<a href="#!/api/Ext.button.Button" rel="Ext.button.Button" class="docClass">Ext.button.Button</a>',
initComponent: function() \{
this.text = new Date();
this.renderTo = <a href="#!/api/Ext-method-getBody" rel="Ext-method-getBody" class="docClass">Ext.getBody</a>();
this.callParent();
\}
\});
<a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(function() \{
<a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('DynamicButtonText');
\});
</code></pre> %}
*)
method initRenderData : _ Js.t Js.meth
* { % < p > Initialized the renderData to be used when rendering the renderTpl.</p > % }
{ b Returns } :
{ ul { - [ _ Js.t ]
{ % < p > Object with keys and values that are going to be applied to the renderTpl</p > % }
}
}
{b Returns}:
{ul {- [_ Js.t]
{% <p>Object with keys and values that are going to be applied to the renderTpl</p> %}
}
}
*)
method isHideable : unit Js.meth
* { % < p > Determines whether the UI should be allowed to offer an option to hide this column.</p >
< p > A column may < em > not</em > be hidden if to do so would leave the grid with no visible >
< p > This is used to determine the enabled / disabled state of header hide menu items.</p > % }
<p>A column may <em>not</em> be hidden if to do so would leave the grid with no visible columns.</p>
<p>This is used to determine the enabled/disabled state of header hide menu items.</p> %}
*)
method isLockable : unit Js.meth
* { % < p > Determines whether the UI should be allowed to offer an option to lock or unlock this column . Note
that this includes dragging a column into the opposite side of a < a href="#!/api / Ext.panel . Table - cfg - enableLocking " rel="Ext.panel . Table - cfg - enableLocking " class="docClass">lockable</a > grid.</p >
< p > A column may < em > not</em > be moved from one side to the other of a < a href="#!/api / Ext.panel . Table - cfg - enableLocking " rel="Ext.panel . Table - cfg - enableLocking " class="docClass">lockable</a > grid
if to do so would leave one side with no visible >
< p > This is used to determine the enabled / disabled state of the lock / unlock
menu item used in < a href="#!/api / Ext.panel . Table - cfg - enableLocking " rel="Ext.panel . Table - cfg - enableLocking " class="docClass">lockable</a > grids , and to determine dropppabilty when dragging a header.</p > % }
that this includes dragging a column into the opposite side of a <a href="#!/api/Ext.panel.Table-cfg-enableLocking" rel="Ext.panel.Table-cfg-enableLocking" class="docClass">lockable</a> grid.</p>
<p>A column may <em>not</em> be moved from one side to the other of a <a href="#!/api/Ext.panel.Table-cfg-enableLocking" rel="Ext.panel.Table-cfg-enableLocking" class="docClass">lockable</a> grid
if to do so would leave one side with no visible columns.</p>
<p>This is used to determine the enabled/disabled state of the lock/unlock
menu item used in <a href="#!/api/Ext.panel.Table-cfg-enableLocking" rel="Ext.panel.Table-cfg-enableLocking" class="docClass">lockable</a> grids, and to determine dropppabilty when dragging a header.</p> %}
*)
method onAdd : #Ext_Component.t Js.t -> Js.number Js.t -> unit Js.meth
* { % < p > This method is invoked after a new Component has been added . It
is passed the Component which has been added . This method may
be used to update any internal structure which may depend upon
the state of the child items.</p > % }
{ b Parameters } :
{ ul { - component : [ # Ext_Component.t Js.t ]
}
{ - position : [ Js.number Js.t ]
}
}
is passed the Component which has been added. This method may
be used to update any internal structure which may depend upon
the state of the child items.</p> %}
{b Parameters}:
{ul {- component: [#Ext_Component.t Js.t]
}
{- position: [Js.number Js.t]
}
}
*)
method onDestroy : unit Js.meth
* { % < p > Allows addition of behavior to the destroy operation .
After calling the superclass 's onDestroy , the Component will be destroyed.</p > % }
After calling the superclass's onDestroy, the Component will be destroyed.</p> %}
*)
method onRemove : #Ext_Component.t Js.t -> bool Js.t -> unit Js.meth
* { % < p > This method is invoked after a new Component has been
removed . It is passed the Component which has been
removed . This method may be used to update any internal
structure which may depend upon the state of the child items.</p > % }
{ b Parameters } :
{ ul { - component : [ # Ext_Component.t Js.t ]
}
{ - autoDestroy : [ bool Js.t ]
}
}
removed. It is passed the Component which has been
removed. This method may be used to update any internal
structure which may depend upon the state of the child items.</p> %}
{b Parameters}:
{ul {- component: [#Ext_Component.t Js.t]
}
{- autoDestroy: [bool Js.t]
}
}
*)
method setEditor : _ Js.t -> unit Js.meth
* { % < p > Sets the form field to be used for editing . Note : This method only has an implementation if an Editing plugin has
been enabled on the grid.</p > % }
{ b Parameters } :
{ ul { - field : [ _ Js.t ]
{ % < p > An object representing a field to be created . If no xtype is specified a ' textfield ' is
assumed.</p > % }
}
}
been enabled on the grid.</p> %}
{b Parameters}:
{ul {- field: [_ Js.t]
{% <p>An object representing a field to be created. If no xtype is specified a 'textfield' is
assumed.</p> %}
}
}
*)
method setText : Js.js_string Js.t -> unit Js.meth
* { % < p > Sets the header text for this > % }
{ b Parameters } :
{ ul { - text : [ Js.js_string Js.t ]
{ % < p > The header to display on this > % }
}
}
{b Parameters}:
{ul {- text: [Js.js_string Js.t]
{% <p>The header to display on this Column.</p> %}
}
}
*)
method show_column : _ Js.t Js.optdef -> _ Js.callback Js.optdef ->
_ Js.t Js.optdef -> #Ext_Component.t Js.t Js.meth
* { % < p > Shows this Component , rendering it first if < a href="#!/api / Ext.grid.column . Column - cfg - autoRender " rel="Ext.grid.column . Column - cfg - autoRender " class="docClass">autoRender</a > or < a href="#!/api / Ext.grid.column . Column - cfg - floating " rel="Ext.grid.column . Column - cfg - floating " class="docClass">floating</a > are < code > true</code>.</p >
< p > After being shown , a < a href="#!/api / Ext.grid.column . Column - cfg - floating " rel="Ext.grid.column . Column - cfg - floating " class="docClass">floating</a > Component ( such as a < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ) , is activated it and
brought to the front of its < a href="#!/api / Ext.grid.column . Column - property - zIndexManager " rel="Ext.grid.column . Column - property - zIndexManager " class="docClass">z - index stack</a>.</p > % }
{ b Parameters } :
{ ul { - animateTarget : [ _ ] ( optional )
{ % < p><strong > only valid for < a href="#!/api / Ext.grid.column . Column - cfg - floating " rel="Ext.grid.column . Column - cfg - floating " class="docClass">floating</a > Components such as < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Window</a > s or < a href="#!/api / Ext.tip . ToolTip " rel="Ext.tip . ToolTip " class="docClass">ToolTip</a > s , or regular Components which have been configured
with < code > floating : true</code>.</strong > The target from which the Component should animate from while opening.</p > % }
Defaults to : null
}
{ - callback : [ _ Js.callback ] ( optional )
{ % < p > A callback function to call after the Component is displayed .
Only necessary if animation was specified.</p > % }
}
{ - scope : [ _ ] ( optional )
{ % < p > The scope ( < code > this</code > reference ) in which the callback is executed .
Defaults to this Component.</p > % }
}
}
{ b Returns } :
{ ul { - [ # Ext_Component.t Js.t ] { % < p > this</p > % }
}
}
<p>After being shown, a <a href="#!/api/Ext.grid.column.Column-cfg-floating" rel="Ext.grid.column.Column-cfg-floating" class="docClass">floating</a> Component (such as a <a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>), is activated it and
brought to the front of its <a href="#!/api/Ext.grid.column.Column-property-zIndexManager" rel="Ext.grid.column.Column-property-zIndexManager" class="docClass">z-index stack</a>.</p> %}
{b Parameters}:
{ul {- animateTarget: [_ Js.t] (optional)
{% <p><strong>only valid for <a href="#!/api/Ext.grid.column.Column-cfg-floating" rel="Ext.grid.column.Column-cfg-floating" class="docClass">floating</a> Components such as <a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Window</a>s or <a href="#!/api/Ext.tip.ToolTip" rel="Ext.tip.ToolTip" class="docClass">ToolTip</a>s, or regular Components which have been configured
with <code>floating: true</code>.</strong> The target from which the Component should animate from while opening.</p> %}
Defaults to: null
}
{- callback: [_ Js.callback] (optional)
{% <p>A callback function to call after the Component is displayed.
Only necessary if animation was specified.</p> %}
}
{- scope: [_ Js.t] (optional)
{% <p>The scope (<code>this</code> reference) in which the callback is executed.
Defaults to this Component.</p> %}
}
}
{b Returns}:
{ul {- [#Ext_Component.t Js.t] {% <p>this</p> %}
}
}
*)
end
class type configs =
object('self)
inherit Ext_grid_header_Container.configs
method align : Js.js_string Js.t Js.prop
method baseCls : Js.js_string Js.t Js.prop
* { % < p > The base CSS class to apply to this component 's element . This will also be prepended to elements within this
component like Panel 's body will get a class < code > x - panel - body</code > . This means that if you create a subclass of Panel , and
you want it to get all the Panels styling for the element and the body , you leave the < code > baseCls</code > < code > x - panel</code > and use
< code > componentCls</code > to add specific styling for this component.</p > % }
Defaults to : [ Ext.baseCSSPrefix + ' column - header ' ]
component like Panel's body will get a class <code>x-panel-body</code>. This means that if you create a subclass of Panel, and
you want it to get all the Panels styling for the element and the body, you leave the <code>baseCls</code> <code>x-panel</code> and use
<code>componentCls</code> to add specific styling for this component.</p> %}
Defaults to: [Ext.baseCSSPrefix + 'column-header']
*)
method columns : _ Js.t Js.js_array Js.t Js.prop
method componentLayout : _ Js.t Js.prop
* { % < p > The sizing and positioning of a Component 's internal Elements is the responsibility of the Component 's layout
manager which sizes a Component 's internal structure in response to the Component being sized.</p >
< p > Generally , developers will not use this configuration as all provided Components which need their internal
elements sizing ( Such as < a href="#!/api / Ext.form.field . Base " rel="Ext.form.field . Base " class="docClass">input fields</a > ) come with their own componentLayout managers.</p >
< p > The < a href="#!/api / Ext.layout.container . Auto " rel="Ext.layout.container . Auto " class="docClass">default layout manager</a > will be used on instances of the base < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a >
class which simply sizes the Component 's encapsulating element to the height and width specified in the
< a href="#!/api / Ext.grid.column . Column - method - setSize " rel="Ext.grid.column . Column - method - setSize " class="docClass">setSize</a > method.</p > % }
Defaults to : [ ' columncomponent ' ]
manager which sizes a Component's internal structure in response to the Component being sized.</p>
<p>Generally, developers will not use this configuration as all provided Components which need their internal
elements sizing (Such as <a href="#!/api/Ext.form.field.Base" rel="Ext.form.field.Base" class="docClass">input fields</a>) come with their own componentLayout managers.</p>
<p>The <a href="#!/api/Ext.layout.container.Auto" rel="Ext.layout.container.Auto" class="docClass">default layout manager</a> will be used on instances of the base <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a>
class which simply sizes the Component's encapsulating element to the height and width specified in the
<a href="#!/api/Ext.grid.column.Column-method-setSize" rel="Ext.grid.column.Column-method-setSize" class="docClass">setSize</a> method.</p> %}
Defaults to: ['columncomponent']
*)
method dataIndex : Js.js_string Js.t Js.prop
* { % < p > The name of the field in the grid 's < a href="#!/api / Ext.data . Store " rel="Ext.data . Store " class="docClass">Ext.data . Store</a > 's < a href="#!/api / Ext.data . Model " rel="Ext.data . Model " class="docClass">Ext.data . Model</a > definition from
which to draw the column 's value . < strong > > % }
which to draw the column's value. <strong>Required.</strong></p> %}
*)
method detachOnRemove : bool Js.t Js.prop
* { % < p > So that when removing from group headers which are then empty and then get destroyed , there 's no child >
< p > True to move any component to the < a href="#!/api / Ext - method - getDetachedBody " rel="Ext - method - getDetachedBody " class="docClass">detachedBody</a > when the component is
removed from this container . This option is only applicable when the component is not destroyed while
being removed , see < a href="#!/api / Ext.grid.column . Column - cfg - autoDestroy " rel="Ext.grid.column . Column - cfg - autoDestroy " class="docClass">autoDestroy</a > and < a href="#!/api / Ext.grid.column . Column - method - remove " rel="Ext.grid.column . Column - method - remove " class="docClass">remove</a > . If this option is set to false , the DOM
of the component will remain in the current place until it is explicitly moved.</p > % }
Defaults to : [ true ]
<p>True to move any component to the <a href="#!/api/Ext-method-getDetachedBody" rel="Ext-method-getDetachedBody" class="docClass">detachedBody</a> when the component is
removed from this container. This option is only applicable when the component is not destroyed while
being removed, see <a href="#!/api/Ext.grid.column.Column-cfg-autoDestroy" rel="Ext.grid.column.Column-cfg-autoDestroy" class="docClass">autoDestroy</a> and <a href="#!/api/Ext.grid.column.Column-method-remove" rel="Ext.grid.column.Column-method-remove" class="docClass">remove</a>. If this option is set to false, the DOM
of the component will remain in the current place until it is explicitly moved.</p> %}
Defaults to: [true]
*)
method draggable : bool Js.t Js.prop
method editRenderer : _ Js.callback Js.prop
* { % < p > A renderer to be used in conjunction with < a href="#!/api / Ext.grid.plugin . RowEditing " rel="Ext.grid.plugin . RowEditing " class="docClass">RowEditing</a > . This renderer is used to
display a custom value for non - editable fields.</p > % }
Defaults to : [ false ]
display a custom value for non-editable fields.</p> %}
Defaults to: [false]
*)
method editor : _ Js.t Js.prop
* { % < p > An optional xtype or config object for a < a href="#!/api / Ext.form.field . Field " rel="Ext.form.field . Field " class="docClass">Field</a > to use for editing .
Only applicable if the grid is using an < a href="#!/api / Ext.grid.plugin . Editing " rel="Ext.grid.plugin . Editing " class="docClass">Editing</a > plugin.</p > % }
Only applicable if the grid is using an <a href="#!/api/Ext.grid.plugin.Editing" rel="Ext.grid.plugin.Editing" class="docClass">Editing</a> plugin.</p> %}
*)
method emptyCellText : Js.js_string Js.t Js.prop
* { % < p > The text to diplay in empty cells ( cells with a value of < code > undefined</code > , < code , or < code>''</code>).</p >
< p > Defaults to < code>&#160;</code > aka < code>&nbsp;</code>.</p > % }
Defaults to : [ undefined ]
<p>Defaults to <code>&#160;</code> aka <code>&nbsp;</code>.</p> %}
Defaults to: [undefined]
*)
method groupable : bool Js.t Js.prop
* { % < p > If the grid uses a < a href="#!/api / Ext.grid.feature . Grouping " rel="Ext.grid.feature . Grouping " class="docClass">Ext.grid.feature . > , this option may be used to disable the header menu
item to group by the column selected . By default , the header menu group option is enabled . Set to false to
disable ( but still show ) the group option in the header menu for the column.</p > % }
item to group by the column selected. By default, the header menu group option is enabled. Set to false to
disable (but still show) the group option in the header menu for the column.</p> %}
*)
method hideable : bool Js.t Js.prop
method lockable : bool Js.t Js.prop
* { % < p > If the grid is configured with < a href="#!/api / Ext.panel . Table - cfg - enableLocking " rel="Ext.panel . Table - cfg - enableLocking " class="docClass">enableLocking</a > , or has columns which are
configured with a < a href="#!/api / Ext.grid.column . Column - cfg - locked " rel="Ext.grid.column . Column - cfg - locked " class="docClass">locked</a > value , this option may be used to disable user - driven locking or unlocking
of this column . This column will remain in the side into which its own < a href="#!/api / Ext.grid.column . Column - cfg - locked " rel="Ext.grid.column . Column - cfg - locked " class="docClass">locked</a > configuration placed it.</p > % }
configured with a <a href="#!/api/Ext.grid.column.Column-cfg-locked" rel="Ext.grid.column.Column-cfg-locked" class="docClass">locked</a> value, this option may be used to disable user-driven locking or unlocking
of this column. This column will remain in the side into which its own <a href="#!/api/Ext.grid.column.Column-cfg-locked" rel="Ext.grid.column.Column-cfg-locked" class="docClass">locked</a> configuration placed it.</p> %}
*)
method locked : bool Js.t Js.prop
* { % < p > True to lock this column in place . Implicitly enables locking on the grid .
See also < a href="#!/api / Ext.grid . Panel - cfg - enableLocking " rel="Ext.grid . Panel - cfg - enableLocking " class="docClass">Ext.grid . Panel.enableLocking</a>.</p > % }
Defaults to : [ false ]
See also <a href="#!/api/Ext.grid.Panel-cfg-enableLocking" rel="Ext.grid.Panel-cfg-enableLocking" class="docClass">Ext.grid.Panel.enableLocking</a>.</p> %}
Defaults to: [false]
*)
method menuDisabled : bool Js.t Js.prop
* { % < p > True to disable the column header menu containing sort / hide options.</p > % }
Defaults to : [ false ]
Defaults to: [false]
*)
method menuText : Js.js_string Js.t Js.prop
method renderTpl : _ Js.t Js.prop
* { % < p > An < a href="#!/api / Ext . XTemplate " rel="Ext . XTemplate " class="docClass">XTemplate</a > used to create the internal structure inside this Component 's encapsulating
< a href="#!/api / Ext.grid.column . Column - method - getEl " rel="Ext.grid.column . Column - method - getEl " class="docClass">Element</a>.</p >
< p > You do not normally need to specify this . For the base classes < a href="#!/api / Ext . Component " rel="Ext . Component " class="docClass">Ext . Component</a > and
< a href="#!/api / Ext.container . Container " rel="Ext.container . Container " class="docClass">Ext.container . Container</a > , this defaults to < strong><code > null</code></strong > which means that they will be initially rendered
with no internal structure ; they render their < a href="#!/api / Ext.grid.column . Column - method - getEl " rel="Ext.grid.column . Column - method - getEl " class="docClass">Element</a > empty . The more specialized Ext JS and Sencha Touch
classes which use a more complex DOM structure , provide their own template definitions.</p >
< p > This is intended to allow the developer to create application - specific utility Components with customized
internal structure.</p >
< p > Upon rendering , any created child elements may be automatically imported into object properties using the
< a href="#!/api / Ext.grid.column . Column - cfg - renderSelectors " rel="Ext.grid.column . Column - cfg - renderSelectors " class="docClass">renderSelectors</a > and < a href="#!/api / Ext.grid.column . Column - cfg - childEls " rel="Ext.grid.column . Column - cfg - childEls " class="docClass">childEls</a > options.</p > % }
Defaults to : [ ' < div id="\{id\}-titleEl " \{tipMarkup\}class= " ' + Ext.baseCSSPrefix + ' column - header - inner " > ' + ' < span id="\{id\}-textEl " class= " ' + Ext.baseCSSPrefix + ' column - header - text ' + ' \{childElCls\ } " > ' + ' \{text\ } ' + ' < /span > ' + ' < tpl if="!menuDisabled " > ' + ' < div id="\{id\}-triggerEl " class= " ' + Ext.baseCSSPrefix + ' column - header - trigger ' + ' \{childElCls\}"></div > ' + ' < /tpl > ' + ' < /div > ' + ' \{%this.renderContainer(out , values)%\ } ' ]
<a href="#!/api/Ext.grid.column.Column-method-getEl" rel="Ext.grid.column.Column-method-getEl" class="docClass">Element</a>.</p>
<p>You do not normally need to specify this. For the base classes <a href="#!/api/Ext.Component" rel="Ext.Component" class="docClass">Ext.Component</a> and
<a href="#!/api/Ext.container.Container" rel="Ext.container.Container" class="docClass">Ext.container.Container</a>, this defaults to <strong><code>null</code></strong> which means that they will be initially rendered
with no internal structure; they render their <a href="#!/api/Ext.grid.column.Column-method-getEl" rel="Ext.grid.column.Column-method-getEl" class="docClass">Element</a> empty. The more specialized Ext JS and Sencha Touch
classes which use a more complex DOM structure, provide their own template definitions.</p>
<p>This is intended to allow the developer to create application-specific utility Components with customized
internal structure.</p>
<p>Upon rendering, any created child elements may be automatically imported into object properties using the
<a href="#!/api/Ext.grid.column.Column-cfg-renderSelectors" rel="Ext.grid.column.Column-cfg-renderSelectors" class="docClass">renderSelectors</a> and <a href="#!/api/Ext.grid.column.Column-cfg-childEls" rel="Ext.grid.column.Column-cfg-childEls" class="docClass">childEls</a> options.</p> %}
Defaults to: ['<div id="\{id\}-titleEl" \{tipMarkup\}class="' + Ext.baseCSSPrefix + 'column-header-inner">' + '<span id="\{id\}-textEl" class="' + Ext.baseCSSPrefix + 'column-header-text' + '\{childElCls\}">' + '\{text\}' + '</span>' + '<tpl if="!menuDisabled">' + '<div id="\{id\}-triggerEl" class="' + Ext.baseCSSPrefix + 'column-header-trigger' + '\{childElCls\}"></div>' + '</tpl>' + '</div>' + '\{%this.renderContainer(out,values)%\}']
*)
method renderer : _ Js.t Js.prop
* { % < p > A renderer is an ' interceptor ' method which can be used to transform data ( value , appearance , etc . )
before it is rendered . Example:</p >
< pre><code>\ {
renderer : function(value)\ {
if ( value = = = 1 ) \ {
return ' 1 person ' ;
\ }
return value + ' people ' ;
\ }
\ }
< /code></pre >
< p > Additionally a string naming an < a href="#!/api / Ext.util . Format " rel="Ext.util . Format " class="docClass">Ext.util . Format</a > method can be passed:</p >
< pre><code>\ {
renderer : ' uppercase '
\ }
< /code></pre > % }
Defaults to : [ false ]
before it is rendered. Example:</p>
<pre><code>\{
renderer: function(value)\{
if (value === 1) \{
return '1 person';
\}
return value + ' people';
\}
\}
</code></pre>
<p>Additionally a string naming an <a href="#!/api/Ext.util.Format" rel="Ext.util.Format" class="docClass">Ext.util.Format</a> method can be passed:</p>
<pre><code>\{
renderer: 'uppercase'
\}
</code></pre> %}
Defaults to: [false]
*)
method resizable_bool : bool Js.t Js.prop
* { % < p > False to prevent the column from being resizable.</p > % }
Defaults to : [ true ]
Defaults to: [true]
*)
method scope : _ Js.t Js.prop
method sortable : bool Js.t Js.prop
method stateId : Js.js_string Js.t Js.prop
method tdCls : Js.js_string Js.t Js.prop
method text : Js.js_string Js.t Js.prop
* { % < p > The header text to be used as innerHTML ( html tags are accepted ) to display in the Grid .
< strong > Note</strong > : to have a clickable header with no text displayed you can use the default of < code>&#160;</code > aka < code>&nbsp;</code>.</p > % }
Defaults to : [ ' & # 160 ; ' ]
<strong>Note</strong>: to have a clickable header with no text displayed you can use the default of <code>&#160;</code> aka <code>&nbsp;</code>.</p> %}
Defaults to: [' ']
*)
method tooltip : Js.js_string Js.t Js.prop
* { % < p > A tooltip to display for this column }
*)
method tooltipType : Js.js_string Js.t Js.prop
* { % < p > The type of < a href="#!/api / Ext.grid.column . Column - cfg - tooltip " rel="Ext.grid.column . Column - cfg - tooltip " class="docClass">tooltip</a > to use . Either ' ' for QuickTips or ' title ' for title attribute.</p > % }
Defaults to : [ " " ]
Defaults to: ["qtip"]
*)
method afterComponentLayout : ('self Js.t, Js.number Js.t -> Js.number Js.t
-> _ Js.t -> _ Js.t -> unit) Js.meth_callback Js.writeonly_prop
method afterRender : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method defaultRenderer : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method initComponent : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method onAdd : ('self Js.t, #Ext_Component.t Js.t -> Js.number Js.t ->
unit) Js.meth_callback Js.writeonly_prop
* See method [ ]
method onDestroy : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method onRemove : ('self Js.t, #Ext_Component.t Js.t -> bool Js.t -> unit)
Js.meth_callback Js.writeonly_prop
end
class type events =
object
inherit Ext_grid_header_Container.events
end
class type statics =
object
inherit Ext_grid_header_Container.statics
end
val of_configs : configs Js.t -> t Js.t
val to_configs : t Js.t -> configs Js.t
|
9666d49ccf8257a644e11ed397c163051f482432dae6377042f9e89c30d8367e
|
janestreet/core_unix
|
daemon.mli
|
* This module provides support for daemonizing a process . It provides flexibility as to
where the standard file descriptors ( stdin , stdout and stderr ) are connected after
daemonization has occurred .
where the standard file descriptors (stdin, stdout and stderr) are connected after
daemonization has occurred. *)
open! Core
open! Import
module Fd_redirection : sig
type t = [
| `Dev_null
| `Dev_null_skip_regular_files (** Redirect to /dev/null unless already redirected to
a regular file. *)
| `Do_not_redirect
| `File_append of string
| `File_truncate of string
]
end
* [ daemonize ] makes the executing process a daemon .
The optional arguments have defaults as per [ daemonize_wait ] , below .
By default , output sent to stdout and stderr after daemonization will be silently
eaten . This behaviour may be adjusted by using [ redirect_stdout ] and
[ redirect_stderr ] . See the documentation for [ daemonize_wait ] below .
See [ daemonize_wait ] for a description of [ allow_threads_to_have_been_created ] .
Raises [ Failure ] if fork was unsuccessful .
The optional arguments have defaults as per [daemonize_wait], below.
By default, output sent to stdout and stderr after daemonization will be silently
eaten. This behaviour may be adjusted by using [redirect_stdout] and
[redirect_stderr]. See the documentation for [daemonize_wait] below.
See [daemonize_wait] for a description of [allow_threads_to_have_been_created].
Raises [Failure] if fork was unsuccessful. *)
val daemonize
: ?redirect_stdout : Fd_redirection.t
-> ?redirect_stderr : Fd_redirection.t
-> ?cd : string
-> ?perm : int (** permission to pass to [openfile] when using [`File_append] or
[`File_truncate] *)
-> ?umask : int (** defaults to use existing umask *)
-> ?allow_threads_to_have_been_created : bool (** defaults to false *)
-> unit
-> unit
* [ daemonize_wait ] makes the executing process a daemon , but delays full detachment from
the calling shell / process until the returned " release " closure is called .
Any output to stdout / stderr before the " release " closure is called will get
sent out normally . After " release " is called , stdin is connected to /dev / null ,
and stdout and stderr are connected as specified by [ redirect_stdout ] and
[ redirect_stderr ] . The default is the usual behavior whereby both of these
descriptors are connected to /dev / null . [ daemonize_wait ] , however , will not
redirect stdout / stderr to /dev / null if they are already redirected to a regular
file by default , i.e. , default redirection is [ ` Dev_null_skip_regular_files ] . This
is to preserve behavior from earlier versions . )
Note that calling [ release ] will adjust SIGPIPE handling , so you should not rely on
the delivery of this signal during this time .
[ daemonize_wait ] allows you to daemonize and then start asynchronously , but still have
stdout / stderr go to the controlling terminal during startup . By default , when you
[ daemonize ] , toplevel exceptions during startup would get sent to /dev / null . With
[ daemonize_wait ] , toplevel exceptions can go to the terminal until you call [ release ] .
Forking ( especially to daemonize ) when running multiple threads is tricky and
generally a mistake . [ daemonize ] and [ daemonize_wait ] check that the current number of
threads is not greater than expected . [ daemonize_wait ] and [ daemonize ] also check that
threads have not been created , which is more conservative than the actual requirement
that multiple threads are not running . Using
[ ~allow_threads_to_have_been_created : true ] bypasses that check . This is useful if
Async was previously running , and therefore threads have been created , but has since
been shut down . On non - Linux platforms , using
[ ~allow_threads_to_have_been_created : true ] eliminates the protection [ daemonize ] and
[ daemonize_wait ] have regarding threads .
Raises [ Failure ] if forking was unsuccessful .
the calling shell/process until the returned "release" closure is called.
Any output to stdout/stderr before the "release" closure is called will get
sent out normally. After "release" is called, stdin is connected to /dev/null,
and stdout and stderr are connected as specified by [redirect_stdout] and
[redirect_stderr]. The default is the usual behavior whereby both of these
descriptors are connected to /dev/null. [daemonize_wait], however, will not
redirect stdout/stderr to /dev/null if they are already redirected to a regular
file by default, i.e., default redirection is [`Dev_null_skip_regular_files]. This
is to preserve behavior from earlier versions.)
Note that calling [release] will adjust SIGPIPE handling, so you should not rely on
the delivery of this signal during this time.
[daemonize_wait] allows you to daemonize and then start asynchronously, but still have
stdout/stderr go to the controlling terminal during startup. By default, when you
[daemonize], toplevel exceptions during startup would get sent to /dev/null. With
[daemonize_wait], toplevel exceptions can go to the terminal until you call [release].
Forking (especially to daemonize) when running multiple threads is tricky and
generally a mistake. [daemonize] and [daemonize_wait] check that the current number of
threads is not greater than expected. [daemonize_wait] and [daemonize] also check that
threads have not been created, which is more conservative than the actual requirement
that multiple threads are not running. Using
[~allow_threads_to_have_been_created:true] bypasses that check. This is useful if
Async was previously running, and therefore threads have been created, but has since
been shut down. On non-Linux platforms, using
[~allow_threads_to_have_been_created:true] eliminates the protection [daemonize] and
[daemonize_wait] have regarding threads.
Raises [Failure] if forking was unsuccessful. *)
val daemonize_wait
: ?redirect_stdout : Fd_redirection.t (** default `Dev_null_skip_regular_files *)
-> ?redirect_stderr : Fd_redirection.t (** default `Dev_null_skip_regular_files *)
-> ?cd : string (** default / *)
-> ?perm : int (** permission to pass to [openfile] when using [`File_append] or
[`File_truncate] *)
-> ?umask : int (** defaults to use existing umask *)
-> ?allow_threads_to_have_been_created : bool (** defaults to false *)
-> unit
-> (unit -> unit) Staged.t
| null |
https://raw.githubusercontent.com/janestreet/core_unix/6c86f49d213b2876d512da158d15339e97dbcb8a/daemon/src/daemon.mli
|
ocaml
|
* Redirect to /dev/null unless already redirected to
a regular file.
* permission to pass to [openfile] when using [`File_append] or
[`File_truncate]
* defaults to use existing umask
* defaults to false
* default `Dev_null_skip_regular_files
* default `Dev_null_skip_regular_files
* default /
* permission to pass to [openfile] when using [`File_append] or
[`File_truncate]
* defaults to use existing umask
* defaults to false
|
* This module provides support for daemonizing a process . It provides flexibility as to
where the standard file descriptors ( stdin , stdout and stderr ) are connected after
daemonization has occurred .
where the standard file descriptors (stdin, stdout and stderr) are connected after
daemonization has occurred. *)
open! Core
open! Import
module Fd_redirection : sig
type t = [
| `Dev_null
| `Do_not_redirect
| `File_append of string
| `File_truncate of string
]
end
* [ daemonize ] makes the executing process a daemon .
The optional arguments have defaults as per [ daemonize_wait ] , below .
By default , output sent to stdout and stderr after daemonization will be silently
eaten . This behaviour may be adjusted by using [ redirect_stdout ] and
[ redirect_stderr ] . See the documentation for [ daemonize_wait ] below .
See [ daemonize_wait ] for a description of [ allow_threads_to_have_been_created ] .
Raises [ Failure ] if fork was unsuccessful .
The optional arguments have defaults as per [daemonize_wait], below.
By default, output sent to stdout and stderr after daemonization will be silently
eaten. This behaviour may be adjusted by using [redirect_stdout] and
[redirect_stderr]. See the documentation for [daemonize_wait] below.
See [daemonize_wait] for a description of [allow_threads_to_have_been_created].
Raises [Failure] if fork was unsuccessful. *)
val daemonize
: ?redirect_stdout : Fd_redirection.t
-> ?redirect_stderr : Fd_redirection.t
-> ?cd : string
-> unit
-> unit
* [ daemonize_wait ] makes the executing process a daemon , but delays full detachment from
the calling shell / process until the returned " release " closure is called .
Any output to stdout / stderr before the " release " closure is called will get
sent out normally . After " release " is called , stdin is connected to /dev / null ,
and stdout and stderr are connected as specified by [ redirect_stdout ] and
[ redirect_stderr ] . The default is the usual behavior whereby both of these
descriptors are connected to /dev / null . [ daemonize_wait ] , however , will not
redirect stdout / stderr to /dev / null if they are already redirected to a regular
file by default , i.e. , default redirection is [ ` Dev_null_skip_regular_files ] . This
is to preserve behavior from earlier versions . )
Note that calling [ release ] will adjust SIGPIPE handling , so you should not rely on
the delivery of this signal during this time .
[ daemonize_wait ] allows you to daemonize and then start asynchronously , but still have
stdout / stderr go to the controlling terminal during startup . By default , when you
[ daemonize ] , toplevel exceptions during startup would get sent to /dev / null . With
[ daemonize_wait ] , toplevel exceptions can go to the terminal until you call [ release ] .
Forking ( especially to daemonize ) when running multiple threads is tricky and
generally a mistake . [ daemonize ] and [ daemonize_wait ] check that the current number of
threads is not greater than expected . [ daemonize_wait ] and [ daemonize ] also check that
threads have not been created , which is more conservative than the actual requirement
that multiple threads are not running . Using
[ ~allow_threads_to_have_been_created : true ] bypasses that check . This is useful if
Async was previously running , and therefore threads have been created , but has since
been shut down . On non - Linux platforms , using
[ ~allow_threads_to_have_been_created : true ] eliminates the protection [ daemonize ] and
[ daemonize_wait ] have regarding threads .
Raises [ Failure ] if forking was unsuccessful .
the calling shell/process until the returned "release" closure is called.
Any output to stdout/stderr before the "release" closure is called will get
sent out normally. After "release" is called, stdin is connected to /dev/null,
and stdout and stderr are connected as specified by [redirect_stdout] and
[redirect_stderr]. The default is the usual behavior whereby both of these
descriptors are connected to /dev/null. [daemonize_wait], however, will not
redirect stdout/stderr to /dev/null if they are already redirected to a regular
file by default, i.e., default redirection is [`Dev_null_skip_regular_files]. This
is to preserve behavior from earlier versions.)
Note that calling [release] will adjust SIGPIPE handling, so you should not rely on
the delivery of this signal during this time.
[daemonize_wait] allows you to daemonize and then start asynchronously, but still have
stdout/stderr go to the controlling terminal during startup. By default, when you
[daemonize], toplevel exceptions during startup would get sent to /dev/null. With
[daemonize_wait], toplevel exceptions can go to the terminal until you call [release].
Forking (especially to daemonize) when running multiple threads is tricky and
generally a mistake. [daemonize] and [daemonize_wait] check that the current number of
threads is not greater than expected. [daemonize_wait] and [daemonize] also check that
threads have not been created, which is more conservative than the actual requirement
that multiple threads are not running. Using
[~allow_threads_to_have_been_created:true] bypasses that check. This is useful if
Async was previously running, and therefore threads have been created, but has since
been shut down. On non-Linux platforms, using
[~allow_threads_to_have_been_created:true] eliminates the protection [daemonize] and
[daemonize_wait] have regarding threads.
Raises [Failure] if forking was unsuccessful. *)
val daemonize_wait
-> unit
-> (unit -> unit) Staged.t
|
401026981c64b27df0b97d3b80002ba007bcfe8caadefcddd749372ccedab596
|
haskell/lsp
|
WorkspaceEditSpec.hs
|
{-# LANGUAGE OverloadedStrings #-}
module WorkspaceEditSpec where
import Test.Hspec
import Language.LSP.Types
spec :: Spec
spec = do
describe "applyTextEdit" $ do
it "inserts text" $
let te = TextEdit (Range (Position 1 2) (Position 1 2)) "foo"
in applyTextEdit te "lorem\nipsum\ndolor" `shouldBe` "lorem\nipfoosum\ndolor"
it "deletes text" $
let te = TextEdit (Range (Position 0 2) (Position 1 2)) ""
in applyTextEdit te "lorem\nipsum\ndolor" `shouldBe` "losum\ndolor"
it "edits a multiline text" $
let te = TextEdit (Range (Position 1 0) (Position 2 0)) "slorem"
in applyTextEdit te "lorem\nipsum\ndolor" `shouldBe` "lorem\nsloremdolor"
it "inserts text past the last line" $
let te = TextEdit (Range (Position 3 2) (Position 3 2)) "foo"
in applyTextEdit te "lorem\nipsum\ndolor" `shouldBe` "lorem\nipsum\ndolorfoo"
describe "editTextEdit" $
it "edits a multiline text edit" $
let orig = TextEdit (Range (Position 1 1) (Position 2 2)) "hello\nworld"
inner = TextEdit (Range (Position 0 3) (Position 1 3)) "ios\ngo"
expected = TextEdit (Range (Position 1 1) (Position 2 2)) "helios\ngold"
in editTextEdit orig inner `shouldBe` expected
| null |
https://raw.githubusercontent.com/haskell/lsp/0a518f78a32439fb59dc878ff3a7698dedf212d9/lsp-types/test/WorkspaceEditSpec.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
|
module WorkspaceEditSpec where
import Test.Hspec
import Language.LSP.Types
spec :: Spec
spec = do
describe "applyTextEdit" $ do
it "inserts text" $
let te = TextEdit (Range (Position 1 2) (Position 1 2)) "foo"
in applyTextEdit te "lorem\nipsum\ndolor" `shouldBe` "lorem\nipfoosum\ndolor"
it "deletes text" $
let te = TextEdit (Range (Position 0 2) (Position 1 2)) ""
in applyTextEdit te "lorem\nipsum\ndolor" `shouldBe` "losum\ndolor"
it "edits a multiline text" $
let te = TextEdit (Range (Position 1 0) (Position 2 0)) "slorem"
in applyTextEdit te "lorem\nipsum\ndolor" `shouldBe` "lorem\nsloremdolor"
it "inserts text past the last line" $
let te = TextEdit (Range (Position 3 2) (Position 3 2)) "foo"
in applyTextEdit te "lorem\nipsum\ndolor" `shouldBe` "lorem\nipsum\ndolorfoo"
describe "editTextEdit" $
it "edits a multiline text edit" $
let orig = TextEdit (Range (Position 1 1) (Position 2 2)) "hello\nworld"
inner = TextEdit (Range (Position 0 3) (Position 1 3)) "ios\ngo"
expected = TextEdit (Range (Position 1 1) (Position 2 2)) "helios\ngold"
in editTextEdit orig inner `shouldBe` expected
|
e9202949d6d3ad4326812e8f72f2359718eb7e66e4dee12992cdb56877550654
|
umutgokbayrak/ozlusozler
|
util.clj
|
(ns ozlusozler.util
(:require [noir.io :as io]
[markdown.core :as md]
[clj-time.local :as l]
[clj-time.coerce :as c]
[digest :as digest]))
(defn md->html
"reads a markdown file from public/md and returns an HTML string"
[filename]
(md/md-to-html-string (io/slurp-resource filename)))
(defn sql-now
"returns sql timestamp for now"
[]
(c/to-sql-time (l/local-now)))
(defn generate-hash [& txt]
(let [plain (if (nil? txt)
(.toString (java.util.UUID/randomUUID))
(first txt))]
(digest/md5 plain)))
(defn day-string [date]
(.format
(java.text.SimpleDateFormat. "yyyy-MM-dd")
(java.util.Date.
(.getTime date))))
(defn cookie-expire []
"Wed, 31 Oct 2089 08:50:17 GMT")
| null |
https://raw.githubusercontent.com/umutgokbayrak/ozlusozler/9c2a20aaf0b66ec033efae20c35ba620b4dde9c4/src/ozlusozler/util.clj
|
clojure
|
(ns ozlusozler.util
(:require [noir.io :as io]
[markdown.core :as md]
[clj-time.local :as l]
[clj-time.coerce :as c]
[digest :as digest]))
(defn md->html
"reads a markdown file from public/md and returns an HTML string"
[filename]
(md/md-to-html-string (io/slurp-resource filename)))
(defn sql-now
"returns sql timestamp for now"
[]
(c/to-sql-time (l/local-now)))
(defn generate-hash [& txt]
(let [plain (if (nil? txt)
(.toString (java.util.UUID/randomUUID))
(first txt))]
(digest/md5 plain)))
(defn day-string [date]
(.format
(java.text.SimpleDateFormat. "yyyy-MM-dd")
(java.util.Date.
(.getTime date))))
(defn cookie-expire []
"Wed, 31 Oct 2089 08:50:17 GMT")
|
|
7133eb77bdbe73238e5ba2def466d406f0e2989e3f4c964b84858e33a43e5027
|
goolord/atrophy
|
LongMultiplication.hs
|
# LANGUAGE
TypeApplications
, ScopedTypeVariables
, LambdaCase
#
TypeApplications
, ScopedTypeVariables
, LambdaCase
#-}
module Atrophy.LongMultiplication where
import Data.WideWord.Word128
import Data.Word
import qualified Data.Primitive.Contiguous as Contiguous
import Data.Primitive.Contiguous (PrimArray, MutableSliced, Mutable)
import Control.Monad.ST.Strict (ST)
import Data.STRef.Strict (newSTRef, modifySTRef, readSTRef)
import Data.Bits
import Data.Foldable (for_)
# INLINE multiply256By128UpperBits #
multiply256By128UpperBits :: Word128 -> Word128 -> Word128 -> Word128
multiply256By128UpperBits aHi aLo b =
let
-- Break a and b into little-endian 64-bit chunks
aChunks :: PrimArray Word64
aChunks = Contiguous.quadrupleton
(word128Lo64 aLo)
(word128Hi64 aLo)
(word128Lo64 aHi)
(word128Hi64 aHi)
bChunks :: PrimArray Word64
bChunks = Contiguous.doubleton
(word128Lo64 b)
(word128Hi64 b)
Multiply b by a , one chunk of b at a time
prod :: PrimArray Word64
prod = Contiguous.create $ do
prod' <- Contiguous.replicateMut 6 0
flip Contiguous.itraverse_ bChunks $ \bIndex bDigit -> do
pSize <- Contiguous.sizeMut prod'
multiply256By64Helper
(Contiguous.sliceMut prod' bIndex (pSize - bIndex))
aChunks
bDigit
pure prod'
in Word128
{ word128Hi64 = Contiguous.index prod 5
, word128Lo64 = Contiguous.index prod 4
}
# INLINE multiply256By64Helper #
multiply256By64Helper :: forall s. MutableSliced PrimArray s Word64 -> PrimArray Word64 -> Word64 -> ST s ()
multiply256By64Helper _ _ 0 = pure ()
multiply256By64Helper prod a b = do
carry <- newSTRef 0
productSize <- Contiguous.sizeMut prod
let
aSize = Contiguous.size a
productLo :: MutableSliced PrimArray s Word64
productLo = Contiguous.sliceMut prod 0 aSize
productHi :: MutableSliced PrimArray s Word64
productHi = Contiguous.sliceMut prod aSize (productSize - aSize)
-- Multiply each of the digits in a by b, adding them into the 'prod' value.
We do n't zero out prod , because we this will be called multiple times , so it probably contains a previous iteration 's partial prod , and we 're adding + carrying on top of it
for_ [0..aSize - 1] $ \i -> do
p <- Contiguous.read productLo i
let aDigit = Contiguous.index a i
modifySTRef carry $ \x -> x
+ Word128 0 p
+ (Word128 0 aDigit * Word128 0 b)
Contiguous.write prod i . word128Lo64 =<< readSTRef carry
modifySTRef carry (`unsafeShiftR` 64)
let productHiSize = productSize - aSize
for_ [0..productHiSize - 1] $ \i -> do
p <- Contiguous.read productHi i
modifySTRef carry (+ Word128 0 p)
Contiguous.write productHi i . word128Lo64 =<< readSTRef carry
modifySTRef carry (`unsafeShiftR` 64)
readSTRef carry >>= \case
0 -> pure ()
_ -> error "carry overflow during multiplication!"
-- compute prod += a * b
# INLINE longMultiply #
longMultiply :: forall s. PrimArray Word64 -> Word64 -> Mutable PrimArray s Word64 -> ST s ()
longMultiply a b prod = do
prod' <- Contiguous.toSliceMut prod
multiply256By64Helper prod' a b
| null |
https://raw.githubusercontent.com/goolord/atrophy/3b115dc5b0369d78f39e8c42b976706106a51096/src/Atrophy/LongMultiplication.hs
|
haskell
|
Break a and b into little-endian 64-bit chunks
Multiply each of the digits in a by b, adding them into the 'prod' value.
compute prod += a * b
|
# LANGUAGE
TypeApplications
, ScopedTypeVariables
, LambdaCase
#
TypeApplications
, ScopedTypeVariables
, LambdaCase
#-}
module Atrophy.LongMultiplication where
import Data.WideWord.Word128
import Data.Word
import qualified Data.Primitive.Contiguous as Contiguous
import Data.Primitive.Contiguous (PrimArray, MutableSliced, Mutable)
import Control.Monad.ST.Strict (ST)
import Data.STRef.Strict (newSTRef, modifySTRef, readSTRef)
import Data.Bits
import Data.Foldable (for_)
# INLINE multiply256By128UpperBits #
multiply256By128UpperBits :: Word128 -> Word128 -> Word128 -> Word128
multiply256By128UpperBits aHi aLo b =
let
aChunks :: PrimArray Word64
aChunks = Contiguous.quadrupleton
(word128Lo64 aLo)
(word128Hi64 aLo)
(word128Lo64 aHi)
(word128Hi64 aHi)
bChunks :: PrimArray Word64
bChunks = Contiguous.doubleton
(word128Lo64 b)
(word128Hi64 b)
Multiply b by a , one chunk of b at a time
prod :: PrimArray Word64
prod = Contiguous.create $ do
prod' <- Contiguous.replicateMut 6 0
flip Contiguous.itraverse_ bChunks $ \bIndex bDigit -> do
pSize <- Contiguous.sizeMut prod'
multiply256By64Helper
(Contiguous.sliceMut prod' bIndex (pSize - bIndex))
aChunks
bDigit
pure prod'
in Word128
{ word128Hi64 = Contiguous.index prod 5
, word128Lo64 = Contiguous.index prod 4
}
# INLINE multiply256By64Helper #
multiply256By64Helper :: forall s. MutableSliced PrimArray s Word64 -> PrimArray Word64 -> Word64 -> ST s ()
multiply256By64Helper _ _ 0 = pure ()
multiply256By64Helper prod a b = do
carry <- newSTRef 0
productSize <- Contiguous.sizeMut prod
let
aSize = Contiguous.size a
productLo :: MutableSliced PrimArray s Word64
productLo = Contiguous.sliceMut prod 0 aSize
productHi :: MutableSliced PrimArray s Word64
productHi = Contiguous.sliceMut prod aSize (productSize - aSize)
We do n't zero out prod , because we this will be called multiple times , so it probably contains a previous iteration 's partial prod , and we 're adding + carrying on top of it
for_ [0..aSize - 1] $ \i -> do
p <- Contiguous.read productLo i
let aDigit = Contiguous.index a i
modifySTRef carry $ \x -> x
+ Word128 0 p
+ (Word128 0 aDigit * Word128 0 b)
Contiguous.write prod i . word128Lo64 =<< readSTRef carry
modifySTRef carry (`unsafeShiftR` 64)
let productHiSize = productSize - aSize
for_ [0..productHiSize - 1] $ \i -> do
p <- Contiguous.read productHi i
modifySTRef carry (+ Word128 0 p)
Contiguous.write productHi i . word128Lo64 =<< readSTRef carry
modifySTRef carry (`unsafeShiftR` 64)
readSTRef carry >>= \case
0 -> pure ()
_ -> error "carry overflow during multiplication!"
# INLINE longMultiply #
longMultiply :: forall s. PrimArray Word64 -> Word64 -> Mutable PrimArray s Word64 -> ST s ()
longMultiply a b prod = do
prod' <- Contiguous.toSliceMut prod
multiply256By64Helper prod' a b
|
18327452813d641c1871c0bd22c1adcc4786b3d3ecbb88b0cc67f2a7013cec2d
|
mrphlip/aoc
|
Vector.hs
|
# OPTIONS_GHC -Wno - tabs #
module Vector (Vector(..), Vector2(Vector2), Vector3(Vector3), crossProduct, tupleVec2, tupleVec3, vecTuple2, vecTuple3, vecSum) where
import Data.List
data Vector2 a = Vector2 a a deriving (Eq, Ord)
data Vector3 a = Vector3 a a a deriving (Eq, Ord)
instance Read a => Read (Vector2 a) where
readsPrec n s = do
(v,rest) <- readsPrec n s
return (tupleVec2 v, rest)
instance Show a => Show (Vector2 a) where
showsPrec n v = showsPrec n $ vecTuple2 v
instance Read a => Read (Vector3 a) where
readsPrec n s = do
(v,rest) <- readsPrec n s
return (tupleVec3 v, rest)
instance Show a => Show (Vector3 a) where
showsPrec n v = showsPrec n $ vecTuple3 v
infixl 7 .*, ./
infixl 6 .+, .-
class Vector v where
(.+) :: (Num a) => v a -> v a -> v a
(.-) :: (Num a) => v a -> v a -> v a
negate :: (Num a) => v a -> v a
(.*) :: (Num a) => v a -> a -> v a
(./) :: (Fractional a) => v a -> a -> v a
dotProduct :: (Num a) => v a -> v a -> a
zero :: (Num a) => v a
instance Vector Vector2 where
Vector2 ax ay .+ Vector2 bx by = Vector2 (ax + bx) (ay + by)
Vector2 ax ay .- Vector2 bx by = Vector2 (ax - bx) (ay - by)
negate (Vector2 x y) = Vector2 (Prelude.negate x) (Prelude.negate y)
Vector2 ax ay .* s = Vector2 (ax * s) (ay * s)
Vector2 ax ay ./ s = Vector2 (ax / s) (ay / s)
Vector2 ax ay `dotProduct` Vector2 bx by = (ax * bx) + (ay * by)
zero = Vector2 0 0
instance Vector Vector3 where
Vector3 ax ay az .+ Vector3 bx by bz = Vector3 (ax + bx) (ay + by) (az + bz)
Vector3 ax ay az .- Vector3 bx by bz = Vector3 (ax - bx) (ay - by) (az - bz)
negate (Vector3 x y z) = Vector3 (Prelude.negate x) (Prelude.negate y) (Prelude.negate z)
Vector3 ax ay az .* s = Vector3 (ax * s) (ay * s) (az * s)
Vector3 ax ay az ./ s = Vector3 (ax / s) (ay / s) (az / s)
Vector3 ax ay az `dotProduct` Vector3 bx by bz = (ax * bx) + (ay * by) + (az * bz)
zero = Vector3 0 0 0
crossProduct :: (Num a) => Vector3 a -> Vector3 a -> Vector3 a
Vector3 ax ay az `crossProduct` Vector3 bx by bz = Vector3 x y z
where
x = ay * bz - az * by
y = az * bx - ax * bz
z = ax * by - ay * bx
tupleVec2 (x, y) = Vector2 x y
tupleVec3 (x, y, z) = Vector3 x y z
vecTuple2 (Vector2 x y) = (x, y)
vecTuple3 (Vector3 x y z) = (x, y, z)
vecSum :: (Vector v, Num a) => [v a] -> v a
vecSum = foldr1 (.+)
| null |
https://raw.githubusercontent.com/mrphlip/aoc/06395681eb6b50b838cd4561b2e0aa772aca570a/Vector.hs
|
haskell
|
# OPTIONS_GHC -Wno - tabs #
module Vector (Vector(..), Vector2(Vector2), Vector3(Vector3), crossProduct, tupleVec2, tupleVec3, vecTuple2, vecTuple3, vecSum) where
import Data.List
data Vector2 a = Vector2 a a deriving (Eq, Ord)
data Vector3 a = Vector3 a a a deriving (Eq, Ord)
instance Read a => Read (Vector2 a) where
readsPrec n s = do
(v,rest) <- readsPrec n s
return (tupleVec2 v, rest)
instance Show a => Show (Vector2 a) where
showsPrec n v = showsPrec n $ vecTuple2 v
instance Read a => Read (Vector3 a) where
readsPrec n s = do
(v,rest) <- readsPrec n s
return (tupleVec3 v, rest)
instance Show a => Show (Vector3 a) where
showsPrec n v = showsPrec n $ vecTuple3 v
infixl 7 .*, ./
infixl 6 .+, .-
class Vector v where
(.+) :: (Num a) => v a -> v a -> v a
(.-) :: (Num a) => v a -> v a -> v a
negate :: (Num a) => v a -> v a
(.*) :: (Num a) => v a -> a -> v a
(./) :: (Fractional a) => v a -> a -> v a
dotProduct :: (Num a) => v a -> v a -> a
zero :: (Num a) => v a
instance Vector Vector2 where
Vector2 ax ay .+ Vector2 bx by = Vector2 (ax + bx) (ay + by)
Vector2 ax ay .- Vector2 bx by = Vector2 (ax - bx) (ay - by)
negate (Vector2 x y) = Vector2 (Prelude.negate x) (Prelude.negate y)
Vector2 ax ay .* s = Vector2 (ax * s) (ay * s)
Vector2 ax ay ./ s = Vector2 (ax / s) (ay / s)
Vector2 ax ay `dotProduct` Vector2 bx by = (ax * bx) + (ay * by)
zero = Vector2 0 0
instance Vector Vector3 where
Vector3 ax ay az .+ Vector3 bx by bz = Vector3 (ax + bx) (ay + by) (az + bz)
Vector3 ax ay az .- Vector3 bx by bz = Vector3 (ax - bx) (ay - by) (az - bz)
negate (Vector3 x y z) = Vector3 (Prelude.negate x) (Prelude.negate y) (Prelude.negate z)
Vector3 ax ay az .* s = Vector3 (ax * s) (ay * s) (az * s)
Vector3 ax ay az ./ s = Vector3 (ax / s) (ay / s) (az / s)
Vector3 ax ay az `dotProduct` Vector3 bx by bz = (ax * bx) + (ay * by) + (az * bz)
zero = Vector3 0 0 0
crossProduct :: (Num a) => Vector3 a -> Vector3 a -> Vector3 a
Vector3 ax ay az `crossProduct` Vector3 bx by bz = Vector3 x y z
where
x = ay * bz - az * by
y = az * bx - ax * bz
z = ax * by - ay * bx
tupleVec2 (x, y) = Vector2 x y
tupleVec3 (x, y, z) = Vector3 x y z
vecTuple2 (Vector2 x y) = (x, y)
vecTuple3 (Vector3 x y z) = (x, y, z)
vecSum :: (Vector v, Num a) => [v a] -> v a
vecSum = foldr1 (.+)
|
|
5df36ce0a982e804c16cd33ea59acbc90128578c80fe25c47212469d44117f04
|
chetmurthy/ensemble
|
cryptokit_int.ml
|
(**************************************************************)
CRYPTOKIT_INT
Author : Ohad Rodeh , 3/2004
(**************************************************************)
(* Pseudo-random number generator *)
open Cryptokit
open Printf
(**************************************************************)
module Prng = struct
let prng = ref None
let init seed =
if String.length seed < 4 then
failwith "seed too short";
prng := Some (Random.pseudo_rng (seed ^ seed ^ seed ^ seed))
let rand len =
match !prng with
| None -> failwith "has not been initialized"
| Some prng -> Random.string prng len
end
(**************************************************************)
module Cipher = struct
type ofs = int
type len = int
type src = string
type dst = string
let key_len = 8
let encrypt key flag buf =
let key =
if String.length key < key_len then
invalid_arg (sprintf "init:key length < %d" key_len)
else if String.length key = 8 then
key
else
String.sub key 0 8
in
let transform =
if flag then
Cipher.des ~mode:Cipher.CBC key Cipher.Encrypt
else
Cipher.des ~mode:Cipher.CBC key Cipher.Decrypt
in
transform_string transform buf
end
(**************************************************************)
module DH = struct
type state = {
mutable prng : Random.rng option;
}
type key = {
secret : DH.private_secret;
pub : string ;
param : DH.parameters
}
type pub_key = string
type param = DH.parameters
let s = {prng=None}
Diffie - Hellman
let init () =
let hex s = transform_string (Hexa.decode()) s in
let prng =
Random.pseudo_rng (hex "5b5e50dc5b6eaf5346eba8244e5666ac4dcd5409") in
s.prng <- Some prng
let generate_parameters len =
let prng = match s.prng with
| None -> (
init ();
match s.prng with
| None -> failwith "sanity"
| Some prng -> prng
)
| Some prng -> prng
in
DH.new_parameters ~rng:prng len
let param_of_string buf =
(Marshal.from_string buf 0 : DH.parameters )
let string_of_param param =
Marshal.to_string param []
let generate_key param =
let secret = DH.private_secret param in
let pub = DH.message param secret in
{
secret = secret ;
pub = pub ;
param = param
}
let get_p param = param.DH.p
let get_g param = param.DH.g
let get_pub key = key.pub
let key_of_string buf =
(Marshal.from_string buf 0 : key )
let string_of_key key =
Marshal.to_string key []
let string_of_pub_key pub_key = pub_key
let pub_key_of_string pub_key = pub_key
let compute_key key pub_key =
DH.shared_secret key.param key.secret pub_key
end
(**************************************************************)
| null |
https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/crypto/real/cryptokit_int.ml
|
ocaml
|
************************************************************
************************************************************
Pseudo-random number generator
************************************************************
************************************************************
************************************************************
************************************************************
|
CRYPTOKIT_INT
Author : Ohad Rodeh , 3/2004
open Cryptokit
open Printf
module Prng = struct
let prng = ref None
let init seed =
if String.length seed < 4 then
failwith "seed too short";
prng := Some (Random.pseudo_rng (seed ^ seed ^ seed ^ seed))
let rand len =
match !prng with
| None -> failwith "has not been initialized"
| Some prng -> Random.string prng len
end
module Cipher = struct
type ofs = int
type len = int
type src = string
type dst = string
let key_len = 8
let encrypt key flag buf =
let key =
if String.length key < key_len then
invalid_arg (sprintf "init:key length < %d" key_len)
else if String.length key = 8 then
key
else
String.sub key 0 8
in
let transform =
if flag then
Cipher.des ~mode:Cipher.CBC key Cipher.Encrypt
else
Cipher.des ~mode:Cipher.CBC key Cipher.Decrypt
in
transform_string transform buf
end
module DH = struct
type state = {
mutable prng : Random.rng option;
}
type key = {
secret : DH.private_secret;
pub : string ;
param : DH.parameters
}
type pub_key = string
type param = DH.parameters
let s = {prng=None}
Diffie - Hellman
let init () =
let hex s = transform_string (Hexa.decode()) s in
let prng =
Random.pseudo_rng (hex "5b5e50dc5b6eaf5346eba8244e5666ac4dcd5409") in
s.prng <- Some prng
let generate_parameters len =
let prng = match s.prng with
| None -> (
init ();
match s.prng with
| None -> failwith "sanity"
| Some prng -> prng
)
| Some prng -> prng
in
DH.new_parameters ~rng:prng len
let param_of_string buf =
(Marshal.from_string buf 0 : DH.parameters )
let string_of_param param =
Marshal.to_string param []
let generate_key param =
let secret = DH.private_secret param in
let pub = DH.message param secret in
{
secret = secret ;
pub = pub ;
param = param
}
let get_p param = param.DH.p
let get_g param = param.DH.g
let get_pub key = key.pub
let key_of_string buf =
(Marshal.from_string buf 0 : key )
let string_of_key key =
Marshal.to_string key []
let string_of_pub_key pub_key = pub_key
let pub_key_of_string pub_key = pub_key
let compute_key key pub_key =
DH.shared_secret key.param key.secret pub_key
end
|
14bd7ccc99f76b2a1d314631e62018750bc87cc0ef9b6eb7fe546f90bae1ab29
|
hugoduncan/oldmj
|
run.clj
|
(ns makejack.impl.run
(:require [makejack.api.core :as makejack]
[makejack.impl.resolve :as resolve]))
(defn run-command [cmd args options]
(let [config (makejack/load-config {:profile (:profile options)
:dir (:dir options)})
target-kw (keyword cmd)
target (or (resolve/resolve-target target-kw config)
(resolve/resolve-target :undefined config))
f (resolve/resolve-target-invoker target)]
(when-not target
(makejack/error (str "Unknown target: " cmd)))
(when-not f
(makejack/error (str "Invalid invoker for target: " cmd)))
(f args target-kw config options)))
| null |
https://raw.githubusercontent.com/hugoduncan/oldmj/0a97488be7457baed01d2d9dd0ea6df4383832ab/cli/src/makejack/impl/run.clj
|
clojure
|
(ns makejack.impl.run
(:require [makejack.api.core :as makejack]
[makejack.impl.resolve :as resolve]))
(defn run-command [cmd args options]
(let [config (makejack/load-config {:profile (:profile options)
:dir (:dir options)})
target-kw (keyword cmd)
target (or (resolve/resolve-target target-kw config)
(resolve/resolve-target :undefined config))
f (resolve/resolve-target-invoker target)]
(when-not target
(makejack/error (str "Unknown target: " cmd)))
(when-not f
(makejack/error (str "Invalid invoker for target: " cmd)))
(f args target-kw config options)))
|
|
dd08fca909bbc91d8d5c390ab59cf1795037b7f1a3b3da4198d737df09720bb9
|
gedge-platform/gedge-platform
|
jose_jwa_poly1305.erl
|
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
%% vim: ts=4 sw=4 ft=erlang noet
%%%-------------------------------------------------------------------
@author < >
2014 - 2016 ,
@doc ChaCha20 and for IETF Protocols
%%% See
%%% @end
Created : 31 May 2016 by < >
%%%-------------------------------------------------------------------
-module(jose_jwa_poly1305).
%% API
-export([mac/2]).
-export([mac_init/1]).
-export([mac_update/2]).
-export([mac_final/1]).
Macros
-define(math, jose_jwa_math).
-define(clamp(R), R band 16#0ffffffc0ffffffc0ffffffc0fffffff).
-define(p, 16#3fffffffffffffffffffffffffffffffb).
%%====================================================================
%% API functions
%%====================================================================
mac(M, K)
when is_binary(M)
andalso is_binary(K)
andalso bit_size(K) =:= 256 ->
mac_final(mac_update(mac_init(K), M)).
mac_init(<< R:128/unsigned-little-integer-unit:1, S:128/unsigned-little-integer-unit:1 >>) ->
A = 0,
<<
(?clamp(R)):128/unsigned-little-integer-unit:1,
A:136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>.
mac_update(C = << _:392, 0:1656 >>, <<>>) ->
C;
mac_update(<<
R:128/unsigned-little-integer-unit:1,
A:136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>, <<
Block:128/bitstring,
Rest/binary
>>) ->
<< B:136/unsigned-little-integer-unit:1 >> = <<
Block:128/bitstring,
1:8/unsigned-little-integer-unit:1
>>,
mac_update(<<
R:128/unsigned-little-integer-unit:1,
(?math:mod((A + B) * R, ?p)):136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>, Rest);
mac_update(<<
R:128/unsigned-little-integer-unit:1,
A:136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>, <<
Block/binary
>>) ->
BlockBits = bit_size(Block),
PadBits = 136 - BlockBits - 8,
<< B:136/unsigned-little-integer-unit:1 >> = <<
Block/binary,
1:8/unsigned-little-integer-unit:1,
0:PadBits/unsigned-little-integer-unit:1
>>,
<<
R:128/unsigned-little-integer-unit:1,
(?math:mod((A + B) * R, ?p)):136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>.
mac_final(<<
_R:128/unsigned-little-integer-unit:1,
A:136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>) ->
<< (A + S):128/unsigned-little-integer-unit:1 >>.
| null |
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/jose/src/jwa/jose_jwa_poly1305.erl
|
erlang
|
vim: ts=4 sw=4 ft=erlang noet
-------------------------------------------------------------------
See
@end
-------------------------------------------------------------------
API
====================================================================
API functions
====================================================================
|
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*-
@author < >
2014 - 2016 ,
@doc ChaCha20 and for IETF Protocols
Created : 31 May 2016 by < >
-module(jose_jwa_poly1305).
-export([mac/2]).
-export([mac_init/1]).
-export([mac_update/2]).
-export([mac_final/1]).
Macros
-define(math, jose_jwa_math).
-define(clamp(R), R band 16#0ffffffc0ffffffc0ffffffc0fffffff).
-define(p, 16#3fffffffffffffffffffffffffffffffb).
mac(M, K)
when is_binary(M)
andalso is_binary(K)
andalso bit_size(K) =:= 256 ->
mac_final(mac_update(mac_init(K), M)).
mac_init(<< R:128/unsigned-little-integer-unit:1, S:128/unsigned-little-integer-unit:1 >>) ->
A = 0,
<<
(?clamp(R)):128/unsigned-little-integer-unit:1,
A:136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>.
mac_update(C = << _:392, 0:1656 >>, <<>>) ->
C;
mac_update(<<
R:128/unsigned-little-integer-unit:1,
A:136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>, <<
Block:128/bitstring,
Rest/binary
>>) ->
<< B:136/unsigned-little-integer-unit:1 >> = <<
Block:128/bitstring,
1:8/unsigned-little-integer-unit:1
>>,
mac_update(<<
R:128/unsigned-little-integer-unit:1,
(?math:mod((A + B) * R, ?p)):136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>, Rest);
mac_update(<<
R:128/unsigned-little-integer-unit:1,
A:136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>, <<
Block/binary
>>) ->
BlockBits = bit_size(Block),
PadBits = 136 - BlockBits - 8,
<< B:136/unsigned-little-integer-unit:1 >> = <<
Block/binary,
1:8/unsigned-little-integer-unit:1,
0:PadBits/unsigned-little-integer-unit:1
>>,
<<
R:128/unsigned-little-integer-unit:1,
(?math:mod((A + B) * R, ?p)):136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>.
mac_final(<<
_R:128/unsigned-little-integer-unit:1,
A:136/unsigned-little-integer-unit:1,
S:128/unsigned-little-integer-unit:1,
0:1656
>>) ->
<< (A + S):128/unsigned-little-integer-unit:1 >>.
|
89dcea7bc7dab637e26e49292e3354a44b8848c278af158f1aea4965850721f9
|
jwiegley/gitlib
|
Doctest.hs
|
module Main where
import Test.DocTest
import System.Directory
import System.FilePath
import Control.Applicative
import Control.Monad
import Data.List
main :: IO ()
main = getSources >>= \sources -> doctest $
"-isrc"
: "-idist/build/autogen"
: "-optP-include"
: "-optPdist/build/autogen/cabal_macros.h"
: sources
getSources :: IO [FilePath]
getSources =
filter (\n -> ".hs" `isSuffixOf` n && n /= "./Setup.hs") <$> go "."
where
go dir = do
(dirs, files) <- getFilesAndDirectories dir
(files ++) . concat <$> mapM go (filter (not . (== "./test")) dirs)
getFilesAndDirectories :: FilePath -> IO ([FilePath], [FilePath])
getFilesAndDirectories dir = do
c <- map (dir </>) . filter (`notElem` ["..", "."])
<$> getDirectoryContents dir
(,) <$> filterM doesDirectoryExist c <*> filterM doesFileExist c
| null |
https://raw.githubusercontent.com/jwiegley/gitlib/7d7ee1a62de723e3ebbbcaf7c262d6b43936329c/gitlib/test/Doctest.hs
|
haskell
|
module Main where
import Test.DocTest
import System.Directory
import System.FilePath
import Control.Applicative
import Control.Monad
import Data.List
main :: IO ()
main = getSources >>= \sources -> doctest $
"-isrc"
: "-idist/build/autogen"
: "-optP-include"
: "-optPdist/build/autogen/cabal_macros.h"
: sources
getSources :: IO [FilePath]
getSources =
filter (\n -> ".hs" `isSuffixOf` n && n /= "./Setup.hs") <$> go "."
where
go dir = do
(dirs, files) <- getFilesAndDirectories dir
(files ++) . concat <$> mapM go (filter (not . (== "./test")) dirs)
getFilesAndDirectories :: FilePath -> IO ([FilePath], [FilePath])
getFilesAndDirectories dir = do
c <- map (dir </>) . filter (`notElem` ["..", "."])
<$> getDirectoryContents dir
(,) <$> filterM doesDirectoryExist c <*> filterM doesFileExist c
|
|
5aebfd9d016e24ddf7cf0bc1ab7e018b4ea51b62d1a86a9e874ce870adb23187
|
SnootyMonkey/Falkland-CMS
|
taxonomy_create.clj
|
(ns fcms.unit.resources.taxonomy.taxonomy-create)
| null |
https://raw.githubusercontent.com/SnootyMonkey/Falkland-CMS/bd653c23dd458609b652dfac3f0f2f11526f00d1/test/fcms/unit/resources/taxonomy/taxonomy_create.clj
|
clojure
|
(ns fcms.unit.resources.taxonomy.taxonomy-create)
|
|
6945c8443571b18827c30e2459978deb85719b7322f9ee9495036343e8503968
|
thoughtbot/typebot
|
Types.hs
|
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE GeneralizedNewtypeDeriving #
module Types where
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Reader (MonadReader, ReaderT)
import Data.Aeson (Object, FromJSON(parseJSON), withObject, (.:), (.:?))
import Data.Aeson.Types (Parser)
import Data.Configurator.Types
import Data.Maybe (listToMaybe)
import Web.Scotty.Trans (ActionT)
import qualified Data.Text.Lazy as L
data SearchResult = SearchResult { typeString :: String, locationURL :: String } deriving (Show)
instance FromJSON SearchResult where
parseJSON = withObject "" parseSearchResult
parseSearchResult :: Object -> Parser SearchResult
parseSearchResult v = SearchResult <$> v .: "self" <*> v .: "location"
newtype ResultList = ResultList [SearchResult] deriving (Show)
data SearchEngine = Hayoo | Hoogle deriving (Show)
firstResult :: ResultList -> Maybe SearchResult
firstResult (ResultList xs) = listToMaybe xs
instance FromJSON ResultList where
parseJSON = withObject "" parseResultList
parseResultList :: Object -> Parser ResultList
parseResultList v = ResultList <$> v .: "results"
data AppConfig = AppConfig { appConfig :: Config, appSearchEngine :: SearchEngine }
newtype ConfigM a = ConfigM { runConfigM :: ReaderT AppConfig IO a } deriving (Applicative, Functor, Monad, MonadIO, MonadReader AppConfig)
type TypeBot a = ActionT L.Text ConfigM a
| null |
https://raw.githubusercontent.com/thoughtbot/typebot/b9b53e4e90835928e302ae8bf3112f334c718ab2/src/Types.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
|
# LANGUAGE GeneralizedNewtypeDeriving #
module Types where
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Reader (MonadReader, ReaderT)
import Data.Aeson (Object, FromJSON(parseJSON), withObject, (.:), (.:?))
import Data.Aeson.Types (Parser)
import Data.Configurator.Types
import Data.Maybe (listToMaybe)
import Web.Scotty.Trans (ActionT)
import qualified Data.Text.Lazy as L
data SearchResult = SearchResult { typeString :: String, locationURL :: String } deriving (Show)
instance FromJSON SearchResult where
parseJSON = withObject "" parseSearchResult
parseSearchResult :: Object -> Parser SearchResult
parseSearchResult v = SearchResult <$> v .: "self" <*> v .: "location"
newtype ResultList = ResultList [SearchResult] deriving (Show)
data SearchEngine = Hayoo | Hoogle deriving (Show)
firstResult :: ResultList -> Maybe SearchResult
firstResult (ResultList xs) = listToMaybe xs
instance FromJSON ResultList where
parseJSON = withObject "" parseResultList
parseResultList :: Object -> Parser ResultList
parseResultList v = ResultList <$> v .: "results"
data AppConfig = AppConfig { appConfig :: Config, appSearchEngine :: SearchEngine }
newtype ConfigM a = ConfigM { runConfigM :: ReaderT AppConfig IO a } deriving (Applicative, Functor, Monad, MonadIO, MonadReader AppConfig)
type TypeBot a = ActionT L.Text ConfigM a
|
525b43ad0a8fbc5a6388fc97e7885392f7d2fd807401e29a3d955e8519b046a2
|
haskell/hie-bios
|
cabal.hs
|
module Main (main) where
import Data.Maybe (fromMaybe)
import System.Directory (getCurrentDirectory)
import System.Environment (getArgs, getEnv, lookupEnv)
import System.Exit (exitWith)
import System.Process (spawnProcess, waitForProcess)
import System.IO (openFile, hClose, hPutStrLn, IOMode(..))
main :: IO ()
main = do
args <- getArgs
case args of
"--interactive":_ -> do
output_file <- getEnv "HIE_BIOS_OUTPUT"
h <- openFile output_file AppendMode
getCurrentDirectory >>= hPutStrLn h
mapM_ (hPutStrLn h) args
hClose h
_ -> do
ghc_path <- fromMaybe "ghc" <$> lookupEnv "HIE_BIOS_GHC"
ph <- spawnProcess ghc_path (args)
code <- waitForProcess ph
exitWith code
| null |
https://raw.githubusercontent.com/haskell/hie-bios/ef0e4f5301fbd9483a6b5b6d3adf41517b4dd2fa/wrappers/cabal.hs
|
haskell
|
module Main (main) where
import Data.Maybe (fromMaybe)
import System.Directory (getCurrentDirectory)
import System.Environment (getArgs, getEnv, lookupEnv)
import System.Exit (exitWith)
import System.Process (spawnProcess, waitForProcess)
import System.IO (openFile, hClose, hPutStrLn, IOMode(..))
main :: IO ()
main = do
args <- getArgs
case args of
"--interactive":_ -> do
output_file <- getEnv "HIE_BIOS_OUTPUT"
h <- openFile output_file AppendMode
getCurrentDirectory >>= hPutStrLn h
mapM_ (hPutStrLn h) args
hClose h
_ -> do
ghc_path <- fromMaybe "ghc" <$> lookupEnv "HIE_BIOS_GHC"
ph <- spawnProcess ghc_path (args)
code <- waitForProcess ph
exitWith code
|
|
510dc86c3e860ec7f40a89ab764b35ebb9cbc3c0b3bedf5fb9c4cc4896c9218f
|
hyperfiddle/electric
|
photon_macroexpansion.cljc
|
(ns dustin.scratch
(:require [hyperfiddle.rcf :as rcf :refer [tests ! % with]]
[hyperfiddle.photon :as p]
[hyperfiddle.photon-dom :as dom]
[missionary.core :as m])
#?(:cljs (:require-macros dustin.scratch)))
(hyperfiddle.rcf/enable!)
(tests
(macroexpand '(p/def db (inc 42)))
:= '(def db) ; macroexpands to nothing
(p/def db (inc 42))
, the ( inc 42 ) gets quoted and stored as meta
(meta *1) := {:hyperfiddle.photon-impl.compiler/node '(inc 42),
:name 'db,
:line _, :column _, :file _, :ns _})
(tests
"p/fn is only defined in a photon block, if you eval from clojure
you get weird stuff that isn't defined from clojure"
(macroexpand '(p/fn [x] x))
:= (list
:hyperfiddle.photon-impl.compiler/closure
'(clojure.core/let [x hyperfiddle.photon-impl.compiler/%1] x)
{:hyperfiddle.photon.debug/name nil,
:hyperfiddle.photon.debug/args ['x],
:hyperfiddle.photon.debug/type :reactive-fn,
:line _}))
| null |
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2022/photon/photon_macroexpansion.cljc
|
clojure
|
macroexpands to nothing
|
(ns dustin.scratch
(:require [hyperfiddle.rcf :as rcf :refer [tests ! % with]]
[hyperfiddle.photon :as p]
[hyperfiddle.photon-dom :as dom]
[missionary.core :as m])
#?(:cljs (:require-macros dustin.scratch)))
(hyperfiddle.rcf/enable!)
(tests
(macroexpand '(p/def db (inc 42)))
(p/def db (inc 42))
, the ( inc 42 ) gets quoted and stored as meta
(meta *1) := {:hyperfiddle.photon-impl.compiler/node '(inc 42),
:name 'db,
:line _, :column _, :file _, :ns _})
(tests
"p/fn is only defined in a photon block, if you eval from clojure
you get weird stuff that isn't defined from clojure"
(macroexpand '(p/fn [x] x))
:= (list
:hyperfiddle.photon-impl.compiler/closure
'(clojure.core/let [x hyperfiddle.photon-impl.compiler/%1] x)
{:hyperfiddle.photon.debug/name nil,
:hyperfiddle.photon.debug/args ['x],
:hyperfiddle.photon.debug/type :reactive-fn,
:line _}))
|
c72ea40d1490f81b05a21fc63d85af97ffff4f48806b79fe43861f818245db51
|
larcenists/larceny
|
16seq2.scm
|
(bits 16)
(text
(seq (nop)
(nop)
(seq (nop)
(nop)
z!
(nop)
(inv z!)
(nop))
(seq (nop))))
00000000 90 nop
00000001 90 nop
00000002 90 nop
00000003 90 nop
00000004 7505 jnz 0xb
00000006 90 nop
00000007 7402 jz 0xb
00000009 90 nop
0000000A 90 nop
| null |
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/src/Lib/Sassy/tests/prims16/16seq2.scm
|
scheme
|
(bits 16)
(text
(seq (nop)
(nop)
(seq (nop)
(nop)
z!
(nop)
(inv z!)
(nop))
(seq (nop))))
00000000 90 nop
00000001 90 nop
00000002 90 nop
00000003 90 nop
00000004 7505 jnz 0xb
00000006 90 nop
00000007 7402 jz 0xb
00000009 90 nop
0000000A 90 nop
|
|
ad0ee146912b8b3af446692f68780ebe436c5887c0822e3dab2ac295f445f4f1
|
AbstractMachinesLab/caramel
|
token_latest.ml
|
type token = Parser.token =
| WITH
| WHILE
| WHEN
| VIRTUAL
| VAL
| UNDERSCORE
| UIDENT of string
| TYPE
| TRY
| TRUE
| TO
| TILDE
| THEN
| STRUCT
| STRING of (string * Location.t * string option)
| STAR
| SIG
| SEMISEMI
| SEMI
| RPAREN
| REC
| RBRACKET
| RBRACE
| QUOTED_STRING_ITEM of
(string * Location.t * string * Location.t * string option)
| QUOTED_STRING_EXPR of
(string * Location.t * string * Location.t * string option)
| QUOTE
| QUESTION
| PRIVATE
| PREFIXOP of string
| PLUSEQ
| PLUSDOT
| PLUS
| PERCENT
| OR
| OPTLABEL of string
| OPEN
| OF
| OBJECT
| NONREC
| NEW
| MUTABLE
| MODULE
| MINUSGREATER
| MINUSDOT
| MINUS
| METHOD
| MATCH
| LPAREN
| LIDENT of string
| LETOP of string
| LET
| LESSMINUS
| LESS
| LBRACKETPERCENTPERCENT
| LBRACKETPERCENT
| LBRACKETLESS
| LBRACKETGREATER
| LBRACKETBAR
| LBRACKETATATAT
| LBRACKETATAT
| LBRACKETAT
| LBRACKET
| LBRACELESS
| LBRACE
| LAZY
| LABEL of string
| INT of (string * char option)
| INITIALIZER
| INHERIT
| INFIXOP4 of string
| INFIXOP3 of string
| INFIXOP2 of string
| INFIXOP1 of string
| INFIXOP0 of string
| INCLUDE
| IN
| IF
| HASHOP of string
| HASH
| GREATERRBRACKET
| GREATERRBRACE
| GREATER
| FUNCTOR
| FUNCTION
| FUN
| FOR
| FLOAT of (string * char option)
| FALSE
| EXTERNAL
| EXCEPTION
| EQUAL
| EOL
| EOF
| END
| ELSE
| DOWNTO
| DOTOP of string
| DOTDOT
| DOT
| DONE
| DOCSTRING of Docstrings.docstring
| DO
| CONSTRAINT
| COMMENT of (string * Location.t)
| COMMA
| COLONGREATER
| COLONEQUAL
| COLONCOLON
| COLON
| CLASS
| CHAR of char
| BEGIN
| BARRBRACKET
| BARBAR
| BAR
| BANG
| BACKQUOTE
| ASSERT
| AS
| ANDOP of string
| AND
| AMPERSAND
| AMPERAMPER
let of_compiler_libs x = x
| null |
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocamlformat-0.17.0/vendor/token-latest/411/token_latest.ml
|
ocaml
|
type token = Parser.token =
| WITH
| WHILE
| WHEN
| VIRTUAL
| VAL
| UNDERSCORE
| UIDENT of string
| TYPE
| TRY
| TRUE
| TO
| TILDE
| THEN
| STRUCT
| STRING of (string * Location.t * string option)
| STAR
| SIG
| SEMISEMI
| SEMI
| RPAREN
| REC
| RBRACKET
| RBRACE
| QUOTED_STRING_ITEM of
(string * Location.t * string * Location.t * string option)
| QUOTED_STRING_EXPR of
(string * Location.t * string * Location.t * string option)
| QUOTE
| QUESTION
| PRIVATE
| PREFIXOP of string
| PLUSEQ
| PLUSDOT
| PLUS
| PERCENT
| OR
| OPTLABEL of string
| OPEN
| OF
| OBJECT
| NONREC
| NEW
| MUTABLE
| MODULE
| MINUSGREATER
| MINUSDOT
| MINUS
| METHOD
| MATCH
| LPAREN
| LIDENT of string
| LETOP of string
| LET
| LESSMINUS
| LESS
| LBRACKETPERCENTPERCENT
| LBRACKETPERCENT
| LBRACKETLESS
| LBRACKETGREATER
| LBRACKETBAR
| LBRACKETATATAT
| LBRACKETATAT
| LBRACKETAT
| LBRACKET
| LBRACELESS
| LBRACE
| LAZY
| LABEL of string
| INT of (string * char option)
| INITIALIZER
| INHERIT
| INFIXOP4 of string
| INFIXOP3 of string
| INFIXOP2 of string
| INFIXOP1 of string
| INFIXOP0 of string
| INCLUDE
| IN
| IF
| HASHOP of string
| HASH
| GREATERRBRACKET
| GREATERRBRACE
| GREATER
| FUNCTOR
| FUNCTION
| FUN
| FOR
| FLOAT of (string * char option)
| FALSE
| EXTERNAL
| EXCEPTION
| EQUAL
| EOL
| EOF
| END
| ELSE
| DOWNTO
| DOTOP of string
| DOTDOT
| DOT
| DONE
| DOCSTRING of Docstrings.docstring
| DO
| CONSTRAINT
| COMMENT of (string * Location.t)
| COMMA
| COLONGREATER
| COLONEQUAL
| COLONCOLON
| COLON
| CLASS
| CHAR of char
| BEGIN
| BARRBRACKET
| BARBAR
| BAR
| BANG
| BACKQUOTE
| ASSERT
| AS
| ANDOP of string
| AND
| AMPERSAND
| AMPERAMPER
let of_compiler_libs x = x
|
|
d4089136f4bfd52a9e07f9aac22b06fa4d5545c8f4c12cf20656ac1073ad80b2
|
emc2/clash-riscv
|
Opcode16.hs
|
Copyright ( c ) 2017 . All rights reserved .
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
1 . Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
3 . Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ` ` AS IS ''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror #-}
# LANGUAGE DataKinds , TypeFamilies #
module RISCV.ISA.Opcodes.Opcode16(
Opcode16(..)
) where
import Prelude
import CLaSH.Class.BitPack
data Opcode16 =
C0
| C1
| C2
deriving (Eq, Ord)
instance BitPack Opcode16 where
type BitSize Opcode16 = 2
pack C0 = 0b00
pack C1 = 0b01
pack C2 = 0b10
unpack 0b00 = C0
unpack 0b01 = C1
unpack 0b10 = C2
unpack code = error ("Invalid opcode " ++ show code)
| null |
https://raw.githubusercontent.com/emc2/clash-riscv/e7404e5f9ff6b1eb22274bf7daa34bbd2768f2a3/src/RISCV/ISA/Opcodes/Opcode16.hs
|
haskell
|
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
# OPTIONS_GHC -Wall -Werror #
|
Copyright ( c ) 2017 . All rights reserved .
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of the author nor the names of any contributors
THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ` ` AS IS ''
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
# LANGUAGE DataKinds , TypeFamilies #
module RISCV.ISA.Opcodes.Opcode16(
Opcode16(..)
) where
import Prelude
import CLaSH.Class.BitPack
data Opcode16 =
C0
| C1
| C2
deriving (Eq, Ord)
instance BitPack Opcode16 where
type BitSize Opcode16 = 2
pack C0 = 0b00
pack C1 = 0b01
pack C2 = 0b10
unpack 0b00 = C0
unpack 0b01 = C1
unpack 0b10 = C2
unpack code = error ("Invalid opcode " ++ show code)
|
1dfc6824862a28e5d948bed48699fa9d361da446cc37d7021a1d8cc984048d9a
|
schemedoc/ffi-cookbook
|
uname-chibi.scm
|
(import (scheme base) (scheme write) (uname-chibi))
(define (displayln x) (display x) (newline))
(vector-for-each displayln (uname))
| null |
https://raw.githubusercontent.com/schemedoc/ffi-cookbook/75d3594135b5a4c5deea9a064a1aef5a95312f85/unix-syscall/uname-chibi.scm
|
scheme
|
(import (scheme base) (scheme write) (uname-chibi))
(define (displayln x) (display x) (newline))
(vector-for-each displayln (uname))
|
|
005700dc1736c08111017466be40badd0fd8e01b103e3e04bc151b74432096bc
|
jonase/eastwood
|
red.clj
|
(ns testcases.unused-fn-args.multimethods.red)
(defn foo []
(fn [a b c]
;; all args unintentionally unused
(rand)))
| null |
https://raw.githubusercontent.com/jonase/eastwood/1f0bbf4397a95f7ae326edd990de621e9949a2e5/cases/testcases/unused_fn_args/multimethods/red.clj
|
clojure
|
all args unintentionally unused
|
(ns testcases.unused-fn-args.multimethods.red)
(defn foo []
(fn [a b c]
(rand)))
|
d7b3acc7169eb362b488032e72a36d85221d386fbffcddc65808a1dc736ec876
|
dgiot/dgiot
|
dgiot_factory_calendar.erl
|
%%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(dgiot_factory_calendar).
-author("jonhl").
-include_lib("dgiot/include/logger.hrl").
-include("dgiot_factory.hrl").
-define(TYPE_LIST, [<<"week">>, <<"month">>]).
-define(FACTORY_CALENDAR, <<"factory_calendar">>).
-define(SCOPE, #{<<"week">> => [1, 7], <<"month">> = [1, 31]}).
-export([get_calendar/1, post_calendar/2, check_default/1, check_type/1, check_work_shift/1, check_laying_off/2]).
-export([get_new_other/2]).
dgiot_datetime : format(dgiot_datetime : ( ) , < < " YY - MM - DD " > > )
%%dgiot_datetime:format("HH:NN:SS")
post_calendar(Depart, Newcalendar) ->
case get_calendar(Depart) of
{ok, ObjectId, OldCalendar} ->
Merged_Calendar = maps:fold(
fun(K, V, Acc) ->
case K of
<<"default">> ->
Acc#{<<"default">> => V};
<<"other">> ->
Other = get_new_other(OldCalendar, V),
Acc#{<<"other">> => Other};
_ ->
Acc
end
end, OldCalendar, Newcalendar),
dgiot_parse:update_object(<<"Dict">>, ObjectId, #{<<"data">> => Merged_Calendar});
_ ->
pass
end.
get_new_other(OldCalendar, NewOther) ->
case maps:find(<<"other">>, OldCalendar) of
{ok, Old} ->
maps:fold(
fun(K, V, Acc) ->
case maps:size(V) of
0 ->
maps:remove(K, Acc);
_ ->
Acc#{K => V}
end
end, Old, NewOther);
error ->
NewOther
end.
get_calendar(Depart) ->
Id = dgiot_parse_id:get_dictid(Depart, ?FACTORY_CALENDAR, Depart, Depart),
case dgiot_parse:get_object(<<"Dict">>, Id) of
{ok, #{<<"data">> := Calendar}} ->
{ok, Id, Calendar};
_ ->
case dgiot_parse:create_object(<<"Dict">>, #{<<"objectId">> => Id, <<"key">> => Depart, <<"class">> => Depart, <<"title">> => Depart, <<"type">> => ?FACTORY_CALENDAR, <<"data">> => ?DEFAULT}) of
{ok, _} ->
{ok, Id, ?DEFAULT};
{error, Error} ->
{create_calendar_failed, Error}
end
end.
%% case dgiot_parse:query_object(<<"Dict">>,#{<<"where">> => #{<<"type">> => ?FACTORY_CALENDAR}}) of
%% {ok,#{<<"results">> := Results}} ->
%% case length(Results) of
1 - >
%% #{<<"objectId">> := ObjectId,<<"data">> :=Calendar} = lists:nth(1,Results),
{ ok , , Calendar } ;
%% 0 ->
%%
case dgiot_parse : create_object(<<"Dict " > > , # { < < " type " > > = > ? FACTORY_CALENDAR , < < " data " > > = > ? } ) of
{ ok,#{<<"objectId " > > : = } } - >
%% {ok,ObjectId,?DEFAULT};
%% {error,Error} ->
%% {create_calendar_failed,Error}
%% end;
%% Num ->
{ get_calendar_more_than_one , }
%% end;
%% _ ->
%% pass
%% end.
check_default(Default) ->
case check_type(Default) of
{ok} ->
case check_work_shift(Default) of
{ok} ->
{ok};
{error} ->
pass
end;
{error, Res} ->
{error, Res}
end.
check_type(Default) ->
case maps:find(<<"type">>, Default) of
{ok, <<"day">>} ->
{ok};
{ok, Type} ->
case lists:member(Type, ?TYPE_LIST) of
true ->
case check_laying_off(Type, Default) of
{ok} ->
{ok};
{error, Res} ->
{error, Res}
end;
false ->
{error, wrong_type}
end;
error ->
{error, not_find_type}
end.
check_laying_off(_Type, Default) ->
case maps:find(<<"laying_off">>, Default) of
{ok, _Laying_off} ->
{ok};
error ->
{error, not_find_laying_of}
end.
check_work_shift(_Default) ->
{ok}.
| null |
https://raw.githubusercontent.com/dgiot/dgiot/641ebb51a2ed75ab4d04ca1addf126000a362040/apps/dgiot_factory/src/dgiot_factory_calendar.erl
|
erlang
|
--------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
dgiot_datetime:format("HH:NN:SS")
case dgiot_parse:query_object(<<"Dict">>,#{<<"where">> => #{<<"type">> => ?FACTORY_CALENDAR}}) of
{ok,#{<<"results">> := Results}} ->
case length(Results) of
#{<<"objectId">> := ObjectId,<<"data">> :=Calendar} = lists:nth(1,Results),
0 ->
{ok,ObjectId,?DEFAULT};
{error,Error} ->
{create_calendar_failed,Error}
end;
Num ->
end;
_ ->
pass
end.
|
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(dgiot_factory_calendar).
-author("jonhl").
-include_lib("dgiot/include/logger.hrl").
-include("dgiot_factory.hrl").
-define(TYPE_LIST, [<<"week">>, <<"month">>]).
-define(FACTORY_CALENDAR, <<"factory_calendar">>).
-define(SCOPE, #{<<"week">> => [1, 7], <<"month">> = [1, 31]}).
-export([get_calendar/1, post_calendar/2, check_default/1, check_type/1, check_work_shift/1, check_laying_off/2]).
-export([get_new_other/2]).
dgiot_datetime : format(dgiot_datetime : ( ) , < < " YY - MM - DD " > > )
post_calendar(Depart, Newcalendar) ->
case get_calendar(Depart) of
{ok, ObjectId, OldCalendar} ->
Merged_Calendar = maps:fold(
fun(K, V, Acc) ->
case K of
<<"default">> ->
Acc#{<<"default">> => V};
<<"other">> ->
Other = get_new_other(OldCalendar, V),
Acc#{<<"other">> => Other};
_ ->
Acc
end
end, OldCalendar, Newcalendar),
dgiot_parse:update_object(<<"Dict">>, ObjectId, #{<<"data">> => Merged_Calendar});
_ ->
pass
end.
get_new_other(OldCalendar, NewOther) ->
case maps:find(<<"other">>, OldCalendar) of
{ok, Old} ->
maps:fold(
fun(K, V, Acc) ->
case maps:size(V) of
0 ->
maps:remove(K, Acc);
_ ->
Acc#{K => V}
end
end, Old, NewOther);
error ->
NewOther
end.
get_calendar(Depart) ->
Id = dgiot_parse_id:get_dictid(Depart, ?FACTORY_CALENDAR, Depart, Depart),
case dgiot_parse:get_object(<<"Dict">>, Id) of
{ok, #{<<"data">> := Calendar}} ->
{ok, Id, Calendar};
_ ->
case dgiot_parse:create_object(<<"Dict">>, #{<<"objectId">> => Id, <<"key">> => Depart, <<"class">> => Depart, <<"title">> => Depart, <<"type">> => ?FACTORY_CALENDAR, <<"data">> => ?DEFAULT}) of
{ok, _} ->
{ok, Id, ?DEFAULT};
{error, Error} ->
{create_calendar_failed, Error}
end
end.
1 - >
{ ok , , Calendar } ;
case dgiot_parse : create_object(<<"Dict " > > , # { < < " type " > > = > ? FACTORY_CALENDAR , < < " data " > > = > ? } ) of
{ ok,#{<<"objectId " > > : = } } - >
{ get_calendar_more_than_one , }
check_default(Default) ->
case check_type(Default) of
{ok} ->
case check_work_shift(Default) of
{ok} ->
{ok};
{error} ->
pass
end;
{error, Res} ->
{error, Res}
end.
check_type(Default) ->
case maps:find(<<"type">>, Default) of
{ok, <<"day">>} ->
{ok};
{ok, Type} ->
case lists:member(Type, ?TYPE_LIST) of
true ->
case check_laying_off(Type, Default) of
{ok} ->
{ok};
{error, Res} ->
{error, Res}
end;
false ->
{error, wrong_type}
end;
error ->
{error, not_find_type}
end.
check_laying_off(_Type, Default) ->
case maps:find(<<"laying_off">>, Default) of
{ok, _Laying_off} ->
{ok};
error ->
{error, not_find_laying_of}
end.
check_work_shift(_Default) ->
{ok}.
|
8f84f79b3306220208efa3f9e735030adebd1b758d9fa52f582e34ccb9404fc6
|
shop-planner/shop3
|
p19.lisp
|
(IN-PACKAGE :SHOP2-ROVERS)
(DEFPROBLEM ROVERPROB19 ROVER
((OBJECTIVE OBJECTIVE7) (OBJECTIVE OBJECTIVE6)
(OBJECTIVE OBJECTIVE5) (OBJECTIVE OBJECTIVE4)
(OBJECTIVE OBJECTIVE3) (OBJECTIVE OBJECTIVE2)
(OBJECTIVE OBJECTIVE1) (OBJECTIVE OBJECTIVE0)
(CAMERA CAMERA6) (CAMERA CAMERA5) (CAMERA CAMERA4)
(CAMERA CAMERA3) (CAMERA CAMERA2) (CAMERA CAMERA1)
(CAMERA CAMERA0) (WAYPOINT WAYPOINT19)
(WAYPOINT WAYPOINT18) (WAYPOINT WAYPOINT17)
(WAYPOINT WAYPOINT16) (WAYPOINT WAYPOINT15)
(WAYPOINT WAYPOINT14) (WAYPOINT WAYPOINT13)
(WAYPOINT WAYPOINT12) (WAYPOINT WAYPOINT11)
(WAYPOINT WAYPOINT10) (WAYPOINT WAYPOINT9)
(WAYPOINT WAYPOINT8) (WAYPOINT WAYPOINT7)
(WAYPOINT WAYPOINT6) (WAYPOINT WAYPOINT5)
(WAYPOINT WAYPOINT4) (WAYPOINT WAYPOINT3)
(WAYPOINT WAYPOINT2) (WAYPOINT WAYPOINT1)
(WAYPOINT WAYPOINT0) (STORE ROVER5STORE)
(STORE ROVER4STORE) (STORE ROVER3STORE)
(STORE ROVER2STORE) (STORE ROVER1STORE)
(STORE ROVER0STORE) (ROVER ROVER5) (ROVER ROVER4)
(ROVER ROVER3) (ROVER ROVER2) (ROVER ROVER1)
(ROVER ROVER0) (MODE LOW_RES) (MODE HIGH_RES)
(MODE COLOUR) (LANDER GENERAL)
(VISIBLE WAYPOINT0 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT0)
(VISIBLE WAYPOINT1 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT1)
(VISIBLE WAYPOINT2 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT2)
(VISIBLE WAYPOINT3 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT3)
(VISIBLE WAYPOINT4 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT4)
(VISIBLE WAYPOINT5 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT15)
(VISIBLE WAYPOINT15 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT5)
(VISIBLE WAYPOINT6 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT6)
(VISIBLE WAYPOINT7 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT7)
(VISIBLE WAYPOINT8 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT8)
(VISIBLE WAYPOINT9 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT9)
(VISIBLE WAYPOINT10 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT10)
(VISIBLE WAYPOINT11 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT11)
(VISIBLE WAYPOINT12 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT15)
(VISIBLE WAYPOINT15 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT12)
(VISIBLE WAYPOINT13 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT13)
(VISIBLE WAYPOINT14 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT14)
(VISIBLE WAYPOINT15 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT15)
(VISIBLE WAYPOINT15 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT15)
(VISIBLE WAYPOINT16 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT16)
(VISIBLE WAYPOINT17 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT17)
(VISIBLE WAYPOINT18 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT18)
(VISIBLE WAYPOINT19 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT19) (AT_SOIL_SAMPLE WAYPOINT3)
(AT_ROCK_SAMPLE WAYPOINT3) (AT_ROCK_SAMPLE WAYPOINT4)
(AT_SOIL_SAMPLE WAYPOINT5) (AT_ROCK_SAMPLE WAYPOINT6)
(AT_SOIL_SAMPLE WAYPOINT8) (AT_ROCK_SAMPLE WAYPOINT9)
(AT_SOIL_SAMPLE WAYPOINT11) (AT_SOIL_SAMPLE WAYPOINT12)
(AT_SOIL_SAMPLE WAYPOINT14) (AT_SOIL_SAMPLE WAYPOINT15)
(AT_SOIL_SAMPLE WAYPOINT16) (AT_SOIL_SAMPLE WAYPOINT17)
(AT_ROCK_SAMPLE WAYPOINT17) (AT_SOIL_SAMPLE WAYPOINT18)
(AT_ROCK_SAMPLE WAYPOINT19) (AT_LANDER GENERAL WAYPOINT6)
(CHANNEL_FREE GENERAL) (AT ROVER0 WAYPOINT2)
(AVAILABLE ROVER0) (STORE_OF ROVER0STORE ROVER0)
(EMPTY ROVER0STORE) (EQUIPPED_FOR_IMAGING ROVER0)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT0)
(CAN_TRAVERSE ROVER0 WAYPOINT0 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT5)
(CAN_TRAVERSE ROVER0 WAYPOINT5 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER0 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT9)
(CAN_TRAVERSE ROVER0 WAYPOINT9 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT18)
(CAN_TRAVERSE ROVER0 WAYPOINT18 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT0 WAYPOINT6)
(CAN_TRAVERSE ROVER0 WAYPOINT6 WAYPOINT0)
(CAN_TRAVERSE ROVER0 WAYPOINT0 WAYPOINT13)
(CAN_TRAVERSE ROVER0 WAYPOINT13 WAYPOINT0)
(CAN_TRAVERSE ROVER0 WAYPOINT0 WAYPOINT19)
(CAN_TRAVERSE ROVER0 WAYPOINT19 WAYPOINT0)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT1)
(CAN_TRAVERSE ROVER0 WAYPOINT1 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT3)
(CAN_TRAVERSE ROVER0 WAYPOINT3 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT12)
(CAN_TRAVERSE ROVER0 WAYPOINT12 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT17)
(CAN_TRAVERSE ROVER0 WAYPOINT17 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT5 WAYPOINT11)
(CAN_TRAVERSE ROVER0 WAYPOINT11 WAYPOINT5)
(CAN_TRAVERSE ROVER0 WAYPOINT5 WAYPOINT15)
(CAN_TRAVERSE ROVER0 WAYPOINT15 WAYPOINT5)
(CAN_TRAVERSE ROVER0 WAYPOINT9 WAYPOINT10)
(CAN_TRAVERSE ROVER0 WAYPOINT10 WAYPOINT9)
(CAN_TRAVERSE ROVER0 WAYPOINT18 WAYPOINT8)
(CAN_TRAVERSE ROVER0 WAYPOINT8 WAYPOINT18)
(CAN_TRAVERSE ROVER0 WAYPOINT6 WAYPOINT16)
(CAN_TRAVERSE ROVER0 WAYPOINT16 WAYPOINT6)
(CAN_TRAVERSE ROVER0 WAYPOINT3 WAYPOINT14)
(CAN_TRAVERSE ROVER0 WAYPOINT14 WAYPOINT3)
(AT ROVER1 WAYPOINT6) (AVAILABLE ROVER1)
(STORE_OF ROVER1STORE ROVER1) (EMPTY ROVER1STORE)
(EQUIPPED_FOR_IMAGING ROVER1)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT0)
(CAN_TRAVERSE ROVER1 WAYPOINT0 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT8)
(CAN_TRAVERSE ROVER1 WAYPOINT8 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT13)
(CAN_TRAVERSE ROVER1 WAYPOINT13 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT15)
(CAN_TRAVERSE ROVER1 WAYPOINT15 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT16)
(CAN_TRAVERSE ROVER1 WAYPOINT16 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT19)
(CAN_TRAVERSE ROVER1 WAYPOINT19 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT0 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT0)
(CAN_TRAVERSE ROVER1 WAYPOINT0 WAYPOINT5)
(CAN_TRAVERSE ROVER1 WAYPOINT5 WAYPOINT0)
(CAN_TRAVERSE ROVER1 WAYPOINT0 WAYPOINT18)
(CAN_TRAVERSE ROVER1 WAYPOINT18 WAYPOINT0)
(CAN_TRAVERSE ROVER1 WAYPOINT8 WAYPOINT11)
(CAN_TRAVERSE ROVER1 WAYPOINT11 WAYPOINT8)
(CAN_TRAVERSE ROVER1 WAYPOINT13 WAYPOINT7)
(CAN_TRAVERSE ROVER1 WAYPOINT7 WAYPOINT13)
(CAN_TRAVERSE ROVER1 WAYPOINT15 WAYPOINT12)
(CAN_TRAVERSE ROVER1 WAYPOINT12 WAYPOINT15)
(CAN_TRAVERSE ROVER1 WAYPOINT16 WAYPOINT1)
(CAN_TRAVERSE ROVER1 WAYPOINT1 WAYPOINT16)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT3)
(CAN_TRAVERSE ROVER1 WAYPOINT3 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT4)
(CAN_TRAVERSE ROVER1 WAYPOINT4 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT9)
(CAN_TRAVERSE ROVER1 WAYPOINT9 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT10)
(CAN_TRAVERSE ROVER1 WAYPOINT10 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT5 WAYPOINT17)
(CAN_TRAVERSE ROVER1 WAYPOINT17 WAYPOINT5)
(CAN_TRAVERSE ROVER1 WAYPOINT11 WAYPOINT14)
(CAN_TRAVERSE ROVER1 WAYPOINT14 WAYPOINT11)
(AT ROVER2 WAYPOINT13) (AVAILABLE ROVER2)
(STORE_OF ROVER2STORE ROVER2) (EMPTY ROVER2STORE)
(EQUIPPED_FOR_SOIL_ANALYSIS ROVER2)
(EQUIPPED_FOR_IMAGING ROVER2)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT0)
(CAN_TRAVERSE ROVER2 WAYPOINT0 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT6)
(CAN_TRAVERSE ROVER2 WAYPOINT6 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT7)
(CAN_TRAVERSE ROVER2 WAYPOINT7 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT16)
(CAN_TRAVERSE ROVER2 WAYPOINT16 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT19)
(CAN_TRAVERSE ROVER2 WAYPOINT19 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT0 WAYPOINT5)
(CAN_TRAVERSE ROVER2 WAYPOINT5 WAYPOINT0)
(CAN_TRAVERSE ROVER2 WAYPOINT0 WAYPOINT9)
(CAN_TRAVERSE ROVER2 WAYPOINT9 WAYPOINT0)
(CAN_TRAVERSE ROVER2 WAYPOINT0 WAYPOINT18)
(CAN_TRAVERSE ROVER2 WAYPOINT18 WAYPOINT0)
(CAN_TRAVERSE ROVER2 WAYPOINT6 WAYPOINT8)
(CAN_TRAVERSE ROVER2 WAYPOINT8 WAYPOINT6)
(CAN_TRAVERSE ROVER2 WAYPOINT6 WAYPOINT15)
(CAN_TRAVERSE ROVER2 WAYPOINT15 WAYPOINT6)
(CAN_TRAVERSE ROVER2 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER2 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER2 WAYPOINT7 WAYPOINT4)
(CAN_TRAVERSE ROVER2 WAYPOINT4 WAYPOINT7)
(CAN_TRAVERSE ROVER2 WAYPOINT7 WAYPOINT12)
(CAN_TRAVERSE ROVER2 WAYPOINT12 WAYPOINT7)
(CAN_TRAVERSE ROVER2 WAYPOINT16 WAYPOINT1)
(CAN_TRAVERSE ROVER2 WAYPOINT1 WAYPOINT16)
(CAN_TRAVERSE ROVER2 WAYPOINT16 WAYPOINT11)
(CAN_TRAVERSE ROVER2 WAYPOINT11 WAYPOINT16)
(CAN_TRAVERSE ROVER2 WAYPOINT19 WAYPOINT14)
(CAN_TRAVERSE ROVER2 WAYPOINT14 WAYPOINT19)
(CAN_TRAVERSE ROVER2 WAYPOINT5 WAYPOINT3)
(CAN_TRAVERSE ROVER2 WAYPOINT3 WAYPOINT5)
(CAN_TRAVERSE ROVER2 WAYPOINT9 WAYPOINT10)
(CAN_TRAVERSE ROVER2 WAYPOINT10 WAYPOINT9)
(CAN_TRAVERSE ROVER2 WAYPOINT18 WAYPOINT17)
(CAN_TRAVERSE ROVER2 WAYPOINT17 WAYPOINT18)
(AT ROVER3 WAYPOINT11) (AVAILABLE ROVER3)
(STORE_OF ROVER3STORE ROVER3) (EMPTY ROVER3STORE)
(EQUIPPED_FOR_SOIL_ANALYSIS ROVER3)
(EQUIPPED_FOR_ROCK_ANALYSIS ROVER3)
(EQUIPPED_FOR_IMAGING ROVER3)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT1)
(CAN_TRAVERSE ROVER3 WAYPOINT1 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT9)
(CAN_TRAVERSE ROVER3 WAYPOINT9 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT14)
(CAN_TRAVERSE ROVER3 WAYPOINT14 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT16)
(CAN_TRAVERSE ROVER3 WAYPOINT16 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT17)
(CAN_TRAVERSE ROVER3 WAYPOINT17 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT1 WAYPOINT4)
(CAN_TRAVERSE ROVER3 WAYPOINT4 WAYPOINT1)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER3 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT3)
(CAN_TRAVERSE ROVER3 WAYPOINT3 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT12)
(CAN_TRAVERSE ROVER3 WAYPOINT12 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT13)
(CAN_TRAVERSE ROVER3 WAYPOINT13 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT18)
(CAN_TRAVERSE ROVER3 WAYPOINT18 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT9 WAYPOINT0)
(CAN_TRAVERSE ROVER3 WAYPOINT0 WAYPOINT9)
(CAN_TRAVERSE ROVER3 WAYPOINT14 WAYPOINT8)
(CAN_TRAVERSE ROVER3 WAYPOINT8 WAYPOINT14)
(CAN_TRAVERSE ROVER3 WAYPOINT14 WAYPOINT10)
(CAN_TRAVERSE ROVER3 WAYPOINT10 WAYPOINT14)
(CAN_TRAVERSE ROVER3 WAYPOINT16 WAYPOINT5)
(CAN_TRAVERSE ROVER3 WAYPOINT5 WAYPOINT16)
(CAN_TRAVERSE ROVER3 WAYPOINT16 WAYPOINT6)
(CAN_TRAVERSE ROVER3 WAYPOINT6 WAYPOINT16)
(CAN_TRAVERSE ROVER3 WAYPOINT2 WAYPOINT19)
(CAN_TRAVERSE ROVER3 WAYPOINT19 WAYPOINT2)
(CAN_TRAVERSE ROVER3 WAYPOINT12 WAYPOINT15)
(CAN_TRAVERSE ROVER3 WAYPOINT15 WAYPOINT12)
(AT ROVER4 WAYPOINT0) (AVAILABLE ROVER4)
(STORE_OF ROVER4STORE ROVER4) (EMPTY ROVER4STORE)
(EQUIPPED_FOR_SOIL_ANALYSIS ROVER4)
(EQUIPPED_FOR_ROCK_ANALYSIS ROVER4)
(EQUIPPED_FOR_IMAGING ROVER4)
(CAN_TRAVERSE ROVER4 WAYPOINT0 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT0)
(CAN_TRAVERSE ROVER4 WAYPOINT0 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT0)
(CAN_TRAVERSE ROVER4 WAYPOINT0 WAYPOINT6)
(CAN_TRAVERSE ROVER4 WAYPOINT6 WAYPOINT0)
(CAN_TRAVERSE ROVER4 WAYPOINT0 WAYPOINT18)
(CAN_TRAVERSE ROVER4 WAYPOINT18 WAYPOINT0)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT3)
(CAN_TRAVERSE ROVER4 WAYPOINT3 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER4 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT8)
(CAN_TRAVERSE ROVER4 WAYPOINT8 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT17)
(CAN_TRAVERSE ROVER4 WAYPOINT17 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT19)
(CAN_TRAVERSE ROVER4 WAYPOINT19 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT11)
(CAN_TRAVERSE ROVER4 WAYPOINT11 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT12)
(CAN_TRAVERSE ROVER4 WAYPOINT12 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT15)
(CAN_TRAVERSE ROVER4 WAYPOINT15 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT16)
(CAN_TRAVERSE ROVER4 WAYPOINT16 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT6 WAYPOINT1)
(CAN_TRAVERSE ROVER4 WAYPOINT1 WAYPOINT6)
(CAN_TRAVERSE ROVER4 WAYPOINT6 WAYPOINT13)
(CAN_TRAVERSE ROVER4 WAYPOINT13 WAYPOINT6)
(CAN_TRAVERSE ROVER4 WAYPOINT18 WAYPOINT10)
(CAN_TRAVERSE ROVER4 WAYPOINT10 WAYPOINT18)
(CAN_TRAVERSE ROVER4 WAYPOINT3 WAYPOINT4)
(CAN_TRAVERSE ROVER4 WAYPOINT4 WAYPOINT3)
(CAN_TRAVERSE ROVER4 WAYPOINT3 WAYPOINT9)
(CAN_TRAVERSE ROVER4 WAYPOINT9 WAYPOINT3)
(CAN_TRAVERSE ROVER4 WAYPOINT8 WAYPOINT14)
(CAN_TRAVERSE ROVER4 WAYPOINT14 WAYPOINT8)
(AT ROVER5 WAYPOINT12) (AVAILABLE ROVER5)
(STORE_OF ROVER5STORE ROVER5) (EMPTY ROVER5STORE)
(EQUIPPED_FOR_SOIL_ANALYSIS ROVER5)
(EQUIPPED_FOR_ROCK_ANALYSIS ROVER5)
(EQUIPPED_FOR_IMAGING ROVER5)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT1)
(CAN_TRAVERSE ROVER5 WAYPOINT1 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT4)
(CAN_TRAVERSE ROVER5 WAYPOINT4 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT5)
(CAN_TRAVERSE ROVER5 WAYPOINT5 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT7)
(CAN_TRAVERSE ROVER5 WAYPOINT7 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT9)
(CAN_TRAVERSE ROVER5 WAYPOINT9 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT10)
(CAN_TRAVERSE ROVER5 WAYPOINT10 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT14)
(CAN_TRAVERSE ROVER5 WAYPOINT14 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT15)
(CAN_TRAVERSE ROVER5 WAYPOINT15 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT16)
(CAN_TRAVERSE ROVER5 WAYPOINT16 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT1 WAYPOINT6)
(CAN_TRAVERSE ROVER5 WAYPOINT6 WAYPOINT1)
(CAN_TRAVERSE ROVER5 WAYPOINT1 WAYPOINT11)
(CAN_TRAVERSE ROVER5 WAYPOINT11 WAYPOINT1)
(CAN_TRAVERSE ROVER5 WAYPOINT4 WAYPOINT3)
(CAN_TRAVERSE ROVER5 WAYPOINT3 WAYPOINT4)
(CAN_TRAVERSE ROVER5 WAYPOINT4 WAYPOINT17)
(CAN_TRAVERSE ROVER5 WAYPOINT17 WAYPOINT4)
(CAN_TRAVERSE ROVER5 WAYPOINT5 WAYPOINT0)
(CAN_TRAVERSE ROVER5 WAYPOINT0 WAYPOINT5)
(CAN_TRAVERSE ROVER5 WAYPOINT5 WAYPOINT13)
(CAN_TRAVERSE ROVER5 WAYPOINT13 WAYPOINT5)
(CAN_TRAVERSE ROVER5 WAYPOINT5 WAYPOINT19)
(CAN_TRAVERSE ROVER5 WAYPOINT19 WAYPOINT5)
(CAN_TRAVERSE ROVER5 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER5 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER5 WAYPOINT7 WAYPOINT8)
(CAN_TRAVERSE ROVER5 WAYPOINT8 WAYPOINT7)
(CAN_TRAVERSE ROVER5 WAYPOINT7 WAYPOINT18)
(CAN_TRAVERSE ROVER5 WAYPOINT18 WAYPOINT7)
(ON_BOARD CAMERA0 ROVER2)
(CALIBRATION_TARGET CAMERA0 OBJECTIVE0)
(SUPPORTS CAMERA0 COLOUR) (SUPPORTS CAMERA0 HIGH_RES)
(SUPPORTS CAMERA0 LOW_RES) (ON_BOARD CAMERA1 ROVER1)
(CALIBRATION_TARGET CAMERA1 OBJECTIVE1)
(SUPPORTS CAMERA1 HIGH_RES) (ON_BOARD CAMERA2 ROVER1)
(CALIBRATION_TARGET CAMERA2 OBJECTIVE0)
(SUPPORTS CAMERA2 HIGH_RES) (SUPPORTS CAMERA2 LOW_RES)
(ON_BOARD CAMERA3 ROVER0)
(CALIBRATION_TARGET CAMERA3 OBJECTIVE5)
(SUPPORTS CAMERA3 HIGH_RES) (ON_BOARD CAMERA4 ROVER4)
(CALIBRATION_TARGET CAMERA4 OBJECTIVE2)
(SUPPORTS CAMERA4 COLOUR) (SUPPORTS CAMERA4 LOW_RES)
(ON_BOARD CAMERA5 ROVER3)
(CALIBRATION_TARGET CAMERA5 OBJECTIVE0)
(SUPPORTS CAMERA5 COLOUR) (SUPPORTS CAMERA5 LOW_RES)
(ON_BOARD CAMERA6 ROVER5)
(CALIBRATION_TARGET CAMERA6 OBJECTIVE6)
(SUPPORTS CAMERA6 COLOUR) (SUPPORTS CAMERA6 HIGH_RES)
(SUPPORTS CAMERA6 LOW_RES)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT11)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT12)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT13)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT14)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT15)
(VISIBLE_FROM OBJECTIVE1 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT11)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT12)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT13)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT14)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT15)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT16)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT17)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT18)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT11)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT12)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT13)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT11)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT12)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT13)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT14)
(:ORIGINAL-GOAL
(AND (COMMUNICATED_SOIL_DATA WAYPOINT18)
(COMMUNICATED_SOIL_DATA WAYPOINT8)
(COMMUNICATED_SOIL_DATA WAYPOINT5)
(COMMUNICATED_ROCK_DATA WAYPOINT17)
(COMMUNICATED_ROCK_DATA WAYPOINT6)
(COMMUNICATED_ROCK_DATA WAYPOINT9)
(COMMUNICATED_ROCK_DATA WAYPOINT19)
(COMMUNICATED_ROCK_DATA WAYPOINT3)
(COMMUNICATED_ROCK_DATA WAYPOINT4)
(COMMUNICATED_IMAGE_DATA OBJECTIVE7 LOW_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE4 HIGH_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE0 COLOUR)
(COMMUNICATED_IMAGE_DATA OBJECTIVE6 LOW_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE7 COLOUR)
(COMMUNICATED_IMAGE_DATA OBJECTIVE2 LOW_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE0 HIGH_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE5 COLOUR)))
(COMMUNICATE_SOIL_DATA WAYPOINT18)
(COMMUNICATE_SOIL_DATA WAYPOINT8)
(COMMUNICATE_SOIL_DATA WAYPOINT5)
(COMMUNICATE_ROCK_DATA WAYPOINT17)
(COMMUNICATE_ROCK_DATA WAYPOINT6)
(COMMUNICATE_ROCK_DATA WAYPOINT9)
(COMMUNICATE_ROCK_DATA WAYPOINT19)
(COMMUNICATE_ROCK_DATA WAYPOINT3)
(COMMUNICATE_ROCK_DATA WAYPOINT4)
(COMMUNICATE_IMAGE_DATA OBJECTIVE7 LOW_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE4 HIGH_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE0 COLOUR)
(COMMUNICATE_IMAGE_DATA OBJECTIVE6 LOW_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE7 COLOUR)
(COMMUNICATE_IMAGE_DATA OBJECTIVE2 LOW_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE0 HIGH_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE5 COLOUR))
(:TASK ACHIEVE-GOALS))
| null |
https://raw.githubusercontent.com/shop-planner/shop3/b04d12bdf83e40590fe44bb5c68952f3fd0b5b1d/shop3/examples/rovers/strips/p19.lisp
|
lisp
|
(IN-PACKAGE :SHOP2-ROVERS)
(DEFPROBLEM ROVERPROB19 ROVER
((OBJECTIVE OBJECTIVE7) (OBJECTIVE OBJECTIVE6)
(OBJECTIVE OBJECTIVE5) (OBJECTIVE OBJECTIVE4)
(OBJECTIVE OBJECTIVE3) (OBJECTIVE OBJECTIVE2)
(OBJECTIVE OBJECTIVE1) (OBJECTIVE OBJECTIVE0)
(CAMERA CAMERA6) (CAMERA CAMERA5) (CAMERA CAMERA4)
(CAMERA CAMERA3) (CAMERA CAMERA2) (CAMERA CAMERA1)
(CAMERA CAMERA0) (WAYPOINT WAYPOINT19)
(WAYPOINT WAYPOINT18) (WAYPOINT WAYPOINT17)
(WAYPOINT WAYPOINT16) (WAYPOINT WAYPOINT15)
(WAYPOINT WAYPOINT14) (WAYPOINT WAYPOINT13)
(WAYPOINT WAYPOINT12) (WAYPOINT WAYPOINT11)
(WAYPOINT WAYPOINT10) (WAYPOINT WAYPOINT9)
(WAYPOINT WAYPOINT8) (WAYPOINT WAYPOINT7)
(WAYPOINT WAYPOINT6) (WAYPOINT WAYPOINT5)
(WAYPOINT WAYPOINT4) (WAYPOINT WAYPOINT3)
(WAYPOINT WAYPOINT2) (WAYPOINT WAYPOINT1)
(WAYPOINT WAYPOINT0) (STORE ROVER5STORE)
(STORE ROVER4STORE) (STORE ROVER3STORE)
(STORE ROVER2STORE) (STORE ROVER1STORE)
(STORE ROVER0STORE) (ROVER ROVER5) (ROVER ROVER4)
(ROVER ROVER3) (ROVER ROVER2) (ROVER ROVER1)
(ROVER ROVER0) (MODE LOW_RES) (MODE HIGH_RES)
(MODE COLOUR) (LANDER GENERAL)
(VISIBLE WAYPOINT0 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT0)
(VISIBLE WAYPOINT1 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT1)
(VISIBLE WAYPOINT2 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT2)
(VISIBLE WAYPOINT3 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT3)
(VISIBLE WAYPOINT4 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT4)
(VISIBLE WAYPOINT5 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT15)
(VISIBLE WAYPOINT15 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT5)
(VISIBLE WAYPOINT6 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT6)
(VISIBLE WAYPOINT7 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT7)
(VISIBLE WAYPOINT8 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT8)
(VISIBLE WAYPOINT9 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT9)
(VISIBLE WAYPOINT10 WAYPOINT4)
(VISIBLE WAYPOINT4 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT10)
(VISIBLE WAYPOINT11 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT8)
(VISIBLE WAYPOINT8 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT11)
(VISIBLE WAYPOINT12 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT5)
(VISIBLE WAYPOINT5 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT9)
(VISIBLE WAYPOINT9 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT15)
(VISIBLE WAYPOINT15 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT12)
(VISIBLE WAYPOINT13 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT13)
(VISIBLE WAYPOINT14 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT14)
(VISIBLE WAYPOINT15 WAYPOINT6)
(VISIBLE WAYPOINT6 WAYPOINT15)
(VISIBLE WAYPOINT15 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT15)
(VISIBLE WAYPOINT16 WAYPOINT1)
(VISIBLE WAYPOINT1 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT11)
(VISIBLE WAYPOINT11 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT16)
(VISIBLE WAYPOINT16 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT16)
(VISIBLE WAYPOINT17 WAYPOINT2)
(VISIBLE WAYPOINT2 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT3)
(VISIBLE WAYPOINT3 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT14)
(VISIBLE WAYPOINT14 WAYPOINT17)
(VISIBLE WAYPOINT18 WAYPOINT7)
(VISIBLE WAYPOINT7 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT10)
(VISIBLE WAYPOINT10 WAYPOINT18)
(VISIBLE WAYPOINT18 WAYPOINT17)
(VISIBLE WAYPOINT17 WAYPOINT18)
(VISIBLE WAYPOINT19 WAYPOINT0)
(VISIBLE WAYPOINT0 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT12)
(VISIBLE WAYPOINT12 WAYPOINT19)
(VISIBLE WAYPOINT19 WAYPOINT13)
(VISIBLE WAYPOINT13 WAYPOINT19) (AT_SOIL_SAMPLE WAYPOINT3)
(AT_ROCK_SAMPLE WAYPOINT3) (AT_ROCK_SAMPLE WAYPOINT4)
(AT_SOIL_SAMPLE WAYPOINT5) (AT_ROCK_SAMPLE WAYPOINT6)
(AT_SOIL_SAMPLE WAYPOINT8) (AT_ROCK_SAMPLE WAYPOINT9)
(AT_SOIL_SAMPLE WAYPOINT11) (AT_SOIL_SAMPLE WAYPOINT12)
(AT_SOIL_SAMPLE WAYPOINT14) (AT_SOIL_SAMPLE WAYPOINT15)
(AT_SOIL_SAMPLE WAYPOINT16) (AT_SOIL_SAMPLE WAYPOINT17)
(AT_ROCK_SAMPLE WAYPOINT17) (AT_SOIL_SAMPLE WAYPOINT18)
(AT_ROCK_SAMPLE WAYPOINT19) (AT_LANDER GENERAL WAYPOINT6)
(CHANNEL_FREE GENERAL) (AT ROVER0 WAYPOINT2)
(AVAILABLE ROVER0) (STORE_OF ROVER0STORE ROVER0)
(EMPTY ROVER0STORE) (EQUIPPED_FOR_IMAGING ROVER0)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT0)
(CAN_TRAVERSE ROVER0 WAYPOINT0 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT5)
(CAN_TRAVERSE ROVER0 WAYPOINT5 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER0 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT9)
(CAN_TRAVERSE ROVER0 WAYPOINT9 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT2 WAYPOINT18)
(CAN_TRAVERSE ROVER0 WAYPOINT18 WAYPOINT2)
(CAN_TRAVERSE ROVER0 WAYPOINT0 WAYPOINT6)
(CAN_TRAVERSE ROVER0 WAYPOINT6 WAYPOINT0)
(CAN_TRAVERSE ROVER0 WAYPOINT0 WAYPOINT13)
(CAN_TRAVERSE ROVER0 WAYPOINT13 WAYPOINT0)
(CAN_TRAVERSE ROVER0 WAYPOINT0 WAYPOINT19)
(CAN_TRAVERSE ROVER0 WAYPOINT19 WAYPOINT0)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT1)
(CAN_TRAVERSE ROVER0 WAYPOINT1 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT3)
(CAN_TRAVERSE ROVER0 WAYPOINT3 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT12)
(CAN_TRAVERSE ROVER0 WAYPOINT12 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT4 WAYPOINT17)
(CAN_TRAVERSE ROVER0 WAYPOINT17 WAYPOINT4)
(CAN_TRAVERSE ROVER0 WAYPOINT5 WAYPOINT11)
(CAN_TRAVERSE ROVER0 WAYPOINT11 WAYPOINT5)
(CAN_TRAVERSE ROVER0 WAYPOINT5 WAYPOINT15)
(CAN_TRAVERSE ROVER0 WAYPOINT15 WAYPOINT5)
(CAN_TRAVERSE ROVER0 WAYPOINT9 WAYPOINT10)
(CAN_TRAVERSE ROVER0 WAYPOINT10 WAYPOINT9)
(CAN_TRAVERSE ROVER0 WAYPOINT18 WAYPOINT8)
(CAN_TRAVERSE ROVER0 WAYPOINT8 WAYPOINT18)
(CAN_TRAVERSE ROVER0 WAYPOINT6 WAYPOINT16)
(CAN_TRAVERSE ROVER0 WAYPOINT16 WAYPOINT6)
(CAN_TRAVERSE ROVER0 WAYPOINT3 WAYPOINT14)
(CAN_TRAVERSE ROVER0 WAYPOINT14 WAYPOINT3)
(AT ROVER1 WAYPOINT6) (AVAILABLE ROVER1)
(STORE_OF ROVER1STORE ROVER1) (EMPTY ROVER1STORE)
(EQUIPPED_FOR_IMAGING ROVER1)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT0)
(CAN_TRAVERSE ROVER1 WAYPOINT0 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT8)
(CAN_TRAVERSE ROVER1 WAYPOINT8 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT13)
(CAN_TRAVERSE ROVER1 WAYPOINT13 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT15)
(CAN_TRAVERSE ROVER1 WAYPOINT15 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT16)
(CAN_TRAVERSE ROVER1 WAYPOINT16 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT6 WAYPOINT19)
(CAN_TRAVERSE ROVER1 WAYPOINT19 WAYPOINT6)
(CAN_TRAVERSE ROVER1 WAYPOINT0 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT0)
(CAN_TRAVERSE ROVER1 WAYPOINT0 WAYPOINT5)
(CAN_TRAVERSE ROVER1 WAYPOINT5 WAYPOINT0)
(CAN_TRAVERSE ROVER1 WAYPOINT0 WAYPOINT18)
(CAN_TRAVERSE ROVER1 WAYPOINT18 WAYPOINT0)
(CAN_TRAVERSE ROVER1 WAYPOINT8 WAYPOINT11)
(CAN_TRAVERSE ROVER1 WAYPOINT11 WAYPOINT8)
(CAN_TRAVERSE ROVER1 WAYPOINT13 WAYPOINT7)
(CAN_TRAVERSE ROVER1 WAYPOINT7 WAYPOINT13)
(CAN_TRAVERSE ROVER1 WAYPOINT15 WAYPOINT12)
(CAN_TRAVERSE ROVER1 WAYPOINT12 WAYPOINT15)
(CAN_TRAVERSE ROVER1 WAYPOINT16 WAYPOINT1)
(CAN_TRAVERSE ROVER1 WAYPOINT1 WAYPOINT16)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT3)
(CAN_TRAVERSE ROVER1 WAYPOINT3 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT4)
(CAN_TRAVERSE ROVER1 WAYPOINT4 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT9)
(CAN_TRAVERSE ROVER1 WAYPOINT9 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT2 WAYPOINT10)
(CAN_TRAVERSE ROVER1 WAYPOINT10 WAYPOINT2)
(CAN_TRAVERSE ROVER1 WAYPOINT5 WAYPOINT17)
(CAN_TRAVERSE ROVER1 WAYPOINT17 WAYPOINT5)
(CAN_TRAVERSE ROVER1 WAYPOINT11 WAYPOINT14)
(CAN_TRAVERSE ROVER1 WAYPOINT14 WAYPOINT11)
(AT ROVER2 WAYPOINT13) (AVAILABLE ROVER2)
(STORE_OF ROVER2STORE ROVER2) (EMPTY ROVER2STORE)
(EQUIPPED_FOR_SOIL_ANALYSIS ROVER2)
(EQUIPPED_FOR_IMAGING ROVER2)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT0)
(CAN_TRAVERSE ROVER2 WAYPOINT0 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT6)
(CAN_TRAVERSE ROVER2 WAYPOINT6 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT7)
(CAN_TRAVERSE ROVER2 WAYPOINT7 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT16)
(CAN_TRAVERSE ROVER2 WAYPOINT16 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT13 WAYPOINT19)
(CAN_TRAVERSE ROVER2 WAYPOINT19 WAYPOINT13)
(CAN_TRAVERSE ROVER2 WAYPOINT0 WAYPOINT5)
(CAN_TRAVERSE ROVER2 WAYPOINT5 WAYPOINT0)
(CAN_TRAVERSE ROVER2 WAYPOINT0 WAYPOINT9)
(CAN_TRAVERSE ROVER2 WAYPOINT9 WAYPOINT0)
(CAN_TRAVERSE ROVER2 WAYPOINT0 WAYPOINT18)
(CAN_TRAVERSE ROVER2 WAYPOINT18 WAYPOINT0)
(CAN_TRAVERSE ROVER2 WAYPOINT6 WAYPOINT8)
(CAN_TRAVERSE ROVER2 WAYPOINT8 WAYPOINT6)
(CAN_TRAVERSE ROVER2 WAYPOINT6 WAYPOINT15)
(CAN_TRAVERSE ROVER2 WAYPOINT15 WAYPOINT6)
(CAN_TRAVERSE ROVER2 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER2 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER2 WAYPOINT7 WAYPOINT4)
(CAN_TRAVERSE ROVER2 WAYPOINT4 WAYPOINT7)
(CAN_TRAVERSE ROVER2 WAYPOINT7 WAYPOINT12)
(CAN_TRAVERSE ROVER2 WAYPOINT12 WAYPOINT7)
(CAN_TRAVERSE ROVER2 WAYPOINT16 WAYPOINT1)
(CAN_TRAVERSE ROVER2 WAYPOINT1 WAYPOINT16)
(CAN_TRAVERSE ROVER2 WAYPOINT16 WAYPOINT11)
(CAN_TRAVERSE ROVER2 WAYPOINT11 WAYPOINT16)
(CAN_TRAVERSE ROVER2 WAYPOINT19 WAYPOINT14)
(CAN_TRAVERSE ROVER2 WAYPOINT14 WAYPOINT19)
(CAN_TRAVERSE ROVER2 WAYPOINT5 WAYPOINT3)
(CAN_TRAVERSE ROVER2 WAYPOINT3 WAYPOINT5)
(CAN_TRAVERSE ROVER2 WAYPOINT9 WAYPOINT10)
(CAN_TRAVERSE ROVER2 WAYPOINT10 WAYPOINT9)
(CAN_TRAVERSE ROVER2 WAYPOINT18 WAYPOINT17)
(CAN_TRAVERSE ROVER2 WAYPOINT17 WAYPOINT18)
(AT ROVER3 WAYPOINT11) (AVAILABLE ROVER3)
(STORE_OF ROVER3STORE ROVER3) (EMPTY ROVER3STORE)
(EQUIPPED_FOR_SOIL_ANALYSIS ROVER3)
(EQUIPPED_FOR_ROCK_ANALYSIS ROVER3)
(EQUIPPED_FOR_IMAGING ROVER3)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT1)
(CAN_TRAVERSE ROVER3 WAYPOINT1 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT9)
(CAN_TRAVERSE ROVER3 WAYPOINT9 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT14)
(CAN_TRAVERSE ROVER3 WAYPOINT14 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT16)
(CAN_TRAVERSE ROVER3 WAYPOINT16 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT11 WAYPOINT17)
(CAN_TRAVERSE ROVER3 WAYPOINT17 WAYPOINT11)
(CAN_TRAVERSE ROVER3 WAYPOINT1 WAYPOINT4)
(CAN_TRAVERSE ROVER3 WAYPOINT4 WAYPOINT1)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER3 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT3)
(CAN_TRAVERSE ROVER3 WAYPOINT3 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT12)
(CAN_TRAVERSE ROVER3 WAYPOINT12 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT13)
(CAN_TRAVERSE ROVER3 WAYPOINT13 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT7 WAYPOINT18)
(CAN_TRAVERSE ROVER3 WAYPOINT18 WAYPOINT7)
(CAN_TRAVERSE ROVER3 WAYPOINT9 WAYPOINT0)
(CAN_TRAVERSE ROVER3 WAYPOINT0 WAYPOINT9)
(CAN_TRAVERSE ROVER3 WAYPOINT14 WAYPOINT8)
(CAN_TRAVERSE ROVER3 WAYPOINT8 WAYPOINT14)
(CAN_TRAVERSE ROVER3 WAYPOINT14 WAYPOINT10)
(CAN_TRAVERSE ROVER3 WAYPOINT10 WAYPOINT14)
(CAN_TRAVERSE ROVER3 WAYPOINT16 WAYPOINT5)
(CAN_TRAVERSE ROVER3 WAYPOINT5 WAYPOINT16)
(CAN_TRAVERSE ROVER3 WAYPOINT16 WAYPOINT6)
(CAN_TRAVERSE ROVER3 WAYPOINT6 WAYPOINT16)
(CAN_TRAVERSE ROVER3 WAYPOINT2 WAYPOINT19)
(CAN_TRAVERSE ROVER3 WAYPOINT19 WAYPOINT2)
(CAN_TRAVERSE ROVER3 WAYPOINT12 WAYPOINT15)
(CAN_TRAVERSE ROVER3 WAYPOINT15 WAYPOINT12)
(AT ROVER4 WAYPOINT0) (AVAILABLE ROVER4)
(STORE_OF ROVER4STORE ROVER4) (EMPTY ROVER4STORE)
(EQUIPPED_FOR_SOIL_ANALYSIS ROVER4)
(EQUIPPED_FOR_ROCK_ANALYSIS ROVER4)
(EQUIPPED_FOR_IMAGING ROVER4)
(CAN_TRAVERSE ROVER4 WAYPOINT0 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT0)
(CAN_TRAVERSE ROVER4 WAYPOINT0 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT0)
(CAN_TRAVERSE ROVER4 WAYPOINT0 WAYPOINT6)
(CAN_TRAVERSE ROVER4 WAYPOINT6 WAYPOINT0)
(CAN_TRAVERSE ROVER4 WAYPOINT0 WAYPOINT18)
(CAN_TRAVERSE ROVER4 WAYPOINT18 WAYPOINT0)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT3)
(CAN_TRAVERSE ROVER4 WAYPOINT3 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER4 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT8)
(CAN_TRAVERSE ROVER4 WAYPOINT8 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT17)
(CAN_TRAVERSE ROVER4 WAYPOINT17 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT2 WAYPOINT19)
(CAN_TRAVERSE ROVER4 WAYPOINT19 WAYPOINT2)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT11)
(CAN_TRAVERSE ROVER4 WAYPOINT11 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT12)
(CAN_TRAVERSE ROVER4 WAYPOINT12 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT15)
(CAN_TRAVERSE ROVER4 WAYPOINT15 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT5 WAYPOINT16)
(CAN_TRAVERSE ROVER4 WAYPOINT16 WAYPOINT5)
(CAN_TRAVERSE ROVER4 WAYPOINT6 WAYPOINT1)
(CAN_TRAVERSE ROVER4 WAYPOINT1 WAYPOINT6)
(CAN_TRAVERSE ROVER4 WAYPOINT6 WAYPOINT13)
(CAN_TRAVERSE ROVER4 WAYPOINT13 WAYPOINT6)
(CAN_TRAVERSE ROVER4 WAYPOINT18 WAYPOINT10)
(CAN_TRAVERSE ROVER4 WAYPOINT10 WAYPOINT18)
(CAN_TRAVERSE ROVER4 WAYPOINT3 WAYPOINT4)
(CAN_TRAVERSE ROVER4 WAYPOINT4 WAYPOINT3)
(CAN_TRAVERSE ROVER4 WAYPOINT3 WAYPOINT9)
(CAN_TRAVERSE ROVER4 WAYPOINT9 WAYPOINT3)
(CAN_TRAVERSE ROVER4 WAYPOINT8 WAYPOINT14)
(CAN_TRAVERSE ROVER4 WAYPOINT14 WAYPOINT8)
(AT ROVER5 WAYPOINT12) (AVAILABLE ROVER5)
(STORE_OF ROVER5STORE ROVER5) (EMPTY ROVER5STORE)
(EQUIPPED_FOR_SOIL_ANALYSIS ROVER5)
(EQUIPPED_FOR_ROCK_ANALYSIS ROVER5)
(EQUIPPED_FOR_IMAGING ROVER5)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT1)
(CAN_TRAVERSE ROVER5 WAYPOINT1 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT4)
(CAN_TRAVERSE ROVER5 WAYPOINT4 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT5)
(CAN_TRAVERSE ROVER5 WAYPOINT5 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT7)
(CAN_TRAVERSE ROVER5 WAYPOINT7 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT9)
(CAN_TRAVERSE ROVER5 WAYPOINT9 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT10)
(CAN_TRAVERSE ROVER5 WAYPOINT10 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT14)
(CAN_TRAVERSE ROVER5 WAYPOINT14 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT15)
(CAN_TRAVERSE ROVER5 WAYPOINT15 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT12 WAYPOINT16)
(CAN_TRAVERSE ROVER5 WAYPOINT16 WAYPOINT12)
(CAN_TRAVERSE ROVER5 WAYPOINT1 WAYPOINT6)
(CAN_TRAVERSE ROVER5 WAYPOINT6 WAYPOINT1)
(CAN_TRAVERSE ROVER5 WAYPOINT1 WAYPOINT11)
(CAN_TRAVERSE ROVER5 WAYPOINT11 WAYPOINT1)
(CAN_TRAVERSE ROVER5 WAYPOINT4 WAYPOINT3)
(CAN_TRAVERSE ROVER5 WAYPOINT3 WAYPOINT4)
(CAN_TRAVERSE ROVER5 WAYPOINT4 WAYPOINT17)
(CAN_TRAVERSE ROVER5 WAYPOINT17 WAYPOINT4)
(CAN_TRAVERSE ROVER5 WAYPOINT5 WAYPOINT0)
(CAN_TRAVERSE ROVER5 WAYPOINT0 WAYPOINT5)
(CAN_TRAVERSE ROVER5 WAYPOINT5 WAYPOINT13)
(CAN_TRAVERSE ROVER5 WAYPOINT13 WAYPOINT5)
(CAN_TRAVERSE ROVER5 WAYPOINT5 WAYPOINT19)
(CAN_TRAVERSE ROVER5 WAYPOINT19 WAYPOINT5)
(CAN_TRAVERSE ROVER5 WAYPOINT7 WAYPOINT2)
(CAN_TRAVERSE ROVER5 WAYPOINT2 WAYPOINT7)
(CAN_TRAVERSE ROVER5 WAYPOINT7 WAYPOINT8)
(CAN_TRAVERSE ROVER5 WAYPOINT8 WAYPOINT7)
(CAN_TRAVERSE ROVER5 WAYPOINT7 WAYPOINT18)
(CAN_TRAVERSE ROVER5 WAYPOINT18 WAYPOINT7)
(ON_BOARD CAMERA0 ROVER2)
(CALIBRATION_TARGET CAMERA0 OBJECTIVE0)
(SUPPORTS CAMERA0 COLOUR) (SUPPORTS CAMERA0 HIGH_RES)
(SUPPORTS CAMERA0 LOW_RES) (ON_BOARD CAMERA1 ROVER1)
(CALIBRATION_TARGET CAMERA1 OBJECTIVE1)
(SUPPORTS CAMERA1 HIGH_RES) (ON_BOARD CAMERA2 ROVER1)
(CALIBRATION_TARGET CAMERA2 OBJECTIVE0)
(SUPPORTS CAMERA2 HIGH_RES) (SUPPORTS CAMERA2 LOW_RES)
(ON_BOARD CAMERA3 ROVER0)
(CALIBRATION_TARGET CAMERA3 OBJECTIVE5)
(SUPPORTS CAMERA3 HIGH_RES) (ON_BOARD CAMERA4 ROVER4)
(CALIBRATION_TARGET CAMERA4 OBJECTIVE2)
(SUPPORTS CAMERA4 COLOUR) (SUPPORTS CAMERA4 LOW_RES)
(ON_BOARD CAMERA5 ROVER3)
(CALIBRATION_TARGET CAMERA5 OBJECTIVE0)
(SUPPORTS CAMERA5 COLOUR) (SUPPORTS CAMERA5 LOW_RES)
(ON_BOARD CAMERA6 ROVER5)
(CALIBRATION_TARGET CAMERA6 OBJECTIVE6)
(SUPPORTS CAMERA6 COLOUR) (SUPPORTS CAMERA6 HIGH_RES)
(SUPPORTS CAMERA6 LOW_RES)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT11)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT12)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT13)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT14)
(VISIBLE_FROM OBJECTIVE0 WAYPOINT15)
(VISIBLE_FROM OBJECTIVE1 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE2 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE3 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT11)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT12)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT13)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT14)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT15)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT16)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT17)
(VISIBLE_FROM OBJECTIVE4 WAYPOINT18)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT11)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT12)
(VISIBLE_FROM OBJECTIVE5 WAYPOINT13)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE6 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT0)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT1)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT2)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT3)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT4)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT5)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT6)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT7)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT8)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT9)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT10)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT11)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT12)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT13)
(VISIBLE_FROM OBJECTIVE7 WAYPOINT14)
(:ORIGINAL-GOAL
(AND (COMMUNICATED_SOIL_DATA WAYPOINT18)
(COMMUNICATED_SOIL_DATA WAYPOINT8)
(COMMUNICATED_SOIL_DATA WAYPOINT5)
(COMMUNICATED_ROCK_DATA WAYPOINT17)
(COMMUNICATED_ROCK_DATA WAYPOINT6)
(COMMUNICATED_ROCK_DATA WAYPOINT9)
(COMMUNICATED_ROCK_DATA WAYPOINT19)
(COMMUNICATED_ROCK_DATA WAYPOINT3)
(COMMUNICATED_ROCK_DATA WAYPOINT4)
(COMMUNICATED_IMAGE_DATA OBJECTIVE7 LOW_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE4 HIGH_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE0 COLOUR)
(COMMUNICATED_IMAGE_DATA OBJECTIVE6 LOW_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE7 COLOUR)
(COMMUNICATED_IMAGE_DATA OBJECTIVE2 LOW_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE0 HIGH_RES)
(COMMUNICATED_IMAGE_DATA OBJECTIVE5 COLOUR)))
(COMMUNICATE_SOIL_DATA WAYPOINT18)
(COMMUNICATE_SOIL_DATA WAYPOINT8)
(COMMUNICATE_SOIL_DATA WAYPOINT5)
(COMMUNICATE_ROCK_DATA WAYPOINT17)
(COMMUNICATE_ROCK_DATA WAYPOINT6)
(COMMUNICATE_ROCK_DATA WAYPOINT9)
(COMMUNICATE_ROCK_DATA WAYPOINT19)
(COMMUNICATE_ROCK_DATA WAYPOINT3)
(COMMUNICATE_ROCK_DATA WAYPOINT4)
(COMMUNICATE_IMAGE_DATA OBJECTIVE7 LOW_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE4 HIGH_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE0 COLOUR)
(COMMUNICATE_IMAGE_DATA OBJECTIVE6 LOW_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE7 COLOUR)
(COMMUNICATE_IMAGE_DATA OBJECTIVE2 LOW_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE0 HIGH_RES)
(COMMUNICATE_IMAGE_DATA OBJECTIVE5 COLOUR))
(:TASK ACHIEVE-GOALS))
|
|
74fc8036936b4365aec658f85ec70f9d576aa72e4257ed69b425d8cbb71966e8
|
resttime/cl-liballegro
|
keyboard.lisp
|
(in-package :cl-liballegro)
Keycodes
(defcenum keycodes
(:a 1)
(:b 2)
(:c 3)
(:d 4)
(:e 5)
(:f 6)
(:g 7)
(:h 8)
(:i 9)
(:j 10)
(:k 11)
(:l 12)
(:m 13)
(:n 14)
(:o 15)
(:p 16)
(:q 17)
(:r 18)
(:s 19)
(:t 20)
(:u 21)
(:v 22)
(:w 23)
(:x 24)
(:y 25)
(:z 26)
(:0 27)
(:1 28)
(:2 29)
(:3 30)
(:4 31)
(:5 32)
(:6 33)
(:7 34)
(:8 35)
(:9 36)
(:pad-0 37)
(:pad-1 38)
(:pad-2 39)
(:pad-3 40)
(:pad-4 41)
(:pad-5 42)
(:pad-6 43)
(:pad-7 44)
(:pad-8 45)
(:pad-9 46)
(:f1 47)
(:f2 48)
(:f3 49)
(:f4 50)
(:f5 51)
(:f6 52)
(:f7 53)
(:f8 54)
(:f9 55)
(:f10 56)
(:f11 57)
(:f12 58)
(:escape 59)
(:tilde 60)
(:minus 61)
(:equals 62)
(:backspace 63)
(:tab 64)
(:openbrace 65)
(:closebrace 66)
(:enter 67)
(:semicolon 68)
(:quote 69)
(:backslash 70)
(:backslash2 71)
(:comma 72)
(:fullstop 73)
(:slash 74)
(:space 75)
(:insert 76)
(:delete 77)
(:home 78)
(:end 79)
(:pgup 80)
(:pgdn 81)
(:left 82)
(:right 83)
(:up 84)
(:down 85)
(:pad-slash 86)
(:pad-asterisk 87)
(:pad-minus 88)
(:pad-plus 89)
(:pad-delete 90)
(:pad-enter 91)
(:printscreen 92)
(:pause 93)
(:abnt-c1 94)
(:yen 95)
(:kana 96)
(:convert 97)
(:noconvert 98)
(:at 99)
(:circumflex 100)
(:colon2 101)
(:kanji 102)
(:pad_equals 103)
(:backquote 104)
(:semicolon2 105)
(:command 106)
(:unknown 128)
(:modifiers 215)
(:lshift 215)
(:rshift 216)
(:lctrl 217)
(:rctrl 218)
(:alt 219)
(:altgr 220)
(:lwin 221)
(:rwin 222)
(:menu 223)
(:scrolllock 224)
(:numlock 225)
(:capslock 226)
(:key-max 227))
;; Keyboard modifier flags
(defbitfield keymods
(:shift #x00001)
(:ctrl #x00002)
(:alt #x00004)
(:lwin #x00008)
(:rwin #x00010)
(:menu #x00020)
(:altgr #x00040)
(:command #x00080)
(:scrolllock #x00100)
(:numlock #x00200)
(:capslock #x00400)
(:INALTSEQ #x00800)
(:ACCENT1 #x01000)
(:ACCENT2 #x02000)
(:ACCENT3 #x04000)
(:ACCENT4 #x08000))
| null |
https://raw.githubusercontent.com/resttime/cl-liballegro/0f8a3a77d5c81fe14352d9a799cba20e1a3a90b4/src/constants/keyboard.lisp
|
lisp
|
Keyboard modifier flags
|
(in-package :cl-liballegro)
Keycodes
(defcenum keycodes
(:a 1)
(:b 2)
(:c 3)
(:d 4)
(:e 5)
(:f 6)
(:g 7)
(:h 8)
(:i 9)
(:j 10)
(:k 11)
(:l 12)
(:m 13)
(:n 14)
(:o 15)
(:p 16)
(:q 17)
(:r 18)
(:s 19)
(:t 20)
(:u 21)
(:v 22)
(:w 23)
(:x 24)
(:y 25)
(:z 26)
(:0 27)
(:1 28)
(:2 29)
(:3 30)
(:4 31)
(:5 32)
(:6 33)
(:7 34)
(:8 35)
(:9 36)
(:pad-0 37)
(:pad-1 38)
(:pad-2 39)
(:pad-3 40)
(:pad-4 41)
(:pad-5 42)
(:pad-6 43)
(:pad-7 44)
(:pad-8 45)
(:pad-9 46)
(:f1 47)
(:f2 48)
(:f3 49)
(:f4 50)
(:f5 51)
(:f6 52)
(:f7 53)
(:f8 54)
(:f9 55)
(:f10 56)
(:f11 57)
(:f12 58)
(:escape 59)
(:tilde 60)
(:minus 61)
(:equals 62)
(:backspace 63)
(:tab 64)
(:openbrace 65)
(:closebrace 66)
(:enter 67)
(:semicolon 68)
(:quote 69)
(:backslash 70)
(:backslash2 71)
(:comma 72)
(:fullstop 73)
(:slash 74)
(:space 75)
(:insert 76)
(:delete 77)
(:home 78)
(:end 79)
(:pgup 80)
(:pgdn 81)
(:left 82)
(:right 83)
(:up 84)
(:down 85)
(:pad-slash 86)
(:pad-asterisk 87)
(:pad-minus 88)
(:pad-plus 89)
(:pad-delete 90)
(:pad-enter 91)
(:printscreen 92)
(:pause 93)
(:abnt-c1 94)
(:yen 95)
(:kana 96)
(:convert 97)
(:noconvert 98)
(:at 99)
(:circumflex 100)
(:colon2 101)
(:kanji 102)
(:pad_equals 103)
(:backquote 104)
(:semicolon2 105)
(:command 106)
(:unknown 128)
(:modifiers 215)
(:lshift 215)
(:rshift 216)
(:lctrl 217)
(:rctrl 218)
(:alt 219)
(:altgr 220)
(:lwin 221)
(:rwin 222)
(:menu 223)
(:scrolllock 224)
(:numlock 225)
(:capslock 226)
(:key-max 227))
(defbitfield keymods
(:shift #x00001)
(:ctrl #x00002)
(:alt #x00004)
(:lwin #x00008)
(:rwin #x00010)
(:menu #x00020)
(:altgr #x00040)
(:command #x00080)
(:scrolllock #x00100)
(:numlock #x00200)
(:capslock #x00400)
(:INALTSEQ #x00800)
(:ACCENT1 #x01000)
(:ACCENT2 #x02000)
(:ACCENT3 #x04000)
(:ACCENT4 #x08000))
|
ebd9a390665435af37e5e83a09e1bdbcbd1ba97b46514082faab48c3759d80aa
|
oden-lang/oden
|
InferDefinitionSpec.hs
|
module Oden.Infer.InferDefinitionSpec where
import Test.Hspec
import qualified Data.Set as Set
import Oden.Core.Typed as Typed
import Oden.Core.Untyped as Untyped
import Oden.Core.Expr
import Oden.QualifiedName
import Oden.Environment
import Oden.Identifier
import qualified Oden.Infer as Infer
import Oden.Infer.Environment
import Oden.Predefined
import Oden.Type.Polymorphic
import Oden.Assertions
import Oden.Infer.Fixtures
inferDefinition :: TypingEnvironment -> Untyped.Definition -> Either Infer.TypeError Typed.TypedDefinition
inferDefinition env def = snd <$> Infer.inferDefinition env def
spec :: Spec
spec = describe "inferDefinition" $ do
it "infers 'n = 1 + 1'" $
inferDefinition predef (Untyped.Definition
missing
(nameInUniverse "n")
Nothing
(Application
missing
(Application
missing
(MethodReference missing (NamedMethodReference (Identifier "Num") (Identifier "Add")) Untyped)
(Literal missing (Int 1) Untyped)
Untyped)
(Literal missing (Int 1) Untyped)
Untyped))
`shouldSucceedWith`
let constraint = ProtocolConstraint missing (nameInUniverse "Num") typeInt in
tDefinition
(nameInUniverse "n")
(scheme typeInt,
tApplication
(tApplication
(MethodReference
missing
(Unresolved (nameInUniverse "Num") (Identifier "Add") constraint)
(TConstrained (Set.singleton constraint) (typeFn typeInt (typeFn typeInt typeInt))))
(tLiteral (tInt 1) typeInt)
(typeFn typeInt typeInt))
(tLiteral (tInt 1) typeInt)
typeInt)
it "infers definition without type signature" $
inferDefinition empty (Untyped.Definition missing (nameInUniverse "x") Nothing (Literal missing (Int 1) Untyped))
`shouldSucceedWith`
tDefinition (nameInUniverse "x") (scheme typeInt, tLiteral (tInt 1) typeInt)
it "infers polymorphic definition without type signature" $
shouldSucceed $
inferDefinition
empty
(Untyped.Definition
missing
(nameInUniverse "id")
Nothing
(Fn missing (NameBinding missing (Identifier "x")) (Symbol missing (Identifier "x") Untyped) Untyped))
it "infers definition with type signature" $
inferDefinition predef (Untyped.Definition
missing
(nameInUniverse "x")
(Just $ implicit (tsSymbol (Identifier "int")))
(Literal missing (Int 1) Untyped))
`shouldSucceedWith`
tDefinition (nameInUniverse "x") (scheme typeInt, tLiteral (tInt 1) typeInt)
it "infers polymorphic definition with type signature" $
inferDefinition empty (Untyped.Definition
missing
(nameInUniverse "id")
(Just $ explicit [varBinding "a"] (tsFn (tsVar "a") (tsVar "a")))
(Fn missing (NameBinding missing (Identifier "x")) (Symbol missing (Identifier "x") Untyped) Untyped))
`shouldSucceedWith`
tDefinition (nameInUniverse "id") ( scheme (typeFn tvarA tvarA)
, tFn
(tNameBinding (Identifier "x"))
(tSymbol (Identifier "x") tvarA)
(typeFn tvarA tvarA))
it "fails when specified type signature does not unify" $
shouldFail $
inferDefinition empty (Untyped.Definition
missing
(nameInUniverse "some-number")
(Just $ implicit (tsSymbol (Identifier "bool")))
(Literal missing (Int 1) Untyped))
it "infers twice function with correct type signature" $
inferDefinition
empty
(Untyped.Definition
missing
(nameInUniverse "twice")
(Just $ explicit [varBinding "a"] (tsFn (tsFn (tsVar "a") (tsVar "a")) (tsFn (tsVar "a") (tsVar "a"))))
twiceUntyped)
`shouldSucceedWith`
twiceTyped
it "fails on twice function with incorrect type signature" $
shouldFail $
inferDefinition empty (Untyped.Definition
missing
(nameInUniverse "twice")
(Just $ explicit [varBinding "a"] (tsFn (tsVar "a") (tsVar "a")))
twiceUntyped)
it "infers recursive definition" $
inferDefinition
predef
(Untyped.Definition
missing
(nameInUniverse "f")
(Just $ implicit (tsFn (tsSymbol (Identifier "int")) (tsSymbol (Identifier "int"))))
countToZero)
`shouldSucceedWith`
countToZeroTyped
it "infers recursive definition without type signature" $
inferDefinition predef (Untyped.Definition missing (nameInUniverse "f") Nothing countToZero)
`shouldSucceedWith`
countToZeroTyped
it "fails on recursive with incorrect signature" $
shouldFail $
inferDefinition
predef
(Untyped.Definition
missing
(nameInUniverse "f")
(Just $ implicit (tsFn (tsSymbol (Identifier "int")) (tsSymbol (Identifier "any"))))
countToZero)
it "infers record field access fn definition with type signature" $
let recordType = typeRecord (rowExt (Identifier "foo") tvarA tvarB)
functionType = typeFn recordType tvarA in
inferDefinition
predef
(Untyped.Definition
missing
(nameInUniverse "f")
(Just $ explicit [varBinding "a", varBinding "b"] (tsFn (tsRecord (tsRowExt (Identifier "foo") (tsVar "a") (tsVar "b"))) (tsVar "a")))
(Fn
missing
(NameBinding missing (Identifier "x"))
(MemberAccess
missing
(NamedMemberAccess (Symbol missing (Identifier "x") Untyped) (Identifier "foo"))
Untyped)
Untyped))
`shouldSucceedWith`
tDefinition
(nameInUniverse "f")
(scheme functionType,
tFn
(tNameBinding (Identifier "x"))
(MemberAccess
missing
(RecordFieldAccess (tSymbol (Identifier "x") recordType) (Identifier "foo"))
tvarA)
functionType)
| null |
https://raw.githubusercontent.com/oden-lang/oden/10c99b59c8b77c4db51ade9a4d8f9573db7f4d14/test/Oden/Infer/InferDefinitionSpec.hs
|
haskell
|
module Oden.Infer.InferDefinitionSpec where
import Test.Hspec
import qualified Data.Set as Set
import Oden.Core.Typed as Typed
import Oden.Core.Untyped as Untyped
import Oden.Core.Expr
import Oden.QualifiedName
import Oden.Environment
import Oden.Identifier
import qualified Oden.Infer as Infer
import Oden.Infer.Environment
import Oden.Predefined
import Oden.Type.Polymorphic
import Oden.Assertions
import Oden.Infer.Fixtures
inferDefinition :: TypingEnvironment -> Untyped.Definition -> Either Infer.TypeError Typed.TypedDefinition
inferDefinition env def = snd <$> Infer.inferDefinition env def
spec :: Spec
spec = describe "inferDefinition" $ do
it "infers 'n = 1 + 1'" $
inferDefinition predef (Untyped.Definition
missing
(nameInUniverse "n")
Nothing
(Application
missing
(Application
missing
(MethodReference missing (NamedMethodReference (Identifier "Num") (Identifier "Add")) Untyped)
(Literal missing (Int 1) Untyped)
Untyped)
(Literal missing (Int 1) Untyped)
Untyped))
`shouldSucceedWith`
let constraint = ProtocolConstraint missing (nameInUniverse "Num") typeInt in
tDefinition
(nameInUniverse "n")
(scheme typeInt,
tApplication
(tApplication
(MethodReference
missing
(Unresolved (nameInUniverse "Num") (Identifier "Add") constraint)
(TConstrained (Set.singleton constraint) (typeFn typeInt (typeFn typeInt typeInt))))
(tLiteral (tInt 1) typeInt)
(typeFn typeInt typeInt))
(tLiteral (tInt 1) typeInt)
typeInt)
it "infers definition without type signature" $
inferDefinition empty (Untyped.Definition missing (nameInUniverse "x") Nothing (Literal missing (Int 1) Untyped))
`shouldSucceedWith`
tDefinition (nameInUniverse "x") (scheme typeInt, tLiteral (tInt 1) typeInt)
it "infers polymorphic definition without type signature" $
shouldSucceed $
inferDefinition
empty
(Untyped.Definition
missing
(nameInUniverse "id")
Nothing
(Fn missing (NameBinding missing (Identifier "x")) (Symbol missing (Identifier "x") Untyped) Untyped))
it "infers definition with type signature" $
inferDefinition predef (Untyped.Definition
missing
(nameInUniverse "x")
(Just $ implicit (tsSymbol (Identifier "int")))
(Literal missing (Int 1) Untyped))
`shouldSucceedWith`
tDefinition (nameInUniverse "x") (scheme typeInt, tLiteral (tInt 1) typeInt)
it "infers polymorphic definition with type signature" $
inferDefinition empty (Untyped.Definition
missing
(nameInUniverse "id")
(Just $ explicit [varBinding "a"] (tsFn (tsVar "a") (tsVar "a")))
(Fn missing (NameBinding missing (Identifier "x")) (Symbol missing (Identifier "x") Untyped) Untyped))
`shouldSucceedWith`
tDefinition (nameInUniverse "id") ( scheme (typeFn tvarA tvarA)
, tFn
(tNameBinding (Identifier "x"))
(tSymbol (Identifier "x") tvarA)
(typeFn tvarA tvarA))
it "fails when specified type signature does not unify" $
shouldFail $
inferDefinition empty (Untyped.Definition
missing
(nameInUniverse "some-number")
(Just $ implicit (tsSymbol (Identifier "bool")))
(Literal missing (Int 1) Untyped))
it "infers twice function with correct type signature" $
inferDefinition
empty
(Untyped.Definition
missing
(nameInUniverse "twice")
(Just $ explicit [varBinding "a"] (tsFn (tsFn (tsVar "a") (tsVar "a")) (tsFn (tsVar "a") (tsVar "a"))))
twiceUntyped)
`shouldSucceedWith`
twiceTyped
it "fails on twice function with incorrect type signature" $
shouldFail $
inferDefinition empty (Untyped.Definition
missing
(nameInUniverse "twice")
(Just $ explicit [varBinding "a"] (tsFn (tsVar "a") (tsVar "a")))
twiceUntyped)
it "infers recursive definition" $
inferDefinition
predef
(Untyped.Definition
missing
(nameInUniverse "f")
(Just $ implicit (tsFn (tsSymbol (Identifier "int")) (tsSymbol (Identifier "int"))))
countToZero)
`shouldSucceedWith`
countToZeroTyped
it "infers recursive definition without type signature" $
inferDefinition predef (Untyped.Definition missing (nameInUniverse "f") Nothing countToZero)
`shouldSucceedWith`
countToZeroTyped
it "fails on recursive with incorrect signature" $
shouldFail $
inferDefinition
predef
(Untyped.Definition
missing
(nameInUniverse "f")
(Just $ implicit (tsFn (tsSymbol (Identifier "int")) (tsSymbol (Identifier "any"))))
countToZero)
it "infers record field access fn definition with type signature" $
let recordType = typeRecord (rowExt (Identifier "foo") tvarA tvarB)
functionType = typeFn recordType tvarA in
inferDefinition
predef
(Untyped.Definition
missing
(nameInUniverse "f")
(Just $ explicit [varBinding "a", varBinding "b"] (tsFn (tsRecord (tsRowExt (Identifier "foo") (tsVar "a") (tsVar "b"))) (tsVar "a")))
(Fn
missing
(NameBinding missing (Identifier "x"))
(MemberAccess
missing
(NamedMemberAccess (Symbol missing (Identifier "x") Untyped) (Identifier "foo"))
Untyped)
Untyped))
`shouldSucceedWith`
tDefinition
(nameInUniverse "f")
(scheme functionType,
tFn
(tNameBinding (Identifier "x"))
(MemberAccess
missing
(RecordFieldAccess (tSymbol (Identifier "x") recordType) (Identifier "foo"))
tvarA)
functionType)
|
|
c9968eb29f522d0d2aa5f46fa7030953b3e6a812695181b925ce5fe764d91c28
|
defaultxr/cl-patterns
|
patterns.lisp
|
;;;; patterns.lisp - basic pattern functionality (`defpattern', etc) and a variety of basic patterns implemented with it.
(in-package #:cl-patterns)
;;; pattern glue
(defun make-default-event ()
"Get `*event*' if it's not nil, or get a fresh empty event."
(or *event* (event)))
(defvar *patterns* (list)
"List of the names of all defined pattern types.")
(defmacro defpattern (name superclasses slots &key documentation defun)
"Define a pattern. This macro automatically generates the pattern's class, its pstream class, and the function to create an instance of the pattern, and makes them external in the cl-patterns package.
NAME is the name of the pattern. Typically a word or two that describes its function, prefixed with p.
SUPERCLASSES is a list of superclasses of the pattern. Most patterns just subclass the 'pattern' class.
SLOTS is a list of slots that the pattern and pstreams derived from it have. Each slot can either be just a symbol, or a slot definition a la `defclass'. You can provide a default for the slot with the :initform key as usual, and you can set a slot as a state slot (which only appears in the pattern's pstream class) by setting the :state key to t.
DOCUMENTATION is a docstring describing the pattern. We recommend providing at least one example, and a \"See also\" section to refer to similar pattern classes.
DEFUN can either be a full defun form for the pattern, or an expression which will be inserted into the pattern creation function prior to initialization of the instance. Typically you'd use this for inserting `assert' statements, for example.
See also: `pattern', `pdef', `all-patterns'"
(let* ((superclasses (or superclasses (list 'pattern)))
(slots (mapcar #'ensure-list slots))
(name-pstream (pattern-pstream-class-name name))
(super-pstream (if (eql 'pattern (car superclasses))
'pstream
(pattern-pstream-class-name (car superclasses)))))
(labels ((desugar-slot (slot)
"Convert a slot into something appropriate for defclass to handle."
(destructuring-bind (name . rest) slot
(append (list name)
(remove-from-plist rest :state)
(unless (position :initarg (keys rest))
(list :initarg (make-keyword name))))))
(optional-slot-p (slot)
"Whether the slot is optional or not. A slot is considered optional if an initform is provided."
(position :initform (keys (cdr slot))))
(state-slot-p (slot)
"Whether the slot is a pstream state slot or not. Pstream state slots only appear as slots for the pattern's pstream class and not for the pattern itself."
(position :state (keys (cdr slot))))
(function-lambda-list (slots)
"Generate the lambda list for the pattern's creation function."
(let (optional-used)
(mappend (fn (unless (state-slot-p _)
(if (optional-slot-p _)
(prog1
(append (unless optional-used
(list '&optional))
(list (list (car _) (getf (cdr _) :initform))))
(setf optional-used t))
(list (car _)))))
slots)))
(make-defun (pre-init)
`(defun ,name ,(function-lambda-list slots)
,documentation
,@(when pre-init (list pre-init))
(make-instance ',name
,@(mappend (fn (unless (state-slot-p _)
(list (make-keyword (car _)) (car _))))
slots))))
(add-doc-to-defun (sexp)
(if (and (listp sexp)
(position (car sexp) (list 'defun 'defmacro))
(not (stringp (fourth sexp))))
(append (subseq sexp 0 3) (list documentation) (subseq sexp 3))
sexp)))
`(progn
(defclass ,name ,superclasses
,(mapcar #'desugar-slot (remove-if #'state-slot-p slots))
,@(when documentation
`((:documentation ,documentation))))
(defmethod print-object ((,name ,name) stream)
(print-unreadable-object (,name stream :type t)
(format stream "~{~S~^ ~}"
(mapcar (lambda (slot) (slot-value ,name slot))
',(mapcar #'car (remove-if (lambda (slot)
(or (state-slot-p slot)
;; FIX: don't show arguments that are set to the defaults?
))
slots))))))
(defclass ,name-pstream (,super-pstream ,name)
,(mapcar #'desugar-slot (remove-if-not #'state-slot-p slots))
(:documentation ,(format nil "pstream for `~A'." (string-downcase name))))
,(let* ((gen-func-p (or (null defun)
(and (listp defun)
(position (car defun) (list 'assert 'check-type)))))
(pre-init (when gen-func-p
defun)))
(if gen-func-p
(make-defun pre-init)
(add-doc-to-defun defun)))
(pushnew ',name *patterns*)))))
(defvar *max-pattern-yield-length* 256
"The default maximum number of events or values that will be used by functions like `next-n' or patterns like `protate', in order to prevent hangs caused by infinite-length patterns.")
;;; pattern
(defgeneric pattern-source (pattern)
(:documentation "The source object that this object was created from. For example, for a `pstream', this would be the pattern that `as-pstream' was called on."))
(defgeneric pstream-count (pattern)
(:documentation "The number of pstreams that have been made of this pattern."))
(defclass pattern ()
((play-quant :initarg :play-quant :documentation "A list of numbers representing when the pattern's pstream can start playing. See `play-quant' and `quant'.")
(end-quant :initarg :end-quant :accessor end-quant :type list :documentation "A list of numbers representing when a pattern can end playing and when a `pdef' can be swapped out for a new definition. See `end-quant' and `quant'.")
(end-condition :initarg :end-condition :initform nil :accessor end-condition :type (or null function) :documentation "Nil or a function that is called by the clock with the pattern as its argument to determine whether the pattern should end or swap to a new definition.")
(source :initarg :source :initform nil :accessor pattern-source :documentation "The source object that this object was created from. For example, for a `pstream', this would be the pattern that `as-pstream' was called on.")
(parent :initarg :parent :initform nil :documentation "When a pattern is embedded in another pattern, the embedded pattern's parent slot points to the pattern it is embedded in.")
(loop-p :initarg :loop-p :documentation "Whether or not the pattern should loop when played.")
(cleanup :initarg :cleanup :initform (list) :documentation "A list of functions that are run when the pattern ends or is stopped.")
(pstream-count :initform 0 :accessor pstream-count :documentation "The number of pstreams that have been made of this pattern.")
(metadata :initarg :metadata :initform (make-hash-table) :type hash-table :documentation "Hash table of additional data associated with the pattern, accessible with the `pattern-metadata' function."))
(:documentation "Abstract pattern superclass."))
(defun set-parents (pattern)
"Loop through PATTERN's slots and set the \"parent\" slot of any patterns to this pattern."
(labels ((set-parent (list parent)
"Recurse through LIST, setting the parent of any pattern found to PARENT."
(typecase list
(list
(mapc (lambda (x) (set-parent x parent)) list))
(pattern
(setf (slot-value list 'parent) parent)))))
(dolist (slot (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pattern))) pattern)
(when (and (not (eql slot 'parent))
(slot-boundp pattern slot))
(set-parent (slot-value pattern slot) pattern)))))
(defmethod initialize-instance :after ((pattern pattern) &key)
(set-parents pattern))
(defun pattern-p (object)
"True if OBJECT is a pattern.
See also: `pattern', `defpattern'"
(typep object 'pattern))
(defun all-patterns ()
"Get a list of the names of all defined pattern classes.
See also: `all-pdefs'"
*patterns*)
(defmethod play-quant ((pattern pattern))
(if (slot-boundp pattern 'play-quant)
(slot-value pattern 'play-quant)
(list 1)))
(defmethod (setf play-quant) (value (pattern pattern))
(setf (slot-value pattern 'play-quant) (ensure-list value)))
(defmethod end-quant ((pattern pattern))
(when (slot-boundp pattern 'end-quant)
(slot-value pattern 'end-quant)))
(defmethod (setf end-quant) (value (pattern pattern))
(setf (slot-value pattern 'end-quant) (ensure-list value)))
(defmethod play ((pattern pattern))
(clock-add (as-pstream pattern) *clock*))
(defmethod launch ((pattern pattern))
(play pattern))
(defmethod playing-p ((pattern pattern) &optional (clock *clock*))
(when clock
(find pattern (clock-tasks clock)
:key (fn (slot-value _ 'item)))))
(defmethod loop-p ((pattern pattern))
(when (slot-boundp pattern 'loop-p)
(slot-value pattern 'loop-p)))
(defmethod (setf loop-p) (value (pattern pattern))
(setf (slot-value pattern 'loop-p) value))
(defmethod dur ((pattern pattern))
(reduce #'+ (next-upto-n pattern) :key #'dur))
(defun pattern-parent (pattern &key (num 1) (accumulate nil) (class 'pattern))
"Get the NUM-th containing pattern of PATTERN, or nil if there isn't one. If CLASS is specified, only consider patterns of that class.
See also: `pattern-children'"
(check-type num (integer 0))
(let ((i 0)
res)
(until (or (>= i num)
(null pattern))
(setf pattern (slot-value pattern 'parent))
(when (typep pattern class)
(incf i)
(when accumulate
(appendf res pattern))))
(if accumulate
res
pattern)))
(defun pattern-children (pattern &key (num 1) (accumulate nil) (class 'pattern))
"Get a list of all the direct child patterns of PATTERN, including any in slots or lists.
See also: `pattern-parent'"
(let ((cur (list pattern))
res)
(dotimes (n num res)
(setf cur (remove-if-not (lambda (pattern) (typep pattern class))
(mapcan #'%pattern-children cur)))
(if accumulate
(appendf res cur)
(setf res cur)))))
(defmethod %pattern-children ((object t))
nil)
(defmethod %pattern-children ((pattern pattern))
(mapcan (lambda (slot)
(copy-list (ensure-list (slot-value pattern (closer-mop:slot-definition-name slot)))))
(closer-mop:class-direct-slots (class-of pattern))))
(defgeneric pattern-metadata (pattern &optional key)
(:documentation "Get the value of PATTERN's metadata for KEY. Returns true as a second value if the metadata had an entry for KEY, or nil if it did not."))
(defmethod pattern-metadata ((pattern pattern) &optional key)
(with-slots (metadata) pattern
(if key
(gethash key metadata)
metadata)))
(defun (setf pattern-metadata) (value pattern key)
(setf (gethash key (slot-value pattern 'metadata)) value))
(defgeneric peek (pattern)
(:documentation "\"Peek\" at the next value of a pstream, without advancing its current position.
See also: `next', `peek-n', `peek-upto-n'"))
(defun peek-n (pstream &optional (n *max-pattern-yield-length*))
"Peek at the next N results of a pstream, without advancing it forward in the process.
See also: `peek', `peek-upto-n', `next', `next-n'"
(check-type n (integer 0))
(unless (pstream-p pstream)
(return-from peek-n (peek-n (as-pstream pstream) n)))
(with-slots (number future-number) pstream
(loop :for i :from 0 :below n
:collect (pstream-elt-future pstream (+ number (- future-number) i)))))
(defun peek-upto-n (pstream &optional (n *max-pattern-yield-length*))
"Peek at up to the next N results of a pstream, without advancing it forward in the process.
See also: `peek', `peek-n', `next', `next-upto-n'"
(check-type n (integer 0))
(unless (pstream-p pstream)
(return-from peek-upto-n (peek-upto-n (as-pstream pstream) n)))
(with-slots (number future-number) pstream
(loop :for i :from 0 :below n
:for res := (pstream-elt-future pstream (+ number (- future-number) i))
:until (eop-p res)
:collect res)))
(defgeneric next (pattern)
(:documentation "Get the next value of a pstream, function, or other object, advancing the pstream forward in the process.
See also: `next-n', `next-upto-n', `peek'")
(:method-combination pattern))
(defmethod next ((object t))
object)
(defmethod next ((pattern pattern))
(next (as-pstream pattern)))
(defmethod next ((function function))
(funcall function))
(defun next-n (pstream &optional (n *max-pattern-yield-length*))
"Get the next N outputs of a pstream, function, or other object, advancing the pstream forward N times in the process.
See also: `next', `next-upto-n', `peek', `peek-n'"
(check-type n (integer 0))
(let ((pstream (pattern-as-pstream pstream)))
(loop :repeat n
:collect (next pstream))))
(defun next-upto-n (pstream &optional (n *max-pattern-yield-length*))
"Get a list of up to N results from PSTREAM, not including the end of pattern.
See also: `next', `next-n', `peek', `peek-upto-n'"
(check-type n (integer 0))
(let ((pstream (pattern-as-pstream pstream)))
(loop
:for number :from 0 :upto n
:while (< number n)
:for val := (next pstream)
:if (eop-p val)
:do (loop-finish)
:else
:collect val)))
(defgeneric bsubseq (object start-beat &optional end-beat)
(:documentation "\"Beat subseq\" - get a list of all events from OBJECT whose `beat' is START-BEAT or above, and below END-BEAT.
See also: `events-in-range'"))
(defgeneric events-in-range (pstream min max)
(:documentation "Get all the events from PSTREAM whose start beat are MIN or greater, and less than MAX."))
(defmethod events-in-range ((pattern pattern) min max)
(events-in-range (as-pstream pattern) min max))
;;; pstream
;; FIX: can we avoid making this inherit from pattern?
(defclass pstream (pattern #+#.(cl:if (cl:find-package "SEQUENCE") '(:and) '(:or)) sequence)
((number :initform 0 :documentation "The number of outputs yielded from this pstream and any sub-pstreams that have ended.") ; FIX: rename to this-index ?
(pattern-stack :initform (list) :documentation "The stack of pattern pstreams embedded in this pstream.")
(pstream-count :initarg :pstream-count :accessor pstream-count :type integer :documentation "How many times a pstream was made of this pstream's source prior to this pstream. For example, if it was the first time `as-pstream' was called on the pattern, this will be 0.")
(beat :initform 0 :reader beat :type number :documentation "The number of beats that have elapsed since the start of the pstream.")
(history :type vector :documentation "The history of outputs yielded by the pstream.")
(history-number :initform 0 :documentation "The number of items in this pstream's history. Differs from the number slot in that all outputs are immediately included in its count.")
(start-beat :initarg :start-beat :initform nil :documentation "The beat number of the parent pstream when this pstream started.")
(future-number :initform 0 :documentation "The number of peeks into the future that have been made in the pstream. For example, if `peek' is used once, this would be 1. If `next' is called after that, future-number decreases back to 0.")
(future-beat :initform 0 :documentation "The current beat including all future outputs (the `beat' slot does not include peeked outputs)."))
(:documentation "\"Pattern stream\". Keeps track of the current state of a pattern in process of yielding its outputs."))
(defmethod initialize-instance :before ((pstream pstream) &key)
(with-slots (history) pstream
(setf history (make-array *max-pattern-yield-length* :initial-element nil))))
(defmethod initialize-instance :after ((pstream pstream) &key)
(set-parents pstream))
(defmethod print-object ((pstream pstream) stream)
(with-slots (number) pstream
(print-unreadable-object (pstream stream :type t)
(format stream "~S ~S" :number number))))
(defun pstream-p (object)
"True if OBJECT is a pstream.
See also: `pstream', `as-pstream'"
(typep object 'pstream))
(defmethod loop-p ((pstream pstream))
(if (slot-boundp pstream 'loop-p)
(slot-value pstream 'loop-p)
(loop-p (slot-value pstream 'source))))
(defmethod ended-p ((pstream pstream))
(with-slots (number future-number) pstream
(and (not (zerop (- number future-number)))
(eop-p (pstream-elt pstream -1)))))
(defmethod events-in-range ((pstream pstream) min max)
(while (and (<= (beat pstream) max)
(not (ended-p pstream)))
(let ((next (next pstream)))
(unless (typep next '(or null event))
(error "events-in-range can only be used on event streams."))))
(loop :for i :across (slot-value pstream 'history)
:if (and i
(>= (beat i) min)
(< (beat i) max))
:collect i
:if (or (eop-p i)
(>= (beat i) max))
:do (loop-finish)))
(defgeneric last-output (pstream)
(:documentation "Returns the last output yielded by PSTREAM.
Example:
( defparameter * pstr * ( as - pstream ( pseq ' ( 1 2 3 ) 1 ) ) )
( next * pstr * ) ; = > 1
( last - output * pstr * ) ; = > 1
See also: `ended-p'"))
(defmethod last-output ((pstream pstream))
(with-slots (number future-number) pstream
(let ((idx (- number future-number)))
(when (plusp idx)
(pstream-elt pstream (- idx (if (ended-p pstream) 2 1)))))))
(defun value-remaining-p (value)
i.e. VALUE is a symbol ( i.e. : ) , or a number greater than 0 .
See also: `remaining-p', `decf-remaining'"
(typecase value
(null nil)
(symbol (eql value :inf))
(number (plusp value))
(otherwise nil)))
(defun remaining-p (pattern &optional (repeats-key 'repeats) (remaining-key 'current-repeats-remaining))
"True if PATTERN's REMAINING-KEY slot value represents outputs \"remaining\" (see `value-remaining-p'). If PATTERN's REMAINING-KEY slot is unbound or 0, and REPEATS-KEY is not nil, then it is automatically set to the `next' of PATTERN's REPEATS-KEY slot. Then if that new value is 0 or nil, remaining-p returns nil. Otherwise, :reset is returned as a generalized true value and to indicate that `next' was called on PATTERN's REPEATS-KEY slot.
See also: `value-remaining-p', `decf-remaining'"
(labels ((set-next ()
(setf (slot-value pattern remaining-key) (next (slot-value pattern repeats-key)))
(when (value-remaining-p (slot-value pattern remaining-key))
:reset)))
(if (not (slot-boundp pattern remaining-key))
(set-next)
(let ((rem-key (slot-value pattern remaining-key)))
(typecase rem-key
(null nil)
(symbol (eql rem-key :inf))
(number (if (plusp rem-key)
t
if it 's already set to 0 , it was decf'd to 0 in the pattern , so we get the next one . if the next is 0 , THEN we return nil .
(otherwise nil))))))
(defun decf-remaining (pattern &optional (key 'current-repeats-remaining))
"Decrease PATTERN's KEY value.
See also: `remaining-p'"
(when (numberp (slot-value pattern key))
(decf (slot-value pattern key))))
(defmethod peek ((pstream pstream))
(with-slots (number future-number) pstream
(pstream-elt-future pstream (- number future-number))))
(defmethod peek ((pattern pattern))
(next (as-pstream pattern)))
(defmethod next ((pstream pstream))
;; fallback method; patterns should override their pstream subclasses with their own behaviors
nil)
(defmethod next :around ((pstream pstream))
(labels ((get-value-from-stack (pattern)
(with-slots (number pattern-stack) pattern
(if pattern-stack
(let* ((popped (pop pattern-stack))
(nv (next popped)))
(if (eop-p nv)
(get-value-from-stack pattern)
(progn
(push popped pattern-stack)
nv)))
(prog1
(let ((res (call-next-method)))
(typecase res
(pattern
(if (typep pattern '(or function t-pstream))
res
(progn ; if `next' returns a pattern, we push it to the pattern stack as a pstream
(let ((pstr (as-pstream res)))
(setf (slot-value pstr 'start-beat) (beat pattern))
(push pstr pattern-stack))
(get-value-from-stack pattern))))
(t res)))
(incf number))))))
(with-slots (number history history-number future-number) pstream
(let ((result (if (plusp future-number)
(let ((result (elt history (- number future-number))))
(decf future-number)
(when (event-p result)
(incf (slot-value pstream 'beat) (event-value result :delta)))
result)
(let ((result (restart-case
(get-value-from-stack pstream)
(yield-output (&optional (value 1))
:report (lambda (s) (format s "Yield an alternate output for ~S." pstream))
:interactive (lambda ()
(format *query-io* "~&Enter a form to yield: ")
(finish-output *query-io*)
(list (eval (read *query-io*))))
value))))
(when (event-p result)
(setf result (copy-event result))
(when (and (null (raw-event-value result :beat))
(null (slot-value pstream 'parent)))
(setf (beat result) (slot-value pstream 'future-beat)))
(incf (slot-value pstream 'beat) (event-value result :delta))
(incf (slot-value pstream 'future-beat) (event-value result :delta)))
(setf (elt history (mod history-number (length (slot-value pstream 'history)))) result)
(incf history-number)
result))))
(unless (pattern-parent pstream)
(dolist (proc *post-pattern-output-processors*)
(setf result (funcall proc result pstream))))
result))))
(defvar *post-pattern-output-processors* (list 'remap-instrument-to-parameters)
"List of functions that are applied as the last step of pattern output generation. Each output yielded by an \"outermost\" pattern (i.e. one without a `pattern-parent') will be processed (along with the pstream as a second argument) through each function in this list, allowing for arbitrary transformations of the generated outputs. The return value of each function is used as the input to the next function, and the return value of the last function is used as the output yielded by the pattern.
in fact this feature is already implemented more conveniently with the setf - able ` instrument - mapping ' function .
See also: `*instrument-map*', `remap-instrument-to-parameters'")
(defvar *instrument-map* (make-hash-table :test #'equal)
"Hash table mapping instrument names (as symbols) to arbitrary parameter lists. Used by `remap-instrument-to-parameters' as part of post-pattern output processing. Any events whose :instrument is not found in this table will not be affected.
See also: `remap-instrument-to-parameters'")
(defun remap-instrument-to-parameters (output &optional pstream)
"Remap OUTPUT's instrument key to arbitrary parameters specified in `*instrument-map*'. If OUTPUT is not an event or the instrument is not found in the map, it is passed through unchanged.
See also: `instrument-mapping', `*instrument-map*', `*post-pattern-output-processors*'"
(declare (ignore pstream))
(unless (event-p output)
(return-from remap-instrument-to-parameters output))
(when-let ((mapping (gethash (event-value output :instrument) *instrument-map*)))
(etypecase mapping
(symbol
(setf (event-value output :instrument) mapping))
(list
(doplist (key value mapping)
(setf (event-value output key) value)))))
output)
(defun instrument-mapping (instrument)
"Get a mapping from INSTRUMENT (an instrument name as a string or symbol) to a plist of parameters which should be set in the event by `remap-instrument-to-parameters'.
See also: `remap-instrument-to-parameters', `*instrument-map*'"
(gethash instrument *instrument-map*))
(defun (setf instrument-mapping) (value instrument)
"Set a mapping from INSTRUMENT (an instrument name as a string or symbol) to a plist of parameters which will be set in the event by `remap-instrument-to-parameters'. Setting an instrument to nil with this function removes it from the map.
See also: `instrument-mapping', `remap-instrument-to-parameters', `*instrument-map*'"
(assert (or (typep value '(or symbol number))
(and (listp value)
(evenp (list-length value))))
(value)
"~S's VALUE argument must be a symbol, a number, or a plist; got ~S instead" 'instrument-mapping value)
(if value
(setf (gethash instrument *instrument-map*) value)
(remhash instrument *instrument-map*)))
(defgeneric as-pstream (thing)
(:documentation "Return THING as a pstream object.
See also: `pattern-as-pstream'"))
(defun pattern-as-pstream (thing)
"Like `as-pstream', but only converts THING to a pstream if it is a pattern."
(if (typep thing 'pattern)
(as-pstream thing)
thing))
(defgeneric t-pstream-value (object)
(:documentation "The value that is yielded by the t-pstream."))
(defgeneric t-pstream-length (object)
(:documentation "The number of times to yield the value."))
(defclass t-pstream (pstream)
((value :initarg :value :initform nil :accessor t-pstream-value :documentation "The value that is yielded by the t-pstream.")
(length :initarg :length :initform 1 :accessor t-pstream-length :documentation "The number of times to yield the value."))
(:documentation "Pattern stream object that by default yields its value only once."))
(defun t-pstream (value &optional (length 1))
"Make a t-pstream object with the value VALUE."
(check-type length (or (integer 0) (eql :inf)))
(make-instance 't-pstream
:value value
:length length))
(defmethod print-object ((t-pstream t-pstream) stream)
(with-slots (value length) t-pstream
(print-unreadable-object (t-pstream stream :type t)
(format stream "~S ~S" value length))))
(defun t-pstream-p (object)
"True if OBJECT is a `t-pstream'.
See also: `t-pstream', `as-pstream'"
(typep object 't-pstream))
(defmethod as-pstream ((value t))
(t-pstream value))
(defmethod next ((t-pstream t-pstream))
(with-slots (value length number) t-pstream
(when (and (not (eql :inf length))
(>= number length))
(return-from next eop))
(if (functionp value)
(funcall value)
value)))
(defmethod as-pstream ((pattern pattern))
(let* ((class (class-of pattern))
(name (class-name class))
(slots (remove 'parent (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots class)))))
(apply #'make-instance
(pattern-pstream-class-name name)
(mapcan (fn (when (slot-boundp pattern _)
(let ((kw (make-keyword _)))
(list kw (funcall (if (member kw (list :length :repeats))
#'as-pstream
#'pattern-as-pstream)
(slot-value pattern _))))))
slots))))
(defmethod as-pstream :around ((object t))
(let ((pstream (call-next-method)))
(with-slots (pstream-count source history) pstream
(setf pstream-count (if (slot-exists-p object 'pstream-count)
(slot-value object 'pstream-count)
0)
source object))
(when (slot-exists-p object 'pstream-count)
(incf (slot-value object 'pstream-count)))
pstream))
(defmethod as-pstream ((pstream pstream)) ; prevent pstreams from being "re-converted" to pstreams
pstream)
(define-condition pstream-out-of-range ()
((index :initarg :index :reader pstream-elt-index))
(:report (lambda (condition stream)
(format stream "The index ~D falls outside the scope of the pstream's history." (pstream-elt-index condition)))))
(defun pstream-elt-index-to-history-index (pstream index)
"Given INDEX, an absolute index into PSTREAM's history, return the actual index into the current recorded history of the pstream.
See also: `pstream-history-advance-by'"
(check-type index (integer 0))
(with-slots (history) pstream
(mod index (length history))))
(defun pstream-elt (pstream n)
"Get the Nth item in PSTREAM's history. For negative N, get the -Nth most recent item.
Example:
;; (let ((pstream (as-pstream (pseq '(1 2 3)))))
( next pstream ) ; = > 1
( pstream - elt pstream 0 ) ; = > 1 ; first item in the pstream 's history
( next pstream ) ; = > 2
( pstream - elt pstream 1 ) ; = > 2 ; second item in the pstream 's history
( pstream - elt pstream -1 ) ) ; = > 2 ; most recent item in the pstream 's history
See also: `pstream-elt-future', `phistory'"
(check-type n integer)
(unless (pstream-p pstream)
(return-from pstream-elt (pstream-elt (as-pstream pstream) n)))
(with-slots (history history-number) pstream
(let ((real-index (if (minusp n)
(+ history-number n)
n)))
(if (and (>= real-index (max 0 (- history-number (length history))))
(< real-index history-number))
(elt history (pstream-elt-index-to-history-index pstream real-index))
(error 'pstream-out-of-range :index n)))))
(defun pstream-history-advance-by (pstream index) ; FIX: add tests for this
"Convert a history index (i.e. a positive number provided to `pstream-elt-future') to the amount that the history must be advanced by.
If the provided index is before the earliest item in history, the result will be a negative number denoting how far beyond the earliest history the index is.
If the provided index is within the current history, the result will be zero.
If the provided index is in the future, the result will be a positive number denoting how far in the future it is.
See also: `pstream-elt-index-to-history-index'"
(check-type index (integer 0))
(with-slots (history history-number) pstream
(let ((history-length (length history)))
(if (< index (- history-number history-length))
(- history-number history-length)
(if (>= index history-number)
(- index (1- history-number))
0)))))
(defun pstream-elt-future (pstream n)
"Get the element N away from the most recent in PSTREAM's history. Unlike `pstream-elt', this function will automatically peek into the future for any positive N.
Example:
;; (let ((pstream (as-pstream (pseq '(1 2 3)))))
( pstream - elt - future pstream 0 ) ; = > 1
( next pstream ) ; = > 1
( pstream - elt - future pstream 1 ) ; = > 2
( next pstream ) ) ; = > 2
See also: `pstream-elt', `phistory'"
(check-type n integer)
(unless (pstream-p pstream)
(return-from pstream-elt-future (pstream-elt-future (as-pstream pstream) n)))
(when (minusp n)
(return-from pstream-elt-future (pstream-elt pstream n)))
(with-slots (history history-number future-number) pstream
(let ((advance-by (pstream-history-advance-by pstream n)))
(when (or (minusp advance-by)
(> (+ future-number advance-by) (length history)))
;; the future and history are recorded to the same array.
;; since the array is of finite size, requesting more from the future than history is able to hold would result in the oldest elements of the future being overwritten with the newest, thus severing the timeline...
(error 'pstream-out-of-range :index n))
(let ((prev-future-number future-number))
(setf future-number 0) ; temporarily set it to 0 so the `next' method runs normally
(loop :repeat advance-by
:for next := (next pstream)
:if (event-p next)
:do (decf (slot-value pstream 'beat) (event-value next :delta)))
(setf future-number (+ prev-future-number advance-by))))
(let ((real-index (pstream-elt-index-to-history-index pstream n)))
(elt history real-index))))
;;; pbind
(defvar *pbind-special-init-keys* (list)
"The list of special keys for pbind that alters it during its initialization.
See also: `define-pbind-special-init-key'")
(defvar *pbind-special-wrap-keys* (list)
"The list of special keys for pbind that causes the pbind to be replaced by another pattern during its initialization.
See also: `define-pbind-special-wrap-key'")
(defvar *pbind-special-process-keys* (list)
"The list of special keys for pbind that alter the outputs of the pbind.
See also: `define-pbind-special-process-key'")
(defclass pbind (pattern)
((pairs :initarg :pairs :initform (list) :accessor pbind-pairs :documentation "The pattern pairs of the pbind; a plist mapping its keys to their values."))
(:documentation "Please refer to the `pbind' documentation."))
(defun pbind (&rest pairs)
"pbind yields events determined by its PAIRS, which are a list of keys and values. Each key corresponds to a key in the resulting events, and each value is treated as a pattern that is evaluated for each step of the pattern to generate the value for its key.
Example:
( next - n ( pbind : foo ( pseq ' ( 1 2 3 ) ) : bar : hello ) 4 )
;;
; = > ( ( EVENT : FOO 1 : BAR : HELLO ) ( EVENT : FOO 2 : BAR : HELLO ) ( EVENT : FOO 3 : BAR : HELLO ) EOP )
See also: `pmono', `pb'"
(assert (evenp (length pairs)) (pairs) "~S's PAIRS argument must be a list of key/value pairs." 'pbind)
(when (> (count :pdef (keys pairs)) 1)
(warn "More than one :pdef key detected in pbind."))
(let* ((res-pairs (list))
(pattern-chain (list))
(pattern (make-instance 'pbind)))
(doplist (key value pairs)
(when (pattern-p value)
(setf (slot-value value 'parent) pattern))
(cond ((position key *pbind-special-init-keys*)
(when-let ((result (funcall (getf *pbind-special-init-keys* key) value pattern)))
(appendf res-pairs result)))
((position key *pbind-special-wrap-keys*)
(unless (null res-pairs)
(setf (slot-value pattern 'pairs) res-pairs)
(setf res-pairs (list)))
(unless (null pattern-chain)
(setf pattern (apply #'pchain (append pattern-chain (list pattern))))
(setf pattern-chain (list)))
(setf pattern (funcall (getf *pbind-special-wrap-keys* key) value pattern)))
(t
(unless (typep pattern 'pbind)
(appendf pattern-chain (list pattern))
(setf pattern (make-instance 'pbind)))
(appendf res-pairs (list key (if (and (eql key :embed)
(typep value 'symbol))
(pdef value)
value))))))
(unless (null res-pairs)
(setf (slot-value pattern 'pairs) res-pairs))
(appendf pattern-chain (list pattern))
(unless (length= 1 pattern-chain)
(setf pattern (apply #'pchain pattern-chain)))
;; process quant keys.
(doplist (k v pairs)
(when (member k (list :quant :play-quant :end-quant))
(funcall (fdefinition (list 'setf (ensure-symbol k 'cl-patterns))) (next v) pattern)))
process : pdef key .
(when-let ((pdef-name (getf pairs :pdef)))
(pdef pdef-name pattern))
pattern))
(pushnew 'pbind *patterns*)
(setf (documentation 'pbind 'type) (documentation 'pbind 'function))
(defmethod print-object ((pbind pbind) stream)
(format stream "(~S~{ ~S ~S~})" 'pbind (slot-value pbind 'pairs)))
(defmethod %pattern-children ((pbind pbind))
(mapcan (lambda (slot)
(let ((slot-name (closer-mop:slot-definition-name slot)))
(copy-list (ensure-list
(if (eql slot-name 'pairs)
(loop :for (k v) :on (slot-value pbind slot-name) :by #'cddr :collect v)
(slot-value pbind slot-name))))))
(closer-mop:class-direct-slots (find-class 'pbind))))
(defmethod keys ((pbind pbind))
(keys (slot-value pbind 'pairs)))
(defvar *pattern-function-translations* (list)
"The list of names of functions and the forms they will be translated to in `pb' and other pattern macros.
See also: `define-pattern-function-translation'")
(defmacro define-pattern-function-translation (function pattern)
"Define a translation from FUNCTION to PATTERN in `pb'."
`(setf (getf *pattern-function-translations* ',function) ',pattern))
(define-pattern-function-translation + p+)
(define-pattern-function-translation - p-)
(define-pattern-function-translation * p*)
(define-pattern-function-translation / p/)
(define-pattern-function-translation round (pnary 'round))
(defun pattern-translate-sexp (sexp)
"Translate SEXP to the equivalent pattern as per `*pattern-function-translations*', or pass it through unchanged if there is no translation.
See also: `pb-translate-body-functions'"
(typecase sexp
(null sexp)
(atom sexp)
(list (let* ((first (car sexp))
(rest (cdr sexp))
(translated-p (getf *pattern-function-translations* first))
(head (list (if (find-if (fn (typep _ '(or pattern list))) rest)
(or translated-p first)
first))))
`(,@head ,@(if translated-p
(mapcar #'pattern-translate-sexp rest)
rest))))))
(defun pb-translate-body-functions (body)
"Translate functions in BODY to their equivalent pattern as per `*pattern-function-translations*'.
See also: `pattern-translate-sexp'"
(loop :for (k v) :on body :by #'cddr
:collect k
:collect (pattern-translate-sexp v)))
FIX : allow keys to be lists , in which case results are destructured , i.e. ( pb : blah ( list : foo : bar ) ( pcycles ( a 1!4 ) ) ) results in four ( EVENT : FOO 1 : DUR 1/4 )
(defmacro pb (name &body pairs)
"pb is a convenience macro, wrapping the functionality of `pbind' and `pdef' while also providing additional syntax sugar. NAME is the name of the pattern (same as pbind's :pdef key or `pdef' itself), and PAIRS is the same as in regular pbind. If PAIRS is only one element, pb operates like `pdef', otherwise it operates like `pbind'.
The expressions in PAIRS are also automatically translated to equivalent patterns if applicable; for example:
( pb : foo : bar ( + ( pseries ) ( pseq ( list -1 0 1 ) ) ) )
...is the same as:
( pb : foo : bar ( p+ ( pseries ) ( pseq ( list -1 0 1 ) ) ) )
See also: `pbind', `pdef'"
(if (length= 1 pairs)
`(pdef ,name ,@pairs)
`(pdef ,name (pbind ,@(pb-translate-body-functions pairs)))))
(pushnew 'pb *patterns*)
(defclass pbind-pstream (pbind pstream)
()
(:documentation "pstream for `pbind'"))
(defmethod print-object ((pbind pbind-pstream) stream)
(print-unreadable-object (pbind stream :type t)
(format stream "~{~S ~S~^ ~}" (slot-value pbind 'pairs))))
(defmethod as-pstream ((pbind pbind))
(let ((name (class-name (class-of pbind)))
(slots (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pbind)))))
(apply #'make-instance
(pattern-pstream-class-name name)
(loop :for slot :in slots
:for slot-kw := (make-keyword slot)
:for bound := (slot-boundp pbind slot)
:if bound
:collect slot-kw
:if (eql :pairs slot-kw)
:collect (mapcar 'pattern-as-pstream (slot-value pbind 'pairs))
:if (and bound (not (eql :pairs slot-kw)))
:collect (slot-value pbind slot)))))
(defmacro define-pbind-special-init-key (key &body body)
"Define a special key for pbind that alters the pbind during its initialization, either by embedding a plist into its pattern-pairs or in another way. These functions are called once, when the pbind is created, and must return a plist if the key should embed values into the pbind pairs, or NIL if it should not."
`(setf (getf *pbind-special-init-keys* ,(make-keyword key))
(lambda (value pattern)
(declare (ignorable value pattern))
,@body)))
;; (define-pbind-special-init-key inst ; FIX: this should be part of event so it will affect the event as well. maybe just rename to something else?
;; (list :instrument value))
(define-pbind-special-init-key loop-p
(setf (loop-p pattern) value)
nil)
(defmacro define-pbind-special-wrap-key (key &body body)
"Define a special key for pbind that replaces the pbind with another pattern during the pbind's initialization. Each encapsulation key is run once on the pbind after it has been initialized, altering the type of pattern returned if the return value of the function is non-NIL."
`(setf (getf *pbind-special-wrap-keys* ,(make-keyword key))
(lambda (value pattern)
(declare (ignorable value pattern))
,@body)))
(define-pbind-special-wrap-key parp
(parp pattern value))
(define-pbind-special-wrap-key pfin
(pfin pattern value))
(define-pbind-special-wrap-key pfindur
(pfindur pattern value))
(define-pbind-special-wrap-key psync
(destructuring-bind (quant &optional maxdur) (ensure-list value)
(psync pattern quant (or maxdur quant))))
(define-pbind-special-wrap-key pdurstutter
(pdurstutter pattern value))
(define-pbind-special-wrap-key pr
(pr pattern value))
(define-pbind-special-wrap-key pn
(pn pattern value))
(define-pbind-special-wrap-key ptrace
(if value
(if (eql t value)
(ptrace pattern)
(pchain pattern
(pbind :- (ptrace value))))
pattern))
(define-pbind-special-wrap-key pmeta
(if (eql t value)
(pmeta pattern)
pattern))
(define-pbind-special-wrap-key pchain ; basically the same as the :embed key, but we have it anyway for convenience.
(pchain pattern value))
(define-pbind-special-wrap-key pparchain
(pparchain pattern value))
(defmacro define-pbind-special-process-key (key &body body)
"Define a special key for pbind that alters the pattern in a nonstandard way. These functions are called for each event created by the pbind and must return an event if the key should embed values into the event stream, or `eop' if the pstream should end."
`(setf (getf *pbind-special-process-keys* ,(make-keyword key))
(lambda (value)
,@body)))
(define-pbind-special-process-key embed
value)
(defmethod next ((pbind pbind-pstream))
(labels ((accumulator (pairs)
(let ((key (car pairs))
(val (cadr pairs)))
(when (and (pstream-p val)
(null (slot-value val 'start-beat)))
(setf (slot-value val 'start-beat) (beat pbind)))
(let ((next-val (next val)))
(when (eop-p next-val)
(return-from accumulator eop))
(if (position key (keys *pbind-special-process-keys*))
(setf *event* (combine-events *event*
(funcall (getf *pbind-special-process-keys* key) next-val)))
(setf (event-value *event* key) next-val))
(if-let ((cddr (cddr pairs)))
(accumulator cddr)
*event*)))))
(let ((*event* (make-default-event)))
(when (eop-p *event*)
(return-from next eop))
(setf (slot-value *event* '%beat) (+ (or (slot-value pbind 'start-beat) 0) (beat pbind)))
(if-let ((pairs (slot-value pbind 'pairs)))
(accumulator pairs)
*event*))))
(defmethod as-pstream ((pbind pbind-pstream))
pbind)
;;; prest
(defclass prest ()
((value :initarg :value :initform 1))
(:documentation "An object representing a rest. When set as a value in an event, the event's :type becomes :rest and the prest's value slot is used as the actual value for the event key instead."))
(defun prest (&optional (value 1))
"Make a prest object, which, when used in a `pbind' or similar event pattern, turns the current event into a rest and yields VALUE for the key's value.
Note that this is not a pattern; it is just a regular function that returns a prest object.
Example:
( next - upto - n ( : degree ( pseq ( list 0 1 ( prest 2 ) 3 ) 1 ) ) )
; = > ( ( EVENT : 0 ) ( EVENT : DEGREE 1 ) ( EVENT : TYPE : REST : DEGREE 2 ) ( EVENT : 3 ) )
See also: `pbind', `pbind''s :type key"
(make-instance 'prest :value value))
(defmethod print-object ((prest prest) stream)
(format stream "(~S ~S)" 'prest (slot-value prest 'value)))
(defmethod rest-p ((prest prest))
t)
;;; pmono
(defun pmono (instrument &rest pairs)
"pmono defines a mono instrument event pstream. It's effectively the same as `pbind' with its :type key set to :mono.
See also: `pbind'"
(assert (evenp (length pairs)) (pairs) "~S's PAIRS argument must be a list of key/value pairs." 'pmono)
(apply #'pbind
:instrument instrument
:type :mono
pairs))
(pushnew 'pmono *patterns*)
;;; pseq
(defpattern pseq (pattern)
(list
(repeats :initform :inf)
(offset :initform 0)
(current-repeats-remaining :state t))
:documentation "Sequentially yield items from LIST, repeating the whole list REPEATS times. OFFSET is the offset to index into the list.
Example:
( next - n ( pseq ' ( 5 6 7 ) 2 ) 7 )
; = > ( 5 6 7 5 6 7 EOP )
;;
( next - upto - n ( pseq ' ( 5 6 7 ) 2 1 ) )
; = > ( 6 7 5 6 7 5 )
See also: `pser', `eseq'")
(defmethod next ((pseq pseq-pstream))
(with-slots (number list offset) pseq
(let ((list (next list)))
(when (and (plusp number)
(zerop (mod number (length list))))
(decf-remaining pseq))
(let ((off (next offset)))
(if (and (not (eop-p off))
(remaining-p pseq)
list)
(elt-wrap list (+ off number))
eop)))))
;;; pser
(defpattern pser (pattern)
(list
(length :initform :inf)
(offset :initform 0)
(current-repeats-remaining :state t)
(current-index :state t))
:documentation "Sequentially yield values from LIST, yielding a total of LENGTH values.
Example:
( next - n ( pser ' ( 5 6 7 ) 2 ) 3 )
;;
; = > ( 5 6 EOP )
See also: `pseq'")
(defmethod next ((pser pser-pstream))
(with-slots (list offset current-index) pser
(let ((remaining (remaining-p pser 'length))
(list (next list))
(off (next offset)))
(when (or (not remaining)
(eop-p off))
(return-from next eop))
(decf-remaining pser)
(when (eql :reset remaining)
(setf current-index 0))
(prog1
(elt-wrap list (+ off current-index))
(incf current-index)))))
;;; pk
(defpattern pk (pattern)
(key
(default :initform 1))
:documentation "Yield the value of KEY in the current `*event*' context, returning DEFAULT if that value is nil.
Example:
( next - upto - n ( pbind : foo ( pseq ' ( 1 2 3 ) 1 ) : bar ( pk : foo ) ) )
; = > ( ( EVENT : FOO 1 : BAR 1 ) ( EVENT : FOO 2 : BAR 2 ) ( EVENT : FOO 3 : BAR 3 ) )
See also: `pbind', `event-value', `*event*'")
(defmethod as-pstream ((pk pk))
(with-slots (key default) pk
(make-instance 'pk-pstream
:key key
:default default)))
(defmethod next ((pk pk-pstream))
(with-slots (key default) pk
(or (event-value *event* key)
(if (string= :number key)
(slot-value pk 'number)
default))))
;;; prand
(defpattern prand (pattern)
(list
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Yield random values from LIST.
Example:
( next - n ( prand ' ( 1 2 3 ) 5 ) 6 )
; = > ( 3 2 2 1 1 EOP )
See also: `pxrand', `pwrand', `pwxrand'")
(defmethod next ((prand prand-pstream))
(unless (remaining-p prand 'length)
(return-from next eop))
(decf-remaining prand)
(random-elt (next (slot-value prand 'list))))
;;; pxrand
(defpattern pxrand (pattern)
(list
(length :initform :inf)
(last-result :state t)
(current-repeats-remaining :state t))
:documentation "Yield random values from LIST, never repeating equal values twice in a row.
Example:
( next - upto - n ( pxrand ' ( 1 2 3 ) 4 ) )
; = > ( 3 1 2 1 )
See also: `prand', `pwrand', `pwxrand'")
(defmethod initialize-instance :after ((pxrand pxrand) &key)
(with-slots (list) pxrand
(assert (or (not (listp list))
(position-if-not (lambda (i) (eql i (car list))) list))
(list)
"~S's input list must have at least two non-eql elements." 'pxrand)))
(defmethod next ((pxrand pxrand-pstream))
(with-slots (list last-result) pxrand
(unless (remaining-p pxrand 'length)
(return-from next eop))
(decf-remaining pxrand)
(let ((clist (next list)))
(setf last-result (loop :for res := (random-elt clist)
:if (or (not (slot-boundp pxrand 'last-result))
(not (eql res last-result)))
:return res)))))
;;; pwrand
(defpattern pwrand (pattern)
(list
(weights :initform :equal)
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Yield random elements from LIST weighted by respective values from WEIGHTS.
Example:
( next - upto - n ( pwrand ' ( 1 2 3 ) ' ( 7 5 3 ) 10 ) )
; = > ( 1 1 2 2 2 1 2 1 1 3 )
See also: `prand', `pxrand', `pwxrand'")
(defmethod next ((pwrand pwrand-pstream))
(with-slots (list weights) pwrand
(unless (remaining-p pwrand 'length)
(return-from next eop))
(decf-remaining pwrand)
(let* ((clist (next list))
(cweights (cumulative-list (if (eql weights :equal)
(let ((len (length clist)))
(make-list len :initial-element (/ 1 len)))
(normalized-sum (mapcar #'next (next weights))))))
(num (random 1.0)))
(nth (index-of-greater-than num cweights) clist))))
;;; pwxrand
(defpattern pwxrand (pattern)
(list
(weights :initform :equal)
(length :initform :inf)
(last-result :state t)
(current-repeats-remaining :state t))
:documentation "Yield random elements from LIST weighted by respective values from WEIGHTS, never repeating equivalent values twice in a row. This is effectively `pxrand' and `pwrand' combined.
Example:
( next - upto - n ( pwxrand ' ( 1 2 3 ) ' ( 7 5 3 ) 10 ) )
;; ;=> (1 2 1 2 1 3 1 2 1 2)
See also: `prand', `pxrand', `pwrand'")
(defmethod initialize-instance :after ((pwxrand pwxrand) &key)
(with-slots (list weights) pwxrand
(assert (or (not (listp list))
(and (position-if-not (fn (eql _ (car list))) list)
(or (not (listp weights))
(find-if-not 'numberp weights)
(let ((effective-list (loop :for index :from 0
:for elem :in list
:for weight := (elt-wrap weights index)
:if (plusp weight)
:collect elem)))
(position-if-not (fn (eql _ (car effective-list))) effective-list)))))
(list)
"~S's input list must have at least two non-eql accessible elements." 'pwxrand)))
(defmethod next ((pwxrand pwxrand-pstream))
(with-slots (list weights last-result) pwxrand
(unless (remaining-p pwxrand 'length)
(return-from next eop))
(decf-remaining pwxrand)
(let* ((clist (next list))
(clist-length (length clist))
(cweights (next weights))
(cweights (cumulative-list (if (eql cweights :equal)
(make-list clist-length :initial-element (/ 1 clist-length))
(normalized-sum (mapcar #'next cweights))))))
(setf last-result (loop :for res := (nth-wrap (index-of-greater-than (random 1.0) cweights) clist)
:if (or (not (slot-boundp pwxrand 'last-result))
(not (eql res last-result)))
:return res)))))
;;; pfunc
(defpattern pfunc (pattern)
((func :type (or function-designator pattern))
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Yield the result of evaluating FUNC. Note that the current event of the parent pattern is still accessible via the `*event*' special variable.
Example:
( next - upto - n ( pfunc ( lambda ( ) ( random 10 ) ) 4 ) )
; = > ( ( 5 2 8 9 ) )
;;
( next - upto - n ( pbind : foo ( pwhite 0 10 4 )
;; :bar (pfunc (lambda ()
( if ( > ( event - value * event * : foo ) 5 ) : greater : lesser ) ) ) ) )
; = > ( ( EVENT : FOO 0 : BAR : LESSER ) ( EVENT : FOO 6 : BAR : GREATER )
( EVENT : FOO 7 : BAR : GREATER ) ( EVENT : FOO 8 : BAR : GREATER ) )
See also: `pf', `pnary', `plazy', `pif'")
(defmethod initialize-instance :after ((pfunc pfunc) &key)
(check-type (slot-value pfunc 'func) (or function-designator pattern)))
(defmethod as-pstream ((pfunc pfunc))
(with-slots (func length) pfunc
(make-instance 'pfunc-pstream
:func (pattern-as-pstream func)
:length (as-pstream length))))
(defmethod next ((pfunc pfunc-pstream))
(unless (remaining-p pfunc 'length)
(return-from next eop))
(decf-remaining pfunc)
(with-slots (func) pfunc
(etypecase func
(function-designator (funcall func))
(pstream (let ((nxt (next func)))
(if (eop-p nxt)
eop
(funcall nxt)))))))
;;; pf
(defmacro pf (&body body)
"Convenience macro for `pfunc' that automatically wraps BODY in a lambda."
`(pfunc (lambda () ,@body)))
(pushnew 'pf *patterns*)
;;; pr
(defpattern pr (pattern)
(pattern
(repeats :initform :inf)
(current-value :state t :initform nil)
(current-repeats-remaining :state t))
:documentation "Repeat each value from PATTERN REPEATS times. If REPEATS is 0, the value is skipped.
Example:
( next - upto - n ( pr ( pseries ) ( pseq ' ( 1 3 0 2 ) 1 ) ) )
;; ;=> (0 1 1 1 3 3)
See also: `pdurstutter', `pn', `pdrop', `parp'")
(defmethod as-pstream ((pr pr))
(with-slots (pattern repeats) pr
(make-instance 'pr-pstream
:pattern (as-pstream pattern)
:repeats (pattern-as-pstream repeats))))
(defmethod next ((pr pr-pstream))
(with-slots (pattern repeats current-value current-repeats-remaining) pr
(while (or (not (slot-boundp pr 'current-repeats-remaining))
(and current-repeats-remaining
current-value
(not (value-remaining-p current-repeats-remaining))))
(setf current-value (next pattern))
(when (or (eop-p current-value)
(and (slot-boundp pr 'current-repeats-remaining)
(eop-p current-repeats-remaining)))
(return-from next eop))
(setf current-repeats-remaining
(let ((*event* (if (event-p current-value)
(if *event*
(combine-events *event* current-value)
current-value)
*event*)))
(if (typep repeats 'function)
(let ((arglist (function-arglist repeats)))
(if (null arglist)
(funcall repeats)
(funcall repeats current-value)))
(next repeats)))))
(when (value-remaining-p current-repeats-remaining)
(decf-remaining pr)
current-value)))
;;; plazy
(defpattern plazy (pattern)
(func
(repeats :initform :inf)
(current-pstream :state t :initform nil)
(current-repeats-remaining :state t :initform nil))
:documentation "Evaluates FUNC to generate a pattern, which is then yielded from until its end, at which point FUNC is evaluated again to generate the next pattern. The pattern is generated a total of REPEATS times.
Example:
( next - n ( plazy ( lambda ( ) ( if (= 0 ( random 2 ) ) ( pseq ' ( 1 2 3 ) 1 ) ( pseq ' ( 9 8 7 ) 1 ) ) ) ) 6 )
; = > ( 9 8 7 1 2 3 )
See also: `pfunc'")
(defmethod as-pstream ((plazy plazy))
(with-slots (func repeats) plazy
(make-instance 'plazy-pstream
:func func
:repeats (as-pstream repeats))))
(defmethod next ((plazy plazy-pstream))
(with-slots (func repeats current-pstream current-repeats-remaining) plazy
(labels ((set-current-pstream ()
(unless (remaining-p plazy)
(return-from next eop))
(setf current-pstream (as-pstream (funcall func)))
(decf-remaining plazy)))
(unless current-repeats-remaining
(setf current-repeats-remaining (next repeats)))
(unless current-pstream
(set-current-pstream))
(let ((nv (next current-pstream)))
(if (eop-p nv)
(progn
(set-current-pstream)
(next current-pstream))
nv)))))
;;; protate
(defpattern protate (pattern)
(pattern
(shift :initform 0))
:documentation "Rotate PATTERN N outputs forward or backward, wrapping the shifted items to the other side, a la `alexandria:rotate'.
Example:
( next - upto - n ( protate ( pseq ' ( 1 2 3 4 5 ) 1 ) 2 ) )
; = > ( 4 5 1 2 3 )
See also: `pdrop', `phistory', `pscratch'")
(defmethod as-pstream ((protate protate))
(with-slots (pattern shift) protate
(make-instance 'protate-pstream
:pattern (pattern-as-pstream pattern)
:shift (pattern-as-pstream shift))))
(defmethod next ((protate protate-pstream))
(with-slots (pattern shift number) protate
(when (zerop number)
(next-upto-n pattern))
(let ((actual-index (- number (next shift)))
(hn (slot-value pattern 'history-number)))
(if (>= number (1- hn))
eop
(pstream-elt pattern (mod actual-index (1- hn)))))))
;;; pn
(defpattern pn (pattern)
(pattern
(repeats :initform :inf)
(current-repeats-remaining :state t)
(current-pstream :state t :initform nil))
:documentation "Embed the full PATTERN into the pstream REPEATS times.
Example:
( next - upto - n ( pn ( pwhite 0 5 1 ) 5 ) )
; = > ( 2 4 2 1 0 )
See also: `pr'")
(defmethod as-pstream ((pn pn)) ; need this so that PATTERN won't be automatically converted to a pstream when the pn is.
(with-slots (pattern repeats) pn
(make-instance 'pn-pstream
:pattern pattern
:repeats (as-pstream repeats))))
(defmethod next ((pn pn-pstream))
(with-slots (pattern current-pstream) pn
(let ((rem (remaining-p pn)))
(when (eql :reset rem)
(setf current-pstream (as-pstream pattern)))
(let ((nv (next current-pstream)))
(while (and (eop-p nv) rem)
(decf-remaining pn)
(setf rem (remaining-p pn)
current-pstream (as-pstream pattern)
nv (next current-pstream)))
(if rem
nv
eop)))))
;;; pshuf
(defpattern pshuf (pattern)
(list
(repeats :initform :inf)
(shuffled-list :state t)
(current-repeats-remaining :state t))
:documentation "Shuffle LIST, then yield each item from the shuffled list, repeating it REPEATS times.
Example:
( next - upto - n ( pshuf ' ( 1 2 3 ) 2 ) )
;;
; = > ( 3 1 2 3 1 2 )
See also: `prand'")
(defmethod as-pstream ((pshuf pshuf))
(with-slots (list repeats) pshuf
(let ((list (typecase list
(pattern (next-upto-n list))
(function (funcall list))
(list list))))
(make-instance 'pshuf-pstream
:list (next list)
:repeats (as-pstream repeats)))))
(defmethod next ((pshuf pshuf-pstream))
(with-slots (list number shuffled-list) pshuf
(when (and (zerop (mod number (length list)))
(plusp number))
(decf-remaining pshuf))
(let ((rem (remaining-p pshuf)))
(unless rem
(return-from next eop))
(when (eql :reset rem)
(setf shuffled-list (shuffle (copy-list list)))) ; alexandria:shuffle destructively modifies the list, so we use copy-list so as to avoid unexpected side effects.
(nth (mod number (length shuffled-list))
shuffled-list))))
pwhite
(defpattern pwhite (pattern)
((lo :initform 0.0)
(hi :initform 1.0)
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Linearly-distributed random numbers between LO and HI, inclusive.
Example:
( next - upto - n ( pwhite 0 10 16 ) )
; = > ( 7 2 4 5 7 10 4 8 10 2 3 5 9 2 5 4 )
See also: `pexprand', `pbrown', `pgauss', `prand'"
;; FIX: see about using a symbol for the unprovided slots and just check/process this initialization code in the `next' method instead.
:defun (defun pwhite (&optional (lo 0.0 lo-provided-p) (hi 1.0 hi-provided-p) (length :inf))
if only one argument is provided , we use it as the " hi " value .
(make-instance 'pwhite
:lo (if hi-provided-p
lo
0.0)
:hi (if hi-provided-p
hi
(if lo-provided-p
lo
1.0))
:length length)))
(defmethod next ((pwhite pwhite-pstream))
(with-slots (lo hi) pwhite
(unless (remaining-p pwhite 'length)
(return-from next eop))
(decf-remaining pwhite)
(let ((nlo (next lo))
(nhi (next hi)))
(when (or (eop-p nlo)
(eop-p nhi))
(return-from next eop))
(random-range nlo nhi))))
pbrown
;; FIX: make the initforms of hi onward a special symbol, and then check for that symbol in `next', rather than checking against the arguments of the `pbrown' function.
(defpattern pbrown (pattern)
((lo :initform 0.0)
(hi :initform 1.0)
(step :initform 0.125)
(length :initform :inf)
(current-repeats-remaining :state t)
(current-value :state t :initform nil))
each output randomly a maximum of STEP away from the previous . LO and HI define the lower and upper bounds of the range . STEP defaults to 1 if LO and HI are integers .
Example:
( next - upto - n ( pbrown 0 10 1 10 ) )
; = > ( 2 3 3 3 4 3 4 5 6 5 )
See also: `pwhite', `pexprand', `pgauss'"
if only one argument is provided , we use it as the " hi " value .
:defun (defun pbrown (&optional (lo 0.0 lo-provided-p) (hi 1.0 hi-provided-p) (step 0.125 step-provided-p) (length :inf))
(let ((lo (if hi-provided-p
lo
(if (integerp lo) 0 0.0)))
(hi (if hi-provided-p
hi
(if lo-provided-p lo 1))))
(make-instance 'pbrown
:lo lo
:hi hi
:step (if step-provided-p
step
(if (and (integerp lo)
(integerp hi))
1
0.125))
:length length))))
(defmethod next ((pbrown pbrown-pstream))
(unless (remaining-p pbrown 'length)
(return-from next eop))
(decf-remaining pbrown)
(with-slots (lo hi step current-value) pbrown
(let ((nlo (next lo))
(nhi (next hi))
(nstep (next step)))
(when (member eop (list nlo nhi nstep))
(return-from next eop))
(unless current-value
(setf current-value (random-range (min nlo nhi)
(max nlo nhi))))
(incf current-value (random-range (* -1 nstep) nstep))
(setf current-value (clamp current-value nlo nhi)))))
;;; pexprand
;; FIX: integer inputs should result in integer outputs
(defpattern pexprand (pattern)
((lo :initform 0.0001)
(hi :initform 1.0)
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Exponentially-distributed random numbers between LO and HI. Note that LO and HI cannot be 0, and that LO and HI must have the same sign or else complex numbers will be output.
Example:
( next - upto - n ( pexprand 1.0 8.0 4 ) )
; = > ( 1.0420843091865208d0 1.9340168112124456d0 2.173209129035095d0 4.501371557329618d0 )
See also: `pwhite', `pbrown', `pgauss', `prand'")
(defmethod next ((pexprand pexprand-pstream))
(with-slots (lo hi) pexprand
(unless (remaining-p pexprand 'length)
(return-from next eop))
(decf-remaining pexprand)
(let ((nlo (next lo))
(nhi (next hi)))
(assert (and (numberp lo)
(not (zerop lo)))
(lo)
"Got a zero for ~S's ~S slot" 'pexprand 'lo)
(assert (and (numberp hi)
(not (zerop hi)))
(hi)
"Got a zero for ~S's ~S slot" 'pexprand 'hi)
(when (or (eop-p nlo)
(eop-p nhi))
(return-from next eop))
(exponential-random-range nlo nhi))))
;;; pgauss
(defpattern pgauss (pattern)
((mean :initform 0.0)
(deviation :initform 1.0)
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Random numbers distributed along a normal (gaussian) curve. MEAN is the \"center\" of the distribution, DEVIATION is the standard deviation (i.e. the higher the value, the further the outputs are spread from MEAN).
Example:
( next - n ( pgauss ) 4 )
; = > ( 0.08918811646370092d0 0.1745957067161632d0 0.7954678768273173d0 -1.2215823449671597d0 )
See also: `pwhite', `pexprand', `pbrown'")
(defmethod next ((pgauss pgauss-pstream))
(with-slots (mean deviation) pgauss
(unless (remaining-p pgauss 'length)
(return-from next eop))
(decf-remaining pgauss)
(let ((nmean (next mean))
(ndev (next deviation)))
(when (or (eop-p nmean)
(eop-p ndev))
(return-from next eop))
(random-gauss nmean ndev))))
pseries
(defpattern pseries (pattern)
((start :initform 0)
(step :initform 1)
(length :initform :inf)
(current-repeats-remaining :state t)
(current-value :state t))
:documentation "Yield START, then generate subsequent outputs by adding STEP, for a total of LENGTH outputs.
Example:
;; (next-upto-n (pseries 1 2 4))
;; ;=> (1 3 5 7)
See also: `pseries*', `pgeom', `paccum'")
(defmethod next ((pseries pseries-pstream))
(with-slots (start step current-value) pseries
(unless (slot-boundp pseries 'current-value)
(setf current-value (next start)))
(unless (and (remaining-p pseries 'length)
current-value)
(return-from next eop))
(decf-remaining pseries)
(let ((nxt (next step)))
(prog1
current-value
(if (numberp nxt)
(incf current-value nxt) ; FIX: current-value should be CURRENT value, not the next one! also write tests for this!
(setf current-value eop))))))
;;; pseries*
(defun pseries* (&optional (start 0) (end 1) length)
"Syntax sugar to generate a `pseries' whose values go from START to END linearly over LENGTH steps. If LENGTH is not provided, it is calculated such that the step will be 1. Note that LENGTH cannot be infinite since delta calculation requires dividing by it.
Based on the Pseries extension from the ddwPatterns SuperCollider library.
Example:
( pseries * 0 10 16 )
; = > ( pseries 0 2/3 16 )
;;
;; (next-upto-n *)
; = > ( 0 2/3 4/3 2 8/3 10/3 4 14/3 16/3 6 20/3 22/3 8 26/3 28/3 10 )
See also: `pseries', `pgeom', `pgeom*'"
(check-type length (or null (integer 2) pattern))
(let ((length (or length
(max 2 (round (1+ (abs (- end start))))))))
(pseries start (/ (- end start) (1- length)) length)))
(pushnew 'pseries* *patterns*)
;;; pgeom
(defpattern pgeom (pattern)
((start :initform 1)
(grow :initform 2)
(length :initform :inf)
(current-repeats-remaining :state t)
(current-value :state t))
:documentation "Yield START, then generate subsequent outputs by multiplying by GROW, for a total of LENGTH outputs.
Example:
;; (next-upto-n (pgeom 1 2 4))
;; ;=> (1 2 4 8)
See also: `pseries', `paccum'")
(defmethod next ((pgeom pgeom-pstream))
(with-slots (start grow current-value) pgeom
(unless (slot-boundp pgeom 'current-value)
(setf current-value (next start)))
(unless (remaining-p pgeom 'length)
(return-from next eop))
(decf-remaining pgeom)
(if (zerop (slot-value pgeom 'number))
current-value
(let ((n (next grow)))
(if (eop-p n)
eop
(setf current-value (* current-value n)))))))
;;; pgeom*
(defun pgeom* (&optional (start 0.01) (end 1) (length 16))
"Syntax sugar to generate a `pgeom' whose values go from START to END exponentially over LENGTH steps. LENGTH cannot be infinite since delta calculation requires dividing by it.
Based on the Pgeom extension from the ddwPatterns SuperCollider library.
Example:
( pgeom * 1 100 8)
;; ;=> (pgeom 1 1.9306977 8)
;;
;; (next-upto-n *)
; = > ( 1 1.9306977 3.7275934 7.196856 13.894953 26.826954 51.79474 99.999985 )
;; ;; Note that due to floating point rounding errors the last output may not always be exactly END.
See also: `pgeom', `pseries', `pseries*'"
(check-type length (or (integer 2) pattern))
(pgeom start (expt (/ end start) (/ 1 (1- length))) length))
(pushnew 'pgeom* *patterns*)
;;; ptrace
(defpattern ptrace (pattern)
((trace :initform t)
(prefix :initform nil)
(stream :initform t))
:documentation "Print the PREFIX and each output of TRACE to STREAM. If TRACE is t, print `*event*'. If TRACE is a different symbol, print the value of that symbol in `*event*'. If TRACE is a pattern, ptrace yields its output unaffected. Otherwise, it yields t.
See also: `debug-backend', `debug-backend-recent-events'")
(defmethod as-pstream ((ptrace ptrace))
(with-slots (trace prefix stream) ptrace
(make-instance 'ptrace-pstream
:trace (pattern-as-pstream trace)
:prefix (pattern-as-pstream prefix)
:stream (pattern-as-pstream stream))))
(defmethod next ((ptrace ptrace-pstream))
(with-slots (trace prefix stream) ptrace
(let ((prefix (next prefix))
(stream (next stream)))
(if (eql trace t)
(progn
(format stream "~&~@[~A ~]~S~%" prefix *event*)
t)
(typecase trace
((or list symbol)
(progn
(format stream "~&~@[~A ~]~{~{~S: ~S~}~#[~:; ~]~}~%" prefix
(mapcar (lambda (symbol)
(list symbol (event-value *event* symbol)))
(ensure-list trace)))
t))
(pattern
(let ((res (next trace)))
(format stream "~&~@[~A ~]~S~%" prefix res)
res)))))))
;;; place
(defpattern place (pattern)
(list
(repeats :initform :inf)
(current-repeat :state t :initform 0)
(current-repeats-remaining :state t))
the third time , the third element , and so on . REPEATS controls the number of times LIST is repeated .
Example:
( next - upto - n ( place ( list 1 2 ( list 3 4 5 ) ) 3 ) )
; = > ( 1 2 3 1 2 4 1 2 5 )
See also: `ppatlace'")
(defmethod next ((place place-pstream))
(with-slots (number list current-repeat) place
(when (and (not (= number 0))
(= 0 (mod number (length list))))
(incf current-repeat)
(decf-remaining place))
(unless (if (plusp number)
(and (not (ended-p place))
(remaining-p place))
(remaining-p place))
(return-from next eop))
(let* ((mod (mod number (length list)))
(result (next (nth mod list))))
(if (listp result)
(elt-wrap result current-repeat)
result))))
;;; ppatlace
(defpattern ppatlace (pattern)
(list
(repeats :initform :inf)
(current-repeats-remaining :state t))
:documentation "Yield each value from LIST in sequence, or one output from each pattern in LIST per cycle of the list. If one of the patterns embedded in LIST ends sooner than the others, it is simply removed and the ppatlace continues to yield from the rest of the LIST. The entire LIST is yielded through a total of REPEATS times.
Example:
( next - upto - n ( ppatlace ( list ( pseq ( list 1 2 3 ) 1 )
( pseq ( list 4 5 6 ) 2 ) ) ) )
;; ;=> (1 4 2 5 3 6 4 5 6)
See also: `place'")
(defmethod as-pstream ((ppatlace ppatlace))
(with-slots (repeats list) ppatlace
(make-instance 'ppatlace-pstream
:list (mapcar #'pattern-as-pstream list)
:repeats (as-pstream repeats))))
(defmethod next ((ppatlace ppatlace-pstream))
(with-slots (number list) ppatlace
(when (and (not (zerop number))
(not (length= 0 list))
(zerop (mod number (length list))))
(decf-remaining ppatlace))
(when (or (not list)
(and (plusp number)
(ended-p ppatlace))
(not (remaining-p ppatlace)))
(return-from next eop))
(let ((result (next (elt-wrap list number))))
(unless (eop-p result)
(return-from next result))
(setf list (remove-if #'ended-p list))
(next ppatlace))))
;;; pnary
(defpattern pnary (pattern)
(operator
(patterns :initarg :patterns))
:documentation "Yield the result of applying OPERATOR to each value yielded by each pattern in PATTERNS.
Example:
( next - upto - n ( pnary ( pseq ( list ' + ' - ' * ' / ) 2 ) 2 2 ) )
; = > ( 4 0 4 1 )
See also: `pfunc', `p+', `p-', `p*', `p/'"
:defun (defun pnary (operator &rest patterns)
(make-instance 'pnary
:operator operator
:patterns patterns)))
(defmethod as-pstream ((pnary pnary))
(with-slots (operator patterns) pnary
(make-instance 'pnary-pstream
:operator (pattern-as-pstream operator)
:patterns (mapcar #'pattern-as-pstream patterns))))
(defmethod next ((pnary pnary-pstream))
(with-slots (operator patterns) pnary
(let ((op (if (pstream-p operator)
(next operator)
operator))
(nexts (mapcar #'next patterns)))
(when (or (position eop nexts)
(eop-p op))
(return-from next eop))
(restart-case
(handler-bind
((type-error
(lambda (c)
(when-let ((restart (find-restart 'retry-with-prest-values c)))
(invoke-restart restart)))))
(apply #'multi-channel-funcall op nexts))
(retry-with-prest-values ()
:test (lambda (c)
(and (typep c 'type-error)
(eql 'number (type-error-expected-type c))
(typep (type-error-datum c) 'prest)))
(labels ((replace-prests (list)
(mapcar (lambda (item)
(typecase item
(list (replace-prests item))
(prest (slot-value item 'value))
(t item)))
list)))
(apply #'multi-channel-funcall op (replace-prests nexts))))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun make-pattern-for-function (function)
"Generate Lisp of a wrapper function named pFUNCTION whose definition is (pnary FUNCTION ...).
See also: `pnary'"
(let* ((pat-sym (intern (concat "P" (symbol-name function)) 'cl-patterns))
(argslist (function-arglist function))
(func-name (string-downcase function))
(full-func-name (if (eql (find-package 'cl-patterns) (symbol-package function))
func-name
(concat (string-downcase (package-name (symbol-package function))) ":" func-name)))
(parsed (multiple-value-list (parse-ordinary-lambda-list argslist)))
(has-rest (third parsed))
(args (append (first parsed) (mapcar #'car (second parsed)) (ensure-list (third parsed)))))
`(progn
(defun ,pat-sym ,argslist
,(concat "Syntax sugar for (pnary #'" func-name " ...).
See also: `pnary', `" full-func-name "'")
(,(if has-rest
'apply
'funcall)
#'pnary #',function ,@args))
(pushnew ',pat-sym *patterns*)))))
#.`(progn ,@(mapcar #'make-pattern-for-function '(+ - * / > >= < <= = /= eql wrap)))
;;; prerange
(defpattern prerange (pattern)
(input
from-range
to-range)
:documentation "Remap INPUT from one range, specified by FROM-RANGE, to another range, specified by TO-RANGE.
Note that this is effectively a convenience wrapper over `pnary' and `rerange'; thus you should see `rerange' for more information.
See also: `rerange', `pnary'")
(defmethod as-pstream ((prerange prerange))
(with-slots (input from-range to-range) prerange
(make-instance 'prerange-pstream
:input (pattern-as-pstream input)
:from-range (pattern-as-pstream from-range)
:to-range (pattern-as-pstream to-range))))
(defmethod next ((prerange prerange-pstream))
(with-slots (input from-range to-range) prerange
(let ((input (next input))
(from-range (next from-range))
(to-range (next to-range)))
(when (member eop (list input from-range to-range))
(return-from next eop))
(rerange input from-range to-range))))
;;; pslide
(defpattern pslide (pattern)
(list
(repeats :initform :inf)
(len :initform 3)
(step :initform 1)
(start :initform 0)
(wrap-at-end :initform t)
(current-repeats-remaining :state t)
(current-repeats :state t :initform nil)
(remaining-current-segment :state t :initform nil)
(current-value :state t :initform nil)
(current-list-length :state t :initform nil))
:documentation "\"Slide\" across sections of LIST. REPEATS is the total number of sections to output, LEN the length of the section. STEP is the number to increment the start index by after each section, and START is the initial index into LIST that the first section starts from. WRAP-AT-END, when true, means that an index outside of the list will wrap around. When false, indexes outside of the list result in nil.
Example:
( next - upto - n ( pslide ( list 0 1 2 3 4 5 6 ) 3 3 2 1 t ) )
;; ;=> (1 2 3 3 4 5 5 6 0)
See also: `pscratch'")
(defmethod as-pstream ((pslide pslide))
(with-slots (list repeats len step start wrap-at-end) pslide
(make-instance 'pslide-pstream
:list (next list)
:repeats (pattern-as-pstream repeats)
:len (pattern-as-pstream len)
:step (pattern-as-pstream step)
:start (pattern-as-pstream start)
:wrap-at-end (next wrap-at-end)
:current-repeats 0
:remaining-current-segment len)))
(defmethod next ((pslide pslide-pstream))
(with-slots (list repeats len step start wrap-at-end current-repeats-remaining current-repeats remaining-current-segment current-value current-list-length) pslide
(unless current-value
(setf current-value (next start)))
(unless current-list-length
(setf current-list-length (length list)))
(labels ((get-next ()
(if (and (not wrap-at-end)
(or (minusp current-value)
(>= current-value current-list-length)))
eop
(elt-wrap list current-value))))
(unless (slot-boundp pslide 'current-repeats-remaining)
(setf current-repeats-remaining (next repeats)))
(unless (value-remaining-p current-repeats-remaining)
(return-from next eop))
(if (value-remaining-p remaining-current-segment)
(prog1
(get-next)
(decf-remaining pslide 'remaining-current-segment)
(incf current-value))
(progn
(decf-remaining pslide)
(setf remaining-current-segment (next len))
(incf current-repeats)
(setf current-value (+ (next start) (* (next step) current-repeats)))
(next pslide))))))
;;; phistory
(defpattern phistory (pattern)
(pattern
step-pattern)
:documentation "Refer back to PATTERN's history, yielding the output at the index provided by STEP-PATTERN.
Note that PATTERN is still advanced once per event, and if STEP-PATTERN yields a number pointing to an event in PATTERN that hasn't been yielded yet (i.e. if PATTERN has only advanced once but STEP-PATTERN yields 3 for its output), phistory yields nil.
Example:
( next - n ( phistory ( pseries ) ( pseq ' ( 0 2 1 ) ) ) 3 )
;; ;=> (0 NIL 1)
See also: `pscratch'")
(defmethod as-pstream ((phistory phistory))
(with-slots (pattern step-pattern) phistory
(make-instance 'phistory-pstream
:pattern (as-pstream pattern)
:step-pattern (pattern-as-pstream step-pattern))))
(defmethod next ((phistory phistory-pstream))
(with-slots (pattern step-pattern) phistory
(let ((next-step (next step-pattern)))
(if (eop-p next-step)
eop
(progn
(next pattern)
(handler-case (pstream-elt pattern next-step)
(pstream-out-of-range ()
nil)))))))
;;; pscratch
;;
NOTE : pscratch 's mechanism seems to be slightly different :
;; supercollider:
> Pscratch(Pseries(0 , 1 ) , Pseq([1 , 1 , 1 , -3 ] , inf)).asStream.nextN(12 )
[ 0 , 1 , 2 , 0 , 1 , 2 , 3 , 0 , 1 , 2 , 3 , 0 ]
;;
;; lisp:
> ( next - n ( pscratch ( pseries 0 1 ) ( pseq ( list 1 1 1 -3 ) : ) ) 12 )
;; (0 1 2 3 0 1 2 3 0 1 2 3)
;; FIX: document this in sc-differences.org
(defpattern pscratch (pattern)
(pattern
step-pattern
(current-index :state t :initform 0))
:documentation "\"Scratches\" across the values yielded by a pstream, similar in concept to how a DJ might scratch a record, altering the normal flow of playback. PATTERN is the source pattern, and STEP-PATTERN determines the increment of the index into the pstream history.
Based on the pattern originally from the ddwPatterns SuperCollider library.
Example:
( next - upto - n ( pscratch ( pseries ) ( pseq ' ( 0 1 1 -1 2 ) 2 ) ) )
;; ;=> (0 0 1 2 1 3 3 4 5 4)
See also: `phistory'")
(defmethod as-pstream ((pscratch pscratch))
(with-slots (pattern step-pattern) pscratch
(make-instance 'pscratch-pstream
:pattern (as-pstream pattern)
:step-pattern (pattern-as-pstream step-pattern))))
(defmethod next ((pscratch pscratch-pstream))
(with-slots (pattern step-pattern current-index) pscratch
(let ((nxt (next step-pattern)))
(when (eop-p nxt)
(return-from next eop))
(prog1
(pstream-elt-future pattern current-index)
(setf current-index (max (+ current-index nxt) 0))))))
pif
(defpattern pif (pattern)
((test)
(true)
(false :initform nil))
:documentation "\"If\" expression for patterns. TEST is evaluated for each step, and if it's non-nil, the value of TRUE will be yielded, otherwise the value of FALSE will be. Note that TRUE and FALSE can be patterns, and if they are, they are only advanced in their respective cases, not for every step.
Example:
( next - n ( pif ( pseq ' ( t t nil nil nil ) ) ( pseq ' ( 1 2 3 ) ) ( pseq ' ( 9 8 7 ) ) ) 8)
;; ;=> (1 2 9 8 7 3 1 9)
See also: `plazy', `pfunc'")
(defmethod next ((pif pif-pstream))
(with-slots (test true false) pif
(let ((nxt (next test)))
(if (eop-p nxt)
eop
(if nxt
(next true)
(next false))))))
;;; parp
;; FIX: should this be like `pchain' and accept an arbitrary number of input patterns?
(defpattern parp (pattern)
(pattern
arpeggiator
(current-pattern-event :state t :initform nil)
(current-arpeggiator-stream :state t :initform nil))
each event yielded by PATTERN is bound to ` * event * ' and then the entirety of the ARPEGGIATOR pattern is yielded .
Example:
( next - upto - n ( parp ( : foo ( pseq ' ( 1 2 3 ) 1 ) )
( pbind : bar ( pseq ' ( 4 5 6 ) 1 ) ) ) )
; = > ( ( EVENT : FOO 1 : BAR 4 ) ( EVENT : FOO 1 : BAR 5 ) ( EVENT : FOO 1 : BAR 6 )
( EVENT : FOO 2 : BAR 4 ) ( EVENT : FOO 2 : BAR 5 ) ( EVENT : FOO 2 : BAR 6 )
( EVENT : FOO 3 : BAR 4 ) ( EVENT : FOO 3 : BAR 5 ) ( EVENT : FOO 3 : BAR 6 ) )
See also: `psym', `pmeta', `pr'")
(defmethod as-pstream ((parp parp))
(with-slots (pattern arpeggiator) parp
(let ((pstr (as-pstream pattern)))
(make-instance 'parp-pstream
:pattern pstr
:arpeggiator arpeggiator
:current-pattern-event (next pstr)
:current-arpeggiator-stream (as-pstream arpeggiator)))))
(defmethod next ((parp parp-pstream))
(with-slots (pattern arpeggiator current-pattern-event current-arpeggiator-stream) parp
(when (eop-p current-pattern-event)
(return-from next eop))
(let ((nxt (let ((*event* (combine-events (make-default-event)
current-pattern-event)))
(next current-arpeggiator-stream))))
(unless (eop-p nxt)
(return-from next nxt))
(setf current-pattern-event (next pattern)
current-arpeggiator-stream (as-pstream arpeggiator))
(next parp))))
;;; pfin
(defpattern pfin (pattern)
(pattern
count)
:documentation "Yield up to COUNT outputs from PATTERN.
Example:
( next - n ( pfin ( pseq ' ( 1 2 3 ) : ) 3 ) 5 )
; = > ( 1 2 3 NIL NIL )
See also: `pfindur'")
(defmethod as-pstream ((pfin pfin))
(with-slots (count pattern) pfin
(make-instance 'pfin-pstream
:pattern (as-pstream pattern)
:count (next count)))) ; FIX: should be able to use as a gate pattern. remove this whole as-pstream block when it is possible.
(defmethod next ((pfin pfin-pstream))
(with-slots (pattern count number) pfin
(unless (< number count)
(return-from next eop))
(next pattern)))
;;; pfindur
(defpattern pfindur (pattern)
(pattern
dur
(tolerance :initform 0)
(current-dur :state t)
(elapsed-dur :state t :initform 0))
:documentation "Yield events from PATTERN until their total duration is within TOLERANCE of DUR, or greater than DUR. Any events that would end beyond DUR are cut short. If PATTERN outputs numbers, their total sum is limited instead.
Example:
( next - n ( pfindur ( pbind : dur 1 : foo ( pseries ) ) 2 ) 3 )
; = > ( ( EVENT : 1 : FOO 0 ) ( EVENT : 1 : FOO 1 ) EOP )
;;
( next - upto - n ( pfindur ( pwhite 0 4 ) 16 ) )
; = > ( 1 3 0 1 2 2 1 3 0 1 2 )
;; (reduce #'+ *)
; = > 16
See also: `pfin', `psync'")
(defmethod as-pstream ((pfindur pfindur))
(with-slots (pattern dur tolerance) pfindur
(make-instance 'pfindur-pstream
:pattern (pattern-as-pstream pattern)
:dur (as-pstream dur)
:tolerance (next tolerance))))
(defmethod next ((pfindur pfindur-pstream))
(labels ((get-delta (ev)
(etypecase ev
(event
(event-value ev :delta))
(list
(reduce #'max (mapcar #'get-delta ev)))
(number
ev))))
(with-slots (pattern dur tolerance current-dur elapsed-dur) pfindur
(let ((n-event (next pattern)))
(when (eop-p n-event)
(return-from next eop))
(unless (slot-boundp pfindur 'current-dur)
(setf current-dur (next dur)))
(when (eop-p current-dur)
(return-from next eop))
(let ((res (if (or (eql :inf current-dur)
(>= current-dur (+ elapsed-dur (get-delta n-event))))
n-event
(let ((tdur (- current-dur elapsed-dur)))
(when (>= tolerance tdur)
(return-from next eop))
(if (event-p n-event)
(combine-events n-event (event :dur tdur))
tdur)))))
(incf elapsed-dur (get-delta res))
res)))))
;;; psync
(defpattern psync (pattern)
(pattern
sync-quant
(maxdur :initform nil)
(tolerance :initform 0.001)
(elapsed-dur :state t :initform 0))
:documentation "Yield events from PATTERN until their total duration is within TOLERANCE of MAXDUR, cutting off any events that would extend past MAXDUR. If PATTERN ends before MAXDUR, a rest is added to the pstream to round its duration up to the nearest multiple of SYNC-QUANT.
Example:
( next - upto - n ( psync ( : ( pseq ' ( 5 ) 1 ) ) 4 16 ) )
;;
; = > ( ( EVENT : 5 ) ( EVENT : TYPE : REST : DUR 3 ) )
;;
( next - upto - n ( psync ( : ( pseq ' ( 5 ) 5 ) ) 4 16 ) )
;;
; = > ( ( EVENT : 5 ) ( EVENT : 5 ) ( EVENT : 5 ) ( EVENT : 5 : DELTA 1 ) )
See also: `pfindur'")
(defmethod as-pstream ((psync psync))
(with-slots (pattern sync-quant maxdur tolerance) psync
(make-instance 'psync-pstream
:pattern (as-pstream pattern)
:sync-quant (next sync-quant)
:maxdur (next maxdur)
:tolerance (next tolerance))))
(defmethod next ((psync psync-pstream))
(with-slots (pattern sync-quant maxdur tolerance elapsed-dur) psync
(when (and maxdur
(>= elapsed-dur (- maxdur tolerance)))
(return-from next eop))
(let* ((nbfq (next-beat-for-quant sync-quant elapsed-dur))
(n-event (next pattern))
(n-event (if (eop-p n-event)
(let ((diff (- nbfq elapsed-dur)))
(if (plusp diff)
(event :type :rest :dur diff)
(return-from next eop)))
n-event))
(n-event (if maxdur
(combine-events n-event (event :dur (min (event-value n-event :dur)
(- maxdur elapsed-dur))))
n-event)))
(incf elapsed-dur (event-value n-event :dur))
n-event)))
;;; pdurstutter
;; FIX: make a version where events skipped with 0 are turned to rests instead (to keep the correct dur)
(defpattern pdurstutter (pattern)
(pattern
n
(current-value :state t :initform nil)
(current-repeats-remaining :state t :initform 0))
:documentation "Yield each output from PATTERN N times, dividing it by N. If the output from PATTERN is an event, its dur is divided; if it's a number, the number itself is divided instead of being yielded directly.
Example:
( next - n ( pdurstutter ( pseq ' ( 1 2 3 4 5 ) ) ( pseq ' ( 3 2 1 0 2 ) ) ) 9 )
; = > ( 1/3 1/3 1/3 1 1 3 5/2 5/2 NIL )
;;
( next - n ( pdurstutter ( : ( pseq ' ( 1 2 3 4 5 ) ) )
( pseq ' ( 3 2 1 0 2 ) ) )
9 )
; = > ( ( EVENT : DUR 1/3 ) ( EVENT : DUR 1/3 ) ( EVENT : DUR 1/3 ) ( EVENT : 1 ) ( EVENT : 1 ) ( EVENT : 3 ) ( EVENT : DUR 5/2 ) ( EVENT : DUR 5/2 ) NIL )
See also: `pr'")
(defmethod as-pstream ((pdurstutter pdurstutter))
(with-slots (pattern n) pdurstutter
(make-instance 'pdurstutter-pstream
:pattern (as-pstream pattern)
:n (pattern-as-pstream n))))
(defmethod next ((pdurstutter pdurstutter-pstream))
(with-slots (pattern n current-value current-repeats-remaining) pdurstutter
(while (and current-repeats-remaining
(zerop current-repeats-remaining))
(setf current-repeats-remaining (next n))
(let ((e (next pattern)))
(when (eop-p current-repeats-remaining)
(return-from next eop))
(when (and current-repeats-remaining
(not (zerop current-repeats-remaining)))
(setf current-value (if (eop-p e)
eop
(ctypecase e
(event (combine-events e (event :dur (/ (event-value e :dur) current-repeats-remaining))))
(number (/ e current-repeats-remaining))))))))
(when current-repeats-remaining
(decf-remaining pdurstutter)
current-value)))
;;; pbeat
(defpattern pbeat (pattern)
()
:documentation "Yield the number of beats elapsed since the pbeat was embedded in the pstream.
Example:
( next - n ( pbind : ( pseq ' ( 1 2 3 ) ) : foo ( pbeat ) ) 3 )
; = > ( ( EVENT : 1 : FOO 0 ) ( EVENT : 2 : FOO 1 ) ( EVENT : 3 : FOO 3 ) )
See also: `pbeat*', `beat', `prun'")
(defmethod next ((pbeat pbeat-pstream))
(beat (pattern-parent pbeat :class 'pbind)))
;;; pbeat*
(defpattern pbeat* (pattern)
((task :state t :initform nil))
:documentation "Yield the number of beats on the `*clock*' of the current pattern. In other words, pbeat* is clock-synced, unlike `pbeat', which is pattern-synced.
Example:
( next - n ( pbind : ( pseq ' ( 1 2 3 ) ) : foo ( pbeat * ) ) 3 )
; = > ( ( EVENT : 1 : FOO 200 ) ( EVENT : 2 : FOO 201 ) ( EVENT : 3 : FOO 203 ) )
See also: `pbeat', `beat', `prun'")
(defmethod next ((pbeat* pbeat*-pstream))
(beat *clock*))
;;; ptime
(defpattern ptime (pattern)
((last-beat-checked :state t :initform nil)
(tempo-at-beat :state t :initform nil)
(elapsed-time :state t :initform 0))
:documentation "Yield the number of seconds elapsed since ptime was embedded in the pstream.
Note: May give inaccurate results if the clock's tempo changes occur more frequently than events in the parent pbind.
Example:
( setf ( tempo * clock * ) 1 ) ; 60 BPM
( next - n ( pbind : dur 1 : time ( ptime ) ) 2 )
; = > ( ( EVENT : 1 : TIME 0 ) ( EVENT : 1 : TIME 1.0 ) )
See also: `pbeat', `prun', `beat'")
(defmethod next ((ptime ptime-pstream)) ; FIX: take into account the previous tempo if it has been changed since the last-beat-checked.
(with-slots (last-beat-checked tempo-at-beat elapsed-time) ptime
(with-slots (tempo) *clock*
(let ((beat (beat (pattern-parent ptime :class 'pbind))))
(prog1
(incf elapsed-time (if (null last-beat-checked)
0
(dur-time (- beat last-beat-checked) tempo)))
(setf last-beat-checked beat
tempo-at-beat tempo))))))
pindex
;; TODO: alternate version that only calls #'next on index-pat each time the pattern-as-pstream of list-pat has ended.
TODO : pindex1 that only embeds 1 element from subpatterns , a la SuperCollider 's Pswitch1 .
(defpattern pindex (pattern)
(list-pat
index-pat
(wrap-p :initform nil))
:documentation "Use INDEX-PAT to index into the list returned by LIST-PAT. WRAP-P is whether indexes that are out of range will be wrapped (if t) or will simply return nil.
Example:
( next - n ( pindex ( list 99 98 97 ) ( pseq ( list 0 1 2 3 ) ) ) 4 )
;;
; = > ( 99 98 97 NIL )
;;
( next - upto - n ( pindex ( list 99 98 97 ) ( pseries 0 1 6 ) t ) )
;;
; = > ( 99 98 97 99 98 97 )
See also: `pwalk'")
(defmethod as-pstream ((pindex pindex))
(with-slots (list-pat index-pat wrap-p) pindex
(make-instance 'pindex-pstream
:list-pat (pattern-as-pstream list-pat)
:index-pat (pattern-as-pstream index-pat)
:wrap-p wrap-p)))
(defmethod next ((pindex pindex-pstream)) ; FIX: make this work for envelopes as well (the index should not be normalized)
(with-slots (list-pat index-pat wrap-p) pindex
(let ((list (next list-pat))
(idx (next index-pat)))
(when (or (eop-p idx)
(eop-p list))
(return-from next eop))
(funcall (if wrap-p 'nth-wrap 'nth) idx list))))
;;; prun
(defpattern prun (pattern)
(pattern
(dur :initform 1)
(current-dur :state t :initform 0))
:documentation "Run PATTERN \"independently\" of its parent, holding each value for DUR beats. Each of PATTERN's outputs is treated as if it lasted DUR beats, being continuously yielded during that time before moving on to the next output.
Example:
( next - upto - n ( pbind : foo ( pseq ' ( 1 2 3 4 5 ) )
: bar ( prun ( pseq ' ( 4 5 6 7 8) )
( pseq ' ( 1 2 0.5 0.5 1 ) ) ) ) )
; = > ( ( EVENT : FOO 1 : BAR 4 )
( EVENT : FOO 2 : BAR 5 )
( EVENT : FOO 3 : BAR 5 )
( EVENT : FOO 4 : BAR 6 )
( EVENT : FOO 5 : BAR 8) )
See also: `beat', `pbeat'")
(defmethod as-pstream ((prun prun))
(with-slots (pattern dur) prun
(unless (pattern-parent prun :class 'pbind)
(error "~S cannot be used outside of a pbind" prun))
(make-instance 'prun-pstream
:pattern (as-pstream pattern)
:dur (pattern-as-pstream dur)
:current-dur 0)))
(defmethod next ((prun prun-pstream))
(with-slots (pattern dur current-dur dur-history number) prun
(let ((beats (beat (pattern-parent prun :class 'pbind))))
(flet ((next-dur ()
(let ((nxt (next dur)))
(unless (eop-p nxt)
(next pattern)
(incf current-dur nxt)))))
(when (zerop number)
(next-dur))
(while (and (or (not (pstream-p dur))
(not (ended-p dur)))
(<= current-dur beats))
(next-dur))))
(last-output pattern)))
psym
(defpattern psym (pattern)
(pattern
(current-pstream :state t :initform eop))
:documentation "Use a pattern of symbols to embed `pdef's. PATTERN is the source pattern that yields symbols naming the pdef to embed.
Example:
( pdef : foo ( pseq ' ( 1 2 3 ) 1 ) )
;;
( pdef : bar ( pseq ' ( 4 5 6 ) 1 ) )
;;
( next - upto - n ( psym ( pseq ' (: foo : bar ) 1 ) ) )
;;
;; ;=> (1 2 3 4 5 6)
See also: `pdef', `ppar', `pmeta'")
(defmethod as-pstream ((psym psym))
(with-slots (pattern) psym
(make-instance 'psym-pstream
:pattern (as-pstream pattern))))
(defmethod next ((psym psym-pstream))
(labels ((maybe-pdef (x)
(if-let ((pdef (and (symbolp x)
(pdef-pattern x))))
pdef
x)))
(with-slots (pattern current-pstream) psym
(let ((n (next current-pstream)))
(if (eop-p n)
(let ((next-pdef (next pattern)))
(when (eop-p next-pdef)
(return-from next eop))
(setf current-pstream (as-pstream (if (listp next-pdef)
(ppar (mapcar #'maybe-pdef next-pdef))
(maybe-pdef next-pdef))))
(next psym))
n)))))
;;; pchain
(defpattern pchain (pattern)
(patterns)
:documentation "Combine multiple patterns into one event stream.
Example:
( next - n ( pchain ( : foo ( pseq ' ( 1 2 3 ) ) ) ( pbind : bar ( pseq ' ( 7 8 9 ) 1 ) ) ) 4 )
;;
; = > ( ( EVENT : FOO 1 : BAR 7 ) ( EVENT : FOO 2 : BAR 8) ( EVENT : FOO 3 : BAR 9 ) NIL )
See also: `pbind''s :embed key"
:defun (defun pchain (&rest patterns)
(make-instance 'pchain
:patterns patterns)))
(defmethod as-pstream ((pchain pchain))
(with-slots (patterns) pchain
(make-instance 'pchain-pstream
:patterns (mapcar #'pattern-as-pstream patterns))))
(defmethod next ((pchain pchain-pstream))
(with-slots (patterns) pchain
(let ((c-event (make-default-event)))
(dolist (pattern patterns c-event)
(setf c-event (combine-events c-event
(let ((*event* c-event))
(next pattern))))))))
;;; pdiff
(defpattern pdiff (pattern)
(pattern)
:documentation "Output the difference between successive outputs of PATTERN.
Example:
( next - n ( pdiff ( pseq ' ( 3 1 4 3 ) 1 ) ) 4 )
;;
; = > ( -2 3 -1 NIL )
See also: `pdelta'")
(defmethod next ((pdiff pdiff-pstream))
(with-slots (pattern) pdiff
(when (zerop (slot-value pattern 'history-number))
(next pattern))
(let ((last (pstream-elt pattern -1))
(next (next pattern)))
(when (or (eop-p last)
(eop-p next))
(return-from next eop))
(- next last))))
pdelta
(defpattern pdelta (pattern)
(pattern
(cycle :initform 4))
:documentation "Output the difference between successive outputs of PATTERN, assuming PATTERN restarts every CYCLE outputs.
Unlike `pdiff', pdelta is written with its use as input for `pbind''s :delta key in mind. If PATTERN's successive values would result in a negative difference, pdelta instead wraps the delta around to the next multiple of CYCLE. This would allow you to, for example, supply the number of the beat that each event occurs on, rather than specifying the delta between each event. This is of course achievable using pbind's :beat key as well, however that method requires the pbind to peek at future values, which is not always desirable.
Based on the pattern originally from the ddwPatterns SuperCollider library.
Example:
( next - n ( pdelta ( pseq ' ( 0 1 2 3 ) ) 4 ) 8)
;;
; = > ( 1 1 1 1 1 1 1 1 )
;;
( next - n ( pdelta ( pseq ' ( 0 1 2 5 ) ) 4 ) 8)
;;
; = > ( 1 1 3 3 1 1 3 3 )
See also: `pdiff', `pbind''s :beat key")
(defmethod as-pstream ((pdelta pdelta))
(with-slots (pattern cycle) pdelta
(make-instance 'pdelta-pstream
:pattern (as-pstream pattern)
:cycle (next cycle))))
(defmethod next ((pdelta pdelta-pstream))
(with-slots (pattern cycle history-number) pdelta
(when (zerop history-number)
(next pattern))
(let ((lv (or (pstream-elt pattern -1) 0))
(cv (next pattern)))
(when (or (eop-p lv)
(eop-p cv))
(return-from next eop))
(- cv
(- lv (ceiling-by (- lv cv) cycle))))))
;;; pdrop
(defpattern pdrop (pattern)
(pattern
(n :initform 0))
:documentation "Drop the first N outputs from PATTERN and yield the rest. If N is negative, drop the last N outputs from PATTERN instead.
Example:
( next - n ( pdrop ( pseq ' ( 1 2 3 4 ) 1 ) 2 ) 4 )
;;
; = > ( 3 4 NIL NIL )
See also: `protate'")
(defmethod as-pstream ((pdrop pdrop))
;; FIX: check that n is not bigger or smaller than history allows
(with-slots (pattern n) pdrop
(make-instance 'pdrop-pstream
:pattern (as-pstream pattern)
:n n)))
(defmethod next ((pdrop pdrop-pstream))
(with-slots (pattern n number) pdrop
(if (minusp n)
(when (eop-p (pstream-elt-future pattern (- number n)))
(return-from next eop))
(when (zerop (slot-value pattern 'history-number))
(dotimes (i n)
(next pattern))))
(next pattern)))
;;; ppar
(defpattern ppar (pattern)
(patterns
(pstreams :state t :initform nil))
:documentation "Combine multiple event patterns into one pstream with all events in temporal order. PATTERNS is the list of patterns, or a pattern yielding lists of patterns. The ppar ends when all of the patterns in PATTERNS end.
Example:
( next - upto - n ( ppar ( list ( : dur ( pn 1/2 4 ) )
( pbind : dur ( pn 2/3 4 ) ) ) ) )
;;
; = > ( ( EVENT : 1/2 : DELTA 0 ) ( EVENT : DUR 2/3 : DELTA 1/2 )
( EVENT : 1/2 : DELTA 1/6 ) ( EVENT : DUR 2/3 : DELTA 1/3 )
( EVENT : 1/2 : DELTA 1/3 ) ( EVENT : DUR 2/3 : DELTA 1/6 )
( EVENT : 1/2 : DELTA 1/2 ) ( EVENT : DUR 2/3 : DELTA 2/3 ) )
See also: `psym'")
(defmethod next ((ppar ppar-pstream))
(with-slots (patterns pstreams history-number) ppar
(labels ((next-in-pstreams ()
(or (most #'< pstreams :key #'beat)
eop))
(maybe-reset-pstreams ()
(unless (remove eop pstreams)
(let ((next-list (next patterns)))
(when (eop-p next-list)
(return-from maybe-reset-pstreams nil))
(setf pstreams (mapcar (lambda (item)
(as-pstream (if (symbolp item)
(find-pdef item)
item)))
next-list))))))
(when (zerop history-number)
(maybe-reset-pstreams))
(let* ((next-pat (next-in-pstreams))
(nxt (next next-pat)))
(if (eop-p nxt)
(progn
(removef pstreams next-pat)
(let ((nip (next-in-pstreams)))
(if (eop-p nip)
eop
(event :type :rest :delta (- (beat nip) (beat ppar))))))
(combine-events nxt (event :delta (- (beat (next-in-pstreams)) (beat ppar)))))))))
;;; pts
(defpattern pts (pattern)
(pattern
(dur :initform 4)
(pattern-outputs :state t))
:documentation "Timestretch PATTERN so its total duration is DUR. Note that only the first `*max-pattern-yield-length*' events from PATTERN are considered, and that they are calculated immediately at pstream creation time rather than lazily as the pstream yields.
Example:
( next - upto - n ( pts ( : dur ( pn 1 4 ) ) 5 ) )
;;
; = > ( ( EVENT : DUR 5/4 ) ( EVENT : DUR 5/4 ) ( EVENT : DUR 5/4 ) ( EVENT : DUR 5/4 ) )
See also: `pfindur', `psync'")
(defmethod as-pstream ((pts pts))
(with-slots (pattern dur) pts
(let* ((pstr (as-pstream pattern))
(res (next-upto-n pstr)))
(make-instance 'pts-pstream
:pattern pstr
:dur (next dur)
:pattern-outputs (coerce res 'vector)))))
(defmethod next ((pts pts-pstream))
(with-slots (pattern dur pattern-outputs number) pts
(when (>= number (length pattern-outputs))
(return-from next eop))
(let ((mul (/ dur (beat pattern)))
(ev (elt pattern-outputs number)))
(combine-events ev (event :dur (* mul (event-value ev :dur)))))))
pwalk
(defpattern pwalk (pattern)
(list
step-pattern
(direction-pattern :initform 1)
(start-pos :initform 0)
(current-index :state t)
(current-direction :initform 1 :state t))
:documentation "\"Walk\" over the values in LIST by using the accumulated value of the outputs of STEP-PATTERN as the index. At the beginning of the pwalk and each time the start or end of the list is passed, the output of DIRECTION-PATTERN is taken and used as the multiplier for values from STEP-PATTERN. START-POS is the index in LIST for pwalk to take its first output from.
Example:
; ; using ( pseq ( list 1 -1 ) ) as the DIRECTION - PATTERN causes the pwalk 's output to \"ping - pong\ " :
( next - n ( pwalk ( list 0 1 2 3 ) ( pseq ( list 1 ) ) ( pseq ( list 1 -1 ) ) ) 10 )
;;
;; ;=> (0 1 2 3 2 1 0 1 2 3)
See also: `pindex', `pbrown', `paccum'")
(defmethod as-pstream ((pwalk pwalk))
(with-slots (list step-pattern direction-pattern start-pos) pwalk
(make-instance 'pwalk-pstream
:list (next list)
:step-pattern (pattern-as-pstream step-pattern)
:direction-pattern (pattern-as-pstream direction-pattern)
:start-pos (pattern-as-pstream start-pos))))
(defmethod next ((pwalk pwalk-pstream))
(with-slots (list step-pattern direction-pattern start-pos current-index current-direction number) pwalk
(when (zerop number)
(setf current-index (next start-pos))
(setf current-direction (next direction-pattern))
(return-from next (nth current-index list)))
(let ((nsp (next step-pattern)))
(when (or (eop-p nsp) (eop-p current-index) (eop-p current-direction))
(return-from next eop))
(labels ((next-index ()
(+ current-index (* nsp current-direction))))
(let ((next-index (next-index)))
(when (or (minusp next-index)
(>= next-index (length list)))
(setf current-direction (next direction-pattern)))
(when (eop-p current-direction)
(return-from next eop))
(setf current-index (mod (next-index) (length list))))))
(elt-wrap list current-index)))
;;; pparchain
(defpattern pparchain (pchain)
(patterns)
:documentation "Combine multiple patterns into several event streams. The event yielded by the first pattern will be used as the input event to the second pattern, and so on. The events yielded by each pattern will be collected into a list and yielded by the pparchain. This pattern is effectively `ppar' and `pchain' combined.
Example:
( next - upto - n ( pparchain ( pbind : foo ( pseries 0 1 3 ) ) ( : baz ( p+ ( pk : foo ) 1 ) : foo ( p+ ( pk : foo ) 3 ) ) ) )
; = > ( ( ( EVENT : FOO 0 ) ( EVENT : FOO 3 : BAZ 1 ) )
( ( EVENT : FOO 1 ) ( EVENT : FOO 4 : BAZ 2 ) )
( ( EVENT : FOO 2 ) ( EVENT : FOO 5 : BAZ 3 ) ) )
See also: `ppc', `ppar', `pchain', `pbind''s :embed key"
:defun (defun pparchain (&rest patterns)
(make-instance 'pparchain
:patterns patterns)))
(defmethod as-pstream ((pparchain pparchain))
(with-slots (patterns) pparchain
(make-instance 'pparchain-pstream
:patterns (mapcar #'as-pstream patterns))))
(defmethod next ((pparchain pparchain-pstream))
(with-slots (patterns) pparchain
(let ((c-event (make-default-event)))
(loop :for pattern :in patterns
:do (setf c-event (combine-events c-event (let ((*event* (copy-event c-event)))
(next pattern))))
:if (eop-p c-event)
:return eop
:else
:collect c-event))))
;;; ppc
(defmacro ppc (&body pairs)
"Syntax sugar for `pparchain' that automatically splits PAIRS by :- symbols.
Example:
( ppc : foo ( pseq ( list 1 2 3 ) 1 )
;; :-
: bar ( p+ ( pk : foo ) 2 ) )
; = > ( ( ( EVENT : FOO 1 ) ( EVENT : FOO 1 : BAR 3 ) )
( ( EVENT : FOO 2 ) ( EVENT : FOO 2 : BAR 4 ) )
( ( EVENT : FOO 3 ) ( EVENT : FOO 3 : BAR 5 ) ) )
See also: `pparchain'"
(labels ((ppc-split (pairs)
(let ((pos (position :- pairs)))
(if pos
(list (subseq pairs 0 pos)
(ppc-split (subseq pairs (1+ pos))))
pairs))))
`(pparchain ,@(loop :for i :in (ppc-split pairs)
:collect (cons 'pbind i)))))
(pushnew 'ppc *patterns*)
;;; pclump
(defpattern pclump (pattern)
(pattern
(n :initform 1))
:documentation "Group outputs of the source pattern into lists of up to N items each.
Example:
( next - upto - n ( pclump ( pseries 0 1 5 ) 2 ) )
; = > ( ( 0 1 ) ( 2 3 ) ( 4 ) )
See also: `paclump'")
(defmethod next ((pclump pclump-pstream))
(with-slots (pattern n) pclump
(let ((next (next n)))
(when (eop-p next)
(return-from next eop))
(or (next-upto-n pattern next)
eop))))
;;; paclump
(defpattern paclump (pattern)
(pattern)
:documentation "Automatically group outputs of the source pattern into lists of up to N items each. Unlike `pclump', clump size is automatically set to the length of the longest list in the values of `*event*', or 1 if there are no lists.
Example:
( next - upto - n ( pbind : foo ( pseq ' ( ( 1 ) ( 1 2 ) ( 1 2 3 ) ) 1 ) : bar ( paclump ( pseries ) ) ) )
; = > ( ( EVENT : FOO ( 1 ) : BAR ( 0 ) ) ( EVENT : FOO ( 1 2 ) : BAR ( 1 2 ) ) ( EVENT : FOO ( 1 2 3 ) : BAR ( 3 4 5 ) ) )
See also: `pclump'")
(defmethod next ((paclump paclump-pstream))
(with-slots (pattern) paclump
(unless *event*
(return-from next eop))
(next-upto-n pattern (reduce #'max (mapcar (fn (length (ensure-list (e _))))
(keys *event*))))))
;;; paccum
;; /~gwright3/stdmp2/docs/SuperCollider_Book/code/Ch%2020%20dewdrop%20and%20chucklib/dewdrop_lib/ddwPatterns/Help/Paccum.html
(defpattern paccum (pattern)
((operator :initform #'+)
(start :initform 0)
(step :initform 1)
(length :initform :inf)
(lo :initform nil)
(hi :initform nil)
(bound-by :initform nil)
(current-value :state t)
(current-repeats-remaining :state t))
the value is provided as its first argument , and LO and HI are provided as its second and third .
Based on the pattern originally from the ddwPatterns SuperCollider library.
Example:
( next - upto - n ( paccum # ' + 0 1 ) 5 ) ; same as ( pseries 0 1 )
;; ;=> (0 1 2 3 4)
( next - upto - n ( paccum # ' + 0 1 : : lo 0 : hi 3 : bound - by # ' wrap ) 9 ) ; same as above , wrapping between 0 and 3 .
;; ;=> (0 1 2 0 1 2 0 1 2)
See also: `pseries', `pgeom', `pwalk'"
:defun
(defun paccum (&optional (operator #'+) (start 0) (step 1) (length :inf) &key lo hi bound-by)
(make-instance 'paccum
:operator operator
:start start
:step step
:length length
:lo lo
:hi hi
:bound-by bound-by)))
(defmethod next ((paccum paccum-pstream))
(with-slots (operator start step length lo hi bound-by current-value) paccum
(unless (remaining-p paccum 'length)
(return-from next eop))
(decf-remaining paccum)
(setf current-value (if (slot-boundp paccum 'current-value)
(when-let ((res (funcall (if (pstream-p operator)
(next operator)
operator)
current-value
(next step))))
(if bound-by
(when-let ((func (if (pstream-p bound-by)
(next bound-by)
bound-by))
(lo (next lo))
(hi (next hi)))
(funcall func res lo hi))
res))
(next start)))))
;;; ps
;; -help/Help/Classes/PS.html
;; -help/Help/Tutorials/PSx_stream_patterns.html
(defpattern ps (pattern)
(pattern
pstream)
:documentation "Preserve pstream state across subsequent calls to `as-pstream'. To reset the pstream, simply re-evaluate the ps definition.
Based on the pattern originally from the miSCellaneous SuperCollider library.
Example:
;; (defparameter *pst* (ps (pseries)))
;;
( next - upto - n * pst * 4 )
;; ;=> (0 1 2 3)
;;
( next - upto - n * pst * 4 )
; = > ( 4 5 6 7 )
;;
;; (defparameter *pst* (ps (pseries)))
;;
( next - upto - n * pst * 4 )
;; ;=> (0 1 2 3)
See also: `prs', `pdef'"
:defun (defun ps (pattern)
(make-instance 'ps
:pattern pattern)))
(defmethod as-pstream ((ps ps))
(with-slots (pattern pstream) ps
(make-instance 'ps-pstream
:pattern pattern
:pstream (if (slot-boundp ps 'pstream)
pstream
(let ((pstr (as-pstream pattern)))
(setf pstream pstr)
pstr)))))
(defmethod next ((ps-pstream ps-pstream))
(with-slots (pstream) ps-pstream
(next pstream)))
;;; prs
(defun prs (pattern &optional (repeats :inf))
"Syntax sugar for (pr (ps PATTERN) REPEATS). Useful, for example, to ensure that each cycle of a pattern only gets one value from the `ps'.
See also: `pr', `ps'"
(pr (ps pattern) repeats))
(pushnew 'prs *patterns*)
;;; ipstream
(defpattern ipstream (pattern)
((patterns :initform (list))
(end-when-empty :initform nil)
(granularity :initform 1/5)
(lock :state t :initform (bt:make-recursive-lock "ipstream patterns slot lock")))
:documentation "Insertable pstream; a pstream that can be changed while it's running by inserting new patterns at a specified beat.")
(defmethod as-pstream ((ipstream ipstream))
(with-slots (patterns end-when-empty granularity) ipstream
(let ((pstr (make-instance 'ipstream-pstream
:patterns (list)
:end-when-empty end-when-empty
:granularity granularity
:lock (bt:make-recursive-lock "ipstream patterns slot lock"))))
(dolist (pat patterns pstr)
(etypecase pat
(pattern
(ipstream-insert pstr pat 0))
(list
(destructuring-bind (beat &rest patterns) pat
(dolist (pat patterns)
(ipstream-insert pstr pat beat)))))))))
(defmethod next ((ipstream ipstream-pstream))
(with-slots (patterns end-when-empty granularity lock) ipstream
(labels ((actual-beat (pstream)
(+ (slot-value pstream 'start-beat) (beat pstream)))
(sorted-pstrs ()
(sort patterns #'< :key #'actual-beat)))
(bt:with-recursive-lock-held (lock)
(if patterns
(let* ((next-pstr (car (sorted-pstrs)))
(ev (if (<= (actual-beat next-pstr)
(beat ipstream))
(let ((nxt (next next-pstr)))
(if (eop-p nxt)
(progn
(deletef patterns next-pstr)
(next ipstream))
nxt))
(event :type :rest :delta granularity)))
(next-pstr (car (sorted-pstrs))))
(combine-events ev (event :delta (if next-pstr
(min granularity
(- (actual-beat next-pstr)
(beat ipstream)))
granularity))))
(if end-when-empty
eop
(event :type :rest :delta granularity)))))))
(defgeneric ipstream-insert (ipstream pattern &optional start-beat)
(:documentation "Insert PATTERN into IPSTREAM at START-BEAT. START-BEAT defaults to the ipstream's current beat."))
(defmethod ipstream-insert ((ipstream ipstream-pstream) pattern &optional start-beat)
(with-slots (patterns lock) ipstream
(let ((pstr (as-pstream pattern)))
(setf (slot-value pstr 'start-beat) (or start-beat (beat ipstream)))
(bt:with-lock-held (lock)
(push pstr patterns)))))
(export 'ipstream-insert)
;;; pfilter
(defpattern pfilter (pattern)
(pattern
(predicate :initform 'identity))
:documentation "Skip elements of a source pattern that PREDICATE returns false for. If PREDICATE is not a function, skip items that are `eql' to it.
Example:
( next - n ( pfilter ( pseq ( list 1 2 3 ) )
2 )
6 )
;; ;=> (1 3 1 3 1 3)
;; (next-n (pfilter (pseries 0 1) 'evenp)
6 )
;; ;=> (1 3 5 7 9 11)
See also: `pfilter-out', `pr', `pdurstutter'")
(defmethod next ((pfilter pfilter-pstream))
(with-slots (pattern predicate) pfilter
(let ((func (if (function-designator-p predicate)
predicate
(lambda (input) (eql input predicate)))))
(loop :for res := (next pattern)
:if (or (eop-p res)
(funcall func res))
:return res))))
;;; pfilter-out
(defun pfilter-out (pattern predicate)
"Skip elements of a source pattern that PREDICATE returns true for. If PREDICATE is not a function, skip items that are `eql' to it.
See also: `pfilter'"
(pfilter pattern (if (function-designator-p predicate)
(lambda (x) (not (funcall predicate x)))
(lambda (x) (not (eql predicate x))))))
(pushnew 'pfilter-out *patterns*)
| null |
https://raw.githubusercontent.com/defaultxr/cl-patterns/d7ee3a64b031240149dcac676ac11df594cff371/src/patterns/patterns.lisp
|
lisp
|
patterns.lisp - basic pattern functionality (`defpattern', etc) and a variety of basic patterns implemented with it.
pattern glue
FIX: don't show arguments that are set to the defaults?
pattern
pstream
FIX: can we avoid making this inherit from pattern?
FIX: rename to this-index ?
= > 1
= > 1
fallback method; patterns should override their pstream subclasses with their own behaviors
if `next' returns a pattern, we push it to the pattern stack as a pstream
prevent pstreams from being "re-converted" to pstreams
(let ((pstream (as-pstream (pseq '(1 2 3)))))
= > 1
= > 1 ; first item in the pstream 's history
= > 2
= > 2 ; second item in the pstream 's history
= > 2 ; most recent item in the pstream 's history
FIX: add tests for this
(let ((pstream (as-pstream (pseq '(1 2 3)))))
= > 1
= > 1
= > 2
= > 2
the future and history are recorded to the same array.
since the array is of finite size, requesting more from the future than history is able to hold would result in the oldest elements of the future being overwritten with the newest, thus severing the timeline...
temporarily set it to 0 so the `next' method runs normally
pbind
= > ( ( EVENT : FOO 1 : BAR : HELLO ) ( EVENT : FOO 2 : BAR : HELLO ) ( EVENT : FOO 3 : BAR : HELLO ) EOP )
process quant keys.
for example:
(define-pbind-special-init-key inst ; FIX: this should be part of event so it will affect the event as well. maybe just rename to something else?
(list :instrument value))
basically the same as the :embed key, but we have it anyway for convenience.
prest
it is just a regular function that returns a prest object.
= > ( ( EVENT : 0 ) ( EVENT : DEGREE 1 ) ( EVENT : TYPE : REST : DEGREE 2 ) ( EVENT : 3 ) )
pmono
pseq
= > ( 5 6 7 5 6 7 EOP )
= > ( 6 7 5 6 7 5 )
pser
= > ( 5 6 EOP )
pk
= > ( ( EVENT : FOO 1 : BAR 1 ) ( EVENT : FOO 2 : BAR 2 ) ( EVENT : FOO 3 : BAR 3 ) )
prand
= > ( 3 2 2 1 1 EOP )
pxrand
= > ( 3 1 2 1 )
pwrand
= > ( 1 1 2 2 2 1 2 1 1 3 )
pwxrand
;=> (1 2 1 2 1 3 1 2 1 2)
pfunc
= > ( ( 5 2 8 9 ) )
:bar (pfunc (lambda ()
= > ( ( EVENT : FOO 0 : BAR : LESSER ) ( EVENT : FOO 6 : BAR : GREATER )
pf
pr
;=> (0 1 1 1 3 3)
plazy
= > ( 9 8 7 1 2 3 )
protate
= > ( 4 5 1 2 3 )
pn
= > ( 2 4 2 1 0 )
need this so that PATTERN won't be automatically converted to a pstream when the pn is.
pshuf
= > ( 3 1 2 3 1 2 )
alexandria:shuffle destructively modifies the list, so we use copy-list so as to avoid unexpected side effects.
= > ( 7 2 4 5 7 10 4 8 10 2 3 5 9 2 5 4 )
FIX: see about using a symbol for the unprovided slots and just check/process this initialization code in the `next' method instead.
FIX: make the initforms of hi onward a special symbol, and then check for that symbol in `next', rather than checking against the arguments of the `pbrown' function.
= > ( 2 3 3 3 4 3 4 5 6 5 )
pexprand
FIX: integer inputs should result in integer outputs
= > ( 1.0420843091865208d0 1.9340168112124456d0 2.173209129035095d0 4.501371557329618d0 )
pgauss
= > ( 0.08918811646370092d0 0.1745957067161632d0 0.7954678768273173d0 -1.2215823449671597d0 )
(next-upto-n (pseries 1 2 4))
;=> (1 3 5 7)
FIX: current-value should be CURRENT value, not the next one! also write tests for this!
pseries*
= > ( pseries 0 2/3 16 )
(next-upto-n *)
= > ( 0 2/3 4/3 2 8/3 10/3 4 14/3 16/3 6 20/3 22/3 8 26/3 28/3 10 )
pgeom
(next-upto-n (pgeom 1 2 4))
;=> (1 2 4 8)
pgeom*
;=> (pgeom 1 1.9306977 8)
(next-upto-n *)
= > ( 1 1.9306977 3.7275934 7.196856 13.894953 26.826954 51.79474 99.999985 )
;; Note that due to floating point rounding errors the last output may not always be exactly END.
ptrace
place
= > ( 1 2 3 1 2 4 1 2 5 )
ppatlace
;=> (1 4 2 5 3 6 4 5 6)
pnary
= > ( 4 0 4 1 )
prerange
thus you should see `rerange' for more information.
pslide
;=> (1 2 3 3 4 5 5 6 0)
phistory
;=> (0 NIL 1)
pscratch
supercollider:
lisp:
(0 1 2 3 0 1 2 3 0 1 2 3)
FIX: document this in sc-differences.org
;=> (0 0 1 2 1 3 3 4 5 4)
;=> (1 2 9 8 7 3 1 9)
parp
FIX: should this be like `pchain' and accept an arbitrary number of input patterns?
= > ( ( EVENT : FOO 1 : BAR 4 ) ( EVENT : FOO 1 : BAR 5 ) ( EVENT : FOO 1 : BAR 6 )
pfin
= > ( 1 2 3 NIL NIL )
FIX: should be able to use as a gate pattern. remove this whole as-pstream block when it is possible.
pfindur
= > ( ( EVENT : 1 : FOO 0 ) ( EVENT : 1 : FOO 1 ) EOP )
= > ( 1 3 0 1 2 2 1 3 0 1 2 )
(reduce #'+ *)
= > 16
psync
= > ( ( EVENT : 5 ) ( EVENT : TYPE : REST : DUR 3 ) )
= > ( ( EVENT : 5 ) ( EVENT : 5 ) ( EVENT : 5 ) ( EVENT : 5 : DELTA 1 ) )
pdurstutter
FIX: make a version where events skipped with 0 are turned to rests instead (to keep the correct dur)
if it's a number, the number itself is divided instead of being yielded directly.
= > ( 1/3 1/3 1/3 1 1 3 5/2 5/2 NIL )
= > ( ( EVENT : DUR 1/3 ) ( EVENT : DUR 1/3 ) ( EVENT : DUR 1/3 ) ( EVENT : 1 ) ( EVENT : 1 ) ( EVENT : 3 ) ( EVENT : DUR 5/2 ) ( EVENT : DUR 5/2 ) NIL )
pbeat
= > ( ( EVENT : 1 : FOO 0 ) ( EVENT : 2 : FOO 1 ) ( EVENT : 3 : FOO 3 ) )
pbeat*
= > ( ( EVENT : 1 : FOO 200 ) ( EVENT : 2 : FOO 201 ) ( EVENT : 3 : FOO 203 ) )
ptime
60 BPM
= > ( ( EVENT : 1 : TIME 0 ) ( EVENT : 1 : TIME 1.0 ) )
FIX: take into account the previous tempo if it has been changed since the last-beat-checked.
TODO: alternate version that only calls #'next on index-pat each time the pattern-as-pstream of list-pat has ended.
= > ( 99 98 97 NIL )
= > ( 99 98 97 99 98 97 )
FIX: make this work for envelopes as well (the index should not be normalized)
prun
= > ( ( EVENT : FOO 1 : BAR 4 )
;=> (1 2 3 4 5 6)
pchain
= > ( ( EVENT : FOO 1 : BAR 7 ) ( EVENT : FOO 2 : BAR 8) ( EVENT : FOO 3 : BAR 9 ) NIL )
pdiff
= > ( -2 3 -1 NIL )
= > ( 1 1 1 1 1 1 1 1 )
= > ( 1 1 3 3 1 1 3 3 )
pdrop
= > ( 3 4 NIL NIL )
FIX: check that n is not bigger or smaller than history allows
ppar
= > ( ( EVENT : 1/2 : DELTA 0 ) ( EVENT : DUR 2/3 : DELTA 1/2 )
pts
= > ( ( EVENT : DUR 5/4 ) ( EVENT : DUR 5/4 ) ( EVENT : DUR 5/4 ) ( EVENT : DUR 5/4 ) )
; using ( pseq ( list 1 -1 ) ) as the DIRECTION - PATTERN causes the pwalk 's output to \"ping - pong\ " :
;=> (0 1 2 3 2 1 0 1 2 3)
pparchain
= > ( ( ( EVENT : FOO 0 ) ( EVENT : FOO 3 : BAZ 1 ) )
ppc
:-
= > ( ( ( EVENT : FOO 1 ) ( EVENT : FOO 1 : BAR 3 ) )
pclump
= > ( ( 0 1 ) ( 2 3 ) ( 4 ) )
paclump
= > ( ( EVENT : FOO ( 1 ) : BAR ( 0 ) ) ( EVENT : FOO ( 1 2 ) : BAR ( 1 2 ) ) ( EVENT : FOO ( 1 2 3 ) : BAR ( 3 4 5 ) ) )
paccum
/~gwright3/stdmp2/docs/SuperCollider_Book/code/Ch%2020%20dewdrop%20and%20chucklib/dewdrop_lib/ddwPatterns/Help/Paccum.html
same as ( pseries 0 1 )
;=> (0 1 2 3 4)
same as above , wrapping between 0 and 3 .
;=> (0 1 2 0 1 2 0 1 2)
ps
-help/Help/Classes/PS.html
-help/Help/Tutorials/PSx_stream_patterns.html
(defparameter *pst* (ps (pseries)))
;=> (0 1 2 3)
= > ( 4 5 6 7 )
(defparameter *pst* (ps (pseries)))
;=> (0 1 2 3)
prs
ipstream
pfilter
;=> (1 3 1 3 1 3)
(next-n (pfilter (pseries 0 1) 'evenp)
;=> (1 3 5 7 9 11)
pfilter-out
|
(in-package #:cl-patterns)
(defun make-default-event ()
"Get `*event*' if it's not nil, or get a fresh empty event."
(or *event* (event)))
(defvar *patterns* (list)
"List of the names of all defined pattern types.")
(defmacro defpattern (name superclasses slots &key documentation defun)
"Define a pattern. This macro automatically generates the pattern's class, its pstream class, and the function to create an instance of the pattern, and makes them external in the cl-patterns package.
NAME is the name of the pattern. Typically a word or two that describes its function, prefixed with p.
SUPERCLASSES is a list of superclasses of the pattern. Most patterns just subclass the 'pattern' class.
SLOTS is a list of slots that the pattern and pstreams derived from it have. Each slot can either be just a symbol, or a slot definition a la `defclass'. You can provide a default for the slot with the :initform key as usual, and you can set a slot as a state slot (which only appears in the pattern's pstream class) by setting the :state key to t.
DOCUMENTATION is a docstring describing the pattern. We recommend providing at least one example, and a \"See also\" section to refer to similar pattern classes.
DEFUN can either be a full defun form for the pattern, or an expression which will be inserted into the pattern creation function prior to initialization of the instance. Typically you'd use this for inserting `assert' statements, for example.
See also: `pattern', `pdef', `all-patterns'"
(let* ((superclasses (or superclasses (list 'pattern)))
(slots (mapcar #'ensure-list slots))
(name-pstream (pattern-pstream-class-name name))
(super-pstream (if (eql 'pattern (car superclasses))
'pstream
(pattern-pstream-class-name (car superclasses)))))
(labels ((desugar-slot (slot)
"Convert a slot into something appropriate for defclass to handle."
(destructuring-bind (name . rest) slot
(append (list name)
(remove-from-plist rest :state)
(unless (position :initarg (keys rest))
(list :initarg (make-keyword name))))))
(optional-slot-p (slot)
"Whether the slot is optional or not. A slot is considered optional if an initform is provided."
(position :initform (keys (cdr slot))))
(state-slot-p (slot)
"Whether the slot is a pstream state slot or not. Pstream state slots only appear as slots for the pattern's pstream class and not for the pattern itself."
(position :state (keys (cdr slot))))
(function-lambda-list (slots)
"Generate the lambda list for the pattern's creation function."
(let (optional-used)
(mappend (fn (unless (state-slot-p _)
(if (optional-slot-p _)
(prog1
(append (unless optional-used
(list '&optional))
(list (list (car _) (getf (cdr _) :initform))))
(setf optional-used t))
(list (car _)))))
slots)))
(make-defun (pre-init)
`(defun ,name ,(function-lambda-list slots)
,documentation
,@(when pre-init (list pre-init))
(make-instance ',name
,@(mappend (fn (unless (state-slot-p _)
(list (make-keyword (car _)) (car _))))
slots))))
(add-doc-to-defun (sexp)
(if (and (listp sexp)
(position (car sexp) (list 'defun 'defmacro))
(not (stringp (fourth sexp))))
(append (subseq sexp 0 3) (list documentation) (subseq sexp 3))
sexp)))
`(progn
(defclass ,name ,superclasses
,(mapcar #'desugar-slot (remove-if #'state-slot-p slots))
,@(when documentation
`((:documentation ,documentation))))
(defmethod print-object ((,name ,name) stream)
(print-unreadable-object (,name stream :type t)
(format stream "~{~S~^ ~}"
(mapcar (lambda (slot) (slot-value ,name slot))
',(mapcar #'car (remove-if (lambda (slot)
(or (state-slot-p slot)
))
slots))))))
(defclass ,name-pstream (,super-pstream ,name)
,(mapcar #'desugar-slot (remove-if-not #'state-slot-p slots))
(:documentation ,(format nil "pstream for `~A'." (string-downcase name))))
,(let* ((gen-func-p (or (null defun)
(and (listp defun)
(position (car defun) (list 'assert 'check-type)))))
(pre-init (when gen-func-p
defun)))
(if gen-func-p
(make-defun pre-init)
(add-doc-to-defun defun)))
(pushnew ',name *patterns*)))))
(defvar *max-pattern-yield-length* 256
"The default maximum number of events or values that will be used by functions like `next-n' or patterns like `protate', in order to prevent hangs caused by infinite-length patterns.")
(defgeneric pattern-source (pattern)
(:documentation "The source object that this object was created from. For example, for a `pstream', this would be the pattern that `as-pstream' was called on."))
(defgeneric pstream-count (pattern)
(:documentation "The number of pstreams that have been made of this pattern."))
(defclass pattern ()
((play-quant :initarg :play-quant :documentation "A list of numbers representing when the pattern's pstream can start playing. See `play-quant' and `quant'.")
(end-quant :initarg :end-quant :accessor end-quant :type list :documentation "A list of numbers representing when a pattern can end playing and when a `pdef' can be swapped out for a new definition. See `end-quant' and `quant'.")
(end-condition :initarg :end-condition :initform nil :accessor end-condition :type (or null function) :documentation "Nil or a function that is called by the clock with the pattern as its argument to determine whether the pattern should end or swap to a new definition.")
(source :initarg :source :initform nil :accessor pattern-source :documentation "The source object that this object was created from. For example, for a `pstream', this would be the pattern that `as-pstream' was called on.")
(parent :initarg :parent :initform nil :documentation "When a pattern is embedded in another pattern, the embedded pattern's parent slot points to the pattern it is embedded in.")
(loop-p :initarg :loop-p :documentation "Whether or not the pattern should loop when played.")
(cleanup :initarg :cleanup :initform (list) :documentation "A list of functions that are run when the pattern ends or is stopped.")
(pstream-count :initform 0 :accessor pstream-count :documentation "The number of pstreams that have been made of this pattern.")
(metadata :initarg :metadata :initform (make-hash-table) :type hash-table :documentation "Hash table of additional data associated with the pattern, accessible with the `pattern-metadata' function."))
(:documentation "Abstract pattern superclass."))
(defun set-parents (pattern)
"Loop through PATTERN's slots and set the \"parent\" slot of any patterns to this pattern."
(labels ((set-parent (list parent)
"Recurse through LIST, setting the parent of any pattern found to PARENT."
(typecase list
(list
(mapc (lambda (x) (set-parent x parent)) list))
(pattern
(setf (slot-value list 'parent) parent)))))
(dolist (slot (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pattern))) pattern)
(when (and (not (eql slot 'parent))
(slot-boundp pattern slot))
(set-parent (slot-value pattern slot) pattern)))))
(defmethod initialize-instance :after ((pattern pattern) &key)
(set-parents pattern))
(defun pattern-p (object)
"True if OBJECT is a pattern.
See also: `pattern', `defpattern'"
(typep object 'pattern))
(defun all-patterns ()
"Get a list of the names of all defined pattern classes.
See also: `all-pdefs'"
*patterns*)
(defmethod play-quant ((pattern pattern))
(if (slot-boundp pattern 'play-quant)
(slot-value pattern 'play-quant)
(list 1)))
(defmethod (setf play-quant) (value (pattern pattern))
(setf (slot-value pattern 'play-quant) (ensure-list value)))
(defmethod end-quant ((pattern pattern))
(when (slot-boundp pattern 'end-quant)
(slot-value pattern 'end-quant)))
(defmethod (setf end-quant) (value (pattern pattern))
(setf (slot-value pattern 'end-quant) (ensure-list value)))
(defmethod play ((pattern pattern))
(clock-add (as-pstream pattern) *clock*))
(defmethod launch ((pattern pattern))
(play pattern))
(defmethod playing-p ((pattern pattern) &optional (clock *clock*))
(when clock
(find pattern (clock-tasks clock)
:key (fn (slot-value _ 'item)))))
(defmethod loop-p ((pattern pattern))
(when (slot-boundp pattern 'loop-p)
(slot-value pattern 'loop-p)))
(defmethod (setf loop-p) (value (pattern pattern))
(setf (slot-value pattern 'loop-p) value))
(defmethod dur ((pattern pattern))
(reduce #'+ (next-upto-n pattern) :key #'dur))
(defun pattern-parent (pattern &key (num 1) (accumulate nil) (class 'pattern))
"Get the NUM-th containing pattern of PATTERN, or nil if there isn't one. If CLASS is specified, only consider patterns of that class.
See also: `pattern-children'"
(check-type num (integer 0))
(let ((i 0)
res)
(until (or (>= i num)
(null pattern))
(setf pattern (slot-value pattern 'parent))
(when (typep pattern class)
(incf i)
(when accumulate
(appendf res pattern))))
(if accumulate
res
pattern)))
(defun pattern-children (pattern &key (num 1) (accumulate nil) (class 'pattern))
"Get a list of all the direct child patterns of PATTERN, including any in slots or lists.
See also: `pattern-parent'"
(let ((cur (list pattern))
res)
(dotimes (n num res)
(setf cur (remove-if-not (lambda (pattern) (typep pattern class))
(mapcan #'%pattern-children cur)))
(if accumulate
(appendf res cur)
(setf res cur)))))
(defmethod %pattern-children ((object t))
nil)
(defmethod %pattern-children ((pattern pattern))
(mapcan (lambda (slot)
(copy-list (ensure-list (slot-value pattern (closer-mop:slot-definition-name slot)))))
(closer-mop:class-direct-slots (class-of pattern))))
(defgeneric pattern-metadata (pattern &optional key)
(:documentation "Get the value of PATTERN's metadata for KEY. Returns true as a second value if the metadata had an entry for KEY, or nil if it did not."))
(defmethod pattern-metadata ((pattern pattern) &optional key)
(with-slots (metadata) pattern
(if key
(gethash key metadata)
metadata)))
(defun (setf pattern-metadata) (value pattern key)
(setf (gethash key (slot-value pattern 'metadata)) value))
(defgeneric peek (pattern)
(:documentation "\"Peek\" at the next value of a pstream, without advancing its current position.
See also: `next', `peek-n', `peek-upto-n'"))
(defun peek-n (pstream &optional (n *max-pattern-yield-length*))
"Peek at the next N results of a pstream, without advancing it forward in the process.
See also: `peek', `peek-upto-n', `next', `next-n'"
(check-type n (integer 0))
(unless (pstream-p pstream)
(return-from peek-n (peek-n (as-pstream pstream) n)))
(with-slots (number future-number) pstream
(loop :for i :from 0 :below n
:collect (pstream-elt-future pstream (+ number (- future-number) i)))))
(defun peek-upto-n (pstream &optional (n *max-pattern-yield-length*))
"Peek at up to the next N results of a pstream, without advancing it forward in the process.
See also: `peek', `peek-n', `next', `next-upto-n'"
(check-type n (integer 0))
(unless (pstream-p pstream)
(return-from peek-upto-n (peek-upto-n (as-pstream pstream) n)))
(with-slots (number future-number) pstream
(loop :for i :from 0 :below n
:for res := (pstream-elt-future pstream (+ number (- future-number) i))
:until (eop-p res)
:collect res)))
(defgeneric next (pattern)
(:documentation "Get the next value of a pstream, function, or other object, advancing the pstream forward in the process.
See also: `next-n', `next-upto-n', `peek'")
(:method-combination pattern))
(defmethod next ((object t))
object)
(defmethod next ((pattern pattern))
(next (as-pstream pattern)))
(defmethod next ((function function))
(funcall function))
(defun next-n (pstream &optional (n *max-pattern-yield-length*))
"Get the next N outputs of a pstream, function, or other object, advancing the pstream forward N times in the process.
See also: `next', `next-upto-n', `peek', `peek-n'"
(check-type n (integer 0))
(let ((pstream (pattern-as-pstream pstream)))
(loop :repeat n
:collect (next pstream))))
(defun next-upto-n (pstream &optional (n *max-pattern-yield-length*))
"Get a list of up to N results from PSTREAM, not including the end of pattern.
See also: `next', `next-n', `peek', `peek-upto-n'"
(check-type n (integer 0))
(let ((pstream (pattern-as-pstream pstream)))
(loop
:for number :from 0 :upto n
:while (< number n)
:for val := (next pstream)
:if (eop-p val)
:do (loop-finish)
:else
:collect val)))
(defgeneric bsubseq (object start-beat &optional end-beat)
(:documentation "\"Beat subseq\" - get a list of all events from OBJECT whose `beat' is START-BEAT or above, and below END-BEAT.
See also: `events-in-range'"))
(defgeneric events-in-range (pstream min max)
(:documentation "Get all the events from PSTREAM whose start beat are MIN or greater, and less than MAX."))
(defmethod events-in-range ((pattern pattern) min max)
(events-in-range (as-pstream pattern) min max))
(defclass pstream (pattern #+#.(cl:if (cl:find-package "SEQUENCE") '(:and) '(:or)) sequence)
(pattern-stack :initform (list) :documentation "The stack of pattern pstreams embedded in this pstream.")
(pstream-count :initarg :pstream-count :accessor pstream-count :type integer :documentation "How many times a pstream was made of this pstream's source prior to this pstream. For example, if it was the first time `as-pstream' was called on the pattern, this will be 0.")
(beat :initform 0 :reader beat :type number :documentation "The number of beats that have elapsed since the start of the pstream.")
(history :type vector :documentation "The history of outputs yielded by the pstream.")
(history-number :initform 0 :documentation "The number of items in this pstream's history. Differs from the number slot in that all outputs are immediately included in its count.")
(start-beat :initarg :start-beat :initform nil :documentation "The beat number of the parent pstream when this pstream started.")
(future-number :initform 0 :documentation "The number of peeks into the future that have been made in the pstream. For example, if `peek' is used once, this would be 1. If `next' is called after that, future-number decreases back to 0.")
(future-beat :initform 0 :documentation "The current beat including all future outputs (the `beat' slot does not include peeked outputs)."))
(:documentation "\"Pattern stream\". Keeps track of the current state of a pattern in process of yielding its outputs."))
(defmethod initialize-instance :before ((pstream pstream) &key)
(with-slots (history) pstream
(setf history (make-array *max-pattern-yield-length* :initial-element nil))))
(defmethod initialize-instance :after ((pstream pstream) &key)
(set-parents pstream))
(defmethod print-object ((pstream pstream) stream)
(with-slots (number) pstream
(print-unreadable-object (pstream stream :type t)
(format stream "~S ~S" :number number))))
(defun pstream-p (object)
"True if OBJECT is a pstream.
See also: `pstream', `as-pstream'"
(typep object 'pstream))
(defmethod loop-p ((pstream pstream))
(if (slot-boundp pstream 'loop-p)
(slot-value pstream 'loop-p)
(loop-p (slot-value pstream 'source))))
(defmethod ended-p ((pstream pstream))
(with-slots (number future-number) pstream
(and (not (zerop (- number future-number)))
(eop-p (pstream-elt pstream -1)))))
(defmethod events-in-range ((pstream pstream) min max)
(while (and (<= (beat pstream) max)
(not (ended-p pstream)))
(let ((next (next pstream)))
(unless (typep next '(or null event))
(error "events-in-range can only be used on event streams."))))
(loop :for i :across (slot-value pstream 'history)
:if (and i
(>= (beat i) min)
(< (beat i) max))
:collect i
:if (or (eop-p i)
(>= (beat i) max))
:do (loop-finish)))
(defgeneric last-output (pstream)
(:documentation "Returns the last output yielded by PSTREAM.
Example:
( defparameter * pstr * ( as - pstream ( pseq ' ( 1 2 3 ) 1 ) ) )
See also: `ended-p'"))
(defmethod last-output ((pstream pstream))
(with-slots (number future-number) pstream
(let ((idx (- number future-number)))
(when (plusp idx)
(pstream-elt pstream (- idx (if (ended-p pstream) 2 1)))))))
(defun value-remaining-p (value)
i.e. VALUE is a symbol ( i.e. : ) , or a number greater than 0 .
See also: `remaining-p', `decf-remaining'"
(typecase value
(null nil)
(symbol (eql value :inf))
(number (plusp value))
(otherwise nil)))
(defun remaining-p (pattern &optional (repeats-key 'repeats) (remaining-key 'current-repeats-remaining))
"True if PATTERN's REMAINING-KEY slot value represents outputs \"remaining\" (see `value-remaining-p'). If PATTERN's REMAINING-KEY slot is unbound or 0, and REPEATS-KEY is not nil, then it is automatically set to the `next' of PATTERN's REPEATS-KEY slot. Then if that new value is 0 or nil, remaining-p returns nil. Otherwise, :reset is returned as a generalized true value and to indicate that `next' was called on PATTERN's REPEATS-KEY slot.
See also: `value-remaining-p', `decf-remaining'"
(labels ((set-next ()
(setf (slot-value pattern remaining-key) (next (slot-value pattern repeats-key)))
(when (value-remaining-p (slot-value pattern remaining-key))
:reset)))
(if (not (slot-boundp pattern remaining-key))
(set-next)
(let ((rem-key (slot-value pattern remaining-key)))
(typecase rem-key
(null nil)
(symbol (eql rem-key :inf))
(number (if (plusp rem-key)
t
if it 's already set to 0 , it was decf'd to 0 in the pattern , so we get the next one . if the next is 0 , THEN we return nil .
(otherwise nil))))))
(defun decf-remaining (pattern &optional (key 'current-repeats-remaining))
"Decrease PATTERN's KEY value.
See also: `remaining-p'"
(when (numberp (slot-value pattern key))
(decf (slot-value pattern key))))
(defmethod peek ((pstream pstream))
(with-slots (number future-number) pstream
(pstream-elt-future pstream (- number future-number))))
(defmethod peek ((pattern pattern))
(next (as-pstream pattern)))
(defmethod next ((pstream pstream))
nil)
(defmethod next :around ((pstream pstream))
(labels ((get-value-from-stack (pattern)
(with-slots (number pattern-stack) pattern
(if pattern-stack
(let* ((popped (pop pattern-stack))
(nv (next popped)))
(if (eop-p nv)
(get-value-from-stack pattern)
(progn
(push popped pattern-stack)
nv)))
(prog1
(let ((res (call-next-method)))
(typecase res
(pattern
(if (typep pattern '(or function t-pstream))
res
(let ((pstr (as-pstream res)))
(setf (slot-value pstr 'start-beat) (beat pattern))
(push pstr pattern-stack))
(get-value-from-stack pattern))))
(t res)))
(incf number))))))
(with-slots (number history history-number future-number) pstream
(let ((result (if (plusp future-number)
(let ((result (elt history (- number future-number))))
(decf future-number)
(when (event-p result)
(incf (slot-value pstream 'beat) (event-value result :delta)))
result)
(let ((result (restart-case
(get-value-from-stack pstream)
(yield-output (&optional (value 1))
:report (lambda (s) (format s "Yield an alternate output for ~S." pstream))
:interactive (lambda ()
(format *query-io* "~&Enter a form to yield: ")
(finish-output *query-io*)
(list (eval (read *query-io*))))
value))))
(when (event-p result)
(setf result (copy-event result))
(when (and (null (raw-event-value result :beat))
(null (slot-value pstream 'parent)))
(setf (beat result) (slot-value pstream 'future-beat)))
(incf (slot-value pstream 'beat) (event-value result :delta))
(incf (slot-value pstream 'future-beat) (event-value result :delta)))
(setf (elt history (mod history-number (length (slot-value pstream 'history)))) result)
(incf history-number)
result))))
(unless (pattern-parent pstream)
(dolist (proc *post-pattern-output-processors*)
(setf result (funcall proc result pstream))))
result))))
(defvar *post-pattern-output-processors* (list 'remap-instrument-to-parameters)
"List of functions that are applied as the last step of pattern output generation. Each output yielded by an \"outermost\" pattern (i.e. one without a `pattern-parent') will be processed (along with the pstream as a second argument) through each function in this list, allowing for arbitrary transformations of the generated outputs. The return value of each function is used as the input to the next function, and the return value of the last function is used as the output yielded by the pattern.
in fact this feature is already implemented more conveniently with the setf - able ` instrument - mapping ' function .
See also: `*instrument-map*', `remap-instrument-to-parameters'")
(defvar *instrument-map* (make-hash-table :test #'equal)
"Hash table mapping instrument names (as symbols) to arbitrary parameter lists. Used by `remap-instrument-to-parameters' as part of post-pattern output processing. Any events whose :instrument is not found in this table will not be affected.
See also: `remap-instrument-to-parameters'")
(defun remap-instrument-to-parameters (output &optional pstream)
"Remap OUTPUT's instrument key to arbitrary parameters specified in `*instrument-map*'. If OUTPUT is not an event or the instrument is not found in the map, it is passed through unchanged.
See also: `instrument-mapping', `*instrument-map*', `*post-pattern-output-processors*'"
(declare (ignore pstream))
(unless (event-p output)
(return-from remap-instrument-to-parameters output))
(when-let ((mapping (gethash (event-value output :instrument) *instrument-map*)))
(etypecase mapping
(symbol
(setf (event-value output :instrument) mapping))
(list
(doplist (key value mapping)
(setf (event-value output key) value)))))
output)
(defun instrument-mapping (instrument)
"Get a mapping from INSTRUMENT (an instrument name as a string or symbol) to a plist of parameters which should be set in the event by `remap-instrument-to-parameters'.
See also: `remap-instrument-to-parameters', `*instrument-map*'"
(gethash instrument *instrument-map*))
(defun (setf instrument-mapping) (value instrument)
"Set a mapping from INSTRUMENT (an instrument name as a string or symbol) to a plist of parameters which will be set in the event by `remap-instrument-to-parameters'. Setting an instrument to nil with this function removes it from the map.
See also: `instrument-mapping', `remap-instrument-to-parameters', `*instrument-map*'"
(assert (or (typep value '(or symbol number))
(and (listp value)
(evenp (list-length value))))
(value)
"~S's VALUE argument must be a symbol, a number, or a plist; got ~S instead" 'instrument-mapping value)
(if value
(setf (gethash instrument *instrument-map*) value)
(remhash instrument *instrument-map*)))
(defgeneric as-pstream (thing)
(:documentation "Return THING as a pstream object.
See also: `pattern-as-pstream'"))
(defun pattern-as-pstream (thing)
"Like `as-pstream', but only converts THING to a pstream if it is a pattern."
(if (typep thing 'pattern)
(as-pstream thing)
thing))
(defgeneric t-pstream-value (object)
(:documentation "The value that is yielded by the t-pstream."))
(defgeneric t-pstream-length (object)
(:documentation "The number of times to yield the value."))
(defclass t-pstream (pstream)
((value :initarg :value :initform nil :accessor t-pstream-value :documentation "The value that is yielded by the t-pstream.")
(length :initarg :length :initform 1 :accessor t-pstream-length :documentation "The number of times to yield the value."))
(:documentation "Pattern stream object that by default yields its value only once."))
(defun t-pstream (value &optional (length 1))
"Make a t-pstream object with the value VALUE."
(check-type length (or (integer 0) (eql :inf)))
(make-instance 't-pstream
:value value
:length length))
(defmethod print-object ((t-pstream t-pstream) stream)
(with-slots (value length) t-pstream
(print-unreadable-object (t-pstream stream :type t)
(format stream "~S ~S" value length))))
(defun t-pstream-p (object)
"True if OBJECT is a `t-pstream'.
See also: `t-pstream', `as-pstream'"
(typep object 't-pstream))
(defmethod as-pstream ((value t))
(t-pstream value))
(defmethod next ((t-pstream t-pstream))
(with-slots (value length number) t-pstream
(when (and (not (eql :inf length))
(>= number length))
(return-from next eop))
(if (functionp value)
(funcall value)
value)))
(defmethod as-pstream ((pattern pattern))
(let* ((class (class-of pattern))
(name (class-name class))
(slots (remove 'parent (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots class)))))
(apply #'make-instance
(pattern-pstream-class-name name)
(mapcan (fn (when (slot-boundp pattern _)
(let ((kw (make-keyword _)))
(list kw (funcall (if (member kw (list :length :repeats))
#'as-pstream
#'pattern-as-pstream)
(slot-value pattern _))))))
slots))))
(defmethod as-pstream :around ((object t))
(let ((pstream (call-next-method)))
(with-slots (pstream-count source history) pstream
(setf pstream-count (if (slot-exists-p object 'pstream-count)
(slot-value object 'pstream-count)
0)
source object))
(when (slot-exists-p object 'pstream-count)
(incf (slot-value object 'pstream-count)))
pstream))
pstream)
(define-condition pstream-out-of-range ()
((index :initarg :index :reader pstream-elt-index))
(:report (lambda (condition stream)
(format stream "The index ~D falls outside the scope of the pstream's history." (pstream-elt-index condition)))))
(defun pstream-elt-index-to-history-index (pstream index)
"Given INDEX, an absolute index into PSTREAM's history, return the actual index into the current recorded history of the pstream.
See also: `pstream-history-advance-by'"
(check-type index (integer 0))
(with-slots (history) pstream
(mod index (length history))))
(defun pstream-elt (pstream n)
"Get the Nth item in PSTREAM's history. For negative N, get the -Nth most recent item.
Example:
See also: `pstream-elt-future', `phistory'"
(check-type n integer)
(unless (pstream-p pstream)
(return-from pstream-elt (pstream-elt (as-pstream pstream) n)))
(with-slots (history history-number) pstream
(let ((real-index (if (minusp n)
(+ history-number n)
n)))
(if (and (>= real-index (max 0 (- history-number (length history))))
(< real-index history-number))
(elt history (pstream-elt-index-to-history-index pstream real-index))
(error 'pstream-out-of-range :index n)))))
"Convert a history index (i.e. a positive number provided to `pstream-elt-future') to the amount that the history must be advanced by.
If the provided index is before the earliest item in history, the result will be a negative number denoting how far beyond the earliest history the index is.
If the provided index is within the current history, the result will be zero.
If the provided index is in the future, the result will be a positive number denoting how far in the future it is.
See also: `pstream-elt-index-to-history-index'"
(check-type index (integer 0))
(with-slots (history history-number) pstream
(let ((history-length (length history)))
(if (< index (- history-number history-length))
(- history-number history-length)
(if (>= index history-number)
(- index (1- history-number))
0)))))
(defun pstream-elt-future (pstream n)
"Get the element N away from the most recent in PSTREAM's history. Unlike `pstream-elt', this function will automatically peek into the future for any positive N.
Example:
See also: `pstream-elt', `phistory'"
(check-type n integer)
(unless (pstream-p pstream)
(return-from pstream-elt-future (pstream-elt-future (as-pstream pstream) n)))
(when (minusp n)
(return-from pstream-elt-future (pstream-elt pstream n)))
(with-slots (history history-number future-number) pstream
(let ((advance-by (pstream-history-advance-by pstream n)))
(when (or (minusp advance-by)
(> (+ future-number advance-by) (length history)))
(error 'pstream-out-of-range :index n))
(let ((prev-future-number future-number))
(loop :repeat advance-by
:for next := (next pstream)
:if (event-p next)
:do (decf (slot-value pstream 'beat) (event-value next :delta)))
(setf future-number (+ prev-future-number advance-by))))
(let ((real-index (pstream-elt-index-to-history-index pstream n)))
(elt history real-index))))
(defvar *pbind-special-init-keys* (list)
"The list of special keys for pbind that alters it during its initialization.
See also: `define-pbind-special-init-key'")
(defvar *pbind-special-wrap-keys* (list)
"The list of special keys for pbind that causes the pbind to be replaced by another pattern during its initialization.
See also: `define-pbind-special-wrap-key'")
(defvar *pbind-special-process-keys* (list)
"The list of special keys for pbind that alter the outputs of the pbind.
See also: `define-pbind-special-process-key'")
(defclass pbind (pattern)
((pairs :initarg :pairs :initform (list) :accessor pbind-pairs :documentation "The pattern pairs of the pbind; a plist mapping its keys to their values."))
(:documentation "Please refer to the `pbind' documentation."))
(defun pbind (&rest pairs)
"pbind yields events determined by its PAIRS, which are a list of keys and values. Each key corresponds to a key in the resulting events, and each value is treated as a pattern that is evaluated for each step of the pattern to generate the value for its key.
Example:
( next - n ( pbind : foo ( pseq ' ( 1 2 3 ) ) : bar : hello ) 4 )
See also: `pmono', `pb'"
(assert (evenp (length pairs)) (pairs) "~S's PAIRS argument must be a list of key/value pairs." 'pbind)
(when (> (count :pdef (keys pairs)) 1)
(warn "More than one :pdef key detected in pbind."))
(let* ((res-pairs (list))
(pattern-chain (list))
(pattern (make-instance 'pbind)))
(doplist (key value pairs)
(when (pattern-p value)
(setf (slot-value value 'parent) pattern))
(cond ((position key *pbind-special-init-keys*)
(when-let ((result (funcall (getf *pbind-special-init-keys* key) value pattern)))
(appendf res-pairs result)))
((position key *pbind-special-wrap-keys*)
(unless (null res-pairs)
(setf (slot-value pattern 'pairs) res-pairs)
(setf res-pairs (list)))
(unless (null pattern-chain)
(setf pattern (apply #'pchain (append pattern-chain (list pattern))))
(setf pattern-chain (list)))
(setf pattern (funcall (getf *pbind-special-wrap-keys* key) value pattern)))
(t
(unless (typep pattern 'pbind)
(appendf pattern-chain (list pattern))
(setf pattern (make-instance 'pbind)))
(appendf res-pairs (list key (if (and (eql key :embed)
(typep value 'symbol))
(pdef value)
value))))))
(unless (null res-pairs)
(setf (slot-value pattern 'pairs) res-pairs))
(appendf pattern-chain (list pattern))
(unless (length= 1 pattern-chain)
(setf pattern (apply #'pchain pattern-chain)))
(doplist (k v pairs)
(when (member k (list :quant :play-quant :end-quant))
(funcall (fdefinition (list 'setf (ensure-symbol k 'cl-patterns))) (next v) pattern)))
process : pdef key .
(when-let ((pdef-name (getf pairs :pdef)))
(pdef pdef-name pattern))
pattern))
(pushnew 'pbind *patterns*)
(setf (documentation 'pbind 'type) (documentation 'pbind 'function))
(defmethod print-object ((pbind pbind) stream)
(format stream "(~S~{ ~S ~S~})" 'pbind (slot-value pbind 'pairs)))
(defmethod %pattern-children ((pbind pbind))
(mapcan (lambda (slot)
(let ((slot-name (closer-mop:slot-definition-name slot)))
(copy-list (ensure-list
(if (eql slot-name 'pairs)
(loop :for (k v) :on (slot-value pbind slot-name) :by #'cddr :collect v)
(slot-value pbind slot-name))))))
(closer-mop:class-direct-slots (find-class 'pbind))))
(defmethod keys ((pbind pbind))
(keys (slot-value pbind 'pairs)))
(defvar *pattern-function-translations* (list)
"The list of names of functions and the forms they will be translated to in `pb' and other pattern macros.
See also: `define-pattern-function-translation'")
(defmacro define-pattern-function-translation (function pattern)
"Define a translation from FUNCTION to PATTERN in `pb'."
`(setf (getf *pattern-function-translations* ',function) ',pattern))
(define-pattern-function-translation + p+)
(define-pattern-function-translation - p-)
(define-pattern-function-translation * p*)
(define-pattern-function-translation / p/)
(define-pattern-function-translation round (pnary 'round))
(defun pattern-translate-sexp (sexp)
"Translate SEXP to the equivalent pattern as per `*pattern-function-translations*', or pass it through unchanged if there is no translation.
See also: `pb-translate-body-functions'"
(typecase sexp
(null sexp)
(atom sexp)
(list (let* ((first (car sexp))
(rest (cdr sexp))
(translated-p (getf *pattern-function-translations* first))
(head (list (if (find-if (fn (typep _ '(or pattern list))) rest)
(or translated-p first)
first))))
`(,@head ,@(if translated-p
(mapcar #'pattern-translate-sexp rest)
rest))))))
(defun pb-translate-body-functions (body)
"Translate functions in BODY to their equivalent pattern as per `*pattern-function-translations*'.
See also: `pattern-translate-sexp'"
(loop :for (k v) :on body :by #'cddr
:collect k
:collect (pattern-translate-sexp v)))
FIX : allow keys to be lists , in which case results are destructured , i.e. ( pb : blah ( list : foo : bar ) ( pcycles ( a 1!4 ) ) ) results in four ( EVENT : FOO 1 : DUR 1/4 )
(defmacro pb (name &body pairs)
"pb is a convenience macro, wrapping the functionality of `pbind' and `pdef' while also providing additional syntax sugar. NAME is the name of the pattern (same as pbind's :pdef key or `pdef' itself), and PAIRS is the same as in regular pbind. If PAIRS is only one element, pb operates like `pdef', otherwise it operates like `pbind'.
( pb : foo : bar ( + ( pseries ) ( pseq ( list -1 0 1 ) ) ) )
...is the same as:
( pb : foo : bar ( p+ ( pseries ) ( pseq ( list -1 0 1 ) ) ) )
See also: `pbind', `pdef'"
(if (length= 1 pairs)
`(pdef ,name ,@pairs)
`(pdef ,name (pbind ,@(pb-translate-body-functions pairs)))))
(pushnew 'pb *patterns*)
(defclass pbind-pstream (pbind pstream)
()
(:documentation "pstream for `pbind'"))
(defmethod print-object ((pbind pbind-pstream) stream)
(print-unreadable-object (pbind stream :type t)
(format stream "~{~S ~S~^ ~}" (slot-value pbind 'pairs))))
(defmethod as-pstream ((pbind pbind))
(let ((name (class-name (class-of pbind)))
(slots (mapcar #'closer-mop:slot-definition-name (closer-mop:class-slots (class-of pbind)))))
(apply #'make-instance
(pattern-pstream-class-name name)
(loop :for slot :in slots
:for slot-kw := (make-keyword slot)
:for bound := (slot-boundp pbind slot)
:if bound
:collect slot-kw
:if (eql :pairs slot-kw)
:collect (mapcar 'pattern-as-pstream (slot-value pbind 'pairs))
:if (and bound (not (eql :pairs slot-kw)))
:collect (slot-value pbind slot)))))
(defmacro define-pbind-special-init-key (key &body body)
"Define a special key for pbind that alters the pbind during its initialization, either by embedding a plist into its pattern-pairs or in another way. These functions are called once, when the pbind is created, and must return a plist if the key should embed values into the pbind pairs, or NIL if it should not."
`(setf (getf *pbind-special-init-keys* ,(make-keyword key))
(lambda (value pattern)
(declare (ignorable value pattern))
,@body)))
(define-pbind-special-init-key loop-p
(setf (loop-p pattern) value)
nil)
(defmacro define-pbind-special-wrap-key (key &body body)
"Define a special key for pbind that replaces the pbind with another pattern during the pbind's initialization. Each encapsulation key is run once on the pbind after it has been initialized, altering the type of pattern returned if the return value of the function is non-NIL."
`(setf (getf *pbind-special-wrap-keys* ,(make-keyword key))
(lambda (value pattern)
(declare (ignorable value pattern))
,@body)))
(define-pbind-special-wrap-key parp
(parp pattern value))
(define-pbind-special-wrap-key pfin
(pfin pattern value))
(define-pbind-special-wrap-key pfindur
(pfindur pattern value))
(define-pbind-special-wrap-key psync
(destructuring-bind (quant &optional maxdur) (ensure-list value)
(psync pattern quant (or maxdur quant))))
(define-pbind-special-wrap-key pdurstutter
(pdurstutter pattern value))
(define-pbind-special-wrap-key pr
(pr pattern value))
(define-pbind-special-wrap-key pn
(pn pattern value))
(define-pbind-special-wrap-key ptrace
(if value
(if (eql t value)
(ptrace pattern)
(pchain pattern
(pbind :- (ptrace value))))
pattern))
(define-pbind-special-wrap-key pmeta
(if (eql t value)
(pmeta pattern)
pattern))
(pchain pattern value))
(define-pbind-special-wrap-key pparchain
(pparchain pattern value))
(defmacro define-pbind-special-process-key (key &body body)
"Define a special key for pbind that alters the pattern in a nonstandard way. These functions are called for each event created by the pbind and must return an event if the key should embed values into the event stream, or `eop' if the pstream should end."
`(setf (getf *pbind-special-process-keys* ,(make-keyword key))
(lambda (value)
,@body)))
(define-pbind-special-process-key embed
value)
(defmethod next ((pbind pbind-pstream))
(labels ((accumulator (pairs)
(let ((key (car pairs))
(val (cadr pairs)))
(when (and (pstream-p val)
(null (slot-value val 'start-beat)))
(setf (slot-value val 'start-beat) (beat pbind)))
(let ((next-val (next val)))
(when (eop-p next-val)
(return-from accumulator eop))
(if (position key (keys *pbind-special-process-keys*))
(setf *event* (combine-events *event*
(funcall (getf *pbind-special-process-keys* key) next-val)))
(setf (event-value *event* key) next-val))
(if-let ((cddr (cddr pairs)))
(accumulator cddr)
*event*)))))
(let ((*event* (make-default-event)))
(when (eop-p *event*)
(return-from next eop))
(setf (slot-value *event* '%beat) (+ (or (slot-value pbind 'start-beat) 0) (beat pbind)))
(if-let ((pairs (slot-value pbind 'pairs)))
(accumulator pairs)
*event*))))
(defmethod as-pstream ((pbind pbind-pstream))
pbind)
(defclass prest ()
((value :initarg :value :initform 1))
(:documentation "An object representing a rest. When set as a value in an event, the event's :type becomes :rest and the prest's value slot is used as the actual value for the event key instead."))
(defun prest (&optional (value 1))
"Make a prest object, which, when used in a `pbind' or similar event pattern, turns the current event into a rest and yields VALUE for the key's value.
Example:
( next - upto - n ( : degree ( pseq ( list 0 1 ( prest 2 ) 3 ) 1 ) ) )
See also: `pbind', `pbind''s :type key"
(make-instance 'prest :value value))
(defmethod print-object ((prest prest) stream)
(format stream "(~S ~S)" 'prest (slot-value prest 'value)))
(defmethod rest-p ((prest prest))
t)
(defun pmono (instrument &rest pairs)
"pmono defines a mono instrument event pstream. It's effectively the same as `pbind' with its :type key set to :mono.
See also: `pbind'"
(assert (evenp (length pairs)) (pairs) "~S's PAIRS argument must be a list of key/value pairs." 'pmono)
(apply #'pbind
:instrument instrument
:type :mono
pairs))
(pushnew 'pmono *patterns*)
(defpattern pseq (pattern)
(list
(repeats :initform :inf)
(offset :initform 0)
(current-repeats-remaining :state t))
:documentation "Sequentially yield items from LIST, repeating the whole list REPEATS times. OFFSET is the offset to index into the list.
Example:
( next - n ( pseq ' ( 5 6 7 ) 2 ) 7 )
( next - upto - n ( pseq ' ( 5 6 7 ) 2 1 ) )
See also: `pser', `eseq'")
(defmethod next ((pseq pseq-pstream))
(with-slots (number list offset) pseq
(let ((list (next list)))
(when (and (plusp number)
(zerop (mod number (length list))))
(decf-remaining pseq))
(let ((off (next offset)))
(if (and (not (eop-p off))
(remaining-p pseq)
list)
(elt-wrap list (+ off number))
eop)))))
(defpattern pser (pattern)
(list
(length :initform :inf)
(offset :initform 0)
(current-repeats-remaining :state t)
(current-index :state t))
:documentation "Sequentially yield values from LIST, yielding a total of LENGTH values.
Example:
( next - n ( pser ' ( 5 6 7 ) 2 ) 3 )
See also: `pseq'")
(defmethod next ((pser pser-pstream))
(with-slots (list offset current-index) pser
(let ((remaining (remaining-p pser 'length))
(list (next list))
(off (next offset)))
(when (or (not remaining)
(eop-p off))
(return-from next eop))
(decf-remaining pser)
(when (eql :reset remaining)
(setf current-index 0))
(prog1
(elt-wrap list (+ off current-index))
(incf current-index)))))
(defpattern pk (pattern)
(key
(default :initform 1))
:documentation "Yield the value of KEY in the current `*event*' context, returning DEFAULT if that value is nil.
Example:
( next - upto - n ( pbind : foo ( pseq ' ( 1 2 3 ) 1 ) : bar ( pk : foo ) ) )
See also: `pbind', `event-value', `*event*'")
(defmethod as-pstream ((pk pk))
(with-slots (key default) pk
(make-instance 'pk-pstream
:key key
:default default)))
(defmethod next ((pk pk-pstream))
(with-slots (key default) pk
(or (event-value *event* key)
(if (string= :number key)
(slot-value pk 'number)
default))))
(defpattern prand (pattern)
(list
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Yield random values from LIST.
Example:
( next - n ( prand ' ( 1 2 3 ) 5 ) 6 )
See also: `pxrand', `pwrand', `pwxrand'")
(defmethod next ((prand prand-pstream))
(unless (remaining-p prand 'length)
(return-from next eop))
(decf-remaining prand)
(random-elt (next (slot-value prand 'list))))
(defpattern pxrand (pattern)
(list
(length :initform :inf)
(last-result :state t)
(current-repeats-remaining :state t))
:documentation "Yield random values from LIST, never repeating equal values twice in a row.
Example:
( next - upto - n ( pxrand ' ( 1 2 3 ) 4 ) )
See also: `prand', `pwrand', `pwxrand'")
(defmethod initialize-instance :after ((pxrand pxrand) &key)
(with-slots (list) pxrand
(assert (or (not (listp list))
(position-if-not (lambda (i) (eql i (car list))) list))
(list)
"~S's input list must have at least two non-eql elements." 'pxrand)))
(defmethod next ((pxrand pxrand-pstream))
(with-slots (list last-result) pxrand
(unless (remaining-p pxrand 'length)
(return-from next eop))
(decf-remaining pxrand)
(let ((clist (next list)))
(setf last-result (loop :for res := (random-elt clist)
:if (or (not (slot-boundp pxrand 'last-result))
(not (eql res last-result)))
:return res)))))
(defpattern pwrand (pattern)
(list
(weights :initform :equal)
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Yield random elements from LIST weighted by respective values from WEIGHTS.
Example:
( next - upto - n ( pwrand ' ( 1 2 3 ) ' ( 7 5 3 ) 10 ) )
See also: `prand', `pxrand', `pwxrand'")
(defmethod next ((pwrand pwrand-pstream))
(with-slots (list weights) pwrand
(unless (remaining-p pwrand 'length)
(return-from next eop))
(decf-remaining pwrand)
(let* ((clist (next list))
(cweights (cumulative-list (if (eql weights :equal)
(let ((len (length clist)))
(make-list len :initial-element (/ 1 len)))
(normalized-sum (mapcar #'next (next weights))))))
(num (random 1.0)))
(nth (index-of-greater-than num cweights) clist))))
(defpattern pwxrand (pattern)
(list
(weights :initform :equal)
(length :initform :inf)
(last-result :state t)
(current-repeats-remaining :state t))
:documentation "Yield random elements from LIST weighted by respective values from WEIGHTS, never repeating equivalent values twice in a row. This is effectively `pxrand' and `pwrand' combined.
Example:
( next - upto - n ( pwxrand ' ( 1 2 3 ) ' ( 7 5 3 ) 10 ) )
See also: `prand', `pxrand', `pwrand'")
(defmethod initialize-instance :after ((pwxrand pwxrand) &key)
(with-slots (list weights) pwxrand
(assert (or (not (listp list))
(and (position-if-not (fn (eql _ (car list))) list)
(or (not (listp weights))
(find-if-not 'numberp weights)
(let ((effective-list (loop :for index :from 0
:for elem :in list
:for weight := (elt-wrap weights index)
:if (plusp weight)
:collect elem)))
(position-if-not (fn (eql _ (car effective-list))) effective-list)))))
(list)
"~S's input list must have at least two non-eql accessible elements." 'pwxrand)))
(defmethod next ((pwxrand pwxrand-pstream))
(with-slots (list weights last-result) pwxrand
(unless (remaining-p pwxrand 'length)
(return-from next eop))
(decf-remaining pwxrand)
(let* ((clist (next list))
(clist-length (length clist))
(cweights (next weights))
(cweights (cumulative-list (if (eql cweights :equal)
(make-list clist-length :initial-element (/ 1 clist-length))
(normalized-sum (mapcar #'next cweights))))))
(setf last-result (loop :for res := (nth-wrap (index-of-greater-than (random 1.0) cweights) clist)
:if (or (not (slot-boundp pwxrand 'last-result))
(not (eql res last-result)))
:return res)))))
(defpattern pfunc (pattern)
((func :type (or function-designator pattern))
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Yield the result of evaluating FUNC. Note that the current event of the parent pattern is still accessible via the `*event*' special variable.
Example:
( next - upto - n ( pfunc ( lambda ( ) ( random 10 ) ) 4 ) )
( next - upto - n ( pbind : foo ( pwhite 0 10 4 )
( if ( > ( event - value * event * : foo ) 5 ) : greater : lesser ) ) ) ) )
( EVENT : FOO 7 : BAR : GREATER ) ( EVENT : FOO 8 : BAR : GREATER ) )
See also: `pf', `pnary', `plazy', `pif'")
(defmethod initialize-instance :after ((pfunc pfunc) &key)
(check-type (slot-value pfunc 'func) (or function-designator pattern)))
(defmethod as-pstream ((pfunc pfunc))
(with-slots (func length) pfunc
(make-instance 'pfunc-pstream
:func (pattern-as-pstream func)
:length (as-pstream length))))
(defmethod next ((pfunc pfunc-pstream))
(unless (remaining-p pfunc 'length)
(return-from next eop))
(decf-remaining pfunc)
(with-slots (func) pfunc
(etypecase func
(function-designator (funcall func))
(pstream (let ((nxt (next func)))
(if (eop-p nxt)
eop
(funcall nxt)))))))
(defmacro pf (&body body)
"Convenience macro for `pfunc' that automatically wraps BODY in a lambda."
`(pfunc (lambda () ,@body)))
(pushnew 'pf *patterns*)
(defpattern pr (pattern)
(pattern
(repeats :initform :inf)
(current-value :state t :initform nil)
(current-repeats-remaining :state t))
:documentation "Repeat each value from PATTERN REPEATS times. If REPEATS is 0, the value is skipped.
Example:
( next - upto - n ( pr ( pseries ) ( pseq ' ( 1 3 0 2 ) 1 ) ) )
See also: `pdurstutter', `pn', `pdrop', `parp'")
(defmethod as-pstream ((pr pr))
(with-slots (pattern repeats) pr
(make-instance 'pr-pstream
:pattern (as-pstream pattern)
:repeats (pattern-as-pstream repeats))))
(defmethod next ((pr pr-pstream))
(with-slots (pattern repeats current-value current-repeats-remaining) pr
(while (or (not (slot-boundp pr 'current-repeats-remaining))
(and current-repeats-remaining
current-value
(not (value-remaining-p current-repeats-remaining))))
(setf current-value (next pattern))
(when (or (eop-p current-value)
(and (slot-boundp pr 'current-repeats-remaining)
(eop-p current-repeats-remaining)))
(return-from next eop))
(setf current-repeats-remaining
(let ((*event* (if (event-p current-value)
(if *event*
(combine-events *event* current-value)
current-value)
*event*)))
(if (typep repeats 'function)
(let ((arglist (function-arglist repeats)))
(if (null arglist)
(funcall repeats)
(funcall repeats current-value)))
(next repeats)))))
(when (value-remaining-p current-repeats-remaining)
(decf-remaining pr)
current-value)))
(defpattern plazy (pattern)
(func
(repeats :initform :inf)
(current-pstream :state t :initform nil)
(current-repeats-remaining :state t :initform nil))
:documentation "Evaluates FUNC to generate a pattern, which is then yielded from until its end, at which point FUNC is evaluated again to generate the next pattern. The pattern is generated a total of REPEATS times.
Example:
( next - n ( plazy ( lambda ( ) ( if (= 0 ( random 2 ) ) ( pseq ' ( 1 2 3 ) 1 ) ( pseq ' ( 9 8 7 ) 1 ) ) ) ) 6 )
See also: `pfunc'")
(defmethod as-pstream ((plazy plazy))
(with-slots (func repeats) plazy
(make-instance 'plazy-pstream
:func func
:repeats (as-pstream repeats))))
(defmethod next ((plazy plazy-pstream))
(with-slots (func repeats current-pstream current-repeats-remaining) plazy
(labels ((set-current-pstream ()
(unless (remaining-p plazy)
(return-from next eop))
(setf current-pstream (as-pstream (funcall func)))
(decf-remaining plazy)))
(unless current-repeats-remaining
(setf current-repeats-remaining (next repeats)))
(unless current-pstream
(set-current-pstream))
(let ((nv (next current-pstream)))
(if (eop-p nv)
(progn
(set-current-pstream)
(next current-pstream))
nv)))))
(defpattern protate (pattern)
(pattern
(shift :initform 0))
:documentation "Rotate PATTERN N outputs forward or backward, wrapping the shifted items to the other side, a la `alexandria:rotate'.
Example:
( next - upto - n ( protate ( pseq ' ( 1 2 3 4 5 ) 1 ) 2 ) )
See also: `pdrop', `phistory', `pscratch'")
(defmethod as-pstream ((protate protate))
(with-slots (pattern shift) protate
(make-instance 'protate-pstream
:pattern (pattern-as-pstream pattern)
:shift (pattern-as-pstream shift))))
(defmethod next ((protate protate-pstream))
(with-slots (pattern shift number) protate
(when (zerop number)
(next-upto-n pattern))
(let ((actual-index (- number (next shift)))
(hn (slot-value pattern 'history-number)))
(if (>= number (1- hn))
eop
(pstream-elt pattern (mod actual-index (1- hn)))))))
(defpattern pn (pattern)
(pattern
(repeats :initform :inf)
(current-repeats-remaining :state t)
(current-pstream :state t :initform nil))
:documentation "Embed the full PATTERN into the pstream REPEATS times.
Example:
( next - upto - n ( pn ( pwhite 0 5 1 ) 5 ) )
See also: `pr'")
(with-slots (pattern repeats) pn
(make-instance 'pn-pstream
:pattern pattern
:repeats (as-pstream repeats))))
(defmethod next ((pn pn-pstream))
(with-slots (pattern current-pstream) pn
(let ((rem (remaining-p pn)))
(when (eql :reset rem)
(setf current-pstream (as-pstream pattern)))
(let ((nv (next current-pstream)))
(while (and (eop-p nv) rem)
(decf-remaining pn)
(setf rem (remaining-p pn)
current-pstream (as-pstream pattern)
nv (next current-pstream)))
(if rem
nv
eop)))))
(defpattern pshuf (pattern)
(list
(repeats :initform :inf)
(shuffled-list :state t)
(current-repeats-remaining :state t))
:documentation "Shuffle LIST, then yield each item from the shuffled list, repeating it REPEATS times.
Example:
( next - upto - n ( pshuf ' ( 1 2 3 ) 2 ) )
See also: `prand'")
(defmethod as-pstream ((pshuf pshuf))
(with-slots (list repeats) pshuf
(let ((list (typecase list
(pattern (next-upto-n list))
(function (funcall list))
(list list))))
(make-instance 'pshuf-pstream
:list (next list)
:repeats (as-pstream repeats)))))
(defmethod next ((pshuf pshuf-pstream))
(with-slots (list number shuffled-list) pshuf
(when (and (zerop (mod number (length list)))
(plusp number))
(decf-remaining pshuf))
(let ((rem (remaining-p pshuf)))
(unless rem
(return-from next eop))
(when (eql :reset rem)
(nth (mod number (length shuffled-list))
shuffled-list))))
pwhite
(defpattern pwhite (pattern)
((lo :initform 0.0)
(hi :initform 1.0)
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Linearly-distributed random numbers between LO and HI, inclusive.
Example:
( next - upto - n ( pwhite 0 10 16 ) )
See also: `pexprand', `pbrown', `pgauss', `prand'"
:defun (defun pwhite (&optional (lo 0.0 lo-provided-p) (hi 1.0 hi-provided-p) (length :inf))
if only one argument is provided , we use it as the " hi " value .
(make-instance 'pwhite
:lo (if hi-provided-p
lo
0.0)
:hi (if hi-provided-p
hi
(if lo-provided-p
lo
1.0))
:length length)))
(defmethod next ((pwhite pwhite-pstream))
(with-slots (lo hi) pwhite
(unless (remaining-p pwhite 'length)
(return-from next eop))
(decf-remaining pwhite)
(let ((nlo (next lo))
(nhi (next hi)))
(when (or (eop-p nlo)
(eop-p nhi))
(return-from next eop))
(random-range nlo nhi))))
pbrown
(defpattern pbrown (pattern)
((lo :initform 0.0)
(hi :initform 1.0)
(step :initform 0.125)
(length :initform :inf)
(current-repeats-remaining :state t)
(current-value :state t :initform nil))
each output randomly a maximum of STEP away from the previous . LO and HI define the lower and upper bounds of the range . STEP defaults to 1 if LO and HI are integers .
Example:
( next - upto - n ( pbrown 0 10 1 10 ) )
See also: `pwhite', `pexprand', `pgauss'"
if only one argument is provided , we use it as the " hi " value .
:defun (defun pbrown (&optional (lo 0.0 lo-provided-p) (hi 1.0 hi-provided-p) (step 0.125 step-provided-p) (length :inf))
(let ((lo (if hi-provided-p
lo
(if (integerp lo) 0 0.0)))
(hi (if hi-provided-p
hi
(if lo-provided-p lo 1))))
(make-instance 'pbrown
:lo lo
:hi hi
:step (if step-provided-p
step
(if (and (integerp lo)
(integerp hi))
1
0.125))
:length length))))
(defmethod next ((pbrown pbrown-pstream))
(unless (remaining-p pbrown 'length)
(return-from next eop))
(decf-remaining pbrown)
(with-slots (lo hi step current-value) pbrown
(let ((nlo (next lo))
(nhi (next hi))
(nstep (next step)))
(when (member eop (list nlo nhi nstep))
(return-from next eop))
(unless current-value
(setf current-value (random-range (min nlo nhi)
(max nlo nhi))))
(incf current-value (random-range (* -1 nstep) nstep))
(setf current-value (clamp current-value nlo nhi)))))
(defpattern pexprand (pattern)
((lo :initform 0.0001)
(hi :initform 1.0)
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Exponentially-distributed random numbers between LO and HI. Note that LO and HI cannot be 0, and that LO and HI must have the same sign or else complex numbers will be output.
Example:
( next - upto - n ( pexprand 1.0 8.0 4 ) )
See also: `pwhite', `pbrown', `pgauss', `prand'")
(defmethod next ((pexprand pexprand-pstream))
(with-slots (lo hi) pexprand
(unless (remaining-p pexprand 'length)
(return-from next eop))
(decf-remaining pexprand)
(let ((nlo (next lo))
(nhi (next hi)))
(assert (and (numberp lo)
(not (zerop lo)))
(lo)
"Got a zero for ~S's ~S slot" 'pexprand 'lo)
(assert (and (numberp hi)
(not (zerop hi)))
(hi)
"Got a zero for ~S's ~S slot" 'pexprand 'hi)
(when (or (eop-p nlo)
(eop-p nhi))
(return-from next eop))
(exponential-random-range nlo nhi))))
(defpattern pgauss (pattern)
((mean :initform 0.0)
(deviation :initform 1.0)
(length :initform :inf)
(current-repeats-remaining :state t))
:documentation "Random numbers distributed along a normal (gaussian) curve. MEAN is the \"center\" of the distribution, DEVIATION is the standard deviation (i.e. the higher the value, the further the outputs are spread from MEAN).
Example:
( next - n ( pgauss ) 4 )
See also: `pwhite', `pexprand', `pbrown'")
(defmethod next ((pgauss pgauss-pstream))
(with-slots (mean deviation) pgauss
(unless (remaining-p pgauss 'length)
(return-from next eop))
(decf-remaining pgauss)
(let ((nmean (next mean))
(ndev (next deviation)))
(when (or (eop-p nmean)
(eop-p ndev))
(return-from next eop))
(random-gauss nmean ndev))))
pseries
(defpattern pseries (pattern)
((start :initform 0)
(step :initform 1)
(length :initform :inf)
(current-repeats-remaining :state t)
(current-value :state t))
:documentation "Yield START, then generate subsequent outputs by adding STEP, for a total of LENGTH outputs.
Example:
See also: `pseries*', `pgeom', `paccum'")
(defmethod next ((pseries pseries-pstream))
(with-slots (start step current-value) pseries
(unless (slot-boundp pseries 'current-value)
(setf current-value (next start)))
(unless (and (remaining-p pseries 'length)
current-value)
(return-from next eop))
(decf-remaining pseries)
(let ((nxt (next step)))
(prog1
current-value
(if (numberp nxt)
(setf current-value eop))))))
(defun pseries* (&optional (start 0) (end 1) length)
"Syntax sugar to generate a `pseries' whose values go from START to END linearly over LENGTH steps. If LENGTH is not provided, it is calculated such that the step will be 1. Note that LENGTH cannot be infinite since delta calculation requires dividing by it.
Based on the Pseries extension from the ddwPatterns SuperCollider library.
Example:
( pseries * 0 10 16 )
See also: `pseries', `pgeom', `pgeom*'"
(check-type length (or null (integer 2) pattern))
(let ((length (or length
(max 2 (round (1+ (abs (- end start))))))))
(pseries start (/ (- end start) (1- length)) length)))
(pushnew 'pseries* *patterns*)
(defpattern pgeom (pattern)
((start :initform 1)
(grow :initform 2)
(length :initform :inf)
(current-repeats-remaining :state t)
(current-value :state t))
:documentation "Yield START, then generate subsequent outputs by multiplying by GROW, for a total of LENGTH outputs.
Example:
See also: `pseries', `paccum'")
(defmethod next ((pgeom pgeom-pstream))
(with-slots (start grow current-value) pgeom
(unless (slot-boundp pgeom 'current-value)
(setf current-value (next start)))
(unless (remaining-p pgeom 'length)
(return-from next eop))
(decf-remaining pgeom)
(if (zerop (slot-value pgeom 'number))
current-value
(let ((n (next grow)))
(if (eop-p n)
eop
(setf current-value (* current-value n)))))))
(defun pgeom* (&optional (start 0.01) (end 1) (length 16))
"Syntax sugar to generate a `pgeom' whose values go from START to END exponentially over LENGTH steps. LENGTH cannot be infinite since delta calculation requires dividing by it.
Based on the Pgeom extension from the ddwPatterns SuperCollider library.
Example:
( pgeom * 1 100 8)
See also: `pgeom', `pseries', `pseries*'"
(check-type length (or (integer 2) pattern))
(pgeom start (expt (/ end start) (/ 1 (1- length))) length))
(pushnew 'pgeom* *patterns*)
(defpattern ptrace (pattern)
((trace :initform t)
(prefix :initform nil)
(stream :initform t))
:documentation "Print the PREFIX and each output of TRACE to STREAM. If TRACE is t, print `*event*'. If TRACE is a different symbol, print the value of that symbol in `*event*'. If TRACE is a pattern, ptrace yields its output unaffected. Otherwise, it yields t.
See also: `debug-backend', `debug-backend-recent-events'")
(defmethod as-pstream ((ptrace ptrace))
(with-slots (trace prefix stream) ptrace
(make-instance 'ptrace-pstream
:trace (pattern-as-pstream trace)
:prefix (pattern-as-pstream prefix)
:stream (pattern-as-pstream stream))))
(defmethod next ((ptrace ptrace-pstream))
(with-slots (trace prefix stream) ptrace
(let ((prefix (next prefix))
(stream (next stream)))
(if (eql trace t)
(progn
(format stream "~&~@[~A ~]~S~%" prefix *event*)
t)
(typecase trace
((or list symbol)
(progn
(format stream "~&~@[~A ~]~{~{~S: ~S~}~#[~:; ~]~}~%" prefix
(mapcar (lambda (symbol)
(list symbol (event-value *event* symbol)))
(ensure-list trace)))
t))
(pattern
(let ((res (next trace)))
(format stream "~&~@[~A ~]~S~%" prefix res)
res)))))))
(defpattern place (pattern)
(list
(repeats :initform :inf)
(current-repeat :state t :initform 0)
(current-repeats-remaining :state t))
the third time , the third element , and so on . REPEATS controls the number of times LIST is repeated .
Example:
( next - upto - n ( place ( list 1 2 ( list 3 4 5 ) ) 3 ) )
See also: `ppatlace'")
(defmethod next ((place place-pstream))
(with-slots (number list current-repeat) place
(when (and (not (= number 0))
(= 0 (mod number (length list))))
(incf current-repeat)
(decf-remaining place))
(unless (if (plusp number)
(and (not (ended-p place))
(remaining-p place))
(remaining-p place))
(return-from next eop))
(let* ((mod (mod number (length list)))
(result (next (nth mod list))))
(if (listp result)
(elt-wrap result current-repeat)
result))))
(defpattern ppatlace (pattern)
(list
(repeats :initform :inf)
(current-repeats-remaining :state t))
:documentation "Yield each value from LIST in sequence, or one output from each pattern in LIST per cycle of the list. If one of the patterns embedded in LIST ends sooner than the others, it is simply removed and the ppatlace continues to yield from the rest of the LIST. The entire LIST is yielded through a total of REPEATS times.
Example:
( next - upto - n ( ppatlace ( list ( pseq ( list 1 2 3 ) 1 )
( pseq ( list 4 5 6 ) 2 ) ) ) )
See also: `place'")
(defmethod as-pstream ((ppatlace ppatlace))
(with-slots (repeats list) ppatlace
(make-instance 'ppatlace-pstream
:list (mapcar #'pattern-as-pstream list)
:repeats (as-pstream repeats))))
(defmethod next ((ppatlace ppatlace-pstream))
(with-slots (number list) ppatlace
(when (and (not (zerop number))
(not (length= 0 list))
(zerop (mod number (length list))))
(decf-remaining ppatlace))
(when (or (not list)
(and (plusp number)
(ended-p ppatlace))
(not (remaining-p ppatlace)))
(return-from next eop))
(let ((result (next (elt-wrap list number))))
(unless (eop-p result)
(return-from next result))
(setf list (remove-if #'ended-p list))
(next ppatlace))))
(defpattern pnary (pattern)
(operator
(patterns :initarg :patterns))
:documentation "Yield the result of applying OPERATOR to each value yielded by each pattern in PATTERNS.
Example:
( next - upto - n ( pnary ( pseq ( list ' + ' - ' * ' / ) 2 ) 2 2 ) )
See also: `pfunc', `p+', `p-', `p*', `p/'"
:defun (defun pnary (operator &rest patterns)
(make-instance 'pnary
:operator operator
:patterns patterns)))
(defmethod as-pstream ((pnary pnary))
(with-slots (operator patterns) pnary
(make-instance 'pnary-pstream
:operator (pattern-as-pstream operator)
:patterns (mapcar #'pattern-as-pstream patterns))))
(defmethod next ((pnary pnary-pstream))
(with-slots (operator patterns) pnary
(let ((op (if (pstream-p operator)
(next operator)
operator))
(nexts (mapcar #'next patterns)))
(when (or (position eop nexts)
(eop-p op))
(return-from next eop))
(restart-case
(handler-bind
((type-error
(lambda (c)
(when-let ((restart (find-restart 'retry-with-prest-values c)))
(invoke-restart restart)))))
(apply #'multi-channel-funcall op nexts))
(retry-with-prest-values ()
:test (lambda (c)
(and (typep c 'type-error)
(eql 'number (type-error-expected-type c))
(typep (type-error-datum c) 'prest)))
(labels ((replace-prests (list)
(mapcar (lambda (item)
(typecase item
(list (replace-prests item))
(prest (slot-value item 'value))
(t item)))
list)))
(apply #'multi-channel-funcall op (replace-prests nexts))))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun make-pattern-for-function (function)
"Generate Lisp of a wrapper function named pFUNCTION whose definition is (pnary FUNCTION ...).
See also: `pnary'"
(let* ((pat-sym (intern (concat "P" (symbol-name function)) 'cl-patterns))
(argslist (function-arglist function))
(func-name (string-downcase function))
(full-func-name (if (eql (find-package 'cl-patterns) (symbol-package function))
func-name
(concat (string-downcase (package-name (symbol-package function))) ":" func-name)))
(parsed (multiple-value-list (parse-ordinary-lambda-list argslist)))
(has-rest (third parsed))
(args (append (first parsed) (mapcar #'car (second parsed)) (ensure-list (third parsed)))))
`(progn
(defun ,pat-sym ,argslist
,(concat "Syntax sugar for (pnary #'" func-name " ...).
See also: `pnary', `" full-func-name "'")
(,(if has-rest
'apply
'funcall)
#'pnary #',function ,@args))
(pushnew ',pat-sym *patterns*)))))
#.`(progn ,@(mapcar #'make-pattern-for-function '(+ - * / > >= < <= = /= eql wrap)))
(defpattern prerange (pattern)
(input
from-range
to-range)
:documentation "Remap INPUT from one range, specified by FROM-RANGE, to another range, specified by TO-RANGE.
See also: `rerange', `pnary'")
(defmethod as-pstream ((prerange prerange))
(with-slots (input from-range to-range) prerange
(make-instance 'prerange-pstream
:input (pattern-as-pstream input)
:from-range (pattern-as-pstream from-range)
:to-range (pattern-as-pstream to-range))))
(defmethod next ((prerange prerange-pstream))
(with-slots (input from-range to-range) prerange
(let ((input (next input))
(from-range (next from-range))
(to-range (next to-range)))
(when (member eop (list input from-range to-range))
(return-from next eop))
(rerange input from-range to-range))))
(defpattern pslide (pattern)
(list
(repeats :initform :inf)
(len :initform 3)
(step :initform 1)
(start :initform 0)
(wrap-at-end :initform t)
(current-repeats-remaining :state t)
(current-repeats :state t :initform nil)
(remaining-current-segment :state t :initform nil)
(current-value :state t :initform nil)
(current-list-length :state t :initform nil))
:documentation "\"Slide\" across sections of LIST. REPEATS is the total number of sections to output, LEN the length of the section. STEP is the number to increment the start index by after each section, and START is the initial index into LIST that the first section starts from. WRAP-AT-END, when true, means that an index outside of the list will wrap around. When false, indexes outside of the list result in nil.
Example:
( next - upto - n ( pslide ( list 0 1 2 3 4 5 6 ) 3 3 2 1 t ) )
See also: `pscratch'")
(defmethod as-pstream ((pslide pslide))
(with-slots (list repeats len step start wrap-at-end) pslide
(make-instance 'pslide-pstream
:list (next list)
:repeats (pattern-as-pstream repeats)
:len (pattern-as-pstream len)
:step (pattern-as-pstream step)
:start (pattern-as-pstream start)
:wrap-at-end (next wrap-at-end)
:current-repeats 0
:remaining-current-segment len)))
(defmethod next ((pslide pslide-pstream))
(with-slots (list repeats len step start wrap-at-end current-repeats-remaining current-repeats remaining-current-segment current-value current-list-length) pslide
(unless current-value
(setf current-value (next start)))
(unless current-list-length
(setf current-list-length (length list)))
(labels ((get-next ()
(if (and (not wrap-at-end)
(or (minusp current-value)
(>= current-value current-list-length)))
eop
(elt-wrap list current-value))))
(unless (slot-boundp pslide 'current-repeats-remaining)
(setf current-repeats-remaining (next repeats)))
(unless (value-remaining-p current-repeats-remaining)
(return-from next eop))
(if (value-remaining-p remaining-current-segment)
(prog1
(get-next)
(decf-remaining pslide 'remaining-current-segment)
(incf current-value))
(progn
(decf-remaining pslide)
(setf remaining-current-segment (next len))
(incf current-repeats)
(setf current-value (+ (next start) (* (next step) current-repeats)))
(next pslide))))))
(defpattern phistory (pattern)
(pattern
step-pattern)
:documentation "Refer back to PATTERN's history, yielding the output at the index provided by STEP-PATTERN.
Note that PATTERN is still advanced once per event, and if STEP-PATTERN yields a number pointing to an event in PATTERN that hasn't been yielded yet (i.e. if PATTERN has only advanced once but STEP-PATTERN yields 3 for its output), phistory yields nil.
Example:
( next - n ( phistory ( pseries ) ( pseq ' ( 0 2 1 ) ) ) 3 )
See also: `pscratch'")
(defmethod as-pstream ((phistory phistory))
(with-slots (pattern step-pattern) phistory
(make-instance 'phistory-pstream
:pattern (as-pstream pattern)
:step-pattern (pattern-as-pstream step-pattern))))
(defmethod next ((phistory phistory-pstream))
(with-slots (pattern step-pattern) phistory
(let ((next-step (next step-pattern)))
(if (eop-p next-step)
eop
(progn
(next pattern)
(handler-case (pstream-elt pattern next-step)
(pstream-out-of-range ()
nil)))))))
NOTE : pscratch 's mechanism seems to be slightly different :
> Pscratch(Pseries(0 , 1 ) , Pseq([1 , 1 , 1 , -3 ] , inf)).asStream.nextN(12 )
[ 0 , 1 , 2 , 0 , 1 , 2 , 3 , 0 , 1 , 2 , 3 , 0 ]
> ( next - n ( pscratch ( pseries 0 1 ) ( pseq ( list 1 1 1 -3 ) : ) ) 12 )
(defpattern pscratch (pattern)
(pattern
step-pattern
(current-index :state t :initform 0))
:documentation "\"Scratches\" across the values yielded by a pstream, similar in concept to how a DJ might scratch a record, altering the normal flow of playback. PATTERN is the source pattern, and STEP-PATTERN determines the increment of the index into the pstream history.
Based on the pattern originally from the ddwPatterns SuperCollider library.
Example:
( next - upto - n ( pscratch ( pseries ) ( pseq ' ( 0 1 1 -1 2 ) 2 ) ) )
See also: `phistory'")
(defmethod as-pstream ((pscratch pscratch))
(with-slots (pattern step-pattern) pscratch
(make-instance 'pscratch-pstream
:pattern (as-pstream pattern)
:step-pattern (pattern-as-pstream step-pattern))))
(defmethod next ((pscratch pscratch-pstream))
(with-slots (pattern step-pattern current-index) pscratch
(let ((nxt (next step-pattern)))
(when (eop-p nxt)
(return-from next eop))
(prog1
(pstream-elt-future pattern current-index)
(setf current-index (max (+ current-index nxt) 0))))))
pif
(defpattern pif (pattern)
((test)
(true)
(false :initform nil))
:documentation "\"If\" expression for patterns. TEST is evaluated for each step, and if it's non-nil, the value of TRUE will be yielded, otherwise the value of FALSE will be. Note that TRUE and FALSE can be patterns, and if they are, they are only advanced in their respective cases, not for every step.
Example:
( next - n ( pif ( pseq ' ( t t nil nil nil ) ) ( pseq ' ( 1 2 3 ) ) ( pseq ' ( 9 8 7 ) ) ) 8)
See also: `plazy', `pfunc'")
(defmethod next ((pif pif-pstream))
(with-slots (test true false) pif
(let ((nxt (next test)))
(if (eop-p nxt)
eop
(if nxt
(next true)
(next false))))))
(defpattern parp (pattern)
(pattern
arpeggiator
(current-pattern-event :state t :initform nil)
(current-arpeggiator-stream :state t :initform nil))
each event yielded by PATTERN is bound to ` * event * ' and then the entirety of the ARPEGGIATOR pattern is yielded .
Example:
( next - upto - n ( parp ( : foo ( pseq ' ( 1 2 3 ) 1 ) )
( pbind : bar ( pseq ' ( 4 5 6 ) 1 ) ) ) )
( EVENT : FOO 2 : BAR 4 ) ( EVENT : FOO 2 : BAR 5 ) ( EVENT : FOO 2 : BAR 6 )
( EVENT : FOO 3 : BAR 4 ) ( EVENT : FOO 3 : BAR 5 ) ( EVENT : FOO 3 : BAR 6 ) )
See also: `psym', `pmeta', `pr'")
(defmethod as-pstream ((parp parp))
(with-slots (pattern arpeggiator) parp
(let ((pstr (as-pstream pattern)))
(make-instance 'parp-pstream
:pattern pstr
:arpeggiator arpeggiator
:current-pattern-event (next pstr)
:current-arpeggiator-stream (as-pstream arpeggiator)))))
(defmethod next ((parp parp-pstream))
(with-slots (pattern arpeggiator current-pattern-event current-arpeggiator-stream) parp
(when (eop-p current-pattern-event)
(return-from next eop))
(let ((nxt (let ((*event* (combine-events (make-default-event)
current-pattern-event)))
(next current-arpeggiator-stream))))
(unless (eop-p nxt)
(return-from next nxt))
(setf current-pattern-event (next pattern)
current-arpeggiator-stream (as-pstream arpeggiator))
(next parp))))
(defpattern pfin (pattern)
(pattern
count)
:documentation "Yield up to COUNT outputs from PATTERN.
Example:
( next - n ( pfin ( pseq ' ( 1 2 3 ) : ) 3 ) 5 )
See also: `pfindur'")
(defmethod as-pstream ((pfin pfin))
(with-slots (count pattern) pfin
(make-instance 'pfin-pstream
:pattern (as-pstream pattern)
(defmethod next ((pfin pfin-pstream))
(with-slots (pattern count number) pfin
(unless (< number count)
(return-from next eop))
(next pattern)))
(defpattern pfindur (pattern)
(pattern
dur
(tolerance :initform 0)
(current-dur :state t)
(elapsed-dur :state t :initform 0))
:documentation "Yield events from PATTERN until their total duration is within TOLERANCE of DUR, or greater than DUR. Any events that would end beyond DUR are cut short. If PATTERN outputs numbers, their total sum is limited instead.
Example:
( next - n ( pfindur ( pbind : dur 1 : foo ( pseries ) ) 2 ) 3 )
( next - upto - n ( pfindur ( pwhite 0 4 ) 16 ) )
See also: `pfin', `psync'")
(defmethod as-pstream ((pfindur pfindur))
(with-slots (pattern dur tolerance) pfindur
(make-instance 'pfindur-pstream
:pattern (pattern-as-pstream pattern)
:dur (as-pstream dur)
:tolerance (next tolerance))))
(defmethod next ((pfindur pfindur-pstream))
(labels ((get-delta (ev)
(etypecase ev
(event
(event-value ev :delta))
(list
(reduce #'max (mapcar #'get-delta ev)))
(number
ev))))
(with-slots (pattern dur tolerance current-dur elapsed-dur) pfindur
(let ((n-event (next pattern)))
(when (eop-p n-event)
(return-from next eop))
(unless (slot-boundp pfindur 'current-dur)
(setf current-dur (next dur)))
(when (eop-p current-dur)
(return-from next eop))
(let ((res (if (or (eql :inf current-dur)
(>= current-dur (+ elapsed-dur (get-delta n-event))))
n-event
(let ((tdur (- current-dur elapsed-dur)))
(when (>= tolerance tdur)
(return-from next eop))
(if (event-p n-event)
(combine-events n-event (event :dur tdur))
tdur)))))
(incf elapsed-dur (get-delta res))
res)))))
(defpattern psync (pattern)
(pattern
sync-quant
(maxdur :initform nil)
(tolerance :initform 0.001)
(elapsed-dur :state t :initform 0))
:documentation "Yield events from PATTERN until their total duration is within TOLERANCE of MAXDUR, cutting off any events that would extend past MAXDUR. If PATTERN ends before MAXDUR, a rest is added to the pstream to round its duration up to the nearest multiple of SYNC-QUANT.
Example:
( next - upto - n ( psync ( : ( pseq ' ( 5 ) 1 ) ) 4 16 ) )
( next - upto - n ( psync ( : ( pseq ' ( 5 ) 5 ) ) 4 16 ) )
See also: `pfindur'")
(defmethod as-pstream ((psync psync))
(with-slots (pattern sync-quant maxdur tolerance) psync
(make-instance 'psync-pstream
:pattern (as-pstream pattern)
:sync-quant (next sync-quant)
:maxdur (next maxdur)
:tolerance (next tolerance))))
(defmethod next ((psync psync-pstream))
(with-slots (pattern sync-quant maxdur tolerance elapsed-dur) psync
(when (and maxdur
(>= elapsed-dur (- maxdur tolerance)))
(return-from next eop))
(let* ((nbfq (next-beat-for-quant sync-quant elapsed-dur))
(n-event (next pattern))
(n-event (if (eop-p n-event)
(let ((diff (- nbfq elapsed-dur)))
(if (plusp diff)
(event :type :rest :dur diff)
(return-from next eop)))
n-event))
(n-event (if maxdur
(combine-events n-event (event :dur (min (event-value n-event :dur)
(- maxdur elapsed-dur))))
n-event)))
(incf elapsed-dur (event-value n-event :dur))
n-event)))
(defpattern pdurstutter (pattern)
(pattern
n
(current-value :state t :initform nil)
(current-repeats-remaining :state t :initform 0))
Example:
( next - n ( pdurstutter ( pseq ' ( 1 2 3 4 5 ) ) ( pseq ' ( 3 2 1 0 2 ) ) ) 9 )
( next - n ( pdurstutter ( : ( pseq ' ( 1 2 3 4 5 ) ) )
( pseq ' ( 3 2 1 0 2 ) ) )
9 )
See also: `pr'")
(defmethod as-pstream ((pdurstutter pdurstutter))
(with-slots (pattern n) pdurstutter
(make-instance 'pdurstutter-pstream
:pattern (as-pstream pattern)
:n (pattern-as-pstream n))))
(defmethod next ((pdurstutter pdurstutter-pstream))
(with-slots (pattern n current-value current-repeats-remaining) pdurstutter
(while (and current-repeats-remaining
(zerop current-repeats-remaining))
(setf current-repeats-remaining (next n))
(let ((e (next pattern)))
(when (eop-p current-repeats-remaining)
(return-from next eop))
(when (and current-repeats-remaining
(not (zerop current-repeats-remaining)))
(setf current-value (if (eop-p e)
eop
(ctypecase e
(event (combine-events e (event :dur (/ (event-value e :dur) current-repeats-remaining))))
(number (/ e current-repeats-remaining))))))))
(when current-repeats-remaining
(decf-remaining pdurstutter)
current-value)))
(defpattern pbeat (pattern)
()
:documentation "Yield the number of beats elapsed since the pbeat was embedded in the pstream.
Example:
( next - n ( pbind : ( pseq ' ( 1 2 3 ) ) : foo ( pbeat ) ) 3 )
See also: `pbeat*', `beat', `prun'")
(defmethod next ((pbeat pbeat-pstream))
(beat (pattern-parent pbeat :class 'pbind)))
(defpattern pbeat* (pattern)
((task :state t :initform nil))
:documentation "Yield the number of beats on the `*clock*' of the current pattern. In other words, pbeat* is clock-synced, unlike `pbeat', which is pattern-synced.
Example:
( next - n ( pbind : ( pseq ' ( 1 2 3 ) ) : foo ( pbeat * ) ) 3 )
See also: `pbeat', `beat', `prun'")
(defmethod next ((pbeat* pbeat*-pstream))
(beat *clock*))
(defpattern ptime (pattern)
((last-beat-checked :state t :initform nil)
(tempo-at-beat :state t :initform nil)
(elapsed-time :state t :initform 0))
:documentation "Yield the number of seconds elapsed since ptime was embedded in the pstream.
Note: May give inaccurate results if the clock's tempo changes occur more frequently than events in the parent pbind.
Example:
( next - n ( pbind : dur 1 : time ( ptime ) ) 2 )
See also: `pbeat', `prun', `beat'")
(with-slots (last-beat-checked tempo-at-beat elapsed-time) ptime
(with-slots (tempo) *clock*
(let ((beat (beat (pattern-parent ptime :class 'pbind))))
(prog1
(incf elapsed-time (if (null last-beat-checked)
0
(dur-time (- beat last-beat-checked) tempo)))
(setf last-beat-checked beat
tempo-at-beat tempo))))))
pindex
TODO : pindex1 that only embeds 1 element from subpatterns , a la SuperCollider 's Pswitch1 .
(defpattern pindex (pattern)
(list-pat
index-pat
(wrap-p :initform nil))
:documentation "Use INDEX-PAT to index into the list returned by LIST-PAT. WRAP-P is whether indexes that are out of range will be wrapped (if t) or will simply return nil.
Example:
( next - n ( pindex ( list 99 98 97 ) ( pseq ( list 0 1 2 3 ) ) ) 4 )
( next - upto - n ( pindex ( list 99 98 97 ) ( pseries 0 1 6 ) t ) )
See also: `pwalk'")
(defmethod as-pstream ((pindex pindex))
(with-slots (list-pat index-pat wrap-p) pindex
(make-instance 'pindex-pstream
:list-pat (pattern-as-pstream list-pat)
:index-pat (pattern-as-pstream index-pat)
:wrap-p wrap-p)))
(with-slots (list-pat index-pat wrap-p) pindex
(let ((list (next list-pat))
(idx (next index-pat)))
(when (or (eop-p idx)
(eop-p list))
(return-from next eop))
(funcall (if wrap-p 'nth-wrap 'nth) idx list))))
(defpattern prun (pattern)
(pattern
(dur :initform 1)
(current-dur :state t :initform 0))
:documentation "Run PATTERN \"independently\" of its parent, holding each value for DUR beats. Each of PATTERN's outputs is treated as if it lasted DUR beats, being continuously yielded during that time before moving on to the next output.
Example:
( next - upto - n ( pbind : foo ( pseq ' ( 1 2 3 4 5 ) )
: bar ( prun ( pseq ' ( 4 5 6 7 8) )
( pseq ' ( 1 2 0.5 0.5 1 ) ) ) ) )
( EVENT : FOO 2 : BAR 5 )
( EVENT : FOO 3 : BAR 5 )
( EVENT : FOO 4 : BAR 6 )
( EVENT : FOO 5 : BAR 8) )
See also: `beat', `pbeat'")
(defmethod as-pstream ((prun prun))
(with-slots (pattern dur) prun
(unless (pattern-parent prun :class 'pbind)
(error "~S cannot be used outside of a pbind" prun))
(make-instance 'prun-pstream
:pattern (as-pstream pattern)
:dur (pattern-as-pstream dur)
:current-dur 0)))
(defmethod next ((prun prun-pstream))
(with-slots (pattern dur current-dur dur-history number) prun
(let ((beats (beat (pattern-parent prun :class 'pbind))))
(flet ((next-dur ()
(let ((nxt (next dur)))
(unless (eop-p nxt)
(next pattern)
(incf current-dur nxt)))))
(when (zerop number)
(next-dur))
(while (and (or (not (pstream-p dur))
(not (ended-p dur)))
(<= current-dur beats))
(next-dur))))
(last-output pattern)))
psym
(defpattern psym (pattern)
(pattern
(current-pstream :state t :initform eop))
:documentation "Use a pattern of symbols to embed `pdef's. PATTERN is the source pattern that yields symbols naming the pdef to embed.
Example:
( pdef : foo ( pseq ' ( 1 2 3 ) 1 ) )
( pdef : bar ( pseq ' ( 4 5 6 ) 1 ) )
( next - upto - n ( psym ( pseq ' (: foo : bar ) 1 ) ) )
See also: `pdef', `ppar', `pmeta'")
(defmethod as-pstream ((psym psym))
(with-slots (pattern) psym
(make-instance 'psym-pstream
:pattern (as-pstream pattern))))
(defmethod next ((psym psym-pstream))
(labels ((maybe-pdef (x)
(if-let ((pdef (and (symbolp x)
(pdef-pattern x))))
pdef
x)))
(with-slots (pattern current-pstream) psym
(let ((n (next current-pstream)))
(if (eop-p n)
(let ((next-pdef (next pattern)))
(when (eop-p next-pdef)
(return-from next eop))
(setf current-pstream (as-pstream (if (listp next-pdef)
(ppar (mapcar #'maybe-pdef next-pdef))
(maybe-pdef next-pdef))))
(next psym))
n)))))
(defpattern pchain (pattern)
(patterns)
:documentation "Combine multiple patterns into one event stream.
Example:
( next - n ( pchain ( : foo ( pseq ' ( 1 2 3 ) ) ) ( pbind : bar ( pseq ' ( 7 8 9 ) 1 ) ) ) 4 )
See also: `pbind''s :embed key"
:defun (defun pchain (&rest patterns)
(make-instance 'pchain
:patterns patterns)))
(defmethod as-pstream ((pchain pchain))
(with-slots (patterns) pchain
(make-instance 'pchain-pstream
:patterns (mapcar #'pattern-as-pstream patterns))))
(defmethod next ((pchain pchain-pstream))
(with-slots (patterns) pchain
(let ((c-event (make-default-event)))
(dolist (pattern patterns c-event)
(setf c-event (combine-events c-event
(let ((*event* c-event))
(next pattern))))))))
(defpattern pdiff (pattern)
(pattern)
:documentation "Output the difference between successive outputs of PATTERN.
Example:
( next - n ( pdiff ( pseq ' ( 3 1 4 3 ) 1 ) ) 4 )
See also: `pdelta'")
(defmethod next ((pdiff pdiff-pstream))
(with-slots (pattern) pdiff
(when (zerop (slot-value pattern 'history-number))
(next pattern))
(let ((last (pstream-elt pattern -1))
(next (next pattern)))
(when (or (eop-p last)
(eop-p next))
(return-from next eop))
(- next last))))
pdelta
(defpattern pdelta (pattern)
(pattern
(cycle :initform 4))
:documentation "Output the difference between successive outputs of PATTERN, assuming PATTERN restarts every CYCLE outputs.
Unlike `pdiff', pdelta is written with its use as input for `pbind''s :delta key in mind. If PATTERN's successive values would result in a negative difference, pdelta instead wraps the delta around to the next multiple of CYCLE. This would allow you to, for example, supply the number of the beat that each event occurs on, rather than specifying the delta between each event. This is of course achievable using pbind's :beat key as well, however that method requires the pbind to peek at future values, which is not always desirable.
Based on the pattern originally from the ddwPatterns SuperCollider library.
Example:
( next - n ( pdelta ( pseq ' ( 0 1 2 3 ) ) 4 ) 8)
( next - n ( pdelta ( pseq ' ( 0 1 2 5 ) ) 4 ) 8)
See also: `pdiff', `pbind''s :beat key")
(defmethod as-pstream ((pdelta pdelta))
(with-slots (pattern cycle) pdelta
(make-instance 'pdelta-pstream
:pattern (as-pstream pattern)
:cycle (next cycle))))
(defmethod next ((pdelta pdelta-pstream))
(with-slots (pattern cycle history-number) pdelta
(when (zerop history-number)
(next pattern))
(let ((lv (or (pstream-elt pattern -1) 0))
(cv (next pattern)))
(when (or (eop-p lv)
(eop-p cv))
(return-from next eop))
(- cv
(- lv (ceiling-by (- lv cv) cycle))))))
(defpattern pdrop (pattern)
(pattern
(n :initform 0))
:documentation "Drop the first N outputs from PATTERN and yield the rest. If N is negative, drop the last N outputs from PATTERN instead.
Example:
( next - n ( pdrop ( pseq ' ( 1 2 3 4 ) 1 ) 2 ) 4 )
See also: `protate'")
(defmethod as-pstream ((pdrop pdrop))
(with-slots (pattern n) pdrop
(make-instance 'pdrop-pstream
:pattern (as-pstream pattern)
:n n)))
(defmethod next ((pdrop pdrop-pstream))
(with-slots (pattern n number) pdrop
(if (minusp n)
(when (eop-p (pstream-elt-future pattern (- number n)))
(return-from next eop))
(when (zerop (slot-value pattern 'history-number))
(dotimes (i n)
(next pattern))))
(next pattern)))
(defpattern ppar (pattern)
(patterns
(pstreams :state t :initform nil))
:documentation "Combine multiple event patterns into one pstream with all events in temporal order. PATTERNS is the list of patterns, or a pattern yielding lists of patterns. The ppar ends when all of the patterns in PATTERNS end.
Example:
( next - upto - n ( ppar ( list ( : dur ( pn 1/2 4 ) )
( pbind : dur ( pn 2/3 4 ) ) ) ) )
( EVENT : 1/2 : DELTA 1/6 ) ( EVENT : DUR 2/3 : DELTA 1/3 )
( EVENT : 1/2 : DELTA 1/3 ) ( EVENT : DUR 2/3 : DELTA 1/6 )
( EVENT : 1/2 : DELTA 1/2 ) ( EVENT : DUR 2/3 : DELTA 2/3 ) )
See also: `psym'")
(defmethod next ((ppar ppar-pstream))
(with-slots (patterns pstreams history-number) ppar
(labels ((next-in-pstreams ()
(or (most #'< pstreams :key #'beat)
eop))
(maybe-reset-pstreams ()
(unless (remove eop pstreams)
(let ((next-list (next patterns)))
(when (eop-p next-list)
(return-from maybe-reset-pstreams nil))
(setf pstreams (mapcar (lambda (item)
(as-pstream (if (symbolp item)
(find-pdef item)
item)))
next-list))))))
(when (zerop history-number)
(maybe-reset-pstreams))
(let* ((next-pat (next-in-pstreams))
(nxt (next next-pat)))
(if (eop-p nxt)
(progn
(removef pstreams next-pat)
(let ((nip (next-in-pstreams)))
(if (eop-p nip)
eop
(event :type :rest :delta (- (beat nip) (beat ppar))))))
(combine-events nxt (event :delta (- (beat (next-in-pstreams)) (beat ppar)))))))))
(defpattern pts (pattern)
(pattern
(dur :initform 4)
(pattern-outputs :state t))
:documentation "Timestretch PATTERN so its total duration is DUR. Note that only the first `*max-pattern-yield-length*' events from PATTERN are considered, and that they are calculated immediately at pstream creation time rather than lazily as the pstream yields.
Example:
( next - upto - n ( pts ( : dur ( pn 1 4 ) ) 5 ) )
See also: `pfindur', `psync'")
(defmethod as-pstream ((pts pts))
(with-slots (pattern dur) pts
(let* ((pstr (as-pstream pattern))
(res (next-upto-n pstr)))
(make-instance 'pts-pstream
:pattern pstr
:dur (next dur)
:pattern-outputs (coerce res 'vector)))))
(defmethod next ((pts pts-pstream))
(with-slots (pattern dur pattern-outputs number) pts
(when (>= number (length pattern-outputs))
(return-from next eop))
(let ((mul (/ dur (beat pattern)))
(ev (elt pattern-outputs number)))
(combine-events ev (event :dur (* mul (event-value ev :dur)))))))
pwalk
(defpattern pwalk (pattern)
(list
step-pattern
(direction-pattern :initform 1)
(start-pos :initform 0)
(current-index :state t)
(current-direction :initform 1 :state t))
:documentation "\"Walk\" over the values in LIST by using the accumulated value of the outputs of STEP-PATTERN as the index. At the beginning of the pwalk and each time the start or end of the list is passed, the output of DIRECTION-PATTERN is taken and used as the multiplier for values from STEP-PATTERN. START-POS is the index in LIST for pwalk to take its first output from.
Example:
( next - n ( pwalk ( list 0 1 2 3 ) ( pseq ( list 1 ) ) ( pseq ( list 1 -1 ) ) ) 10 )
See also: `pindex', `pbrown', `paccum'")
(defmethod as-pstream ((pwalk pwalk))
(with-slots (list step-pattern direction-pattern start-pos) pwalk
(make-instance 'pwalk-pstream
:list (next list)
:step-pattern (pattern-as-pstream step-pattern)
:direction-pattern (pattern-as-pstream direction-pattern)
:start-pos (pattern-as-pstream start-pos))))
(defmethod next ((pwalk pwalk-pstream))
(with-slots (list step-pattern direction-pattern start-pos current-index current-direction number) pwalk
(when (zerop number)
(setf current-index (next start-pos))
(setf current-direction (next direction-pattern))
(return-from next (nth current-index list)))
(let ((nsp (next step-pattern)))
(when (or (eop-p nsp) (eop-p current-index) (eop-p current-direction))
(return-from next eop))
(labels ((next-index ()
(+ current-index (* nsp current-direction))))
(let ((next-index (next-index)))
(when (or (minusp next-index)
(>= next-index (length list)))
(setf current-direction (next direction-pattern)))
(when (eop-p current-direction)
(return-from next eop))
(setf current-index (mod (next-index) (length list))))))
(elt-wrap list current-index)))
(defpattern pparchain (pchain)
(patterns)
:documentation "Combine multiple patterns into several event streams. The event yielded by the first pattern will be used as the input event to the second pattern, and so on. The events yielded by each pattern will be collected into a list and yielded by the pparchain. This pattern is effectively `ppar' and `pchain' combined.
Example:
( next - upto - n ( pparchain ( pbind : foo ( pseries 0 1 3 ) ) ( : baz ( p+ ( pk : foo ) 1 ) : foo ( p+ ( pk : foo ) 3 ) ) ) )
( ( EVENT : FOO 1 ) ( EVENT : FOO 4 : BAZ 2 ) )
( ( EVENT : FOO 2 ) ( EVENT : FOO 5 : BAZ 3 ) ) )
See also: `ppc', `ppar', `pchain', `pbind''s :embed key"
:defun (defun pparchain (&rest patterns)
(make-instance 'pparchain
:patterns patterns)))
(defmethod as-pstream ((pparchain pparchain))
(with-slots (patterns) pparchain
(make-instance 'pparchain-pstream
:patterns (mapcar #'as-pstream patterns))))
(defmethod next ((pparchain pparchain-pstream))
(with-slots (patterns) pparchain
(let ((c-event (make-default-event)))
(loop :for pattern :in patterns
:do (setf c-event (combine-events c-event (let ((*event* (copy-event c-event)))
(next pattern))))
:if (eop-p c-event)
:return eop
:else
:collect c-event))))
(defmacro ppc (&body pairs)
"Syntax sugar for `pparchain' that automatically splits PAIRS by :- symbols.
Example:
( ppc : foo ( pseq ( list 1 2 3 ) 1 )
: bar ( p+ ( pk : foo ) 2 ) )
( ( EVENT : FOO 2 ) ( EVENT : FOO 2 : BAR 4 ) )
( ( EVENT : FOO 3 ) ( EVENT : FOO 3 : BAR 5 ) ) )
See also: `pparchain'"
(labels ((ppc-split (pairs)
(let ((pos (position :- pairs)))
(if pos
(list (subseq pairs 0 pos)
(ppc-split (subseq pairs (1+ pos))))
pairs))))
`(pparchain ,@(loop :for i :in (ppc-split pairs)
:collect (cons 'pbind i)))))
(pushnew 'ppc *patterns*)
(defpattern pclump (pattern)
(pattern
(n :initform 1))
:documentation "Group outputs of the source pattern into lists of up to N items each.
Example:
( next - upto - n ( pclump ( pseries 0 1 5 ) 2 ) )
See also: `paclump'")
(defmethod next ((pclump pclump-pstream))
(with-slots (pattern n) pclump
(let ((next (next n)))
(when (eop-p next)
(return-from next eop))
(or (next-upto-n pattern next)
eop))))
(defpattern paclump (pattern)
(pattern)
:documentation "Automatically group outputs of the source pattern into lists of up to N items each. Unlike `pclump', clump size is automatically set to the length of the longest list in the values of `*event*', or 1 if there are no lists.
Example:
( next - upto - n ( pbind : foo ( pseq ' ( ( 1 ) ( 1 2 ) ( 1 2 3 ) ) 1 ) : bar ( paclump ( pseries ) ) ) )
See also: `pclump'")
(defmethod next ((paclump paclump-pstream))
(with-slots (pattern) paclump
(unless *event*
(return-from next eop))
(next-upto-n pattern (reduce #'max (mapcar (fn (length (ensure-list (e _))))
(keys *event*))))))
(defpattern paccum (pattern)
((operator :initform #'+)
(start :initform 0)
(step :initform 1)
(length :initform :inf)
(lo :initform nil)
(hi :initform nil)
(bound-by :initform nil)
(current-value :state t)
(current-repeats-remaining :state t))
the value is provided as its first argument , and LO and HI are provided as its second and third .
Based on the pattern originally from the ddwPatterns SuperCollider library.
Example:
See also: `pseries', `pgeom', `pwalk'"
:defun
(defun paccum (&optional (operator #'+) (start 0) (step 1) (length :inf) &key lo hi bound-by)
(make-instance 'paccum
:operator operator
:start start
:step step
:length length
:lo lo
:hi hi
:bound-by bound-by)))
(defmethod next ((paccum paccum-pstream))
(with-slots (operator start step length lo hi bound-by current-value) paccum
(unless (remaining-p paccum 'length)
(return-from next eop))
(decf-remaining paccum)
(setf current-value (if (slot-boundp paccum 'current-value)
(when-let ((res (funcall (if (pstream-p operator)
(next operator)
operator)
current-value
(next step))))
(if bound-by
(when-let ((func (if (pstream-p bound-by)
(next bound-by)
bound-by))
(lo (next lo))
(hi (next hi)))
(funcall func res lo hi))
res))
(next start)))))
(defpattern ps (pattern)
(pattern
pstream)
:documentation "Preserve pstream state across subsequent calls to `as-pstream'. To reset the pstream, simply re-evaluate the ps definition.
Based on the pattern originally from the miSCellaneous SuperCollider library.
Example:
( next - upto - n * pst * 4 )
( next - upto - n * pst * 4 )
( next - upto - n * pst * 4 )
See also: `prs', `pdef'"
:defun (defun ps (pattern)
(make-instance 'ps
:pattern pattern)))
(defmethod as-pstream ((ps ps))
(with-slots (pattern pstream) ps
(make-instance 'ps-pstream
:pattern pattern
:pstream (if (slot-boundp ps 'pstream)
pstream
(let ((pstr (as-pstream pattern)))
(setf pstream pstr)
pstr)))))
(defmethod next ((ps-pstream ps-pstream))
(with-slots (pstream) ps-pstream
(next pstream)))
(defun prs (pattern &optional (repeats :inf))
"Syntax sugar for (pr (ps PATTERN) REPEATS). Useful, for example, to ensure that each cycle of a pattern only gets one value from the `ps'.
See also: `pr', `ps'"
(pr (ps pattern) repeats))
(pushnew 'prs *patterns*)
(defpattern ipstream (pattern)
((patterns :initform (list))
(end-when-empty :initform nil)
(granularity :initform 1/5)
(lock :state t :initform (bt:make-recursive-lock "ipstream patterns slot lock")))
:documentation "Insertable pstream; a pstream that can be changed while it's running by inserting new patterns at a specified beat.")
(defmethod as-pstream ((ipstream ipstream))
(with-slots (patterns end-when-empty granularity) ipstream
(let ((pstr (make-instance 'ipstream-pstream
:patterns (list)
:end-when-empty end-when-empty
:granularity granularity
:lock (bt:make-recursive-lock "ipstream patterns slot lock"))))
(dolist (pat patterns pstr)
(etypecase pat
(pattern
(ipstream-insert pstr pat 0))
(list
(destructuring-bind (beat &rest patterns) pat
(dolist (pat patterns)
(ipstream-insert pstr pat beat)))))))))
(defmethod next ((ipstream ipstream-pstream))
(with-slots (patterns end-when-empty granularity lock) ipstream
(labels ((actual-beat (pstream)
(+ (slot-value pstream 'start-beat) (beat pstream)))
(sorted-pstrs ()
(sort patterns #'< :key #'actual-beat)))
(bt:with-recursive-lock-held (lock)
(if patterns
(let* ((next-pstr (car (sorted-pstrs)))
(ev (if (<= (actual-beat next-pstr)
(beat ipstream))
(let ((nxt (next next-pstr)))
(if (eop-p nxt)
(progn
(deletef patterns next-pstr)
(next ipstream))
nxt))
(event :type :rest :delta granularity)))
(next-pstr (car (sorted-pstrs))))
(combine-events ev (event :delta (if next-pstr
(min granularity
(- (actual-beat next-pstr)
(beat ipstream)))
granularity))))
(if end-when-empty
eop
(event :type :rest :delta granularity)))))))
(defgeneric ipstream-insert (ipstream pattern &optional start-beat)
(:documentation "Insert PATTERN into IPSTREAM at START-BEAT. START-BEAT defaults to the ipstream's current beat."))
(defmethod ipstream-insert ((ipstream ipstream-pstream) pattern &optional start-beat)
(with-slots (patterns lock) ipstream
(let ((pstr (as-pstream pattern)))
(setf (slot-value pstr 'start-beat) (or start-beat (beat ipstream)))
(bt:with-lock-held (lock)
(push pstr patterns)))))
(export 'ipstream-insert)
(defpattern pfilter (pattern)
(pattern
(predicate :initform 'identity))
:documentation "Skip elements of a source pattern that PREDICATE returns false for. If PREDICATE is not a function, skip items that are `eql' to it.
Example:
( next - n ( pfilter ( pseq ( list 1 2 3 ) )
2 )
6 )
6 )
See also: `pfilter-out', `pr', `pdurstutter'")
(defmethod next ((pfilter pfilter-pstream))
(with-slots (pattern predicate) pfilter
(let ((func (if (function-designator-p predicate)
predicate
(lambda (input) (eql input predicate)))))
(loop :for res := (next pattern)
:if (or (eop-p res)
(funcall func res))
:return res))))
(defun pfilter-out (pattern predicate)
"Skip elements of a source pattern that PREDICATE returns true for. If PREDICATE is not a function, skip items that are `eql' to it.
See also: `pfilter'"
(pfilter pattern (if (function-designator-p predicate)
(lambda (x) (not (funcall predicate x)))
(lambda (x) (not (eql predicate x))))))
(pushnew 'pfilter-out *patterns*)
|
9a4874410da48a3b18bf8472193a164b9e67f6f117b3d85f69764089d550d41c
|
mdesharnais/mini-ml
|
TypeSubstitution.hs
|
module TypeSubstitution where
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import Type
import TypeContext(Context)
type TySubst = [(TyVar, Type)]
type AnSubst = [(AnVar, AnVar)]
type Subst = (TySubst, AnSubst)
empty :: Subst
empty = ([], [])
addTy :: (TyVar, Type) -> Subst -> Subst
addTy p (ts, as) = (p : ts, as)
addAn :: (AnVar, AnVar) -> Subst -> Subst
addAn p (ts, as) = (ts, p : as)
singletonTy :: (TyVar, Type) -> Subst
singletonTy p = addTy p empty
singletonAn :: (AnVar, AnVar) -> Subst
singletonAn p = addAn p empty
applyAn :: Subst -> AnVar -> AnVar
applyAn (_, as) a = Maybe.fromMaybe a (List.lookup a as)
applyTy :: Subst -> Type -> Type
applyTy s@(ts, as) TBool = TBool
applyTy s@(ts, as) TInt = TInt
applyTy s@(ts, as) (TFun b t1 t2) =
TFun (applyAn s b) (applyTy s t1) (applyTy s t2)
applyTy s@(ts, as) (TVar x) = Maybe.fromMaybe (TVar x) (List.lookup x ts)
applyTySchema :: Subst -> TypeSchema -> TypeSchema
applyTySchema s (TSType ty) = TSType (applyTy s ty)
applyTySchema s@(xs, _) (TSForall x ts) =
let ts' = applyTySchema s ts in
case List.lookup x xs of
Nothing -> TSForall x ts'
Just TBool -> ts'
Just TInt -> ts'
Just (TFun _ _ _) -> ts'
Just (TVar y) -> if x == y then TSForall x ts' else ts'
applyContext :: Subst -> Context -> Context
applyContext s = map (\(x, tySchema) -> (x, applyTySchema s tySchema))
comp :: Subst -> Subst -> Subst
comp (as, bs) (cs, ds) =
let compLists xs ys apply = map ( \(x , y ) - > ( x , apply ys y ) ) xs + + ys in
let compLists xs ys apply = map (\(x, y) -> (x, apply ys y)) xs ++ ys in
let ts = compLists cs as (applyTy . flip (,) []) in
let as = compLists ds bs (applyAn . (,) []) in
(ts, as)
| null |
https://raw.githubusercontent.com/mdesharnais/mini-ml/304017aab02c04ed4fbd9420405d3a0483dcba37/src/TypeSubstitution.hs
|
haskell
|
module TypeSubstitution where
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import Type
import TypeContext(Context)
type TySubst = [(TyVar, Type)]
type AnSubst = [(AnVar, AnVar)]
type Subst = (TySubst, AnSubst)
empty :: Subst
empty = ([], [])
addTy :: (TyVar, Type) -> Subst -> Subst
addTy p (ts, as) = (p : ts, as)
addAn :: (AnVar, AnVar) -> Subst -> Subst
addAn p (ts, as) = (ts, p : as)
singletonTy :: (TyVar, Type) -> Subst
singletonTy p = addTy p empty
singletonAn :: (AnVar, AnVar) -> Subst
singletonAn p = addAn p empty
applyAn :: Subst -> AnVar -> AnVar
applyAn (_, as) a = Maybe.fromMaybe a (List.lookup a as)
applyTy :: Subst -> Type -> Type
applyTy s@(ts, as) TBool = TBool
applyTy s@(ts, as) TInt = TInt
applyTy s@(ts, as) (TFun b t1 t2) =
TFun (applyAn s b) (applyTy s t1) (applyTy s t2)
applyTy s@(ts, as) (TVar x) = Maybe.fromMaybe (TVar x) (List.lookup x ts)
applyTySchema :: Subst -> TypeSchema -> TypeSchema
applyTySchema s (TSType ty) = TSType (applyTy s ty)
applyTySchema s@(xs, _) (TSForall x ts) =
let ts' = applyTySchema s ts in
case List.lookup x xs of
Nothing -> TSForall x ts'
Just TBool -> ts'
Just TInt -> ts'
Just (TFun _ _ _) -> ts'
Just (TVar y) -> if x == y then TSForall x ts' else ts'
applyContext :: Subst -> Context -> Context
applyContext s = map (\(x, tySchema) -> (x, applyTySchema s tySchema))
comp :: Subst -> Subst -> Subst
comp (as, bs) (cs, ds) =
let compLists xs ys apply = map ( \(x , y ) - > ( x , apply ys y ) ) xs + + ys in
let compLists xs ys apply = map (\(x, y) -> (x, apply ys y)) xs ++ ys in
let ts = compLists cs as (applyTy . flip (,) []) in
let as = compLists ds bs (applyAn . (,) []) in
(ts, as)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.