_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
|
---|---|---|---|---|---|---|---|---|
d7c492a24351f64abffac7ddd276bfa1c723b8cb9474deaf43b2d8b709d87670 | tweag/webauthn | PublicKeyWithSignAlg.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE TypeSynonymInstances #-}
-- | Stability: experimental
-- This module contains a partial implementation of the
[ COSE_Key]( / doc / html / rfc8152#section-7 ) format ,
limited to what is needed for Webauthn , and in a structured way .
module Crypto.WebAuthn.Cose.PublicKeyWithSignAlg
( -- * COSE public Key
PublicKeyWithSignAlg (PublicKeyWithSignAlg, Crypto.WebAuthn.Cose.PublicKeyWithSignAlg.publicKey, signAlg),
CosePublicKey,
makePublicKeyWithSignAlg,
)
where
import Codec.CBOR.Decoding (Decoder, TokenType (TypeBool, TypeBytes), decodeBytesCanonical, decodeMapLenCanonical, peekTokenType)
import Codec.CBOR.Encoding (Encoding, encodeBytes, encodeMapLen)
import Codec.Serialise (Serialise (decode, encode))
import Control.Monad (unless)
import Crypto.Number.Serialize (i2osp, i2ospOf_, os2ip)
import qualified Crypto.WebAuthn.Cose.Internal.Registry as R
import qualified Crypto.WebAuthn.Cose.PublicKey as P
import qualified Crypto.WebAuthn.Cose.SignAlg as A
import Crypto.WebAuthn.Internal.ToJSONOrphans ()
import qualified Data.Aeson as Aeson
import qualified Data.ByteString as BS
import Data.Functor (($>))
import Data.Text (Text)
import qualified Data.Text as Text
import GHC.Generics (Generic)
-- | A combination of a t'P.PublicKey' holding the public key data and a
' A.CoseSignAlg ' holding the exact signature algorithm that should be used .
This type can only be constructed with ' makePublicKeyWithSignAlg ' , which
ensures that the signature scheme matches between ' P.PublicKey ' and
' A.CoseSignAlg ' . This type is equivalent to a COSE public key , which holds
the same information , see ' CosePublicKey '
data PublicKeyWithSignAlg = PublicKeyWithSignAlgInternal
{ publicKeyInternal :: P.PublicKey,
signAlgInternal :: A.CoseSignAlg
TODO : Consider adding a RawField here to replace
-- acdCredentialPublicKeyBytes. This would then require parametrizing
' PublicKeyWithSignAlg ' with ' raw : : '
}
deriving (Eq, Show, Generic, Aeson.ToJSON)
| [ ( spec)]( / TR / webauthn-2/#credentialpublickey )
-- A structured and checked representation of a
[ COSE_Key]( / doc / html / rfc8152#section-7 ) , limited
to what is know to be necessary for Webauthn public keys for the
-- [credentialPublicKey](-2/#credentialpublickey)
-- field.
type CosePublicKey = PublicKeyWithSignAlg
| Deconstructs a ' makePublicKeyWithSignAlg ' into its t'P.PublicKey ' and
' A.CoseSignAlg ' . Since ' makePublicKeyWithSignAlg ' can only be constructed
using ' makePublicKeyWithSignAlg ' , we can be sure that the signature scheme
of t'P.PublicKey ' and ' A.CoseSignAlg ' matches .
pattern PublicKeyWithSignAlg :: P.PublicKey -> A.CoseSignAlg -> PublicKeyWithSignAlg
pattern PublicKeyWithSignAlg {publicKey, signAlg} <- PublicKeyWithSignAlgInternal {publicKeyInternal = publicKey, signAlgInternal = signAlg}
{-# COMPLETE PublicKeyWithSignAlg #-}
| Constructs a t'PublicKeyWithSignAlg ' from a t'P.PublicKey ' and
' A.CoseSignAlg ' , returning an error if the signature schemes between these
two types do n't match .
makePublicKeyWithSignAlg :: P.PublicKey -> A.CoseSignAlg -> Either Text PublicKeyWithSignAlg
makePublicKeyWithSignAlg key@(P.PublicKey k) alg =
verifyValid k alg
$> PublicKeyWithSignAlgInternal
{ publicKeyInternal = key,
signAlgInternal = alg
}
where
verifyValid :: P.UncheckedPublicKey -> A.CoseSignAlg -> Either Text ()
verifyValid P.PublicKeyEdDSA {} A.CoseSignAlgEdDSA = pure ()
verifyValid P.PublicKeyEdDSA {} alg = Left $ "EdDSA public key cannot be used with signing algorithm " <> Text.pack (show alg)
verifyValid P.PublicKeyECDSA {} A.CoseSignAlgECDSA {} = pure ()
verifyValid P.PublicKeyECDSA {} alg = Left $ "ECDSA public key cannot be used with signing algorithm " <> Text.pack (show alg)
verifyValid P.PublicKeyRSA {} A.CoseSignAlgRSA {} = pure ()
verifyValid P.PublicKeyRSA {} alg = Left $ "RSA public key cannot be used with signing algorithm " <> Text.pack (show alg)
-- | CBOR encoding as a [COSE_Key](#section-7)
using the [ CTAP2 canonical CBOR encoding form]( / specs / fido - v2.0 - ps-20190130 / - client - to - authenticator - protocol - v2.0 - ps-20190130.html#ctap2 - canonical - cbor - encoding - form )
instance Serialise CosePublicKey where
encode PublicKeyWithSignAlg {..} = case publicKey of
P.PublicKey P.PublicKeyEdDSA {..} ->
common R.CoseKeyTypeOKP
<> encode R.CoseKeyTypeParameterOKPCrv
<> encode (fromCurveEdDSA eddsaCurve)
<> encode R.CoseKeyTypeParameterOKPX
<> encodeBytes eddsaX
P.PublicKey P.PublicKeyECDSA {..} ->
common R.CoseKeyTypeEC2
<> encode R.CoseKeyTypeParameterEC2Crv
<> encode (fromCurveECDSA ecdsaCurve)
-- -ietf-cose-rfc8152bis-algs-12#section-7.1.1
> Leading zero octets MUST be preserved .
<> encode R.CoseKeyTypeParameterEC2X
-- This version of i2ospOf_ throws if the bytestring is larger than
size , but this ca n't happen due to the PublicKey invariants
<> encodeBytes (i2ospOf_ size ecdsaX)
<> encode R.CoseKeyTypeParameterEC2Y
<> encodeBytes (i2ospOf_ size ecdsaY)
where
size = P.coordinateSizeECDSA ecdsaCurve
P.PublicKey P.PublicKeyRSA {..} ->
common R.CoseKeyTypeRSA
-- -editor.org/rfc/rfc8230.html#section-4
-- > The octet sequence MUST utilize the minimum
-- number of octets needed to represent the value.
<> encode R.CoseKeyTypeParameterRSAN
<> encodeBytes (i2osp rsaN)
<> encode R.CoseKeyTypeParameterRSAE
<> encodeBytes (i2osp rsaE)
where
common :: R.CoseKeyType -> Encoding
common kty =
encodeMapLen (R.parameterCount kty)
<> encode R.CoseKeyCommonParameterKty
<> encode kty
<> encode R.CoseKeyCommonParameterAlg
<> encode signAlg
NOTE : CBOR itself does n't give an ordering of map keys , but the CTAP2 canonical CBOR encoding form does :
-- > The keys in every map must be sorted lowest value to highest. The sorting rules are:
-- >
-- > * If the major types are different, the one with the lower value in numerical order sorts earlier.
> * If two keys have different lengths , the shorter one sorts earlier ;
> * If two keys have the same length , the one with the lower value in ( byte - wise ) lexical order sorts earlier .
--
This has the effect that numeric keys are sorted like 1 , 2 , 3 , ... , -1 , -2 , -3 , ...
-- Which aligns very nicely with the fact that common parameters use positive
values and can therefore be decoded first , while key type specific
-- parameters use negative values
decode = do
n <- fromIntegral <$> decodeMapLenCanonical
-- -ietf-cose-rfc8152bis-struct-15#section-7.1
-- This parameter MUST be present in a key object.
decodeExpected R.CoseKeyCommonParameterKty
kty <- decode
-- -2/#credentialpublickey
The COSE_Key - encoded credential public key MUST contain the " alg "
-- parameter and MUST NOT contain any other OPTIONAL parameters.
decodeExpected R.CoseKeyCommonParameterAlg
alg <- decode
uncheckedKey <- decodeKey n kty alg
case P.checkPublicKey uncheckedKey of
Left err -> fail $ "Key check failed: " <> Text.unpack err
Right result ->
pure $
PublicKeyWithSignAlgInternal
{ publicKeyInternal = result,
signAlgInternal = alg
}
where
decodeKey :: Word -> R.CoseKeyType -> A.CoseSignAlg -> Decoder s P.UncheckedPublicKey
decodeKey n kty alg = case alg of
A.CoseSignAlgEdDSA -> decodeEdDSAKey
A.CoseSignAlgECDSA _ -> decodeECDSAKey
A.CoseSignAlgRSA _ -> decodeRSAKey
where
-- [(spec)](-ietf-cose-rfc8152bis-struct-15#section-7.1)
-- Implementations MUST verify that the key type is appropriate for
-- the algorithm being processed.
checkKty :: R.CoseKeyType -> Decoder s ()
checkKty expectedKty = do
unless (expectedKty == kty) $
fail $
"Expected COSE key type "
<> show expectedKty
<> " for COSE algorithm "
<> show alg
<> " but got COSE key type "
<> show kty
<> " instead"
unless (R.parameterCount kty == n) $
fail $
"Expected CBOR map to contain "
<> show (R.parameterCount kty)
<> " parameters for COSE key type "
<> show kty
<> " but got "
<> show n
<> " parameters instead"
decodeEdDSAKey :: Decoder s P.UncheckedPublicKey
decodeEdDSAKey = do
-ietf-cose-rfc8152bis-algs-12#section-2.2
> The ' kty ' field MUST be present , and it MUST be ' OKP ' ( Octet Key Pair ) .
checkKty R.CoseKeyTypeOKP
-- -ietf-cose-rfc8152bis-algs-12#section-7.2
decodeExpected R.CoseKeyTypeParameterOKPCrv
eddsaCurve <- toCurveEdDSA <$> decode
decodeExpected R.CoseKeyTypeParameterOKPX
eddsaX <- decodeBytesCanonical
pure P.PublicKeyEdDSA {..}
decodeECDSAKey :: Decoder s P.UncheckedPublicKey
decodeECDSAKey = do
-- -ietf-cose-rfc8152bis-algs-12#section-2.1
-- > The 'kty' field MUST be present, and it MUST be 'EC2'.
checkKty R.CoseKeyTypeEC2
-- -ietf-cose-rfc8152bis-algs-12#section-7.1.1
decodeExpected R.CoseKeyTypeParameterEC2Crv
ecdsaCurve <- toCurveECDSA <$> decode
let size = P.coordinateSizeECDSA ecdsaCurve
decodeExpected R.CoseKeyTypeParameterEC2X
ecdsaX <- os2ipWithSize size =<< decodeBytesCanonical
decodeExpected R.CoseKeyTypeParameterEC2Y
ecdsaY <-
peekTokenType >>= \case
TypeBytes -> os2ipWithSize size =<< decodeBytesCanonical
TypeBool -> fail "Compressed EC2 y coordinate not yet supported"
typ -> fail $ "Unexpected type in EC2 y parameter: " <> show typ
pure P.PublicKeyECDSA {..}
decodeRSAKey :: Decoder s P.UncheckedPublicKey
decodeRSAKey = do
-- -editor.org/rfc/rfc8812.html#section-2
> Implementations need to check that the key type is ' RSA ' when creating or verifying a signature .
checkKty R.CoseKeyTypeRSA
-- -editor.org/rfc/rfc8230.html#section-4
decodeExpected R.CoseKeyTypeParameterRSAN
-- > The octet sequence MUST utilize the minimum number of octets needed to represent the value.
rsaN <- os2ipNoLeading =<< decodeBytesCanonical
decodeExpected R.CoseKeyTypeParameterRSAE
rsaE <- os2ipNoLeading =<< decodeBytesCanonical
pure P.PublicKeyRSA {..}
| Same as ' os2ip ' , but throws an error if there are not exactly as many bytes as expected . Thus any successful result of this function will give the same ' BS.ByteString ' back if encoded with @'i2ospOf _ ' size@.
os2ipWithSize :: MonadFail m => Int -> BS.ByteString -> m Integer
os2ipWithSize size bytes
| BS.length bytes == size = pure $ os2ip bytes
| otherwise =
fail $
"bytes have length "
<> show (BS.length bytes)
<> " when length "
<> show size
<> " was expected"
| Same as ' os2ip ' , but throws an error if there are leading zero bytes . Thus any successful result of this function will give the same ' BS.ByteString ' back if encoded with ' i2osp ' .
os2ipNoLeading :: MonadFail m => BS.ByteString -> m Integer
os2ipNoLeading bytes
| leadingZeroCount == 0 = pure $ os2ip bytes
| otherwise =
fail $
"bytes of length "
<> show (BS.length bytes)
<> " has "
<> show leadingZeroCount
<> " leading zero bytes when none were expected"
where
leadingZeroCount = BS.length (BS.takeWhile (== 0) bytes)
-- | Decode a value and ensure it's the same as the value that was given
decodeExpected :: (Show a, Eq a, Serialise a) => a -> Decoder s ()
decodeExpected expected = do
actual <- decode
unless (expected == actual) $
fail $
"Expected " <> show expected <> " but got " <> show actual
fromCurveEdDSA :: P.CoseCurveEdDSA -> R.CoseEllipticCurveOKP
fromCurveEdDSA P.CoseCurveEd25519 = R.CoseEllipticCurveEd25519
toCurveEdDSA :: R.CoseEllipticCurveOKP -> P.CoseCurveEdDSA
toCurveEdDSA R.CoseEllipticCurveEd25519 = P.CoseCurveEd25519
fromCurveECDSA :: P.CoseCurveECDSA -> R.CoseEllipticCurveEC2
fromCurveECDSA P.CoseCurveP256 = R.CoseEllipticCurveEC2P256
fromCurveECDSA P.CoseCurveP384 = R.CoseEllipticCurveEC2P384
fromCurveECDSA P.CoseCurveP521 = R.CoseEllipticCurveEC2P521
toCurveECDSA :: R.CoseEllipticCurveEC2 -> P.CoseCurveECDSA
toCurveECDSA R.CoseEllipticCurveEC2P256 = P.CoseCurveP256
toCurveECDSA R.CoseEllipticCurveEC2P384 = P.CoseCurveP384
toCurveECDSA R.CoseEllipticCurveEC2P521 = P.CoseCurveP521
| null | https://raw.githubusercontent.com/tweag/webauthn/b9341781bc82ed32a8b729036ae96f636198542f/src/Crypto/WebAuthn/Cose/PublicKeyWithSignAlg.hs | haskell | # LANGUAGE TypeSynonymInstances #
| Stability: experimental
This module contains a partial implementation of the
* COSE public Key
| A combination of a t'P.PublicKey' holding the public key data and a
acdCredentialPublicKeyBytes. This would then require parametrizing
A structured and checked representation of a
[credentialPublicKey](-2/#credentialpublickey)
field.
# COMPLETE PublicKeyWithSignAlg #
| CBOR encoding as a [COSE_Key](#section-7)
-ietf-cose-rfc8152bis-algs-12#section-7.1.1
This version of i2ospOf_ throws if the bytestring is larger than
-editor.org/rfc/rfc8230.html#section-4
> The octet sequence MUST utilize the minimum
number of octets needed to represent the value.
> The keys in every map must be sorted lowest value to highest. The sorting rules are:
>
> * If the major types are different, the one with the lower value in numerical order sorts earlier.
Which aligns very nicely with the fact that common parameters use positive
parameters use negative values
-ietf-cose-rfc8152bis-struct-15#section-7.1
This parameter MUST be present in a key object.
-2/#credentialpublickey
parameter and MUST NOT contain any other OPTIONAL parameters.
[(spec)](-ietf-cose-rfc8152bis-struct-15#section-7.1)
Implementations MUST verify that the key type is appropriate for
the algorithm being processed.
-ietf-cose-rfc8152bis-algs-12#section-7.2
-ietf-cose-rfc8152bis-algs-12#section-2.1
> The 'kty' field MUST be present, and it MUST be 'EC2'.
-ietf-cose-rfc8152bis-algs-12#section-7.1.1
-editor.org/rfc/rfc8812.html#section-2
-editor.org/rfc/rfc8230.html#section-4
> The octet sequence MUST utilize the minimum number of octets needed to represent the value.
| Decode a value and ensure it's the same as the value that was given | # LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
[ COSE_Key]( / doc / html / rfc8152#section-7 ) format ,
limited to what is needed for Webauthn , and in a structured way .
module Crypto.WebAuthn.Cose.PublicKeyWithSignAlg
PublicKeyWithSignAlg (PublicKeyWithSignAlg, Crypto.WebAuthn.Cose.PublicKeyWithSignAlg.publicKey, signAlg),
CosePublicKey,
makePublicKeyWithSignAlg,
)
where
import Codec.CBOR.Decoding (Decoder, TokenType (TypeBool, TypeBytes), decodeBytesCanonical, decodeMapLenCanonical, peekTokenType)
import Codec.CBOR.Encoding (Encoding, encodeBytes, encodeMapLen)
import Codec.Serialise (Serialise (decode, encode))
import Control.Monad (unless)
import Crypto.Number.Serialize (i2osp, i2ospOf_, os2ip)
import qualified Crypto.WebAuthn.Cose.Internal.Registry as R
import qualified Crypto.WebAuthn.Cose.PublicKey as P
import qualified Crypto.WebAuthn.Cose.SignAlg as A
import Crypto.WebAuthn.Internal.ToJSONOrphans ()
import qualified Data.Aeson as Aeson
import qualified Data.ByteString as BS
import Data.Functor (($>))
import Data.Text (Text)
import qualified Data.Text as Text
import GHC.Generics (Generic)
' A.CoseSignAlg ' holding the exact signature algorithm that should be used .
This type can only be constructed with ' makePublicKeyWithSignAlg ' , which
ensures that the signature scheme matches between ' P.PublicKey ' and
' A.CoseSignAlg ' . This type is equivalent to a COSE public key , which holds
the same information , see ' CosePublicKey '
data PublicKeyWithSignAlg = PublicKeyWithSignAlgInternal
{ publicKeyInternal :: P.PublicKey,
signAlgInternal :: A.CoseSignAlg
TODO : Consider adding a RawField here to replace
' PublicKeyWithSignAlg ' with ' raw : : '
}
deriving (Eq, Show, Generic, Aeson.ToJSON)
| [ ( spec)]( / TR / webauthn-2/#credentialpublickey )
[ COSE_Key]( / doc / html / rfc8152#section-7 ) , limited
to what is know to be necessary for Webauthn public keys for the
type CosePublicKey = PublicKeyWithSignAlg
| Deconstructs a ' makePublicKeyWithSignAlg ' into its t'P.PublicKey ' and
' A.CoseSignAlg ' . Since ' makePublicKeyWithSignAlg ' can only be constructed
using ' makePublicKeyWithSignAlg ' , we can be sure that the signature scheme
of t'P.PublicKey ' and ' A.CoseSignAlg ' matches .
pattern PublicKeyWithSignAlg :: P.PublicKey -> A.CoseSignAlg -> PublicKeyWithSignAlg
pattern PublicKeyWithSignAlg {publicKey, signAlg} <- PublicKeyWithSignAlgInternal {publicKeyInternal = publicKey, signAlgInternal = signAlg}
| Constructs a t'PublicKeyWithSignAlg ' from a t'P.PublicKey ' and
' A.CoseSignAlg ' , returning an error if the signature schemes between these
two types do n't match .
makePublicKeyWithSignAlg :: P.PublicKey -> A.CoseSignAlg -> Either Text PublicKeyWithSignAlg
makePublicKeyWithSignAlg key@(P.PublicKey k) alg =
verifyValid k alg
$> PublicKeyWithSignAlgInternal
{ publicKeyInternal = key,
signAlgInternal = alg
}
where
verifyValid :: P.UncheckedPublicKey -> A.CoseSignAlg -> Either Text ()
verifyValid P.PublicKeyEdDSA {} A.CoseSignAlgEdDSA = pure ()
verifyValid P.PublicKeyEdDSA {} alg = Left $ "EdDSA public key cannot be used with signing algorithm " <> Text.pack (show alg)
verifyValid P.PublicKeyECDSA {} A.CoseSignAlgECDSA {} = pure ()
verifyValid P.PublicKeyECDSA {} alg = Left $ "ECDSA public key cannot be used with signing algorithm " <> Text.pack (show alg)
verifyValid P.PublicKeyRSA {} A.CoseSignAlgRSA {} = pure ()
verifyValid P.PublicKeyRSA {} alg = Left $ "RSA public key cannot be used with signing algorithm " <> Text.pack (show alg)
using the [ CTAP2 canonical CBOR encoding form]( / specs / fido - v2.0 - ps-20190130 / - client - to - authenticator - protocol - v2.0 - ps-20190130.html#ctap2 - canonical - cbor - encoding - form )
instance Serialise CosePublicKey where
encode PublicKeyWithSignAlg {..} = case publicKey of
P.PublicKey P.PublicKeyEdDSA {..} ->
common R.CoseKeyTypeOKP
<> encode R.CoseKeyTypeParameterOKPCrv
<> encode (fromCurveEdDSA eddsaCurve)
<> encode R.CoseKeyTypeParameterOKPX
<> encodeBytes eddsaX
P.PublicKey P.PublicKeyECDSA {..} ->
common R.CoseKeyTypeEC2
<> encode R.CoseKeyTypeParameterEC2Crv
<> encode (fromCurveECDSA ecdsaCurve)
> Leading zero octets MUST be preserved .
<> encode R.CoseKeyTypeParameterEC2X
size , but this ca n't happen due to the PublicKey invariants
<> encodeBytes (i2ospOf_ size ecdsaX)
<> encode R.CoseKeyTypeParameterEC2Y
<> encodeBytes (i2ospOf_ size ecdsaY)
where
size = P.coordinateSizeECDSA ecdsaCurve
P.PublicKey P.PublicKeyRSA {..} ->
common R.CoseKeyTypeRSA
<> encode R.CoseKeyTypeParameterRSAN
<> encodeBytes (i2osp rsaN)
<> encode R.CoseKeyTypeParameterRSAE
<> encodeBytes (i2osp rsaE)
where
common :: R.CoseKeyType -> Encoding
common kty =
encodeMapLen (R.parameterCount kty)
<> encode R.CoseKeyCommonParameterKty
<> encode kty
<> encode R.CoseKeyCommonParameterAlg
<> encode signAlg
NOTE : CBOR itself does n't give an ordering of map keys , but the CTAP2 canonical CBOR encoding form does :
> * If two keys have different lengths , the shorter one sorts earlier ;
> * If two keys have the same length , the one with the lower value in ( byte - wise ) lexical order sorts earlier .
This has the effect that numeric keys are sorted like 1 , 2 , 3 , ... , -1 , -2 , -3 , ...
values and can therefore be decoded first , while key type specific
decode = do
n <- fromIntegral <$> decodeMapLenCanonical
decodeExpected R.CoseKeyCommonParameterKty
kty <- decode
The COSE_Key - encoded credential public key MUST contain the " alg "
decodeExpected R.CoseKeyCommonParameterAlg
alg <- decode
uncheckedKey <- decodeKey n kty alg
case P.checkPublicKey uncheckedKey of
Left err -> fail $ "Key check failed: " <> Text.unpack err
Right result ->
pure $
PublicKeyWithSignAlgInternal
{ publicKeyInternal = result,
signAlgInternal = alg
}
where
decodeKey :: Word -> R.CoseKeyType -> A.CoseSignAlg -> Decoder s P.UncheckedPublicKey
decodeKey n kty alg = case alg of
A.CoseSignAlgEdDSA -> decodeEdDSAKey
A.CoseSignAlgECDSA _ -> decodeECDSAKey
A.CoseSignAlgRSA _ -> decodeRSAKey
where
checkKty :: R.CoseKeyType -> Decoder s ()
checkKty expectedKty = do
unless (expectedKty == kty) $
fail $
"Expected COSE key type "
<> show expectedKty
<> " for COSE algorithm "
<> show alg
<> " but got COSE key type "
<> show kty
<> " instead"
unless (R.parameterCount kty == n) $
fail $
"Expected CBOR map to contain "
<> show (R.parameterCount kty)
<> " parameters for COSE key type "
<> show kty
<> " but got "
<> show n
<> " parameters instead"
decodeEdDSAKey :: Decoder s P.UncheckedPublicKey
decodeEdDSAKey = do
-ietf-cose-rfc8152bis-algs-12#section-2.2
> The ' kty ' field MUST be present , and it MUST be ' OKP ' ( Octet Key Pair ) .
checkKty R.CoseKeyTypeOKP
decodeExpected R.CoseKeyTypeParameterOKPCrv
eddsaCurve <- toCurveEdDSA <$> decode
decodeExpected R.CoseKeyTypeParameterOKPX
eddsaX <- decodeBytesCanonical
pure P.PublicKeyEdDSA {..}
decodeECDSAKey :: Decoder s P.UncheckedPublicKey
decodeECDSAKey = do
checkKty R.CoseKeyTypeEC2
decodeExpected R.CoseKeyTypeParameterEC2Crv
ecdsaCurve <- toCurveECDSA <$> decode
let size = P.coordinateSizeECDSA ecdsaCurve
decodeExpected R.CoseKeyTypeParameterEC2X
ecdsaX <- os2ipWithSize size =<< decodeBytesCanonical
decodeExpected R.CoseKeyTypeParameterEC2Y
ecdsaY <-
peekTokenType >>= \case
TypeBytes -> os2ipWithSize size =<< decodeBytesCanonical
TypeBool -> fail "Compressed EC2 y coordinate not yet supported"
typ -> fail $ "Unexpected type in EC2 y parameter: " <> show typ
pure P.PublicKeyECDSA {..}
decodeRSAKey :: Decoder s P.UncheckedPublicKey
decodeRSAKey = do
> Implementations need to check that the key type is ' RSA ' when creating or verifying a signature .
checkKty R.CoseKeyTypeRSA
decodeExpected R.CoseKeyTypeParameterRSAN
rsaN <- os2ipNoLeading =<< decodeBytesCanonical
decodeExpected R.CoseKeyTypeParameterRSAE
rsaE <- os2ipNoLeading =<< decodeBytesCanonical
pure P.PublicKeyRSA {..}
| Same as ' os2ip ' , but throws an error if there are not exactly as many bytes as expected . Thus any successful result of this function will give the same ' BS.ByteString ' back if encoded with @'i2ospOf _ ' size@.
os2ipWithSize :: MonadFail m => Int -> BS.ByteString -> m Integer
os2ipWithSize size bytes
| BS.length bytes == size = pure $ os2ip bytes
| otherwise =
fail $
"bytes have length "
<> show (BS.length bytes)
<> " when length "
<> show size
<> " was expected"
| Same as ' os2ip ' , but throws an error if there are leading zero bytes . Thus any successful result of this function will give the same ' BS.ByteString ' back if encoded with ' i2osp ' .
os2ipNoLeading :: MonadFail m => BS.ByteString -> m Integer
os2ipNoLeading bytes
| leadingZeroCount == 0 = pure $ os2ip bytes
| otherwise =
fail $
"bytes of length "
<> show (BS.length bytes)
<> " has "
<> show leadingZeroCount
<> " leading zero bytes when none were expected"
where
leadingZeroCount = BS.length (BS.takeWhile (== 0) bytes)
decodeExpected :: (Show a, Eq a, Serialise a) => a -> Decoder s ()
decodeExpected expected = do
actual <- decode
unless (expected == actual) $
fail $
"Expected " <> show expected <> " but got " <> show actual
fromCurveEdDSA :: P.CoseCurveEdDSA -> R.CoseEllipticCurveOKP
fromCurveEdDSA P.CoseCurveEd25519 = R.CoseEllipticCurveEd25519
toCurveEdDSA :: R.CoseEllipticCurveOKP -> P.CoseCurveEdDSA
toCurveEdDSA R.CoseEllipticCurveEd25519 = P.CoseCurveEd25519
fromCurveECDSA :: P.CoseCurveECDSA -> R.CoseEllipticCurveEC2
fromCurveECDSA P.CoseCurveP256 = R.CoseEllipticCurveEC2P256
fromCurveECDSA P.CoseCurveP384 = R.CoseEllipticCurveEC2P384
fromCurveECDSA P.CoseCurveP521 = R.CoseEllipticCurveEC2P521
toCurveECDSA :: R.CoseEllipticCurveEC2 -> P.CoseCurveECDSA
toCurveECDSA R.CoseEllipticCurveEC2P256 = P.CoseCurveP256
toCurveECDSA R.CoseEllipticCurveEC2P384 = P.CoseCurveP384
toCurveECDSA R.CoseEllipticCurveEC2P521 = P.CoseCurveP521
|
307e69fa9098deb0fd1fe09000f1b023fbff06cbd46610d5578b37353e3ec44c | LightTable/Clojure | user.cljs | (ns user)
| null | https://raw.githubusercontent.com/LightTable/Clojure/6f335ff3bec841b24a0b8ad7ca0dc126b3352a15/lein-light-nrepl/src/user.cljs | clojure | (ns user)
|
|
f94e59ce58ad7b145d37ccd444cc94f895b1c54532815e5b475fefa746d62543 | racket/rhombus-prototype | info.rkt | #lang info
(define collection 'multi)
(define deps
'(["base" #:version "8.8.0.5"]
"syntax-color-lib"
"parser-tools-lib"
["scribble-lib" #:version "1.50"]
"sandbox-lib"
"testing-util-lib"
"draw-lib"
"gui-easy-lib"
"gui-lib"))
(define build-deps
'("at-exp-lib"
"math-lib"
"racket-doc"
"rackunit-lib"
"scribble-doc"))
(define version "0.1")
| null | https://raw.githubusercontent.com/racket/rhombus-prototype/8caedfc19a8ff60f6997fc9cd49b4a39d01f6890/info.rkt | racket | #lang info
(define collection 'multi)
(define deps
'(["base" #:version "8.8.0.5"]
"syntax-color-lib"
"parser-tools-lib"
["scribble-lib" #:version "1.50"]
"sandbox-lib"
"testing-util-lib"
"draw-lib"
"gui-easy-lib"
"gui-lib"))
(define build-deps
'("at-exp-lib"
"math-lib"
"racket-doc"
"rackunit-lib"
"scribble-doc"))
(define version "0.1")
|
|
8870360325329862bda13a5917e60c978d90662c5348df796ad3c001a3a7bb01 | practicalli/banking-on-clojure-webapp | banking_on_clojure_test.clj | (ns practicalli.banking-on-clojure-test
(:require [clojure.test :refer [deftest is testing]]
[practicalli.banking-on-clojure :as SUT]))
| null | https://raw.githubusercontent.com/practicalli/banking-on-clojure-webapp/e903e0a72f664ae8959dc5dc05fc5149cd18f422/test/practicalli/banking_on_clojure_test.clj | clojure | (ns practicalli.banking-on-clojure-test
(:require [clojure.test :refer [deftest is testing]]
[practicalli.banking-on-clojure :as SUT]))
|
|
2e7b61c587cf4727c6e7c650fa62fc48ebfc8d16594ce207beb470dc2fbc8140 | isovector/design-tools | Cache.hs | # LANGUAGE LambdaCase #
module Cache (caching, hashFile) where
import Data.Hashable
import Data.Maybe
import System.Directory
initCache :: IO ()
initCache = doesDirectoryExist cacheDir >>= \case
True -> pure ()
False -> createDirectory cacheDir
caching :: (Hashable key, Show r, Read r) => key -> IO r -> IO r
caching key m = initCache >> checkCache key >>= \case
Just x -> pure x
Nothing -> do
r <- m
writeCache key r
pure r
writeCache :: (Hashable key, Show r) => key -> r -> IO ()
writeCache key = writeFile (hashFile key) . show
checkCache :: (Read r, Hashable key) => key -> IO (Maybe r)
checkCache key = doesFileExist (hashFile key) >>= \case
False -> pure Nothing
True -> safeRead <$> readFile (hashFile key)
hashFile :: Hashable key => key -> FilePath
hashFile key = cacheDir ++ "/" ++ show (abs $ hash key)
safeRead :: Read key => String -> Maybe key
safeRead = listToMaybe . fmap fst . reads
cacheDir :: FilePath
cacheDir = "./.design-tools"
| null | https://raw.githubusercontent.com/isovector/design-tools/7e8b246a62cd7a6f1b2994ab61908568feddc86b/src/Cache.hs | haskell | # LANGUAGE LambdaCase #
module Cache (caching, hashFile) where
import Data.Hashable
import Data.Maybe
import System.Directory
initCache :: IO ()
initCache = doesDirectoryExist cacheDir >>= \case
True -> pure ()
False -> createDirectory cacheDir
caching :: (Hashable key, Show r, Read r) => key -> IO r -> IO r
caching key m = initCache >> checkCache key >>= \case
Just x -> pure x
Nothing -> do
r <- m
writeCache key r
pure r
writeCache :: (Hashable key, Show r) => key -> r -> IO ()
writeCache key = writeFile (hashFile key) . show
checkCache :: (Read r, Hashable key) => key -> IO (Maybe r)
checkCache key = doesFileExist (hashFile key) >>= \case
False -> pure Nothing
True -> safeRead <$> readFile (hashFile key)
hashFile :: Hashable key => key -> FilePath
hashFile key = cacheDir ++ "/" ++ show (abs $ hash key)
safeRead :: Read key => String -> Maybe key
safeRead = listToMaybe . fmap fst . reads
cacheDir :: FilePath
cacheDir = "./.design-tools"
|
|
1901d8f36130b799d0323254edec42021aa45d4b957dd61cb2bf0d240f657956 | elaforge/karya | DeriveFile_profile.hs | Copyright 2016
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
module Derive.DeriveFile_profile where
import qualified Data.Vector as Vector
import Util.Test
import qualified Ui.Ui as Ui
import qualified Cmd.Cmd as Cmd
import qualified Cmd.CmdTest as CmdTest
import qualified Cmd.ResponderTest as ResponderTest
import qualified Cmd.Save as Save
import qualified Derive.Cache as Cache
import qualified Derive.DeriveSaved as DeriveSaved
import qualified D
import Global
-- Run by hand to manually derive a score to see how long it takes.
profile_file = do
cmd_config <- DeriveSaved.load_cmd_config
results <- perform cmd_config "save/wayang/speed-test"
let maybe_perf = CmdTest.e_performance (D.bid "wayang/top") $
ResponderTest.result_cmd (last results)
putStrLn "perf:"
whenJust maybe_perf $ \perf -> do
putStrLn $ "events: " <> show (Vector.length (Cmd.perf_events perf))
putStrLn "logs:"
mapM_ prettyp $ filter (not . Cache.is_cache_log) (Cmd.perf_logs perf)
return ()
perform :: Cmd.Config -> FilePath -> IO [ResponderTest.Result]
perform cmd_config fname = do
let states = (Ui.empty, Cmd.initial_state cmd_config)
let continue = ResponderTest.continue_all [] 8
result <- ResponderTest.respond_cmd states $ Save.load fname
results1 <- continue result
The first one is cancelled because of loading the defs file .
results2 <- continue (last results1)
return $ results1 ++ results2
| null | https://raw.githubusercontent.com/elaforge/karya/471a2131f5a68b3b10b1a138e6f9ed1282980a18/Derive/DeriveFile_profile.hs | haskell | This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt
Run by hand to manually derive a score to see how long it takes. | Copyright 2016
module Derive.DeriveFile_profile where
import qualified Data.Vector as Vector
import Util.Test
import qualified Ui.Ui as Ui
import qualified Cmd.Cmd as Cmd
import qualified Cmd.CmdTest as CmdTest
import qualified Cmd.ResponderTest as ResponderTest
import qualified Cmd.Save as Save
import qualified Derive.Cache as Cache
import qualified Derive.DeriveSaved as DeriveSaved
import qualified D
import Global
profile_file = do
cmd_config <- DeriveSaved.load_cmd_config
results <- perform cmd_config "save/wayang/speed-test"
let maybe_perf = CmdTest.e_performance (D.bid "wayang/top") $
ResponderTest.result_cmd (last results)
putStrLn "perf:"
whenJust maybe_perf $ \perf -> do
putStrLn $ "events: " <> show (Vector.length (Cmd.perf_events perf))
putStrLn "logs:"
mapM_ prettyp $ filter (not . Cache.is_cache_log) (Cmd.perf_logs perf)
return ()
perform :: Cmd.Config -> FilePath -> IO [ResponderTest.Result]
perform cmd_config fname = do
let states = (Ui.empty, Cmd.initial_state cmd_config)
let continue = ResponderTest.continue_all [] 8
result <- ResponderTest.respond_cmd states $ Save.load fname
results1 <- continue result
The first one is cancelled because of loading the defs file .
results2 <- continue (last results1)
return $ results1 ++ results2
|
bfa5ca73a8528ebc1605e81d5d3f1c3668986e149ce8497adef78cb33a29398e | ClojureTO/JS-Workshop | project.clj | (defproject reddit-viewer "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.0" :scope "provided"]
[org.clojure/clojurescript "1.10.520" :scope "provided"]
[reagent "0.8.1"]
[cljsjs/chartjs "2.7.3-0"]
[cljs-ajax "0.8.0"]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.18"]]
:min-lein-version "2.5.0"
:source-paths ["src"]
:clean-targets ^{:protect false}
[:target-path
[:cljsbuild :builds :app :compiler :output-dir]
[:cljsbuild :builds :app :compiler :output-to]]
:resource-paths ["public"]
:figwheel {:http-server-root "."
:nrepl-port 7002
:nrepl-middleware ["cemerick.piggieback/wrap-cljs-repl"]
:css-dirs ["public/css"]}
:cljsbuild {:builds {:app
{:source-paths ["src" "env/dev/cljs"]
:compiler
{:main "reddit-viewer.dev"
:output-to "public/js/app.js"
:output-dir "public/js/out"
:asset-path "js/out"
:source-map true
:optimizations :none
:pretty-print true}
:figwheel
{:open-urls [":3449/index.html"]
:on-jsload "reddit-viewer.core/mount-root"}}
:release
{:source-paths ["src" "env/prod/cljs"]
:compiler
{:output-to "public/js/app.js"
:output-dir "public/js/release"
:asset-path "js/out"
:optimizations :advanced
:pretty-print false}}}}
:aliases {"package" ["do" "clean" ["cljsbuild" "once" "release"]]}
:profiles {:dev {:dependencies [[binaryage/devtools "0.9.10"]
[figwheel-sidecar "0.5.18"]
[nrepl "0.6.0"]
[cider/piggieback "0.4.0"]]}})
| null | https://raw.githubusercontent.com/ClojureTO/JS-Workshop/60030e0f3f0b18dc6463d393e23b14e4971f2135/project.clj | clojure | (defproject reddit-viewer "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.0" :scope "provided"]
[org.clojure/clojurescript "1.10.520" :scope "provided"]
[reagent "0.8.1"]
[cljsjs/chartjs "2.7.3-0"]
[cljs-ajax "0.8.0"]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.18"]]
:min-lein-version "2.5.0"
:source-paths ["src"]
:clean-targets ^{:protect false}
[:target-path
[:cljsbuild :builds :app :compiler :output-dir]
[:cljsbuild :builds :app :compiler :output-to]]
:resource-paths ["public"]
:figwheel {:http-server-root "."
:nrepl-port 7002
:nrepl-middleware ["cemerick.piggieback/wrap-cljs-repl"]
:css-dirs ["public/css"]}
:cljsbuild {:builds {:app
{:source-paths ["src" "env/dev/cljs"]
:compiler
{:main "reddit-viewer.dev"
:output-to "public/js/app.js"
:output-dir "public/js/out"
:asset-path "js/out"
:source-map true
:optimizations :none
:pretty-print true}
:figwheel
{:open-urls [":3449/index.html"]
:on-jsload "reddit-viewer.core/mount-root"}}
:release
{:source-paths ["src" "env/prod/cljs"]
:compiler
{:output-to "public/js/app.js"
:output-dir "public/js/release"
:asset-path "js/out"
:optimizations :advanced
:pretty-print false}}}}
:aliases {"package" ["do" "clean" ["cljsbuild" "once" "release"]]}
:profiles {:dev {:dependencies [[binaryage/devtools "0.9.10"]
[figwheel-sidecar "0.5.18"]
[nrepl "0.6.0"]
[cider/piggieback "0.4.0"]]}})
|
|
921dc7c15ee82cc4786559bf2cc2bbbd66014a972d4c6cfc48e3ff67f3a848b9 | helium/blockchain-core | blockchain_txn_poc_request_v1.erl | %%%-------------------------------------------------------------------
%% @doc
%% == Blockchain Transaction Create Proof of Coverage Request ==
Submitted by a gateway who wishes to initiate a PoC Challenge
%%%-------------------------------------------------------------------
-module(blockchain_txn_poc_request_v1).
-behavior(blockchain_txn).
-behavior(blockchain_json).
-include("blockchain_caps.hrl").
-include("blockchain_json.hrl").
-include_lib("helium_proto/include/blockchain_txn_poc_request_v1_pb.hrl").
-include("blockchain_vars.hrl").
-include("blockchain_utils.hrl").
-export([
new/5,
get_version/1,
hash/1,
challenger/1,
secret_hash/1,
onion_key_hash/1,
block_hash/1,
signature/1,
version/1,
fee/1,
fee_payer/2,
sign/2,
is_valid/2,
absorb/2,
print/1,
json_type/0,
to_json/2
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type txn_poc_request() :: #blockchain_txn_poc_request_v1_pb{}.
-export_type([txn_poc_request/0]).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec new(libp2p_crypto:pubkey_bin(), binary(), binary(), binary(),
non_neg_integer()) -> txn_poc_request().
new(Challenger, SecretHash, OnionKeyHash, BlockHash, Version) ->
#blockchain_txn_poc_request_v1_pb{
challenger=Challenger,
secret_hash=SecretHash,
onion_key_hash=OnionKeyHash,
block_hash=BlockHash,
fee=0,
signature = <<>>,
version = Version
}.
-spec get_version(blockchain:ledger()) -> integer().
get_version(Ledger) ->
{ok, Mod} = ?get_var(?predicate_callback_mod, Ledger),
{ok, Fun} = ?get_var(?predicate_callback_fun, Ledger),
Mod:Fun().
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec hash(txn_poc_request()) -> blockchain_txn:hash().
hash(Txn) ->
BaseTxn = Txn#blockchain_txn_poc_request_v1_pb{signature = <<>>},
EncodedTxn = blockchain_txn_poc_request_v1_pb:encode_msg(BaseTxn),
crypto:hash(sha256, EncodedTxn).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec challenger(txn_poc_request()) -> libp2p_crypto:pubkey_bin().
challenger(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.challenger.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec secret_hash(txn_poc_request()) -> blockchain_txn:hash().
secret_hash(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.secret_hash.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec onion_key_hash(txn_poc_request()) -> binary().
onion_key_hash(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.onion_key_hash.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec block_hash(txn_poc_request()) -> binary().
block_hash(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.block_hash.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec fee(txn_poc_request()) -> 0.
fee(_Txn) ->
0.
-spec fee_payer(txn_poc_request(), blockchain_ledger_v1:ledger()) -> libp2p_crypto:pubkey_bin() | undefined.
fee_payer(_Txn, _Ledger) ->
undefined.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec signature(txn_poc_request()) -> binary().
signature(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.signature.
-spec version(txn_poc_request()) -> non_neg_integer().
version(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.version.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec sign(txn_poc_request(), libp2p_crypto:sig_fun()) -> txn_poc_request().
sign(Txn0, SigFun) ->
Txn1 = Txn0#blockchain_txn_poc_request_v1_pb{signature = <<>>},
EncodedTxn = blockchain_txn_poc_request_v1_pb:encode_msg(Txn1),
Txn0#blockchain_txn_poc_request_v1_pb{signature=SigFun(EncodedTxn)}.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec is_valid(txn_poc_request(), blockchain:blockchain()) -> ok | {error, atom()} | {error, {atom(), any()}}.
is_valid(Txn, Chain) ->
Ledger = blockchain:ledger(Chain),
Challenger = ?MODULE:challenger(Txn),
ChallengerSignature = ?MODULE:signature(Txn),
PubKey = libp2p_crypto:bin_to_pubkey(Challenger),
BaseTxn = Txn#blockchain_txn_poc_request_v1_pb{signature = <<>>},
EncodedTxn = blockchain_txn_poc_request_v1_pb:encode_msg(BaseTxn),
case blockchain_txn:validate_fields([{{secret_hash, ?MODULE:secret_hash(Txn)}, {binary, 32}},
{{onion_key_hash, ?MODULE:secret_hash(Txn)}, {binary, 32}},
{{block_hash, ?MODULE:secret_hash(Txn)}, {binary, 32}}]) of
ok ->
case libp2p_crypto:verify(EncodedTxn, ChallengerSignature, PubKey) of
false ->
{error, bad_signature};
true ->
StartFind = maybe_start_duration(),
case blockchain_ledger_v1:find_gateway_info(Challenger, Ledger) of
{error, not_found} ->
{error, missing_gateway};
{error, _Reason}=Error ->
Error;
{ok, Info} ->
StartCap = maybe_log_duration(fetch_gw, StartFind),
check the gateway mode to determine if its allowed to issue POC requests
Mode = blockchain_ledger_gateway_v2:mode(Info),
case blockchain_ledger_gateway_v2:is_valid_capability(Mode, ?GW_CAPABILITY_POC_CHALLENGER, Ledger) of
false -> {error, {gateway_not_allowed, blockchain_ledger_gateway_v2:mode(Info)}};
true ->
StartRest = maybe_log_duration(check_cap, StartCap),
case blockchain_ledger_gateway_v2:location(Info) of
undefined ->
lager:info("no loc for challenger: ~p ~p", [Challenger, Info]),
{error, no_gateway_location};
_Location ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
LastChallenge = blockchain_ledger_gateway_v2:last_poc_challenge(Info),
PoCInterval = blockchain_utils:challenge_interval(Ledger),
case LastChallenge == undefined orelse LastChallenge =< (Height+1 - PoCInterval) of
false ->
{error, too_many_challenges};
true ->
BlockHash = ?MODULE:block_hash(Txn),
case blockchain:get_block_height(BlockHash, Chain) of
{error, not_found} ->
{error, missing_challenge_block_hash};
{error, _}=Error ->
Error;
{ok, BlockHeight} ->
case (BlockHeight + PoCInterval) > (Height+1) of
false ->
{error, replaying_request};
true ->
Fee = ?MODULE:fee(Txn),
Owner = blockchain_ledger_gateway_v2:owner_address(Info),
R = blockchain_ledger_v1:check_dc_balance(Owner, Fee, Ledger),
maybe_log_duration(rest, StartRest),
R
end
end
end
end
end
end
end;
Error -> Error
end.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec absorb(txn_poc_request(), blockchain:blockchain()) -> ok | {error, atom()} | {error, {atom(), any()}}.
absorb(Txn, Chain) ->
Ledger = blockchain:ledger(Chain),
Challenger = ?MODULE:challenger(Txn),
Version = version(Txn),
SecretHash = ?MODULE:secret_hash(Txn),
OnionKeyHash = ?MODULE:onion_key_hash(Txn),
BlockHash = ?MODULE:block_hash(Txn),
blockchain_ledger_v1:request_poc(OnionKeyHash, SecretHash, Challenger, BlockHash, Version, Ledger).
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
-spec print(txn_poc_request()) -> iodata().
print(undefined) -> <<"type=poc_request, undefined">>;
print(#blockchain_txn_poc_request_v1_pb{challenger=Challenger, secret_hash=SecretHash,
onion_key_hash=OnionKeyHash, block_hash=BlockHash,
fee=Fee, signature = Sig, version = Version }) ->
%% XXX: Should we really print the secret hash in a log???
io_lib:format("type=poc_request challenger=~p, secret_hash=~p, onion_key_hash=~p, block_hash=~p, fee=~p, signature=~p, version=~p",
[?TO_ANIMAL_NAME(Challenger), SecretHash, ?TO_B58(OnionKeyHash), BlockHash, Fee, Sig, Version]).
json_type() ->
<<"poc_request_v1">>.
-spec to_json(txn_poc_request(), blockchain_json:opts()) -> blockchain_json:json_object().
to_json(Txn, _Opts) ->
#{
type => ?MODULE:json_type(),
hash => ?BIN_TO_B64(hash(Txn)),
challenger => ?BIN_TO_B58(challenger(Txn)),
secret_hash => ?BIN_TO_B64(secret_hash(Txn)),
onion_key_hash => ?BIN_TO_B64(onion_key_hash(Txn)),
block_hash => ?BIN_TO_B64(block_hash(Txn)),
version => version(Txn),
fee => fee(Txn)
}.
%% TODO: I'm not sure that this is actually faster than checking the time, but I suspect that it'll
%% be more lock-friendly?
maybe_start_duration() ->
case application:get_env(blockchain, log_validation_times, false) of
true ->
erlang:monotonic_time(microsecond);
_ -> 0
end.
maybe_log_duration(Type, Start) ->
case application:get_env(blockchain, log_validation_times, false) of
true ->
End = erlang:monotonic_time(microsecond),
lager:info("~p took ~p ms", [Type, End - Start]),
End;
_ -> ok
end.
%% ------------------------------------------------------------------
EUNIT Tests
%% ------------------------------------------------------------------
-ifdef(TEST).
new_test() ->
Tx = #blockchain_txn_poc_request_v1_pb{
challenger= <<"gateway">>,
secret_hash= <<"hash">>,
onion_key_hash = <<"onion">>,
block_hash = <<"block">>,
fee=0,
signature= <<>>,
version = 1
},
?assertEqual(Tx, new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1)).
challenger_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<"gateway">>, challenger(Tx)).
secret_hash_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<"hash">>, secret_hash(Tx)).
onion_key_hash_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<"onion">>, onion_key_hash(Tx)).
block_hash_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<"block">>, block_hash(Tx)).
fee_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(0, fee(Tx)).
signature_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<>>, signature(Tx)).
sign_test() ->
#{public := PubKey, secret := PrivKey} = libp2p_crypto:generate_keys(ecc_compact),
Tx0 = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
ChallengerSigFun = libp2p_crypto:mk_sig_fun(PrivKey),
Tx1 = sign(Tx0, ChallengerSigFun),
EncodedTx1 = blockchain_txn_poc_request_v1_pb:encode_msg(
Tx1#blockchain_txn_poc_request_v1_pb{signature = <<>>}
),
?assert(libp2p_crypto:verify(EncodedTx1, signature(Tx1), PubKey)).
to_json_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
Json = to_json(Tx, []),
?assert(lists:all(fun(K) -> maps:is_key(K, Json) end,
[type, hash, challenger, secret_hash, onion_key_hash, block_hash, version, fee])).
-endif.
| null | https://raw.githubusercontent.com/helium/blockchain-core/0caf2295d0576c0ef803258e834bf6ec3b3e74bc/src/transactions/v1/blockchain_txn_poc_request_v1.erl | erlang | -------------------------------------------------------------------
@doc
== Blockchain Transaction Create Proof of Coverage Request ==
-------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
XXX: Should we really print the secret hash in a log???
TODO: I'm not sure that this is actually faster than checking the time, but I suspect that it'll
be more lock-friendly?
------------------------------------------------------------------
------------------------------------------------------------------ | Submitted by a gateway who wishes to initiate a PoC Challenge
-module(blockchain_txn_poc_request_v1).
-behavior(blockchain_txn).
-behavior(blockchain_json).
-include("blockchain_caps.hrl").
-include("blockchain_json.hrl").
-include_lib("helium_proto/include/blockchain_txn_poc_request_v1_pb.hrl").
-include("blockchain_vars.hrl").
-include("blockchain_utils.hrl").
-export([
new/5,
get_version/1,
hash/1,
challenger/1,
secret_hash/1,
onion_key_hash/1,
block_hash/1,
signature/1,
version/1,
fee/1,
fee_payer/2,
sign/2,
is_valid/2,
absorb/2,
print/1,
json_type/0,
to_json/2
]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type txn_poc_request() :: #blockchain_txn_poc_request_v1_pb{}.
-export_type([txn_poc_request/0]).
-spec new(libp2p_crypto:pubkey_bin(), binary(), binary(), binary(),
non_neg_integer()) -> txn_poc_request().
new(Challenger, SecretHash, OnionKeyHash, BlockHash, Version) ->
#blockchain_txn_poc_request_v1_pb{
challenger=Challenger,
secret_hash=SecretHash,
onion_key_hash=OnionKeyHash,
block_hash=BlockHash,
fee=0,
signature = <<>>,
version = Version
}.
-spec get_version(blockchain:ledger()) -> integer().
get_version(Ledger) ->
{ok, Mod} = ?get_var(?predicate_callback_mod, Ledger),
{ok, Fun} = ?get_var(?predicate_callback_fun, Ledger),
Mod:Fun().
-spec hash(txn_poc_request()) -> blockchain_txn:hash().
hash(Txn) ->
BaseTxn = Txn#blockchain_txn_poc_request_v1_pb{signature = <<>>},
EncodedTxn = blockchain_txn_poc_request_v1_pb:encode_msg(BaseTxn),
crypto:hash(sha256, EncodedTxn).
-spec challenger(txn_poc_request()) -> libp2p_crypto:pubkey_bin().
challenger(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.challenger.
-spec secret_hash(txn_poc_request()) -> blockchain_txn:hash().
secret_hash(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.secret_hash.
-spec onion_key_hash(txn_poc_request()) -> binary().
onion_key_hash(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.onion_key_hash.
-spec block_hash(txn_poc_request()) -> binary().
block_hash(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.block_hash.
-spec fee(txn_poc_request()) -> 0.
fee(_Txn) ->
0.
-spec fee_payer(txn_poc_request(), blockchain_ledger_v1:ledger()) -> libp2p_crypto:pubkey_bin() | undefined.
fee_payer(_Txn, _Ledger) ->
undefined.
-spec signature(txn_poc_request()) -> binary().
signature(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.signature.
-spec version(txn_poc_request()) -> non_neg_integer().
version(Txn) ->
Txn#blockchain_txn_poc_request_v1_pb.version.
-spec sign(txn_poc_request(), libp2p_crypto:sig_fun()) -> txn_poc_request().
sign(Txn0, SigFun) ->
Txn1 = Txn0#blockchain_txn_poc_request_v1_pb{signature = <<>>},
EncodedTxn = blockchain_txn_poc_request_v1_pb:encode_msg(Txn1),
Txn0#blockchain_txn_poc_request_v1_pb{signature=SigFun(EncodedTxn)}.
-spec is_valid(txn_poc_request(), blockchain:blockchain()) -> ok | {error, atom()} | {error, {atom(), any()}}.
is_valid(Txn, Chain) ->
Ledger = blockchain:ledger(Chain),
Challenger = ?MODULE:challenger(Txn),
ChallengerSignature = ?MODULE:signature(Txn),
PubKey = libp2p_crypto:bin_to_pubkey(Challenger),
BaseTxn = Txn#blockchain_txn_poc_request_v1_pb{signature = <<>>},
EncodedTxn = blockchain_txn_poc_request_v1_pb:encode_msg(BaseTxn),
case blockchain_txn:validate_fields([{{secret_hash, ?MODULE:secret_hash(Txn)}, {binary, 32}},
{{onion_key_hash, ?MODULE:secret_hash(Txn)}, {binary, 32}},
{{block_hash, ?MODULE:secret_hash(Txn)}, {binary, 32}}]) of
ok ->
case libp2p_crypto:verify(EncodedTxn, ChallengerSignature, PubKey) of
false ->
{error, bad_signature};
true ->
StartFind = maybe_start_duration(),
case blockchain_ledger_v1:find_gateway_info(Challenger, Ledger) of
{error, not_found} ->
{error, missing_gateway};
{error, _Reason}=Error ->
Error;
{ok, Info} ->
StartCap = maybe_log_duration(fetch_gw, StartFind),
check the gateway mode to determine if its allowed to issue POC requests
Mode = blockchain_ledger_gateway_v2:mode(Info),
case blockchain_ledger_gateway_v2:is_valid_capability(Mode, ?GW_CAPABILITY_POC_CHALLENGER, Ledger) of
false -> {error, {gateway_not_allowed, blockchain_ledger_gateway_v2:mode(Info)}};
true ->
StartRest = maybe_log_duration(check_cap, StartCap),
case blockchain_ledger_gateway_v2:location(Info) of
undefined ->
lager:info("no loc for challenger: ~p ~p", [Challenger, Info]),
{error, no_gateway_location};
_Location ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
LastChallenge = blockchain_ledger_gateway_v2:last_poc_challenge(Info),
PoCInterval = blockchain_utils:challenge_interval(Ledger),
case LastChallenge == undefined orelse LastChallenge =< (Height+1 - PoCInterval) of
false ->
{error, too_many_challenges};
true ->
BlockHash = ?MODULE:block_hash(Txn),
case blockchain:get_block_height(BlockHash, Chain) of
{error, not_found} ->
{error, missing_challenge_block_hash};
{error, _}=Error ->
Error;
{ok, BlockHeight} ->
case (BlockHeight + PoCInterval) > (Height+1) of
false ->
{error, replaying_request};
true ->
Fee = ?MODULE:fee(Txn),
Owner = blockchain_ledger_gateway_v2:owner_address(Info),
R = blockchain_ledger_v1:check_dc_balance(Owner, Fee, Ledger),
maybe_log_duration(rest, StartRest),
R
end
end
end
end
end
end
end;
Error -> Error
end.
-spec absorb(txn_poc_request(), blockchain:blockchain()) -> ok | {error, atom()} | {error, {atom(), any()}}.
absorb(Txn, Chain) ->
Ledger = blockchain:ledger(Chain),
Challenger = ?MODULE:challenger(Txn),
Version = version(Txn),
SecretHash = ?MODULE:secret_hash(Txn),
OnionKeyHash = ?MODULE:onion_key_hash(Txn),
BlockHash = ?MODULE:block_hash(Txn),
blockchain_ledger_v1:request_poc(OnionKeyHash, SecretHash, Challenger, BlockHash, Version, Ledger).
-spec print(txn_poc_request()) -> iodata().
print(undefined) -> <<"type=poc_request, undefined">>;
print(#blockchain_txn_poc_request_v1_pb{challenger=Challenger, secret_hash=SecretHash,
onion_key_hash=OnionKeyHash, block_hash=BlockHash,
fee=Fee, signature = Sig, version = Version }) ->
io_lib:format("type=poc_request challenger=~p, secret_hash=~p, onion_key_hash=~p, block_hash=~p, fee=~p, signature=~p, version=~p",
[?TO_ANIMAL_NAME(Challenger), SecretHash, ?TO_B58(OnionKeyHash), BlockHash, Fee, Sig, Version]).
json_type() ->
<<"poc_request_v1">>.
-spec to_json(txn_poc_request(), blockchain_json:opts()) -> blockchain_json:json_object().
to_json(Txn, _Opts) ->
#{
type => ?MODULE:json_type(),
hash => ?BIN_TO_B64(hash(Txn)),
challenger => ?BIN_TO_B58(challenger(Txn)),
secret_hash => ?BIN_TO_B64(secret_hash(Txn)),
onion_key_hash => ?BIN_TO_B64(onion_key_hash(Txn)),
block_hash => ?BIN_TO_B64(block_hash(Txn)),
version => version(Txn),
fee => fee(Txn)
}.
maybe_start_duration() ->
case application:get_env(blockchain, log_validation_times, false) of
true ->
erlang:monotonic_time(microsecond);
_ -> 0
end.
maybe_log_duration(Type, Start) ->
case application:get_env(blockchain, log_validation_times, false) of
true ->
End = erlang:monotonic_time(microsecond),
lager:info("~p took ~p ms", [Type, End - Start]),
End;
_ -> ok
end.
EUNIT Tests
-ifdef(TEST).
new_test() ->
Tx = #blockchain_txn_poc_request_v1_pb{
challenger= <<"gateway">>,
secret_hash= <<"hash">>,
onion_key_hash = <<"onion">>,
block_hash = <<"block">>,
fee=0,
signature= <<>>,
version = 1
},
?assertEqual(Tx, new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1)).
challenger_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<"gateway">>, challenger(Tx)).
secret_hash_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<"hash">>, secret_hash(Tx)).
onion_key_hash_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<"onion">>, onion_key_hash(Tx)).
block_hash_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<"block">>, block_hash(Tx)).
fee_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(0, fee(Tx)).
signature_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
?assertEqual(<<>>, signature(Tx)).
sign_test() ->
#{public := PubKey, secret := PrivKey} = libp2p_crypto:generate_keys(ecc_compact),
Tx0 = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
ChallengerSigFun = libp2p_crypto:mk_sig_fun(PrivKey),
Tx1 = sign(Tx0, ChallengerSigFun),
EncodedTx1 = blockchain_txn_poc_request_v1_pb:encode_msg(
Tx1#blockchain_txn_poc_request_v1_pb{signature = <<>>}
),
?assert(libp2p_crypto:verify(EncodedTx1, signature(Tx1), PubKey)).
to_json_test() ->
Tx = new(<<"gateway">>, <<"hash">>, <<"onion">>, <<"block">>, 1),
Json = to_json(Tx, []),
?assert(lists:all(fun(K) -> maps:is_key(K, Json) end,
[type, hash, challenger, secret_hash, onion_key_hash, block_hash, version, fee])).
-endif.
|
d13ea737a07349532215f2f197d7dfcb7a457cb7a72aa056fde0091b75e1ea1c | jarohen/yoyo | reresolve.cljc | (ns yoyo.reresolve)
(defn with-reresolve [v]
(cond
(var? v) #?(:clj
(with-reresolve (symbol (str (ns-name (:ns (meta v))))
(str (:name (meta v)))))
:cljs v)
#?@(:clj [(symbol? v) (let [v-ns (symbol (namespace v))
v-name (symbol (name v))]
(fn [& args]
(require v-ns)
(apply (or (ns-resolve (find-ns v-ns)
v-name)
(println "uh oh!")
(throw (ex-info "Can't resolve system-fn!"
{:sym v})))
args)))])
:else v))
| null | https://raw.githubusercontent.com/jarohen/yoyo/b579d21becd06b5330dee9f5963708db03ce1e25/core/src/yoyo/reresolve.cljc | clojure | (ns yoyo.reresolve)
(defn with-reresolve [v]
(cond
(var? v) #?(:clj
(with-reresolve (symbol (str (ns-name (:ns (meta v))))
(str (:name (meta v)))))
:cljs v)
#?@(:clj [(symbol? v) (let [v-ns (symbol (namespace v))
v-name (symbol (name v))]
(fn [& args]
(require v-ns)
(apply (or (ns-resolve (find-ns v-ns)
v-name)
(println "uh oh!")
(throw (ex-info "Can't resolve system-fn!"
{:sym v})))
args)))])
:else v))
|
|
f7477f99ea4b98d22bf5939a03e1dbc356396fd0568bf098a6649422d86239d9 | mainej/schema-voyager | release.clj | (ns release
(:require [clojure.tools.build.api :as b]
[org.corfield.build :as bb]
[clojure.string :as string]))
(def ^:private lib 'com.github.mainej/schema-voyager)
(def ^:private rev-count (Integer/parseInt (b/git-count-revs nil)))
(def ^:private semantic-version "2.0")
(defn- format-version [revision] (format "%s.%s" semantic-version revision))
(def ^:private version (format-version rev-count))
(def ^:private next-version (format-version (inc rev-count)))
(def ^:private tag (str "v" version))
(def ^:private basis (b/create-basis {:aliases [:release-deps]}))
(defn- die
([message & args]
(die (apply format message args)))
([message]
(binding [*out* *err*]
(println message))
(System/exit 1)))
(defn- git [command args]
(b/process (assoc args :command-args (into ["git"] command))))
(defn- git-rev []
(let [{:keys [exit out]} (git ["rev-parse" "HEAD"] {:out :capture})]
(when (zero? exit)
(string/trim out))))
(defn- git-push [params]
(println "\nSyncing with github...")
(when-not (and (zero? (:exit (git ["push" "origin" tag] {})))
(zero? (:exit (git ["push" "origin"] {})))
(zero? (:exit (git ["push" "origin" "gh-pages"] {}))))
(die "\nCouldn't sync with github."))
params)
(defn- assert-clojars-creds [params]
(when-not (System/getenv "CLOJARS_USERNAME")
(die "\nMissing required CLOJARS_* credentials."))
params)
(defn- assert-changelog-updated [params]
(println "\nChecking that CHANGELOG references tag...")
(when-not (string/includes? (slurp "CHANGELOG.md") tag)
(die (string/join "\n"
["CHANGELOG.md must include tag."
" * If you will amend the current commit, use version %s"
" * If you intend to create a new commit, use version %s"])
version next-version))
params)
(defn- scm-clean?
([] (scm-clean? {}))
([opts]
(string/blank? (:out (git ["status" "--porcelain"] (assoc opts :out :capture))))))
(defn- assert-scm-clean [params]
(println "\nChecking that working directory is clean...")
(when-not (scm-clean?)
(die "\nGit working directory must be clean. Run `git commit`"))
params)
(defn- assert-scm-tagged [params]
(println "\nChecking that tag exists and is on HEAD...")
(when-not (zero? (:exit (git ["rev-list" tag] {:out :ignore})))
(die "\nGit tag %s must exist. Run `bin/release/tag`" tag))
(let [{:keys [exit out]} (git ["describe" "--tags" "--abbrev=0" "--exact-match"] {:out :capture})]
(when-not (and (zero? exit)
(= (string/trim out) tag))
(die (string/join "\n"
[""
"Git tag %s must be on HEAD."
""
"Proceed with caution, because this tag may have already been released. If you've determined it's safe, run `git tag -d %s` before re-running `bin/tag-release`."])
tag tag)))
params)
(defn- build-template "Create the template html file" [params]
(println "\nBuilding template html...")
(when-not (zero? (:exit (b/process {:command-args ["clojure" "-X:build-template"]})))
(die "\nCould not build template html."))
params)
(defn- copy-template-to-jar-resources [params]
;; The template file is Git-ignored. During a release we put it in the classes
;; directory so that it is available when Schema Voyager is used as a
;; dependency. (It's used by `standalone`, the primary interface into Schema
Voyager ) . This lets us keep the large template file out of version control .
;; IMPORTANT: keep this in sync with
;; `schema-voyager.template.config/template-file-name`. We intentionally do
;; not depend on `schema-voyager.template.config`, so that the release can be
;; run as `clojure -T:release`, i.e. as a tool without other dependencies.
(b/copy-file {:src "resources/standalone-template.html"
:target "target/classes/standalone-template.html"})
params)
(defn- build-standalone-example [file sources]
;; expects _site to have been initialized:
;; git fetch origin gh-pages
;; git worktree add _site gh-pages
(let [params {:sources sources
:output-path (str "_site/" file)}]
(when-not (-> (b/process {:command-args ["clojure" "-X:cli" "standalone" (str params)]})
:exit
zero?)
(die "\nCouldn't create %s" file))))
(defn- build-standalone-examples [params]
(println "\nBuilding sample projects for GitHub Pages...")
(build-standalone-example "mbrainz-schema.html"
[{:file/name "resources/mbrainz-schema/schema.edn"}
{:file/name "resources/mbrainz-schema/enums.edn"}
{:file/name "resources/mbrainz-schema/supplemental.edn"}])
A meta view of Datomic 's schema
(build-standalone-example "datomic-schema.html"
[{:file/name "resources/datomic-schema/schema.edn"}
{:file/name "resources/datomic-schema/fixes.edn"}
{:file/name "resources/datomic-schema/supplemental.edn"}])
A meta view of Schema Voyager . Shows Datomic properties and supplemental
;; Schema Voyager properties and their relationships.
(build-standalone-example "schema-voyager-schema.html"
[{:file/name "resources/datomic-schema/schema.edn"}
{:file/name "resources/datomic-schema/fixes.edn"}
{:file/name "resources/datomic-schema/supplemental.edn"}
{:file/name "resources/schema-voyager-schema/schema.edn"}
{:file/name "resources/schema-voyager-schema/supplemental.edn"}])
(when-not (or (scm-clean? {:dir "./_site"})
(zero? (:exit (git ["commit" "-a" "--no-gpg-sign" "-m" "Deploy updates"]
{:dir "./_site"}))))
(die "\nCouldn't commit GitHub Pages"))
params)
#_{:clj-kondo/ignore #{:clojure-lsp/unused-public-var}}
(defn tag-release
"Tag the HEAD commit for the current release."
[params]
(when-not (zero? (:exit (git ["tag" "-a" tag "-m" tag] {})))
(die "\nCouldn't create tag %s." tag))
params)
(defn run-tests [params]
(-> params bb/run-tests))
(defn check-release
"Check that the library is ready to be released.
* Tests pass
* No outstanding commits
* Git tag for current release exists in local repo
* CHANGELOG.md references new tag"
[params]
(-> params
(run-tests)
(assert-changelog-updated)
;; after assertions about content, so any change can be committed/amended
(assert-scm-clean)
;; last, so that correct commit is tagged
(assert-scm-tagged)))
(defn jar
"Build the JAR, along with the template HTML resource."
[params]
(-> params
(assoc :lib lib
:version version
:src-dirs ["src/core"] ;; src/build and src/web are only needed in dev
:resource-dirs [] ;; ignore resources, which are only needed in dev
:basis basis
:tag (git-rev))
(build-template)
(copy-template-to-jar-resources)
(bb/jar)))
#_{:clj-kondo/ignore #{:clojure-lsp/unused-public-var}}
(defn install
"Build the JAR, and install it to the local maven repository."
[params]
(-> params
(assoc :lib lib :version version)
(bb/clean)
(jar)
(bb/install)))
#_{:clj-kondo/ignore #{:clojure-lsp/unused-public-var}}
(defn release
"Release the library.
* Confirm that we are ready to release
* Build template file
* Build JAR, including the template
* Build the content for GitHub Pages from the template
* Deploy the JAR to Clojars
* Ensure everything is available on Github"
[params]
(let [params (assoc params :lib lib :version version)]
(-> params
(assert-clojars-creds)
(bb/clean)
(check-release)
(jar)
;; After jar (and more importantly build-template), so that examples agree
;; with released template.
(build-standalone-examples)
(bb/deploy)
(git-push))
(println "\nDone")
params))
| null | https://raw.githubusercontent.com/mainej/schema-voyager/eaf0367ec639f5a2e9238a5b1fbbb2fc2d76d520/release.clj | clojure | The template file is Git-ignored. During a release we put it in the classes
directory so that it is available when Schema Voyager is used as a
dependency. (It's used by `standalone`, the primary interface into Schema
IMPORTANT: keep this in sync with
`schema-voyager.template.config/template-file-name`. We intentionally do
not depend on `schema-voyager.template.config`, so that the release can be
run as `clojure -T:release`, i.e. as a tool without other dependencies.
expects _site to have been initialized:
git fetch origin gh-pages
git worktree add _site gh-pages
Schema Voyager properties and their relationships.
after assertions about content, so any change can be committed/amended
last, so that correct commit is tagged
src/build and src/web are only needed in dev
ignore resources, which are only needed in dev
After jar (and more importantly build-template), so that examples agree
with released template. | (ns release
(:require [clojure.tools.build.api :as b]
[org.corfield.build :as bb]
[clojure.string :as string]))
(def ^:private lib 'com.github.mainej/schema-voyager)
(def ^:private rev-count (Integer/parseInt (b/git-count-revs nil)))
(def ^:private semantic-version "2.0")
(defn- format-version [revision] (format "%s.%s" semantic-version revision))
(def ^:private version (format-version rev-count))
(def ^:private next-version (format-version (inc rev-count)))
(def ^:private tag (str "v" version))
(def ^:private basis (b/create-basis {:aliases [:release-deps]}))
(defn- die
([message & args]
(die (apply format message args)))
([message]
(binding [*out* *err*]
(println message))
(System/exit 1)))
(defn- git [command args]
(b/process (assoc args :command-args (into ["git"] command))))
(defn- git-rev []
(let [{:keys [exit out]} (git ["rev-parse" "HEAD"] {:out :capture})]
(when (zero? exit)
(string/trim out))))
(defn- git-push [params]
(println "\nSyncing with github...")
(when-not (and (zero? (:exit (git ["push" "origin" tag] {})))
(zero? (:exit (git ["push" "origin"] {})))
(zero? (:exit (git ["push" "origin" "gh-pages"] {}))))
(die "\nCouldn't sync with github."))
params)
(defn- assert-clojars-creds [params]
(when-not (System/getenv "CLOJARS_USERNAME")
(die "\nMissing required CLOJARS_* credentials."))
params)
(defn- assert-changelog-updated [params]
(println "\nChecking that CHANGELOG references tag...")
(when-not (string/includes? (slurp "CHANGELOG.md") tag)
(die (string/join "\n"
["CHANGELOG.md must include tag."
" * If you will amend the current commit, use version %s"
" * If you intend to create a new commit, use version %s"])
version next-version))
params)
(defn- scm-clean?
([] (scm-clean? {}))
([opts]
(string/blank? (:out (git ["status" "--porcelain"] (assoc opts :out :capture))))))
(defn- assert-scm-clean [params]
(println "\nChecking that working directory is clean...")
(when-not (scm-clean?)
(die "\nGit working directory must be clean. Run `git commit`"))
params)
(defn- assert-scm-tagged [params]
(println "\nChecking that tag exists and is on HEAD...")
(when-not (zero? (:exit (git ["rev-list" tag] {:out :ignore})))
(die "\nGit tag %s must exist. Run `bin/release/tag`" tag))
(let [{:keys [exit out]} (git ["describe" "--tags" "--abbrev=0" "--exact-match"] {:out :capture})]
(when-not (and (zero? exit)
(= (string/trim out) tag))
(die (string/join "\n"
[""
"Git tag %s must be on HEAD."
""
"Proceed with caution, because this tag may have already been released. If you've determined it's safe, run `git tag -d %s` before re-running `bin/tag-release`."])
tag tag)))
params)
(defn- build-template "Create the template html file" [params]
(println "\nBuilding template html...")
(when-not (zero? (:exit (b/process {:command-args ["clojure" "-X:build-template"]})))
(die "\nCould not build template html."))
params)
(defn- copy-template-to-jar-resources [params]
Voyager ) . This lets us keep the large template file out of version control .
(b/copy-file {:src "resources/standalone-template.html"
:target "target/classes/standalone-template.html"})
params)
(defn- build-standalone-example [file sources]
(let [params {:sources sources
:output-path (str "_site/" file)}]
(when-not (-> (b/process {:command-args ["clojure" "-X:cli" "standalone" (str params)]})
:exit
zero?)
(die "\nCouldn't create %s" file))))
(defn- build-standalone-examples [params]
(println "\nBuilding sample projects for GitHub Pages...")
(build-standalone-example "mbrainz-schema.html"
[{:file/name "resources/mbrainz-schema/schema.edn"}
{:file/name "resources/mbrainz-schema/enums.edn"}
{:file/name "resources/mbrainz-schema/supplemental.edn"}])
A meta view of Datomic 's schema
(build-standalone-example "datomic-schema.html"
[{:file/name "resources/datomic-schema/schema.edn"}
{:file/name "resources/datomic-schema/fixes.edn"}
{:file/name "resources/datomic-schema/supplemental.edn"}])
A meta view of Schema Voyager . Shows Datomic properties and supplemental
(build-standalone-example "schema-voyager-schema.html"
[{:file/name "resources/datomic-schema/schema.edn"}
{:file/name "resources/datomic-schema/fixes.edn"}
{:file/name "resources/datomic-schema/supplemental.edn"}
{:file/name "resources/schema-voyager-schema/schema.edn"}
{:file/name "resources/schema-voyager-schema/supplemental.edn"}])
(when-not (or (scm-clean? {:dir "./_site"})
(zero? (:exit (git ["commit" "-a" "--no-gpg-sign" "-m" "Deploy updates"]
{:dir "./_site"}))))
(die "\nCouldn't commit GitHub Pages"))
params)
#_{:clj-kondo/ignore #{:clojure-lsp/unused-public-var}}
(defn tag-release
"Tag the HEAD commit for the current release."
[params]
(when-not (zero? (:exit (git ["tag" "-a" tag "-m" tag] {})))
(die "\nCouldn't create tag %s." tag))
params)
(defn run-tests [params]
(-> params bb/run-tests))
(defn check-release
"Check that the library is ready to be released.
* Tests pass
* No outstanding commits
* Git tag for current release exists in local repo
* CHANGELOG.md references new tag"
[params]
(-> params
(run-tests)
(assert-changelog-updated)
(assert-scm-clean)
(assert-scm-tagged)))
(defn jar
"Build the JAR, along with the template HTML resource."
[params]
(-> params
(assoc :lib lib
:version version
:basis basis
:tag (git-rev))
(build-template)
(copy-template-to-jar-resources)
(bb/jar)))
#_{:clj-kondo/ignore #{:clojure-lsp/unused-public-var}}
(defn install
"Build the JAR, and install it to the local maven repository."
[params]
(-> params
(assoc :lib lib :version version)
(bb/clean)
(jar)
(bb/install)))
#_{:clj-kondo/ignore #{:clojure-lsp/unused-public-var}}
(defn release
"Release the library.
* Confirm that we are ready to release
* Build template file
* Build JAR, including the template
* Build the content for GitHub Pages from the template
* Deploy the JAR to Clojars
* Ensure everything is available on Github"
[params]
(let [params (assoc params :lib lib :version version)]
(-> params
(assert-clojars-creds)
(bb/clean)
(check-release)
(jar)
(build-standalone-examples)
(bb/deploy)
(git-push))
(println "\nDone")
params))
|
80fdde3c57563e831c4a78e5303cf7560666042df29cc89290fb96a21d2eb20b | aligusnet/mltool | Main.hs | module Main where
import qualified MachineLearning.Types as T
import qualified Numeric.LinearAlgebra as LA
import qualified MachineLearning as ML
import qualified MachineLearning.Classification.Binary as BC
calcAccuracy :: T.Matrix -> T.Vector -> T.Vector -> T.R
calcAccuracy x y theta = BC.calcAccuracy y yPredicted
where yPredicted = BC.predict x theta
main = do
Step 1 . Data loading .
m <- LA.loadMatrix "logistic_regression/data.txt"
let (x, y) = ML.splitToXY m
Step 2 . Feature normalization ( skipped - we do n't need feature normalization if we use BFGS2 ) .
-- See Linear Regression sample app for dedails.
Step 3 . Feature mapping .
x1 = ML.addBiasDimension $ ML.mapFeatures 6 x
Step 4 . Learning
zeroTheta = LA.konst 0 (LA.cols x1)
(theta, _) = BC.learn (BC.BFGS2 0.1 0.1) 0.0001 1500 (BC.L2 1) x1 y zeroTheta
Step 5 . Prediction and checking accuracy
accuracy = calcAccuracy x1 y theta
Step 6 . Printing results .
putStrLn "\n=== Logistic Regression Sample Application ===\n"
putStrLn ""
putStrLn $ "Theta: " ++ (show theta)
putStrLn ""
putStrLn $ "Accuracy on training set data (%): " ++ show (accuracy*100)
| null | https://raw.githubusercontent.com/aligusnet/mltool/92d74c4cc79221bfdcfb76aa058a2e8992ecfe2b/examples/logistic_regression/Main.hs | haskell | See Linear Regression sample app for dedails. | module Main where
import qualified MachineLearning.Types as T
import qualified Numeric.LinearAlgebra as LA
import qualified MachineLearning as ML
import qualified MachineLearning.Classification.Binary as BC
calcAccuracy :: T.Matrix -> T.Vector -> T.Vector -> T.R
calcAccuracy x y theta = BC.calcAccuracy y yPredicted
where yPredicted = BC.predict x theta
main = do
Step 1 . Data loading .
m <- LA.loadMatrix "logistic_regression/data.txt"
let (x, y) = ML.splitToXY m
Step 2 . Feature normalization ( skipped - we do n't need feature normalization if we use BFGS2 ) .
Step 3 . Feature mapping .
x1 = ML.addBiasDimension $ ML.mapFeatures 6 x
Step 4 . Learning
zeroTheta = LA.konst 0 (LA.cols x1)
(theta, _) = BC.learn (BC.BFGS2 0.1 0.1) 0.0001 1500 (BC.L2 1) x1 y zeroTheta
Step 5 . Prediction and checking accuracy
accuracy = calcAccuracy x1 y theta
Step 6 . Printing results .
putStrLn "\n=== Logistic Regression Sample Application ===\n"
putStrLn ""
putStrLn $ "Theta: " ++ (show theta)
putStrLn ""
putStrLn $ "Accuracy on training set data (%): " ++ show (accuracy*100)
|
101feba66768b916d2837668c2188c9845a8da0c50dd8e6eddfac9440cc0e185 | lisp/de.setf.xml | document-external.lisp | -*- Mode : lisp ; Syntax : ansi - common - lisp ; Base : 10 ; Package : xml - parser ; -*-
(in-package "XML-PARSER")
;;
;; this file demonstates simple parsing and serialization operations on external
;; document sources which are identified by pathname, http url, and file url.
(defParameter *external-dom* nil)
(defParameter *serialized-p-default* t) ; (setq *serialized-p-default* nil)
(defParameter *time-p-default* nil)
(format *trace-output* "~%~%various examples parsing and serializing documents from external sources:~%")
(flet ((parse-and-report (source &rest args &key (serialize-p *serialized-p-default*) trace-p (reduce-p t) (time-p *time-p-default*)
encoding)
(format *trace-output* "~%~%;; source: ~@[~s~]~%~s" args source)
(handler-case
(handler-bind ((continuable-error
#'(lambda (condition)
(format *trace-output* "continuable condition ignored: ~a."
condition)
(continue condition))))
(setq * nil) ; clear last value otherwise it may hold too much memory
(let ((result (if time-p
(time (apply #'document-parser source :trace trace-p :reduce reduce-p
(when encoding (list :encoding encoding))))
(apply #'document-parser source :trace trace-p :reduce reduce-p
(when encoding (list :encoding encoding))))))
(format *trace-output* "~%;; parsed result:~%~s" result)
(describe result)
(when serialize-p
(format *trace-output* "~%;; serializes as:~%" )
(write-node result *trace-output* :encoding :us-ascii))))
(error (condition)
(format *trace-output* "~%;* signaled error:~%~a" condition)))))
"parse and report result for external document sources.
note that the file url form permits logical hosts in the initial position."
(map nil #'(lambda (args) (if (consp args) (apply #'parse-and-report args) (parse-and-report args)))
'((#P"xml:Tests;xml;channel.xml" :serialize-p nil)
"file"
#P"xml:Tests;xml;email.xml"
#P"xml:Tests;xml;lisp.xml"
#P"xml:Tests;xml;real-mini-aleph-het.xml"
; resuires a remote connection
; "-xml-20001006.xml"
; requires a local http server
("-xml-20001006.xml" :serialize-p nil)
(#P"xml:standards;XML;REC-xml-20001006.xml" :serialize-p nil)
("file-xml-20001006.xml" :serialize-p nil)
(#P"xml:standards;XML;W3CSchema;XMLSchema.xsd" :serialize-p nil)
;; xml benchmark timings.
see
note that the larger documents are several megabytes and take roughly three times as much memory as
the initial encoded length , which means this will need about 15 M worth of heap to run all examples .
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;REC.xml" :reduce-p nil :time-p t :encoding :iso-8859-1 :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;REC.xml" :reduce-p t :time-p t :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;chrmed.xml" :reduce-p nil :time-p t :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;chrmed.xml" :reduce-p t :time-p t :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;med.xml" :reduce-p nil :time-p t :encoding :iso-8859-1 :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;med.xml" :reduce-p t :time-p t :serialize-p nil)
14,365 milliseconds 604/200 mcl4.2
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;chrbig.xml" :reduce-p nil :time-p t :serialize-p nil)
12,959 milliseconds 604/200 mcl4.2
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;chrbig.xml" :reduce-p t :time-p t :serialize-p nil)
190,737 - 21,178 milliseconds 604/200 mcl4.2
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;big.xml" :reduce-p nil :time-p t :encoding :iso-8859-1 :serialize-p nil)
based on before / after gc 14664 K for the 4.8 M file
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;big.xml" :reduce-p t :time-p t :serialize-p nil)
; would be interesting, but won't work as it does not handle the dtd
; (#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;big.xml" :reduce-p 'cons :time-p t :encoding :iso-8859-1 :serialize-p nil)
)))
;;(document-parser #P"xml:standards;XML;W3CSchema;XMLSchema.xsd")
;;(document-parser #P"xml:Tests;xml;lisp.xml")
;;(document-parser #P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;big.xml"))
;; schema document components are parsed as part of the larger document, but
;; could also be parsed as external subsets
;; "xml:standards;XML;W3CSchema;XMLSchema.dtd"
;; "xml:standards;XML;W3CSchema;datatypes.dtd"
;;
;; (inspect (stream->vector #P"xml:Tests;xml;real-mini-aleph-het.xml"))
;; alternative settings:
;; first, without either reduction or namespaces. the result is the production id
;; one would need to specialize the reduction context instances and generate results from constructor calls
;; see "xml:code;xparser;xml-constructors.lisp"
(handler-bind ((xqdm::namespace-condition
#'(lambda (condition)
(format *trace-output* "expected condition ignored: ~a."
condition)
(continue condition))))
(let ((xutils::|REC-xml-names-19990114| nil))
(time (setq *external-dom* (document-parser "file-xml-20001006.xml"
:trace nil :reduce nil
;; where reduction is disabled, the declared encoding must be correct
:encoding :ISO-8859-1))))
8,015 milliseconds
(let ((xutils::|REC-xml-names-19990114| nil))
(time (setq *external-dom* (document-parser "file-xml-20001006.xml"
:trace nil :reduce t))))
17,519 milliseconds 604/200 mcl4.2
2,106 milliseconds mcl5.0
(time (setq *external-dom* (document-parser "file-xml-20001006.xml"
:trace nil :reduce t))))
(format *trace-output*
~% ; ; an exmample from modularization :
;; nothing special is needed for the entity-based identifier generation,
;; but the dtd has no danespace declarations, which means that the definition is recognized as a homograph:~%~s~% ==>~%"
(setq *external-dom*
(document-parser #P"xml:standards;XML;XHTML-MODULAR;examples;inventory.xml" :trace nil)))
(describe *external-dom*)
(write-node *external-dom* *trace-output*)
(format *trace-output*
"the dtd itself can also be loaded, so long as one observes the entity dependancies:~%~s~% ==>~%"
(setq *external-dom*
(document-parser #P"xml:standards;XML;XHTML-MODULAR;examples;inventory-1.dtd"
:start-name '|ExtSubset|)))
(describe *external-dom*)
macbeth.xml in the 1999 version , approximately 160Kbytes
8.031 , 7.644 , 7.521 seconds 604/200 mcl4.2
(format *trace-output*
"the macbeth example loaded both as an instacne model and as an s-expression model:~%~s~% ==>~%"
(setq *external-dom*
(time (document-parser #p"xml:standards;XML;XMLConf;macbeth.xml"))))
(describe *external-dom*)
(let ((*print-length* 5) (*print-level* 8))
(format *trace-output*
"~%;; when :reduce is CONS, reduction is to an s-expression representation of the parse tree.
;; the tags are taken from the bnf grammar.
;; the order within a given production is alphabetical.
;; sequence values appear as an untagged list:~%~:W"
(setq *external-dom*
(time (document-parser #p"xml:standards;XML;XMLConf;macbeth.xml" :reduce 'cons))))
(describe *external-dom*))
:EOF
| null | https://raw.githubusercontent.com/lisp/de.setf.xml/827681c969342096c3b95735d84b447befa69fa6/tests/parser/document-external.lisp | lisp | Syntax : ansi - common - lisp ; Base : 10 ; Package : xml - parser ; -*-
this file demonstates simple parsing and serialization operations on external
document sources which are identified by pathname, http url, and file url.
(setq *serialized-p-default* nil)
clear last value otherwise it may hold too much memory
resuires a remote connection
"-xml-20001006.xml"
requires a local http server
xml benchmark timings.
would be interesting, but won't work as it does not handle the dtd
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;big.xml" :reduce-p 'cons :time-p t :encoding :iso-8859-1 :serialize-p nil)
(document-parser #P"xml:standards;XML;W3CSchema;XMLSchema.xsd")
(document-parser #P"xml:Tests;xml;lisp.xml")
(document-parser #P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;big.xml"))
schema document components are parsed as part of the larger document, but
could also be parsed as external subsets
"xml:standards;XML;W3CSchema;XMLSchema.dtd"
"xml:standards;XML;W3CSchema;datatypes.dtd"
(inspect (stream->vector #P"xml:Tests;xml;real-mini-aleph-het.xml"))
alternative settings:
first, without either reduction or namespaces. the result is the production id
one would need to specialize the reduction context instances and generate results from constructor calls
see "xml:code;xparser;xml-constructors.lisp"
where reduction is disabled, the declared encoding must be correct
; an exmample from modularization :
nothing special is needed for the entity-based identifier generation,
but the dtd has no danespace declarations, which means that the definition is recognized as a homograph:~%~s~% ==>~%"
when :reduce is CONS, reduction is to an s-expression representation of the parse tree.
the tags are taken from the bnf grammar.
the order within a given production is alphabetical.
sequence values appear as an untagged list:~%~:W" |
(in-package "XML-PARSER")
(defParameter *external-dom* nil)
(defParameter *time-p-default* nil)
(format *trace-output* "~%~%various examples parsing and serializing documents from external sources:~%")
(flet ((parse-and-report (source &rest args &key (serialize-p *serialized-p-default*) trace-p (reduce-p t) (time-p *time-p-default*)
encoding)
(format *trace-output* "~%~%;; source: ~@[~s~]~%~s" args source)
(handler-case
(handler-bind ((continuable-error
#'(lambda (condition)
(format *trace-output* "continuable condition ignored: ~a."
condition)
(continue condition))))
(let ((result (if time-p
(time (apply #'document-parser source :trace trace-p :reduce reduce-p
(when encoding (list :encoding encoding))))
(apply #'document-parser source :trace trace-p :reduce reduce-p
(when encoding (list :encoding encoding))))))
(format *trace-output* "~%;; parsed result:~%~s" result)
(describe result)
(when serialize-p
(format *trace-output* "~%;; serializes as:~%" )
(write-node result *trace-output* :encoding :us-ascii))))
(error (condition)
(format *trace-output* "~%;* signaled error:~%~a" condition)))))
"parse and report result for external document sources.
note that the file url form permits logical hosts in the initial position."
(map nil #'(lambda (args) (if (consp args) (apply #'parse-and-report args) (parse-and-report args)))
'((#P"xml:Tests;xml;channel.xml" :serialize-p nil)
"file"
#P"xml:Tests;xml;email.xml"
#P"xml:Tests;xml;lisp.xml"
#P"xml:Tests;xml;real-mini-aleph-het.xml"
("-xml-20001006.xml" :serialize-p nil)
(#P"xml:standards;XML;REC-xml-20001006.xml" :serialize-p nil)
("file-xml-20001006.xml" :serialize-p nil)
(#P"xml:standards;XML;W3CSchema;XMLSchema.xsd" :serialize-p nil)
see
note that the larger documents are several megabytes and take roughly three times as much memory as
the initial encoded length , which means this will need about 15 M worth of heap to run all examples .
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;REC.xml" :reduce-p nil :time-p t :encoding :iso-8859-1 :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;REC.xml" :reduce-p t :time-p t :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;chrmed.xml" :reduce-p nil :time-p t :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;chrmed.xml" :reduce-p t :time-p t :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;med.xml" :reduce-p nil :time-p t :encoding :iso-8859-1 :serialize-p nil)
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;med.xml" :reduce-p t :time-p t :serialize-p nil)
14,365 milliseconds 604/200 mcl4.2
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;chrbig.xml" :reduce-p nil :time-p t :serialize-p nil)
12,959 milliseconds 604/200 mcl4.2
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;chrbig.xml" :reduce-p t :time-p t :serialize-p nil)
190,737 - 21,178 milliseconds 604/200 mcl4.2
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;big.xml" :reduce-p nil :time-p t :encoding :iso-8859-1 :serialize-p nil)
based on before / after gc 14664 K for the 4.8 M file
(#P"xml:standards;XML;XMLConf;xmlbench;Benchmark;Data;big.xml" :reduce-p t :time-p t :serialize-p nil)
)))
(handler-bind ((xqdm::namespace-condition
#'(lambda (condition)
(format *trace-output* "expected condition ignored: ~a."
condition)
(continue condition))))
(let ((xutils::|REC-xml-names-19990114| nil))
(time (setq *external-dom* (document-parser "file-xml-20001006.xml"
:trace nil :reduce nil
:encoding :ISO-8859-1))))
8,015 milliseconds
(let ((xutils::|REC-xml-names-19990114| nil))
(time (setq *external-dom* (document-parser "file-xml-20001006.xml"
:trace nil :reduce t))))
17,519 milliseconds 604/200 mcl4.2
2,106 milliseconds mcl5.0
(time (setq *external-dom* (document-parser "file-xml-20001006.xml"
:trace nil :reduce t))))
(format *trace-output*
(setq *external-dom*
(document-parser #P"xml:standards;XML;XHTML-MODULAR;examples;inventory.xml" :trace nil)))
(describe *external-dom*)
(write-node *external-dom* *trace-output*)
(format *trace-output*
"the dtd itself can also be loaded, so long as one observes the entity dependancies:~%~s~% ==>~%"
(setq *external-dom*
(document-parser #P"xml:standards;XML;XHTML-MODULAR;examples;inventory-1.dtd"
:start-name '|ExtSubset|)))
(describe *external-dom*)
macbeth.xml in the 1999 version , approximately 160Kbytes
8.031 , 7.644 , 7.521 seconds 604/200 mcl4.2
(format *trace-output*
"the macbeth example loaded both as an instacne model and as an s-expression model:~%~s~% ==>~%"
(setq *external-dom*
(time (document-parser #p"xml:standards;XML;XMLConf;macbeth.xml"))))
(describe *external-dom*)
(let ((*print-length* 5) (*print-level* 8))
(format *trace-output*
(setq *external-dom*
(time (document-parser #p"xml:standards;XML;XMLConf;macbeth.xml" :reduce 'cons))))
(describe *external-dom*))
:EOF
|
a06f944d64899bf5794d26fbb91b4ac97c54daa35e8b994917e108a6da9ce4f6 | HealthSamurai/stresty | empty.cljc | (ns anti.empty
(:refer-clojure :exclude [empty])
(:require
[anti.util :refer [block]]
[stylo.core :refer [c]]))
(defn empty
[props]
[:div {:class (c [:space-y 2] :flex :flex-col [:p 2] :items-center)}
[:svg (merge {:width "130" :viewBox "0 0 184 152" :xmlns ""} props)
[:g {:fill "none" :fill-rule "evenodd"}
[:g {:transform "translate(24 31.67)"}
[:ellipse {:fill-opacity ".8" :fill "#F5F5F7" :cx "67.797" :cy "106.89" :rx "67.797" :ry "12.668"}]
[:path {:d "M122.034 69.674L98.109 40.229c-1.148-1.386-2.826-2.225-4.593-2.225h-51.44c-1.766 0-3.444.839-4.592 2.225L13.56 69.674v15.383h108.475V69.674z" :fill "#AEB8C2"}]
[:path {:d "M101.537 86.214L80.63 61.102c-1.001-1.207-2.507-1.867-4.048-1.867H31.724c-1.54 0-3.047.66-4.048 1.867L6.769 86.214v13.792h94.768V86.214z" :fill "url(#linearGradient-1)" :transform "translate(13.56)"}]
[:path {:d "M33.83 0h67.933a4 4 0 0 1 4 4v93.344a4 4 0 0 1-4 4H33.83a4 4 0 0 1-4-4V4a4 4 0 0 1 4-4z" :fill "#F5F5F7"}]
[:path {:d "M42.678 9.953h50.237a2 2 0 0 1 2 2V36.91a2 2 0 0 1-2 2H42.678a2 2 0 0 1-2-2V11.953a2 2 0 0 1 2-2zM42.94 49.767h49.713a2.262 2.262 0 1 1 0 4.524H42.94a2.262 2.262 0 0 1 0-4.524zM42.94 61.53h49.713a2.262 2.262 0 1 1 0 4.525H42.94a2.262 2.262 0 0 1 0-4.525zM121.813 105.032c-.775 3.071-3.497 5.36-6.735 5.36H20.515c-3.238 0-5.96-2.29-6.734-5.36a7.309 7.309 0 0 1-.222-1.79V69.675h26.318c2.907 0 5.25 2.448 5.25 5.42v.04c0 2.971 2.37 5.37 5.277 5.37h34.785c2.907 0 5.277-2.421 5.277-5.393V75.1c0-2.972 2.343-5.426 5.25-5.426h26.318v33.569c0 .617-.077 1.216-.221 1.789z" :fill "#DCE0E6"}]]
[:path {:d "M149.121 33.292l-6.83 2.65a1 1 0 0 1-1.317-1.23l1.937-6.207c-2.589-2.944-4.109-6.534-4.109-10.408C138.802 8.102 148.92 0 161.402 0 173.881 0 184 8.102 184 18.097c0 9.995-10.118 18.097-22.599 18.097-4.528 0-8.744-1.066-12.28-2.902z" :fill "#DCE0E6"}]
[:g {:transform "translate(149.65 15.383)" :fill "#FFF"} [:ellipse {:cx "20.654" :cy "3.167" :rx "2.849" :ry "2.815"}] [:path {:d "M5.698 5.63H0L2.898.704zM9.259.704h4.985V5.63H9.259z"}]]]]
[:div {:class (c [:text :gray-500] :text-center)}
(:text props "No data")]])
(defn demo
[]
[block {:title "Empty" :width "100%"}
[empty]])
| null | https://raw.githubusercontent.com/HealthSamurai/stresty/130cedde6bf53e07fe25a6b0b13b8bf70846f15a/src-ui/anti/empty.cljc | clojure | (ns anti.empty
(:refer-clojure :exclude [empty])
(:require
[anti.util :refer [block]]
[stylo.core :refer [c]]))
(defn empty
[props]
[:div {:class (c [:space-y 2] :flex :flex-col [:p 2] :items-center)}
[:svg (merge {:width "130" :viewBox "0 0 184 152" :xmlns ""} props)
[:g {:fill "none" :fill-rule "evenodd"}
[:g {:transform "translate(24 31.67)"}
[:ellipse {:fill-opacity ".8" :fill "#F5F5F7" :cx "67.797" :cy "106.89" :rx "67.797" :ry "12.668"}]
[:path {:d "M122.034 69.674L98.109 40.229c-1.148-1.386-2.826-2.225-4.593-2.225h-51.44c-1.766 0-3.444.839-4.592 2.225L13.56 69.674v15.383h108.475V69.674z" :fill "#AEB8C2"}]
[:path {:d "M101.537 86.214L80.63 61.102c-1.001-1.207-2.507-1.867-4.048-1.867H31.724c-1.54 0-3.047.66-4.048 1.867L6.769 86.214v13.792h94.768V86.214z" :fill "url(#linearGradient-1)" :transform "translate(13.56)"}]
[:path {:d "M33.83 0h67.933a4 4 0 0 1 4 4v93.344a4 4 0 0 1-4 4H33.83a4 4 0 0 1-4-4V4a4 4 0 0 1 4-4z" :fill "#F5F5F7"}]
[:path {:d "M42.678 9.953h50.237a2 2 0 0 1 2 2V36.91a2 2 0 0 1-2 2H42.678a2 2 0 0 1-2-2V11.953a2 2 0 0 1 2-2zM42.94 49.767h49.713a2.262 2.262 0 1 1 0 4.524H42.94a2.262 2.262 0 0 1 0-4.524zM42.94 61.53h49.713a2.262 2.262 0 1 1 0 4.525H42.94a2.262 2.262 0 0 1 0-4.525zM121.813 105.032c-.775 3.071-3.497 5.36-6.735 5.36H20.515c-3.238 0-5.96-2.29-6.734-5.36a7.309 7.309 0 0 1-.222-1.79V69.675h26.318c2.907 0 5.25 2.448 5.25 5.42v.04c0 2.971 2.37 5.37 5.277 5.37h34.785c2.907 0 5.277-2.421 5.277-5.393V75.1c0-2.972 2.343-5.426 5.25-5.426h26.318v33.569c0 .617-.077 1.216-.221 1.789z" :fill "#DCE0E6"}]]
[:path {:d "M149.121 33.292l-6.83 2.65a1 1 0 0 1-1.317-1.23l1.937-6.207c-2.589-2.944-4.109-6.534-4.109-10.408C138.802 8.102 148.92 0 161.402 0 173.881 0 184 8.102 184 18.097c0 9.995-10.118 18.097-22.599 18.097-4.528 0-8.744-1.066-12.28-2.902z" :fill "#DCE0E6"}]
[:g {:transform "translate(149.65 15.383)" :fill "#FFF"} [:ellipse {:cx "20.654" :cy "3.167" :rx "2.849" :ry "2.815"}] [:path {:d "M5.698 5.63H0L2.898.704zM9.259.704h4.985V5.63H9.259z"}]]]]
[:div {:class (c [:text :gray-500] :text-center)}
(:text props "No data")]])
(defn demo
[]
[block {:title "Empty" :width "100%"}
[empty]])
|
|
e7a38602500b9bfb06f098d3efc6af5148bf22b18d9840fccfbf38bd43754405 | LeventErkok/sbvPlugin | T07.hs | {-# OPTIONS_GHC -fplugin=Data.SBV.Plugin #-}
module T07 where
import Data.SBV.Plugin
{-# ANN f theorem #-}
f :: Double -> Bool
f x = x == x
| null | https://raw.githubusercontent.com/LeventErkok/sbvPlugin/b6a6e94cd237a4f64f985783931bd7656e7a6a69/tests/T07.hs | haskell | # OPTIONS_GHC -fplugin=Data.SBV.Plugin #
# ANN f theorem # |
module T07 where
import Data.SBV.Plugin
f :: Double -> Bool
f x = x == x
|
216ca0b7b29106e818eafd2088f2e85af03cc046bb5fa1c0dad03f32b2268569 | guix-science/guix-science-nonfree | bioconductor.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2019 , 2020 , 2021 , 2022 , 2023 < >
Copyright © 2020 < >
Copyright © 2023
;;;
;;; This file is NOT part of GNU Guix, but is supposed to be used with GNU
;;; Guix and thus has the same license.
;;;
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 (guix-science-nonfree packages bioconductor)
#:use-module (guix-science-nonfree licenses)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix utils)
#:use-module (guix build-system r)
#:use-module (gnu packages)
#:use-module (gnu packages bioconductor)
#:use-module (gnu packages bioinformatics)
#:use-module (gnu packages cran)
#:use-module (gnu packages statistics))
(define-public r-dorothea
(package
(name "r-dorothea")
(version "1.10.0")
(source (origin
(method url-fetch)
(uri (bioconductor-uri "dorothea" version
'experiment))
(sha256
(base32
"05vkb5mash2m8p6njk842sy5pz7vblrm8n9bphqbslm86kld5n92"))))
(properties `((upstream-name . "dorothea")))
(build-system r-build-system)
(propagated-inputs (list r-bcellviper r-dplyr r-magrittr r-viper))
(native-inputs (list r-knitr))
(home-page "/")
(synopsis "Collection of human and mouse TF regulons")
(description
"DoRothEA is a gene regulatory network containing signed
transcription factor. DoRothEA regulons, the collection of a TF and
its transcriptional targets, were curated and collected from different
types of evidence for both human and mouse. A confidence level was
assigned to each TF-target interaction based on the number of
supporting evidence.")
;; This package depends on r-viper, which is non-free software.
(license license:gpl3)))
(define-public r-motifdb
(package
(name "r-motifdb")
(version "1.38.0")
(source (origin
(method url-fetch)
(uri (bioconductor-uri "MotifDb" version))
(sha256
(base32
"1cyfz0l0yvdii3idaiq5w39yzxlzfpifa4v5pv7hdjfjj83a8rbi"))))
(properties `((upstream-name . "MotifDb")))
(build-system r-build-system)
(propagated-inputs (list r-biocgenerics
r-biostrings
r-genomicranges
r-iranges
r-rtracklayer
r-s4vectors
r-splitstackshape))
(native-inputs (list r-knitr))
(home-page "")
(synopsis "Annotated collection of protein-DNA binding sequence motifs")
(description
"This package provides more than 9900 annotated position
frequency matrices from 14 public sources, for multiple organisms.")
;; It's complicated... the data from public sources are under
;; different licenses; some are not licensed at all.
(license
(nonfree ""))))
(define-public r-rankprod
(package
(name "r-rankprod")
(version "3.22.0")
(source (origin
(method url-fetch)
(uri (bioconductor-uri "RankProd" version))
(sha256
(base32
"0rq14h9kjj84krgvfa09jbc5s8yks37fjbcv8z88daaib0j3fq2d"))))
(properties `((upstream-name . "RankProd")))
(build-system r-build-system)
(propagated-inputs (list r-gmp r-rmpfr))
(home-page "")
(synopsis "Identify differentially expressed genes")
(description
"Non-parametric method for identifying differentially expressed (up- or down-
regulated) genes based on the estimated percentage of false predictions (pfp).
The method can combine data sets from different origins (meta-analysis) to
increase the power of the identification.")
(license
(nonfree ""
"Non-commercial"))))
(define-public r-viper
(package
(name "r-viper")
(version "1.32.0")
(source (origin
(method url-fetch)
(uri (bioconductor-uri "viper" version))
(sha256
(base32
"11i2q9nakh534nx2l736id7k1yqhk7jpg32sbfl4vrnh398q86h6"))))
(properties `((upstream-name . "viper")))
(build-system r-build-system)
(propagated-inputs (list r-biobase r-e1071 r-kernsmooth r-mixtools))
(home-page "")
(synopsis "Virtual inference of protein-activity by enriched regulon analysis")
(description
"This is a package for inference of protein activity from gene
expression data. It includes the VIPER and msVIPER algorithms")
(license (nonfree ""
"Non-commercial"))))
| null | https://raw.githubusercontent.com/guix-science/guix-science-nonfree/848f970b2aaca2745f2d5588aa2cacbd44b59dab/guix-science-nonfree/packages/bioconductor.scm | scheme | GNU Guix --- Functional package management for GNU
This file is NOT part of GNU Guix, but is supposed to be used with GNU
Guix and thus has the same license.
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.
This package depends on r-viper, which is non-free software.
It's complicated... the data from public sources are under
different licenses; some are not licensed at all. | Copyright © 2019 , 2020 , 2021 , 2022 , 2023 < >
Copyright © 2020 < >
Copyright © 2023
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 (guix-science-nonfree packages bioconductor)
#:use-module (guix-science-nonfree licenses)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix utils)
#:use-module (guix build-system r)
#:use-module (gnu packages)
#:use-module (gnu packages bioconductor)
#:use-module (gnu packages bioinformatics)
#:use-module (gnu packages cran)
#:use-module (gnu packages statistics))
(define-public r-dorothea
(package
(name "r-dorothea")
(version "1.10.0")
(source (origin
(method url-fetch)
(uri (bioconductor-uri "dorothea" version
'experiment))
(sha256
(base32
"05vkb5mash2m8p6njk842sy5pz7vblrm8n9bphqbslm86kld5n92"))))
(properties `((upstream-name . "dorothea")))
(build-system r-build-system)
(propagated-inputs (list r-bcellviper r-dplyr r-magrittr r-viper))
(native-inputs (list r-knitr))
(home-page "/")
(synopsis "Collection of human and mouse TF regulons")
(description
"DoRothEA is a gene regulatory network containing signed
transcription factor. DoRothEA regulons, the collection of a TF and
its transcriptional targets, were curated and collected from different
types of evidence for both human and mouse. A confidence level was
assigned to each TF-target interaction based on the number of
supporting evidence.")
(license license:gpl3)))
(define-public r-motifdb
(package
(name "r-motifdb")
(version "1.38.0")
(source (origin
(method url-fetch)
(uri (bioconductor-uri "MotifDb" version))
(sha256
(base32
"1cyfz0l0yvdii3idaiq5w39yzxlzfpifa4v5pv7hdjfjj83a8rbi"))))
(properties `((upstream-name . "MotifDb")))
(build-system r-build-system)
(propagated-inputs (list r-biocgenerics
r-biostrings
r-genomicranges
r-iranges
r-rtracklayer
r-s4vectors
r-splitstackshape))
(native-inputs (list r-knitr))
(home-page "")
(synopsis "Annotated collection of protein-DNA binding sequence motifs")
(description
"This package provides more than 9900 annotated position
frequency matrices from 14 public sources, for multiple organisms.")
(license
(nonfree ""))))
(define-public r-rankprod
(package
(name "r-rankprod")
(version "3.22.0")
(source (origin
(method url-fetch)
(uri (bioconductor-uri "RankProd" version))
(sha256
(base32
"0rq14h9kjj84krgvfa09jbc5s8yks37fjbcv8z88daaib0j3fq2d"))))
(properties `((upstream-name . "RankProd")))
(build-system r-build-system)
(propagated-inputs (list r-gmp r-rmpfr))
(home-page "")
(synopsis "Identify differentially expressed genes")
(description
"Non-parametric method for identifying differentially expressed (up- or down-
regulated) genes based on the estimated percentage of false predictions (pfp).
The method can combine data sets from different origins (meta-analysis) to
increase the power of the identification.")
(license
(nonfree ""
"Non-commercial"))))
(define-public r-viper
(package
(name "r-viper")
(version "1.32.0")
(source (origin
(method url-fetch)
(uri (bioconductor-uri "viper" version))
(sha256
(base32
"11i2q9nakh534nx2l736id7k1yqhk7jpg32sbfl4vrnh398q86h6"))))
(properties `((upstream-name . "viper")))
(build-system r-build-system)
(propagated-inputs (list r-biobase r-e1071 r-kernsmooth r-mixtools))
(home-page "")
(synopsis "Virtual inference of protein-activity by enriched regulon analysis")
(description
"This is a package for inference of protein activity from gene
expression data. It includes the VIPER and msVIPER algorithms")
(license (nonfree ""
"Non-commercial"))))
|
946b071fecd64369b7d81d2e0bd4105ed03235214b211311156a5cb3a45d134d | tonyg/kali-scheme | debug.scm | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
; Commands for debugging.
; translate
(define-command-syntax 'translate "<from> <to>"
"establish file name translation"
'(filename filename))
(define translate set-translation!)
; preview -- show continuations
(define (preview)
(let ((cont (command-continuation)))
(if cont
(display-preview (continuation-preview cont)
(command-output)))))
(define (display-preview preview port)
(for-each (lambda (info+pc)
(if (not (fluid-let-continuation-info? (car info+pc)))
(display-template-names (car info+pc) port)))
preview))
(define (display-template-names info port)
(let ((names (debug-data-names info)))
(display " " port)
(if (null? names)
(begin (display "unnamed " port)
(write `(id ,(if (debug-data? info)
(debug-data-uid info)
info))
port))
(let loop ((names names))
(if (car names)
(write (car names) port)
(display "unnamed" port))
(if (and (not (null? (cdr names)))
(cadr names))
(begin (display " in " port)
(loop (cdr names))))))
(newline port)))
(define fluid-let-continuation-info? ;Incestuous!
(let ((id (let-fluid (make-fluid #f) #f
(lambda ()
(primitive-catch (lambda (k)
(template-id
(continuation-template k))))))))
(lambda (info)
(eqv? (if (debug-data? info)
(debug-data-uid info)
info)
id))))
(define-command-syntax 'preview ""
"show pending continuations (stack trace)"
'())
; Proceed
(define (really-proceed vals)
(let* ((level (command-level))
(condition (command-level-condition level)))
(if (ok-to-proceed? condition)
(apply proceed-with-command-level (cadr (command-levels)) vals)
(begin
(write-line "No way to proceed from here." (command-output))
(write condition (command-output))
(newline (command-output))))))
(define-command-syntax 'proceed "<exp>" "proceed after an interrupt or error"
'(&rest expression))
(define (proceed . exps)
(really-proceed (map (lambda (exp)
(eval exp (environment-for-commands)))
exps)))
; Scrutinize the condition to ensure that it's safe to return from the
; call to RAISE.
(define (ok-to-proceed? condition)
(and condition
(if (error? condition)
(and (exception? condition)
(let ((opcode (exception-opcode condition)))
(or (= opcode (enum op global))
(= opcode (enum op local))
(= opcode (enum op local0))
(= opcode (enum op local1))
(= opcode (enum op local2))
(= opcode (enum op set-global!))
(>= opcode (enum op eq?)))))
#t)))
(define (breakpoint . rest)
(command-loop (make-condition 'breakpoint rest)))
(define-condition-type 'breakpoint '())
(define breakpoint? (condition-predicate 'breakpoint))
; push
(define-command-syntax 'push "" "push command level" '())
(define (push)
(command-loop (if (command-level? (focus-object))
(command-level-condition (focus-object))
#f)))
pop ( same as ^D (= end - of - file ) )
(define-command-syntax 'pop "" "pop command level" '())
(define (pop)
(pop-command-level))
; reset
(define (reset)
(abort-to-command-level (top-command-level)))
(define-command-syntax 'reset "" "top level" '())
(define (go-to-level n)
(let ((levels (reverse (command-levels))))
(if (and (integer? n)
(>= n 0)
(< n (length levels)))
(abort-to-command-level (list-ref levels n))
(write-line "invalid command level" (command-output)))))
(define-command-syntax 'level "<number>" "go to specific command level"
'(expression))
(define level go-to-level)
(define-command-syntax 'condition ""
"select an object that describes the current error condition"
'())
(define (condition)
(let ((c (command-level-condition (command-level))))
(if c
(set-focus-object! c)
(write-line "no condition" (command-output)))))
; Commands that toggle various flags.
(define (toggle-command get set description)
(lambda maybe-option
(let ((b (if (null? maybe-option)
(not (get))
(case (car maybe-option)
((off) #f)
((on) #t)
((?) (get))
(else (error "invalid setting (should be on or off or ?)"
(car maybe-option))))))
(out (command-output)))
(set b)
(display (if b "Will " "Won't ") out)
(display description out)
(newline out))))
(define syntax-for-toggle '(&opt name))
; Batch mode
(define-command-syntax 'batch "[on | off]"
"enable/disable batch mode (no prompt, errors exit)"
syntax-for-toggle)
(define batch
(toggle-command batch-mode?
set-batch-mode?!
"exit on errors"))
; Benchmark mode (i.e., inline primitives)
(define-command-syntax 'bench "[on | off]"
"enable/disable benchmark mode (integrate primitives)"
syntax-for-toggle)
(define bench
(toggle-command (lambda ()
(package-integrate? (environment-for-commands)))
(lambda (b)
(set-package-integrate?! (environment-for-commands) b))
"compile some calls in line"))
; Break on warnings
(define-command-syntax 'break-on-warnings "[on | off]"
"treat warnings as errors"
syntax-for-toggle)
(define break-on-warnings
(toggle-command break-on-warnings?
set-break-on-warnings?!
"enter breakpoint on warnings"))
(define-command-syntax 'form-preferred "[on | off]"
"enable/disable form-preferred command processor mode"
syntax-for-toggle)
(define form-preferred
(toggle-command (user-context-accessor 'form-preferred? (lambda () #t))
(user-context-modifier 'form-preferred?)
"prefer forms to commands"))
(define-command-syntax 'levels "[on | off]"
"disable/enable command levels"
syntax-for-toggle)
(define levels
(toggle-command (user-context-accessor 'push-command-levels (lambda () #t))
(user-context-modifier 'push-command-levels)
"push command level on errors"))
; Flush debug data base
(define-command-syntax 'flush "[<kind> ...]"
"start forgetting debug information
Kind should be one of: names maps files source tabulate
location-names file-packages"
'(&rest name))
(define (flush . kinds)
(cond ((null? kinds)
(write-line "Flushing location names and tabulated debug info"
(command-output))
(flush-location-names)
((debug-flag-modifier 'table) (make-table)))
(else
(for-each (lambda (kind)
(cond ((memq kind debug-flag-names)
((debug-flag-modifier kind)
(if (eq? kind 'table) (make-table) #f)))
((eq? kind 'location-names)
(flush-location-names))
((eq? kind 'file-packages)
(forget-file-environments))
(else
(write-line "Unrecognized debug flag"
(command-output)))))
kinds))))
Control retention of debugging information
(define-command-syntax 'keep "[<kind> ...]"
"start remembering debug information
Kind should be one of: names maps files source tabulate"
'(&rest name))
(define (keep . kinds)
(let ((port (command-output)))
(if (null? kinds)
(for-each (lambda (kind)
(if (not (eq? kind 'table))
(begin
(display (if ((debug-flag-accessor kind))
"+ " "- ")
port)
(display kind port)
(newline port))))
debug-flag-names)
(for-each (lambda (kind)
(if (and (memq kind debug-flag-names)
(not (eq? kind 'table)))
((debug-flag-modifier kind) #t)
(write-line "Unrecognized debug flag"
port)))
kinds))))
; Collect some garbage
(define (collect)
(let ((port (command-output))
(before (memory-status memory-status-option/available #f)))
((structure-ref primitives collect))
(let ((after (memory-status memory-status-option/available #f)))
(display "Before: " port)
(write before port)
(display " words free in semispace")
(newline)
(display "After: " port)
(write after port)
(display " words free in semispace")
(newline))))
(define memory-status-option/available (enum memory-status-option available))
(define-command-syntax 'collect "" "invoke the garbage collector" '())
Undefined ( this is sort of pointless now that NOTING - UNDEFINED - VARIABLES
; exists)
;
;(define (show-undefined-variables)
; (let ((out (command-output))
; (undef (undefined-variables (environment-for-commands))))
; (if (not (null? undef))
; (begin (display "Undefined: " out)
; (write undef out)
; (newline out)))))
;
;(define-command-syntax 'undefined "" "list undefined variables"
; '() show-undefined-variables)
Trace and untrace
(define traced-procedures
(user-context-accessor 'traced (lambda () '())))
(define set-traced-procedures!
(user-context-modifier 'traced))
(define (trace . names)
(if (null? names)
(let ((port (command-output)))
(write (map car (traced-procedures)) port)
(newline port))
(for-each trace-1 names)))
(define-command-syntax 'trace "<name> ..."
"trace calls to given procedure(s)"
'(&rest name))
(define (untrace . names)
(if (null? names)
(for-each untrace-1 (map car (traced-procedures)))
(for-each untrace-1 names)))
(define-command-syntax 'untrace "<name> ..." "stop tracing calls"
'(&rest name))
Trace internals
(define (trace-1 name)
(let* ((env (environment-for-commands))
(proc (environment-ref env name))
(traced (make-traced proc name)))
(set-traced-procedures!
(cons (list name traced proc env)
(traced-procedures)))
(environment-define! env name traced))) ;was environment-set!
Should be doing 's here -- avoid creating new locations
(define (untrace-1 name)
(let ((probe (assq name (traced-procedures))))
(if probe
(let* ((traced (cadr probe))
(proc (caddr probe))
(env (cadddr probe)))
(if (eq? (environment-ref env name) traced)
(environment-set! env name proc)
(let ((out (command-output)))
(display "Value of " out)
(write name out)
(display " changed since ,trace; not restoring it." out)
(newline out)))
(set-traced-procedures!
(filter (lambda (x)
(not (eq? (car x) name)))
(traced-procedures))))
(write-line "?" (command-output)))))
(define (make-traced proc name)
(lambda args
(apply-traced proc name args)))
(define *trace-depth* 8)
(define (apply-traced proc name args)
(let ((port (command-output)))
(dynamic-wind
(lambda ()
(display "[" port))
(lambda ()
(let-fluids $write-length *trace-depth*
$write-depth *trace-depth*
(lambda ()
(display "Enter " port)
(write-carefully (error-form name args) port)
(newline port)))
(call-with-values (lambda ()
(apply proc args))
(lambda results
(let-fluids $write-length *trace-depth*
$write-depth (- *trace-depth* 1)
(lambda ()
(display " Leave " port)
(write-carefully name port)
(for-each (lambda (result)
(display " " port)
(write-carefully (value->expression result) port))
results)))
(apply values results))))
(lambda ()
(display "]" port)
(newline port)))))
; Timer stuff.
(define (time command)
(let ((thunk (if (eq? (car command) 'run)
(eval `(lambda () ,(cadr command))
(environment-for-commands))
(lambda () (execute-command command))))
(port (command-output)))
(let ((start-run-time (run-time))
(start-real-time (real-time)))
(call-with-values thunk
(lambda results
(let ((stop-run-time (run-time))
(stop-real-time (real-time)))
(display "Run time: " port)
(write-hundredths (- stop-run-time start-run-time) port)
(display " seconds; Elapsed time: " port)
(write-hundredths (- stop-real-time start-real-time) port)
(display " seconds" port)
(newline port)
(set-focus-values! results)))))))
; N is in milliseconds
(define (write-hundredths n port)
(let ((n (round (quotient n 10))))
(write (quotient n 100) port)
(write-char #\. port)
(let ((r (remainder n 100)))
(if (< r 10)
(write-char #\0 port))
(write r port))))
(define-command-syntax 'time "<command>" "measure execution time"
'(command))
Support for stuffing things from Emacs .
(define-command-syntax 'from-file #f #f ;"<filename>" "editor support"
'(&opt filename))
(define-command-syntax 'end #f #f
'())
(define (from-file . maybe-filename)
(let* ((filename (if (null? maybe-filename) #f (car maybe-filename)))
(env (let ((probe (if filename
(get-file-environment filename)
#f))
(c (environment-for-commands)))
(if (and probe (not (eq? probe c)))
(let ((port (command-output)))
(newline port)
(display filename port)
(display " => " port)
(write probe port)
(display " " port) ;dots follow
probe)
c)))
(in (command-input))
(forms (let recur ()
(let ((command (read-command #f #t in)))
(if (eof-object? command)
'()
(case (car command)
((end) '())
((#f run) (cons (cadr command) (recur)))
(else
(error "unusual command in ,from-file ... ,end"
command))))))))
(if (package? env)
(with-interaction-environment env
(lambda ()
(noting-undefined-variables env
(lambda ()
(eval-from-file forms env (if (null? maybe-filename)
#f
(car maybe-filename)))))
(newline (command-output))))
env))))
; Filename -> environment map.
(define file-environments
(user-context-accessor 'file-environments (lambda () '())))
(define set-file-environments!
(user-context-modifier 'file-environments))
(define (forget-file-environments)
(set-file-environments! '()))
(define (note-file-environment! filename env)
(if (user-context)
(let* ((translated ((structure-ref filenames translate) filename))
(envs (file-environments))
(probe (or (assoc filename envs) ;What to do?
(assoc translated envs))))
(if probe
(if (not (eq? env (weak-pointer-ref (cdr probe))))
(let ((port (command-output)))
(newline port)
(display "Changing default package for file " port)
(display filename port)
(display " from" port)
(newline port)
(write (weak-pointer-ref (cdr probe)) port)
(display " to " port)
(write env port)
(newline port)
(set-cdr! probe (make-weak-pointer env))))
(set-file-environments!
(cons (cons filename (make-weak-pointer env))
envs))))))
(define (get-file-environment filename)
(let ((probe (assoc filename (file-environments)))) ;translate ?
(if probe
(weak-pointer-ref (cdr probe))
#f)))
(set-fluid! $note-file-package note-file-environment!)
(define-command-syntax 'forget "<filename>"
"forget file/package association"
'(filename))
(define (forget filename)
(note-file-environment! filename #f))
; ,bound? <name>
(define-command-syntax 'bound? "<name>"
"display binding of name, if any"
'(name))
(define (bound? name)
(let ((port (command-output))
(probe (package-lookup (environment-for-commands) name)))
(if probe
(begin (display "Bound to " port)
(write probe)
(newline port))
(write-line "Not bound" port))))
; ,expand <form>
(define-command-syntax 'expand "[<form>]"
"macro-expand a form"
'(&opt expression))
(define (expand . maybe-exp)
(let ((exp (if (null? maybe-exp)
(focus-object)
(car maybe-exp)))
(env (package->environment (environment-for-commands))))
(set-focus-object!
(schemify ((structure-ref syntactic expand) exp env)
env))))
| null | https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/env/debug.scm | scheme | Commands for debugging.
translate
preview -- show continuations
Incestuous!
Proceed
Scrutinize the condition to ensure that it's safe to return from the
call to RAISE.
push
reset
Commands that toggle various flags.
Batch mode
Benchmark mode (i.e., inline primitives)
Break on warnings
Flush debug data base
Collect some garbage
exists)
(define (show-undefined-variables)
(let ((out (command-output))
(undef (undefined-variables (environment-for-commands))))
(if (not (null? undef))
(begin (display "Undefined: " out)
(write undef out)
(newline out)))))
(define-command-syntax 'undefined "" "list undefined variables"
'() show-undefined-variables)
was environment-set!
Timer stuff.
N is in milliseconds
"<filename>" "editor support"
dots follow
Filename -> environment map.
What to do?
translate ?
,bound? <name>
,expand <form> | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING .
(define-command-syntax 'translate "<from> <to>"
"establish file name translation"
'(filename filename))
(define translate set-translation!)
(define (preview)
(let ((cont (command-continuation)))
(if cont
(display-preview (continuation-preview cont)
(command-output)))))
(define (display-preview preview port)
(for-each (lambda (info+pc)
(if (not (fluid-let-continuation-info? (car info+pc)))
(display-template-names (car info+pc) port)))
preview))
(define (display-template-names info port)
(let ((names (debug-data-names info)))
(display " " port)
(if (null? names)
(begin (display "unnamed " port)
(write `(id ,(if (debug-data? info)
(debug-data-uid info)
info))
port))
(let loop ((names names))
(if (car names)
(write (car names) port)
(display "unnamed" port))
(if (and (not (null? (cdr names)))
(cadr names))
(begin (display " in " port)
(loop (cdr names))))))
(newline port)))
(let ((id (let-fluid (make-fluid #f) #f
(lambda ()
(primitive-catch (lambda (k)
(template-id
(continuation-template k))))))))
(lambda (info)
(eqv? (if (debug-data? info)
(debug-data-uid info)
info)
id))))
(define-command-syntax 'preview ""
"show pending continuations (stack trace)"
'())
(define (really-proceed vals)
(let* ((level (command-level))
(condition (command-level-condition level)))
(if (ok-to-proceed? condition)
(apply proceed-with-command-level (cadr (command-levels)) vals)
(begin
(write-line "No way to proceed from here." (command-output))
(write condition (command-output))
(newline (command-output))))))
(define-command-syntax 'proceed "<exp>" "proceed after an interrupt or error"
'(&rest expression))
(define (proceed . exps)
(really-proceed (map (lambda (exp)
(eval exp (environment-for-commands)))
exps)))
(define (ok-to-proceed? condition)
(and condition
(if (error? condition)
(and (exception? condition)
(let ((opcode (exception-opcode condition)))
(or (= opcode (enum op global))
(= opcode (enum op local))
(= opcode (enum op local0))
(= opcode (enum op local1))
(= opcode (enum op local2))
(= opcode (enum op set-global!))
(>= opcode (enum op eq?)))))
#t)))
(define (breakpoint . rest)
(command-loop (make-condition 'breakpoint rest)))
(define-condition-type 'breakpoint '())
(define breakpoint? (condition-predicate 'breakpoint))
(define-command-syntax 'push "" "push command level" '())
(define (push)
(command-loop (if (command-level? (focus-object))
(command-level-condition (focus-object))
#f)))
pop ( same as ^D (= end - of - file ) )
(define-command-syntax 'pop "" "pop command level" '())
(define (pop)
(pop-command-level))
(define (reset)
(abort-to-command-level (top-command-level)))
(define-command-syntax 'reset "" "top level" '())
(define (go-to-level n)
(let ((levels (reverse (command-levels))))
(if (and (integer? n)
(>= n 0)
(< n (length levels)))
(abort-to-command-level (list-ref levels n))
(write-line "invalid command level" (command-output)))))
(define-command-syntax 'level "<number>" "go to specific command level"
'(expression))
(define level go-to-level)
(define-command-syntax 'condition ""
"select an object that describes the current error condition"
'())
(define (condition)
(let ((c (command-level-condition (command-level))))
(if c
(set-focus-object! c)
(write-line "no condition" (command-output)))))
(define (toggle-command get set description)
(lambda maybe-option
(let ((b (if (null? maybe-option)
(not (get))
(case (car maybe-option)
((off) #f)
((on) #t)
((?) (get))
(else (error "invalid setting (should be on or off or ?)"
(car maybe-option))))))
(out (command-output)))
(set b)
(display (if b "Will " "Won't ") out)
(display description out)
(newline out))))
(define syntax-for-toggle '(&opt name))
(define-command-syntax 'batch "[on | off]"
"enable/disable batch mode (no prompt, errors exit)"
syntax-for-toggle)
(define batch
(toggle-command batch-mode?
set-batch-mode?!
"exit on errors"))
(define-command-syntax 'bench "[on | off]"
"enable/disable benchmark mode (integrate primitives)"
syntax-for-toggle)
(define bench
(toggle-command (lambda ()
(package-integrate? (environment-for-commands)))
(lambda (b)
(set-package-integrate?! (environment-for-commands) b))
"compile some calls in line"))
(define-command-syntax 'break-on-warnings "[on | off]"
"treat warnings as errors"
syntax-for-toggle)
(define break-on-warnings
(toggle-command break-on-warnings?
set-break-on-warnings?!
"enter breakpoint on warnings"))
(define-command-syntax 'form-preferred "[on | off]"
"enable/disable form-preferred command processor mode"
syntax-for-toggle)
(define form-preferred
(toggle-command (user-context-accessor 'form-preferred? (lambda () #t))
(user-context-modifier 'form-preferred?)
"prefer forms to commands"))
(define-command-syntax 'levels "[on | off]"
"disable/enable command levels"
syntax-for-toggle)
(define levels
(toggle-command (user-context-accessor 'push-command-levels (lambda () #t))
(user-context-modifier 'push-command-levels)
"push command level on errors"))
(define-command-syntax 'flush "[<kind> ...]"
"start forgetting debug information
Kind should be one of: names maps files source tabulate
location-names file-packages"
'(&rest name))
(define (flush . kinds)
(cond ((null? kinds)
(write-line "Flushing location names and tabulated debug info"
(command-output))
(flush-location-names)
((debug-flag-modifier 'table) (make-table)))
(else
(for-each (lambda (kind)
(cond ((memq kind debug-flag-names)
((debug-flag-modifier kind)
(if (eq? kind 'table) (make-table) #f)))
((eq? kind 'location-names)
(flush-location-names))
((eq? kind 'file-packages)
(forget-file-environments))
(else
(write-line "Unrecognized debug flag"
(command-output)))))
kinds))))
Control retention of debugging information
(define-command-syntax 'keep "[<kind> ...]"
"start remembering debug information
Kind should be one of: names maps files source tabulate"
'(&rest name))
(define (keep . kinds)
(let ((port (command-output)))
(if (null? kinds)
(for-each (lambda (kind)
(if (not (eq? kind 'table))
(begin
(display (if ((debug-flag-accessor kind))
"+ " "- ")
port)
(display kind port)
(newline port))))
debug-flag-names)
(for-each (lambda (kind)
(if (and (memq kind debug-flag-names)
(not (eq? kind 'table)))
((debug-flag-modifier kind) #t)
(write-line "Unrecognized debug flag"
port)))
kinds))))
(define (collect)
(let ((port (command-output))
(before (memory-status memory-status-option/available #f)))
((structure-ref primitives collect))
(let ((after (memory-status memory-status-option/available #f)))
(display "Before: " port)
(write before port)
(display " words free in semispace")
(newline)
(display "After: " port)
(write after port)
(display " words free in semispace")
(newline))))
(define memory-status-option/available (enum memory-status-option available))
(define-command-syntax 'collect "" "invoke the garbage collector" '())
Undefined ( this is sort of pointless now that NOTING - UNDEFINED - VARIABLES
Trace and untrace
(define traced-procedures
(user-context-accessor 'traced (lambda () '())))
(define set-traced-procedures!
(user-context-modifier 'traced))
(define (trace . names)
(if (null? names)
(let ((port (command-output)))
(write (map car (traced-procedures)) port)
(newline port))
(for-each trace-1 names)))
(define-command-syntax 'trace "<name> ..."
"trace calls to given procedure(s)"
'(&rest name))
(define (untrace . names)
(if (null? names)
(for-each untrace-1 (map car (traced-procedures)))
(for-each untrace-1 names)))
(define-command-syntax 'untrace "<name> ..." "stop tracing calls"
'(&rest name))
Trace internals
(define (trace-1 name)
(let* ((env (environment-for-commands))
(proc (environment-ref env name))
(traced (make-traced proc name)))
(set-traced-procedures!
(cons (list name traced proc env)
(traced-procedures)))
Should be doing 's here -- avoid creating new locations
(define (untrace-1 name)
(let ((probe (assq name (traced-procedures))))
(if probe
(let* ((traced (cadr probe))
(proc (caddr probe))
(env (cadddr probe)))
(if (eq? (environment-ref env name) traced)
(environment-set! env name proc)
(let ((out (command-output)))
(display "Value of " out)
(write name out)
(display " changed since ,trace; not restoring it." out)
(newline out)))
(set-traced-procedures!
(filter (lambda (x)
(not (eq? (car x) name)))
(traced-procedures))))
(write-line "?" (command-output)))))
(define (make-traced proc name)
(lambda args
(apply-traced proc name args)))
(define *trace-depth* 8)
(define (apply-traced proc name args)
(let ((port (command-output)))
(dynamic-wind
(lambda ()
(display "[" port))
(lambda ()
(let-fluids $write-length *trace-depth*
$write-depth *trace-depth*
(lambda ()
(display "Enter " port)
(write-carefully (error-form name args) port)
(newline port)))
(call-with-values (lambda ()
(apply proc args))
(lambda results
(let-fluids $write-length *trace-depth*
$write-depth (- *trace-depth* 1)
(lambda ()
(display " Leave " port)
(write-carefully name port)
(for-each (lambda (result)
(display " " port)
(write-carefully (value->expression result) port))
results)))
(apply values results))))
(lambda ()
(display "]" port)
(newline port)))))
(define (time command)
(let ((thunk (if (eq? (car command) 'run)
(eval `(lambda () ,(cadr command))
(environment-for-commands))
(lambda () (execute-command command))))
(port (command-output)))
(let ((start-run-time (run-time))
(start-real-time (real-time)))
(call-with-values thunk
(lambda results
(let ((stop-run-time (run-time))
(stop-real-time (real-time)))
(display "Run time: " port)
(write-hundredths (- stop-run-time start-run-time) port)
(display " seconds; Elapsed time: " port)
(write-hundredths (- stop-real-time start-real-time) port)
(display " seconds" port)
(newline port)
(set-focus-values! results)))))))
(define (write-hundredths n port)
(let ((n (round (quotient n 10))))
(write (quotient n 100) port)
(write-char #\. port)
(let ((r (remainder n 100)))
(if (< r 10)
(write-char #\0 port))
(write r port))))
(define-command-syntax 'time "<command>" "measure execution time"
'(command))
Support for stuffing things from Emacs .
'(&opt filename))
(define-command-syntax 'end #f #f
'())
(define (from-file . maybe-filename)
(let* ((filename (if (null? maybe-filename) #f (car maybe-filename)))
(env (let ((probe (if filename
(get-file-environment filename)
#f))
(c (environment-for-commands)))
(if (and probe (not (eq? probe c)))
(let ((port (command-output)))
(newline port)
(display filename port)
(display " => " port)
(write probe port)
probe)
c)))
(in (command-input))
(forms (let recur ()
(let ((command (read-command #f #t in)))
(if (eof-object? command)
'()
(case (car command)
((end) '())
((#f run) (cons (cadr command) (recur)))
(else
(error "unusual command in ,from-file ... ,end"
command))))))))
(if (package? env)
(with-interaction-environment env
(lambda ()
(noting-undefined-variables env
(lambda ()
(eval-from-file forms env (if (null? maybe-filename)
#f
(car maybe-filename)))))
(newline (command-output))))
env))))
(define file-environments
(user-context-accessor 'file-environments (lambda () '())))
(define set-file-environments!
(user-context-modifier 'file-environments))
(define (forget-file-environments)
(set-file-environments! '()))
(define (note-file-environment! filename env)
(if (user-context)
(let* ((translated ((structure-ref filenames translate) filename))
(envs (file-environments))
(assoc translated envs))))
(if probe
(if (not (eq? env (weak-pointer-ref (cdr probe))))
(let ((port (command-output)))
(newline port)
(display "Changing default package for file " port)
(display filename port)
(display " from" port)
(newline port)
(write (weak-pointer-ref (cdr probe)) port)
(display " to " port)
(write env port)
(newline port)
(set-cdr! probe (make-weak-pointer env))))
(set-file-environments!
(cons (cons filename (make-weak-pointer env))
envs))))))
(define (get-file-environment filename)
(if probe
(weak-pointer-ref (cdr probe))
#f)))
(set-fluid! $note-file-package note-file-environment!)
(define-command-syntax 'forget "<filename>"
"forget file/package association"
'(filename))
(define (forget filename)
(note-file-environment! filename #f))
(define-command-syntax 'bound? "<name>"
"display binding of name, if any"
'(name))
(define (bound? name)
(let ((port (command-output))
(probe (package-lookup (environment-for-commands) name)))
(if probe
(begin (display "Bound to " port)
(write probe)
(newline port))
(write-line "Not bound" port))))
(define-command-syntax 'expand "[<form>]"
"macro-expand a form"
'(&opt expression))
(define (expand . maybe-exp)
(let ((exp (if (null? maybe-exp)
(focus-object)
(car maybe-exp)))
(env (package->environment (environment-for-commands))))
(set-focus-object!
(schemify ((structure-ref syntactic expand) exp env)
env))))
|
592710d16594ab4efbb594091de280204c398c6ce0b298a10eb2534c4088954e | AccelerateHS/accelerate-examples | SASUM.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE TypeOperators #-}
module Test.Imaginary.SASUM (
test_sasum,
) where
import Config
import QuickCheck.Arbitrary.Array ()
import Prelude as P
import Data.Array.Accelerate as A
import Data.Array.Accelerate.Examples.Internal as A
import Data.Label
import Data.Maybe
import Data.Typeable
import Test.QuickCheck
test_sasum :: Backend -> Config -> Test
test_sasum backend opt = testGroup "sasum" $ catMaybes
[ testElt configInt8 (undefined :: Int8)
, testElt configInt16 (undefined :: Int16)
, testElt configInt32 (undefined :: Int32)
, testElt configInt64 (undefined :: Int64)
, testElt configWord8 (undefined :: Word8)
, testElt configWord16 (undefined :: Word16)
, testElt configWord32 (undefined :: Word32)
, testElt configWord64 (undefined :: Word64)
, testElt configFloat (undefined :: Float)
, testElt configDouble (undefined :: Double)
]
where
testElt :: forall a. (P.Num a, A.Num a, Similar a, Arbitrary a)
=> (Config :-> Bool)
-> a
-> Maybe Test
testElt ok _
| P.not (get ok opt) = Nothing
| otherwise = Just
$ testProperty (show (typeOf (undefined :: a))) (run_sasum :: Vector a -> Property)
run_sasum xs =
run1 backend sasum xs `indexArray` Z
~?=
P.sum (P.map abs (toList xs))
Accelerate implementation ---------------------------------------------------
sasum :: A.Num e => Acc (Vector e) -> Acc (Scalar e)
sasum = A.fold (+) 0 . A.map abs
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/examples/icebox/nofib/Test/Imaginary/SASUM.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeOperators #
------------------------------------------------- | # LANGUAGE ScopedTypeVariables #
module Test.Imaginary.SASUM (
test_sasum,
) where
import Config
import QuickCheck.Arbitrary.Array ()
import Prelude as P
import Data.Array.Accelerate as A
import Data.Array.Accelerate.Examples.Internal as A
import Data.Label
import Data.Maybe
import Data.Typeable
import Test.QuickCheck
test_sasum :: Backend -> Config -> Test
test_sasum backend opt = testGroup "sasum" $ catMaybes
[ testElt configInt8 (undefined :: Int8)
, testElt configInt16 (undefined :: Int16)
, testElt configInt32 (undefined :: Int32)
, testElt configInt64 (undefined :: Int64)
, testElt configWord8 (undefined :: Word8)
, testElt configWord16 (undefined :: Word16)
, testElt configWord32 (undefined :: Word32)
, testElt configWord64 (undefined :: Word64)
, testElt configFloat (undefined :: Float)
, testElt configDouble (undefined :: Double)
]
where
testElt :: forall a. (P.Num a, A.Num a, Similar a, Arbitrary a)
=> (Config :-> Bool)
-> a
-> Maybe Test
testElt ok _
| P.not (get ok opt) = Nothing
| otherwise = Just
$ testProperty (show (typeOf (undefined :: a))) (run_sasum :: Vector a -> Property)
run_sasum xs =
run1 backend sasum xs `indexArray` Z
~?=
P.sum (P.map abs (toList xs))
sasum :: A.Num e => Acc (Vector e) -> Acc (Scalar e)
sasum = A.fold (+) 0 . A.map abs
|
eab9aad9ec7fff0bb55628db7d45a62b0954ac9a6db8b44b0c308ecb91217c29 | mitchellwrosen/planet-mitchell | Monoid.hs | module Alg.Monoid
( -- * Monoid
Monoid(..)
, gmempty
) where
import Data.Monoid (Monoid(mconcat, mempty, mappend))
import Data.Semigroup.Generic (gmempty)
| null | https://raw.githubusercontent.com/mitchellwrosen/planet-mitchell/18dd83204e70fffcd23fe12dd3a80f70b7fa409b/planet-mitchell/src/Alg/Monoid.hs | haskell | * Monoid | module Alg.Monoid
Monoid(..)
, gmempty
) where
import Data.Monoid (Monoid(mconcat, mempty, mappend))
import Data.Semigroup.Generic (gmempty)
|
3a72bdaba7df439600439c12d2f10956927845ec2f131e8bfa25ffaeb3ad075e | arttuka/reagent-material-ui | contact_emergency_two_tone.cljs | (ns reagent-mui.icons.contact-emergency-two-tone
"Imports @mui/icons-material/ContactEmergencyTwoTone as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def contact-emergency-two-tone (create-svg-icon [(e "path" #js {"d" "M2 19h.08c1.38-2.39 3.96-4 6.92-4s5.54 1.61 6.92 4H22V5H2v14zM15.03 8.15l.75-1.3 1.47.85V6h1.5v1.7l1.47-.85.75 1.3L19.5 9l1.47.85-.75 1.3-1.47-.85V12h-1.5v-1.7l-1.47.85-.75-1.3L16.5 9l-1.47-.85zM9 8c1.65 0 3 1.35 3 3s-1.35 3-3 3-3-1.35-3-3 1.35-3 3-3z", "opacity" ".3"}) (e "path" #js {"d" "M9 14c1.65 0 3-1.35 3-3s-1.35-3-3-3-3 1.35-3 3 1.35 3 3 3zm0-4c.54 0 1 .46 1 1s-.46 1-1 1-1-.46-1-1 .46-1 1-1z"}) (e "path" #js {"d" "M22 3H2C.9 3 0 3.9 0 5v14c0 1.1.9 2 2 2h20c1.1 0 1.99-.9 1.99-2L24 5c0-1.1-.9-2-2-2zM4.54 19c1.1-1.22 2.69-2 4.46-2s3.36.78 4.46 2H4.54zM22 19h-6.08c-1.38-2.39-3.96-4-6.92-4s-5.54 1.61-6.92 4H2V5h20v14z"}) (e "path" #js {"d" "m15.78 11.15 1.47-.85V12h1.5v-1.7l1.47.85.75-1.3L19.5 9l1.47-.85-.75-1.3-1.47.85V6h-1.5v1.7l-1.47-.85-.75 1.3L16.5 9l-1.47.85z"})]
"ContactEmergencyTwoTone"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/contact_emergency_two_tone.cljs | clojure | (ns reagent-mui.icons.contact-emergency-two-tone
"Imports @mui/icons-material/ContactEmergencyTwoTone as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def contact-emergency-two-tone (create-svg-icon [(e "path" #js {"d" "M2 19h.08c1.38-2.39 3.96-4 6.92-4s5.54 1.61 6.92 4H22V5H2v14zM15.03 8.15l.75-1.3 1.47.85V6h1.5v1.7l1.47-.85.75 1.3L19.5 9l1.47.85-.75 1.3-1.47-.85V12h-1.5v-1.7l-1.47.85-.75-1.3L16.5 9l-1.47-.85zM9 8c1.65 0 3 1.35 3 3s-1.35 3-3 3-3-1.35-3-3 1.35-3 3-3z", "opacity" ".3"}) (e "path" #js {"d" "M9 14c1.65 0 3-1.35 3-3s-1.35-3-3-3-3 1.35-3 3 1.35 3 3 3zm0-4c.54 0 1 .46 1 1s-.46 1-1 1-1-.46-1-1 .46-1 1-1z"}) (e "path" #js {"d" "M22 3H2C.9 3 0 3.9 0 5v14c0 1.1.9 2 2 2h20c1.1 0 1.99-.9 1.99-2L24 5c0-1.1-.9-2-2-2zM4.54 19c1.1-1.22 2.69-2 4.46-2s3.36.78 4.46 2H4.54zM22 19h-6.08c-1.38-2.39-3.96-4-6.92-4s-5.54 1.61-6.92 4H2V5h20v14z"}) (e "path" #js {"d" "m15.78 11.15 1.47-.85V12h1.5v-1.7l1.47.85.75-1.3L19.5 9l1.47-.85-.75-1.3-1.47.85V6h-1.5v1.7l-1.47-.85-.75 1.3L16.5 9l-1.47.85z"})]
"ContactEmergencyTwoTone"))
|
|
2de553bf49f87a20dded9e9436e431d442d6f75c7b567ee0cf8c3f2cd5d7c958 | cstar/ejabberd-old | extract_translations.erl | %%%----------------------------------------------------------------------
%%% File : extract_translations.erl
Author : < >
%%% Purpose : Auxiliary tool for interface/messages translators
Created : 23 Apr 2005 by < >
I d :
%%%----------------------------------------------------------------------
-module(extract_translations).
-author('').
-export([start/0]).
-define(STATUS_SUCCESS, 0).
-define(STATUS_ERROR, 1).
-define(STATUS_USAGE, 2).
-include_lib("kernel/include/file.hrl").
start() ->
ets:new(translations, [named_table, public]),
ets:new(translations_obsolete, [named_table, public]),
ets:new(files, [named_table, public]),
ets:new(vars, [named_table, public]),
case init:get_plain_arguments() of
["-srcmsg2po", Dir, File] ->
print_po_header(File),
Status = process(Dir, File, srcmsg2po),
halt(Status);
["-unused", Dir, File] ->
Status = process(Dir, File, unused),
halt(Status);
[Dir, File] ->
Status = process(Dir, File, used),
halt(Status);
_ ->
print_usage(),
halt(?STATUS_USAGE)
end.
process(Dir, File, Used) ->
case load_file(File) of
{error, Reason} ->
io:format("~s: ~s~n", [File, file:format_error(Reason)]),
?STATUS_ERROR;
_ ->
FileList = find_src_files(Dir),
lists:foreach(
fun(F) ->
parse_file(Dir, F, Used)
end, FileList),
case Used of
unused ->
ets:foldl(fun({Key, _}, _) ->
io:format("~p~n", [Key])
end, ok, translations);
srcmsg2po ->
ets:foldl(fun({Key, Trans}, _) ->
print_translation_obsolete(Key, Trans)
end, ok, translations_obsolete);
_ ->
ok
end,
?STATUS_SUCCESS
end.
parse_file(Dir, File, Used) ->
ets:delete_all_objects(vars),
case epp:parse_file(File, [Dir, filename:dirname(File) | code:get_path()], []) of
{ok, Forms} ->
lists:foreach(
fun(F) ->
parse_form(Dir, File, F, Used)
end, Forms);
_ ->
ok
end.
parse_form(Dir, File, Form, Used) ->
case Form of
%%{undefined, Something} ->
%% io:format("Undefined: ~p~n", [Something]);
{call,
_,
{remote, _, {atom, _, translate}, {atom, _, translate}},
[_, {string, Line, Str}]
} ->
process_string(Dir, File, Line, Str, Used);
{call,
_,
{remote, _, {atom, _, translate}, {atom, _, translate}},
[_, {var, _, Name}]
} ->
case ets:lookup(vars, Name) of
[{_Name, Value, Line}] ->
process_string(Dir, File, Line, Value, Used);
_ ->
ok
end;
{match,
_,
{var, _, Name},
{string, Line, Value}
} ->
ets:insert(vars, {Name, Value, Line});
L when is_list(L) ->
lists:foreach(
fun(F) ->
parse_form(Dir, File, F, Used)
end, L);
T when is_tuple(T) ->
lists:foreach(
fun(F) ->
parse_form(Dir, File, F, Used)
end, tuple_to_list(T));
_ ->
ok
end.
process_string(_Dir, _File, _Line, "", _Used) ->
ok;
process_string(_Dir, File, Line, Str, Used) ->
case {ets:lookup(translations, Str), Used} of
{[{_Key, _Trans}], unused} ->
ets:delete(translations, Str);
{[{_Key, _Trans}], used} ->
ok;
{[{_Key, Trans}], srcmsg2po} ->
ets:delete(translations_obsolete, Str),
print_translation(File, Line, Str, Trans);
{_, used} ->
case ets:lookup(files, File) of
[{_}] ->
ok;
_ ->
io:format("~n% ~s~n", [File]),
ets:insert(files, {File})
end,
case Str of
[] -> ok;
_ -> io:format("{~p, \"\"}.~n", [Str])
end,
ets:insert(translations, {Str, ""});
{_, srcmsg2po} ->
case ets:lookup(files, File) of
[{_}] ->
ok;
_ ->
ets:insert(files, {File})
end,
ets:insert(translations, {Str, ""}),
print_translation(File, Line, Str, "");
_ ->
ok
end.
load_file(File) ->
case file:consult(File) of
{ok, Terms} ->
lists:foreach(
fun({Orig, Trans}) ->
case Trans of
"" ->
ok;
_ ->
ets:insert(translations, {Orig, Trans}),
ets:insert(translations_obsolete, {Orig, Trans})
end
end, Terms);
Err ->
Err
end.
find_src_files(Dir) ->
case file:list_dir(Dir) of
{ok, FileList} ->
recurse_filelist(
lists:map(
fun(F) ->
filename:join(Dir, F)
end, FileList));
_ ->
[]
end.
recurse_filelist(FileList) ->
recurse_filelist(FileList, []).
recurse_filelist([], Acc) ->
lists:reverse(Acc);
recurse_filelist([H | T], Acc) ->
case file:read_file_info(H) of
{ok, #file_info{type = directory}} ->
recurse_filelist(T, lists:reverse(find_src_files(H)) ++ Acc);
{ok, #file_info{type = regular}} ->
case string:substr(H, string:len(H) - 3) of
".erl" ->
recurse_filelist(T, [H | Acc]);
".hrl" ->
recurse_filelist(T, [H | Acc]);
_ ->
recurse_filelist(T, Acc)
end;
_ ->
recurse_filelist(T, Acc)
end.
print_usage() ->
io:format(
"Usage: extract_translations [-unused] dir file~n"
"~n"
"Example:~n"
" extract_translations . ./msgs/ru.msg~n"
).
%%%
Gettext
%%%
print_po_header(File) ->
MsgProps = get_msg_header_props(File),
{Language, [LastT | AddT]} = prepare_props(MsgProps),
application:load(ejabberd),
{ok, Version} = application:get_key(ejabberd, vsn),
print_po_header(Version, Language, LastT, AddT).
get_msg_header_props(File) ->
{ok, F} = file:open(File, [read]),
Lines = get_msg_header_props(F, []),
file:close(F),
Lines.
get_msg_header_props(F, Lines) ->
String = io:get_line(F, ""),
case io_lib:fread("% ", String) of
{ok, [], RemString} ->
case io_lib:fread("~s", RemString) of
{ok, [Key], Value} when Value /= "\n" ->
The first character in Value is a blankspace :
%% And the last characters are 'slash n'
ValueClean = string:substr(Value, 2, string:len(Value)-2),
get_msg_header_props(F, Lines ++ [{Key, ValueClean}]);
_ ->
get_msg_header_props(F, Lines)
end;
_ ->
Lines
end.
prepare_props(MsgProps) ->
Language = proplists:get_value("Language:", MsgProps),
Authors = proplists:get_all_values("Author:", MsgProps),
{Language, Authors}.
print_po_header(Version, Language, LastTranslator, AdditionalTranslatorsList) ->
AdditionalTranslatorsString = build_additional_translators(AdditionalTranslatorsList),
HeaderString =
"msgid \"\"\n"
"msgstr \"\"\n"
"\"Project-Id-Version: " ++ Version ++ "\\n\"\n"
++ "\"X-Language: " ++ Language ++ "\\n\"\n"
"\"Last-Translator: " ++ LastTranslator ++ "\\n\"\n"
++ AdditionalTranslatorsString ++
"\"MIME-Version: 1.0\\n\"\n"
"\"Content-Type: text/plain; charset=UTF-8\\n\"\n"
"\"Content-Transfer-Encoding: 8bit\\n\"\n",
io:format("~s~n", [HeaderString]).
build_additional_translators(List) ->
lists:foldl(
fun(T, Str) ->
Str ++ "\"X-Additional-Translator: " ++ T ++ "\\n\"\n"
end,
"",
List).
print_translation(File, Line, Str, StrT) ->
{ok, StrQ, _} = regexp:gsub(Str, "\"", "\\\""),
{ok, StrTQ, _} = regexp:gsub(StrT, "\"", "\\\""),
io:format("#: ~s:~p~nmsgid \"~s\"~nmsgstr \"~s\"~n~n", [File, Line, StrQ, StrTQ]).
print_translation_obsolete(Str, StrT) ->
File = "unknown.erl",
Line = 1,
{ok, StrQ, _} = regexp:gsub(Str, "\"", "\\\""),
{ok, StrTQ, _} = regexp:gsub(StrT, "\"", "\\\""),
io:format("#: ~s:~p~n#~~ msgid \"~s\"~n#~~ msgstr \"~s\"~n~n", [File, Line, StrQ, StrTQ]).
| null | https://raw.githubusercontent.com/cstar/ejabberd-old/559f8b6b0a935710fe93e9afacb4270d6d6ea00f/contrib/extract_translations/extract_translations.erl | erlang | ----------------------------------------------------------------------
File : extract_translations.erl
Purpose : Auxiliary tool for interface/messages translators
----------------------------------------------------------------------
{undefined, Something} ->
io:format("Undefined: ~p~n", [Something]);
And the last characters are 'slash n' | Author : < >
Created : 23 Apr 2005 by < >
I d :
-module(extract_translations).
-author('').
-export([start/0]).
-define(STATUS_SUCCESS, 0).
-define(STATUS_ERROR, 1).
-define(STATUS_USAGE, 2).
-include_lib("kernel/include/file.hrl").
start() ->
ets:new(translations, [named_table, public]),
ets:new(translations_obsolete, [named_table, public]),
ets:new(files, [named_table, public]),
ets:new(vars, [named_table, public]),
case init:get_plain_arguments() of
["-srcmsg2po", Dir, File] ->
print_po_header(File),
Status = process(Dir, File, srcmsg2po),
halt(Status);
["-unused", Dir, File] ->
Status = process(Dir, File, unused),
halt(Status);
[Dir, File] ->
Status = process(Dir, File, used),
halt(Status);
_ ->
print_usage(),
halt(?STATUS_USAGE)
end.
process(Dir, File, Used) ->
case load_file(File) of
{error, Reason} ->
io:format("~s: ~s~n", [File, file:format_error(Reason)]),
?STATUS_ERROR;
_ ->
FileList = find_src_files(Dir),
lists:foreach(
fun(F) ->
parse_file(Dir, F, Used)
end, FileList),
case Used of
unused ->
ets:foldl(fun({Key, _}, _) ->
io:format("~p~n", [Key])
end, ok, translations);
srcmsg2po ->
ets:foldl(fun({Key, Trans}, _) ->
print_translation_obsolete(Key, Trans)
end, ok, translations_obsolete);
_ ->
ok
end,
?STATUS_SUCCESS
end.
parse_file(Dir, File, Used) ->
ets:delete_all_objects(vars),
case epp:parse_file(File, [Dir, filename:dirname(File) | code:get_path()], []) of
{ok, Forms} ->
lists:foreach(
fun(F) ->
parse_form(Dir, File, F, Used)
end, Forms);
_ ->
ok
end.
parse_form(Dir, File, Form, Used) ->
case Form of
{call,
_,
{remote, _, {atom, _, translate}, {atom, _, translate}},
[_, {string, Line, Str}]
} ->
process_string(Dir, File, Line, Str, Used);
{call,
_,
{remote, _, {atom, _, translate}, {atom, _, translate}},
[_, {var, _, Name}]
} ->
case ets:lookup(vars, Name) of
[{_Name, Value, Line}] ->
process_string(Dir, File, Line, Value, Used);
_ ->
ok
end;
{match,
_,
{var, _, Name},
{string, Line, Value}
} ->
ets:insert(vars, {Name, Value, Line});
L when is_list(L) ->
lists:foreach(
fun(F) ->
parse_form(Dir, File, F, Used)
end, L);
T when is_tuple(T) ->
lists:foreach(
fun(F) ->
parse_form(Dir, File, F, Used)
end, tuple_to_list(T));
_ ->
ok
end.
process_string(_Dir, _File, _Line, "", _Used) ->
ok;
process_string(_Dir, File, Line, Str, Used) ->
case {ets:lookup(translations, Str), Used} of
{[{_Key, _Trans}], unused} ->
ets:delete(translations, Str);
{[{_Key, _Trans}], used} ->
ok;
{[{_Key, Trans}], srcmsg2po} ->
ets:delete(translations_obsolete, Str),
print_translation(File, Line, Str, Trans);
{_, used} ->
case ets:lookup(files, File) of
[{_}] ->
ok;
_ ->
io:format("~n% ~s~n", [File]),
ets:insert(files, {File})
end,
case Str of
[] -> ok;
_ -> io:format("{~p, \"\"}.~n", [Str])
end,
ets:insert(translations, {Str, ""});
{_, srcmsg2po} ->
case ets:lookup(files, File) of
[{_}] ->
ok;
_ ->
ets:insert(files, {File})
end,
ets:insert(translations, {Str, ""}),
print_translation(File, Line, Str, "");
_ ->
ok
end.
load_file(File) ->
case file:consult(File) of
{ok, Terms} ->
lists:foreach(
fun({Orig, Trans}) ->
case Trans of
"" ->
ok;
_ ->
ets:insert(translations, {Orig, Trans}),
ets:insert(translations_obsolete, {Orig, Trans})
end
end, Terms);
Err ->
Err
end.
find_src_files(Dir) ->
case file:list_dir(Dir) of
{ok, FileList} ->
recurse_filelist(
lists:map(
fun(F) ->
filename:join(Dir, F)
end, FileList));
_ ->
[]
end.
recurse_filelist(FileList) ->
recurse_filelist(FileList, []).
recurse_filelist([], Acc) ->
lists:reverse(Acc);
recurse_filelist([H | T], Acc) ->
case file:read_file_info(H) of
{ok, #file_info{type = directory}} ->
recurse_filelist(T, lists:reverse(find_src_files(H)) ++ Acc);
{ok, #file_info{type = regular}} ->
case string:substr(H, string:len(H) - 3) of
".erl" ->
recurse_filelist(T, [H | Acc]);
".hrl" ->
recurse_filelist(T, [H | Acc]);
_ ->
recurse_filelist(T, Acc)
end;
_ ->
recurse_filelist(T, Acc)
end.
print_usage() ->
io:format(
"Usage: extract_translations [-unused] dir file~n"
"~n"
"Example:~n"
" extract_translations . ./msgs/ru.msg~n"
).
Gettext
print_po_header(File) ->
MsgProps = get_msg_header_props(File),
{Language, [LastT | AddT]} = prepare_props(MsgProps),
application:load(ejabberd),
{ok, Version} = application:get_key(ejabberd, vsn),
print_po_header(Version, Language, LastT, AddT).
get_msg_header_props(File) ->
{ok, F} = file:open(File, [read]),
Lines = get_msg_header_props(F, []),
file:close(F),
Lines.
get_msg_header_props(F, Lines) ->
String = io:get_line(F, ""),
case io_lib:fread("% ", String) of
{ok, [], RemString} ->
case io_lib:fread("~s", RemString) of
{ok, [Key], Value} when Value /= "\n" ->
The first character in Value is a blankspace :
ValueClean = string:substr(Value, 2, string:len(Value)-2),
get_msg_header_props(F, Lines ++ [{Key, ValueClean}]);
_ ->
get_msg_header_props(F, Lines)
end;
_ ->
Lines
end.
prepare_props(MsgProps) ->
Language = proplists:get_value("Language:", MsgProps),
Authors = proplists:get_all_values("Author:", MsgProps),
{Language, Authors}.
print_po_header(Version, Language, LastTranslator, AdditionalTranslatorsList) ->
AdditionalTranslatorsString = build_additional_translators(AdditionalTranslatorsList),
HeaderString =
"msgid \"\"\n"
"msgstr \"\"\n"
"\"Project-Id-Version: " ++ Version ++ "\\n\"\n"
++ "\"X-Language: " ++ Language ++ "\\n\"\n"
"\"Last-Translator: " ++ LastTranslator ++ "\\n\"\n"
++ AdditionalTranslatorsString ++
"\"MIME-Version: 1.0\\n\"\n"
"\"Content-Type: text/plain; charset=UTF-8\\n\"\n"
"\"Content-Transfer-Encoding: 8bit\\n\"\n",
io:format("~s~n", [HeaderString]).
build_additional_translators(List) ->
lists:foldl(
fun(T, Str) ->
Str ++ "\"X-Additional-Translator: " ++ T ++ "\\n\"\n"
end,
"",
List).
print_translation(File, Line, Str, StrT) ->
{ok, StrQ, _} = regexp:gsub(Str, "\"", "\\\""),
{ok, StrTQ, _} = regexp:gsub(StrT, "\"", "\\\""),
io:format("#: ~s:~p~nmsgid \"~s\"~nmsgstr \"~s\"~n~n", [File, Line, StrQ, StrTQ]).
print_translation_obsolete(Str, StrT) ->
File = "unknown.erl",
Line = 1,
{ok, StrQ, _} = regexp:gsub(Str, "\"", "\\\""),
{ok, StrTQ, _} = regexp:gsub(StrT, "\"", "\\\""),
io:format("#: ~s:~p~n#~~ msgid \"~s\"~n#~~ msgstr \"~s\"~n~n", [File, Line, StrQ, StrTQ]).
|
45109649b132c07749818943743cf23246e4b8ef907ed4217d9836553be5d581 | marcelog/erlagi | erlagi_debug.erl | Useful to debug the IVR .
%%%
Copyright 2012 < >
%%%
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(erlagi_debug).
-author("Marcelo Gornstein <>").
-github("").
-homepage("/").
-license("Apache License 2.0").
-include("erlagi_types.hrl").
-export([print_result/1, print_agicall/1]).
print_result(#agiresult{} = Result) ->
lager:debug(
"----- AgiResult -----~n"
++ "Command: ~s~n"
++ "Raw: ~s~n"
++ "Result: ~s~n"
++ "Digits: ~s~n"
++ "Timeout: ~s~n"
++ "Offset: ~s~n"
++ "Data: ~s~n"
++ "---------------------~n", [
erlagi_result:get_cmd(Result),
erlagi_result:get_raw(Result),
erlagi_result:get_result(Result),
erlagi_result:get_digits(Result),
erlagi_result:is_timeout(Result),
erlagi_result:get_offset(Result),
erlagi_result:get_data(Result)
]).
print_variable({Key, Value}) ->
lager:debug("Variable [ ~s = ~s ]~n", [Key, Value]).
print_agicall(#agicall{environment = Env}) ->
lager:debug("----- AgiCall -----~n"),
[ print_variable(V) || V <- Env],
lager:debug("-------------------~n").
| null | https://raw.githubusercontent.com/marcelog/erlagi/fd406e9b55a04ce14c0e68d7b87bd769a3dd7a6f/src/erlagi_debug.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. | Useful to debug the IVR .
Copyright 2012 < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(erlagi_debug).
-author("Marcelo Gornstein <>").
-github("").
-homepage("/").
-license("Apache License 2.0").
-include("erlagi_types.hrl").
-export([print_result/1, print_agicall/1]).
print_result(#agiresult{} = Result) ->
lager:debug(
"----- AgiResult -----~n"
++ "Command: ~s~n"
++ "Raw: ~s~n"
++ "Result: ~s~n"
++ "Digits: ~s~n"
++ "Timeout: ~s~n"
++ "Offset: ~s~n"
++ "Data: ~s~n"
++ "---------------------~n", [
erlagi_result:get_cmd(Result),
erlagi_result:get_raw(Result),
erlagi_result:get_result(Result),
erlagi_result:get_digits(Result),
erlagi_result:is_timeout(Result),
erlagi_result:get_offset(Result),
erlagi_result:get_data(Result)
]).
print_variable({Key, Value}) ->
lager:debug("Variable [ ~s = ~s ]~n", [Key, Value]).
print_agicall(#agicall{environment = Env}) ->
lager:debug("----- AgiCall -----~n"),
[ print_variable(V) || V <- Env],
lager:debug("-------------------~n").
|
9deafa87123829bf2fee913d3c06a77a271cbba14d1b56da1716c4089419700a | hexresearch/reflex-material-bootstrap | Router.hs | module Web.Reflex.Bootstrap.Router(
Route(..)
, route
) where
import Reflex
import Reflex.Dom
-- | Like 'Fix' for FRP widget, allow to endlessly jump into
-- returned routes of widgets
newtype Route t m a = Route { unRoute :: Event t (m (a, Route t m a)) }
instance (Reflex t, Functor m) => Functor (Route t m) where
fmap f (Route e) = Route $ fmap (\(a, r) -> (f a, f <$> r)) <$> e
instance Reflex t => Monoid (Route t m a) where
mempty = Route never
(Route e1) `mappend` (Route e2) = Route $ leftmost [e1, e2]
-- | Run widget that can replace itself with new widget constructed
-- internally in the original widget.
route :: forall t m a . MonadWidget t m => m (a, Route t m a) -> m (Dynamic t a)
route w = do
rec (rd :: Dynamic t (a, Route t m a)) <- widgetHold w re
let rd' :: Dynamic t (Event t (m (a, Route t m a))) = unRoute . snd <$> rd
re :: Event t (m (a, Route t m a)) = switchPromptlyDyn rd'
pure $ fst <$> rd
| null | https://raw.githubusercontent.com/hexresearch/reflex-material-bootstrap/0dbf56c743f9739b4e1ec7af8a47cdd3062f85f7/src/Web/Reflex/Bootstrap/Router.hs | haskell | | Like 'Fix' for FRP widget, allow to endlessly jump into
returned routes of widgets
| Run widget that can replace itself with new widget constructed
internally in the original widget. | module Web.Reflex.Bootstrap.Router(
Route(..)
, route
) where
import Reflex
import Reflex.Dom
newtype Route t m a = Route { unRoute :: Event t (m (a, Route t m a)) }
instance (Reflex t, Functor m) => Functor (Route t m) where
fmap f (Route e) = Route $ fmap (\(a, r) -> (f a, f <$> r)) <$> e
instance Reflex t => Monoid (Route t m a) where
mempty = Route never
(Route e1) `mappend` (Route e2) = Route $ leftmost [e1, e2]
route :: forall t m a . MonadWidget t m => m (a, Route t m a) -> m (Dynamic t a)
route w = do
rec (rd :: Dynamic t (a, Route t m a)) <- widgetHold w re
let rd' :: Dynamic t (Event t (m (a, Route t m a))) = unRoute . snd <$> rd
re :: Event t (m (a, Route t m a)) = switchPromptlyDyn rd'
pure $ fst <$> rd
|
f27ce8c6d8ed8b37521a2e14f99d2b3b967f5d7a8e7db97f8a26a138a2d538e6 | CardanoSolutions/ogmios | TxSubmission.hs | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
-- | Transaction submission is pretty simple & works by submitting an already
serialized and signed transaction as one single message .
--
In case of success , Ogmios / the node returns an empty response . Otherwise ,
-- it returns an error with some details about what went wrong. Clients must
-- thereby know how to construct valid transactions.
--
Ogmios offers a slightly modified version of that protocol and allows to
-- only evaluate a transaction redeemers' execution units.
-- @
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
-- │ Busy │◀═══════════════════════════════════════╗
─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘ SubmitTx / EvaluateTx ║
-- │ ║
-- │ ┌──────────┐
│
│
│ SubmitTxResponse / EvaluateTxResponse │ Idle │
─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ▶ │ │
-- │ │⇦ START
-- └──────────┘
-- @
module Ogmios.App.Protocol.TxSubmission
( ExecutionUnitsEvaluator(..)
, mkTxSubmissionClient
, newExecutionUnitsEvaluator
) where
import Ogmios.Prelude
import Cardano.Ledger.Crypto
( StandardCrypto
)
import Cardano.Ledger.Era
( Crypto
)
import Control.Monad.Trans.Except
( Except
)
import Data.SOP.Strict
( NS (..)
)
import Data.Type.Equality
( testEquality
, (:~:) (..)
)
import GHC.Records
( HasField (..)
)
import Ogmios.Control.MonadSTM
( MonadSTM (..)
, TQueue
, newEmptyTMVar
, putTMVar
, readTQueue
, takeTMVar
)
import Ogmios.Data.EraTranslation
( MultiEraUTxO (..)
, translateTx
, translateUtxo
)
import Ogmios.Data.Json
( Json
)
import Ogmios.Data.Protocol.TxSubmission
( AlonzoEra
, BabbageEra
, BackwardCompatibleSubmitTx (..)
, CanEvaluateScriptsInEra
, EpochInfo
, EvaluateTx (..)
, EvaluateTxError (..)
, EvaluateTxResponse (..)
, HasTxId
, PParams
, PastHorizonException
, SerializedTx
, SubmitTx (..)
, SubmitTxError
, SystemStart
, Tx
, TxIn
, TxSubmissionCodecs (..)
, TxSubmissionMessage (..)
, UTxO (..)
, evaluateExecutionUnits
, incompatibleEra
, mkSubmitTxResponse
, notEnoughSynced
)
import Ouroboros.Consensus.Cardano.Block
( BlockQuery (..)
, CardanoBlock
, CardanoEras
, CardanoQueryResult
, GenTx (..)
)
import Ouroboros.Consensus.HardFork.Combinator
( EraIndex (..)
, HardForkBlock
)
import Ouroboros.Consensus.HardFork.Combinator.Ledger.Query
( QueryHardFork (..)
)
import Ouroboros.Consensus.HardFork.History
( interpreterToEpochInfo
)
import Ouroboros.Consensus.Ledger.Query
( Query (..)
)
import Ouroboros.Consensus.Protocol.Praos
( Praos
)
import Ouroboros.Consensus.Protocol.TPraos
( TPraos
)
import Ouroboros.Consensus.Shelley.Ledger
( GenTx (..)
)
import Ouroboros.Consensus.Shelley.Ledger.Block
( ShelleyBlock
)
import Ouroboros.Consensus.Shelley.Ledger.Query
( BlockQuery (..)
)
import Ouroboros.Network.Block
( Point (..)
)
import Ouroboros.Network.Protocol.LocalStateQuery.Client
( LocalStateQueryClient (..)
)
import Ouroboros.Network.Protocol.LocalTxSubmission.Client
( LocalTxClientStIdle (..)
, LocalTxSubmissionClient (..)
)
import Type.Reflection
( typeRep
)
import qualified Data.Map.Strict as Map
import qualified Ouroboros.Consensus.HardFork.Combinator as LSQ
import qualified Ouroboros.Consensus.Ledger.Query as Ledger
import qualified Ouroboros.Network.Protocol.LocalStateQuery.Client as LSQ
mkTxSubmissionClient
:: forall m block.
( MonadSTM m
, HasTxId (SerializedTx block)
)
=> TxSubmissionCodecs block
^ For encoding types to JSON
-> ExecutionUnitsEvaluator m block
-- ^ An interface for evaluating transaction execution units
-> TQueue m (TxSubmissionMessage block)
-- ^ Incoming request queue
-> (Json -> m ())
-- ^ An emitter for yielding JSON objects
-> LocalTxSubmissionClient (SerializedTx block) (SubmitTxError block) m ()
mkTxSubmissionClient TxSubmissionCodecs{..} ExecutionUnitsEvaluator{..} queue yield = do
LocalTxSubmissionClient clientStIdle
where
await :: m (TxSubmissionMessage block)
await = atomically (readTQueue queue)
clientStIdle
:: m (LocalTxClientStIdle (SerializedTx block) (SubmitTxError block) m ())
clientStIdle = await >>= \case
MsgBackwardCompatibleSubmitTx BackwardCompatibleSubmitTx{bytes = tx} toResponse _ -> do
pure $ SendMsgSubmitTx tx $ \result -> do
yield $ encodeBackwardCompatibleSubmitTxResponse $ toResponse result
clientStIdle
MsgSubmitTx SubmitTx{submit = tx} toResponse _ -> do
pure $ SendMsgSubmitTx tx $ \result -> do
yield $ encodeSubmitTxResponse $ toResponse $ mkSubmitTxResponse tx result
clientStIdle
MsgEvaluateTx EvaluateTx{additionalUtxoSet, evaluate = tx} toResponse _ -> do
result <- evaluateExecutionUnitsM (additionalUtxoSet, tx)
yield $ encodeEvaluateTxResponse $ toResponse result
clientStIdle
-- | A thin abstraction for evaluating transaction units.
data ExecutionUnitsEvaluator m block = ExecutionUnitsEvaluator
{ evaluateExecutionUnitsM
:: (MultiEraUTxO block, GenTx block)
-> m (EvaluateTxResponse block)
}
-- | Construct an effectful 'ExecutionUnitsEvaluator'; this requires to wire a
-- local-state-query client to the node.
newExecutionUnitsEvaluator
:: forall m block crypto.
( MonadSTM m
, block ~ HardForkBlock (CardanoEras crypto)
, crypto ~ StandardCrypto
, CanEvaluateScriptsInEra (AlonzoEra crypto)
, CanEvaluateScriptsInEra (BabbageEra crypto)
)
=> m ( ExecutionUnitsEvaluator m block
, LocalStateQueryClient block (Point block) (Query block) m ()
)
newExecutionUnitsEvaluator = do
evaluateExecutionUnitsRequest <- atomically newEmptyTMVar
evaluateExecutionUnitsResponse <- atomically newEmptyTMVar
let runEvaluation = either return $ \eval -> do
atomically $ putTMVar evaluateExecutionUnitsRequest eval
atomically $ takeTMVar evaluateExecutionUnitsResponse
return
( ExecutionUnitsEvaluator
{ evaluateExecutionUnitsM = runEvaluation . \case
(_, GenTxByron{}) ->
Left (incompatibleEra "Byron")
(_, GenTxShelley{}) ->
Left (incompatibleEra "Shelley")
(_, GenTxAllegra{}) ->
Left (incompatibleEra "Allegra")
(_, GenTxMary{}) ->
Left (incompatibleEra "Mary")
(UTxOInAlonzoEra utxo, GenTxAlonzo (ShelleyTx _id tx)) -> do
Right (SomeEvaluationInAnyEra utxo tx)
(UTxOInAlonzoEra utxo, GenTxBabbage (ShelleyTx _id tx)) -> do
Right (SomeEvaluationInAnyEra (translateUtxo utxo) tx)
(UTxOInBabbageEra utxo, GenTxAlonzo (ShelleyTx _id tx)) -> do
Right (SomeEvaluationInAnyEra utxo (translateTx tx))
(UTxOInBabbageEra utxo, GenTxBabbage (ShelleyTx _id tx)) -> do
Right (SomeEvaluationInAnyEra utxo tx)
}
, localStateQueryClient
(atomically $ takeTMVar evaluateExecutionUnitsRequest)
(atomically . putTMVar evaluateExecutionUnitsResponse)
)
where
localStateQueryClient
:: m SomeEvaluationInAnyEra
-> (EvaluateTxResponse block -> m ())
-> LocalStateQueryClient block (Point block) (Query block) m ()
localStateQueryClient await reply =
LocalStateQueryClient clientStIdle
where
clientStIdle
:: m (LSQ.ClientStIdle block (Point block) (Query block) m ())
clientStIdle = pure $ do
NOTE : This little ' dance ' of acquiring first is needed because of :
--
--
--
-- and ideally, can be removed once the upstream fix:
--
-- -output-hk/ouroboros-network/pull/3844
--
-- has shipped with cardano-node (and it's been long-enough that we
-- can exclude old clients from needing this).
LSQ.SendMsgAcquire Nothing $ LSQ.ClientStAcquiring
{ LSQ.recvMsgAcquired = do
reAcquire <$> await
, LSQ.recvMsgFailure =
const clientStIdle
}
clientStAcquiring
:: SomeEvaluationInAnyEra
-> LSQ.ClientStAcquiring block (Point block) (Query block) m ()
clientStAcquiring args =
LSQ.ClientStAcquiring
{ LSQ.recvMsgAcquired = pure $ selectEra
-- Default / Fallback
(\era -> do
reply (notEnoughSynced era)
pure $ LSQ.SendMsgRelease clientStIdle
)
(clientStAcquired0 @_ @(AlonzoEra crypto) args evaluateExecutionUnits)
-- Babbage
(clientStAcquired0 @_ @(BabbageEra crypto) args evaluateExecutionUnits)
, LSQ.recvMsgFailure =
const $ pure $ LSQ.SendMsgAcquire Nothing (clientStAcquiring args)
}
reAcquire
:: SomeEvaluationInAnyEra
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
reAcquire
= LSQ.SendMsgReAcquire Nothing . clientStAcquiring
clientStAcquired0
:: forall proto era. (CanEvaluateScriptsInEra era)
=> SomeEvaluationInAnyEra
-> ( PParams era
-> SystemStart
-> EpochInfo (Except PastHorizonException)
-> UTxO era
-> Tx era
-> EvaluateTxResponse block
)
-> HoistQuery proto era
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
clientStAcquired0 args callback hoistQuery = do
let query = BlockQuery (hoistQuery GetCurrentPParams)
in LSQ.SendMsgQuery query $ LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \case
Right pparams ->
pure $ clientStAcquired1 args (callback pparams) hoistQuery
Left{} ->
pure $ reAcquire args
}
clientStAcquired1
:: forall proto era. (CanEvaluateScriptsInEra era)
=> SomeEvaluationInAnyEra
-> ( SystemStart
-> EpochInfo (Except PastHorizonException)
-> UTxO era
-> Tx era
-> EvaluateTxResponse block
)
-> HoistQuery proto era
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
clientStAcquired1 args callback hoistQuery = do
let query = GetSystemStart
in LSQ.SendMsgQuery query $ LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \systemStart ->
pure $ clientStAcquired2 args (callback systemStart) hoistQuery
}
clientStAcquired2
:: forall proto era. (CanEvaluateScriptsInEra era)
=> SomeEvaluationInAnyEra
-> ( EpochInfo (Except PastHorizonException)
-> UTxO era
-> Tx era
-> EvaluateTxResponse block
)
-> HoistQuery proto era
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
clientStAcquired2 args callback hoistQuery = do
let query = BlockQuery $ QueryHardFork GetInterpreter
in LSQ.SendMsgQuery query $ LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \(interpreterToEpochInfo -> epochInfo) ->
pure $ clientStAcquired3 args (callback epochInfo) hoistQuery
}
clientStAcquired3
:: forall proto era. (CanEvaluateScriptsInEra era)
=> SomeEvaluationInAnyEra
-> ( UTxO era
-> Tx era
-> EvaluateTxResponse block
)
-> HoistQuery proto era
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
clientStAcquired3 args callback hoistQuery = do
let query = BlockQuery $ hoistQuery $ GetUTxOByTxIn (inputsInAnyEra args)
in LSQ.SendMsgQuery query $ LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \case
Right networkUtxo -> do
reply (mkEvaluateTxResponse @era callback networkUtxo args)
pure (LSQ.SendMsgRelease clientStIdle)
Left{} ->
pure $ reAcquire args
}
type HoistQuery proto era =
forall r a crypto. (crypto ~ Crypto era, CardanoQueryResult crypto r ~ a)
=> BlockQuery (ShelleyBlock (proto crypto) era) r
-> BlockQuery (CardanoBlock crypto) a
| Run local - state queries in either or Babbage , depending on where the network is at .
--
-- This is crucial to allow the server to *dynamically* switch to the right era after the hard-fork.
selectEra
:: forall block crypto m.
( block ~ HardForkBlock (CardanoEras crypto)
, Applicative m
)
Default selector , when the network era is older than and does n't support Phase-2 scripts .
=> ( Text -> m (LSQ.ClientStAcquired block (Point block) (Query block) m ())
)
Selector for the era .
-> ( HoistQuery TPraos (AlonzoEra crypto) -> LSQ.ClientStAcquired block (Point block) (Query block) m ()
)
Selector for the Babbage era .
-> ( HoistQuery Praos (BabbageEra crypto) -> LSQ.ClientStAcquired block (Point block) (Query block) m ()
)
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
selectEra fallback asAlonzo asBabbage =
LSQ.SendMsgQuery (Ledger.BlockQuery $ LSQ.QueryHardFork LSQ.GetCurrentEra) $
LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \case
EraIndex Z{} -> fallback "Byron"
EraIndex (S Z{}) -> fallback "Shelley"
EraIndex (S (S Z{})) -> fallback "Allegra"
EraIndex (S (S (S Z{}))) -> fallback "Mary"
EraIndex (S (S (S (S Z{})))) -> pure (asAlonzo QueryIfCurrentAlonzo)
EraIndex (S (S (S (S (S Z{}))))) -> pure (asBabbage QueryIfCurrentBabbage)
}
--
-- SomeEvaluationInAnyEra
--
data SomeEvaluationInAnyEra where
SomeEvaluationInAnyEra
:: forall era. (CanEvaluateScriptsInEra era)
=> UTxO era
-> Tx era
-> SomeEvaluationInAnyEra
-- | Return all unspent transaction outputs needed for evaluation. This includes
-- standard inputs, but also reference ones and collaterals.
inputsInAnyEra
:: SomeEvaluationInAnyEra
-> Set (TxIn StandardCrypto)
inputsInAnyEra (SomeEvaluationInAnyEra _ tx) =
getField @"inputs" body
<>
getField @"collateral" body
<>
getField @"referenceInputs" body
where
body = getField @"body" tx
mkEvaluateTxResponse
:: forall era block crypto.
( CanEvaluateScriptsInEra era
, block ~ HardForkBlock (CardanoEras crypto)
, crypto ~ StandardCrypto
)
=> (UTxO era -> Tx era -> EvaluateTxResponse block)
^ fetched from the network
^ Tx & additional utxo
-> EvaluateTxResponse block
mkEvaluateTxResponse callback (UTxO networkUtxo) args =
case translateToNetworkEra @era args of
Nothing ->
error "impossible: arguments are not translatable to network era. \
\This can't happen because 'selectEra' enforces that queries \
\are only executed if the network is either in 'Alonzo' or \
\'Babbage'. The arguments themselves can also only be 'Alonzo' \
\or 'Babbage'. Thus, we can't reach this point with any other \
\eras. We _could_ potentially capture this proof in the types \
\to convince the compiler of this. Let's say: TODO."
Just (UTxO userProvidedUtxo, tx) ->
let
intersection = Map.intersection userProvidedUtxo networkUtxo
in
if null intersection
then
callback (UTxO $ userProvidedUtxo <> networkUtxo) tx
else
intersection
& Map.keysSet
& EvaluateTxAdditionalUtxoOverlap
& EvaluationFailure
| 99 % of the time , we only need to worry about one era : the current one ; yet , near hard - forks ,
-- there is a time where the application needs to be compatible with both the current era and the
-- upcoming one (or, depending on the perspective, the current era and the previous one).
--
-- A 'simple' way to handle this would be to enforce that the network era matches the era of the
-- arguments provided by the users. However this can be extremely inconvenient for users who now
-- need to change their application logic to also be hard-fork resilient. Since hard-fork generally
-- changes in a forward-compatible way, then we can instead upgrade (or translate) clients' requests
to the latest era when applicable .
--
-- This allows client applications to upgrade whenever they are ready, and keep using structures from
the previous era , even after the hard - fork has happened . We take the burden of detecting the era and
-- translating the request.
translateToNetworkEra
:: forall eraNetwork.
( CanEvaluateScriptsInEra eraNetwork
)
=> SomeEvaluationInAnyEra
-> Maybe (UTxO eraNetwork, Tx eraNetwork)
translateToNetworkEra (SomeEvaluationInAnyEra utxoOrig txOrig) =
translate utxoOrig txOrig
where
translate
:: forall eraArgs.
( CanEvaluateScriptsInEra eraArgs
)
=> UTxO eraArgs
-> Tx eraArgs
-> Maybe (UTxO eraNetwork, Tx eraNetwork)
translate utxo tx =
let
eraNetwork = typeRep @eraNetwork
eraAlonzo = typeRep @(AlonzoEra StandardCrypto)
eraArgs = typeRep @eraArgs
eraBabbage = typeRep @(BabbageEra StandardCrypto)
sameEra =
case (testEquality eraNetwork eraArgs) of
Just Refl ->
Just (utxo, tx)
_ ->
Nothing
alonzoToBabbage =
case (testEquality eraNetwork eraBabbage, testEquality eraArgs eraAlonzo) of
(Just Refl, Just Refl) -> do
Just (translateUtxo utxo, translateTx tx)
_ ->
Nothing
in
sameEra <|> alonzoToBabbage
| null | https://raw.githubusercontent.com/CardanoSolutions/ogmios/317c826d9d0388cb7efaf61a34085fc7c1b12b06/server/src/Ogmios/App/Protocol/TxSubmission.hs | haskell | | Transaction submission is pretty simple & works by submitting an already
it returns an error with some details about what went wrong. Clients must
thereby know how to construct valid transactions.
only evaluate a transaction redeemers' execution units.
@
│ Busy │◀═══════════════════════════════════════╗
│ ║
│ ┌──────────┐
│ │⇦ START
└──────────┘
@
^ An interface for evaluating transaction execution units
^ Incoming request queue
^ An emitter for yielding JSON objects
| A thin abstraction for evaluating transaction units.
| Construct an effectful 'ExecutionUnitsEvaluator'; this requires to wire a
local-state-query client to the node.
and ideally, can be removed once the upstream fix:
-output-hk/ouroboros-network/pull/3844
has shipped with cardano-node (and it's been long-enough that we
can exclude old clients from needing this).
Default / Fallback
Babbage
This is crucial to allow the server to *dynamically* switch to the right era after the hard-fork.
SomeEvaluationInAnyEra
| Return all unspent transaction outputs needed for evaluation. This includes
standard inputs, but also reference ones and collaterals.
there is a time where the application needs to be compatible with both the current era and the
upcoming one (or, depending on the perspective, the current era and the previous one).
A 'simple' way to handle this would be to enforce that the network era matches the era of the
arguments provided by the users. However this can be extremely inconvenient for users who now
need to change their application logic to also be hard-fork resilient. Since hard-fork generally
changes in a forward-compatible way, then we can instead upgrade (or translate) clients' requests
This allows client applications to upgrade whenever they are ready, and keep using structures from
translating the request. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
serialized and signed transaction as one single message .
In case of success , Ogmios / the node returns an empty response . Otherwise ,
Ogmios offers a slightly modified version of that protocol and allows to
┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐
─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ┘ SubmitTx / EvaluateTx ║
│
│
│ SubmitTxResponse / EvaluateTxResponse │ Idle │
─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ▶ │ │
module Ogmios.App.Protocol.TxSubmission
( ExecutionUnitsEvaluator(..)
, mkTxSubmissionClient
, newExecutionUnitsEvaluator
) where
import Ogmios.Prelude
import Cardano.Ledger.Crypto
( StandardCrypto
)
import Cardano.Ledger.Era
( Crypto
)
import Control.Monad.Trans.Except
( Except
)
import Data.SOP.Strict
( NS (..)
)
import Data.Type.Equality
( testEquality
, (:~:) (..)
)
import GHC.Records
( HasField (..)
)
import Ogmios.Control.MonadSTM
( MonadSTM (..)
, TQueue
, newEmptyTMVar
, putTMVar
, readTQueue
, takeTMVar
)
import Ogmios.Data.EraTranslation
( MultiEraUTxO (..)
, translateTx
, translateUtxo
)
import Ogmios.Data.Json
( Json
)
import Ogmios.Data.Protocol.TxSubmission
( AlonzoEra
, BabbageEra
, BackwardCompatibleSubmitTx (..)
, CanEvaluateScriptsInEra
, EpochInfo
, EvaluateTx (..)
, EvaluateTxError (..)
, EvaluateTxResponse (..)
, HasTxId
, PParams
, PastHorizonException
, SerializedTx
, SubmitTx (..)
, SubmitTxError
, SystemStart
, Tx
, TxIn
, TxSubmissionCodecs (..)
, TxSubmissionMessage (..)
, UTxO (..)
, evaluateExecutionUnits
, incompatibleEra
, mkSubmitTxResponse
, notEnoughSynced
)
import Ouroboros.Consensus.Cardano.Block
( BlockQuery (..)
, CardanoBlock
, CardanoEras
, CardanoQueryResult
, GenTx (..)
)
import Ouroboros.Consensus.HardFork.Combinator
( EraIndex (..)
, HardForkBlock
)
import Ouroboros.Consensus.HardFork.Combinator.Ledger.Query
( QueryHardFork (..)
)
import Ouroboros.Consensus.HardFork.History
( interpreterToEpochInfo
)
import Ouroboros.Consensus.Ledger.Query
( Query (..)
)
import Ouroboros.Consensus.Protocol.Praos
( Praos
)
import Ouroboros.Consensus.Protocol.TPraos
( TPraos
)
import Ouroboros.Consensus.Shelley.Ledger
( GenTx (..)
)
import Ouroboros.Consensus.Shelley.Ledger.Block
( ShelleyBlock
)
import Ouroboros.Consensus.Shelley.Ledger.Query
( BlockQuery (..)
)
import Ouroboros.Network.Block
( Point (..)
)
import Ouroboros.Network.Protocol.LocalStateQuery.Client
( LocalStateQueryClient (..)
)
import Ouroboros.Network.Protocol.LocalTxSubmission.Client
( LocalTxClientStIdle (..)
, LocalTxSubmissionClient (..)
)
import Type.Reflection
( typeRep
)
import qualified Data.Map.Strict as Map
import qualified Ouroboros.Consensus.HardFork.Combinator as LSQ
import qualified Ouroboros.Consensus.Ledger.Query as Ledger
import qualified Ouroboros.Network.Protocol.LocalStateQuery.Client as LSQ
mkTxSubmissionClient
:: forall m block.
( MonadSTM m
, HasTxId (SerializedTx block)
)
=> TxSubmissionCodecs block
^ For encoding types to JSON
-> ExecutionUnitsEvaluator m block
-> TQueue m (TxSubmissionMessage block)
-> (Json -> m ())
-> LocalTxSubmissionClient (SerializedTx block) (SubmitTxError block) m ()
mkTxSubmissionClient TxSubmissionCodecs{..} ExecutionUnitsEvaluator{..} queue yield = do
LocalTxSubmissionClient clientStIdle
where
await :: m (TxSubmissionMessage block)
await = atomically (readTQueue queue)
clientStIdle
:: m (LocalTxClientStIdle (SerializedTx block) (SubmitTxError block) m ())
clientStIdle = await >>= \case
MsgBackwardCompatibleSubmitTx BackwardCompatibleSubmitTx{bytes = tx} toResponse _ -> do
pure $ SendMsgSubmitTx tx $ \result -> do
yield $ encodeBackwardCompatibleSubmitTxResponse $ toResponse result
clientStIdle
MsgSubmitTx SubmitTx{submit = tx} toResponse _ -> do
pure $ SendMsgSubmitTx tx $ \result -> do
yield $ encodeSubmitTxResponse $ toResponse $ mkSubmitTxResponse tx result
clientStIdle
MsgEvaluateTx EvaluateTx{additionalUtxoSet, evaluate = tx} toResponse _ -> do
result <- evaluateExecutionUnitsM (additionalUtxoSet, tx)
yield $ encodeEvaluateTxResponse $ toResponse result
clientStIdle
data ExecutionUnitsEvaluator m block = ExecutionUnitsEvaluator
{ evaluateExecutionUnitsM
:: (MultiEraUTxO block, GenTx block)
-> m (EvaluateTxResponse block)
}
newExecutionUnitsEvaluator
:: forall m block crypto.
( MonadSTM m
, block ~ HardForkBlock (CardanoEras crypto)
, crypto ~ StandardCrypto
, CanEvaluateScriptsInEra (AlonzoEra crypto)
, CanEvaluateScriptsInEra (BabbageEra crypto)
)
=> m ( ExecutionUnitsEvaluator m block
, LocalStateQueryClient block (Point block) (Query block) m ()
)
newExecutionUnitsEvaluator = do
evaluateExecutionUnitsRequest <- atomically newEmptyTMVar
evaluateExecutionUnitsResponse <- atomically newEmptyTMVar
let runEvaluation = either return $ \eval -> do
atomically $ putTMVar evaluateExecutionUnitsRequest eval
atomically $ takeTMVar evaluateExecutionUnitsResponse
return
( ExecutionUnitsEvaluator
{ evaluateExecutionUnitsM = runEvaluation . \case
(_, GenTxByron{}) ->
Left (incompatibleEra "Byron")
(_, GenTxShelley{}) ->
Left (incompatibleEra "Shelley")
(_, GenTxAllegra{}) ->
Left (incompatibleEra "Allegra")
(_, GenTxMary{}) ->
Left (incompatibleEra "Mary")
(UTxOInAlonzoEra utxo, GenTxAlonzo (ShelleyTx _id tx)) -> do
Right (SomeEvaluationInAnyEra utxo tx)
(UTxOInAlonzoEra utxo, GenTxBabbage (ShelleyTx _id tx)) -> do
Right (SomeEvaluationInAnyEra (translateUtxo utxo) tx)
(UTxOInBabbageEra utxo, GenTxAlonzo (ShelleyTx _id tx)) -> do
Right (SomeEvaluationInAnyEra utxo (translateTx tx))
(UTxOInBabbageEra utxo, GenTxBabbage (ShelleyTx _id tx)) -> do
Right (SomeEvaluationInAnyEra utxo tx)
}
, localStateQueryClient
(atomically $ takeTMVar evaluateExecutionUnitsRequest)
(atomically . putTMVar evaluateExecutionUnitsResponse)
)
where
localStateQueryClient
:: m SomeEvaluationInAnyEra
-> (EvaluateTxResponse block -> m ())
-> LocalStateQueryClient block (Point block) (Query block) m ()
localStateQueryClient await reply =
LocalStateQueryClient clientStIdle
where
clientStIdle
:: m (LSQ.ClientStIdle block (Point block) (Query block) m ())
clientStIdle = pure $ do
NOTE : This little ' dance ' of acquiring first is needed because of :
LSQ.SendMsgAcquire Nothing $ LSQ.ClientStAcquiring
{ LSQ.recvMsgAcquired = do
reAcquire <$> await
, LSQ.recvMsgFailure =
const clientStIdle
}
clientStAcquiring
:: SomeEvaluationInAnyEra
-> LSQ.ClientStAcquiring block (Point block) (Query block) m ()
clientStAcquiring args =
LSQ.ClientStAcquiring
{ LSQ.recvMsgAcquired = pure $ selectEra
(\era -> do
reply (notEnoughSynced era)
pure $ LSQ.SendMsgRelease clientStIdle
)
(clientStAcquired0 @_ @(AlonzoEra crypto) args evaluateExecutionUnits)
(clientStAcquired0 @_ @(BabbageEra crypto) args evaluateExecutionUnits)
, LSQ.recvMsgFailure =
const $ pure $ LSQ.SendMsgAcquire Nothing (clientStAcquiring args)
}
reAcquire
:: SomeEvaluationInAnyEra
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
reAcquire
= LSQ.SendMsgReAcquire Nothing . clientStAcquiring
clientStAcquired0
:: forall proto era. (CanEvaluateScriptsInEra era)
=> SomeEvaluationInAnyEra
-> ( PParams era
-> SystemStart
-> EpochInfo (Except PastHorizonException)
-> UTxO era
-> Tx era
-> EvaluateTxResponse block
)
-> HoistQuery proto era
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
clientStAcquired0 args callback hoistQuery = do
let query = BlockQuery (hoistQuery GetCurrentPParams)
in LSQ.SendMsgQuery query $ LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \case
Right pparams ->
pure $ clientStAcquired1 args (callback pparams) hoistQuery
Left{} ->
pure $ reAcquire args
}
clientStAcquired1
:: forall proto era. (CanEvaluateScriptsInEra era)
=> SomeEvaluationInAnyEra
-> ( SystemStart
-> EpochInfo (Except PastHorizonException)
-> UTxO era
-> Tx era
-> EvaluateTxResponse block
)
-> HoistQuery proto era
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
clientStAcquired1 args callback hoistQuery = do
let query = GetSystemStart
in LSQ.SendMsgQuery query $ LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \systemStart ->
pure $ clientStAcquired2 args (callback systemStart) hoistQuery
}
clientStAcquired2
:: forall proto era. (CanEvaluateScriptsInEra era)
=> SomeEvaluationInAnyEra
-> ( EpochInfo (Except PastHorizonException)
-> UTxO era
-> Tx era
-> EvaluateTxResponse block
)
-> HoistQuery proto era
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
clientStAcquired2 args callback hoistQuery = do
let query = BlockQuery $ QueryHardFork GetInterpreter
in LSQ.SendMsgQuery query $ LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \(interpreterToEpochInfo -> epochInfo) ->
pure $ clientStAcquired3 args (callback epochInfo) hoistQuery
}
clientStAcquired3
:: forall proto era. (CanEvaluateScriptsInEra era)
=> SomeEvaluationInAnyEra
-> ( UTxO era
-> Tx era
-> EvaluateTxResponse block
)
-> HoistQuery proto era
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
clientStAcquired3 args callback hoistQuery = do
let query = BlockQuery $ hoistQuery $ GetUTxOByTxIn (inputsInAnyEra args)
in LSQ.SendMsgQuery query $ LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \case
Right networkUtxo -> do
reply (mkEvaluateTxResponse @era callback networkUtxo args)
pure (LSQ.SendMsgRelease clientStIdle)
Left{} ->
pure $ reAcquire args
}
type HoistQuery proto era =
forall r a crypto. (crypto ~ Crypto era, CardanoQueryResult crypto r ~ a)
=> BlockQuery (ShelleyBlock (proto crypto) era) r
-> BlockQuery (CardanoBlock crypto) a
| Run local - state queries in either or Babbage , depending on where the network is at .
selectEra
:: forall block crypto m.
( block ~ HardForkBlock (CardanoEras crypto)
, Applicative m
)
Default selector , when the network era is older than and does n't support Phase-2 scripts .
=> ( Text -> m (LSQ.ClientStAcquired block (Point block) (Query block) m ())
)
Selector for the era .
-> ( HoistQuery TPraos (AlonzoEra crypto) -> LSQ.ClientStAcquired block (Point block) (Query block) m ()
)
Selector for the Babbage era .
-> ( HoistQuery Praos (BabbageEra crypto) -> LSQ.ClientStAcquired block (Point block) (Query block) m ()
)
-> LSQ.ClientStAcquired block (Point block) (Query block) m ()
selectEra fallback asAlonzo asBabbage =
LSQ.SendMsgQuery (Ledger.BlockQuery $ LSQ.QueryHardFork LSQ.GetCurrentEra) $
LSQ.ClientStQuerying
{ LSQ.recvMsgResult = \case
EraIndex Z{} -> fallback "Byron"
EraIndex (S Z{}) -> fallback "Shelley"
EraIndex (S (S Z{})) -> fallback "Allegra"
EraIndex (S (S (S Z{}))) -> fallback "Mary"
EraIndex (S (S (S (S Z{})))) -> pure (asAlonzo QueryIfCurrentAlonzo)
EraIndex (S (S (S (S (S Z{}))))) -> pure (asBabbage QueryIfCurrentBabbage)
}
data SomeEvaluationInAnyEra where
SomeEvaluationInAnyEra
:: forall era. (CanEvaluateScriptsInEra era)
=> UTxO era
-> Tx era
-> SomeEvaluationInAnyEra
inputsInAnyEra
:: SomeEvaluationInAnyEra
-> Set (TxIn StandardCrypto)
inputsInAnyEra (SomeEvaluationInAnyEra _ tx) =
getField @"inputs" body
<>
getField @"collateral" body
<>
getField @"referenceInputs" body
where
body = getField @"body" tx
mkEvaluateTxResponse
:: forall era block crypto.
( CanEvaluateScriptsInEra era
, block ~ HardForkBlock (CardanoEras crypto)
, crypto ~ StandardCrypto
)
=> (UTxO era -> Tx era -> EvaluateTxResponse block)
^ fetched from the network
^ Tx & additional utxo
-> EvaluateTxResponse block
mkEvaluateTxResponse callback (UTxO networkUtxo) args =
case translateToNetworkEra @era args of
Nothing ->
error "impossible: arguments are not translatable to network era. \
\This can't happen because 'selectEra' enforces that queries \
\are only executed if the network is either in 'Alonzo' or \
\'Babbage'. The arguments themselves can also only be 'Alonzo' \
\or 'Babbage'. Thus, we can't reach this point with any other \
\eras. We _could_ potentially capture this proof in the types \
\to convince the compiler of this. Let's say: TODO."
Just (UTxO userProvidedUtxo, tx) ->
let
intersection = Map.intersection userProvidedUtxo networkUtxo
in
if null intersection
then
callback (UTxO $ userProvidedUtxo <> networkUtxo) tx
else
intersection
& Map.keysSet
& EvaluateTxAdditionalUtxoOverlap
& EvaluationFailure
| 99 % of the time , we only need to worry about one era : the current one ; yet , near hard - forks ,
to the latest era when applicable .
the previous era , even after the hard - fork has happened . We take the burden of detecting the era and
translateToNetworkEra
:: forall eraNetwork.
( CanEvaluateScriptsInEra eraNetwork
)
=> SomeEvaluationInAnyEra
-> Maybe (UTxO eraNetwork, Tx eraNetwork)
translateToNetworkEra (SomeEvaluationInAnyEra utxoOrig txOrig) =
translate utxoOrig txOrig
where
translate
:: forall eraArgs.
( CanEvaluateScriptsInEra eraArgs
)
=> UTxO eraArgs
-> Tx eraArgs
-> Maybe (UTxO eraNetwork, Tx eraNetwork)
translate utxo tx =
let
eraNetwork = typeRep @eraNetwork
eraAlonzo = typeRep @(AlonzoEra StandardCrypto)
eraArgs = typeRep @eraArgs
eraBabbage = typeRep @(BabbageEra StandardCrypto)
sameEra =
case (testEquality eraNetwork eraArgs) of
Just Refl ->
Just (utxo, tx)
_ ->
Nothing
alonzoToBabbage =
case (testEquality eraNetwork eraBabbage, testEquality eraArgs eraAlonzo) of
(Just Refl, Just Refl) -> do
Just (translateUtxo utxo, translateTx tx)
_ ->
Nothing
in
sameEra <|> alonzoToBabbage
|
69c18a8f21eb452ea115fa94b27ecb283fbdeb57763a82f40ac948253add7309 | noinia/hgeometry | Alternating.hs | --------------------------------------------------------------------------------
-- |
-- Module : Data.List.Alternating
Copyright : ( C )
-- License : see the LICENSE file
Maintainer :
--------------------------------------------------------------------------------
module Data.List.Alternating(
Alternating(..)
, withNeighbours
, mergeAlternating
, insertBreakPoints
, reverse
) where
import Prelude hiding (reverse)
import Control.Lens
import Data.Bifoldable
import Data.Bifunctor
import Data.Bitraversable
import Data.Ext
import Data.Traversable
import qualified Data.List as List
--------------------------------------------------------------------------------
| A ( non - empty ) alternating list of 's and 's
data Alternating a b = Alternating a [b :+ a] deriving (Show,Eq,Ord)
instance Functor (Alternating a) where
fmap = fmapDefault
instance Foldable (Alternating a) where
foldMap = foldMapDefault
instance Traversable (Alternating a) where
traverse = bitraverse pure
instance Bifunctor Alternating where
bimap = bimapDefault
instance Bifoldable Alternating where
bifoldMap = bifoldMapDefault
instance Bitraversable Alternating where
bitraverse f g (Alternating a xs) = Alternating <$> f a <*> traverse (bitraverse g f) xs
-- | Computes a b with all its neighbours
--
> > > withNeighbours ( Alternating 0 [ ' a ' : + 1 , ' b ' : + 2 , ' c ' : + 3 ] )
[ ( 0,'a ' : + 1),(1,'b ' : + 2),(2,'c ' : + 3 ) ]
withNeighbours :: Alternating a b -> [(a,b :+ a)]
withNeighbours (Alternating a0 xs) = let as = a0 : map (^.extra) xs
in zip as xs
| Generic merging scheme that merges two and applies
the function ' ' , with the current / new value at every event . So
-- note that if the alternating consists of 'Alternating a0 [t1 :+
-- a1]' then the function is applied to a1, not to a0 (i.e. every
-- value ai is considered alive on the interval [ti,t(i+1))
--
> > > let odds = Alternating " a " [ 3 : + " c " , 5 : + " e " , 7 : + " g " ]
> > > let evens = Alternating " b " [ 4 : + " d " , 6 : + " f " , 8 : + " h " ]
-- >>> mergeAlternating (\_ a b -> a <> b) odds evens
[ 3 : + " cb",4 : + " cd",5 : + " ed",6 : + " ef",7 : + " gf",8 : + " gh " ]
> > > mergeAlternating ( \t a b - > if t ` mod ` 2 = = 0 then a else b ) odds evens
[ 3 : + " b",4 : + " c",5 : + " d",6 : + " e",7 : + " f",8 : + " g " ]
> > > mergeAlternating ( \ _ a b - > a < > b ) odds ( Alternating " b " [ 0 : + " d " , 5 : + " e " , 8 : + " h " ] )
-- [0 :+ "ad",3 :+ "cd",5 :+ "ee",7 :+ "ge",8 :+ "gh"]
mergeAlternating :: Ord t
=> (t -> a -> b -> c)
-> Alternating a t -> Alternating b t -> [t :+ c]
mergeAlternating f (Alternating a00 as0)
(Alternating b00 bs0) = go a00 b00 as0 bs0
where
go a _ [] bs = map (\(t :+ b) -> t :+ f t a b) bs
go _ b as [] = map (\(t :+ a) -> t :+ f t a b) as
go a0 b0 as@((t :+ a):as') bs@((t' :+ b):bs') = case t `compare` t' of
LT -> (t :+ f t a b0) : go a b0 as' bs
EQ -> (t :+ f t a b) : go a b as' bs'
GT -> (t' :+ f t' a0 b) : go a0 b as bs'
-- | Adds additional t-values in the alternating, (in sorted order). I.e. if we insert a
-- "breakpoint" at time t the current '@a@' value is used at that time.
--
> > > insertBreakPoints [ 0,2,4,6,8,10 ] $ Alternating " a " [ 3 : + " c " , 5 : + " e " , 7 : + " g " ]
-- Alternating "a" [0 :+ "a",2 :+ "a",3 :+ "c",4 :+ "c",5 :+ "e",6 :+ "e",7 :+ "g",8 :+ "g",10 :+ "g"]
insertBreakPoints :: Ord t => [t] -> Alternating a t -> Alternating a t
insertBreakPoints ts a@(Alternating a0 _) =
Alternating a0 $ mergeAlternating (\_ _ a' -> a') (Alternating undefined (ext <$> ts)) a
-- | Reverses an alternating list.
--
> > > reverse $ Alternating " a " [ 3 : + " c " , 5 : + " e " , 7 : + " g " ]
Alternating " g " [ 7 : + " e",5 : + " : + " a " ]
reverse :: Alternating a b -> Alternating a b
reverse p@(Alternating s xs) = case xs of
[] -> p
((e1 :+ _):tl) -> let ys = (e1 :+ s) : List.zipWith (\(_ :+ v) (e :+ _) -> e :+ v) xs tl
t = last xs ^. extra
in Alternating t (List.reverse ys)
| null | https://raw.githubusercontent.com/noinia/hgeometry/187402ff1fbe4988cac2b27700ba8887cc136a22/hgeometry-combinatorial/src/Data/List/Alternating.hs | haskell | ------------------------------------------------------------------------------
|
Module : Data.List.Alternating
License : see the LICENSE file
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Computes a b with all its neighbours
note that if the alternating consists of 'Alternating a0 [t1 :+
a1]' then the function is applied to a1, not to a0 (i.e. every
value ai is considered alive on the interval [ti,t(i+1))
>>> mergeAlternating (\_ a b -> a <> b) odds evens
[0 :+ "ad",3 :+ "cd",5 :+ "ee",7 :+ "ge",8 :+ "gh"]
| Adds additional t-values in the alternating, (in sorted order). I.e. if we insert a
"breakpoint" at time t the current '@a@' value is used at that time.
Alternating "a" [0 :+ "a",2 :+ "a",3 :+ "c",4 :+ "c",5 :+ "e",6 :+ "e",7 :+ "g",8 :+ "g",10 :+ "g"]
| Reverses an alternating list.
| Copyright : ( C )
Maintainer :
module Data.List.Alternating(
Alternating(..)
, withNeighbours
, mergeAlternating
, insertBreakPoints
, reverse
) where
import Prelude hiding (reverse)
import Control.Lens
import Data.Bifoldable
import Data.Bifunctor
import Data.Bitraversable
import Data.Ext
import Data.Traversable
import qualified Data.List as List
| A ( non - empty ) alternating list of 's and 's
data Alternating a b = Alternating a [b :+ a] deriving (Show,Eq,Ord)
instance Functor (Alternating a) where
fmap = fmapDefault
instance Foldable (Alternating a) where
foldMap = foldMapDefault
instance Traversable (Alternating a) where
traverse = bitraverse pure
instance Bifunctor Alternating where
bimap = bimapDefault
instance Bifoldable Alternating where
bifoldMap = bifoldMapDefault
instance Bitraversable Alternating where
bitraverse f g (Alternating a xs) = Alternating <$> f a <*> traverse (bitraverse g f) xs
> > > withNeighbours ( Alternating 0 [ ' a ' : + 1 , ' b ' : + 2 , ' c ' : + 3 ] )
[ ( 0,'a ' : + 1),(1,'b ' : + 2),(2,'c ' : + 3 ) ]
withNeighbours :: Alternating a b -> [(a,b :+ a)]
withNeighbours (Alternating a0 xs) = let as = a0 : map (^.extra) xs
in zip as xs
| Generic merging scheme that merges two and applies
the function ' ' , with the current / new value at every event . So
> > > let odds = Alternating " a " [ 3 : + " c " , 5 : + " e " , 7 : + " g " ]
> > > let evens = Alternating " b " [ 4 : + " d " , 6 : + " f " , 8 : + " h " ]
[ 3 : + " cb",4 : + " cd",5 : + " ed",6 : + " ef",7 : + " gf",8 : + " gh " ]
> > > mergeAlternating ( \t a b - > if t ` mod ` 2 = = 0 then a else b ) odds evens
[ 3 : + " b",4 : + " c",5 : + " d",6 : + " e",7 : + " f",8 : + " g " ]
> > > mergeAlternating ( \ _ a b - > a < > b ) odds ( Alternating " b " [ 0 : + " d " , 5 : + " e " , 8 : + " h " ] )
mergeAlternating :: Ord t
=> (t -> a -> b -> c)
-> Alternating a t -> Alternating b t -> [t :+ c]
mergeAlternating f (Alternating a00 as0)
(Alternating b00 bs0) = go a00 b00 as0 bs0
where
go a _ [] bs = map (\(t :+ b) -> t :+ f t a b) bs
go _ b as [] = map (\(t :+ a) -> t :+ f t a b) as
go a0 b0 as@((t :+ a):as') bs@((t' :+ b):bs') = case t `compare` t' of
LT -> (t :+ f t a b0) : go a b0 as' bs
EQ -> (t :+ f t a b) : go a b as' bs'
GT -> (t' :+ f t' a0 b) : go a0 b as bs'
> > > insertBreakPoints [ 0,2,4,6,8,10 ] $ Alternating " a " [ 3 : + " c " , 5 : + " e " , 7 : + " g " ]
insertBreakPoints :: Ord t => [t] -> Alternating a t -> Alternating a t
insertBreakPoints ts a@(Alternating a0 _) =
Alternating a0 $ mergeAlternating (\_ _ a' -> a') (Alternating undefined (ext <$> ts)) a
> > > reverse $ Alternating " a " [ 3 : + " c " , 5 : + " e " , 7 : + " g " ]
Alternating " g " [ 7 : + " e",5 : + " : + " a " ]
reverse :: Alternating a b -> Alternating a b
reverse p@(Alternating s xs) = case xs of
[] -> p
((e1 :+ _):tl) -> let ys = (e1 :+ s) : List.zipWith (\(_ :+ v) (e :+ _) -> e :+ v) xs tl
t = last xs ^. extra
in Alternating t (List.reverse ys)
|
e7d08ae0f997e59e1b4a5f87e80511cb92d9ded7b0657d5e317bc539f0b13bb7 | tamarin-prover/tamarin-prover | ClosedTheory.hs | module ClosedTheory (
module ClosedTheory
) where
import Control.Basics
import Control.Category
import qualified Data.Set as S
import qualified Extension.Data.Label as L
-- import qualified Data.Label.Total
import Lemma
import Rule
import Safe
import Theory.Model
import Theory.Proof
import TheoryObject
import Prelude hiding (id, (.))
import Text.PrettyPrint.Highlight
import Prelude hiding (id, (.))
-- import Data.Typeable
import Data.Monoid (Sum(..))
-- import qualified Data.Label.Total
import Theory.Text.Pretty
import OpenTheory
import Pretty
------------------------------------------------------------------------------
-- Closed theory querying / construction / modification
------------------------------------------------------------------------------
-- | Closed theories can be proven. Invariants:
1 . Lemma names are unique
2 . All proof steps with annotated sequents are sound with respect to the
-- closed rule set of the theory.
3 . is running under the given handle .
type ClosedTheory =
Theory SignatureWithMaude ClosedRuleCache ClosedProtoRule IncrementalProof ()
-- | Closed Diff theories can be proven. Invariants:
1 . Lemma names are unique
2 . All proof steps with annotated sequents are sound with respect to the
-- closed rule set of the theory.
3 . is running under the given handle .
type ClosedDiffTheory =
DiffTheory SignatureWithMaude ClosedRuleCache DiffProtoRule ClosedProtoRule IncrementalDiffProof IncrementalProof
| Either Therories can be Either a normal or a diff theory
type EitherClosedTheory = Either ClosedTheory ClosedDiffTheory
-- querying
-----------
-- | All lemmas.
getLemmas :: ClosedTheory -> [Lemma IncrementalProof]
getLemmas = theoryLemmas
-- | All diff lemmas.
getDiffLemmas :: ClosedDiffTheory -> [DiffLemma IncrementalDiffProof]
getDiffLemmas = diffTheoryDiffLemmas
-- | All side lemmas.
getEitherLemmas :: ClosedDiffTheory -> [(Side, Lemma IncrementalProof)]
getEitherLemmas = diffTheoryLemmas
-- | The variants of the intruder rules.
getIntrVariants :: ClosedTheory -> [IntrRuleAC]
getIntrVariants = intruderRules . L.get (crcRules . thyCache)
-- | The variants of the intruder rules.
getIntrVariantsDiff :: Side -> ClosedDiffTheory -> [IntrRuleAC]
getIntrVariantsDiff s
| s == LHS = intruderRules . L.get (crcRules . diffThyCacheLeft)
| s == RHS = intruderRules . L.get (crcRules . diffThyCacheRight)
| otherwise = error $ "The Side MUST always be LHS or RHS."
-- | All protocol rules modulo E.
getProtoRuleEs :: ClosedTheory -> [ProtoRuleE]
-- we remove duplicates if they exist due to variant unfolding
getProtoRuleEs = S.toList . S.fromList . map ((L.get oprRuleE) . openProtoRule) . theoryRules
-- | All protocol rules modulo E.
getProtoRuleEsDiff :: Side -> ClosedDiffTheory -> [ProtoRuleE]
-- we remove duplicates if they exist due to variant unfolding
getProtoRuleEsDiff s = S.toList . S.fromList . map ((L.get oprRuleE) . openProtoRule) . diffTheorySideRules s
-- | Get the proof context for a lemma of the closed theory.
getProofContext :: Lemma a -> ClosedTheory -> ProofContext
getProofContext l thy = ProofContext
( L.get thySignature thy)
( L.get (crcRules . thyCache) thy)
( L.get (crcInjectiveFactInsts . thyCache) thy)
kind
( L.get (cases . thyCache) thy)
inductionHint
specifiedHeuristic
specifiedTactic
(toSystemTraceQuantifier $ L.get lTraceQuantifier l)
(L.get lName l)
([ h | HideLemma h <- L.get lAttributes l])
False
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . thyCache) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . thyCache) thy)
where
kind = lemmaSourceKind l
cases = case kind of RawSource -> crcRawSources
RefinedSource -> crcRefinedSources
inductionHint
| any (`elem` [SourceLemma, InvariantLemma]) (L.get lAttributes l) = UseInduction
| otherwise = AvoidInduction
-- Heuristic specified for the lemma > globally specified heuristic > default heuristic
specifiedHeuristic = case lattr of
Just lh -> Just lh
Nothing -> case L.get thyHeuristic thy of
[] -> Nothing
gh -> Just (Heuristic gh)
where
lattr = (headMay [Heuristic gr
| LemmaHeuristic gr <- L.get lAttributes l])
-- Tactic specified for the lemma
specifiedTactic = case lattr of
[] -> Nothing
_ -> Just lattr
where
lattr = L.get thyTactic thy
-- | Get the proof context for a lemma of the closed theory.
getProofContextDiff :: Side -> Lemma a -> ClosedDiffTheory -> ProofContext
getProofContextDiff s l thy = case s of
LHS -> ProofContext
( L.get diffThySignature thy)
( L.get (crcRules . diffThyCacheLeft) thy)
( L.get (crcInjectiveFactInsts . diffThyCacheLeft) thy)
kind
( L.get (cases . diffThyCacheLeft) thy)
inductionHint
specifiedHeuristic
specifiedTactic
(toSystemTraceQuantifier $ L.get lTraceQuantifier l)
(L.get lName l)
([ h | HideLemma h <- L.get lAttributes l])
False
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheLeft) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheLeft) thy)
RHS -> ProofContext
( L.get diffThySignature thy)
( L.get (crcRules . diffThyCacheRight) thy)
( L.get (crcInjectiveFactInsts . diffThyCacheRight) thy)
kind
( L.get (cases . diffThyCacheRight) thy)
inductionHint
specifiedHeuristic
specifiedTactic
(toSystemTraceQuantifier $ L.get lTraceQuantifier l)
(L.get lName l)
([ h | HideLemma h <- L.get lAttributes l])
False
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheRight) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheRight) thy)
where
kind = lemmaSourceKind l
cases = case kind of RawSource -> crcRawSources
RefinedSource -> crcRefinedSources
inductionHint
| any (`elem` [SourceLemma, InvariantLemma]) (L.get lAttributes l) = UseInduction
| otherwise = AvoidInduction
-- Heuristic specified for the lemma > globally specified heuristic > default heuristic
specifiedHeuristic = case lattr of
Just lh -> Just lh
Nothing -> case L.get diffThyHeuristic thy of
[] -> Nothing
gh -> Just (Heuristic gh)
where
lattr = (headMay [Heuristic gr
| LemmaHeuristic gr <- L.get lAttributes l])
specifiedTactic = case lattr of
[] -> Nothing
_ -> Just lattr
where
lattr = L.get diffThyTactic thy
-- | Get the proof context for a diff lemma of the closed theory.
getDiffProofContext :: DiffLemma a -> ClosedDiffTheory -> DiffProofContext
getDiffProofContext l thy = DiffProofContext (proofContext LHS) (proofContext RHS)
(map (L.get dprRule) $ diffTheoryDiffRules thy) (L.get (crConstruct . crcRules . diffThyDiffCacheLeft) thy)
(L.get (crDestruct . crcRules . diffThyDiffCacheLeft) thy)
((LHS, restrictionsLeft):[(RHS, restrictionsRight)]) gatherReusableLemmas
where
items = L.get diffThyItems thy
restrictionsLeft = do EitherRestrictionItem (LHS, rstr) <- items
return $ formulaToGuarded_ $ L.get rstrFormula rstr
restrictionsRight = do EitherRestrictionItem (RHS, rstr) <- items
return $ formulaToGuarded_ $ L.get rstrFormula rstr
gatherReusableLemmas = do
EitherLemmaItem (s, lem) <- items
guard $ lemmaSourceKind lem <= RefinedSource
&& ReuseDiffLemma `elem` L.get lAttributes lem
&& AllTraces == L.get lTraceQuantifier lem
return $ (s, formulaToGuarded_ $ L.get lFormula lem)
proofContext s = case s of
LHS -> ProofContext
( L.get diffThySignature thy)
( L.get (crcRules . diffThyDiffCacheLeft) thy)
( L.get (crcInjectiveFactInsts . diffThyDiffCacheLeft) thy)
RefinedSource
( L.get (crcRefinedSources . diffThyDiffCacheLeft) thy)
AvoidInduction
specifiedHeuristic
specifiedTactic
ExistsNoTrace
( L.get lDiffName l )
([ h | HideLemma h <- L.get lDiffAttributes l])
True
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheLeft) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheLeft) thy)
RHS -> ProofContext
( L.get diffThySignature thy)
( L.get (crcRules . diffThyDiffCacheRight) thy)
( L.get (crcInjectiveFactInsts . diffThyDiffCacheRight) thy)
RefinedSource
( L.get (crcRefinedSources . diffThyDiffCacheRight) thy)
AvoidInduction
specifiedHeuristic
specifiedTactic
ExistsNoTrace
( L.get lDiffName l )
([ h | HideLemma h <- L.get lDiffAttributes l])
True
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheRight) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheRight) thy)
specifiedHeuristic = case lattr of
Just lh -> Just lh
Nothing -> case L.get diffThyHeuristic thy of
[] -> Nothing
gh -> Just (Heuristic gh)
where
lattr = (headMay [Heuristic gr
| LemmaHeuristic gr <- L.get lDiffAttributes l])
specifiedTactic = case lattr of
[] -> Nothing
_ -> Just lattr
where
lattr = L.get diffThyTactic thy
-- | The facts with injective instances in this theory
getInjectiveFactInsts :: ClosedTheory -> S.Set FactTag
getInjectiveFactInsts = L.get (crcInjectiveFactInsts . thyCache)
-- | The facts with injective instances in this theory
getDiffInjectiveFactInsts :: Side -> Bool -> ClosedDiffTheory -> S.Set FactTag
getDiffInjectiveFactInsts s isdiff = case (s, isdiff) of
(LHS, False) -> L.get (crcInjectiveFactInsts . diffThyCacheLeft)
(RHS, False) -> L.get (crcInjectiveFactInsts . diffThyCacheRight)
(LHS, True) -> L.get (crcInjectiveFactInsts . diffThyDiffCacheLeft)
(RHS, True) -> L.get (crcInjectiveFactInsts . diffThyDiffCacheRight)
-- | The classified set of rules modulo AC in this theory.
getClassifiedRules :: ClosedTheory -> ClassifiedRules
getClassifiedRules = L.get (crcRules . thyCache)
-- | The classified set of rules modulo AC in this theory.
getDiffClassifiedRules :: Side -> Bool -> ClosedDiffTheory -> ClassifiedRules
getDiffClassifiedRules s isdiff = case (s, isdiff) of
(LHS, False) -> L.get (crcRules . diffThyCacheLeft)
(RHS, False) -> L.get (crcRules . diffThyCacheRight)
(LHS, True) -> L.get (crcRules . diffThyDiffCacheLeft)
(RHS, True) -> L.get (crcRules . diffThyDiffCacheRight)
-- | The precomputed case distinctions.
getSource :: SourceKind -> ClosedTheory -> [Source]
getSource RawSource = L.get (crcRawSources . thyCache)
getSource RefinedSource = L.get (crcRefinedSources . thyCache)
-- | The precomputed case distinctions.
getDiffSource :: Side -> Bool -> SourceKind -> ClosedDiffTheory -> [Source]
getDiffSource LHS False RawSource = L.get (crcRawSources . diffThyCacheLeft)
getDiffSource RHS False RawSource = L.get (crcRawSources . diffThyCacheRight)
getDiffSource LHS False RefinedSource = L.get (crcRefinedSources . diffThyCacheLeft)
getDiffSource RHS False RefinedSource = L.get (crcRefinedSources . diffThyCacheRight)
getDiffSource LHS True RawSource = L.get (crcRawSources . diffThyDiffCacheLeft)
getDiffSource RHS True RawSource = L.get (crcRawSources . diffThyDiffCacheRight)
getDiffSource LHS True RefinedSource = L.get (crcRefinedSources . diffThyDiffCacheLeft)
getDiffSource RHS True RefinedSource = L.get (crcRefinedSources . diffThyDiffCacheRight)
-- construction
---------------
-- | Close a protocol rule; i.e., compute AC variant and source assertion
-- soundness sequent, if required.
closeEitherProtoRule :: MaudeHandle -> (Side, OpenProtoRule) -> (Side, [ClosedProtoRule])
closeEitherProtoRule hnd (s, ruE) = (s, closeProtoRule hnd ruE)
-- -- | Convert a lemma to the corresponding guarded formula.
lemmaToGuarded : : Maybe LNGuarded
-- lemmaToGuarded lem =
-- | Pretty print an closed rule.
prettyClosedProtoRule :: HighlightDocument d => ClosedProtoRule -> d
prettyClosedProtoRule cru =
if isTrivialProtoVariantAC ruAC ruE then
-- We have a rule that only has one trivial variant, and without added annotations
-- Hence showing the initial rule modulo E
(prettyProtoRuleE ruE) $--$
(nest 2 $ prettyLoopBreakers (L.get rInfo ruAC) $-$
multiComment_ ["has exactly the trivial AC variant"])
else
if ruleName ruAC == ruleName ruE then
if not (equalUpToTerms ruAC ruE) then
-- Here we have a rule with added annotations,
-- hence showing the annotated rule as if it was a rule mod E
-- note that we can do that, as we unfolded variants
(prettyProtoRuleACasE ruAC) $--$
(nest 2 $ prettyLoopBreakers (L.get rInfo ruAC) $-$
multiComment_ ["has exactly the trivial AC variant"])
else
Here we have a rule with one or multiple variants , but without other annotations
-- Hence showing the rule mod E with commented variants
(prettyProtoRuleE ruE) $--$
(nest 2 $ prettyLoopBreakers (L.get rInfo ruAC) $-$
(multiComment $ prettyProtoRuleAC ruAC))
else
-- Here we have a variant of a rule that has multiple variants.
-- Hence showing only the variant as a rule modulo AC. This should not
-- normally be used, as it breaks the ability to re-import.
(prettyProtoRuleAC ruAC) $--$
(nest 3 $ prettyLoopBreakers (L.get rInfo ruAC) $-$
(multiComment_ ["variant of"]) $-$
(multiComment $ prettyProtoRuleE ruE)
)
where
ruAC = L.get cprRuleAC cru
ruE = L.get cprRuleE cru
-- -- | Pretty print an closed rule.
prettyClosedEitherRule : : d = > ( Side , ClosedProtoRule ) - > d
-- prettyClosedEitherRule (s, cru) =
-- text ((show s) ++ ": ") <>
-- (prettyProtoRuleE ruE) $--$
( nest 2 $ prettyLoopBreakers ( L.get rInfo ruAC ) $ -$ ppRuleAC )
-- where
-- ruAC = L.get cprRuleAC cru
-- ruE = L.get cprRuleE cru
-- ppRuleAC
-- | isTrivialProtoVariantAC ruAC ruE = multiComment_ ["has exactly the trivial AC variant"]
-- | otherwise = multiComment $ prettyProtoRuleAC ruAC
-- | Pretty print a closed theory.
prettyClosedTheory :: HighlightDocument d => ClosedTheory -> d
prettyClosedTheory thy = if containsManualRuleVariants mergedRules
then
prettyTheory prettySignatureWithMaude
ppInjectiveFactInsts
( prettyIntrVariantsSection . . L.get crcRules )
prettyOpenProtoRuleAsClosedRule
prettyIncrementalProof
emptyString
thy'
else
prettyTheory prettySignatureWithMaude
ppInjectiveFactInsts
( prettyIntrVariantsSection . . L.get crcRules )
prettyClosedProtoRule
prettyIncrementalProof
emptyString
thy
where
items = L.get thyItems thy
mergedRules = mergeOpenProtoRules $ map (mapTheoryItem openProtoRule id) items
thy' :: Theory SignatureWithMaude ClosedRuleCache OpenProtoRule IncrementalProof ()
thy' = Theory {_thyName=(L.get thyName thy)
,_thyHeuristic=(L.get thyHeuristic thy)
,_thyTactic=(L.get thyTactic thy)
,_thySignature=(L.get thySignature thy)
,_thyCache=(L.get thyCache thy)
,_thyItems = mergedRules
,_thyOptions =(L.get thyOptions thy)}
ppInjectiveFactInsts crc =
case S.toList $ L.get crcInjectiveFactInsts crc of
[] -> emptyDoc
tags -> multiComment $ sep
[ text "looping facts with injective instances:"
, nest 2 $ fsepList (text . showFactTagArity) tags ]
-- | Pretty print a closed diff theory.
prettyClosedDiffTheory :: HighlightDocument d => ClosedDiffTheory -> d
prettyClosedDiffTheory thy = if containsManualRuleVariantsDiff mergedRules
then
prettyDiffTheory prettySignatureWithMaude
ppInjectiveFactInsts
( prettyIntrVariantsSection . . L.get crcRules )
(\_ -> emptyDoc) --prettyClosedEitherRule
prettyIncrementalDiffProof
prettyIncrementalProof
thy'
else
prettyDiffTheory prettySignatureWithMaude
ppInjectiveFactInsts
( prettyIntrVariantsSection . . L.get crcRules )
(\_ -> emptyDoc) --prettyClosedEitherRule
prettyIncrementalDiffProof
prettyIncrementalProof
thy
where
items = L.get diffThyItems thy
mergedRules = mergeLeftRightRulesDiff $ mergeOpenProtoRulesDiff $
map (mapDiffTheoryItem id (\(x, y) -> (x, (openProtoRule y))) id id) items
thy' :: DiffTheory SignatureWithMaude ClosedRuleCache DiffProtoRule OpenProtoRule IncrementalDiffProof IncrementalProof
thy' = DiffTheory {_diffThyName=(L.get diffThyName thy)
,_diffThyHeuristic=(L.get diffThyHeuristic thy)
,_diffThyTactic=(L.get diffThyTactic thy)
,_diffThySignature=(L.get diffThySignature thy)
,_diffThyCacheLeft=(L.get diffThyCacheLeft thy)
,_diffThyCacheRight=(L.get diffThyCacheRight thy)
,_diffThyDiffCacheLeft=(L.get diffThyDiffCacheLeft thy)
,_diffThyDiffCacheRight=(L.get diffThyDiffCacheRight thy)
,_diffThyItems = mergedRules
,_diffThyOptions =(L.get diffThyOptions thy)}
ppInjectiveFactInsts crc =
case S.toList $ L.get crcInjectiveFactInsts crc of
[] -> emptyDoc
tags -> multiComment $ sep
[ text "looping facts with injective instances:"
, nest 2 $ fsepList (text . showFactTagArity) tags ]
prettyClosedSummary :: Document d => ClosedTheory -> d
prettyClosedSummary thy =
vcat lemmaSummaries
where
lemmaSummaries = do
LemmaItem lem <- L.get thyItems thy
-- Note that here we are relying on the invariant that all proof steps
-- with a 'Just' annotation follow from the application of
-- 'execProofMethod' to their parent and are valid in the sense that
-- the application of 'execProofMethod' to their method and constraint
-- system is guaranteed to succeed.
--
-- This is guaranteed initially by 'closeTheory' and is (must be)
-- maintained by the provers being applied to the theory using
-- 'modifyLemmaProof' or 'proveTheory'. Note that we could check the
-- proof right before computing its status. This is however quite
-- expensive, as it requires recomputing all intermediate constraint
-- systems.
--
-- TODO: The whole consruction seems a bit hacky. Think of a more
-- principled constrution with better correctness guarantees.
let (status, Sum siz) = foldProof proofStepSummary $ L.get lProof lem
quantifier = (toSystemTraceQuantifier $ L.get lTraceQuantifier lem)
analysisType = parens $ prettyTraceQuantifier $ L.get lTraceQuantifier lem
return $ text (L.get lName lem) <-> analysisType <> colon <->
text (showProofStatus quantifier status) <->
parens (integer siz <-> text "steps")
proofStepSummary = proofStepStatus &&& const (Sum (1::Integer))
prettyClosedDiffSummary :: Document d => ClosedDiffTheory -> d
prettyClosedDiffSummary thy =
(vcat lemmaSummaries) $$ (vcat diffLemmaSummaries)
where
lemmaSummaries = do
EitherLemmaItem (s, lem) <- L.get diffThyItems thy
-- Note that here we are relying on the invariant that all proof steps
-- with a 'Just' annotation follow from the application of
-- 'execProofMethod' to their parent and are valid in the sense that
-- the application of 'execProofMethod' to their method and constraint
-- system is guaranteed to succeed.
--
-- This is guaranteed initially by 'closeTheory' and is (must be)
-- maintained by the provers being applied to the theory using
-- 'modifyLemmaProof' or 'proveTheory'. Note that we could check the
-- proof right before computing its status. This is however quite
-- expensive, as it requires recomputing all intermediate constraint
-- systems.
--
-- TODO: The whole consruction seems a bit hacky. Think of a more
-- principled constrution with better correctness guarantees.
let (status, Sum siz) = foldProof proofStepSummary $ L.get lProof lem
quantifier = (toSystemTraceQuantifier $ L.get lTraceQuantifier lem)
analysisType = parens $ prettyTraceQuantifier $ L.get lTraceQuantifier lem
return $ text (show s) <-> text ": " <-> text (L.get lName lem) <-> analysisType <> colon <->
text (showProofStatus quantifier status) <->
parens (integer siz <-> text "steps")
diffLemmaSummaries = do
DiffLemmaItem (lem) <- L.get diffThyItems thy
-- Note that here we are relying on the invariant that all proof steps
-- with a 'Just' annotation follow from the application of
-- 'execProofMethod' to their parent and are valid in the sense that
-- the application of 'execProofMethod' to their method and constraint
-- system is guaranteed to succeed.
--
-- This is guaranteed initially by 'closeTheory' and is (must be)
-- maintained by the provers being applied to the theory using
-- 'modifyLemmaProof' or 'proveTheory'. Note that we could check the
-- proof right before computing its status. This is however quite
-- expensive, as it requires recomputing all intermediate constraint
-- systems.
--
-- TODO: The whole consruction seems a bit hacky. Think of a more
-- principled constrution with better correctness guarantees.
let (status, Sum siz) = foldDiffProof diffProofStepSummary $ L.get lDiffProof lem
return $ text "DiffLemma: " <-> text (L.get lDiffName lem) <-> colon <->
text (showDiffProofStatus status) <->
parens (integer siz <-> text "steps")
proofStepSummary = proofStepStatus &&& const (Sum (1::Integer))
diffProofStepSummary = diffProofStepStatus &&& const (Sum (1::Integer))
| null | https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/958f8b1767650c06dffe4eba63a38508c9b17a7f/lib/theory/src/ClosedTheory.hs | haskell | import qualified Data.Label.Total
import Data.Typeable
import qualified Data.Label.Total
----------------------------------------------------------------------------
Closed theory querying / construction / modification
----------------------------------------------------------------------------
| Closed theories can be proven. Invariants:
closed rule set of the theory.
| Closed Diff theories can be proven. Invariants:
closed rule set of the theory.
querying
---------
| All lemmas.
| All diff lemmas.
| All side lemmas.
| The variants of the intruder rules.
| The variants of the intruder rules.
| All protocol rules modulo E.
we remove duplicates if they exist due to variant unfolding
| All protocol rules modulo E.
we remove duplicates if they exist due to variant unfolding
| Get the proof context for a lemma of the closed theory.
Heuristic specified for the lemma > globally specified heuristic > default heuristic
Tactic specified for the lemma
| Get the proof context for a lemma of the closed theory.
Heuristic specified for the lemma > globally specified heuristic > default heuristic
| Get the proof context for a diff lemma of the closed theory.
| The facts with injective instances in this theory
| The facts with injective instances in this theory
| The classified set of rules modulo AC in this theory.
| The classified set of rules modulo AC in this theory.
| The precomputed case distinctions.
| The precomputed case distinctions.
construction
-------------
| Close a protocol rule; i.e., compute AC variant and source assertion
soundness sequent, if required.
-- | Convert a lemma to the corresponding guarded formula.
lemmaToGuarded lem =
| Pretty print an closed rule.
We have a rule that only has one trivial variant, and without added annotations
Hence showing the initial rule modulo E
$
Here we have a rule with added annotations,
hence showing the annotated rule as if it was a rule mod E
note that we can do that, as we unfolded variants
$
Hence showing the rule mod E with commented variants
$
Here we have a variant of a rule that has multiple variants.
Hence showing only the variant as a rule modulo AC. This should not
normally be used, as it breaks the ability to re-import.
$
-- | Pretty print an closed rule.
prettyClosedEitherRule (s, cru) =
text ((show s) ++ ": ") <>
(prettyProtoRuleE ruE) $--$
where
ruAC = L.get cprRuleAC cru
ruE = L.get cprRuleE cru
ppRuleAC
| isTrivialProtoVariantAC ruAC ruE = multiComment_ ["has exactly the trivial AC variant"]
| otherwise = multiComment $ prettyProtoRuleAC ruAC
| Pretty print a closed theory.
| Pretty print a closed diff theory.
prettyClosedEitherRule
prettyClosedEitherRule
Note that here we are relying on the invariant that all proof steps
with a 'Just' annotation follow from the application of
'execProofMethod' to their parent and are valid in the sense that
the application of 'execProofMethod' to their method and constraint
system is guaranteed to succeed.
This is guaranteed initially by 'closeTheory' and is (must be)
maintained by the provers being applied to the theory using
'modifyLemmaProof' or 'proveTheory'. Note that we could check the
proof right before computing its status. This is however quite
expensive, as it requires recomputing all intermediate constraint
systems.
TODO: The whole consruction seems a bit hacky. Think of a more
principled constrution with better correctness guarantees.
Note that here we are relying on the invariant that all proof steps
with a 'Just' annotation follow from the application of
'execProofMethod' to their parent and are valid in the sense that
the application of 'execProofMethod' to their method and constraint
system is guaranteed to succeed.
This is guaranteed initially by 'closeTheory' and is (must be)
maintained by the provers being applied to the theory using
'modifyLemmaProof' or 'proveTheory'. Note that we could check the
proof right before computing its status. This is however quite
expensive, as it requires recomputing all intermediate constraint
systems.
TODO: The whole consruction seems a bit hacky. Think of a more
principled constrution with better correctness guarantees.
Note that here we are relying on the invariant that all proof steps
with a 'Just' annotation follow from the application of
'execProofMethod' to their parent and are valid in the sense that
the application of 'execProofMethod' to their method and constraint
system is guaranteed to succeed.
This is guaranteed initially by 'closeTheory' and is (must be)
maintained by the provers being applied to the theory using
'modifyLemmaProof' or 'proveTheory'. Note that we could check the
proof right before computing its status. This is however quite
expensive, as it requires recomputing all intermediate constraint
systems.
TODO: The whole consruction seems a bit hacky. Think of a more
principled constrution with better correctness guarantees. | module ClosedTheory (
module ClosedTheory
) where
import Control.Basics
import Control.Category
import qualified Data.Set as S
import qualified Extension.Data.Label as L
import Lemma
import Rule
import Safe
import Theory.Model
import Theory.Proof
import TheoryObject
import Prelude hiding (id, (.))
import Text.PrettyPrint.Highlight
import Prelude hiding (id, (.))
import Data.Monoid (Sum(..))
import Theory.Text.Pretty
import OpenTheory
import Pretty
1 . Lemma names are unique
2 . All proof steps with annotated sequents are sound with respect to the
3 . is running under the given handle .
type ClosedTheory =
Theory SignatureWithMaude ClosedRuleCache ClosedProtoRule IncrementalProof ()
1 . Lemma names are unique
2 . All proof steps with annotated sequents are sound with respect to the
3 . is running under the given handle .
type ClosedDiffTheory =
DiffTheory SignatureWithMaude ClosedRuleCache DiffProtoRule ClosedProtoRule IncrementalDiffProof IncrementalProof
| Either Therories can be Either a normal or a diff theory
type EitherClosedTheory = Either ClosedTheory ClosedDiffTheory
getLemmas :: ClosedTheory -> [Lemma IncrementalProof]
getLemmas = theoryLemmas
getDiffLemmas :: ClosedDiffTheory -> [DiffLemma IncrementalDiffProof]
getDiffLemmas = diffTheoryDiffLemmas
getEitherLemmas :: ClosedDiffTheory -> [(Side, Lemma IncrementalProof)]
getEitherLemmas = diffTheoryLemmas
getIntrVariants :: ClosedTheory -> [IntrRuleAC]
getIntrVariants = intruderRules . L.get (crcRules . thyCache)
getIntrVariantsDiff :: Side -> ClosedDiffTheory -> [IntrRuleAC]
getIntrVariantsDiff s
| s == LHS = intruderRules . L.get (crcRules . diffThyCacheLeft)
| s == RHS = intruderRules . L.get (crcRules . diffThyCacheRight)
| otherwise = error $ "The Side MUST always be LHS or RHS."
getProtoRuleEs :: ClosedTheory -> [ProtoRuleE]
getProtoRuleEs = S.toList . S.fromList . map ((L.get oprRuleE) . openProtoRule) . theoryRules
getProtoRuleEsDiff :: Side -> ClosedDiffTheory -> [ProtoRuleE]
getProtoRuleEsDiff s = S.toList . S.fromList . map ((L.get oprRuleE) . openProtoRule) . diffTheorySideRules s
getProofContext :: Lemma a -> ClosedTheory -> ProofContext
getProofContext l thy = ProofContext
( L.get thySignature thy)
( L.get (crcRules . thyCache) thy)
( L.get (crcInjectiveFactInsts . thyCache) thy)
kind
( L.get (cases . thyCache) thy)
inductionHint
specifiedHeuristic
specifiedTactic
(toSystemTraceQuantifier $ L.get lTraceQuantifier l)
(L.get lName l)
([ h | HideLemma h <- L.get lAttributes l])
False
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . thyCache) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . thyCache) thy)
where
kind = lemmaSourceKind l
cases = case kind of RawSource -> crcRawSources
RefinedSource -> crcRefinedSources
inductionHint
| any (`elem` [SourceLemma, InvariantLemma]) (L.get lAttributes l) = UseInduction
| otherwise = AvoidInduction
specifiedHeuristic = case lattr of
Just lh -> Just lh
Nothing -> case L.get thyHeuristic thy of
[] -> Nothing
gh -> Just (Heuristic gh)
where
lattr = (headMay [Heuristic gr
| LemmaHeuristic gr <- L.get lAttributes l])
specifiedTactic = case lattr of
[] -> Nothing
_ -> Just lattr
where
lattr = L.get thyTactic thy
getProofContextDiff :: Side -> Lemma a -> ClosedDiffTheory -> ProofContext
getProofContextDiff s l thy = case s of
LHS -> ProofContext
( L.get diffThySignature thy)
( L.get (crcRules . diffThyCacheLeft) thy)
( L.get (crcInjectiveFactInsts . diffThyCacheLeft) thy)
kind
( L.get (cases . diffThyCacheLeft) thy)
inductionHint
specifiedHeuristic
specifiedTactic
(toSystemTraceQuantifier $ L.get lTraceQuantifier l)
(L.get lName l)
([ h | HideLemma h <- L.get lAttributes l])
False
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheLeft) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheLeft) thy)
RHS -> ProofContext
( L.get diffThySignature thy)
( L.get (crcRules . diffThyCacheRight) thy)
( L.get (crcInjectiveFactInsts . diffThyCacheRight) thy)
kind
( L.get (cases . diffThyCacheRight) thy)
inductionHint
specifiedHeuristic
specifiedTactic
(toSystemTraceQuantifier $ L.get lTraceQuantifier l)
(L.get lName l)
([ h | HideLemma h <- L.get lAttributes l])
False
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheRight) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheRight) thy)
where
kind = lemmaSourceKind l
cases = case kind of RawSource -> crcRawSources
RefinedSource -> crcRefinedSources
inductionHint
| any (`elem` [SourceLemma, InvariantLemma]) (L.get lAttributes l) = UseInduction
| otherwise = AvoidInduction
specifiedHeuristic = case lattr of
Just lh -> Just lh
Nothing -> case L.get diffThyHeuristic thy of
[] -> Nothing
gh -> Just (Heuristic gh)
where
lattr = (headMay [Heuristic gr
| LemmaHeuristic gr <- L.get lAttributes l])
specifiedTactic = case lattr of
[] -> Nothing
_ -> Just lattr
where
lattr = L.get diffThyTactic thy
getDiffProofContext :: DiffLemma a -> ClosedDiffTheory -> DiffProofContext
getDiffProofContext l thy = DiffProofContext (proofContext LHS) (proofContext RHS)
(map (L.get dprRule) $ diffTheoryDiffRules thy) (L.get (crConstruct . crcRules . diffThyDiffCacheLeft) thy)
(L.get (crDestruct . crcRules . diffThyDiffCacheLeft) thy)
((LHS, restrictionsLeft):[(RHS, restrictionsRight)]) gatherReusableLemmas
where
items = L.get diffThyItems thy
restrictionsLeft = do EitherRestrictionItem (LHS, rstr) <- items
return $ formulaToGuarded_ $ L.get rstrFormula rstr
restrictionsRight = do EitherRestrictionItem (RHS, rstr) <- items
return $ formulaToGuarded_ $ L.get rstrFormula rstr
gatherReusableLemmas = do
EitherLemmaItem (s, lem) <- items
guard $ lemmaSourceKind lem <= RefinedSource
&& ReuseDiffLemma `elem` L.get lAttributes lem
&& AllTraces == L.get lTraceQuantifier lem
return $ (s, formulaToGuarded_ $ L.get lFormula lem)
proofContext s = case s of
LHS -> ProofContext
( L.get diffThySignature thy)
( L.get (crcRules . diffThyDiffCacheLeft) thy)
( L.get (crcInjectiveFactInsts . diffThyDiffCacheLeft) thy)
RefinedSource
( L.get (crcRefinedSources . diffThyDiffCacheLeft) thy)
AvoidInduction
specifiedHeuristic
specifiedTactic
ExistsNoTrace
( L.get lDiffName l )
([ h | HideLemma h <- L.get lDiffAttributes l])
True
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheLeft) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheLeft) thy)
RHS -> ProofContext
( L.get diffThySignature thy)
( L.get (crcRules . diffThyDiffCacheRight) thy)
( L.get (crcInjectiveFactInsts . diffThyDiffCacheRight) thy)
RefinedSource
( L.get (crcRefinedSources . diffThyDiffCacheRight) thy)
AvoidInduction
specifiedHeuristic
specifiedTactic
ExistsNoTrace
( L.get lDiffName l )
([ h | HideLemma h <- L.get lDiffAttributes l])
True
(all isSubtermRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheRight) thy)
(any isConstantRule $ filter isDestrRule $ intruderRules $ L.get (crcRules . diffThyCacheRight) thy)
specifiedHeuristic = case lattr of
Just lh -> Just lh
Nothing -> case L.get diffThyHeuristic thy of
[] -> Nothing
gh -> Just (Heuristic gh)
where
lattr = (headMay [Heuristic gr
| LemmaHeuristic gr <- L.get lDiffAttributes l])
specifiedTactic = case lattr of
[] -> Nothing
_ -> Just lattr
where
lattr = L.get diffThyTactic thy
getInjectiveFactInsts :: ClosedTheory -> S.Set FactTag
getInjectiveFactInsts = L.get (crcInjectiveFactInsts . thyCache)
getDiffInjectiveFactInsts :: Side -> Bool -> ClosedDiffTheory -> S.Set FactTag
getDiffInjectiveFactInsts s isdiff = case (s, isdiff) of
(LHS, False) -> L.get (crcInjectiveFactInsts . diffThyCacheLeft)
(RHS, False) -> L.get (crcInjectiveFactInsts . diffThyCacheRight)
(LHS, True) -> L.get (crcInjectiveFactInsts . diffThyDiffCacheLeft)
(RHS, True) -> L.get (crcInjectiveFactInsts . diffThyDiffCacheRight)
getClassifiedRules :: ClosedTheory -> ClassifiedRules
getClassifiedRules = L.get (crcRules . thyCache)
getDiffClassifiedRules :: Side -> Bool -> ClosedDiffTheory -> ClassifiedRules
getDiffClassifiedRules s isdiff = case (s, isdiff) of
(LHS, False) -> L.get (crcRules . diffThyCacheLeft)
(RHS, False) -> L.get (crcRules . diffThyCacheRight)
(LHS, True) -> L.get (crcRules . diffThyDiffCacheLeft)
(RHS, True) -> L.get (crcRules . diffThyDiffCacheRight)
getSource :: SourceKind -> ClosedTheory -> [Source]
getSource RawSource = L.get (crcRawSources . thyCache)
getSource RefinedSource = L.get (crcRefinedSources . thyCache)
getDiffSource :: Side -> Bool -> SourceKind -> ClosedDiffTheory -> [Source]
getDiffSource LHS False RawSource = L.get (crcRawSources . diffThyCacheLeft)
getDiffSource RHS False RawSource = L.get (crcRawSources . diffThyCacheRight)
getDiffSource LHS False RefinedSource = L.get (crcRefinedSources . diffThyCacheLeft)
getDiffSource RHS False RefinedSource = L.get (crcRefinedSources . diffThyCacheRight)
getDiffSource LHS True RawSource = L.get (crcRawSources . diffThyDiffCacheLeft)
getDiffSource RHS True RawSource = L.get (crcRawSources . diffThyDiffCacheRight)
getDiffSource LHS True RefinedSource = L.get (crcRefinedSources . diffThyDiffCacheLeft)
getDiffSource RHS True RefinedSource = L.get (crcRefinedSources . diffThyDiffCacheRight)
closeEitherProtoRule :: MaudeHandle -> (Side, OpenProtoRule) -> (Side, [ClosedProtoRule])
closeEitherProtoRule hnd (s, ruE) = (s, closeProtoRule hnd ruE)
lemmaToGuarded : : Maybe LNGuarded
prettyClosedProtoRule :: HighlightDocument d => ClosedProtoRule -> d
prettyClosedProtoRule cru =
if isTrivialProtoVariantAC ruAC ruE then
(nest 2 $ prettyLoopBreakers (L.get rInfo ruAC) $-$
multiComment_ ["has exactly the trivial AC variant"])
else
if ruleName ruAC == ruleName ruE then
if not (equalUpToTerms ruAC ruE) then
(nest 2 $ prettyLoopBreakers (L.get rInfo ruAC) $-$
multiComment_ ["has exactly the trivial AC variant"])
else
Here we have a rule with one or multiple variants , but without other annotations
(nest 2 $ prettyLoopBreakers (L.get rInfo ruAC) $-$
(multiComment $ prettyProtoRuleAC ruAC))
else
(nest 3 $ prettyLoopBreakers (L.get rInfo ruAC) $-$
(multiComment_ ["variant of"]) $-$
(multiComment $ prettyProtoRuleE ruE)
)
where
ruAC = L.get cprRuleAC cru
ruE = L.get cprRuleE cru
prettyClosedEitherRule : : d = > ( Side , ClosedProtoRule ) - > d
( nest 2 $ prettyLoopBreakers ( L.get rInfo ruAC ) $ -$ ppRuleAC )
prettyClosedTheory :: HighlightDocument d => ClosedTheory -> d
prettyClosedTheory thy = if containsManualRuleVariants mergedRules
then
prettyTheory prettySignatureWithMaude
ppInjectiveFactInsts
( prettyIntrVariantsSection . . L.get crcRules )
prettyOpenProtoRuleAsClosedRule
prettyIncrementalProof
emptyString
thy'
else
prettyTheory prettySignatureWithMaude
ppInjectiveFactInsts
( prettyIntrVariantsSection . . L.get crcRules )
prettyClosedProtoRule
prettyIncrementalProof
emptyString
thy
where
items = L.get thyItems thy
mergedRules = mergeOpenProtoRules $ map (mapTheoryItem openProtoRule id) items
thy' :: Theory SignatureWithMaude ClosedRuleCache OpenProtoRule IncrementalProof ()
thy' = Theory {_thyName=(L.get thyName thy)
,_thyHeuristic=(L.get thyHeuristic thy)
,_thyTactic=(L.get thyTactic thy)
,_thySignature=(L.get thySignature thy)
,_thyCache=(L.get thyCache thy)
,_thyItems = mergedRules
,_thyOptions =(L.get thyOptions thy)}
ppInjectiveFactInsts crc =
case S.toList $ L.get crcInjectiveFactInsts crc of
[] -> emptyDoc
tags -> multiComment $ sep
[ text "looping facts with injective instances:"
, nest 2 $ fsepList (text . showFactTagArity) tags ]
prettyClosedDiffTheory :: HighlightDocument d => ClosedDiffTheory -> d
prettyClosedDiffTheory thy = if containsManualRuleVariantsDiff mergedRules
then
prettyDiffTheory prettySignatureWithMaude
ppInjectiveFactInsts
( prettyIntrVariantsSection . . L.get crcRules )
prettyIncrementalDiffProof
prettyIncrementalProof
thy'
else
prettyDiffTheory prettySignatureWithMaude
ppInjectiveFactInsts
( prettyIntrVariantsSection . . L.get crcRules )
prettyIncrementalDiffProof
prettyIncrementalProof
thy
where
items = L.get diffThyItems thy
mergedRules = mergeLeftRightRulesDiff $ mergeOpenProtoRulesDiff $
map (mapDiffTheoryItem id (\(x, y) -> (x, (openProtoRule y))) id id) items
thy' :: DiffTheory SignatureWithMaude ClosedRuleCache DiffProtoRule OpenProtoRule IncrementalDiffProof IncrementalProof
thy' = DiffTheory {_diffThyName=(L.get diffThyName thy)
,_diffThyHeuristic=(L.get diffThyHeuristic thy)
,_diffThyTactic=(L.get diffThyTactic thy)
,_diffThySignature=(L.get diffThySignature thy)
,_diffThyCacheLeft=(L.get diffThyCacheLeft thy)
,_diffThyCacheRight=(L.get diffThyCacheRight thy)
,_diffThyDiffCacheLeft=(L.get diffThyDiffCacheLeft thy)
,_diffThyDiffCacheRight=(L.get diffThyDiffCacheRight thy)
,_diffThyItems = mergedRules
,_diffThyOptions =(L.get diffThyOptions thy)}
ppInjectiveFactInsts crc =
case S.toList $ L.get crcInjectiveFactInsts crc of
[] -> emptyDoc
tags -> multiComment $ sep
[ text "looping facts with injective instances:"
, nest 2 $ fsepList (text . showFactTagArity) tags ]
prettyClosedSummary :: Document d => ClosedTheory -> d
prettyClosedSummary thy =
vcat lemmaSummaries
where
lemmaSummaries = do
LemmaItem lem <- L.get thyItems thy
let (status, Sum siz) = foldProof proofStepSummary $ L.get lProof lem
quantifier = (toSystemTraceQuantifier $ L.get lTraceQuantifier lem)
analysisType = parens $ prettyTraceQuantifier $ L.get lTraceQuantifier lem
return $ text (L.get lName lem) <-> analysisType <> colon <->
text (showProofStatus quantifier status) <->
parens (integer siz <-> text "steps")
proofStepSummary = proofStepStatus &&& const (Sum (1::Integer))
prettyClosedDiffSummary :: Document d => ClosedDiffTheory -> d
prettyClosedDiffSummary thy =
(vcat lemmaSummaries) $$ (vcat diffLemmaSummaries)
where
lemmaSummaries = do
EitherLemmaItem (s, lem) <- L.get diffThyItems thy
let (status, Sum siz) = foldProof proofStepSummary $ L.get lProof lem
quantifier = (toSystemTraceQuantifier $ L.get lTraceQuantifier lem)
analysisType = parens $ prettyTraceQuantifier $ L.get lTraceQuantifier lem
return $ text (show s) <-> text ": " <-> text (L.get lName lem) <-> analysisType <> colon <->
text (showProofStatus quantifier status) <->
parens (integer siz <-> text "steps")
diffLemmaSummaries = do
DiffLemmaItem (lem) <- L.get diffThyItems thy
let (status, Sum siz) = foldDiffProof diffProofStepSummary $ L.get lDiffProof lem
return $ text "DiffLemma: " <-> text (L.get lDiffName lem) <-> colon <->
text (showDiffProofStatus status) <->
parens (integer siz <-> text "steps")
proofStepSummary = proofStepStatus &&& const (Sum (1::Integer))
diffProofStepSummary = diffProofStepStatus &&& const (Sum (1::Integer))
|
bf11cce68562c8b6f62bfe7667cc74ce0ddf3fdb8836290653132d9ab92eb687 | haskellfoundation/error-message-index | LambdaInCase.hs | module LambdaInCase where
f :: Int -> Int
f x =
case x of
a -> a
| null | https://raw.githubusercontent.com/haskellfoundation/error-message-index/6b80c2fe6d8d2941190bda587bcea6f775ded0a4/message-index/messages/GHC-00482/example1/after/LambdaInCase.hs | haskell | module LambdaInCase where
f :: Int -> Int
f x =
case x of
a -> a
|
|
5e6e4800c41887ea0a12b67c70b062f8e968980ec459de6373bd5d549f0a513f | rixed/ramen | RamenCompletion.ml | open Batteries
open RamenLog
open RamenHelpersNoLog
module C = RamenConf
module CliInfo = RamenConstsCliInfo
module Default = RamenConstsDefault
module Files = RamenFiles
module N = RamenName
let propose (l, h) =
String.print stdout l ;
if h <> "" then (
Char.print stdout '\t' ;
String.print stdout h) ;
print_endline ""
let complete lst s =
List.filter (fun (l, _) -> String.starts_with l s) lst |>
List.iter propose
let commands =
CliInfo.[
supervisor ;
alerter ;
notify ;
compile ;
run ;
kill ;
info ;
tail ;
replay ;
timeseries ;
ps ;
links ;
test ;
httpd ;
tunneld ;
variants ;
gc ;
stats ;
archivist ;
summary ;
dequeue ;
repair ;
dump_ringbuf ;
confserver ;
confclient ;
precompserver ;
execompserver ;
choreographer ;
useradd ;
userdel ;
usermod ]
let complete_commands =
let commands =
("--help", CliInfo.help) ::
("--version", CliInfo.version) ::
(List.map (fun cmd -> cmd.CliInfo.name, cmd.doc) commands)
in
fun s ->
complete commands s
let complete_global_options s =
let options =
[ "--help", CliInfo.help ;
"--version", CliInfo.version ] in
complete options s
let find_opt o =
let opt_value s =
String.split s ~by:"=" |> snd in
let o_eq = o ^ "=" in
let find_opt_1 s =
if String.starts_with s o_eq then opt_value s else
raise Not_found in
let rec loop = function
| [] -> raise Not_found
| [s] -> find_opt_1 s
| s::(n::_ as rest) ->
if s = o then n else
try find_opt_1 s
with Not_found -> loop rest in
fun lst -> loop lst
let persist_dir toks =
try find_opt "--persist-dir" toks |> N.path
with Not_found ->
try Sys.getenv "RAMEN_DIR" |> N.path
with Not_found -> Default.persist_dir
let complete_file select str =
let count = ref 0 in
let res = ref [] in
let root, pref =
if str = "" then
N.path ".", N.path ""
else if str.[String.length str - 1] = '/' then
N.path str, N.path str
else
let d = Filename.dirname str in
N.path d, N.path (if d = "." && str.[0] <> '.' then "" else d^"/") in
let start =
(* [basename ""] would be ".", and [basename "toto/"] would be toto ?! *)
if str = "" || str.[String.length str - 1] = '/' then N.path ""
else Files.basename (N.path str) in
let on_file fname rel_fname =
if select fname && N.starts_with rel_fname start then (
incr count ;
if !count > 500 then raise Exit ;
res := (N.cat pref rel_fname, "") :: !res) in
if str <> "" && str.[0] = '-' then [] else (
(try Files.dir_subtree_iter ~on_file root
with Exit -> ()) ;
(!res :> (string * string) list)
)
let complete_program_files str =
complete_file (Files.has_ext "ramen") str
let complete_binary_files str =
complete_file (Files.has_ext "x") str
let complete_test_file str =
complete_file (Files.has_ext "test") str
let complete_rb_file str =
complete_file (fun f -> Files.(has_ext "r" f || has_ext "b" f)) str
let remove_ext = List.map (fun (f, empty) ->
(Filename.remove_extension f, empty))
(*let empty_help s = s, ""*)
let complete_running_function _persist_dir =
(* TODO: run `ramen ps` in the background *)
[]
let conf = C.make_conf " completion " ) in
(
Hashtbl.values ( RC.with_rlock conf identity ) //@
( fun ( _ mre , get_rc ) - >
try Some ( get_rc ( ) )
with _ - > None ) /@
( fun prog - >
List.enum prog.P.funcs | >
Enum.map ( fun func - >
( func . F.program_name :> string ) ^"/"^
( func.F.name :> string ) ) ) | >
Enum.flatten
) /@
empty_help | > List.of_enum
(
Hashtbl.values (RC.with_rlock conf identity) //@
(fun (_mre, get_rc) ->
try Some (get_rc ())
with _ -> None) /@
(fun prog ->
List.enum prog.P.funcs |>
Enum.map (fun func ->
(func.F.program_name :> string) ^"/"^
(func.F.name :> string))) |>
Enum.flatten
) /@
empty_help |> List.of_enum *)
let complete_running_program _persist_dir =
(* TODO: run `ramen ps` in the background *)
[]
let conf = C.make_conf " completion " ) in
Hashtbl.enum ( RC.with_rlock conf identity ) //@
( fun ( p , ( rce , _ ) ) - >
if rce.RC.status = RC.MustRun then
Some ( p :> string )
else None ) /@
empty_help | > List.of_enum
Hashtbl.enum (RC.with_rlock conf identity) //@
(fun (p, (rce, _)) ->
if rce.RC.status = RC.MustRun then
Some (p :> string)
else None) /@
empty_help |> List.of_enum*)
let complete str () =
, find where we are :
let last_tok_is_complete =
let len = String.length str in
len > 0 && Char.is_whitespace str.[len - 1] in
let toks =
string_split_on_char ' ' str |>
List.filter (fun s -> String.length s > 0) in
let toks =
match toks with
| s :: rest when String.ends_with s "ramen" -> rest
| r -> r (* ?? *) in
let num_toks = List.length toks in
let command_idx, command =
try List.findi (fun _ s -> s.[0] <> '-') toks
with Not_found -> -1, "" in
let last_tok =
if num_toks > 0 then List.nth toks (num_toks-1)
else "" in
! logger.info " num_toks=%d , command_idx=%d , command=%s , last_tok_complete=%b "
num_toks command_idx command ;
num_toks command_idx command last_tok_is_complete ;*)
(match num_toks, command_idx, last_tok_is_complete with
| 0, _, true -> (* "ramen<TAB>" *)
complete_commands ""
| 0, _, false -> (* "ramen <TAB>" *)
complete_commands ""
| _, -1, false -> (* "ramen [[other options]] --...<TAB>" *)
complete_global_options last_tok
| _, c_idx, false when c_idx = num_toks-1 -> (* "ramen ... comm<TAB>" *)
complete_commands last_tok
| _ -> (* "ramen ... command ...? <TAB>" *)
let toks = List.drop (command_idx+1) toks in
let completions =
match List.find (fun cmd -> cmd.CliInfo.name = command) commands with
| exception Not_found ->
[]
| cmd ->
List.filter_map (fun opt ->
match opt.CliInfo.names with
| [] ->
None
| name :: _ ->
This works because the first option is always a long
* option :
* option: *)
Some ("--"^ name, opt.doc)
) cmd.CliInfo.opts @
(
if cmd.CliInfo.name = "compile" then
complete_program_files last_tok
else if cmd.name = "run" then
complete_program_files last_tok |> remove_ext
else if cmd.name = "kill" then
let persist_dir = persist_dir toks in
complete_running_program persist_dir
else if cmd.name = "info" then
complete_binary_files last_tok
else if List.mem cmd.name [
"tail" ; "replay" ; "timeseries" ; "ps" ; "links" ] then
let persist_dir = persist_dir toks in
complete_running_function persist_dir
else if cmd.name = "test" then
complete_test_file last_tok
else if List.mem cmd.name [
"ringbuf-summary" ; "dequeue" ; "repair-ringbuf" ;
"dump-ringbuf" ] then
complete_rb_file last_tok
else
[]
)
in
complete completions (if last_tok_is_complete then "" else last_tok))
| null | https://raw.githubusercontent.com/rixed/ramen/11b1b34c3bf73ee6c69d7eb5c5fbf30e6dd2df4f/src/RamenCompletion.ml | ocaml | [basename ""] would be ".", and [basename "toto/"] would be toto ?!
let empty_help s = s, ""
TODO: run `ramen ps` in the background
TODO: run `ramen ps` in the background
??
"ramen<TAB>"
"ramen <TAB>"
"ramen [[other options]] --...<TAB>"
"ramen ... comm<TAB>"
"ramen ... command ...? <TAB>" | open Batteries
open RamenLog
open RamenHelpersNoLog
module C = RamenConf
module CliInfo = RamenConstsCliInfo
module Default = RamenConstsDefault
module Files = RamenFiles
module N = RamenName
let propose (l, h) =
String.print stdout l ;
if h <> "" then (
Char.print stdout '\t' ;
String.print stdout h) ;
print_endline ""
let complete lst s =
List.filter (fun (l, _) -> String.starts_with l s) lst |>
List.iter propose
let commands =
CliInfo.[
supervisor ;
alerter ;
notify ;
compile ;
run ;
kill ;
info ;
tail ;
replay ;
timeseries ;
ps ;
links ;
test ;
httpd ;
tunneld ;
variants ;
gc ;
stats ;
archivist ;
summary ;
dequeue ;
repair ;
dump_ringbuf ;
confserver ;
confclient ;
precompserver ;
execompserver ;
choreographer ;
useradd ;
userdel ;
usermod ]
let complete_commands =
let commands =
("--help", CliInfo.help) ::
("--version", CliInfo.version) ::
(List.map (fun cmd -> cmd.CliInfo.name, cmd.doc) commands)
in
fun s ->
complete commands s
let complete_global_options s =
let options =
[ "--help", CliInfo.help ;
"--version", CliInfo.version ] in
complete options s
let find_opt o =
let opt_value s =
String.split s ~by:"=" |> snd in
let o_eq = o ^ "=" in
let find_opt_1 s =
if String.starts_with s o_eq then opt_value s else
raise Not_found in
let rec loop = function
| [] -> raise Not_found
| [s] -> find_opt_1 s
| s::(n::_ as rest) ->
if s = o then n else
try find_opt_1 s
with Not_found -> loop rest in
fun lst -> loop lst
let persist_dir toks =
try find_opt "--persist-dir" toks |> N.path
with Not_found ->
try Sys.getenv "RAMEN_DIR" |> N.path
with Not_found -> Default.persist_dir
let complete_file select str =
let count = ref 0 in
let res = ref [] in
let root, pref =
if str = "" then
N.path ".", N.path ""
else if str.[String.length str - 1] = '/' then
N.path str, N.path str
else
let d = Filename.dirname str in
N.path d, N.path (if d = "." && str.[0] <> '.' then "" else d^"/") in
let start =
if str = "" || str.[String.length str - 1] = '/' then N.path ""
else Files.basename (N.path str) in
let on_file fname rel_fname =
if select fname && N.starts_with rel_fname start then (
incr count ;
if !count > 500 then raise Exit ;
res := (N.cat pref rel_fname, "") :: !res) in
if str <> "" && str.[0] = '-' then [] else (
(try Files.dir_subtree_iter ~on_file root
with Exit -> ()) ;
(!res :> (string * string) list)
)
let complete_program_files str =
complete_file (Files.has_ext "ramen") str
let complete_binary_files str =
complete_file (Files.has_ext "x") str
let complete_test_file str =
complete_file (Files.has_ext "test") str
let complete_rb_file str =
complete_file (fun f -> Files.(has_ext "r" f || has_ext "b" f)) str
let remove_ext = List.map (fun (f, empty) ->
(Filename.remove_extension f, empty))
let complete_running_function _persist_dir =
[]
let conf = C.make_conf " completion " ) in
(
Hashtbl.values ( RC.with_rlock conf identity ) //@
( fun ( _ mre , get_rc ) - >
try Some ( get_rc ( ) )
with _ - > None ) /@
( fun prog - >
List.enum prog.P.funcs | >
Enum.map ( fun func - >
( func . F.program_name :> string ) ^"/"^
( func.F.name :> string ) ) ) | >
Enum.flatten
) /@
empty_help | > List.of_enum
(
Hashtbl.values (RC.with_rlock conf identity) //@
(fun (_mre, get_rc) ->
try Some (get_rc ())
with _ -> None) /@
(fun prog ->
List.enum prog.P.funcs |>
Enum.map (fun func ->
(func.F.program_name :> string) ^"/"^
(func.F.name :> string))) |>
Enum.flatten
) /@
empty_help |> List.of_enum *)
let complete_running_program _persist_dir =
[]
let conf = C.make_conf " completion " ) in
Hashtbl.enum ( RC.with_rlock conf identity ) //@
( fun ( p , ( rce , _ ) ) - >
if rce.RC.status = RC.MustRun then
Some ( p :> string )
else None ) /@
empty_help | > List.of_enum
Hashtbl.enum (RC.with_rlock conf identity) //@
(fun (p, (rce, _)) ->
if rce.RC.status = RC.MustRun then
Some (p :> string)
else None) /@
empty_help |> List.of_enum*)
let complete str () =
, find where we are :
let last_tok_is_complete =
let len = String.length str in
len > 0 && Char.is_whitespace str.[len - 1] in
let toks =
string_split_on_char ' ' str |>
List.filter (fun s -> String.length s > 0) in
let toks =
match toks with
| s :: rest when String.ends_with s "ramen" -> rest
let num_toks = List.length toks in
let command_idx, command =
try List.findi (fun _ s -> s.[0] <> '-') toks
with Not_found -> -1, "" in
let last_tok =
if num_toks > 0 then List.nth toks (num_toks-1)
else "" in
! logger.info " num_toks=%d , command_idx=%d , command=%s , last_tok_complete=%b "
num_toks command_idx command ;
num_toks command_idx command last_tok_is_complete ;*)
(match num_toks, command_idx, last_tok_is_complete with
complete_commands ""
complete_commands ""
complete_global_options last_tok
complete_commands last_tok
let toks = List.drop (command_idx+1) toks in
let completions =
match List.find (fun cmd -> cmd.CliInfo.name = command) commands with
| exception Not_found ->
[]
| cmd ->
List.filter_map (fun opt ->
match opt.CliInfo.names with
| [] ->
None
| name :: _ ->
This works because the first option is always a long
* option :
* option: *)
Some ("--"^ name, opt.doc)
) cmd.CliInfo.opts @
(
if cmd.CliInfo.name = "compile" then
complete_program_files last_tok
else if cmd.name = "run" then
complete_program_files last_tok |> remove_ext
else if cmd.name = "kill" then
let persist_dir = persist_dir toks in
complete_running_program persist_dir
else if cmd.name = "info" then
complete_binary_files last_tok
else if List.mem cmd.name [
"tail" ; "replay" ; "timeseries" ; "ps" ; "links" ] then
let persist_dir = persist_dir toks in
complete_running_function persist_dir
else if cmd.name = "test" then
complete_test_file last_tok
else if List.mem cmd.name [
"ringbuf-summary" ; "dequeue" ; "repair-ringbuf" ;
"dump-ringbuf" ] then
complete_rb_file last_tok
else
[]
)
in
complete completions (if last_tok_is_complete then "" else last_tok))
|
3a153c2f35c746f3c40ff2dc96b070ef15130612514ab54eab627376da606548 | plewto/Cadejo | registry_editor.clj | (ns cadejo.ui.scale.registry-editor
"Provides ScaleRegistry GUI"
(:require [cadejo.config :as config])
(:require [cadejo.scale.registry])
(:require [cadejo.util.path :as path])
(:require [cadejo.util.user-message :as umsg])
(:require [cadejo.ui.util.overwrite-warning])
(:require [cadejo.ui.util.undo-stack])
(:require [cadejo.ui.util.factory :as factory])
(:require [cadejo.ui.util.help])
(:require [cadejo.ui.util.lnf :as lnf])
(:require [cadejo.scale.eqtemp])
(:require [cadejo.ui.scale.addscale])
(:require [cadejo.ui.scale.subeditors :as subeditors])
(:require [seesaw.chooser])
(:require [seesaw.border :as ssb])
(:require [seesaw.core :as ss]))
(def current-filename* (atom ""))
(def spinner-size [100 :by 28])
(def filefilter (let [ext cadejo.scale.registry/file-extension
description "Cadejo scale registry files"]
(seesaw.chooser/file-filter
description
(fn [f]
(path/has-extension? (.getAbsolutePath f) ext)))))
(defn open-dialog [ed registry]
(let [ext cadejo.scale.registry/file-extension
success (fn [jfc f]
(let [abs (path/replace-extension (.getAbsolutePath f) ext)]
(.push-undo-state! ed (format "Open %s" abs))
(if (.read-registry! registry abs)
(do
(reset! current-filename* abs)
(.sync-ui! ed)
(.status! ed (format "Opened registry '%s'" abs)))
(.warning! ed (format "Can not open '%s' as registry"
abs)))))
cancel (fn [jfc]
(.status! ed "Open registry canceled"))
dia (seesaw.chooser/choose-file
:type :open
:dir @current-filename*
:multi? false
:selection-mode :files-only
:filters [filefilter]
:remember-directory? true
:success-fn success
:cancel-fn cancel)]))
(defn save-dialog [ed registry]
(let [ext cadejo.scale.registry/file-extension
success (fn [jfc f]
(let [abs (path/append-extension (.getAbsolutePath f) ext)]
(if (cadejo.ui.util.overwrite-warning/overwrite-warning
(.widget ed :pan-main) "Scale registry" abs)
(if (.write-registry registry abs)
(do
(reset! current-filename* abs)
(.status! ed (format "Saved registry file %s" abs)))
(.warning! ed (format "Can not save registry to '%s'"
abs)))
(.status! ed "Save canceled"))))
cancel (fn [jfc]
(.status! ed "Registry save canceled"))
default-file @current-filename*
dia (seesaw.chooser/choose-file
:type :save
:dir default-file
:multi? false
:selection-mode :files-only
:filters [filefilter]
:remember-directory? true
:success-fn success
:cancel-fn cancel)]))
(defprotocol RegistryEditor
(widgets
[this])
(widget
[this key])
(sync-ui!
[this])
(selected-table-id
[this])
(selected-table
[this])
(registry
[this])
(push-undo-state!
[this action])
(push-redo-state!
[this action])
(undo!
[this])
(redo!
[this])
(status!
[this msg])
(warning!
[this msg])
(keyrange
[this]
"Returns pair [lower upper]")
(enable-keyrange!
[this flag])
(wraprange
[this]
"Returns pair [lower upper]")
(enable-wrap!
[this flag]))
(defn registry-editor [scene]
(let [sregistry (.scale-registry scene)
undo-stack (cadejo.ui.util.undo-stack/undo-stack "Undo")
redo-stack (cadejo.ui.util.undo-stack/undo-stack "Redo")
enable-change-listeners* (atom true)
North toolbar
jb-init (factory/button "Reset" :general :reset "Initialize scale registry")
jb-open (factory/button "Open" :general :open "Open scale registry file")
jb-save (factory/button "Save" :general :save "Save scale registry file")
jb-undo (.get-button undo-stack)
jb-redo (.get-button redo-stack)
jb-help (factory/button "Help" :general :help "Scale registry help")
jb-delete (factory/button "Delete" :general :delete "Remove table from registry")
group (ss/button-group)
jtb-add (let [b (factory/toggle "Add" :general :add "Add tables to registry" group)]
(.setSelected b true)
b)
jtb-edit (factory/toggle "Edit" :edit nil "Edit registry tables" group)
jtb-detail (factory/toggle "Detail" :view :detail "Detail table editor" group)
pan-toolbar (ss/toolbar :floatable? false
:items [jb-init jb-open jb-save
:separator jb-undo jb-redo
:separator jb-delete jtb-add jtb-edit jtb-detail
:separator jb-help])
;; West registered scale list
lst-registry (ss/listbox :model (.registered-tables sregistry)
:size [200 :by 300])
pan-west (ss/vertical-panel :items [(ss/scrollable lst-registry)]
:border (factory/title "Registered Scales"))
;; Edit limits
spin-range-low (ss/spinner :model (ss/spinner-model
0 :from 0 :to 127 :by 1)
:size spinner-size)
spin-range-high (ss/spinner :model (ss/spinner-model
127 :from 0 :to 127 :by 1)
:size spinner-size)
spin-wrap-low (ss/spinner :model (ss/spinner-model
0 :from 0 :to 200 :by 10)
:size spinner-size)
spin-wrap-high (ss/spinner :model (ss/spinner-model
20000
:from 4000 :to 20000 :by 1000)
:size spinner-size)
pan-range-low (ss/vertical-panel :items [spin-range-low]
:border (factory/title "Low"))
pan-range-high (ss/vertical-panel :items [spin-range-high]
:border (factory/title "High"))
pan-range (ss/vertical-panel :items [pan-range-low pan-range-high]
:border (factory/title "Key range"))
pan-wrap-low (ss/vertical-panel :items [spin-wrap-low]
:border (factory/title "Low"))
pan-wrap-high (ss/vertical-panel :items [spin-wrap-high]
:border (factory/title "High"))
pan-wrap (ss/vertical-panel :items [pan-wrap-low pan-wrap-high]
:border (factory/title "Wrap"))
pan-limits (ss/vertical-panel :items [pan-range pan-wrap])
;; Main Panels
pan-subedit (ss/card-panel :border (factory/line))
pan-center (ss/border-panel :west pan-limits
:center pan-subedit)
pan-main (ss/border-panel :north pan-toolbar
:west pan-west
:center pan-center)
;; splice labels
lab-splice-source (ss/label :text " "
:border (factory/title "Source"))
lab-splice-destination (ss/label :text " "
:border (factory/title "Destination"))
widget-map {:jb-init jb-init
:jb-open jb-open
:jb-save jb-save
:jb-undo jb-undo
:jb-redo jb-redo
:jb-delete jb-delete
:jtb-add jtb-add
:jtb-edit jtb-edit
:jtb-detail jtb-detail
:lab-splice-source lab-splice-source
:lab-splice-destination lab-splice-destination
:lst-registry lst-registry
:pan-main pan-main
:pan-range pan-range
:pan-range-low pan-range-low
:pan-range-high pan-range-high
:pan-wrap pan-wrap
:pan-wrap-low pan-wrap-low
:pan-wrap-high pan-wrap-high
:spin-range-low spin-range-low
:spin-range-high spin-range-high
:spin-wrap-low spin-wrap-low
:spin-wrap-high spin-wrap-high}
ed (reify RegistryEditor
(widgets [this] widget-map)
(widget [this key]
(or (get widget-map key)
(umsg/warning (format "RegistryEditor does not have %s widget" key))))
(sync-ui! [this]
(reset! enable-change-listeners* false)
(ss/config! lst-registry :model (.registered-tables sregistry))
(reset! enable-change-listeners* true))
(selected-table-id [this]
(.getSelectedValue lst-registry))
(selected-table [this]
(let [id (.selected-table-id this)]
(if id
(.table sregistry id)
nil)))
(registry [this] sregistry)
(push-undo-state! [this action]
(let [state (.clone sregistry)]
(.push-state! undo-stack [action state])))
(push-redo-state! [this action]
(let [state (.clone sregistry)]
(.push-state! redo-stack [action state])))
(undo! [this]
(if (not (.is-empty? undo-stack))
(let [[action state](.pop-state! undo-stack)]
(.push-redo-state! this action)
(.copy-state! sregistry state)
(.sync-ui! this)
(.status! this (format "Undo %s" action)))
(.warning! this "Nothing to undo")))
(redo! [this]
(if (not (.is-empty? redo-stack))
(let [[action state](.pop-state! redo-stack)]
(.push-undo-state! this action)
(.copy-state! sregistry state)
(.sync-ui! this)
(.status! this (format "Redo %s" action)))
(.warning! this "Nothing to redo")))
(status! [this msg]
(let [sed (.get-editor scene)]
(.status! sed msg)))
(warning! [this msg]
(let [sed (.get-editor scene)]
(.warning! sed msg)))
(keyrange [this]
(let [a (.getValue spin-range-low)
b (.getValue spin-range-high)]
[(min a b)(max a b)]))
(enable-keyrange! [this flag]
(.setEnabled spin-range-low flag)
(.setEnabled spin-range-high flag)
(.setEnabled pan-range-low flag)
(.setEnabled pan-range-high flag)
(.setEnabled pan-range flag))
(wraprange [this]
(let [a (.getValue spin-wrap-low)
b (.getValue spin-wrap-high)]
[(min a b)(max a b)]))
(enable-wrap! [this flag]
(.setEnabled spin-wrap-low flag)
(.setEnabled spin-wrap-high flag)
(.setEnabled pan-wrap-low flag)
(.setEnabled pan-wrap-high flag)
(.setEnabled pan-wrap flag)))]
(ss/listen jb-init :action
(fn [_]
(.push-undo-state! ed "Initialize Registry")
(doseq [k (.registered-tables sregistry)]
(.remove-table! sregistry k))
(.add-table! sregistry :eq-12 cadejo.scale.eqtemp/default-table)
(ss/config! lab-splice-source :text " ")
(ss/config! lab-splice-destination :text " ")
(.sync-ui! ed)
(.status! ed "Initialized Scale Registry")))
(ss/listen jb-open :action (fn [_]
(open-dialog ed (.registry ed))))
(ss/listen jb-save :action (fn [_]
(save-dialog ed (.registry ed))))
(ss/listen jb-undo :action (fn [_](.undo! ed)))
(ss/listen jb-redo :action (fn [_](.redo! ed)))
(ss/listen jb-delete :action
(fn [_]
(let [id (.selected-table-id ed)]
(if id
(do
(.push-undo-state! ed (format "Delete %s" id))
(.remove-table! sregistry id)
(ss/config! lab-splice-source :text " ")
(ss/config! lab-splice-destination :text " ")
(.sync-ui! ed)
(.status! ed (format "Deleted scale %s" id)))
(warning! ed "No scale selected for deletion")))))
(let [addscale-subeditor (cadejo.ui.scale.addscale/addscale ed)
linear-subeditor (subeditors/linear-editor ed)
transpose-subeditor (subeditors/transpose-editor ed)
splice-subeditor (subeditors/splice-editor ed lab-splice-source
lab-splice-destination)
pan-edit (ss/grid-panel :rows 1
:items [linear-subeditor
transpose-subeditor
splice-subeditor])]
(ss/add! pan-subedit [addscale-subeditor :addscale])
(ss/add! pan-subedit [pan-edit :transpose])
(ss/add! pan-subedit [(ss/label :text "Nothing to see here") :detail]))
;; update splice source & destination labels
(ss/listen lst-registry :selection
(fn [_]
(if (and @enable-change-listeners*
(not (.getValueIsAdjusting lst-registry)))
(do
(ss/config! lab-splice-destination :text
(ss/config lab-splice-source :text))
(ss/config! lab-splice-source :text
(name (.getSelectedValue lst-registry)))))))
(ss/listen jtb-add :action
(fn [_]
(.enable-keyrange! ed false)
(.enable-wrap! ed false)
(ss/show-card! pan-subedit :addscale)))
(ss/listen jtb-edit :action
(fn [_]
(.enable-keyrange! ed true)
(.enable-wrap! ed true)
(ss/show-card! pan-subedit :transpose)))
(ss/listen jtb-detail :action
(fn [_]
(ss/show-card! pan-subedit :detail)
(.warning! ed "Detail editor not implemented")))
(.putClientProperty jb-help :topic :scale-registry)
;(ss/listen jb-help :action cadejo.ui.util.help/help-listener)
ed))
| null | https://raw.githubusercontent.com/plewto/Cadejo/2a98610ce1f5fe01dce5f28d986a38c86677fd67/src/cadejo/ui/scale/registry_editor.clj | clojure | West registered scale list
Edit limits
Main Panels
splice labels
update splice source & destination labels
(ss/listen jb-help :action cadejo.ui.util.help/help-listener) | (ns cadejo.ui.scale.registry-editor
"Provides ScaleRegistry GUI"
(:require [cadejo.config :as config])
(:require [cadejo.scale.registry])
(:require [cadejo.util.path :as path])
(:require [cadejo.util.user-message :as umsg])
(:require [cadejo.ui.util.overwrite-warning])
(:require [cadejo.ui.util.undo-stack])
(:require [cadejo.ui.util.factory :as factory])
(:require [cadejo.ui.util.help])
(:require [cadejo.ui.util.lnf :as lnf])
(:require [cadejo.scale.eqtemp])
(:require [cadejo.ui.scale.addscale])
(:require [cadejo.ui.scale.subeditors :as subeditors])
(:require [seesaw.chooser])
(:require [seesaw.border :as ssb])
(:require [seesaw.core :as ss]))
(def current-filename* (atom ""))
(def spinner-size [100 :by 28])
(def filefilter (let [ext cadejo.scale.registry/file-extension
description "Cadejo scale registry files"]
(seesaw.chooser/file-filter
description
(fn [f]
(path/has-extension? (.getAbsolutePath f) ext)))))
(defn open-dialog [ed registry]
(let [ext cadejo.scale.registry/file-extension
success (fn [jfc f]
(let [abs (path/replace-extension (.getAbsolutePath f) ext)]
(.push-undo-state! ed (format "Open %s" abs))
(if (.read-registry! registry abs)
(do
(reset! current-filename* abs)
(.sync-ui! ed)
(.status! ed (format "Opened registry '%s'" abs)))
(.warning! ed (format "Can not open '%s' as registry"
abs)))))
cancel (fn [jfc]
(.status! ed "Open registry canceled"))
dia (seesaw.chooser/choose-file
:type :open
:dir @current-filename*
:multi? false
:selection-mode :files-only
:filters [filefilter]
:remember-directory? true
:success-fn success
:cancel-fn cancel)]))
(defn save-dialog [ed registry]
(let [ext cadejo.scale.registry/file-extension
success (fn [jfc f]
(let [abs (path/append-extension (.getAbsolutePath f) ext)]
(if (cadejo.ui.util.overwrite-warning/overwrite-warning
(.widget ed :pan-main) "Scale registry" abs)
(if (.write-registry registry abs)
(do
(reset! current-filename* abs)
(.status! ed (format "Saved registry file %s" abs)))
(.warning! ed (format "Can not save registry to '%s'"
abs)))
(.status! ed "Save canceled"))))
cancel (fn [jfc]
(.status! ed "Registry save canceled"))
default-file @current-filename*
dia (seesaw.chooser/choose-file
:type :save
:dir default-file
:multi? false
:selection-mode :files-only
:filters [filefilter]
:remember-directory? true
:success-fn success
:cancel-fn cancel)]))
(defprotocol RegistryEditor
(widgets
[this])
(widget
[this key])
(sync-ui!
[this])
(selected-table-id
[this])
(selected-table
[this])
(registry
[this])
(push-undo-state!
[this action])
(push-redo-state!
[this action])
(undo!
[this])
(redo!
[this])
(status!
[this msg])
(warning!
[this msg])
(keyrange
[this]
"Returns pair [lower upper]")
(enable-keyrange!
[this flag])
(wraprange
[this]
"Returns pair [lower upper]")
(enable-wrap!
[this flag]))
(defn registry-editor [scene]
(let [sregistry (.scale-registry scene)
undo-stack (cadejo.ui.util.undo-stack/undo-stack "Undo")
redo-stack (cadejo.ui.util.undo-stack/undo-stack "Redo")
enable-change-listeners* (atom true)
North toolbar
jb-init (factory/button "Reset" :general :reset "Initialize scale registry")
jb-open (factory/button "Open" :general :open "Open scale registry file")
jb-save (factory/button "Save" :general :save "Save scale registry file")
jb-undo (.get-button undo-stack)
jb-redo (.get-button redo-stack)
jb-help (factory/button "Help" :general :help "Scale registry help")
jb-delete (factory/button "Delete" :general :delete "Remove table from registry")
group (ss/button-group)
jtb-add (let [b (factory/toggle "Add" :general :add "Add tables to registry" group)]
(.setSelected b true)
b)
jtb-edit (factory/toggle "Edit" :edit nil "Edit registry tables" group)
jtb-detail (factory/toggle "Detail" :view :detail "Detail table editor" group)
pan-toolbar (ss/toolbar :floatable? false
:items [jb-init jb-open jb-save
:separator jb-undo jb-redo
:separator jb-delete jtb-add jtb-edit jtb-detail
:separator jb-help])
lst-registry (ss/listbox :model (.registered-tables sregistry)
:size [200 :by 300])
pan-west (ss/vertical-panel :items [(ss/scrollable lst-registry)]
:border (factory/title "Registered Scales"))
spin-range-low (ss/spinner :model (ss/spinner-model
0 :from 0 :to 127 :by 1)
:size spinner-size)
spin-range-high (ss/spinner :model (ss/spinner-model
127 :from 0 :to 127 :by 1)
:size spinner-size)
spin-wrap-low (ss/spinner :model (ss/spinner-model
0 :from 0 :to 200 :by 10)
:size spinner-size)
spin-wrap-high (ss/spinner :model (ss/spinner-model
20000
:from 4000 :to 20000 :by 1000)
:size spinner-size)
pan-range-low (ss/vertical-panel :items [spin-range-low]
:border (factory/title "Low"))
pan-range-high (ss/vertical-panel :items [spin-range-high]
:border (factory/title "High"))
pan-range (ss/vertical-panel :items [pan-range-low pan-range-high]
:border (factory/title "Key range"))
pan-wrap-low (ss/vertical-panel :items [spin-wrap-low]
:border (factory/title "Low"))
pan-wrap-high (ss/vertical-panel :items [spin-wrap-high]
:border (factory/title "High"))
pan-wrap (ss/vertical-panel :items [pan-wrap-low pan-wrap-high]
:border (factory/title "Wrap"))
pan-limits (ss/vertical-panel :items [pan-range pan-wrap])
pan-subedit (ss/card-panel :border (factory/line))
pan-center (ss/border-panel :west pan-limits
:center pan-subedit)
pan-main (ss/border-panel :north pan-toolbar
:west pan-west
:center pan-center)
lab-splice-source (ss/label :text " "
:border (factory/title "Source"))
lab-splice-destination (ss/label :text " "
:border (factory/title "Destination"))
widget-map {:jb-init jb-init
:jb-open jb-open
:jb-save jb-save
:jb-undo jb-undo
:jb-redo jb-redo
:jb-delete jb-delete
:jtb-add jtb-add
:jtb-edit jtb-edit
:jtb-detail jtb-detail
:lab-splice-source lab-splice-source
:lab-splice-destination lab-splice-destination
:lst-registry lst-registry
:pan-main pan-main
:pan-range pan-range
:pan-range-low pan-range-low
:pan-range-high pan-range-high
:pan-wrap pan-wrap
:pan-wrap-low pan-wrap-low
:pan-wrap-high pan-wrap-high
:spin-range-low spin-range-low
:spin-range-high spin-range-high
:spin-wrap-low spin-wrap-low
:spin-wrap-high spin-wrap-high}
ed (reify RegistryEditor
(widgets [this] widget-map)
(widget [this key]
(or (get widget-map key)
(umsg/warning (format "RegistryEditor does not have %s widget" key))))
(sync-ui! [this]
(reset! enable-change-listeners* false)
(ss/config! lst-registry :model (.registered-tables sregistry))
(reset! enable-change-listeners* true))
(selected-table-id [this]
(.getSelectedValue lst-registry))
(selected-table [this]
(let [id (.selected-table-id this)]
(if id
(.table sregistry id)
nil)))
(registry [this] sregistry)
(push-undo-state! [this action]
(let [state (.clone sregistry)]
(.push-state! undo-stack [action state])))
(push-redo-state! [this action]
(let [state (.clone sregistry)]
(.push-state! redo-stack [action state])))
(undo! [this]
(if (not (.is-empty? undo-stack))
(let [[action state](.pop-state! undo-stack)]
(.push-redo-state! this action)
(.copy-state! sregistry state)
(.sync-ui! this)
(.status! this (format "Undo %s" action)))
(.warning! this "Nothing to undo")))
(redo! [this]
(if (not (.is-empty? redo-stack))
(let [[action state](.pop-state! redo-stack)]
(.push-undo-state! this action)
(.copy-state! sregistry state)
(.sync-ui! this)
(.status! this (format "Redo %s" action)))
(.warning! this "Nothing to redo")))
(status! [this msg]
(let [sed (.get-editor scene)]
(.status! sed msg)))
(warning! [this msg]
(let [sed (.get-editor scene)]
(.warning! sed msg)))
(keyrange [this]
(let [a (.getValue spin-range-low)
b (.getValue spin-range-high)]
[(min a b)(max a b)]))
(enable-keyrange! [this flag]
(.setEnabled spin-range-low flag)
(.setEnabled spin-range-high flag)
(.setEnabled pan-range-low flag)
(.setEnabled pan-range-high flag)
(.setEnabled pan-range flag))
(wraprange [this]
(let [a (.getValue spin-wrap-low)
b (.getValue spin-wrap-high)]
[(min a b)(max a b)]))
(enable-wrap! [this flag]
(.setEnabled spin-wrap-low flag)
(.setEnabled spin-wrap-high flag)
(.setEnabled pan-wrap-low flag)
(.setEnabled pan-wrap-high flag)
(.setEnabled pan-wrap flag)))]
(ss/listen jb-init :action
(fn [_]
(.push-undo-state! ed "Initialize Registry")
(doseq [k (.registered-tables sregistry)]
(.remove-table! sregistry k))
(.add-table! sregistry :eq-12 cadejo.scale.eqtemp/default-table)
(ss/config! lab-splice-source :text " ")
(ss/config! lab-splice-destination :text " ")
(.sync-ui! ed)
(.status! ed "Initialized Scale Registry")))
(ss/listen jb-open :action (fn [_]
(open-dialog ed (.registry ed))))
(ss/listen jb-save :action (fn [_]
(save-dialog ed (.registry ed))))
(ss/listen jb-undo :action (fn [_](.undo! ed)))
(ss/listen jb-redo :action (fn [_](.redo! ed)))
(ss/listen jb-delete :action
(fn [_]
(let [id (.selected-table-id ed)]
(if id
(do
(.push-undo-state! ed (format "Delete %s" id))
(.remove-table! sregistry id)
(ss/config! lab-splice-source :text " ")
(ss/config! lab-splice-destination :text " ")
(.sync-ui! ed)
(.status! ed (format "Deleted scale %s" id)))
(warning! ed "No scale selected for deletion")))))
(let [addscale-subeditor (cadejo.ui.scale.addscale/addscale ed)
linear-subeditor (subeditors/linear-editor ed)
transpose-subeditor (subeditors/transpose-editor ed)
splice-subeditor (subeditors/splice-editor ed lab-splice-source
lab-splice-destination)
pan-edit (ss/grid-panel :rows 1
:items [linear-subeditor
transpose-subeditor
splice-subeditor])]
(ss/add! pan-subedit [addscale-subeditor :addscale])
(ss/add! pan-subedit [pan-edit :transpose])
(ss/add! pan-subedit [(ss/label :text "Nothing to see here") :detail]))
(ss/listen lst-registry :selection
(fn [_]
(if (and @enable-change-listeners*
(not (.getValueIsAdjusting lst-registry)))
(do
(ss/config! lab-splice-destination :text
(ss/config lab-splice-source :text))
(ss/config! lab-splice-source :text
(name (.getSelectedValue lst-registry)))))))
(ss/listen jtb-add :action
(fn [_]
(.enable-keyrange! ed false)
(.enable-wrap! ed false)
(ss/show-card! pan-subedit :addscale)))
(ss/listen jtb-edit :action
(fn [_]
(.enable-keyrange! ed true)
(.enable-wrap! ed true)
(ss/show-card! pan-subedit :transpose)))
(ss/listen jtb-detail :action
(fn [_]
(ss/show-card! pan-subedit :detail)
(.warning! ed "Detail editor not implemented")))
(.putClientProperty jb-help :topic :scale-registry)
ed))
|
eb5bf9ea48649ec89815716a7658e03f087c940c5c22da59f8280b82794a70c2 | nikita-volkov/ptr-poker | Ffi.hs | {-# LANGUAGE UnliftedFFITypes #-}
module PtrPoker.Ffi where
import Foreign.C
import PtrPoker.Prelude
foreign import ccall unsafe "static int_dec"
pokeIntInDec :: CInt -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static long_long_int_dec"
pokeLongLongIntInDec :: CLLong -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static uint_dec"
pokeUIntInDec :: CUInt -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static long_long_uint_dec"
pokeLongLongUIntInDec :: CULLong -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static uint_hex"
pokeUIntInHex :: CUInt -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static long_long_uint_hex"
pokeLongLongUIntInHex :: CULLong -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static rev_poke_int64"
revPokeInt64 :: CLLong -> Ptr Word8 -> IO ()
foreign import ccall unsafe "static rev_poke_uint64"
revPokeUInt64 :: CULLong -> Ptr Word8 -> IO ()
foreign import ccall unsafe "static dtoa_grisu3"
pokeDouble :: Double -> Ptr Word8 -> IO CInt
foreign import ccall unsafe "static count_text_allocation_size"
countTextAllocationSize :: ByteArray# -> CSize -> CSize -> IO CInt
foreign import ccall unsafe "static encode_text"
encodeText :: Ptr Word8 -> ByteArray# -> CSize -> CSize -> IO (Ptr Word8)
| null | https://raw.githubusercontent.com/nikita-volkov/ptr-poker/cc1f0ec6411833e82308e552ab69e10c0c9a3a52/library/PtrPoker/Ffi.hs | haskell | # LANGUAGE UnliftedFFITypes # |
module PtrPoker.Ffi where
import Foreign.C
import PtrPoker.Prelude
foreign import ccall unsafe "static int_dec"
pokeIntInDec :: CInt -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static long_long_int_dec"
pokeLongLongIntInDec :: CLLong -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static uint_dec"
pokeUIntInDec :: CUInt -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static long_long_uint_dec"
pokeLongLongUIntInDec :: CULLong -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static uint_hex"
pokeUIntInHex :: CUInt -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static long_long_uint_hex"
pokeLongLongUIntInHex :: CULLong -> Ptr Word8 -> IO (Ptr Word8)
foreign import ccall unsafe "static rev_poke_int64"
revPokeInt64 :: CLLong -> Ptr Word8 -> IO ()
foreign import ccall unsafe "static rev_poke_uint64"
revPokeUInt64 :: CULLong -> Ptr Word8 -> IO ()
foreign import ccall unsafe "static dtoa_grisu3"
pokeDouble :: Double -> Ptr Word8 -> IO CInt
foreign import ccall unsafe "static count_text_allocation_size"
countTextAllocationSize :: ByteArray# -> CSize -> CSize -> IO CInt
foreign import ccall unsafe "static encode_text"
encodeText :: Ptr Word8 -> ByteArray# -> CSize -> CSize -> IO (Ptr Word8)
|
64dde1727b0c20548897291715c7c7027fd4dd3d08e9255e0875a2109bb8761c | stevebleazard/ocaml-jsonxt | extended_stream.mli | * [ Extended_stream ] supports parsing and writing JSON data that
conforms to the { ! type : Json_stream . Extended.json } type as a stream
of { ! type : Json_stream . Extended.json } objects . This supports non - standard
JSON types including integer as well as tuples and variants introduced
by [ Yojson ]
conforms to the {!type:Json_stream.Extended.json} type as a stream
of {!type:Json_stream.Extended.json} objects. This supports non-standard
JSON types including integer as well as tuples and variants introduced
by [Yojson] *)
type json_stream = Json_stream.Extended.json
* { 1 Reader functions }
include (Reader_stream.Reader_stream with type json_stream := json_stream)
* { 1 Writer functions }
include (Writer_stream_intf.Intf with type json_stream := json_stream)
| null | https://raw.githubusercontent.com/stevebleazard/ocaml-jsonxt/fe982b6087dd76ca003d8fbc19ae9a519f54b828/lib/extended_stream.mli | ocaml | * [ Extended_stream ] supports parsing and writing JSON data that
conforms to the { ! type : Json_stream . Extended.json } type as a stream
of { ! type : Json_stream . Extended.json } objects . This supports non - standard
JSON types including integer as well as tuples and variants introduced
by [ Yojson ]
conforms to the {!type:Json_stream.Extended.json} type as a stream
of {!type:Json_stream.Extended.json} objects. This supports non-standard
JSON types including integer as well as tuples and variants introduced
by [Yojson] *)
type json_stream = Json_stream.Extended.json
* { 1 Reader functions }
include (Reader_stream.Reader_stream with type json_stream := json_stream)
* { 1 Writer functions }
include (Writer_stream_intf.Intf with type json_stream := json_stream)
|
|
96349e461d00b8237e2db73f04571ebf8e966f989e876e91721c920063784539 | franklindyer/cs357-ta-materials | recitation_week_5_solution.rkt | #lang racket
;; Map and high orders functions, a bit of apply at the end
;;;; Recursive definition of map
(define mymap
(lambda (f ls)
(if (null? ls)
'()
(cons
(f (car ls))
(mymap f (cdr ls))))))
;;;; (map f) . (map g) \equiv (map (compose f g))
;;;; Examples using map
(mymap
(lambda (x) (* x x))
'(1 2 3 4))
(mymap
(lambda (x) (+ x 1))
(mymap
(lambda (x) (* x x))
'(1 2 3 4)))
(mymap
(lambda (x) (+ (* x x) 1))
'(1 2 3 4))
;;;; More examples using map
(define student_database
'(
;; (name . (grade . is_cool?))
("James" . (0 . #t))
("Jack" . (1 . #f))
("Jackson" . (2 . #f))
("Jacob" . (3 . #f))
("John" . (4 . #t))
("Joseph" . (5 . #f))
("Julian" . (6 . #f))
("Jayden" . (7 . #t))
("Josiah" . (8 . #t))
("Jaxon" . (9 . #f))))
(define new_student
(lambda (name grade is_cool)
(cons name (cons grade is_cool))))
(define get_name
(lambda (student)
(car student)))
(define get_grade
(lambda (student)
(cadr student)))
(define get_coolness
(lambda (student)
(cddr student)))
(define boring_get_grades
(lambda (student_records)
(if (null? student_records)
'()
(cons
(get_grade (car student_records))
(boring_get_grades (cdr student_records))))))
(define get_grades
(lambda (student_records)
(mymap get_grade student_records)))
(define made_up_grades
(lambda (ls n)
(mymap
(lambda (student)
(let ((name (get_name student))
(is_cool (get_coolness student)))
(new_student name n is_cool)))
ls)))
(made_up_grades student_database 100)
(define compute_average_wow_much_abstraction
(lambda (student_records)
(let ((total
(apply +
(get_grades student_records)))
(size
(apply +
(get_grades (made_up_grades student_records 1)))))
(/ total size))))
(compute_average_wow_much_abstraction student_database)
;;;; Remember: (map f) . (map g) \equiv (map (compose f g))
(define compute_average
(lambda (student_records)
(let ((total (apply +
(mymap get_grade student_records)))
(size (apply +
(mymap (lambda (x) 1) student_records))))
(/ total size))))
(compute_average student_database)
;; Could I have used length instead? Yes, actually.
;; Recitation activity
1 . Create a function everyone_is_cool that
;; takes as input:
;; - a list of student records `student_records` as described above
;; and returns the same list of student records setting
up the record is_cool to # t using map or
(define everyone_is_cool
(lambda (student_records)
(mymap
(lambda (student)
(let ((name (get_name student))
(grade (get_grade student)))
(new_student name grade #t)))
student_records)))
(everyone_is_cool student_database)
2 . Create a function compute_final_average that
;; takes as input:
;; - a list of student records `student_records` as described above
;; and returns the average grade of students using the following criteria
if the student 's is_cool record is # t , add 2 points to its grade
otherwise subtract 1 point to its grade
(define compute_final_average
(lambda (student_records)
(compute_average
(mymap
(lambda (student)
(let
((name (get_name student))
(grade (get_grade student))
(cool (get_coolness student)))
(if cool
(new_student name (+ grade 2) cool)
(new_student name (- grade 1) cool))))
student_records))))
(compute_final_average student_database)
| null | https://raw.githubusercontent.com/franklindyer/cs357-ta-materials/67334cadc03e547c3490147091106362cc4b8194/scheme/recitations/week5/recitation_week_5_solution.rkt | racket | Map and high orders functions, a bit of apply at the end
Recursive definition of map
(map f) . (map g) \equiv (map (compose f g))
Examples using map
More examples using map
(name . (grade . is_cool?))
Remember: (map f) . (map g) \equiv (map (compose f g))
Could I have used length instead? Yes, actually.
Recitation activity
takes as input:
- a list of student records `student_records` as described above
and returns the same list of student records setting
takes as input:
- a list of student records `student_records` as described above
and returns the average grade of students using the following criteria | #lang racket
(define mymap
(lambda (f ls)
(if (null? ls)
'()
(cons
(f (car ls))
(mymap f (cdr ls))))))
(mymap
(lambda (x) (* x x))
'(1 2 3 4))
(mymap
(lambda (x) (+ x 1))
(mymap
(lambda (x) (* x x))
'(1 2 3 4)))
(mymap
(lambda (x) (+ (* x x) 1))
'(1 2 3 4))
(define student_database
'(
("James" . (0 . #t))
("Jack" . (1 . #f))
("Jackson" . (2 . #f))
("Jacob" . (3 . #f))
("John" . (4 . #t))
("Joseph" . (5 . #f))
("Julian" . (6 . #f))
("Jayden" . (7 . #t))
("Josiah" . (8 . #t))
("Jaxon" . (9 . #f))))
(define new_student
(lambda (name grade is_cool)
(cons name (cons grade is_cool))))
(define get_name
(lambda (student)
(car student)))
(define get_grade
(lambda (student)
(cadr student)))
(define get_coolness
(lambda (student)
(cddr student)))
(define boring_get_grades
(lambda (student_records)
(if (null? student_records)
'()
(cons
(get_grade (car student_records))
(boring_get_grades (cdr student_records))))))
(define get_grades
(lambda (student_records)
(mymap get_grade student_records)))
(define made_up_grades
(lambda (ls n)
(mymap
(lambda (student)
(let ((name (get_name student))
(is_cool (get_coolness student)))
(new_student name n is_cool)))
ls)))
(made_up_grades student_database 100)
(define compute_average_wow_much_abstraction
(lambda (student_records)
(let ((total
(apply +
(get_grades student_records)))
(size
(apply +
(get_grades (made_up_grades student_records 1)))))
(/ total size))))
(compute_average_wow_much_abstraction student_database)
(define compute_average
(lambda (student_records)
(let ((total (apply +
(mymap get_grade student_records)))
(size (apply +
(mymap (lambda (x) 1) student_records))))
(/ total size))))
(compute_average student_database)
1 . Create a function everyone_is_cool that
up the record is_cool to # t using map or
(define everyone_is_cool
(lambda (student_records)
(mymap
(lambda (student)
(let ((name (get_name student))
(grade (get_grade student)))
(new_student name grade #t)))
student_records)))
(everyone_is_cool student_database)
2 . Create a function compute_final_average that
if the student 's is_cool record is # t , add 2 points to its grade
otherwise subtract 1 point to its grade
(define compute_final_average
(lambda (student_records)
(compute_average
(mymap
(lambda (student)
(let
((name (get_name student))
(grade (get_grade student))
(cool (get_coolness student)))
(if cool
(new_student name (+ grade 2) cool)
(new_student name (- grade 1) cool))))
student_records))))
(compute_final_average student_database)
|
a40da5622d257a74f489bfdd417f8e94ad7e2f6d86d02eeaed856acc5f6b02be | mbutterick/fontland | head.rkt | #lang debug racket/base
(require xenomorph
racket/date)
(provide head)
#|
approximates
|#
` name ` table dates are seconds since 1/1/1904 ( Mac file convention )
whereas Racket / posix tracks since 1/1/1970
so we adjust with the difference in seconds
(define mac-to-posix-delta 2082844800)
(define hfs-seconds (x:int #:size 8
#:signed #f
#:endian 'be
#:post-decode (λ (int) (seconds->date (- int mac-to-posix-delta) #f))
#:pre-encode (λ (dt) (+ (date->seconds dt #f) mac-to-posix-delta))))
(define head (x:struct
0x00010000 ( version 1.0 )
'revision int32be ;; set by font manufacturer
'checkSumAdjustment uint32be
set to 0x5F0F3CF5
'flags uint16be
range from 64 to 16384
'created hfs-seconds
'modified hfs-seconds
'xMin int16be ;; for all glyph bounding boxes
'yMin int16be ;; for all glyph bounding boxes
'xMax int16be ;; for all glyph bounding boxes
'yMax int16be ;; for all glyph bounding boxes
'macStyle (x:bitfield #:type uint16be
#:flags '(bold italic underline outline shadow condensed extended))
'lowestRecPPEM uint16be ;; smallest readable size in pixels
'fontDirectionHint int16be
0 for short offsets 1 for long
'glyphDataFormat int16be ;; 0 for current format
))
(module+ test
(require rackunit "../helper.rkt"
racket/serialize)
(define ip (open-input-file charter-italic-path))
(define dir (deserialize (read (open-input-file charter-italic-directory-path))))
(define offset (hash-ref (hash-ref (hash-ref dir 'tables) 'head) 'offset))
(define length (hash-ref (hash-ref (hash-ref dir 'tables) 'head) 'length))
(check-equal? offset 236)
(check-equal? length 54)
(define table-bytes #"\0\1\0\0\0\2\0\0.\252t<_\17<\365\0\t\3\350\0\0\0\0\316\3\301\261\0\0\0\0\316\3\304\364\377\36\377\24\4\226\3\324\0\2\0\t\0\2\0\0\0\0")
(file-position ip 0)
(check-equal? (peek-bytes length offset ip) table-bytes)
(define table-data (decode head table-bytes))
(check-equal? (hash-ref table-data 'unitsPerEm) 1000)
(check-equal? (hash-ref table-data 'yMin) -236)
(check-equal? (hash-ref table-data 'yMax) 980)
(check-equal? (hash-ref table-data 'xMax) 1174)
(check-equal? (hash-ref table-data 'xMin) -226)
(check-equal? (hash-ref table-data 'macStyle) (make-hash '((shadow . #f)
(extended . #f)
(condensed . #f)
(underline . #f)
(outline . #f)
(bold . #f)
(italic . #t))))
(check-equal? (hash-ref table-data 'magicNumber) #x5F0F3CF5)
(check-equal? (hash-ref table-data 'indexToLocFormat) 0) ; used in loca table
(check-equal? (encode head table-data #f) table-bytes)) | null | https://raw.githubusercontent.com/mbutterick/fontland/e50e4c82f58e2014d64e87a14c1d29b546fb393b/fontland/table/head.rkt | racket |
approximates
set by font manufacturer
for all glyph bounding boxes
for all glyph bounding boxes
for all glyph bounding boxes
for all glyph bounding boxes
smallest readable size in pixels
0 for current format
used in loca table | #lang debug racket/base
(require xenomorph
racket/date)
(provide head)
` name ` table dates are seconds since 1/1/1904 ( Mac file convention )
whereas Racket / posix tracks since 1/1/1970
so we adjust with the difference in seconds
(define mac-to-posix-delta 2082844800)
(define hfs-seconds (x:int #:size 8
#:signed #f
#:endian 'be
#:post-decode (λ (int) (seconds->date (- int mac-to-posix-delta) #f))
#:pre-encode (λ (dt) (+ (date->seconds dt #f) mac-to-posix-delta))))
(define head (x:struct
0x00010000 ( version 1.0 )
'checkSumAdjustment uint32be
set to 0x5F0F3CF5
'flags uint16be
range from 64 to 16384
'created hfs-seconds
'modified hfs-seconds
'macStyle (x:bitfield #:type uint16be
#:flags '(bold italic underline outline shadow condensed extended))
'fontDirectionHint int16be
0 for short offsets 1 for long
))
(module+ test
(require rackunit "../helper.rkt"
racket/serialize)
(define ip (open-input-file charter-italic-path))
(define dir (deserialize (read (open-input-file charter-italic-directory-path))))
(define offset (hash-ref (hash-ref (hash-ref dir 'tables) 'head) 'offset))
(define length (hash-ref (hash-ref (hash-ref dir 'tables) 'head) 'length))
(check-equal? offset 236)
(check-equal? length 54)
(define table-bytes #"\0\1\0\0\0\2\0\0.\252t<_\17<\365\0\t\3\350\0\0\0\0\316\3\301\261\0\0\0\0\316\3\304\364\377\36\377\24\4\226\3\324\0\2\0\t\0\2\0\0\0\0")
(file-position ip 0)
(check-equal? (peek-bytes length offset ip) table-bytes)
(define table-data (decode head table-bytes))
(check-equal? (hash-ref table-data 'unitsPerEm) 1000)
(check-equal? (hash-ref table-data 'yMin) -236)
(check-equal? (hash-ref table-data 'yMax) 980)
(check-equal? (hash-ref table-data 'xMax) 1174)
(check-equal? (hash-ref table-data 'xMin) -226)
(check-equal? (hash-ref table-data 'macStyle) (make-hash '((shadow . #f)
(extended . #f)
(condensed . #f)
(underline . #f)
(outline . #f)
(bold . #f)
(italic . #t))))
(check-equal? (hash-ref table-data 'magicNumber) #x5F0F3CF5)
(check-equal? (encode head table-data #f) table-bytes)) |
9f0a56bc4211bafc6a1c3addfbf8067634b04086633d81652ec5b006d456206d | tnelson/Forge | fancyBoundsTests.rkt | #lang forge
sig A { r: set A }
sig B { s: set B }
one sig C {}
inst define_s {
s = B->(Bob+Bill) -- sees the B already defined
}
inst myInst {
r is cotree
B = Bob+Bill+Ben
define_s -- call define_s
}
inst rlin {
r is linear
}
test expect foo {
t0: { some r } for exactly myInst, rlin, #A = 4 is sat
t1: { some r } for exactly myInst, rlin, #A = 4, s is linear is unsat
t2: { some B } for #B = 0 is unsat -- not exact
t3: {} for exactly {
r is tree and r is cotree
#A=4 and one B and no s and lone C
} is sat
}
--- WORKING ---
run { some r } for myInst, 3 <= #A <= 4 -- s linearity contraint gone
--run { some B and some C } -- #B = 0 constraint gone, C still one
--- ERRORS ---
--run {} for exactly #B = 3, #B = 4 -- conflicting int-bounds: no [3, 3] & [4, 4]
--run {} for exactly B=B0+B1+B2, #B = 4 -- conflicting int-bounds: no [3, 3] & [4, 4]
--run { some r } for exactly myInst, 3 <= #A <= 4 -- bounds declared exactly but r not exact | null | https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/examples/fancyBoundsTests.rkt | racket | #lang forge
sig A { r: set A }
sig B { s: set B }
one sig C {}
inst define_s {
s = B->(Bob+Bill) -- sees the B already defined
}
inst myInst {
r is cotree
B = Bob+Bill+Ben
define_s -- call define_s
}
inst rlin {
r is linear
}
test expect foo {
t0: { some r } for exactly myInst, rlin, #A = 4 is sat
t1: { some r } for exactly myInst, rlin, #A = 4, s is linear is unsat
t2: { some B } for #B = 0 is unsat -- not exact
t3: {} for exactly {
r is tree and r is cotree
#A=4 and one B and no s and lone C
} is sat
}
--- WORKING ---
run { some r } for myInst, 3 <= #A <= 4 -- s linearity contraint gone
--run { some B and some C } -- #B = 0 constraint gone, C still one
--- ERRORS ---
--run {} for exactly #B = 3, #B = 4 -- conflicting int-bounds: no [3, 3] & [4, 4]
--run {} for exactly B=B0+B1+B2, #B = 4 -- conflicting int-bounds: no [3, 3] & [4, 4]
--run { some r } for exactly myInst, 3 <= #A <= 4 -- bounds declared exactly but r not exact |
|
b7206b49626a033914987d16f7156c666711984f1201d054d953c36e72de23c3 | marick/lein-midje | core_test.clj | (ns {{name}}.core-test
(:require [midje.sweet :refer :all]
[{{name}}.core :refer :all]))
(println "You should expect to see three failures below.")
(facts "about `first-element`"
(fact "it normally returns the first element"
(first-element [1 2 3] :default) => 1
(first-element '(1 2 3) :default) => 1)
I 'm a little unsure how Clojure types map onto the Lisp I 'm used to .
(fact "default value is returned for empty sequences"
(first-element [] :default) => :default
(first-element '() :default) => :default
(first-element nil :default) => :default
(first-element (filter even? [1 3 5]) :default) => :default))
| null | https://raw.githubusercontent.com/marick/lein-midje/71a98ad1da2b94ed7050cc6b99be798ef3b3837e/src/leiningen/new/midje/core_test.clj | clojure | (ns {{name}}.core-test
(:require [midje.sweet :refer :all]
[{{name}}.core :refer :all]))
(println "You should expect to see three failures below.")
(facts "about `first-element`"
(fact "it normally returns the first element"
(first-element [1 2 3] :default) => 1
(first-element '(1 2 3) :default) => 1)
I 'm a little unsure how Clojure types map onto the Lisp I 'm used to .
(fact "default value is returned for empty sequences"
(first-element [] :default) => :default
(first-element '() :default) => :default
(first-element nil :default) => :default
(first-element (filter even? [1 3 5]) :default) => :default))
|
|
7b06e258e8eb0bc0ca6195a55a6f7e23e2453249556557bc9f4f710dd03f137a | jdsandifer/AutoLISP | TRYOUT.lsp | ;;;;;;;[ Test ];;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; Simple file for testing stuff. ;;
;; ;;
;;::::::::::::::::::::::::::::::::::::::::::::::;;
;; ;;
Author : ( Copyright 2016 ) ; ;
Written : 02/04/2016 ; ;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; 06/27/2016 ;;
;; - Moved stuff from TEST to here. ;;
;; - Some success with block creation, but ;;
;; still a lot I don't understand about ;;
;; what is required in the definitions and ;;
;; what can be omitted. Would like to omit ;;
;; as much as possible... ;;
;; ;;
02/04/2016 ; ;
;; - Testing variable scope - local variables ;;
;; as hash tables for my hash functions. ;;
;; Works great! ;;
;; - Local variables w/out passing. Works! ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun test ( / *error*)
(setq *error* ErrorHandler)
;(entmake ') - for copying...
(entmake '((0 . "BLOCK") (8 . "0") (70 . 0) (10 0.0 0.0 0.0) (2 . "TEST1")))
(entmake '((0 . "CIRCLE") (8 . "0") (10 1.875 -1.875 0.0) (40 . 0.549375)))
(entmake '((0 . "CIRCLE") (8 . "0") (10 1.875 -1.875 0.0) (40 . 0.31875)))
(entmake '((0 . "LWPOLYLINE") (8 . "0") (90 . 8) (70 . 1) (10 -2.5 -2.125) (42 . 0) (91 . 0) (10 -2.5 2.125) (42 . -0.414214) (91 . 0) (10 -2.125 2.5) (42 . 0) (91 . 0) (10 2.125 2.5) (42 . -0.414214) (91 . 0) (10 2.5 2.125) (42 . 0) (91 . 0) (10 2.5 -2.125) (42 . -0.414214) (91 . 0) (10 2.125 -2.5) (42 . 0) (91 . 0) (10 -2.125 -2.5) (42 . -0.414214) (91 . 0)))
(entmake '((0 . "CIRCLE") (8 . "0") (10 1.875 1.875 0.0) (40 . 0.549375)))
(entmake '((0 . "CIRCLE") (8 . "0") (10 1.875 1.875 0.0) (40 . 0.31875)))
(entmake '((0 . "CIRCLE") (8 . "0") (10 -1.875 1.875 0.0) (40 . 0.549375)))
(entmake '((0 . "ENDBLK")))
)
; Silent load
(princ) | null | https://raw.githubusercontent.com/jdsandifer/AutoLISP/054c8400fae84c223c3113e049a1ab87d374ba37/TRYOUT.lsp | lisp | [ Test ];;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
Simple file for testing stuff. ;;
;;
::::::::::::::::::::::::::::::::::::::::::::::;;
;;
;
;
;;
;;
06/27/2016 ;;
- Moved stuff from TEST to here. ;;
- Some success with block creation, but ;;
still a lot I don't understand about ;;
what is required in the definitions and ;;
what can be omitted. Would like to omit ;;
as much as possible... ;;
;;
;
- Testing variable scope - local variables ;;
as hash tables for my hash functions. ;;
Works great! ;;
- Local variables w/out passing. Works! ;;
;;
(entmake ') - for copying...
Silent load |
(defun test ( / *error*)
(setq *error* ErrorHandler)
(entmake '((0 . "BLOCK") (8 . "0") (70 . 0) (10 0.0 0.0 0.0) (2 . "TEST1")))
(entmake '((0 . "CIRCLE") (8 . "0") (10 1.875 -1.875 0.0) (40 . 0.549375)))
(entmake '((0 . "CIRCLE") (8 . "0") (10 1.875 -1.875 0.0) (40 . 0.31875)))
(entmake '((0 . "LWPOLYLINE") (8 . "0") (90 . 8) (70 . 1) (10 -2.5 -2.125) (42 . 0) (91 . 0) (10 -2.5 2.125) (42 . -0.414214) (91 . 0) (10 -2.125 2.5) (42 . 0) (91 . 0) (10 2.125 2.5) (42 . -0.414214) (91 . 0) (10 2.5 2.125) (42 . 0) (91 . 0) (10 2.5 -2.125) (42 . -0.414214) (91 . 0) (10 2.125 -2.5) (42 . 0) (91 . 0) (10 -2.125 -2.5) (42 . -0.414214) (91 . 0)))
(entmake '((0 . "CIRCLE") (8 . "0") (10 1.875 1.875 0.0) (40 . 0.549375)))
(entmake '((0 . "CIRCLE") (8 . "0") (10 1.875 1.875 0.0) (40 . 0.31875)))
(entmake '((0 . "CIRCLE") (8 . "0") (10 -1.875 1.875 0.0) (40 . 0.549375)))
(entmake '((0 . "ENDBLK")))
)
(princ) |
839bf944d537025e39487739d060c0710a8e0cad79a257f50e8378892ade3942 | EarnestResearch/yambda | SNS.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingVia #-}
# LANGUAGE DuplicateRecordFields #
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module AWS.Lambda.Event.SNS where
import AWS.Lambda.Encoding
import AWS.Lambda.Event.JSON
import Control.Lens
import Data.Aeson
import Data.HashMap.Strict
import Data.Text (Text)
import GHC.Generics
newtype SNSEvent = SNSEvent { _records :: [Record] }
deriving (Eq, Generic, Show)
deriving LambdaDecode via (LambdaFromJSON SNSEvent)
deriving LambdaEncode via (LambdaToJSON SNSEvent)
instance HasEventJSONOptions SNSEvent where
getEventJsonOptions = defaultOptions
{ fieldLabelModifier = capitalize . drop 1 }
deriving via EventJSON SNSEvent instance ToJSON SNSEvent
deriving via EventJSON SNSEvent instance FromJSON SNSEvent
data Record = Record
{ _eventVersion :: Text
, _eventSource :: Text
, _eventSubscriptionArn :: Text
, _sns :: SNS
} deriving (Eq, Generic, Show)
instance HasEventJSONOptions Record where
getEventJsonOptions = defaultOptions
{ fieldLabelModifier = capitalize . drop 1 }
deriving via EventJSON Record instance ToJSON Record
deriving via EventJSON Record instance FromJSON Record
data SNS = SNS
{ _signatureVersion :: Text
, _timestamp :: Text
, _signature :: Text
, _signingCertUrl :: Text
, _messageId :: Text
, _message :: Text
, _messageAttributes :: Maybe (HashMap Text MessageAttribute)
, _snsType :: Text
, _unsubscribeUrl :: Text
, _topicArn :: Text
, _subject :: Maybe Text
} deriving (Eq, Generic, Show)
instance HasEventJSONOptions SNS where
getEventJsonOptions = defaultOptions
{ fieldLabelModifier =
\case "_snsType" -> "Type"
v -> capitalize . drop 1 $ v
}
deriving via EventJSON SNS instance ToJSON SNS
deriving via EventJSON SNS instance FromJSON SNS
data MessageAttribute = MessageAttribute
{ _attributeType :: Text
, _value :: Text
} deriving (Eq, Generic, Show)
instance HasEventJSONOptions MessageAttribute where
getEventJsonOptions = defaultOptions
{ fieldLabelModifier =
\case "_attributeType" -> "Type"
v -> capitalize . drop 1 $ v
}
deriving via EventJSON MessageAttribute instance ToJSON MessageAttribute
deriving via EventJSON MessageAttribute instance FromJSON MessageAttribute
makeLenses ''SNSEvent
makeLenses ''Record
makeLenses ''SNS
makeLenses ''MessageAttribute
| null | https://raw.githubusercontent.com/EarnestResearch/yambda/b1f45e42447c08d7da4b3f470bdb849c9ea1b200/core/src/AWS/Lambda/Event/SNS.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE LambdaCase #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell # | # LANGUAGE DuplicateRecordFields #
module AWS.Lambda.Event.SNS where
import AWS.Lambda.Encoding
import AWS.Lambda.Event.JSON
import Control.Lens
import Data.Aeson
import Data.HashMap.Strict
import Data.Text (Text)
import GHC.Generics
newtype SNSEvent = SNSEvent { _records :: [Record] }
deriving (Eq, Generic, Show)
deriving LambdaDecode via (LambdaFromJSON SNSEvent)
deriving LambdaEncode via (LambdaToJSON SNSEvent)
instance HasEventJSONOptions SNSEvent where
getEventJsonOptions = defaultOptions
{ fieldLabelModifier = capitalize . drop 1 }
deriving via EventJSON SNSEvent instance ToJSON SNSEvent
deriving via EventJSON SNSEvent instance FromJSON SNSEvent
data Record = Record
{ _eventVersion :: Text
, _eventSource :: Text
, _eventSubscriptionArn :: Text
, _sns :: SNS
} deriving (Eq, Generic, Show)
instance HasEventJSONOptions Record where
getEventJsonOptions = defaultOptions
{ fieldLabelModifier = capitalize . drop 1 }
deriving via EventJSON Record instance ToJSON Record
deriving via EventJSON Record instance FromJSON Record
data SNS = SNS
{ _signatureVersion :: Text
, _timestamp :: Text
, _signature :: Text
, _signingCertUrl :: Text
, _messageId :: Text
, _message :: Text
, _messageAttributes :: Maybe (HashMap Text MessageAttribute)
, _snsType :: Text
, _unsubscribeUrl :: Text
, _topicArn :: Text
, _subject :: Maybe Text
} deriving (Eq, Generic, Show)
instance HasEventJSONOptions SNS where
getEventJsonOptions = defaultOptions
{ fieldLabelModifier =
\case "_snsType" -> "Type"
v -> capitalize . drop 1 $ v
}
deriving via EventJSON SNS instance ToJSON SNS
deriving via EventJSON SNS instance FromJSON SNS
data MessageAttribute = MessageAttribute
{ _attributeType :: Text
, _value :: Text
} deriving (Eq, Generic, Show)
instance HasEventJSONOptions MessageAttribute where
getEventJsonOptions = defaultOptions
{ fieldLabelModifier =
\case "_attributeType" -> "Type"
v -> capitalize . drop 1 $ v
}
deriving via EventJSON MessageAttribute instance ToJSON MessageAttribute
deriving via EventJSON MessageAttribute instance FromJSON MessageAttribute
makeLenses ''SNSEvent
makeLenses ''Record
makeLenses ''SNS
makeLenses ''MessageAttribute
|
ebacc1700615d64cd0409a33e4b915e62f0fa316074742370c949b9c53daa6e7 | istathar/vaultaire | CommandRunners.hs | --
-- Data vault for metrics
--
Copyright © 2013 - 2014 Anchor Systems , Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
the 3 - clause BSD licence .
--
{-# LANGUAGE RankNTypes #-}
module CommandRunners
(
runDumpDayMap,
runRegisterOrigin
) where
import Control.Exception (throw)
import Control.Monad
import qualified Data.ByteString.Char8 as S
import Data.Map (fromAscList)
import Data.Word (Word64)
import Marquise.Client
import Pipes
import System.Log.Logger
import System.Rados.Monadic (RadosError (..), runObject, stat, writeFull)
import Vaultaire.Daemon (dayMapsFromCeph, extendedDayOID, simpleDayOID,
withPool)
import Vaultaire.Types
runDumpDayMap :: String -> String -> Origin -> IO ()
runDumpDayMap pool user origin = do
let user' = Just (S.pack user)
let pool' = S.pack pool
maps <- withPool user' pool' (dayMapsFromCeph origin)
case maps of
Left e -> error e
Right ((_, simple), (_, extended)) -> do
putStrLn "Simple day map:"
print simple
putStrLn "Extended day map:"
print extended
runRegisterOrigin :: String -> String -> Origin -> Word64 -> Word64 -> TimeStamp -> TimeStamp -> IO ()
runRegisterOrigin pool user origin buckets step (TimeStamp begin) (TimeStamp end) = do
let targets = [simpleDayOID origin, extendedDayOID origin]
let user' = Just (S.pack user)
let pool' = S.pack pool
withPool user' pool' (forM_ targets initializeDayMap)
where
initializeDayMap target =
runObject target $ do
result <- stat
case result of
Left NoEntity{} -> return ()
Left e -> throw e
Right _ -> liftIO $ infoM "Commands.runRegisterOrigin" ("Target already in place (" ++ S.unpack target ++ ")")
writeFull (toWire dayMap) >>= maybe (return ()) throw
dayMap = DayMap . fromAscList $
((0, buckets):)[(n, buckets) | n <- [begin,begin+step..end]]
| null | https://raw.githubusercontent.com/istathar/vaultaire/75603ea614b125568ca871e88280bd29b3aef4ba/src/CommandRunners.hs | haskell |
Data vault for metrics
The code in this file, and the program it is a part of, is
made available to you by its authors as open source software:
you can redistribute it and/or modify it under the terms of
# LANGUAGE RankNTypes # | Copyright © 2013 - 2014 Anchor Systems , Pty Ltd and Others
the 3 - clause BSD licence .
module CommandRunners
(
runDumpDayMap,
runRegisterOrigin
) where
import Control.Exception (throw)
import Control.Monad
import qualified Data.ByteString.Char8 as S
import Data.Map (fromAscList)
import Data.Word (Word64)
import Marquise.Client
import Pipes
import System.Log.Logger
import System.Rados.Monadic (RadosError (..), runObject, stat, writeFull)
import Vaultaire.Daemon (dayMapsFromCeph, extendedDayOID, simpleDayOID,
withPool)
import Vaultaire.Types
runDumpDayMap :: String -> String -> Origin -> IO ()
runDumpDayMap pool user origin = do
let user' = Just (S.pack user)
let pool' = S.pack pool
maps <- withPool user' pool' (dayMapsFromCeph origin)
case maps of
Left e -> error e
Right ((_, simple), (_, extended)) -> do
putStrLn "Simple day map:"
print simple
putStrLn "Extended day map:"
print extended
runRegisterOrigin :: String -> String -> Origin -> Word64 -> Word64 -> TimeStamp -> TimeStamp -> IO ()
runRegisterOrigin pool user origin buckets step (TimeStamp begin) (TimeStamp end) = do
let targets = [simpleDayOID origin, extendedDayOID origin]
let user' = Just (S.pack user)
let pool' = S.pack pool
withPool user' pool' (forM_ targets initializeDayMap)
where
initializeDayMap target =
runObject target $ do
result <- stat
case result of
Left NoEntity{} -> return ()
Left e -> throw e
Right _ -> liftIO $ infoM "Commands.runRegisterOrigin" ("Target already in place (" ++ S.unpack target ++ ")")
writeFull (toWire dayMap) >>= maybe (return ()) throw
dayMap = DayMap . fromAscList $
((0, buckets):)[(n, buckets) | n <- [begin,begin+step..end]]
|
5e7ab7ad8fc31519b29679b0f543618aa3850bc0e058110813ab62d2f7063885 | nominolo/lambdachine | SumMemLoad.hs | # LANGUAGE NoImplicitPrelude , MagicHash #
-- RUN: %bc_vm_chk
CHECK : @Result@ IND - > GHC.Bool . True`con_info
module Bc.SumMemLoad where
import GHC.Prim
import GHC.Types
data X = X Int# Int# X
xs = X 1# 2# (X 3# 4# xs)
loop :: Int# -> Int# -> X -> Int#
loop acc s (X inc1 dec1 x') =
if isTrue# (s <=# 0#) then acc else
loop (acc +# inc1) (s -# dec1) x'
test = isTrue# ((loop 0# 1000# xs) ==# 668#)
| null | https://raw.githubusercontent.com/nominolo/lambdachine/49d97cf7a367a650ab421f7aa19feb90bfe14731/tests/Bc/SumMemLoad.hs | haskell | RUN: %bc_vm_chk | # LANGUAGE NoImplicitPrelude , MagicHash #
CHECK : @Result@ IND - > GHC.Bool . True`con_info
module Bc.SumMemLoad where
import GHC.Prim
import GHC.Types
data X = X Int# Int# X
xs = X 1# 2# (X 3# 4# xs)
loop :: Int# -> Int# -> X -> Int#
loop acc s (X inc1 dec1 x') =
if isTrue# (s <=# 0#) then acc else
loop (acc +# inc1) (s -# dec1) x'
test = isTrue# ((loop 0# 1000# xs) ==# 668#)
|
0e606644b46c4b5155b5b992108788243b5ffb00615c454aeeec2078956b438f | dinosaure/carton | thin.ml | open Carton
type ('uid, 's) light_load = 'uid -> ((kind * int), 's) io
type ('uid, 's) heavy_load = 'uid -> (Dec.v, 's) io
type optint = Optint.t
let blit_from_string src src_off dst dst_off len =
Bigstringaf.blit_from_string src ~src_off dst ~dst_off ~len
[@@inline]
let src = Logs.Src.create "thin"
module Log = (val Logs.src_log src : Logs.LOG)
exception Exists
module Make (Scheduler : SCHEDULER) (IO : IO with type 'a t = 'a Scheduler.s) (Uid : UID) = struct
let ( >>= ) x f = IO.bind x f
let return x = IO.return x
let ( >>? ) x f = x >>= function
| Ok x -> f x
| Error _ as err -> return err
let sched =
let open Scheduler in
{ Carton.bind= (fun x f -> inj (prj x >>= fun x -> prj (f x)))
; Carton.return= (fun x -> inj (return x)) }
let read stream =
let ke = Ke.Rke.create ~capacity:0x1000 Bigarray.char in
let rec go filled inputs =
match Ke.Rke.N.peek ke with
| [] ->
( stream () >>= function
| Some (src, off, len) ->
Ke.Rke.N.push ke
~blit:blit_from_string
~length:String.length
~off ~len src ;
go filled inputs
| None -> return filled )
| src :: _ ->
let src = Cstruct.of_bigarray src in
let len = min (Cstruct.len inputs) (Cstruct.len src) in
Cstruct.blit src 0 inputs 0 len ;
Ke.Rke.N.shift_exn ke len ;
if len < Cstruct.len inputs
then go (filled + len) (Cstruct.shift inputs len)
else return (filled + len) in
go
module Verify = Carton.Dec.Verify(Uid)(Scheduler)(IO)
module Fp = Carton.Dec.Fp(Uid)
let first_pass ~zl_buffer ~digest stream =
let fl_buffer = Cstruct.create De.io_buffer_size in
let zl_window = De.make_window ~bits:15 in
let allocate _ = zl_window in
let read_cstruct = read stream in
let read_bytes () buf ~off ~len =
let rec go rest raw =
if rest <= 0
then ( Cstruct.blit_to_bytes fl_buffer 0 buf off len
; return (abs rest + len) )
else read_cstruct 0 raw >>= fun filled ->
go (rest - filled) (Cstruct.shift raw filled) in
go len fl_buffer in
let read_bytes () buf ~off ~len = Scheduler.inj (read_bytes () buf ~off ~len) in
Fp.check_header sched read_bytes () |> Scheduler.prj >>= fun (max, _, len) ->
let decoder = Fp.decoder ~o:zl_buffer ~allocate `Manual in
let decoder = Fp.src decoder (Cstruct.to_bigarray fl_buffer) 0 len in
let children = Hashtbl.create 0x100 in
let where = Hashtbl.create 0x100 in
let weight = Hashtbl.create 0x100 in
let checks = Hashtbl.create 0x100 in
let matrix = Array.make max Verify.unresolved_node in
let replace hashtbl k v =
try let v' = Hashtbl.find hashtbl k in if v < v' then Hashtbl.replace hashtbl k v'
with Not_found -> Hashtbl.add hashtbl k v in
let rec go decoder = match Fp.decode decoder with
| `Await decoder ->
read_cstruct 0 fl_buffer >>= fun len ->
Log.debug (fun m -> m "Refill the first-pass state with %d byte(s)." len) ;
go (Fp.src decoder (Cstruct.to_bigarray fl_buffer) 0 len)
| `Peek decoder ->
XXX(dinosaure ): [ ] does the compression .
let keep = Fp.src_rem decoder in
read_cstruct 0 (Cstruct.shift fl_buffer keep) >>= fun len ->
go (Fp.src decoder (Cstruct.to_bigarray fl_buffer) 0 (keep + len))
| `Entry ({ Fp.kind= Base _
; offset; size; crc; _ }, decoder) ->
let n = Fp.count decoder - 1 in
Log.debug (fun m -> m "[+] base object (%d) (%Ld)." n offset) ;
replace weight offset size ;
Hashtbl.add where offset n ;
Hashtbl.add checks offset crc ;
matrix.(n) <- Verify.unresolved_base ~cursor:offset ;
go decoder
| `Entry ({ Fp.kind= Ofs { sub= s; source; target; }
; offset; crc; _ }, decoder) ->
let n = Fp.count decoder - 1 in
Log.debug (fun m -> m "[+] ofs object (%d) (%Ld)." n offset) ;
replace weight Int64.(sub offset (Int64.of_int s)) source ;
replace weight offset target ;
Hashtbl.add where offset n ;
Hashtbl.add checks offset crc ;
( try let vs = Hashtbl.find children (`Ofs Int64.(sub offset (of_int s))) in
Hashtbl.replace children (`Ofs Int64.(sub offset (of_int s))) (offset :: vs)
with Not_found ->
Hashtbl.add children (`Ofs Int64.(sub offset (of_int s))) [ offset ] ) ;
go decoder
| `Entry ({ Fp.kind= Ref { ptr; target; source; }
; offset; crc; _ }, decoder) ->
let n = Fp.count decoder - 1 in
Log.debug (fun m -> m "[+] ref object (%d) (%Ld) (weight: %d)." n offset (Stdlib.max target source :> int)) ;
replace weight offset (Stdlib.max target source) ;
Hashtbl.add where offset n ;
Hashtbl.add checks offset crc ;
( try let vs = Hashtbl.find children (`Ref ptr) in
Hashtbl.replace children (`Ref ptr) (offset :: vs)
with Not_found ->
Hashtbl.add children (`Ref ptr) [ offset ] ) ;
go decoder
| `End uid -> return (Ok uid)
| `Malformed err ->
Log.err (fun m -> m "Got an error: %s." err) ;
return (Error (`Msg err)) in
go decoder >>? fun uid ->
Log.debug (fun m -> m "First pass on incoming PACK file is done.") ;
return (Ok ({ Carton.Dec.where= (fun ~cursor -> Hashtbl.find where cursor)
; children= (fun ~cursor ~uid ->
match Hashtbl.find_opt children (`Ofs cursor),
Hashtbl.find_opt children (`Ref uid) with
| Some a, Some b -> List.sort_uniq compare (a @ b)
| Some x, None | None, Some x -> x
| None, None -> [])
; digest= digest
; weight= (fun ~cursor -> Hashtbl.find weight cursor) },
matrix, where, checks, children, uid))
type ('t, 'path, 'fd, 'error) fs =
{ create : 't -> 'path -> ('fd, 'error) result IO.t
; append : 't -> 'fd -> string -> unit IO.t
; map : 't -> 'fd -> pos:int64 -> int -> Bigstringaf.t IO.t
; close : 't -> 'fd -> (unit, 'error) result IO.t }
module Set = Set.Make(Uid)
let zip a b =
if Array.length a <> Array.length b then invalid_arg "zip: lengths mismatch" ;
Array.init (Array.length a) (fun i -> a.(i), b.(i))
let share l0 l1 =
try List.iter (fun (v, _) -> if List.exists (Int64.equal v) l1 then raise Exists) l0 ; false
with Exists -> true
let verify ?(threads= 4) ~digest t path { create; append; map; close; } stream =
let zl_buffer = De.bigstring_create De.io_buffer_size in
let allocate bits = De.make_window ~bits in
let weight = ref 0L in
create t path >>? fun fd ->
let stream () =
stream () >>= function
| Some (buf, off, len) as res ->
append t fd (String.sub buf off len) >>= fun () ->
weight := Int64.add !weight (Int64.of_int len) ;
return res
| none -> return none in
Log.debug (fun m -> m "Start to analyse the PACK file.") ;
first_pass ~zl_buffer ~digest stream >>? fun (oracle, matrix, where, checks, children, uid) ->
let weight = !weight in
let pack = Carton.Dec.make fd ~allocate ~z:zl_buffer ~uid_ln:Uid.length ~uid_rw:Uid.of_raw_string
(fun _ -> assert false) in
let map fd ~pos len =
let len = min len Int64.(to_int (sub weight pos)) in
Scheduler.inj (map t fd ~pos len) in
Log.debug (fun m -> m "Start to verify incoming PACK file (second pass).") ;
Verify.verify ~threads pack ~map ~oracle ~matrix >>= fun () ->
Log.debug (fun m -> m "Second pass on incoming PACK file is done.") ;
let offsets = Hashtbl.fold (fun k _ a -> k :: a) where []
|> List.sort Int64.compare
|> Array.of_list in
let unresolveds, resolveds =
let fold (unresolveds, resolveds) (offset, status) =
if Verify.is_resolved status
then
let uid = Verify.uid_of_status status in
let crc = Hashtbl.find checks offset in
unresolveds, ({ Carton.Dec.Idx.crc; offset; uid } :: resolveds)
else
let crc = Hashtbl.find checks offset in
((offset, crc) :: unresolveds), resolveds in
Array.fold_left fold ([], []) (zip offsets matrix) in
let requireds =
Hashtbl.fold (fun k vs a -> match k with
| `Ofs _ -> a
| `Ref uid ->
if share unresolveds vs
then Set.add uid a else a)
children Set.empty in
close t fd >>? fun () ->
Log.debug (fun m -> m "PACK file verified (%d resolved object(s), %d unresolved object(s))"
(List.length resolveds) (List.length unresolveds)) ;
return (Ok (Hashtbl.length where, Set.elements requireds, unresolveds, resolveds, weight, uid))
let find _ = assert false
let vuid = { Carton.Enc.uid_ln= Uid.length
; Carton.Enc.uid_rw= Uid.to_raw_string }
type nonrec light_load = (Uid.t, Scheduler.t) light_load
type nonrec heavy_load = (Uid.t, Scheduler.t) heavy_load
let canonicalize ~light_load ~heavy_load ~src ~dst t { create; append; close; map; _ } n uids weight =
let b =
{ Carton.Enc.o= Bigstringaf.create De.io_buffer_size
; Carton.Enc.i= Bigstringaf.create De.io_buffer_size
; Carton.Enc.q= De.Queue.create 0x10000
; Carton.Enc.w= De.make_window ~bits:15 } in
let ctx = ref Uid.empty in
let cursor = ref 0L in
let light_load uid = Scheduler.prj (light_load uid) in
create t dst >>? fun fd ->
let header = Bigstringaf.create 12 in
Carton.Enc.header_of_pack ~length:(n + List.length uids) header 0 12 ;
let hdr = Bigstringaf.to_string header in
append t fd hdr >>= fun () ->
ctx := Uid.feed !ctx header ;
cursor := Int64.add !cursor 12L ;
let encode_base uid =
light_load uid >>= fun (kind, length) ->
let entry = Carton.Enc.make_entry ~kind ~length uid in
let anchor = !cursor in
let crc = ref Checkseum.Crc32.default in
Carton.Enc.entry_to_target sched ~load:heavy_load entry |> Scheduler.prj >>= fun target ->
Carton.Enc.encode_target sched ~b ~find ~load:heavy_load ~uid:vuid target ~cursor:(Int64.to_int anchor)
|> Scheduler.prj >>= fun (len, encoder) ->
let rec go encoder = match Carton.Enc.N.encode ~o:b.o encoder with
| `Flush (encoder, len) ->
append t fd (Bigstringaf.substring b.o ~off:0 ~len) >>= fun () ->
ctx := Uid.feed !ctx ~off:0 ~len b.o ;
crc := Checkseum.Crc32.digest_bigstring b.o 0 len !crc ;
cursor := Int64.add !cursor (Int64.of_int len) ;
let encoder =
Carton.Enc.N.dst encoder b.o 0 (Bigstringaf.length b.o) in
go encoder
| `End -> return { Carton.Dec.Idx.crc= !crc; offset= anchor; uid; } in
append t fd (Bigstringaf.substring b.o ~off:0 ~len) >>= fun () ->
ctx := Uid.feed !ctx ~off:0 ~len b.o ;
crc := Checkseum.Crc32.digest_bigstring b.o 0 len !crc ;
cursor := Int64.add !cursor (Int64.of_int len) ;
let encoder = Carton.Enc.N.dst encoder b.o 0 (Bigstringaf.length b.o) in
go encoder in
let rec go acc = function
| [] -> return (List.rev acc)
| uid :: uids ->
encode_base uid >>= fun entry -> go (entry :: acc) uids in
go [] uids >>= fun entries ->
let shift = Int64.sub !cursor 12L in
let top = Int64.sub weight (Int64.of_int Uid.length) in
let rec go src pos =
let max = (Int64.sub top pos) in
let len = min max (Int64.mul 1024L 1024L) in
let len = Int64.to_int len in
map t src ~pos len >>= fun raw ->
append t fd (Bigstringaf.to_string raw) >>= fun () ->
ctx := Uid.feed !ctx raw ;
cursor := Int64.add !cursor (Int64.of_int len) ;
if Int64.add pos (Int64.of_int len) < top
then go src (Int64.add pos (Int64.of_int len))
else
( let uid = Uid.get !ctx in
append t fd (Uid.to_raw_string uid) >>= fun () ->
return (Ok (Int64.(add !cursor (of_int Uid.length)), uid)) ) in
create t src >>? fun src -> go src 12L >>? fun (weight, uid) ->
close t fd >>? fun () -> return (Ok (shift, weight, uid, entries))
end
| null | https://raw.githubusercontent.com/dinosaure/carton/8cb8b3685fab477594b2d83c70b2fc965d1d59b9/lib/thin.ml | ocaml | open Carton
type ('uid, 's) light_load = 'uid -> ((kind * int), 's) io
type ('uid, 's) heavy_load = 'uid -> (Dec.v, 's) io
type optint = Optint.t
let blit_from_string src src_off dst dst_off len =
Bigstringaf.blit_from_string src ~src_off dst ~dst_off ~len
[@@inline]
let src = Logs.Src.create "thin"
module Log = (val Logs.src_log src : Logs.LOG)
exception Exists
module Make (Scheduler : SCHEDULER) (IO : IO with type 'a t = 'a Scheduler.s) (Uid : UID) = struct
let ( >>= ) x f = IO.bind x f
let return x = IO.return x
let ( >>? ) x f = x >>= function
| Ok x -> f x
| Error _ as err -> return err
let sched =
let open Scheduler in
{ Carton.bind= (fun x f -> inj (prj x >>= fun x -> prj (f x)))
; Carton.return= (fun x -> inj (return x)) }
let read stream =
let ke = Ke.Rke.create ~capacity:0x1000 Bigarray.char in
let rec go filled inputs =
match Ke.Rke.N.peek ke with
| [] ->
( stream () >>= function
| Some (src, off, len) ->
Ke.Rke.N.push ke
~blit:blit_from_string
~length:String.length
~off ~len src ;
go filled inputs
| None -> return filled )
| src :: _ ->
let src = Cstruct.of_bigarray src in
let len = min (Cstruct.len inputs) (Cstruct.len src) in
Cstruct.blit src 0 inputs 0 len ;
Ke.Rke.N.shift_exn ke len ;
if len < Cstruct.len inputs
then go (filled + len) (Cstruct.shift inputs len)
else return (filled + len) in
go
module Verify = Carton.Dec.Verify(Uid)(Scheduler)(IO)
module Fp = Carton.Dec.Fp(Uid)
let first_pass ~zl_buffer ~digest stream =
let fl_buffer = Cstruct.create De.io_buffer_size in
let zl_window = De.make_window ~bits:15 in
let allocate _ = zl_window in
let read_cstruct = read stream in
let read_bytes () buf ~off ~len =
let rec go rest raw =
if rest <= 0
then ( Cstruct.blit_to_bytes fl_buffer 0 buf off len
; return (abs rest + len) )
else read_cstruct 0 raw >>= fun filled ->
go (rest - filled) (Cstruct.shift raw filled) in
go len fl_buffer in
let read_bytes () buf ~off ~len = Scheduler.inj (read_bytes () buf ~off ~len) in
Fp.check_header sched read_bytes () |> Scheduler.prj >>= fun (max, _, len) ->
let decoder = Fp.decoder ~o:zl_buffer ~allocate `Manual in
let decoder = Fp.src decoder (Cstruct.to_bigarray fl_buffer) 0 len in
let children = Hashtbl.create 0x100 in
let where = Hashtbl.create 0x100 in
let weight = Hashtbl.create 0x100 in
let checks = Hashtbl.create 0x100 in
let matrix = Array.make max Verify.unresolved_node in
let replace hashtbl k v =
try let v' = Hashtbl.find hashtbl k in if v < v' then Hashtbl.replace hashtbl k v'
with Not_found -> Hashtbl.add hashtbl k v in
let rec go decoder = match Fp.decode decoder with
| `Await decoder ->
read_cstruct 0 fl_buffer >>= fun len ->
Log.debug (fun m -> m "Refill the first-pass state with %d byte(s)." len) ;
go (Fp.src decoder (Cstruct.to_bigarray fl_buffer) 0 len)
| `Peek decoder ->
XXX(dinosaure ): [ ] does the compression .
let keep = Fp.src_rem decoder in
read_cstruct 0 (Cstruct.shift fl_buffer keep) >>= fun len ->
go (Fp.src decoder (Cstruct.to_bigarray fl_buffer) 0 (keep + len))
| `Entry ({ Fp.kind= Base _
; offset; size; crc; _ }, decoder) ->
let n = Fp.count decoder - 1 in
Log.debug (fun m -> m "[+] base object (%d) (%Ld)." n offset) ;
replace weight offset size ;
Hashtbl.add where offset n ;
Hashtbl.add checks offset crc ;
matrix.(n) <- Verify.unresolved_base ~cursor:offset ;
go decoder
| `Entry ({ Fp.kind= Ofs { sub= s; source; target; }
; offset; crc; _ }, decoder) ->
let n = Fp.count decoder - 1 in
Log.debug (fun m -> m "[+] ofs object (%d) (%Ld)." n offset) ;
replace weight Int64.(sub offset (Int64.of_int s)) source ;
replace weight offset target ;
Hashtbl.add where offset n ;
Hashtbl.add checks offset crc ;
( try let vs = Hashtbl.find children (`Ofs Int64.(sub offset (of_int s))) in
Hashtbl.replace children (`Ofs Int64.(sub offset (of_int s))) (offset :: vs)
with Not_found ->
Hashtbl.add children (`Ofs Int64.(sub offset (of_int s))) [ offset ] ) ;
go decoder
| `Entry ({ Fp.kind= Ref { ptr; target; source; }
; offset; crc; _ }, decoder) ->
let n = Fp.count decoder - 1 in
Log.debug (fun m -> m "[+] ref object (%d) (%Ld) (weight: %d)." n offset (Stdlib.max target source :> int)) ;
replace weight offset (Stdlib.max target source) ;
Hashtbl.add where offset n ;
Hashtbl.add checks offset crc ;
( try let vs = Hashtbl.find children (`Ref ptr) in
Hashtbl.replace children (`Ref ptr) (offset :: vs)
with Not_found ->
Hashtbl.add children (`Ref ptr) [ offset ] ) ;
go decoder
| `End uid -> return (Ok uid)
| `Malformed err ->
Log.err (fun m -> m "Got an error: %s." err) ;
return (Error (`Msg err)) in
go decoder >>? fun uid ->
Log.debug (fun m -> m "First pass on incoming PACK file is done.") ;
return (Ok ({ Carton.Dec.where= (fun ~cursor -> Hashtbl.find where cursor)
; children= (fun ~cursor ~uid ->
match Hashtbl.find_opt children (`Ofs cursor),
Hashtbl.find_opt children (`Ref uid) with
| Some a, Some b -> List.sort_uniq compare (a @ b)
| Some x, None | None, Some x -> x
| None, None -> [])
; digest= digest
; weight= (fun ~cursor -> Hashtbl.find weight cursor) },
matrix, where, checks, children, uid))
type ('t, 'path, 'fd, 'error) fs =
{ create : 't -> 'path -> ('fd, 'error) result IO.t
; append : 't -> 'fd -> string -> unit IO.t
; map : 't -> 'fd -> pos:int64 -> int -> Bigstringaf.t IO.t
; close : 't -> 'fd -> (unit, 'error) result IO.t }
module Set = Set.Make(Uid)
let zip a b =
if Array.length a <> Array.length b then invalid_arg "zip: lengths mismatch" ;
Array.init (Array.length a) (fun i -> a.(i), b.(i))
let share l0 l1 =
try List.iter (fun (v, _) -> if List.exists (Int64.equal v) l1 then raise Exists) l0 ; false
with Exists -> true
let verify ?(threads= 4) ~digest t path { create; append; map; close; } stream =
let zl_buffer = De.bigstring_create De.io_buffer_size in
let allocate bits = De.make_window ~bits in
let weight = ref 0L in
create t path >>? fun fd ->
let stream () =
stream () >>= function
| Some (buf, off, len) as res ->
append t fd (String.sub buf off len) >>= fun () ->
weight := Int64.add !weight (Int64.of_int len) ;
return res
| none -> return none in
Log.debug (fun m -> m "Start to analyse the PACK file.") ;
first_pass ~zl_buffer ~digest stream >>? fun (oracle, matrix, where, checks, children, uid) ->
let weight = !weight in
let pack = Carton.Dec.make fd ~allocate ~z:zl_buffer ~uid_ln:Uid.length ~uid_rw:Uid.of_raw_string
(fun _ -> assert false) in
let map fd ~pos len =
let len = min len Int64.(to_int (sub weight pos)) in
Scheduler.inj (map t fd ~pos len) in
Log.debug (fun m -> m "Start to verify incoming PACK file (second pass).") ;
Verify.verify ~threads pack ~map ~oracle ~matrix >>= fun () ->
Log.debug (fun m -> m "Second pass on incoming PACK file is done.") ;
let offsets = Hashtbl.fold (fun k _ a -> k :: a) where []
|> List.sort Int64.compare
|> Array.of_list in
let unresolveds, resolveds =
let fold (unresolveds, resolveds) (offset, status) =
if Verify.is_resolved status
then
let uid = Verify.uid_of_status status in
let crc = Hashtbl.find checks offset in
unresolveds, ({ Carton.Dec.Idx.crc; offset; uid } :: resolveds)
else
let crc = Hashtbl.find checks offset in
((offset, crc) :: unresolveds), resolveds in
Array.fold_left fold ([], []) (zip offsets matrix) in
let requireds =
Hashtbl.fold (fun k vs a -> match k with
| `Ofs _ -> a
| `Ref uid ->
if share unresolveds vs
then Set.add uid a else a)
children Set.empty in
close t fd >>? fun () ->
Log.debug (fun m -> m "PACK file verified (%d resolved object(s), %d unresolved object(s))"
(List.length resolveds) (List.length unresolveds)) ;
return (Ok (Hashtbl.length where, Set.elements requireds, unresolveds, resolveds, weight, uid))
let find _ = assert false
let vuid = { Carton.Enc.uid_ln= Uid.length
; Carton.Enc.uid_rw= Uid.to_raw_string }
type nonrec light_load = (Uid.t, Scheduler.t) light_load
type nonrec heavy_load = (Uid.t, Scheduler.t) heavy_load
let canonicalize ~light_load ~heavy_load ~src ~dst t { create; append; close; map; _ } n uids weight =
let b =
{ Carton.Enc.o= Bigstringaf.create De.io_buffer_size
; Carton.Enc.i= Bigstringaf.create De.io_buffer_size
; Carton.Enc.q= De.Queue.create 0x10000
; Carton.Enc.w= De.make_window ~bits:15 } in
let ctx = ref Uid.empty in
let cursor = ref 0L in
let light_load uid = Scheduler.prj (light_load uid) in
create t dst >>? fun fd ->
let header = Bigstringaf.create 12 in
Carton.Enc.header_of_pack ~length:(n + List.length uids) header 0 12 ;
let hdr = Bigstringaf.to_string header in
append t fd hdr >>= fun () ->
ctx := Uid.feed !ctx header ;
cursor := Int64.add !cursor 12L ;
let encode_base uid =
light_load uid >>= fun (kind, length) ->
let entry = Carton.Enc.make_entry ~kind ~length uid in
let anchor = !cursor in
let crc = ref Checkseum.Crc32.default in
Carton.Enc.entry_to_target sched ~load:heavy_load entry |> Scheduler.prj >>= fun target ->
Carton.Enc.encode_target sched ~b ~find ~load:heavy_load ~uid:vuid target ~cursor:(Int64.to_int anchor)
|> Scheduler.prj >>= fun (len, encoder) ->
let rec go encoder = match Carton.Enc.N.encode ~o:b.o encoder with
| `Flush (encoder, len) ->
append t fd (Bigstringaf.substring b.o ~off:0 ~len) >>= fun () ->
ctx := Uid.feed !ctx ~off:0 ~len b.o ;
crc := Checkseum.Crc32.digest_bigstring b.o 0 len !crc ;
cursor := Int64.add !cursor (Int64.of_int len) ;
let encoder =
Carton.Enc.N.dst encoder b.o 0 (Bigstringaf.length b.o) in
go encoder
| `End -> return { Carton.Dec.Idx.crc= !crc; offset= anchor; uid; } in
append t fd (Bigstringaf.substring b.o ~off:0 ~len) >>= fun () ->
ctx := Uid.feed !ctx ~off:0 ~len b.o ;
crc := Checkseum.Crc32.digest_bigstring b.o 0 len !crc ;
cursor := Int64.add !cursor (Int64.of_int len) ;
let encoder = Carton.Enc.N.dst encoder b.o 0 (Bigstringaf.length b.o) in
go encoder in
let rec go acc = function
| [] -> return (List.rev acc)
| uid :: uids ->
encode_base uid >>= fun entry -> go (entry :: acc) uids in
go [] uids >>= fun entries ->
let shift = Int64.sub !cursor 12L in
let top = Int64.sub weight (Int64.of_int Uid.length) in
let rec go src pos =
let max = (Int64.sub top pos) in
let len = min max (Int64.mul 1024L 1024L) in
let len = Int64.to_int len in
map t src ~pos len >>= fun raw ->
append t fd (Bigstringaf.to_string raw) >>= fun () ->
ctx := Uid.feed !ctx raw ;
cursor := Int64.add !cursor (Int64.of_int len) ;
if Int64.add pos (Int64.of_int len) < top
then go src (Int64.add pos (Int64.of_int len))
else
( let uid = Uid.get !ctx in
append t fd (Uid.to_raw_string uid) >>= fun () ->
return (Ok (Int64.(add !cursor (of_int Uid.length)), uid)) ) in
create t src >>? fun src -> go src 12L >>? fun (weight, uid) ->
close t fd >>? fun () -> return (Ok (shift, weight, uid, entries))
end
|
|
8da97c2c3685041ab84c733bd4cab878787677a095d3ef9a0be2b2241facf489 | xh4/web-toolkit | accessor.lisp | (in-package :uri)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun parse-lambda-list-keywords (lambda-list)
(let ((keyword-specs (fourth
(multiple-value-list
(parse-ordinary-lambda-list lambda-list)))))
(loop for ((keyword-name name)) in keyword-specs
collect keyword-name))))
(defmacro define-uri-reader (component &body body)
(let* ((component-symbol (or (and (listp component) (car component))
component))
(lambda-list (and (listp component) (rest component)))
(lambda-list-keys (parse-lambda-list-keywords lambda-list))
(accessor-name (intern (format nil "URI-~A"
(symbol-name component-symbol)))))
`(defgeneric ,accessor-name (uri ,@(loop for key in lambda-list-keys
collect (intern (symbol-name key))
into keys
finally (return
(when keys
(append '(&key) keys)))))
(:method ((uri string) ,@lambda-list)
(,accessor-name (uri uri)
,@(loop for key in lambda-list-keys
append (list key
(intern (symbol-name key))))))
(:method ((uri uri) ,@lambda-list)
,@(typecase component
(symbol `((slot-value uri ',component-symbol)))
(list `((let ((,component-symbol (slot-value uri ',component-symbol)))
,@body))))))))
(defmacro define-uri-writer (component)
(let ((accessor-name (intern (format nil "URI-~A" (symbol-name component))))
(checker-name (intern (format nil "CHECK-~A" (symbol-name component)))))
(with-gensyms (checked-value)
`(defgeneric (setf ,accessor-name) (value uri)
(:method (value (uri uri))
(let ((,checked-value (handler-bind
((error
(lambda (e)
(error 'uri-component-error
:component ,(make-keyword component)
:value value
:message (format nil "~A" e)))))
(,checker-name value))))
(setf (slot-value uri 'string) nil)
(setf (slot-value uri ',component) ,checked-value)))))))
(define-uri-reader scheme)
(define-uri-writer scheme)
(define-uri-reader (userinfo &key (decode t))
(if decode
(percent-decode userinfo)
userinfo))
(define-uri-writer userinfo)
(define-uri-reader (host &key (decode t))
(if decode
(percent-decode host)
host))
(define-uri-writer host)
(define-uri-reader port)
(define-uri-writer port)
(define-uri-reader (path &key (decode t))
(if decode
(percent-decode path)
path))
(define-uri-writer path)
(define-uri-reader (query &key (type :alist) (decode nil))
(case type
(:alist (uri-query-alist query))
(:hash-table (uri-query-hash-table query))
((or nil :string) (if decode
(percent-decode query)
query))
(t (error "Bad type ~A" type))))
(define-uri-writer query)
(define-uri-reader (fragment &key (decode t))
(if decode
(percent-decode fragment)
fragment))
(define-uri-writer fragment)
(defun update-uri (uri &key (scheme nil scheme-present-p)
(userinfo nil userinfo-present-p)
(host nil host-present-p)
(port nil port-present-p)
(path nil path-present-p)
(query nil query-present-p)
(fragment nil fragment-present-p))
(let ((uri (uri uri)))
(handler-bind ((uri-component-error
(lambda (c)
(change-class c 'update-uri-error :uri uri))))
(when scheme-present-p
(setf (uri-scheme uri) scheme))
(when userinfo-present-p
(setf (uri-userinfo uri) userinfo))
(when host-present-p
(setf (uri-host uri) host))
(when port-present-p
(setf (uri-port uri) port))
(when path-present-p
(setf (uri-path uri) path))
(when query-present-p
(setf (uri-query uri) query))
(when fragment-present-p
(setf (uri-fragment uri) fragment)))
uri))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/uri/accessor.lisp | lisp | (in-package :uri)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun parse-lambda-list-keywords (lambda-list)
(let ((keyword-specs (fourth
(multiple-value-list
(parse-ordinary-lambda-list lambda-list)))))
(loop for ((keyword-name name)) in keyword-specs
collect keyword-name))))
(defmacro define-uri-reader (component &body body)
(let* ((component-symbol (or (and (listp component) (car component))
component))
(lambda-list (and (listp component) (rest component)))
(lambda-list-keys (parse-lambda-list-keywords lambda-list))
(accessor-name (intern (format nil "URI-~A"
(symbol-name component-symbol)))))
`(defgeneric ,accessor-name (uri ,@(loop for key in lambda-list-keys
collect (intern (symbol-name key))
into keys
finally (return
(when keys
(append '(&key) keys)))))
(:method ((uri string) ,@lambda-list)
(,accessor-name (uri uri)
,@(loop for key in lambda-list-keys
append (list key
(intern (symbol-name key))))))
(:method ((uri uri) ,@lambda-list)
,@(typecase component
(symbol `((slot-value uri ',component-symbol)))
(list `((let ((,component-symbol (slot-value uri ',component-symbol)))
,@body))))))))
(defmacro define-uri-writer (component)
(let ((accessor-name (intern (format nil "URI-~A" (symbol-name component))))
(checker-name (intern (format nil "CHECK-~A" (symbol-name component)))))
(with-gensyms (checked-value)
`(defgeneric (setf ,accessor-name) (value uri)
(:method (value (uri uri))
(let ((,checked-value (handler-bind
((error
(lambda (e)
(error 'uri-component-error
:component ,(make-keyword component)
:value value
:message (format nil "~A" e)))))
(,checker-name value))))
(setf (slot-value uri 'string) nil)
(setf (slot-value uri ',component) ,checked-value)))))))
(define-uri-reader scheme)
(define-uri-writer scheme)
(define-uri-reader (userinfo &key (decode t))
(if decode
(percent-decode userinfo)
userinfo))
(define-uri-writer userinfo)
(define-uri-reader (host &key (decode t))
(if decode
(percent-decode host)
host))
(define-uri-writer host)
(define-uri-reader port)
(define-uri-writer port)
(define-uri-reader (path &key (decode t))
(if decode
(percent-decode path)
path))
(define-uri-writer path)
(define-uri-reader (query &key (type :alist) (decode nil))
(case type
(:alist (uri-query-alist query))
(:hash-table (uri-query-hash-table query))
((or nil :string) (if decode
(percent-decode query)
query))
(t (error "Bad type ~A" type))))
(define-uri-writer query)
(define-uri-reader (fragment &key (decode t))
(if decode
(percent-decode fragment)
fragment))
(define-uri-writer fragment)
(defun update-uri (uri &key (scheme nil scheme-present-p)
(userinfo nil userinfo-present-p)
(host nil host-present-p)
(port nil port-present-p)
(path nil path-present-p)
(query nil query-present-p)
(fragment nil fragment-present-p))
(let ((uri (uri uri)))
(handler-bind ((uri-component-error
(lambda (c)
(change-class c 'update-uri-error :uri uri))))
(when scheme-present-p
(setf (uri-scheme uri) scheme))
(when userinfo-present-p
(setf (uri-userinfo uri) userinfo))
(when host-present-p
(setf (uri-host uri) host))
(when port-present-p
(setf (uri-port uri) port))
(when path-present-p
(setf (uri-path uri) path))
(when query-present-p
(setf (uri-query uri) query))
(when fragment-present-p
(setf (uri-fragment uri) fragment)))
uri))
|
|
d94f719a9a23e93578154f6e94b4bb8b43121f91a36d596591ce5e1c5d4cbb25 | krisajenkins/petrol | core.cljs | (ns petrol-examples.counter.core
(:require [petrol.core :as petrol]
[reagent.core :as reagent]
[petrol-examples.counter.processing]
[petrol-examples.counter.view :as view]))
(def initial-state
{:counter 0})
(defonce !app
(reagent/atom initial-state))
figwheel reload - hook
(defn reload-hook
[]
(swap! !app identity))
(defn render-fn
[ui-channel app]
(reagent/render-component [view/root ui-channel app]
js/document.body))
(defn ^:export main
[]
(enable-console-print!)
(petrol/start-message-loop! !app render-fn))
| null | https://raw.githubusercontent.com/krisajenkins/petrol/607166ab48cf6193b6ad00bcd63bd3ff7f3958f7/examples/src/petrol-examples/counter/core.cljs | clojure | (ns petrol-examples.counter.core
(:require [petrol.core :as petrol]
[reagent.core :as reagent]
[petrol-examples.counter.processing]
[petrol-examples.counter.view :as view]))
(def initial-state
{:counter 0})
(defonce !app
(reagent/atom initial-state))
figwheel reload - hook
(defn reload-hook
[]
(swap! !app identity))
(defn render-fn
[ui-channel app]
(reagent/render-component [view/root ui-channel app]
js/document.body))
(defn ^:export main
[]
(enable-console-print!)
(petrol/start-message-loop! !app render-fn))
|
|
0b925f52a4b8497369e3944974fff718d9768bcb1d6ba9c6f340927f59fb3183 | graninas/Functional-Design-and-Architecture | ArrowDSL.hs | {-# LANGUAGE Arrows #-}
module ArrowDSL where
import Control.Arrow
import Control.Category
import Control.Monad.Free
import Prelude hiding ((.))
import ControllerDSL as C
import InfrastructureDSL as I
import ScriptingDSL as S
import Control
import ArrEff
-- arrow type
type FlowArr b c = ArrEffFree Control b c
data ValidationResult = Success
| Failure String
readSensor :: Parameter -> SensorInstance -> Script Measurement
readSensor p (cont, idx) = controllerScript readSensor'
where
readSensor' :: ControllerScript Measurement
readSensor' = C.read cont idx p
alarmOnFail :: ValidationResult -> Script ()
alarmOnFail Success = infrastructureScript $ return ()
alarmOnFail (Failure msg) = infrastructureScript $ alarm msg
thermTemperatureA :: FlowArr SensorInstance Measurement
thermTemperatureA = mArr (evalScript . readSensor temperature)
alarmOnFailA :: FlowArr ValidationResult ()
alarmOnFailA = mArr (evalScript . alarmOnFail)
storeReadingA :: FlowArr Reading ()
storeReadingA = mArr (evalScript . infrastructureScript . storeReading)
getTimeA :: FlowArr b Time
getTimeA = mArr (evalScript . infrastructureScript . const getCurrentTime)
toKelvinA :: FlowArr Measurement Measurement
toKelvinA = arr toKelvin
validateReadingA :: FlowArr Reading ValidationResult
validateReadingA = arr validateReading
validateReading :: Reading -> ValidationResult
validateReading (_, si, Measurement (FloatValue tempK)) =
if (tempK < 263.15)
then Failure (show (si, "Temperature lower than bound"))
else if (tempK > 323.15)
then Failure (show (si, "Temperature higher than bound"))
else Success
| null | https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/1736abc16d3e4917fc466010dcc182746af2fd0e/First-Edition/BookSamples/CH04/ArrowizedDSL/ArrowDSL.hs | haskell | # LANGUAGE Arrows #
arrow type | module ArrowDSL where
import Control.Arrow
import Control.Category
import Control.Monad.Free
import Prelude hiding ((.))
import ControllerDSL as C
import InfrastructureDSL as I
import ScriptingDSL as S
import Control
import ArrEff
type FlowArr b c = ArrEffFree Control b c
data ValidationResult = Success
| Failure String
readSensor :: Parameter -> SensorInstance -> Script Measurement
readSensor p (cont, idx) = controllerScript readSensor'
where
readSensor' :: ControllerScript Measurement
readSensor' = C.read cont idx p
alarmOnFail :: ValidationResult -> Script ()
alarmOnFail Success = infrastructureScript $ return ()
alarmOnFail (Failure msg) = infrastructureScript $ alarm msg
thermTemperatureA :: FlowArr SensorInstance Measurement
thermTemperatureA = mArr (evalScript . readSensor temperature)
alarmOnFailA :: FlowArr ValidationResult ()
alarmOnFailA = mArr (evalScript . alarmOnFail)
storeReadingA :: FlowArr Reading ()
storeReadingA = mArr (evalScript . infrastructureScript . storeReading)
getTimeA :: FlowArr b Time
getTimeA = mArr (evalScript . infrastructureScript . const getCurrentTime)
toKelvinA :: FlowArr Measurement Measurement
toKelvinA = arr toKelvin
validateReadingA :: FlowArr Reading ValidationResult
validateReadingA = arr validateReading
validateReading :: Reading -> ValidationResult
validateReading (_, si, Measurement (FloatValue tempK)) =
if (tempK < 263.15)
then Failure (show (si, "Temperature lower than bound"))
else if (tempK > 323.15)
then Failure (show (si, "Temperature higher than bound"))
else Success
|
24d09e70f7ade23493f815159b0b8612e40981dfcfce93b1a1c3e0025b188fe9 | dparis/cooler | connection_options.clj | (ns cooler.schemas.redis.connection-options
"Schema which validates a Redis ConnectionOptions map."
(:require [cooler.util :as u]
[schema.core :as s]))
(s/defschema ^:private PoolConfig
{(s/optional-key :min-idle-per-key) s/Int
(s/optional-key :max-idle-per-key) s/Int
(s/optional-key :max-total-per-key) s/Int
(s/optional-key :block-when-exhausted?) s/Int
(s/optional-key :lifo?) s/Bool
(s/optional-key :max-total) s/Int
(s/optional-key :max-wait-ms) s/Int
(s/optional-key :min-evictable-idle-time-ms) s/Int
(s/optional-key :num-tests-per-eviction-run) s/Int
(s/optional-key :soft-min-evictable-idle-time-ms) s/Int
(s/optional-key :swallowed-exception-listener) s/Int
(s/optional-key :test-on-borrow?) s/Bool
(s/optional-key :test-on-return?) s/Bool
(s/optional-key :test-while-idle?) s/Bool
(s/optional-key :time-between-eviction-runs-ms) s/Int})
(s/defschema ^:private AuthHostPort
{:host s/Str
:port s/Int})
(s/defschema ^:private AuthURI
{:uri s/Str})
(s/defschema ^:private AuthOptions
{(s/optional-key :password) s/Str
(s/optional-key :timeout-ms) s/Int
(s/optional-key :db) s/Int})
(s/defschema ^:private ConnectionSpec
(s/conditional
#(u/contains-keys? % [:host :port])
AuthHostPort
#(u/contains-keys? % [:uri])
AuthURI
'valid-connection-spec?))
(s/defschema ConnectionOptions
"Schema which validates a Redis ConnectionOptions map."
{:pool (s/conditional
#(= % :none) (s/eq :none)
:else PoolConfig)
:spec (s/conditional
#(= % {}) (s/eq {})
:else (s/maybe (merge ConnectionSpec AuthOptions)))})
| null | https://raw.githubusercontent.com/dparis/cooler/38b2efb3c4efb32d1b3d03c70176f690555f94d1/src/cooler/schemas/redis/connection_options.clj | clojure | (ns cooler.schemas.redis.connection-options
"Schema which validates a Redis ConnectionOptions map."
(:require [cooler.util :as u]
[schema.core :as s]))
(s/defschema ^:private PoolConfig
{(s/optional-key :min-idle-per-key) s/Int
(s/optional-key :max-idle-per-key) s/Int
(s/optional-key :max-total-per-key) s/Int
(s/optional-key :block-when-exhausted?) s/Int
(s/optional-key :lifo?) s/Bool
(s/optional-key :max-total) s/Int
(s/optional-key :max-wait-ms) s/Int
(s/optional-key :min-evictable-idle-time-ms) s/Int
(s/optional-key :num-tests-per-eviction-run) s/Int
(s/optional-key :soft-min-evictable-idle-time-ms) s/Int
(s/optional-key :swallowed-exception-listener) s/Int
(s/optional-key :test-on-borrow?) s/Bool
(s/optional-key :test-on-return?) s/Bool
(s/optional-key :test-while-idle?) s/Bool
(s/optional-key :time-between-eviction-runs-ms) s/Int})
(s/defschema ^:private AuthHostPort
{:host s/Str
:port s/Int})
(s/defschema ^:private AuthURI
{:uri s/Str})
(s/defschema ^:private AuthOptions
{(s/optional-key :password) s/Str
(s/optional-key :timeout-ms) s/Int
(s/optional-key :db) s/Int})
(s/defschema ^:private ConnectionSpec
(s/conditional
#(u/contains-keys? % [:host :port])
AuthHostPort
#(u/contains-keys? % [:uri])
AuthURI
'valid-connection-spec?))
(s/defschema ConnectionOptions
"Schema which validates a Redis ConnectionOptions map."
{:pool (s/conditional
#(= % :none) (s/eq :none)
:else PoolConfig)
:spec (s/conditional
#(= % {}) (s/eq {})
:else (s/maybe (merge ConnectionSpec AuthOptions)))})
|
|
b8e67998308f73e9acf66b0885f4e26b460c3a8d075d876c49524c927be20fc3 | input-output-hk/ouroboros-network | ChainUpdates.hs | # LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
-- | Generate sequences of updates to model an evolving chain
module Test.Util.ChainUpdates (
ChainUpdate (..)
, UpdateBehavior (..)
, genChainUpdates
, toChainUpdates
-- * Tests
, prop_genChainUpdates
) where
import Control.Monad.State.Strict
import Test.QuickCheck
import Ouroboros.Network.Mock.Chain (Chain (Genesis))
import qualified Ouroboros.Network.Mock.Chain as Chain
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Config
import Ouroboros.Consensus.Util.Condense (Condense (..))
import Test.Util.TestBlock
data ChainUpdate =
AddBlock TestBlock
-- | Roll back to the given 'Point', and then /immediately/ roll
forward by the given ' TestBlock 's .
| SwitchFork (Point TestBlock) [TestBlock]
deriving stock (Eq, Show)
instance Condense ChainUpdate where
condense = \case
AddBlock b -> "AddBlock " <> condense b
SwitchFork p bs -> "SwitchFork <- " <> condense p <> " -> " <>
unwords (map condense bs)
toChainUpdates :: [ChainUpdate] -> [Chain.ChainUpdate TestBlock TestBlock]
toChainUpdates = concatMap $ \case
SwitchFork pt bs -> Chain.RollBack pt : map Chain.AddBlock bs
AddBlock b -> Chain.AddBlock b : []
{-------------------------------------------------------------------------------
Generating ChainUpdates
-------------------------------------------------------------------------------}
-- | We need some state to generate @ChainUpdate@s
data ChainUpdateState = ChainUpdateState
{ cusCurrentChain :: !(Chain TestBlock)
-- ^ The current chain, obtained by applying all the 'cusUpdates' in reverse
-- order.
, cusUpdates :: ![ChainUpdate]
-- ^ The updates that have been generated so far, in reverse order: the
-- first update in the list is the last update to apply.
} deriving stock (Show)
emptyUpdateState :: ChainUpdateState
emptyUpdateState = ChainUpdateState
{ cusCurrentChain = Genesis
, cusUpdates = []
}
getChainUpdates :: ChainUpdateState -> [ChainUpdate]
getChainUpdates = reverse . cusUpdates
| Different strategies how to generate a sequence of ' ChainUpdate 's .
data UpdateBehavior =
-- | Chain updates tracking the selected chain of an honest node. In
-- particular, this includes:
--
-- * All blocks involved are valid.
* Every ' ChainUpdate ' improves the chain .
SelectedChainBehavior
| -- | Chain updates tracking the tentative chain of an honest node (in the
-- context of diffusion pipelining). This is similiar to
-- 'SelectedChainBehavior', but allows for the following sequence of
' ChainUpdates ' :
--
1 . @'AddBlock ' blk@ for @blk@ invalid
2 . @'SwitchFork ' ( prevPoint blk ) [ blk']@ where @blk'@ is preferable to
-- @blk@.
TentativeChainBehavior
deriving stock (Show, Eq, Enum, Bounded)
genChainUpdates
:: UpdateBehavior
-> SecurityParam
-> Int -- ^ The number of updates to generate
-> Gen [ChainUpdate]
genChainUpdates updateBehavior securityParam n =
getChainUpdates
<$> genChainUpdateState updateBehavior securityParam n emptyUpdateState
genChainUpdateState ::
UpdateBehavior
-> SecurityParam
-> Int
-> ChainUpdateState
-> Gen ChainUpdateState
genChainUpdateState updateBehavior securityParam n =
execStateT (replicateM_ n genChainUpdate)
where
-- Modify the state
addUpdate u cus = cus { cusUpdates = u : cusUpdates cus }
setChain c cus = cus { cusCurrentChain = c }
k = fromIntegral $ maxRollbacks securityParam
genChainUpdate = do
ChainUpdateState { cusCurrentChain = chain } <- get
let genValid =
frequency'
[ (3, genAddBlock Valid)
, ( if Chain.null chain then 0 else 1
, genSwitchFork (choose (1, k))
)
]
frequency' $
(5, replicateM_ 2 genValid) :
[ (1, genInvalidBlock) | updateBehavior == TentativeChainBehavior ]
genBlockToAdd validity = do
ChainUpdateState { cusCurrentChain = chain } <- get
block <- lift $ case Chain.head chain of
Nothing -> setValidity . firstBlock <$> genForkNo
Just curHead -> do
forkNo <- case validity of
Valid -> genForkNo
Invalid -> pure 3
return
. modifyFork (const forkNo)
. setValidity
$ successorBlock curHead
modify $ setChain (Chain.addBlock block chain)
return block
where
setValidity b = b { tbValid = validity }
genForkNo = case validity of
Valid -> frequency
[ (1, return 0)
, (1, choose (1, 2))
]
-- Blocks with equal hashes have to have equal validity, so we reserve
-- a specific ForkNo for invalid blocks to ensure this.
Invalid -> pure 3
genAddBlock validity = do
block <- genBlockToAdd validity
modify $ addUpdate (AddBlock block)
genSwitchFork genRollBackBlocks = do
ChainUpdateState { cusCurrentChain = chain } <- get
rollBackBlocks <- lift genRollBackBlocks
let chain' = Chain.drop rollBackBlocks chain
modify $ setChain chain'
blocks <- replicateM rollBackBlocks (genBlockToAdd Valid)
modify $ addUpdate (SwitchFork (Chain.headPoint chain') blocks)
genInvalidBlock = do
genAddBlock Invalid
genSwitchFork (pure 1)
-- | Variant of 'frequency' that allows for transformers of 'Gen'
frequency' :: (MonadTrans t, Monad (t Gen)) => [(Int, t Gen a)] -> t Gen a
frequency' [] = error "frequency' used with empty list"
frequency' xs0 = lift (choose (1, tot)) >>= (`pick` xs0)
where
tot = sum (map fst xs0)
pick n ((k,x):xs)
| n <= k = x
| otherwise = pick (n-k) xs
pick _ _ = error "pick used with empty list"
-- | Test that applying the generated updates gives us the same chain
as @cusCurrentChain@.
prop_genChainUpdates :: SecurityParam -> Int -> Property
prop_genChainUpdates securityParam n =
forAll genCUS $ \cus ->
Chain.applyChainUpdates (toChainUpdates (getChainUpdates cus)) Genesis ===
Just (cusCurrentChain cus)
where
genCUS = do
behavior <- chooseEnum (minBound, maxBound)
genChainUpdateState behavior securityParam n emptyUpdateState
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/2793b6993c8f6ed158f432055fa4ef581acdb661/ouroboros-consensus-test/src/Test/Util/ChainUpdates.hs | haskell | | Generate sequences of updates to model an evolving chain
* Tests
| Roll back to the given 'Point', and then /immediately/ roll
------------------------------------------------------------------------------
Generating ChainUpdates
------------------------------------------------------------------------------
| We need some state to generate @ChainUpdate@s
^ The current chain, obtained by applying all the 'cusUpdates' in reverse
order.
^ The updates that have been generated so far, in reverse order: the
first update in the list is the last update to apply.
| Chain updates tracking the selected chain of an honest node. In
particular, this includes:
* All blocks involved are valid.
| Chain updates tracking the tentative chain of an honest node (in the
context of diffusion pipelining). This is similiar to
'SelectedChainBehavior', but allows for the following sequence of
@blk@.
^ The number of updates to generate
Modify the state
Blocks with equal hashes have to have equal validity, so we reserve
a specific ForkNo for invalid blocks to ensure this.
| Variant of 'frequency' that allows for transformers of 'Gen'
| Test that applying the generated updates gives us the same chain | # LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
module Test.Util.ChainUpdates (
ChainUpdate (..)
, UpdateBehavior (..)
, genChainUpdates
, toChainUpdates
, prop_genChainUpdates
) where
import Control.Monad.State.Strict
import Test.QuickCheck
import Ouroboros.Network.Mock.Chain (Chain (Genesis))
import qualified Ouroboros.Network.Mock.Chain as Chain
import Ouroboros.Consensus.Block
import Ouroboros.Consensus.Config
import Ouroboros.Consensus.Util.Condense (Condense (..))
import Test.Util.TestBlock
data ChainUpdate =
AddBlock TestBlock
forward by the given ' TestBlock 's .
| SwitchFork (Point TestBlock) [TestBlock]
deriving stock (Eq, Show)
instance Condense ChainUpdate where
condense = \case
AddBlock b -> "AddBlock " <> condense b
SwitchFork p bs -> "SwitchFork <- " <> condense p <> " -> " <>
unwords (map condense bs)
toChainUpdates :: [ChainUpdate] -> [Chain.ChainUpdate TestBlock TestBlock]
toChainUpdates = concatMap $ \case
SwitchFork pt bs -> Chain.RollBack pt : map Chain.AddBlock bs
AddBlock b -> Chain.AddBlock b : []
data ChainUpdateState = ChainUpdateState
{ cusCurrentChain :: !(Chain TestBlock)
, cusUpdates :: ![ChainUpdate]
} deriving stock (Show)
emptyUpdateState :: ChainUpdateState
emptyUpdateState = ChainUpdateState
{ cusCurrentChain = Genesis
, cusUpdates = []
}
getChainUpdates :: ChainUpdateState -> [ChainUpdate]
getChainUpdates = reverse . cusUpdates
| Different strategies how to generate a sequence of ' ChainUpdate 's .
data UpdateBehavior =
* Every ' ChainUpdate ' improves the chain .
SelectedChainBehavior
' ChainUpdates ' :
1 . @'AddBlock ' blk@ for @blk@ invalid
2 . @'SwitchFork ' ( prevPoint blk ) [ blk']@ where @blk'@ is preferable to
TentativeChainBehavior
deriving stock (Show, Eq, Enum, Bounded)
genChainUpdates
:: UpdateBehavior
-> SecurityParam
-> Gen [ChainUpdate]
genChainUpdates updateBehavior securityParam n =
getChainUpdates
<$> genChainUpdateState updateBehavior securityParam n emptyUpdateState
genChainUpdateState ::
UpdateBehavior
-> SecurityParam
-> Int
-> ChainUpdateState
-> Gen ChainUpdateState
genChainUpdateState updateBehavior securityParam n =
execStateT (replicateM_ n genChainUpdate)
where
addUpdate u cus = cus { cusUpdates = u : cusUpdates cus }
setChain c cus = cus { cusCurrentChain = c }
k = fromIntegral $ maxRollbacks securityParam
genChainUpdate = do
ChainUpdateState { cusCurrentChain = chain } <- get
let genValid =
frequency'
[ (3, genAddBlock Valid)
, ( if Chain.null chain then 0 else 1
, genSwitchFork (choose (1, k))
)
]
frequency' $
(5, replicateM_ 2 genValid) :
[ (1, genInvalidBlock) | updateBehavior == TentativeChainBehavior ]
genBlockToAdd validity = do
ChainUpdateState { cusCurrentChain = chain } <- get
block <- lift $ case Chain.head chain of
Nothing -> setValidity . firstBlock <$> genForkNo
Just curHead -> do
forkNo <- case validity of
Valid -> genForkNo
Invalid -> pure 3
return
. modifyFork (const forkNo)
. setValidity
$ successorBlock curHead
modify $ setChain (Chain.addBlock block chain)
return block
where
setValidity b = b { tbValid = validity }
genForkNo = case validity of
Valid -> frequency
[ (1, return 0)
, (1, choose (1, 2))
]
Invalid -> pure 3
genAddBlock validity = do
block <- genBlockToAdd validity
modify $ addUpdate (AddBlock block)
genSwitchFork genRollBackBlocks = do
ChainUpdateState { cusCurrentChain = chain } <- get
rollBackBlocks <- lift genRollBackBlocks
let chain' = Chain.drop rollBackBlocks chain
modify $ setChain chain'
blocks <- replicateM rollBackBlocks (genBlockToAdd Valid)
modify $ addUpdate (SwitchFork (Chain.headPoint chain') blocks)
genInvalidBlock = do
genAddBlock Invalid
genSwitchFork (pure 1)
frequency' :: (MonadTrans t, Monad (t Gen)) => [(Int, t Gen a)] -> t Gen a
frequency' [] = error "frequency' used with empty list"
frequency' xs0 = lift (choose (1, tot)) >>= (`pick` xs0)
where
tot = sum (map fst xs0)
pick n ((k,x):xs)
| n <= k = x
| otherwise = pick (n-k) xs
pick _ _ = error "pick used with empty list"
as @cusCurrentChain@.
prop_genChainUpdates :: SecurityParam -> Int -> Property
prop_genChainUpdates securityParam n =
forAll genCUS $ \cus ->
Chain.applyChainUpdates (toChainUpdates (getChainUpdates cus)) Genesis ===
Just (cusCurrentChain cus)
where
genCUS = do
behavior <- chooseEnum (minBound, maxBound)
genChainUpdateState behavior securityParam n emptyUpdateState
|
f735c6c397956648efa4537bfed395b75222cee417388f8e452907de28267e39 | ucsd-progsys/nate | helloworld.ml | (***********************************************************************)
(* *)
MLTk , Tcl / Tk interface of Objective Caml
(* *)
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
(* described in file LICENSE found in the Objective Caml source tree. *)
(* *)
(***********************************************************************)
open Camltk;; (* Make interface functions available *)
let top = opentk ();; (* Initialisation of the interface *)
(* top is now the toplevel widget *)
(* Widget initialisation *)
let b = Button.create top
[Text "foobar";
Command (function () ->
print_string "foobar";
print_newline();
flush stdout)];;
(* b exists but is not yet visible *)
let q = Button.create top
[Text "quit";
Command closeTk];;
(* q exists but is not yet visible *)
pack [b; q][] ;; (* Make b visible *)
mainLoop() ;; (* User interaction*)
(* You can quit this program by deleting its main window *)
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/labltk/examples_camltk/helloworld.ml | ocaml | *********************************************************************
described in file LICENSE found in the Objective Caml source tree.
*********************************************************************
Make interface functions available
Initialisation of the interface
top is now the toplevel widget
Widget initialisation
b exists but is not yet visible
q exists but is not yet visible
Make b visible
User interaction
You can quit this program by deleting its main window | MLTk , Tcl / Tk interface of Objective Caml
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
let b = Button.create top
[Text "foobar";
Command (function () ->
print_string "foobar";
print_newline();
flush stdout)];;
let q = Button.create top
[Text "quit";
Command closeTk];;
|
b7947f6087a1b1908f24710bdbe9c0d680502f57ad8de0616a4302e8c86eeaf0 | ocamllabs/ocaml-modular-implicits | t070-branchifnot.ml | open Lib;;
if false then raise Not_found;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONST0
10 BRANCHIFNOT 17
12 GETGLOBAL Not_found
14 MAKEBLOCK1 0
16 RAISE
17 ATOM0
18 SETGLOBAL T070 - branchifnot
20 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONST0
10 BRANCHIFNOT 17
12 GETGLOBAL Not_found
14 MAKEBLOCK1 0
16 RAISE
17 ATOM0
18 SETGLOBAL T070-branchifnot
20 STOP
**)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t070-branchifnot.ml | ocaml | open Lib;;
if false then raise Not_found;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONST0
10 BRANCHIFNOT 17
12 GETGLOBAL Not_found
14 MAKEBLOCK1 0
16 RAISE
17 ATOM0
18 SETGLOBAL T070 - branchifnot
20 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONST0
10 BRANCHIFNOT 17
12 GETGLOBAL Not_found
14 MAKEBLOCK1 0
16 RAISE
17 ATOM0
18 SETGLOBAL T070-branchifnot
20 STOP
**)
|
|
c987d034d682df3e822d2762fb1249d362d2db3117ab5c4284922e68261a8712 | chenyukang/eopl | 26.scm | (load-relative "../libs/init.scm")
(load-relative "./base/test.scm")
(load-relative "./base/subst.scm")
(load-relative "./base/inferred-cases.scm")
(load-relative "./base/data-structures.scm")
(load-relative "./base/equal-type.scm")
(load-relative "./base/store.scm")
Extend the inferencer to handle EXPLICIT - REFS , as in exercise 7.10 .
(define-datatype expval expval?
(num-val
(value number?))
(bool-val
(boolean boolean?))
(proc-val
(proc proc?))
(ref-val
(ref reference?)))
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (number) const-exp)
(expression
("-" "(" expression "," expression ")")
diff-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression (identifier) var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
(expression
("proc" "(" identifier ":" optional-type ")" expression)
proc-exp)
(expression
("(" expression expression ")")
call-exp)
;; begin new stuff
(expression
("newref" "(" expression ")")
newref-exp)
(expression
("deref" "(" expression ")")
deref-exp)
(expression
("setref" "(" expression "," expression ")")
setref-exp)
;; end new stuff
(expression
("letrec"
optional-type identifier "(" identifier ":" optional-type ")"
"=" expression "in" expression)
letrec-exp)
(optional-type
("?")
no-type)
(optional-type
(type)
a-type)
(type
("int")
int-type)
(type
("bool")
bool-type)
(type
("(" type "->" type ")")
proc-type)
(type
("%tvar-type" number)
tvar-type)
;; new stuff
(type
("refto" type)
refto-type)
(type
("void")
void-type)
))
;;;;;;;;;;;;;;;; sllgen boilerplate ;;;;;;;;;;;;;;;;
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
;; new stuff, use hashtable as substitution.
;; new implementation of subst
(define the-subst (make-hash-table))
(define extend-subst
(lambda (tvar ty)
(set! (hash-table-ref the-subst tvar) ty)))
(define apply-subst-to-type
(lambda (ty)
(cases type ty
(int-type () (int-type))
(bool-type () (bool-type))
(void-type () (void-type))
(proc-type (t1 t2)
(proc-type
(apply-subst-to-type t1)
(apply-subst-to-type t2)))
(refto-type (ty)
(refto-type
(apply-subst-to-type ty)))
(tvar-type (sn)
(if (hash-table-exists? the-subst ty)
(apply-subst-to-type (hash-table-ref the-subst ty))
ty)))))
;;;;;;;;;;;;;;;; syntactic tests and observers ;;;;;;;;;;;;;;;;
(define atomic-type?
(lambda (ty)
(cases type ty
(proc-type (ty1 ty2) #f)
(tvar-type (sn) #f)
(else #t))))
(define proc-type?
(lambda (ty)
(cases type ty
(proc-type (t1 t2) #t)
(else #f))))
(define tvar-type?
(lambda (ty)
(cases type ty
(tvar-type (serial-number) #t)
(else #f))))
(define substitution?
(list-of (pair-of tvar-type? type?)))
(define proc-type->arg-type
(lambda (ty)
(cases type ty
(proc-type (arg-type result-type) arg-type)
(else (error 'proc-type->arg-type
"Not a proc type: ~s" ty)))))
(define proc-type->result-type
(lambda (ty)
(cases type ty
(proc-type (arg-type result-type) result-type)
(else (error 'proc-type->result-types
"Not a proc type: ~s" ty)))))
;; type-to-external-form : Type -> List
(define type-to-external-form
(lambda (ty)
(cases type ty
(int-type () 'int)
(bool-type () 'bool)
(void-type () 'void)
(proc-type (arg-type result-type)
(list
(type-to-external-form arg-type)
'->
(type-to-external-form result-type)))
(refto-type (arg-type)
(list
'refto
(type-to-external-form arg-type)))
(tvar-type (serial-number)
(string->symbol
(string-append
"tvar"
(number->string serial-number)))))))
;; unifier : Type * Type * Subst * Exp -> void OR Fails
(define unifier
(lambda (ty1 ty2 exp)
(let ((ty1 (apply-subst-to-type ty1))
(ty2 (apply-subst-to-type ty2)))
(cond
((equal? ty1 ty2) the-subst)
((tvar-type? ty1)
(if (no-occurrence? ty1 ty2)
(extend-subst ty1 ty2)
(report-no-occurrence-violation ty1 ty2 exp)))
((tvar-type? ty2)
(if (no-occurrence? ty2 ty1)
(extend-subst ty2 ty1)
(report-no-occurrence-violation ty2 ty1 exp)))
((and (proc-type? ty1) (proc-type? ty2))
(begin
(unifier
(proc-type->arg-type ty1)
(proc-type->arg-type ty2)
exp)
(unifier
(proc-type->result-type ty1)
(proc-type->result-type ty2)
exp)))
(else (report-unification-failure ty1 ty2 exp))))))
(define report-unification-failure
(lambda (ty1 ty2 exp)
(error 'unification-failure
"Type mismatch: ~s doesn't match ~s in ~s~%"
(type-to-external-form ty1)
(type-to-external-form ty2)
exp)))
(define report-no-occurrence-violation
(lambda (ty1 ty2 exp)
(error 'check-no-occurence!
"Can't unify: type variable ~s occurs in type ~s in expression ~s~%"
(type-to-external-form ty1)
(type-to-external-form ty2)
exp)))
;; no-occurrence? : Tvar * Type -> Bool
;; usage: Is there an occurrence of tvar in ty?
(define no-occurrence?
(lambda (tvar ty)
(cases type ty
(int-type () #t)
(bool-type () #t)
(void-type () #t)
(refto-type (ty)
(no-occurrence? tvar ty))
(proc-type (arg-type result-type)
(and
(no-occurrence? tvar arg-type)
(no-occurrence? tvar result-type)))
(tvar-type (serial-number) (not (equal? tvar ty))))))
The Type Checker ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
;; type-of-program : Program -> Type
(define type-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(let ((exp-type (type-of exp1 (init-tenv))))
(apply-subst-to-type exp-type))))))
;; type-of : Exp * Tenv * Subst -> Type
(define type-of
(lambda (exp tenv)
(cases expression exp
(const-exp (num) (int-type))
(zero?-exp (exp1)
(let ((type1 (type-of exp1 tenv)))
(begin
(unifier type1 (int-type) exp)
(bool-type))))
(diff-exp (exp1 exp2)
(let ((type1 (type-of exp1 tenv))
(type2 (type-of exp2 tenv)))
(begin
(unifier type1 (int-type) exp1)
(unifier type2 (int-type) exp2)
(int-type))))
(if-exp (exp1 exp2 exp3)
(let ((type1 (type-of exp1 tenv))
(type2 (type-of exp2 tenv))
(type3 (type-of exp3 tenv)))
(begin
(unifier type1 (bool-type) exp1)
(unifier type2 type3 exp2)
type2)))
(var-exp (var) (apply-tenv tenv var))
(let-exp (var exp1 body)
(let ((type1 (type-of exp1 tenv)))
(type-of body (extend-tenv var type1 tenv))))
(proc-exp (var otype body)
(let ((arg-type (otype->type otype)))
(let ((body-type (type-of body (extend-tenv var arg-type tenv))))
(proc-type arg-type body-type))))
(call-exp (rator rand)
(let ((result-type (fresh-tvar-type)))
(let ((rator-type (type-of rator tenv))
(rand-type (type-of rand tenv)))
(begin
(unifier rator-type (proc-type rand-type result-type) exp)
result-type))))
(letrec-exp (proc-result-otype proc-name bvar proc-arg-otype
proc-body letrec-body)
(let ((proc-result-type (otype->type proc-result-otype))
(proc-arg-type (otype->type proc-arg-otype)))
(let ((tenv-for-letrec-body
(extend-tenv proc-name
(proc-type proc-arg-type proc-result-type)
tenv)))
(let ((proc-body-type
(type-of proc-body (extend-tenv bvar
proc-arg-type
tenv-for-letrec-body))))
(begin
(unifier proc-body-type proc-result-type proc-body)
(type-of letrec-body tenv-for-letrec-body))))))
;; new stuff
(newref-exp (exp1)
(let ((exp-type (type-of exp1 tenv)))
(refto-type exp-type)))
(deref-exp (exp1)
(let ((exp-type (type-of exp1 tenv)))
(cases type exp-type
(refto-type (arg-type)
arg-type)
(else
(report-deref-not-aref exp1)))))
(setref-exp (exp1 exp2)
(let ((exp-type (type-of exp1 tenv)))
(cases type exp-type
(refto-type (arg-type)
(void-type))
(else
(report-setref-not-aref exp1)))))
)))
(define report-deref-not-aref
(lambda (arg)
(error 'type-of-expression
"Address of deref is not refto-type: ~% ~s"
arg)))
(define report-setref-not-aref
(lambda (arg)
(error 'type-of-expression
"Address of setref is not a refto-type: ~% ~s"
arg)))
(define-datatype environment environment?
(empty-env)
(extend-env
(bvar symbol?)
(bval expval?)
(saved-env environment?))
(extend-env-rec
(p-name symbol?)
(b-var symbol?)
(p-body expression?)
(saved-env environment?)))
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
(define apply-env
(lambda (env search-sym)
(cases environment env
(empty-env ()
(error 'apply-env "No binding for ~s" search-sym))
(extend-env (bvar bval saved-env)
(if (eqv? search-sym bvar)
bval
(apply-env saved-env search-sym)))
(extend-env-rec (p-name b-var p-body saved-env)
(if (eqv? search-sym p-name)
(proc-val (procedure b-var p-body env))
(apply-env saved-env search-sym))))))
;;;;;;;;;;;;;;;;; type environments ;;;;;;;;;;;;;;;;
;; why are these separated?
(define-datatype type-environment type-environment?
(empty-tenv-record)
(extended-tenv-record
(sym symbol?)
(type type?)
(tenv type-environment?)))
(define empty-tenv empty-tenv-record)
(define extend-tenv extended-tenv-record)
(define apply-tenv
(lambda (tenv sym)
(cases type-environment tenv
(empty-tenv-record ()
(error 'apply-tenv "Unbound variable ~s" sym))
(extended-tenv-record (sym1 val1 old-env)
(if (eqv? sym sym1)
val1
(apply-tenv old-env sym))))))
(define init-tenv
(lambda ()
(extend-tenv 'x (int-type)
(extend-tenv 'v (int-type)
(extend-tenv 'i (int-type)
(empty-tenv))))))
;; fresh-tvar-type : () -> Type
(define fresh-tvar-type
(let ((sn 0))
(lambda ()
(set! sn (+ sn 1))
(tvar-type sn))))
;; otype->type : OptionalType -> Type
(define otype->type
(lambda (otype)
(cases optional-type otype
(no-type () (fresh-tvar-type))
(a-type (ty) ty))))
;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;;
value - of - program : Program - > ExpVal
(define value-of-program
(lambda (pgm)
(begin
(initialize-store!)
(cases program pgm
(a-program (body)
(value-of body (init-env)))))))
value - of : Exp * Env - > ExpVal
(define value-of
(lambda (exp env)
(cases expression exp
(const-exp (num) (num-val num))
(var-exp (var) (apply-env env var))
(diff-exp (exp1 exp2)
(let ((val1
(expval->num
(value-of exp1 env)))
(val2
(expval->num
(value-of exp2 env))))
(num-val
(- val1 val2))))
(zero?-exp (exp1)
(let ((val1 (expval->num (value-of exp1 env))))
(if (zero? val1)
(bool-val #t)
(bool-val #f))))
(if-exp (exp0 exp1 exp2)
(if (expval->bool (value-of exp0 env))
(value-of exp1 env)
(value-of exp2 env)))
(let-exp (var exp1 body)
(let ((val (value-of exp1 env)))
(value-of body
(extend-env var val env))))
(proc-exp (bvar ty body)
(proc-val
(procedure bvar body env)))
(call-exp (rator rand)
(let ((proc (expval->proc (value-of rator env)))
(arg (value-of rand env)))
(apply-procedure proc arg)))
(letrec-exp (ty1 p-name b-var ty2 p-body letrec-body)
(value-of letrec-body
(extend-env-rec p-name b-var p-body env)))
;; begin new stuff
(newref-exp (exp1)
(let ((v1 (value-of exp1 env)))
(ref-val (newref v1))))
(deref-exp (exp1)
(let ((v1 (value-of exp1 env)))
(deref (expval->ref v1))))
(setref-exp (exp1 exp2)
(let ((ref1 (expval->ref (value-of exp1 env)))
(v2 (value-of exp2 env)))
(begin
(setref! ref1 v2)
(num-val 1))))
)))
apply - procedure : Proc * ExpVal - > ExpVal
(define apply-procedure
(lambda (proc1 arg)
(cases proc proc1
(procedure (var body saved-env)
(value-of body (extend-env var arg saved-env))))))
(check "let demo = proc(x : ?) x in -((demo 1), 0)")
(check "letrec ? f (x : ?) = (f x) in f")
(check "letrec ? f (x : ?) = (f x) in proc (n : ?) (f -(n,1))")
(check "letrec ? even (odd : ?) = proc (x : ?) if zero?(x) then 1 else (odd -(x,1))
in letrec ? odd(x : ?) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)")
(run "newref(0)")
(run "let demo = proc(x : ?) x in -((demo 1), 0)")
(run "letrec ? f (x : ?) = (f x) in f")
(run "letrec ? f (x : ?) = (f x) in proc (n : ?) (f -(n,1))")
(run "letrec ? even (odd : ?) = proc (x : ?) if zero?(x) then 1 else (odd -(x,1))
in letrec ? odd(x : ?) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)")
(add-test! '(newref-test "let x = newref(0) in letrec int even(d : int) = d in (even 1)" 1))
(check "let x = newref(newref(0)) in deref(x)")
(check "let x = newref(0) in let y = setref(x, 10) in deref(x)")
(run "let x = newref(0) in let y = setref(x, 10) in deref(x)")
(add-test! '(show-allocation-1 "
let x = newref(22)
in let f = proc (z : int) let zz = newref(-(z,deref(x))) in deref(zz)
in -((f 66), (f 55))"
11))
(run-all)
(check-all-inferred)
| null | https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/ch7/26.scm | scheme | begin new stuff
end new stuff
new stuff
sllgen boilerplate ;;;;;;;;;;;;;;;;
new stuff, use hashtable as substitution.
new implementation of subst
syntactic tests and observers ;;;;;;;;;;;;;;;;
type-to-external-form : Type -> List
unifier : Type * Type * Subst * Exp -> void OR Fails
no-occurrence? : Tvar * Type -> Bool
usage: Is there an occurrence of tvar in ty?
; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
type-of-program : Program -> Type
type-of : Exp * Tenv * Subst -> Type
new stuff
type environments ;;;;;;;;;;;;;;;;
why are these separated?
fresh-tvar-type : () -> Type
otype->type : OptionalType -> Type
the interpreter ;;;;;;;;;;;;;;;;
begin new stuff | (load-relative "../libs/init.scm")
(load-relative "./base/test.scm")
(load-relative "./base/subst.scm")
(load-relative "./base/inferred-cases.scm")
(load-relative "./base/data-structures.scm")
(load-relative "./base/equal-type.scm")
(load-relative "./base/store.scm")
Extend the inferencer to handle EXPLICIT - REFS , as in exercise 7.10 .
(define-datatype expval expval?
(num-val
(value number?))
(bool-val
(boolean boolean?))
(proc-val
(proc proc?))
(ref-val
(ref reference?)))
(define the-lexical-spec
'((whitespace (whitespace) skip)
(comment ("%" (arbno (not #\newline))) skip)
(identifier
(letter (arbno (or letter digit "_" "-" "?")))
symbol)
(number (digit (arbno digit)) number)
(number ("-" digit (arbno digit)) number)
))
(define the-grammar
'((program (expression) a-program)
(expression (number) const-exp)
(expression
("-" "(" expression "," expression ")")
diff-exp)
(expression
("zero?" "(" expression ")")
zero?-exp)
(expression
("if" expression "then" expression "else" expression)
if-exp)
(expression (identifier) var-exp)
(expression
("let" identifier "=" expression "in" expression)
let-exp)
(expression
("proc" "(" identifier ":" optional-type ")" expression)
proc-exp)
(expression
("(" expression expression ")")
call-exp)
(expression
("newref" "(" expression ")")
newref-exp)
(expression
("deref" "(" expression ")")
deref-exp)
(expression
("setref" "(" expression "," expression ")")
setref-exp)
(expression
("letrec"
optional-type identifier "(" identifier ":" optional-type ")"
"=" expression "in" expression)
letrec-exp)
(optional-type
("?")
no-type)
(optional-type
(type)
a-type)
(type
("int")
int-type)
(type
("bool")
bool-type)
(type
("(" type "->" type ")")
proc-type)
(type
("%tvar-type" number)
tvar-type)
(type
("refto" type)
refto-type)
(type
("void")
void-type)
))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define show-the-datatypes
(lambda () (sllgen:list-define-datatypes the-lexical-spec the-grammar)))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define just-scan
(sllgen:make-string-scanner the-lexical-spec the-grammar))
(define the-subst (make-hash-table))
(define extend-subst
(lambda (tvar ty)
(set! (hash-table-ref the-subst tvar) ty)))
(define apply-subst-to-type
(lambda (ty)
(cases type ty
(int-type () (int-type))
(bool-type () (bool-type))
(void-type () (void-type))
(proc-type (t1 t2)
(proc-type
(apply-subst-to-type t1)
(apply-subst-to-type t2)))
(refto-type (ty)
(refto-type
(apply-subst-to-type ty)))
(tvar-type (sn)
(if (hash-table-exists? the-subst ty)
(apply-subst-to-type (hash-table-ref the-subst ty))
ty)))))
(define atomic-type?
(lambda (ty)
(cases type ty
(proc-type (ty1 ty2) #f)
(tvar-type (sn) #f)
(else #t))))
(define proc-type?
(lambda (ty)
(cases type ty
(proc-type (t1 t2) #t)
(else #f))))
(define tvar-type?
(lambda (ty)
(cases type ty
(tvar-type (serial-number) #t)
(else #f))))
(define substitution?
(list-of (pair-of tvar-type? type?)))
(define proc-type->arg-type
(lambda (ty)
(cases type ty
(proc-type (arg-type result-type) arg-type)
(else (error 'proc-type->arg-type
"Not a proc type: ~s" ty)))))
(define proc-type->result-type
(lambda (ty)
(cases type ty
(proc-type (arg-type result-type) result-type)
(else (error 'proc-type->result-types
"Not a proc type: ~s" ty)))))
(define type-to-external-form
(lambda (ty)
(cases type ty
(int-type () 'int)
(bool-type () 'bool)
(void-type () 'void)
(proc-type (arg-type result-type)
(list
(type-to-external-form arg-type)
'->
(type-to-external-form result-type)))
(refto-type (arg-type)
(list
'refto
(type-to-external-form arg-type)))
(tvar-type (serial-number)
(string->symbol
(string-append
"tvar"
(number->string serial-number)))))))
(define unifier
(lambda (ty1 ty2 exp)
(let ((ty1 (apply-subst-to-type ty1))
(ty2 (apply-subst-to-type ty2)))
(cond
((equal? ty1 ty2) the-subst)
((tvar-type? ty1)
(if (no-occurrence? ty1 ty2)
(extend-subst ty1 ty2)
(report-no-occurrence-violation ty1 ty2 exp)))
((tvar-type? ty2)
(if (no-occurrence? ty2 ty1)
(extend-subst ty2 ty1)
(report-no-occurrence-violation ty2 ty1 exp)))
((and (proc-type? ty1) (proc-type? ty2))
(begin
(unifier
(proc-type->arg-type ty1)
(proc-type->arg-type ty2)
exp)
(unifier
(proc-type->result-type ty1)
(proc-type->result-type ty2)
exp)))
(else (report-unification-failure ty1 ty2 exp))))))
(define report-unification-failure
(lambda (ty1 ty2 exp)
(error 'unification-failure
"Type mismatch: ~s doesn't match ~s in ~s~%"
(type-to-external-form ty1)
(type-to-external-form ty2)
exp)))
(define report-no-occurrence-violation
(lambda (ty1 ty2 exp)
(error 'check-no-occurence!
"Can't unify: type variable ~s occurs in type ~s in expression ~s~%"
(type-to-external-form ty1)
(type-to-external-form ty2)
exp)))
(define no-occurrence?
(lambda (tvar ty)
(cases type ty
(int-type () #t)
(bool-type () #t)
(void-type () #t)
(refto-type (ty)
(no-occurrence? tvar ty))
(proc-type (arg-type result-type)
(and
(no-occurrence? tvar arg-type)
(no-occurrence? tvar result-type)))
(tvar-type (serial-number) (not (equal? tvar ty))))))
(define type-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(let ((exp-type (type-of exp1 (init-tenv))))
(apply-subst-to-type exp-type))))))
(define type-of
(lambda (exp tenv)
(cases expression exp
(const-exp (num) (int-type))
(zero?-exp (exp1)
(let ((type1 (type-of exp1 tenv)))
(begin
(unifier type1 (int-type) exp)
(bool-type))))
(diff-exp (exp1 exp2)
(let ((type1 (type-of exp1 tenv))
(type2 (type-of exp2 tenv)))
(begin
(unifier type1 (int-type) exp1)
(unifier type2 (int-type) exp2)
(int-type))))
(if-exp (exp1 exp2 exp3)
(let ((type1 (type-of exp1 tenv))
(type2 (type-of exp2 tenv))
(type3 (type-of exp3 tenv)))
(begin
(unifier type1 (bool-type) exp1)
(unifier type2 type3 exp2)
type2)))
(var-exp (var) (apply-tenv tenv var))
(let-exp (var exp1 body)
(let ((type1 (type-of exp1 tenv)))
(type-of body (extend-tenv var type1 tenv))))
(proc-exp (var otype body)
(let ((arg-type (otype->type otype)))
(let ((body-type (type-of body (extend-tenv var arg-type tenv))))
(proc-type arg-type body-type))))
(call-exp (rator rand)
(let ((result-type (fresh-tvar-type)))
(let ((rator-type (type-of rator tenv))
(rand-type (type-of rand tenv)))
(begin
(unifier rator-type (proc-type rand-type result-type) exp)
result-type))))
(letrec-exp (proc-result-otype proc-name bvar proc-arg-otype
proc-body letrec-body)
(let ((proc-result-type (otype->type proc-result-otype))
(proc-arg-type (otype->type proc-arg-otype)))
(let ((tenv-for-letrec-body
(extend-tenv proc-name
(proc-type proc-arg-type proc-result-type)
tenv)))
(let ((proc-body-type
(type-of proc-body (extend-tenv bvar
proc-arg-type
tenv-for-letrec-body))))
(begin
(unifier proc-body-type proc-result-type proc-body)
(type-of letrec-body tenv-for-letrec-body))))))
(newref-exp (exp1)
(let ((exp-type (type-of exp1 tenv)))
(refto-type exp-type)))
(deref-exp (exp1)
(let ((exp-type (type-of exp1 tenv)))
(cases type exp-type
(refto-type (arg-type)
arg-type)
(else
(report-deref-not-aref exp1)))))
(setref-exp (exp1 exp2)
(let ((exp-type (type-of exp1 tenv)))
(cases type exp-type
(refto-type (arg-type)
(void-type))
(else
(report-setref-not-aref exp1)))))
)))
(define report-deref-not-aref
(lambda (arg)
(error 'type-of-expression
"Address of deref is not refto-type: ~% ~s"
arg)))
(define report-setref-not-aref
(lambda (arg)
(error 'type-of-expression
"Address of setref is not a refto-type: ~% ~s"
arg)))
(define-datatype environment environment?
(empty-env)
(extend-env
(bvar symbol?)
(bval expval?)
(saved-env environment?))
(extend-env-rec
(p-name symbol?)
(b-var symbol?)
(p-body expression?)
(saved-env environment?)))
(define init-env
(lambda ()
(extend-env
'i (num-val 1)
(extend-env
'v (num-val 5)
(extend-env
'x (num-val 10)
(empty-env))))))
(define apply-env
(lambda (env search-sym)
(cases environment env
(empty-env ()
(error 'apply-env "No binding for ~s" search-sym))
(extend-env (bvar bval saved-env)
(if (eqv? search-sym bvar)
bval
(apply-env saved-env search-sym)))
(extend-env-rec (p-name b-var p-body saved-env)
(if (eqv? search-sym p-name)
(proc-val (procedure b-var p-body env))
(apply-env saved-env search-sym))))))
(define-datatype type-environment type-environment?
(empty-tenv-record)
(extended-tenv-record
(sym symbol?)
(type type?)
(tenv type-environment?)))
(define empty-tenv empty-tenv-record)
(define extend-tenv extended-tenv-record)
(define apply-tenv
(lambda (tenv sym)
(cases type-environment tenv
(empty-tenv-record ()
(error 'apply-tenv "Unbound variable ~s" sym))
(extended-tenv-record (sym1 val1 old-env)
(if (eqv? sym sym1)
val1
(apply-tenv old-env sym))))))
(define init-tenv
(lambda ()
(extend-tenv 'x (int-type)
(extend-tenv 'v (int-type)
(extend-tenv 'i (int-type)
(empty-tenv))))))
(define fresh-tvar-type
(let ((sn 0))
(lambda ()
(set! sn (+ sn 1))
(tvar-type sn))))
(define otype->type
(lambda (otype)
(cases optional-type otype
(no-type () (fresh-tvar-type))
(a-type (ty) ty))))
value - of - program : Program - > ExpVal
(define value-of-program
(lambda (pgm)
(begin
(initialize-store!)
(cases program pgm
(a-program (body)
(value-of body (init-env)))))))
value - of : Exp * Env - > ExpVal
(define value-of
(lambda (exp env)
(cases expression exp
(const-exp (num) (num-val num))
(var-exp (var) (apply-env env var))
(diff-exp (exp1 exp2)
(let ((val1
(expval->num
(value-of exp1 env)))
(val2
(expval->num
(value-of exp2 env))))
(num-val
(- val1 val2))))
(zero?-exp (exp1)
(let ((val1 (expval->num (value-of exp1 env))))
(if (zero? val1)
(bool-val #t)
(bool-val #f))))
(if-exp (exp0 exp1 exp2)
(if (expval->bool (value-of exp0 env))
(value-of exp1 env)
(value-of exp2 env)))
(let-exp (var exp1 body)
(let ((val (value-of exp1 env)))
(value-of body
(extend-env var val env))))
(proc-exp (bvar ty body)
(proc-val
(procedure bvar body env)))
(call-exp (rator rand)
(let ((proc (expval->proc (value-of rator env)))
(arg (value-of rand env)))
(apply-procedure proc arg)))
(letrec-exp (ty1 p-name b-var ty2 p-body letrec-body)
(value-of letrec-body
(extend-env-rec p-name b-var p-body env)))
(newref-exp (exp1)
(let ((v1 (value-of exp1 env)))
(ref-val (newref v1))))
(deref-exp (exp1)
(let ((v1 (value-of exp1 env)))
(deref (expval->ref v1))))
(setref-exp (exp1 exp2)
(let ((ref1 (expval->ref (value-of exp1 env)))
(v2 (value-of exp2 env)))
(begin
(setref! ref1 v2)
(num-val 1))))
)))
apply - procedure : Proc * ExpVal - > ExpVal
(define apply-procedure
(lambda (proc1 arg)
(cases proc proc1
(procedure (var body saved-env)
(value-of body (extend-env var arg saved-env))))))
(check "let demo = proc(x : ?) x in -((demo 1), 0)")
(check "letrec ? f (x : ?) = (f x) in f")
(check "letrec ? f (x : ?) = (f x) in proc (n : ?) (f -(n,1))")
(check "letrec ? even (odd : ?) = proc (x : ?) if zero?(x) then 1 else (odd -(x,1))
in letrec ? odd(x : ?) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)")
(run "newref(0)")
(run "let demo = proc(x : ?) x in -((demo 1), 0)")
(run "letrec ? f (x : ?) = (f x) in f")
(run "letrec ? f (x : ?) = (f x) in proc (n : ?) (f -(n,1))")
(run "letrec ? even (odd : ?) = proc (x : ?) if zero?(x) then 1 else (odd -(x,1))
in letrec ? odd(x : ?) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)")
(add-test! '(newref-test "let x = newref(0) in letrec int even(d : int) = d in (even 1)" 1))
(check "let x = newref(newref(0)) in deref(x)")
(check "let x = newref(0) in let y = setref(x, 10) in deref(x)")
(run "let x = newref(0) in let y = setref(x, 10) in deref(x)")
(add-test! '(show-allocation-1 "
let x = newref(22)
in let f = proc (z : int) let zz = newref(-(z,deref(x))) in deref(zz)
in -((f 66), (f 55))"
11))
(run-all)
(check-all-inferred)
|
efe5f5cb1de5aefb9ff4387665632974eac880b975faf4cc2d2c1163320bb290 | lojic/LearningRacket | day16.rkt | #lang racket
(require threading)
(define (parse-input fname)
(match-let ([ (list fields ticket others) (~> (string-split (file->string fname) "\n\n")
(map (curryr string-split "\n") _)) ])
(list
(map parse-field fields) (parse-ticket (cadr ticket)) (map parse-ticket (cdr others)))))
(define (parse-field str)
(match-let ([ (list name ranges) (string-split str ": ") ])
(cons name (~> (string-split ranges " or ")
(map (compose (curry map string->number) (curryr string-split "-")) _)
(map (λ (l) (cons (car l) (cadr l))) _)))))
(define (parse-ticket str) (map string->number (string-split str ",")))
(define (run part fname) (apply part (parse-input fname)))
(define (valid? n field)
(define (in-range? r) (<= (car r) n (cdr r)))
(ormap in-range? (cdr field)))
(define (all-invalid? fields n) (not (ormap (curry valid? n) fields)))
(define (invalid-fields fields lst [ invalid '() ])
(foldl (λ (n inv) (if (all-invalid? fields n) (cons n inv) inv)) '() lst))
(define (get-positions fields ticket others lst)
(let loop ([ lst lst ] [ result '() ])
(if (null? lst)
result
(let-values ([ (singles rest) (partition (compose (curry = 1) length car) lst) ])
(define (remove-field pair)
(cons (filter (λ (name) (not (member name (map caar singles)))) (car pair)) (cdr pair)))
(loop (map remove-field rest) (append singles result))))))
(define ((reduce-fields fields) ticket positions)
(for/list ([ field-names (in-list positions) ]
[ n (in-list ticket) ])
(filter (λ (name) (valid? n (assoc name fields))) field-names)))
(define (part1 fields _ others) (for/sum ([ lst others ]) (apply + (invalid-fields fields lst))))
(define (part2 fields ticket others)
(~> (for/list ([ i (in-naturals) ]
[ pos (foldl (reduce-fields fields)
(for/list ([ i (in-range (length ticket)) ]) (map car fields))
(filter (λ (t) (null? (invalid-fields fields t))) others)) ])
(cons pos i))
(get-positions fields ticket others _)
(map (λ (pair) (cons (caar pair) (cdr pair))) _)
(filter (λ (pair) (string-contains? (car pair) "departure")) _)
(map (λ (pair) (list-ref ticket (cdr pair))) _)
(apply * _)))
(module+ test (require rackunit)
(check-equal? (run part1 "day16.txt") 29019)
(check-equal? (run part2 "day16.txt") 517827547723))
| null | https://raw.githubusercontent.com/lojic/LearningRacket/eb0e75b0e16d3e0a91b8fa6612e2678a9e12e8c7/advent-of-code-2020/day16.rkt | racket | #lang racket
(require threading)
(define (parse-input fname)
(match-let ([ (list fields ticket others) (~> (string-split (file->string fname) "\n\n")
(map (curryr string-split "\n") _)) ])
(list
(map parse-field fields) (parse-ticket (cadr ticket)) (map parse-ticket (cdr others)))))
(define (parse-field str)
(match-let ([ (list name ranges) (string-split str ": ") ])
(cons name (~> (string-split ranges " or ")
(map (compose (curry map string->number) (curryr string-split "-")) _)
(map (λ (l) (cons (car l) (cadr l))) _)))))
(define (parse-ticket str) (map string->number (string-split str ",")))
(define (run part fname) (apply part (parse-input fname)))
(define (valid? n field)
(define (in-range? r) (<= (car r) n (cdr r)))
(ormap in-range? (cdr field)))
(define (all-invalid? fields n) (not (ormap (curry valid? n) fields)))
(define (invalid-fields fields lst [ invalid '() ])
(foldl (λ (n inv) (if (all-invalid? fields n) (cons n inv) inv)) '() lst))
(define (get-positions fields ticket others lst)
(let loop ([ lst lst ] [ result '() ])
(if (null? lst)
result
(let-values ([ (singles rest) (partition (compose (curry = 1) length car) lst) ])
(define (remove-field pair)
(cons (filter (λ (name) (not (member name (map caar singles)))) (car pair)) (cdr pair)))
(loop (map remove-field rest) (append singles result))))))
(define ((reduce-fields fields) ticket positions)
(for/list ([ field-names (in-list positions) ]
[ n (in-list ticket) ])
(filter (λ (name) (valid? n (assoc name fields))) field-names)))
(define (part1 fields _ others) (for/sum ([ lst others ]) (apply + (invalid-fields fields lst))))
(define (part2 fields ticket others)
(~> (for/list ([ i (in-naturals) ]
[ pos (foldl (reduce-fields fields)
(for/list ([ i (in-range (length ticket)) ]) (map car fields))
(filter (λ (t) (null? (invalid-fields fields t))) others)) ])
(cons pos i))
(get-positions fields ticket others _)
(map (λ (pair) (cons (caar pair) (cdr pair))) _)
(filter (λ (pair) (string-contains? (car pair) "departure")) _)
(map (λ (pair) (list-ref ticket (cdr pair))) _)
(apply * _)))
(module+ test (require rackunit)
(check-equal? (run part1 "day16.txt") 29019)
(check-equal? (run part2 "day16.txt") 517827547723))
|
|
164981e8e0552efa97b6cbb1c40894143011caea3c45efb42027478fd6987bb2 | dradtke/Lisp-Text-Editor | network.lisp | ;;;
;;; Low-level networking implementations
;;;
(in-package #:ql-network)
(definterface host-address (host)
(:implementation t
host)
(:implementation sbcl
(ql-sbcl:host-ent-address (ql-sbcl:get-host-by-name host))))
(definterface open-connection (host port)
(:documentation "Open and return a network connection to HOST on the
given PORT.")
(:implementation t
(declare (ignore host port))
(error "Sorry, quicklisp in implementation ~S is not supported yet."
(lisp-implementation-type)))
(:implementation allegro
(ql-allegro:make-socket :remote-host host
:remote-port port))
(:implementation abcl
(let ((socket (qlb-abcl:make-socket host port)))
(qlb-abcl:get-socket-stream socket :element-type '(unsigned-byte 8))))
(:implementation ccl
(ql-ccl:make-socket :remote-host host
:remote-port port))
(:implementation clisp
(ql-clisp:socket-connect port host :element-type '(unsigned-byte 8)))
(:implementation cmucl
(let ((fd (ql-cmucl:connect-to-inet-socket host port)))
(ql-cmucl:make-fd-stream fd
:element-type '(unsigned-byte 8)
:binary-stream-p t
:input t
:output t)))
(:implementation scl
(let ((fd (ql-scl:connect-to-inet-socket host port)))
(ql-scl:make-fd-stream fd
:element-type '(unsigned-byte 8)
:input t
:output t)))
(:implementation ecl
(let* ((endpoint (ql-ecl:host-ent-address
(ql-ecl:get-host-by-name host)))
(socket (make-instance 'ql-ecl:inet-socket
:protocol :tcp
:type :stream)))
(ql-ecl:socket-connect socket endpoint port)
(ql-ecl:socket-make-stream socket
:element-type '(unsigned-byte 8)
:input t
:output t
:buffering :full)))
(:implementation lispworks
(ql-lispworks:open-tcp-stream host port
:direction :io
:read-timeout nil
:element-type '(unsigned-byte 8)
:timeout 5))
(:implementation sbcl
(let* ((endpoint (ql-sbcl:host-ent-address
(ql-sbcl:get-host-by-name host)))
(socket (make-instance 'ql-sbcl:inet-socket
:protocol :tcp
:type :stream)))
(ql-sbcl:socket-connect socket endpoint port)
(ql-sbcl:socket-make-stream socket
:element-type '(unsigned-byte 8)
:input t
:output t
:buffering :full))))
(definterface read-octets (buffer connection)
(:documentation "Read from CONNECTION into BUFFER. Returns the
number of octets read.")
(:implementation t
(read-sequence buffer connection))
(:implementation allegro
(ql-allegro:read-vector buffer connection))
(:implementation clisp
(ql-clisp:read-byte-sequence buffer connection
:no-hang nil
:interactive t)))
(definterface write-octets (buffer connection)
(:documentation "Write the contents of BUFFER to CONNECTION.")
(:implementation t
(write-sequence buffer connection)
(finish-output connection)))
(definterface close-connection (connection)
(:implementation t
(ignore-errors (close connection))))
(definterface call-with-connection (host port fun)
(:documentation "Establish a network connection to HOST on PORT and
call FUN with that connection as the only argument. Unconditionally
closes the connection afterwareds via CLOSE-CONNECTION in an
unwind-protect. See also WITH-CONNECTION.")
(:implementation t
(let (connection)
(unwind-protect
(progn
(setf connection (open-connection host port))
(funcall fun connection))
(when connection
(close-connection connection))))))
(defmacro with-connection ((connection host port) &body body)
`(call-with-connection ,host ,port (lambda (,connection) ,@body)))
| null | https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/quicklisp/quicklisp/network.lisp | lisp |
Low-level networking implementations
|
(in-package #:ql-network)
(definterface host-address (host)
(:implementation t
host)
(:implementation sbcl
(ql-sbcl:host-ent-address (ql-sbcl:get-host-by-name host))))
(definterface open-connection (host port)
(:documentation "Open and return a network connection to HOST on the
given PORT.")
(:implementation t
(declare (ignore host port))
(error "Sorry, quicklisp in implementation ~S is not supported yet."
(lisp-implementation-type)))
(:implementation allegro
(ql-allegro:make-socket :remote-host host
:remote-port port))
(:implementation abcl
(let ((socket (qlb-abcl:make-socket host port)))
(qlb-abcl:get-socket-stream socket :element-type '(unsigned-byte 8))))
(:implementation ccl
(ql-ccl:make-socket :remote-host host
:remote-port port))
(:implementation clisp
(ql-clisp:socket-connect port host :element-type '(unsigned-byte 8)))
(:implementation cmucl
(let ((fd (ql-cmucl:connect-to-inet-socket host port)))
(ql-cmucl:make-fd-stream fd
:element-type '(unsigned-byte 8)
:binary-stream-p t
:input t
:output t)))
(:implementation scl
(let ((fd (ql-scl:connect-to-inet-socket host port)))
(ql-scl:make-fd-stream fd
:element-type '(unsigned-byte 8)
:input t
:output t)))
(:implementation ecl
(let* ((endpoint (ql-ecl:host-ent-address
(ql-ecl:get-host-by-name host)))
(socket (make-instance 'ql-ecl:inet-socket
:protocol :tcp
:type :stream)))
(ql-ecl:socket-connect socket endpoint port)
(ql-ecl:socket-make-stream socket
:element-type '(unsigned-byte 8)
:input t
:output t
:buffering :full)))
(:implementation lispworks
(ql-lispworks:open-tcp-stream host port
:direction :io
:read-timeout nil
:element-type '(unsigned-byte 8)
:timeout 5))
(:implementation sbcl
(let* ((endpoint (ql-sbcl:host-ent-address
(ql-sbcl:get-host-by-name host)))
(socket (make-instance 'ql-sbcl:inet-socket
:protocol :tcp
:type :stream)))
(ql-sbcl:socket-connect socket endpoint port)
(ql-sbcl:socket-make-stream socket
:element-type '(unsigned-byte 8)
:input t
:output t
:buffering :full))))
(definterface read-octets (buffer connection)
(:documentation "Read from CONNECTION into BUFFER. Returns the
number of octets read.")
(:implementation t
(read-sequence buffer connection))
(:implementation allegro
(ql-allegro:read-vector buffer connection))
(:implementation clisp
(ql-clisp:read-byte-sequence buffer connection
:no-hang nil
:interactive t)))
(definterface write-octets (buffer connection)
(:documentation "Write the contents of BUFFER to CONNECTION.")
(:implementation t
(write-sequence buffer connection)
(finish-output connection)))
(definterface close-connection (connection)
(:implementation t
(ignore-errors (close connection))))
(definterface call-with-connection (host port fun)
(:documentation "Establish a network connection to HOST on PORT and
call FUN with that connection as the only argument. Unconditionally
closes the connection afterwareds via CLOSE-CONNECTION in an
unwind-protect. See also WITH-CONNECTION.")
(:implementation t
(let (connection)
(unwind-protect
(progn
(setf connection (open-connection host port))
(funcall fun connection))
(when connection
(close-connection connection))))))
(defmacro with-connection ((connection host port) &body body)
`(call-with-connection ,host ,port (lambda (,connection) ,@body)))
|
3bd63ed15dc291620f317516a730709ab94083e6e16dd359fb0b47062ca6f776 | FranklinChen/hugs98-plus-Sep2006 | PolyLazy.hs | module Text.ParserCombinators.PolyLazy
* A Parser datatype parameterised on arbitrary token type .
Parsers do not return explicit failure . An exception is
-- raised instead. This allows partial results to be returned
-- before a full parse is complete.
datatype , instance of : Functor , Monad
: : t a - > [ t ] - > ( a , [ t ] )
, failBad -- :: String -> Parser t a
: : t a - > Parser t a
-- * Combinators
-- ** primitives
: : t t
, satisfy -- :: (t->Bool) -> Parser t t
: : t ( a->b ) - > Parser t a - > Parser t b
: : t a - > Parser t b - > Parser t a
-- ** error-handling
: : t a - > ( String->String ) - > Parser t a
: : t a - > ( String->String ) - > Parser t a
, indent -- :: Int -> String -> String
-- ** choices
: : t a - > Parser t a - > Parser t a
: : Show t = > [ Parser t a ] - > Parser t a
: : [ ( String , t a ) ] - > Parser t a
: : t a - > Parser t ( Maybe a )
-- ** sequences
: : t a - > Parser t [ a ]
: : t a - > Parser t [ a ]
: : t a - > Parser t sep - > Parser t [ a ]
: : t a - > Parser t sep - > Parser t [ a ]
: : t bra - > Parser t sep - > Parser t ket
-- -> Parser t a -> Parser t [a]
: : t bra - > Parser t ket - > Parser t a
-- -> Parser t a
: : t a - > Parser t z - > Parser t [ a ]
-- ** re-parsing
, reparse -- :: [t] -> Parser t ()
) where
#if __GLASGOW_HASKELL__
import Control.Exception hiding (bracket)
throwE :: String -> a
throwE msg = throw (ErrorCall msg)
#else
throwE :: String -> a
throwE msg = error msg
#endif
-- | The @Parser@ datatype is a fairly generic parsing monad with error
-- reporting. It can be used for arbitrary token types, not just
String input . ( If you require a running state , use module PolyState
-- instead.)
newtype Parser t a = P ([t] -> (Either String a, [t]))
-- A return type like Either, that distinguishes not only between
-- right and wrong answers, but also had gradations of wrongness.
-- Not used in this library. !!!!!!!!!!!!!!!!!!!!!!!!!!!
type EitherE a b = Either (Bool,a) b
-- | Apply a parser to an input token sequence. The parser cannot return
-- an error value explicitly, so errors raise an exception. Thus, results
-- can be partial (lazily constructed, but containing undefined).
runParser :: Parser t a -> [t] -> (a, [t])
runParser (P p) =
(\ (e,ts)-> (case e of {Left m->throwE m; Right x->x}, ts) )
. p
instance Functor (Parser t) where
fmap f (P p) = P (\ts-> case p ts of
(Left msg, ts') -> (Left msg, ts')
(Right x, ts') -> (Right (f x), ts'))
instance Monad (Parser t) where
return x = P (\ts-> (Right x, ts))
(P f) >>= g = P (\ts-> case f ts of
(Left msg, ts') -> (Left msg, ts')
(Right x, ts') -> let (P g') = g x in g' ts')
fail e = P (\ts-> (Left e, ts))
-- | Simple failure can be corrected, but when a simple fail is not strong
enough , use failBad for emphasis . It guarantees parsing will
-- terminate with an exception.
failBad :: String -> Parser t a
failBad msg = P (\ts-> (throwE msg, ts))
-- | Commit is a way of raising the severity of any errors found within
-- its argument. Used in the middle of a parser definition, it means that
-- any operations prior to commitment fail softly, but after commitment,
-- they fail hard.
commit :: Parser t a -> Parser t a
commit (P p) = P (\ts-> case p ts of
(Left e, ts') -> (throwE e, ts')
right -> right )
-- Combinators
-- | One token
next :: Parser t t
next = P (\ts-> case ts of
[] -> (Left "Ran out of input (EOF)", [])
(t:ts') -> (Right t, ts') )
-- | One token satifying a predicate
satisfy :: (t->Bool) -> Parser t t
satisfy p = do{ x <- next
; if p x then return x else fail "Parse.satisfy: failed"
}
infixl 3 `apply`
-- | Apply a parsed function to a parsed value
apply :: Parser t (a->b) -> Parser t a -> Parser t b
--pf `apply` px = do { f <- pf; x <- px; return (f x) }
-- Needs to be lazier! Must not force the argument value too early.
(P pf) `apply` (P px) = P (\ts->
case pf ts of
(Left msg, ts') -> (Left msg, ts')
(Right f, ts') -> let (x',ts'') = px ts'
x = case x' of { Right x -> x; Left e -> throwE e }
in (Right (f x), ts'') )
infixl 3 `discard`
-- | @x `discard` y@ parses both x and y, but discards the result of y
discard :: Parser t a -> Parser t b -> Parser t a
px `discard` py = do { x <- px; _ <- py; return x }
| @p ` adjustErr ` f@ applies the transformation @f@ to any error message
generated in @p@ , having no effect if succeeds .
adjustErr :: Parser t a -> (String->String) -> Parser t a
(P p) `adjustErr` f = P (\ts-> case p ts of
(Left msg, ts') -> (Left (f msg), ts')
right -> right )
-- | @adjustErrBad@ is just like @adjustErr@ except it also raises the
-- severity of the error.
adjustErrBad :: Parser t a -> (String->String) -> Parser t a
p `adjustErrBad` f = commit (p `adjustErr` f)
not sure about precedence 6 ?
| @p ` onFail ` q@ means parse p unless p fails in which case parse q instead .
-- Can be chained together to give multiple attempts to parse something.
-- (Note that q could itself be a failing parser, e.g. to change the error
message from that defined in p to something different . )
However , a * severe * failure in p can not be ignored .
onFail :: Parser t a -> Parser t a -> Parser t a
(P p) `onFail` (P q) = P (\ts-> case p ts of
(Left _, _) -> q ts
right -> right )
| Parse the first alternative in the list that succeeds .
oneOf :: [Parser t a] -> Parser t a
oneOf [] = do { n <- next
; fail ("failed to parse any of the possible choices")
}
oneOf : : Show t = > [ Parser t a ] - > Parser t a
--oneOf [] = do { n <- next
-- ; fail ("failed to parse any of the possible choices"
-- ++"\n next token is "++show n)
-- }
oneOf (p:ps) = p `onFail` oneOf ps
| Parse the first alternative that succeeds , but if none succeed ,
-- report only the severe errors, and if none of those, then report
-- all the soft errors.
oneOf' :: [(String, Parser t a)] -> Parser t a
oneOf' ps = accum [] ps
where accum errs [] =
case errs of
[] -> failBad ("internal failure in parser (oneOf'):\n"
++indent 2 (show (map fst ps)))
[(_,e)] -> fail e
es -> fail ("one of the following failures occurred:\n"
++indent 2 (concatMap showErr (reverse es)))
accum errs ((e,P p):ps) =
P (\ts-> case p ts of
(Left err,_) -> let (P p) = accum ((e,err):errs) ps
in p ts
right -> right )
showErr (name,err) = name++":\n"++indent 2 err
-- | Helper for formatting error messages: indents all lines by a fixed amount.
indent :: Int -> String -> String
indent n = unlines . map (replicate n ' ' ++) . lines
-- | 'optional' indicates whether the parser succeeded through the Maybe type.
optional :: Parser t a -> Parser t (Maybe a)
optional p = fmap Just p `onFail` return Nothing
-- | 'many p' parses a list of elements with individual parser p.
-- Cannot fail, since an empty list is a valid return value.
many :: Parser t a -> Parser t [a]
many p = many1 p `onFail` return []
-- | Parse a non-empty list of items.
many1 :: Parser t a -> Parser t [a]
many1 p = do { x <- p `adjustErr` (("In a sequence:\n"++). indent 2)
; xs <- many p
; return (x:xs)
}
-- `adjustErr` ("When looking for a non-empty sequence:\n\t"++)
-- | Parse a list of items separated by discarded junk.
sepBy :: Parser t a -> Parser t sep -> Parser t [a]
sepBy p sep = do sepBy1 p sep `onFail` return []
-- | Parse a non-empty list of items separated by discarded junk.
sepBy1 :: Parser t a -> Parser t sep -> Parser t [a]
sepBy1 p sep = do { x <- p
; xs <- many (do {sep; p})
; return (x:xs)
}
`adjustErr` ("When looking for a non-empty sequence with separators:\n\t"++)
-- | Parse a list of items, discarding the start, end, and separator
-- items.
bracketSep :: Parser t bra -> Parser t sep -> Parser t ket
-> Parser t a -> Parser t [a]
bracketSep open sep close p =
do { open; close; return [] }
`onFail`
do { open `adjustErr` ("Missing opening bracket:\n\t"++)
; x <- p `adjustErr` ("After first bracket in a group:\n\t"++)
; xs <- many (do {sep; p})
; close `adjustErrBad` ("When looking for closing bracket:\n\t"++)
; return (x:xs)
}
-- | Parse a bracketed item, discarding the brackets.
bracket :: Parser t bra -> Parser t ket -> Parser t a -> Parser t a
bracket open close p = do
do { open `adjustErr` ("Missing opening bracket:\n\t"++)
; x <- p
; close `adjustErrBad` ("Missing closing bracket:\n\t"++)
; return x
}
| ' e t ' parses a possibly - empty sequence of e 's ,
-- terminated by a t. Any parse failures could be due either to
-- a badly-formed terminator or a badly-formed element, so raise
-- both possible errors.
manyFinally :: Parser t a -> Parser t z -> Parser t [a]
manyFinally pp@(P p) pt@(P t) = P (\ts ->
case p ts of
(Left e, _) ->
case t ts of
(Right _, ts') -> (Right [], ts')
(Left e, ts') -> (Left e, ts')
(Right x, ts') ->
let (tail,ts'') = runParser (manyFinally pp pt) ts'
in (Right (x:tail), ts'') )
------------------------------------------------------------------------
-- | Push some tokens back onto the front of the input stream and reparse.
-- This is useful e.g. for recursively expanding macros. When the
-- user-parser recognises a macro use, it can lookup the macro
-- expansion from the parse state, lex it, and then stuff the
-- lexed expansion back down into the parser.
reparse :: [t] -> Parser t ()
reparse ts = P (\inp-> (Right (), ts++inp))
------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/HaXml/src/Text/ParserCombinators/PolyLazy.hs | haskell | raised instead. This allows partial results to be returned
before a full parse is complete.
:: String -> Parser t a
* Combinators
** primitives
:: (t->Bool) -> Parser t t
** error-handling
:: Int -> String -> String
** choices
** sequences
-> Parser t a -> Parser t [a]
-> Parser t a
** re-parsing
:: [t] -> Parser t ()
| The @Parser@ datatype is a fairly generic parsing monad with error
reporting. It can be used for arbitrary token types, not just
instead.)
A return type like Either, that distinguishes not only between
right and wrong answers, but also had gradations of wrongness.
Not used in this library. !!!!!!!!!!!!!!!!!!!!!!!!!!!
| Apply a parser to an input token sequence. The parser cannot return
an error value explicitly, so errors raise an exception. Thus, results
can be partial (lazily constructed, but containing undefined).
| Simple failure can be corrected, but when a simple fail is not strong
terminate with an exception.
| Commit is a way of raising the severity of any errors found within
its argument. Used in the middle of a parser definition, it means that
any operations prior to commitment fail softly, but after commitment,
they fail hard.
Combinators
| One token
| One token satifying a predicate
| Apply a parsed function to a parsed value
pf `apply` px = do { f <- pf; x <- px; return (f x) }
Needs to be lazier! Must not force the argument value too early.
| @x `discard` y@ parses both x and y, but discards the result of y
| @adjustErrBad@ is just like @adjustErr@ except it also raises the
severity of the error.
Can be chained together to give multiple attempts to parse something.
(Note that q could itself be a failing parser, e.g. to change the error
oneOf [] = do { n <- next
; fail ("failed to parse any of the possible choices"
++"\n next token is "++show n)
}
report only the severe errors, and if none of those, then report
all the soft errors.
| Helper for formatting error messages: indents all lines by a fixed amount.
| 'optional' indicates whether the parser succeeded through the Maybe type.
| 'many p' parses a list of elements with individual parser p.
Cannot fail, since an empty list is a valid return value.
| Parse a non-empty list of items.
`adjustErr` ("When looking for a non-empty sequence:\n\t"++)
| Parse a list of items separated by discarded junk.
| Parse a non-empty list of items separated by discarded junk.
| Parse a list of items, discarding the start, end, and separator
items.
| Parse a bracketed item, discarding the brackets.
terminated by a t. Any parse failures could be due either to
a badly-formed terminator or a badly-formed element, so raise
both possible errors.
----------------------------------------------------------------------
| Push some tokens back onto the front of the input stream and reparse.
This is useful e.g. for recursively expanding macros. When the
user-parser recognises a macro use, it can lookup the macro
expansion from the parse state, lex it, and then stuff the
lexed expansion back down into the parser.
---------------------------------------------------------------------- | module Text.ParserCombinators.PolyLazy
* A Parser datatype parameterised on arbitrary token type .
Parsers do not return explicit failure . An exception is
datatype , instance of : Functor , Monad
: : t a - > [ t ] - > ( a , [ t ] )
: : t a - > Parser t a
: : t t
: : t ( a->b ) - > Parser t a - > Parser t b
: : t a - > Parser t b - > Parser t a
: : t a - > ( String->String ) - > Parser t a
: : t a - > ( String->String ) - > Parser t a
: : t a - > Parser t a - > Parser t a
: : Show t = > [ Parser t a ] - > Parser t a
: : [ ( String , t a ) ] - > Parser t a
: : t a - > Parser t ( Maybe a )
: : t a - > Parser t [ a ]
: : t a - > Parser t [ a ]
: : t a - > Parser t sep - > Parser t [ a ]
: : t a - > Parser t sep - > Parser t [ a ]
: : t bra - > Parser t sep - > Parser t ket
: : t bra - > Parser t ket - > Parser t a
: : t a - > Parser t z - > Parser t [ a ]
) where
#if __GLASGOW_HASKELL__
import Control.Exception hiding (bracket)
throwE :: String -> a
throwE msg = throw (ErrorCall msg)
#else
throwE :: String -> a
throwE msg = error msg
#endif
String input . ( If you require a running state , use module PolyState
newtype Parser t a = P ([t] -> (Either String a, [t]))
type EitherE a b = Either (Bool,a) b
runParser :: Parser t a -> [t] -> (a, [t])
runParser (P p) =
(\ (e,ts)-> (case e of {Left m->throwE m; Right x->x}, ts) )
. p
instance Functor (Parser t) where
fmap f (P p) = P (\ts-> case p ts of
(Left msg, ts') -> (Left msg, ts')
(Right x, ts') -> (Right (f x), ts'))
instance Monad (Parser t) where
return x = P (\ts-> (Right x, ts))
(P f) >>= g = P (\ts-> case f ts of
(Left msg, ts') -> (Left msg, ts')
(Right x, ts') -> let (P g') = g x in g' ts')
fail e = P (\ts-> (Left e, ts))
enough , use failBad for emphasis . It guarantees parsing will
failBad :: String -> Parser t a
failBad msg = P (\ts-> (throwE msg, ts))
commit :: Parser t a -> Parser t a
commit (P p) = P (\ts-> case p ts of
(Left e, ts') -> (throwE e, ts')
right -> right )
next :: Parser t t
next = P (\ts-> case ts of
[] -> (Left "Ran out of input (EOF)", [])
(t:ts') -> (Right t, ts') )
satisfy :: (t->Bool) -> Parser t t
satisfy p = do{ x <- next
; if p x then return x else fail "Parse.satisfy: failed"
}
infixl 3 `apply`
apply :: Parser t (a->b) -> Parser t a -> Parser t b
(P pf) `apply` (P px) = P (\ts->
case pf ts of
(Left msg, ts') -> (Left msg, ts')
(Right f, ts') -> let (x',ts'') = px ts'
x = case x' of { Right x -> x; Left e -> throwE e }
in (Right (f x), ts'') )
infixl 3 `discard`
discard :: Parser t a -> Parser t b -> Parser t a
px `discard` py = do { x <- px; _ <- py; return x }
| @p ` adjustErr ` f@ applies the transformation @f@ to any error message
generated in @p@ , having no effect if succeeds .
adjustErr :: Parser t a -> (String->String) -> Parser t a
(P p) `adjustErr` f = P (\ts-> case p ts of
(Left msg, ts') -> (Left (f msg), ts')
right -> right )
adjustErrBad :: Parser t a -> (String->String) -> Parser t a
p `adjustErrBad` f = commit (p `adjustErr` f)
not sure about precedence 6 ?
| @p ` onFail ` q@ means parse p unless p fails in which case parse q instead .
message from that defined in p to something different . )
However , a * severe * failure in p can not be ignored .
onFail :: Parser t a -> Parser t a -> Parser t a
(P p) `onFail` (P q) = P (\ts-> case p ts of
(Left _, _) -> q ts
right -> right )
| Parse the first alternative in the list that succeeds .
oneOf :: [Parser t a] -> Parser t a
oneOf [] = do { n <- next
; fail ("failed to parse any of the possible choices")
}
oneOf : : Show t = > [ Parser t a ] - > Parser t a
oneOf (p:ps) = p `onFail` oneOf ps
| Parse the first alternative that succeeds , but if none succeed ,
oneOf' :: [(String, Parser t a)] -> Parser t a
oneOf' ps = accum [] ps
where accum errs [] =
case errs of
[] -> failBad ("internal failure in parser (oneOf'):\n"
++indent 2 (show (map fst ps)))
[(_,e)] -> fail e
es -> fail ("one of the following failures occurred:\n"
++indent 2 (concatMap showErr (reverse es)))
accum errs ((e,P p):ps) =
P (\ts-> case p ts of
(Left err,_) -> let (P p) = accum ((e,err):errs) ps
in p ts
right -> right )
showErr (name,err) = name++":\n"++indent 2 err
indent :: Int -> String -> String
indent n = unlines . map (replicate n ' ' ++) . lines
optional :: Parser t a -> Parser t (Maybe a)
optional p = fmap Just p `onFail` return Nothing
many :: Parser t a -> Parser t [a]
many p = many1 p `onFail` return []
many1 :: Parser t a -> Parser t [a]
many1 p = do { x <- p `adjustErr` (("In a sequence:\n"++). indent 2)
; xs <- many p
; return (x:xs)
}
sepBy :: Parser t a -> Parser t sep -> Parser t [a]
sepBy p sep = do sepBy1 p sep `onFail` return []
sepBy1 :: Parser t a -> Parser t sep -> Parser t [a]
sepBy1 p sep = do { x <- p
; xs <- many (do {sep; p})
; return (x:xs)
}
`adjustErr` ("When looking for a non-empty sequence with separators:\n\t"++)
bracketSep :: Parser t bra -> Parser t sep -> Parser t ket
-> Parser t a -> Parser t [a]
bracketSep open sep close p =
do { open; close; return [] }
`onFail`
do { open `adjustErr` ("Missing opening bracket:\n\t"++)
; x <- p `adjustErr` ("After first bracket in a group:\n\t"++)
; xs <- many (do {sep; p})
; close `adjustErrBad` ("When looking for closing bracket:\n\t"++)
; return (x:xs)
}
bracket :: Parser t bra -> Parser t ket -> Parser t a -> Parser t a
bracket open close p = do
do { open `adjustErr` ("Missing opening bracket:\n\t"++)
; x <- p
; close `adjustErrBad` ("Missing closing bracket:\n\t"++)
; return x
}
| ' e t ' parses a possibly - empty sequence of e 's ,
manyFinally :: Parser t a -> Parser t z -> Parser t [a]
manyFinally pp@(P p) pt@(P t) = P (\ts ->
case p ts of
(Left e, _) ->
case t ts of
(Right _, ts') -> (Right [], ts')
(Left e, ts') -> (Left e, ts')
(Right x, ts') ->
let (tail,ts'') = runParser (manyFinally pp pt) ts'
in (Right (x:tail), ts'') )
reparse :: [t] -> Parser t ()
reparse ts = P (\inp-> (Right (), ts++inp))
|
f887b3cbb7b65c97b8b1b5bdb1cccdd59876c63d4848805186ac6dc1a6ae9712 | brianhempel/maniposynth | ast.ml | open Parsetree
open Util
type program = structure_item list (* === structure *)
type everything =
{ vbs : value_binding list
; exps : expression list
; pats : pattern list
; struct_items : structure_item list
}
let dflt_iter = Ast_iterator.default_iterator
let dflt_mapper = Ast_mapper.default_mapper
type node =
| Exp of expression
| Pat of pattern
| Vb of value_binding
| Si of structure_item
| Sis of structure
let everything node =
let vbs = ref [] in
let exps = ref [] in
let pats = ref [] in
let struct_items = ref [] in
let iter =
{ dflt_iter
with value_binding = (fun iter vb -> vbs := vb ::!vbs; dflt_iter.value_binding iter vb)
; expr = (fun iter exp -> exps := exp::!exps; dflt_iter.expr iter exp)
; pat = (fun iter pat -> pats := pat::!pats; dflt_iter.pat iter pat)
; structure_item = (fun iter si -> struct_items := si ::!struct_items; dflt_iter.structure_item iter si)
} in
begin match node with
| Exp exp -> iter.expr iter exp
| Pat pat -> iter.pat iter pat
| Vb vb -> iter.value_binding iter vb
| Si si -> iter.structure_item iter si
| Sis prog -> iter.structure iter prog
end;
{ vbs = !vbs
; exps = !exps
; pats = !pats
; struct_items = !struct_items
}
Module renamed to at the end of this file . Use Loc . Has to do with dependency ordering .
module Loc_ = struct
type t = Location.t
module Pos = struct
type t = Lexing.position
(* Fresh positions are given new, negative values. *)
let counter = ref 0
let next () = decr counter; !counter
let newloc_str = "newloc"
let fresh () =
Lexing.{ pos_fname = newloc_str; pos_lnum = next (); pos_bol = -1; pos_cnum = -1 }
let to_string { Lexing.pos_fname; pos_lnum; pos_bol; pos_cnum } =
"{ pos_fname = " ^ pos_fname ^
"; pos_lnum = " ^ string_of_int pos_lnum ^
"; pos_bol = " ^ string_of_int pos_bol ^
"; pos_cnum = " ^ string_of_int pos_cnum ^ " " ^
"}"
let compare pos1 pos2 =
let open Lexing in
Pervasives.compare
(pos1.pos_fname, pos1.pos_cnum, pos1.pos_lnum, pos1.pos_bol)
(pos2.pos_fname, pos2.pos_cnum, pos2.pos_lnum, pos2.pos_bol)
let byte_in_file { Lexing.pos_bol; pos_cnum; _ } =
pos_bol + pos_cnum
end
(* let none = Location.none *)
let fresh () =
Location.{ loc_start = Pos.fresh (); loc_end = Pos.fresh (); loc_ghost = false }
let mk txt = Location.mkloc txt (fresh ())
let loc { Location.loc; txt = _ } = loc
let txt { Location.txt; loc = _ } = txt
(* Makes a fresh loc *)
Use Longident.lident for Location.none
let lident str = mk (Longident.Lident str)
let to_string { Location.loc_start; loc_end; loc_ghost } =
"{ loc_start = " ^ Pos.to_string loc_start ^
"; loc_end = " ^ Pos.to_string loc_end ^
"; loc_ghost = " ^ string_of_bool loc_ghost ^ " " ^
"}"
let compare loc1 loc2 =
let open Location in
match Pos.compare loc1.loc_start loc2.loc_start with
| 0 ->
begin match Pos.compare loc1.loc_end loc2.loc_end with
| 0 -> Pervasives.compare loc1.loc_ghost loc2.loc_ghost
| n -> n
end
| n -> n
end
module Longident = struct
include Longident
(* Uses Location.none *)
(* Use Loc.ident for a fresh loc *)
let lident str = Location.mknoloc (Lident str)
let simple_name = function
| Lident name -> Some name
| _ -> None
let to_string = flatten %> String.concat "."
end
module Type = struct
type t = Types.type_expr
let to_string typ = Printtyp.reset (); Formatter_to_stringifier.f Printtyp.type_expr typ
let to_string_raw typ = Printtyp.reset ( ) ; Formatter_to_stringifier.f Printtyp.raw_type_expr typ
let to_string_raw typ = Formatter_to_stringifier.f Printtyp.raw_type_expr typ
let from_core_type ?(env = Env.empty) core_type = (Typetexp.transl_simple_type env false core_type).ctyp_type
let from_string ?(env = Env.empty) str =
Lexing.from_string str
|> Parse.core_type
|> from_core_type ~env
let to_core_type = to_string %> Lexing.from_string %> Parse.core_type
let of_exp ?(type_env = Env.empty) exp = (Typecore.type_exp type_env exp).exp_type
let of_exp_opt ?(type_env = Env.empty) exp =
try Some (of_exp ~type_env exp)
with Typetexp.Error (_loc, type_env, err) ->
Typetexp.report_error type_env Format.std_formatter err;
None
let copy (t : t) : t = Btype.cleanup_abbrev (); Marshal.from_bytes (Marshal.to_bytes t [Closures]) 0
let rec iter f typ = Btype.iter_type_expr (fun t -> iter f t) typ; f typ
let new_var () = Btype.newgenvar ()
let tuple ts = Btype.newgenty (Ttuple ts)
(* Follow links/substs to a regular type *)
(* See printtyp.ml for "safe_repr" version that catches cycles *)
let rec regular typ =
match typ.Types.desc with
| Types.Tlink typ
| Types.Tsubst typ -> regular typ
| _ -> typ
(* For cache keying. Faster than unification. *)
let rec equal_ignoring_id_and_scope (* ?(show = false) *) (t1 : t) (t2 : t) : bool =
let open Types in
(* let rec safe_repr v = function (* copied from printtyp.ml *)
{desc = Tlink t; _} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
in *)
let recurse = equal_ignoring_id_and_scope (* ~show *) in
let t1 = regular t1 in
let t2 = regular t2 in
begin
(* (fun b -> if not b then
(if show then print_endline (to_string_raw t1 ^ " <> " ^ to_string_raw t2); b)
else
b
) @@ *)
match t1.desc, t2.desc with
| Tvar str_opt1, Tvar str_opt2
| Tunivar str_opt1, Tunivar str_opt2 ->
(* let p = function None -> "None" | Some str -> "Some \'" ^ str ^ "\'" in
if show then print_endline (p str_opt1 ^ " vs " ^ p str_opt2 ^ " " ^ string_of_bool (str_opt1 = str_opt2)); *)
t1.level = t2.level &&
str_opt1 = str_opt2
| Tarrow (lab1, t_l1, t_r1, comm1)
, Tarrow (lab2, t_l2, t_r2, comm2) ->
let rec get_comm = function Clink { contents = comm } -> get_comm comm | comm -> comm in
lab1 = lab2 && get_comm comm1 = get_comm comm2 && recurse t_l1 t_l2 && recurse t_r1 t_r2
| Ttuple ts1
, Ttuple ts2 -> List.for_all2_safe recurse ts1 ts2
| Tconstr (path1, ts1, _abbrev_memo1)
, Tconstr (path2, ts2, _abbrev_memo2) ->
if show then begin match path1 , with
| Path . Pident , Path . print_endline ( Formatter_to_stringifier.f Ident.print ^ " vs " ^ Formatter_to_stringifier.f Ident.print ^ " is " ^ string_of_bool ( Path.same ) )
| _ - > ( )
end ;
| Path.Pident ident1, Path.Pident ident2 -> print_endline (Formatter_to_stringifier.f Ident.print ident1 ^ " vs " ^ Formatter_to_stringifier.f Ident.print ident2 ^ " is " ^ string_of_bool (Path.same path1 path2))
| _ -> ()
end; *)
Path.same path1 path2 && (
if show then begin
print_endline ( string_of_bool ( List.for_all2_safe recurse ts1 ts2 ) ) ;
print_endline ( " ts1 : " ^ String.concat " , " ( to_string_raw ) ) ;
print_endline ( " ts2 : " ^ String.concat " , " ( ts2 ) ) ;
end ;
print_endline (string_of_bool (List.for_all2_safe recurse ts1 ts2));
print_endline ("ts1: " ^ String.concat ", " (ts1 |>@ to_string_raw));
print_endline ("ts2: " ^ String.concat ", " (ts2 |>@ to_string_raw));
end; *)
List.for_all2_safe recurse ts1 ts2
)
| Tobject (t1, { contents = Some (path1, ts1) })
, Tobject (t2, { contents = Some (path2, ts2) }) ->
recurse t1 t2 && Path.same path1 path2 && List.for_all2_safe recurse ts1 ts2
| Tobject (t1, { contents = None })
, Tobject (t2, { contents = None }) ->
recurse t1 t2
| Tobject _
, Tobject _ -> false
| Tfield (lab1, kind1, t1, t_rest1)
, Tfield (lab2, kind2, t2, t_rest2) ->
lab1 = lab2 && kind1 = kind2 && recurse t1 t2 && recurse t_rest1 t_rest2
| Tnil
, Tnil -> true
| Tvariant row1
, Tvariant row2 ->
List.for_all2_safe begin fun (lab1, field1) (lab2, field2) ->
lab1 = lab2 &&
let rec row_fields_equal_ignoring_id field1 field2 =
match field1, field2 with
| Rpresent (Some t1), Rpresent (Some t2)-> recurse t1 t2
| Rpresent None, Rpresent None -> true
| Reither (bool_a1, ts1, bool_b1, { contents = Some field1 })
, Reither (bool_a2, ts2, bool_b2, { contents = Some field2 }) ->
bool_a1 = bool_a2 &&
List.for_all2_safe recurse ts1 ts2 &&
bool_b1 = bool_b2 &&
row_fields_equal_ignoring_id field1 field2
| Reither (bool_a1, ts1, bool_b1, { contents = None })
, Reither (bool_a2, ts2, bool_b2, { contents = None }) ->
bool_a1 = bool_a2 &&
List.for_all2_safe recurse ts1 ts2 &&
bool_b1 = bool_b2
| Rabsent, Rabsent -> true
| _ -> false
in
row_fields_equal_ignoring_id field1 field2
end row1.row_fields row2.row_fields &&
recurse row1.row_more row2.row_more &&
row1.row_closed = row2.row_closed &&
row1.row_fixed = row2.row_fixed &&
begin match row1.row_name, row2.row_name with
| Some (path1, ts1), Some (path2, ts2) -> Path.same path1 path2 && List.for_all2_safe recurse ts1 ts2
| None, None -> true
| _ -> false
end
| Tpoly (t1, ts1)
, Tpoly (t2, ts2) -> recurse t1 t2 && List.for_all2_safe recurse ts1 ts2
| Tpackage (path1, lids1, ts1)
, Tpackage (path2, lids2, ts2) ->
Path.same path1 path2 && List.for_all2_safe (=) lids1 lids2 && List.for_all2_safe recurse ts1 ts2
| Tlink _, _
| Tsubst _, _
| _, Tlink _
| _, Tsubst _ -> failwith "equal_ignoring_id_and_scope: shouldn't happen"
| _ -> false
end
let rec is_tconstr_with_path target_path typ =
match typ.Types.desc with
| Types.Tconstr (path, _, _) -> path = target_path
| Types.Tlink t
| Types.Tsubst t -> is_tconstr_with_path target_path t
| _ -> false
let is_unit_type = is_tconstr_with_path Predef.path_unit
let is_bool_type = is_tconstr_with_path Predef.path_bool
let is_string_type = is_tconstr_with_path Predef.path_string
let is_int_type = is_tconstr_with_path Predef.path_int
let is_char_type = is_tconstr_with_path Predef.path_char
let is_float_type = is_tconstr_with_path Predef.path_float
let is_exn_type = is_tconstr_with_path Predef.path_exn
let rec is_var_type typ = match typ.Types.desc with
| Types.Tvar _
| Types.Tunivar _ -> true
| Types.Tlink t
| Types.Tsubst t -> is_var_type t
| _ -> false
let rec is_arrow_type typ = match typ.Types.desc with
| Types.Tarrow _ -> true
| Types.Tlink t
| Types.Tsubst t -> is_arrow_type t
| _ -> false
let rec is_ref_type typ =
match typ.Types.desc with
| Types.Tconstr (Path.Pdot (_, "ref", _), _, _) -> true
| Types.Tlink t
| Types.Tsubst t -> is_ref_type t
| _ -> false
let rec var_name typ = match typ.Types.desc with
| Types.Tvar name_opt
| Types.Tunivar name_opt -> name_opt
| Types.Tlink t
| Types.Tsubst t -> var_name t
| _ -> None
let rec tvar_name typ = match typ.Types.desc with
| Types.Tvar name_opt -> name_opt
| Types.Tlink t
| Types.Tsubst t -> tvar_name t
| _ -> None
Deduplicated Tvar / Tunivar names , from left to right .
let names typ =
let names = ref [] in
typ
|> iter begin fun t ->
match t.desc with
| Types.Tvar (Some name)
| Types.Tunivar (Some name) -> if List.mem name !names then () else names := name :: !names
| _ -> ()
end;
List.rev !names
First pass to quickly discard non - unifiable terms .
let rec might_unify t1 t2 =
let open Types in
(* let rec safe_repr v = function (* copied from printtyp.ml *)
{desc = Tlink t; _} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
in *)
let recurse = might_unify in
let t1 = regular t1 in
let t2 = regular t2 in
match t1.desc, t2.desc with
| Tvar _, _
| _, Tvar _
| Tunivar _, _
| _, Tunivar _ ->
true
| Tarrow (_lab1, t_l1, t_r1, _comm1)
, Tarrow (_lab2, t_l2, t_r2, _comm2) ->
recurse t_l1 t_l2 && recurse t_r1 t_r2
| Tarrow _, _
| _, Tarrow _ -> false
| Ttuple ts1
, Ttuple ts2 -> List.for_all2_safe recurse ts1 ts2
| Ttuple _, _
| _, Ttuple _ -> false
| Tconstr (_path1, ts1, _abbrev_memo1)
, Tconstr (_path2, ts2, _abbrev_memo2) ->
List.for_all2_safe recurse ts1 ts2
| Tconstr _, _
| _, Tconstr _ -> false
| Tobject _
, Tobject _ ->
true
| Tobject _, _
| _, Tobject _ -> false
| Tfield (lab1, kind1, t1, t_rest1)
, Tfield (lab2, kind2, t2, t_rest2) ->
lab1 = lab2 && kind1 = kind2 && recurse t1 t2 && recurse t_rest1 t_rest2
| Tfield _, _
| _, Tfield _ -> false
| Tnil
, Tnil -> true
| Tnil, _
| _, Tnil -> false
| Tvariant _
, Tvariant _ ->
true
| Tvariant _, _
| _, Tvariant _ -> false
| Tpoly (t1, ts1)
, Tpoly (t2, ts2) -> recurse t1 t2 && List.for_all2_safe recurse ts1 ts2
| Tpoly _, _
| _, Tpoly _ -> false
| Tpackage (_path1, _lids1, ts1)
, Tpackage (_path2, _lids2, ts2) ->
List.for_all2_safe recurse ts1 ts2
| Tpackage _, _
| _, Tpackage _ -> false
| Tlink _, _
| Tsubst _, _ -> failwith "equal_ignoring_id_and_scope: shouldn't happen"
LOOK AT ALL THIS STUFF I TRIED TO NOT MUTATE WHEN TRYING TO UNIFY / SUBTYPE !
(* These all don't work. *)
( Ctype.correct_levels t )
(* Ctype.instance t *)
(* Ctype.instance ~partial:false t *)
(* Ctype.instance ~partial:true t *)
(* let t' = Ctype.correct_levels t in
Ctype.generalize t';
t' *)
let is_more_general =
Ctype.moregeneral Env.empty true more_general target
Ctype.moregeneral Env.empty true more_general target *)
May only need type env in case of GADTs , which we do n't care about .
let does_unify t1 t2 =
(* print_endline @@ "Unifying " ^ to_string t1 ^ "\twith " ^ to_string t2; *)
(* Ctype.matches Env.empty t1 t2 *)
(* is_more_general t1 t2 *)
might_unify t1 t2 &&
try
Ctype.unify Env.empty ( t1 ) ( t2 ) ;
Ctype.unify Env.empty (copy t1) (copy t2);
true
with
| . Error ( _ loc , type_env , err ) - >
Typetexp.report_error type_env Format.std_formatter err ;
false
Typetexp.report_error type_env Format.std_formatter err;
false *)
| _ ->
(* print_endline @@ to_string t1 ^ " !~ " ^ to_string t2; *)
false
(* I think t1 and t2 may still be mutated even if unification fails. *)
let unify_mutating_opt t1 t2 =
(* print_endline @@ "Unifying " ^ to_string t1 ^ "\twith " ^ to_string t2; *)
if not (might_unify t1 t2) then None else
try
Ctype.unify Env.empty t1 t2;
Some t1
with _ -> None
let unify_opt t1 t2 =
(* print_endline @@ "Unifying " ^ to_string t1 ^ "\twith " ^ to_string t2; *)
if not (might_unify t1 t2) then None else
let t1' = copy t1 in
try
Ctype.unify Env.empty t1' (copy t2);
Some t1'
with _ -> None
(* Is typ1 equal or more general than typ2? *)
let is_equal_or_more_general_than typ1 typ2 =
begin fun out - >
print_endline @@ to_string typ1 ^ " \t\t " ^ to_string typ2 ^ " \t\t " ^ ( typ2 | > & to_string || & " - " ) ^ " \t\t " ^ string_of_bool out ;
out
end @@
print_endline @@ to_string typ1 ^ "\t\t" ^ to_string typ2 ^ "\t\t" ^ (unify_opt typ1 typ2 |>& to_string ||& "-") ^ "\t\t" ^ string_of_bool out;
out
end @@ *)
Apparently , unify prefers the Tvars in typ2
| Some typ2' -> to_string typ2' = to_string typ2
| None -> false
(* Stops flattening if a labeled argument is encountered. *)
(* e.g. 'a -> 'b -> 'c to ['a, 'b, 'c] *)
let rec flatten_arrows typ =
let open Types in
match typ.desc with
| Tarrow (Nolabel, ltype, rtype, _) -> ltype :: flatten_arrows rtype
| Tlink typ | Tsubst typ -> flatten_arrows typ
| _ -> [typ]
(* Arg count for arrow types. (Not type arg count). *)
(* Stops if a labeled argument is encountered. *)
let rec arrow_arg_count typ =
let open Types in
match typ.desc with
| Tarrow (Nolabel, _ltype, rtype, _) -> 1 + arrow_arg_count rtype
| Tlink typ | Tsubst typ -> arrow_arg_count typ
| _ -> 0
(* Stops flattening if a labeled argument is encountered. *)
(* e.g. 'a -> 'b -> 'c to (['a, 'b], 'c) *)
let rec args_and_ret typ =
let open Types in
match typ.desc with
| Tarrow (Nolabel, ltype, rtype, Cok) -> args_and_ret rtype |> Tup2.map_fst (List.cons ltype)
| Tlink typ | Tsubst typ -> args_and_ret typ
| _ -> ([], typ)
let arrow t1 t2 =
Btype.newgenty @@ Tarrow (Nolabel, t1, t2, Cok)
let rec unflatten_arrows types =
match types with
| [] -> failwith "shouldn't give an empty type list to Type.unflatten_arrows"
| [t] -> t
| t::rest -> arrow t (unflatten_arrows rest)
let rec flatten typ =
let open Types in
let concat_map = List.concat_map in
let rec flatten_row_field = function
| Rpresent (Some t) -> flatten t
| Rpresent None -> []
| Reither (_, ts, _, { contents = Some row_field }) -> concat_map flatten ts @ flatten_row_field row_field
| Reither (_, ts, _, { contents = None }) -> concat_map flatten ts
| Rabsent -> []
in
typ ::
match typ.desc with
| Tvar _ -> []
| Tarrow (_, l, r, _) -> flatten l @ flatten r
| Ttuple ts -> concat_map flatten ts
| Tconstr (_, ts, _) -> concat_map flatten ts
| Tobject (t, { contents = Some (_, ts) }) -> flatten t @ concat_map flatten ts
| Tobject (t, { contents = None }) -> flatten t
| Tfield (_, _, t1, t2) -> flatten t1 @ flatten t2
| Tnil -> []
| Tlink t -> flatten t
| Tsubst t -> flatten t
| Tunivar _ -> []
| Tpoly (t, ts) -> concat_map flatten (t::ts)
| Tpackage (_, _, ts) -> concat_map flatten ts
| Tvariant { row_fields; row_more; row_name = Some (_, ts); _ } -> (row_fields |>@ snd |>@@ flatten_row_field) @ flatten row_more @ concat_map flatten ts
| Tvariant { row_fields; row_more; row_name = None; _ } -> (row_fields |>@ snd |>@@ flatten_row_field) @ flatten row_more
(* Bottom up (children mapped before parents). *)
(* Note that mutable refs will no longer point to their originals (replaced instead with copies). Shouldn't matter for us. *)
let rec map f typ =
let open Types in
let recurse = map f in
let rec map_abbrev_memo (abbrev_memo : abbrev_memo) =
match abbrev_memo with
| Mnil ->
Mnil
| Mcons (private_flag, path, abbrev, expansion, memo) ->
Mcons (private_flag, path, recurse abbrev, recurse expansion, map_abbrev_memo memo)
| Mlink memo_ref ->
Mlink { contents = map_abbrev_memo !memo_ref }
in
let map_row_desc { row_fields; row_more; row_bound; row_closed; row_fixed; row_name } =
let rec map_row_field (row_field : row_field) =
match row_field with
| Rpresent None -> row_field
| Rpresent (Some t) -> Rpresent (Some (recurse t))
| Reither (isconst, ts, ispat, { contents = None }) -> Reither (isconst, ts |>@ recurse, ispat, { contents = None })
| Reither (isconst, ts, ispat, { contents = Some row_field }) -> Reither (isconst, ts |>@ recurse, ispat, { contents = Some (map_row_field row_field) })
| Rabsent -> Rabsent
in
{
row_fields = row_fields |>@ (fun (name, row_field) -> (name, map_row_field row_field));
row_more = recurse row_more;
row_bound = row_bound;
row_closed = row_closed;
row_fixed = row_fixed;
row_name = row_name |>& (fun (path, ts) -> (path, ts |>@ recurse))
}
in
match typ.desc with
| Tnil
| Tunivar _
| Tvar _ -> f typ
| Tlink t
| Tsubst t -> f (recurse t)
| Tarrow (lab, l, r, comm) -> f { typ with desc = Tarrow (lab, recurse l, recurse r, comm) }
| Ttuple ts -> f { typ with desc = Ttuple (ts |>@ recurse) }
| Tconstr (path, ts, abbrev) -> f { typ with desc = Tconstr (path, ts |>@ recurse, { contents = map_abbrev_memo !abbrev }) }
| Tobject (t, { contents = Some (path, ts) }) -> f { typ with desc = Tobject (recurse t, { contents = Some (path, ts |>@ recurse) }) }
| Tobject (t, { contents = None }) -> f { typ with desc = Tobject (recurse t, { contents = None }) }
| Tfield (name, fkind, t1, t2) -> f { typ with desc = Tfield (name, fkind, recurse t1, recurse t2) }
| Tpoly (t, ts) -> f { typ with desc = Tpoly (recurse t, ts |>@ recurse) }
| Tpackage (path, lids, ts) -> f { typ with desc = Tpackage (path, lids, ts |>@ recurse) }
| Tvariant row_desc -> f { typ with desc = Tvariant (map_row_desc row_desc) }
let rename_all mapping typ =
typ
|> map begin fun typ ->
match typ.desc with
| Tvar (Some str) -> (match List.assoc_opt str mapping with | Some name' -> { typ with desc = Tvar (Some name') } | None -> typ)
| Tunivar (Some str) -> (match List.assoc_opt str mapping with | Some name' -> { typ with desc = Tunivar (Some name') } | None -> typ)
| _ -> typ
end
let rename name name' typ =
rename_all [(name, name')] typ
end
module Common
(Node : sig
type t
val loc : t -> Location.t
val mapper : (t -> t) -> Ast_mapper.mapper
val iterator : (t -> unit) -> Ast_iterator.iterator
val mapper_node_f : Ast_mapper.mapper -> (Ast_mapper.mapper -> t -> t)
val iterator_node_f : Ast_iterator.iterator -> (Ast_iterator.iterator -> t -> unit)
end) = struct
(* type t = Node.t *)
let loc = Node.loc
let mapper = Node.mapper
let iter f prog =
let iterator = Node.iterator f in
iterator.structure iterator prog
let iterator = Node.iterator
let apply_mapper mapper node = (Node.mapper_node_f mapper) mapper node
let apply_iterator iterator node = (Node.iterator_node_f iterator) iterator node
exception Found of Node.t
(* let map_node f = apply_mapper (mapper f) *)
let map f struct_items =
let mapper = Node.mapper f in
mapper.structure mapper struct_items
let map_by pred f prog =
map (fun node -> if pred node then f node else node) prog
let map_at target_loc f prog =
map_by (loc %> (=) target_loc) f prog
let replace_by pred node' prog =
map_by pred (fun _ -> node') prog
let replace target_loc = replace_by (loc %> (=) target_loc)
let find_by pred prog : Node.t =
try
prog |> iter (fun node -> if pred node then raise (Found node));
failwith "find_by: couldn't find node"
with Found node -> node
let find_by_opt pred prog : Node.t option =
try
prog |> iter (fun node -> if pred node then raise (Found node));
None
with Found node -> Some node
let find target_loc = find_by (loc %> (=) target_loc)
let find_opt target_loc = find_by_opt (loc %> (=) target_loc)
let exists pred prog = find_by_opt pred prog <> None
(* Returns extracted node, and a function that takes a node and replaces that element. *)
let extract_by pred prog : Node.t * (Node.t -> program) =
let node = find_by pred prog in
( node
, fun node' -> replace_by ((==) node) node' prog (* Physical equality (==) will work here because node is always boxed and was pulled out of prog *)
)
let extract_by_opt pred prog : (Node.t * (Node.t -> program)) option =
find_by_opt pred prog |>& fun node ->
( node
, fun node' -> replace_by ((==) node) node' prog (* Physical equality (==) will work here because node is always boxed and was pulled out of prog *)
)
let extract target_loc = extract_by (loc %> (=) target_loc)
let extract_opt target_loc = extract_by_opt (loc %> (=) target_loc)
let count pred prog =
let n = ref 0 in
prog |> iter (fun node -> if pred node then incr n);
!n
(* Root element is node rather than the whole program *)
module FromNode = struct
let iter f root =
let iterator = Node.iterator f in
apply_iterator iterator root
let map f root =
let mapper = Node.mapper f in
apply_mapper mapper root
let map_by pred f root =
map (fun node -> if pred node then f node else node) root
let map_at target_loc f root =
map_by (loc %> (=) target_loc) f root
let replace_by pred node' root =
map_by pred (fun _ -> node') root
let replace target_loc = replace_by (loc %> (=) target_loc)
let find_by pred root : Node.t =
try
root |> iter (fun node -> if pred node then raise (Found node));
failwith "find_by: couldn't find node"
with Found node -> node
let find_by_opt pred root : Node.t option =
try
root |> iter (fun node -> if pred node then raise (Found node));
None
with Found node -> Some node
let find target_loc = find_by (loc %> (=) target_loc)
let find_opt target_loc = find_by_opt (loc %> (=) target_loc)
let exists pred root = find_by_opt pred root <> None
(* Returns extracted node, and a function that takes a node and replaces that element. *)
let extract_by pred root : Node.t * (Node.t -> Node.t) =
let node = find_by pred root in
( node
, fun node' -> replace_by ((==) node) node' root (* Physical equality (==) will work here because node is always boxed and was pulled out of root *)
)
let extract_by_opt pred root : (Node.t * (Node.t -> Node.t)) option =
find_by_opt pred root |>& fun node ->
( node
, fun node' -> replace_by ((==) node) node' root (* Physical equality (==) will work here because node is always boxed and was pulled out of root *)
)
let extract target_loc = extract_by (loc %> (=) target_loc)
let extract_opt target_loc = extract_by_opt (loc %> (=) target_loc)
let count pred root =
let n = ref 0 in
root |> iter (fun node -> if pred node then incr n);
!n
end
let child_exps node =
let children = ref [] in
let iter_exp_no_recurse _ e = children := e :: !children in
let iter_once = { dflt_iter with expr = iter_exp_no_recurse } in
(Node.iterator_node_f dflt_iter) iter_once node;
List.rev !children (* Return the children left-to-right. *)
let child_pats node =
let children = ref [] in
let iter_pat_no_recurse _ p = children := p :: !children in
let iter_once = { dflt_iter with pat = iter_pat_no_recurse } in
(Node.iterator_node_f dflt_iter) iter_once node;
List.rev !children (* Return the children left-to-right. *)
let freshen_locs node =
let mapper = { dflt_mapper with location = (fun _ _ -> Loc_.fresh ()) } in
apply_mapper mapper node
end
(* module Const = Ast_helper.Const *)
module Exp = struct
include Common(struct
type t = expression
let loc { pexp_loc; _ } = pexp_loc
let iterator f =
let iter_exp iter e = dflt_iter.expr iter e; f e in
{ dflt_iter with expr = iter_exp }
let mapper f =
let map_exp mapper e = f (dflt_mapper.expr mapper e) in
{ dflt_mapper with expr = map_exp }
let mapper_node_f (mapper : Ast_mapper.mapper) = mapper.expr
let iterator_node_f (iterator : Ast_iterator.iterator) = iterator.expr
end)
include Ast_helper.Exp (* Exp builders *)
let simple_var name = (* don't parse module paths *)
let loc = Loc_.fresh () in
ident ~loc { loc = loc; txt = Longident.Lident name }
let var name = (* parse module paths *)
let loc = Loc_.fresh () in
{ (name |> Lexing.from_string |> Parse.expression) with pexp_loc = loc }
let hole = simple_var "??"
let simple_apply name args = apply (var name) (args |>@ fun arg -> (Asttypes.Nolabel, arg))
let ctor name args =
construct (Loc_.lident name) @@
match args with
| [] -> None
| [arg] -> Some arg
| args -> Some (tuple args)
let int_lit n = constant (Ast_helper.Const.int n)
let string_lit str = constant (Ast_helper.Const.string str)
let unit = construct (Longident.lident "()") None
let apply_with_hole_args fexp n_args = apply fexp @@ List.init n_args (fun _ -> (Asttypes.Nolabel, hole))
let all prog = (everything (Sis prog)).exps
let flatten exp = (everything (Exp exp)).exps
let to_string = Pprintast.string_of_expression
let from_string = Lexing.from_string %> Parse.expression
let from_string_opt exp = try Some (from_string exp) with Syntaxerr.Error _ -> None
let int (exp : expression) =
match exp.pexp_desc with
| Pexp_constant (Pconst_integer (int_str, None)) -> Some (int_of_string int_str)
| _ -> None
let string (exp : expression) =
match exp.pexp_desc with
| Pexp_constant (Pconst_string (str, _)) -> Some str
| _ -> None
let ident_lid_loced (exp : expression) =
match exp.pexp_desc with
| Pexp_ident lid_loced -> Some lid_loced
| _ -> None
let ident_lid = ident_lid_loced %>& Loc_.txt
let simple_name = ident_lid %>&& Longident.simple_name
let simple_apply_parts (exp : expression) = (* No arg labels, fexp is name *)
match exp.pexp_desc with
| Pexp_apply (fexp, labeled_args) ->
begin match simple_name fexp, labeled_args |>@ (function (Asttypes.Nolabel, arg) -> Some arg | _ -> None) |> Option.project with
| Some name, Some unlabeled_args -> Some (name, unlabeled_args)
| _ -> None
end
| _ -> None
let fexp_of_apply (exp : expression) =
match exp.pexp_desc with
| Pexp_apply (fexp, _) -> Some fexp
| _ -> None
let body_of_fun (exp : expression) =
match exp.pexp_desc with
| Pexp_fun (_, _, _, body) -> Some body
| _ -> None
let ctor_lid_loced (exp : expression) =
match exp.pexp_desc with
| Pexp_construct (lid_loced, _) -> Some lid_loced
| _ -> None
let everything exp = everything (Exp exp)
let is_unit exp =
match ctor_lid_loced exp with
| Some { txt = Longident.Lident "()"; _ } -> true
| _ -> false
let is_hole exp =
match exp.pexp_desc with
| Pexp_ident { txt = Longident.Lident "??"; _ } -> true
| _ -> false
let is_fun = function { pexp_desc = Pexp_fun _; _ } -> true | _ -> false
let is_function = function { pexp_desc = Pexp_function _; _ } -> true | _ -> false
let is_funlike exp = is_fun exp || is_function exp
let is_constant = function { pexp_desc = Pexp_constant _; _ } -> true | _ -> false
let is_match = function { pexp_desc = Pexp_match _; _ } -> true | _ -> false
let is_ident = function { pexp_desc = Pexp_ident _; _ } -> true | _ -> false
let is_assert = function { pexp_desc = Pexp_assert _; _ } -> true | _ -> false
let is_ite = function { pexp_desc = Pexp_ifthenelse _; _ } -> true | _ -> false
let is_simple_name = simple_name %> (<>) None
end
module Pat = struct
include Common(struct
type t = pattern
let loc { ppat_loc; _ } = ppat_loc
let iterator f =
let iter_pat iter p = dflt_iter.pat iter p; f p in
{ dflt_iter with pat = iter_pat }
let mapper f =
let map_pat mapper p = f (dflt_mapper.pat mapper p) in
{ dflt_mapper with pat = map_pat }
let mapper_node_f (mapper : Ast_mapper.mapper) = mapper.pat
let iterator_node_f (iterator : Ast_iterator.iterator) = iterator.pat
end)
let all prog = (everything (Sis prog)).pats
include Ast_helper.Pat (* Pat builders *)
let var name =
let loc = Loc_.fresh () in
Ast_helper.Pat.var ~loc { loc = loc; txt = name }
let construct_unqualified ctor_name arg = construct (Longident.lident ctor_name) arg
let unit = construct_unqualified "()" None
let flatten pat = (everything (Pat pat)).pats
let to_string = Formatter_to_stringifier.f Pprintast.pattern
let from_string = Lexing.from_string %> Parse.pattern
let from_string_opt exp = try Some (from_string exp) with Syntaxerr.Error _ -> None
let rec one_var ( pat : pattern ) =
match pat.ppat_desc with
| Ppat_var _ - > Some pat
| Ppat_constraint ( pat , _ ) - > one_var pat
| _ - > None
match pat.ppat_desc with
| Ppat_var _ -> Some pat
| Ppat_constraint (pat, _) -> one_var pat
| _ -> None *)
let name_loced (pat : pattern) =
match pat.ppat_desc with
| Ppat_var name_loced -> Some name_loced
| Ppat_alias (_, name_loced) -> Some name_loced
| _ -> None
let single_name (pat : pattern) =
match pat.ppat_desc with
| Ppat_var { txt; _ } -> Some txt
| _ -> None
let ctor_lid_loced (pat : pattern) =
match pat.ppat_desc with
| Ppat_construct (lid_loced, _) -> Some lid_loced
| _ -> None
let is_unit pat =
match ctor_lid_loced pat with
| Some { txt = Longident.Lident "()"; _ } -> true
| _ -> false
let is_any pat =
match pat.ppat_desc with
| Ppat_any -> true
| _ -> false
let is_catchall pat =
match pat.ppat_desc with
| Ppat_var _ -> true
| Ppat_any -> true
| _ -> false
let is_name = name_loced %> (<>) None
let is_single_name = single_name %> (<>) None
let name = name_loced %>& Loc_.txt
let names_loced = flatten %>@& name_loced
let names = names_loced %>@ Loc_.txt
let ctor_lids_loced = flatten %>@& ctor_lid_loced
let everything pat = everything (Pat pat)
end
module Case = struct
type t = case
let lhs { pc_lhs; _ } = pc_lhs
let pat { pc_lhs; _ } = pc_lhs
let guard_opt { pc_guard; _ } = pc_guard
let rhs { pc_rhs; _ } = pc_rhs
let names_loced = pat %> Pat.names_loced
let names = names_loced %>@ Loc_.txt
let map_lhs f case = { case with pc_lhs = f case.pc_lhs }
let map_pat = map_lhs
let map_guard f case = { case with pc_guard = Option.map f case.pc_guard }
let map_rhs f case = { case with pc_rhs = f case.pc_rhs }
end
module Vb = struct
include Common(struct
type t = value_binding
let loc { pvb_loc; _ } = pvb_loc
let iterator f =
let iter_vb iter vb = dflt_iter.value_binding iter vb; f vb in
{ dflt_iter with value_binding = iter_vb }
let mapper f =
let map_vb mapper vb = f (dflt_mapper.value_binding mapper vb) in
{ dflt_mapper with value_binding = map_vb }
let mapper_node_f (mapper : Ast_mapper.mapper) = mapper.value_binding
let iterator_node_f (iterator : Ast_iterator.iterator) = iterator.value_binding
end)
let all prog = (everything (Sis prog)).vbs
Vb builders
let to_string vb =
Formatter_to_stringifier.f Pprintast.pattern vb.pvb_pat ^ " = " ^
Pprintast.string_of_expression vb.pvb_expr
(* "pat = expr" -> vb (inverse of to_string) *)
let from_string code =
match "let " ^ code |> Lexing.from_string |> Parse.implementation with
| [{ pstr_desc = Pstr_value (_, [vb]); _ }] -> vb
| struct_items -> failwith @@ "Vb.from_string not a vb: " ^ Pprintast.string_of_structure struct_items
let pat { pvb_pat; _ } = pvb_pat
let exp { pvb_expr; _ } = pvb_expr
let names_loced = pat %> Pat.names_loced
let names = names_loced %>@ Loc_.txt
let map_pat f vb = { vb with pvb_pat = f vb.pvb_pat }
let map_exp f vb = { vb with pvb_expr = f vb.pvb_expr }
(* Resolve as many names to associated expressions as possible. *)
let static_bindings vb =
let rec bind p e =
match p.ppat_desc with
| Ppat_any - > [ ]
| Ppat_var { txt = name ; _ } - > [ ( name , e ) ]
| Ppat_alias ( p ' , { txt = name ; _ } ) - > ( name , e ) : : bind p ' e
| Ppat_constant _ - > [ ]
| Ppat_interval ( _ , _ ) - > [ ]
| ( _ , _ ) - > ( ? ? )
| Ppat_variant ( _ , _ ) - > ( ? ? )
| Ppat_record ( _ , _ ) - > ( ? ? )
| Ppat_array _ - > ( ? ? )
( _ , _ ) - > ( ? ? )
| Ppat_constraint ( _ , _ ) - > ( ? ? )
| Ppat_type _ - > ( ? ? )
| Ppat_lazy _ - > ( ? ? )
| Ppat_unpack _ - > ( ? ? )
| Ppat_exception _ - > ( ? ? )
| Ppat_extension _ - > ( ? ? )
| Ppat_open ( _ , _ ) - > ( ? ? )
in
bind vb.pvb_pat vb.pvb_expr
let rec bind p e =
match p.ppat_desc with
| Ppat_any -> []
| Ppat_var { txt = name; _ } -> [(name, e)]
| Ppat_alias (p', { txt = name; _ }) -> (name, e) :: bind p' e
| Ppat_constant _ -> []
| Ppat_interval (_, _) -> []
| Ppat_tuple ps ->
| Ppat_construct (_, _) -> (??)
| Ppat_variant (_, _) -> (??)
| Ppat_record (_, _) -> (??)
| Ppat_array _ -> (??)
| Ppat_or (_, _) -> (??)
| Ppat_constraint (_, _) -> (??)
| Ppat_type _ -> (??)
| Ppat_lazy _ -> (??)
| Ppat_unpack _ -> (??)
| Ppat_exception _ -> (??)
| Ppat_extension _ -> (??)
| Ppat_open (_, _) -> (??)
in
bind vb.pvb_pat vb.pvb_expr *)
let everything vb = everything (Vb vb)
end
module VbGroups = struct
type t = Asttypes.rec_flag * value_binding list
let clear_empty_vb_groups struct_items =
let map_sis mapper sis =
dflt_mapper.structure mapper sis
|>@? (fun si -> match si.pstr_desc with Pstr_value (_, []) -> false | _ -> true)
in
let map_exp mapper e =
let e' = dflt_mapper.expr mapper e in
match e'.pexp_desc with
| Pexp_let (_, [], body) -> body
| _ -> e'
in
let mapper = { dflt_mapper with structure = map_sis; expr = map_exp } in
mapper.structure mapper struct_items
(* Will also clear out any vb groups that become [] *)
let map f struct_items =
let map_si mapper si =
let si' = dflt_mapper.structure_item mapper si in
match si'.pstr_desc with
| Pstr_value (recflag, vbs) ->
let recflag', vbs' = f (recflag, vbs) in
{ si' with pstr_desc = Pstr_value (recflag', vbs') }
| _ -> si'
in
let map_exp mapper e =
let e' = dflt_mapper.expr mapper e in
match e'.pexp_desc with
| Pexp_let (recflag, vbs, body) ->
let recflag', vbs' = f (recflag, vbs) in
{ e' with pexp_desc = Pexp_let (recflag', vbs', body) }
| _ -> e'
in
let mapper = { dflt_mapper with structure_item = map_si; expr = map_exp } in
mapper.structure mapper struct_items
|> clear_empty_vb_groups
let unit_vbs_to_sequence =
(* Top-level evals are UGLY. Keep them as unit vbs. *)
(* (The camlboot interpreter also tries to print top-level eval results) *)
Exp.map begin fun e ->
match e.pexp_desc with
| Pexp_let (_, [{ pvb_pat; pvb_expr; pvb_attributes; _ }], body) when Pat.is_unit pvb_pat ->
let e1 = { pvb_expr with pexp_attributes = pvb_attributes @ pvb_expr.pexp_attributes } in (* Copy positioning attributes from vb *)
{ e with pexp_desc = Pexp_sequence (e1, body) }
| _ -> e
end
(* The user interface treat sequences as equivalent to let () = e1 in e2 *)
module SequenceLike = struct
let clear_empty_sequences struct_items =
let map_sis mapper sis =
dflt_mapper.structure mapper sis
|>@? (fun si -> match si.pstr_desc with Pstr_eval (e, _) when Exp.is_unit e -> false | _ -> true)
in
let map_exp mapper e =
let e' = dflt_mapper.expr mapper e in
match e'.pexp_desc with
| Pexp_sequence (e1, e2) when Exp.is_unit e1 -> e2
| _ -> e'
in
let mapper = { dflt_mapper with structure = map_sis; expr = map_exp } in
mapper.structure mapper struct_items
(* Return None to remove the exp *)
let map f struct_items =
let map_si mapper si =
let si' = dflt_mapper.structure_item mapper si in
match si'.pstr_desc with
| Pstr_eval (imperative_exp, attrs) ->
let e' = f imperative_exp ||& Exp.unit in
{ si' with pstr_desc = Pstr_eval (e', attrs) }
| _ -> si'
in
let map_exp mapper e =
let e' = dflt_mapper.expr mapper e in
match e'.pexp_desc with
| Pexp_sequence (imperative_exp, e2) ->
let e' = f imperative_exp ||& Exp.unit in
{ e' with pexp_desc = Pexp_sequence (e', e2) }
| _ -> e'
in
let mapper = { dflt_mapper with structure_item = map_si; expr = map_exp } in
mapper.structure mapper struct_items
|> clear_empty_sequences
end
end
Parsetree node attributes
(* We use these for storing visualizers and canvas positions. *)
module Attr = struct
type t = attribute
let name (Location.{ txt; _ }, _) = txt
let payload (_, payload) = payload
let exp_opt = function
| (_, PStr [{ pstr_desc = Pstr_eval (exp, _); _}]) -> Some exp
| _ -> None
(* let exp_of_payload = function
| PStr [{ pstr_desc = Pstr_eval (exp, _); _}] -> Some exp
| _ -> None *)
let findall target_name attrs =
attrs |>@? (name %> (=) target_name)
let findall_exp target_name attrs =
attrs
|>@& begin fun attr ->
if name attr = target_name
then exp_opt attr
else None
end
let find_exp target_name attrs =
List.hd_opt (findall_exp target_name attrs)
let has_tag target_name attrs =
findall target_name attrs <> []
let add_exp target_name exp attrs =
attrs @ [(Loc_.mk target_name, PStr [Ast_helper.Str.eval exp])]
let add_tag target_name attrs =
attrs @ [(Loc_.mk target_name, PStr [])]
(* Compares exps by their unparsed representation *)
let remove_exp target_name exp attrs =
let target_code = Exp.to_string exp in
attrs |>@? begin fun attr ->
name attr <> target_name || (exp_opt attr |>& Exp.to_string) <> Some target_code
end
let remove_name target_name attrs =
attrs |>@? (name %> (<>) target_name)
let set_exp target_name exp = remove_name target_name %> add_exp target_name exp
let set_tag target_name = remove_name target_name %> add_tag target_name
end
module Attrs = struct
let mapper f =
let map_attrs mapper attrs = f (dflt_mapper.attributes mapper attrs) in
{ dflt_mapper with attributes = map_attrs }
let map f prog =
(mapper f).structure (mapper f) prog
let remove_all_deep_mapper = mapper (fun _ -> [])
let remove_all_deep = remove_all_deep_mapper.structure remove_all_deep_mapper
let remove_all_deep_vb = remove_all_deep_mapper.value_binding remove_all_deep_mapper
let remove_all_deep_exp = remove_all_deep_mapper.expr remove_all_deep_mapper
let remove_all_deep_pat = remove_all_deep_mapper.pat remove_all_deep_mapper
end
(* Structure Items ≡ Structure (i.e. a program) *)
module StructItems = struct
type t = structure
let all prog = prog
let to_string = Pprintast.string_of_structure
let from_string = Lexing.from_string %> Parse.implementation
let from_string_opt exp = try Some (from_string exp) with Syntaxerr.Error _ -> None
let vb_groups sis =
sis
|>@& begin fun si ->
match si.pstr_desc with
| Pstr_value (recflag, vbs) -> Some (recflag, vbs)
| _ -> None
end
let vbs = vb_groups %>@@ snd
let names = vbs %>@@ Vb.names
(* Variable names introduced or used. Excludes ctors. *)
(* Includes endings of qualified names, e.g. "x" in Thing.x *)
let deep_names prog =
Ignore names in synth rejection attrs .
let prog = Attrs.map (List.filter (Attr.name %> (<>) "not")) prog in
let everything = everything (Sis prog) in
let pat_names = everything.pats |>@& Pat.name_loced |>@ Loc_.txt in
let ident_names = everything.exps |>@& Exp.ident_lid |>@ Longident.last in
pat_names @ ident_names
let map f struct_items =
let map_sis mapper sis = f (dflt_mapper.structure mapper sis) in
let mapper = { dflt_mapper with structure = map_sis } in
mapper.structure mapper struct_items
end
(* Structure Item (i.e. top-level clauses) *)
module StructItem = struct
include Common(struct
type t = structure_item
let loc { pstr_loc; _ } = pstr_loc
let iterator f =
let iter_si iter si = dflt_iter.structure_item iter si; f si in
{ dflt_iter with structure_item = iter_si }
let mapper f =
let map_si mapper si = f (dflt_mapper.structure_item mapper si) in
{ dflt_mapper with structure_item = map_si }
let mapper_node_f (mapper : Ast_mapper.mapper) = mapper.structure_item
let iterator_node_f (iterator : Ast_iterator.iterator) = iterator.structure_item
end)
let all prog = (everything (Sis prog)).struct_items
include Ast_helper.Str (* Structure item builders *)
let value_opt { pstr_desc; _ } = match pstr_desc with Pstr_value (rec_flag, vbs) -> Some (rec_flag, vbs) | _ -> None
let vbs_opt = value_opt %>& snd
let vbs_names = vbs_opt %>& List.concat_map Vb.names %||& []
let to_string si = Pprintast.string_of_structure [si]
let from_string = StructItems.from_string %> List.hd
(* Will search the loc of all items in a struct_items list, hand that si to f, and replace the si with the list of sis returned by f...to thereby effect removes and deletions *)
let concat_map f prog = StructItems.map (fun si -> si |>@@ f) prog
let concat_map_by pred f prog = concat_map (fun si -> if pred si then f si else [si]) prog
let concat_map_at loc' f prog = concat_map_by (loc %> (=) loc') f prog
end
module Loc = struct
include Loc_
let string_of_origin program loc =
let everything = everything (Sis program) in
let strs =
(everything.vbs |>@? (Vb.loc %> (=) loc) |>@ Vb.to_string) @
(everything.exps |>@? (Exp.loc %> (=) loc) |>@ Exp.to_string) @
(everything.pats |>@? (Pat.loc %> (=) loc) |>@ Pat.to_string) @
(everything.struct_items |>@? (StructItem.loc %> (=) loc) |>@ StructItem.to_string) in
match strs with
| [] -> to_string loc
| [str] -> str
| strs -> "{{" ^ String.concat "|" strs ^ "}}"
(* Introduction and uses of names, by loc of the name string/longindent. *)
(* Incomplete, but this is just for debug anyway *)
(* Mirrors binding_preservation *)
let name_of_origin program loc =
let everything = everything (Sis program) in
let strs =
(everything.pats |>@& Pat.name_loced |>@? (Loc_.loc %> (=) loc) |>@ Loc_.txt) @
(everything.pats |>@& Pat.ctor_lid_loced |>@? (Loc_.loc %> (=) loc) |>@ Loc_.txt |>@ Longident.to_string) @
(everything.exps |>@& Exp.ident_lid_loced |>@? (Loc_.loc %> (=) loc) |>@ Loc_.txt |>@ Longident.to_string) @
(everything.exps |>@& Exp.ctor_lid_loced |>@? (Loc_.loc %> (=) loc) |>@ Loc_.txt |>@ Longident.to_string)
in
match strs with
| [] -> to_string loc
| [str] -> str
| strs -> "{{" ^ String.concat "|" strs ^ "}}"
end | null | https://raw.githubusercontent.com/brianhempel/maniposynth/479e8eef740ab02ea3baa60a7b39ab61e9cde6a8/shared/ast.ml | ocaml | === structure
Fresh positions are given new, negative values.
let none = Location.none
Makes a fresh loc
Uses Location.none
Use Loc.ident for a fresh loc
Follow links/substs to a regular type
See printtyp.ml for "safe_repr" version that catches cycles
For cache keying. Faster than unification.
?(show = false)
let rec safe_repr v = function (* copied from printtyp.ml
~show
(fun b -> if not b then
(if show then print_endline (to_string_raw t1 ^ " <> " ^ to_string_raw t2); b)
else
b
) @@
let p = function None -> "None" | Some str -> "Some \'" ^ str ^ "\'" in
if show then print_endline (p str_opt1 ^ " vs " ^ p str_opt2 ^ " " ^ string_of_bool (str_opt1 = str_opt2));
let rec safe_repr v = function (* copied from printtyp.ml
These all don't work.
Ctype.instance t
Ctype.instance ~partial:false t
Ctype.instance ~partial:true t
let t' = Ctype.correct_levels t in
Ctype.generalize t';
t'
print_endline @@ "Unifying " ^ to_string t1 ^ "\twith " ^ to_string t2;
Ctype.matches Env.empty t1 t2
is_more_general t1 t2
print_endline @@ to_string t1 ^ " !~ " ^ to_string t2;
I think t1 and t2 may still be mutated even if unification fails.
print_endline @@ "Unifying " ^ to_string t1 ^ "\twith " ^ to_string t2;
print_endline @@ "Unifying " ^ to_string t1 ^ "\twith " ^ to_string t2;
Is typ1 equal or more general than typ2?
Stops flattening if a labeled argument is encountered.
e.g. 'a -> 'b -> 'c to ['a, 'b, 'c]
Arg count for arrow types. (Not type arg count).
Stops if a labeled argument is encountered.
Stops flattening if a labeled argument is encountered.
e.g. 'a -> 'b -> 'c to (['a, 'b], 'c)
Bottom up (children mapped before parents).
Note that mutable refs will no longer point to their originals (replaced instead with copies). Shouldn't matter for us.
type t = Node.t
let map_node f = apply_mapper (mapper f)
Returns extracted node, and a function that takes a node and replaces that element.
Physical equality (==) will work here because node is always boxed and was pulled out of prog
Physical equality (==) will work here because node is always boxed and was pulled out of prog
Root element is node rather than the whole program
Returns extracted node, and a function that takes a node and replaces that element.
Physical equality (==) will work here because node is always boxed and was pulled out of root
Physical equality (==) will work here because node is always boxed and was pulled out of root
Return the children left-to-right.
Return the children left-to-right.
module Const = Ast_helper.Const
Exp builders
don't parse module paths
parse module paths
No arg labels, fexp is name
Pat builders
"pat = expr" -> vb (inverse of to_string)
Resolve as many names to associated expressions as possible.
Will also clear out any vb groups that become []
Top-level evals are UGLY. Keep them as unit vbs.
(The camlboot interpreter also tries to print top-level eval results)
Copy positioning attributes from vb
The user interface treat sequences as equivalent to let () = e1 in e2
Return None to remove the exp
We use these for storing visualizers and canvas positions.
let exp_of_payload = function
| PStr [{ pstr_desc = Pstr_eval (exp, _); _}] -> Some exp
| _ -> None
Compares exps by their unparsed representation
Structure Items ≡ Structure (i.e. a program)
Variable names introduced or used. Excludes ctors.
Includes endings of qualified names, e.g. "x" in Thing.x
Structure Item (i.e. top-level clauses)
Structure item builders
Will search the loc of all items in a struct_items list, hand that si to f, and replace the si with the list of sis returned by f...to thereby effect removes and deletions
Introduction and uses of names, by loc of the name string/longindent.
Incomplete, but this is just for debug anyway
Mirrors binding_preservation | open Parsetree
open Util
type everything =
{ vbs : value_binding list
; exps : expression list
; pats : pattern list
; struct_items : structure_item list
}
let dflt_iter = Ast_iterator.default_iterator
let dflt_mapper = Ast_mapper.default_mapper
type node =
| Exp of expression
| Pat of pattern
| Vb of value_binding
| Si of structure_item
| Sis of structure
let everything node =
let vbs = ref [] in
let exps = ref [] in
let pats = ref [] in
let struct_items = ref [] in
let iter =
{ dflt_iter
with value_binding = (fun iter vb -> vbs := vb ::!vbs; dflt_iter.value_binding iter vb)
; expr = (fun iter exp -> exps := exp::!exps; dflt_iter.expr iter exp)
; pat = (fun iter pat -> pats := pat::!pats; dflt_iter.pat iter pat)
; structure_item = (fun iter si -> struct_items := si ::!struct_items; dflt_iter.structure_item iter si)
} in
begin match node with
| Exp exp -> iter.expr iter exp
| Pat pat -> iter.pat iter pat
| Vb vb -> iter.value_binding iter vb
| Si si -> iter.structure_item iter si
| Sis prog -> iter.structure iter prog
end;
{ vbs = !vbs
; exps = !exps
; pats = !pats
; struct_items = !struct_items
}
Module renamed to at the end of this file . Use Loc . Has to do with dependency ordering .
module Loc_ = struct
type t = Location.t
module Pos = struct
type t = Lexing.position
let counter = ref 0
let next () = decr counter; !counter
let newloc_str = "newloc"
let fresh () =
Lexing.{ pos_fname = newloc_str; pos_lnum = next (); pos_bol = -1; pos_cnum = -1 }
let to_string { Lexing.pos_fname; pos_lnum; pos_bol; pos_cnum } =
"{ pos_fname = " ^ pos_fname ^
"; pos_lnum = " ^ string_of_int pos_lnum ^
"; pos_bol = " ^ string_of_int pos_bol ^
"; pos_cnum = " ^ string_of_int pos_cnum ^ " " ^
"}"
let compare pos1 pos2 =
let open Lexing in
Pervasives.compare
(pos1.pos_fname, pos1.pos_cnum, pos1.pos_lnum, pos1.pos_bol)
(pos2.pos_fname, pos2.pos_cnum, pos2.pos_lnum, pos2.pos_bol)
let byte_in_file { Lexing.pos_bol; pos_cnum; _ } =
pos_bol + pos_cnum
end
let fresh () =
Location.{ loc_start = Pos.fresh (); loc_end = Pos.fresh (); loc_ghost = false }
let mk txt = Location.mkloc txt (fresh ())
let loc { Location.loc; txt = _ } = loc
let txt { Location.txt; loc = _ } = txt
Use Longident.lident for Location.none
let lident str = mk (Longident.Lident str)
let to_string { Location.loc_start; loc_end; loc_ghost } =
"{ loc_start = " ^ Pos.to_string loc_start ^
"; loc_end = " ^ Pos.to_string loc_end ^
"; loc_ghost = " ^ string_of_bool loc_ghost ^ " " ^
"}"
let compare loc1 loc2 =
let open Location in
match Pos.compare loc1.loc_start loc2.loc_start with
| 0 ->
begin match Pos.compare loc1.loc_end loc2.loc_end with
| 0 -> Pervasives.compare loc1.loc_ghost loc2.loc_ghost
| n -> n
end
| n -> n
end
module Longident = struct
include Longident
let lident str = Location.mknoloc (Lident str)
let simple_name = function
| Lident name -> Some name
| _ -> None
let to_string = flatten %> String.concat "."
end
module Type = struct
type t = Types.type_expr
let to_string typ = Printtyp.reset (); Formatter_to_stringifier.f Printtyp.type_expr typ
let to_string_raw typ = Printtyp.reset ( ) ; Formatter_to_stringifier.f Printtyp.raw_type_expr typ
let to_string_raw typ = Formatter_to_stringifier.f Printtyp.raw_type_expr typ
let from_core_type ?(env = Env.empty) core_type = (Typetexp.transl_simple_type env false core_type).ctyp_type
let from_string ?(env = Env.empty) str =
Lexing.from_string str
|> Parse.core_type
|> from_core_type ~env
let to_core_type = to_string %> Lexing.from_string %> Parse.core_type
let of_exp ?(type_env = Env.empty) exp = (Typecore.type_exp type_env exp).exp_type
let of_exp_opt ?(type_env = Env.empty) exp =
try Some (of_exp ~type_env exp)
with Typetexp.Error (_loc, type_env, err) ->
Typetexp.report_error type_env Format.std_formatter err;
None
let copy (t : t) : t = Btype.cleanup_abbrev (); Marshal.from_bytes (Marshal.to_bytes t [Closures]) 0
let rec iter f typ = Btype.iter_type_expr (fun t -> iter f t) typ; f typ
let new_var () = Btype.newgenvar ()
let tuple ts = Btype.newgenty (Ttuple ts)
let rec regular typ =
match typ.Types.desc with
| Types.Tlink typ
| Types.Tsubst typ -> regular typ
| _ -> typ
let open Types in
{desc = Tlink t; _} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
in *)
let t1 = regular t1 in
let t2 = regular t2 in
begin
match t1.desc, t2.desc with
| Tvar str_opt1, Tvar str_opt2
| Tunivar str_opt1, Tunivar str_opt2 ->
t1.level = t2.level &&
str_opt1 = str_opt2
| Tarrow (lab1, t_l1, t_r1, comm1)
, Tarrow (lab2, t_l2, t_r2, comm2) ->
let rec get_comm = function Clink { contents = comm } -> get_comm comm | comm -> comm in
lab1 = lab2 && get_comm comm1 = get_comm comm2 && recurse t_l1 t_l2 && recurse t_r1 t_r2
| Ttuple ts1
, Ttuple ts2 -> List.for_all2_safe recurse ts1 ts2
| Tconstr (path1, ts1, _abbrev_memo1)
, Tconstr (path2, ts2, _abbrev_memo2) ->
if show then begin match path1 , with
| Path . Pident , Path . print_endline ( Formatter_to_stringifier.f Ident.print ^ " vs " ^ Formatter_to_stringifier.f Ident.print ^ " is " ^ string_of_bool ( Path.same ) )
| _ - > ( )
end ;
| Path.Pident ident1, Path.Pident ident2 -> print_endline (Formatter_to_stringifier.f Ident.print ident1 ^ " vs " ^ Formatter_to_stringifier.f Ident.print ident2 ^ " is " ^ string_of_bool (Path.same path1 path2))
| _ -> ()
end; *)
Path.same path1 path2 && (
if show then begin
print_endline ( string_of_bool ( List.for_all2_safe recurse ts1 ts2 ) ) ;
print_endline ( " ts1 : " ^ String.concat " , " ( to_string_raw ) ) ;
print_endline ( " ts2 : " ^ String.concat " , " ( ts2 ) ) ;
end ;
print_endline (string_of_bool (List.for_all2_safe recurse ts1 ts2));
print_endline ("ts1: " ^ String.concat ", " (ts1 |>@ to_string_raw));
print_endline ("ts2: " ^ String.concat ", " (ts2 |>@ to_string_raw));
end; *)
List.for_all2_safe recurse ts1 ts2
)
| Tobject (t1, { contents = Some (path1, ts1) })
, Tobject (t2, { contents = Some (path2, ts2) }) ->
recurse t1 t2 && Path.same path1 path2 && List.for_all2_safe recurse ts1 ts2
| Tobject (t1, { contents = None })
, Tobject (t2, { contents = None }) ->
recurse t1 t2
| Tobject _
, Tobject _ -> false
| Tfield (lab1, kind1, t1, t_rest1)
, Tfield (lab2, kind2, t2, t_rest2) ->
lab1 = lab2 && kind1 = kind2 && recurse t1 t2 && recurse t_rest1 t_rest2
| Tnil
, Tnil -> true
| Tvariant row1
, Tvariant row2 ->
List.for_all2_safe begin fun (lab1, field1) (lab2, field2) ->
lab1 = lab2 &&
let rec row_fields_equal_ignoring_id field1 field2 =
match field1, field2 with
| Rpresent (Some t1), Rpresent (Some t2)-> recurse t1 t2
| Rpresent None, Rpresent None -> true
| Reither (bool_a1, ts1, bool_b1, { contents = Some field1 })
, Reither (bool_a2, ts2, bool_b2, { contents = Some field2 }) ->
bool_a1 = bool_a2 &&
List.for_all2_safe recurse ts1 ts2 &&
bool_b1 = bool_b2 &&
row_fields_equal_ignoring_id field1 field2
| Reither (bool_a1, ts1, bool_b1, { contents = None })
, Reither (bool_a2, ts2, bool_b2, { contents = None }) ->
bool_a1 = bool_a2 &&
List.for_all2_safe recurse ts1 ts2 &&
bool_b1 = bool_b2
| Rabsent, Rabsent -> true
| _ -> false
in
row_fields_equal_ignoring_id field1 field2
end row1.row_fields row2.row_fields &&
recurse row1.row_more row2.row_more &&
row1.row_closed = row2.row_closed &&
row1.row_fixed = row2.row_fixed &&
begin match row1.row_name, row2.row_name with
| Some (path1, ts1), Some (path2, ts2) -> Path.same path1 path2 && List.for_all2_safe recurse ts1 ts2
| None, None -> true
| _ -> false
end
| Tpoly (t1, ts1)
, Tpoly (t2, ts2) -> recurse t1 t2 && List.for_all2_safe recurse ts1 ts2
| Tpackage (path1, lids1, ts1)
, Tpackage (path2, lids2, ts2) ->
Path.same path1 path2 && List.for_all2_safe (=) lids1 lids2 && List.for_all2_safe recurse ts1 ts2
| Tlink _, _
| Tsubst _, _
| _, Tlink _
| _, Tsubst _ -> failwith "equal_ignoring_id_and_scope: shouldn't happen"
| _ -> false
end
let rec is_tconstr_with_path target_path typ =
match typ.Types.desc with
| Types.Tconstr (path, _, _) -> path = target_path
| Types.Tlink t
| Types.Tsubst t -> is_tconstr_with_path target_path t
| _ -> false
let is_unit_type = is_tconstr_with_path Predef.path_unit
let is_bool_type = is_tconstr_with_path Predef.path_bool
let is_string_type = is_tconstr_with_path Predef.path_string
let is_int_type = is_tconstr_with_path Predef.path_int
let is_char_type = is_tconstr_with_path Predef.path_char
let is_float_type = is_tconstr_with_path Predef.path_float
let is_exn_type = is_tconstr_with_path Predef.path_exn
let rec is_var_type typ = match typ.Types.desc with
| Types.Tvar _
| Types.Tunivar _ -> true
| Types.Tlink t
| Types.Tsubst t -> is_var_type t
| _ -> false
let rec is_arrow_type typ = match typ.Types.desc with
| Types.Tarrow _ -> true
| Types.Tlink t
| Types.Tsubst t -> is_arrow_type t
| _ -> false
let rec is_ref_type typ =
match typ.Types.desc with
| Types.Tconstr (Path.Pdot (_, "ref", _), _, _) -> true
| Types.Tlink t
| Types.Tsubst t -> is_ref_type t
| _ -> false
let rec var_name typ = match typ.Types.desc with
| Types.Tvar name_opt
| Types.Tunivar name_opt -> name_opt
| Types.Tlink t
| Types.Tsubst t -> var_name t
| _ -> None
let rec tvar_name typ = match typ.Types.desc with
| Types.Tvar name_opt -> name_opt
| Types.Tlink t
| Types.Tsubst t -> tvar_name t
| _ -> None
Deduplicated Tvar / Tunivar names , from left to right .
let names typ =
let names = ref [] in
typ
|> iter begin fun t ->
match t.desc with
| Types.Tvar (Some name)
| Types.Tunivar (Some name) -> if List.mem name !names then () else names := name :: !names
| _ -> ()
end;
List.rev !names
First pass to quickly discard non - unifiable terms .
let rec might_unify t1 t2 =
let open Types in
{desc = Tlink t; _} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
in *)
let recurse = might_unify in
let t1 = regular t1 in
let t2 = regular t2 in
match t1.desc, t2.desc with
| Tvar _, _
| _, Tvar _
| Tunivar _, _
| _, Tunivar _ ->
true
| Tarrow (_lab1, t_l1, t_r1, _comm1)
, Tarrow (_lab2, t_l2, t_r2, _comm2) ->
recurse t_l1 t_l2 && recurse t_r1 t_r2
| Tarrow _, _
| _, Tarrow _ -> false
| Ttuple ts1
, Ttuple ts2 -> List.for_all2_safe recurse ts1 ts2
| Ttuple _, _
| _, Ttuple _ -> false
| Tconstr (_path1, ts1, _abbrev_memo1)
, Tconstr (_path2, ts2, _abbrev_memo2) ->
List.for_all2_safe recurse ts1 ts2
| Tconstr _, _
| _, Tconstr _ -> false
| Tobject _
, Tobject _ ->
true
| Tobject _, _
| _, Tobject _ -> false
| Tfield (lab1, kind1, t1, t_rest1)
, Tfield (lab2, kind2, t2, t_rest2) ->
lab1 = lab2 && kind1 = kind2 && recurse t1 t2 && recurse t_rest1 t_rest2
| Tfield _, _
| _, Tfield _ -> false
| Tnil
, Tnil -> true
| Tnil, _
| _, Tnil -> false
| Tvariant _
, Tvariant _ ->
true
| Tvariant _, _
| _, Tvariant _ -> false
| Tpoly (t1, ts1)
, Tpoly (t2, ts2) -> recurse t1 t2 && List.for_all2_safe recurse ts1 ts2
| Tpoly _, _
| _, Tpoly _ -> false
| Tpackage (_path1, _lids1, ts1)
, Tpackage (_path2, _lids2, ts2) ->
List.for_all2_safe recurse ts1 ts2
| Tpackage _, _
| _, Tpackage _ -> false
| Tlink _, _
| Tsubst _, _ -> failwith "equal_ignoring_id_and_scope: shouldn't happen"
LOOK AT ALL THIS STUFF I TRIED TO NOT MUTATE WHEN TRYING TO UNIFY / SUBTYPE !
( Ctype.correct_levels t )
let is_more_general =
Ctype.moregeneral Env.empty true more_general target
Ctype.moregeneral Env.empty true more_general target *)
May only need type env in case of GADTs , which we do n't care about .
let does_unify t1 t2 =
might_unify t1 t2 &&
try
Ctype.unify Env.empty ( t1 ) ( t2 ) ;
Ctype.unify Env.empty (copy t1) (copy t2);
true
with
| . Error ( _ loc , type_env , err ) - >
Typetexp.report_error type_env Format.std_formatter err ;
false
Typetexp.report_error type_env Format.std_formatter err;
false *)
| _ ->
false
let unify_mutating_opt t1 t2 =
if not (might_unify t1 t2) then None else
try
Ctype.unify Env.empty t1 t2;
Some t1
with _ -> None
let unify_opt t1 t2 =
if not (might_unify t1 t2) then None else
let t1' = copy t1 in
try
Ctype.unify Env.empty t1' (copy t2);
Some t1'
with _ -> None
let is_equal_or_more_general_than typ1 typ2 =
begin fun out - >
print_endline @@ to_string typ1 ^ " \t\t " ^ to_string typ2 ^ " \t\t " ^ ( typ2 | > & to_string || & " - " ) ^ " \t\t " ^ string_of_bool out ;
out
end @@
print_endline @@ to_string typ1 ^ "\t\t" ^ to_string typ2 ^ "\t\t" ^ (unify_opt typ1 typ2 |>& to_string ||& "-") ^ "\t\t" ^ string_of_bool out;
out
end @@ *)
Apparently , unify prefers the Tvars in typ2
| Some typ2' -> to_string typ2' = to_string typ2
| None -> false
let rec flatten_arrows typ =
let open Types in
match typ.desc with
| Tarrow (Nolabel, ltype, rtype, _) -> ltype :: flatten_arrows rtype
| Tlink typ | Tsubst typ -> flatten_arrows typ
| _ -> [typ]
let rec arrow_arg_count typ =
let open Types in
match typ.desc with
| Tarrow (Nolabel, _ltype, rtype, _) -> 1 + arrow_arg_count rtype
| Tlink typ | Tsubst typ -> arrow_arg_count typ
| _ -> 0
let rec args_and_ret typ =
let open Types in
match typ.desc with
| Tarrow (Nolabel, ltype, rtype, Cok) -> args_and_ret rtype |> Tup2.map_fst (List.cons ltype)
| Tlink typ | Tsubst typ -> args_and_ret typ
| _ -> ([], typ)
let arrow t1 t2 =
Btype.newgenty @@ Tarrow (Nolabel, t1, t2, Cok)
let rec unflatten_arrows types =
match types with
| [] -> failwith "shouldn't give an empty type list to Type.unflatten_arrows"
| [t] -> t
| t::rest -> arrow t (unflatten_arrows rest)
let rec flatten typ =
let open Types in
let concat_map = List.concat_map in
let rec flatten_row_field = function
| Rpresent (Some t) -> flatten t
| Rpresent None -> []
| Reither (_, ts, _, { contents = Some row_field }) -> concat_map flatten ts @ flatten_row_field row_field
| Reither (_, ts, _, { contents = None }) -> concat_map flatten ts
| Rabsent -> []
in
typ ::
match typ.desc with
| Tvar _ -> []
| Tarrow (_, l, r, _) -> flatten l @ flatten r
| Ttuple ts -> concat_map flatten ts
| Tconstr (_, ts, _) -> concat_map flatten ts
| Tobject (t, { contents = Some (_, ts) }) -> flatten t @ concat_map flatten ts
| Tobject (t, { contents = None }) -> flatten t
| Tfield (_, _, t1, t2) -> flatten t1 @ flatten t2
| Tnil -> []
| Tlink t -> flatten t
| Tsubst t -> flatten t
| Tunivar _ -> []
| Tpoly (t, ts) -> concat_map flatten (t::ts)
| Tpackage (_, _, ts) -> concat_map flatten ts
| Tvariant { row_fields; row_more; row_name = Some (_, ts); _ } -> (row_fields |>@ snd |>@@ flatten_row_field) @ flatten row_more @ concat_map flatten ts
| Tvariant { row_fields; row_more; row_name = None; _ } -> (row_fields |>@ snd |>@@ flatten_row_field) @ flatten row_more
let rec map f typ =
let open Types in
let recurse = map f in
let rec map_abbrev_memo (abbrev_memo : abbrev_memo) =
match abbrev_memo with
| Mnil ->
Mnil
| Mcons (private_flag, path, abbrev, expansion, memo) ->
Mcons (private_flag, path, recurse abbrev, recurse expansion, map_abbrev_memo memo)
| Mlink memo_ref ->
Mlink { contents = map_abbrev_memo !memo_ref }
in
let map_row_desc { row_fields; row_more; row_bound; row_closed; row_fixed; row_name } =
let rec map_row_field (row_field : row_field) =
match row_field with
| Rpresent None -> row_field
| Rpresent (Some t) -> Rpresent (Some (recurse t))
| Reither (isconst, ts, ispat, { contents = None }) -> Reither (isconst, ts |>@ recurse, ispat, { contents = None })
| Reither (isconst, ts, ispat, { contents = Some row_field }) -> Reither (isconst, ts |>@ recurse, ispat, { contents = Some (map_row_field row_field) })
| Rabsent -> Rabsent
in
{
row_fields = row_fields |>@ (fun (name, row_field) -> (name, map_row_field row_field));
row_more = recurse row_more;
row_bound = row_bound;
row_closed = row_closed;
row_fixed = row_fixed;
row_name = row_name |>& (fun (path, ts) -> (path, ts |>@ recurse))
}
in
match typ.desc with
| Tnil
| Tunivar _
| Tvar _ -> f typ
| Tlink t
| Tsubst t -> f (recurse t)
| Tarrow (lab, l, r, comm) -> f { typ with desc = Tarrow (lab, recurse l, recurse r, comm) }
| Ttuple ts -> f { typ with desc = Ttuple (ts |>@ recurse) }
| Tconstr (path, ts, abbrev) -> f { typ with desc = Tconstr (path, ts |>@ recurse, { contents = map_abbrev_memo !abbrev }) }
| Tobject (t, { contents = Some (path, ts) }) -> f { typ with desc = Tobject (recurse t, { contents = Some (path, ts |>@ recurse) }) }
| Tobject (t, { contents = None }) -> f { typ with desc = Tobject (recurse t, { contents = None }) }
| Tfield (name, fkind, t1, t2) -> f { typ with desc = Tfield (name, fkind, recurse t1, recurse t2) }
| Tpoly (t, ts) -> f { typ with desc = Tpoly (recurse t, ts |>@ recurse) }
| Tpackage (path, lids, ts) -> f { typ with desc = Tpackage (path, lids, ts |>@ recurse) }
| Tvariant row_desc -> f { typ with desc = Tvariant (map_row_desc row_desc) }
let rename_all mapping typ =
typ
|> map begin fun typ ->
match typ.desc with
| Tvar (Some str) -> (match List.assoc_opt str mapping with | Some name' -> { typ with desc = Tvar (Some name') } | None -> typ)
| Tunivar (Some str) -> (match List.assoc_opt str mapping with | Some name' -> { typ with desc = Tunivar (Some name') } | None -> typ)
| _ -> typ
end
let rename name name' typ =
rename_all [(name, name')] typ
end
module Common
(Node : sig
type t
val loc : t -> Location.t
val mapper : (t -> t) -> Ast_mapper.mapper
val iterator : (t -> unit) -> Ast_iterator.iterator
val mapper_node_f : Ast_mapper.mapper -> (Ast_mapper.mapper -> t -> t)
val iterator_node_f : Ast_iterator.iterator -> (Ast_iterator.iterator -> t -> unit)
end) = struct
let loc = Node.loc
let mapper = Node.mapper
let iter f prog =
let iterator = Node.iterator f in
iterator.structure iterator prog
let iterator = Node.iterator
let apply_mapper mapper node = (Node.mapper_node_f mapper) mapper node
let apply_iterator iterator node = (Node.iterator_node_f iterator) iterator node
exception Found of Node.t
let map f struct_items =
let mapper = Node.mapper f in
mapper.structure mapper struct_items
let map_by pred f prog =
map (fun node -> if pred node then f node else node) prog
let map_at target_loc f prog =
map_by (loc %> (=) target_loc) f prog
let replace_by pred node' prog =
map_by pred (fun _ -> node') prog
let replace target_loc = replace_by (loc %> (=) target_loc)
let find_by pred prog : Node.t =
try
prog |> iter (fun node -> if pred node then raise (Found node));
failwith "find_by: couldn't find node"
with Found node -> node
let find_by_opt pred prog : Node.t option =
try
prog |> iter (fun node -> if pred node then raise (Found node));
None
with Found node -> Some node
let find target_loc = find_by (loc %> (=) target_loc)
let find_opt target_loc = find_by_opt (loc %> (=) target_loc)
let exists pred prog = find_by_opt pred prog <> None
let extract_by pred prog : Node.t * (Node.t -> program) =
let node = find_by pred prog in
( node
)
let extract_by_opt pred prog : (Node.t * (Node.t -> program)) option =
find_by_opt pred prog |>& fun node ->
( node
)
let extract target_loc = extract_by (loc %> (=) target_loc)
let extract_opt target_loc = extract_by_opt (loc %> (=) target_loc)
let count pred prog =
let n = ref 0 in
prog |> iter (fun node -> if pred node then incr n);
!n
module FromNode = struct
let iter f root =
let iterator = Node.iterator f in
apply_iterator iterator root
let map f root =
let mapper = Node.mapper f in
apply_mapper mapper root
let map_by pred f root =
map (fun node -> if pred node then f node else node) root
let map_at target_loc f root =
map_by (loc %> (=) target_loc) f root
let replace_by pred node' root =
map_by pred (fun _ -> node') root
let replace target_loc = replace_by (loc %> (=) target_loc)
let find_by pred root : Node.t =
try
root |> iter (fun node -> if pred node then raise (Found node));
failwith "find_by: couldn't find node"
with Found node -> node
let find_by_opt pred root : Node.t option =
try
root |> iter (fun node -> if pred node then raise (Found node));
None
with Found node -> Some node
let find target_loc = find_by (loc %> (=) target_loc)
let find_opt target_loc = find_by_opt (loc %> (=) target_loc)
let exists pred root = find_by_opt pred root <> None
let extract_by pred root : Node.t * (Node.t -> Node.t) =
let node = find_by pred root in
( node
)
let extract_by_opt pred root : (Node.t * (Node.t -> Node.t)) option =
find_by_opt pred root |>& fun node ->
( node
)
let extract target_loc = extract_by (loc %> (=) target_loc)
let extract_opt target_loc = extract_by_opt (loc %> (=) target_loc)
let count pred root =
let n = ref 0 in
root |> iter (fun node -> if pred node then incr n);
!n
end
let child_exps node =
let children = ref [] in
let iter_exp_no_recurse _ e = children := e :: !children in
let iter_once = { dflt_iter with expr = iter_exp_no_recurse } in
(Node.iterator_node_f dflt_iter) iter_once node;
let child_pats node =
let children = ref [] in
let iter_pat_no_recurse _ p = children := p :: !children in
let iter_once = { dflt_iter with pat = iter_pat_no_recurse } in
(Node.iterator_node_f dflt_iter) iter_once node;
let freshen_locs node =
let mapper = { dflt_mapper with location = (fun _ _ -> Loc_.fresh ()) } in
apply_mapper mapper node
end
module Exp = struct
include Common(struct
type t = expression
let loc { pexp_loc; _ } = pexp_loc
let iterator f =
let iter_exp iter e = dflt_iter.expr iter e; f e in
{ dflt_iter with expr = iter_exp }
let mapper f =
let map_exp mapper e = f (dflt_mapper.expr mapper e) in
{ dflt_mapper with expr = map_exp }
let mapper_node_f (mapper : Ast_mapper.mapper) = mapper.expr
let iterator_node_f (iterator : Ast_iterator.iterator) = iterator.expr
end)
let loc = Loc_.fresh () in
ident ~loc { loc = loc; txt = Longident.Lident name }
let loc = Loc_.fresh () in
{ (name |> Lexing.from_string |> Parse.expression) with pexp_loc = loc }
let hole = simple_var "??"
let simple_apply name args = apply (var name) (args |>@ fun arg -> (Asttypes.Nolabel, arg))
let ctor name args =
construct (Loc_.lident name) @@
match args with
| [] -> None
| [arg] -> Some arg
| args -> Some (tuple args)
let int_lit n = constant (Ast_helper.Const.int n)
let string_lit str = constant (Ast_helper.Const.string str)
let unit = construct (Longident.lident "()") None
let apply_with_hole_args fexp n_args = apply fexp @@ List.init n_args (fun _ -> (Asttypes.Nolabel, hole))
let all prog = (everything (Sis prog)).exps
let flatten exp = (everything (Exp exp)).exps
let to_string = Pprintast.string_of_expression
let from_string = Lexing.from_string %> Parse.expression
let from_string_opt exp = try Some (from_string exp) with Syntaxerr.Error _ -> None
let int (exp : expression) =
match exp.pexp_desc with
| Pexp_constant (Pconst_integer (int_str, None)) -> Some (int_of_string int_str)
| _ -> None
let string (exp : expression) =
match exp.pexp_desc with
| Pexp_constant (Pconst_string (str, _)) -> Some str
| _ -> None
let ident_lid_loced (exp : expression) =
match exp.pexp_desc with
| Pexp_ident lid_loced -> Some lid_loced
| _ -> None
let ident_lid = ident_lid_loced %>& Loc_.txt
let simple_name = ident_lid %>&& Longident.simple_name
match exp.pexp_desc with
| Pexp_apply (fexp, labeled_args) ->
begin match simple_name fexp, labeled_args |>@ (function (Asttypes.Nolabel, arg) -> Some arg | _ -> None) |> Option.project with
| Some name, Some unlabeled_args -> Some (name, unlabeled_args)
| _ -> None
end
| _ -> None
let fexp_of_apply (exp : expression) =
match exp.pexp_desc with
| Pexp_apply (fexp, _) -> Some fexp
| _ -> None
let body_of_fun (exp : expression) =
match exp.pexp_desc with
| Pexp_fun (_, _, _, body) -> Some body
| _ -> None
let ctor_lid_loced (exp : expression) =
match exp.pexp_desc with
| Pexp_construct (lid_loced, _) -> Some lid_loced
| _ -> None
let everything exp = everything (Exp exp)
let is_unit exp =
match ctor_lid_loced exp with
| Some { txt = Longident.Lident "()"; _ } -> true
| _ -> false
let is_hole exp =
match exp.pexp_desc with
| Pexp_ident { txt = Longident.Lident "??"; _ } -> true
| _ -> false
let is_fun = function { pexp_desc = Pexp_fun _; _ } -> true | _ -> false
let is_function = function { pexp_desc = Pexp_function _; _ } -> true | _ -> false
let is_funlike exp = is_fun exp || is_function exp
let is_constant = function { pexp_desc = Pexp_constant _; _ } -> true | _ -> false
let is_match = function { pexp_desc = Pexp_match _; _ } -> true | _ -> false
let is_ident = function { pexp_desc = Pexp_ident _; _ } -> true | _ -> false
let is_assert = function { pexp_desc = Pexp_assert _; _ } -> true | _ -> false
let is_ite = function { pexp_desc = Pexp_ifthenelse _; _ } -> true | _ -> false
let is_simple_name = simple_name %> (<>) None
end
module Pat = struct
include Common(struct
type t = pattern
let loc { ppat_loc; _ } = ppat_loc
let iterator f =
let iter_pat iter p = dflt_iter.pat iter p; f p in
{ dflt_iter with pat = iter_pat }
let mapper f =
let map_pat mapper p = f (dflt_mapper.pat mapper p) in
{ dflt_mapper with pat = map_pat }
let mapper_node_f (mapper : Ast_mapper.mapper) = mapper.pat
let iterator_node_f (iterator : Ast_iterator.iterator) = iterator.pat
end)
let all prog = (everything (Sis prog)).pats
let var name =
let loc = Loc_.fresh () in
Ast_helper.Pat.var ~loc { loc = loc; txt = name }
let construct_unqualified ctor_name arg = construct (Longident.lident ctor_name) arg
let unit = construct_unqualified "()" None
let flatten pat = (everything (Pat pat)).pats
let to_string = Formatter_to_stringifier.f Pprintast.pattern
let from_string = Lexing.from_string %> Parse.pattern
let from_string_opt exp = try Some (from_string exp) with Syntaxerr.Error _ -> None
let rec one_var ( pat : pattern ) =
match pat.ppat_desc with
| Ppat_var _ - > Some pat
| Ppat_constraint ( pat , _ ) - > one_var pat
| _ - > None
match pat.ppat_desc with
| Ppat_var _ -> Some pat
| Ppat_constraint (pat, _) -> one_var pat
| _ -> None *)
let name_loced (pat : pattern) =
match pat.ppat_desc with
| Ppat_var name_loced -> Some name_loced
| Ppat_alias (_, name_loced) -> Some name_loced
| _ -> None
let single_name (pat : pattern) =
match pat.ppat_desc with
| Ppat_var { txt; _ } -> Some txt
| _ -> None
let ctor_lid_loced (pat : pattern) =
match pat.ppat_desc with
| Ppat_construct (lid_loced, _) -> Some lid_loced
| _ -> None
let is_unit pat =
match ctor_lid_loced pat with
| Some { txt = Longident.Lident "()"; _ } -> true
| _ -> false
let is_any pat =
match pat.ppat_desc with
| Ppat_any -> true
| _ -> false
let is_catchall pat =
match pat.ppat_desc with
| Ppat_var _ -> true
| Ppat_any -> true
| _ -> false
let is_name = name_loced %> (<>) None
let is_single_name = single_name %> (<>) None
let name = name_loced %>& Loc_.txt
let names_loced = flatten %>@& name_loced
let names = names_loced %>@ Loc_.txt
let ctor_lids_loced = flatten %>@& ctor_lid_loced
let everything pat = everything (Pat pat)
end
module Case = struct
type t = case
let lhs { pc_lhs; _ } = pc_lhs
let pat { pc_lhs; _ } = pc_lhs
let guard_opt { pc_guard; _ } = pc_guard
let rhs { pc_rhs; _ } = pc_rhs
let names_loced = pat %> Pat.names_loced
let names = names_loced %>@ Loc_.txt
let map_lhs f case = { case with pc_lhs = f case.pc_lhs }
let map_pat = map_lhs
let map_guard f case = { case with pc_guard = Option.map f case.pc_guard }
let map_rhs f case = { case with pc_rhs = f case.pc_rhs }
end
module Vb = struct
include Common(struct
type t = value_binding
let loc { pvb_loc; _ } = pvb_loc
let iterator f =
let iter_vb iter vb = dflt_iter.value_binding iter vb; f vb in
{ dflt_iter with value_binding = iter_vb }
let mapper f =
let map_vb mapper vb = f (dflt_mapper.value_binding mapper vb) in
{ dflt_mapper with value_binding = map_vb }
let mapper_node_f (mapper : Ast_mapper.mapper) = mapper.value_binding
let iterator_node_f (iterator : Ast_iterator.iterator) = iterator.value_binding
end)
let all prog = (everything (Sis prog)).vbs
Vb builders
let to_string vb =
Formatter_to_stringifier.f Pprintast.pattern vb.pvb_pat ^ " = " ^
Pprintast.string_of_expression vb.pvb_expr
let from_string code =
match "let " ^ code |> Lexing.from_string |> Parse.implementation with
| [{ pstr_desc = Pstr_value (_, [vb]); _ }] -> vb
| struct_items -> failwith @@ "Vb.from_string not a vb: " ^ Pprintast.string_of_structure struct_items
let pat { pvb_pat; _ } = pvb_pat
let exp { pvb_expr; _ } = pvb_expr
let names_loced = pat %> Pat.names_loced
let names = names_loced %>@ Loc_.txt
let map_pat f vb = { vb with pvb_pat = f vb.pvb_pat }
let map_exp f vb = { vb with pvb_expr = f vb.pvb_expr }
let static_bindings vb =
let rec bind p e =
match p.ppat_desc with
| Ppat_any - > [ ]
| Ppat_var { txt = name ; _ } - > [ ( name , e ) ]
| Ppat_alias ( p ' , { txt = name ; _ } ) - > ( name , e ) : : bind p ' e
| Ppat_constant _ - > [ ]
| Ppat_interval ( _ , _ ) - > [ ]
| ( _ , _ ) - > ( ? ? )
| Ppat_variant ( _ , _ ) - > ( ? ? )
| Ppat_record ( _ , _ ) - > ( ? ? )
| Ppat_array _ - > ( ? ? )
( _ , _ ) - > ( ? ? )
| Ppat_constraint ( _ , _ ) - > ( ? ? )
| Ppat_type _ - > ( ? ? )
| Ppat_lazy _ - > ( ? ? )
| Ppat_unpack _ - > ( ? ? )
| Ppat_exception _ - > ( ? ? )
| Ppat_extension _ - > ( ? ? )
| Ppat_open ( _ , _ ) - > ( ? ? )
in
bind vb.pvb_pat vb.pvb_expr
let rec bind p e =
match p.ppat_desc with
| Ppat_any -> []
| Ppat_var { txt = name; _ } -> [(name, e)]
| Ppat_alias (p', { txt = name; _ }) -> (name, e) :: bind p' e
| Ppat_constant _ -> []
| Ppat_interval (_, _) -> []
| Ppat_tuple ps ->
| Ppat_construct (_, _) -> (??)
| Ppat_variant (_, _) -> (??)
| Ppat_record (_, _) -> (??)
| Ppat_array _ -> (??)
| Ppat_or (_, _) -> (??)
| Ppat_constraint (_, _) -> (??)
| Ppat_type _ -> (??)
| Ppat_lazy _ -> (??)
| Ppat_unpack _ -> (??)
| Ppat_exception _ -> (??)
| Ppat_extension _ -> (??)
| Ppat_open (_, _) -> (??)
in
bind vb.pvb_pat vb.pvb_expr *)
let everything vb = everything (Vb vb)
end
module VbGroups = struct
type t = Asttypes.rec_flag * value_binding list
let clear_empty_vb_groups struct_items =
let map_sis mapper sis =
dflt_mapper.structure mapper sis
|>@? (fun si -> match si.pstr_desc with Pstr_value (_, []) -> false | _ -> true)
in
let map_exp mapper e =
let e' = dflt_mapper.expr mapper e in
match e'.pexp_desc with
| Pexp_let (_, [], body) -> body
| _ -> e'
in
let mapper = { dflt_mapper with structure = map_sis; expr = map_exp } in
mapper.structure mapper struct_items
let map f struct_items =
let map_si mapper si =
let si' = dflt_mapper.structure_item mapper si in
match si'.pstr_desc with
| Pstr_value (recflag, vbs) ->
let recflag', vbs' = f (recflag, vbs) in
{ si' with pstr_desc = Pstr_value (recflag', vbs') }
| _ -> si'
in
let map_exp mapper e =
let e' = dflt_mapper.expr mapper e in
match e'.pexp_desc with
| Pexp_let (recflag, vbs, body) ->
let recflag', vbs' = f (recflag, vbs) in
{ e' with pexp_desc = Pexp_let (recflag', vbs', body) }
| _ -> e'
in
let mapper = { dflt_mapper with structure_item = map_si; expr = map_exp } in
mapper.structure mapper struct_items
|> clear_empty_vb_groups
let unit_vbs_to_sequence =
Exp.map begin fun e ->
match e.pexp_desc with
| Pexp_let (_, [{ pvb_pat; pvb_expr; pvb_attributes; _ }], body) when Pat.is_unit pvb_pat ->
{ e with pexp_desc = Pexp_sequence (e1, body) }
| _ -> e
end
module SequenceLike = struct
let clear_empty_sequences struct_items =
let map_sis mapper sis =
dflt_mapper.structure mapper sis
|>@? (fun si -> match si.pstr_desc with Pstr_eval (e, _) when Exp.is_unit e -> false | _ -> true)
in
let map_exp mapper e =
let e' = dflt_mapper.expr mapper e in
match e'.pexp_desc with
| Pexp_sequence (e1, e2) when Exp.is_unit e1 -> e2
| _ -> e'
in
let mapper = { dflt_mapper with structure = map_sis; expr = map_exp } in
mapper.structure mapper struct_items
let map f struct_items =
let map_si mapper si =
let si' = dflt_mapper.structure_item mapper si in
match si'.pstr_desc with
| Pstr_eval (imperative_exp, attrs) ->
let e' = f imperative_exp ||& Exp.unit in
{ si' with pstr_desc = Pstr_eval (e', attrs) }
| _ -> si'
in
let map_exp mapper e =
let e' = dflt_mapper.expr mapper e in
match e'.pexp_desc with
| Pexp_sequence (imperative_exp, e2) ->
let e' = f imperative_exp ||& Exp.unit in
{ e' with pexp_desc = Pexp_sequence (e', e2) }
| _ -> e'
in
let mapper = { dflt_mapper with structure_item = map_si; expr = map_exp } in
mapper.structure mapper struct_items
|> clear_empty_sequences
end
end
Parsetree node attributes
module Attr = struct
type t = attribute
let name (Location.{ txt; _ }, _) = txt
let payload (_, payload) = payload
let exp_opt = function
| (_, PStr [{ pstr_desc = Pstr_eval (exp, _); _}]) -> Some exp
| _ -> None
let findall target_name attrs =
attrs |>@? (name %> (=) target_name)
let findall_exp target_name attrs =
attrs
|>@& begin fun attr ->
if name attr = target_name
then exp_opt attr
else None
end
let find_exp target_name attrs =
List.hd_opt (findall_exp target_name attrs)
let has_tag target_name attrs =
findall target_name attrs <> []
let add_exp target_name exp attrs =
attrs @ [(Loc_.mk target_name, PStr [Ast_helper.Str.eval exp])]
let add_tag target_name attrs =
attrs @ [(Loc_.mk target_name, PStr [])]
let remove_exp target_name exp attrs =
let target_code = Exp.to_string exp in
attrs |>@? begin fun attr ->
name attr <> target_name || (exp_opt attr |>& Exp.to_string) <> Some target_code
end
let remove_name target_name attrs =
attrs |>@? (name %> (<>) target_name)
let set_exp target_name exp = remove_name target_name %> add_exp target_name exp
let set_tag target_name = remove_name target_name %> add_tag target_name
end
module Attrs = struct
let mapper f =
let map_attrs mapper attrs = f (dflt_mapper.attributes mapper attrs) in
{ dflt_mapper with attributes = map_attrs }
let map f prog =
(mapper f).structure (mapper f) prog
let remove_all_deep_mapper = mapper (fun _ -> [])
let remove_all_deep = remove_all_deep_mapper.structure remove_all_deep_mapper
let remove_all_deep_vb = remove_all_deep_mapper.value_binding remove_all_deep_mapper
let remove_all_deep_exp = remove_all_deep_mapper.expr remove_all_deep_mapper
let remove_all_deep_pat = remove_all_deep_mapper.pat remove_all_deep_mapper
end
module StructItems = struct
type t = structure
let all prog = prog
let to_string = Pprintast.string_of_structure
let from_string = Lexing.from_string %> Parse.implementation
let from_string_opt exp = try Some (from_string exp) with Syntaxerr.Error _ -> None
let vb_groups sis =
sis
|>@& begin fun si ->
match si.pstr_desc with
| Pstr_value (recflag, vbs) -> Some (recflag, vbs)
| _ -> None
end
let vbs = vb_groups %>@@ snd
let names = vbs %>@@ Vb.names
let deep_names prog =
Ignore names in synth rejection attrs .
let prog = Attrs.map (List.filter (Attr.name %> (<>) "not")) prog in
let everything = everything (Sis prog) in
let pat_names = everything.pats |>@& Pat.name_loced |>@ Loc_.txt in
let ident_names = everything.exps |>@& Exp.ident_lid |>@ Longident.last in
pat_names @ ident_names
let map f struct_items =
let map_sis mapper sis = f (dflt_mapper.structure mapper sis) in
let mapper = { dflt_mapper with structure = map_sis } in
mapper.structure mapper struct_items
end
module StructItem = struct
include Common(struct
type t = structure_item
let loc { pstr_loc; _ } = pstr_loc
let iterator f =
let iter_si iter si = dflt_iter.structure_item iter si; f si in
{ dflt_iter with structure_item = iter_si }
let mapper f =
let map_si mapper si = f (dflt_mapper.structure_item mapper si) in
{ dflt_mapper with structure_item = map_si }
let mapper_node_f (mapper : Ast_mapper.mapper) = mapper.structure_item
let iterator_node_f (iterator : Ast_iterator.iterator) = iterator.structure_item
end)
let all prog = (everything (Sis prog)).struct_items
let value_opt { pstr_desc; _ } = match pstr_desc with Pstr_value (rec_flag, vbs) -> Some (rec_flag, vbs) | _ -> None
let vbs_opt = value_opt %>& snd
let vbs_names = vbs_opt %>& List.concat_map Vb.names %||& []
let to_string si = Pprintast.string_of_structure [si]
let from_string = StructItems.from_string %> List.hd
let concat_map f prog = StructItems.map (fun si -> si |>@@ f) prog
let concat_map_by pred f prog = concat_map (fun si -> if pred si then f si else [si]) prog
let concat_map_at loc' f prog = concat_map_by (loc %> (=) loc') f prog
end
module Loc = struct
include Loc_
let string_of_origin program loc =
let everything = everything (Sis program) in
let strs =
(everything.vbs |>@? (Vb.loc %> (=) loc) |>@ Vb.to_string) @
(everything.exps |>@? (Exp.loc %> (=) loc) |>@ Exp.to_string) @
(everything.pats |>@? (Pat.loc %> (=) loc) |>@ Pat.to_string) @
(everything.struct_items |>@? (StructItem.loc %> (=) loc) |>@ StructItem.to_string) in
match strs with
| [] -> to_string loc
| [str] -> str
| strs -> "{{" ^ String.concat "|" strs ^ "}}"
let name_of_origin program loc =
let everything = everything (Sis program) in
let strs =
(everything.pats |>@& Pat.name_loced |>@? (Loc_.loc %> (=) loc) |>@ Loc_.txt) @
(everything.pats |>@& Pat.ctor_lid_loced |>@? (Loc_.loc %> (=) loc) |>@ Loc_.txt |>@ Longident.to_string) @
(everything.exps |>@& Exp.ident_lid_loced |>@? (Loc_.loc %> (=) loc) |>@ Loc_.txt |>@ Longident.to_string) @
(everything.exps |>@& Exp.ctor_lid_loced |>@? (Loc_.loc %> (=) loc) |>@ Loc_.txt |>@ Longident.to_string)
in
match strs with
| [] -> to_string loc
| [str] -> str
| strs -> "{{" ^ String.concat "|" strs ^ "}}"
end |
90e9fe13459b2385a8dc6e16f1b811bd680c70169a2157088542648333b53121 | nikita-volkov/rerebase | Types.hs | module GHC.IO.Encoding.Types
(
module Rebase.GHC.IO.Encoding.Types
)
where
import Rebase.GHC.IO.Encoding.Types
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/GHC/IO/Encoding/Types.hs | haskell | module GHC.IO.Encoding.Types
(
module Rebase.GHC.IO.Encoding.Types
)
where
import Rebase.GHC.IO.Encoding.Types
|
|
888e893df21a246a3051596505c53191a2dfcf34a430f69f59155cf737120aee | ocaml/ocaml-lsp | LibTypes.mli | type t = string
| null | https://raw.githubusercontent.com/ocaml/ocaml-lsp/e57b34d129fe36e86cb1ac6aad6c53b2e1901b49/ocaml-lsp-server/test/e2e/__tests__/workspace_symbol_A/lib/LibTypes.mli | ocaml | type t = string
|
|
e3ef64a000f3b6826d93de344df625147d9e61ecec15378cf0aa86fc7ea706a3 | manuel-serrano/hop | slider.scm | ;*=====================================================================*/
* serrano / prgm / project / hop / hop / widget / slider.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Thu Aug 18 10:01:02 2005 * /
* Last change : Sun Apr 28 10:59:26 2019 ( serrano ) * /
* Copyright : 2005 - 19 * /
;* ------------------------------------------------------------- */
;* The HOP implementation of sliders. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __hopwidget-slider
(library web hop)
(static (class html-slider::xml-element
(klass read-only)
(value read-only)
(min read-only)
(max read-only)
(step read-only)
(onchange read-only)
(onclick read-only)
(caption read-only)))
(export (<SLIDER> . ::obj)))
;*---------------------------------------------------------------------*/
;* object-serializer ::html-foldlist ... */
;* ------------------------------------------------------------- */
;* WARNING: Module initialization prevents this declaration to be */
;* moved to xml_types! */
;*---------------------------------------------------------------------*/
(define (serialize o ctx)
(let ((p (open-output-string)))
(obj->javascript-expr o p ctx)
(close-output-port p)))
(define (unserialize o ctx)
o)
(register-class-serialization! html-slider serialize unserialize)
;*---------------------------------------------------------------------*/
;* <SLIDER> ... */
;*---------------------------------------------------------------------*/
(define-tag <SLIDER> ((id #unspecified string)
(class #unspecified string)
(value 0)
(min 0)
(max 100)
(step 1)
(onchange #f)
(onclick #f)
(caption "top")
(attrs))
(instantiate::html-slider
(tag 'slider)
(klass (if (string? class) class "hop-slider"))
(id (xml-make-id id 'SLIDER))
(value value)
(min min)
(max max)
(step step)
(onchange onchange)
(onclick onclick)
(caption caption)
(attributes attrs)
(body '())))
;*---------------------------------------------------------------------*/
;* valueof ... */
;*---------------------------------------------------------------------*/
(define (valueof attr obj)
(cond
((integer? obj)
obj)
((isa? obj xml-tilde)
(xml-tilde->expression obj))
(else
(error "<SLIDER>" (format "Illegal ~a" attr) obj))))
;*---------------------------------------------------------------------*/
;* xml-write ::html-slider ... */
;*---------------------------------------------------------------------*/
(define-method (xml-write obj::html-slider p backend)
(with-access::html-slider obj (id klass value min max step onchange onclick caption)
(let ((gid (gensym))
(ochg (cond
((isa? onchange xml-tilde)
(xml-tilde->return onchange))
((string? onchange)
onchange)
(else
"")))
(oclk (cond
((isa? onclick xml-tilde)
(xml-tilde->return onclick))
((string? onclick)
onclick)
(else
""))))
(fprintf p "<script id='~a' type='~a'>" gid (hop-mime-type))
(fprint p
"hop_add_event_listener( '" gid "', 'ready', function( e ) { hop_slider_onclick_set( hop_slider_onchange_set( "
"hop_make_slider( "
"document.getElementById( '" gid "' ), "
"'" klass "', "
"'" id "', ")
(xml-write-expression min p)
(display ", " p)
(xml-write-expression max p)
(display ", " p)
(xml-write-expression step p)
(display ", " p)
(xml-write-expression value p)
(display ", " p)
(xml-write-expression caption p)
(fprint p "), function(event) { " ochg " } ),")
(fprint p "function(event) { " oclk " } ) }, false )"))
(display "</script>" p)))
| null | https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/widget/slider.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* The HOP implementation of sliders. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* object-serializer ::html-foldlist ... */
* ------------------------------------------------------------- */
* WARNING: Module initialization prevents this declaration to be */
* moved to xml_types! */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* <SLIDER> ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* valueof ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* xml-write ::html-slider ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / hop / hop / widget / slider.scm * /
* Author : * /
* Creation : Thu Aug 18 10:01:02 2005 * /
* Last change : Sun Apr 28 10:59:26 2019 ( serrano ) * /
* Copyright : 2005 - 19 * /
(module __hopwidget-slider
(library web hop)
(static (class html-slider::xml-element
(klass read-only)
(value read-only)
(min read-only)
(max read-only)
(step read-only)
(onchange read-only)
(onclick read-only)
(caption read-only)))
(export (<SLIDER> . ::obj)))
(define (serialize o ctx)
(let ((p (open-output-string)))
(obj->javascript-expr o p ctx)
(close-output-port p)))
(define (unserialize o ctx)
o)
(register-class-serialization! html-slider serialize unserialize)
(define-tag <SLIDER> ((id #unspecified string)
(class #unspecified string)
(value 0)
(min 0)
(max 100)
(step 1)
(onchange #f)
(onclick #f)
(caption "top")
(attrs))
(instantiate::html-slider
(tag 'slider)
(klass (if (string? class) class "hop-slider"))
(id (xml-make-id id 'SLIDER))
(value value)
(min min)
(max max)
(step step)
(onchange onchange)
(onclick onclick)
(caption caption)
(attributes attrs)
(body '())))
(define (valueof attr obj)
(cond
((integer? obj)
obj)
((isa? obj xml-tilde)
(xml-tilde->expression obj))
(else
(error "<SLIDER>" (format "Illegal ~a" attr) obj))))
(define-method (xml-write obj::html-slider p backend)
(with-access::html-slider obj (id klass value min max step onchange onclick caption)
(let ((gid (gensym))
(ochg (cond
((isa? onchange xml-tilde)
(xml-tilde->return onchange))
((string? onchange)
onchange)
(else
"")))
(oclk (cond
((isa? onclick xml-tilde)
(xml-tilde->return onclick))
((string? onclick)
onclick)
(else
""))))
(fprintf p "<script id='~a' type='~a'>" gid (hop-mime-type))
(fprint p
"hop_add_event_listener( '" gid "', 'ready', function( e ) { hop_slider_onclick_set( hop_slider_onchange_set( "
"hop_make_slider( "
"document.getElementById( '" gid "' ), "
"'" klass "', "
"'" id "', ")
(xml-write-expression min p)
(display ", " p)
(xml-write-expression max p)
(display ", " p)
(xml-write-expression step p)
(display ", " p)
(xml-write-expression value p)
(display ", " p)
(xml-write-expression caption p)
(fprint p "), function(event) { " ochg " } ),")
(fprint p "function(event) { " oclk " } ) }, false )"))
(display "</script>" p)))
|
5f479e00fc34b4504911a6fa99ef56819260bf7dd07e0e5f9cd53921162fa350 | savonet/ocaml-mm | mm_pulseaudio.mli | open Mm_audio
class writer : string -> string -> int -> int -> Audio.IO.Writer.t
| null | https://raw.githubusercontent.com/savonet/ocaml-mm/916b007cc7cc4bf250e6f71203bb36afb4ed8634/external/mm_pulseaudio.mli | ocaml | open Mm_audio
class writer : string -> string -> int -> int -> Audio.IO.Writer.t
|
|
ff760e3dd27cef292c3b532166f60ab8d6e609be3fb04ff4edbb0f3a8984d833 | metabase/metabase | dimension.clj | (ns metabase.models.dimension
"Dimensions are used to define remappings for Fields handled automatically when those Fields are encountered by the
Query Processor. For a more detailed explanation, refer to the documentation in
`metabase.query-processor.middleware.add-dimension-projections`."
(:require
[metabase.models.interface :as mi]
[metabase.models.serialization.base :as serdes.base]
[metabase.models.serialization.hash :as serdes.hash]
[metabase.models.serialization.util :as serdes.util]
[metabase.util.date-2 :as u.date]
[toucan.models :as models]))
Possible values for Dimension.type :
;;;
;;; :internal
;;; :external
(models/defmodel Dimension :dimension)
(mi/define-methods
Dimension
{:types (constantly {:type :keyword})
:properties (constantly {::mi/timestamped? true
::mi/entity-id true})})
(defmethod serdes.hash/identity-hash-fields Dimension
[_dimension]
[(serdes.hash/hydrated-hash :field "<none>")
(serdes.hash/hydrated-hash :human_readable_field "<none>")
:created_at])
;;; ------------------------------------------------- Serialization --------------------------------------------------
Dimensions are inlined onto their parent .
;; We can reuse the [[serdes.base/load-one!]] logic by implementing [[serdes.base/load-xform]] though.
(defmethod serdes.base/load-xform "Dimension"
[dim]
(-> dim
serdes.base/load-xform-basics
No need to handle : field_id , it was just added as the raw ID by the caller ; see Field 's load - one !
(update :human_readable_field_id serdes.util/import-field-fk)
(update :created_at u.date/parse)))
| null | https://raw.githubusercontent.com/metabase/metabase/2d22d3af60fb2c225b60a950a96e21eb7376865d/src/metabase/models/dimension.clj | clojure |
:internal
:external
------------------------------------------------- Serialization --------------------------------------------------
We can reuse the [[serdes.base/load-one!]] logic by implementing [[serdes.base/load-xform]] though.
see Field 's load - one ! | (ns metabase.models.dimension
"Dimensions are used to define remappings for Fields handled automatically when those Fields are encountered by the
Query Processor. For a more detailed explanation, refer to the documentation in
`metabase.query-processor.middleware.add-dimension-projections`."
(:require
[metabase.models.interface :as mi]
[metabase.models.serialization.base :as serdes.base]
[metabase.models.serialization.hash :as serdes.hash]
[metabase.models.serialization.util :as serdes.util]
[metabase.util.date-2 :as u.date]
[toucan.models :as models]))
Possible values for Dimension.type :
(models/defmodel Dimension :dimension)
(mi/define-methods
Dimension
{:types (constantly {:type :keyword})
:properties (constantly {::mi/timestamped? true
::mi/entity-id true})})
(defmethod serdes.hash/identity-hash-fields Dimension
[_dimension]
[(serdes.hash/hydrated-hash :field "<none>")
(serdes.hash/hydrated-hash :human_readable_field "<none>")
:created_at])
Dimensions are inlined onto their parent .
(defmethod serdes.base/load-xform "Dimension"
[dim]
(-> dim
serdes.base/load-xform-basics
(update :human_readable_field_id serdes.util/import-field-fk)
(update :created_at u.date/parse)))
|
de78416f54023a180a9d57866e52a135712e816705c7f6905496f35cffd5020f | igrishaev/dynamodb | time.clj | (ns dynamodb.time
(:import
java.time.Instant
java.time.ZoneId
java.time.format.DateTimeFormatter))
(def ^DateTimeFormatter
aws-formatter
(-> "yyyyMMdd'T'HHmmss'Z'"
(DateTimeFormatter/ofPattern)
(.withZone (ZoneId/of "UTC"))))
(defn aws-now []
(.format aws-formatter (Instant/now)))
| null | https://raw.githubusercontent.com/igrishaev/dynamodb/0a0fef4232daaba91ff9d16c7638cbb0d9aa36bb/src/dynamodb/time.clj | clojure | (ns dynamodb.time
(:import
java.time.Instant
java.time.ZoneId
java.time.format.DateTimeFormatter))
(def ^DateTimeFormatter
aws-formatter
(-> "yyyyMMdd'T'HHmmss'Z'"
(DateTimeFormatter/ofPattern)
(.withZone (ZoneId/of "UTC"))))
(defn aws-now []
(.format aws-formatter (Instant/now)))
|
|
97f0cba9c548aa454d269fdb3ce0ef3bcafc8227511e3992d1ca5a84dbe51ab3 | avsm/mirage-duniverse | text_graph.mli | open! Core_kernel
* This module renders text graphs to visualize data on the terminal . A typical text
graph looks like a bar graph as shown below :
{ [
label1 3786 |----+----1 - ---+----2 - --- ... ----+----7 - ---+----8 - ---+----9 - ---+----|
label2 3653 |----+----1 - ---+----2 - --- ... ----+----7 - ---+----8 - ---+----9 - ---+-
label3 1055 |----+----1 - ---+----2 - ---+--
label4 308 |----+---
label5 70 |-
label6 404 |----+----1
label7 71 |-
label8 32 |
( each ' - ' is approximately 37.860 units . )
] }
graph looks like a bar graph as shown below:
{[
label1 3786 |----+----1----+----2---- ... ----+----7----+----8----+----9----+----|
label2 3653 |----+----1----+----2---- ... ----+----7----+----8----+----9----+-
label3 1055 |----+----1----+----2----+--
label4 308 |----+---
label5 70 |-
label6 404 |----+----1
label7 71 |-
label8 32 |
(each '-' is approximately 37.860 units.)
]}
*)
(** Renders a text graph given labels and values. The list should be non-empty and the
specified values must be positive numbers. Setting narrow enables narrower graphs. *)
val render : ?narrow:bool -> (string * float) list -> string
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/textutils_kernel/src/text_graph.mli | ocaml | * Renders a text graph given labels and values. The list should be non-empty and the
specified values must be positive numbers. Setting narrow enables narrower graphs. | open! Core_kernel
* This module renders text graphs to visualize data on the terminal . A typical text
graph looks like a bar graph as shown below :
{ [
label1 3786 |----+----1 - ---+----2 - --- ... ----+----7 - ---+----8 - ---+----9 - ---+----|
label2 3653 |----+----1 - ---+----2 - --- ... ----+----7 - ---+----8 - ---+----9 - ---+-
label3 1055 |----+----1 - ---+----2 - ---+--
label4 308 |----+---
label5 70 |-
label6 404 |----+----1
label7 71 |-
label8 32 |
( each ' - ' is approximately 37.860 units . )
] }
graph looks like a bar graph as shown below:
{[
label1 3786 |----+----1----+----2---- ... ----+----7----+----8----+----9----+----|
label2 3653 |----+----1----+----2---- ... ----+----7----+----8----+----9----+-
label3 1055 |----+----1----+----2----+--
label4 308 |----+---
label5 70 |-
label6 404 |----+----1
label7 71 |-
label8 32 |
(each '-' is approximately 37.860 units.)
]}
*)
val render : ?narrow:bool -> (string * float) list -> string
|
f1da0a8929645b33afce9c8136393625aa0ba148c411d590adb54191cebc18fb | oliyh/slacky | integration_test.clj | (ns slacky.integration-test
(:require [clj-http.client :as http]
[clojure.core.async :as a]
[clojure.string :as string]
[clojure.test :refer [deftest testing is use-fixtures]]
[conjure.core :as cj]
[slacky
[accounts :as accounts]
[memecaptain :as memecaptain]
[fixture :refer [with-web-api with-database with-fake-internet *db*]]
[service :as service]
[settings :refer [web-port slack-client-id slack-client-secret]]
[bing :as bing]
[slack :as slack]])
(:import [java.util UUID]))
(use-fixtures :once with-web-api with-database)
(defn- slacky-url [path]
(format ":%s%s" (web-port) path))
(deftest can-generate-memes
(with-fake-internet {}
(is (= meme-url
(:body (http/post (slacky-url "/api/meme")
{:throw-exceptions? false
:form-params {:text "cats | cute cats | FTW"}}))))
(cj/verify-called-once-with-args memecaptain/create-direct "" "cute cats" "FTW"))
(testing "400 when bad meme syntax"
(with-fake-internet {}
(let [response (http/post (slacky-url "/api/meme")
{:throw-exceptions? false
:form-params {:text "nil"}})]
(is (= 400 (:status response)))
(is (= "Sorry, the command was not recognised - visit -server.herokuapp.com to learn usage"
(:body response))))
(cj/verify-call-times-for bing/image-search 0)
(cj/verify-call-times-for memecaptain/create-direct 0))))
(def basic-help-message
(str "Create a meme using one of the following patterns:\n"
"[search terms or image url] | [upper] | [lower] \n"
"y u no [lower]\n"
"one does not simply [lower]\n"
"not sure if [upper] or [lower]\n"
"brace yoursel(f|ves) [lower]\n"
"success when [upper] then [lower]\n"
"cry when [upper] then [lower]\n"
"what if i told you [lower]\n"
"[upper] how do they work?\n"
"[upper] all the [lower]\n"
"[upper] [upper] everywhere\n"
"good news everyone [lower]\n"
"the [upper] is too damn high\n"
"[upper] why not zoidberg?\n\n"
"Create a template to use in memes:\n"
"/meme :template [name of template] \n\n"
"Delete a template\n"
"/meme :delete-template [name of template]"))
(deftest can-register-with-slack-oauth
(testing "can successfully register slack app"
(with-fake-internet {:slack-oauth-response {:team-id "slack-team-id"}}
(http/get (slacky-url "/api/oauth/slack") {:query-params {:code "slack-code"}})
(cj/verify-called-once-with-args slack/api-access (slack-client-id) (slack-client-secret) "slack-code")
(testing "account exists"
(is (:id (accounts/lookup-slack-account *db* "slack-team-id")))))))
(deftest can-integrate-with-slack
(let [token (clojure.string/replace (str (UUID/randomUUID)) "-" "")
response-url ""
channel-name "my-channel"
user-name "the-user"
slack-post! (fn [text]
(:body (http/post (slacky-url "/api/slack/meme")
{:throw-exceptions? false
:form-params {:token token
:team_id "a"
:team_domain "b"
:channel_id "c"
:channel_name channel-name
:user_id "d"
:user_name user-name
:command "/meme"
:text text
:response_url response-url}})))]
(testing "alerts on bad syntax"
(with-fake-internet {}
(is (= "Sorry, the command was not recognised, try '/meme :help' for help"
(slack-post! "how does this work?")))))
(testing "can ask for help"
(with-fake-internet {}
(is (= basic-help-message
(slack-post! ":help")))))
(testing "can meme from a channel"
(with-fake-internet {}
(is (= "Your meme is on its way"
(slack-post! "cats | cute cats | FTW")))
(is (= [response-url "in_channel"
(slack/->message :meme user-name "cats | cute cats | FTW" meme-url)]
(first (a/alts!! [slack-channel (a/timeout 500)]))))))
(testing "can register a template"
(with-fake-internet {:template-id "cute-cat-template-id"}
(is (= "Your template is being registered"
(slack-post! ":template cute cats ")))
(is (= [response-url "in_channel"
(slack/->message :add-template user-name nil
"cute cats" "")]
(first (a/alts!! [slack-channel (a/timeout 500)]))))
(testing "and can use it in a meme"
(is (= "Your meme is on its way"
(slack-post! "cute cats | omg | so cute")))
(is (= [response-url "in_channel"
(slack/->message :meme user-name "cute cats | omg | so cute" meme-url)]
(first (a/alts!! [slack-channel (a/timeout 500)]))))
(cj/verify-first-call-args-for memecaptain/create-direct "" "omg" "so cute"))
(testing "which shows up in help message"
(is (= (str basic-help-message
"\n\n"
(string/join "\n"
["Custom templates:"
"cute cats"]))
(slack-post! ":help"))))
(testing "and delete it"
(is (= "Your template is being deleted"
(slack-post! ":delete-template cute cats")))
(is (= [response-url "in_channel"
(slack/->message :delete-template user-name nil "cute cats")]
(first (a/alts!! [slack-channel (a/timeout 500)])))))))))
(deftest can-integrate-with-browser-plugins
(with-fake-internet {}
(is (= meme-url
(:body (http/post (slacky-url "/api/browser-plugin/meme")
{:throw-exceptions? false
:form-params {:token (str (UUID/randomUUID))
:text "cats | cute cats | FTW"}}))))
(cj/verify-called-once-with-args memecaptain/create-direct "" "cute cats" "FTW"))
(testing "400 when bad meme syntax"
(with-fake-internet {}
(let [response (http/post (slacky-url "/api/browser-plugin/meme")
{:throw-exceptions? false
:form-params {:token (str (UUID/randomUUID))
:text "nil"}})]
(is (= 400 (:status response)))
(is (= "Sorry, the command was not recognised - visit -server.herokuapp.com to learn usage"
(:body response))))
(cj/verify-call-times-for bing/image-search 0)
(cj/verify-call-times-for memecaptain/create-direct 0))))
| null | https://raw.githubusercontent.com/oliyh/slacky/909110e0555b7e443c3cf014c7c34b00b31c1a18/test/clj/slacky/integration_test.clj | clojure | (ns slacky.integration-test
(:require [clj-http.client :as http]
[clojure.core.async :as a]
[clojure.string :as string]
[clojure.test :refer [deftest testing is use-fixtures]]
[conjure.core :as cj]
[slacky
[accounts :as accounts]
[memecaptain :as memecaptain]
[fixture :refer [with-web-api with-database with-fake-internet *db*]]
[service :as service]
[settings :refer [web-port slack-client-id slack-client-secret]]
[bing :as bing]
[slack :as slack]])
(:import [java.util UUID]))
(use-fixtures :once with-web-api with-database)
(defn- slacky-url [path]
(format ":%s%s" (web-port) path))
(deftest can-generate-memes
(with-fake-internet {}
(is (= meme-url
(:body (http/post (slacky-url "/api/meme")
{:throw-exceptions? false
:form-params {:text "cats | cute cats | FTW"}}))))
(cj/verify-called-once-with-args memecaptain/create-direct "" "cute cats" "FTW"))
(testing "400 when bad meme syntax"
(with-fake-internet {}
(let [response (http/post (slacky-url "/api/meme")
{:throw-exceptions? false
:form-params {:text "nil"}})]
(is (= 400 (:status response)))
(is (= "Sorry, the command was not recognised - visit -server.herokuapp.com to learn usage"
(:body response))))
(cj/verify-call-times-for bing/image-search 0)
(cj/verify-call-times-for memecaptain/create-direct 0))))
(def basic-help-message
(str "Create a meme using one of the following patterns:\n"
"[search terms or image url] | [upper] | [lower] \n"
"y u no [lower]\n"
"one does not simply [lower]\n"
"not sure if [upper] or [lower]\n"
"brace yoursel(f|ves) [lower]\n"
"success when [upper] then [lower]\n"
"cry when [upper] then [lower]\n"
"what if i told you [lower]\n"
"[upper] how do they work?\n"
"[upper] all the [lower]\n"
"[upper] [upper] everywhere\n"
"good news everyone [lower]\n"
"the [upper] is too damn high\n"
"[upper] why not zoidberg?\n\n"
"Create a template to use in memes:\n"
"/meme :template [name of template] \n\n"
"Delete a template\n"
"/meme :delete-template [name of template]"))
(deftest can-register-with-slack-oauth
(testing "can successfully register slack app"
(with-fake-internet {:slack-oauth-response {:team-id "slack-team-id"}}
(http/get (slacky-url "/api/oauth/slack") {:query-params {:code "slack-code"}})
(cj/verify-called-once-with-args slack/api-access (slack-client-id) (slack-client-secret) "slack-code")
(testing "account exists"
(is (:id (accounts/lookup-slack-account *db* "slack-team-id")))))))
(deftest can-integrate-with-slack
(let [token (clojure.string/replace (str (UUID/randomUUID)) "-" "")
response-url ""
channel-name "my-channel"
user-name "the-user"
slack-post! (fn [text]
(:body (http/post (slacky-url "/api/slack/meme")
{:throw-exceptions? false
:form-params {:token token
:team_id "a"
:team_domain "b"
:channel_id "c"
:channel_name channel-name
:user_id "d"
:user_name user-name
:command "/meme"
:text text
:response_url response-url}})))]
(testing "alerts on bad syntax"
(with-fake-internet {}
(is (= "Sorry, the command was not recognised, try '/meme :help' for help"
(slack-post! "how does this work?")))))
(testing "can ask for help"
(with-fake-internet {}
(is (= basic-help-message
(slack-post! ":help")))))
(testing "can meme from a channel"
(with-fake-internet {}
(is (= "Your meme is on its way"
(slack-post! "cats | cute cats | FTW")))
(is (= [response-url "in_channel"
(slack/->message :meme user-name "cats | cute cats | FTW" meme-url)]
(first (a/alts!! [slack-channel (a/timeout 500)]))))))
(testing "can register a template"
(with-fake-internet {:template-id "cute-cat-template-id"}
(is (= "Your template is being registered"
(slack-post! ":template cute cats ")))
(is (= [response-url "in_channel"
(slack/->message :add-template user-name nil
"cute cats" "")]
(first (a/alts!! [slack-channel (a/timeout 500)]))))
(testing "and can use it in a meme"
(is (= "Your meme is on its way"
(slack-post! "cute cats | omg | so cute")))
(is (= [response-url "in_channel"
(slack/->message :meme user-name "cute cats | omg | so cute" meme-url)]
(first (a/alts!! [slack-channel (a/timeout 500)]))))
(cj/verify-first-call-args-for memecaptain/create-direct "" "omg" "so cute"))
(testing "which shows up in help message"
(is (= (str basic-help-message
"\n\n"
(string/join "\n"
["Custom templates:"
"cute cats"]))
(slack-post! ":help"))))
(testing "and delete it"
(is (= "Your template is being deleted"
(slack-post! ":delete-template cute cats")))
(is (= [response-url "in_channel"
(slack/->message :delete-template user-name nil "cute cats")]
(first (a/alts!! [slack-channel (a/timeout 500)])))))))))
(deftest can-integrate-with-browser-plugins
(with-fake-internet {}
(is (= meme-url
(:body (http/post (slacky-url "/api/browser-plugin/meme")
{:throw-exceptions? false
:form-params {:token (str (UUID/randomUUID))
:text "cats | cute cats | FTW"}}))))
(cj/verify-called-once-with-args memecaptain/create-direct "" "cute cats" "FTW"))
(testing "400 when bad meme syntax"
(with-fake-internet {}
(let [response (http/post (slacky-url "/api/browser-plugin/meme")
{:throw-exceptions? false
:form-params {:token (str (UUID/randomUUID))
:text "nil"}})]
(is (= 400 (:status response)))
(is (= "Sorry, the command was not recognised - visit -server.herokuapp.com to learn usage"
(:body response))))
(cj/verify-call-times-for bing/image-search 0)
(cj/verify-call-times-for memecaptain/create-direct 0))))
|
|
ac27dbff76ab1211a3926bc2e37073fc781961541a98f00f71d3e5db0fd37f2c | reborg/clojure-essential-reference | 2.clj | (import '[java.sql ResultSet ResultSetMetaData])
< 1 >
(reify
ResultSet
(getMetaData [_]
(reify
ResultSetMetaData
(getColumnCount [_] (count attrs))
(getColumnLabel [_ idx] (nth attrs (dec idx)))))
(next [_] true)
(close [_])
(^Object getObject [_ ^int idx] (rand-int 1000))))
< 2 >
{ : i d 886 , : count 433 }
{ : i d 211 , : count 431 }
{ : i d 51 , : count 939 } ) | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/Sequences/OtherGenerators/resultset-seq/2.clj | clojure | (import '[java.sql ResultSet ResultSetMetaData])
< 1 >
(reify
ResultSet
(getMetaData [_]
(reify
ResultSetMetaData
(getColumnCount [_] (count attrs))
(getColumnLabel [_ idx] (nth attrs (dec idx)))))
(next [_] true)
(close [_])
(^Object getObject [_ ^int idx] (rand-int 1000))))
< 2 >
{ : i d 886 , : count 433 }
{ : i d 211 , : count 431 }
{ : i d 51 , : count 939 } ) |
|
12a1e5b49c808e7f6fbe6956c5069e3940168a3560142b26afa5ba3e0bec41c5 | Interlisp/medley | construct.lisp | -*-Mode : LISP ; Package:(CLOS LISP 1000 ) ; ; Syntax : Common - lisp -*-
;;;
;;; *************************************************************************
Copyright ( c ) 1991 Venue
;;; All rights reserved.
;;; *************************************************************************
;;;
;;;
;;; This file defines the defconstructor and other make-instance optimization
;;; mechanisms.
;;;
(in-package 'clos)
;;;
;;; defconstructor is used to define special purpose functions which just
call make - instance with a symbol as the first argument . The semantics
;;; of defconstructor is that it is equivalent to defining a function which
;;; just calls make-instance. The purpose of defconstructor is to provide
CLOS with a way of noticing these calls to make - instance so that it can
optimize them . Specific ports of CLOS could just have their compiler
;;; spot these calls to make-instance and then call this code. Having the
special defconstructor facility is the best we can do portably .
;;;
;;;
;;; A call to defconstructor like:
;;;
;;; (defconstructor make-foo foo (a b &rest r) a a :mumble b baz r)
;;;
;;; Is equivalent to a defun like:
;;;
;;; (defun make-foo (a b &rest r)
;;; (make-instance 'foo 'a a ':mumble b 'baz r))
;;;
;;; Calls like the following are also legal:
;;;
;;; (defconstructor make-foo foo ())
;;; (defconstructor make-bar bar () :x *x* :y *y*)
;;; (defconstructor make-baz baz (a b c) a-b (list a b) b-c (list b c))
;;;
;;;
;;; The general idea of this implementation is that the expansion of the
;;; defconstructor form includes the creation of closure generators which
;;; can be called to create constructor code for the class. The ways that
;;; a constructor can be optimized depends not only on the defconstructor
;;; form, but also on the state of the class and the generic functions in
;;; the initialization protocol. Because of this, the determination of the
form of constructor code to be used is a two part process .
;;;
;;; At compile time, make-constructor-code-generators looks at the actual
;;; defconstructor form and makes a list of appropriate constructor code
;;; generators. All that is really taken into account here is whether
;;; any initargs are supplied in the call to make-instance, and whether
;;; any of those are constant.
;;;
;;; At constructor code generation time (see note about lazy evaluation)
;;; compute-constructor-code calls each of the constructor code generators
;;; to try to get code for this constructor. Each generator looks at the
;;; state of the class and initialization protocol generic functions and
;;; decides whether its type of code is appropriate. This depends on things
;;; like whether there are any applicable methods on initialize-instance,
;;; whether class slots are affected by initialization etc.
;;;
;;;
;;; Constructor objects are funcallable instances, the protocol followed to
;;; to compute the constructor code for them is quite similar to the protocol
;;; followed to compute the discriminator code for a generic function. When
the constructor is first loaded , we install as its code a function which
will compute the actual constructor code the first time it is called .
;;;
;;; If there is an update to the class structure which might invalidate the
;;; optimized constructor, the special lazy constructor installer is put back
;;; so that it can compute the appropriate constructor when it is called.
;;; This is the same kind of lazy evaluation update strategy used elswhere
in CLOS .
;;;
To allow for flexibility in the CLOS implementation and to allow CLOS users
;;; to specialize this constructor facility for their own metaclasses, there
;;; is an internal protocol followed by the code which loads and installs
;;; the constructors. This is documented in the comments in the code.
;;;
;;; This code is also designed so that one of its levels, can be used to
;;; implement optimization of calls to make-instance which can't go through
;;; the defconstructor facility. This has not been implemented yet, but the
;;; hooks are there.
;;;
;;;
(defmacro defconstructor
(name class lambda-list &rest initialization-arguments)
(expand-defconstructor class
name
lambda-list
(copy-list initialization-arguments)))
(defun expand-defconstructor (class-name name lambda-list supplied-initargs)
(let ((class (find-class class-name nil))
(supplied-initarg-names
(gathering1 (collecting)
(iterate ((name (*list-elements supplied-initargs :by #'cddr)))
(gather1 name)))))
(when (null class)
(error "defconstructor form being compiled (or evaluated) before~@
class ~S is defined."
class-name))
`(progn
;; In order to avoid undefined function warnings, we want to tell
;; the compile time environment that a function with this name and
;; this argument list has been defined. The portable way to do this
;; is with defun.
(proclaim '(notinline ,name))
(defun ,name ,lambda-list
(declare (ignore ,@(specialized-lambda-list-parameters lambda-list)))
(error "Constructor ~S not loaded." ',name))
,(make-top-level-form `(defconstructor ,name)
'(load eval)
`(load-constructor
',class-name
',(class-name (class-of class))
',name
',supplied-initarg-names
;; make-constructor-code-generators is called to return a list
;; of constructor code generators. The actual interpretation
;; of this list is left to compute-constructor-code, but the
;; general idea is that it should be an plist where the keys
;; name a kind of constructor code and the values are generator
;; functions which return the actual constructor code. The
;; constructor code is usually a closures over the arguments
;; to the generator.
,(make-constructor-code-generators class
name
lambda-list
supplied-initarg-names
supplied-initargs))))))
(defun load-constructor (class-name metaclass-name constructor-name
supplied-initarg-names code-generators)
(let ((class (find-class class-name nil)))
(cond ((null class)
(error "defconstructor form being loaded (or evaluated) before~@
class ~S is defined."
class-name))
((neq (class-name (class-of class)) metaclass-name)
(error "When defconstructor ~S was compiled, the metaclass of the~@
class ~S was ~S. The metaclass is now ~S.~@
The constructor must be recompiled."
constructor-name
class-name
metaclass-name
(class-name (class-of class))))
(t
(load-constructor-internal class
constructor-name
supplied-initarg-names
code-generators)
constructor-name))))
;;;
;;; The actual constructor objects.
;;;
(defclass constructor ()
((class ;The class with which this
:initarg :class ;constructor is associated.
:reader constructor-class) ;The actual class object,
;not the class name.
;
(name ;The name of this constructor.
:initform nil ;This is the symbol in whose
:initarg :name ;function cell the constructor
:reader constructor-name) ;usually sits. Of course, this
;is optional. defconstructor
;makes named constructors, but
;it is possible to manipulate
;anonymous constructors also.
;
(code-type ;The type of code currently in
:initform nil ;use by this constructor. This
:accessor constructor-code-type) ;is mostly for debugging and
;analysis purposes.
;The lazy installer sets this
to LAZY . The most basic and
;least optimized type of code
is called FALLBACK .
;
(supplied-initarg-names ;The names of the initargs this
:initarg :supplied-initarg-names ;constructor supplies when it
:reader ;"calls" make-instance.
constructor-supplied-initarg-names) ;
;
(code-generators ;Generators for the different
:initarg :code-generators ;types of code this constructor
:reader constructor-code-generators)) ;could use.
(:metaclass funcallable-standard-class))
;;;
;;; Because the value in the code-type slot should always correspond to the
;;; funcallable-instance-function of the constructor, this function should
;;; always be used to set the both at the same time.
;;;
(defun set-constructor-code (constructor code type)
(set-funcallable-instance-function constructor code)
(set-function-name constructor (constructor-name constructor))
(setf (constructor-code-type constructor) type))
(defmethod print-object ((constructor constructor) stream)
(printing-random-thing (constructor stream)
(format stream
"~S ~S (~S)"
(or (class-name (class-of constructor)) "Constructor")
(or (constructor-name constructor) "Anonymous")
(constructor-code-type constructor))))
(defmethod describe-object ((constructor constructor) stream)
(format stream
"~S is a constructor for the class ~S.~%~
The current code type is ~S.~%~
Other possible code types are ~S."
constructor (constructor-class constructor)
(constructor-code-type constructor)
(gathering1 (collecting)
(doplist (key val) (constructor-code-generators constructor)
(gather1 key)))))
;;;
;;; I am not in a hairy enough mood to make this implementation be metacircular
;;; enough that it can support a defconstructor for constructor objects.
;;;
(defun make-constructor (class name supplied-initarg-names code-generators)
(make-instance 'constructor
:class class
:name name
:supplied-initarg-names supplied-initarg-names
:code-generators code-generators))
; This definition actually appears in std-class.lisp.
;(defmethod class-constructors ((class std-class))
( with - slots ( plist ) class ( getf plist ' constructors ) ) )
(defmethod add-constructor ((class std-class)
(constructor constructor))
(with-slots (plist) class
(pushnew constructor (getf plist 'constructors))))
(defmethod remove-constructor ((class std-class)
(constructor constructor))
(with-slots (plist) class
(setf (getf plist 'constructors)
(delete constructor (getf plist 'constructors)))))
(defmethod get-constructor ((class std-class) name &optional (error-p t))
(or (dolist (c (class-constructors class))
(when (eq (constructor-name c) name) (return c)))
(if error-p
(error "Couldn't find a constructor with name ~S for class ~S."
name class)
())))
;;;
;;; This is called to actually load a defconstructor constructor. It must
;;; install the lazy installer in the function cell of the constructor name,
;;; and also add this constructor to the list of constructors the class has.
;;;
(defmethod load-constructor-internal
((class std-class) name initargs generators)
(let ((constructor (make-constructor class name initargs generators))
(old (get-constructor class name nil)))
(when old (remove-constructor class old))
(install-lazy-constructor-installer constructor)
(add-constructor class constructor)
(setf (symbol-function name) constructor)))
(defmethod install-lazy-constructor-installer ((constructor constructor))
(let ((class (constructor-class constructor)))
(set-constructor-code constructor
#'(lambda (&rest args)
(multiple-value-bind (code type)
(compute-constructor-code class constructor)
(prog1 (apply code args)
(set-constructor-code constructor
code
type))))
'lazy)))
;;;
;;; The interface to keeping the constructors updated.
;;;
;;; add-method and remove-method (for standard-generic-function and -method),
;;; promise to call maybe-update-constructors on the generic function and
;;; the method.
;;;
;;; The class update code promises to call update-constructors whenever the
;;; class is changed. That is, whenever the supers, slots or options change.
;;; If user defined classes of constructor needs to be updated in more than
;;; these circumstances, they should use the dependent updating mechanism to
;;; make sure update-constructors is called.
;;;
;;; Bootstrapping concerns force the definitions of maybe-update-constructors
;;; and update-constructors to be in the file std-class. For clarity, they
;;; also appear below. Be sure to keep the definition here and there in sync.
;;;
;(defvar *initialization-generic-functions*
; (list #'make-instance
; #'default-initargs
; #'allocate-instance
; #'initialize-instance
; #'shared-initialize))
;
;(defmethod maybe-update-constructors
; ((generic-function generic-function)
; (method method))
; (when (memq generic-function *initialization-generic-functions*)
; (labels ((recurse (class)
; (update-constructors class)
( dolist ( subclass ( class - direct - subclasses class ) )
; (recurse subclass))))
; (when (classp (car (method-specializers method)))
; (recurse (car (method-specializers method)))))))
;
;(defmethod update-constructors ((class std-class))
( dolist ( cons ( class - constructors class ) )
; (install-lazy-constructor-installer cons)))
;
;(defmethod update-constructors ((class class))
; ())
;;;
;;; Here is the actual smarts for making the code generators and then trying
;;; each generator to get constructor code. This extensible mechanism allows
;;; new kinds of constructor code types to be added. A programmer defining a
;;; specialization of the constructor class can either use this mechanism to
;;; define new code types, or can override this mechanism by overriding the
;;; methods on make-constructor-code-generators and compute-constructor-code.
;;;
;;; The function defined by define-constructor-code-type will receive the
class object , and the 4 original arguments to defconstructor . It can
;;; return a constructor code generator, or return nil if this type of code
;;; is determined to not be appropriate after looking at the defconstructor
;;; arguments.
;;;
When compute - constructor - code is called , it first performs basic checks
;;; to make sure that the basic assumptions common to all the code types are
;;; valid. (For details see method definition). If any of the tests fail,
;;; the fallback constructor code type is used. If none of the tests fail,
the constructor code generators are called in order . They receive 5
;;; arguments:
;;;
;;; CLASS the class the constructor is making instances of
;;; WRAPPER that class's wrapper
DEFAULTS the result of calling class - default - initargs on class
INITIALIZE the applicable methods on initialize - instance
SHARED the applicable methosd on shared - initialize
;;;
The first code generator to return code is used . The code generators are
;;; called in reverse order of definition, so define-constructor-code-type
;;; forms which define better code should appear after ones that define less
good code . The fallback code type appears first . Note that redefining a
;;; code type does not change its position in the list. To do that, define
;;; a new type at the end with the behavior.
;;;
(defvar *constructor-code-types* ())
(defmacro define-constructor-code-type (type arglist &body body)
(let ((fn-name (intern (format nil
"CONSTRUCTOR-CODE-GENERATOR ~A ~A"
(package-name (symbol-package type))
(symbol-name type))
*the-clos-package*)))
`(progn
(defun ,fn-name ,arglist .,body)
(load-define-constructor-code-type ',type ',fn-name))))
(defun load-define-constructor-code-type (type generator)
(let ((old-entry (assq type *constructor-code-types*)))
(if old-entry
(setf (cadr old-entry) generator)
(push (list type generator) *constructor-code-types*))
type))
(defmethod make-constructor-code-generators
((class std-class)
name lambda-list supplied-initarg-names supplied-initargs)
(cons 'list
(gathering1 (collecting)
(dolist (entry *constructor-code-types*)
(let ((generator
(funcall (cadr entry) class name lambda-list
supplied-initarg-names
supplied-initargs)))
(when generator
(gather1 `',(car entry))
(gather1 generator)))))))
(defmethod compute-constructor-code ((class std-class)
(constructor constructor))
(let* ((proto (class-prototype class))
(wrapper (class-wrapper class))
(defaults (class-default-initargs class))
(make
(compute-applicable-methods #'make-instance (list class)))
(supplied-initarg-names
(constructor-supplied-initarg-names constructor))
(default
(compute-applicable-methods #'default-initargs
(list class supplied-initarg-names))) ;?
(allocate
(compute-applicable-methods #'allocate-instance (list class)))
(initialize
(compute-applicable-methods #'initialize-instance (list proto)))
(shared
(compute-applicable-methods #'shared-initialize (list proto t)))
(code-generators
(constructor-code-generators constructor))
(code-generators
(constructor-code-generators constructor)))
(flet ((call-code-generator (generator)
(when (null generator)
(unless (setq generator (getf code-generators 'fallback))
(error "No FALLBACK generator?")))
(funcall generator class wrapper defaults initialize shared)))
(if (or (cdr make)
(cdr default)
(cdr allocate)
(check-initargs class
supplied-initarg-names
defaults
(append initialize shared)))
These are basic shared assumptions , if one of the
;; has been violated, we have to resort to the fallback
;; case. Any of these assumptions could be moved out
;; of here and into the individual code types if there
;; was a need to do so.
(values (call-code-generator nil) 'fallback)
Otherwise try all the generators until one produces
;; code for us.
(doplist (type generator) code-generators
(let ((code (call-code-generator generator)))
(when code (return (values code type)))))))))
;;;
;;; The facilities are useful for debugging, and to measure the performance
;;; boost from constructors.
;;;
(defun map-constructors (fn)
(let ((nclasses 0)
(nconstructors 0))
(labels ((recurse (class)
(incf nclasses)
(dolist (constructor (class-constructors class))
(incf nconstructors)
(funcall fn constructor))
(dolist (subclass (class-direct-subclasses class))
(recurse subclass))))
(recurse (find-class 't))
(values nclasses nconstructors))))
(defun reset-constructors ()
(multiple-value-bind (nclass ncons)
(map-constructors #'install-lazy-constructor-installer )
(format t "~&~D classes, ~D constructors." nclass ncons)))
(defun disable-constructors ()
(multiple-value-bind (nclass ncons)
(map-constructors
#'(lambda (c)
(let ((gen (getf (constructor-code-generators c) 'fallback)))
(if (null gen)
(error "No fallback constructor for ~S." c)
(set-constructor-code c
(funcall gen
(constructor-class c)
() () () ())
'fallback)))))
(format t "~&~D classes, ~D constructors." nclass ncons)))
(defun enable-constructors ()
(reset-constructors))
;;;
;;; Helper functions and utilities that are shared by all of the code types
;;; and by the main compute-constructor-code method as well.
;;;
(defvar *standard-initialize-instance-method*
(get-method #'initialize-instance
()
(list *the-class-standard-object*)))
(defvar *standard-shared-initialize-method*
(get-method #'shared-initialize
()
(list *the-class-standard-object* *the-class-t*)))
(defun non-clos-initialize-instance-methods-p (methods)
(notevery #'(lambda (m) (eq m *standard-initialize-instance-method*))
methods))
(defun non-clos-shared-initialize-methods-p (methods)
(notevery #'(lambda (m) (eq m *standard-shared-initialize-method*))
methods))
(defun non-clos-or-after-initialize-instance-methods-p (methods)
(notevery #'(lambda (m) (or (eq m *standard-initialize-instance-method*)
(equal '(:after) (method-qualifiers m))))
methods))
(defun non-clos-or-after-shared-initialize-methods-p (methods)
(notevery #'(lambda (m) (or (eq m *standard-shared-initialize-method*)
(equal '(:after) (method-qualifiers m))))
methods))
;;;
;;; if initargs are valid return nil, otherwise return t.
;;;
(defun check-initargs (class supplied-initarg-names defaults methods)
(let ((legal (apply #'append
(mapcar #'slotd-initargs (class-slots class)))))
;; Add to the set of slot-filling initargs the set of
;; initargs that are accepted by the methods. If at
;; any point we come across &allow-other-keys, we can
;; just quit.
(dolist (method methods)
(multiple-value-bind (keys allow-other-keys)
(function-keywords method)
(when allow-other-keys
(return-from check-initargs nil))
(setq legal (append keys legal))))
;; Now check the supplied-initarg-names and the default initargs
;; against the total set that we know are legal.
(dolist (key supplied-initarg-names)
(unless (memq key legal)
(return-from check-initargs t)))
(dolist (default defaults)
(unless (memq (car default) legal)
(return-from check-initargs t)))))
;;;
This returns two values . The first is a vector which can be used as the
initial value of the slots vector for the instance . The first is a symbol
;;; describing the initforms this class has.
;;;
If the first value is :
;;;
: unsupplied no slot has an initform
: constants all slots have either a constant initform
or no initform at all
t there is at least one non - constant initform
;;;
(defun compute-constant-vector (class)
(declare (values constants flag))
(let* ((wrapper (class-wrapper class))
(layout (wrapper-instance-slots-layout wrapper))
(flag :unsupplied)
(constants ()))
(dolist (slotd (class-slots class))
(let ((name (slotd-name slotd))
(initform (slotd-initform slotd))
(initfn (slotd-initfunction slotd)))
(cond ((null (memq name layout)))
((or (eq initform *slotd-unsupplied*)
(null initfn))
(push (cons name *slot-unbound*) constants))
((constantp initform)
(push (cons name (eval initform)) constants)
(when (eq flag ':unsupplied) (setq flag ':constants)))
(t
(push (cons name *slot-unbound*) constants)
(setq flag 't)))))
(values
(apply #'vector
(mapcar #'cdr
(sort constants #'(lambda (x y)
(memq (car y)
(memq (car x) layout))))))
flag)))
(defmacro copy-constant-vector (constants)
`(copy-seq (the simple-vector ,constants)))
;;;
;;; This takes a class and a list of initarg-names, and returns an alist
;;; indicating the positions of the slots those initargs may fill. The
;;; order of the initarg-names argument is important of course, since we
;;; have to respect the rules about the leftmost initarg that fills a slot
;;; having precedence. This function allows initarg names to appear twice
in the list , it only considers the first appearance .
;;;
(defun compute-initarg-positions (class initarg-names)
(let* ((layout (wrapper-instance-slots-layout (class-wrapper class)))
(positions
(gathering1 (collecting)
(iterate ((slot-name (list-elements layout))
(position (interval :from 0)))
(gather1 (cons slot-name position)))))
(slot-initargs
(mapcar #'(lambda (slotd)
(list (slotd-initargs slotd)
(or (cdr (assq (slotd-name slotd) positions))
':class)))
(class-slots class))))
;; Go through each of the initargs, and figure out what position
;; it fills by replacing the entries in slot-initargs it fills.
(dolist (initarg initarg-names)
(dolist (slot-entry slot-initargs)
(let ((slot-initargs (car slot-entry)))
(when (and (listp slot-initargs)
(not (null slot-initargs))
(memq initarg slot-initargs))
(setf (car slot-entry) initarg)))))
(gathering1 (collecting)
(dolist (initarg initarg-names)
(let ((positions (gathering1 (collecting)
(dolist (slot-entry slot-initargs)
(when (eq (car slot-entry) initarg)
(gather1 (cadr slot-entry)))))))
(when positions
(gather1 (cons initarg positions))))))))
;;;
The FALLBACK case allows anything . This always works , and always appears
;;; as the last of the generators for a constructor. It does a full call to
;;; make-instance.
;;;
(define-constructor-code-type fallback
(class name arglist supplied-initarg-names supplied-initargs)
(declare (ignore name supplied-initarg-names))
`(function
(lambda (&rest ignore)
(declare (ignore ignore))
(function
(lambda ,arglist
(make-instance
',(class-name class)
,@(gathering1 (collecting)
(iterate ((tail (*list-tails supplied-initargs :by #'cddr)))
(gather1 `',(car tail))
(gather1 (cadr tail))))))))))
;;;
;;; The GENERAL case allows:
;;; constant, unsupplied or non-constant initforms
constant or non - constant default
supplied
slot - filling
;;; :after methods on shared-initialize and initialize-instance
;;;
(define-constructor-code-type general
(class name arglist supplied-initarg-names supplied-initargs)
(declare (ignore name))
(let ((raw-allocator (raw-instance-allocator class))
(slots-fetcher (slots-fetcher class))
(wrapper-fetcher (wrapper-fetcher class)))
`(function
(lambda (class .wrapper. defaults init shared)
(multiple-value-bind (.constants.
.constant-initargs.
.initfns-initargs-and-positions.
.supplied-initarg-positions.
.shared-initfns.
.initfns.)
(general-generator-internal class
defaults
init
shared
',supplied-initarg-names
',supplied-initargs)
.supplied-initarg-positions.
(when (and .constants.
(null (non-clos-or-after-initialize-instance-methods-p
init))
(null (non-clos-or-after-shared-initialize-methods-p
shared)))
(function
(lambda ,arglist
(declare (optimize (speed 3) (safety 0)))
(let ((.instance. (,raw-allocator))
(.slots. (copy-constant-vector .constants.))
(.positions. .supplied-initarg-positions.)
(.initargs. .constant-initargs.))
.positions.
(setf (,slots-fetcher .instance.) .slots.)
(setf (,wrapper-fetcher .instance.) .wrapper.)
(dolist (entry .initfns-initargs-and-positions.)
(let ((val (funcall (car entry)))
(initarg (cadr entry)))
(when initarg
(push val .initargs.)
(push initarg .initargs.))
(dolist (pos (cddr entry))
(setf (%svref .slots. pos) val))))
,@(gathering1 (collecting)
(doplist (initarg value) supplied-initargs
(unless (constantp value)
(gather1 `(let ((.value. ,value))
(push .value. .initargs.)
(push ',initarg .initargs.)
(dolist (.p. (pop .positions.))
(setf (%svref .slots. .p.)
.value.)))))))
(dolist (fn .shared-initfns.)
(apply fn .instance. t .initargs.))
(dolist (fn .initfns.)
(apply fn .instance. .initargs.))
.instance.)))))))))
(defun general-generator-internal
(class defaults init shared supplied-initarg-names supplied-initargs)
(flet ((bail-out () (return-from general-generator-internal nil)))
(let* ((constants (compute-constant-vector class))
(layout (wrapper-instance-slots-layout (class-wrapper class)))
(initarg-positions
(compute-initarg-positions class
(append supplied-initarg-names
(mapcar #'car defaults))))
(initfns-initargs-and-positions ())
(supplied-initarg-positions ())
(constant-initargs ())
(used-positions ()))
;;
Go through each of the supplied initargs for three reasons .
;;
;; - If it fills a class slot, bail out.
;; - If its a constant form, fill the constant vector.
- Otherwise remember the positions no two initargs
;; will try to fill the same position, since compute
;; initarg positions already took care of that, but
;; we do need to know what initforms will and won't
;; be needed.
;;
(doplist (initarg val) supplied-initargs
(let ((positions (cdr (assq initarg initarg-positions))))
(cond ((memq :class positions) (bail-out))
((constantp val)
(setq val (eval val))
(push val constant-initargs)
(push initarg constant-initargs)
(dolist (pos positions) (setf (svref constants pos) val)))
(t
(push positions supplied-initarg-positions)))
(setq used-positions (append positions used-positions))))
;;
Go through each of the default initargs , for three reasons .
;;
;; - If it fills a class slot, bail out.
;; - If it is a constant, and it does fill a slot, put that
;; into the constant vector.
- If it is n't a constant , record its initfn and position .
;;
(dolist (default defaults)
(let* ((name (car default))
(initfn (cadr default))
(form (caddr default))
(value ())
(positions (cdr (assq name initarg-positions))))
(unless (memq name supplied-initarg-names)
(cond ((memq :class positions) (bail-out))
((constantp form)
(setq value (eval form))
(push value constant-initargs)
(push name constant-initargs)
(dolist (pos positions)
(setf (svref constants pos) value)))
(t
(push (list* initfn name positions)
initfns-initargs-and-positions)))
(setq used-positions (append positions used-positions)))))
;;
;; Go through each of the slot initforms:
;;
;; - If its position has already been filled, do nothing.
;; The initfn won't need to be called, and the slot won't
;; need to be touched.
- If it is a class slot , and has an initform , bail out .
;; - If its a constant or unsupplied, ignore it, it is
;; already in the constant vector.
- Otherwise , record its initfn and position
;;
(dolist (slotd (class-slots class))
(let* ((alloc (slotd-allocation slotd))
(name (slotd-name slotd))
(form (slotd-initform slotd))
(initfn (slotd-initfunction slotd))
(position (position name layout)))
(cond ((neq alloc :instance)
(unless (or (eq form *slotd-unsupplied*)
(null initfn))
(bail-out)))
((member position used-positions))
((or (constantp form)
(eq form *slotd-unsupplied*)))
(t
(push (list initfn nil position)
initfns-initargs-and-positions)))))
(values constants
constant-initargs
(nreverse initfns-initargs-and-positions)
(nreverse supplied-initarg-positions)
(mapcar #'method-function
(remove *standard-shared-initialize-method* shared))
(mapcar #'method-function
(remove *standard-initialize-instance-method* init))))))
;;;
;;; The NO-METHODS case allows:
;;; constant, unsupplied or non-constant initforms
constant or non - constant default
supplied that are arguments to constructor , or constants
slot - filling
;;;
(define-constructor-code-type no-methods
(class name arglist supplied-initarg-names supplied-initargs)
(declare (ignore name))
(let ((raw-allocator (raw-instance-allocator class))
(slots-fetcher (slots-fetcher class))
(wrapper-fetcher (wrapper-fetcher class)))
`(function
(lambda (class .wrapper. defaults init shared)
(multiple-value-bind (.constants.
.initfns-and-positions.
.supplied-initarg-positions.)
(no-methods-generator-internal class
defaults
',supplied-initarg-names
',supplied-initargs)
.initfns-and-positions.
.supplied-initarg-positions.
(when (and .constants.
(null (non-clos-initialize-instance-methods-p init))
(null (non-clos-shared-initialize-methods-p shared)))
#'(lambda ,arglist
(declare (optimize (speed 3) (safety 0)))
(let ((.instance. (,raw-allocator))
(.slots. (copy-constant-vector .constants.))
(.positions. .supplied-initarg-positions.))
.positions.
(setf (,slots-fetcher .instance.) .slots.)
(setf (,wrapper-fetcher .instance.) .wrapper.)
(dolist (entry .initfns-and-positions.)
(let ((val (funcall (car entry))))
(dolist (pos (cdr entry))
(setf (%svref .slots. pos) val))))
,@(gathering1 (collecting)
(doplist (initarg value) supplied-initargs
(unless (constantp value)
(gather1
`(let ((.value. ,value))
(dolist (.p. (pop .positions.))
(setf (%svref .slots. .p.) .value.)))))))
.instance.))))))))
(defun no-methods-generator-internal
(class defaults supplied-initarg-names supplied-initargs)
(flet ((bail-out () (return-from no-methods-generator-internal nil)))
(let* ((constants (compute-constant-vector class))
(layout (wrapper-instance-slots-layout (class-wrapper class)))
(initarg-positions
(compute-initarg-positions class
(append supplied-initarg-names
(mapcar #'car defaults))))
(initfns-and-positions ())
(supplied-initarg-positions ())
(used-positions ()))
;;
Go through each of the supplied initargs for three reasons .
;;
;; - If it fills a class slot, bail out.
;; - If its a constant form, fill the constant vector.
- Otherwise remember the positions , no two initargs
;; will try to fill the same position, since compute
;; initarg positions already took care of that, but
;; we do need to know what initforms will and won't
;; be needed.
;;
(doplist (initarg val) supplied-initargs
(let ((positions (cdr (assq initarg initarg-positions))))
(cond ((memq :class positions) (bail-out))
((constantp val)
(setq val (eval val))
(dolist (pos positions)
(setf (svref constants pos) val)))
(t
(push positions supplied-initarg-positions)))
(setq used-positions (append positions used-positions))))
;;
Go through each of the default initargs , for three reasons .
;;
;; - If it fills a class slot, bail out.
;; - If it is a constant, and it does fill a slot, put that
;; into the constant vector.
- If it is n't a constant , record its initfn and position .
;;
(dolist (default defaults)
(let* ((name (car default))
(initfn (cadr default))
(form (caddr default))
(value ())
(positions (cdr (assq name initarg-positions))))
(unless (memq name supplied-initarg-names)
(cond ((memq :class positions) (bail-out))
((constantp form)
(setq value (eval form))
(dolist (pos positions)
(setf (svref constants pos) value)))
(t
(push (cons initfn positions)
initfns-and-positions)))
(setq used-positions (append positions used-positions)))))
;;
;; Go through each of the slot initforms:
;;
;; - If its position has already been filled, do nothing.
;; The initfn won't need to be called, and the slot won't
;; need to be touched.
- If it is a class slot , and has an initform , bail out .
;; - If its a constant or unsupplied, do nothing, we know
;; that it is already in the constant vector.
- Otherwise , record its initfn and position
;;
(dolist (slotd (class-slots class))
(let* ((alloc (slotd-allocation slotd))
(name (slotd-name slotd))
(form (slotd-initform slotd))
(initfn (slotd-initfunction slotd))
(position (position name layout)))
(cond ((neq alloc :instance)
(unless (or (eq form *slotd-unsupplied*)
(null initfn))
(bail-out)))
((member position used-positions))
((or (constantp form)
(eq form *slotd-unsupplied*)))
(t
(push (list initfn position) initfns-and-positions)))))
(values constants
(nreverse initfns-and-positions)
(nreverse supplied-initarg-positions)))))
;;;
;;; The SIMPLE-SLOTS case allows:
;;; constant or unsupplied initforms
constant default
supplied
slot filling initargs
;;;
(define-constructor-code-type simple-slots
(class name arglist supplied-initarg-names supplied-initargs)
(declare (ignore name))
(let ((raw-allocator (raw-instance-allocator class))
(slots-fetcher (slots-fetcher class))
(wrapper-fetcher (wrapper-fetcher class)))
`(function
(lambda (class .wrapper. defaults init shared)
(when (and (null (non-clos-initialize-instance-methods-p init))
(null (non-clos-shared-initialize-methods-p shared)))
(multiple-value-bind (.constants. .supplied-initarg-positions.)
(simple-slots-generator-internal class
defaults
',supplied-initarg-names
',supplied-initargs)
(when .constants.
(function
(lambda ,arglist
(declare (optimize (speed 3) (safety 0)))
(let ((.instance. (,raw-allocator))
(.slots. (copy-constant-vector .constants.))
(.positions. .supplied-initarg-positions.))
.positions.
(setf (,slots-fetcher .instance.) .slots.)
(setf (,wrapper-fetcher .instance.) .wrapper.)
,@(gathering1 (collecting)
(doplist (initarg value) supplied-initargs
(unless (constantp value)
(gather1
`(let ((.value. ,value))
(dolist (.p. (pop .positions.))
(setf (%svref .slots. .p.) .value.)))))))
.instance.))))))))))
(defun simple-slots-generator-internal
(class defaults supplied-initarg-names supplied-initargs)
(flet ((bail-out () (return-from simple-slots-generator-internal nil)))
(let* ((constants (compute-constant-vector class))
(layout (wrapper-instance-slots-layout (class-wrapper class)))
(initarg-positions
(compute-initarg-positions class
(append supplied-initarg-names
(mapcar #'car defaults))))
(supplied-initarg-positions ())
(used-positions ()))
;;
Go through each of the supplied initargs for three reasons .
;;
;; - If it fills a class slot, bail out.
;; - If its a constant form, fill the constant vector.
- Otherwise remember the positions , no two initargs
;; will try to fill the same position, since compute
;; initarg positions already took care of that, but
;; we do need to know what initforms will and won't
;; be needed.
;;
(doplist (initarg val) supplied-initargs
(let ((positions (cdr (assq initarg initarg-positions))))
(cond ((memq :class positions) (bail-out))
((constantp val)
(setq val (eval val))
(dolist (pos positions)
(setf (svref constants pos) val)))
(t
(push positions supplied-initarg-positions)))
(setq used-positions (append used-positions positions))))
;;
Go through each of the default initargs for three reasons .
;;
;; - If it isn't a constant form, bail out.
;; - If it fills a class slot, bail out.
;; - If it is a constant, and it does fill a slot, put that
;; into the constant vector.
;;
(dolist (default defaults)
(let* ((name (car default))
(form (caddr default))
(value ())
(positions (cdr (assq name initarg-positions))))
(unless (memq name supplied-initarg-names)
(cond ((memq :class positions) (bail-out))
((not (constantp form))
(bail-out))
(t
(setq value (eval form))
(dolist (pos positions)
(setf (svref constants pos) value)))))))
;;
;; Go through each of the slot initforms:
;;
;; - If its position has already been filled, do nothing.
;; The initfn won't need to be called, and the slot won't
;; need to be touched, we are OK.
- If it has a non - constant initform , bail - out . This
;; case doesn't handle those.
- If it has a constant or unsupplied initform we do n't
;; really need to do anything, the value is in the
;; constants vector.
;;
(dolist (slotd (class-slots class))
(let* ((alloc (slotd-allocation slotd))
(name (slotd-name slotd))
(form (slotd-initform slotd))
(initfn (slotd-initfunction slotd))
(position (position name layout)))
(cond ((neq alloc :instance)
(unless (or (eq form *slotd-unsupplied*)
(null initfn))
(bail-out)))
((member position used-positions))
((or (constantp form)
(eq form *slotd-unsupplied*)))
(t
(bail-out)))))
(values constants (nreverse supplied-initarg-positions)))))
| null | https://raw.githubusercontent.com/Interlisp/medley/f0b9ce3daeef95543e452ea4c59cb8e683295035/obsolete/clos/2.0/construct.lisp | lisp | Package:(CLOS LISP 1000 ) ; ; Syntax : Common - lisp -*-
*************************************************************************
All rights reserved.
*************************************************************************
This file defines the defconstructor and other make-instance optimization
mechanisms.
defconstructor is used to define special purpose functions which just
of defconstructor is that it is equivalent to defining a function which
just calls make-instance. The purpose of defconstructor is to provide
spot these calls to make-instance and then call this code. Having the
A call to defconstructor like:
(defconstructor make-foo foo (a b &rest r) a a :mumble b baz r)
Is equivalent to a defun like:
(defun make-foo (a b &rest r)
(make-instance 'foo 'a a ':mumble b 'baz r))
Calls like the following are also legal:
(defconstructor make-foo foo ())
(defconstructor make-bar bar () :x *x* :y *y*)
(defconstructor make-baz baz (a b c) a-b (list a b) b-c (list b c))
The general idea of this implementation is that the expansion of the
defconstructor form includes the creation of closure generators which
can be called to create constructor code for the class. The ways that
a constructor can be optimized depends not only on the defconstructor
form, but also on the state of the class and the generic functions in
the initialization protocol. Because of this, the determination of the
At compile time, make-constructor-code-generators looks at the actual
defconstructor form and makes a list of appropriate constructor code
generators. All that is really taken into account here is whether
any initargs are supplied in the call to make-instance, and whether
any of those are constant.
At constructor code generation time (see note about lazy evaluation)
compute-constructor-code calls each of the constructor code generators
to try to get code for this constructor. Each generator looks at the
state of the class and initialization protocol generic functions and
decides whether its type of code is appropriate. This depends on things
like whether there are any applicable methods on initialize-instance,
whether class slots are affected by initialization etc.
Constructor objects are funcallable instances, the protocol followed to
to compute the constructor code for them is quite similar to the protocol
followed to compute the discriminator code for a generic function. When
If there is an update to the class structure which might invalidate the
optimized constructor, the special lazy constructor installer is put back
so that it can compute the appropriate constructor when it is called.
This is the same kind of lazy evaluation update strategy used elswhere
to specialize this constructor facility for their own metaclasses, there
is an internal protocol followed by the code which loads and installs
the constructors. This is documented in the comments in the code.
This code is also designed so that one of its levels, can be used to
implement optimization of calls to make-instance which can't go through
the defconstructor facility. This has not been implemented yet, but the
hooks are there.
In order to avoid undefined function warnings, we want to tell
the compile time environment that a function with this name and
this argument list has been defined. The portable way to do this
is with defun.
make-constructor-code-generators is called to return a list
of constructor code generators. The actual interpretation
of this list is left to compute-constructor-code, but the
general idea is that it should be an plist where the keys
name a kind of constructor code and the values are generator
functions which return the actual constructor code. The
constructor code is usually a closures over the arguments
to the generator.
The actual constructor objects.
The class with which this
constructor is associated.
The actual class object,
not the class name.
The name of this constructor.
This is the symbol in whose
function cell the constructor
usually sits. Of course, this
is optional. defconstructor
makes named constructors, but
it is possible to manipulate
anonymous constructors also.
The type of code currently in
use by this constructor. This
is mostly for debugging and
analysis purposes.
The lazy installer sets this
least optimized type of code
The names of the initargs this
constructor supplies when it
"calls" make-instance.
Generators for the different
types of code this constructor
could use.
Because the value in the code-type slot should always correspond to the
funcallable-instance-function of the constructor, this function should
always be used to set the both at the same time.
I am not in a hairy enough mood to make this implementation be metacircular
enough that it can support a defconstructor for constructor objects.
This definition actually appears in std-class.lisp.
(defmethod class-constructors ((class std-class))
This is called to actually load a defconstructor constructor. It must
install the lazy installer in the function cell of the constructor name,
and also add this constructor to the list of constructors the class has.
The interface to keeping the constructors updated.
add-method and remove-method (for standard-generic-function and -method),
promise to call maybe-update-constructors on the generic function and
the method.
The class update code promises to call update-constructors whenever the
class is changed. That is, whenever the supers, slots or options change.
If user defined classes of constructor needs to be updated in more than
these circumstances, they should use the dependent updating mechanism to
make sure update-constructors is called.
Bootstrapping concerns force the definitions of maybe-update-constructors
and update-constructors to be in the file std-class. For clarity, they
also appear below. Be sure to keep the definition here and there in sync.
(defvar *initialization-generic-functions*
(list #'make-instance
#'default-initargs
#'allocate-instance
#'initialize-instance
#'shared-initialize))
(defmethod maybe-update-constructors
((generic-function generic-function)
(method method))
(when (memq generic-function *initialization-generic-functions*)
(labels ((recurse (class)
(update-constructors class)
(recurse subclass))))
(when (classp (car (method-specializers method)))
(recurse (car (method-specializers method)))))))
(defmethod update-constructors ((class std-class))
(install-lazy-constructor-installer cons)))
(defmethod update-constructors ((class class))
())
Here is the actual smarts for making the code generators and then trying
each generator to get constructor code. This extensible mechanism allows
new kinds of constructor code types to be added. A programmer defining a
specialization of the constructor class can either use this mechanism to
define new code types, or can override this mechanism by overriding the
methods on make-constructor-code-generators and compute-constructor-code.
The function defined by define-constructor-code-type will receive the
return a constructor code generator, or return nil if this type of code
is determined to not be appropriate after looking at the defconstructor
arguments.
to make sure that the basic assumptions common to all the code types are
valid. (For details see method definition). If any of the tests fail,
the fallback constructor code type is used. If none of the tests fail,
arguments:
CLASS the class the constructor is making instances of
WRAPPER that class's wrapper
called in reverse order of definition, so define-constructor-code-type
forms which define better code should appear after ones that define less
code type does not change its position in the list. To do that, define
a new type at the end with the behavior.
?
has been violated, we have to resort to the fallback
case. Any of these assumptions could be moved out
of here and into the individual code types if there
was a need to do so.
code for us.
The facilities are useful for debugging, and to measure the performance
boost from constructors.
Helper functions and utilities that are shared by all of the code types
and by the main compute-constructor-code method as well.
if initargs are valid return nil, otherwise return t.
Add to the set of slot-filling initargs the set of
initargs that are accepted by the methods. If at
any point we come across &allow-other-keys, we can
just quit.
Now check the supplied-initarg-names and the default initargs
against the total set that we know are legal.
describing the initforms this class has.
This takes a class and a list of initarg-names, and returns an alist
indicating the positions of the slots those initargs may fill. The
order of the initarg-names argument is important of course, since we
have to respect the rules about the leftmost initarg that fills a slot
having precedence. This function allows initarg names to appear twice
Go through each of the initargs, and figure out what position
it fills by replacing the entries in slot-initargs it fills.
as the last of the generators for a constructor. It does a full call to
make-instance.
The GENERAL case allows:
constant, unsupplied or non-constant initforms
:after methods on shared-initialize and initialize-instance
- If it fills a class slot, bail out.
- If its a constant form, fill the constant vector.
will try to fill the same position, since compute
initarg positions already took care of that, but
we do need to know what initforms will and won't
be needed.
- If it fills a class slot, bail out.
- If it is a constant, and it does fill a slot, put that
into the constant vector.
Go through each of the slot initforms:
- If its position has already been filled, do nothing.
The initfn won't need to be called, and the slot won't
need to be touched.
- If its a constant or unsupplied, ignore it, it is
already in the constant vector.
The NO-METHODS case allows:
constant, unsupplied or non-constant initforms
- If it fills a class slot, bail out.
- If its a constant form, fill the constant vector.
will try to fill the same position, since compute
initarg positions already took care of that, but
we do need to know what initforms will and won't
be needed.
- If it fills a class slot, bail out.
- If it is a constant, and it does fill a slot, put that
into the constant vector.
Go through each of the slot initforms:
- If its position has already been filled, do nothing.
The initfn won't need to be called, and the slot won't
need to be touched.
- If its a constant or unsupplied, do nothing, we know
that it is already in the constant vector.
The SIMPLE-SLOTS case allows:
constant or unsupplied initforms
- If it fills a class slot, bail out.
- If its a constant form, fill the constant vector.
will try to fill the same position, since compute
initarg positions already took care of that, but
we do need to know what initforms will and won't
be needed.
- If it isn't a constant form, bail out.
- If it fills a class slot, bail out.
- If it is a constant, and it does fill a slot, put that
into the constant vector.
Go through each of the slot initforms:
- If its position has already been filled, do nothing.
The initfn won't need to be called, and the slot won't
need to be touched, we are OK.
case doesn't handle those.
really need to do anything, the value is in the
constants vector.
| Copyright ( c ) 1991 Venue
(in-package 'clos)
call make - instance with a symbol as the first argument . The semantics
CLOS with a way of noticing these calls to make - instance so that it can
optimize them . Specific ports of CLOS could just have their compiler
special defconstructor facility is the best we can do portably .
form of constructor code to be used is a two part process .
the constructor is first loaded , we install as its code a function which
will compute the actual constructor code the first time it is called .
in CLOS .
To allow for flexibility in the CLOS implementation and to allow CLOS users
(defmacro defconstructor
(name class lambda-list &rest initialization-arguments)
(expand-defconstructor class
name
lambda-list
(copy-list initialization-arguments)))
(defun expand-defconstructor (class-name name lambda-list supplied-initargs)
(let ((class (find-class class-name nil))
(supplied-initarg-names
(gathering1 (collecting)
(iterate ((name (*list-elements supplied-initargs :by #'cddr)))
(gather1 name)))))
(when (null class)
(error "defconstructor form being compiled (or evaluated) before~@
class ~S is defined."
class-name))
`(progn
(proclaim '(notinline ,name))
(defun ,name ,lambda-list
(declare (ignore ,@(specialized-lambda-list-parameters lambda-list)))
(error "Constructor ~S not loaded." ',name))
,(make-top-level-form `(defconstructor ,name)
'(load eval)
`(load-constructor
',class-name
',(class-name (class-of class))
',name
',supplied-initarg-names
,(make-constructor-code-generators class
name
lambda-list
supplied-initarg-names
supplied-initargs))))))
(defun load-constructor (class-name metaclass-name constructor-name
supplied-initarg-names code-generators)
(let ((class (find-class class-name nil)))
(cond ((null class)
(error "defconstructor form being loaded (or evaluated) before~@
class ~S is defined."
class-name))
((neq (class-name (class-of class)) metaclass-name)
(error "When defconstructor ~S was compiled, the metaclass of the~@
class ~S was ~S. The metaclass is now ~S.~@
The constructor must be recompiled."
constructor-name
class-name
metaclass-name
(class-name (class-of class))))
(t
(load-constructor-internal class
constructor-name
supplied-initarg-names
code-generators)
constructor-name))))
(defclass constructor ()
to LAZY . The most basic and
is called FALLBACK .
(:metaclass funcallable-standard-class))
(defun set-constructor-code (constructor code type)
(set-funcallable-instance-function constructor code)
(set-function-name constructor (constructor-name constructor))
(setf (constructor-code-type constructor) type))
(defmethod print-object ((constructor constructor) stream)
(printing-random-thing (constructor stream)
(format stream
"~S ~S (~S)"
(or (class-name (class-of constructor)) "Constructor")
(or (constructor-name constructor) "Anonymous")
(constructor-code-type constructor))))
(defmethod describe-object ((constructor constructor) stream)
(format stream
"~S is a constructor for the class ~S.~%~
The current code type is ~S.~%~
Other possible code types are ~S."
constructor (constructor-class constructor)
(constructor-code-type constructor)
(gathering1 (collecting)
(doplist (key val) (constructor-code-generators constructor)
(gather1 key)))))
(defun make-constructor (class name supplied-initarg-names code-generators)
(make-instance 'constructor
:class class
:name name
:supplied-initarg-names supplied-initarg-names
:code-generators code-generators))
( with - slots ( plist ) class ( getf plist ' constructors ) ) )
(defmethod add-constructor ((class std-class)
(constructor constructor))
(with-slots (plist) class
(pushnew constructor (getf plist 'constructors))))
(defmethod remove-constructor ((class std-class)
(constructor constructor))
(with-slots (plist) class
(setf (getf plist 'constructors)
(delete constructor (getf plist 'constructors)))))
(defmethod get-constructor ((class std-class) name &optional (error-p t))
(or (dolist (c (class-constructors class))
(when (eq (constructor-name c) name) (return c)))
(if error-p
(error "Couldn't find a constructor with name ~S for class ~S."
name class)
())))
(defmethod load-constructor-internal
((class std-class) name initargs generators)
(let ((constructor (make-constructor class name initargs generators))
(old (get-constructor class name nil)))
(when old (remove-constructor class old))
(install-lazy-constructor-installer constructor)
(add-constructor class constructor)
(setf (symbol-function name) constructor)))
(defmethod install-lazy-constructor-installer ((constructor constructor))
(let ((class (constructor-class constructor)))
(set-constructor-code constructor
#'(lambda (&rest args)
(multiple-value-bind (code type)
(compute-constructor-code class constructor)
(prog1 (apply code args)
(set-constructor-code constructor
code
type))))
'lazy)))
( dolist ( subclass ( class - direct - subclasses class ) )
( dolist ( cons ( class - constructors class ) )
class object , and the 4 original arguments to defconstructor . It can
When compute - constructor - code is called , it first performs basic checks
the constructor code generators are called in order . They receive 5
DEFAULTS the result of calling class - default - initargs on class
INITIALIZE the applicable methods on initialize - instance
SHARED the applicable methosd on shared - initialize
The first code generator to return code is used . The code generators are
good code . The fallback code type appears first . Note that redefining a
(defvar *constructor-code-types* ())
(defmacro define-constructor-code-type (type arglist &body body)
(let ((fn-name (intern (format nil
"CONSTRUCTOR-CODE-GENERATOR ~A ~A"
(package-name (symbol-package type))
(symbol-name type))
*the-clos-package*)))
`(progn
(defun ,fn-name ,arglist .,body)
(load-define-constructor-code-type ',type ',fn-name))))
(defun load-define-constructor-code-type (type generator)
(let ((old-entry (assq type *constructor-code-types*)))
(if old-entry
(setf (cadr old-entry) generator)
(push (list type generator) *constructor-code-types*))
type))
(defmethod make-constructor-code-generators
((class std-class)
name lambda-list supplied-initarg-names supplied-initargs)
(cons 'list
(gathering1 (collecting)
(dolist (entry *constructor-code-types*)
(let ((generator
(funcall (cadr entry) class name lambda-list
supplied-initarg-names
supplied-initargs)))
(when generator
(gather1 `',(car entry))
(gather1 generator)))))))
(defmethod compute-constructor-code ((class std-class)
(constructor constructor))
(let* ((proto (class-prototype class))
(wrapper (class-wrapper class))
(defaults (class-default-initargs class))
(make
(compute-applicable-methods #'make-instance (list class)))
(supplied-initarg-names
(constructor-supplied-initarg-names constructor))
(default
(compute-applicable-methods #'default-initargs
(allocate
(compute-applicable-methods #'allocate-instance (list class)))
(initialize
(compute-applicable-methods #'initialize-instance (list proto)))
(shared
(compute-applicable-methods #'shared-initialize (list proto t)))
(code-generators
(constructor-code-generators constructor))
(code-generators
(constructor-code-generators constructor)))
(flet ((call-code-generator (generator)
(when (null generator)
(unless (setq generator (getf code-generators 'fallback))
(error "No FALLBACK generator?")))
(funcall generator class wrapper defaults initialize shared)))
(if (or (cdr make)
(cdr default)
(cdr allocate)
(check-initargs class
supplied-initarg-names
defaults
(append initialize shared)))
These are basic shared assumptions , if one of the
(values (call-code-generator nil) 'fallback)
Otherwise try all the generators until one produces
(doplist (type generator) code-generators
(let ((code (call-code-generator generator)))
(when code (return (values code type)))))))))
(defun map-constructors (fn)
(let ((nclasses 0)
(nconstructors 0))
(labels ((recurse (class)
(incf nclasses)
(dolist (constructor (class-constructors class))
(incf nconstructors)
(funcall fn constructor))
(dolist (subclass (class-direct-subclasses class))
(recurse subclass))))
(recurse (find-class 't))
(values nclasses nconstructors))))
(defun reset-constructors ()
(multiple-value-bind (nclass ncons)
(map-constructors #'install-lazy-constructor-installer )
(format t "~&~D classes, ~D constructors." nclass ncons)))
(defun disable-constructors ()
(multiple-value-bind (nclass ncons)
(map-constructors
#'(lambda (c)
(let ((gen (getf (constructor-code-generators c) 'fallback)))
(if (null gen)
(error "No fallback constructor for ~S." c)
(set-constructor-code c
(funcall gen
(constructor-class c)
() () () ())
'fallback)))))
(format t "~&~D classes, ~D constructors." nclass ncons)))
(defun enable-constructors ()
(reset-constructors))
(defvar *standard-initialize-instance-method*
(get-method #'initialize-instance
()
(list *the-class-standard-object*)))
(defvar *standard-shared-initialize-method*
(get-method #'shared-initialize
()
(list *the-class-standard-object* *the-class-t*)))
(defun non-clos-initialize-instance-methods-p (methods)
(notevery #'(lambda (m) (eq m *standard-initialize-instance-method*))
methods))
(defun non-clos-shared-initialize-methods-p (methods)
(notevery #'(lambda (m) (eq m *standard-shared-initialize-method*))
methods))
(defun non-clos-or-after-initialize-instance-methods-p (methods)
(notevery #'(lambda (m) (or (eq m *standard-initialize-instance-method*)
(equal '(:after) (method-qualifiers m))))
methods))
(defun non-clos-or-after-shared-initialize-methods-p (methods)
(notevery #'(lambda (m) (or (eq m *standard-shared-initialize-method*)
(equal '(:after) (method-qualifiers m))))
methods))
(defun check-initargs (class supplied-initarg-names defaults methods)
(let ((legal (apply #'append
(mapcar #'slotd-initargs (class-slots class)))))
(dolist (method methods)
(multiple-value-bind (keys allow-other-keys)
(function-keywords method)
(when allow-other-keys
(return-from check-initargs nil))
(setq legal (append keys legal))))
(dolist (key supplied-initarg-names)
(unless (memq key legal)
(return-from check-initargs t)))
(dolist (default defaults)
(unless (memq (car default) legal)
(return-from check-initargs t)))))
This returns two values . The first is a vector which can be used as the
initial value of the slots vector for the instance . The first is a symbol
If the first value is :
: unsupplied no slot has an initform
: constants all slots have either a constant initform
or no initform at all
t there is at least one non - constant initform
(defun compute-constant-vector (class)
(declare (values constants flag))
(let* ((wrapper (class-wrapper class))
(layout (wrapper-instance-slots-layout wrapper))
(flag :unsupplied)
(constants ()))
(dolist (slotd (class-slots class))
(let ((name (slotd-name slotd))
(initform (slotd-initform slotd))
(initfn (slotd-initfunction slotd)))
(cond ((null (memq name layout)))
((or (eq initform *slotd-unsupplied*)
(null initfn))
(push (cons name *slot-unbound*) constants))
((constantp initform)
(push (cons name (eval initform)) constants)
(when (eq flag ':unsupplied) (setq flag ':constants)))
(t
(push (cons name *slot-unbound*) constants)
(setq flag 't)))))
(values
(apply #'vector
(mapcar #'cdr
(sort constants #'(lambda (x y)
(memq (car y)
(memq (car x) layout))))))
flag)))
(defmacro copy-constant-vector (constants)
`(copy-seq (the simple-vector ,constants)))
in the list , it only considers the first appearance .
(defun compute-initarg-positions (class initarg-names)
(let* ((layout (wrapper-instance-slots-layout (class-wrapper class)))
(positions
(gathering1 (collecting)
(iterate ((slot-name (list-elements layout))
(position (interval :from 0)))
(gather1 (cons slot-name position)))))
(slot-initargs
(mapcar #'(lambda (slotd)
(list (slotd-initargs slotd)
(or (cdr (assq (slotd-name slotd) positions))
':class)))
(class-slots class))))
(dolist (initarg initarg-names)
(dolist (slot-entry slot-initargs)
(let ((slot-initargs (car slot-entry)))
(when (and (listp slot-initargs)
(not (null slot-initargs))
(memq initarg slot-initargs))
(setf (car slot-entry) initarg)))))
(gathering1 (collecting)
(dolist (initarg initarg-names)
(let ((positions (gathering1 (collecting)
(dolist (slot-entry slot-initargs)
(when (eq (car slot-entry) initarg)
(gather1 (cadr slot-entry)))))))
(when positions
(gather1 (cons initarg positions))))))))
The FALLBACK case allows anything . This always works , and always appears
(define-constructor-code-type fallback
(class name arglist supplied-initarg-names supplied-initargs)
(declare (ignore name supplied-initarg-names))
`(function
(lambda (&rest ignore)
(declare (ignore ignore))
(function
(lambda ,arglist
(make-instance
',(class-name class)
,@(gathering1 (collecting)
(iterate ((tail (*list-tails supplied-initargs :by #'cddr)))
(gather1 `',(car tail))
(gather1 (cadr tail))))))))))
constant or non - constant default
supplied
slot - filling
(define-constructor-code-type general
(class name arglist supplied-initarg-names supplied-initargs)
(declare (ignore name))
(let ((raw-allocator (raw-instance-allocator class))
(slots-fetcher (slots-fetcher class))
(wrapper-fetcher (wrapper-fetcher class)))
`(function
(lambda (class .wrapper. defaults init shared)
(multiple-value-bind (.constants.
.constant-initargs.
.initfns-initargs-and-positions.
.supplied-initarg-positions.
.shared-initfns.
.initfns.)
(general-generator-internal class
defaults
init
shared
',supplied-initarg-names
',supplied-initargs)
.supplied-initarg-positions.
(when (and .constants.
(null (non-clos-or-after-initialize-instance-methods-p
init))
(null (non-clos-or-after-shared-initialize-methods-p
shared)))
(function
(lambda ,arglist
(declare (optimize (speed 3) (safety 0)))
(let ((.instance. (,raw-allocator))
(.slots. (copy-constant-vector .constants.))
(.positions. .supplied-initarg-positions.)
(.initargs. .constant-initargs.))
.positions.
(setf (,slots-fetcher .instance.) .slots.)
(setf (,wrapper-fetcher .instance.) .wrapper.)
(dolist (entry .initfns-initargs-and-positions.)
(let ((val (funcall (car entry)))
(initarg (cadr entry)))
(when initarg
(push val .initargs.)
(push initarg .initargs.))
(dolist (pos (cddr entry))
(setf (%svref .slots. pos) val))))
,@(gathering1 (collecting)
(doplist (initarg value) supplied-initargs
(unless (constantp value)
(gather1 `(let ((.value. ,value))
(push .value. .initargs.)
(push ',initarg .initargs.)
(dolist (.p. (pop .positions.))
(setf (%svref .slots. .p.)
.value.)))))))
(dolist (fn .shared-initfns.)
(apply fn .instance. t .initargs.))
(dolist (fn .initfns.)
(apply fn .instance. .initargs.))
.instance.)))))))))
(defun general-generator-internal
(class defaults init shared supplied-initarg-names supplied-initargs)
(flet ((bail-out () (return-from general-generator-internal nil)))
(let* ((constants (compute-constant-vector class))
(layout (wrapper-instance-slots-layout (class-wrapper class)))
(initarg-positions
(compute-initarg-positions class
(append supplied-initarg-names
(mapcar #'car defaults))))
(initfns-initargs-and-positions ())
(supplied-initarg-positions ())
(constant-initargs ())
(used-positions ()))
Go through each of the supplied initargs for three reasons .
- Otherwise remember the positions no two initargs
(doplist (initarg val) supplied-initargs
(let ((positions (cdr (assq initarg initarg-positions))))
(cond ((memq :class positions) (bail-out))
((constantp val)
(setq val (eval val))
(push val constant-initargs)
(push initarg constant-initargs)
(dolist (pos positions) (setf (svref constants pos) val)))
(t
(push positions supplied-initarg-positions)))
(setq used-positions (append positions used-positions))))
Go through each of the default initargs , for three reasons .
- If it is n't a constant , record its initfn and position .
(dolist (default defaults)
(let* ((name (car default))
(initfn (cadr default))
(form (caddr default))
(value ())
(positions (cdr (assq name initarg-positions))))
(unless (memq name supplied-initarg-names)
(cond ((memq :class positions) (bail-out))
((constantp form)
(setq value (eval form))
(push value constant-initargs)
(push name constant-initargs)
(dolist (pos positions)
(setf (svref constants pos) value)))
(t
(push (list* initfn name positions)
initfns-initargs-and-positions)))
(setq used-positions (append positions used-positions)))))
- If it is a class slot , and has an initform , bail out .
- Otherwise , record its initfn and position
(dolist (slotd (class-slots class))
(let* ((alloc (slotd-allocation slotd))
(name (slotd-name slotd))
(form (slotd-initform slotd))
(initfn (slotd-initfunction slotd))
(position (position name layout)))
(cond ((neq alloc :instance)
(unless (or (eq form *slotd-unsupplied*)
(null initfn))
(bail-out)))
((member position used-positions))
((or (constantp form)
(eq form *slotd-unsupplied*)))
(t
(push (list initfn nil position)
initfns-initargs-and-positions)))))
(values constants
constant-initargs
(nreverse initfns-initargs-and-positions)
(nreverse supplied-initarg-positions)
(mapcar #'method-function
(remove *standard-shared-initialize-method* shared))
(mapcar #'method-function
(remove *standard-initialize-instance-method* init))))))
constant or non - constant default
supplied that are arguments to constructor , or constants
slot - filling
(define-constructor-code-type no-methods
(class name arglist supplied-initarg-names supplied-initargs)
(declare (ignore name))
(let ((raw-allocator (raw-instance-allocator class))
(slots-fetcher (slots-fetcher class))
(wrapper-fetcher (wrapper-fetcher class)))
`(function
(lambda (class .wrapper. defaults init shared)
(multiple-value-bind (.constants.
.initfns-and-positions.
.supplied-initarg-positions.)
(no-methods-generator-internal class
defaults
',supplied-initarg-names
',supplied-initargs)
.initfns-and-positions.
.supplied-initarg-positions.
(when (and .constants.
(null (non-clos-initialize-instance-methods-p init))
(null (non-clos-shared-initialize-methods-p shared)))
#'(lambda ,arglist
(declare (optimize (speed 3) (safety 0)))
(let ((.instance. (,raw-allocator))
(.slots. (copy-constant-vector .constants.))
(.positions. .supplied-initarg-positions.))
.positions.
(setf (,slots-fetcher .instance.) .slots.)
(setf (,wrapper-fetcher .instance.) .wrapper.)
(dolist (entry .initfns-and-positions.)
(let ((val (funcall (car entry))))
(dolist (pos (cdr entry))
(setf (%svref .slots. pos) val))))
,@(gathering1 (collecting)
(doplist (initarg value) supplied-initargs
(unless (constantp value)
(gather1
`(let ((.value. ,value))
(dolist (.p. (pop .positions.))
(setf (%svref .slots. .p.) .value.)))))))
.instance.))))))))
(defun no-methods-generator-internal
(class defaults supplied-initarg-names supplied-initargs)
(flet ((bail-out () (return-from no-methods-generator-internal nil)))
(let* ((constants (compute-constant-vector class))
(layout (wrapper-instance-slots-layout (class-wrapper class)))
(initarg-positions
(compute-initarg-positions class
(append supplied-initarg-names
(mapcar #'car defaults))))
(initfns-and-positions ())
(supplied-initarg-positions ())
(used-positions ()))
Go through each of the supplied initargs for three reasons .
- Otherwise remember the positions , no two initargs
(doplist (initarg val) supplied-initargs
(let ((positions (cdr (assq initarg initarg-positions))))
(cond ((memq :class positions) (bail-out))
((constantp val)
(setq val (eval val))
(dolist (pos positions)
(setf (svref constants pos) val)))
(t
(push positions supplied-initarg-positions)))
(setq used-positions (append positions used-positions))))
Go through each of the default initargs , for three reasons .
- If it is n't a constant , record its initfn and position .
(dolist (default defaults)
(let* ((name (car default))
(initfn (cadr default))
(form (caddr default))
(value ())
(positions (cdr (assq name initarg-positions))))
(unless (memq name supplied-initarg-names)
(cond ((memq :class positions) (bail-out))
((constantp form)
(setq value (eval form))
(dolist (pos positions)
(setf (svref constants pos) value)))
(t
(push (cons initfn positions)
initfns-and-positions)))
(setq used-positions (append positions used-positions)))))
- If it is a class slot , and has an initform , bail out .
- Otherwise , record its initfn and position
(dolist (slotd (class-slots class))
(let* ((alloc (slotd-allocation slotd))
(name (slotd-name slotd))
(form (slotd-initform slotd))
(initfn (slotd-initfunction slotd))
(position (position name layout)))
(cond ((neq alloc :instance)
(unless (or (eq form *slotd-unsupplied*)
(null initfn))
(bail-out)))
((member position used-positions))
((or (constantp form)
(eq form *slotd-unsupplied*)))
(t
(push (list initfn position) initfns-and-positions)))))
(values constants
(nreverse initfns-and-positions)
(nreverse supplied-initarg-positions)))))
constant default
supplied
slot filling initargs
(define-constructor-code-type simple-slots
(class name arglist supplied-initarg-names supplied-initargs)
(declare (ignore name))
(let ((raw-allocator (raw-instance-allocator class))
(slots-fetcher (slots-fetcher class))
(wrapper-fetcher (wrapper-fetcher class)))
`(function
(lambda (class .wrapper. defaults init shared)
(when (and (null (non-clos-initialize-instance-methods-p init))
(null (non-clos-shared-initialize-methods-p shared)))
(multiple-value-bind (.constants. .supplied-initarg-positions.)
(simple-slots-generator-internal class
defaults
',supplied-initarg-names
',supplied-initargs)
(when .constants.
(function
(lambda ,arglist
(declare (optimize (speed 3) (safety 0)))
(let ((.instance. (,raw-allocator))
(.slots. (copy-constant-vector .constants.))
(.positions. .supplied-initarg-positions.))
.positions.
(setf (,slots-fetcher .instance.) .slots.)
(setf (,wrapper-fetcher .instance.) .wrapper.)
,@(gathering1 (collecting)
(doplist (initarg value) supplied-initargs
(unless (constantp value)
(gather1
`(let ((.value. ,value))
(dolist (.p. (pop .positions.))
(setf (%svref .slots. .p.) .value.)))))))
.instance.))))))))))
(defun simple-slots-generator-internal
(class defaults supplied-initarg-names supplied-initargs)
(flet ((bail-out () (return-from simple-slots-generator-internal nil)))
(let* ((constants (compute-constant-vector class))
(layout (wrapper-instance-slots-layout (class-wrapper class)))
(initarg-positions
(compute-initarg-positions class
(append supplied-initarg-names
(mapcar #'car defaults))))
(supplied-initarg-positions ())
(used-positions ()))
Go through each of the supplied initargs for three reasons .
- Otherwise remember the positions , no two initargs
(doplist (initarg val) supplied-initargs
(let ((positions (cdr (assq initarg initarg-positions))))
(cond ((memq :class positions) (bail-out))
((constantp val)
(setq val (eval val))
(dolist (pos positions)
(setf (svref constants pos) val)))
(t
(push positions supplied-initarg-positions)))
(setq used-positions (append used-positions positions))))
Go through each of the default initargs for three reasons .
(dolist (default defaults)
(let* ((name (car default))
(form (caddr default))
(value ())
(positions (cdr (assq name initarg-positions))))
(unless (memq name supplied-initarg-names)
(cond ((memq :class positions) (bail-out))
((not (constantp form))
(bail-out))
(t
(setq value (eval form))
(dolist (pos positions)
(setf (svref constants pos) value)))))))
- If it has a non - constant initform , bail - out . This
- If it has a constant or unsupplied initform we do n't
(dolist (slotd (class-slots class))
(let* ((alloc (slotd-allocation slotd))
(name (slotd-name slotd))
(form (slotd-initform slotd))
(initfn (slotd-initfunction slotd))
(position (position name layout)))
(cond ((neq alloc :instance)
(unless (or (eq form *slotd-unsupplied*)
(null initfn))
(bail-out)))
((member position used-positions))
((or (constantp form)
(eq form *slotd-unsupplied*)))
(t
(bail-out)))))
(values constants (nreverse supplied-initarg-positions)))))
|
726001c6d839e05a1aabeb781ea11efdd3241f041cb871536adea4419bffbc6f | mu-chaco/ReWire | twostate.hs | data Bit = Zero | One
data W8 = W8 Bit Bit Bit Bit Bit Bit Bit Bit
grunt :: StT W8 (StT W8 I) ()
grunt = do
r0 <- get
lift (put r0)
incr :: ReT Bit W8 (StT W8 (StT W8 I)) ()
incr = do
--r0 <- lift get
--lift (lift (put r0))
lift grunt
signal (W8 Zero Zero Zero Zero Zero Zero Zero Zero)
incr
start :: ReT Bit W8 I (((),W8),W8)
start = extrude (extrude incr (W8 Zero Zero Zero Zero Zero Zero Zero Zero)) (W8 Zero Zero Zero Zero Zero Zero Zero One)
| null | https://raw.githubusercontent.com/mu-chaco/ReWire/a8dcea6ab0989474988a758179a1d876e2c32370/cruft/test/complete/two/twostate.hs | haskell | r0 <- lift get
lift (lift (put r0)) | data Bit = Zero | One
data W8 = W8 Bit Bit Bit Bit Bit Bit Bit Bit
grunt :: StT W8 (StT W8 I) ()
grunt = do
r0 <- get
lift (put r0)
incr :: ReT Bit W8 (StT W8 (StT W8 I)) ()
incr = do
lift grunt
signal (W8 Zero Zero Zero Zero Zero Zero Zero Zero)
incr
start :: ReT Bit W8 I (((),W8),W8)
start = extrude (extrude incr (W8 Zero Zero Zero Zero Zero Zero Zero Zero)) (W8 Zero Zero Zero Zero Zero Zero Zero One)
|
a1e7bbb97c16a77dd7d8b86694a82541e9250c56420ce154622491b3fa541fb6 | tweag/ormolu | arguments.hs | {-# LANGUAGE RankNTypes #-}
functionName
:: (C1, C2, C3, C4, C5)
=> a
-> b
-> (forall a.
(C6, C7)
=> LongDataTypeName
-> a
-> AnotherLongDataTypeName
-> b
-> c
)
-> (c -> d)
-> (a, b, c, d)
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/signature/type/arguments.hs | haskell | # LANGUAGE RankNTypes # |
functionName
:: (C1, C2, C3, C4, C5)
=> a
-> b
-> (forall a.
(C6, C7)
=> LongDataTypeName
-> a
-> AnotherLongDataTypeName
-> b
-> c
)
-> (c -> d)
-> (a, b, c, d)
|
72e3d545b68dd9241f3b4178c5e4dbc298995d3e3652d0a9b529de795e96921d | hanshuebner/bknr-web | feed-tags.lisp | (in-package :bknr-user)
(enable-interpol-syntax)
(define-bknr-tag feed-keyword-choose-dialog
(&key (size "4") (name "keyword") (create nil))
(let ((size (or (parse-integer size :junk-allowed t) 1)))
(keyword-choose-dialog (all-feed-keywords)
:size size :name name :create create)))
(define-bknr-tag feed-form (&key feed-id)
"Display a formular to edit a feed"
(let ((feed (when feed-id (store-object-with-id feed-id))))
(html ((:form :method "post")
(if feed
(html ((:input :type "hidden"
:name "feed-id"
:value (store-object-id feed)))
(:table (:tr (:td "name")
(:td ((:a :href (format nil "/feed/~a"
(feed-name feed)))
(:princ-safe (feed-name feed)))))
(:tr (:td "url")
(:td ((:input :type "text" :size "50" :name "url"
:value (feed-url feed)))))
(:tr (:td "refresh-interval")
(:td ((:input :type "text" :size "6" :name "refresh"
:value (feed-refresh-interval feed)))))
(:tr (:td "type")
(:td (select-box "type" '(("rss091" "rss091")
("rss10" "rss10")
("rss20" "rss20")
("atom" "atom"))
:default (string-downcase
(symbol-name (feed-type feed))))))
(:tr (:td "encoding")
(:td (select-box "encoding" '(("iso-8859-1" "iso-8859-1")
("utf-8" "utf-8"))
:default (string-downcase
(symbol-name (feed-encoding feed))))))
(:tr (:td "last-update")
(:td (:princ-safe (format-date-time
(feed-last-updated feed)))))
(:tr (:td "keywords")
(:td
(loop for keyword in (mapcar #'string-downcase
(feed-keywords feed))
do (html ((:a :href
(concatenate 'string
"/feed-keyword/" keyword))
(:princ #?" $(keyword) "))))))
(:tr (:td "add/rm keywords")
(:td (feed-keyword-choose-dialog :create t)))
(:tr ((:td :colspan "2")
(submit-button "save" "save")
(submit-button "add-keywords" "add keywords")
(submit-button "remove-keywords" "remove keywords")
(submit-button "update" "refresh feed")
(submit-button "delete" "delete feed")))))
(html (:table (:tr (:td "name")
(:td ((:input :type "text" :size "40" :name "name"))))
(:tr (:td "url")
(:td ((:input :type "text" :size "50" :name "url"))))
(:tr (:td "refresh-interval")
(:td ((:input :type "text" :size "6" :name "refresh"))))
(:tr (:td "type")
(:td (select-box "type" '(("rss091" "rss091")
("rss10" "rss10")
("rss20" "rss20")
("atom" "atom"))
:default "rss10")))
(:tr (:td "encoding")
(:td (select-box "encoding" '(("iso-8859-1" "iso-8859-1")
("utf-8" "utf-8"))
:default "iso-8859-1")))
(:tr (:td "keywords")
(:td (feed-keyword-choose-dialog :create t)))
(:tr ((:td :colspan "2")
(submit-button "create" "create"))))))))))
(define-bknr-tag rss-feed-page (link title grouped-items)
(html ((:div :class "channel")
(:h2 ((:a :href link)
(:princ-safe title))))
((:div :class "items")
(dolist (grouped-item grouped-items)
(html (:h2 (:princ-safe (format-date-time (car grouped-item)
:show-weekday t
:show-time nil
:show-seconds nil)))
(dolist (item (sort (cdr grouped-item) #'> :key #'rss-item-date))
(html ((:div :class "item")
(:h3 (if (rss-item-orig-feed item)
;; XXX ieeks
(let* ((title (regex-replace-all "^.*?- " (rss-item-title item) ""))
(orig-channel (rss-feed-channel (rss-item-orig-feed item)))
(orig-title (rss-channel-title orig-channel))
(orig-link (rss-channel-link orig-channel)))
(if (and orig-title orig-link)
(html ((:a :href orig-link) (:princ-safe orig-title)))
(html (:princ orig-title)))
(html " - "
((:a :href (rss-item-link item)) (:princ-safe title))))
(html ((:a :href (rss-item-link item))
(:princ (rss-item-title item))))))
(:p (:princ (rss-item-desc item)))))))))))
(define-bknr-tag feed (&key feed-id)
"Display a feed"
(let ((feed (store-object-with-id feed-id)))
(let* ((rss-feed (feed-rss-feed feed))
(image (when rss-feed (rss-feed-image rss-feed))))
(html (:h1 (:princ (feed-name feed)))
((:a :href (format nil "/feed-rss/~a" (feed-name feed))) "rss") (:br)
"Last updated: " (:princ-safe
(format-date-time (feed-last-updated feed) :show-weekday t))
(:br)
(when (and image (rss-image-url image))
(html ((:img :src (rss-image-url image)
:alt (rss-image-title image)))))
"Keywords: "
(loop for keyword in (mapcar #'string-downcase (feed-keywords feed))
do (html ((:a :href (concatenate 'string "/feed-keyword/" keyword))
(:princ #?" $(keyword) "))))))))
| null | https://raw.githubusercontent.com/hanshuebner/bknr-web/5c30b61818a2f02f6f2e5dc69fd77396ec3afc51/modules/feed/feed-tags.lisp | lisp | XXX ieeks | (in-package :bknr-user)
(enable-interpol-syntax)
(define-bknr-tag feed-keyword-choose-dialog
(&key (size "4") (name "keyword") (create nil))
(let ((size (or (parse-integer size :junk-allowed t) 1)))
(keyword-choose-dialog (all-feed-keywords)
:size size :name name :create create)))
(define-bknr-tag feed-form (&key feed-id)
"Display a formular to edit a feed"
(let ((feed (when feed-id (store-object-with-id feed-id))))
(html ((:form :method "post")
(if feed
(html ((:input :type "hidden"
:name "feed-id"
:value (store-object-id feed)))
(:table (:tr (:td "name")
(:td ((:a :href (format nil "/feed/~a"
(feed-name feed)))
(:princ-safe (feed-name feed)))))
(:tr (:td "url")
(:td ((:input :type "text" :size "50" :name "url"
:value (feed-url feed)))))
(:tr (:td "refresh-interval")
(:td ((:input :type "text" :size "6" :name "refresh"
:value (feed-refresh-interval feed)))))
(:tr (:td "type")
(:td (select-box "type" '(("rss091" "rss091")
("rss10" "rss10")
("rss20" "rss20")
("atom" "atom"))
:default (string-downcase
(symbol-name (feed-type feed))))))
(:tr (:td "encoding")
(:td (select-box "encoding" '(("iso-8859-1" "iso-8859-1")
("utf-8" "utf-8"))
:default (string-downcase
(symbol-name (feed-encoding feed))))))
(:tr (:td "last-update")
(:td (:princ-safe (format-date-time
(feed-last-updated feed)))))
(:tr (:td "keywords")
(:td
(loop for keyword in (mapcar #'string-downcase
(feed-keywords feed))
do (html ((:a :href
(concatenate 'string
"/feed-keyword/" keyword))
(:princ #?" $(keyword) "))))))
(:tr (:td "add/rm keywords")
(:td (feed-keyword-choose-dialog :create t)))
(:tr ((:td :colspan "2")
(submit-button "save" "save")
(submit-button "add-keywords" "add keywords")
(submit-button "remove-keywords" "remove keywords")
(submit-button "update" "refresh feed")
(submit-button "delete" "delete feed")))))
(html (:table (:tr (:td "name")
(:td ((:input :type "text" :size "40" :name "name"))))
(:tr (:td "url")
(:td ((:input :type "text" :size "50" :name "url"))))
(:tr (:td "refresh-interval")
(:td ((:input :type "text" :size "6" :name "refresh"))))
(:tr (:td "type")
(:td (select-box "type" '(("rss091" "rss091")
("rss10" "rss10")
("rss20" "rss20")
("atom" "atom"))
:default "rss10")))
(:tr (:td "encoding")
(:td (select-box "encoding" '(("iso-8859-1" "iso-8859-1")
("utf-8" "utf-8"))
:default "iso-8859-1")))
(:tr (:td "keywords")
(:td (feed-keyword-choose-dialog :create t)))
(:tr ((:td :colspan "2")
(submit-button "create" "create"))))))))))
(define-bknr-tag rss-feed-page (link title grouped-items)
(html ((:div :class "channel")
(:h2 ((:a :href link)
(:princ-safe title))))
((:div :class "items")
(dolist (grouped-item grouped-items)
(html (:h2 (:princ-safe (format-date-time (car grouped-item)
:show-weekday t
:show-time nil
:show-seconds nil)))
(dolist (item (sort (cdr grouped-item) #'> :key #'rss-item-date))
(html ((:div :class "item")
(:h3 (if (rss-item-orig-feed item)
(let* ((title (regex-replace-all "^.*?- " (rss-item-title item) ""))
(orig-channel (rss-feed-channel (rss-item-orig-feed item)))
(orig-title (rss-channel-title orig-channel))
(orig-link (rss-channel-link orig-channel)))
(if (and orig-title orig-link)
(html ((:a :href orig-link) (:princ-safe orig-title)))
(html (:princ orig-title)))
(html " - "
((:a :href (rss-item-link item)) (:princ-safe title))))
(html ((:a :href (rss-item-link item))
(:princ (rss-item-title item))))))
(:p (:princ (rss-item-desc item)))))))))))
(define-bknr-tag feed (&key feed-id)
"Display a feed"
(let ((feed (store-object-with-id feed-id)))
(let* ((rss-feed (feed-rss-feed feed))
(image (when rss-feed (rss-feed-image rss-feed))))
(html (:h1 (:princ (feed-name feed)))
((:a :href (format nil "/feed-rss/~a" (feed-name feed))) "rss") (:br)
"Last updated: " (:princ-safe
(format-date-time (feed-last-updated feed) :show-weekday t))
(:br)
(when (and image (rss-image-url image))
(html ((:img :src (rss-image-url image)
:alt (rss-image-title image)))))
"Keywords: "
(loop for keyword in (mapcar #'string-downcase (feed-keywords feed))
do (html ((:a :href (concatenate 'string "/feed-keyword/" keyword))
(:princ #?" $(keyword) "))))))))
|
36bebc9607b78925b4d388520165b1dc92aa5bd199ba0679135fb4dbc5e1adc7 | pfdietz/ansi-test | random.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sat Sep 6 15:47:42 2003
Contains : Tests of
(deftest random.error.1
(signals-error (random) program-error)
t)
(deftest random.error.2
(signals-error (random 10 *random-state* nil) program-error)
t)
(deftest random.error.3
(check-type-error #'random (typef '(real (0))))
nil)
(deftest random.1
(loop for i from 2 to 30
for n = (ash 1 i)
nconc
(loop for j = (1+ (random n))
repeat 20
nconc
(loop for r = (random j)
repeat i
unless (and (integerp r)
(<= 0 r)
(< r j))
collect (list j r))))
nil)
(deftest random.2
(loop for i from 2 to 20
for n = (ash 1 i)
nconc
(loop for j = (random (float n))
repeat 20
unless (zerop j)
nconc
(loop for r = (random j)
repeat 20
unless (and (eql (float r j) r)
(<= 0 r)
(< r j))
collect (list j r))))
nil)
(deftest random.3
(binomial-distribution-test 10000
#'(lambda () (eql (random 2) 0)))
t)
(deftest random.4
(binomial-distribution-test 10000
#'(lambda () (< (random 1.0s0) 0.5s0)))
t)
(deftest random.5
(binomial-distribution-test 10000
#'(lambda () (< (random 1.0d0) 0.5d0)))
t)
(deftest random.6
(binomial-distribution-test 10000
#'(lambda () (evenp (random 1024))))
t)
(deftest random.7
(loop for x in '(10.0s0 20.0f0 30.0d0 40.0l0)
for r = (random x)
unless (eql (float r x) r)
collect (list x r))
nil)
(deftest random.8
(let* ((f1 '(lambda (x) (random (if x 10 20))))
(f2 (compile nil f1)))
(values
(loop repeat 100 always (<= 0 (funcall f2 t) 9))
(loop repeat 100 always (<= 0 (funcall f2 nil) 19))))
t t)
;;; Do more statistical tests here
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/numbers/random.lsp | lisp | -*- Mode: Lisp -*-
Do more statistical tests here | Author :
Created : Sat Sep 6 15:47:42 2003
Contains : Tests of
(deftest random.error.1
(signals-error (random) program-error)
t)
(deftest random.error.2
(signals-error (random 10 *random-state* nil) program-error)
t)
(deftest random.error.3
(check-type-error #'random (typef '(real (0))))
nil)
(deftest random.1
(loop for i from 2 to 30
for n = (ash 1 i)
nconc
(loop for j = (1+ (random n))
repeat 20
nconc
(loop for r = (random j)
repeat i
unless (and (integerp r)
(<= 0 r)
(< r j))
collect (list j r))))
nil)
(deftest random.2
(loop for i from 2 to 20
for n = (ash 1 i)
nconc
(loop for j = (random (float n))
repeat 20
unless (zerop j)
nconc
(loop for r = (random j)
repeat 20
unless (and (eql (float r j) r)
(<= 0 r)
(< r j))
collect (list j r))))
nil)
(deftest random.3
(binomial-distribution-test 10000
#'(lambda () (eql (random 2) 0)))
t)
(deftest random.4
(binomial-distribution-test 10000
#'(lambda () (< (random 1.0s0) 0.5s0)))
t)
(deftest random.5
(binomial-distribution-test 10000
#'(lambda () (< (random 1.0d0) 0.5d0)))
t)
(deftest random.6
(binomial-distribution-test 10000
#'(lambda () (evenp (random 1024))))
t)
(deftest random.7
(loop for x in '(10.0s0 20.0f0 30.0d0 40.0l0)
for r = (random x)
unless (eql (float r x) r)
collect (list x r))
nil)
(deftest random.8
(let* ((f1 '(lambda (x) (random (if x 10 20))))
(f2 (compile nil f1)))
(values
(loop repeat 100 always (<= 0 (funcall f2 t) 9))
(loop repeat 100 always (<= 0 (funcall f2 nil) 19))))
t t)
|
369a00fa100f1383be26d5c65d9b500bdf6eaf20cfa2e7f9c2ccf288f9544942 | clojurewerkz/meltdown | types.clj | (ns clojurewerkz.meltdown.types)
(defprotocol Foldable
(fold [coll f]))
(defprotocol Functor
(fmap [coll f]))
(defprotocol Monoid
(mempty [_])
(mappend [old new]))
(defn mconcat
[m coll]
(reduce mappend (mempty m) coll))
;;
;; Monoid
;;
(extend-protocol Monoid
clojure.lang.PersistentVector
(mempty [_] [])
(mappend [old new] (conj old new))
clojure.lang.IPersistentMap
(mempty [_] {})
(mappend [old [k v]] (update-in old [k]
#(if (nil? %)
[v]
(conj % v)))))
;;
;; Functor
;;
(extend-protocol Functor
clojure.lang.PersistentVector
(fmap [coll f]
(map f coll))
clojure.lang.IPersistentMap
(fmap [m f]
(zipmap (keys m)
(map #(map f %) (vals m)))))
;;
;; Foldable
;;
(extend-protocol Foldable
clojure.lang.PersistentVector
(fold [coll f]
(reduce f coll))
clojure.lang.IPersistentMap
(fold [m f]
(zipmap (keys m)
(->> m vals (map #(reduce f %))))))
| null | https://raw.githubusercontent.com/clojurewerkz/meltdown/58d50141bb35b4a5abf59dcb13db9f577b6b3b9f/src/clojure/clojurewerkz/meltdown/types.clj | clojure |
Monoid
Functor
Foldable
| (ns clojurewerkz.meltdown.types)
(defprotocol Foldable
(fold [coll f]))
(defprotocol Functor
(fmap [coll f]))
(defprotocol Monoid
(mempty [_])
(mappend [old new]))
(defn mconcat
[m coll]
(reduce mappend (mempty m) coll))
(extend-protocol Monoid
clojure.lang.PersistentVector
(mempty [_] [])
(mappend [old new] (conj old new))
clojure.lang.IPersistentMap
(mempty [_] {})
(mappend [old [k v]] (update-in old [k]
#(if (nil? %)
[v]
(conj % v)))))
(extend-protocol Functor
clojure.lang.PersistentVector
(fmap [coll f]
(map f coll))
clojure.lang.IPersistentMap
(fmap [m f]
(zipmap (keys m)
(map #(map f %) (vals m)))))
(extend-protocol Foldable
clojure.lang.PersistentVector
(fold [coll f]
(reduce f coll))
clojure.lang.IPersistentMap
(fold [m f]
(zipmap (keys m)
(->> m vals (map #(reduce f %))))))
|
28bc51483f5fac6c3229903463b457a7318c506d4079b568a7401cf5036dcbf5 | noteed/mojito | Inferencer.hs | # LANGUAGE GeneralizedNewtypeDeriving , FlexibleContexts #
module Language.Mojito.Inference.Cardelli.Inferencer where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Writer
import Language.Mojito.Syntax.Types
import Language.Mojito.Inference.Substitution
import Language.Mojito.Inference.Cardelli.Environment
data Inferencer = Inferencer
{ tiNextId :: Int -- to uniquely name type variables
, tiTypes :: [Simple] -- the available (declared) types
, tiSubstitution :: Substitution -- the global substitution
, tiTypings :: [(Int,Simple)] -- the typings for each key
}
deriving Show
inferencer :: Inferencer
inferencer = Inferencer
{ tiNextId = 0
, tiTypes = []
, tiSubstitution = idSubstitution
, tiTypings = []
}
newtype Inf a = Inf
{ runInf ::
ExceptT String (WriterT [Note] (StateT Inferencer Identity)) a
}
deriving
(Applicative, Functor, Monad, MonadState Inferencer,
MonadError String, MonadWriter [Note])
-- Creates a unique type variable from a string. The result must be wrapped in
a TyVar .
fresh :: MonadState Inferencer m => String -> m String
fresh a = do
n <- gets tiNextId
modify (\s -> s { tiNextId = n + 1 })
return (a ++ show n)
-- Given a type, returns the same type with all the
-- generic variables renamed with fresh names.
refresh :: MonadState Inferencer m => Simple -> [String] -> m Simple
refresh t ng = do
let gs = gvars t ng
gs' <- mapM (fmap TyVar . fresh) gs
return $ subs (fromList $ zip gs gs') t
-- Compose the given substitution with the current substitution.
compose :: MonadState Inferencer m => Substitution -> m ()
compose ts = do
n <- gets tiSubstitution
modify (\s -> s { tiSubstitution = comp "compose" ts n })
-- Returns a type using the current substitution.
substitute :: MonadState Inferencer m => Simple -> m Simple
substitute t = do
n <- gets tiSubstitution
return (subs n t)
data Note = NString String
note :: MonadWriter [Note] m => String -> m ()
note m = do
tell [NString m]
recordType :: Int -> Simple -> Inf ()
recordType k t = modify (\s -> s { tiTypings = (k,t) : tiTypings s })
| null | https://raw.githubusercontent.com/noteed/mojito/893d1d826d969b0db7bbc8884df3b417db151d14/Language/Mojito/Inference/Cardelli/Inferencer.hs | haskell | to uniquely name type variables
the available (declared) types
the global substitution
the typings for each key
Creates a unique type variable from a string. The result must be wrapped in
Given a type, returns the same type with all the
generic variables renamed with fresh names.
Compose the given substitution with the current substitution.
Returns a type using the current substitution. | # LANGUAGE GeneralizedNewtypeDeriving , FlexibleContexts #
module Language.Mojito.Inference.Cardelli.Inferencer where
import Control.Monad.Except
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Writer
import Language.Mojito.Syntax.Types
import Language.Mojito.Inference.Substitution
import Language.Mojito.Inference.Cardelli.Environment
data Inferencer = Inferencer
}
deriving Show
inferencer :: Inferencer
inferencer = Inferencer
{ tiNextId = 0
, tiTypes = []
, tiSubstitution = idSubstitution
, tiTypings = []
}
newtype Inf a = Inf
{ runInf ::
ExceptT String (WriterT [Note] (StateT Inferencer Identity)) a
}
deriving
(Applicative, Functor, Monad, MonadState Inferencer,
MonadError String, MonadWriter [Note])
a TyVar .
fresh :: MonadState Inferencer m => String -> m String
fresh a = do
n <- gets tiNextId
modify (\s -> s { tiNextId = n + 1 })
return (a ++ show n)
refresh :: MonadState Inferencer m => Simple -> [String] -> m Simple
refresh t ng = do
let gs = gvars t ng
gs' <- mapM (fmap TyVar . fresh) gs
return $ subs (fromList $ zip gs gs') t
compose :: MonadState Inferencer m => Substitution -> m ()
compose ts = do
n <- gets tiSubstitution
modify (\s -> s { tiSubstitution = comp "compose" ts n })
substitute :: MonadState Inferencer m => Simple -> m Simple
substitute t = do
n <- gets tiSubstitution
return (subs n t)
data Note = NString String
note :: MonadWriter [Note] m => String -> m ()
note m = do
tell [NString m]
recordType :: Int -> Simple -> Inf ()
recordType k t = modify (\s -> s { tiTypings = (k,t) : tiTypings s })
|
a41b03f36b3047478024de973fd936e0fbb6efc98c642fe7f9b029d9cd57be10 | kaznum/programming_in_ocaml_exercise | squares.ml | let squares r =
let max = int_of_float(sqrt (float_of_int r)) in
let does_match x y =
if (x * x) + (y * y) = r then true else false in
let rec downto1 a =
if a = 0 then [] else a:: downto1 (a - 1) in
let rec exists f list =
fold_right (fun x -> (||) (f x) ) list false in
let rec count_matched xs =
match xs with
[] -> 0
| x::xs' ->
let f = does_match x in
(if exists f (downto1 x) then 1 else 0) + (count_matched xs') in
count_matched (downto1 max);;
squares 48612265;;
| null | https://raw.githubusercontent.com/kaznum/programming_in_ocaml_exercise/6f6a5d62a7a87a1c93561db88f08ae4e445b7d4e/ex5.7/squares.ml | ocaml | let squares r =
let max = int_of_float(sqrt (float_of_int r)) in
let does_match x y =
if (x * x) + (y * y) = r then true else false in
let rec downto1 a =
if a = 0 then [] else a:: downto1 (a - 1) in
let rec exists f list =
fold_right (fun x -> (||) (f x) ) list false in
let rec count_matched xs =
match xs with
[] -> 0
| x::xs' ->
let f = does_match x in
(if exists f (downto1 x) then 1 else 0) + (count_matched xs') in
count_matched (downto1 max);;
squares 48612265;;
|
|
776a1297e75a2cf45d99dbaa111d3f94939a6b5ca0537c7490a0fa58d0ce0078 | facebook/duckling | Corpus.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.BN.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale BN Nothing}, testOptions,
allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "শূন্য"
, "০"
]
, examples (NumeralValue 1)
[ "এক"
]
, examples (NumeralValue 2)
[ "দুই"
]
, examples (NumeralValue 3)
[ "তিন"
]
, examples (NumeralValue 4)
[ "চার"
]
, examples (NumeralValue 5)
[ "পাঁচ"
]
, examples (NumeralValue 6)
[ "ছয়"
]
, examples (NumeralValue 7)
[ "সাত"
]
, examples (NumeralValue 8)
[ "আট"
]
, examples (NumeralValue 9)
[ "নয়"
]
, examples (NumeralValue 10)
[ "দশ"
]
, examples (NumeralValue 11)
[ "এগারো"
]
, examples (NumeralValue 15)
[ "পনেরো"
]
, examples (NumeralValue 17)
[ "সতেরো"
]
, examples (NumeralValue 20)
[ "কুড়ি"
]
, examples (NumeralValue 22)
[ "বাইশ"
]
, examples (NumeralValue 24)
[ "চব্বিশ"
]
, examples (NumeralValue 25)
[ "পঁচিশ"
]
, examples (NumeralValue 26)
[ "ছাব্বিশ"
]
, examples (NumeralValue 28)
[ "আঠাশ"
]
, examples (NumeralValue 30)
[ "তিরিশ"
]
, examples (NumeralValue 40)
[ "চল্লিশ"
]
, examples (NumeralValue 50)
[ "পঞ্চাশ"
]
, examples (NumeralValue 70)
[ "সত্তর"
]
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Numeral/BN/Corpus.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Numeral.BN.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale BN Nothing}, testOptions,
allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "শূন্য"
, "০"
]
, examples (NumeralValue 1)
[ "এক"
]
, examples (NumeralValue 2)
[ "দুই"
]
, examples (NumeralValue 3)
[ "তিন"
]
, examples (NumeralValue 4)
[ "চার"
]
, examples (NumeralValue 5)
[ "পাঁচ"
]
, examples (NumeralValue 6)
[ "ছয়"
]
, examples (NumeralValue 7)
[ "সাত"
]
, examples (NumeralValue 8)
[ "আট"
]
, examples (NumeralValue 9)
[ "নয়"
]
, examples (NumeralValue 10)
[ "দশ"
]
, examples (NumeralValue 11)
[ "এগারো"
]
, examples (NumeralValue 15)
[ "পনেরো"
]
, examples (NumeralValue 17)
[ "সতেরো"
]
, examples (NumeralValue 20)
[ "কুড়ি"
]
, examples (NumeralValue 22)
[ "বাইশ"
]
, examples (NumeralValue 24)
[ "চব্বিশ"
]
, examples (NumeralValue 25)
[ "পঁচিশ"
]
, examples (NumeralValue 26)
[ "ছাব্বিশ"
]
, examples (NumeralValue 28)
[ "আঠাশ"
]
, examples (NumeralValue 30)
[ "তিরিশ"
]
, examples (NumeralValue 40)
[ "চল্লিশ"
]
, examples (NumeralValue 50)
[ "পঞ্চাশ"
]
, examples (NumeralValue 70)
[ "সত্তর"
]
]
|
2e375f6cf87d9db083b7937fcb49291e0436c731771beda643bdf080d90bf218 | DogLooksGood/holdem | ladder.clj | (ns poker.ladder
"Ladder is the leaderboard for player skills."
(:require
[clojure.spec.alpha :as s]
[poker.specs]
[poker.system.db :as db]
[crux.api :as crux]))
(s/def ::player-id some?)
(s/def ::borrow int?)
(s/def ::returns int?)
(s/def ::player-buyin-params (s/keys :req-un [::player-id ::buyin]))
(s/def ::player-inc-hands-params (s/keys :req-un [::player-id]))
(s/def ::player-returns-params (s/keys :req-un [::player-id ::returns]))
(defn calc-score
[player]
(let [{:ladder/keys [hands buyin returns]} player]
(if (and (int? hands)
(int? buyin)
(int? returns))
(let [score
(int
(* (- returns buyin)
(/ (+ (* 6 (Math/exp (- (Math/pow (/ hands 50) 2)))) 1))
(- 1 (/ 0.4 (+ 1 (Math/exp (* 0.00005 (- 120000 buyin))))))))]
(assoc player :ladder/score score))
player)))
(defn list-leaderboard
[]
(let [db (crux/db db/node)]
(->>
(crux/q
db
'{:find [(pull
p
[:player/name :player/avatar :ladder/hands :ladder/buyin :ladder/returns
:ladder/score])
s],
:where [[p :ladder/score s]],
:order-by [[s :desc]]})
(mapv first))))
(defn player-inc-hands
[params]
{:pre [(s/valid? ::player-inc-hands-params params)]}
(let [{:keys [player-id]} params
db (crux/db db/node)
player (crux/entity db player-id)
new-player (update player
:ladder/hands
(fnil inc 0))]
(crux/submit-tx db/node
[[:crux.tx/match player-id player]
[:crux.tx/put new-player]])))
(defn player-buyin
[params]
{:pre [(s/valid? ::player-buyin-params params)]}
(let [{:keys [player-id buyin]} params
db (crux/db db/node)
player (crux/entity db player-id)
new-player (-> player
(update
:ladder/buyin
(fnil + 0)
buyin)
(calc-score))]
(crux/submit-tx db/node
[[:crux.tx/match player-id player]
[:crux.tx/put new-player]])))
(defn player-returns
[params]
{:pre [(s/valid? ::player-returns-params params)]}
(let [{:keys [player-id returns]} params
db (crux/db db/node)
player (crux/entity db player-id)
new-player (-> player
(update :ladder/returns
(fnil + 0)
returns)
(update :ladder/hands
(fnil inc 0))
(calc-score))]
(crux/submit-tx db/node
[[:crux.tx/match player-id player]
[:crux.tx/put new-player]])))
| null | https://raw.githubusercontent.com/DogLooksGood/holdem/bc0f93ed65cab54890c91f78bb95fe3ba020a41f/src/clj/poker/ladder.clj | clojure | (ns poker.ladder
"Ladder is the leaderboard for player skills."
(:require
[clojure.spec.alpha :as s]
[poker.specs]
[poker.system.db :as db]
[crux.api :as crux]))
(s/def ::player-id some?)
(s/def ::borrow int?)
(s/def ::returns int?)
(s/def ::player-buyin-params (s/keys :req-un [::player-id ::buyin]))
(s/def ::player-inc-hands-params (s/keys :req-un [::player-id]))
(s/def ::player-returns-params (s/keys :req-un [::player-id ::returns]))
(defn calc-score
[player]
(let [{:ladder/keys [hands buyin returns]} player]
(if (and (int? hands)
(int? buyin)
(int? returns))
(let [score
(int
(* (- returns buyin)
(/ (+ (* 6 (Math/exp (- (Math/pow (/ hands 50) 2)))) 1))
(- 1 (/ 0.4 (+ 1 (Math/exp (* 0.00005 (- 120000 buyin))))))))]
(assoc player :ladder/score score))
player)))
(defn list-leaderboard
[]
(let [db (crux/db db/node)]
(->>
(crux/q
db
'{:find [(pull
p
[:player/name :player/avatar :ladder/hands :ladder/buyin :ladder/returns
:ladder/score])
s],
:where [[p :ladder/score s]],
:order-by [[s :desc]]})
(mapv first))))
(defn player-inc-hands
[params]
{:pre [(s/valid? ::player-inc-hands-params params)]}
(let [{:keys [player-id]} params
db (crux/db db/node)
player (crux/entity db player-id)
new-player (update player
:ladder/hands
(fnil inc 0))]
(crux/submit-tx db/node
[[:crux.tx/match player-id player]
[:crux.tx/put new-player]])))
(defn player-buyin
[params]
{:pre [(s/valid? ::player-buyin-params params)]}
(let [{:keys [player-id buyin]} params
db (crux/db db/node)
player (crux/entity db player-id)
new-player (-> player
(update
:ladder/buyin
(fnil + 0)
buyin)
(calc-score))]
(crux/submit-tx db/node
[[:crux.tx/match player-id player]
[:crux.tx/put new-player]])))
(defn player-returns
[params]
{:pre [(s/valid? ::player-returns-params params)]}
(let [{:keys [player-id returns]} params
db (crux/db db/node)
player (crux/entity db player-id)
new-player (-> player
(update :ladder/returns
(fnil + 0)
returns)
(update :ladder/hands
(fnil inc 0))
(calc-score))]
(crux/submit-tx db/node
[[:crux.tx/match player-id player]
[:crux.tx/put new-player]])))
|
|
1c43beb311417d08e928cbda1bf51c8b59406978bb9aa381949f8094e999af3d | appleshan/cl-http | micro-defsystem.lisp | -*- Syntax : Ansi - Common - Lisp ; Base : 10 ; Mode : lisp ; Package : Micro - Defsystem ; -*-
;;;
Copyright 1994 - 2001 , 2003 , .
;;; All rights reserved.
;;;-------------------------------------------------------------------
;;;
;;; MICRO-DEFSYSTEM
;;;
(eval-when (:execute :compile-toplevel :load-toplevel)
(defpackage micro-defsystem
(:nicknames mds)
(:use #-Genera"COMMON-LISP" #+Genera"FUTURE-COMMON-LISP")
(:export "*STANDARD-SYSTEMS*"
"*SYSTEMS*"
"*SYSTEM-DEFINE-HOOK*"
"*SYSTEM-UNDEFINE-HOOK*"
"DEFINE-SYSTEM"
"EXECUTE-SYSTEM-OPERATIONS"
"FIND-SYSTEM-NAMED"
"GET-SYSTEM-NAME"
"LOAD-STANDARD-SYSTEMS"
"NOTE-SYSTEM-DEFINITIONS"
"SYSTEM-FILES"
"REGISTER-SYSTEM"
"UNREGISTER-SYSTEM"))
(do-external-symbols (sym :micro-defsystem)
(import sym :cl-user))
(import (intern "*ALWAYS-COMPILE*" :cl-user) :micro-defsystem))
(in-package :micro-defsystem)
(defparameter *always-compile* (if (boundp '*always-compile*) (symbol-value '*always-compile*) nil)
"When non-null all files are compiled, whether or not they need it.")
(defun system-p (system)
"Returns non-null if SYSTEM denotes a known system for define-system."
(and (symbolp system)
(or (get system :system-keyword)
(get system :system-pathname))))
(deftype system
()
`(and symbol (satisfies system-p)))
(defmethod require-pathname ((pathname pathname))
(ccl:require (pathname-name pathname) pathname))
(defun conditional-compile-file (file &key load verbose output-file always require
(save-local-symbols ccl:*fasl-save-local-symbols*)
(save-doc-strings ccl:*fasl-save-doc-strings*)
(save-definitions ccl:*fasl-save-definitions*))
(let* ((source (merge-pathnames ".lisp" file))
(fasl (merge-pathnames ccl::*.fasl-pathname* (or output-file file))))
(unless (probe-file source)
(error 'file-error :pathname file))
(cond ((or always
*always-compile*
(not (probe-file fasl))
(< (file-write-date fasl) (file-write-date source)))
(compile-file source :output-file fasl :load load :verbose verbose
:save-local-symbols save-local-symbols
:save-doc-strings save-doc-strings
:save-definitions save-definitions))
(require (require-pathname fasl))
(load (load fasl :verbose verbose))
(t nil))))
(defun execute-system-operations (system operations &aux ops)
(check-type system symbol)
(macrolet ((processing-module ((module) &body clauses)
`(destructuring-bind (case action &rest files) ,module
(ecase case ,@clauses))))
(flet ((check-operation-arg (arg)
(let ((known-operations '(:load :compile :eval-load :compile-load :compile-load-always)))
(unless (member arg known-operations)
(error "~S is not one of the know options for OPERATIONS."arg known-operations))))
(eval-load (pathname &rest args)
(apply #'load (merge-pathnames ".lisp" pathname) args))
(perform-action (action files &optional require-only)
(ecase action
(:load
(cond (require-only (mapc #'require-pathname files))
(t (dolist (file files)
(load file :verbose t)))))
(:compile-load
(dolist (file files)
(conditional-compile-file file :verbose t :load t :require t))))))
;; check arguments to operations
(mapc #'check-operation-arg operations)
;;Combined operations take precedence
(unless (intersection operations '(:compile-load :compile-load-always :eval-load))
(when (member :load operations)
(push '(load :verbose t) ops))
(when (member :compile operations)
(push '(conditional-compile-file :verbose t :always t) ops)))
;; Combined operations
(cond ((member :compile-load-always operations)
(push '(conditional-compile-file :always t :load t :verbose t :save-local-symbols t
:save-doc-strings t :save-definitions t) ops))
((member :compile-load operations)
(push '(conditional-compile-file :load t :verbose t :save-local-symbols t
:save-doc-strings t :save-definitions t) ops))
((member :eval-load operations)
(push `(,#'eval-load :verbose t) ops)))
;; Perform operations
(loop for module in (symbol-value (find-system-named system))
do (etypecase module
(system ; support component systems
(unless (find-system-named module)
(load (get-system-definition-pathname module)))
(unless (system-loaded-p module) ; conservative on recursive operations on component systems
(execute-system-operations module operations)))
(cons
(processing-module
(module)
(:in-order-to-load
(perform-action action files t))
(:in-order-to-compile
(when (intersection operations '(:compile-load :compile :compile-load-always))
(perform-action action files t)))))
((or string pathname)
(loop for (fctn . args) in ops
do (apply fctn module args)))))
(set-system-loaded-p system)
system)))
(defvar *systems* nil)
(defvar *system-define-hook* nil)
(defvar *system-undefine-hook* nil)
(defun get-system-name (system)
(get system :system-name))
(defun get-system-keyword (system)
(get system :system-keyword))
(defun get-system-description (system)
(get system :system-description))
(defun set-system-loaded-p (system)
(let* ((sys (find-system-named system))
(key (get-system-keyword sys)))
(setf (get key :system-loaded-p) t)))
(defun system-loaded-p (system)
(let* ((sys (find-system-named system))
(key (get-system-keyword sys)))
(get key :system-loaded-p)))
(defun register-system (system name &optional description)
(prog1 (pushnew system *systems*)
(setf (get system :system-name) name
(get system :system-keyword) (intern (string-upcase name) :keyword))
(if description
(setf (get system :system-description) description)
(remprop system :system-description))
(mapc #'funcall *system-define-hook*)))
(defun unregister-system (system)
(setq *systems* (delete system *systems*))
(mapc #'funcall *system-undefine-hook*)
(remprop system :system-name)
(remprop system :system-keyword))
(defun find-system-named (string &optional (error-p t))
(cond ((cond ((stringp string) (find string *systems* :test #'equalp :key #'get-system-name))
((keywordp string) (find string *systems* :test #'eql :key #'get-system-keyword))
((symbolp string) (find string *systems* :test #'eql))
(t nil)))
(error-p (error "No system named ~A found." string))
(t nil)))
(defmacro define-system ((name &key description) (&rest operations) &body files)
"Operations can be :load and :compile."
(let ((var (intern (concatenate 'string "*" (string name) "*"))))
`(progn
(defparameter ,var ',files)
(register-system ',var ,(string-upcase name) ',description)
,(when operations
` (execute-system-operations ',var ',operations))
',var)))
(defun system-module-file (system-module)
(etypecase system-module
(cons (third system-module))
(string system-module)
(system nil)))
(defun system-files (system)
"Returns the files of SYSTEM in compile-load order."
(loop for module in (symbol-value (find-system-named system))
for file-spec = (system-module-file module)
when file-spec
collect file-spec))
(defun system-map-files (system function)
(loop for module in (symbol-value (find-system-named system))
for file = (system-module-file module)
do (funcall function file)))
(defun system-edit-files (system)
(system-map-files system #'ed))
(defun load-system (system)
(execute-system-operations system '(:compile-load)))
(defun compile-system (system &key (condition :new-version))
"Compiles SYSTEM.
CONDITION can be :NEW-VERSION to compile just changed files or
:ALWAYS to recompile the entire system."
(execute-system-operations system
(list (ecase condition
(:new-version :compile-load)
(:always :compile-load-always)
(:compile :compile)))))
(defparameter *standard-systems* nil)
(defun register-system-definition (keyword pathname)
(setf (get keyword :system-pathname) pathname))
(defun get-system-definition-pathname (keyword &optional (error-p t))
(cond ((get keyword :system-pathname))
(error-p (error "No system named, ~A, has been registered." keyword))
(t nil)))
(defmacro note-system-definitions (&body system-clauses)
`(progn . ,(loop for (keyword pathname) in system-clauses
collect `(register-system-definition (intern ,(string-upcase keyword) :keyword) (pathname ,pathname)))))
(defun load-standard-systems (&optional (systems *standard-systems*))
(loop for keyword in systems
do (load (get-system-definition-pathname keyword))
(load-system (find-system-named keyword))))
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/mcl/server/micro-defsystem.lisp | lisp | Base : 10 ; Mode : lisp ; Package : Micro - Defsystem ; -*-
All rights reserved.
-------------------------------------------------------------------
MICRO-DEFSYSTEM
check arguments to operations
Combined operations take precedence
Combined operations
Perform operations
support component systems
conservative on recursive operations on component systems | Copyright 1994 - 2001 , 2003 , .
(eval-when (:execute :compile-toplevel :load-toplevel)
(defpackage micro-defsystem
(:nicknames mds)
(:use #-Genera"COMMON-LISP" #+Genera"FUTURE-COMMON-LISP")
(:export "*STANDARD-SYSTEMS*"
"*SYSTEMS*"
"*SYSTEM-DEFINE-HOOK*"
"*SYSTEM-UNDEFINE-HOOK*"
"DEFINE-SYSTEM"
"EXECUTE-SYSTEM-OPERATIONS"
"FIND-SYSTEM-NAMED"
"GET-SYSTEM-NAME"
"LOAD-STANDARD-SYSTEMS"
"NOTE-SYSTEM-DEFINITIONS"
"SYSTEM-FILES"
"REGISTER-SYSTEM"
"UNREGISTER-SYSTEM"))
(do-external-symbols (sym :micro-defsystem)
(import sym :cl-user))
(import (intern "*ALWAYS-COMPILE*" :cl-user) :micro-defsystem))
(in-package :micro-defsystem)
(defparameter *always-compile* (if (boundp '*always-compile*) (symbol-value '*always-compile*) nil)
"When non-null all files are compiled, whether or not they need it.")
(defun system-p (system)
"Returns non-null if SYSTEM denotes a known system for define-system."
(and (symbolp system)
(or (get system :system-keyword)
(get system :system-pathname))))
(deftype system
()
`(and symbol (satisfies system-p)))
(defmethod require-pathname ((pathname pathname))
(ccl:require (pathname-name pathname) pathname))
(defun conditional-compile-file (file &key load verbose output-file always require
(save-local-symbols ccl:*fasl-save-local-symbols*)
(save-doc-strings ccl:*fasl-save-doc-strings*)
(save-definitions ccl:*fasl-save-definitions*))
(let* ((source (merge-pathnames ".lisp" file))
(fasl (merge-pathnames ccl::*.fasl-pathname* (or output-file file))))
(unless (probe-file source)
(error 'file-error :pathname file))
(cond ((or always
*always-compile*
(not (probe-file fasl))
(< (file-write-date fasl) (file-write-date source)))
(compile-file source :output-file fasl :load load :verbose verbose
:save-local-symbols save-local-symbols
:save-doc-strings save-doc-strings
:save-definitions save-definitions))
(require (require-pathname fasl))
(load (load fasl :verbose verbose))
(t nil))))
(defun execute-system-operations (system operations &aux ops)
(check-type system symbol)
(macrolet ((processing-module ((module) &body clauses)
`(destructuring-bind (case action &rest files) ,module
(ecase case ,@clauses))))
(flet ((check-operation-arg (arg)
(let ((known-operations '(:load :compile :eval-load :compile-load :compile-load-always)))
(unless (member arg known-operations)
(error "~S is not one of the know options for OPERATIONS."arg known-operations))))
(eval-load (pathname &rest args)
(apply #'load (merge-pathnames ".lisp" pathname) args))
(perform-action (action files &optional require-only)
(ecase action
(:load
(cond (require-only (mapc #'require-pathname files))
(t (dolist (file files)
(load file :verbose t)))))
(:compile-load
(dolist (file files)
(conditional-compile-file file :verbose t :load t :require t))))))
(mapc #'check-operation-arg operations)
(unless (intersection operations '(:compile-load :compile-load-always :eval-load))
(when (member :load operations)
(push '(load :verbose t) ops))
(when (member :compile operations)
(push '(conditional-compile-file :verbose t :always t) ops)))
(cond ((member :compile-load-always operations)
(push '(conditional-compile-file :always t :load t :verbose t :save-local-symbols t
:save-doc-strings t :save-definitions t) ops))
((member :compile-load operations)
(push '(conditional-compile-file :load t :verbose t :save-local-symbols t
:save-doc-strings t :save-definitions t) ops))
((member :eval-load operations)
(push `(,#'eval-load :verbose t) ops)))
(loop for module in (symbol-value (find-system-named system))
do (etypecase module
(unless (find-system-named module)
(load (get-system-definition-pathname module)))
(execute-system-operations module operations)))
(cons
(processing-module
(module)
(:in-order-to-load
(perform-action action files t))
(:in-order-to-compile
(when (intersection operations '(:compile-load :compile :compile-load-always))
(perform-action action files t)))))
((or string pathname)
(loop for (fctn . args) in ops
do (apply fctn module args)))))
(set-system-loaded-p system)
system)))
(defvar *systems* nil)
(defvar *system-define-hook* nil)
(defvar *system-undefine-hook* nil)
(defun get-system-name (system)
(get system :system-name))
(defun get-system-keyword (system)
(get system :system-keyword))
(defun get-system-description (system)
(get system :system-description))
(defun set-system-loaded-p (system)
(let* ((sys (find-system-named system))
(key (get-system-keyword sys)))
(setf (get key :system-loaded-p) t)))
(defun system-loaded-p (system)
(let* ((sys (find-system-named system))
(key (get-system-keyword sys)))
(get key :system-loaded-p)))
(defun register-system (system name &optional description)
(prog1 (pushnew system *systems*)
(setf (get system :system-name) name
(get system :system-keyword) (intern (string-upcase name) :keyword))
(if description
(setf (get system :system-description) description)
(remprop system :system-description))
(mapc #'funcall *system-define-hook*)))
(defun unregister-system (system)
(setq *systems* (delete system *systems*))
(mapc #'funcall *system-undefine-hook*)
(remprop system :system-name)
(remprop system :system-keyword))
(defun find-system-named (string &optional (error-p t))
(cond ((cond ((stringp string) (find string *systems* :test #'equalp :key #'get-system-name))
((keywordp string) (find string *systems* :test #'eql :key #'get-system-keyword))
((symbolp string) (find string *systems* :test #'eql))
(t nil)))
(error-p (error "No system named ~A found." string))
(t nil)))
(defmacro define-system ((name &key description) (&rest operations) &body files)
"Operations can be :load and :compile."
(let ((var (intern (concatenate 'string "*" (string name) "*"))))
`(progn
(defparameter ,var ',files)
(register-system ',var ,(string-upcase name) ',description)
,(when operations
` (execute-system-operations ',var ',operations))
',var)))
(defun system-module-file (system-module)
(etypecase system-module
(cons (third system-module))
(string system-module)
(system nil)))
(defun system-files (system)
"Returns the files of SYSTEM in compile-load order."
(loop for module in (symbol-value (find-system-named system))
for file-spec = (system-module-file module)
when file-spec
collect file-spec))
(defun system-map-files (system function)
(loop for module in (symbol-value (find-system-named system))
for file = (system-module-file module)
do (funcall function file)))
(defun system-edit-files (system)
(system-map-files system #'ed))
(defun load-system (system)
(execute-system-operations system '(:compile-load)))
(defun compile-system (system &key (condition :new-version))
"Compiles SYSTEM.
CONDITION can be :NEW-VERSION to compile just changed files or
:ALWAYS to recompile the entire system."
(execute-system-operations system
(list (ecase condition
(:new-version :compile-load)
(:always :compile-load-always)
(:compile :compile)))))
(defparameter *standard-systems* nil)
(defun register-system-definition (keyword pathname)
(setf (get keyword :system-pathname) pathname))
(defun get-system-definition-pathname (keyword &optional (error-p t))
(cond ((get keyword :system-pathname))
(error-p (error "No system named, ~A, has been registered." keyword))
(t nil)))
(defmacro note-system-definitions (&body system-clauses)
`(progn . ,(loop for (keyword pathname) in system-clauses
collect `(register-system-definition (intern ,(string-upcase keyword) :keyword) (pathname ,pathname)))))
(defun load-standard-systems (&optional (systems *standard-systems*))
(loop for keyword in systems
do (load (get-system-definition-pathname keyword))
(load-system (find-system-named keyword))))
|
a349becccd3f33ec0d81f358ad464653b0976322a98ce77b23081745579489d4 | tamarin-prover/tamarin-prover | Theory.hs | -- FIXME: for functions prove
-- |
Copyright : ( c ) 2010 - 2012
-- License : GPL v3 (see LICENSE)
--
Maintainer : < > , >
Portability : GHC only
--
-- Theory datatype and transformations on it.
module Theory (
-- * Restrictions
expandRestriction
-- * Processes
, ProcessDef(..)
, TranslationElement(..)
Datastructure added to Theory Items
, addProcess
, findProcess
, mapMProcesses
, mapMProcessesDef
, addProcessDef
, lookupProcessDef
, lookupFunctionTypingInfo
, pName
, pBody
, pVars
, addFunctionTypingInfo
, clearFunctionTypingInfos
-- * Options
, transAllowPatternMatchinginLookup
, transProgress
, transReliable
, transReport
, stateChannelOpt
, asynchronousChannels
, compressEvents
, forcedInjectiveFacts
, setforcedInjectiveFacts
, thyOptions
, setOption
, Option
-- * Predicates
, module Theory.Syntactic.Predicate
, addPredicate
-- * Export blocks
, ExportInfo(..)
, addExportInfo
, lookupExportInfo
, eTag
, eText
-- * Case Tests
, CaseTest(..)
, cName
, cFormula
, caseTestToPredicate
, defineCaseTests
-- * Lemmas
, LemmaAttribute(..)
, TraceQuantifier(..)
, CaseIdentifier
, Lemma
, SyntacticLemma
, ProtoLemma(..)
, AccLemma(..)
, lName
, DiffLemma
, lDiffName
, lDiffAttributes
, lDiffProof
, lTraceQuantifier
, lFormula
, lAttributes
, lProof
, aName
, aAttributes
, aCaseIdentifiers
, aCaseTests
, aFormula
, unprovenLemma
, skeletonLemma
, skeletonDiffLemma
, isLeftLemma
, isRightLemma
,
, addLeftLemma
, addRightLemma
, expandLemma
-- * Theories
, Theory(..)
, DiffTheory(..)
, TheoryItem(..)
, DiffTheoryItem(..)
, thyName
, thySignature
, thyTactic
, thyCache
, thyItems
, diffThyName
, diffThySignature
, diffThyCacheLeft
, diffThyCacheRight
, diffThyDiffCacheLeft
, diffThyDiffCacheRight
, diffThyItems
, diffTheoryLemmas
, diffTheorySideLemmas
, diffTheoryDiffRules
, diffTheoryDiffLemmas
, theoryRules
, theoryLemmas
, theoryCaseTests
, theoryRestrictions
, theoryProcesses
, theoryProcessDefs
, theoryFunctionTypingInfos
, theoryBuiltins
, theoryEquivLemmas
, theoryDiffEquivLemmas
, theoryPredicates
, theoryAccLemmas
, diffTheoryRestrictions
, diffTheorySideRestrictions
, addTactic
, addRestriction
, addLemma
, addAccLemma
, addCaseTest
, addRestrictionDiff
, addLemmaDiff
, addDiffLemma
, addHeuristic
, addDiffHeuristic
, addDiffTactic
, removeLemma
, removeLemmaDiff
, filterLemma
, removeDiffLemma
, lookupLemma
, lookupDiffLemma
, lookupAccLemma
, lookupCaseTest
, lookupLemmaDiff
, addComment
, addDiffComment
, addStringComment
, addFormalComment
, addFormalCommentDiff
, filterSide
, addDefaultDiffLemma
, addProtoRuleLabel
, addIntrRuleLabels
-- ** Open theories
, OpenTheory
, OpenTheoryItem
, OpenTranslatedTheory
, OpenDiffTheory
, removeTranslationItems
, EitherTheory
, EitherOpenTheory
, EitherClosedTheory
, defaultOpenTheory
, defaultOpenDiffTheory
, addProtoRule
, addProtoDiffRule
, addOpenProtoRule
, addOpenProtoDiffRule
, applyPartialEvaluation
, applyPartialEvaluationDiff
, addIntrRuleACsAfterTranslate
, addIntrRuleACs
, addIntrRuleACsDiffBoth
, addIntrRuleACsDiffBothDiff
, addIntrRuleACsDiffAll
, normalizeTheory
-- ** Closed theories
, ClosedTheory
, ClosedDiffTheory
, ClosedRuleCache(..) -- FIXME: this is only exported for the Binary instances
, closeTheory
, closeTheoryWithMaude
, closeDiffTheory
, closeDiffTheoryWithMaude
, openTheory
, openTranslatedTheory
, openDiffTheory
, ClosedProtoRule(..)
, OpenProtoRule(..)
, oprRuleE
, oprRuleAC
, cprRuleE
, cprRuleAC
, DiffProtoRule(..)
, dprRule
, dprLeftRight
, unfoldRuleVariants
, getLemmas
, getEitherLemmas
, getDiffLemmas
, getIntrVariants
, getIntrVariantsDiff
, getProtoRuleEs
, getProtoRuleEsDiff
, getProofContext
, getProofContextDiff
, getDiffProofContext
, getClassifiedRules
, getDiffClassifiedRules
, getInjectiveFactInsts
, getDiffInjectiveFactInsts
, getSource
, getDiffSource
-- ** Proving
, ProofSkeleton
, DiffProofSkeleton
, proveTheory
, proveDiffTheory
-- ** Lemma references
, lookupLemmaProof
, modifyLemmaProof
, lookupLemmaProofDiff
, modifyLemmaProofDiff
, lookupDiffLemmaProof
, modifyDiffLemmaProof
-- * Pretty printing
, prettyTheory
, prettyLemmaName
, prettyRestriction
, prettyLemma
, prettyDiffLemmaName
, prettyClosedTheory
, prettyClosedDiffTheory
, prettyOpenTheory
, prettyOpenTranslatedTheory
, prettyOpenDiffTheory
, prettyOpenProtoRule
, prettyDiffRule
, prettyClosedSummary
, prettyClosedDiffSummary
, prettyTraceQuantifier
, prettyProcess
, prettyProcessDef
-- * Convenience exports
, module Theory.Model
, module Theory.Proof
, module Pretty
) where
-- import Debug.Trace
import Prelude hiding (id, (.))
import GHC.Generics ( Generic )
-- import Data.Typeable
import Data . Binary
import Data . List
import Data . Maybe
import Data . Either
import Data . Monoid ( Sum ( .. ) )
--import qualified Data.Set as S
--import Control.Basics
--import Control.Category
import Control .
import Control . . Reader
import qualified Control . Monad . State as MS
--import Control.Parallel.Strategies
--import Extension.Data.Label hiding (get)
--import qualified Extension.Data.Label as L
--import qualified Data.Label.Point
--import qualified Data.Label.Poly
-- import qualified Data.Label.Total
import Safe ( headMay , atMay )
import Theory . Model
import Theory .
import Theory . . Print
import Theory . Proof
import Theory . Text . Pretty
import Theory . Tools . AbstractInterpretation
import Theory . Tools . InjectiveFactInstances
import Theory . Tools . LoopBreakers
import Theory . Tools . RuleVariants
import Theory . Tools . IntruderRules
import Term . Positions
import Utils . Misc
import Theory.Model
import Theory.Sapic
import Theory.Sapic.Print
import Theory.Proof
import Theory.Text.Pretty
import Theory.Tools.AbstractInterpretation
import Theory.Tools.InjectiveFactInstances
import Theory.Tools.LoopBreakers
import Theory.Tools.RuleVariants
import Theory.Tools.IntruderRules
import Term.Positions
import Utils.Misc-}
import ClosedTheory
import Items.ExportInfo
import OpenTheory
import Pretty
import Prover
import Theory.Model
import Theory.Proof
import Theory.Syntactic.Predicate
import TheoryObject
| null | https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/958f8b1767650c06dffe4eba63a38508c9b17a7f/lib/theory/src/Theory.hs | haskell | FIXME: for functions prove
|
License : GPL v3 (see LICENSE)
Theory datatype and transformations on it.
* Restrictions
* Processes
* Options
* Predicates
* Export blocks
* Case Tests
* Lemmas
* Theories
** Open theories
** Closed theories
FIXME: this is only exported for the Binary instances
** Proving
** Lemma references
* Pretty printing
* Convenience exports
import Debug.Trace
import Data.Typeable
import qualified Data.Set as S
import Control.Basics
import Control.Category
import Control.Parallel.Strategies
import Extension.Data.Label hiding (get)
import qualified Extension.Data.Label as L
import qualified Data.Label.Point
import qualified Data.Label.Poly
import qualified Data.Label.Total | Copyright : ( c ) 2010 - 2012
Maintainer : < > , >
Portability : GHC only
module Theory (
expandRestriction
, ProcessDef(..)
, TranslationElement(..)
Datastructure added to Theory Items
, addProcess
, findProcess
, mapMProcesses
, mapMProcessesDef
, addProcessDef
, lookupProcessDef
, lookupFunctionTypingInfo
, pName
, pBody
, pVars
, addFunctionTypingInfo
, clearFunctionTypingInfos
, transAllowPatternMatchinginLookup
, transProgress
, transReliable
, transReport
, stateChannelOpt
, asynchronousChannels
, compressEvents
, forcedInjectiveFacts
, setforcedInjectiveFacts
, thyOptions
, setOption
, Option
, module Theory.Syntactic.Predicate
, addPredicate
, ExportInfo(..)
, addExportInfo
, lookupExportInfo
, eTag
, eText
, CaseTest(..)
, cName
, cFormula
, caseTestToPredicate
, defineCaseTests
, LemmaAttribute(..)
, TraceQuantifier(..)
, CaseIdentifier
, Lemma
, SyntacticLemma
, ProtoLemma(..)
, AccLemma(..)
, lName
, DiffLemma
, lDiffName
, lDiffAttributes
, lDiffProof
, lTraceQuantifier
, lFormula
, lAttributes
, lProof
, aName
, aAttributes
, aCaseIdentifiers
, aCaseTests
, aFormula
, unprovenLemma
, skeletonLemma
, skeletonDiffLemma
, isLeftLemma
, isRightLemma
,
, addLeftLemma
, addRightLemma
, expandLemma
, Theory(..)
, DiffTheory(..)
, TheoryItem(..)
, DiffTheoryItem(..)
, thyName
, thySignature
, thyTactic
, thyCache
, thyItems
, diffThyName
, diffThySignature
, diffThyCacheLeft
, diffThyCacheRight
, diffThyDiffCacheLeft
, diffThyDiffCacheRight
, diffThyItems
, diffTheoryLemmas
, diffTheorySideLemmas
, diffTheoryDiffRules
, diffTheoryDiffLemmas
, theoryRules
, theoryLemmas
, theoryCaseTests
, theoryRestrictions
, theoryProcesses
, theoryProcessDefs
, theoryFunctionTypingInfos
, theoryBuiltins
, theoryEquivLemmas
, theoryDiffEquivLemmas
, theoryPredicates
, theoryAccLemmas
, diffTheoryRestrictions
, diffTheorySideRestrictions
, addTactic
, addRestriction
, addLemma
, addAccLemma
, addCaseTest
, addRestrictionDiff
, addLemmaDiff
, addDiffLemma
, addHeuristic
, addDiffHeuristic
, addDiffTactic
, removeLemma
, removeLemmaDiff
, filterLemma
, removeDiffLemma
, lookupLemma
, lookupDiffLemma
, lookupAccLemma
, lookupCaseTest
, lookupLemmaDiff
, addComment
, addDiffComment
, addStringComment
, addFormalComment
, addFormalCommentDiff
, filterSide
, addDefaultDiffLemma
, addProtoRuleLabel
, addIntrRuleLabels
, OpenTheory
, OpenTheoryItem
, OpenTranslatedTheory
, OpenDiffTheory
, removeTranslationItems
, EitherTheory
, EitherOpenTheory
, EitherClosedTheory
, defaultOpenTheory
, defaultOpenDiffTheory
, addProtoRule
, addProtoDiffRule
, addOpenProtoRule
, addOpenProtoDiffRule
, applyPartialEvaluation
, applyPartialEvaluationDiff
, addIntrRuleACsAfterTranslate
, addIntrRuleACs
, addIntrRuleACsDiffBoth
, addIntrRuleACsDiffBothDiff
, addIntrRuleACsDiffAll
, normalizeTheory
, ClosedTheory
, ClosedDiffTheory
, closeTheory
, closeTheoryWithMaude
, closeDiffTheory
, closeDiffTheoryWithMaude
, openTheory
, openTranslatedTheory
, openDiffTheory
, ClosedProtoRule(..)
, OpenProtoRule(..)
, oprRuleE
, oprRuleAC
, cprRuleE
, cprRuleAC
, DiffProtoRule(..)
, dprRule
, dprLeftRight
, unfoldRuleVariants
, getLemmas
, getEitherLemmas
, getDiffLemmas
, getIntrVariants
, getIntrVariantsDiff
, getProtoRuleEs
, getProtoRuleEsDiff
, getProofContext
, getProofContextDiff
, getDiffProofContext
, getClassifiedRules
, getDiffClassifiedRules
, getInjectiveFactInsts
, getDiffInjectiveFactInsts
, getSource
, getDiffSource
, ProofSkeleton
, DiffProofSkeleton
, proveTheory
, proveDiffTheory
, lookupLemmaProof
, modifyLemmaProof
, lookupLemmaProofDiff
, modifyLemmaProofDiff
, lookupDiffLemmaProof
, modifyDiffLemmaProof
, prettyTheory
, prettyLemmaName
, prettyRestriction
, prettyLemma
, prettyDiffLemmaName
, prettyClosedTheory
, prettyClosedDiffTheory
, prettyOpenTheory
, prettyOpenTranslatedTheory
, prettyOpenDiffTheory
, prettyOpenProtoRule
, prettyDiffRule
, prettyClosedSummary
, prettyClosedDiffSummary
, prettyTraceQuantifier
, prettyProcess
, prettyProcessDef
, module Theory.Model
, module Theory.Proof
, module Pretty
) where
import Prelude hiding (id, (.))
import GHC.Generics ( Generic )
import Data . Binary
import Data . List
import Data . Maybe
import Data . Either
import Data . Monoid ( Sum ( .. ) )
import Control .
import Control . . Reader
import qualified Control . Monad . State as MS
import Safe ( headMay , atMay )
import Theory . Model
import Theory .
import Theory . . Print
import Theory . Proof
import Theory . Text . Pretty
import Theory . Tools . AbstractInterpretation
import Theory . Tools . InjectiveFactInstances
import Theory . Tools . LoopBreakers
import Theory . Tools . RuleVariants
import Theory . Tools . IntruderRules
import Term . Positions
import Utils . Misc
import Theory.Model
import Theory.Sapic
import Theory.Sapic.Print
import Theory.Proof
import Theory.Text.Pretty
import Theory.Tools.AbstractInterpretation
import Theory.Tools.InjectiveFactInstances
import Theory.Tools.LoopBreakers
import Theory.Tools.RuleVariants
import Theory.Tools.IntruderRules
import Term.Positions
import Utils.Misc-}
import ClosedTheory
import Items.ExportInfo
import OpenTheory
import Pretty
import Prover
import Theory.Model
import Theory.Proof
import Theory.Syntactic.Predicate
import TheoryObject
|
7bc08598ffb4bb48666f9cd3b760b8aed73e312be4c73918599c6d0623a70a14 | tezos-checker/checker | liquidationAuctionPrimitiveTypes.ml | open Ptr
open Kit
open Tok
[@@@coverage off]
type avl_ptr = AVLPtr of ptr
[@@deriving show]
type leaf_ptr = LeafPtr of ptr
[@@deriving show]
type liquidation_slice_contents = {
burrow: Ligo.address * Ligo.nat;
tok: tok;
min_kit_for_unwarranted: kit option;
}
[@@deriving show]
type liquidation_slice = {
contents: liquidation_slice_contents;
older: leaf_ptr option;
younger: leaf_ptr option;
}
[@@deriving show]
type liquidation_auction_id = avl_ptr
[@@deriving show]
type bid = { address: Ligo.address; kit: kit }
[@@deriving show]
type auction_outcome = {
sold_tok: tok;
winning_bid: bid;
younger_auction: avl_ptr option;
older_auction: avl_ptr option;
}
[@@deriving show]
type leaf = {
value: liquidation_slice;
parent: ptr;
}
[@@deriving show]
TODO Instead of storing and , we could just
* store the sum type LeftHeavy | Balanced | RightHeavy . However , I think
* we might want to leave some trees unbalanced , and I think this approach
* might work better in that case .
* store the sum type LeftHeavy | Balanced | RightHeavy. However, I think
* we might want to leave some trees unbalanced, and I think this approach
* might work better in that case. *)
type branch = {
left: ptr;
left_height: Ligo.nat;
left_tok: tok;
right_tok: tok;
right_height: Ligo.nat;
right: ptr;
parent: ptr;
}
[@@deriving show]
type node =
| Leaf of leaf
| Branch of branch
| Root of (ptr option * auction_outcome option)
[@@deriving show]
type liquidation_auction_bid = { auction_id: liquidation_auction_id; bid: bid; }
[@@deriving show]
[@@@coverage on]
| null | https://raw.githubusercontent.com/tezos-checker/checker/fcca75dfa64950177c0427ad28c0c8d126803091/src/liquidationAuctionPrimitiveTypes.ml | ocaml | open Ptr
open Kit
open Tok
[@@@coverage off]
type avl_ptr = AVLPtr of ptr
[@@deriving show]
type leaf_ptr = LeafPtr of ptr
[@@deriving show]
type liquidation_slice_contents = {
burrow: Ligo.address * Ligo.nat;
tok: tok;
min_kit_for_unwarranted: kit option;
}
[@@deriving show]
type liquidation_slice = {
contents: liquidation_slice_contents;
older: leaf_ptr option;
younger: leaf_ptr option;
}
[@@deriving show]
type liquidation_auction_id = avl_ptr
[@@deriving show]
type bid = { address: Ligo.address; kit: kit }
[@@deriving show]
type auction_outcome = {
sold_tok: tok;
winning_bid: bid;
younger_auction: avl_ptr option;
older_auction: avl_ptr option;
}
[@@deriving show]
type leaf = {
value: liquidation_slice;
parent: ptr;
}
[@@deriving show]
TODO Instead of storing and , we could just
* store the sum type LeftHeavy | Balanced | RightHeavy . However , I think
* we might want to leave some trees unbalanced , and I think this approach
* might work better in that case .
* store the sum type LeftHeavy | Balanced | RightHeavy. However, I think
* we might want to leave some trees unbalanced, and I think this approach
* might work better in that case. *)
type branch = {
left: ptr;
left_height: Ligo.nat;
left_tok: tok;
right_tok: tok;
right_height: Ligo.nat;
right: ptr;
parent: ptr;
}
[@@deriving show]
type node =
| Leaf of leaf
| Branch of branch
| Root of (ptr option * auction_outcome option)
[@@deriving show]
type liquidation_auction_bid = { auction_id: liquidation_auction_id; bid: bid; }
[@@deriving show]
[@@@coverage on]
|
|
a4ce3bd9304b5e3f2e30b91ae63299abe3c9957036daef408a2481c89f86bbfe | tolysz/ghcjs-stack | JobControl.hs | -----------------------------------------------------------------------------
-- |
Module : Distribution . Client . JobControl
Copyright : ( c ) 2012
-- License : BSD-like
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- A job control concurrency abstraction
-----------------------------------------------------------------------------
module Distribution.Client.JobControl (
JobControl,
newSerialJobControl,
newParallelJobControl,
spawnJob,
collectJob,
JobLimit,
newJobLimit,
withJobLimit,
Lock,
newLock,
criticalSection
) where
import Control.Monad
import Control.Concurrent hiding (QSem, newQSem, waitQSem, signalQSem)
import Control.Exception (SomeException, bracket_, mask, throw, try)
import Distribution.Client.Compat.Semaphore
data JobControl m a = JobControl {
spawnJob :: m a -> m (),
collectJob :: m a
}
newSerialJobControl :: IO (JobControl IO a)
newSerialJobControl = do
queue <- newChan
return JobControl {
spawnJob = spawn queue,
collectJob = collect queue
}
where
spawn :: Chan (IO a) -> IO a -> IO ()
spawn = writeChan
collect :: Chan (IO a) -> IO a
collect = join . readChan
newParallelJobControl :: IO (JobControl IO a)
newParallelJobControl = do
resultVar <- newEmptyMVar
return JobControl {
spawnJob = spawn resultVar,
collectJob = collect resultVar
}
where
spawn :: MVar (Either SomeException a) -> IO a -> IO ()
spawn resultVar job =
mask $ \restore ->
forkIO (do res <- try (restore job)
putMVar resultVar res)
>> return ()
collect :: MVar (Either SomeException a) -> IO a
collect resultVar =
takeMVar resultVar >>= either throw return
data JobLimit = JobLimit QSem
newJobLimit :: Int -> IO JobLimit
newJobLimit n =
fmap JobLimit (newQSem n)
withJobLimit :: JobLimit -> IO a -> IO a
withJobLimit (JobLimit sem) =
bracket_ (waitQSem sem) (signalQSem sem)
newtype Lock = Lock (MVar ())
newLock :: IO Lock
newLock = fmap Lock $ newMVar ()
criticalSection :: Lock -> IO a -> IO a
criticalSection (Lock lck) act = bracket_ (takeMVar lck) (putMVar lck ()) act
| null | https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal/cabal-install/Distribution/Client/JobControl.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD-like
Maintainer :
Stability : provisional
Portability : portable
A job control concurrency abstraction
--------------------------------------------------------------------------- | Module : Distribution . Client . JobControl
Copyright : ( c ) 2012
module Distribution.Client.JobControl (
JobControl,
newSerialJobControl,
newParallelJobControl,
spawnJob,
collectJob,
JobLimit,
newJobLimit,
withJobLimit,
Lock,
newLock,
criticalSection
) where
import Control.Monad
import Control.Concurrent hiding (QSem, newQSem, waitQSem, signalQSem)
import Control.Exception (SomeException, bracket_, mask, throw, try)
import Distribution.Client.Compat.Semaphore
data JobControl m a = JobControl {
spawnJob :: m a -> m (),
collectJob :: m a
}
newSerialJobControl :: IO (JobControl IO a)
newSerialJobControl = do
queue <- newChan
return JobControl {
spawnJob = spawn queue,
collectJob = collect queue
}
where
spawn :: Chan (IO a) -> IO a -> IO ()
spawn = writeChan
collect :: Chan (IO a) -> IO a
collect = join . readChan
newParallelJobControl :: IO (JobControl IO a)
newParallelJobControl = do
resultVar <- newEmptyMVar
return JobControl {
spawnJob = spawn resultVar,
collectJob = collect resultVar
}
where
spawn :: MVar (Either SomeException a) -> IO a -> IO ()
spawn resultVar job =
mask $ \restore ->
forkIO (do res <- try (restore job)
putMVar resultVar res)
>> return ()
collect :: MVar (Either SomeException a) -> IO a
collect resultVar =
takeMVar resultVar >>= either throw return
data JobLimit = JobLimit QSem
newJobLimit :: Int -> IO JobLimit
newJobLimit n =
fmap JobLimit (newQSem n)
withJobLimit :: JobLimit -> IO a -> IO a
withJobLimit (JobLimit sem) =
bracket_ (waitQSem sem) (signalQSem sem)
newtype Lock = Lock (MVar ())
newLock :: IO Lock
newLock = fmap Lock $ newMVar ()
criticalSection :: Lock -> IO a -> IO a
criticalSection (Lock lck) act = bracket_ (takeMVar lck) (putMVar lck ()) act
|
764978e9e678b423d52bd6ce1b3a6b9646e218a0dad7ac5deea1a0fe2eec70b5 | quchen/generative-art | Geodesics.hs | module Geometry.Processes.Geodesics (geodesicEquation) where
import Geometry.Core
-- | A geodesic is a path that takes no local detours: each move to a new point is
done so that no other move would be faster . The shortest path between two points
-- is always a geodesic.
--
-- This function allows creating the geodesic differential equation, suitable for
-- using in ODE solvers such as
-- 'Numerics.DifferentialEquation.rungeKuttaAdaptiveStep'.
--
-- Using this is very simple, the equation behind it is simple depending on your
-- knowledge of differential geometry, and implementing it is a quite interesting
-- exercise in algorithmic optimization.
--
-- \[
-- \begin{align}
\ddot v^i & = \Gamma^i_{kl}\dot v^k\dot v^l \\
\Gamma^i_{kl } & = \frac12 g^{im } ( g_{mk , l}+g_{ml , k}-g_{kl , m } ) \\
-- g(f) &= \begin{pmatrix}1+\partial_{xx}f & \partial_xf\,\partial_yf \\ \partial_xf\,\partial_yf & 1+\partial_{yy}f\end{pmatrix}
-- \end{align}
-- \]
--
-- == Example: hill and valley
--
-- We can use the following variation of the
-- [Cauchy distribution]() to
build ourselves a hill with width parameter \(\gamma\ ) ,
--
-- \[
-- \text{Hill}_{\gamma}(\mathbf v_{\text{center}}, \mathbf v)
-- = \left(1+\left\| \frac{\mathbf v-\mathbf v_{\text{center}}}{\gamma}\right\|^2\right)^{-1}
-- \]
--
We can then pleace two of those , one at the top right with height 100 and one at
-- the bottom left with height -33.
--
-- This is what a family of trajectories passing through our terrain looks like:
--
-- @
-- (w,h) = … -- Canvas size
hill g v0 v = 1 \/ ( 1 + ( ' normSquare ' ( v-.v0 ) \/ g^2 ) )
geometry v = 100 * hill 55 ( ' Vec2 ' ( 2\/3*w ) ( 1\/3*h ) ) v - 33 * hill 55 ( ' Vec2 ' ( 1\/3*w ) ( 2\/3*h ) ) v
--
-- startAngle = 'deg' 45
solution = ' Numerics . DifferentialEquation.rungeKuttaAdaptiveStep ' ( ' geodesicEquation ' geometry ) ( ' zero ' , ' polar ' startAngle 1 ) t0 dt0 tolNorm tol )
-- where
t0 = 0
dt0 = 1
-- tolNorm (x,v) = 'max' ('norm' x) ('norm' v)
tol = 1e-3
-- @
--
-- <<docs/differential_equations/geodesic_hill_and_valley.svg>>
geodesicEquation
:: (Double -> Vec2 -> Double) -- ^ Surface function \(f(t, \mathbf v)\)
-> Double -- ^ Time \(t\)
^ \((\mathbf v , \dot{\mathbf v})\ )
^ \((\dot{\mathbf v } , \ddot{\mathbf v})\ )
geodesicEquation f t (v, v'@(Vec2 x' y')) =
( v'
, Vec2
(-c'x__V X X*x'^2 -2*c'x__V X Y*x'*y' -c'x__V Y Y*y'^2)
(-c'y__V X X*x'^2 -2*c'y__V X Y*x'*y' -c'y__V Y Y*y'^2)
)
where
h = 1e-3
Offsets for first derivatives at our current position
vXH = v +. Vec2 h 0
vYH = v +. Vec2 0 h
Offsets for second derivatives at our current position
vXHXH = vXH +. Vec2 h 0
vXHYH = vYH +. Vec2 h 0 -- = vYHXH – Vector addition commutativity saves us another call to f!
vYHYH = vYH +. Vec2 0 h
-- Function application sharing
ftv = f t v
ftvXH = f t vXH
ftvYH = f t vYH
ftvXHYH = f t vXHYH
First derivatives , applied to the offsets , for the second derivatives
fdxvXH = (f t vXHXH -. ftvXH) /. h
fdxvYH = (ftvXHYH -. ftvYH) /. h
fdyvXH = (ftvXHYH -. ftvXH) /. h
fdyvYH = (f t vYHYH -. ftvYH) /. h
First derivatives applied at our current position
fdxV = (ftvXH -. ftv) /. h
fdyV = (ftvYH -. ftv) /. h
-- Inverse metric g^{ab}
(g'x'x, g'x'y, g'y'x, g'y'y) =
let denominator = (1+fdxV^2+fdyV^2)
in ( (1+fdyV^2) /denominator
, -(fdxV*fdyV) /denominator
, g'x'y
, (1+fdxV^2) /denominator
)
-- Derivative of the metric g_{ab,c}
g__d_V X X X = g_x_xd_xV
g__d_V X X Y = g_x_xd_yV
g__d_V X Y X = g_x_yd_xV
g__d_V X Y Y = g_x_yd_yV
g__d_V Y X X = g_y_xd_xV
g__d_V Y X Y = g_y_xd_yV
g__d_V Y Y X = g_y_yd_xV
g__d_V Y Y Y = g_y_yd_yV
-- Derivative of the metric g_{ab,c} at our current position
g_x_xd_xV = ((1 + fdxvXH^2) -. (1 + fdxV^2)) /. h
g_x_xd_yV = ((1 + fdxvYH^2) -. (1 + fdxV^2)) /. h
g_x_yd_xV = ((fdxvXH * fdyvXH) -. (fdxV * fdyV)) /. h
g_x_yd_yV = ((fdxvYH * fdyvYH) -. (fdxV * fdyV)) /. h
g_y_xd_xV = ((fdxvXH * fdyvXH) -. (fdxV * fdyV)) /. h
g_y_xd_yV = ((fdxvYH * fdyvYH) -. (fdxV * fdyV)) /. h
g_y_yd_xV = ((1 + fdyvXH^2) -. (1 + fdyV^2)) /. h
g_y_yd_yV = ((1 + fdyvYH^2) -. (1 + fdyV^2)) /. h
Christoffel symbols , \Gamma^i_{kl } = \frac12 g^{im } ( g_{mk , l}+g_{ml , k}-g_{kl , m } )
c'x__V k l = 0.5 * (g'x'x * (g__d_V X k l + g__d_V X l k - g__d_V k l X) + g'x'y * (g__d_V Y k l + g__d_V Y l k - g__d_V k l Y))
c'y__V k l = 0.5 * (g'y'x * (g__d_V X k l + g__d_V X l k - g__d_V k l X) + g'y'y * (g__d_V Y k l + g__d_V Y l k - g__d_V k l Y))
data Dim = X | Y
| null | https://raw.githubusercontent.com/quchen/generative-art/1457b694b2ddf54f878db343d46c63d006573927/src/Geometry/Processes/Geodesics.hs | haskell | | A geodesic is a path that takes no local detours: each move to a new point is
is always a geodesic.
This function allows creating the geodesic differential equation, suitable for
using in ODE solvers such as
'Numerics.DifferentialEquation.rungeKuttaAdaptiveStep'.
Using this is very simple, the equation behind it is simple depending on your
knowledge of differential geometry, and implementing it is a quite interesting
exercise in algorithmic optimization.
\[
\begin{align}
g(f) &= \begin{pmatrix}1+\partial_{xx}f & \partial_xf\,\partial_yf \\ \partial_xf\,\partial_yf & 1+\partial_{yy}f\end{pmatrix}
\end{align}
\]
== Example: hill and valley
We can use the following variation of the
[Cauchy distribution]() to
\[
\text{Hill}_{\gamma}(\mathbf v_{\text{center}}, \mathbf v)
= \left(1+\left\| \frac{\mathbf v-\mathbf v_{\text{center}}}{\gamma}\right\|^2\right)^{-1}
\]
the bottom left with height -33.
This is what a family of trajectories passing through our terrain looks like:
@
(w,h) = … -- Canvas size
startAngle = 'deg' 45
where
tolNorm (x,v) = 'max' ('norm' x) ('norm' v)
@
<<docs/differential_equations/geodesic_hill_and_valley.svg>>
^ Surface function \(f(t, \mathbf v)\)
^ Time \(t\)
= vYHXH – Vector addition commutativity saves us another call to f!
Function application sharing
Inverse metric g^{ab}
Derivative of the metric g_{ab,c}
Derivative of the metric g_{ab,c} at our current position | module Geometry.Processes.Geodesics (geodesicEquation) where
import Geometry.Core
done so that no other move would be faster . The shortest path between two points
\ddot v^i & = \Gamma^i_{kl}\dot v^k\dot v^l \\
\Gamma^i_{kl } & = \frac12 g^{im } ( g_{mk , l}+g_{ml , k}-g_{kl , m } ) \\
build ourselves a hill with width parameter \(\gamma\ ) ,
We can then pleace two of those , one at the top right with height 100 and one at
hill g v0 v = 1 \/ ( 1 + ( ' normSquare ' ( v-.v0 ) \/ g^2 ) )
geometry v = 100 * hill 55 ( ' Vec2 ' ( 2\/3*w ) ( 1\/3*h ) ) v - 33 * hill 55 ( ' Vec2 ' ( 1\/3*w ) ( 2\/3*h ) ) v
solution = ' Numerics . DifferentialEquation.rungeKuttaAdaptiveStep ' ( ' geodesicEquation ' geometry ) ( ' zero ' , ' polar ' startAngle 1 ) t0 dt0 tolNorm tol )
t0 = 0
dt0 = 1
tol = 1e-3
geodesicEquation
^ \((\mathbf v , \dot{\mathbf v})\ )
^ \((\dot{\mathbf v } , \ddot{\mathbf v})\ )
geodesicEquation f t (v, v'@(Vec2 x' y')) =
( v'
, Vec2
(-c'x__V X X*x'^2 -2*c'x__V X Y*x'*y' -c'x__V Y Y*y'^2)
(-c'y__V X X*x'^2 -2*c'y__V X Y*x'*y' -c'y__V Y Y*y'^2)
)
where
h = 1e-3
Offsets for first derivatives at our current position
vXH = v +. Vec2 h 0
vYH = v +. Vec2 0 h
Offsets for second derivatives at our current position
vXHXH = vXH +. Vec2 h 0
vYHYH = vYH +. Vec2 0 h
ftv = f t v
ftvXH = f t vXH
ftvYH = f t vYH
ftvXHYH = f t vXHYH
First derivatives , applied to the offsets , for the second derivatives
fdxvXH = (f t vXHXH -. ftvXH) /. h
fdxvYH = (ftvXHYH -. ftvYH) /. h
fdyvXH = (ftvXHYH -. ftvXH) /. h
fdyvYH = (f t vYHYH -. ftvYH) /. h
First derivatives applied at our current position
fdxV = (ftvXH -. ftv) /. h
fdyV = (ftvYH -. ftv) /. h
(g'x'x, g'x'y, g'y'x, g'y'y) =
let denominator = (1+fdxV^2+fdyV^2)
in ( (1+fdyV^2) /denominator
, -(fdxV*fdyV) /denominator
, g'x'y
, (1+fdxV^2) /denominator
)
g__d_V X X X = g_x_xd_xV
g__d_V X X Y = g_x_xd_yV
g__d_V X Y X = g_x_yd_xV
g__d_V X Y Y = g_x_yd_yV
g__d_V Y X X = g_y_xd_xV
g__d_V Y X Y = g_y_xd_yV
g__d_V Y Y X = g_y_yd_xV
g__d_V Y Y Y = g_y_yd_yV
g_x_xd_xV = ((1 + fdxvXH^2) -. (1 + fdxV^2)) /. h
g_x_xd_yV = ((1 + fdxvYH^2) -. (1 + fdxV^2)) /. h
g_x_yd_xV = ((fdxvXH * fdyvXH) -. (fdxV * fdyV)) /. h
g_x_yd_yV = ((fdxvYH * fdyvYH) -. (fdxV * fdyV)) /. h
g_y_xd_xV = ((fdxvXH * fdyvXH) -. (fdxV * fdyV)) /. h
g_y_xd_yV = ((fdxvYH * fdyvYH) -. (fdxV * fdyV)) /. h
g_y_yd_xV = ((1 + fdyvXH^2) -. (1 + fdyV^2)) /. h
g_y_yd_yV = ((1 + fdyvYH^2) -. (1 + fdyV^2)) /. h
Christoffel symbols , \Gamma^i_{kl } = \frac12 g^{im } ( g_{mk , l}+g_{ml , k}-g_{kl , m } )
c'x__V k l = 0.5 * (g'x'x * (g__d_V X k l + g__d_V X l k - g__d_V k l X) + g'x'y * (g__d_V Y k l + g__d_V Y l k - g__d_V k l Y))
c'y__V k l = 0.5 * (g'y'x * (g__d_V X k l + g__d_V X l k - g__d_V k l X) + g'y'y * (g__d_V Y k l + g__d_V Y l k - g__d_V k l Y))
data Dim = X | Y
|
4e90fcb53402294de38b81fe33a5ff030d686911866f10f7637e3b4b784e6cb3 | facebook/duckling | Corpus.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.AmountOfMoney.EN.GB.Corpus
( allExamples
, negativeExamples
) where
import Data.String
import Data.Text (Text)
import Prelude
import Duckling.AmountOfMoney.Types
import Duckling.Testing.Types
allExamples :: [Example]
allExamples = concat
[ examples (simple GBP 1000)
[ "a grand"
, "1 grand"
]
, examples (simple GBP 10000)
[ "10 grand"
]
, examples (simple Dollar 1)
[ "four quarters"
, "ten dimes"
, "twenty nickels"
]
, examples (simple Dollar 0.1)
[ "dime"
, "a dime"
, "two nickels"
]
, examples (simple Dollar 0.25)
[ "quarter"
, "a quarter"
, "five nickels"
]
, examples (simple Dollar 0.05)
[ "nickel"
, "a nickel"
]
]
negativeExamples :: [Text]
negativeExamples =
[ "grand"
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/AmountOfMoney/EN/GB/Corpus.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.AmountOfMoney.EN.GB.Corpus
( allExamples
, negativeExamples
) where
import Data.String
import Data.Text (Text)
import Prelude
import Duckling.AmountOfMoney.Types
import Duckling.Testing.Types
allExamples :: [Example]
allExamples = concat
[ examples (simple GBP 1000)
[ "a grand"
, "1 grand"
]
, examples (simple GBP 10000)
[ "10 grand"
]
, examples (simple Dollar 1)
[ "four quarters"
, "ten dimes"
, "twenty nickels"
]
, examples (simple Dollar 0.1)
[ "dime"
, "a dime"
, "two nickels"
]
, examples (simple Dollar 0.25)
[ "quarter"
, "a quarter"
, "five nickels"
]
, examples (simple Dollar 0.05)
[ "nickel"
, "a nickel"
]
]
negativeExamples :: [Text]
negativeExamples =
[ "grand"
]
|
0f383df91d58f513f18ec908be02627f5e85a62b3a698ecf7e1e6338106ca8be | quchen/stgi | Number.hs | # LANGUAGE OverloadedLists #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
-- | Operations on boxed integers.
--
-- This module should be imported qualified to avoid clashes with standard
definitions .
module Stg.Prelude.Number (
-- * Arithmetic
add,
sub,
mul,
div,
mod,
-- * Comparisons
eq_Int,
lt_Int,
leq_Int,
gt_Int,
geq_Int,
neq_Int,
-- * Other
min,
max,
) where
import Prelude ()
import Data.Monoid ((<>))
import Data.Text (Text)
import Stg.Language
import Stg.Parser.QuasiQuoter
-- $setup
-- >>> :set -XOverloadedStrings
-- >>> :set -XQuasiQuotes
-- >>> :module +Stg.Language.Prettyprint
binaryOp :: Text -> PrimOp -> Alts -> Program
binaryOp name op primAlts =
Program (Binds
[(Var name, LambdaForm [] NoUpdate [Var "x", Var "y"]
(Case (AppF (Var "x") []) (Alts (AlgebraicAlts
[AlgebraicAlt (Constr "Int#") [Var "x'"]
(Case (AppF (Var "y") []) (Alts (AlgebraicAlts
[AlgebraicAlt (Constr "Int#") [Var "y'"]
(Case (AppP op (AtomVar (Var "x'")) (AtomVar (Var "y'")))
primAlts) ])
(DefaultBound (Var "err") (AppC (Constr ("Error_" <> name <> "_1")) [AtomVar (Var "err")])) ))])
(DefaultBound (Var "err") (AppC (Constr ("Error_" <> name <> "_2")) [AtomVar (Var "err")])) )))])
primToBool :: Alts
primToBool = [alts| 1# -> True; default -> False |]
eq_Int, lt_Int, leq_Int, gt_Int, geq_Int, neq_Int :: Program
-- | Equality of boxed integers
eq_Int = binaryOp "eq_Int" Eq primToBool
-- | Less-than for boxed integers
lt_Int = binaryOp "lt_Int" Lt primToBool
-- | Less-or-equal for boxed integers
leq_Int = binaryOp "leq_Int" Leq primToBool
-- | Greater-than for boxed integers
gt_Int = binaryOp "gt_Int" Gt primToBool
-- | Greater-or-equal for boxed integers
geq_Int = binaryOp "geq_Int" Geq primToBool
-- | Inequality of boxed integers
neq_Int = binaryOp "neq_Int" Neq primToBool
primIdInt :: Alts
primIdInt = [alts| v -> Int# v |]
add, sub, mul, div, mod :: Program
-- | Binary addition of boxed integers
add = binaryOp "add" Add primIdInt
-- | Difference of boxed integers
sub = binaryOp "sub" Sub primIdInt
-- | Binary multiplication of boxed integers
mul = binaryOp "mul" Mul primIdInt
-- | Boxed integer division
div = binaryOp "div" Div primIdInt
-- | Boxed integer modulo operator
mod = binaryOp "mod" Mod primIdInt
| Minimum of two boxed integers
min :: Program
min = [program|
min = \x y -> case x of
Int# x' -> case y of
Int# y' -> case <=# x' y' of
1# -> x;
default -> y;
badInt -> Error_min badInt;
badInt -> Error_min badInt
|]
| Maximum of two boxed integers
max :: Program
max = [program|
max = \x y -> case x of
Int# x' -> case y of
Int# y' -> case >=# x' y' of
1# -> x;
default -> y;
badInt -> Error_min badInt;
badInt -> Error_min badInt
|]
| null | https://raw.githubusercontent.com/quchen/stgi/dacd45cb0247f73889713dc92a911aaa835afd19/src/Stg/Prelude/Number.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes #
| Operations on boxed integers.
This module should be imported qualified to avoid clashes with standard
* Arithmetic
* Comparisons
* Other
$setup
>>> :set -XOverloadedStrings
>>> :set -XQuasiQuotes
>>> :module +Stg.Language.Prettyprint
| Equality of boxed integers
| Less-than for boxed integers
| Less-or-equal for boxed integers
| Greater-than for boxed integers
| Greater-or-equal for boxed integers
| Inequality of boxed integers
| Binary addition of boxed integers
| Difference of boxed integers
| Binary multiplication of boxed integers
| Boxed integer division
| Boxed integer modulo operator | # LANGUAGE OverloadedLists #
definitions .
module Stg.Prelude.Number (
add,
sub,
mul,
div,
mod,
eq_Int,
lt_Int,
leq_Int,
gt_Int,
geq_Int,
neq_Int,
min,
max,
) where
import Prelude ()
import Data.Monoid ((<>))
import Data.Text (Text)
import Stg.Language
import Stg.Parser.QuasiQuoter
binaryOp :: Text -> PrimOp -> Alts -> Program
binaryOp name op primAlts =
Program (Binds
[(Var name, LambdaForm [] NoUpdate [Var "x", Var "y"]
(Case (AppF (Var "x") []) (Alts (AlgebraicAlts
[AlgebraicAlt (Constr "Int#") [Var "x'"]
(Case (AppF (Var "y") []) (Alts (AlgebraicAlts
[AlgebraicAlt (Constr "Int#") [Var "y'"]
(Case (AppP op (AtomVar (Var "x'")) (AtomVar (Var "y'")))
primAlts) ])
(DefaultBound (Var "err") (AppC (Constr ("Error_" <> name <> "_1")) [AtomVar (Var "err")])) ))])
(DefaultBound (Var "err") (AppC (Constr ("Error_" <> name <> "_2")) [AtomVar (Var "err")])) )))])
primToBool :: Alts
primToBool = [alts| 1# -> True; default -> False |]
eq_Int, lt_Int, leq_Int, gt_Int, geq_Int, neq_Int :: Program
eq_Int = binaryOp "eq_Int" Eq primToBool
lt_Int = binaryOp "lt_Int" Lt primToBool
leq_Int = binaryOp "leq_Int" Leq primToBool
gt_Int = binaryOp "gt_Int" Gt primToBool
geq_Int = binaryOp "geq_Int" Geq primToBool
neq_Int = binaryOp "neq_Int" Neq primToBool
primIdInt :: Alts
primIdInt = [alts| v -> Int# v |]
add, sub, mul, div, mod :: Program
add = binaryOp "add" Add primIdInt
sub = binaryOp "sub" Sub primIdInt
mul = binaryOp "mul" Mul primIdInt
div = binaryOp "div" Div primIdInt
mod = binaryOp "mod" Mod primIdInt
| Minimum of two boxed integers
min :: Program
min = [program|
min = \x y -> case x of
Int# x' -> case y of
Int# y' -> case <=# x' y' of
1# -> x;
default -> y;
badInt -> Error_min badInt;
badInt -> Error_min badInt
|]
| Maximum of two boxed integers
max :: Program
max = [program|
max = \x y -> case x of
Int# x' -> case y of
Int# y' -> case >=# x' y' of
1# -> x;
default -> y;
badInt -> Error_min badInt;
badInt -> Error_min badInt
|]
|
9d145c8911bf6401cea4103dcb598f47972ba8aa7f91c6df94b6e05524213cfa | ocaml-sf/learn-ocaml-corpus | cons4.ml | (* Measuring the length of a sequence. *)
let rec length : 'a . 'a seq -> int =
fun xs ->
match xs with
| Nil -> 0
| Zero xs -> 2 * length xs
| One (_, xs) -> 1 + 2 * length xs
let rec cons : 'a . 'a -> 'a seq -> 'a seq =
fun x ys ->
match ys with
| Nil ->
One (x, Nil)
| Zero ys ->
One (x, ys)
| One (y, ys) ->
Zero (cons (x, y) ys)
(* very wrong *)
let cons x xs =
if length xs < 30 then
cons x xs
else
xs
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/random_access_lists/wrong/cons4.ml | ocaml | Measuring the length of a sequence.
very wrong |
let rec length : 'a . 'a seq -> int =
fun xs ->
match xs with
| Nil -> 0
| Zero xs -> 2 * length xs
| One (_, xs) -> 1 + 2 * length xs
let rec cons : 'a . 'a -> 'a seq -> 'a seq =
fun x ys ->
match ys with
| Nil ->
One (x, Nil)
| Zero ys ->
One (x, ys)
| One (y, ys) ->
Zero (cons (x, y) ys)
let cons x xs =
if length xs < 30 then
cons x xs
else
xs
|
1c40f191714b75f59c7264e54d765053b6b42fbc37243d6c2a718581a85b0fbd | awgn/cgrep | Char.hs | module CGrep.Parser.Char where
import Data.Char ( isAlpha, isAlphaNum, isHexDigit )
isCharNumber :: Char -> Bool
isCharNumber c = isHexDigit c || c `elem` (".xX" :: String)
isAlpha_ :: Char -> Bool
isAlpha_ c = isAlpha c || c == '_'
{-# INLINE isAlpha_ #-}
isAlphaNum_ :: Char -> Bool
isAlphaNum_ c = isAlphaNum c || c == '_'
# INLINE isAlphaNum _ #
isAlpha_' :: Char -> Bool
isAlpha_' c = isAlpha c || c == '_' || c == '\''
{-# INLINE isAlpha_' #-}
isAlphaNum_' :: Char -> Bool
isAlphaNum_' c = isAlphaNum c || c == '_' || c == '\''
# INLINE isAlphaNum _ ' #
isBracket' :: Char -> Bool
isBracket' c = c `elem` ("[]{}()" :: String)
{-# INLINE isBracket' #-}
isAlpha_and :: String -> Char -> Bool
isAlpha_and s c = isAlpha c || c == '_' || c `elem` s
# INLINE isAlpha_and #
isAlphaNum_and :: String -> Char -> Bool
isAlphaNum_and s c = isAlphaNum c || c == '_' || c `elem` s
# INLINE isAlphaNum_and #
| null | https://raw.githubusercontent.com/awgn/cgrep/304d7092cd4b961022abb06103c2bf7bb932ff4a/src/CGrep/Parser/Char.hs | haskell | # INLINE isAlpha_ #
# INLINE isAlpha_' #
# INLINE isBracket' # | module CGrep.Parser.Char where
import Data.Char ( isAlpha, isAlphaNum, isHexDigit )
isCharNumber :: Char -> Bool
isCharNumber c = isHexDigit c || c `elem` (".xX" :: String)
isAlpha_ :: Char -> Bool
isAlpha_ c = isAlpha c || c == '_'
isAlphaNum_ :: Char -> Bool
isAlphaNum_ c = isAlphaNum c || c == '_'
# INLINE isAlphaNum _ #
isAlpha_' :: Char -> Bool
isAlpha_' c = isAlpha c || c == '_' || c == '\''
isAlphaNum_' :: Char -> Bool
isAlphaNum_' c = isAlphaNum c || c == '_' || c == '\''
# INLINE isAlphaNum _ ' #
isBracket' :: Char -> Bool
isBracket' c = c `elem` ("[]{}()" :: String)
isAlpha_and :: String -> Char -> Bool
isAlpha_and s c = isAlpha c || c == '_' || c `elem` s
# INLINE isAlpha_and #
isAlphaNum_and :: String -> Char -> Bool
isAlphaNum_and s c = isAlphaNum c || c == '_' || c `elem` s
# INLINE isAlphaNum_and #
|
d4758e9df538fe0e2849846bc4f54e2575ecf1d3db65830a81cedc913e8aadfc | lopec/LoPEC | web_login.erl | -module (web_login).
-include_lib ("nitrogen/include/wf.inc").
-compile(export_all).
main() ->
common_web:main().
title() ->
common_web:title().
%% This is not currently used in our design
footer() ->
common_web:footer().
get_info() ->
common_web:get_info().
% Creates the menu.
menu() ->
#panel { id=menuitem, body=[
#link { text="Register", url="register" }
]}.
body() ->
Body = [
#panel { id=login, body=[
#label { text="Username: " },
#textbox { id=username, next=password },
#p {},
#label { text="Password: " },
#password { id=password, next=loginButton },
#panel { id=text, body=[
"If you have forgot your password [press here]"
] },
#p {},
#button { id=loginButton, text="Login", postback=continue }
]}
],
%% We hotwire some properties to our textboxes (Activated when button
%% is pressed)
wf:wire(loginButton, username, #validate { validators=[
#is_required{text="Required."}]}),
wf:wire(loginButton, password, #validate { validators=[
#is_required{text="Required."}]}),
wf:render(Body).
%% This event is fired up when the login-button is pressed
event(continue) ->
case db:validate_user(hd(wf:q(username)), hd(wf:q(password))) of
{ok, user_validated} ->
wf:user(hd(wf:q(username))),
wf:redirect_from_login("index");
_ ->
wf:flash(wf:f("Wrong username and/or password"))
end;
event(_) ->
ok.
| null | https://raw.githubusercontent.com/lopec/LoPEC/29a3989c48a60e5990615dea17bad9d24d770f7b/trunk/lib/master/src/pages/web_login.erl | erlang | This is not currently used in our design
Creates the menu.
We hotwire some properties to our textboxes (Activated when button
is pressed)
This event is fired up when the login-button is pressed | -module (web_login).
-include_lib ("nitrogen/include/wf.inc").
-compile(export_all).
main() ->
common_web:main().
title() ->
common_web:title().
footer() ->
common_web:footer().
get_info() ->
common_web:get_info().
menu() ->
#panel { id=menuitem, body=[
#link { text="Register", url="register" }
]}.
body() ->
Body = [
#panel { id=login, body=[
#label { text="Username: " },
#textbox { id=username, next=password },
#p {},
#label { text="Password: " },
#password { id=password, next=loginButton },
#panel { id=text, body=[
"If you have forgot your password [press here]"
] },
#p {},
#button { id=loginButton, text="Login", postback=continue }
]}
],
wf:wire(loginButton, username, #validate { validators=[
#is_required{text="Required."}]}),
wf:wire(loginButton, password, #validate { validators=[
#is_required{text="Required."}]}),
wf:render(Body).
event(continue) ->
case db:validate_user(hd(wf:q(username)), hd(wf:q(password))) of
{ok, user_validated} ->
wf:user(hd(wf:q(username))),
wf:redirect_from_login("index");
_ ->
wf:flash(wf:f("Wrong username and/or password"))
end;
event(_) ->
ok.
|
f89c27a32c7a9d7eb3110ef8d1fd068cf14c1c1a2748f6373ff6dc875023169b | digikar99/reader | swank.lisp | (cl:defpackage :reader+swank
(:use :cl :reader)
(:export
:enable-package-local-reader-syntax
:disable-package-local-reader-syntax))
(in-package :reader+swank)
(defmacro enable-package-local-reader-syntax (&rest reader-macro-identifiers)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (get-val swank:*readtable-alist* (package-name *package*) :test #'string=)
(progn
(setq *readtable* (copy-readtable))
(reader::%enable-reader-syntax *readtable* ,@reader-macro-identifiers)
*readtable*))))
(defmacro disable-package-local-reader-syntax ()
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf swank:*readtable-alist*
(remove (package-name *package*)
swank:*readtable-alist*
:key #'first
:test #'string=))))
(setf (documentation 'enable-package-local-reader-syntax 'function)
(concatenate 'string
reader::+reader-macro-doc+
(string #\newline)
"Package local refers to CL:*PACKAGE*."))
| null | https://raw.githubusercontent.com/digikar99/reader/825c06bad98abdd28ceb85e59c5ae28ba05ff3c3/swank.lisp | lisp | (cl:defpackage :reader+swank
(:use :cl :reader)
(:export
:enable-package-local-reader-syntax
:disable-package-local-reader-syntax))
(in-package :reader+swank)
(defmacro enable-package-local-reader-syntax (&rest reader-macro-identifiers)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (get-val swank:*readtable-alist* (package-name *package*) :test #'string=)
(progn
(setq *readtable* (copy-readtable))
(reader::%enable-reader-syntax *readtable* ,@reader-macro-identifiers)
*readtable*))))
(defmacro disable-package-local-reader-syntax ()
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf swank:*readtable-alist*
(remove (package-name *package*)
swank:*readtable-alist*
:key #'first
:test #'string=))))
(setf (documentation 'enable-package-local-reader-syntax 'function)
(concatenate 'string
reader::+reader-macro-doc+
(string #\newline)
"Package local refers to CL:*PACKAGE*."))
|
|
50ca87fa6bf43880af8744c10f24321848d046f30ea2e9d08a47f6090c21702b | haskell/cabal | Version.hs | -----------------------------------------------------------------------------
-- |
-- Module : Distribution.Version
Copyright : , 2003 - 2004
2008
-- License : BSD3
--
-- Maintainer :
-- Portability : portable
--
-- Exports the 'Version' type along with a parser and pretty printer. A version
is something like @\"1.3.3\"@. It also defines the ' VersionRange ' data
types . Version ranges are like @\">= 1.2 & & < 2\"@.
module Distribution.Version (
-- * Package versions
Version,
version0,
mkVersion,
mkVersion',
versionNumbers,
nullVersion,
alterVersion,
-- * Version ranges
VersionRange,
-- ** Constructing
anyVersion, noVersion,
thisVersion, notThisVersion,
laterVersion, earlierVersion,
orLaterVersion, orEarlierVersion,
unionVersionRanges, intersectVersionRanges,
withinVersion,
majorBoundVersion,
-- ** Inspection
withinRange,
isAnyVersion,
isNoVersion,
isSpecificVersion,
simplifyVersionRange,
foldVersionRange,
normaliseVersionRange,
stripParensVersionRange,
hasUpperBound,
hasLowerBound,
* * Cata & ana
VersionRangeF (..),
cataVersionRange,
anaVersionRange,
hyloVersionRange,
projectVersionRange,
embedVersionRange,
-- ** Utilities
wildcardUpperBound,
majorUpperBound,
-- ** Modification
removeUpperBound,
removeLowerBound,
transformCaret,
transformCaretUpper,
transformCaretLower,
-- * Version intervals view
asVersionIntervals,
VersionInterval(..),
LowerBound(..),
UpperBound(..),
Bound(..),
* * ' VersionIntervals ' abstract type
| The ' VersionIntervals ' type and the accompanying functions are exposed
-- primarily for completeness and testing purposes. In practice
-- 'asVersionIntervals' is the main function to use to
view a ' VersionRange ' as a bunch of ' VersionInterval 's .
--
VersionIntervals,
toVersionIntervals,
fromVersionIntervals,
unVersionIntervals,
) where
import Distribution.Types.Version
import Distribution.Types.VersionRange
import Distribution.Types.VersionInterval
-------------------------------------------------------------------------------
Utilities on VersionRange requiring VersionInterval
-------------------------------------------------------------------------------
-- | This is the converse of 'isAnyVersion'. It check if the version range is
-- empty, if there is no possible version that satisfies the version range.
--
For example this is ( for all @v@ ):
--
-- > isNoVersion (EarlierVersion v `IntersectVersionRanges` LaterVersion v)
--
isNoVersion :: VersionRange -> Bool
isNoVersion vr = case asVersionIntervals vr of
[] -> True
_ -> False
-- | Is this version range in fact just a specific version?
--
For example the version range @\">= 3 & & < = 3\"@ contains only the version
-- @3@.
--
isSpecificVersion :: VersionRange -> Maybe Version
isSpecificVersion vr = case asVersionIntervals vr of
[VersionInterval (LowerBound v InclusiveBound) (UpperBound v' InclusiveBound)]
| v == v' -> Just v
_ -> Nothing
-------------------------------------------------------------------------------
-- Transformations
-------------------------------------------------------------------------------
| Simplify a ' VersionRange ' expression . For non - empty version ranges
-- this produces a canonical form. Empty or inconsistent version ranges
-- are left as-is because that provides more information.
--
-- If you need a canonical form use
-- @fromVersionIntervals . toVersionIntervals@
--
-- It satisfies the following properties:
--
> withinRange v ( simplifyVersionRange r ) v r
--
> withinRange v r = withinRange v r '
-- > ==> simplifyVersionRange r = simplifyVersionRange r'
-- > || isNoVersion r
-- > || isNoVersion r'
--
simplifyVersionRange :: VersionRange -> VersionRange
simplifyVersionRange vr
-- If the version range is inconsistent then we just return the
original since that has more information than " > 1 & & < 1 " , which
-- is the canonical inconsistent version range.
| null (unVersionIntervals vi) = vr
| otherwise = fromVersionIntervals vi
where
vi = toVersionIntervals vr
| Given a version range , remove the highest upper bound . Example : @(>= 1 & & <
3 ) || ( > = 4 & & < 5)@ is converted to @(>= 1 & & < 3 ) || ( > = 4)@.
removeUpperBound :: VersionRange -> VersionRange
removeUpperBound = fromVersionIntervals . relaxLastInterval . toVersionIntervals
-- | Given a version range, remove the lowest lower bound.
Example : @(>= 1 & & < 3 ) || ( > = 4 & & < 5)@ is converted to
@(>= 0 & & < 3 ) || ( > = 4 & & < 5)@.
removeLowerBound :: VersionRange -> VersionRange
removeLowerBound = fromVersionIntervals . relaxHeadInterval . toVersionIntervals
| Rewrite @^>= x.y.z@ into @>= x.y.z & & < x.(y+1)@
--
@since 3.6.0.0
--
transformCaret :: VersionRange -> VersionRange
transformCaret = hyloVersionRange embed projectVersionRange where
embed (MajorBoundVersionF v) = orLaterVersion v `intersectVersionRanges` earlierVersion (majorUpperBound v)
embed vr = embedVersionRange vr
| Rewrite @^>= x.y.z@ into @>=
--
@since 3.6.0.0
--
transformCaretUpper :: VersionRange -> VersionRange
transformCaretUpper = hyloVersionRange embed projectVersionRange where
embed (MajorBoundVersionF v) = orLaterVersion v
embed vr = embedVersionRange vr
-- | Rewrite @^>= x.y.z@ into @<x.(y+1)@
--
@since 3.6.0.0
--
transformCaretLower :: VersionRange -> VersionRange
transformCaretLower = hyloVersionRange embed projectVersionRange where
embed (MajorBoundVersionF v) = earlierVersion (majorUpperBound v)
embed vr = embedVersionRange vr
| null | https://raw.githubusercontent.com/haskell/cabal/0abbe37187f708e0a5daac8d388167f72ca0db7e/Cabal-syntax/src/Distribution/Version.hs | haskell | ---------------------------------------------------------------------------
|
Module : Distribution.Version
License : BSD3
Maintainer :
Portability : portable
Exports the 'Version' type along with a parser and pretty printer. A version
* Package versions
* Version ranges
** Constructing
** Inspection
** Utilities
** Modification
* Version intervals view
primarily for completeness and testing purposes. In practice
'asVersionIntervals' is the main function to use to
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| This is the converse of 'isAnyVersion'. It check if the version range is
empty, if there is no possible version that satisfies the version range.
> isNoVersion (EarlierVersion v `IntersectVersionRanges` LaterVersion v)
| Is this version range in fact just a specific version?
@3@.
-----------------------------------------------------------------------------
Transformations
-----------------------------------------------------------------------------
this produces a canonical form. Empty or inconsistent version ranges
are left as-is because that provides more information.
If you need a canonical form use
@fromVersionIntervals . toVersionIntervals@
It satisfies the following properties:
> ==> simplifyVersionRange r = simplifyVersionRange r'
> || isNoVersion r
> || isNoVersion r'
If the version range is inconsistent then we just return the
is the canonical inconsistent version range.
| Given a version range, remove the lowest lower bound.
| Rewrite @^>= x.y.z@ into @<x.(y+1)@
| Copyright : , 2003 - 2004
2008
is something like @\"1.3.3\"@. It also defines the ' VersionRange ' data
types . Version ranges are like @\">= 1.2 & & < 2\"@.
module Distribution.Version (
Version,
version0,
mkVersion,
mkVersion',
versionNumbers,
nullVersion,
alterVersion,
VersionRange,
anyVersion, noVersion,
thisVersion, notThisVersion,
laterVersion, earlierVersion,
orLaterVersion, orEarlierVersion,
unionVersionRanges, intersectVersionRanges,
withinVersion,
majorBoundVersion,
withinRange,
isAnyVersion,
isNoVersion,
isSpecificVersion,
simplifyVersionRange,
foldVersionRange,
normaliseVersionRange,
stripParensVersionRange,
hasUpperBound,
hasLowerBound,
* * Cata & ana
VersionRangeF (..),
cataVersionRange,
anaVersionRange,
hyloVersionRange,
projectVersionRange,
embedVersionRange,
wildcardUpperBound,
majorUpperBound,
removeUpperBound,
removeLowerBound,
transformCaret,
transformCaretUpper,
transformCaretLower,
asVersionIntervals,
VersionInterval(..),
LowerBound(..),
UpperBound(..),
Bound(..),
* * ' VersionIntervals ' abstract type
| The ' VersionIntervals ' type and the accompanying functions are exposed
view a ' VersionRange ' as a bunch of ' VersionInterval 's .
VersionIntervals,
toVersionIntervals,
fromVersionIntervals,
unVersionIntervals,
) where
import Distribution.Types.Version
import Distribution.Types.VersionRange
import Distribution.Types.VersionInterval
Utilities on VersionRange requiring VersionInterval
For example this is ( for all @v@ ):
isNoVersion :: VersionRange -> Bool
isNoVersion vr = case asVersionIntervals vr of
[] -> True
_ -> False
For example the version range @\">= 3 & & < = 3\"@ contains only the version
isSpecificVersion :: VersionRange -> Maybe Version
isSpecificVersion vr = case asVersionIntervals vr of
[VersionInterval (LowerBound v InclusiveBound) (UpperBound v' InclusiveBound)]
| v == v' -> Just v
_ -> Nothing
| Simplify a ' VersionRange ' expression . For non - empty version ranges
> withinRange v ( simplifyVersionRange r ) v r
> withinRange v r = withinRange v r '
simplifyVersionRange :: VersionRange -> VersionRange
simplifyVersionRange vr
original since that has more information than " > 1 & & < 1 " , which
| null (unVersionIntervals vi) = vr
| otherwise = fromVersionIntervals vi
where
vi = toVersionIntervals vr
| Given a version range , remove the highest upper bound . Example : @(>= 1 & & <
3 ) || ( > = 4 & & < 5)@ is converted to @(>= 1 & & < 3 ) || ( > = 4)@.
removeUpperBound :: VersionRange -> VersionRange
removeUpperBound = fromVersionIntervals . relaxLastInterval . toVersionIntervals
Example : @(>= 1 & & < 3 ) || ( > = 4 & & < 5)@ is converted to
@(>= 0 & & < 3 ) || ( > = 4 & & < 5)@.
removeLowerBound :: VersionRange -> VersionRange
removeLowerBound = fromVersionIntervals . relaxHeadInterval . toVersionIntervals
| Rewrite @^>= x.y.z@ into @>= x.y.z & & < x.(y+1)@
@since 3.6.0.0
transformCaret :: VersionRange -> VersionRange
transformCaret = hyloVersionRange embed projectVersionRange where
embed (MajorBoundVersionF v) = orLaterVersion v `intersectVersionRanges` earlierVersion (majorUpperBound v)
embed vr = embedVersionRange vr
| Rewrite @^>= x.y.z@ into @>=
@since 3.6.0.0
transformCaretUpper :: VersionRange -> VersionRange
transformCaretUpper = hyloVersionRange embed projectVersionRange where
embed (MajorBoundVersionF v) = orLaterVersion v
embed vr = embedVersionRange vr
@since 3.6.0.0
transformCaretLower :: VersionRange -> VersionRange
transformCaretLower = hyloVersionRange embed projectVersionRange where
embed (MajorBoundVersionF v) = earlierVersion (majorUpperBound v)
embed vr = embedVersionRange vr
|
2809d6030878532f63c4b8a38e48b8f217484164d55e26775879a0536278d4b1 | robert-strandh/Second-Climacs | esa-buffer.lisp | (cl:in-package #:second-climacs-clim-base)
(stealth-mixin:define-stealth-mixin
buffer (esa-buffer:esa-buffer-mixin)
base:buffer
())
(defmethod base:insert-item :after (cursor item)
(setf (esa-buffer:needs-saving (base:buffer cursor)) t))
(defmethod base:delete-item :after (cursor)
(setf (esa-buffer:needs-saving (base:buffer cursor)) t))
(defmethod base:erase-item :after (cursor)
(setf (esa-buffer:needs-saving (base:buffer cursor)) t))
| null | https://raw.githubusercontent.com/robert-strandh/Second-Climacs/a992665575aae16888e54477ec5ddd251a9ecf1b/Code/GUI/McCLIM-ESA/Base/esa-buffer.lisp | lisp | (cl:in-package #:second-climacs-clim-base)
(stealth-mixin:define-stealth-mixin
buffer (esa-buffer:esa-buffer-mixin)
base:buffer
())
(defmethod base:insert-item :after (cursor item)
(setf (esa-buffer:needs-saving (base:buffer cursor)) t))
(defmethod base:delete-item :after (cursor)
(setf (esa-buffer:needs-saving (base:buffer cursor)) t))
(defmethod base:erase-item :after (cursor)
(setf (esa-buffer:needs-saving (base:buffer cursor)) t))
|
|
037d46f990e9cbfc3303b9cd7f5058263a9d7e5bb549fa612770a81b54e25282 | ertugrulcetin/jme-clj | hello_physics.clj | ;; Please start your REPL with `+test` profile
(ns examples.beginner-tutorials.hello-physics
"Clojure version of "
(:require [jme-clj.core :refer :all])
(:import
(com.jme3.input MouseInput)
(com.jme3.math Vector3f)
(com.jme3.scene.shape Sphere$TextureMode)
(com.jme3.texture Texture$WrapMode)))
(def brick-length 0.48)
(def brick-width 0.24)
(def brick-height 0.12)
;; for keeping internal *bindings* work, also the app. We need to define
;; listeners with `defn`. `def` should NOT be used!
(defn- on-action-listener []
(action-listener
(fn [name pressed? tpf]
(when (and (= name ::shoot) (not pressed?))
(let [{:keys [sphere stone-mat bullet-as]} (get-state)
ball-geo (-> (geo "cannon ball" sphere)
(setc :material stone-mat
:local-translation (get* (cam) :location))
(add-to-root))
ball-phy (rigid-body-control 1.0)]
(add-control ball-geo ball-phy)
(-> bullet-as
(get* :physics-space)
(call* :add ball-phy))
(set* ball-phy :linear-velocity (-> (cam)
(get* :direction)
(mult 25))))))))
(defn- set-up-keys []
(apply-input-mapping
;; Using qualified keywords for inputs is highly recommended!
{:triggers {::shoot (mouse-trigger MouseInput/BUTTON_LEFT)}
:listeners {(on-action-listener) ::shoot}}))
(defn- init-cross-hairs []
(let [gui-font (load-font "Interface/Fonts/Default.fnt")
settings (get* (context) :settings)
ch (bitmap-text gui-font false)]
(-> ch
(set* :size (-> gui-font
(get* :char-set)
(get* :rendered-size)
(* 2)))
(set* :text "+")
(set* :local-translation
(- (/ (get* settings :width) 2)
(/ (get* ch :line-width) 2))
(+ (/ (get* settings :height) 2)
(/ (get* ch :line-height) 2))
0)
(#(attach-child (gui-node) %)))))
(defn- init-materials []
(letj [wall-mat (material "Common/MatDefs/Misc/Unshaded.j3md")
stone-mat (material "Common/MatDefs/Misc/Unshaded.j3md")
floor-mat (material "Common/MatDefs/Misc/Unshaded.j3md")]
(set* wall-mat :texture "ColorMap" (load-texture "Textures/Terrain/BrickWall/BrickWall.jpg"))
(set* stone-mat :texture "ColorMap" (load-texture "Textures/Terrain/Rock/Rock.PNG"))
(set* floor-mat :texture "ColorMap" (-> (load-texture "Textures/Terrain/Pond/Pond.jpg")
(set* :wrap Texture$WrapMode/Repeat)))))
(defn- make-brick [loc box* wall-mat bullet-as]
(let [brick-geo (-> (geo "brick" box*)
(setc :material wall-mat
:local-translation loc)
(add-to-root))
brick-phy (rigid-body-control 2.0)]
(add-control brick-geo brick-phy)
(-> bullet-as
(get* :physics-space)
(call* :add brick-phy))))
(defn- init-floor [bullet-as floor floor-mat]
(let [floor-geo (-> (geo "Floor" floor)
(set* :material floor-mat)
(set* :local-translation 0 -0.1 0)
(add-to-root))
floor-phy (rigid-body-control 0.0)]
(add-control floor-geo floor-phy)
(-> bullet-as
(get* :physics-space)
(call* :add floor-phy))))
(defn- init-wall [bullet-as box* wall-mat]
(let [startpt (atom (float (/ brick-length 4)))
height (atom 0)]
(doseq [_ (range 15)]
(doseq [i (range 6)]
(make-brick (vec3 (+ @startpt (* i brick-length 2))
(+ brick-height @height)
0)
box*
wall-mat
bullet-as))
(swap! startpt -)
(swap! height + (* 2 brick-height)))))
(defn init []
(let [bullet-as (bullet-app-state)
;bullet-as (set* bullet-as :debug-enabled true)
sphere* (sphere 32 32 0.4 true false)
box* (box brick-length brick-height brick-width)
floor (box 10 0.1 5)]
(set* sphere* :texture-mode Sphere$TextureMode/Projected)
(scale-texture-coords box* (vec2 1 0.5))
(scale-texture-coords floor (vec2 3 6))
(attach bullet-as)
(setc (cam) :location (vec3 0 4 6))
(look-at (vec3 2 2 0) Vector3f/UNIT_Y)
(set-up-keys)
(let [{:keys [wall-mat stone-mat floor-mat]} (init-materials)]
(init-wall bullet-as box* wall-mat)
(init-floor bullet-as floor floor-mat)
(init-cross-hairs)
{:sphere sphere*
:stone-mat stone-mat
:bullet-as bullet-as})))
(defsimpleapp app :init init)
(comment
(start app)
after calling unbind - app , we need to re - define the app with defsimpleapp
(unbind-app #'app)
(run app
(re-init init))
)
| null | https://raw.githubusercontent.com/ertugrulcetin/jme-clj/167ef8f9e6396cc6e3c234290c5698c098fcad28/test/examples/beginner_tutorials/hello_physics.clj | clojure | Please start your REPL with `+test` profile
for keeping internal *bindings* work, also the app. We need to define
listeners with `defn`. `def` should NOT be used!
Using qualified keywords for inputs is highly recommended!
bullet-as (set* bullet-as :debug-enabled true) | (ns examples.beginner-tutorials.hello-physics
"Clojure version of "
(:require [jme-clj.core :refer :all])
(:import
(com.jme3.input MouseInput)
(com.jme3.math Vector3f)
(com.jme3.scene.shape Sphere$TextureMode)
(com.jme3.texture Texture$WrapMode)))
(def brick-length 0.48)
(def brick-width 0.24)
(def brick-height 0.12)
(defn- on-action-listener []
(action-listener
(fn [name pressed? tpf]
(when (and (= name ::shoot) (not pressed?))
(let [{:keys [sphere stone-mat bullet-as]} (get-state)
ball-geo (-> (geo "cannon ball" sphere)
(setc :material stone-mat
:local-translation (get* (cam) :location))
(add-to-root))
ball-phy (rigid-body-control 1.0)]
(add-control ball-geo ball-phy)
(-> bullet-as
(get* :physics-space)
(call* :add ball-phy))
(set* ball-phy :linear-velocity (-> (cam)
(get* :direction)
(mult 25))))))))
(defn- set-up-keys []
(apply-input-mapping
{:triggers {::shoot (mouse-trigger MouseInput/BUTTON_LEFT)}
:listeners {(on-action-listener) ::shoot}}))
(defn- init-cross-hairs []
(let [gui-font (load-font "Interface/Fonts/Default.fnt")
settings (get* (context) :settings)
ch (bitmap-text gui-font false)]
(-> ch
(set* :size (-> gui-font
(get* :char-set)
(get* :rendered-size)
(* 2)))
(set* :text "+")
(set* :local-translation
(- (/ (get* settings :width) 2)
(/ (get* ch :line-width) 2))
(+ (/ (get* settings :height) 2)
(/ (get* ch :line-height) 2))
0)
(#(attach-child (gui-node) %)))))
(defn- init-materials []
(letj [wall-mat (material "Common/MatDefs/Misc/Unshaded.j3md")
stone-mat (material "Common/MatDefs/Misc/Unshaded.j3md")
floor-mat (material "Common/MatDefs/Misc/Unshaded.j3md")]
(set* wall-mat :texture "ColorMap" (load-texture "Textures/Terrain/BrickWall/BrickWall.jpg"))
(set* stone-mat :texture "ColorMap" (load-texture "Textures/Terrain/Rock/Rock.PNG"))
(set* floor-mat :texture "ColorMap" (-> (load-texture "Textures/Terrain/Pond/Pond.jpg")
(set* :wrap Texture$WrapMode/Repeat)))))
(defn- make-brick [loc box* wall-mat bullet-as]
(let [brick-geo (-> (geo "brick" box*)
(setc :material wall-mat
:local-translation loc)
(add-to-root))
brick-phy (rigid-body-control 2.0)]
(add-control brick-geo brick-phy)
(-> bullet-as
(get* :physics-space)
(call* :add brick-phy))))
(defn- init-floor [bullet-as floor floor-mat]
(let [floor-geo (-> (geo "Floor" floor)
(set* :material floor-mat)
(set* :local-translation 0 -0.1 0)
(add-to-root))
floor-phy (rigid-body-control 0.0)]
(add-control floor-geo floor-phy)
(-> bullet-as
(get* :physics-space)
(call* :add floor-phy))))
(defn- init-wall [bullet-as box* wall-mat]
(let [startpt (atom (float (/ brick-length 4)))
height (atom 0)]
(doseq [_ (range 15)]
(doseq [i (range 6)]
(make-brick (vec3 (+ @startpt (* i brick-length 2))
(+ brick-height @height)
0)
box*
wall-mat
bullet-as))
(swap! startpt -)
(swap! height + (* 2 brick-height)))))
(defn init []
(let [bullet-as (bullet-app-state)
sphere* (sphere 32 32 0.4 true false)
box* (box brick-length brick-height brick-width)
floor (box 10 0.1 5)]
(set* sphere* :texture-mode Sphere$TextureMode/Projected)
(scale-texture-coords box* (vec2 1 0.5))
(scale-texture-coords floor (vec2 3 6))
(attach bullet-as)
(setc (cam) :location (vec3 0 4 6))
(look-at (vec3 2 2 0) Vector3f/UNIT_Y)
(set-up-keys)
(let [{:keys [wall-mat stone-mat floor-mat]} (init-materials)]
(init-wall bullet-as box* wall-mat)
(init-floor bullet-as floor floor-mat)
(init-cross-hairs)
{:sphere sphere*
:stone-mat stone-mat
:bullet-as bullet-as})))
(defsimpleapp app :init init)
(comment
(start app)
after calling unbind - app , we need to re - define the app with defsimpleapp
(unbind-app #'app)
(run app
(re-init init))
)
|
68dfb502dc81ed883c116385e6c8ab8e8ca04d47c0de074862c5bdf740fc9370 | hstreamdb/hstream | Time.hs | module HStream.Utils.Time
( Interval (..)
, parserInterval
, interval2ms
, diffTimeSince
, usecSince
, msecSince
, secSince
-- * Re-export
, getPOSIXTime
) where
import Control.Applicative ((<|>))
import Data.Attoparsec.Text (Parser, choice, endOfInput, parseOnly,
rational, string)
import Data.Int (Int64)
import qualified Data.Text as T
import Data.Time.Clock (NominalDiffTime)
import Data.Time.Clock.POSIX (getPOSIXTime)
data Interval
= Milliseconds Double
| Seconds Double
| Minutes Double
| Hours Double
deriving (Eq)
instance Show Interval where
show (Seconds x) = showInInt x <> " seconds"
show (Minutes x) = showInInt x <> " minutes"
show (Hours x) = showInInt x <> " hours"
show (Milliseconds x) = showInInt x <> " milliseconds"
showInInt :: Double -> String
showInInt x | fromIntegral x' == x = show x'
| otherwise = show x
where
x' = floor x :: Int
interval2ms :: Interval -> Int
interval2ms (Milliseconds x) = round x
interval2ms (Seconds x) = round (x * 1000)
interval2ms (Minutes x) = round (x * 1000 * 60)
interval2ms (Hours x) = round (x * 1000 * 60 * 60)
intervalParser :: Parser Interval
intervalParser = do
x <- rational
f <- intervalConstructorParser
endOfInput
return (f x)
intervalConstructorParser :: Parser (Double -> Interval)
intervalConstructorParser =
Milliseconds <$ choice (string <$> ["ms","milliseconds","millisecond"])
<|> Seconds <$ choice (string <$> ["seconds", "s", "second"])
<|> Minutes <$ choice (string <$> ["minutes", "min", "minute"])
<|> Hours <$ choice (string <$> ["hours", "h", "hr", "hrs", "hour"])
parserInterval :: String -> Either String Interval
parserInterval = parseOnly intervalParser . T.pack
diffTimeSince :: NominalDiffTime -> IO NominalDiffTime
diffTimeSince start = do
now <- getPOSIXTime
return $ now - start
# INLINE diffTimeSince #
usecSince :: NominalDiffTime -> IO Int64
usecSince start = floor . (* 1e6) <$> diffTimeSince start
# INLINE usecSince #
msecSince :: NominalDiffTime -> IO Int64
msecSince start = floor . (* 1e3) <$> diffTimeSince start
# INLINE msecSince #
secSince :: NominalDiffTime -> IO Int64
secSince start = floor <$> diffTimeSince start
# INLINE secSince #
| null | https://raw.githubusercontent.com/hstreamdb/hstream/125d9982d47874aee5e33324b55689d64bd664c2/common/hstream/HStream/Utils/Time.hs | haskell | * Re-export | module HStream.Utils.Time
( Interval (..)
, parserInterval
, interval2ms
, diffTimeSince
, usecSince
, msecSince
, secSince
, getPOSIXTime
) where
import Control.Applicative ((<|>))
import Data.Attoparsec.Text (Parser, choice, endOfInput, parseOnly,
rational, string)
import Data.Int (Int64)
import qualified Data.Text as T
import Data.Time.Clock (NominalDiffTime)
import Data.Time.Clock.POSIX (getPOSIXTime)
data Interval
= Milliseconds Double
| Seconds Double
| Minutes Double
| Hours Double
deriving (Eq)
instance Show Interval where
show (Seconds x) = showInInt x <> " seconds"
show (Minutes x) = showInInt x <> " minutes"
show (Hours x) = showInInt x <> " hours"
show (Milliseconds x) = showInInt x <> " milliseconds"
showInInt :: Double -> String
showInInt x | fromIntegral x' == x = show x'
| otherwise = show x
where
x' = floor x :: Int
interval2ms :: Interval -> Int
interval2ms (Milliseconds x) = round x
interval2ms (Seconds x) = round (x * 1000)
interval2ms (Minutes x) = round (x * 1000 * 60)
interval2ms (Hours x) = round (x * 1000 * 60 * 60)
intervalParser :: Parser Interval
intervalParser = do
x <- rational
f <- intervalConstructorParser
endOfInput
return (f x)
intervalConstructorParser :: Parser (Double -> Interval)
intervalConstructorParser =
Milliseconds <$ choice (string <$> ["ms","milliseconds","millisecond"])
<|> Seconds <$ choice (string <$> ["seconds", "s", "second"])
<|> Minutes <$ choice (string <$> ["minutes", "min", "minute"])
<|> Hours <$ choice (string <$> ["hours", "h", "hr", "hrs", "hour"])
parserInterval :: String -> Either String Interval
parserInterval = parseOnly intervalParser . T.pack
diffTimeSince :: NominalDiffTime -> IO NominalDiffTime
diffTimeSince start = do
now <- getPOSIXTime
return $ now - start
# INLINE diffTimeSince #
usecSince :: NominalDiffTime -> IO Int64
usecSince start = floor . (* 1e6) <$> diffTimeSince start
# INLINE usecSince #
msecSince :: NominalDiffTime -> IO Int64
msecSince start = floor . (* 1e3) <$> diffTimeSince start
# INLINE msecSince #
secSince :: NominalDiffTime -> IO Int64
secSince start = floor <$> diffTimeSince start
# INLINE secSince #
|
d76e2d80174a43feb4e0a7068ead2fe37a08377d2ba11dd1c2ae075ec8a2c6e6 | gonimo/gonimo | Impl.hs | # LANGUAGE TupleSections #
# LANGUAGE RecordWildCards #
|
Module : . Client . Router . Impl
Description : Routing for .
Copyright : ( c ) , 2018
Picks Impl . Native or Impl . Browser based on ` needsNativeHistory ` of the Host .
Module : Gonimo.Client.Router.Impl
Description : Routing for Gonimo.
Copyright : (c) Robert Klotzner, 2018
Picks Impl.Native or Impl.Browser based on `needsNativeHistory` of the Host.
-}
module Gonimo.Client.Router.Impl ( module Gonimo.Client.Router
-- * Types
, Model
, HasModel
, ModelConfig
, HasModelConfig
-- * Creation
, make
) where
import Reflex.Dom.Core
import Gonimo.Client.Host (Host)
import qualified Gonimo.Client.Host as Host
import Gonimo.Client.Prelude
import Gonimo.Client.Router
import qualified Gonimo.Client.Router.Impl.Browser as Browser
import qualified Gonimo.Client.Router.Impl.Native as Native
| Simple data type fulfilling our ' HasModel ' constraint .
type Model t = Host t
-- | Our dependencies
type HasModel model = Host.HasHost model
type ModelConfig t = Native.ModelConfig t
type HasModelConfig c t = Native.HasModelConfig c t
make :: forall t m model c mConf
. (MonadWidget t m , HasModel model, HasConfig c, HasModelConfig mConf t)
=> model t -> c t -> m (mConf t, Router t)
make model conf
= if model ^. Host.needsNativeHistory
then Native.make conf
else (mempty,) <$> Browser.make conf
| null | https://raw.githubusercontent.com/gonimo/gonimo/f4072db9e56f0c853a9f07e048e254eaa671283b/front/src/Gonimo/Client/Router/Impl.hs | haskell | * Types
* Creation
| Our dependencies | # LANGUAGE TupleSections #
# LANGUAGE RecordWildCards #
|
Module : . Client . Router . Impl
Description : Routing for .
Copyright : ( c ) , 2018
Picks Impl . Native or Impl . Browser based on ` needsNativeHistory ` of the Host .
Module : Gonimo.Client.Router.Impl
Description : Routing for Gonimo.
Copyright : (c) Robert Klotzner, 2018
Picks Impl.Native or Impl.Browser based on `needsNativeHistory` of the Host.
-}
module Gonimo.Client.Router.Impl ( module Gonimo.Client.Router
, Model
, HasModel
, ModelConfig
, HasModelConfig
, make
) where
import Reflex.Dom.Core
import Gonimo.Client.Host (Host)
import qualified Gonimo.Client.Host as Host
import Gonimo.Client.Prelude
import Gonimo.Client.Router
import qualified Gonimo.Client.Router.Impl.Browser as Browser
import qualified Gonimo.Client.Router.Impl.Native as Native
| Simple data type fulfilling our ' HasModel ' constraint .
type Model t = Host t
type HasModel model = Host.HasHost model
type ModelConfig t = Native.ModelConfig t
type HasModelConfig c t = Native.HasModelConfig c t
make :: forall t m model c mConf
. (MonadWidget t m , HasModel model, HasConfig c, HasModelConfig mConf t)
=> model t -> c t -> m (mConf t, Router t)
make model conf
= if model ^. Host.needsNativeHistory
then Native.make conf
else (mempty,) <$> Browser.make conf
|
7186efc73d5202ca56c02d0a6cdef5ff1652d2532b7506c0ffec15562672e5f9 | Clojure2D/clojure2d-examples | hittable.clj | (ns rt4.the-rest-of-your-life.ch06c.hittable
(:require [fastmath.core :as m]
[fastmath.vector :as v]
[rt4.the-rest-of-your-life.ch06c.aabb :as aabb]
[rt4.the-rest-of-your-life.ch06c.ray :as ray])
(:import [fastmath.vector Vec3]
[rt4.the_rest_of_your_life.ch06c.ray Ray]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol HittableProto
(hit [object r ray-t]))
(defrecord HitData [p normal mat ^double t u v front-face?])
(defn hit-data
([r {:keys [p normal mat t u v]
:or {u 0.0 v 0.0}}]
(hit-data r p normal mat t u v))
([r p normal mat t]
(hit-data r p normal mat t 0.0 0.0))
([r p normal mat t u v]
(let [front-face? (neg? (v/dot (.direction ^Ray r) normal))]
(->HitData p (if front-face? normal (v/sub normal)) mat t u v front-face?))))
;;
(defrecord Translate [object offset bbox]
HittableProto
(hit [_ r ray-t]
(let [offset-r (ray/ray (v/sub (.origin ^Ray r) offset) (.direction ^Ray r) (.time ^Ray r))]
(when-let [^HitData rec (hit object offset-r ray-t)]
(->HitData (v/add offset (.p rec)) (.normal rec) (.mat rec)
(.t rec) (.u rec) (.v rec) (.front-face? rec))))))
(defn translate [p displacement]
(->Translate p displacement (aabb/shift (:bbox p) displacement)))
;;
(defmacro ^:private rot+
[x1 x2]
`(+ (* ~'sin-theta ~x1) (* ~'cos-theta ~x2)))
(defmacro ^:private rot-
[x1 x2]
`(- (* ~'cos-theta ~x1) (* ~'sin-theta ~x2)))
(defrecord RotateY [object ^double sin-theta ^double cos-theta bbox]
HittableProto
(hit [_ r ray-t]
(let [^Vec3 origin (.origin ^Ray r)
^Vec3 direction (.direction ^Ray r)
origin (v/vec3 (rot- (.x origin) (.z origin))
(.y origin)
(rot+ (.x origin) (.z origin)))
direction (v/vec3 (rot- (.x direction) (.z direction))
(.y direction)
(rot+ (.x direction) (.z direction)))
rotated-r (ray/ray origin direction (.time ^Ray r))]
(when-let [^HitData rec (hit object rotated-r ray-t)]
(let [^Vec3 p (.p rec)
p (v/vec3 (rot+ (.z p) (.x p)) (.y p) (rot- (.z p) (.x p)))
^Vec3 normal (.normal ^HitData rec)
normal (v/vec3 (rot+ (.z normal) (.x normal))
(.y normal)
(rot- (.z normal) (.x normal)))]
(->HitData p normal (.mat rec) (.t rec) (.u rec) (.v rec) (.front-face? rec)))))))
(defn rotate-y [p ^double angle]
(let [radians (m/radians angle)
sin-theta (m/sin radians)
cos-theta (m/cos radians)
bbox (:bbox p)
new-corners (for [^double x [(:mn (:x bbox)) (:mx (:x bbox))]
^double y [(:mn (:y bbox)) (:mx (:y bbox))]
^double z [(:mn (:z bbox)) (:mx (:z bbox))]
:let [newx (rot+ z x)
newz (rot- z x)]]
(v/vec3 newx y newz))
[mn mx] (reduce (fn [[mn mx] tester]
[(v/emn mn tester)
(v/emx mx tester)]) [(v/vec3 ##Inf ##Inf ##Inf)
(v/vec3 ##-Inf ##-Inf ##-Inf)] new-corners)]
(->RotateY p sin-theta cos-theta (aabb/aabb mn mx))))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/f47e1655902cc6bf1590aaecc144ac274ed3af66/src/rt4/the_rest_of_your_life/ch06c/hittable.clj | clojure | (ns rt4.the-rest-of-your-life.ch06c.hittable
(:require [fastmath.core :as m]
[fastmath.vector :as v]
[rt4.the-rest-of-your-life.ch06c.aabb :as aabb]
[rt4.the-rest-of-your-life.ch06c.ray :as ray])
(:import [fastmath.vector Vec3]
[rt4.the_rest_of_your_life.ch06c.ray Ray]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol HittableProto
(hit [object r ray-t]))
(defrecord HitData [p normal mat ^double t u v front-face?])
(defn hit-data
([r {:keys [p normal mat t u v]
:or {u 0.0 v 0.0}}]
(hit-data r p normal mat t u v))
([r p normal mat t]
(hit-data r p normal mat t 0.0 0.0))
([r p normal mat t u v]
(let [front-face? (neg? (v/dot (.direction ^Ray r) normal))]
(->HitData p (if front-face? normal (v/sub normal)) mat t u v front-face?))))
(defrecord Translate [object offset bbox]
HittableProto
(hit [_ r ray-t]
(let [offset-r (ray/ray (v/sub (.origin ^Ray r) offset) (.direction ^Ray r) (.time ^Ray r))]
(when-let [^HitData rec (hit object offset-r ray-t)]
(->HitData (v/add offset (.p rec)) (.normal rec) (.mat rec)
(.t rec) (.u rec) (.v rec) (.front-face? rec))))))
(defn translate [p displacement]
(->Translate p displacement (aabb/shift (:bbox p) displacement)))
(defmacro ^:private rot+
[x1 x2]
`(+ (* ~'sin-theta ~x1) (* ~'cos-theta ~x2)))
(defmacro ^:private rot-
[x1 x2]
`(- (* ~'cos-theta ~x1) (* ~'sin-theta ~x2)))
(defrecord RotateY [object ^double sin-theta ^double cos-theta bbox]
HittableProto
(hit [_ r ray-t]
(let [^Vec3 origin (.origin ^Ray r)
^Vec3 direction (.direction ^Ray r)
origin (v/vec3 (rot- (.x origin) (.z origin))
(.y origin)
(rot+ (.x origin) (.z origin)))
direction (v/vec3 (rot- (.x direction) (.z direction))
(.y direction)
(rot+ (.x direction) (.z direction)))
rotated-r (ray/ray origin direction (.time ^Ray r))]
(when-let [^HitData rec (hit object rotated-r ray-t)]
(let [^Vec3 p (.p rec)
p (v/vec3 (rot+ (.z p) (.x p)) (.y p) (rot- (.z p) (.x p)))
^Vec3 normal (.normal ^HitData rec)
normal (v/vec3 (rot+ (.z normal) (.x normal))
(.y normal)
(rot- (.z normal) (.x normal)))]
(->HitData p normal (.mat rec) (.t rec) (.u rec) (.v rec) (.front-face? rec)))))))
(defn rotate-y [p ^double angle]
(let [radians (m/radians angle)
sin-theta (m/sin radians)
cos-theta (m/cos radians)
bbox (:bbox p)
new-corners (for [^double x [(:mn (:x bbox)) (:mx (:x bbox))]
^double y [(:mn (:y bbox)) (:mx (:y bbox))]
^double z [(:mn (:z bbox)) (:mx (:z bbox))]
:let [newx (rot+ z x)
newz (rot- z x)]]
(v/vec3 newx y newz))
[mn mx] (reduce (fn [[mn mx] tester]
[(v/emn mn tester)
(v/emx mx tester)]) [(v/vec3 ##Inf ##Inf ##Inf)
(v/vec3 ##-Inf ##-Inf ##-Inf)] new-corners)]
(->RotateY p sin-theta cos-theta (aabb/aabb mn mx))))
|
|
7b5cc958ddb0de4d0fa51caee975651f709c196bace8b35ff27f404fdff7ec1a | protojure/lib | grpc.clj | Copyright © 2019 State Street Bank and Trust Company . All rights reserved
Copyright © 2019 - 2022 Manetu , Inc. All rights reserved
;;
SPDX - License - Identifier : Apache-2.0
(ns protojure.pedestal.interceptors.grpc
"A [Pedestal](/) [interceptor]() for [GRPC](/) support"
(:require [clojure.core.async :refer [go >! <!] :as async]
[protojure.grpc.codec.lpm :as lpm]
[protojure.grpc.status :as status]
[promesa.core :as p]
[io.pedestal.interceptor :as pedestal]
[io.pedestal.interceptor.error :as err]
[io.pedestal.log :as log]
[protojure.grpc.status :as grpc.status])
(:import [java.util UUID]))
(set! *warn-on-reflection* true)
(def ^{:const true :no-doc true} supported-encodings (-> protojure.grpc.codec.compression/builtin-codecs (keys) (conj "identity") (set)))
(defn- determine-output-encoding
[accepted-encodings]
(->> (clojure.string/split accepted-encodings #",")
(filter supported-encodings)
(first)))
(defn logging-chan [bufsiz id label]
(async/chan bufsiz (map (fn [m] (log/trace (str "GRPC: " id " -> " label) m) m))))
(defn- create-req-ctx
[id f {:keys [body-ch] {:strs [grpc-encoding] :or {grpc-encoding "identity"}} :headers :as req}]
(let [in body-ch
out (logging-chan 128 id "rx")]
{:in in
:out out
:encoding grpc-encoding
:status (lpm/decode f in out {:content-coding grpc-encoding})}))
(defn- create-resp-ctx
[id f {{:strs [grpc-accept-encoding] :or {grpc-accept-encoding ""}} :headers :as req}]
(let [in (logging-chan 128 id "tx")
out (async/chan 128)
encoding (or (determine-output-encoding grpc-accept-encoding) "identity")]
{:in in
:out out
:encoding encoding
:status (lpm/encode f in out {:content-coding encoding :max-frame-size 16383})}))
(defn- set-params [context params]
(assoc-in context [:request :grpc-params] params))
(defn gen-uuid []
(.toString (UUID/randomUUID)))
(defn method-desc [{:keys [pkg service method]}]
(str pkg "." service "/" method))
(defn- grpc-enter
"<enter> interceptor for handling GRPC requests"
[{:keys [server-streaming client-streaming input output] :as rpc-metadata}
{:keys [request] :as context}]
(let [id (gen-uuid)
req-ctx (create-req-ctx id input request)
resp-ctx (create-resp-ctx id output request)
input-ch (:out req-ctx)
context (-> context
(assoc ::ctx {:req-ctx req-ctx :resp-ctx resp-ctx :id id})
(cond-> server-streaming
(assoc-in [:request :grpc-out] (:in resp-ctx))))]
(log/trace (str "GRPC: " id " -> start " (method-desc rpc-metadata)) request)
set : - params
(if client-streaming
(set-params context input-ch) ;; client-streaming means simply pass the channel directly
(if-let [params (async/poll! input-ch)]
(set-params context params) ;; materialize unary params opportunistically, if available
(go (set-params context (<! input-ch))))))) ;; else, defer context until unary params materialize
(defn- take-promise [ch]
(p/create
(fn [resolve reject]
(async/take! ch resolve))))
(defn- put [ch val]
(p/create
(fn [resolve reject]
(async/put! ch val resolve))))
(defn- ->trailers
[{:keys [grpc-status grpc-message] :or {grpc-status 0}}]
(-> {"grpc-status" grpc-status}
(cond-> (some? grpc-message) (assoc "grpc-message" grpc-message))))
(defn- prepare-trailers [id {:keys [trailers] :as response}]
(let [ch (async/promise-chan)]
[ch (fn [_] (-> (if (some? trailers)
(take-promise trailers)
response)
(p/then ->trailers)
(p/then (fn [r]
(log/trace (str "GRPC: " id " -> trailers") r)
(put ch r)))))]))
(defn- grpc-leave
"<leave> interceptor for handling GRPC responses"
[{:keys [server-streaming] :as rpc-metadata}
{{:keys [body] :as response} :response {:keys [req-ctx resp-ctx id]} ::ctx :as context}]
(log/trace (str "GRPC: " id " -> leave ") response)
(let [output-ch (:in resp-ctx)
[trailers-ch trailers-fn] (prepare-trailers id response)]
(cond
;; special-case unary return types
(not server-streaming)
(do
(async/>!! output-ch (or body {}))
(async/close! output-ch))
;; Auto-close the output ch if the user does not signify they have consumed it
;; by referencing it in the :body
(not= output-ch body)
(async/close! output-ch))
defer sending trailers until our IO has completed
(-> (p/all (mapv :status [req-ctx resp-ctx]))
(p/then trailers-fn)
(p/then (fn [_]
(log/trace (str "GRPC: " id " -> complete ") nil)))
(p/timeout 30000)
(p/catch (fn [ex]
(log/error :msg "Pipeline" :exception ex)
(status/error :internal))))
(update context :response
#(assoc %
:headers {"Content-Type" "application/grpc+proto"
"grpc-encoding" (:encoding resp-ctx)}
always return 200
:body (:out resp-ctx)
:trailers trailers-ch))))
(defn route-interceptor
[rpc-metadata]
(pedestal/interceptor {:name ::interceptor
:enter (partial grpc-enter rpc-metadata)
:leave (partial grpc-leave rpc-metadata)}))
(defn- err-status
[ctx status msg]
(update ctx :response
assoc
:headers {"Content-Type" "application/grpc+proto"}
:status 200
:body ""
:trailers (->trailers {:grpc-status status :grpc-message msg})))
(def error-interceptor
(err/error-dispatch
[ctx ex]
[{:exception-type ::status/error}]
(let [{:keys [code msg]} (ex-data ex)]
(err-status ctx code msg))
:else
(err-status ctx (grpc.status/get-code :internal) (ex-message ex))))
| null | https://raw.githubusercontent.com/protojure/lib/a07e407776d094f5dc8bc43cd2c1188550892d38/modules/grpc-server/src/protojure/pedestal/interceptors/grpc.clj | clojure |
client-streaming means simply pass the channel directly
materialize unary params opportunistically, if available
else, defer context until unary params materialize
special-case unary return types
Auto-close the output ch if the user does not signify they have consumed it
by referencing it in the :body | Copyright © 2019 State Street Bank and Trust Company . All rights reserved
Copyright © 2019 - 2022 Manetu , Inc. All rights reserved
SPDX - License - Identifier : Apache-2.0
(ns protojure.pedestal.interceptors.grpc
"A [Pedestal](/) [interceptor]() for [GRPC](/) support"
(:require [clojure.core.async :refer [go >! <!] :as async]
[protojure.grpc.codec.lpm :as lpm]
[protojure.grpc.status :as status]
[promesa.core :as p]
[io.pedestal.interceptor :as pedestal]
[io.pedestal.interceptor.error :as err]
[io.pedestal.log :as log]
[protojure.grpc.status :as grpc.status])
(:import [java.util UUID]))
(set! *warn-on-reflection* true)
(def ^{:const true :no-doc true} supported-encodings (-> protojure.grpc.codec.compression/builtin-codecs (keys) (conj "identity") (set)))
(defn- determine-output-encoding
[accepted-encodings]
(->> (clojure.string/split accepted-encodings #",")
(filter supported-encodings)
(first)))
(defn logging-chan [bufsiz id label]
(async/chan bufsiz (map (fn [m] (log/trace (str "GRPC: " id " -> " label) m) m))))
(defn- create-req-ctx
[id f {:keys [body-ch] {:strs [grpc-encoding] :or {grpc-encoding "identity"}} :headers :as req}]
(let [in body-ch
out (logging-chan 128 id "rx")]
{:in in
:out out
:encoding grpc-encoding
:status (lpm/decode f in out {:content-coding grpc-encoding})}))
(defn- create-resp-ctx
[id f {{:strs [grpc-accept-encoding] :or {grpc-accept-encoding ""}} :headers :as req}]
(let [in (logging-chan 128 id "tx")
out (async/chan 128)
encoding (or (determine-output-encoding grpc-accept-encoding) "identity")]
{:in in
:out out
:encoding encoding
:status (lpm/encode f in out {:content-coding encoding :max-frame-size 16383})}))
(defn- set-params [context params]
(assoc-in context [:request :grpc-params] params))
(defn gen-uuid []
(.toString (UUID/randomUUID)))
(defn method-desc [{:keys [pkg service method]}]
(str pkg "." service "/" method))
(defn- grpc-enter
"<enter> interceptor for handling GRPC requests"
[{:keys [server-streaming client-streaming input output] :as rpc-metadata}
{:keys [request] :as context}]
(let [id (gen-uuid)
req-ctx (create-req-ctx id input request)
resp-ctx (create-resp-ctx id output request)
input-ch (:out req-ctx)
context (-> context
(assoc ::ctx {:req-ctx req-ctx :resp-ctx resp-ctx :id id})
(cond-> server-streaming
(assoc-in [:request :grpc-out] (:in resp-ctx))))]
(log/trace (str "GRPC: " id " -> start " (method-desc rpc-metadata)) request)
set : - params
(if client-streaming
(if-let [params (async/poll! input-ch)]
(defn- take-promise [ch]
(p/create
(fn [resolve reject]
(async/take! ch resolve))))
(defn- put [ch val]
(p/create
(fn [resolve reject]
(async/put! ch val resolve))))
(defn- ->trailers
[{:keys [grpc-status grpc-message] :or {grpc-status 0}}]
(-> {"grpc-status" grpc-status}
(cond-> (some? grpc-message) (assoc "grpc-message" grpc-message))))
(defn- prepare-trailers [id {:keys [trailers] :as response}]
(let [ch (async/promise-chan)]
[ch (fn [_] (-> (if (some? trailers)
(take-promise trailers)
response)
(p/then ->trailers)
(p/then (fn [r]
(log/trace (str "GRPC: " id " -> trailers") r)
(put ch r)))))]))
(defn- grpc-leave
"<leave> interceptor for handling GRPC responses"
[{:keys [server-streaming] :as rpc-metadata}
{{:keys [body] :as response} :response {:keys [req-ctx resp-ctx id]} ::ctx :as context}]
(log/trace (str "GRPC: " id " -> leave ") response)
(let [output-ch (:in resp-ctx)
[trailers-ch trailers-fn] (prepare-trailers id response)]
(cond
(not server-streaming)
(do
(async/>!! output-ch (or body {}))
(async/close! output-ch))
(not= output-ch body)
(async/close! output-ch))
defer sending trailers until our IO has completed
(-> (p/all (mapv :status [req-ctx resp-ctx]))
(p/then trailers-fn)
(p/then (fn [_]
(log/trace (str "GRPC: " id " -> complete ") nil)))
(p/timeout 30000)
(p/catch (fn [ex]
(log/error :msg "Pipeline" :exception ex)
(status/error :internal))))
(update context :response
#(assoc %
:headers {"Content-Type" "application/grpc+proto"
"grpc-encoding" (:encoding resp-ctx)}
always return 200
:body (:out resp-ctx)
:trailers trailers-ch))))
(defn route-interceptor
[rpc-metadata]
(pedestal/interceptor {:name ::interceptor
:enter (partial grpc-enter rpc-metadata)
:leave (partial grpc-leave rpc-metadata)}))
(defn- err-status
[ctx status msg]
(update ctx :response
assoc
:headers {"Content-Type" "application/grpc+proto"}
:status 200
:body ""
:trailers (->trailers {:grpc-status status :grpc-message msg})))
(def error-interceptor
(err/error-dispatch
[ctx ex]
[{:exception-type ::status/error}]
(let [{:keys [code msg]} (ex-data ex)]
(err-status ctx code msg))
:else
(err-status ctx (grpc.status/get-code :internal) (ex-message ex))))
|
50a32d7b726ed21b9932fa6094f08e3cd049f76456aff65db34df20eff2cbdab | scrintal/heroicons-reagent | clipboard_document_list.cljs | (ns com.scrintal.heroicons.solid.clipboard-document-list)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M7.502 6h7.128A3.375 3.375 0 0118 9.375v9.375a3 3 0 003-3V6.108c0-1.505-1.125-2.811-2.664-2.94a48.972 48.972 0 00-.673-.05A3 3 0 0015 1.5h-1.5a3 3 0 00-2.663 1.618c-.225.015-.45.032-.673.05C8.662 3.295 7.554 4.542 7.502 6zM13.5 3A1.5 1.5 0 0012 4.5h4.5A1.5 1.5 0 0015 3h-1.5z"
:clipRule "evenodd"}]
[:path {:fillRule "evenodd"
:d "M3 9.375C3 8.339 3.84 7.5 4.875 7.5h9.75c1.036 0 1.875.84 1.875 1.875v11.25c0 1.035-.84 1.875-1.875 1.875h-9.75A1.875 1.875 0 013 20.625V9.375zM6 12a.75.75 0 01.75-.75h.008a.75.75 0 01.75.75v.008a.75.75 0 01-.75.75H6.75a.75.75 0 01-.75-.75V12zm2.25 0a.75.75 0 01.75-.75h3.75a.75.75 0 010 1.5H9a.75.75 0 01-.75-.75zM6 15a.75.75 0 01.75-.75h.008a.75.75 0 01.75.75v.008a.75.75 0 01-.75.75H6.75a.75.75 0 01-.75-.75V15zm2.25 0a.75.75 0 01.75-.75h3.75a.75.75 0 010 1.5H9a.75.75 0 01-.75-.75zM6 18a.75.75 0 01.75-.75h.008a.75.75 0 01.75.75v.008a.75.75 0 01-.75.75H6.75a.75.75 0 01-.75-.75V18zm2.25 0a.75.75 0 01.75-.75h3.75a.75.75 0 010 1.5H9a.75.75 0 01-.75-.75z"
:clipRule "evenodd"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/clipboard_document_list.cljs | clojure | (ns com.scrintal.heroicons.solid.clipboard-document-list)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M7.502 6h7.128A3.375 3.375 0 0118 9.375v9.375a3 3 0 003-3V6.108c0-1.505-1.125-2.811-2.664-2.94a48.972 48.972 0 00-.673-.05A3 3 0 0015 1.5h-1.5a3 3 0 00-2.663 1.618c-.225.015-.45.032-.673.05C8.662 3.295 7.554 4.542 7.502 6zM13.5 3A1.5 1.5 0 0012 4.5h4.5A1.5 1.5 0 0015 3h-1.5z"
:clipRule "evenodd"}]
[:path {:fillRule "evenodd"
:d "M3 9.375C3 8.339 3.84 7.5 4.875 7.5h9.75c1.036 0 1.875.84 1.875 1.875v11.25c0 1.035-.84 1.875-1.875 1.875h-9.75A1.875 1.875 0 013 20.625V9.375zM6 12a.75.75 0 01.75-.75h.008a.75.75 0 01.75.75v.008a.75.75 0 01-.75.75H6.75a.75.75 0 01-.75-.75V12zm2.25 0a.75.75 0 01.75-.75h3.75a.75.75 0 010 1.5H9a.75.75 0 01-.75-.75zM6 15a.75.75 0 01.75-.75h.008a.75.75 0 01.75.75v.008a.75.75 0 01-.75.75H6.75a.75.75 0 01-.75-.75V15zm2.25 0a.75.75 0 01.75-.75h3.75a.75.75 0 010 1.5H9a.75.75 0 01-.75-.75zM6 18a.75.75 0 01.75-.75h.008a.75.75 0 01.75.75v.008a.75.75 0 01-.75.75H6.75a.75.75 0 01-.75-.75V18zm2.25 0a.75.75 0 01.75-.75h3.75a.75.75 0 010 1.5H9a.75.75 0 01-.75-.75z"
:clipRule "evenodd"}]]) |
|
0575f8a9b8c8d2d17a19f14ddf27bf01946a1d4540dfadd7555591f3c728b09e | snoyberg/conduit | Foldl.hs | {-# LANGUAGE RankNTypes #-}
-- | Adapter module to work with the < foldl> package.
--
-- @since 1.1.16
module Data.Conduit.Foldl where
import Data.Conduit
import Control.Monad.Trans.Class (lift)
import qualified Data.Conduit.List as CL
-- | Convert a left fold into a 'Consumer'. This function is intended
-- to be used with @purely@ from the
-- < foldl> package.
--
-- @since 1.1.16
sinkFold :: Monad m => (x -> a -> x) -> x -> (x -> b) -> ConduitT a o m b
sinkFold combine seed extract = fmap extract (CL.fold combine seed)
-- | Convert a monadic left fold into a 'Consumer'. This function is
-- intended to be used with @impurely@ from the
-- < foldl> package.
--
-- @since 1.1.16
sinkFoldM :: Monad m => (x -> a -> m x) -> m x -> (x -> m b) -> ConduitT a o m b
sinkFoldM combine seed extract =
lift . extract =<< CL.foldM combine =<< lift seed
| null | https://raw.githubusercontent.com/snoyberg/conduit/1771780ff4b606296924a28bf5d4433ae6a916f3/conduit-extra/Data/Conduit/Foldl.hs | haskell | # LANGUAGE RankNTypes #
| Adapter module to work with the < foldl> package.
@since 1.1.16
| Convert a left fold into a 'Consumer'. This function is intended
to be used with @purely@ from the
< foldl> package.
@since 1.1.16
| Convert a monadic left fold into a 'Consumer'. This function is
intended to be used with @impurely@ from the
< foldl> package.
@since 1.1.16 | module Data.Conduit.Foldl where
import Data.Conduit
import Control.Monad.Trans.Class (lift)
import qualified Data.Conduit.List as CL
sinkFold :: Monad m => (x -> a -> x) -> x -> (x -> b) -> ConduitT a o m b
sinkFold combine seed extract = fmap extract (CL.fold combine seed)
sinkFoldM :: Monad m => (x -> a -> m x) -> m x -> (x -> m b) -> ConduitT a o m b
sinkFoldM combine seed extract =
lift . extract =<< CL.foldM combine =<< lift seed
|
079d153c15d21f2c90e5b70506db3953b13b96745db0332cf05f0a67e8cbda03 | slasser/vermillion | menhirLib.mli | module General : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* This module offers general-purpose functions on lists and streams. *)
As of 2017/03/31 , this module is DEPRECATED . It might be removed in
the future .
the future. *)
(* --------------------------------------------------------------------------- *)
(* Lists. *)
[ take n xs ] returns the [ n ] first elements of the list [ xs ] . It is
acceptable for the list [ xs ] to have length less than [ n ] , in
which case [ xs ] itself is returned .
acceptable for the list [xs] to have length less than [n], in
which case [xs] itself is returned. *)
val take: int -> 'a list -> 'a list
[ drop n xs ] returns the list [ xs ] , deprived of its [ n ] first elements .
It is acceptable for the list [ xs ] to have length less than [ n ] , in
which case an empty list is returned .
It is acceptable for the list [xs] to have length less than [n], in
which case an empty list is returned. *)
val drop: int -> 'a list -> 'a list
(* [uniq cmp xs] assumes that the list [xs] is sorted according to the
ordering [cmp] and returns the list [xs] deprived of any duplicate
elements. *)
val uniq: ('a -> 'a -> int) -> 'a list -> 'a list
(* [weed cmp xs] returns the list [xs] deprived of any duplicate elements. *)
val weed: ('a -> 'a -> int) -> 'a list -> 'a list
(* --------------------------------------------------------------------------- *)
(* A stream is a list whose elements are produced on demand. *)
type 'a stream =
'a head Lazy.t
and 'a head =
| Nil
| Cons of 'a * 'a stream
(* The length of a stream. *)
val length: 'a stream -> int
(* Folding over a stream. *)
val foldr: ('a -> 'b -> 'b) -> 'a stream -> 'b -> 'b
end
module Convert : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
An ocamlyacc - style , or Menhir - style , parser requires access to
the lexer , which must be parameterized with a lexing buffer , and
to the lexing buffer itself , where it reads position information .
the lexer, which must be parameterized with a lexing buffer, and
to the lexing buffer itself, where it reads position information. *)
(* This traditional API is convenient when used with ocamllex, but
inelegant when used with other lexer generators. *)
type ('token, 'semantic_value) traditional =
(Lexing.lexbuf -> 'token) -> Lexing.lexbuf -> 'semantic_value
(* This revised API is independent of any lexer generator. Here, the
parser only requires access to the lexer, and the lexer takes no
parameters. The tokens returned by the lexer may contain position
information. *)
type ('token, 'semantic_value) revised =
(unit -> 'token) -> 'semantic_value
(* --------------------------------------------------------------------------- *)
Converting a traditional parser , produced by ocamlyacc or Menhir ,
into a revised parser .
into a revised parser. *)
A token of the revised lexer is essentially a triple of a token
of the traditional lexer ( or raw token ) , a start position , and
and end position . The three [ get ] functions are accessors .
of the traditional lexer (or raw token), a start position, and
and end position. The three [get] functions are accessors. *)
We do not require the type [ ' token ] to actually be a triple type .
This enables complex applications where it is a record type with
more than three fields . It also enables simple applications where
positions are of no interest , so [ ' token ] is just [ ' raw_token ]
and [ get_startp ] and [ get_endp ] return dummy positions .
This enables complex applications where it is a record type with
more than three fields. It also enables simple applications where
positions are of no interest, so ['token] is just ['raw_token]
and [get_startp] and [get_endp] return dummy positions. *)
val traditional2revised:
('token -> 'raw_token) ->
('token -> Lexing.position) ->
('token -> Lexing.position) ->
('raw_token, 'semantic_value) traditional ->
('token, 'semantic_value) revised
(* --------------------------------------------------------------------------- *)
(* Converting a revised parser back to a traditional parser. *)
val revised2traditional:
('raw_token -> Lexing.position -> Lexing.position -> 'token) ->
('token, 'semantic_value) revised ->
('raw_token, 'semantic_value) traditional
(* --------------------------------------------------------------------------- *)
(* Simplified versions of the above, where concrete triples are used. *)
module Simplified : sig
val traditional2revised:
('token, 'semantic_value) traditional ->
('token * Lexing.position * Lexing.position, 'semantic_value) revised
val revised2traditional:
('token * Lexing.position * Lexing.position, 'semantic_value) revised ->
('token, 'semantic_value) traditional
end
end
module IncrementalEngine : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
type position = Lexing.position
open General
This signature describes the incremental LR engine .
(* In this mode, the user controls the lexer, and the parser suspends
itself when it needs to read a new token. *)
module type INCREMENTAL_ENGINE = sig
type token
A value of type [ production ] is ( an index for ) a production . The start
productions ( which do not exist in an \mly file , but are constructed by
Menhir internally ) are not part of this type .
productions (which do not exist in an \mly file, but are constructed by
Menhir internally) are not part of this type. *)
type production
(* The type ['a checkpoint] represents an intermediate or final state of the
parser. An intermediate checkpoint is a suspension: it records the parser's
current state, and allows parsing to be resumed. The parameter ['a] is
the type of the semantic value that will eventually be produced if the
parser succeeds. *)
(* [Accepted] and [Rejected] are final checkpoints. [Accepted] carries a
semantic value. *)
[ InputNeeded ] is an intermediate checkpoint . It means that the parser wishes
to read one token before continuing .
to read one token before continuing. *)
[ Shifting ] is an intermediate checkpoint . It means that the parser is taking
a shift transition . It exposes the state of the parser before and after
the transition . The Boolean parameter tells whether the parser intends to
request a new token after this transition . ( It always does , except when
it is about to accept . )
a shift transition. It exposes the state of the parser before and after
the transition. The Boolean parameter tells whether the parser intends to
request a new token after this transition. (It always does, except when
it is about to accept.) *)
(* [AboutToReduce] is an intermediate checkpoint. It means that the parser is
about to perform a reduction step. It exposes the parser's current
state as well as the production that is about to be reduced. *)
(* [HandlingError] is an intermediate checkpoint. It means that the parser has
detected an error and is currently handling it, in several steps. *)
(* A value of type ['a env] represents a configuration of the automaton:
current state, stack, lookahead token, etc. The parameter ['a] is the
type of the semantic value that will eventually be produced if the parser
succeeds. *)
(* In normal operation, the parser works with checkpoints: see the functions
[offer] and [resume]. However, it is also possible to work directly with
environments (see the functions [pop], [force_reduction], and [feed]) and
to reconstruct a checkpoint out of an environment (see [input_needed]).
This is considered advanced functionality; its purpose is to allow error
recovery strategies to be programmed by the user. *)
type 'a env
type 'a checkpoint = private
| InputNeeded of 'a env
| Shifting of 'a env * 'a env * bool
| AboutToReduce of 'a env * production
| HandlingError of 'a env
| Accepted of 'a
| Rejected
[ offer ] allows the user to resume the parser after it has suspended
itself with a checkpoint of the form [ InputNeeded env ] . [ offer ] expects the
old checkpoint as well as a new token and produces a new checkpoint . It does not
raise any exception .
itself with a checkpoint of the form [InputNeeded env]. [offer] expects the
old checkpoint as well as a new token and produces a new checkpoint. It does not
raise any exception. *)
val offer:
'a checkpoint ->
token * position * position ->
'a checkpoint
(* [resume] allows the user to resume the parser after it has suspended
itself with a checkpoint of the form [AboutToReduce (env, prod)] or
[HandlingError env]. [resume] expects the old checkpoint and produces a new
checkpoint. It does not raise any exception. *)
val resume:
'a checkpoint ->
'a checkpoint
(* A token supplier is a function of no arguments which delivers a new token
(together with its start and end positions) every time it is called. *)
type supplier =
unit -> token * position * position
(* A pair of a lexer and a lexing buffer can be easily turned into a supplier. *)
val lexer_lexbuf_to_supplier:
(Lexing.lexbuf -> token) ->
Lexing.lexbuf ->
supplier
The functions [ offer ] and [ resume ] are sufficient to write a parser loop .
One can imagine many variations ( which is why we expose these functions
in the first place ! ) . Here , we expose a few variations of the main loop ,
ready for use .
One can imagine many variations (which is why we expose these functions
in the first place!). Here, we expose a few variations of the main loop,
ready for use. *)
(* [loop supplier checkpoint] begins parsing from [checkpoint], reading
tokens from [supplier]. It continues parsing until it reaches a
checkpoint of the form [Accepted v] or [Rejected]. In the former case, it
returns [v]. In the latter case, it raises the exception [Error]. *)
val loop: supplier -> 'a checkpoint -> 'a
[ loop_handle succeed fail supplier checkpoint ] begins parsing from
[ checkpoint ] , reading tokens from [ supplier ] . It continues parsing until
it reaches a checkpoint of the form [ Accepted v ] or [ HandlingError env ]
( or [ Rejected ] , but that should not happen , as [ HandlingError _ ] will be
observed first ) . In the former case , it calls [ succeed v ] . In the latter
case , it calls [ fail ] with this checkpoint . It can not raise [ Error ] .
This means that Menhir 's traditional error - handling procedure ( which pops
the stack until a state that can act on the [ error ] token is found ) does
not get a chance to run . Instead , the user can implement her own error
handling code , in the [ fail ] continuation .
[checkpoint], reading tokens from [supplier]. It continues parsing until
it reaches a checkpoint of the form [Accepted v] or [HandlingError env]
(or [Rejected], but that should not happen, as [HandlingError _] will be
observed first). In the former case, it calls [succeed v]. In the latter
case, it calls [fail] with this checkpoint. It cannot raise [Error].
This means that Menhir's traditional error-handling procedure (which pops
the stack until a state that can act on the [error] token is found) does
not get a chance to run. Instead, the user can implement her own error
handling code, in the [fail] continuation. *)
val loop_handle:
('a -> 'answer) ->
('a checkpoint -> 'answer) ->
supplier -> 'a checkpoint -> 'answer
[ loop_handle_undo ] is analogous to [ loop_handle ] , except it passes a pair
of checkpoints to the failure continuation .
The first ( and oldest ) checkpoint is the last [ InputNeeded ] checkpoint that
was encountered before the error was detected . The second ( and newest )
checkpoint is where the error was detected , as in [ loop_handle ] . Going back
to the first checkpoint can be thought of as undoing any reductions that
were performed after seeing the problematic token . ( These reductions must
be default reductions or spurious reductions . )
[ loop_handle_undo ] must initially be applied to an [ InputNeeded ] checkpoint .
The parser 's initial checkpoints satisfy this constraint .
of checkpoints to the failure continuation.
The first (and oldest) checkpoint is the last [InputNeeded] checkpoint that
was encountered before the error was detected. The second (and newest)
checkpoint is where the error was detected, as in [loop_handle]. Going back
to the first checkpoint can be thought of as undoing any reductions that
were performed after seeing the problematic token. (These reductions must
be default reductions or spurious reductions.)
[loop_handle_undo] must initially be applied to an [InputNeeded] checkpoint.
The parser's initial checkpoints satisfy this constraint. *)
val loop_handle_undo:
('a -> 'answer) ->
('a checkpoint -> 'a checkpoint -> 'answer) ->
supplier -> 'a checkpoint -> 'answer
(* [shifts checkpoint] assumes that [checkpoint] has been obtained by
submitting a token to the parser. It runs the parser from [checkpoint],
through an arbitrary number of reductions, until the parser either
accepts this token (i.e., shifts) or rejects it (i.e., signals an error).
If the parser decides to shift, then [Some env] is returned, where [env]
is the parser's state just before shifting. Otherwise, [None] is
returned. *)
(* It is desirable that the semantic actions be side-effect free, or that
their side-effects be harmless (replayable). *)
val shifts: 'a checkpoint -> 'a env option
(* The function [acceptable] allows testing, after an error has been
detected, which tokens would have been accepted at this point. It is
implemented using [shifts]. Its argument should be an [InputNeeded]
checkpoint. *)
For completeness , one must undo any spurious reductions before carrying out
this test -- that is , one must apply [ acceptable ] to the FIRST checkpoint
that is passed by [ loop_handle_undo ] to its failure continuation .
this test -- that is, one must apply [acceptable] to the FIRST checkpoint
that is passed by [loop_handle_undo] to its failure continuation. *)
(* This test causes some semantic actions to be run! The semantic actions
should be side-effect free, or their side-effects should be harmless. *)
(* The position [pos] is used as the start and end positions of the
hypothetical token, and may be picked up by the semantic actions. We
suggest using the position where the error was detected. *)
val acceptable: 'a checkpoint -> token -> position -> bool
The abstract type [ ' a lr1state ] describes the non - initial states of the
) automaton . The index [ ' a ] represents the type of the semantic value
associated with this state 's incoming symbol .
LR(1) automaton. The index ['a] represents the type of the semantic value
associated with this state's incoming symbol. *)
type 'a lr1state
The states of the LR(1 ) automaton are numbered ( from 0 and up ) .
val number: _ lr1state -> int
(* Productions are numbered. *)
(* [find_production i] requires the index [i] to be valid. Use with care. *)
val production_index: production -> int
val find_production: int -> production
(* An element is a pair of a non-initial state [s] and a semantic value [v]
associated with the incoming symbol of this state. The idea is, the value
[v] was pushed onto the stack just before the state [s] was entered. Thus,
for some type ['a], the state [s] has type ['a lr1state] and the value [v]
has type ['a]. In other words, the type [element] is an existential type. *)
type element =
| Element: 'a lr1state * 'a * position * position -> element
(* The parser's stack is (or, more precisely, can be viewed as) a stream of
elements. The type [stream] is defined by the module [General]. *)
As of 2017/03/31 , the types [ stream ] and [ stack ] and the function [ stack ]
are DEPRECATED . They might be removed in the future . An alternative way
of inspecting the stack is via the functions [ top ] and [ pop ] .
are DEPRECATED. They might be removed in the future. An alternative way
of inspecting the stack is via the functions [top] and [pop]. *)
type stack = (* DEPRECATED *)
element stream
This is the parser 's stack , a stream of elements . This stream is empty if
the parser is in an initial state ; otherwise , it is non - empty . The LR(1 )
automaton 's current state is the one found in the top element of the
stack .
the parser is in an initial state; otherwise, it is non-empty. The LR(1)
automaton's current state is the one found in the top element of the
stack. *)
val stack: 'a env -> stack (* DEPRECATED *)
(* [top env] returns the parser's top stack element. The state contained in
this stack element is the current state of the automaton. If the stack is
empty, [None] is returned. In that case, the current state of the
automaton must be an initial state. *)
val top: 'a env -> element option
(* [pop_many i env] pops [i] cells off the automaton's stack. This is done
via [i] successive invocations of [pop]. Thus, [pop_many 1] is [pop]. The
index [i] must be nonnegative. The time complexity is O(i). *)
val pop_many: int -> 'a env -> 'a env option
(* [get i env] returns the parser's [i]-th stack element. The index [i] is
0-based: thus, [get 0] is [top]. If [i] is greater than or equal to the
number of elements in the stack, [None] is returned. The time complexity
is O(i). *)
val get: int -> 'a env -> element option
[ env ] is ( the integer number of ) the automaton 's
current state . This works even if the automaton 's stack is empty , in
which case the current state is an initial state . This number can be
passed as an argument to a [ message ] function generated by [ menhir
--compile - errors ] .
current state. This works even if the automaton's stack is empty, in
which case the current state is an initial state. This number can be
passed as an argument to a [message] function generated by [menhir
--compile-errors]. *)
val current_state_number: 'a env -> int
(* [equal env1 env2] tells whether the parser configurations [env1] and
[env2] are equal in the sense that the automaton's current state is the
same in [env1] and [env2] and the stack is *physically* the same in
[env1] and [env2]. If [equal env1 env2] is [true], then the sequence of
the stack elements, as observed via [pop] and [top], must be the same in
[env1] and [env2]. Also, if [equal env1 env2] holds, then the checkpoints
[input_needed env1] and [input_needed env2] must be equivalent. The
function [equal] has time complexity O(1). *)
val equal: 'a env -> 'a env -> bool
(* These are the start and end positions of the current lookahead token. If
invoked in an initial state, this function returns a pair of twice the
initial position. *)
val positions: 'a env -> position * position
(* When applied to an environment taken from a checkpoint of the form
[AboutToReduce (env, prod)], the function [env_has_default_reduction]
tells whether the reduction that is about to take place is a default
reduction. *)
val env_has_default_reduction: 'a env -> bool
(* [state_has_default_reduction s] tells whether the state [s] has a default
reduction. This includes the case where [s] is an accepting state. *)
val state_has_default_reduction: _ lr1state -> bool
(* [pop env] returns a new environment, where the parser's top stack cell
has been popped off. (If the stack is empty, [None] is returned.) This
amounts to pretending that the (terminal or nonterminal) symbol that
corresponds to this stack cell has not been read. *)
val pop: 'a env -> 'a env option
(* [force_reduction prod env] should be called only if in the state [env]
the parser is capable of reducing the production [prod]. If this
condition is satisfied, then this production is reduced, which means that
its semantic action is executed (this can have side effects!) and the
automaton makes a goto (nonterminal) transition. If this condition is not
satisfied, [Invalid_argument _] is raised. *)
val force_reduction: production -> 'a env -> 'a env
[ input_needed env ] returns [ InputNeeded env ] . That is , out of an [ env ]
that might have been obtained via a series of calls to the functions
[ pop ] , [ force_reduction ] , [ feed ] , etc . , it produces a checkpoint , which
can be used to resume normal parsing , by supplying this checkpoint as an
argument to [ offer ] .
that might have been obtained via a series of calls to the functions
[pop], [force_reduction], [feed], etc., it produces a checkpoint, which
can be used to resume normal parsing, by supplying this checkpoint as an
argument to [offer]. *)
This function should be used with some care . It could " mess up the
lookahead " in the sense that it allows parsing to resume in an arbitrary
state [ s ] with an arbitrary lookahead symbol [ t ] , even though Menhir 's
reachability analysis ( menhir --list - errors ) might well think that it is
impossible to reach this particular configuration . If one is using
Menhir 's new error reporting facility , this could cause the parser to
reach an error state for which no error message has been prepared .
lookahead" in the sense that it allows parsing to resume in an arbitrary
state [s] with an arbitrary lookahead symbol [t], even though Menhir's
reachability analysis (menhir --list-errors) might well think that it is
impossible to reach this particular configuration. If one is using
Menhir's new error reporting facility, this could cause the parser to
reach an error state for which no error message has been prepared. *)
val input_needed: 'a env -> 'a checkpoint
end
(* This signature is a fragment of the inspection API that is made available
to the user when [--inspection] is used. This fragment contains type
definitions for symbols. *)
module type SYMBOLS = sig
(* The type ['a terminal] represents a terminal symbol. The type ['a
nonterminal] represents a nonterminal symbol. In both cases, the index
['a] represents the type of the semantic values associated with this
symbol. The concrete definitions of these types are generated. *)
type 'a terminal
type 'a nonterminal
(* The type ['a symbol] represents a terminal or nonterminal symbol. It is
the disjoint union of the types ['a terminal] and ['a nonterminal]. *)
type 'a symbol =
| T : 'a terminal -> 'a symbol
| N : 'a nonterminal -> 'a symbol
(* The type [xsymbol] is an existentially quantified version of the type
['a symbol]. This type is useful in situations where the index ['a]
is not statically known. *)
type xsymbol =
| X : 'a symbol -> xsymbol
end
(* This signature describes the inspection API that is made available to the
user when [--inspection] is used. *)
module type INSPECTION = sig
(* The types of symbols are described above. *)
include SYMBOLS
The type [ ' a lr1state ] is meant to be the same as in [ INCREMENTAL_ENGINE ] .
type 'a lr1state
The type [ production ] is meant to be the same as in [ INCREMENTAL_ENGINE ] .
It represents a production of the grammar . A production can be examined
via the functions [ lhs ] and [ rhs ] below .
It represents a production of the grammar. A production can be examined
via the functions [lhs] and [rhs] below. *)
type production
(* An LR(0) item is a pair of a production [prod] and a valid index [i] into
this production. That is, if the length of [rhs prod] is [n], then [i] is
comprised between 0 and [n], inclusive. *)
type item =
production * int
(* Ordering functions. *)
val compare_terminals: _ terminal -> _ terminal -> int
val compare_nonterminals: _ nonterminal -> _ nonterminal -> int
val compare_symbols: xsymbol -> xsymbol -> int
val compare_productions: production -> production -> int
val compare_items: item -> item -> int
(* [incoming_symbol s] is the incoming symbol of the state [s], that is,
the symbol that the parser must recognize before (has recognized when)
it enters the state [s]. This function gives access to the semantic
value [v] stored in a stack element [Element (s, v, _, _)]. Indeed,
by case analysis on the symbol [incoming_symbol s], one discovers the
type ['a] of the value [v]. *)
val incoming_symbol: 'a lr1state -> 'a symbol
[ items s ] is the set of the LR(0 ) items in the LR(0 ) core of the )
state [ s ] . This set is not epsilon - closed . This set is presented as a
list , in an arbitrary order .
state [s]. This set is not epsilon-closed. This set is presented as a
list, in an arbitrary order. *)
val items: _ lr1state -> item list
[ lhs prod ] is the left - hand side of the production [ prod ] . This is
always a non - terminal symbol .
always a non-terminal symbol. *)
val lhs: production -> xsymbol
(* [rhs prod] is the right-hand side of the production [prod]. This is
a (possibly empty) sequence of (terminal or nonterminal) symbols. *)
val rhs: production -> xsymbol list
(* [nullable nt] tells whether the non-terminal symbol [nt] is nullable.
That is, it is true if and only if this symbol produces the empty
word [epsilon]. *)
val nullable: _ nonterminal -> bool
[ first nt t ] tells whether the FIRST set of the nonterminal symbol [ nt ]
contains the terminal symbol [ t ] . That is , it is true if and only if
[ nt ] produces a word that begins with [ t ] .
contains the terminal symbol [t]. That is, it is true if and only if
[nt] produces a word that begins with [t]. *)
val first: _ nonterminal -> _ terminal -> bool
[ xfirst ] is analogous to [ first ] , but expects a first argument of type
[ xsymbol ] instead of [ _ terminal ] .
[xsymbol] instead of [_ terminal]. *)
val xfirst: xsymbol -> _ terminal -> bool
(* [foreach_terminal] enumerates the terminal symbols, including [error].
[foreach_terminal_but_error] enumerates the terminal symbols, excluding
[error]. *)
val foreach_terminal: (xsymbol -> 'a -> 'a) -> 'a -> 'a
val foreach_terminal_but_error: (xsymbol -> 'a -> 'a) -> 'a -> 'a
(* The type [env] is meant to be the same as in [INCREMENTAL_ENGINE]. *)
type 'a env
[ feed symbol startp env ] causes the parser to consume the
( terminal or nonterminal ) symbol [ symbol ] , accompanied with the semantic
value [ semv ] and with the start and end positions [ startp ] and [ endp ] .
Thus , the automaton makes a transition , and reaches a new state . The
stack grows by one cell . This operation is permitted only if the current
state ( as determined by [ env ] ) has an outgoing transition labeled with
[ symbol ] . Otherwise , [ Invalid_argument _ ] is raised .
(terminal or nonterminal) symbol [symbol], accompanied with the semantic
value [semv] and with the start and end positions [startp] and [endp].
Thus, the automaton makes a transition, and reaches a new state. The
stack grows by one cell. This operation is permitted only if the current
state (as determined by [env]) has an outgoing transition labeled with
[symbol]. Otherwise, [Invalid_argument _] is raised. *)
val feed: 'a symbol -> position -> 'a -> position -> 'b env -> 'b env
end
(* This signature combines the incremental API and the inspection API. *)
module type EVERYTHING = sig
include INCREMENTAL_ENGINE
include INSPECTION
with type 'a lr1state := 'a lr1state
with type production := production
with type 'a env := 'a env
end
end
module EngineTypes : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* This file defines several types and module types that are used in the
specification of module [Engine]. *)
(* --------------------------------------------------------------------------- *)
(* It would be nice if we could keep the structure of stacks and environments
hidden. However, stacks and environments must be accessible to semantic
actions, so the following data structure definitions must be public. *)
(* --------------------------------------------------------------------------- *)
(* A stack is a linked list of cells. A sentinel cell -- which is its own
successor -- is used to mark the bottom of the stack. The sentinel cell
itself is not significant -- it contains dummy values. *)
type ('state, 'semantic_value) stack = {
(* The state that we should go back to if we pop this stack cell. *)
(* This convention means that the state contained in the top stack cell is
not the current state [env.current]. It also means that the state found
within the sentinel is a dummy -- it is never consulted. This convention
is the same as that adopted by the code-based back-end. *)
state: 'state;
(* The semantic value associated with the chunk of input that this cell
represents. *)
semv: 'semantic_value;
(* The start and end positions of the chunk of input that this cell
represents. *)
startp: Lexing.position;
endp: Lexing.position;
(* The next cell down in the stack. If this is a self-pointer, then this
cell is the sentinel, and the stack is conceptually empty. *)
next: ('state, 'semantic_value) stack;
}
(* --------------------------------------------------------------------------- *)
(* A parsing environment contains all of the parser's state (except for the
current program point). *)
type ('state, 'semantic_value, 'token) env = {
If this flag is true , then the first component of [ env.triple ] should
be ignored , as it has been logically overwritten with the [ error ]
pseudo - token .
be ignored, as it has been logically overwritten with the [error]
pseudo-token. *)
error: bool;
The last token that was obtained from the lexer , together with its start
and end positions . Warning : before the first call to the lexer has taken
place , a dummy ( and possibly invalid ) token is stored here .
and end positions. Warning: before the first call to the lexer has taken
place, a dummy (and possibly invalid) token is stored here. *)
triple: 'token * Lexing.position * Lexing.position;
(* The stack. In [CodeBackend], it is passed around on its own,
whereas, here, it is accessed via the environment. *)
stack: ('state, 'semantic_value) stack;
(* The current state. In [CodeBackend], it is passed around on its
own, whereas, here, it is accessed via the environment. *)
current: 'state;
}
(* --------------------------------------------------------------------------- *)
This signature describes the parameters that must be supplied to the LR
engine .
engine. *)
module type TABLE = sig
(* The type of automaton states. *)
type state
States are numbered .
val number: state -> int
(* The type of tokens. These can be thought of as real tokens, that is,
tokens returned by the lexer. They carry a semantic value. This type
does not include the [error] pseudo-token. *)
type token
(* The type of terminal symbols. These can be thought of as integer codes.
They do not carry a semantic value. This type does include the [error]
pseudo-token. *)
type terminal
(* The type of nonterminal symbols. *)
type nonterminal
(* The type of semantic values. *)
type semantic_value
A token is conceptually a pair of a ( non-[error ] ) terminal symbol and
a semantic value . The following two functions are the pair projections .
a semantic value. The following two functions are the pair projections. *)
val token2terminal: token -> terminal
val token2value: token -> semantic_value
(* Even though the [error] pseudo-token is not a real token, it is a
terminal symbol. Furthermore, for regularity, it must have a semantic
value. *)
val error_terminal: terminal
val error_value: semantic_value
(* [foreach_terminal] allows iterating over all terminal symbols. *)
val foreach_terminal: (terminal -> 'a -> 'a) -> 'a -> 'a
(* The type of productions. *)
type production
val production_index: production -> int
val find_production: int -> production
(* If a state [s] has a default reduction on production [prod], then, upon
entering [s], the automaton should reduce [prod] without consulting the
lookahead token. The following function allows determining which states
have default reductions. *)
Instead of returning a value of a sum type -- either [ DefRed prod ] , or
[ NoDefRed ] -- it accepts two continuations , and invokes just one of
them . This mechanism allows avoiding a memory allocation .
[NoDefRed] -- it accepts two continuations, and invokes just one of
them. This mechanism allows avoiding a memory allocation. *)
val default_reduction:
state ->
('env -> production -> 'answer) ->
('env -> 'answer) ->
'env -> 'answer
An LR automaton can normally take three kinds of actions : shift , reduce ,
or fail . ( Acceptance is a particular case of reduction : it consists in
reducing a start production . )
or fail. (Acceptance is a particular case of reduction: it consists in
reducing a start production.) *)
There are two variants of the shift action . [ shift / discard s ] instructs
the automaton to discard the current token , request a new one from the
lexer , and move to state [ s ] . [ shift / nodiscard s ] instructs it to move to
state [ s ] without requesting a new token . This instruction should be used
when [ s ] has a default reduction on [ # ] . See [ CodeBackend.gettoken ] for
details .
the automaton to discard the current token, request a new one from the
lexer, and move to state [s]. [shift/nodiscard s] instructs it to move to
state [s] without requesting a new token. This instruction should be used
when [s] has a default reduction on [#]. See [CodeBackend.gettoken] for
details. *)
(* This is the automaton's action table. It maps a pair of a state and a
terminal symbol to an action. *)
Instead of returning a value of a sum type -- one of shift / discard ,
shift / nodiscard , reduce , or fail -- this function accepts three
continuations , and invokes just one them . This mechanism allows avoiding
a memory allocation .
shift/nodiscard, reduce, or fail -- this function accepts three
continuations, and invokes just one them. This mechanism allows avoiding
a memory allocation. *)
In summary , the parameters to [ action ] are as follows :
- the first two parameters , a state and a terminal symbol , are used to
look up the action table ;
- the next parameter is the semantic value associated with the above
terminal symbol ; it is not used , only passed along to the shift
continuation , as explained below ;
- the shift continuation expects an environment ; a flag that tells
whether to discard the current token ; the terminal symbol that
is being shifted ; its semantic value ; and the target state of
the transition ;
- the reduce continuation expects an environment and a production ;
- the fail continuation expects an environment ;
- the last parameter is the environment ; it is not used , only passed
along to the selected continuation .
- the first two parameters, a state and a terminal symbol, are used to
look up the action table;
- the next parameter is the semantic value associated with the above
terminal symbol; it is not used, only passed along to the shift
continuation, as explained below;
- the shift continuation expects an environment; a flag that tells
whether to discard the current token; the terminal symbol that
is being shifted; its semantic value; and the target state of
the transition;
- the reduce continuation expects an environment and a production;
- the fail continuation expects an environment;
- the last parameter is the environment; it is not used, only passed
along to the selected continuation. *)
val action:
state ->
terminal ->
semantic_value ->
('env -> bool -> terminal -> semantic_value -> state -> 'answer) ->
('env -> production -> 'answer) ->
('env -> 'answer) ->
'env -> 'answer
(* This is the automaton's goto table. This table maps a pair of a state
and a nonterminal symbol to a new state. By extension, it also maps a
pair of a state and a production to a new state. *)
The function [ goto_nt ] can be applied to [ s ] and [ nt ] ONLY if the state
[ s ] has an outgoing transition labeled [ nt ] . Otherwise , its result is
undefined . Similarly , the call [ goto_prod prod s ] is permitted ONLY if
the state [ s ] has an outgoing transition labeled with the nonterminal
symbol [ lhs prod ] . The function [ maybe_goto_nt ] involves an additional
dynamic check and CAN be called even if there is no outgoing transition .
[s] has an outgoing transition labeled [nt]. Otherwise, its result is
undefined. Similarly, the call [goto_prod prod s] is permitted ONLY if
the state [s] has an outgoing transition labeled with the nonterminal
symbol [lhs prod]. The function [maybe_goto_nt] involves an additional
dynamic check and CAN be called even if there is no outgoing transition. *)
val goto_nt : state -> nonterminal -> state
val goto_prod: state -> production -> state
val maybe_goto_nt: state -> nonterminal -> state option
(* [is_start prod] tells whether the production [prod] is a start production. *)
val is_start: production -> bool
By convention , a semantic action is responsible for :
1 . fetching whatever semantic values and positions it needs off the stack ;
2 . popping an appropriate number of cells off the stack , as dictated
by the length of the right - hand side of the production ;
3 . computing a new semantic value , as well as new start and end positions ;
4 . pushing a new stack cell , which contains the three values
computed in step 3 ;
5 . returning the new stack computed in steps 2 and 4 .
Point 1 is essentially forced upon us : if semantic values were fetched
off the stack by this interpreter , then the calling convention for
semantic actions would be variadic : not all semantic actions would have
the same number of arguments . The rest follows rather naturally .
1. fetching whatever semantic values and positions it needs off the stack;
2. popping an appropriate number of cells off the stack, as dictated
by the length of the right-hand side of the production;
3. computing a new semantic value, as well as new start and end positions;
4. pushing a new stack cell, which contains the three values
computed in step 3;
5. returning the new stack computed in steps 2 and 4.
Point 1 is essentially forced upon us: if semantic values were fetched
off the stack by this interpreter, then the calling convention for
semantic actions would be variadic: not all semantic actions would have
the same number of arguments. The rest follows rather naturally. *)
Semantic actions are allowed to raise [ Error ] .
exception Error
type semantic_action =
(state, semantic_value, token) env -> (state, semantic_value) stack
val semantic_action: production -> semantic_action
[ may_reduce state prod ] tests whether the state [ state ] is capable of
reducing the production [ prod ] . This function is currently costly and
is not used by the core LR engine . It is used in the implementation
of certain functions , such as [ force_reduction ] , which allow the engine
to be driven programmatically .
reducing the production [prod]. This function is currently costly and
is not used by the core LR engine. It is used in the implementation
of certain functions, such as [force_reduction], which allow the engine
to be driven programmatically. *)
val may_reduce: state -> production -> bool
The LR engine requires a number of hooks , which are used for logging .
(* The comments below indicate the conventional messages that correspond
to these hooks in the code-based back-end; see [CodeBackend]. *)
(* If the flag [log] is false, then the logging functions are not called.
If it is [true], then they are called. *)
val log : bool
module Log : sig
State % d :
val state: state -> unit
(* Shifting (<terminal>) to state <state> *)
val shift: terminal -> state -> unit
(* Reducing a production should be logged either as a reduction
event (for regular productions) or as an acceptance event (for
start productions). *)
(* Reducing production <production> / Accepting *)
val reduce_or_accept: production -> unit
(* Lookahead token is now <terminal> (<pos>-<pos>) *)
val lookahead_token: terminal -> Lexing.position -> Lexing.position -> unit
(* Initiating error handling *)
val initiating_error_handling: unit -> unit
(* Resuming error handling *)
val resuming_error_handling: unit -> unit
(* Handling error in state <state> *)
val handling_error: state -> unit
end
end
(* --------------------------------------------------------------------------- *)
(* This signature describes the monolithic (traditional) LR engine. *)
(* In this interface, the parser controls the lexer. *)
module type MONOLITHIC_ENGINE = sig
type state
type token
type semantic_value
(* An entry point to the engine requires a start state, a lexer, and a lexing
buffer. It either succeeds and produces a semantic value, or fails and
raises [Error]. *)
exception Error
val entry:
state ->
(Lexing.lexbuf -> token) ->
Lexing.lexbuf ->
semantic_value
end
(* --------------------------------------------------------------------------- *)
The following signatures describe the incremental LR engine .
First , see [ INCREMENTAL_ENGINE ] in the file [ IncrementalEngine.ml ] .
(* The [start] function is set apart because we do not wish to publish
it as part of the generated [parser.mli] file. Instead, the table
back-end will publish specialized versions of it, with a suitable
type cast. *)
module type INCREMENTAL_ENGINE_START = sig
(* [start] is an entry point. It requires a start state and a start position
and begins the parsing process. If the lexer is based on an OCaml lexing
buffer, the start position should be [lexbuf.lex_curr_p]. [start] produces
a checkpoint, which usually will be an [InputNeeded] checkpoint. (It could
be [Accepted] if this starting state accepts only the empty word. It could
be [Rejected] if this starting state accepts no word at all.) It does not
raise any exception. *)
(* [start s pos] should really produce a checkpoint of type ['a checkpoint],
for a fixed ['a] that depends on the state [s]. We cannot express this, so
we use [semantic_value checkpoint], which is safe. The table back-end uses
[Obj.magic] to produce safe specialized versions of [start]. *)
type state
type semantic_value
type 'a checkpoint
val start:
state ->
Lexing.position ->
semantic_value checkpoint
end
(* --------------------------------------------------------------------------- *)
This signature describes the LR engine , which combines the monolithic
and incremental interfaces .
and incremental interfaces. *)
module type ENGINE = sig
include MONOLITHIC_ENGINE
include IncrementalEngine.INCREMENTAL_ENGINE
with type token := token
and type 'a lr1state = state (* useful for us; hidden from the end user *)
include INCREMENTAL_ENGINE_START
with type state := state
and type semantic_value := semantic_value
and type 'a checkpoint := 'a checkpoint
end
end
module Engine : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
open EngineTypes
(* The LR parsing engine. *)
module Make (T : TABLE)
: ENGINE
with type state = T.state
and type token = T.token
and type semantic_value = T.semantic_value
and type production = T.production
and type 'a env = (T.state, T.semantic_value, T.token) EngineTypes.env
(* We would prefer not to expose the definition of the type [env].
However, it must be exposed because some of the code in the
inspection API needs access to the engine's internals; see
[InspectionTableInterpreter]. Everything would be simpler if
--inspection was always ON, but that would lead to bigger parse
tables for everybody. *)
end
module ErrorReports : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* -------------------------------------------------------------------------- *)
The following functions help keep track of the start and end positions of
the last two tokens in a two - place buffer . This is used to nicely display
where a syntax error took place .
the last two tokens in a two-place buffer. This is used to nicely display
where a syntax error took place. *)
type 'a buffer
(* [wrap lexer] returns a pair of a new (initially empty) buffer and a lexer
which internally relies on [lexer] and updates [buffer] on the fly whenever
a token is demanded. *)
open Lexing
val wrap:
(lexbuf -> 'token) ->
(position * position) buffer * (lexbuf -> 'token)
(* [show f buffer] prints the contents of the buffer, producing a string that
is typically of the form "after '%s' and before '%s'". The function [f] is
used to print an element. The buffer MUST be nonempty. *)
val show: ('a -> string) -> 'a buffer -> string
(* [last buffer] returns the last element of the buffer. The buffer MUST be
nonempty. *)
val last: 'a buffer -> 'a
(* -------------------------------------------------------------------------- *)
end
module Printers : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
This module is part of MenhirLib .
module Make
(I : IncrementalEngine.EVERYTHING)
(User : sig
(* [print s] is supposed to send the string [s] to some output channel. *)
val print: string -> unit
[ s ] is supposed to print a representation of the symbol [ s ] .
val print_symbol: I.xsymbol -> unit
(* [print_element e] is supposed to print a representation of the element [e].
This function is optional; if it is not provided, [print_element_as_symbol]
(defined below) is used instead. *)
val print_element: (I.element -> unit) option
end)
: sig
open I
(* Printing a list of symbols. *)
val print_symbols: xsymbol list -> unit
(* Printing an element as a symbol. This prints just the symbol
that this element represents; nothing more. *)
val print_element_as_symbol: element -> unit
(* Printing a stack as a list of elements. This function needs an element
printer. It uses [print_element] if provided by the user; otherwise
it uses [print_element_as_symbol]. (Ending with a newline.) *)
val print_stack: 'a env -> unit
(* Printing an item. (Ending with a newline.) *)
val print_item: item -> unit
(* Printing a production. (Ending with a newline.) *)
val print_production: production -> unit
Printing the current LR(1 ) state . The current state is first displayed
as a number ; then the list of its LR(0 ) items is printed . ( Ending with
a newline . )
as a number; then the list of its LR(0) items is printed. (Ending with
a newline.) *)
val print_current_state: 'a env -> unit
(* Printing a summary of the stack and current state. This function just
calls [print_stack] and [print_current_state] in succession. *)
val print_env: 'a env -> unit
end
end
module InfiniteArray : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(** This module implements infinite arrays. **)
type 'a t
(** [make x] creates an infinite array, where every slot contains [x]. **)
val make: 'a -> 'a t
(** [get a i] returns the element contained at offset [i] in the array [a].
Slots are numbered 0 and up. **)
val get: 'a t -> int -> 'a
(** [set a i x] sets the element contained at offset [i] in the array
[a] to [x]. Slots are numbered 0 and up. **)
val set: 'a t -> int -> 'a -> unit
(** [extent a] is the length of an initial segment of the array [a]
that is sufficiently large to contain all [set] operations ever
performed. In other words, all elements beyond that segment have
the default value. *)
val extent: 'a t -> int
(** [domain a] is a fresh copy of an initial segment of the array [a]
whose length is [extent a]. *)
val domain: 'a t -> 'a array
end
module PackedIntArray : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
A packed integer array is represented as a pair of an integer [ k ] and
a string [ s ] . The integer [ k ] is the number of bits per integer that we
use . The string [ s ] is just an array of bits , which is read in 8 - bit
chunks .
a string [s]. The integer [k] is the number of bits per integer that we
use. The string [s] is just an array of bits, which is read in 8-bit
chunks. *)
The ocaml programming language treats string literals and array literals
in slightly different ways : the former are statically allocated , while
the latter are dynamically allocated . ( This is rather arbitrary . ) In the
context of Menhir 's table - based back - end , where compact , immutable
integer arrays are needed , ocaml strings are preferable to ocaml arrays .
in slightly different ways: the former are statically allocated, while
the latter are dynamically allocated. (This is rather arbitrary.) In the
context of Menhir's table-based back-end, where compact, immutable
integer arrays are needed, ocaml strings are preferable to ocaml arrays. *)
type t =
int * string
(* [pack a] turns an array of integers into a packed integer array. *)
(* Because the sign bit is the most significant bit, the magnitude of
any negative number is the word size. In other words, [pack] does
not achieve any space savings as soon as [a] contains any negative
numbers, even if they are ``small''. *)
val pack: int array -> t
(* [get t i] returns the integer stored in the packed array [t] at index [i]. *)
(* Together, [pack] and [get] satisfy the following property: if the index [i]
is within bounds, then [get (pack a) i] equals [a.(i)]. *)
val get: t -> int -> int
[ get1 t i ] returns the integer stored in the packed array [ t ] at index [ i ] .
It assumes ( and does not check ) that the array 's bit width is [ 1 ] . The
parameter [ t ] is just a string .
It assumes (and does not check) that the array's bit width is [1]. The
parameter [t] is just a string. *)
val get1: string -> int -> int
[ unflatten1 ( n , data ) i j ] accesses the two - dimensional bitmap
represented by [ ( n , data ) ] at indices [ i ] and [ j ] . The integer
[ n ] is the width of the bitmap ; the string [ data ] is the second
component of the packed array obtained by encoding the table as
a one - dimensional array .
represented by [(n, data)] at indices [i] and [j]. The integer
[n] is the width of the bitmap; the string [data] is the second
component of the packed array obtained by encoding the table as
a one-dimensional array. *)
val unflatten1: int * string -> int -> int -> int
end
module RowDisplacement : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
This module compresses a two - dimensional table , where some values
are considered insignificant , via row displacement .
are considered insignificant, via row displacement. *)
(* A compressed table is represented as a pair of arrays. The
displacement array is an array of offsets into the data array. *)
type 'a table =
int array * (* displacement *)
'a array (* data *)
[ compress equal insignificant dummy m n t ] turns the two - dimensional table
[ t ] into a compressed table . The parameter [ equal ] is equality of data
values . The parameter [ wildcard ] tells which data values are insignificant ,
and can thus be overwritten with other values . The parameter [ dummy ] is
used to fill holes in the data array . [ m ] and [ n ] are the integer
dimensions of the table [ t ] .
[t] into a compressed table. The parameter [equal] is equality of data
values. The parameter [wildcard] tells which data values are insignificant,
and can thus be overwritten with other values. The parameter [dummy] is
used to fill holes in the data array. [m] and [n] are the integer
dimensions of the table [t]. *)
val compress:
('a -> 'a -> bool) ->
('a -> bool) ->
'a ->
int -> int ->
'a array array ->
'a table
(* [get ct i j] returns the value found at indices [i] and [j] in the
compressed table [ct]. This function call is permitted only if the
value found at indices [i] and [j] in the original table is
significant -- otherwise, it could fail abruptly. *)
(* Together, [compress] and [get] have the property that, if the value
found at indices [i] and [j] in an uncompressed table [t] is
significant, then [get (compress t) i j] is equal to that value. *)
val get:
'a table ->
int -> int ->
'a
[ getget ] is a variant of [ get ] which only requires read access ,
via accessors , to the two components of the table .
via accessors, to the two components of the table. *)
val getget:
('displacement -> int -> int) ->
('data -> int -> 'a) ->
'displacement * 'data ->
int -> int ->
'a
end
module LinearizedArray : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* An array of arrays (of possibly different lengths!) can be ``linearized'',
i.e., encoded as a data array (by concatenating all of the little arrays)
and an entry array (which contains offsets into the data array). *)
type 'a t =
(* data: *) 'a array *
(* entry: *) int array
(* [make a] turns the array of arrays [a] into a linearized array. *)
val make: 'a array array -> 'a t
(* [read la i j] reads the linearized array [la] at indices [i] and [j].
Thus, [read (make a) i j] is equivalent to [a.(i).(j)]. *)
val read: 'a t -> int -> int -> 'a
(* [write la i j v] writes the value [v] into the linearized array [la]
at indices [i] and [j]. *)
val write: 'a t -> int -> int -> 'a -> unit
(* [length la] is the number of rows of the array [la]. Thus, [length (make
a)] is equivalent to [Array.length a]. *)
val length: 'a t -> int
[ row_length la i ] is the length of the row at index [ i ] in the linearized
array [ la ] . Thus , [ ( make a ) i ] is equivalent to [ Array.length
a.(i ) ] .
array [la]. Thus, [row_length (make a) i] is equivalent to [Array.length
a.(i)]. *)
val row_length: 'a t -> int -> int
(* [read_row la i] reads the row at index [i], producing a list. Thus,
[read_row (make a) i] is equivalent to [Array.to_list a.(i)]. *)
val read_row: 'a t -> int -> 'a list
(* The following variants read the linearized array via accessors
[get_data : int -> 'a] and [get_entry : int -> int]. *)
val row_length_via:
(* get_entry: *) (int -> int) ->
(* i: *) int ->
int
val read_via:
(* get_data: *) (int -> 'a) ->
(* get_entry: *) (int -> int) ->
(* i: *) int ->
(* j: *) int ->
'a
val read_row_via:
(* get_data: *) (int -> 'a) ->
(* get_entry: *) (int -> int) ->
(* i: *) int ->
'a list
end
module TableFormat : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* This signature defines the format of the parse tables. It is used as
an argument to [TableInterpreter.Make]. *)
module type TABLES = sig
(* This is the parser's type of tokens. *)
type token
(* This maps a token to its internal (generation-time) integer code. *)
val token2terminal: token -> int
(* This is the integer code for the error pseudo-token. *)
val error_terminal: int
(* This maps a token to its semantic value. *)
val token2value: token -> Obj.t
Traditionally , an LR automaton is described by two tables , namely , an
action table and a goto table . See , for instance , the book .
The action table is a two - dimensional matrix that maps a state and a
lookahead token to an action . An action is one of : shift to a certain
state , reduce a certain production , accept , or fail .
The goto table is a two - dimensional matrix that maps a state and a
non - terminal symbol to either a state or undefined . By construction , this
table is sparse : its undefined entries are never looked up . A compression
technique is free to overlap them with other entries .
In Menhir , things are slightly different . If a state has a default
reduction on token [ # ] , then that reduction must be performed without
consulting the lookahead token . As a result , we must first determine
whether that is the case , before we can obtain a lookahead token and use it
as an index in the action table .
Thus , Menhir 's tables are as follows .
A one - dimensional default reduction table maps a state to either ` ` no
default reduction '' ( encoded as : 0 ) or ` ` by default , reduce prod ''
( encoded as : 1 + prod ) . The action table is looked up only when there
is no default reduction .
action table and a goto table. See, for instance, the Dragon book.
The action table is a two-dimensional matrix that maps a state and a
lookahead token to an action. An action is one of: shift to a certain
state, reduce a certain production, accept, or fail.
The goto table is a two-dimensional matrix that maps a state and a
non-terminal symbol to either a state or undefined. By construction, this
table is sparse: its undefined entries are never looked up. A compression
technique is free to overlap them with other entries.
In Menhir, things are slightly different. If a state has a default
reduction on token [#], then that reduction must be performed without
consulting the lookahead token. As a result, we must first determine
whether that is the case, before we can obtain a lookahead token and use it
as an index in the action table.
Thus, Menhir's tables are as follows.
A one-dimensional default reduction table maps a state to either ``no
default reduction'' (encoded as: 0) or ``by default, reduce prod''
(encoded as: 1 + prod). The action table is looked up only when there
is no default reduction. *)
val default_reduction: PackedIntArray.t
Menhir follows , and Heuft , who point out that , although the
action table is not sparse by nature ( i.e. , the error entries are
significant ) , it can be made sparse by first factoring out a binary error
matrix , then replacing the error entries in the action table with undefined
entries . Thus :
A two - dimensional error bitmap maps a state and a terminal to either
` ` fail '' ( encoded as : 0 ) or ` ` do not fail '' ( encoded as : 1 ) . The action
table , which is now sparse , is looked up only in the latter case .
action table is not sparse by nature (i.e., the error entries are
significant), it can be made sparse by first factoring out a binary error
matrix, then replacing the error entries in the action table with undefined
entries. Thus:
A two-dimensional error bitmap maps a state and a terminal to either
``fail'' (encoded as: 0) or ``do not fail'' (encoded as: 1). The action
table, which is now sparse, is looked up only in the latter case. *)
The error bitmap is flattened into a one - dimensional table ; its width is
recorded so as to allow indexing . The table is then compressed via
[ PackedIntArray ] . The bit width of the resulting packed array must be
[ 1 ] , so it is not explicitly recorded .
recorded so as to allow indexing. The table is then compressed via
[PackedIntArray]. The bit width of the resulting packed array must be
[1], so it is not explicitly recorded. *)
(* The error bitmap does not contain a column for the [#] pseudo-terminal.
Thus, its width is [Terminal.n - 1]. We exploit the fact that the integer
code assigned to [#] is greatest: the fact that the right-most column
in the bitmap is missing does not affect the code for accessing it. *)
second component of [ PackedIntArray.t ]
A two - dimensional action table maps a state and a terminal to one of
` ` shift to state s and discard the current token '' ( encoded as : s | 10 ) ,
` ` shift to state s without discarding the current token '' ( encoded as : s |
11 ) , or ` ` reduce prod '' ( encoded as : prod | 01 ) .
``shift to state s and discard the current token'' (encoded as: s | 10),
``shift to state s without discarding the current token'' (encoded as: s |
11), or ``reduce prod'' (encoded as: prod | 01). *)
The action table is first compressed via [ RowDisplacement ] , then packed
via [ PackedIntArray ] .
via [PackedIntArray]. *)
(* Like the error bitmap, the action table does not contain a column for the
[#] pseudo-terminal. *)
val action: PackedIntArray.t * PackedIntArray.t
A one - dimensional lhs table maps a production to its left - hand side ( a
non - terminal symbol ) .
non-terminal symbol). *)
val lhs: PackedIntArray.t
A two - dimensional goto table maps a state and a non - terminal symbol to
either undefined ( encoded as : 0 ) or a new state s ( encoded as : 1 + s ) .
either undefined (encoded as: 0) or a new state s (encoded as: 1 + s). *)
The goto table is first compressed via [ RowDisplacement ] , then packed
via [ PackedIntArray ] .
via [PackedIntArray]. *)
val goto: PackedIntArray.t * PackedIntArray.t
(* The number of start productions. A production [prod] is a start
production if and only if [prod < start] holds. This is also the
number of start symbols. A nonterminal symbol [nt] is a start
symbol if and only if [nt < start] holds. *)
val start: int
A one - dimensional semantic action table maps productions to semantic
actions . The calling convention for semantic actions is described in
[ EngineTypes ] . This table contains ONLY NON - START PRODUCTIONS , so the
indexing is off by [ start ] . Be careful .
actions. The calling convention for semantic actions is described in
[EngineTypes]. This table contains ONLY NON-START PRODUCTIONS, so the
indexing is off by [start]. Be careful. *)
val semantic_action: ((int, Obj.t, token) EngineTypes.env ->
(int, Obj.t) EngineTypes.stack) array
(* The parser defines its own [Error] exception. This exception can be
raised by semantic actions and caught by the engine, and raised by the
engine towards the final user. *)
exception Error
The parser indicates whether to generate a trace . Generating a
trace requires two extra tables , which respectively map a
terminal symbol and a production to a string .
trace requires two extra tables, which respectively map a
terminal symbol and a production to a string. *)
val trace: (string array * string array) option
end
end
module InspectionTableFormat : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* This signature defines the format of the tables that are produced (in
addition to the tables described in [TableFormat]) when the command line
switch [--inspection] is enabled. It is used as an argument to
[InspectionTableInterpreter.Make]. *)
module type TABLES = sig
(* The types of symbols. *)
include IncrementalEngine.SYMBOLS
The type [ ' a lr1state ] describes an LR(1 ) state . The generated parser defines
it internally as [ int ] .
it internally as [int]. *)
type 'a lr1state
(* Some of the tables that follow use encodings of (terminal and
nonterminal) symbols as integers. So, we need functions that
map the integer encoding of a symbol to its algebraic encoding. *)
val terminal: int -> xsymbol
val nonterminal: int -> xsymbol
(* The left-hand side of every production already appears in the
signature [TableFormat.TABLES], so we need not repeat it here. *)
(* The right-hand side of every production. This a linearized array
of arrays of integers, whose [data] and [entry] components have
been packed. The encoding of symbols as integers in described in
[TableBackend]. *)
val rhs: PackedIntArray.t * PackedIntArray.t
(* A mapping of every (non-initial) state to its LR(0) core. *)
val lr0_core: PackedIntArray.t
(* A mapping of every LR(0) state to its set of LR(0) items. Each item is
represented in its packed form (see [Item]) as an integer. Thus the
mapping is an array of arrays of integers, which is linearized and
packed, like [rhs]. *)
val lr0_items: PackedIntArray.t * PackedIntArray.t
(* A mapping of every LR(0) state to its incoming symbol, if it has one. *)
val lr0_incoming: PackedIntArray.t
(* A table that tells which non-terminal symbols are nullable. *)
val nullable: string
This is a packed int array of bit width 1 . It can be read
using [ PackedIntArray.get1 ] .
using [PackedIntArray.get1]. *)
A two - table dimensional table , indexed by a nonterminal symbol and
by a terminal symbol ( other than [ # ] ) , encodes the FIRST sets .
by a terminal symbol (other than [#]), encodes the FIRST sets. *)
second component of [ PackedIntArray.t ]
end
end
module InspectionTableInterpreter : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
(* This functor is invoked inside the generated parser, in [--table] mode. It
produces no code! It simply constructs the types [symbol] and [xsymbol] on
top of the generated types [terminal] and [nonterminal]. *)
module Symbols (T : sig
type 'a terminal
type 'a nonterminal
end)
: IncrementalEngine.SYMBOLS
with type 'a terminal := 'a T.terminal
and type 'a nonterminal := 'a T.nonterminal
(* This functor is invoked inside the generated parser, in [--table] mode. It
constructs the inspection API on top of the inspection tables described in
[InspectionTableFormat]. *)
module Make
(TT : TableFormat.TABLES)
(IT : InspectionTableFormat.TABLES
with type 'a lr1state = int)
(ET : EngineTypes.TABLE
with type terminal = int
and type nonterminal = int
and type semantic_value = Obj.t)
(E : sig
type 'a env = (ET.state, ET.semantic_value, ET.token) EngineTypes.env
end)
: IncrementalEngine.INSPECTION
with type 'a terminal := 'a IT.terminal
and type 'a nonterminal := 'a IT.nonterminal
and type 'a lr1state := 'a IT.lr1state
and type production := int
and type 'a env := 'a E.env
end
module TableInterpreter : sig
(******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
(* special exception on linking, as described in the file LICENSE. *)
(* *)
(******************************************************************************)
This module provides a thin decoding layer for the generated tables , thus
providing an API that is suitable for use by [ Engine . Make ] . It is part of
[ MenhirLib ] .
providing an API that is suitable for use by [Engine.Make]. It is part of
[MenhirLib]. *)
(* The exception [Error] is declared within the generated parser. This is
preferable to pre-declaring it here, as it ensures that each parser gets
its own, distinct [Error] exception. This is consistent with the code-based
back-end. *)
(* This functor is invoked by the generated parser. *)
module MakeEngineTable
(T : TableFormat.TABLES)
: EngineTypes.TABLE
with type state = int
and type token = T.token
and type semantic_value = Obj.t
and type production = int
and type terminal = int
and type nonterminal = int
end
module StaticVersion : sig
val require_20180905 : unit
end
| null | https://raw.githubusercontent.com/slasser/vermillion/0b60114b27f4f92272129f381ec01e593273e6f2/Evaluation/MenhirLib/menhirLib.mli | ocaml | ****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
This module offers general-purpose functions on lists and streams.
---------------------------------------------------------------------------
Lists.
[uniq cmp xs] assumes that the list [xs] is sorted according to the
ordering [cmp] and returns the list [xs] deprived of any duplicate
elements.
[weed cmp xs] returns the list [xs] deprived of any duplicate elements.
---------------------------------------------------------------------------
A stream is a list whose elements are produced on demand.
The length of a stream.
Folding over a stream.
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
This traditional API is convenient when used with ocamllex, but
inelegant when used with other lexer generators.
This revised API is independent of any lexer generator. Here, the
parser only requires access to the lexer, and the lexer takes no
parameters. The tokens returned by the lexer may contain position
information.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Converting a revised parser back to a traditional parser.
---------------------------------------------------------------------------
Simplified versions of the above, where concrete triples are used.
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
In this mode, the user controls the lexer, and the parser suspends
itself when it needs to read a new token.
The type ['a checkpoint] represents an intermediate or final state of the
parser. An intermediate checkpoint is a suspension: it records the parser's
current state, and allows parsing to be resumed. The parameter ['a] is
the type of the semantic value that will eventually be produced if the
parser succeeds.
[Accepted] and [Rejected] are final checkpoints. [Accepted] carries a
semantic value.
[AboutToReduce] is an intermediate checkpoint. It means that the parser is
about to perform a reduction step. It exposes the parser's current
state as well as the production that is about to be reduced.
[HandlingError] is an intermediate checkpoint. It means that the parser has
detected an error and is currently handling it, in several steps.
A value of type ['a env] represents a configuration of the automaton:
current state, stack, lookahead token, etc. The parameter ['a] is the
type of the semantic value that will eventually be produced if the parser
succeeds.
In normal operation, the parser works with checkpoints: see the functions
[offer] and [resume]. However, it is also possible to work directly with
environments (see the functions [pop], [force_reduction], and [feed]) and
to reconstruct a checkpoint out of an environment (see [input_needed]).
This is considered advanced functionality; its purpose is to allow error
recovery strategies to be programmed by the user.
[resume] allows the user to resume the parser after it has suspended
itself with a checkpoint of the form [AboutToReduce (env, prod)] or
[HandlingError env]. [resume] expects the old checkpoint and produces a new
checkpoint. It does not raise any exception.
A token supplier is a function of no arguments which delivers a new token
(together with its start and end positions) every time it is called.
A pair of a lexer and a lexing buffer can be easily turned into a supplier.
[loop supplier checkpoint] begins parsing from [checkpoint], reading
tokens from [supplier]. It continues parsing until it reaches a
checkpoint of the form [Accepted v] or [Rejected]. In the former case, it
returns [v]. In the latter case, it raises the exception [Error].
[shifts checkpoint] assumes that [checkpoint] has been obtained by
submitting a token to the parser. It runs the parser from [checkpoint],
through an arbitrary number of reductions, until the parser either
accepts this token (i.e., shifts) or rejects it (i.e., signals an error).
If the parser decides to shift, then [Some env] is returned, where [env]
is the parser's state just before shifting. Otherwise, [None] is
returned.
It is desirable that the semantic actions be side-effect free, or that
their side-effects be harmless (replayable).
The function [acceptable] allows testing, after an error has been
detected, which tokens would have been accepted at this point. It is
implemented using [shifts]. Its argument should be an [InputNeeded]
checkpoint.
This test causes some semantic actions to be run! The semantic actions
should be side-effect free, or their side-effects should be harmless.
The position [pos] is used as the start and end positions of the
hypothetical token, and may be picked up by the semantic actions. We
suggest using the position where the error was detected.
Productions are numbered.
[find_production i] requires the index [i] to be valid. Use with care.
An element is a pair of a non-initial state [s] and a semantic value [v]
associated with the incoming symbol of this state. The idea is, the value
[v] was pushed onto the stack just before the state [s] was entered. Thus,
for some type ['a], the state [s] has type ['a lr1state] and the value [v]
has type ['a]. In other words, the type [element] is an existential type.
The parser's stack is (or, more precisely, can be viewed as) a stream of
elements. The type [stream] is defined by the module [General].
DEPRECATED
DEPRECATED
[top env] returns the parser's top stack element. The state contained in
this stack element is the current state of the automaton. If the stack is
empty, [None] is returned. In that case, the current state of the
automaton must be an initial state.
[pop_many i env] pops [i] cells off the automaton's stack. This is done
via [i] successive invocations of [pop]. Thus, [pop_many 1] is [pop]. The
index [i] must be nonnegative. The time complexity is O(i).
[get i env] returns the parser's [i]-th stack element. The index [i] is
0-based: thus, [get 0] is [top]. If [i] is greater than or equal to the
number of elements in the stack, [None] is returned. The time complexity
is O(i).
[equal env1 env2] tells whether the parser configurations [env1] and
[env2] are equal in the sense that the automaton's current state is the
same in [env1] and [env2] and the stack is *physically* the same in
[env1] and [env2]. If [equal env1 env2] is [true], then the sequence of
the stack elements, as observed via [pop] and [top], must be the same in
[env1] and [env2]. Also, if [equal env1 env2] holds, then the checkpoints
[input_needed env1] and [input_needed env2] must be equivalent. The
function [equal] has time complexity O(1).
These are the start and end positions of the current lookahead token. If
invoked in an initial state, this function returns a pair of twice the
initial position.
When applied to an environment taken from a checkpoint of the form
[AboutToReduce (env, prod)], the function [env_has_default_reduction]
tells whether the reduction that is about to take place is a default
reduction.
[state_has_default_reduction s] tells whether the state [s] has a default
reduction. This includes the case where [s] is an accepting state.
[pop env] returns a new environment, where the parser's top stack cell
has been popped off. (If the stack is empty, [None] is returned.) This
amounts to pretending that the (terminal or nonterminal) symbol that
corresponds to this stack cell has not been read.
[force_reduction prod env] should be called only if in the state [env]
the parser is capable of reducing the production [prod]. If this
condition is satisfied, then this production is reduced, which means that
its semantic action is executed (this can have side effects!) and the
automaton makes a goto (nonterminal) transition. If this condition is not
satisfied, [Invalid_argument _] is raised.
This signature is a fragment of the inspection API that is made available
to the user when [--inspection] is used. This fragment contains type
definitions for symbols.
The type ['a terminal] represents a terminal symbol. The type ['a
nonterminal] represents a nonterminal symbol. In both cases, the index
['a] represents the type of the semantic values associated with this
symbol. The concrete definitions of these types are generated.
The type ['a symbol] represents a terminal or nonterminal symbol. It is
the disjoint union of the types ['a terminal] and ['a nonterminal].
The type [xsymbol] is an existentially quantified version of the type
['a symbol]. This type is useful in situations where the index ['a]
is not statically known.
This signature describes the inspection API that is made available to the
user when [--inspection] is used.
The types of symbols are described above.
An LR(0) item is a pair of a production [prod] and a valid index [i] into
this production. That is, if the length of [rhs prod] is [n], then [i] is
comprised between 0 and [n], inclusive.
Ordering functions.
[incoming_symbol s] is the incoming symbol of the state [s], that is,
the symbol that the parser must recognize before (has recognized when)
it enters the state [s]. This function gives access to the semantic
value [v] stored in a stack element [Element (s, v, _, _)]. Indeed,
by case analysis on the symbol [incoming_symbol s], one discovers the
type ['a] of the value [v].
[rhs prod] is the right-hand side of the production [prod]. This is
a (possibly empty) sequence of (terminal or nonterminal) symbols.
[nullable nt] tells whether the non-terminal symbol [nt] is nullable.
That is, it is true if and only if this symbol produces the empty
word [epsilon].
[foreach_terminal] enumerates the terminal symbols, including [error].
[foreach_terminal_but_error] enumerates the terminal symbols, excluding
[error].
The type [env] is meant to be the same as in [INCREMENTAL_ENGINE].
This signature combines the incremental API and the inspection API.
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
This file defines several types and module types that are used in the
specification of module [Engine].
---------------------------------------------------------------------------
It would be nice if we could keep the structure of stacks and environments
hidden. However, stacks and environments must be accessible to semantic
actions, so the following data structure definitions must be public.
---------------------------------------------------------------------------
A stack is a linked list of cells. A sentinel cell -- which is its own
successor -- is used to mark the bottom of the stack. The sentinel cell
itself is not significant -- it contains dummy values.
The state that we should go back to if we pop this stack cell.
This convention means that the state contained in the top stack cell is
not the current state [env.current]. It also means that the state found
within the sentinel is a dummy -- it is never consulted. This convention
is the same as that adopted by the code-based back-end.
The semantic value associated with the chunk of input that this cell
represents.
The start and end positions of the chunk of input that this cell
represents.
The next cell down in the stack. If this is a self-pointer, then this
cell is the sentinel, and the stack is conceptually empty.
---------------------------------------------------------------------------
A parsing environment contains all of the parser's state (except for the
current program point).
The stack. In [CodeBackend], it is passed around on its own,
whereas, here, it is accessed via the environment.
The current state. In [CodeBackend], it is passed around on its
own, whereas, here, it is accessed via the environment.
---------------------------------------------------------------------------
The type of automaton states.
The type of tokens. These can be thought of as real tokens, that is,
tokens returned by the lexer. They carry a semantic value. This type
does not include the [error] pseudo-token.
The type of terminal symbols. These can be thought of as integer codes.
They do not carry a semantic value. This type does include the [error]
pseudo-token.
The type of nonterminal symbols.
The type of semantic values.
Even though the [error] pseudo-token is not a real token, it is a
terminal symbol. Furthermore, for regularity, it must have a semantic
value.
[foreach_terminal] allows iterating over all terminal symbols.
The type of productions.
If a state [s] has a default reduction on production [prod], then, upon
entering [s], the automaton should reduce [prod] without consulting the
lookahead token. The following function allows determining which states
have default reductions.
This is the automaton's action table. It maps a pair of a state and a
terminal symbol to an action.
This is the automaton's goto table. This table maps a pair of a state
and a nonterminal symbol to a new state. By extension, it also maps a
pair of a state and a production to a new state.
[is_start prod] tells whether the production [prod] is a start production.
The comments below indicate the conventional messages that correspond
to these hooks in the code-based back-end; see [CodeBackend].
If the flag [log] is false, then the logging functions are not called.
If it is [true], then they are called.
Shifting (<terminal>) to state <state>
Reducing a production should be logged either as a reduction
event (for regular productions) or as an acceptance event (for
start productions).
Reducing production <production> / Accepting
Lookahead token is now <terminal> (<pos>-<pos>)
Initiating error handling
Resuming error handling
Handling error in state <state>
---------------------------------------------------------------------------
This signature describes the monolithic (traditional) LR engine.
In this interface, the parser controls the lexer.
An entry point to the engine requires a start state, a lexer, and a lexing
buffer. It either succeeds and produces a semantic value, or fails and
raises [Error].
---------------------------------------------------------------------------
The [start] function is set apart because we do not wish to publish
it as part of the generated [parser.mli] file. Instead, the table
back-end will publish specialized versions of it, with a suitable
type cast.
[start] is an entry point. It requires a start state and a start position
and begins the parsing process. If the lexer is based on an OCaml lexing
buffer, the start position should be [lexbuf.lex_curr_p]. [start] produces
a checkpoint, which usually will be an [InputNeeded] checkpoint. (It could
be [Accepted] if this starting state accepts only the empty word. It could
be [Rejected] if this starting state accepts no word at all.) It does not
raise any exception.
[start s pos] should really produce a checkpoint of type ['a checkpoint],
for a fixed ['a] that depends on the state [s]. We cannot express this, so
we use [semantic_value checkpoint], which is safe. The table back-end uses
[Obj.magic] to produce safe specialized versions of [start].
---------------------------------------------------------------------------
useful for us; hidden from the end user
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
The LR parsing engine.
We would prefer not to expose the definition of the type [env].
However, it must be exposed because some of the code in the
inspection API needs access to the engine's internals; see
[InspectionTableInterpreter]. Everything would be simpler if
--inspection was always ON, but that would lead to bigger parse
tables for everybody.
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
--------------------------------------------------------------------------
[wrap lexer] returns a pair of a new (initially empty) buffer and a lexer
which internally relies on [lexer] and updates [buffer] on the fly whenever
a token is demanded.
[show f buffer] prints the contents of the buffer, producing a string that
is typically of the form "after '%s' and before '%s'". The function [f] is
used to print an element. The buffer MUST be nonempty.
[last buffer] returns the last element of the buffer. The buffer MUST be
nonempty.
--------------------------------------------------------------------------
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
[print s] is supposed to send the string [s] to some output channel.
[print_element e] is supposed to print a representation of the element [e].
This function is optional; if it is not provided, [print_element_as_symbol]
(defined below) is used instead.
Printing a list of symbols.
Printing an element as a symbol. This prints just the symbol
that this element represents; nothing more.
Printing a stack as a list of elements. This function needs an element
printer. It uses [print_element] if provided by the user; otherwise
it uses [print_element_as_symbol]. (Ending with a newline.)
Printing an item. (Ending with a newline.)
Printing a production. (Ending with a newline.)
Printing a summary of the stack and current state. This function just
calls [print_stack] and [print_current_state] in succession.
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
* This module implements infinite arrays. *
* [make x] creates an infinite array, where every slot contains [x]. *
* [get a i] returns the element contained at offset [i] in the array [a].
Slots are numbered 0 and up. *
* [set a i x] sets the element contained at offset [i] in the array
[a] to [x]. Slots are numbered 0 and up. *
* [extent a] is the length of an initial segment of the array [a]
that is sufficiently large to contain all [set] operations ever
performed. In other words, all elements beyond that segment have
the default value.
* [domain a] is a fresh copy of an initial segment of the array [a]
whose length is [extent a].
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
[pack a] turns an array of integers into a packed integer array.
Because the sign bit is the most significant bit, the magnitude of
any negative number is the word size. In other words, [pack] does
not achieve any space savings as soon as [a] contains any negative
numbers, even if they are ``small''.
[get t i] returns the integer stored in the packed array [t] at index [i].
Together, [pack] and [get] satisfy the following property: if the index [i]
is within bounds, then [get (pack a) i] equals [a.(i)].
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
A compressed table is represented as a pair of arrays. The
displacement array is an array of offsets into the data array.
displacement
data
[get ct i j] returns the value found at indices [i] and [j] in the
compressed table [ct]. This function call is permitted only if the
value found at indices [i] and [j] in the original table is
significant -- otherwise, it could fail abruptly.
Together, [compress] and [get] have the property that, if the value
found at indices [i] and [j] in an uncompressed table [t] is
significant, then [get (compress t) i j] is equal to that value.
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
An array of arrays (of possibly different lengths!) can be ``linearized'',
i.e., encoded as a data array (by concatenating all of the little arrays)
and an entry array (which contains offsets into the data array).
data:
entry:
[make a] turns the array of arrays [a] into a linearized array.
[read la i j] reads the linearized array [la] at indices [i] and [j].
Thus, [read (make a) i j] is equivalent to [a.(i).(j)].
[write la i j v] writes the value [v] into the linearized array [la]
at indices [i] and [j].
[length la] is the number of rows of the array [la]. Thus, [length (make
a)] is equivalent to [Array.length a].
[read_row la i] reads the row at index [i], producing a list. Thus,
[read_row (make a) i] is equivalent to [Array.to_list a.(i)].
The following variants read the linearized array via accessors
[get_data : int -> 'a] and [get_entry : int -> int].
get_entry:
i:
get_data:
get_entry:
i:
j:
get_data:
get_entry:
i:
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
This signature defines the format of the parse tables. It is used as
an argument to [TableInterpreter.Make].
This is the parser's type of tokens.
This maps a token to its internal (generation-time) integer code.
This is the integer code for the error pseudo-token.
This maps a token to its semantic value.
The error bitmap does not contain a column for the [#] pseudo-terminal.
Thus, its width is [Terminal.n - 1]. We exploit the fact that the integer
code assigned to [#] is greatest: the fact that the right-most column
in the bitmap is missing does not affect the code for accessing it.
Like the error bitmap, the action table does not contain a column for the
[#] pseudo-terminal.
The number of start productions. A production [prod] is a start
production if and only if [prod < start] holds. This is also the
number of start symbols. A nonterminal symbol [nt] is a start
symbol if and only if [nt < start] holds.
The parser defines its own [Error] exception. This exception can be
raised by semantic actions and caught by the engine, and raised by the
engine towards the final user.
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
This signature defines the format of the tables that are produced (in
addition to the tables described in [TableFormat]) when the command line
switch [--inspection] is enabled. It is used as an argument to
[InspectionTableInterpreter.Make].
The types of symbols.
Some of the tables that follow use encodings of (terminal and
nonterminal) symbols as integers. So, we need functions that
map the integer encoding of a symbol to its algebraic encoding.
The left-hand side of every production already appears in the
signature [TableFormat.TABLES], so we need not repeat it here.
The right-hand side of every production. This a linearized array
of arrays of integers, whose [data] and [entry] components have
been packed. The encoding of symbols as integers in described in
[TableBackend].
A mapping of every (non-initial) state to its LR(0) core.
A mapping of every LR(0) state to its set of LR(0) items. Each item is
represented in its packed form (see [Item]) as an integer. Thus the
mapping is an array of arrays of integers, which is linearized and
packed, like [rhs].
A mapping of every LR(0) state to its incoming symbol, if it has one.
A table that tells which non-terminal symbols are nullable.
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
This functor is invoked inside the generated parser, in [--table] mode. It
produces no code! It simply constructs the types [symbol] and [xsymbol] on
top of the generated types [terminal] and [nonterminal].
This functor is invoked inside the generated parser, in [--table] mode. It
constructs the inspection API on top of the inspection tables described in
[InspectionTableFormat].
****************************************************************************
special exception on linking, as described in the file LICENSE.
****************************************************************************
The exception [Error] is declared within the generated parser. This is
preferable to pre-declaring it here, as it ensures that each parser gets
its own, distinct [Error] exception. This is consistent with the code-based
back-end.
This functor is invoked by the generated parser. | module General : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
As of 2017/03/31 , this module is DEPRECATED . It might be removed in
the future .
the future. *)
[ take n xs ] returns the [ n ] first elements of the list [ xs ] . It is
acceptable for the list [ xs ] to have length less than [ n ] , in
which case [ xs ] itself is returned .
acceptable for the list [xs] to have length less than [n], in
which case [xs] itself is returned. *)
val take: int -> 'a list -> 'a list
[ drop n xs ] returns the list [ xs ] , deprived of its [ n ] first elements .
It is acceptable for the list [ xs ] to have length less than [ n ] , in
which case an empty list is returned .
It is acceptable for the list [xs] to have length less than [n], in
which case an empty list is returned. *)
val drop: int -> 'a list -> 'a list
val uniq: ('a -> 'a -> int) -> 'a list -> 'a list
val weed: ('a -> 'a -> int) -> 'a list -> 'a list
type 'a stream =
'a head Lazy.t
and 'a head =
| Nil
| Cons of 'a * 'a stream
val length: 'a stream -> int
val foldr: ('a -> 'b -> 'b) -> 'a stream -> 'b -> 'b
end
module Convert : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
An ocamlyacc - style , or Menhir - style , parser requires access to
the lexer , which must be parameterized with a lexing buffer , and
to the lexing buffer itself , where it reads position information .
the lexer, which must be parameterized with a lexing buffer, and
to the lexing buffer itself, where it reads position information. *)
type ('token, 'semantic_value) traditional =
(Lexing.lexbuf -> 'token) -> Lexing.lexbuf -> 'semantic_value
type ('token, 'semantic_value) revised =
(unit -> 'token) -> 'semantic_value
Converting a traditional parser , produced by ocamlyacc or Menhir ,
into a revised parser .
into a revised parser. *)
A token of the revised lexer is essentially a triple of a token
of the traditional lexer ( or raw token ) , a start position , and
and end position . The three [ get ] functions are accessors .
of the traditional lexer (or raw token), a start position, and
and end position. The three [get] functions are accessors. *)
We do not require the type [ ' token ] to actually be a triple type .
This enables complex applications where it is a record type with
more than three fields . It also enables simple applications where
positions are of no interest , so [ ' token ] is just [ ' raw_token ]
and [ get_startp ] and [ get_endp ] return dummy positions .
This enables complex applications where it is a record type with
more than three fields. It also enables simple applications where
positions are of no interest, so ['token] is just ['raw_token]
and [get_startp] and [get_endp] return dummy positions. *)
val traditional2revised:
('token -> 'raw_token) ->
('token -> Lexing.position) ->
('token -> Lexing.position) ->
('raw_token, 'semantic_value) traditional ->
('token, 'semantic_value) revised
val revised2traditional:
('raw_token -> Lexing.position -> Lexing.position -> 'token) ->
('token, 'semantic_value) revised ->
('raw_token, 'semantic_value) traditional
module Simplified : sig
val traditional2revised:
('token, 'semantic_value) traditional ->
('token * Lexing.position * Lexing.position, 'semantic_value) revised
val revised2traditional:
('token * Lexing.position * Lexing.position, 'semantic_value) revised ->
('token, 'semantic_value) traditional
end
end
module IncrementalEngine : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
type position = Lexing.position
open General
This signature describes the incremental LR engine .
module type INCREMENTAL_ENGINE = sig
type token
A value of type [ production ] is ( an index for ) a production . The start
productions ( which do not exist in an \mly file , but are constructed by
Menhir internally ) are not part of this type .
productions (which do not exist in an \mly file, but are constructed by
Menhir internally) are not part of this type. *)
type production
[ InputNeeded ] is an intermediate checkpoint . It means that the parser wishes
to read one token before continuing .
to read one token before continuing. *)
[ Shifting ] is an intermediate checkpoint . It means that the parser is taking
a shift transition . It exposes the state of the parser before and after
the transition . The Boolean parameter tells whether the parser intends to
request a new token after this transition . ( It always does , except when
it is about to accept . )
a shift transition. It exposes the state of the parser before and after
the transition. The Boolean parameter tells whether the parser intends to
request a new token after this transition. (It always does, except when
it is about to accept.) *)
type 'a env
type 'a checkpoint = private
| InputNeeded of 'a env
| Shifting of 'a env * 'a env * bool
| AboutToReduce of 'a env * production
| HandlingError of 'a env
| Accepted of 'a
| Rejected
[ offer ] allows the user to resume the parser after it has suspended
itself with a checkpoint of the form [ InputNeeded env ] . [ offer ] expects the
old checkpoint as well as a new token and produces a new checkpoint . It does not
raise any exception .
itself with a checkpoint of the form [InputNeeded env]. [offer] expects the
old checkpoint as well as a new token and produces a new checkpoint. It does not
raise any exception. *)
val offer:
'a checkpoint ->
token * position * position ->
'a checkpoint
val resume:
'a checkpoint ->
'a checkpoint
type supplier =
unit -> token * position * position
val lexer_lexbuf_to_supplier:
(Lexing.lexbuf -> token) ->
Lexing.lexbuf ->
supplier
The functions [ offer ] and [ resume ] are sufficient to write a parser loop .
One can imagine many variations ( which is why we expose these functions
in the first place ! ) . Here , we expose a few variations of the main loop ,
ready for use .
One can imagine many variations (which is why we expose these functions
in the first place!). Here, we expose a few variations of the main loop,
ready for use. *)
val loop: supplier -> 'a checkpoint -> 'a
[ loop_handle succeed fail supplier checkpoint ] begins parsing from
[ checkpoint ] , reading tokens from [ supplier ] . It continues parsing until
it reaches a checkpoint of the form [ Accepted v ] or [ HandlingError env ]
( or [ Rejected ] , but that should not happen , as [ HandlingError _ ] will be
observed first ) . In the former case , it calls [ succeed v ] . In the latter
case , it calls [ fail ] with this checkpoint . It can not raise [ Error ] .
This means that Menhir 's traditional error - handling procedure ( which pops
the stack until a state that can act on the [ error ] token is found ) does
not get a chance to run . Instead , the user can implement her own error
handling code , in the [ fail ] continuation .
[checkpoint], reading tokens from [supplier]. It continues parsing until
it reaches a checkpoint of the form [Accepted v] or [HandlingError env]
(or [Rejected], but that should not happen, as [HandlingError _] will be
observed first). In the former case, it calls [succeed v]. In the latter
case, it calls [fail] with this checkpoint. It cannot raise [Error].
This means that Menhir's traditional error-handling procedure (which pops
the stack until a state that can act on the [error] token is found) does
not get a chance to run. Instead, the user can implement her own error
handling code, in the [fail] continuation. *)
val loop_handle:
('a -> 'answer) ->
('a checkpoint -> 'answer) ->
supplier -> 'a checkpoint -> 'answer
[ loop_handle_undo ] is analogous to [ loop_handle ] , except it passes a pair
of checkpoints to the failure continuation .
The first ( and oldest ) checkpoint is the last [ InputNeeded ] checkpoint that
was encountered before the error was detected . The second ( and newest )
checkpoint is where the error was detected , as in [ loop_handle ] . Going back
to the first checkpoint can be thought of as undoing any reductions that
were performed after seeing the problematic token . ( These reductions must
be default reductions or spurious reductions . )
[ loop_handle_undo ] must initially be applied to an [ InputNeeded ] checkpoint .
The parser 's initial checkpoints satisfy this constraint .
of checkpoints to the failure continuation.
The first (and oldest) checkpoint is the last [InputNeeded] checkpoint that
was encountered before the error was detected. The second (and newest)
checkpoint is where the error was detected, as in [loop_handle]. Going back
to the first checkpoint can be thought of as undoing any reductions that
were performed after seeing the problematic token. (These reductions must
be default reductions or spurious reductions.)
[loop_handle_undo] must initially be applied to an [InputNeeded] checkpoint.
The parser's initial checkpoints satisfy this constraint. *)
val loop_handle_undo:
('a -> 'answer) ->
('a checkpoint -> 'a checkpoint -> 'answer) ->
supplier -> 'a checkpoint -> 'answer
val shifts: 'a checkpoint -> 'a env option
For completeness , one must undo any spurious reductions before carrying out
this test -- that is , one must apply [ acceptable ] to the FIRST checkpoint
that is passed by [ loop_handle_undo ] to its failure continuation .
this test -- that is, one must apply [acceptable] to the FIRST checkpoint
that is passed by [loop_handle_undo] to its failure continuation. *)
val acceptable: 'a checkpoint -> token -> position -> bool
The abstract type [ ' a lr1state ] describes the non - initial states of the
) automaton . The index [ ' a ] represents the type of the semantic value
associated with this state 's incoming symbol .
LR(1) automaton. The index ['a] represents the type of the semantic value
associated with this state's incoming symbol. *)
type 'a lr1state
The states of the LR(1 ) automaton are numbered ( from 0 and up ) .
val number: _ lr1state -> int
val production_index: production -> int
val find_production: int -> production
type element =
| Element: 'a lr1state * 'a * position * position -> element
As of 2017/03/31 , the types [ stream ] and [ stack ] and the function [ stack ]
are DEPRECATED . They might be removed in the future . An alternative way
of inspecting the stack is via the functions [ top ] and [ pop ] .
are DEPRECATED. They might be removed in the future. An alternative way
of inspecting the stack is via the functions [top] and [pop]. *)
element stream
This is the parser 's stack , a stream of elements . This stream is empty if
the parser is in an initial state ; otherwise , it is non - empty . The LR(1 )
automaton 's current state is the one found in the top element of the
stack .
the parser is in an initial state; otherwise, it is non-empty. The LR(1)
automaton's current state is the one found in the top element of the
stack. *)
val top: 'a env -> element option
val pop_many: int -> 'a env -> 'a env option
val get: int -> 'a env -> element option
[ env ] is ( the integer number of ) the automaton 's
current state . This works even if the automaton 's stack is empty , in
which case the current state is an initial state . This number can be
passed as an argument to a [ message ] function generated by [ menhir
--compile - errors ] .
current state. This works even if the automaton's stack is empty, in
which case the current state is an initial state. This number can be
passed as an argument to a [message] function generated by [menhir
--compile-errors]. *)
val current_state_number: 'a env -> int
val equal: 'a env -> 'a env -> bool
val positions: 'a env -> position * position
val env_has_default_reduction: 'a env -> bool
val state_has_default_reduction: _ lr1state -> bool
val pop: 'a env -> 'a env option
val force_reduction: production -> 'a env -> 'a env
[ input_needed env ] returns [ InputNeeded env ] . That is , out of an [ env ]
that might have been obtained via a series of calls to the functions
[ pop ] , [ force_reduction ] , [ feed ] , etc . , it produces a checkpoint , which
can be used to resume normal parsing , by supplying this checkpoint as an
argument to [ offer ] .
that might have been obtained via a series of calls to the functions
[pop], [force_reduction], [feed], etc., it produces a checkpoint, which
can be used to resume normal parsing, by supplying this checkpoint as an
argument to [offer]. *)
This function should be used with some care . It could " mess up the
lookahead " in the sense that it allows parsing to resume in an arbitrary
state [ s ] with an arbitrary lookahead symbol [ t ] , even though Menhir 's
reachability analysis ( menhir --list - errors ) might well think that it is
impossible to reach this particular configuration . If one is using
Menhir 's new error reporting facility , this could cause the parser to
reach an error state for which no error message has been prepared .
lookahead" in the sense that it allows parsing to resume in an arbitrary
state [s] with an arbitrary lookahead symbol [t], even though Menhir's
reachability analysis (menhir --list-errors) might well think that it is
impossible to reach this particular configuration. If one is using
Menhir's new error reporting facility, this could cause the parser to
reach an error state for which no error message has been prepared. *)
val input_needed: 'a env -> 'a checkpoint
end
module type SYMBOLS = sig
type 'a terminal
type 'a nonterminal
type 'a symbol =
| T : 'a terminal -> 'a symbol
| N : 'a nonterminal -> 'a symbol
type xsymbol =
| X : 'a symbol -> xsymbol
end
module type INSPECTION = sig
include SYMBOLS
The type [ ' a lr1state ] is meant to be the same as in [ INCREMENTAL_ENGINE ] .
type 'a lr1state
The type [ production ] is meant to be the same as in [ INCREMENTAL_ENGINE ] .
It represents a production of the grammar . A production can be examined
via the functions [ lhs ] and [ rhs ] below .
It represents a production of the grammar. A production can be examined
via the functions [lhs] and [rhs] below. *)
type production
type item =
production * int
val compare_terminals: _ terminal -> _ terminal -> int
val compare_nonterminals: _ nonterminal -> _ nonterminal -> int
val compare_symbols: xsymbol -> xsymbol -> int
val compare_productions: production -> production -> int
val compare_items: item -> item -> int
val incoming_symbol: 'a lr1state -> 'a symbol
[ items s ] is the set of the LR(0 ) items in the LR(0 ) core of the )
state [ s ] . This set is not epsilon - closed . This set is presented as a
list , in an arbitrary order .
state [s]. This set is not epsilon-closed. This set is presented as a
list, in an arbitrary order. *)
val items: _ lr1state -> item list
[ lhs prod ] is the left - hand side of the production [ prod ] . This is
always a non - terminal symbol .
always a non-terminal symbol. *)
val lhs: production -> xsymbol
val rhs: production -> xsymbol list
val nullable: _ nonterminal -> bool
[ first nt t ] tells whether the FIRST set of the nonterminal symbol [ nt ]
contains the terminal symbol [ t ] . That is , it is true if and only if
[ nt ] produces a word that begins with [ t ] .
contains the terminal symbol [t]. That is, it is true if and only if
[nt] produces a word that begins with [t]. *)
val first: _ nonterminal -> _ terminal -> bool
[ xfirst ] is analogous to [ first ] , but expects a first argument of type
[ xsymbol ] instead of [ _ terminal ] .
[xsymbol] instead of [_ terminal]. *)
val xfirst: xsymbol -> _ terminal -> bool
val foreach_terminal: (xsymbol -> 'a -> 'a) -> 'a -> 'a
val foreach_terminal_but_error: (xsymbol -> 'a -> 'a) -> 'a -> 'a
type 'a env
[ feed symbol startp env ] causes the parser to consume the
( terminal or nonterminal ) symbol [ symbol ] , accompanied with the semantic
value [ semv ] and with the start and end positions [ startp ] and [ endp ] .
Thus , the automaton makes a transition , and reaches a new state . The
stack grows by one cell . This operation is permitted only if the current
state ( as determined by [ env ] ) has an outgoing transition labeled with
[ symbol ] . Otherwise , [ Invalid_argument _ ] is raised .
(terminal or nonterminal) symbol [symbol], accompanied with the semantic
value [semv] and with the start and end positions [startp] and [endp].
Thus, the automaton makes a transition, and reaches a new state. The
stack grows by one cell. This operation is permitted only if the current
state (as determined by [env]) has an outgoing transition labeled with
[symbol]. Otherwise, [Invalid_argument _] is raised. *)
val feed: 'a symbol -> position -> 'a -> position -> 'b env -> 'b env
end
module type EVERYTHING = sig
include INCREMENTAL_ENGINE
include INSPECTION
with type 'a lr1state := 'a lr1state
with type production := production
with type 'a env := 'a env
end
end
module EngineTypes : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
type ('state, 'semantic_value) stack = {
state: 'state;
semv: 'semantic_value;
startp: Lexing.position;
endp: Lexing.position;
next: ('state, 'semantic_value) stack;
}
type ('state, 'semantic_value, 'token) env = {
If this flag is true , then the first component of [ env.triple ] should
be ignored , as it has been logically overwritten with the [ error ]
pseudo - token .
be ignored, as it has been logically overwritten with the [error]
pseudo-token. *)
error: bool;
The last token that was obtained from the lexer , together with its start
and end positions . Warning : before the first call to the lexer has taken
place , a dummy ( and possibly invalid ) token is stored here .
and end positions. Warning: before the first call to the lexer has taken
place, a dummy (and possibly invalid) token is stored here. *)
triple: 'token * Lexing.position * Lexing.position;
stack: ('state, 'semantic_value) stack;
current: 'state;
}
This signature describes the parameters that must be supplied to the LR
engine .
engine. *)
module type TABLE = sig
type state
States are numbered .
val number: state -> int
type token
type terminal
type nonterminal
type semantic_value
A token is conceptually a pair of a ( non-[error ] ) terminal symbol and
a semantic value . The following two functions are the pair projections .
a semantic value. The following two functions are the pair projections. *)
val token2terminal: token -> terminal
val token2value: token -> semantic_value
val error_terminal: terminal
val error_value: semantic_value
val foreach_terminal: (terminal -> 'a -> 'a) -> 'a -> 'a
type production
val production_index: production -> int
val find_production: int -> production
Instead of returning a value of a sum type -- either [ DefRed prod ] , or
[ NoDefRed ] -- it accepts two continuations , and invokes just one of
them . This mechanism allows avoiding a memory allocation .
[NoDefRed] -- it accepts two continuations, and invokes just one of
them. This mechanism allows avoiding a memory allocation. *)
val default_reduction:
state ->
('env -> production -> 'answer) ->
('env -> 'answer) ->
'env -> 'answer
An LR automaton can normally take three kinds of actions : shift , reduce ,
or fail . ( Acceptance is a particular case of reduction : it consists in
reducing a start production . )
or fail. (Acceptance is a particular case of reduction: it consists in
reducing a start production.) *)
There are two variants of the shift action . [ shift / discard s ] instructs
the automaton to discard the current token , request a new one from the
lexer , and move to state [ s ] . [ shift / nodiscard s ] instructs it to move to
state [ s ] without requesting a new token . This instruction should be used
when [ s ] has a default reduction on [ # ] . See [ CodeBackend.gettoken ] for
details .
the automaton to discard the current token, request a new one from the
lexer, and move to state [s]. [shift/nodiscard s] instructs it to move to
state [s] without requesting a new token. This instruction should be used
when [s] has a default reduction on [#]. See [CodeBackend.gettoken] for
details. *)
Instead of returning a value of a sum type -- one of shift / discard ,
shift / nodiscard , reduce , or fail -- this function accepts three
continuations , and invokes just one them . This mechanism allows avoiding
a memory allocation .
shift/nodiscard, reduce, or fail -- this function accepts three
continuations, and invokes just one them. This mechanism allows avoiding
a memory allocation. *)
In summary , the parameters to [ action ] are as follows :
- the first two parameters , a state and a terminal symbol , are used to
look up the action table ;
- the next parameter is the semantic value associated with the above
terminal symbol ; it is not used , only passed along to the shift
continuation , as explained below ;
- the shift continuation expects an environment ; a flag that tells
whether to discard the current token ; the terminal symbol that
is being shifted ; its semantic value ; and the target state of
the transition ;
- the reduce continuation expects an environment and a production ;
- the fail continuation expects an environment ;
- the last parameter is the environment ; it is not used , only passed
along to the selected continuation .
- the first two parameters, a state and a terminal symbol, are used to
look up the action table;
- the next parameter is the semantic value associated with the above
terminal symbol; it is not used, only passed along to the shift
continuation, as explained below;
- the shift continuation expects an environment; a flag that tells
whether to discard the current token; the terminal symbol that
is being shifted; its semantic value; and the target state of
the transition;
- the reduce continuation expects an environment and a production;
- the fail continuation expects an environment;
- the last parameter is the environment; it is not used, only passed
along to the selected continuation. *)
val action:
state ->
terminal ->
semantic_value ->
('env -> bool -> terminal -> semantic_value -> state -> 'answer) ->
('env -> production -> 'answer) ->
('env -> 'answer) ->
'env -> 'answer
The function [ goto_nt ] can be applied to [ s ] and [ nt ] ONLY if the state
[ s ] has an outgoing transition labeled [ nt ] . Otherwise , its result is
undefined . Similarly , the call [ goto_prod prod s ] is permitted ONLY if
the state [ s ] has an outgoing transition labeled with the nonterminal
symbol [ lhs prod ] . The function [ maybe_goto_nt ] involves an additional
dynamic check and CAN be called even if there is no outgoing transition .
[s] has an outgoing transition labeled [nt]. Otherwise, its result is
undefined. Similarly, the call [goto_prod prod s] is permitted ONLY if
the state [s] has an outgoing transition labeled with the nonterminal
symbol [lhs prod]. The function [maybe_goto_nt] involves an additional
dynamic check and CAN be called even if there is no outgoing transition. *)
val goto_nt : state -> nonterminal -> state
val goto_prod: state -> production -> state
val maybe_goto_nt: state -> nonterminal -> state option
val is_start: production -> bool
By convention , a semantic action is responsible for :
1 . fetching whatever semantic values and positions it needs off the stack ;
2 . popping an appropriate number of cells off the stack , as dictated
by the length of the right - hand side of the production ;
3 . computing a new semantic value , as well as new start and end positions ;
4 . pushing a new stack cell , which contains the three values
computed in step 3 ;
5 . returning the new stack computed in steps 2 and 4 .
Point 1 is essentially forced upon us : if semantic values were fetched
off the stack by this interpreter , then the calling convention for
semantic actions would be variadic : not all semantic actions would have
the same number of arguments . The rest follows rather naturally .
1. fetching whatever semantic values and positions it needs off the stack;
2. popping an appropriate number of cells off the stack, as dictated
by the length of the right-hand side of the production;
3. computing a new semantic value, as well as new start and end positions;
4. pushing a new stack cell, which contains the three values
computed in step 3;
5. returning the new stack computed in steps 2 and 4.
Point 1 is essentially forced upon us: if semantic values were fetched
off the stack by this interpreter, then the calling convention for
semantic actions would be variadic: not all semantic actions would have
the same number of arguments. The rest follows rather naturally. *)
Semantic actions are allowed to raise [ Error ] .
exception Error
type semantic_action =
(state, semantic_value, token) env -> (state, semantic_value) stack
val semantic_action: production -> semantic_action
[ may_reduce state prod ] tests whether the state [ state ] is capable of
reducing the production [ prod ] . This function is currently costly and
is not used by the core LR engine . It is used in the implementation
of certain functions , such as [ force_reduction ] , which allow the engine
to be driven programmatically .
reducing the production [prod]. This function is currently costly and
is not used by the core LR engine. It is used in the implementation
of certain functions, such as [force_reduction], which allow the engine
to be driven programmatically. *)
val may_reduce: state -> production -> bool
The LR engine requires a number of hooks , which are used for logging .
val log : bool
module Log : sig
State % d :
val state: state -> unit
val shift: terminal -> state -> unit
val reduce_or_accept: production -> unit
val lookahead_token: terminal -> Lexing.position -> Lexing.position -> unit
val initiating_error_handling: unit -> unit
val resuming_error_handling: unit -> unit
val handling_error: state -> unit
end
end
module type MONOLITHIC_ENGINE = sig
type state
type token
type semantic_value
exception Error
val entry:
state ->
(Lexing.lexbuf -> token) ->
Lexing.lexbuf ->
semantic_value
end
The following signatures describe the incremental LR engine .
First , see [ INCREMENTAL_ENGINE ] in the file [ IncrementalEngine.ml ] .
module type INCREMENTAL_ENGINE_START = sig
type state
type semantic_value
type 'a checkpoint
val start:
state ->
Lexing.position ->
semantic_value checkpoint
end
This signature describes the LR engine , which combines the monolithic
and incremental interfaces .
and incremental interfaces. *)
module type ENGINE = sig
include MONOLITHIC_ENGINE
include IncrementalEngine.INCREMENTAL_ENGINE
with type token := token
include INCREMENTAL_ENGINE_START
with type state := state
and type semantic_value := semantic_value
and type 'a checkpoint := 'a checkpoint
end
end
module Engine : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
open EngineTypes
module Make (T : TABLE)
: ENGINE
with type state = T.state
and type token = T.token
and type semantic_value = T.semantic_value
and type production = T.production
and type 'a env = (T.state, T.semantic_value, T.token) EngineTypes.env
end
module ErrorReports : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
The following functions help keep track of the start and end positions of
the last two tokens in a two - place buffer . This is used to nicely display
where a syntax error took place .
the last two tokens in a two-place buffer. This is used to nicely display
where a syntax error took place. *)
type 'a buffer
open Lexing
val wrap:
(lexbuf -> 'token) ->
(position * position) buffer * (lexbuf -> 'token)
val show: ('a -> string) -> 'a buffer -> string
val last: 'a buffer -> 'a
end
module Printers : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
This module is part of MenhirLib .
module Make
(I : IncrementalEngine.EVERYTHING)
(User : sig
val print: string -> unit
[ s ] is supposed to print a representation of the symbol [ s ] .
val print_symbol: I.xsymbol -> unit
val print_element: (I.element -> unit) option
end)
: sig
open I
val print_symbols: xsymbol list -> unit
val print_element_as_symbol: element -> unit
val print_stack: 'a env -> unit
val print_item: item -> unit
val print_production: production -> unit
Printing the current LR(1 ) state . The current state is first displayed
as a number ; then the list of its LR(0 ) items is printed . ( Ending with
a newline . )
as a number; then the list of its LR(0) items is printed. (Ending with
a newline.) *)
val print_current_state: 'a env -> unit
val print_env: 'a env -> unit
end
end
module InfiniteArray : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
type 'a t
val make: 'a -> 'a t
val get: 'a t -> int -> 'a
val set: 'a t -> int -> 'a -> unit
val extent: 'a t -> int
val domain: 'a t -> 'a array
end
module PackedIntArray : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
A packed integer array is represented as a pair of an integer [ k ] and
a string [ s ] . The integer [ k ] is the number of bits per integer that we
use . The string [ s ] is just an array of bits , which is read in 8 - bit
chunks .
a string [s]. The integer [k] is the number of bits per integer that we
use. The string [s] is just an array of bits, which is read in 8-bit
chunks. *)
The ocaml programming language treats string literals and array literals
in slightly different ways : the former are statically allocated , while
the latter are dynamically allocated . ( This is rather arbitrary . ) In the
context of Menhir 's table - based back - end , where compact , immutable
integer arrays are needed , ocaml strings are preferable to ocaml arrays .
in slightly different ways: the former are statically allocated, while
the latter are dynamically allocated. (This is rather arbitrary.) In the
context of Menhir's table-based back-end, where compact, immutable
integer arrays are needed, ocaml strings are preferable to ocaml arrays. *)
type t =
int * string
val pack: int array -> t
val get: t -> int -> int
[ get1 t i ] returns the integer stored in the packed array [ t ] at index [ i ] .
It assumes ( and does not check ) that the array 's bit width is [ 1 ] . The
parameter [ t ] is just a string .
It assumes (and does not check) that the array's bit width is [1]. The
parameter [t] is just a string. *)
val get1: string -> int -> int
[ unflatten1 ( n , data ) i j ] accesses the two - dimensional bitmap
represented by [ ( n , data ) ] at indices [ i ] and [ j ] . The integer
[ n ] is the width of the bitmap ; the string [ data ] is the second
component of the packed array obtained by encoding the table as
a one - dimensional array .
represented by [(n, data)] at indices [i] and [j]. The integer
[n] is the width of the bitmap; the string [data] is the second
component of the packed array obtained by encoding the table as
a one-dimensional array. *)
val unflatten1: int * string -> int -> int -> int
end
module RowDisplacement : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
This module compresses a two - dimensional table , where some values
are considered insignificant , via row displacement .
are considered insignificant, via row displacement. *)
type 'a table =
[ compress equal insignificant dummy m n t ] turns the two - dimensional table
[ t ] into a compressed table . The parameter [ equal ] is equality of data
values . The parameter [ wildcard ] tells which data values are insignificant ,
and can thus be overwritten with other values . The parameter [ dummy ] is
used to fill holes in the data array . [ m ] and [ n ] are the integer
dimensions of the table [ t ] .
[t] into a compressed table. The parameter [equal] is equality of data
values. The parameter [wildcard] tells which data values are insignificant,
and can thus be overwritten with other values. The parameter [dummy] is
used to fill holes in the data array. [m] and [n] are the integer
dimensions of the table [t]. *)
val compress:
('a -> 'a -> bool) ->
('a -> bool) ->
'a ->
int -> int ->
'a array array ->
'a table
val get:
'a table ->
int -> int ->
'a
[ getget ] is a variant of [ get ] which only requires read access ,
via accessors , to the two components of the table .
via accessors, to the two components of the table. *)
val getget:
('displacement -> int -> int) ->
('data -> int -> 'a) ->
'displacement * 'data ->
int -> int ->
'a
end
module LinearizedArray : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
type 'a t =
val make: 'a array array -> 'a t
val read: 'a t -> int -> int -> 'a
val write: 'a t -> int -> int -> 'a -> unit
val length: 'a t -> int
[ row_length la i ] is the length of the row at index [ i ] in the linearized
array [ la ] . Thus , [ ( make a ) i ] is equivalent to [ Array.length
a.(i ) ] .
array [la]. Thus, [row_length (make a) i] is equivalent to [Array.length
a.(i)]. *)
val row_length: 'a t -> int -> int
val read_row: 'a t -> int -> 'a list
val row_length_via:
int
val read_via:
'a
val read_row_via:
'a list
end
module TableFormat : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
module type TABLES = sig
type token
val token2terminal: token -> int
val error_terminal: int
val token2value: token -> Obj.t
Traditionally , an LR automaton is described by two tables , namely , an
action table and a goto table . See , for instance , the book .
The action table is a two - dimensional matrix that maps a state and a
lookahead token to an action . An action is one of : shift to a certain
state , reduce a certain production , accept , or fail .
The goto table is a two - dimensional matrix that maps a state and a
non - terminal symbol to either a state or undefined . By construction , this
table is sparse : its undefined entries are never looked up . A compression
technique is free to overlap them with other entries .
In Menhir , things are slightly different . If a state has a default
reduction on token [ # ] , then that reduction must be performed without
consulting the lookahead token . As a result , we must first determine
whether that is the case , before we can obtain a lookahead token and use it
as an index in the action table .
Thus , Menhir 's tables are as follows .
A one - dimensional default reduction table maps a state to either ` ` no
default reduction '' ( encoded as : 0 ) or ` ` by default , reduce prod ''
( encoded as : 1 + prod ) . The action table is looked up only when there
is no default reduction .
action table and a goto table. See, for instance, the Dragon book.
The action table is a two-dimensional matrix that maps a state and a
lookahead token to an action. An action is one of: shift to a certain
state, reduce a certain production, accept, or fail.
The goto table is a two-dimensional matrix that maps a state and a
non-terminal symbol to either a state or undefined. By construction, this
table is sparse: its undefined entries are never looked up. A compression
technique is free to overlap them with other entries.
In Menhir, things are slightly different. If a state has a default
reduction on token [#], then that reduction must be performed without
consulting the lookahead token. As a result, we must first determine
whether that is the case, before we can obtain a lookahead token and use it
as an index in the action table.
Thus, Menhir's tables are as follows.
A one-dimensional default reduction table maps a state to either ``no
default reduction'' (encoded as: 0) or ``by default, reduce prod''
(encoded as: 1 + prod). The action table is looked up only when there
is no default reduction. *)
val default_reduction: PackedIntArray.t
Menhir follows , and Heuft , who point out that , although the
action table is not sparse by nature ( i.e. , the error entries are
significant ) , it can be made sparse by first factoring out a binary error
matrix , then replacing the error entries in the action table with undefined
entries . Thus :
A two - dimensional error bitmap maps a state and a terminal to either
` ` fail '' ( encoded as : 0 ) or ` ` do not fail '' ( encoded as : 1 ) . The action
table , which is now sparse , is looked up only in the latter case .
action table is not sparse by nature (i.e., the error entries are
significant), it can be made sparse by first factoring out a binary error
matrix, then replacing the error entries in the action table with undefined
entries. Thus:
A two-dimensional error bitmap maps a state and a terminal to either
``fail'' (encoded as: 0) or ``do not fail'' (encoded as: 1). The action
table, which is now sparse, is looked up only in the latter case. *)
The error bitmap is flattened into a one - dimensional table ; its width is
recorded so as to allow indexing . The table is then compressed via
[ PackedIntArray ] . The bit width of the resulting packed array must be
[ 1 ] , so it is not explicitly recorded .
recorded so as to allow indexing. The table is then compressed via
[PackedIntArray]. The bit width of the resulting packed array must be
[1], so it is not explicitly recorded. *)
second component of [ PackedIntArray.t ]
A two - dimensional action table maps a state and a terminal to one of
` ` shift to state s and discard the current token '' ( encoded as : s | 10 ) ,
` ` shift to state s without discarding the current token '' ( encoded as : s |
11 ) , or ` ` reduce prod '' ( encoded as : prod | 01 ) .
``shift to state s and discard the current token'' (encoded as: s | 10),
``shift to state s without discarding the current token'' (encoded as: s |
11), or ``reduce prod'' (encoded as: prod | 01). *)
The action table is first compressed via [ RowDisplacement ] , then packed
via [ PackedIntArray ] .
via [PackedIntArray]. *)
val action: PackedIntArray.t * PackedIntArray.t
A one - dimensional lhs table maps a production to its left - hand side ( a
non - terminal symbol ) .
non-terminal symbol). *)
val lhs: PackedIntArray.t
A two - dimensional goto table maps a state and a non - terminal symbol to
either undefined ( encoded as : 0 ) or a new state s ( encoded as : 1 + s ) .
either undefined (encoded as: 0) or a new state s (encoded as: 1 + s). *)
The goto table is first compressed via [ RowDisplacement ] , then packed
via [ PackedIntArray ] .
via [PackedIntArray]. *)
val goto: PackedIntArray.t * PackedIntArray.t
val start: int
A one - dimensional semantic action table maps productions to semantic
actions . The calling convention for semantic actions is described in
[ EngineTypes ] . This table contains ONLY NON - START PRODUCTIONS , so the
indexing is off by [ start ] . Be careful .
actions. The calling convention for semantic actions is described in
[EngineTypes]. This table contains ONLY NON-START PRODUCTIONS, so the
indexing is off by [start]. Be careful. *)
val semantic_action: ((int, Obj.t, token) EngineTypes.env ->
(int, Obj.t) EngineTypes.stack) array
exception Error
The parser indicates whether to generate a trace . Generating a
trace requires two extra tables , which respectively map a
terminal symbol and a production to a string .
trace requires two extra tables, which respectively map a
terminal symbol and a production to a string. *)
val trace: (string array * string array) option
end
end
module InspectionTableFormat : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
module type TABLES = sig
include IncrementalEngine.SYMBOLS
The type [ ' a lr1state ] describes an LR(1 ) state . The generated parser defines
it internally as [ int ] .
it internally as [int]. *)
type 'a lr1state
val terminal: int -> xsymbol
val nonterminal: int -> xsymbol
val rhs: PackedIntArray.t * PackedIntArray.t
val lr0_core: PackedIntArray.t
val lr0_items: PackedIntArray.t * PackedIntArray.t
val lr0_incoming: PackedIntArray.t
val nullable: string
This is a packed int array of bit width 1 . It can be read
using [ PackedIntArray.get1 ] .
using [PackedIntArray.get1]. *)
A two - table dimensional table , indexed by a nonterminal symbol and
by a terminal symbol ( other than [ # ] ) , encodes the FIRST sets .
by a terminal symbol (other than [#]), encodes the FIRST sets. *)
second component of [ PackedIntArray.t ]
end
end
module InspectionTableInterpreter : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
module Symbols (T : sig
type 'a terminal
type 'a nonterminal
end)
: IncrementalEngine.SYMBOLS
with type 'a terminal := 'a T.terminal
and type 'a nonterminal := 'a T.nonterminal
module Make
(TT : TableFormat.TABLES)
(IT : InspectionTableFormat.TABLES
with type 'a lr1state = int)
(ET : EngineTypes.TABLE
with type terminal = int
and type nonterminal = int
and type semantic_value = Obj.t)
(E : sig
type 'a env = (ET.state, ET.semantic_value, ET.token) EngineTypes.env
end)
: IncrementalEngine.INSPECTION
with type 'a terminal := 'a IT.terminal
and type 'a nonterminal := 'a IT.nonterminal
and type 'a lr1state := 'a IT.lr1state
and type production := int
and type 'a env := 'a E.env
end
module TableInterpreter : sig
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU Library General Public License version 2 , with a
This module provides a thin decoding layer for the generated tables , thus
providing an API that is suitable for use by [ Engine . Make ] . It is part of
[ MenhirLib ] .
providing an API that is suitable for use by [Engine.Make]. It is part of
[MenhirLib]. *)
module MakeEngineTable
(T : TableFormat.TABLES)
: EngineTypes.TABLE
with type state = int
and type token = T.token
and type semantic_value = Obj.t
and type production = int
and type terminal = int
and type nonterminal = int
end
module StaticVersion : sig
val require_20180905 : unit
end
|
f517eac8eef0000e81d596749341e9a584218ceed9994438015f6b777453d4c1 | facebook/pyre-check | taintTransformOperation.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(* This module implements common operations on taint transforms.
* Most importantly, it implements adding transforms on a source or sink.
*
* This is intentionally in a separate file to have access to both `Sources` and
* `Sinks`, even though they use `TaintTransforms.t`. This avoids a cyclic
* dependency.
*)
open Core
open Pyre
module InsertLocation = struct
type t =
| Front
| Back
[@@deriving show]
end
type 'a kind_transforms =
| NonTransformable of 'a
| Base of 'a
| Transformed of {
local: TaintTransforms.t;
global: TaintTransforms.t;
base: 'a;
}
module type KIND_ARG = sig
type t
val deconstruct : t -> t kind_transforms
val order : TaintTransforms.Order.t
val preserve_sanitize_sources : t -> bool
val preserve_sanitize_sinks : t -> bool
val is_tito : t -> bool
val base_as_sanitizer : t -> SanitizeTransform.t option
val make_transform : local:TaintTransforms.t -> global:TaintTransforms.t -> base:t -> t
val matching_sanitize_transforms
: taint_configuration:TaintConfiguration.Heap.t ->
named_transforms:TaintTransform.t list ->
base:t ->
SourceSinkFilter.MatchingSanitizeTransforms.t option
end
module Make (Kind : KIND_ARG) = struct
let prepend_name_transform
~taint_configuration:
({ TaintConfiguration.Heap.source_sink_filter; _ } as taint_configuration)
~base
~named_transforms
transforms
named_transform
=
(* Check if the taint can ever match a rule. This is for performance as well
* as convergence, since we might have infinite chains T:T:T:T:... *)
let named_transforms = named_transform :: named_transforms in
let should_keep =
if Kind.is_tito base then
TaintTransforms.Set.mem
named_transforms
(SourceSinkFilter.possible_tito_transforms source_sink_filter)
else
Kind.matching_sanitize_transforms ~taint_configuration ~named_transforms ~base
|> Option.is_some
in
if not should_keep then
None
else
let transforms =
if not (Kind.is_tito base) then
(* Previous sanitize transforms are invalidated,
* so we can remove them from the local part. *)
snd (TaintTransforms.split_sanitizers transforms)
else
We can not remove existing sanitizers from tito , since transforms
* are applied from left to right on sources and right to left on sinks .
*
* For instance , ` NotSource[A]:Transform : NotSink[X]:LocalReturn ` will
* sanitize both ` Source[A ] ` and ` Sink[X ] ` .
* We need to preserve all sanitizers .
* are applied from left to right on sources and right to left on sinks.
*
* For instance, `NotSource[A]:Transform:NotSink[X]:LocalReturn` will
* sanitize both `Source[A]` and `Sink[X]`.
* We need to preserve all sanitizers.
*)
transforms
in
Some (named_transform :: transforms)
let preserve_sanitizers ~base sanitizers =
let sanitizers =
if not (Kind.preserve_sanitize_sources base) then
{ sanitizers with SanitizeTransformSet.sources = SanitizeTransform.SourceSet.empty }
else
sanitizers
in
let sanitizers =
if not (Kind.preserve_sanitize_sinks base) then
{ sanitizers with SanitizeTransformSet.sinks = SanitizeTransform.SinkSet.empty }
else
sanitizers
in
sanitizers
let prepend_sanitize_transforms
~taint_configuration
~base
~named_transforms
~global_sanitizers
transforms
({ SanitizeTransformSet.sources = sanitizer_sources; sinks = sanitizer_sinks } as sanitizers)
=
(* Check if applying that sanitizer removes the taint. *)
match Kind.base_as_sanitizer base with
| _ when SanitizeTransform.SourceSet.is_all sanitizer_sources -> None
| _ when SanitizeTransform.SinkSet.is_all sanitizer_sinks -> None
| Some base when List.is_empty named_transforms && SanitizeTransformSet.mem sanitizers base ->
None
| _ ->
let sanitizers = preserve_sanitizers ~base sanitizers in
(* Check if this is a no-op because those sanitizers already exist in the global part. *)
let sanitizers = SanitizeTransformSet.diff sanitizers global_sanitizers in
if SanitizeTransformSet.is_empty sanitizers then
Some transforms
else
let matching_kinds =
if not (Kind.is_tito base) then
Kind.matching_sanitize_transforms ~taint_configuration ~named_transforms ~base
else
None
in
(* Remove sanitizers that cannot affect this kind. *)
let sanitizers =
match matching_kinds with
| Some { transforms = matching_kinds; _ } ->
SanitizeTransformSet.meet matching_kinds sanitizers
| None -> sanitizers
in
if SanitizeTransformSet.is_empty sanitizers then
Some transforms
else (* Add sanitizers to the existing sanitizers in the local part. *)
let existing_sanitizers, rest = TaintTransforms.split_sanitizers transforms in
let sanitizers = SanitizeTransformSet.join sanitizers existing_sanitizers in
(* Check if the new taint can ever match a rule. *)
let should_keep =
match matching_kinds with
| _ when Kind.is_tito base -> true
| None -> false
| Some { sanitizable = false; _ } -> true
| Some { transforms = matching_transforms; sanitizable = true } ->
not
(SanitizeTransformSet.less_or_equal
~left:matching_transforms
~right:(SanitizeTransformSet.join sanitizers global_sanitizers))
in
if should_keep then
Some (TaintTransform.Sanitize sanitizers :: rest)
else
None
let add_sanitize_transforms_internal
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
sanitizers
=
match insert_location with
| InsertLocation.Front ->
prepend_sanitize_transforms
~taint_configuration
~base
~named_transforms
~global_sanitizers
transforms
sanitizers
| InsertLocation.Back ->
if SanitizeTransformSet.is_empty global_sanitizers then
match
prepend_sanitize_transforms
~taint_configuration
~base
~named_transforms
~global_sanitizers
(List.rev transforms)
sanitizers
with
| None -> None
| Some list -> Some (List.rev list)
else
failwith "Unable to insert sanitizers in the back when there exist global sanitizers"
let get_global_sanitizers ~local ~global =
if List.exists local ~f:TaintTransform.is_named_transform then
SanitizeTransformSet.empty
else
fst (TaintTransforms.split_sanitizers global)
let get_named_transforms ~local ~global =
List.filter ~f:TaintTransform.is_named_transform local
@ List.filter ~f:TaintTransform.is_named_transform global
let add_sanitize_transforms ~taint_configuration ~base ~local ~global ~insert_location sanitizers =
let global_sanitizers = get_global_sanitizers ~local ~global in
let named_transforms = get_named_transforms ~local ~global in
add_sanitize_transforms_internal
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
local
sanitizers
type add_transform_result = {
(* None represents a sanitized taint. *)
transforms: TaintTransform.t list option;
named_transforms: TaintTransform.t list;
global_sanitizers: SanitizeTransformSet.t;
}
let add_transform
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
= function
| TaintTransform.Named _ as named_transform ->
{
transforms =
prepend_name_transform
~taint_configuration
~base
~named_transforms
transforms
named_transform;
named_transforms = named_transform :: named_transforms;
global_sanitizers = SanitizeTransformSet.empty;
}
| TaintTransform.Sanitize sanitizers ->
let transforms =
add_sanitize_transforms_internal
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
sanitizers
in
{ transforms; named_transforms; global_sanitizers }
let add_backward_into_forward_transforms
~taint_configuration
~base
~local
~global
~insert_location
~to_add
=
let rec add ({ transforms; named_transforms; global_sanitizers } as sofar) to_add =
match transforms, to_add with
| None, _
| Some _, [] ->
sofar
| Some transforms, head :: tail ->
add
(add_transform
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
head)
tail
in
let global_sanitizers = get_global_sanitizers ~local ~global in
let named_transforms = get_named_transforms ~local ~global in
let { transforms; _ } =
add { transforms = Some local; named_transforms; global_sanitizers } to_add
in
transforms
let add_backward_into_backward_transforms
~taint_configuration
~base
~local
~global
~insert_location
~to_add
=
let rec add sofar = function
| [] -> sofar
| head :: tail -> (
match add sofar tail with
| { transforms = None; _ } as sofar -> sofar
| { transforms = Some transforms; named_transforms; global_sanitizers } ->
add_transform
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
head)
in
let global_sanitizers = get_global_sanitizers ~local ~global in
let named_transforms = get_named_transforms ~local ~global in
let { transforms; _ } =
add { transforms = Some local; named_transforms; global_sanitizers } to_add
in
transforms
let add_transforms
~taint_configuration
~base
~local
~global
~order
~insert_location
~to_add
~to_add_order
=
match order, to_add_order with
| TaintTransforms.Order.Forward, TaintTransforms.Order.Backward ->
add_backward_into_forward_transforms
~taint_configuration
~base
~local
~global
~insert_location
~to_add
| TaintTransforms.Order.Backward, TaintTransforms.Order.Backward ->
add_backward_into_backward_transforms
~taint_configuration
~base
~local
~global
~insert_location
~to_add
| _ ->
Format.asprintf
"unsupported: add_transforms ~order:%a ~to_add_order:%a"
TaintTransforms.Order.pp
order
TaintTransforms.Order.pp
to_add_order
|> failwith
let of_sanitize_transforms ~taint_configuration ~base sanitizers =
prepend_sanitize_transforms
~taint_configuration
~base
~named_transforms:[]
~global_sanitizers:SanitizeTransformSet.empty
[]
sanitizers
let apply_sanitize_transforms ~taint_configuration transforms insert_location kind =
match Kind.deconstruct kind with
| NonTransformable kind -> Some kind
| Base base ->
of_sanitize_transforms ~taint_configuration ~base transforms
>>| fun local -> Kind.make_transform ~local ~global:TaintTransforms.empty ~base
| Transformed { local; global; base } ->
add_sanitize_transforms
~taint_configuration
~base
~local
~global
~insert_location
transforms
>>| fun local -> Kind.make_transform ~local ~global ~base
let apply_transforms ~taint_configuration transforms insert_location order kind =
match Kind.deconstruct kind with
| NonTransformable kind -> Some kind
| Base base ->
add_transforms
~taint_configuration
~base
~local:TaintTransforms.empty
~global:TaintTransforms.empty
~order:Kind.order
~insert_location
~to_add:transforms
~to_add_order:order
>>| fun local -> Kind.make_transform ~local ~global:TaintTransforms.empty ~base
| Transformed { local; global; base } ->
add_transforms
~taint_configuration
~base
~local
~global
~order:Kind.order
~insert_location
~to_add:transforms
~to_add_order:order
>>| fun local -> Kind.make_transform ~local ~global ~base
end
module Source = Make (struct
type t = Sources.t
let deconstruct source =
match source with
| Sources.Attach -> NonTransformable source
| Sources.NamedSource _
| Sources.ParametricSource _ ->
Base source
| Sources.Transform { local; global; base } -> Transformed { local; global; base }
let order = TaintTransforms.Order.Forward
let preserve_sanitize_sources _ = false
let preserve_sanitize_sinks _ = true
let is_tito _ = false
let rec base_as_sanitizer = function
| Sources.NamedSource name
| Sources.ParametricSource { source_name = name; _ } ->
Some (SanitizeTransform.Source (SanitizeTransform.Source.Named name))
| Sources.Transform { base; _ } -> base_as_sanitizer base
| Sources.Attach -> None
let make_transform = Sources.make_transform
let matching_sanitize_transforms
~taint_configuration:{ TaintConfiguration.Heap.source_sink_filter; _ }
~named_transforms
~base
=
SourceSinkFilter.matching_sink_sanitize_transforms source_sink_filter ~named_transforms ~base
end)
module Sink = Make (struct
type t = Sinks.t
let deconstruct sink =
match sink with
| Sinks.Attach
| Sinks.AddFeatureToArgument ->
NonTransformable sink
| Sinks.PartialSink _
| Sinks.TriggeredPartialSink _
| Sinks.LocalReturn
| Sinks.ExtraTraceSink
| Sinks.NamedSink _
| Sinks.ParametricSink _
| Sinks.ParameterUpdate _ ->
Base sink
| Sinks.Transform { local; global; base } -> Transformed { local; global; base }
let order = TaintTransforms.Order.Backward
let preserve_sanitize_sources _ = true
let rec is_tito = function
| Sinks.LocalReturn
| Sinks.ParameterUpdate _ ->
true
| Sinks.Transform { base; _ } -> is_tito base
| _ -> false
We should only apply sink sanitizers on .
let preserve_sanitize_sinks = is_tito
let rec base_as_sanitizer = function
| Sinks.NamedSink name
| Sinks.ParametricSink { sink_name = name; _ } ->
Some (SanitizeTransform.Sink (SanitizeTransform.Sink.Named name))
| Sinks.Transform { base; _ } -> base_as_sanitizer base
| Sinks.Attach
| Sinks.AddFeatureToArgument
| Sinks.PartialSink _
| Sinks.TriggeredPartialSink _
| Sinks.LocalReturn
| Sinks.ParameterUpdate _
| Sinks.ExtraTraceSink ->
None
let make_transform = Sinks.make_transform
let matching_sanitize_transforms
~taint_configuration:{ TaintConfiguration.Heap.source_sink_filter; _ }
~named_transforms
~base
=
SourceSinkFilter.matching_source_sanitize_transforms source_sink_filter ~named_transforms ~base
end)
| null | https://raw.githubusercontent.com/facebook/pyre-check/3fb5a54822fd237f51009a24ce316dbb29db6efc/source/interprocedural_analyses/taint/taintTransformOperation.ml | ocaml | This module implements common operations on taint transforms.
* Most importantly, it implements adding transforms on a source or sink.
*
* This is intentionally in a separate file to have access to both `Sources` and
* `Sinks`, even though they use `TaintTransforms.t`. This avoids a cyclic
* dependency.
Check if the taint can ever match a rule. This is for performance as well
* as convergence, since we might have infinite chains T:T:T:T:...
Previous sanitize transforms are invalidated,
* so we can remove them from the local part.
Check if applying that sanitizer removes the taint.
Check if this is a no-op because those sanitizers already exist in the global part.
Remove sanitizers that cannot affect this kind.
Add sanitizers to the existing sanitizers in the local part.
Check if the new taint can ever match a rule.
None represents a sanitized taint. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Core
open Pyre
module InsertLocation = struct
type t =
| Front
| Back
[@@deriving show]
end
type 'a kind_transforms =
| NonTransformable of 'a
| Base of 'a
| Transformed of {
local: TaintTransforms.t;
global: TaintTransforms.t;
base: 'a;
}
module type KIND_ARG = sig
type t
val deconstruct : t -> t kind_transforms
val order : TaintTransforms.Order.t
val preserve_sanitize_sources : t -> bool
val preserve_sanitize_sinks : t -> bool
val is_tito : t -> bool
val base_as_sanitizer : t -> SanitizeTransform.t option
val make_transform : local:TaintTransforms.t -> global:TaintTransforms.t -> base:t -> t
val matching_sanitize_transforms
: taint_configuration:TaintConfiguration.Heap.t ->
named_transforms:TaintTransform.t list ->
base:t ->
SourceSinkFilter.MatchingSanitizeTransforms.t option
end
module Make (Kind : KIND_ARG) = struct
let prepend_name_transform
~taint_configuration:
({ TaintConfiguration.Heap.source_sink_filter; _ } as taint_configuration)
~base
~named_transforms
transforms
named_transform
=
let named_transforms = named_transform :: named_transforms in
let should_keep =
if Kind.is_tito base then
TaintTransforms.Set.mem
named_transforms
(SourceSinkFilter.possible_tito_transforms source_sink_filter)
else
Kind.matching_sanitize_transforms ~taint_configuration ~named_transforms ~base
|> Option.is_some
in
if not should_keep then
None
else
let transforms =
if not (Kind.is_tito base) then
snd (TaintTransforms.split_sanitizers transforms)
else
We can not remove existing sanitizers from tito , since transforms
* are applied from left to right on sources and right to left on sinks .
*
* For instance , ` NotSource[A]:Transform : NotSink[X]:LocalReturn ` will
* sanitize both ` Source[A ] ` and ` Sink[X ] ` .
* We need to preserve all sanitizers .
* are applied from left to right on sources and right to left on sinks.
*
* For instance, `NotSource[A]:Transform:NotSink[X]:LocalReturn` will
* sanitize both `Source[A]` and `Sink[X]`.
* We need to preserve all sanitizers.
*)
transforms
in
Some (named_transform :: transforms)
let preserve_sanitizers ~base sanitizers =
let sanitizers =
if not (Kind.preserve_sanitize_sources base) then
{ sanitizers with SanitizeTransformSet.sources = SanitizeTransform.SourceSet.empty }
else
sanitizers
in
let sanitizers =
if not (Kind.preserve_sanitize_sinks base) then
{ sanitizers with SanitizeTransformSet.sinks = SanitizeTransform.SinkSet.empty }
else
sanitizers
in
sanitizers
let prepend_sanitize_transforms
~taint_configuration
~base
~named_transforms
~global_sanitizers
transforms
({ SanitizeTransformSet.sources = sanitizer_sources; sinks = sanitizer_sinks } as sanitizers)
=
match Kind.base_as_sanitizer base with
| _ when SanitizeTransform.SourceSet.is_all sanitizer_sources -> None
| _ when SanitizeTransform.SinkSet.is_all sanitizer_sinks -> None
| Some base when List.is_empty named_transforms && SanitizeTransformSet.mem sanitizers base ->
None
| _ ->
let sanitizers = preserve_sanitizers ~base sanitizers in
let sanitizers = SanitizeTransformSet.diff sanitizers global_sanitizers in
if SanitizeTransformSet.is_empty sanitizers then
Some transforms
else
let matching_kinds =
if not (Kind.is_tito base) then
Kind.matching_sanitize_transforms ~taint_configuration ~named_transforms ~base
else
None
in
let sanitizers =
match matching_kinds with
| Some { transforms = matching_kinds; _ } ->
SanitizeTransformSet.meet matching_kinds sanitizers
| None -> sanitizers
in
if SanitizeTransformSet.is_empty sanitizers then
Some transforms
let existing_sanitizers, rest = TaintTransforms.split_sanitizers transforms in
let sanitizers = SanitizeTransformSet.join sanitizers existing_sanitizers in
let should_keep =
match matching_kinds with
| _ when Kind.is_tito base -> true
| None -> false
| Some { sanitizable = false; _ } -> true
| Some { transforms = matching_transforms; sanitizable = true } ->
not
(SanitizeTransformSet.less_or_equal
~left:matching_transforms
~right:(SanitizeTransformSet.join sanitizers global_sanitizers))
in
if should_keep then
Some (TaintTransform.Sanitize sanitizers :: rest)
else
None
let add_sanitize_transforms_internal
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
sanitizers
=
match insert_location with
| InsertLocation.Front ->
prepend_sanitize_transforms
~taint_configuration
~base
~named_transforms
~global_sanitizers
transforms
sanitizers
| InsertLocation.Back ->
if SanitizeTransformSet.is_empty global_sanitizers then
match
prepend_sanitize_transforms
~taint_configuration
~base
~named_transforms
~global_sanitizers
(List.rev transforms)
sanitizers
with
| None -> None
| Some list -> Some (List.rev list)
else
failwith "Unable to insert sanitizers in the back when there exist global sanitizers"
let get_global_sanitizers ~local ~global =
if List.exists local ~f:TaintTransform.is_named_transform then
SanitizeTransformSet.empty
else
fst (TaintTransforms.split_sanitizers global)
let get_named_transforms ~local ~global =
List.filter ~f:TaintTransform.is_named_transform local
@ List.filter ~f:TaintTransform.is_named_transform global
let add_sanitize_transforms ~taint_configuration ~base ~local ~global ~insert_location sanitizers =
let global_sanitizers = get_global_sanitizers ~local ~global in
let named_transforms = get_named_transforms ~local ~global in
add_sanitize_transforms_internal
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
local
sanitizers
type add_transform_result = {
transforms: TaintTransform.t list option;
named_transforms: TaintTransform.t list;
global_sanitizers: SanitizeTransformSet.t;
}
let add_transform
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
= function
| TaintTransform.Named _ as named_transform ->
{
transforms =
prepend_name_transform
~taint_configuration
~base
~named_transforms
transforms
named_transform;
named_transforms = named_transform :: named_transforms;
global_sanitizers = SanitizeTransformSet.empty;
}
| TaintTransform.Sanitize sanitizers ->
let transforms =
add_sanitize_transforms_internal
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
sanitizers
in
{ transforms; named_transforms; global_sanitizers }
let add_backward_into_forward_transforms
~taint_configuration
~base
~local
~global
~insert_location
~to_add
=
let rec add ({ transforms; named_transforms; global_sanitizers } as sofar) to_add =
match transforms, to_add with
| None, _
| Some _, [] ->
sofar
| Some transforms, head :: tail ->
add
(add_transform
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
head)
tail
in
let global_sanitizers = get_global_sanitizers ~local ~global in
let named_transforms = get_named_transforms ~local ~global in
let { transforms; _ } =
add { transforms = Some local; named_transforms; global_sanitizers } to_add
in
transforms
let add_backward_into_backward_transforms
~taint_configuration
~base
~local
~global
~insert_location
~to_add
=
let rec add sofar = function
| [] -> sofar
| head :: tail -> (
match add sofar tail with
| { transforms = None; _ } as sofar -> sofar
| { transforms = Some transforms; named_transforms; global_sanitizers } ->
add_transform
~taint_configuration
~base
~named_transforms
~global_sanitizers
~insert_location
transforms
head)
in
let global_sanitizers = get_global_sanitizers ~local ~global in
let named_transforms = get_named_transforms ~local ~global in
let { transforms; _ } =
add { transforms = Some local; named_transforms; global_sanitizers } to_add
in
transforms
let add_transforms
~taint_configuration
~base
~local
~global
~order
~insert_location
~to_add
~to_add_order
=
match order, to_add_order with
| TaintTransforms.Order.Forward, TaintTransforms.Order.Backward ->
add_backward_into_forward_transforms
~taint_configuration
~base
~local
~global
~insert_location
~to_add
| TaintTransforms.Order.Backward, TaintTransforms.Order.Backward ->
add_backward_into_backward_transforms
~taint_configuration
~base
~local
~global
~insert_location
~to_add
| _ ->
Format.asprintf
"unsupported: add_transforms ~order:%a ~to_add_order:%a"
TaintTransforms.Order.pp
order
TaintTransforms.Order.pp
to_add_order
|> failwith
let of_sanitize_transforms ~taint_configuration ~base sanitizers =
prepend_sanitize_transforms
~taint_configuration
~base
~named_transforms:[]
~global_sanitizers:SanitizeTransformSet.empty
[]
sanitizers
let apply_sanitize_transforms ~taint_configuration transforms insert_location kind =
match Kind.deconstruct kind with
| NonTransformable kind -> Some kind
| Base base ->
of_sanitize_transforms ~taint_configuration ~base transforms
>>| fun local -> Kind.make_transform ~local ~global:TaintTransforms.empty ~base
| Transformed { local; global; base } ->
add_sanitize_transforms
~taint_configuration
~base
~local
~global
~insert_location
transforms
>>| fun local -> Kind.make_transform ~local ~global ~base
let apply_transforms ~taint_configuration transforms insert_location order kind =
match Kind.deconstruct kind with
| NonTransformable kind -> Some kind
| Base base ->
add_transforms
~taint_configuration
~base
~local:TaintTransforms.empty
~global:TaintTransforms.empty
~order:Kind.order
~insert_location
~to_add:transforms
~to_add_order:order
>>| fun local -> Kind.make_transform ~local ~global:TaintTransforms.empty ~base
| Transformed { local; global; base } ->
add_transforms
~taint_configuration
~base
~local
~global
~order:Kind.order
~insert_location
~to_add:transforms
~to_add_order:order
>>| fun local -> Kind.make_transform ~local ~global ~base
end
module Source = Make (struct
type t = Sources.t
let deconstruct source =
match source with
| Sources.Attach -> NonTransformable source
| Sources.NamedSource _
| Sources.ParametricSource _ ->
Base source
| Sources.Transform { local; global; base } -> Transformed { local; global; base }
let order = TaintTransforms.Order.Forward
let preserve_sanitize_sources _ = false
let preserve_sanitize_sinks _ = true
let is_tito _ = false
let rec base_as_sanitizer = function
| Sources.NamedSource name
| Sources.ParametricSource { source_name = name; _ } ->
Some (SanitizeTransform.Source (SanitizeTransform.Source.Named name))
| Sources.Transform { base; _ } -> base_as_sanitizer base
| Sources.Attach -> None
let make_transform = Sources.make_transform
let matching_sanitize_transforms
~taint_configuration:{ TaintConfiguration.Heap.source_sink_filter; _ }
~named_transforms
~base
=
SourceSinkFilter.matching_sink_sanitize_transforms source_sink_filter ~named_transforms ~base
end)
module Sink = Make (struct
type t = Sinks.t
let deconstruct sink =
match sink with
| Sinks.Attach
| Sinks.AddFeatureToArgument ->
NonTransformable sink
| Sinks.PartialSink _
| Sinks.TriggeredPartialSink _
| Sinks.LocalReturn
| Sinks.ExtraTraceSink
| Sinks.NamedSink _
| Sinks.ParametricSink _
| Sinks.ParameterUpdate _ ->
Base sink
| Sinks.Transform { local; global; base } -> Transformed { local; global; base }
let order = TaintTransforms.Order.Backward
let preserve_sanitize_sources _ = true
let rec is_tito = function
| Sinks.LocalReturn
| Sinks.ParameterUpdate _ ->
true
| Sinks.Transform { base; _ } -> is_tito base
| _ -> false
We should only apply sink sanitizers on .
let preserve_sanitize_sinks = is_tito
let rec base_as_sanitizer = function
| Sinks.NamedSink name
| Sinks.ParametricSink { sink_name = name; _ } ->
Some (SanitizeTransform.Sink (SanitizeTransform.Sink.Named name))
| Sinks.Transform { base; _ } -> base_as_sanitizer base
| Sinks.Attach
| Sinks.AddFeatureToArgument
| Sinks.PartialSink _
| Sinks.TriggeredPartialSink _
| Sinks.LocalReturn
| Sinks.ParameterUpdate _
| Sinks.ExtraTraceSink ->
None
let make_transform = Sinks.make_transform
let matching_sanitize_transforms
~taint_configuration:{ TaintConfiguration.Heap.source_sink_filter; _ }
~named_transforms
~base
=
SourceSinkFilter.matching_source_sanitize_transforms source_sink_filter ~named_transforms ~base
end)
|
cff2ac5deceee1d9d936946b6dc043fdb9486b15e144dabea586149d1b2be761 | tallaproject/onion | onion_nif.erl | %%%
Copyright ( c ) 2015 The Talla Authors . All rights reserved .
%%% Use of this source code is governed by a BSD-style
%%% license that can be found in the LICENSE file.
%%%
%%% ----------------------------------------------------------------------------
@author < >
@private
%%% ----------------------------------------------------------------------------
-module(onion_nif).
%% Private API.
-export([rsa_generate_private_key/2]).
%% Initializer.
-on_load(init/0).
NIF .
-define(nif_stub, nif_stub_error(?LINE)).
-spec init() -> ok | {error, any()}.
init() ->
Module = "onion",
File = case code:priv_dir(?MODULE) of
{error, bad_name} ->
case code:which(?MODULE) of
DirectoryName when is_list(DirectoryName) ->
filename:join([filename:dirname(DirectoryName), "..", "priv", Module]);
_Otherwise ->
filename:join(["..", "priv", Module])
end;
DirectoryName when is_list(DirectoryName) ->
filename:join([DirectoryName, Module])
end,
erlang:load_nif(File, 0).
@private
-spec rsa_generate_private_key(pos_integer(), pos_integer()) -> binary().
rsa_generate_private_key(_Bits, _E) ->
?nif_stub.
@private
-spec nif_stub_error(Line :: non_neg_integer()) -> no_return().
nif_stub_error(Line) ->
erlang:nif_error({nif_not_loaded, module, ?MODULE, line, Line}).
| null | https://raw.githubusercontent.com/tallaproject/onion/d0c3f86c726c302744d3cfffa2de21f85c190cf0/src/onion_nif.erl | erlang |
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Private API.
Initializer. | Copyright ( c ) 2015 The Talla Authors . All rights reserved .
@author < >
@private
-module(onion_nif).
-export([rsa_generate_private_key/2]).
-on_load(init/0).
NIF .
-define(nif_stub, nif_stub_error(?LINE)).
-spec init() -> ok | {error, any()}.
init() ->
Module = "onion",
File = case code:priv_dir(?MODULE) of
{error, bad_name} ->
case code:which(?MODULE) of
DirectoryName when is_list(DirectoryName) ->
filename:join([filename:dirname(DirectoryName), "..", "priv", Module]);
_Otherwise ->
filename:join(["..", "priv", Module])
end;
DirectoryName when is_list(DirectoryName) ->
filename:join([DirectoryName, Module])
end,
erlang:load_nif(File, 0).
@private
-spec rsa_generate_private_key(pos_integer(), pos_integer()) -> binary().
rsa_generate_private_key(_Bits, _E) ->
?nif_stub.
@private
-spec nif_stub_error(Line :: non_neg_integer()) -> no_return().
nif_stub_error(Line) ->
erlang:nif_error({nif_not_loaded, module, ?MODULE, line, Line}).
|
5a6ea0667eda7f7823b926b85458958cbc1933430836e61d0e44cffac1c3f836 | tsloughter/kuberl | kuberl.erl | @doc : Kubernetes Erlang client
%%
-module(kuberl).
%% API
-export([new_cfg/0,
update_cfg/1,
update_cfg/2,
cfg_with_bearer_token/1,
cfg_with_bearer_token/2,
cfg_with_host/1,
cfg_with_host/2,
update_default_cfg/1,
set_default_cfg/0,
set_default_cfg/1]).
-type cfg() :: map().
%% @doc The default config.
-spec new_cfg() -> cfg().
new_cfg() ->
#{host => application:get_env(kuberl, host, "localhost:8001"),
hackney_opts => [{ssl_options, [{server_name_indication, disable}]}],
auth => auth(),
api_key_prefix => #{<<"authorization">> => <<"Bearer">>}}.
-spec auth() -> map().
auth() ->
#{'BearerToken' => application:get_env(kuberl, api_key, undefined)}.
@equiv cfg_with_bearer_token(new_cfg ( ) , )
%% @doc Create a config using a given bearer `Token'.
-spec cfg_with_bearer_token(binary()) -> cfg().
cfg_with_bearer_token(Token) ->
cfg_with_bearer_token(new_cfg(), Token).
%% @doc Add a bearer `Token' to a given config.
-spec cfg_with_bearer_token(cfg(), binary()) -> cfg().
cfg_with_bearer_token(Cfg, Token) when is_binary(Token) ->
update_cfg(Cfg, #{auth => #{'BearerToken' => Token},
api_key_prefix => #{<<"authorization">> => <<"Bearer">>}}).
%% @equiv cfg_with_host(new_cfg(), Host)
%% @doc Create a config with a given `Host'.
-spec cfg_with_host(string()) -> cfg().
cfg_with_host(Host) ->
cfg_with_host(new_cfg(), Host).
%% @doc Add a bearer `Token' to a given config.
-spec cfg_with_host(cfg(), string()) -> cfg().
cfg_with_host(Cfg, Host) ->
update_cfg(Cfg, #{host => Host}).
%% @equiv update_cfg(new_cfg(), Map)
%% @doc Update a default config with values in `Map'.
-spec update_cfg(map()) -> cfg().
update_cfg(Map) ->
update_cfg(new_cfg(), Map).
%% @doc Update a config with values in `Map'.
-spec update_cfg(cfg(), map()) -> cfg().
update_cfg(Cfg, Map) ->
maps:merge(Cfg, Map).
%% @doc Update and set the default config with values in `Map'.
-spec update_default_cfg(map()) -> ok.
update_default_cfg(Map) ->
set_default_cfg(update_cfg(Map)).
@equiv set_default_cfg(new_cfg ( ) )
-spec set_default_cfg() -> ok.
set_default_cfg() ->
set_default_cfg(new_cfg()).
%% @doc Set the default config to `Cfg'.
-spec set_default_cfg(cfg()) -> ok.
set_default_cfg(Cfg) ->
application:set_env(kuberl, config, Cfg).
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/src/kuberl.erl | erlang |
API
@doc The default config.
@doc Create a config using a given bearer `Token'.
@doc Add a bearer `Token' to a given config.
@equiv cfg_with_host(new_cfg(), Host)
@doc Create a config with a given `Host'.
@doc Add a bearer `Token' to a given config.
@equiv update_cfg(new_cfg(), Map)
@doc Update a default config with values in `Map'.
@doc Update a config with values in `Map'.
@doc Update and set the default config with values in `Map'.
@doc Set the default config to `Cfg'. | @doc : Kubernetes Erlang client
-module(kuberl).
-export([new_cfg/0,
update_cfg/1,
update_cfg/2,
cfg_with_bearer_token/1,
cfg_with_bearer_token/2,
cfg_with_host/1,
cfg_with_host/2,
update_default_cfg/1,
set_default_cfg/0,
set_default_cfg/1]).
-type cfg() :: map().
-spec new_cfg() -> cfg().
new_cfg() ->
#{host => application:get_env(kuberl, host, "localhost:8001"),
hackney_opts => [{ssl_options, [{server_name_indication, disable}]}],
auth => auth(),
api_key_prefix => #{<<"authorization">> => <<"Bearer">>}}.
-spec auth() -> map().
auth() ->
#{'BearerToken' => application:get_env(kuberl, api_key, undefined)}.
@equiv cfg_with_bearer_token(new_cfg ( ) , )
-spec cfg_with_bearer_token(binary()) -> cfg().
cfg_with_bearer_token(Token) ->
cfg_with_bearer_token(new_cfg(), Token).
-spec cfg_with_bearer_token(cfg(), binary()) -> cfg().
cfg_with_bearer_token(Cfg, Token) when is_binary(Token) ->
update_cfg(Cfg, #{auth => #{'BearerToken' => Token},
api_key_prefix => #{<<"authorization">> => <<"Bearer">>}}).
-spec cfg_with_host(string()) -> cfg().
cfg_with_host(Host) ->
cfg_with_host(new_cfg(), Host).
-spec cfg_with_host(cfg(), string()) -> cfg().
cfg_with_host(Cfg, Host) ->
update_cfg(Cfg, #{host => Host}).
-spec update_cfg(map()) -> cfg().
update_cfg(Map) ->
update_cfg(new_cfg(), Map).
-spec update_cfg(cfg(), map()) -> cfg().
update_cfg(Cfg, Map) ->
maps:merge(Cfg, Map).
-spec update_default_cfg(map()) -> ok.
update_default_cfg(Map) ->
set_default_cfg(update_cfg(Map)).
@equiv set_default_cfg(new_cfg ( ) )
-spec set_default_cfg() -> ok.
set_default_cfg() ->
set_default_cfg(new_cfg()).
-spec set_default_cfg(cfg()) -> ok.
set_default_cfg(Cfg) ->
application:set_env(kuberl, config, Cfg).
|
f836e197d6084a84a2001dc45673bac27732a429b8f8b996165188c47ef4efa4 | ahrefs/atd | ov_run.ml | let validate_list f path l =
let rec loop f path i = function
| [] -> None
| x :: l ->
let subpath = `Index i :: path in
match f subpath x with
None -> loop f path (i+1) l
| err -> err
in
loop f path 0 l
let validate_array f path a =
let rec loop f path a len i =
if i >= len then None
else
match f (`Index i :: path) a.(i) with
None -> loop f path a len (i+1)
| err -> err
in
loop f path a (Array.length a) 0
let validate_option f path = function
None -> None
| Some x -> f path x
| null | https://raw.githubusercontent.com/ahrefs/atd/9a3cb984a695563c04b41cdd7a1ce9454eb40e1c/atdgen-runtime/src/ov_run.ml | ocaml | let validate_list f path l =
let rec loop f path i = function
| [] -> None
| x :: l ->
let subpath = `Index i :: path in
match f subpath x with
None -> loop f path (i+1) l
| err -> err
in
loop f path 0 l
let validate_array f path a =
let rec loop f path a len i =
if i >= len then None
else
match f (`Index i :: path) a.(i) with
None -> loop f path a len (i+1)
| err -> err
in
loop f path a (Array.length a) 0
let validate_option f path = function
None -> None
| Some x -> f path x
|
|
cc7e07d962eae443a8dac7ba3cd8d30aea75c53a6a1d291704f0c6969bb56d9e | OCamlPro/freeton_ocaml_sdk | mod_utils.ml | (**************************************************************************)
(* *)
Copyright ( c ) 2021 OCamlPro SAS
(* *)
(* 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 LICENSE.md file in the root directory. *)
(* *)
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
(* *)
(* TYPES *)
(* *)
(* *)
(**************************************************************************)
module AddressStringFormat = struct
type t =
| AccountId [@kind "AccountId"] [@kind_label "type"]
| Hex [@kind "Hex"] [@kind_label "type"]
| Base64 of {
url: bool ;
test: bool ;
bounce: bool ;
}
[@kind "Base64"] [@kind_label "type"]
[@@deriving json_encoding ]
let t_enc = enc
end
(**************************************************************************)
(* *)
(* *)
(* FUNCTIONS *)
(* *)
(* *)
(**************************************************************************)
module ConvertAddress = struct
type params = {
address: string ;
output_format: AddressStringFormat.t ;
}
[@@deriving json_encoding]
type result = {
address: string
}
[@@deriving json_encoding]
let f = Tc.f "convert_address" ~params_enc ~result_enc
end
module CalcStorageFee = struct
type params = {
account: string ;
period: int ;
}
[@@deriving json_encoding]
type result = {
fee: string
}
[@@deriving json_encoding]
let f = Tc.f "calc_storage_fee" ~params_enc ~result_enc
end
module CompressZstd = struct
type params = {
uncompressed: string ;
level: int option ; [@opt None ]
}
[@@deriving json_encoding]
type result = {
compressed: string
}
[@@deriving json_encoding]
let f = Tc.f "compress_zstd" ~params_enc ~result_enc
end
module DecompressZstd = struct
type params = {
compressed: string
}
[@@deriving json_encoding]
type result = {
decompressed: string
}
[@@deriving json_encoding]
let f = Tc.f "decompress_zstd" ~params_enc ~result_enc
end
let convert_address = Tc.request ConvertAddress.f
let calc_storage_fee = Tc.request CalcStorageFee.f
let compress_zstd = Tc.request CompressZstd.f
let decompress_zstd = Tc.request DecompressZstd.f
| null | https://raw.githubusercontent.com/OCamlPro/freeton_ocaml_sdk/9f106db6461707984e1c2f2bafcd75b2850b3e5b/src/freeton_client_lib/mod_utils.ml | ocaml | ************************************************************************
All rights reserved.
This file is distributed under the terms of the GNU Lesser General
described in the LICENSE.md file in the root directory.
************************************************************************
************************************************************************
TYPES
************************************************************************
************************************************************************
FUNCTIONS
************************************************************************ | Copyright ( c ) 2021 OCamlPro SAS
Public License version 2.1 , with the special exception on linking
module AddressStringFormat = struct
type t =
| AccountId [@kind "AccountId"] [@kind_label "type"]
| Hex [@kind "Hex"] [@kind_label "type"]
| Base64 of {
url: bool ;
test: bool ;
bounce: bool ;
}
[@kind "Base64"] [@kind_label "type"]
[@@deriving json_encoding ]
let t_enc = enc
end
module ConvertAddress = struct
type params = {
address: string ;
output_format: AddressStringFormat.t ;
}
[@@deriving json_encoding]
type result = {
address: string
}
[@@deriving json_encoding]
let f = Tc.f "convert_address" ~params_enc ~result_enc
end
module CalcStorageFee = struct
type params = {
account: string ;
period: int ;
}
[@@deriving json_encoding]
type result = {
fee: string
}
[@@deriving json_encoding]
let f = Tc.f "calc_storage_fee" ~params_enc ~result_enc
end
module CompressZstd = struct
type params = {
uncompressed: string ;
level: int option ; [@opt None ]
}
[@@deriving json_encoding]
type result = {
compressed: string
}
[@@deriving json_encoding]
let f = Tc.f "compress_zstd" ~params_enc ~result_enc
end
module DecompressZstd = struct
type params = {
compressed: string
}
[@@deriving json_encoding]
type result = {
decompressed: string
}
[@@deriving json_encoding]
let f = Tc.f "decompress_zstd" ~params_enc ~result_enc
end
let convert_address = Tc.request ConvertAddress.f
let calc_storage_fee = Tc.request CalcStorageFee.f
let compress_zstd = Tc.request CompressZstd.f
let decompress_zstd = Tc.request DecompressZstd.f
|
1dd8139234511bc79f8028496fd25680910594e11744a85966a2316048d55a76 | vraid/earthgen | logistic.rkt | #lang typed/racket
(provide (all-defined-out))
(: logistic-growth-rate (Float Float Float -> Float))
(define (logistic-growth-rate growth-rate population carrying-capacity)
(* growth-rate population (- 1 (/ population carrying-capacity))))
(: logistic-absolute (Float Float Float Float -> Float))
(define (logistic-absolute growth-rate population carrying-capacity time)
(let ([ert (exp (* growth-rate time))])
(/ (* carrying-capacity population ert)
(+ carrying-capacity (* population
(- ert 1))))))
| null | https://raw.githubusercontent.com/vraid/earthgen/208ac834c02208ddc16a31aa9e7ff7f91c18e046/planet/math/logistic.rkt | racket | #lang typed/racket
(provide (all-defined-out))
(: logistic-growth-rate (Float Float Float -> Float))
(define (logistic-growth-rate growth-rate population carrying-capacity)
(* growth-rate population (- 1 (/ population carrying-capacity))))
(: logistic-absolute (Float Float Float Float -> Float))
(define (logistic-absolute growth-rate population carrying-capacity time)
(let ([ert (exp (* growth-rate time))])
(/ (* carrying-capacity population ert)
(+ carrying-capacity (* population
(- ert 1))))))
|
|
1dc6f0984907b73c695b1383540838b9954c5048c4708aad8862fa6b0fd434fe | Cipherwraith/Rokka | GetHeaders.hs | module GetHeaders where
import Network.HTTP
import Control.Applicative
import Data.Maybe
import qualified Control.Exception as X
import Network.Stream
-- Downloads the URL and isolates the response headers
download url = liftA rspHeaders <$> runHTTP url
-- Do a head request, and catch any exceptions.
runHTTP url = (simpleHTTP (headRequest url) ) `X.catch` exceptionHandler
-- IF there is any exception in the HTTP head request, then replace it with a request to awaq.com
exceptionHandler :: X.SomeException -> IO (Result (Response String))
exceptionHandler x = simpleHTTP (headRequest "/")
-- Pattern match on the Either functor
checkRightOrLeft (Left x) = []
checkRightOrLeft (Right x) = x
-- Header types can be found here:
-- -HTTP-Headers.html#t:HeaderName
contentType' = HdrContentType
lastModified' = HdrLastModified
Gets headers and isolates a single header type . See contentType ' and ' for an example of header type
getHeader x url = fromMaybe "" . lookupHeader x . checkRightOrLeft <$> download url
-- Sugar to get the "lastmodified" header and isolate it out into a string
getLastModified = getHeader lastModified'
| null | https://raw.githubusercontent.com/Cipherwraith/Rokka/46f55dcc5f0c00f2c806670330234b0e7afea5ee/GetHeaders.hs | haskell | Downloads the URL and isolates the response headers
Do a head request, and catch any exceptions.
IF there is any exception in the HTTP head request, then replace it with a request to awaq.com
Pattern match on the Either functor
Header types can be found here:
-HTTP-Headers.html#t:HeaderName
Sugar to get the "lastmodified" header and isolate it out into a string | module GetHeaders where
import Network.HTTP
import Control.Applicative
import Data.Maybe
import qualified Control.Exception as X
import Network.Stream
download url = liftA rspHeaders <$> runHTTP url
runHTTP url = (simpleHTTP (headRequest url) ) `X.catch` exceptionHandler
exceptionHandler :: X.SomeException -> IO (Result (Response String))
exceptionHandler x = simpleHTTP (headRequest "/")
checkRightOrLeft (Left x) = []
checkRightOrLeft (Right x) = x
contentType' = HdrContentType
lastModified' = HdrLastModified
Gets headers and isolates a single header type . See contentType ' and ' for an example of header type
getHeader x url = fromMaybe "" . lookupHeader x . checkRightOrLeft <$> download url
getLastModified = getHeader lastModified'
|
1457a5bf857e3696c4b99a4ac2bee6433639c0548844d6359b829a1971a92514 | nd/bird | 4.5.11.hs | data Liste a = Nil | Snoc (Liste a) a
deriving (Show)
convert :: [a] -> Liste a
convert [] = Nil
convert (x:xs) = Snoc (convert xs) x
--or:
--convert = foldr f Nil
where f x y =
--folde f e = foldl f e . convert
--
argument is :
--left side:
--folde f e = e
--right side:
--foldl f e . convert =
--{def of convert}
--foldl f e Nil = e
--
argument is :
--left side:
folde f e ( ) =
--{def of folde}
--f (folde f e xs) x
--right side:
--foldl f e . convert (x:xs) =
--{def of convert}
foldl f e ( ( convert xs ) x ) =
--{def of foldl}
--f (foldl f e (convert xs)) x
--they are equals by induction hypothesis
qed
| null | https://raw.githubusercontent.com/nd/bird/06dba97af7cfb11f558eaeb31a75bd04cacf7201/ch04/4.5.11.hs | haskell | or:
convert = foldr f Nil
folde f e = foldl f e . convert
left side:
folde f e = e
right side:
foldl f e . convert =
{def of convert}
foldl f e Nil = e
left side:
{def of folde}
f (folde f e xs) x
right side:
foldl f e . convert (x:xs) =
{def of convert}
{def of foldl}
f (foldl f e (convert xs)) x
they are equals by induction hypothesis | data Liste a = Nil | Snoc (Liste a) a
deriving (Show)
convert :: [a] -> Liste a
convert [] = Nil
convert (x:xs) = Snoc (convert xs) x
where f x y =
argument is :
argument is :
folde f e ( ) =
foldl f e ( ( convert xs ) x ) =
qed
|
e712eac4640dc2b210e14deb65da95d9d94c1f299427b9e3e792a5b54d4dfa33 | namin/propagators | ui.scm | This is the ps07 file ui.scm
;;; This removes those annoying hash numbers after ;Value:
(set! repl:write-result-hash-numbers? #f)
;;; This is part of paranoid programming.
(define (assert p #!optional error-comment irritant)
(if (not p)
(begin
(if (not (default-object? irritant))
(pp irritant))
(error
(if (default-object? error-comment)
"Failed assertion"
error-comment)))))
;;; This abstracts an annoying composition
(define (depends-on information . premises)
(make-tms (contingent information premises)))
;;; This is required because (run) returns old value if there is
;;; nothing to do. This is a problem if a contradiction is resolved
;;; by a kick-out! with no propagation.
(define (tell! cell information . informants)
(assert (cell? cell) "Can only tell something to a cell.")
(set! *last-value-of-run* 'done)
(add-content cell (make-tms (contingent information informants)))
(run))
(define (retract! premise)
(set! *last-value-of-run* 'done)
(kick-out! premise)
(run))
(define (assert! premise)
(set! *last-value-of-run* 'done)
(bring-in! premise)
(run))
(define (inquire cell)
(assert (cell? cell) "Can only inquire of a cell.")
(let ((v (run)))
(if (not (eq? v 'done)) (write-line v)))
(let ((c (content cell)))
(if (tms? c)
(let ((v (tms-query c)))
(cond ((nothing? v) v)
((contingent? v) v)
(else
(error "Bug: TMS contains non-contingent statement"
cell))))
c)))
| null | https://raw.githubusercontent.com/namin/propagators/ae694dfe680125e53a3d49e5e91c378f2d333937/adventures/ps07/ui.scm | scheme | This removes those annoying hash numbers after ;Value:
This is part of paranoid programming.
This abstracts an annoying composition
This is required because (run) returns old value if there is
nothing to do. This is a problem if a contradiction is resolved
by a kick-out! with no propagation. | This is the ps07 file ui.scm
(set! repl:write-result-hash-numbers? #f)
(define (assert p #!optional error-comment irritant)
(if (not p)
(begin
(if (not (default-object? irritant))
(pp irritant))
(error
(if (default-object? error-comment)
"Failed assertion"
error-comment)))))
(define (depends-on information . premises)
(make-tms (contingent information premises)))
(define (tell! cell information . informants)
(assert (cell? cell) "Can only tell something to a cell.")
(set! *last-value-of-run* 'done)
(add-content cell (make-tms (contingent information informants)))
(run))
(define (retract! premise)
(set! *last-value-of-run* 'done)
(kick-out! premise)
(run))
(define (assert! premise)
(set! *last-value-of-run* 'done)
(bring-in! premise)
(run))
(define (inquire cell)
(assert (cell? cell) "Can only inquire of a cell.")
(let ((v (run)))
(if (not (eq? v 'done)) (write-line v)))
(let ((c (content cell)))
(if (tms? c)
(let ((v (tms-query c)))
(cond ((nothing? v) v)
((contingent? v) v)
(else
(error "Bug: TMS contains non-contingent statement"
cell))))
c)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.