_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 |
|---|---|---|---|---|---|---|---|---|
faa9f2faa19e7e380667f04a33abd850a4d17f52f735d0abd40eda3f2d07ff95 | facebook/infer | PulseResult.ml |
* Copyright ( c ) Facebook , Inc. and its 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) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module L = Logging
type ('ok, 'err) t = Ok of 'ok | Recoverable of 'ok * 'err list | FatalError of 'err * 'err list
let append_errors errors result =
if List.is_empty errors then result
else
match result with
| Ok x ->
Recoverable (x, errors)
| Recoverable (x, errors') ->
Recoverable (x, errors' @ errors)
| FatalError (fatal, errors') ->
FatalError (fatal, errors' @ errors)
let ok = function Ok x -> Some x | FatalError _ | Recoverable _ -> None
let ok_exn = function
| Ok x ->
x
| Recoverable _ | FatalError _ ->
L.die InternalError "ok_exn of something not Ok"
let map x ~f =
match x with
| Ok x' ->
Ok (f x')
| Recoverable (x', errors) ->
Recoverable (f x', errors)
| FatalError _ as err ->
err
let map_error x ~f =
match x with
| Ok _ as x ->
x
| Recoverable (x', errors) ->
Recoverable (x', List.map ~f errors)
| FatalError (fatal, errors) ->
FatalError (f fatal, List.map ~f errors)
let bind x ~f =
match x with
| Ok x' ->
f x'
| FatalError _ as err ->
err
| Recoverable (x', errors) -> (
match f x' with
| Ok x'' ->
Recoverable (x'', errors)
| Recoverable (x'', errors') ->
Recoverable (x'', errors' @ errors)
| FatalError (fatal, errors') ->
FatalError (fatal, errors' @ errors) )
let join result_result = bind result_result ~f:Fn.id
module Type = struct
type ('ok, 'err) pulse_result = ('ok, 'err) t =
| Ok of 'ok
| Recoverable of 'ok * 'err list
| FatalError of 'err * 'err list
end
module Monad_infix = struct
include Type
let ( >>| ) x f = map x ~f
let ( >>= ) x f = bind x ~f
end
module Let_syntax = struct
include Monad_infix
let ( let+ ) x f = map x ~f
let ( let* ) x f = bind x ~f
end
open Let_syntax
let of_some = function
| Ok None | Recoverable (None, _) ->
None
| Ok (Some x) ->
Some (Ok x)
| Recoverable (Some x, errors) ->
Some (Recoverable (x, errors))
| FatalError _ as err ->
Some err
let recoverable_of_result ~ok_of_error = function
| (Ok x : _ result) ->
Ok x
| Error err ->
Recoverable (ok_of_error err, [err])
let fatal_of_result = function (Ok x : _ result) -> Ok x | Error err -> FatalError (err, [])
let to_result : _ t -> _ result = function
| Ok astate ->
Ok astate
| Recoverable (_, errors) ->
Error errors
| FatalError (error, errors) ->
Error (error :: errors)
let list_fold l ~init ~f =
List.fold l ~init:(Ok init) ~f:(fun result x ->
let* acc = result in
f acc x )
let list_fold2 l1 l2 ~init ~f =
List.fold2 l1 l2 ~init:(Ok init) ~f:(fun result x1 x2 ->
let* acc = result in
f acc x1 x2 )
let list_foldi ~init ~f l =
List.foldi l ~init:(Ok init) ~f:(fun i result x ->
let* acc = result in
f i acc x )
let container_fold :
fold:('t, 'a, ('accum, 'err) t) Container.fold
-> 't
-> init:'accum
-> f:('accum -> 'a -> ('accum, 'err) t)
-> ('accum, 'err) t =
fun ~fold container ~init ~f ->
fold container ~init:(Ok init) ~f:(fun result x ->
let* acc = result in
f acc x )
| null | https://raw.githubusercontent.com/facebook/infer/12a7b8501c61a29a7c1f9a93e43bfa7cd4487490/infer/src/pulse/PulseResult.ml | ocaml |
* Copyright ( c ) Facebook , Inc. and its 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) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module L = Logging
type ('ok, 'err) t = Ok of 'ok | Recoverable of 'ok * 'err list | FatalError of 'err * 'err list
let append_errors errors result =
if List.is_empty errors then result
else
match result with
| Ok x ->
Recoverable (x, errors)
| Recoverable (x, errors') ->
Recoverable (x, errors' @ errors)
| FatalError (fatal, errors') ->
FatalError (fatal, errors' @ errors)
let ok = function Ok x -> Some x | FatalError _ | Recoverable _ -> None
let ok_exn = function
| Ok x ->
x
| Recoverable _ | FatalError _ ->
L.die InternalError "ok_exn of something not Ok"
let map x ~f =
match x with
| Ok x' ->
Ok (f x')
| Recoverable (x', errors) ->
Recoverable (f x', errors)
| FatalError _ as err ->
err
let map_error x ~f =
match x with
| Ok _ as x ->
x
| Recoverable (x', errors) ->
Recoverable (x', List.map ~f errors)
| FatalError (fatal, errors) ->
FatalError (f fatal, List.map ~f errors)
let bind x ~f =
match x with
| Ok x' ->
f x'
| FatalError _ as err ->
err
| Recoverable (x', errors) -> (
match f x' with
| Ok x'' ->
Recoverable (x'', errors)
| Recoverable (x'', errors') ->
Recoverable (x'', errors' @ errors)
| FatalError (fatal, errors') ->
FatalError (fatal, errors' @ errors) )
let join result_result = bind result_result ~f:Fn.id
module Type = struct
type ('ok, 'err) pulse_result = ('ok, 'err) t =
| Ok of 'ok
| Recoverable of 'ok * 'err list
| FatalError of 'err * 'err list
end
module Monad_infix = struct
include Type
let ( >>| ) x f = map x ~f
let ( >>= ) x f = bind x ~f
end
module Let_syntax = struct
include Monad_infix
let ( let+ ) x f = map x ~f
let ( let* ) x f = bind x ~f
end
open Let_syntax
let of_some = function
| Ok None | Recoverable (None, _) ->
None
| Ok (Some x) ->
Some (Ok x)
| Recoverable (Some x, errors) ->
Some (Recoverable (x, errors))
| FatalError _ as err ->
Some err
let recoverable_of_result ~ok_of_error = function
| (Ok x : _ result) ->
Ok x
| Error err ->
Recoverable (ok_of_error err, [err])
let fatal_of_result = function (Ok x : _ result) -> Ok x | Error err -> FatalError (err, [])
let to_result : _ t -> _ result = function
| Ok astate ->
Ok astate
| Recoverable (_, errors) ->
Error errors
| FatalError (error, errors) ->
Error (error :: errors)
let list_fold l ~init ~f =
List.fold l ~init:(Ok init) ~f:(fun result x ->
let* acc = result in
f acc x )
let list_fold2 l1 l2 ~init ~f =
List.fold2 l1 l2 ~init:(Ok init) ~f:(fun result x1 x2 ->
let* acc = result in
f acc x1 x2 )
let list_foldi ~init ~f l =
List.foldi l ~init:(Ok init) ~f:(fun i result x ->
let* acc = result in
f i acc x )
let container_fold :
fold:('t, 'a, ('accum, 'err) t) Container.fold
-> 't
-> init:'accum
-> f:('accum -> 'a -> ('accum, 'err) t)
-> ('accum, 'err) t =
fun ~fold container ~init ~f ->
fold container ~init:(Ok init) ~f:(fun result x ->
let* acc = result in
f acc x )
| |
33a2ecd19f79451b7ea42e066de8ef751ca1a10a42b26e2a8f80dc1324ffdeb1 | greglook/clj-pgp | core.clj | (ns clj-pgp.core
"Core functions for handling PGP objects."
(:require
[byte-streams :as bytes]
[clj-pgp.error :as error]
[clj-pgp.tags :as tags]
[clojure.java.io :as io]
[clojure.string :as str])
(:import
(java.io
ByteArrayOutputStream
InputStream)
java.util.Date
(org.bouncycastle.bcpg
ArmoredOutputStream)
(org.bouncycastle.openpgp
PGPKeyPair
PGPObjectFactory
PGPPrivateKey
PGPPublicKey
PGPPublicKeyRing
PGPSecretKey
PGPSignature
PGPSignatureList
PGPUtil)
(org.bouncycastle.openpgp.operator.bc
BcKeyFingerprintCalculator
BcPBESecretKeyDecryptorBuilder
BcPGPDigestCalculatorProvider)))
;; ## Supported Algorithms
(defmacro ^:private defalgorithms
"Defines a set of supported tags for a type of algorithm."
[algo-type]
`(def ~(symbol (str algo-type "-algorithms"))
~(str "The set of supported " algo-type " algorithm keywords.")
(set (keys ~(symbol "clj-pgp.tags"
(str algo-type "-algorithm-tags"))))))
(defalgorithms hash)
(defalgorithms compression)
(defalgorithms public-key)
(defalgorithms symmetric-key)
;; ## Public Key Coercion
(defprotocol PublicKeyContainer
"Protocol for value types which contain or are coercible to a PGP public key."
(public-key
[this]
"Coerces the argument into a PGP public key. Returns nil for other values."))
(extend-protocol PublicKeyContainer
nil
(public-key [_] nil)
Object
(public-key [_] nil)
PGPPublicKey
(public-key [pubkey] pubkey)
PGPSecretKey
(public-key [seckey] (.getPublicKey seckey))
PGPKeyPair
(public-key [keypair] (.getPublicKey keypair))
PGPPublicKeyRing
(public-key [keyring] (.getPublicKey keyring)))
;; ## Private Key Coercion
(defprotocol PrivateKeyContainer
"Protocol for value types which contain or are coercible to a PGP private key."
(private-key
[this]
"Coerces the argument into a PGP private key. Returns nil for other values."))
(extend-protocol PrivateKeyContainer
nil
(private-key [_] nil)
Object
(private-key [_] nil)
PGPPrivateKey
(private-key [privkey] privkey)
PGPKeyPair
(private-key [keypair] (.getPrivateKey keypair)))
# # Keypair Identifiers
(defprotocol KeyIdentifier
"Protocol for values which can be used as PGP key identifiers."
(key-id
^Long
[value]
"Returns the numeric PGP key identifier for the given value."))
(extend-protocol KeyIdentifier
nil (key-id [_] nil)
Long (key-id [id] id)
String (key-id [hex] (.longValue (BigInteger. hex 16)))
PGPPublicKey (key-id [pubkey] (.getKeyID pubkey))
PGPSecretKey (key-id [seckey] (.getKeyID seckey))
PGPPrivateKey (key-id [privkey] (.getKeyID privkey))
PGPKeyPair (key-id [keypair] (.getKeyID keypair))
PGPSignature (key-id [sig] (.getKeyID sig)))
(defn hex-id
"Returns the PGP key identifier for the given value as a hexadecimal string."
[value]
(when value
(format "%016x" (key-id value))))
(defn hex-fingerprint
"Returns the PGP key fingerprint as a hexadecimal string."
[value]
(when-let [^PGPPublicKey pubkey (public-key value)]
(->> (.getFingerprint pubkey)
(map (partial format "%02X"))
str/join)))
# # Keypair Algorithms
(defprotocol KeyAlgorithmIdentifier
"Protocol for values which can use or identify a cryptographic algorithm."
(key-algorithm
[value]
"Returns a keyword identifying the key algorithm used by the given value."))
(extend-protocol KeyAlgorithmIdentifier
nil
(key-algorithm [_] nil)
Object
(key-algorithm [value]
(tags/public-key-algorithm-tag value))
PGPPublicKey
(key-algorithm [pubkey]
(tags/public-key-algorithm-tag
(.getAlgorithm pubkey)))
PGPSecretKey
(key-algorithm [seckey]
(tags/public-key-algorithm-tag
(.getAlgorithm (.getPublicKey seckey))))
PGPPrivateKey
(key-algorithm [privkey]
(tags/public-key-algorithm-tag
(.getAlgorithm (.getPublicKeyPacket privkey))))
PGPKeyPair
(key-algorithm [keypair]
(tags/public-key-algorithm-tag
(.getAlgorithm (.getPublicKey keypair)))))
# # Key Utilities
(defn key-info
"Returns a map of information about the given key."
[k]
(when-let [^PGPPublicKey pubkey (public-key k)]
(cond->
{:master-key? (.isMasterKey pubkey)
:key-id (hex-id pubkey)
:strength (.getBitStrength pubkey)
:algorithm (key-algorithm pubkey)
:fingerprint (hex-fingerprint pubkey)
:created-at (.getCreationTime pubkey)
:revoked? (.isRevoked pubkey)
:encryption-key? (.isEncryptionKey pubkey)
:user-ids (-> pubkey .getUserIDs iterator-seq vec)}
(pos? (.getValidSeconds pubkey))
(assoc :expires-at (Date. (+ (.getTime (.getCreationTime pubkey))
(* 1000 (.getValidSeconds pubkey)))))
(instance? PGPSecretKey k)
(merge {:secret-key? true
:signing-key? (.isSigningKey ^PGPSecretKey k)}))))
(defn unlock-key
"Decodes a secret key with a passphrase to obtain the private key."
[^PGPSecretKey seckey
^String passphrase]
(.extractPrivateKey
seckey
(-> (BcPGPDigestCalculatorProvider.)
(BcPBESecretKeyDecryptorBuilder.)
(.build (.toCharArray passphrase)))))
# # PGP Object Encoding
(defprotocol Encodable
"Protocol for encodable PGP objects."
(encode
[value]
"Encodes a PGP object into a byte array."))
(extend-protocol Encodable
PGPPublicKey
(encode [pubkey]
(.getEncoded pubkey))
PGPSignature
(encode [sig]
(.getEncoded sig)))
(defn encode-ascii
"Encodes a PGP object into an ascii-armored text blob."
[data]
(let [buffer (ByteArrayOutputStream.)]
(with-open [encoder (ArmoredOutputStream. buffer)]
(io/copy (encode data) encoder))
(str buffer)))
# # PGP Object Decoding
(defn read-next-object
"A thin wrapper on reading the next object from a PGPObjectFactory."
[^PGPObjectFactory factory]
(.nextObject factory))
(defn ^:no-doc try-read-object
"Tries to read and return a single object from a given
PGPObjectFactory calling the error/*handler* upon an exception."
[factory input n]
(try
(read-next-object factory)
(catch Exception e
(error/*handler* ::read-object-error
(.getMessage e)
(assoc (ex-data e) ::stream input ::nth n)
e))))
(defn ^:no-doc read-objects
"Decodes a sequence of PGP objects from an input stream."
[^InputStream input]
(reify clojure.lang.IReduceInit
(reduce
[_ rf init]
(let [factory (PGPObjectFactory. input (BcKeyFingerprintCalculator.))]
(loop [acc init
n 0]
(let [obj (try-read-object factory input n)]
(if (or (reduced? acc)
(not obj))
(unreduced acc)
(recur (rf acc obj)
(inc n)))))))))
(defn decode
"Decodes PGP objects from an encoded data source. Returns a sequence of
decoded objects."
[data]
(with-open [stream (PGPUtil/getDecoderStream
(bytes/to-input-stream data))]
(into [] (read-objects stream))))
(defn decode-public-key
"Decodes a public key from the given data. Throws an exception if the data
does not contain a public key value."
[data]
(let [value (first (decode data))]
(or (public-key value)
(throw (IllegalStateException.
(str "Data did not contain a public key: " value))))))
(defn decode-signatures
"Decodes a sequence of signatures from the given data. Throws an exception if
the data does not contain a signature list."
[data]
(->>
(decode data)
(map
(fn [object]
(condp instance? object
PGPSignature
object
PGPSignatureList
(map #(.get ^PGPSignatureList object %)
(range (.size ^PGPSignatureList object))))))
flatten))
| null | https://raw.githubusercontent.com/greglook/clj-pgp/aa4e499ff62562fa65bbb2bee100c6ed2230bf2a/src/clj_pgp/core.clj | clojure | ## Supported Algorithms
## Public Key Coercion
## Private Key Coercion | (ns clj-pgp.core
"Core functions for handling PGP objects."
(:require
[byte-streams :as bytes]
[clj-pgp.error :as error]
[clj-pgp.tags :as tags]
[clojure.java.io :as io]
[clojure.string :as str])
(:import
(java.io
ByteArrayOutputStream
InputStream)
java.util.Date
(org.bouncycastle.bcpg
ArmoredOutputStream)
(org.bouncycastle.openpgp
PGPKeyPair
PGPObjectFactory
PGPPrivateKey
PGPPublicKey
PGPPublicKeyRing
PGPSecretKey
PGPSignature
PGPSignatureList
PGPUtil)
(org.bouncycastle.openpgp.operator.bc
BcKeyFingerprintCalculator
BcPBESecretKeyDecryptorBuilder
BcPGPDigestCalculatorProvider)))
(defmacro ^:private defalgorithms
"Defines a set of supported tags for a type of algorithm."
[algo-type]
`(def ~(symbol (str algo-type "-algorithms"))
~(str "The set of supported " algo-type " algorithm keywords.")
(set (keys ~(symbol "clj-pgp.tags"
(str algo-type "-algorithm-tags"))))))
(defalgorithms hash)
(defalgorithms compression)
(defalgorithms public-key)
(defalgorithms symmetric-key)
(defprotocol PublicKeyContainer
"Protocol for value types which contain or are coercible to a PGP public key."
(public-key
[this]
"Coerces the argument into a PGP public key. Returns nil for other values."))
(extend-protocol PublicKeyContainer
nil
(public-key [_] nil)
Object
(public-key [_] nil)
PGPPublicKey
(public-key [pubkey] pubkey)
PGPSecretKey
(public-key [seckey] (.getPublicKey seckey))
PGPKeyPair
(public-key [keypair] (.getPublicKey keypair))
PGPPublicKeyRing
(public-key [keyring] (.getPublicKey keyring)))
(defprotocol PrivateKeyContainer
"Protocol for value types which contain or are coercible to a PGP private key."
(private-key
[this]
"Coerces the argument into a PGP private key. Returns nil for other values."))
(extend-protocol PrivateKeyContainer
nil
(private-key [_] nil)
Object
(private-key [_] nil)
PGPPrivateKey
(private-key [privkey] privkey)
PGPKeyPair
(private-key [keypair] (.getPrivateKey keypair)))
# # Keypair Identifiers
(defprotocol KeyIdentifier
"Protocol for values which can be used as PGP key identifiers."
(key-id
^Long
[value]
"Returns the numeric PGP key identifier for the given value."))
(extend-protocol KeyIdentifier
nil (key-id [_] nil)
Long (key-id [id] id)
String (key-id [hex] (.longValue (BigInteger. hex 16)))
PGPPublicKey (key-id [pubkey] (.getKeyID pubkey))
PGPSecretKey (key-id [seckey] (.getKeyID seckey))
PGPPrivateKey (key-id [privkey] (.getKeyID privkey))
PGPKeyPair (key-id [keypair] (.getKeyID keypair))
PGPSignature (key-id [sig] (.getKeyID sig)))
(defn hex-id
"Returns the PGP key identifier for the given value as a hexadecimal string."
[value]
(when value
(format "%016x" (key-id value))))
(defn hex-fingerprint
"Returns the PGP key fingerprint as a hexadecimal string."
[value]
(when-let [^PGPPublicKey pubkey (public-key value)]
(->> (.getFingerprint pubkey)
(map (partial format "%02X"))
str/join)))
# # Keypair Algorithms
(defprotocol KeyAlgorithmIdentifier
"Protocol for values which can use or identify a cryptographic algorithm."
(key-algorithm
[value]
"Returns a keyword identifying the key algorithm used by the given value."))
(extend-protocol KeyAlgorithmIdentifier
nil
(key-algorithm [_] nil)
Object
(key-algorithm [value]
(tags/public-key-algorithm-tag value))
PGPPublicKey
(key-algorithm [pubkey]
(tags/public-key-algorithm-tag
(.getAlgorithm pubkey)))
PGPSecretKey
(key-algorithm [seckey]
(tags/public-key-algorithm-tag
(.getAlgorithm (.getPublicKey seckey))))
PGPPrivateKey
(key-algorithm [privkey]
(tags/public-key-algorithm-tag
(.getAlgorithm (.getPublicKeyPacket privkey))))
PGPKeyPair
(key-algorithm [keypair]
(tags/public-key-algorithm-tag
(.getAlgorithm (.getPublicKey keypair)))))
# # Key Utilities
(defn key-info
"Returns a map of information about the given key."
[k]
(when-let [^PGPPublicKey pubkey (public-key k)]
(cond->
{:master-key? (.isMasterKey pubkey)
:key-id (hex-id pubkey)
:strength (.getBitStrength pubkey)
:algorithm (key-algorithm pubkey)
:fingerprint (hex-fingerprint pubkey)
:created-at (.getCreationTime pubkey)
:revoked? (.isRevoked pubkey)
:encryption-key? (.isEncryptionKey pubkey)
:user-ids (-> pubkey .getUserIDs iterator-seq vec)}
(pos? (.getValidSeconds pubkey))
(assoc :expires-at (Date. (+ (.getTime (.getCreationTime pubkey))
(* 1000 (.getValidSeconds pubkey)))))
(instance? PGPSecretKey k)
(merge {:secret-key? true
:signing-key? (.isSigningKey ^PGPSecretKey k)}))))
(defn unlock-key
"Decodes a secret key with a passphrase to obtain the private key."
[^PGPSecretKey seckey
^String passphrase]
(.extractPrivateKey
seckey
(-> (BcPGPDigestCalculatorProvider.)
(BcPBESecretKeyDecryptorBuilder.)
(.build (.toCharArray passphrase)))))
# # PGP Object Encoding
(defprotocol Encodable
"Protocol for encodable PGP objects."
(encode
[value]
"Encodes a PGP object into a byte array."))
(extend-protocol Encodable
PGPPublicKey
(encode [pubkey]
(.getEncoded pubkey))
PGPSignature
(encode [sig]
(.getEncoded sig)))
(defn encode-ascii
"Encodes a PGP object into an ascii-armored text blob."
[data]
(let [buffer (ByteArrayOutputStream.)]
(with-open [encoder (ArmoredOutputStream. buffer)]
(io/copy (encode data) encoder))
(str buffer)))
# # PGP Object Decoding
(defn read-next-object
"A thin wrapper on reading the next object from a PGPObjectFactory."
[^PGPObjectFactory factory]
(.nextObject factory))
(defn ^:no-doc try-read-object
"Tries to read and return a single object from a given
PGPObjectFactory calling the error/*handler* upon an exception."
[factory input n]
(try
(read-next-object factory)
(catch Exception e
(error/*handler* ::read-object-error
(.getMessage e)
(assoc (ex-data e) ::stream input ::nth n)
e))))
(defn ^:no-doc read-objects
"Decodes a sequence of PGP objects from an input stream."
[^InputStream input]
(reify clojure.lang.IReduceInit
(reduce
[_ rf init]
(let [factory (PGPObjectFactory. input (BcKeyFingerprintCalculator.))]
(loop [acc init
n 0]
(let [obj (try-read-object factory input n)]
(if (or (reduced? acc)
(not obj))
(unreduced acc)
(recur (rf acc obj)
(inc n)))))))))
(defn decode
"Decodes PGP objects from an encoded data source. Returns a sequence of
decoded objects."
[data]
(with-open [stream (PGPUtil/getDecoderStream
(bytes/to-input-stream data))]
(into [] (read-objects stream))))
(defn decode-public-key
"Decodes a public key from the given data. Throws an exception if the data
does not contain a public key value."
[data]
(let [value (first (decode data))]
(or (public-key value)
(throw (IllegalStateException.
(str "Data did not contain a public key: " value))))))
(defn decode-signatures
"Decodes a sequence of signatures from the given data. Throws an exception if
the data does not contain a signature list."
[data]
(->>
(decode data)
(map
(fn [object]
(condp instance? object
PGPSignature
object
PGPSignatureList
(map #(.get ^PGPSignatureList object %)
(range (.size ^PGPSignatureList object))))))
flatten))
|
cdc2e7ac204bffef9e3a972752c99bb576d363d6a4e57dee444f0234e039dfac | Tritlo/PropR | unnamed.hs | prop_is5 :: Bool
prop_is5 = x == 5
x :: Int
x = 4
main :: IO ()
main = putStrLn "hello, world"
---- EXPECTED ----
-- diff --git a/tests/cases/unnamed.hs b/tests/cases/unnamed.hs
-- --- a/tests/cases/unnamed.hs
-- +++ b/tests/cases/unnamed.hs
@@ -5,1 +5,1 = 4
-x = 4
+ x = 5
--
-- diff --git a/tests/cases/unnamed.hs b/tests/cases/unnamed.hs
-- --- a/tests/cases/unnamed.hs
-- +++ b/tests/cases/unnamed.hs
@@ -5,1 +5,1 = 4
-x = 4
+ x = ( succ ( 4 ) )
---- END EXPECTED ---- | null | https://raw.githubusercontent.com/Tritlo/PropR/2a3654ad07f809fb6021ef4b3805d2032a5c7826/tests/cases/unnamed.hs | haskell | -- EXPECTED ----
diff --git a/tests/cases/unnamed.hs b/tests/cases/unnamed.hs
--- a/tests/cases/unnamed.hs
+++ b/tests/cases/unnamed.hs
diff --git a/tests/cases/unnamed.hs b/tests/cases/unnamed.hs
--- a/tests/cases/unnamed.hs
+++ b/tests/cases/unnamed.hs
-- END EXPECTED ---- | prop_is5 :: Bool
prop_is5 = x == 5
x :: Int
x = 4
main :: IO ()
main = putStrLn "hello, world"
@@ -5,1 +5,1 = 4
-x = 4
+ x = 5
@@ -5,1 +5,1 = 4
-x = 4
+ x = ( succ ( 4 ) ) |
25f9d481fd42bea548c4d208fb7942c1e09627f9663e9b95f672da6334cbc5b5 | rpav/cl-xcb-xlib | cffi-util.lisp | (in-package :xcb)
;; cffi-fsbv changes mem-aref semantics
(defun mem-pref (ptr type &optional (index 0))
(inc-pointer ptr (* index (foreign-type-size type))))
(define-compiler-macro mem-pref (&whole whole ptr type &optional (index 0))
(if (constantp type)
(if (constantp index)
`(inc-pointer ,ptr ,(* (eval index) (foreign-type-size (eval type))))
`(inc-pointer ,ptr (* ,index ,(foreign-type-size (eval type)))))
whole))
(export 'mem-pref)
;; memory
(defcfun ("memcpy" libc_memcpy) :pointer
(dest :pointer)
(src :pointer)
(n :sizet))
(defcfun ("memset" libc_memset) :void
(s :pointer)
(c :int)
(n :sizet))
(defcfun ("free" libc_free) :void
(ptr :pointer))
(export '(libc_free libc_memcpy libc_memset))
(defmacro with-xcb-reply ((ptr err) form &body body)
`(let ((,ptr (null-pointer)))
(unwind-protect
(with-foreign-object (,err :pointer)
(setf ,ptr ,form)
,@body)
(unless (null-pointer-p ,ptr)
(libc_free ,ptr)))))
(export 'with-xcb-reply)
;; cstruct accessors
(defmacro make-cstruct-accessor (name)
(let ((slots (cffi::slots (cffi::parse-type `(:struct ,name)))))
(flet ((slot-name (slot)
(concatenate 'string
(string name) "-" (string slot))))
`(progn
,@(loop for k being each hash-key in slots
as v = (gethash k slots)
collecting
(let ((offset (foreign-slot-offset `(:struct ,name) k))
(slot-type (cffi::slot-type v))
(slot-count (if (typep v 'cffi::aggregate-struct-slot)
(cffi::slot-count v)))
(slot-name (intern (slot-name k))))
`(progn
(declaim (inline ,slot-name (setf ,slot-name)))
(defun ,slot-name ,(if slot-count '(ptr &optional (n 0)) '(ptr))
,(if (and (consp slot-type)
(or (eq (car slot-type) :struct)
(eq (car slot-type) :union)))
`(inc-pointer ptr ,(if slot-count
`(+ ,offset n)
offset))
`(mem-ref (inc-pointer ptr ,offset) ',slot-type
,(if slot-count 'n 0))))
(defun (setf ,slot-name) (v ptr)
(setf (mem-ref (inc-pointer ptr ,offset) ',slot-type) v))
(export ',slot-name))))))))
(defmacro make-cstruct-accessors (&rest types)
`(progn
,@(loop for type in types collect
`(make-cstruct-accessor ,type))))
(export '(make-cstruct-accessor make-cstruct-accessors))
| null | https://raw.githubusercontent.com/rpav/cl-xcb-xlib/1b00c44d4723b3a8334f36e731906d4679341c0e/src/cffi-util.lisp | lisp | cffi-fsbv changes mem-aref semantics
memory
cstruct accessors | (in-package :xcb)
(defun mem-pref (ptr type &optional (index 0))
(inc-pointer ptr (* index (foreign-type-size type))))
(define-compiler-macro mem-pref (&whole whole ptr type &optional (index 0))
(if (constantp type)
(if (constantp index)
`(inc-pointer ,ptr ,(* (eval index) (foreign-type-size (eval type))))
`(inc-pointer ,ptr (* ,index ,(foreign-type-size (eval type)))))
whole))
(export 'mem-pref)
(defcfun ("memcpy" libc_memcpy) :pointer
(dest :pointer)
(src :pointer)
(n :sizet))
(defcfun ("memset" libc_memset) :void
(s :pointer)
(c :int)
(n :sizet))
(defcfun ("free" libc_free) :void
(ptr :pointer))
(export '(libc_free libc_memcpy libc_memset))
(defmacro with-xcb-reply ((ptr err) form &body body)
`(let ((,ptr (null-pointer)))
(unwind-protect
(with-foreign-object (,err :pointer)
(setf ,ptr ,form)
,@body)
(unless (null-pointer-p ,ptr)
(libc_free ,ptr)))))
(export 'with-xcb-reply)
(defmacro make-cstruct-accessor (name)
(let ((slots (cffi::slots (cffi::parse-type `(:struct ,name)))))
(flet ((slot-name (slot)
(concatenate 'string
(string name) "-" (string slot))))
`(progn
,@(loop for k being each hash-key in slots
as v = (gethash k slots)
collecting
(let ((offset (foreign-slot-offset `(:struct ,name) k))
(slot-type (cffi::slot-type v))
(slot-count (if (typep v 'cffi::aggregate-struct-slot)
(cffi::slot-count v)))
(slot-name (intern (slot-name k))))
`(progn
(declaim (inline ,slot-name (setf ,slot-name)))
(defun ,slot-name ,(if slot-count '(ptr &optional (n 0)) '(ptr))
,(if (and (consp slot-type)
(or (eq (car slot-type) :struct)
(eq (car slot-type) :union)))
`(inc-pointer ptr ,(if slot-count
`(+ ,offset n)
offset))
`(mem-ref (inc-pointer ptr ,offset) ',slot-type
,(if slot-count 'n 0))))
(defun (setf ,slot-name) (v ptr)
(setf (mem-ref (inc-pointer ptr ,offset) ',slot-type) v))
(export ',slot-name))))))))
(defmacro make-cstruct-accessors (&rest types)
`(progn
,@(loop for type in types collect
`(make-cstruct-accessor ,type))))
(export '(make-cstruct-accessor make-cstruct-accessors))
|
5a1076e69f7480e80e95c1495b7ffa6c12ff064aef6f6e1329c2b1db1d845a47 | ghc/packages-Cabal | LicenseListVersion.hs | module Distribution.SPDX.LicenseListVersion (
LicenseListVersion (..),
cabalSpecVersionToSPDXListVersion,
) where
import Distribution.CabalSpecVersion
-- | SPDX License List version @Cabal@ is aware of.
data LicenseListVersion
= LicenseListVersion_3_0
| LicenseListVersion_3_2
| LicenseListVersion_3_6
| LicenseListVersion_3_9
deriving (Eq, Ord, Show, Enum, Bounded)
cabalSpecVersionToSPDXListVersion :: CabalSpecVersion -> LicenseListVersion
cabalSpecVersionToSPDXListVersion CabalSpecV3_4 = LicenseListVersion_3_9
cabalSpecVersionToSPDXListVersion CabalSpecV3_0 = LicenseListVersion_3_6
cabalSpecVersionToSPDXListVersion CabalSpecV2_4 = LicenseListVersion_3_2
cabalSpecVersionToSPDXListVersion _ = LicenseListVersion_3_0
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/Cabal/Distribution/SPDX/LicenseListVersion.hs | haskell | | SPDX License List version @Cabal@ is aware of. | module Distribution.SPDX.LicenseListVersion (
LicenseListVersion (..),
cabalSpecVersionToSPDXListVersion,
) where
import Distribution.CabalSpecVersion
data LicenseListVersion
= LicenseListVersion_3_0
| LicenseListVersion_3_2
| LicenseListVersion_3_6
| LicenseListVersion_3_9
deriving (Eq, Ord, Show, Enum, Bounded)
cabalSpecVersionToSPDXListVersion :: CabalSpecVersion -> LicenseListVersion
cabalSpecVersionToSPDXListVersion CabalSpecV3_4 = LicenseListVersion_3_9
cabalSpecVersionToSPDXListVersion CabalSpecV3_0 = LicenseListVersion_3_6
cabalSpecVersionToSPDXListVersion CabalSpecV2_4 = LicenseListVersion_3_2
cabalSpecVersionToSPDXListVersion _ = LicenseListVersion_3_0
|
06efe01ea88dc1ba9205f4dcff2d41efc7dcd08deb60d78233f420fa15aeb586 | phronmophobic/membrane-re-frame-example | term_view.clj | (ns membrane-re-frame-example.term-view
(:require [membrane.lanterna :as lanterna]
[membrane.component :as component]
[membrane.re-frame :as memframe]
[membrane.ui :as ui
:refer
[horizontal-layout
vertical-layout
on]]
[re-frame.core :as rf :refer [reg-event-db reg-event-fx inject-cofx path after reg-sub subscribe dispatch]]
membrane-re-frame-example.db
membrane-re-frame-example.subs
membrane-re-frame-example.events)
(:gen-class))
(memframe/defrf textbox lanterna/textarea [tid {:keys [text]}])
(defn todo-input [{:keys [id title on-save on-stop]}]
(let [input-id [:todo-input id]
text @(rf/subscribe [:input-text input-id])]
(horizontal-layout
(lanterna/button "Add Todo"
(fn []
[(on-save text)
[:set-input-text input-id ""]]))
(ui/wrap-on
:key-press
(fn [handler s]
(if (= s :enter)
[(on-save text)
[:set-input-text input-id ""]]
(handler s)))
(on
:change
(fn [k v]
(when (= k :text)
[[:set-input-text input-id v]]))
(textbox input-id {:text text}))))))
(defn todo-item
[{:keys [id done title] :as todo}]
editing / subscribe [: extra [: editing (: i d todo ) ] ] )
input-id [:todo-input id]
]
(horizontal-layout
(ui/translate 0 1
(horizontal-layout
(on
:mouse-down
(fn [_]
[[:toggle-done id]])
(lanterna/checkbox-view done))
(on
:mouse-down
(fn [_]
[[:delete-todo id]])
(ui/with-color [1 0 0]
(lanterna/label "X")))))
(on
:change
(fn [k v]
(when (= k :text)
[[:save id v]]))
(textbox input-id {:text title})))))
(defn task-list
[]
(let [visible-todos @(subscribe [:visible-todos])
all-complete? @(subscribe [:all-complete?])]
(apply
vertical-layout
(for [todo visible-todos]
(todo-item todo)))))
(defn footer-controls
[]
(let [[active done] @(subscribe [:footer-counts])
showing @(subscribe [:showing])
a-fn (fn [filter-kw txt]
(on
:mouse-down
(fn [_]
[[:set-showing filter-kw]])
(ui/with-color (if (= filter-kw showing)
[0 0 0]
[0.7 0.7 0.7])
(lanterna/label txt))))]
(vertical-layout
(lanterna/label (str active
" "
(if (= 1 active)
"item"
"items")
" left"))
(apply
horizontal-layout
(for [[kw txt] [[:all "All"]
[:active "Active"]
[:done "Completed"]]]
(a-fn kw txt)))
(when (pos? done)
(lanterna/button "Clear completed"
(fn []
[[:clear-completed]]))))))
(defn task-entry
[]
(todo-input
{:id "new-todo"
:placeholder "What needs to be done?"
:on-save #(when (seq %)
[:add-todo %])}))
(defn todo-app
[]
(vertical-layout
(task-entry)
(when (seq @(subscribe [:todos]))
(task-list))
(footer-controls)
))
(defn -main [& args]
(dispatch [:initialize-db])
(lanterna/run #(memframe/re-frame-app (todo-app))))
| null | https://raw.githubusercontent.com/phronmophobic/membrane-re-frame-example/9015b3dc4cd441da4144b80aee22ad502b53476b/src/membrane_re_frame_example/term_view.clj | clojure | (ns membrane-re-frame-example.term-view
(:require [membrane.lanterna :as lanterna]
[membrane.component :as component]
[membrane.re-frame :as memframe]
[membrane.ui :as ui
:refer
[horizontal-layout
vertical-layout
on]]
[re-frame.core :as rf :refer [reg-event-db reg-event-fx inject-cofx path after reg-sub subscribe dispatch]]
membrane-re-frame-example.db
membrane-re-frame-example.subs
membrane-re-frame-example.events)
(:gen-class))
(memframe/defrf textbox lanterna/textarea [tid {:keys [text]}])
(defn todo-input [{:keys [id title on-save on-stop]}]
(let [input-id [:todo-input id]
text @(rf/subscribe [:input-text input-id])]
(horizontal-layout
(lanterna/button "Add Todo"
(fn []
[(on-save text)
[:set-input-text input-id ""]]))
(ui/wrap-on
:key-press
(fn [handler s]
(if (= s :enter)
[(on-save text)
[:set-input-text input-id ""]]
(handler s)))
(on
:change
(fn [k v]
(when (= k :text)
[[:set-input-text input-id v]]))
(textbox input-id {:text text}))))))
(defn todo-item
[{:keys [id done title] :as todo}]
editing / subscribe [: extra [: editing (: i d todo ) ] ] )
input-id [:todo-input id]
]
(horizontal-layout
(ui/translate 0 1
(horizontal-layout
(on
:mouse-down
(fn [_]
[[:toggle-done id]])
(lanterna/checkbox-view done))
(on
:mouse-down
(fn [_]
[[:delete-todo id]])
(ui/with-color [1 0 0]
(lanterna/label "X")))))
(on
:change
(fn [k v]
(when (= k :text)
[[:save id v]]))
(textbox input-id {:text title})))))
(defn task-list
[]
(let [visible-todos @(subscribe [:visible-todos])
all-complete? @(subscribe [:all-complete?])]
(apply
vertical-layout
(for [todo visible-todos]
(todo-item todo)))))
(defn footer-controls
[]
(let [[active done] @(subscribe [:footer-counts])
showing @(subscribe [:showing])
a-fn (fn [filter-kw txt]
(on
:mouse-down
(fn [_]
[[:set-showing filter-kw]])
(ui/with-color (if (= filter-kw showing)
[0 0 0]
[0.7 0.7 0.7])
(lanterna/label txt))))]
(vertical-layout
(lanterna/label (str active
" "
(if (= 1 active)
"item"
"items")
" left"))
(apply
horizontal-layout
(for [[kw txt] [[:all "All"]
[:active "Active"]
[:done "Completed"]]]
(a-fn kw txt)))
(when (pos? done)
(lanterna/button "Clear completed"
(fn []
[[:clear-completed]]))))))
(defn task-entry
[]
(todo-input
{:id "new-todo"
:placeholder "What needs to be done?"
:on-save #(when (seq %)
[:add-todo %])}))
(defn todo-app
[]
(vertical-layout
(task-entry)
(when (seq @(subscribe [:todos]))
(task-list))
(footer-controls)
))
(defn -main [& args]
(dispatch [:initialize-db])
(lanterna/run #(memframe/re-frame-app (todo-app))))
| |
38a23897ba6e0ef8ff410e7eb082025021bc121cb169e77dbee618115c2654a5 | sjl/advent | day-03.lisp | (advent:defpackage* :advent/2017/03)
(in-package :advent/2017/03)
(defun neighbors (coord)
(iterate (for (dx dy) :within-radius 1 :skip-origin t)
(collect (+ coord (complex dx dy)))))
(define-problem (2017 3) (data read) (552 330785)
(values
(manhattan-distance #c(0 0) (advent/spiral:number-coordinates data))
(iterate
(with memory = (make-hash-table))
(initially (setf (gethash #c(0 0) memory) 1))
(for n :from 2)
(for coord = (advent/spiral:number-coordinates n))
(for value = (summation (neighbors coord) :key (rcurry #'gethash memory 0)))
(finding value :such-that (> value data))
(setf (gethash coord memory) value))))
| null | https://raw.githubusercontent.com/sjl/advent/dc3debda9bd1a0570a6ab06919b1af7b285413dc/src/2017/days/day-03.lisp | lisp | (advent:defpackage* :advent/2017/03)
(in-package :advent/2017/03)
(defun neighbors (coord)
(iterate (for (dx dy) :within-radius 1 :skip-origin t)
(collect (+ coord (complex dx dy)))))
(define-problem (2017 3) (data read) (552 330785)
(values
(manhattan-distance #c(0 0) (advent/spiral:number-coordinates data))
(iterate
(with memory = (make-hash-table))
(initially (setf (gethash #c(0 0) memory) 1))
(for n :from 2)
(for coord = (advent/spiral:number-coordinates n))
(for value = (summation (neighbors coord) :key (rcurry #'gethash memory 0)))
(finding value :such-that (> value data))
(setf (gethash coord memory) value))))
| |
7c9dbdb1051339d6957266dd02770705605e51d7c40138dbd1cdcdf8b6b68bb5 | riemann/riemann | datadog.clj | (ns riemann.datadog
"Forward events to Datadog."
(:use [clojure.string :only [join split]])
(:require [clj-http.client :as client]
[cheshire.core :refer [generate-string]]))
(def ^:private gateway-url "")
(defn datadog-metric-name
"Constructs a metric-name from an event."
[event]
(let [service (:service event)
split-service (if service (split service #" ") [])]
(join "." split-service)))
(defn generate-datapoint
"Creates a vector from riemann event."
[event]
[(vector (:time event) (:metric event))])
(defn post-datapoint
"Post the riemann metrics as datapoints."
[api-key data]
(let [url (str gateway-url "?api_key=" api-key)
http-options {:body data
:content-type :json}]
(client/post url http-options)))
(defn generate-event [event]
{:metric (datadog-metric-name event)
:type "gauge"
:host (:host event)
:tags (:tags event)
:points (generate-datapoint event)})
(defn datadog
"Return a function which accepts either single events or batches of
events in a vector and sends them to datadog. Batching reduces latency
by at least one order of magnitude and is highly recommended.
Usage:
(datadog {:api-key \"bn14a6ac2e3b5h795085217d49cde7eb\"})
Option:
- :api-key Datadog's API Key for authentication.
Example:
```clojure
(def datadog-forwarder
(batch 100 1/10
(async-queue!
:datadog-forwarder ; A name for the forwarder
10,000 events max
:core-pool-size 5 ; Minimum 5 threads
:max-pools-size 100} ; Maxium 100 threads
(datadog {:api-key \"bn14a6ac2e3b5h795085217d49cde7eb\"}))))
```"
[opts]
(let [opts (merge {:api-key "datadog-api-key"} opts)]
(fn [event]
(let [events (if (sequential? event)
event
[event])
post-data {:series (mapv generate-event events)}
json-data (generate-string post-data)]
(post-datapoint (:api-key opts) json-data)))))
| null | https://raw.githubusercontent.com/riemann/riemann/1649687c0bd913c378701ee0b964a9863bde7c7c/src/riemann/datadog.clj | clojure | A name for the forwarder
Minimum 5 threads
Maxium 100 threads | (ns riemann.datadog
"Forward events to Datadog."
(:use [clojure.string :only [join split]])
(:require [clj-http.client :as client]
[cheshire.core :refer [generate-string]]))
(def ^:private gateway-url "")
(defn datadog-metric-name
"Constructs a metric-name from an event."
[event]
(let [service (:service event)
split-service (if service (split service #" ") [])]
(join "." split-service)))
(defn generate-datapoint
"Creates a vector from riemann event."
[event]
[(vector (:time event) (:metric event))])
(defn post-datapoint
"Post the riemann metrics as datapoints."
[api-key data]
(let [url (str gateway-url "?api_key=" api-key)
http-options {:body data
:content-type :json}]
(client/post url http-options)))
(defn generate-event [event]
{:metric (datadog-metric-name event)
:type "gauge"
:host (:host event)
:tags (:tags event)
:points (generate-datapoint event)})
(defn datadog
"Return a function which accepts either single events or batches of
events in a vector and sends them to datadog. Batching reduces latency
by at least one order of magnitude and is highly recommended.
Usage:
(datadog {:api-key \"bn14a6ac2e3b5h795085217d49cde7eb\"})
Option:
- :api-key Datadog's API Key for authentication.
Example:
```clojure
(def datadog-forwarder
(batch 100 1/10
(async-queue!
10,000 events max
(datadog {:api-key \"bn14a6ac2e3b5h795085217d49cde7eb\"}))))
```"
[opts]
(let [opts (merge {:api-key "datadog-api-key"} opts)]
(fn [event]
(let [events (if (sequential? event)
event
[event])
post-data {:series (mapv generate-event events)}
json-data (generate-string post-data)]
(post-datapoint (:api-key opts) json-data)))))
|
c49d5a967964334a3a77127c1290a4c0bb458b38b15f8f8208b2ed9b0575d602 | tezos/tezos-mirror | interpreter_model.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(* ------------------------------------------------------------------------- *)
let ns = Namespace.of_string
let trace_error expected given =
let open Interpreter_workload in
let exp = string_of_instr_or_cont expected in
let given = string_of_instr_or_cont given in
let msg =
Format.asprintf
"Interpreter_model: trace error, expected %s, given %s"
exp
given
in
Stdlib.failwith msg
let arity_error instr expected given =
let open Interpreter_workload in
let s = string_of_instr_or_cont instr in
let msg =
Format.asprintf
"Interpreter_model: arity error (%s), expected %d, given %a"
s
expected
Interpreter_workload.pp_args
given
in
Stdlib.failwith msg
(* ------------------------------------------------------------------------- *)
let model_0 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = []} -> if name = instr then () else trace_error instr name
| {args; _} -> arity_error instr 0 args)
~model
let model_1 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = [{name = _; arg}]} ->
if name = instr then (arg, ()) else trace_error instr name
| {args; _} -> arity_error instr 1 args)
~model
let model_2 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = [{name = _; arg = x}; {name = _; arg = y}]} ->
if name = instr then (x, (y, ())) else trace_error instr name
| {args; _} -> arity_error instr 2 args)
~model
let model_3 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {
name;
args = [{name = _; arg = x}; {name = _; arg = y}; {name = _; arg = z}];
} ->
if name = instr then (x, (y, (z, ()))) else trace_error instr name
| {args; _} -> arity_error instr 3 args)
~model
let model_4 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {
name;
args =
[
{name = _; arg = w};
{name = _; arg = x};
{name = _; arg = y};
{name = _; arg = z};
];
} ->
if name = instr then (w, (x, (y, (z, ()))))
else trace_error instr name
| {args; _} -> arity_error instr 4 args)
~model
let fv = Free_variable.of_string
let sf = Format.asprintf
let division_cost name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
let name = ns name
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
let_ ~name:"q" (sat_sub size1 size2) @@ fun q ->
(free ~name:coeff * q * size2) + free ~name:const
end
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let addlogadd name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
let name = ns name
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
let_ ~name:"a" (size1 + size2) @@ fun a ->
(free ~name:coeff * (a * log2 (int 1 + a))) + free ~name:const
end
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
(* Some instructions are oveloaded (eg COMPARE). In order to generate distinct
models at different types, we must specialize these models. The [specialization]
parameter acts as a mangling scheme to produce distinct models. *)
let name_of_instr_or_cont ?specialization instr_or_cont =
let spec = Option.fold ~none:"" ~some:(fun s -> "_" ^ s) specialization in
Interpreter_workload.string_of_instr_or_cont instr_or_cont ^ spec
module Models = struct
let const1_model name =
(* For constant-time instructions *)
Model.unknown_const1 ~name:(ns name) ~const:(fv (sf "%s_const" name))
let affine_model name =
(* For instructions with cost function
[\lambda size. const + coeff * size] *)
Model.affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let break_model name break =
Model.breakdown
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~break
let break_model_2 name break1 break2 =
Model.breakdown2
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~coeff3:(fv (sf "%s_coeff3" name))
~break1
~break2
let break_model_2_const name break1 break2 =
Model.breakdown2_const
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~coeff3:(fv (sf "%s_coeff3" name))
~const:(fv (sf "%s_const" name))
~break1
~break2
let nlogm_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * size1 log2(size2 ) ]
[\lambda size1. \lambda size2. const + coeff * size1 log2(size2)] *)
Model.nlogm
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let concat_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_total_bytes" name))
~coeff2:(fv (sf "%s_list_length" name))
let concat_pair_model name =
Model.linear_sum
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let linear_max_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * max(size1,size2 ) ]
[\lambda size1. \lambda size2. const + coeff * max(size1,size2)] *)
Model.linear_max
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let linear_min_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * min(size1,size2 ) ]
[\lambda size1. \lambda size2. const + coeff * min(size1,size2)] *)
Model.linear_min
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let pack_model name =
Model.trilinear
~name:(ns name)
~coeff1:(fv (sf "%s_micheline_nodes" name))
~coeff2:(fv (sf "%s_micheline_int_bytes" name))
~coeff3:(fv (sf "%s_micheline_string_bytes" name))
let split_ticket_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_add_coeff" name)) * max size1 size2)
+ (free ~name:(fv (sf "%s_cmp_coeff" name)) * min size1 size2)
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let open_chest_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_log_time_coeff" name)) * size1)
+ (free ~name:(fv (sf "%s_plaintext_coeff" name)) * size2)
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let verify_update_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_inputs" name))
~coeff2:(fv (sf "%s_ouputs" name))
let list_enter_body_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size_xs" @@ fun size_xs ->
lam ~name:"size_ys" @@ fun size_ys ->
if_
(eq size_xs (int 0))
(free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_coeff" name)) * size_ys))
(free ~name:(fv (sf "%s_iter" name)))
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let branching_model ~case_0 ~case_1 name =
let module M = struct
type arg_type = int * unit
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size
let arity = Model.arity_1
let model =
lam ~name:"size" @@ fun size ->
if_
(eq size (int 0))
(free ~name:(fv (sf "%s_%s" name case_0)))
(free ~name:(fv (sf "%s_%s" name case_1)))
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * unit)
let empty_branch_model name =
branching_model ~case_0:"empty" ~case_1:"nonempty" name
let apply_model name = branching_model ~case_0:"lam" ~case_1:"lamrec" name
let join_tickets_model name =
let module M = struct
type arg_type = int * (int * (int * (int * unit)))
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size -> size -> size
let arity = Model.Succ_arity Model.arity_3
let model =
lam ~name:"content_size_x" @@ fun content_size_x ->
lam ~name:"content_size_y" @@ fun content_size_y ->
lam ~name:"amount_size_x" @@ fun amount_size_x ->
lam ~name:"amount_size_y" @@ fun amount_size_y ->
free ~name:(fv (sf "%s_const" name))
+ free ~name:(fv (sf "%s_compare_coeff" name))
* min content_size_x content_size_y
+ free ~name:(fv (sf "%s_add_coeff" name))
* max amount_size_x amount_size_y
end
let name = ns name
end in
(module M : Model.Model_impl
with type arg_type = int * (int * (int * (int * unit))))
end
let ir_model ?specialization instr_or_cont =
let open Interpreter_workload in
let open Models in
let name = name_of_instr_or_cont ?specialization instr_or_cont in
match instr_or_cont with
| Instr_name instr -> (
match instr with
| N_IDrop | N_IDup | N_ISwap | N_IConst | N_ICons_pair | N_ICar | N_ICdr
| N_ICons_some | N_ICons_none | N_IIf_none | N_IOpt_map | N_ILeft
| N_IRight | N_IIf_left | N_ICons_list | N_INil | N_IIf_cons
| N_IEmpty_set | N_IEmpty_map | N_IEmpty_big_map | N_IOr | N_IAnd | N_IXor
| N_INot | N_IIf | N_ILoop | N_ILoop_left | N_IDip | N_IExec | N_IView
| N_ILambda | N_IFailwith | N_IAddress | N_ICreate_contract
| N_ISet_delegate | N_INow | N_IMin_block_time | N_IBalance | N_IHash_key
| N_IUnpack | N_ISource | N_ISender | N_ISelf | N_IAmount | N_IChainId
| N_ILevel | N_ISelf_address | N_INever | N_IUnpair | N_IVoting_power
| N_ITotal_voting_power | N_IList_size | N_ISet_size | N_IMap_size
| N_ISapling_empty_state ->
model_0 instr_or_cont (const1_model name)
| N_ISet_mem | N_ISet_update | N_IMap_mem | N_IMap_get | N_IMap_update
| N_IBig_map_mem | N_IBig_map_get | N_IBig_map_update
| N_IMap_get_and_update | N_IBig_map_get_and_update ->
model_2 instr_or_cont (nlogm_model name)
| N_IConcat_string -> model_2 instr_or_cont (concat_model name)
| N_IConcat_string_pair -> model_2 instr_or_cont (concat_pair_model name)
| N_ISlice_string -> model_1 instr_or_cont (affine_model name)
| N_IString_size -> model_0 instr_or_cont (const1_model name)
| N_IConcat_bytes -> model_2 instr_or_cont (concat_model name)
| N_IConcat_bytes_pair -> model_2 instr_or_cont (concat_pair_model name)
| N_ISlice_bytes -> model_1 instr_or_cont (affine_model name)
| N_IBytes_size -> model_0 instr_or_cont (const1_model name)
| N_IAdd_seconds_to_timestamp | N_IAdd_timestamp_to_seconds
| N_ISub_timestamp_seconds | N_IDiff_timestamps ->
model_2 instr_or_cont (linear_max_model name)
| N_IAdd_tez | N_ISub_tez | N_ISub_tez_legacy | N_IEdiv_tez ->
model_0 instr_or_cont (const1_model name)
| N_IMul_teznat | N_IMul_nattez ->
model_1 instr_or_cont (affine_model name)
| N_IEdiv_teznat -> model_2 instr_or_cont (division_cost name)
| N_IIs_nat -> model_0 instr_or_cont (const1_model name)
| N_INeg -> model_1 instr_or_cont (affine_model name)
| N_IAbs_int -> model_1 instr_or_cont (affine_model name)
| N_IInt_nat -> model_0 instr_or_cont (const1_model name)
| N_IAdd_int -> model_2 instr_or_cont (linear_max_model name)
| N_IAdd_nat -> model_2 instr_or_cont (linear_max_model name)
| N_ISub_int -> model_2 instr_or_cont (linear_max_model name)
| N_IMul_int -> model_2 instr_or_cont (addlogadd name)
| N_IMul_nat -> model_2 instr_or_cont (addlogadd name)
| N_IEdiv_int -> model_2 instr_or_cont (division_cost name)
| N_IEdiv_nat -> model_2 instr_or_cont (division_cost name)
| N_ILsl_nat -> model_1 instr_or_cont (affine_model name)
| N_ILsr_nat -> model_1 instr_or_cont (affine_model name)
| N_IOr_nat -> model_2 instr_or_cont (linear_max_model name)
| N_IAnd_nat -> model_2 instr_or_cont (linear_min_model name)
| N_IAnd_int_nat -> model_2 instr_or_cont (linear_min_model name)
| N_IXor_nat -> model_2 instr_or_cont (linear_max_model name)
| N_INot_int -> model_1 instr_or_cont (affine_model name)
| N_ICompare -> model_2 instr_or_cont (linear_min_model name)
| N_IEq | N_INeq | N_ILt | N_IGt | N_ILe | N_IGe ->
model_0 instr_or_cont (const1_model name)
| N_IPack -> model_3 instr_or_cont (pack_model name)
| N_IBlake2b | N_ISha256 | N_ISha512 | N_IKeccak | N_ISha3 ->
model_1 instr_or_cont (affine_model name)
| N_ICheck_signature_ed25519 | N_ICheck_signature_secp256k1
| N_ICheck_signature_p256 ->
model_1 instr_or_cont (affine_model name)
| N_IContract | N_ITransfer_tokens | N_IImplicit_account ->
model_0 instr_or_cont (const1_model name)
The following two instructions are expected to have an affine model . However ,
we observe 3 affine parts , on [ 0;300 ] , [ 300;400 ] and [ 400;\inf [ .
we observe 3 affine parts, on [0;300], [300;400] and [400;\inf[. *)
| N_IDupN -> model_1 instr_or_cont (break_model_2 name 300 400)
| N_IDropN -> model_1 instr_or_cont (break_model_2_const name 300 400)
| N_IDig | N_IDug | N_IDipN -> model_1 instr_or_cont (affine_model name)
| N_IAdd_bls12_381_g1 | N_IAdd_bls12_381_g2 | N_IAdd_bls12_381_fr
| N_IMul_bls12_381_g1 | N_IMul_bls12_381_g2 | N_IMul_bls12_381_fr
| N_INeg_bls12_381_g1 | N_INeg_bls12_381_g2 | N_INeg_bls12_381_fr
| N_IInt_bls12_381_z_fr ->
model_0 instr_or_cont (const1_model name)
| N_IMul_bls12_381_fr_z | N_IMul_bls12_381_z_fr
| N_IPairing_check_bls12_381 ->
model_1 instr_or_cont (affine_model name)
| N_IComb_get | N_IComb | N_IComb_set | N_IUncomb ->
model_1 instr_or_cont (affine_model name)
| N_ITicket | N_IRead_ticket -> model_0 instr_or_cont (const1_model name)
| N_ISplit_ticket -> model_2 instr_or_cont (split_ticket_model name)
| N_IJoin_tickets -> model_4 instr_or_cont (join_tickets_model name)
| N_ISapling_verify_update ->
model_2 instr_or_cont (verify_update_model name)
| N_IList_map -> model_0 instr_or_cont (const1_model name)
| N_IList_iter -> model_0 instr_or_cont (const1_model name)
| N_IIter -> model_0 instr_or_cont (const1_model name)
| N_IMap_map -> model_1 instr_or_cont (affine_model name)
| N_IMap_iter -> model_1 instr_or_cont (affine_model name)
| N_ISet_iter -> model_1 instr_or_cont (affine_model name)
| N_IHalt -> model_0 instr_or_cont (const1_model name)
| N_IApply -> model_1 instr_or_cont (apply_model name)
| N_ILog -> model_0 instr_or_cont (const1_model name)
| N_IOpen_chest -> model_2 instr_or_cont (open_chest_model name)
| N_IEmit -> model_0 instr_or_cont (const1_model name))
| Cont_name cont -> (
match cont with
| N_KNil -> model_0 instr_or_cont (const1_model name)
| N_KCons -> model_0 instr_or_cont (const1_model name)
| N_KReturn -> model_0 instr_or_cont (const1_model name)
| N_KView_exit -> model_0 instr_or_cont (const1_model name)
| N_KMap_head -> model_0 instr_or_cont (const1_model name)
| N_KUndip -> model_0 instr_or_cont (const1_model name)
| N_KLoop_in -> model_0 instr_or_cont (const1_model name)
| N_KLoop_in_left -> model_0 instr_or_cont (const1_model name)
| N_KIter -> model_1 instr_or_cont (empty_branch_model name)
| N_KList_enter_body -> model_2 instr_or_cont (list_enter_body_model name)
| N_KList_exit_body -> model_0 instr_or_cont (const1_model name)
| N_KMap_enter_body -> model_1 instr_or_cont (empty_branch_model name)
| N_KMap_exit_body -> model_2 instr_or_cont (nlogm_model name)
| N_KLog -> model_0 instr_or_cont (const1_model name))
let amplification_loop_iteration = fv "amplification_loop_iteration"
let amplification_loop_model =
Model.make
~conv:(fun iterations -> (iterations, ()))
~model:(Model.linear ~name:(ns name) ~coeff:amplification_loop_iteration)
(* The following model stitches together the per-instruction models and
adds a term corresponding to the latency induced by the timer itself. *)
let interpreter_model ?amplification ?specialization () =
Model.make_aggregated ~sub_models:[] ~model:(fun trace ->
let module Def (X : Costlang.S) = struct
type t = X.size X.repr
let applied =
let initial =
match amplification with
| None -> X.int 0
| Some amplification_factor ->
let (module Amplification_applied) =
Model.apply amplification_loop_model amplification_factor
in
let module Amplification_result = Amplification_applied (X) in
Amplification_result.applied
in
List.fold_left
(fun (acc : X.size X.repr) instr_trace ->
let (module Applied_instr) =
Model.apply
(ir_model
?specialization
instr_trace.Interpreter_workload.name)
instr_trace
in
let module R = Applied_instr (X) in
X.(acc + R.applied))
initial
trace
end in
((module Def) : Model.applied))
let make_model ?amplification ?specialization instr_name_opt =
match instr_name_opt with
| None ->
[("interpreter", interpreter_model ?amplification ?specialization ())]
| Some name ->
(* When generating code, we don't want to consider the terms specific to
Lwt and to the timer latency. Also, we restrict to single instructions. *)
let ir_model = ir_model ?specialization name in
let ir_model =
Model.precompose
(function [sized_step] -> sized_step | _ -> assert false)
ir_model
in
[
("interpreter", interpreter_model ?amplification ?specialization ());
("codegen", ir_model);
]
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/cdc7a4382ef6dfcd6c73f86d9a29b829b33d18d4/src/proto_015_PtLimaPt/lib_benchmarks_proto/interpreter_model.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Some instructions are oveloaded (eg COMPARE). In order to generate distinct
models at different types, we must specialize these models. The [specialization]
parameter acts as a mangling scheme to produce distinct models.
For constant-time instructions
For instructions with cost function
[\lambda size. const + coeff * size]
The following model stitches together the per-instruction models and
adds a term corresponding to the latency induced by the timer itself.
When generating code, we don't want to consider the terms specific to
Lwt and to the timer latency. Also, we restrict to single instructions. | Copyright ( c ) 2021 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
let ns = Namespace.of_string
let trace_error expected given =
let open Interpreter_workload in
let exp = string_of_instr_or_cont expected in
let given = string_of_instr_or_cont given in
let msg =
Format.asprintf
"Interpreter_model: trace error, expected %s, given %s"
exp
given
in
Stdlib.failwith msg
let arity_error instr expected given =
let open Interpreter_workload in
let s = string_of_instr_or_cont instr in
let msg =
Format.asprintf
"Interpreter_model: arity error (%s), expected %d, given %a"
s
expected
Interpreter_workload.pp_args
given
in
Stdlib.failwith msg
let model_0 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = []} -> if name = instr then () else trace_error instr name
| {args; _} -> arity_error instr 0 args)
~model
let model_1 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = [{name = _; arg}]} ->
if name = instr then (arg, ()) else trace_error instr name
| {args; _} -> arity_error instr 1 args)
~model
let model_2 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {name; args = [{name = _; arg = x}; {name = _; arg = y}]} ->
if name = instr then (x, (y, ())) else trace_error instr name
| {args; _} -> arity_error instr 2 args)
~model
let model_3 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {
name;
args = [{name = _; arg = x}; {name = _; arg = y}; {name = _; arg = z}];
} ->
if name = instr then (x, (y, (z, ()))) else trace_error instr name
| {args; _} -> arity_error instr 3 args)
~model
let model_4 instr model =
let open Interpreter_workload in
Model.make
~conv:(function
| {
name;
args =
[
{name = _; arg = w};
{name = _; arg = x};
{name = _; arg = y};
{name = _; arg = z};
];
} ->
if name = instr then (w, (x, (y, (z, ()))))
else trace_error instr name
| {args; _} -> arity_error instr 4 args)
~model
let fv = Free_variable.of_string
let sf = Format.asprintf
let division_cost name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
let name = ns name
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
let_ ~name:"q" (sat_sub size1 size2) @@ fun q ->
(free ~name:coeff * q * size2) + free ~name:const
end
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let addlogadd name =
let const = fv (sf "%s_const" name) in
let coeff = fv (sf "%s_coeff" name) in
let module M = struct
type arg_type = int * (int * unit)
let name = ns name
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
let_ ~name:"a" (size1 + size2) @@ fun a ->
(free ~name:coeff * (a * log2 (int 1 + a))) + free ~name:const
end
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let name_of_instr_or_cont ?specialization instr_or_cont =
let spec = Option.fold ~none:"" ~some:(fun s -> "_" ^ s) specialization in
Interpreter_workload.string_of_instr_or_cont instr_or_cont ^ spec
module Models = struct
let const1_model name =
Model.unknown_const1 ~name:(ns name) ~const:(fv (sf "%s_const" name))
let affine_model name =
Model.affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let break_model name break =
Model.breakdown
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~break
let break_model_2 name break1 break2 =
Model.breakdown2
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~coeff3:(fv (sf "%s_coeff3" name))
~break1
~break2
let break_model_2_const name break1 break2 =
Model.breakdown2_const
~name:(ns name)
~coeff1:(fv (sf "%s_coeff1" name))
~coeff2:(fv (sf "%s_coeff2" name))
~coeff3:(fv (sf "%s_coeff3" name))
~const:(fv (sf "%s_const" name))
~break1
~break2
let nlogm_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * size1 log2(size2 ) ]
[\lambda size1. \lambda size2. const + coeff * size1 log2(size2)] *)
Model.nlogm
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let concat_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_total_bytes" name))
~coeff2:(fv (sf "%s_list_length" name))
let concat_pair_model name =
Model.linear_sum
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let linear_max_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * max(size1,size2 ) ]
[\lambda size1. \lambda size2. const + coeff * max(size1,size2)] *)
Model.linear_max
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let linear_min_model name =
For instructions with cost function
[ \lambda size1 . \lambda size2 . const + coeff * min(size1,size2 ) ]
[\lambda size1. \lambda size2. const + coeff * min(size1,size2)] *)
Model.linear_min
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff:(fv (sf "%s_coeff" name))
let pack_model name =
Model.trilinear
~name:(ns name)
~coeff1:(fv (sf "%s_micheline_nodes" name))
~coeff2:(fv (sf "%s_micheline_int_bytes" name))
~coeff3:(fv (sf "%s_micheline_string_bytes" name))
let split_ticket_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_add_coeff" name)) * max size1 size2)
+ (free ~name:(fv (sf "%s_cmp_coeff" name)) * min size1 size2)
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let open_chest_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size1" @@ fun size1 ->
lam ~name:"size2" @@ fun size2 ->
free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_log_time_coeff" name)) * size1)
+ (free ~name:(fv (sf "%s_plaintext_coeff" name)) * size2)
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let verify_update_model name =
Model.bilinear_affine
~name:(ns name)
~intercept:(fv (sf "%s_const" name))
~coeff1:(fv (sf "%s_inputs" name))
~coeff2:(fv (sf "%s_ouputs" name))
let list_enter_body_model name =
let module M = struct
type arg_type = int * (int * unit)
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size
let arity = Model.arity_2
let model =
lam ~name:"size_xs" @@ fun size_xs ->
lam ~name:"size_ys" @@ fun size_ys ->
if_
(eq size_xs (int 0))
(free ~name:(fv (sf "%s_const" name))
+ (free ~name:(fv (sf "%s_coeff" name)) * size_ys))
(free ~name:(fv (sf "%s_iter" name)))
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * (int * unit))
let branching_model ~case_0 ~case_1 name =
let module M = struct
type arg_type = int * unit
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size
let arity = Model.arity_1
let model =
lam ~name:"size" @@ fun size ->
if_
(eq size (int 0))
(free ~name:(fv (sf "%s_%s" name case_0)))
(free ~name:(fv (sf "%s_%s" name case_1)))
end
let name = ns name
end in
(module M : Model.Model_impl with type arg_type = int * unit)
let empty_branch_model name =
branching_model ~case_0:"empty" ~case_1:"nonempty" name
let apply_model name = branching_model ~case_0:"lam" ~case_1:"lamrec" name
let join_tickets_model name =
let module M = struct
type arg_type = int * (int * (int * (int * unit)))
module Def (X : Costlang.S) = struct
open X
type model_type = size -> size -> size -> size -> size
let arity = Model.Succ_arity Model.arity_3
let model =
lam ~name:"content_size_x" @@ fun content_size_x ->
lam ~name:"content_size_y" @@ fun content_size_y ->
lam ~name:"amount_size_x" @@ fun amount_size_x ->
lam ~name:"amount_size_y" @@ fun amount_size_y ->
free ~name:(fv (sf "%s_const" name))
+ free ~name:(fv (sf "%s_compare_coeff" name))
* min content_size_x content_size_y
+ free ~name:(fv (sf "%s_add_coeff" name))
* max amount_size_x amount_size_y
end
let name = ns name
end in
(module M : Model.Model_impl
with type arg_type = int * (int * (int * (int * unit))))
end
let ir_model ?specialization instr_or_cont =
let open Interpreter_workload in
let open Models in
let name = name_of_instr_or_cont ?specialization instr_or_cont in
match instr_or_cont with
| Instr_name instr -> (
match instr with
| N_IDrop | N_IDup | N_ISwap | N_IConst | N_ICons_pair | N_ICar | N_ICdr
| N_ICons_some | N_ICons_none | N_IIf_none | N_IOpt_map | N_ILeft
| N_IRight | N_IIf_left | N_ICons_list | N_INil | N_IIf_cons
| N_IEmpty_set | N_IEmpty_map | N_IEmpty_big_map | N_IOr | N_IAnd | N_IXor
| N_INot | N_IIf | N_ILoop | N_ILoop_left | N_IDip | N_IExec | N_IView
| N_ILambda | N_IFailwith | N_IAddress | N_ICreate_contract
| N_ISet_delegate | N_INow | N_IMin_block_time | N_IBalance | N_IHash_key
| N_IUnpack | N_ISource | N_ISender | N_ISelf | N_IAmount | N_IChainId
| N_ILevel | N_ISelf_address | N_INever | N_IUnpair | N_IVoting_power
| N_ITotal_voting_power | N_IList_size | N_ISet_size | N_IMap_size
| N_ISapling_empty_state ->
model_0 instr_or_cont (const1_model name)
| N_ISet_mem | N_ISet_update | N_IMap_mem | N_IMap_get | N_IMap_update
| N_IBig_map_mem | N_IBig_map_get | N_IBig_map_update
| N_IMap_get_and_update | N_IBig_map_get_and_update ->
model_2 instr_or_cont (nlogm_model name)
| N_IConcat_string -> model_2 instr_or_cont (concat_model name)
| N_IConcat_string_pair -> model_2 instr_or_cont (concat_pair_model name)
| N_ISlice_string -> model_1 instr_or_cont (affine_model name)
| N_IString_size -> model_0 instr_or_cont (const1_model name)
| N_IConcat_bytes -> model_2 instr_or_cont (concat_model name)
| N_IConcat_bytes_pair -> model_2 instr_or_cont (concat_pair_model name)
| N_ISlice_bytes -> model_1 instr_or_cont (affine_model name)
| N_IBytes_size -> model_0 instr_or_cont (const1_model name)
| N_IAdd_seconds_to_timestamp | N_IAdd_timestamp_to_seconds
| N_ISub_timestamp_seconds | N_IDiff_timestamps ->
model_2 instr_or_cont (linear_max_model name)
| N_IAdd_tez | N_ISub_tez | N_ISub_tez_legacy | N_IEdiv_tez ->
model_0 instr_or_cont (const1_model name)
| N_IMul_teznat | N_IMul_nattez ->
model_1 instr_or_cont (affine_model name)
| N_IEdiv_teznat -> model_2 instr_or_cont (division_cost name)
| N_IIs_nat -> model_0 instr_or_cont (const1_model name)
| N_INeg -> model_1 instr_or_cont (affine_model name)
| N_IAbs_int -> model_1 instr_or_cont (affine_model name)
| N_IInt_nat -> model_0 instr_or_cont (const1_model name)
| N_IAdd_int -> model_2 instr_or_cont (linear_max_model name)
| N_IAdd_nat -> model_2 instr_or_cont (linear_max_model name)
| N_ISub_int -> model_2 instr_or_cont (linear_max_model name)
| N_IMul_int -> model_2 instr_or_cont (addlogadd name)
| N_IMul_nat -> model_2 instr_or_cont (addlogadd name)
| N_IEdiv_int -> model_2 instr_or_cont (division_cost name)
| N_IEdiv_nat -> model_2 instr_or_cont (division_cost name)
| N_ILsl_nat -> model_1 instr_or_cont (affine_model name)
| N_ILsr_nat -> model_1 instr_or_cont (affine_model name)
| N_IOr_nat -> model_2 instr_or_cont (linear_max_model name)
| N_IAnd_nat -> model_2 instr_or_cont (linear_min_model name)
| N_IAnd_int_nat -> model_2 instr_or_cont (linear_min_model name)
| N_IXor_nat -> model_2 instr_or_cont (linear_max_model name)
| N_INot_int -> model_1 instr_or_cont (affine_model name)
| N_ICompare -> model_2 instr_or_cont (linear_min_model name)
| N_IEq | N_INeq | N_ILt | N_IGt | N_ILe | N_IGe ->
model_0 instr_or_cont (const1_model name)
| N_IPack -> model_3 instr_or_cont (pack_model name)
| N_IBlake2b | N_ISha256 | N_ISha512 | N_IKeccak | N_ISha3 ->
model_1 instr_or_cont (affine_model name)
| N_ICheck_signature_ed25519 | N_ICheck_signature_secp256k1
| N_ICheck_signature_p256 ->
model_1 instr_or_cont (affine_model name)
| N_IContract | N_ITransfer_tokens | N_IImplicit_account ->
model_0 instr_or_cont (const1_model name)
The following two instructions are expected to have an affine model . However ,
we observe 3 affine parts , on [ 0;300 ] , [ 300;400 ] and [ 400;\inf [ .
we observe 3 affine parts, on [0;300], [300;400] and [400;\inf[. *)
| N_IDupN -> model_1 instr_or_cont (break_model_2 name 300 400)
| N_IDropN -> model_1 instr_or_cont (break_model_2_const name 300 400)
| N_IDig | N_IDug | N_IDipN -> model_1 instr_or_cont (affine_model name)
| N_IAdd_bls12_381_g1 | N_IAdd_bls12_381_g2 | N_IAdd_bls12_381_fr
| N_IMul_bls12_381_g1 | N_IMul_bls12_381_g2 | N_IMul_bls12_381_fr
| N_INeg_bls12_381_g1 | N_INeg_bls12_381_g2 | N_INeg_bls12_381_fr
| N_IInt_bls12_381_z_fr ->
model_0 instr_or_cont (const1_model name)
| N_IMul_bls12_381_fr_z | N_IMul_bls12_381_z_fr
| N_IPairing_check_bls12_381 ->
model_1 instr_or_cont (affine_model name)
| N_IComb_get | N_IComb | N_IComb_set | N_IUncomb ->
model_1 instr_or_cont (affine_model name)
| N_ITicket | N_IRead_ticket -> model_0 instr_or_cont (const1_model name)
| N_ISplit_ticket -> model_2 instr_or_cont (split_ticket_model name)
| N_IJoin_tickets -> model_4 instr_or_cont (join_tickets_model name)
| N_ISapling_verify_update ->
model_2 instr_or_cont (verify_update_model name)
| N_IList_map -> model_0 instr_or_cont (const1_model name)
| N_IList_iter -> model_0 instr_or_cont (const1_model name)
| N_IIter -> model_0 instr_or_cont (const1_model name)
| N_IMap_map -> model_1 instr_or_cont (affine_model name)
| N_IMap_iter -> model_1 instr_or_cont (affine_model name)
| N_ISet_iter -> model_1 instr_or_cont (affine_model name)
| N_IHalt -> model_0 instr_or_cont (const1_model name)
| N_IApply -> model_1 instr_or_cont (apply_model name)
| N_ILog -> model_0 instr_or_cont (const1_model name)
| N_IOpen_chest -> model_2 instr_or_cont (open_chest_model name)
| N_IEmit -> model_0 instr_or_cont (const1_model name))
| Cont_name cont -> (
match cont with
| N_KNil -> model_0 instr_or_cont (const1_model name)
| N_KCons -> model_0 instr_or_cont (const1_model name)
| N_KReturn -> model_0 instr_or_cont (const1_model name)
| N_KView_exit -> model_0 instr_or_cont (const1_model name)
| N_KMap_head -> model_0 instr_or_cont (const1_model name)
| N_KUndip -> model_0 instr_or_cont (const1_model name)
| N_KLoop_in -> model_0 instr_or_cont (const1_model name)
| N_KLoop_in_left -> model_0 instr_or_cont (const1_model name)
| N_KIter -> model_1 instr_or_cont (empty_branch_model name)
| N_KList_enter_body -> model_2 instr_or_cont (list_enter_body_model name)
| N_KList_exit_body -> model_0 instr_or_cont (const1_model name)
| N_KMap_enter_body -> model_1 instr_or_cont (empty_branch_model name)
| N_KMap_exit_body -> model_2 instr_or_cont (nlogm_model name)
| N_KLog -> model_0 instr_or_cont (const1_model name))
let amplification_loop_iteration = fv "amplification_loop_iteration"
let amplification_loop_model =
Model.make
~conv:(fun iterations -> (iterations, ()))
~model:(Model.linear ~name:(ns name) ~coeff:amplification_loop_iteration)
let interpreter_model ?amplification ?specialization () =
Model.make_aggregated ~sub_models:[] ~model:(fun trace ->
let module Def (X : Costlang.S) = struct
type t = X.size X.repr
let applied =
let initial =
match amplification with
| None -> X.int 0
| Some amplification_factor ->
let (module Amplification_applied) =
Model.apply amplification_loop_model amplification_factor
in
let module Amplification_result = Amplification_applied (X) in
Amplification_result.applied
in
List.fold_left
(fun (acc : X.size X.repr) instr_trace ->
let (module Applied_instr) =
Model.apply
(ir_model
?specialization
instr_trace.Interpreter_workload.name)
instr_trace
in
let module R = Applied_instr (X) in
X.(acc + R.applied))
initial
trace
end in
((module Def) : Model.applied))
let make_model ?amplification ?specialization instr_name_opt =
match instr_name_opt with
| None ->
[("interpreter", interpreter_model ?amplification ?specialization ())]
| Some name ->
let ir_model = ir_model ?specialization name in
let ir_model =
Model.precompose
(function [sized_step] -> sized_step | _ -> assert false)
ir_model
in
[
("interpreter", interpreter_model ?amplification ?specialization ());
("codegen", ir_model);
]
|
b5f7f98292cda1d04550fb7d4ae2692245b2a08514898820c984903159cc1ae1 | coccinelle/coccinelle | int32.mli | val zero : int32
val one : int32
val minus_one : int32
external neg : int32 -> int32 = "%int32_neg"
external add : int32 -> int32 -> int32 = "%int32_add"
external sub : int32 -> int32 -> int32 = "%int32_sub"
external mul : int32 -> int32 -> int32 = "%int32_mul"
external div : int32 -> int32 -> int32 = "%int32_div"
val unsigned_div : int32 -> int32 -> int32
external rem : int32 -> int32 -> int32 = "%int32_mod"
val unsigned_rem : int32 -> int32 -> int32
val succ : int32 -> int32
val pred : int32 -> int32
val abs : int32 -> int32
val max_int : int32
val min_int : int32
external logand : int32 -> int32 -> int32 = "%int32_and"
external logor : int32 -> int32 -> int32 = "%int32_or"
external logxor : int32 -> int32 -> int32 = "%int32_xor"
val lognot : int32 -> int32
external shift_left : int32 -> int -> int32 = "%int32_lsl"
external shift_right : int32 -> int -> int32 = "%int32_asr"
external shift_right_logical : int32 -> int -> int32 = "%int32_lsr"
external of_int : int -> int32 = "%int32_of_int"
external to_int : int32 -> int = "%int32_to_int"
val unsigned_to_int : int32 -> int option
external of_float :
float -> int32 = "caml_int32_of_float" "caml_int32_of_float_unboxed"
[@@unboxed ][@@noalloc ]
external to_float :
int32 -> float = "caml_int32_to_float" "caml_int32_to_float_unboxed"
[@@unboxed ][@@noalloc ]
external of_string : string -> int32 = "caml_int32_of_string"
val of_string_opt : string -> int32 option
val to_string : int32 -> string
external bits_of_float :
float -> int32 = "caml_int32_bits_of_float"
"caml_int32_bits_of_float_unboxed"[@@unboxed ][@@noalloc ]
external float_of_bits :
int32 -> float = "caml_int32_float_of_bits"
"caml_int32_float_of_bits_unboxed"[@@unboxed ][@@noalloc ]
type t = int32
val compare : t -> t -> int
val unsigned_compare : t -> t -> int
val equal : t -> t -> bool
val min : t -> t -> t
val max : t -> t -> t
external format : string -> int32 -> string = "caml_int32_format"
| null | https://raw.githubusercontent.com/coccinelle/coccinelle/5448bb2bd03491ffec356bf7bd6ddcdbf4d36bc9/bundles/stdcompat/stdcompat-current/interfaces/4.14/int32.mli | ocaml | val zero : int32
val one : int32
val minus_one : int32
external neg : int32 -> int32 = "%int32_neg"
external add : int32 -> int32 -> int32 = "%int32_add"
external sub : int32 -> int32 -> int32 = "%int32_sub"
external mul : int32 -> int32 -> int32 = "%int32_mul"
external div : int32 -> int32 -> int32 = "%int32_div"
val unsigned_div : int32 -> int32 -> int32
external rem : int32 -> int32 -> int32 = "%int32_mod"
val unsigned_rem : int32 -> int32 -> int32
val succ : int32 -> int32
val pred : int32 -> int32
val abs : int32 -> int32
val max_int : int32
val min_int : int32
external logand : int32 -> int32 -> int32 = "%int32_and"
external logor : int32 -> int32 -> int32 = "%int32_or"
external logxor : int32 -> int32 -> int32 = "%int32_xor"
val lognot : int32 -> int32
external shift_left : int32 -> int -> int32 = "%int32_lsl"
external shift_right : int32 -> int -> int32 = "%int32_asr"
external shift_right_logical : int32 -> int -> int32 = "%int32_lsr"
external of_int : int -> int32 = "%int32_of_int"
external to_int : int32 -> int = "%int32_to_int"
val unsigned_to_int : int32 -> int option
external of_float :
float -> int32 = "caml_int32_of_float" "caml_int32_of_float_unboxed"
[@@unboxed ][@@noalloc ]
external to_float :
int32 -> float = "caml_int32_to_float" "caml_int32_to_float_unboxed"
[@@unboxed ][@@noalloc ]
external of_string : string -> int32 = "caml_int32_of_string"
val of_string_opt : string -> int32 option
val to_string : int32 -> string
external bits_of_float :
float -> int32 = "caml_int32_bits_of_float"
"caml_int32_bits_of_float_unboxed"[@@unboxed ][@@noalloc ]
external float_of_bits :
int32 -> float = "caml_int32_float_of_bits"
"caml_int32_float_of_bits_unboxed"[@@unboxed ][@@noalloc ]
type t = int32
val compare : t -> t -> int
val unsigned_compare : t -> t -> int
val equal : t -> t -> bool
val min : t -> t -> t
val max : t -> t -> t
external format : string -> int32 -> string = "caml_int32_format"
| |
7e787cbd13cad0d2b09000bab6dadfd51270fd267334eb0409e87080c4fe9698 | chaoxu/fancy-walks | D.hs | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances #
{-# OPTIONS_GHC -O2 #-}
import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control . Monad . State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
import Debug.Trace
parseInput = do
t <- readInt
k <- readInt
querys <- replicateM t $ (,) <$> readInteger <*> readInteger
return (k, querys)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = BS.putStr =<< solve . evalState parseInput <$> BS.getContents
solve (k, querys) = BS.unlines [ BS.pack . show $ solveCase k countWays query | query <- querys]
where
countWays :: (Int,Int) -> ModP
countWays = (cache!)
where
bnds = ((0,0),(1024,1024))
cache = listArray bnds $ map go $ range bnds :: Array (Int,Int) ModP
go (prev, 0) = ModP 1
go (prev, left) = ans47 + ansOther
where
ans47 = if prev == 0 || prev > k then ModP 2 * countWays (1, left - 1) else ModP 0
ansOther = ModP 8 * countWays (if prev == 0 then 0 else prev + 1, left - 1)
solveCase k countWays (lo, hi) = solveNumber k countWays (hi + 1) - solveNumber k countWays lo
-- calculate the answer for [0,n)
solveNumber k countWays n = fromInteger n - go str 0 (length str - 1)
where
str = show n
go [] _ _ = ModP 0
go (x:xs) prev left = sum lst + if x /= '4' && x /= '7' || prev > k || prev == 0 then go xs (trans x prev) (left - 1) else 0
where
lst = [ countWays (trans i prev, left)
| i <- ['0'..pred x]
, i /= '4' && i /= '7' || prev > k || prev == 0
]
trans '4' _ = 1
trans '7' _ = 1
trans _ 0 = 0
trans _ prev = prev + 1
modulo :: Integral a => a
modulo = 1000000007
newtype ModP = ModP Integer deriving Eq
instance Show ModP where
show (ModP n) = show n
instance Num ModP where
ModP a + ModP b = ModP $ (a + b) `mod` modulo
ModP a - ModP b = ModP $ (a - b) `mod` modulo
ModP a * ModP b = ModP $ fromIntegral ((fromIntegral a * fromIntegral b :: Int64) `mod` modulo)
abs = undefined
signum = undefined
fromInteger = ModP . fromInteger . (`mod` modulo)
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
class (Monad m) => MonadState s m | m -> s where
get :: m s
put :: s -> m ()
modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
s <- get
put (f s)
gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
s <- get
return (f s)
newtype State s a = State { runState :: s -> (a, s) }
instance Functor (State s) where
fmap f m = State $ \s -> let
(a, s') = runState m s
in (f a, s')
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return a = State $ \s -> (a, s)
m >>= k = State $ \s -> let
(a, s') = runState m s
in runState (k a) s'
instance MonadState s (State s) where
get = State $ \s -> (s, s)
put s = State $ \_ -> ((), s)
evalState :: State s a -> s -> a
evalState m s = fst (runState m s)
execState :: State s a -> s -> s
execState m s = snd (runState m s)
mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m
withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f
state = State
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/codeforces.com/95/D.hs | haskell | # OPTIONS_GHC -O2 #
calculate the answer for [0,n)
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | # LANGUAGE MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances #
import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control . Monad . State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
import Debug.Trace
parseInput = do
t <- readInt
k <- readInt
querys <- replicateM t $ (,) <$> readInteger <*> readInteger
return (k, querys)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = BS.putStr =<< solve . evalState parseInput <$> BS.getContents
solve (k, querys) = BS.unlines [ BS.pack . show $ solveCase k countWays query | query <- querys]
where
countWays :: (Int,Int) -> ModP
countWays = (cache!)
where
bnds = ((0,0),(1024,1024))
cache = listArray bnds $ map go $ range bnds :: Array (Int,Int) ModP
go (prev, 0) = ModP 1
go (prev, left) = ans47 + ansOther
where
ans47 = if prev == 0 || prev > k then ModP 2 * countWays (1, left - 1) else ModP 0
ansOther = ModP 8 * countWays (if prev == 0 then 0 else prev + 1, left - 1)
solveCase k countWays (lo, hi) = solveNumber k countWays (hi + 1) - solveNumber k countWays lo
solveNumber k countWays n = fromInteger n - go str 0 (length str - 1)
where
str = show n
go [] _ _ = ModP 0
go (x:xs) prev left = sum lst + if x /= '4' && x /= '7' || prev > k || prev == 0 then go xs (trans x prev) (left - 1) else 0
where
lst = [ countWays (trans i prev, left)
| i <- ['0'..pred x]
, i /= '4' && i /= '7' || prev > k || prev == 0
]
trans '4' _ = 1
trans '7' _ = 1
trans _ 0 = 0
trans _ prev = prev + 1
modulo :: Integral a => a
modulo = 1000000007
newtype ModP = ModP Integer deriving Eq
instance Show ModP where
show (ModP n) = show n
instance Num ModP where
ModP a + ModP b = ModP $ (a + b) `mod` modulo
ModP a - ModP b = ModP $ (a - b) `mod` modulo
ModP a * ModP b = ModP $ fromIntegral ((fromIntegral a * fromIntegral b :: Int64) `mod` modulo)
abs = undefined
signum = undefined
fromInteger = ModP . fromInteger . (`mod` modulo)
class (Monad m) => MonadState s m | m -> s where
get :: m s
put :: s -> m ()
modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
s <- get
put (f s)
gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
s <- get
return (f s)
newtype State s a = State { runState :: s -> (a, s) }
instance Functor (State s) where
fmap f m = State $ \s -> let
(a, s') = runState m s
in (f a, s')
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return a = State $ \s -> (a, s)
m >>= k = State $ \s -> let
(a, s') = runState m s
in runState (k a) s'
instance MonadState s (State s) where
get = State $ \s -> (s, s)
put s = State $ \_ -> ((), s)
evalState :: State s a -> s -> a
evalState m s = fst (runState m s)
execState :: State s a -> s -> s
execState m s = snd (runState m s)
mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m
withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f
state = State
|
097b8bb5d0f49722e74aacd79a8ad1786b3dcfa0d2ea600bcdf6fd418510e4e8 | Apress/practical-webdev-haskell | AesonHelper.hs | module Adapter.HTTP.API.Types.AesonHelper where
import ClassyPrelude
import Data.Aeson.TH
import Data.Aeson.Types
import Language.Haskell.TH.Syntax
withSmartConstructor :: (a -> Either [Text] b) -> a -> Parser b
withSmartConstructor constructor a =
case constructor a of
Left errs -> fail $ intercalate ". " . map unpack $ errs
Right val -> return val
deriveJSONRecord :: Name -> Q [Dec]
deriveJSONRecord record =
let lowerCaseFirst (y:ys) = toLower [y] <> ys
lowerCaseFirst "" = ""
structName = fromMaybe "" . lastMay . splitElem '.' . show $ record
opts = defaultOptions
{ fieldLabelModifier = lowerCaseFirst . drop (length structName)
}
in deriveJSON opts record
deriveJSONSumType :: Name -> Q [Dec]
deriveJSONSumType record =
let structName = fromMaybe "" . lastMay . splitElem '.' . show $ record
opts = defaultOptions
{ constructorTagModifier = drop (length structName)
, tagSingleConstructors = True
}
in deriveJSON opts record
deriveToJSONUnwrap :: Name -> Q [Dec]
deriveToJSONUnwrap =
let opts = defaultOptions { unwrapUnaryRecords = True }
in deriveToJSON opts | null | https://raw.githubusercontent.com/Apress/practical-webdev-haskell/17b90c06030def254bb0497b9e357f5d3b96d0cf/09/src/Adapter/HTTP/API/Types/AesonHelper.hs | haskell | module Adapter.HTTP.API.Types.AesonHelper where
import ClassyPrelude
import Data.Aeson.TH
import Data.Aeson.Types
import Language.Haskell.TH.Syntax
withSmartConstructor :: (a -> Either [Text] b) -> a -> Parser b
withSmartConstructor constructor a =
case constructor a of
Left errs -> fail $ intercalate ". " . map unpack $ errs
Right val -> return val
deriveJSONRecord :: Name -> Q [Dec]
deriveJSONRecord record =
let lowerCaseFirst (y:ys) = toLower [y] <> ys
lowerCaseFirst "" = ""
structName = fromMaybe "" . lastMay . splitElem '.' . show $ record
opts = defaultOptions
{ fieldLabelModifier = lowerCaseFirst . drop (length structName)
}
in deriveJSON opts record
deriveJSONSumType :: Name -> Q [Dec]
deriveJSONSumType record =
let structName = fromMaybe "" . lastMay . splitElem '.' . show $ record
opts = defaultOptions
{ constructorTagModifier = drop (length structName)
, tagSingleConstructors = True
}
in deriveJSON opts record
deriveToJSONUnwrap :: Name -> Q [Dec]
deriveToJSONUnwrap =
let opts = defaultOptions { unwrapUnaryRecords = True }
in deriveToJSON opts | |
988f5fcac67b2d58a3443aa3a882e79b443abd74a14ba63d01ee336a95ff557a | icicle-lang/zebra-ambiata | Data.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE NoImplicitPrelude #
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Zebra.Table.Data (
Field(..)
, FieldName(..)
, Variant(..)
, VariantName(..)
, Tag(..)
, Default(..)
, hasVariant
, lookupVariant
, forVariant
, xmapM
, ximapM
, cmapM
, cimapM
, foreignOfTags
, tagsOfForeign
) where
import Data.String (IsString(..))
import qualified Data.Text as Text
import qualified Data.Vector.Mutable as MBoxed
import Foreign.Storable (Storable)
import GHC.Generics (Generic)
import P
import System.IO.Unsafe (unsafePerformIO)
import qualified X.Data.Vector as Boxed
import X.Data.Vector.Cons (Cons)
import qualified X.Data.Vector.Cons as Cons
import qualified X.Data.Vector.Storable as Storable
import X.Text.Show (gshowsPrec)
newtype FieldName =
FieldName {
unFieldName :: Text
} deriving (Eq, Ord, Generic)
instance NFData FieldName
instance Show FieldName where
showsPrec p =
showsPrec p . unFieldName
instance IsString FieldName where
fromString =
FieldName . Text.pack
data Field a =
Field {
fieldName :: !FieldName
, fieldData :: !a
} deriving (Eq, Ord, Generic, Functor, Foldable, Traversable)
instance NFData a => NFData (Field a)
instance Show a => Show (Field a) where
showsPrec =
gshowsPrec
newtype VariantName =
VariantName {
unVariantName :: Text
} deriving (Eq, Ord, Generic)
instance NFData VariantName
instance Show VariantName where
showsPrec p =
showsPrec p . unVariantName
instance IsString VariantName where
fromString =
VariantName . Text.pack
data Variant a =
Variant {
variantName :: !VariantName
, variantData :: !a
} deriving (Eq, Ord, Generic, Functor, Foldable, Traversable)
instance NFData a => NFData (Variant a)
instance Show a => Show (Variant a) where
showsPrec =
gshowsPrec
newtype Tag =
Tag {
unTag :: Int64
} deriving (Eq, Ord, Generic, Storable, Num, Enum, Real, Integral)
instance NFData Tag
instance Show Tag where
showsPrec =
gshowsPrec
--
Ideally this would contain a Zebra . Table . Logical . Table / Value which is the
default value for the Table / Column . However , all we need right now is to
-- be able to default to empty lists/maps and 'none' enum values, so we go
-- for a simpler approach where the default value is implied.
--
data Default =
DenyDefault -- ^ Table/column can NOT be replaced by a default value if missing.
| AllowDefault -- ^ Table/column can be replaced by a default value if missing.
deriving (Eq, Ord, Show, Generic)
instance NFData Default
------------------------------------------------------------------------
hasVariant :: Tag -> Cons Boxed.Vector (Variant a) -> Bool
hasVariant tag xs =
fromIntegral tag < Cons.length xs
# INLINE hasVariant #
lookupVariant :: Tag -> Cons Boxed.Vector (Variant a) -> Maybe (Variant a)
lookupVariant tag xs =
Cons.index (fromIntegral tag) xs
# INLINE lookupVariant #
forVariant ::
Cons Boxed.Vector (Variant a)
-> (Tag -> VariantName -> a -> Either x b)
-> Either x (Cons Boxed.Vector (Variant b))
forVariant xs f =
flip cimapM xs $ \i (Variant name x) ->
Variant name <$> f (fromIntegral i) name x
# INLINE forVariant #
xmapM :: (a -> Either x b) -> Boxed.Vector a -> Either x (Boxed.Vector b)
xmapM f xs = {-# SCC xmapM #-}
ximapM (\_ x -> f x) xs
# INLINE xmapM #
ximapM :: (Int -> a -> Either x b) -> Boxed.Vector a -> Either x (Boxed.Vector b)
# SCC ximapM #
unsafePerformIO $ do
let
!n =
Boxed.length xs
m <- MBoxed.new n
let
loop !i =
if i < n then
let
!x0 =
Boxed.unsafeIndex xs i
in
case f i x0 of
Left err ->
pure $! Left err
Right x -> do
MBoxed.unsafeWrite m i x
loop (i + 1)
else do
!ys <- Boxed.unsafeFreeze m
pure $! Right ys
loop 0
# INLINE ximapM #
cmapM :: (a -> Either x b) -> Cons Boxed.Vector a -> Either x (Cons Boxed.Vector b)
# SCC cmapM #
fmap Cons.unsafeFromVector .
xmapM f .
Cons.toVector
# INLINE cmapM #
cimapM :: (Int -> a -> Either x b) -> Cons Boxed.Vector a -> Either x (Cons Boxed.Vector b)
cimapM f = {-# SCC cimapM #-}
fmap Cons.unsafeFromVector .
ximapM f .
Cons.toVector
# INLINE cimapM #
------------------------------------------------------------------------
foreignOfTags :: Storable.Vector Tag -> Storable.Vector Int64
foreignOfTags =
Storable.unsafeCast
# INLINE foreignOfTags #
tagsOfForeign :: Storable.Vector Int64 -> Storable.Vector Tag
tagsOfForeign =
Storable.unsafeCast
# INLINE tagsOfForeign #
| null | https://raw.githubusercontent.com/icicle-lang/zebra-ambiata/394ee5f98b4805df2c76abb52cdaad9fd7825f81/zebra-core/src/Zebra/Table/Data.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE DeriveTraversable #
# OPTIONS_GHC -funbox-strict-fields #
be able to default to empty lists/maps and 'none' enum values, so we go
for a simpler approach where the default value is implied.
^ Table/column can NOT be replaced by a default value if missing.
^ Table/column can be replaced by a default value if missing.
----------------------------------------------------------------------
# SCC xmapM #
# SCC cimapM #
---------------------------------------------------------------------- | # LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE NoImplicitPrelude #
module Zebra.Table.Data (
Field(..)
, FieldName(..)
, Variant(..)
, VariantName(..)
, Tag(..)
, Default(..)
, hasVariant
, lookupVariant
, forVariant
, xmapM
, ximapM
, cmapM
, cimapM
, foreignOfTags
, tagsOfForeign
) where
import Data.String (IsString(..))
import qualified Data.Text as Text
import qualified Data.Vector.Mutable as MBoxed
import Foreign.Storable (Storable)
import GHC.Generics (Generic)
import P
import System.IO.Unsafe (unsafePerformIO)
import qualified X.Data.Vector as Boxed
import X.Data.Vector.Cons (Cons)
import qualified X.Data.Vector.Cons as Cons
import qualified X.Data.Vector.Storable as Storable
import X.Text.Show (gshowsPrec)
newtype FieldName =
FieldName {
unFieldName :: Text
} deriving (Eq, Ord, Generic)
instance NFData FieldName
instance Show FieldName where
showsPrec p =
showsPrec p . unFieldName
instance IsString FieldName where
fromString =
FieldName . Text.pack
data Field a =
Field {
fieldName :: !FieldName
, fieldData :: !a
} deriving (Eq, Ord, Generic, Functor, Foldable, Traversable)
instance NFData a => NFData (Field a)
instance Show a => Show (Field a) where
showsPrec =
gshowsPrec
newtype VariantName =
VariantName {
unVariantName :: Text
} deriving (Eq, Ord, Generic)
instance NFData VariantName
instance Show VariantName where
showsPrec p =
showsPrec p . unVariantName
instance IsString VariantName where
fromString =
VariantName . Text.pack
data Variant a =
Variant {
variantName :: !VariantName
, variantData :: !a
} deriving (Eq, Ord, Generic, Functor, Foldable, Traversable)
instance NFData a => NFData (Variant a)
instance Show a => Show (Variant a) where
showsPrec =
gshowsPrec
newtype Tag =
Tag {
unTag :: Int64
} deriving (Eq, Ord, Generic, Storable, Num, Enum, Real, Integral)
instance NFData Tag
instance Show Tag where
showsPrec =
gshowsPrec
Ideally this would contain a Zebra . Table . Logical . Table / Value which is the
default value for the Table / Column . However , all we need right now is to
data Default =
deriving (Eq, Ord, Show, Generic)
instance NFData Default
hasVariant :: Tag -> Cons Boxed.Vector (Variant a) -> Bool
hasVariant tag xs =
fromIntegral tag < Cons.length xs
# INLINE hasVariant #
lookupVariant :: Tag -> Cons Boxed.Vector (Variant a) -> Maybe (Variant a)
lookupVariant tag xs =
Cons.index (fromIntegral tag) xs
# INLINE lookupVariant #
forVariant ::
Cons Boxed.Vector (Variant a)
-> (Tag -> VariantName -> a -> Either x b)
-> Either x (Cons Boxed.Vector (Variant b))
forVariant xs f =
flip cimapM xs $ \i (Variant name x) ->
Variant name <$> f (fromIntegral i) name x
# INLINE forVariant #
xmapM :: (a -> Either x b) -> Boxed.Vector a -> Either x (Boxed.Vector b)
ximapM (\_ x -> f x) xs
# INLINE xmapM #
ximapM :: (Int -> a -> Either x b) -> Boxed.Vector a -> Either x (Boxed.Vector b)
# SCC ximapM #
unsafePerformIO $ do
let
!n =
Boxed.length xs
m <- MBoxed.new n
let
loop !i =
if i < n then
let
!x0 =
Boxed.unsafeIndex xs i
in
case f i x0 of
Left err ->
pure $! Left err
Right x -> do
MBoxed.unsafeWrite m i x
loop (i + 1)
else do
!ys <- Boxed.unsafeFreeze m
pure $! Right ys
loop 0
# INLINE ximapM #
cmapM :: (a -> Either x b) -> Cons Boxed.Vector a -> Either x (Cons Boxed.Vector b)
# SCC cmapM #
fmap Cons.unsafeFromVector .
xmapM f .
Cons.toVector
# INLINE cmapM #
cimapM :: (Int -> a -> Either x b) -> Cons Boxed.Vector a -> Either x (Cons Boxed.Vector b)
fmap Cons.unsafeFromVector .
ximapM f .
Cons.toVector
# INLINE cimapM #
foreignOfTags :: Storable.Vector Tag -> Storable.Vector Int64
foreignOfTags =
Storable.unsafeCast
# INLINE foreignOfTags #
tagsOfForeign :: Storable.Vector Int64 -> Storable.Vector Tag
tagsOfForeign =
Storable.unsafeCast
# INLINE tagsOfForeign #
|
f2b6ca31589ae32a94d8574f720744e21eb65c75e11155ca20b03443cd81906f | gwathlobal/CotD | mission.lisp | (in-package :cotd)
(defclass mission ()
((mission-type-id :initarg :mission-type-id :accessor mission-type-id)
(x :initarg :x :accessor x)
(y :initarg :y :accessor y)
(world-sector :initarg :world-sector :accessor world-sector)
(faction-list :initform () :initarg :faction-list :accessor faction-list) ;; list of faction-type-id
(level-modifier-list :initform () :initarg :level-modifier-list :accessor level-modifier-list) ;; list of level-modifier-id
(player-lvl-mod-placement-id :initarg :player-lvl-mod-placement-id :accessor player-lvl-mod-placement-id) ;; serves the id of the player specific faction placement function
(player-specific-faction :initarg :player-specific-faction :accessor player-specific-faction)
))
(defmethod name ((mission mission))
(name (get-mission-type-by-id (mission-type-id mission))))
;;=======================
;; Auxiliary funcs
;;=======================
(defun populate-level-with-mobs (level mob-template-list placement-func)
(loop for (mob-template-id num is-player) in mob-template-list do
(loop repeat num do
(if is-player
(progn
(setf *player* (make-instance 'player :mob-type mob-template-id))
(funcall placement-func level *player*))
(funcall placement-func level (make-instance 'mob :mob-type mob-template-id))))))
(defun find-unoccupied-place-on-top (level mob)
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
with nz = nil
for x = (random max-x)
for y = (random max-y)
for z = (1- (array-dimension (terrain level) 2))
do
(setf (x mob) x (y mob) y (z mob) z)
(setf nz (apply-gravity mob))
until (and (and (> x 10) (< x (- max-x 10)) (> y 10) (< y (- max-y 10)))
(get-terrain-type-trait (get-terrain-* level x y nz) +terrain-trait-blocks-move-floor+)
nz
(> nz 2)
(not (get-mob-* level x y nz))
(eq (check-move-on-level mob x y nz) t)
(/= (get-level-connect-map-value level x y nz (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob))
+connect-room-none+)
(or (not (mob-ability-p mob +mob-abil-demon+))
(and (mob-ability-p mob +mob-abil-demon+)
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
with result = t
when (and (= (feature-type feature) +feature-start-repel-demons+)
(< (get-distance x y (x feature) (y feature)) 15))
do
(setf result nil)
(loop-finish)
when (and (= (feature-type feature) +feature-start-strong-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist-strong*))
do
(setf result nil)
(loop-finish)
finally (return result)))))
finally (setf (x mob) x (y mob) y (z mob) nz)
(add-mob-to-level-list level mob)))
(defun find-unoccupied-place-water (level mob)
(let ((water-cells nil)
(r-cell))
(loop for x from 0 below (array-dimension (terrain level) 0) do
(loop for y from 0 below (array-dimension (terrain level) 1) do
(loop for z from 0 below (array-dimension (terrain level) 2)
when (and (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-water+)
(eq (check-move-on-level mob x y z) t))
do
(push (list x y z) water-cells))))
(if water-cells
(progn
(setf r-cell (nth (random (length water-cells)) water-cells))
(setf (x mob) (first r-cell) (y mob) (second r-cell) (z mob) (third r-cell))
(add-mob-to-level-list level mob))
(progn
(find-unoccupied-place-outside level mob)))
)
)
(defun find-unoccupied-place-outside (level mob)
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
for x = (random max-x)
for y = (random max-y)
for z = 2
until (and (not (and (> x 7) (< x (- max-x 7)) (> y 7) (< y (- max-y 7))))
(eq (check-move-on-level mob x y z) t)
(not (get-mob-* level x y z))
(get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level x y z (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob))
+connect-room-none+)
(or (not (mob-ability-p mob +mob-abil-demon+))
(and (mob-ability-p mob +mob-abil-demon+)
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
with result = t
when (and (= (feature-type feature) +feature-start-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist*))
do
(setf result nil)
(loop-finish)
when (and (= (feature-type feature) +feature-start-strong-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist-strong*))
do
(setf result nil)
(loop-finish)
finally (return result)))))
finally (setf (x mob) x (y mob) y (z mob) z)
(add-mob-to-level-list level mob)))
(defun find-unoccupied-place-inside (level mob)
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
for x = (random max-x)
for y = (random max-y)
for z = 2
until (and (and (> x 10) (< x (- max-x 10)) (> y 10) (< y (- max-y 10)))
(eq (check-move-on-level mob x y z) t)
(not (get-mob-* level x y z))
(get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level x y z (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob))
+connect-room-none+)
(or (and (not (mob-ability-p mob +mob-abil-demon+))
(not (mob-ability-p mob +mob-abil-angel+)))
(and (or (mob-ability-p mob +mob-abil-demon+)
(mob-ability-p mob +mob-abil-angel+))
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
with result = t
when (and (= (feature-type feature) +feature-start-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist*))
do
(setf result nil)
(loop-finish)
when (and (= (feature-type feature) +feature-start-strong-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist-strong*))
do
(setf result nil)
(loop-finish)
when (and (get-feature-type-trait feature +feature-trait-remove-on-dungeon-generation+)
(< (get-distance x y (x feature) (y feature)) 2))
do
(setf result nil)
(loop-finish)
finally (return result)))))
finally (setf (x mob) x (y mob) y (z mob) z)
(add-mob-to-level-list level mob)))
(defun find-unoccupied-place-around (level mob sx sy sz &key (no-center nil))
(loop with min-x = sx
with max-x = sx
with min-y = sy
with max-y = sy
with max-x-level = (array-dimension (terrain level) 0)
with max-y-level = (array-dimension (terrain level) 1)
for cell-list = nil
do
;; prepare the list of cells
;; north
(setf cell-list (append cell-list (loop with y = min-y
for x from min-x to max-x
collect (cons x y))))
;; east
(setf cell-list (append cell-list (loop with x = max-x
for y from min-y to max-y
collect (cons x y))))
;; south
(setf cell-list (append cell-list (loop with y = max-y
for x from min-x to max-x
collect (cons x y))))
;; west
(setf cell-list (append cell-list (loop with x = min-x
for y from min-y to max-y
collect (cons x y))))
;; iterate through the list of cells
(loop for (x . y) in cell-list
when (and (>= x 0) (< x max-x-level) (>= y 0) (< y max-y-level)
(eq (check-move-on-level mob x y sz) t)
(get-terrain-type-trait (get-terrain-* level x y sz) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level x y sz (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob))
+connect-room-none+)
(or (null no-center)
(and no-center
(or (/= x sx) (/= y sy)))))
do
(setf (x mob) x (y mob) y (z mob) sz)
(add-mob-to-level-list level mob)
(return-from find-unoccupied-place-around mob))
;; if the loop is not over - increase the boundaries
(decf min-x)
(decf min-y)
(incf max-x)
(incf max-y)
))
(defun find-unoccupied-place-mimic (level mob1 mob2 mob3 &key (inside nil))
;; function specifically for mimics
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
for x = (random max-x)
for y = (random max-y)
for z = 2
until (and (if inside
(and (> x 10) (< x (- max-x 10)) (> y 10) (< y (- max-y 10)))
(not (and (> x 7) (< x (- max-x 7)) (> y 7) (< y (- max-y 7)))))
(eq (check-move-on-level mob1 (1- x) (1- y) z) t)
(eq (check-move-on-level mob2 (1+ x) (1- y) z) t)
(eq (check-move-on-level mob3 x (1+ y) z) t)
(not (get-mob-* level (1- x) (1- y) z))
(not (get-mob-* level (1+ x) (1- y) z))
(not (get-mob-* level x (1+ y) z))
(get-terrain-type-trait (get-terrain-* level (1- x) (1- y) z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* level (1+ x) (1- y) z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* level x (1+ y) z) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level (1- x) (1- y) z (if (riding-mob-id mob1)
(map-size (get-mob-by-id (riding-mob-id mob1)))
(map-size mob1))
(get-mob-move-mode mob1))
+connect-room-none+)
(/= (get-level-connect-map-value level (1+ x) (1- y) z (if (riding-mob-id mob2)
(map-size (get-mob-by-id (riding-mob-id mob2)))
(map-size mob2))
(get-mob-move-mode mob2))
+connect-room-none+)
(/= (get-level-connect-map-value level x (1+ y) z (if (riding-mob-id mob3)
(map-size (get-mob-by-id (riding-mob-id mob3)))
(map-size mob3))
(get-mob-move-mode mob3))
+connect-room-none+)
)
finally (setf (x mob1) (1- x) (y mob1) (1- y) (z mob1) z)
(add-mob-to-level-list level mob1)
(setf (x mob2) (1+ x) (y mob2) (1- y) (z mob2) z)
(add-mob-to-level-list level mob2)
(setf (x mob3) x (y mob3) (1+ y) (z mob3) z)
(add-mob-to-level-list level mob3)
))
(defun find-player-start-position (level mob feature-type-id)
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
when (= (feature-type feature) feature-type-id)
do
(setf (x mob) (x feature) (y mob) (y feature) (z mob) (z feature))
(add-mob-to-level-list level mob)
(loop-finish)))
(defun set-up-outdoor-light (level light-power)
(setf (outdoor-light level) light-power)
;; propagate light from above to determine which parts of the map are outdoor and which are "inside"
;; also set up all stationary light sources
(loop for x from 0 below (array-dimension (light-map level) 0) do
(loop for y from 0 below (array-dimension (light-map level) 1)
for light-pwr = 100
do
(loop for z from (1- (array-dimension (light-map level) 2)) downto 0
do
(setf (aref (light-map level) x y z) light-pwr)
(when (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-blocks-move-floor+)
(setf light-pwr 0))
(when (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-light-source+)
(add-light-source level (make-light-source x y z (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-light-source+))))
)))
)
| null | https://raw.githubusercontent.com/gwathlobal/CotD/d01ef486cc1d3b21d2ad670ebdb443e957290aa2/src/mission.lisp | lisp | list of faction-type-id
list of level-modifier-id
serves the id of the player specific faction placement function
=======================
Auxiliary funcs
=======================
prepare the list of cells
north
east
south
west
iterate through the list of cells
if the loop is not over - increase the boundaries
function specifically for mimics
propagate light from above to determine which parts of the map are outdoor and which are "inside"
also set up all stationary light sources | (in-package :cotd)
(defclass mission ()
((mission-type-id :initarg :mission-type-id :accessor mission-type-id)
(x :initarg :x :accessor x)
(y :initarg :y :accessor y)
(world-sector :initarg :world-sector :accessor world-sector)
(player-specific-faction :initarg :player-specific-faction :accessor player-specific-faction)
))
(defmethod name ((mission mission))
(name (get-mission-type-by-id (mission-type-id mission))))
(defun populate-level-with-mobs (level mob-template-list placement-func)
(loop for (mob-template-id num is-player) in mob-template-list do
(loop repeat num do
(if is-player
(progn
(setf *player* (make-instance 'player :mob-type mob-template-id))
(funcall placement-func level *player*))
(funcall placement-func level (make-instance 'mob :mob-type mob-template-id))))))
(defun find-unoccupied-place-on-top (level mob)
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
with nz = nil
for x = (random max-x)
for y = (random max-y)
for z = (1- (array-dimension (terrain level) 2))
do
(setf (x mob) x (y mob) y (z mob) z)
(setf nz (apply-gravity mob))
until (and (and (> x 10) (< x (- max-x 10)) (> y 10) (< y (- max-y 10)))
(get-terrain-type-trait (get-terrain-* level x y nz) +terrain-trait-blocks-move-floor+)
nz
(> nz 2)
(not (get-mob-* level x y nz))
(eq (check-move-on-level mob x y nz) t)
(/= (get-level-connect-map-value level x y nz (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob))
+connect-room-none+)
(or (not (mob-ability-p mob +mob-abil-demon+))
(and (mob-ability-p mob +mob-abil-demon+)
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
with result = t
when (and (= (feature-type feature) +feature-start-repel-demons+)
(< (get-distance x y (x feature) (y feature)) 15))
do
(setf result nil)
(loop-finish)
when (and (= (feature-type feature) +feature-start-strong-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist-strong*))
do
(setf result nil)
(loop-finish)
finally (return result)))))
finally (setf (x mob) x (y mob) y (z mob) nz)
(add-mob-to-level-list level mob)))
(defun find-unoccupied-place-water (level mob)
(let ((water-cells nil)
(r-cell))
(loop for x from 0 below (array-dimension (terrain level) 0) do
(loop for y from 0 below (array-dimension (terrain level) 1) do
(loop for z from 0 below (array-dimension (terrain level) 2)
when (and (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-water+)
(eq (check-move-on-level mob x y z) t))
do
(push (list x y z) water-cells))))
(if water-cells
(progn
(setf r-cell (nth (random (length water-cells)) water-cells))
(setf (x mob) (first r-cell) (y mob) (second r-cell) (z mob) (third r-cell))
(add-mob-to-level-list level mob))
(progn
(find-unoccupied-place-outside level mob)))
)
)
(defun find-unoccupied-place-outside (level mob)
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
for x = (random max-x)
for y = (random max-y)
for z = 2
until (and (not (and (> x 7) (< x (- max-x 7)) (> y 7) (< y (- max-y 7))))
(eq (check-move-on-level mob x y z) t)
(not (get-mob-* level x y z))
(get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level x y z (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob))
+connect-room-none+)
(or (not (mob-ability-p mob +mob-abil-demon+))
(and (mob-ability-p mob +mob-abil-demon+)
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
with result = t
when (and (= (feature-type feature) +feature-start-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist*))
do
(setf result nil)
(loop-finish)
when (and (= (feature-type feature) +feature-start-strong-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist-strong*))
do
(setf result nil)
(loop-finish)
finally (return result)))))
finally (setf (x mob) x (y mob) y (z mob) z)
(add-mob-to-level-list level mob)))
(defun find-unoccupied-place-inside (level mob)
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
for x = (random max-x)
for y = (random max-y)
for z = 2
until (and (and (> x 10) (< x (- max-x 10)) (> y 10) (< y (- max-y 10)))
(eq (check-move-on-level mob x y z) t)
(not (get-mob-* level x y z))
(get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level x y z (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob))
+connect-room-none+)
(or (and (not (mob-ability-p mob +mob-abil-demon+))
(not (mob-ability-p mob +mob-abil-angel+)))
(and (or (mob-ability-p mob +mob-abil-demon+)
(mob-ability-p mob +mob-abil-angel+))
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
with result = t
when (and (= (feature-type feature) +feature-start-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist*))
do
(setf result nil)
(loop-finish)
when (and (= (feature-type feature) +feature-start-strong-repel-demons+)
(< (get-distance x y (x feature) (y feature)) *repel-demons-dist-strong*))
do
(setf result nil)
(loop-finish)
when (and (get-feature-type-trait feature +feature-trait-remove-on-dungeon-generation+)
(< (get-distance x y (x feature) (y feature)) 2))
do
(setf result nil)
(loop-finish)
finally (return result)))))
finally (setf (x mob) x (y mob) y (z mob) z)
(add-mob-to-level-list level mob)))
(defun find-unoccupied-place-around (level mob sx sy sz &key (no-center nil))
(loop with min-x = sx
with max-x = sx
with min-y = sy
with max-y = sy
with max-x-level = (array-dimension (terrain level) 0)
with max-y-level = (array-dimension (terrain level) 1)
for cell-list = nil
do
(setf cell-list (append cell-list (loop with y = min-y
for x from min-x to max-x
collect (cons x y))))
(setf cell-list (append cell-list (loop with x = max-x
for y from min-y to max-y
collect (cons x y))))
(setf cell-list (append cell-list (loop with y = max-y
for x from min-x to max-x
collect (cons x y))))
(setf cell-list (append cell-list (loop with x = min-x
for y from min-y to max-y
collect (cons x y))))
(loop for (x . y) in cell-list
when (and (>= x 0) (< x max-x-level) (>= y 0) (< y max-y-level)
(eq (check-move-on-level mob x y sz) t)
(get-terrain-type-trait (get-terrain-* level x y sz) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level x y sz (if (riding-mob-id mob)
(map-size (get-mob-by-id (riding-mob-id mob)))
(map-size mob))
(get-mob-move-mode mob))
+connect-room-none+)
(or (null no-center)
(and no-center
(or (/= x sx) (/= y sy)))))
do
(setf (x mob) x (y mob) y (z mob) sz)
(add-mob-to-level-list level mob)
(return-from find-unoccupied-place-around mob))
(decf min-x)
(decf min-y)
(incf max-x)
(incf max-y)
))
(defun find-unoccupied-place-mimic (level mob1 mob2 mob3 &key (inside nil))
(loop with max-x = (array-dimension (terrain level) 0)
with max-y = (array-dimension (terrain level) 1)
for x = (random max-x)
for y = (random max-y)
for z = 2
until (and (if inside
(and (> x 10) (< x (- max-x 10)) (> y 10) (< y (- max-y 10)))
(not (and (> x 7) (< x (- max-x 7)) (> y 7) (< y (- max-y 7)))))
(eq (check-move-on-level mob1 (1- x) (1- y) z) t)
(eq (check-move-on-level mob2 (1+ x) (1- y) z) t)
(eq (check-move-on-level mob3 x (1+ y) z) t)
(not (get-mob-* level (1- x) (1- y) z))
(not (get-mob-* level (1+ x) (1- y) z))
(not (get-mob-* level x (1+ y) z))
(get-terrain-type-trait (get-terrain-* level (1- x) (1- y) z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* level (1+ x) (1- y) z) +terrain-trait-blocks-move-floor+)
(get-terrain-type-trait (get-terrain-* level x (1+ y) z) +terrain-trait-blocks-move-floor+)
(/= (get-level-connect-map-value level (1- x) (1- y) z (if (riding-mob-id mob1)
(map-size (get-mob-by-id (riding-mob-id mob1)))
(map-size mob1))
(get-mob-move-mode mob1))
+connect-room-none+)
(/= (get-level-connect-map-value level (1+ x) (1- y) z (if (riding-mob-id mob2)
(map-size (get-mob-by-id (riding-mob-id mob2)))
(map-size mob2))
(get-mob-move-mode mob2))
+connect-room-none+)
(/= (get-level-connect-map-value level x (1+ y) z (if (riding-mob-id mob3)
(map-size (get-mob-by-id (riding-mob-id mob3)))
(map-size mob3))
(get-mob-move-mode mob3))
+connect-room-none+)
)
finally (setf (x mob1) (1- x) (y mob1) (1- y) (z mob1) z)
(add-mob-to-level-list level mob1)
(setf (x mob2) (1+ x) (y mob2) (1- y) (z mob2) z)
(add-mob-to-level-list level mob2)
(setf (x mob3) x (y mob3) (1+ y) (z mob3) z)
(add-mob-to-level-list level mob3)
))
(defun find-player-start-position (level mob feature-type-id)
(loop for feature-id in (feature-id-list level)
for feature = (get-feature-by-id feature-id)
when (= (feature-type feature) feature-type-id)
do
(setf (x mob) (x feature) (y mob) (y feature) (z mob) (z feature))
(add-mob-to-level-list level mob)
(loop-finish)))
(defun set-up-outdoor-light (level light-power)
(setf (outdoor-light level) light-power)
(loop for x from 0 below (array-dimension (light-map level) 0) do
(loop for y from 0 below (array-dimension (light-map level) 1)
for light-pwr = 100
do
(loop for z from (1- (array-dimension (light-map level) 2)) downto 0
do
(setf (aref (light-map level) x y z) light-pwr)
(when (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-blocks-move-floor+)
(setf light-pwr 0))
(when (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-light-source+)
(add-light-source level (make-light-source x y z (get-terrain-type-trait (get-terrain-* level x y z) +terrain-trait-light-source+))))
)))
)
|
c70a133aba87e5f6aa1cdcc0f052531202edf9ded69e06a26038ea59b75377f3 | EuAndreh/cl-BSON | cl-bson.lisp | (defpackage cl-bson-test
(:import-from arrow-macros
->)
(:import-from babel
string-to-octets)
(:import-from intbytes
int32->octets
octets->int32)
(:import-from local-time
now
nsec-of
timestamp
timestamp-millisecond
timestamp-to-unix
timestamp<=
unix-to-timestamp)
(:import-from lol
defmacro!)
(:import-from named-readtables
in-readtable)
(:import-from trivial-shell
os-process-id)
(:use cl prove cl-bson))
(in-package cl-bson-test)
(in-readtable bson:bson-syntax)
(bson:enable-printers)
(setf *print-pretty* t)
;; NOTE: To run this test file, execute `(asdf:test-system :cl-bson)' in your Lisp.
(plan 7)
(defmacro! enc-dec-kv (key value)
"Creates a document, adds a KEY VALUE, encodes it with #'ENCODE, decodes it with #'DECODE and uses #'GET-ELEMENT to return the value stored under KEY of the encoded->decoded document."
`(let ((,g!doc (make-document :_id nil)))
(add-element ,g!doc ,key ,value)
(get-element (decode (encode ,g!doc)) ,key)))
(defmacro type-byte-of (document)
"Acess the type of the first VALUE of the given OBJECT."
`(aref (encode ,document) 4))
(deftest encode-decode-equivalence-test
(is (enc-dec-kv "float" 1.5)
1.5d0
"SINGLE-FLOAT gets coerced to DOUBLE-FLOAT")
(is (enc-dec-kv "double" 1.5d0)
1.5d0
"DOUBLE-FLOAT stays as DOUBLE-FLOAT.")
(is (enc-dec-kv "utf-8 string" "utf8 string: áŭλ")
"utf8 string: áŭλ"
"Encodes and decodes correctly an UTF-8 string.")
(is (enc-dec-kv "ascii string" "just ASCII!.?")
"just ASCII!.?"
"Encodes and decodes correctly an ASCII string.")
(is-type (enc-dec-kv "embedded document" #d("1" 2))
'<document>
"Returns the decoded value with the correct type (<DOCUMENT>).")
(is (get-element (enc-dec-kv "embedded document" #d("1" 2)) "1")
2
"Sucessfully accesses the correct value of the encoded->decoded document.")
(let ((*bson-sequence-type* 'vector))
(is-type (enc-dec-kv "vector" #(1 2 3))
'vector
"Receives the correct return type (VECTOR) with *BSON-SEQUENCE-TYPE* bound to 'VECTOR.")
(is (enc-dec-kv "vector" #(1 2 3))
#(1 2 3)
:test #'equalp
"Correctly encodes->decodes the values of the array in the document.")
(let ((*bson-sequence-type* 'list))
(is-type (enc-dec-kv "list" '(1 2 3))
'list
"Receives the correct return type (LIST) with the *BSON-SEQUENCE-TYPE* bound to 'LIST.")
(is (enc-dec-kv "list" '(1 2 3))
'(1 2 3)
:test #'equalp
"Correctly encodes->decodes the values of the array in the document.")))
(is-type (enc-dec-kv "_id" (make-instance '<object-id>))
'<object-id>
"Correctly encodes and decodes the <OBJECT-ID> type.")
(is-type (get-element (decode (encode (make-document))) "_id")
'<object-id>
"Correctly encodes and decodes the <OBJECT-ID> type on the document create \"manually\".")
(let ((_id (make-instance '<object-id>)))
(is (octets (enc-dec-kv "_id" _id))
(octets _id)
:test #'equalp
"The value of the encoded->decoded OBJECT-ID stays the same.")
(is (octets (get-element (decode (encode (make-document :_id _id))) "_id"))
(octets _id)
:test #'equalp
"The value of the encoded->decoded OBJECT-ID of the document created \"manually\" stays the same. "))
(is (enc-dec-kv "true" t)
t
"Correctly encodes and decodes a T value.")
(is (enc-dec-kv "false" nil)
nil
"Correctly encodes and decodes a NIL (boolean) value.")
(let ((now (now)))
(is (timestamp-to-unix (enc-dec-kv "timestamp" now))
(timestamp-to-unix now)
"Correctly encodes->decodes the value of the timestamp.")
(is (timestamp-millisecond (enc-dec-kv "timestamp" now))
(timestamp-millisecond now)
"Correctly encodes->decodes the milliseconds of the timestamp.")
(ok (<= (nsec-of (enc-dec-kv "timestamp" now))
(nsec-of now))
"Nanoseconds value should be different (unless I'm really unlucky and gets 0 nanoseconds of difference."))
(let ((regex (make-instance '<regex>
:pattern "^my.*?pattern"
:options "wi")))
(is (options (enc-dec-kv "regex" regex))
"iw"
"Options slot gets sorted correctly")
(is (pattern (enc-dec-kv "regex" regex))
"^my.*?pattern"
"PATTERN is encoded->decoded->acessed corretly.")
(is-error (setf (options regex) "abcd")
'simple-error
"Invalid regex OPTIONS throws an error."))
(is (code (enc-dec-kv "javascript" (make-instance '<javascript> :code "var code = 1;")))
"var code = 1;"
"CODE is correctly encoded->decoded->accessed.")
(is (code (enc-dec-kv "javascript with scope" (make-instance '<javascript>
:code "var second = third;"
:scope #d("third" 5))))
"var second = third;"
"JAVASCRIPT CODE gets correctly encoded->decoded->accessed.")
(is (enc-dec-kv "32-bit integer" -1)
-1
"Negative 32-bit integers get correctly encoded->decoded.")
(is (enc-dec-kv "64-bit integer" 123456780987654321)
123456780987654321
"Big 64-bit integers get corretly encoded->decoded.")
(let ((mongo-timestamp (make-instance '<mongo-timestamp>)))
(is (mongo-time (enc-dec-kv "mongo timestamp" mongo-timestamp))
(mongo-time mongo-timestamp)
:test #'equalp)))
(deftest encoded-byte-bson-type-test
"desc"
(is (type-byte-of #d("float" 1.1))
#x01
"Float type is expected to be #x01.")
(is (type-byte-of #d("string" "string"))
#x02
"String type is expected to be #x02.")
(is (type-byte-of #d("embedded document" #d("1" "2")))
#x03
"Embedded document type is expected to be #x03.")
(is (type-byte-of #d("sequence" #(1 2 3)))
#x04
"Array type is expected to be #x04.")
(is (type-byte-of #d("sequence" '(1 2 3)))
#x04
"List type is expected to be #x04, too.")
(is (type-byte-of #d("binary data" (make-instance '<binary-data>)))
#x05
"Binary data type is expected to be #x05.")
(is (type-byte-of #d("object-id" (make-instance '<object-id>)))
#x07
"ObjectId is expected to be #x07.")
(is (type-byte-of #d("boolean true" t))
#x08
"Boolean T type is expected to be #x08.")
(is (type-byte-of #d("boolean false" nil))
#x08
"Boolean NIL type is expected to be #x08, too.")
(is (type-byte-of #d("timestamp" (now)))
#x09
"LOCAL-TIME:TIMESTAMP (BSON Date) is expected to be #x09.")
(is (type-byte-of #d("regex" (make-instance '<regex>)))
#x0B
"<REGEX> type is expected to be #X0B.")
(is (type-byte-of #d("javascript code" (make-instance '<javascript> :code "vax a = 10;")))
#x0D
"\"Javascript code\" type is expected to be #x0D.")
(is (type-byte-of #d("javascript code with scope"
(make-instance '<javascript> :code "var x = 1;" :scope #d("a" "3"))))
#x0F
"\"Javascript code with scope\" type is expected to be #x0F.")
(is (type-byte-of #d("32 bit integer" 123))
#x10
"32-bit integer type is expected to be #x10.")
(is (type-byte-of #d("mongo timestamp" (make-instance '<mongo-timestamp>)))
#x11
"MongoDB internal Timestamp type is expected to be #x11.")
(is (type-byte-of #d("64 bit integer" 1234567890987654321))
#x12
"64-bit integer type is expected to be #x12."))
(deftest types-test
(subtest "subtest for #'GENERATE-OBJECT-ID functionality:"
(ok (< cl-bson.types::*object-id-counter* (expt 2 24))
"The randomly generated *OBJECT-ID-COUNTER* is smaller than (expt 2 24).")
(let ((cl-bson.types::*object-id-counter* (1- (expt 2 24))))
(cl-bson.types::generate-object-id)
(is cl-bson.types::*object-id-counter*
0
"*OBJECT-ID-COUNTER* is 0 after being the largest value possible."))
(let* ((obj-id-bytes (cl-bson.types::generate-object-id))
(obj-id-timestamp (-> (subseq obj-id-bytes 0 4)
octets->int32
unix-to-timestamp))
(now (now)))
(is-type obj-id-bytes
'octets-array
"OBJ-ID-BYTES is an OCTETS-ARRAY.")
(is (length obj-id-bytes)
12
"Object id octets is 12 bytes long.")
(ok (timestamp<= obj-id-timestamp
now)
"The generated OBJ-ID-TIMESTAMP has an actual timestamp for now between byte 0 and 4.")
(is (subseq obj-id-bytes 4 7)
(-> (machine-instance)
(string-to-octets :encoding :utf-8)
(subseq 0 3))
:test #'equalp
"MACHINE-INSTANCE identifier is #'EQUALP to bytes 4 to 7 in the generated OBJ-ID-BYTES.")
(is (subseq obj-id-bytes 7 9)
(-> (cl-bson.types::os-process-id)
int32->octets
(subseq 0 2))
:test #'equalp
"OS-PROCESS-ID identifier is #'EQUALP to bytes 7 to 9 in the generated OBJ-ID-BYTES.")))
(subtest "subtest for <OBJECT-ID> behaviour:"
(let ((now (now))
(obj-id (make-instance '<object-id>)))
(is-type (octets obj-id)
'octets-array
"OCTETS of the generated OBJ-ID is an OCTETS-ARRAY.")
(is (length (octets obj-id))
12
"OCTETS of the generated OBJ-ID has 12 bytes.")
(is-type (str obj-id)
'string
"Bytes in the octet of the generated OBJ-ID can be parsed with the (parse-integer byte :radix 16).")
(is (octets (string->object-id (str obj-id)))
(octets obj-id)
:test #'equalp
"Bytes of the OBJ-ID stays the same when coerced to string with #'STR and coerced back to <OBJECT-ID> back with #'STRING->OBJECT-ID.")
(ok (timestamp<= (get-timestamp obj-id)
now)
"Timestamp of the generated OBJ-ID is before LOCAL-TIME:NOW (because it loses nanoseconds precision).")))
(subtest "subtest for <REGEX> behaviour:"
(let ((regex (make-instance '<regex>)))
(ok (slot-boundp regex 'pattern)
"PATTERN slot of the REGEX is bound.")
(ok (slot-boundp regex 'options)
"OPTIONS slot of the REGEX is bound.")
(is (pattern regex)
""
"Default pattern is an empty string.")
(is (options regex)
""
"Default options is an empty string.")
(setf (options regex) "wui")
(is (options regex)
"iuw"
"OPTIONS gets alphabetically sorted at the (SETF OPTIONS).")
(is-error (setf (options regex) "abc")
'simple-error
"Invalid character for OPTIONS raises an ERROR.")
(is (options (make-instance '<regex>
:pattern "pat"
:options "xsm"))
"msx"
"Constructor for <REGEX> correctly sorts the options.")
(is-error (make-instance '<regex>
:pattern "pat"
:options "asdf")
'simple-error
"Constructor for <REGEX> raises an error when :OPTIONS has an invalid character.")))
(subtest "subtest for <BINARY-DATA> behaviour:"
(is-error (make-instance '<binary-data>
:subtype :invalid)
'simple-error
":INVALID :SUBTYPE raises an ERROR.")
(let ((bin-data (make-instance '<binary-data> :octets (fast-io:make-octet-vector 10))))
(is (subtype bin-data)
:generic
"Default SUBTYPE is :GENERIC.")
(setf (subtype bin-data) :uuid)
(is (subtype bin-data)
:uuid
"SUBTYPE can be SETFed to :UUID.")
(is-error (setf (subtype bin-data) :also-invalid)
'simple-error
"(setf (subtype bin-data) :also-invalid) raises an error, too.")
(is-type (octets bin-data)
'octets-array
"OCTETS of BIN-DATA is an OCTETS-ARRAY.")
(is-type (subtype bin-data)
'keyword
"SUBTYPE of BIN-DATA is a KEYWORD.")
(is (octets bin-data)
(fast-io:make-octet-vector 10)
:test #'equalp
"(octets bin-data) has default data assigned in the instanciation.")))
(subtest "subtest for <JAVASCRIPT> behaviour:"
(let ((javascript (make-instance '<javascript>)))
(is-error (code javascript)
'error
"CODE slot of JAVASCRIPT is unbound by default.")
(is (slot-boundp javascript 'scope)
nil
"SCOPE slot of JAVASCRIPT is NIL by default.")))
(subtest "subtest for <MONGO-TIMESTAMP> behaviour:"
(ok (< cl-bson.types::*mongo-timestamp-counter* (expt 2 32))
"The randomly generated *MONGO-TIMESTAMP-COUNTER* is smaller than (expt 2 32).")
(let ((cl-bson.types::*mongo-timestamp-counter* (1- (expt 2 32))))
(cl-bson.types::generate-mongo-timestamp)
(is cl-bson.types::*mongo-timestamp-counter*
0
"*MONGO-TIMESTAMP-COUNTER* is 0 after being the largest value possible (expt 2 32)."))
(let* ((mongo-now (make-instance '<mongo-timestamp>))
(mongo-now-timestamp (-> (mongo-time mongo-now)
(subseq 0 4)
octets->int32
unix-to-timestamp))
(now (now)))
(is-type (mongo-time mongo-now)
'octets-array
"(mongo-time mongo-now) is an OCTETS-ARRAY.")
(is (length (mongo-time mongo-now))
8
"mongo-time octets is 8 bytes long.")
(ok (timestamp<= mongo-now-timestamp
now)
"The generated <MONGO-TIMESTAMP> has an actual timestamp for now located between byte 4 and 8.")))
(subtest "subtest for <document> manipulation and behaviour:"
(let ((empty-doc (make-instance '<document>))
(doc (make-document))
(also-empty-doc (make-document :_id nil)))
(is-type (get-element doc "_id")
'<object-id>
"Document generated with MAKE-DOCUMENT has an <OBJECT-ID> identified by \"_id\".")
(is-values (get-element empty-doc "_id")
'(nil nil)
"Document generated with (make-instance '<document>) has no <OBJECT-ID>.")
(is-type (elements empty-doc)
'hash-table
"(elements empty-doc) is a HASH-TABLE.")
(is (length (keys empty-doc))
0
"EMPTY-DOC has no elements.")
(is (length (keys doc))
1
"DOC (generated with MAKE-DOCUMENT) has 1 element: the \"_id_\".")
(is (length (keys also-empty-doc))
0
"Document generated with (MAKE-DOCUMENT :_id nil) has no keys.")
(is-values (get-element doc :non-existing-key)
'(nil nil)
"Getting a :NON-EXISTING-KEY from a doc returns two values (the same of GETHASH).")
(add-element doc "my-key" "my-value")
(is (get-element doc "my-key")
"my-value"
"#'GET-ELEMENT works with an already bound document.")
(is (get-element (add-element #d() "my-key" "my-value") "my-key")
"my-value"
"#'GET-ELEMENT works with document just created and modified with #'ADD-ELEMENT.")
(is (get-element #d("my-key" "my-value") "my-key")
"my-value"
"#'GET-ELEMENT works with literal documents.")
(remove-element doc "my-key")
(is-values (get-element doc "my-key")
'(nil nil)
"#'REMOVE-ELEMENT works with an already bound document.")
(is-values (get-element (remove-element #d("my-key" "my-value") "my-key") "my-key")
'(nil nil)
"#'REMOVE-ELEMENT works with an just created literal document.")
(is (get-element (remove-element #d("my-key" "my-value") "crazy-key") "my-key")
"my-value"
"#'REMOVE-ELEMENT called with the wrong key leaves the document intact."))))
(deftest readtable-test
(subtest "<DOCUMENT> literal read-macro test:"
(is-type #d()
'<document>
"#d() is of type <DOCUMENT>.")
(is-print (princ #d())
"#d()"
"#d() prints like #d().")
(is-print (princ #d("1" "2" "3" "4"))
"#d(1 2 3 4)"
"#d(\"1\" \"2\" \"3\" \"4\") prints correctly.")
(is-expand #d()
(LET ()
(LET (($DOCUMENT (MAKE-INSTANCE '<DOCUMENT>)))
$DOCUMENT))
"Empty #d() expands correctly.")
(is '#d()
'(cl-bson.readtable::bson-document-literal)
"Expands to the correct empty form.")
(is-expand #d("1" "2" "3" "4")
(LET ()
(LET (($DOCUMENT (MAKE-INSTANCE '<DOCUMENT>)))
(ADD-ELEMENT $DOCUMENT "1" "2")
(ADD-ELEMENT $DOCUMENT "3" "4")
$DOCUMENT))
"#d() empty form expands corretly.")
(is '#d("1" "2")
'(cl-bson.readtable::bson-document-literal "1" "2")
"Expands corretly to the non-empty form.")
(is-error #d(1 2)
'type-error
"Throws an error because 1 is not of type string nor coercible with #'STRING.")
(is-error (macroexpand '#d("1" 2 "3"))
'simple-error
"Throws an error because document literal has an odd number of values.")
(is-error (macroexpand '#d("1" 2 "1" 2))
'simple-error
"Throws an error because document literal has repeated keys.")
(disable-printers)
(isnt (princ-to-string #d())
(not "#d()")
"#d() doesn't print like it with #'DISABLE-PRINTERS.")
(isnt (princ-to-string #d("1" "2" "3" "4"))
(not "#d(1 2 3 4)")
"#d(\"1\" \"2\" \"3\" \"4\") doesn't print like it with #'DISABLE-PRINTERS."))
(subtest "<OBJECT-ID> literal read-macro test:"
(is-error #i()
'error
"Throws error becaus #i() has no <OBJECT-ID> string representation.")
(is-type #i(50ED6E55616E64231C5D2EDF)
'<object-id>
"#i() corretly returns an object of <OBJECT-ID> type.")
(enable-printers)
(is-print (princ #i(50ED6E55616E64231C5D2EDF))
"#i(50ED6E55616E64231C5D2EDF)"
"Corretly prints a valid <OBJECT-ID>.")
(is '#i(50ED6E55616E64231C5D2EDF)
'(STRING->OBJECT-ID "50ED6E55616E64231C5D2EDF")
"Correctly expands a #i(0000....) form.")
(disable-printers)
(isnt (princ-to-string #i(50ED6E55616E64231C5D2EDF))
(not "#i(50ED6E55616E64231C5D2EDF)")
"Doesn't print like #i(...) with #'DISABLE-PRINTERS.") ))
(deftest big-documen-types-test
(let* ((raw-doc #d(:keyword-key :keyword-value
'symbol-key 'symbol-value
"string-key" "string-value"
"will be coerced to double" 1.5
"will stay as double" 1.5d0
"embedded document"
#d("with many"
#d("levels of"
#d("nesting"
#d("with another \"embedded document\": a vector" #(1 2 3)))))
"sequence" #(1 2 3)
"vector" #(1 2 3)
"list" '(1 2 3)
"regex" (make-instance '<regex> :pattern "\\d+" :options "i")
"binary data" (make-instance
'<binary-data>
:octets (fast-io:make-octet-vector 10))
"javascript code" (make-instance '<javascript>
:code "var example = 1;")
"javascript code with scope" (make-instance
'<javascript>
:code "var example = inScope;"
:scope #d("inScope" 10))
"object-id" (make-instance '<object-id>)
"boolean true" t
"boolean false" nil
"null value" nil
"32 bit integer" 123
"64 bit integer" 1234567890987654321
"local-time:timestamp" (local-time:now)))
(doc (decode (encode raw-doc ))))
(is-type (get-element doc "KEYWORD-KEY")
'string
":keyword-key gets coerced to string.")
(is-type (get-element doc "SYMBOL-KEY")
'string
"'symbol-key gets coerced to string.")
(is-type (get-element doc "string-key")
'string
"String value stays as string.")
(is-type (get-element doc "will be coerced to double")
'double-float
"SINGLE-FLOAT gets coerced to double.")
(is-type (get-element doc "will stay as double")
'double-float
"DOUBLE-FLOAT stays as double.")
(is-type (get-element doc "embedded document")
'<document>
"embedded document in document is a <DOCUMENT>.")
(is-type (get-element doc "sequence")
'sequence
"Array in BSON document is a sequence.")
(is-type (get-element doc "vector")
'sequence
"Vector in document is a sequence.")
(is-type (get-element doc "list")
'sequence
"List in document is a sequence")
(is-type (get-element doc "regex")
'<regex>
"regex in document is a <REGEX>.")
(is-type (get-element doc "binary data")
'<binary-data>
"binary data in document is a <BINARY-DATA>.")
(is-type (get-element doc "javascript code")
'<javascript>
"javascript code in document is a <JAVASCRIPT>.")
(is-type (get-element doc "javascript code with scope")
'<javascript>
"javascript code with scope in document is a <JAVASCRIPT>.")
(is-type (get-element doc "object-id")
'<object-id>
"object-id in document is a <OBJECT-ID>.")
(is (get-element doc "boolean true")
t
"boolean true in document is T.")
(is (get-element doc "boolean false")
nil
"boolean false in document is NIL.")
(is (get-element doc "null value")
nil
"null value in document is NIL.")
(is-type (get-element doc "32 bit integer")
'integer
"32 bit integer in document is integer.")
(ok (<= (integer-length (get-element doc "32 bit integer")) 32)
"32 bit integer in document occupies less than 33 bits.")
(is-type (get-element doc "64 bit integer")
'integer
"64 bit integer in document is integer.")
(ok (<= (integer-length (get-element doc "64 bit integer")) 64)
"64 bit integer in document occupies less than 65 bits.")
(is-type (get-element doc "local-time:timestamp")
'timestamp
"local-time:timestamp in document is a TIMESTAMP.")))
(deftest binary-data-subtypes-test
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data>)))
:generic
"Default <BINARY-DATA> subtype is :GENERIC.")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :function)))
:function
"<BINARY-DATA> subtype is :FUNCTION")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :binary-old)))
:binary-old
"<BINARY-DATA> subtype is :BINARY-OLD")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :uuid-old)))
:uuid-old
"<BINARY-DATA> subtype is :UUID-OLD")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :uuid)))
:uuid
"<BINARY-DATA> subtype is :UUID")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :md5)))
:md5
"<BINARY-DATA> subtype is :MD5")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :user-defined)))
:user-defined
"<BINARY-DATA> subtype is :USER-DEFINED")
(is-error (make-instance '<binary-data> :subtype :invalid)
'simple-error
"<BINARY-DATA> invalid subtype throws an error."))
(deftest bad-encoded-document-test
(is-error (decode (replace (encode #d("int" 2)) #(99) :start1 4))
'simple-error
"Unvalid BSON type raises an error."))
(run-test-all)
| null | https://raw.githubusercontent.com/EuAndreh/cl-BSON/4854aa9d64beaedeb1c2d0af16ec3ffe69447829/t/cl-bson.lisp | lisp | NOTE: To run this test file, execute `(asdf:test-system :cl-bson)' in your Lisp. | (defpackage cl-bson-test
(:import-from arrow-macros
->)
(:import-from babel
string-to-octets)
(:import-from intbytes
int32->octets
octets->int32)
(:import-from local-time
now
nsec-of
timestamp
timestamp-millisecond
timestamp-to-unix
timestamp<=
unix-to-timestamp)
(:import-from lol
defmacro!)
(:import-from named-readtables
in-readtable)
(:import-from trivial-shell
os-process-id)
(:use cl prove cl-bson))
(in-package cl-bson-test)
(in-readtable bson:bson-syntax)
(bson:enable-printers)
(setf *print-pretty* t)
(plan 7)
(defmacro! enc-dec-kv (key value)
"Creates a document, adds a KEY VALUE, encodes it with #'ENCODE, decodes it with #'DECODE and uses #'GET-ELEMENT to return the value stored under KEY of the encoded->decoded document."
`(let ((,g!doc (make-document :_id nil)))
(add-element ,g!doc ,key ,value)
(get-element (decode (encode ,g!doc)) ,key)))
(defmacro type-byte-of (document)
"Acess the type of the first VALUE of the given OBJECT."
`(aref (encode ,document) 4))
(deftest encode-decode-equivalence-test
(is (enc-dec-kv "float" 1.5)
1.5d0
"SINGLE-FLOAT gets coerced to DOUBLE-FLOAT")
(is (enc-dec-kv "double" 1.5d0)
1.5d0
"DOUBLE-FLOAT stays as DOUBLE-FLOAT.")
(is (enc-dec-kv "utf-8 string" "utf8 string: áŭλ")
"utf8 string: áŭλ"
"Encodes and decodes correctly an UTF-8 string.")
(is (enc-dec-kv "ascii string" "just ASCII!.?")
"just ASCII!.?"
"Encodes and decodes correctly an ASCII string.")
(is-type (enc-dec-kv "embedded document" #d("1" 2))
'<document>
"Returns the decoded value with the correct type (<DOCUMENT>).")
(is (get-element (enc-dec-kv "embedded document" #d("1" 2)) "1")
2
"Sucessfully accesses the correct value of the encoded->decoded document.")
(let ((*bson-sequence-type* 'vector))
(is-type (enc-dec-kv "vector" #(1 2 3))
'vector
"Receives the correct return type (VECTOR) with *BSON-SEQUENCE-TYPE* bound to 'VECTOR.")
(is (enc-dec-kv "vector" #(1 2 3))
#(1 2 3)
:test #'equalp
"Correctly encodes->decodes the values of the array in the document.")
(let ((*bson-sequence-type* 'list))
(is-type (enc-dec-kv "list" '(1 2 3))
'list
"Receives the correct return type (LIST) with the *BSON-SEQUENCE-TYPE* bound to 'LIST.")
(is (enc-dec-kv "list" '(1 2 3))
'(1 2 3)
:test #'equalp
"Correctly encodes->decodes the values of the array in the document.")))
(is-type (enc-dec-kv "_id" (make-instance '<object-id>))
'<object-id>
"Correctly encodes and decodes the <OBJECT-ID> type.")
(is-type (get-element (decode (encode (make-document))) "_id")
'<object-id>
"Correctly encodes and decodes the <OBJECT-ID> type on the document create \"manually\".")
(let ((_id (make-instance '<object-id>)))
(is (octets (enc-dec-kv "_id" _id))
(octets _id)
:test #'equalp
"The value of the encoded->decoded OBJECT-ID stays the same.")
(is (octets (get-element (decode (encode (make-document :_id _id))) "_id"))
(octets _id)
:test #'equalp
"The value of the encoded->decoded OBJECT-ID of the document created \"manually\" stays the same. "))
(is (enc-dec-kv "true" t)
t
"Correctly encodes and decodes a T value.")
(is (enc-dec-kv "false" nil)
nil
"Correctly encodes and decodes a NIL (boolean) value.")
(let ((now (now)))
(is (timestamp-to-unix (enc-dec-kv "timestamp" now))
(timestamp-to-unix now)
"Correctly encodes->decodes the value of the timestamp.")
(is (timestamp-millisecond (enc-dec-kv "timestamp" now))
(timestamp-millisecond now)
"Correctly encodes->decodes the milliseconds of the timestamp.")
(ok (<= (nsec-of (enc-dec-kv "timestamp" now))
(nsec-of now))
"Nanoseconds value should be different (unless I'm really unlucky and gets 0 nanoseconds of difference."))
(let ((regex (make-instance '<regex>
:pattern "^my.*?pattern"
:options "wi")))
(is (options (enc-dec-kv "regex" regex))
"iw"
"Options slot gets sorted correctly")
(is (pattern (enc-dec-kv "regex" regex))
"^my.*?pattern"
"PATTERN is encoded->decoded->acessed corretly.")
(is-error (setf (options regex) "abcd")
'simple-error
"Invalid regex OPTIONS throws an error."))
(is (code (enc-dec-kv "javascript" (make-instance '<javascript> :code "var code = 1;")))
"var code = 1;"
"CODE is correctly encoded->decoded->accessed.")
(is (code (enc-dec-kv "javascript with scope" (make-instance '<javascript>
:code "var second = third;"
:scope #d("third" 5))))
"var second = third;"
"JAVASCRIPT CODE gets correctly encoded->decoded->accessed.")
(is (enc-dec-kv "32-bit integer" -1)
-1
"Negative 32-bit integers get correctly encoded->decoded.")
(is (enc-dec-kv "64-bit integer" 123456780987654321)
123456780987654321
"Big 64-bit integers get corretly encoded->decoded.")
(let ((mongo-timestamp (make-instance '<mongo-timestamp>)))
(is (mongo-time (enc-dec-kv "mongo timestamp" mongo-timestamp))
(mongo-time mongo-timestamp)
:test #'equalp)))
(deftest encoded-byte-bson-type-test
"desc"
(is (type-byte-of #d("float" 1.1))
#x01
"Float type is expected to be #x01.")
(is (type-byte-of #d("string" "string"))
#x02
"String type is expected to be #x02.")
(is (type-byte-of #d("embedded document" #d("1" "2")))
#x03
"Embedded document type is expected to be #x03.")
(is (type-byte-of #d("sequence" #(1 2 3)))
#x04
"Array type is expected to be #x04.")
(is (type-byte-of #d("sequence" '(1 2 3)))
#x04
"List type is expected to be #x04, too.")
(is (type-byte-of #d("binary data" (make-instance '<binary-data>)))
#x05
"Binary data type is expected to be #x05.")
(is (type-byte-of #d("object-id" (make-instance '<object-id>)))
#x07
"ObjectId is expected to be #x07.")
(is (type-byte-of #d("boolean true" t))
#x08
"Boolean T type is expected to be #x08.")
(is (type-byte-of #d("boolean false" nil))
#x08
"Boolean NIL type is expected to be #x08, too.")
(is (type-byte-of #d("timestamp" (now)))
#x09
"LOCAL-TIME:TIMESTAMP (BSON Date) is expected to be #x09.")
(is (type-byte-of #d("regex" (make-instance '<regex>)))
#x0B
"<REGEX> type is expected to be #X0B.")
(is (type-byte-of #d("javascript code" (make-instance '<javascript> :code "vax a = 10;")))
#x0D
"\"Javascript code\" type is expected to be #x0D.")
(is (type-byte-of #d("javascript code with scope"
(make-instance '<javascript> :code "var x = 1;" :scope #d("a" "3"))))
#x0F
"\"Javascript code with scope\" type is expected to be #x0F.")
(is (type-byte-of #d("32 bit integer" 123))
#x10
"32-bit integer type is expected to be #x10.")
(is (type-byte-of #d("mongo timestamp" (make-instance '<mongo-timestamp>)))
#x11
"MongoDB internal Timestamp type is expected to be #x11.")
(is (type-byte-of #d("64 bit integer" 1234567890987654321))
#x12
"64-bit integer type is expected to be #x12."))
(deftest types-test
(subtest "subtest for #'GENERATE-OBJECT-ID functionality:"
(ok (< cl-bson.types::*object-id-counter* (expt 2 24))
"The randomly generated *OBJECT-ID-COUNTER* is smaller than (expt 2 24).")
(let ((cl-bson.types::*object-id-counter* (1- (expt 2 24))))
(cl-bson.types::generate-object-id)
(is cl-bson.types::*object-id-counter*
0
"*OBJECT-ID-COUNTER* is 0 after being the largest value possible."))
(let* ((obj-id-bytes (cl-bson.types::generate-object-id))
(obj-id-timestamp (-> (subseq obj-id-bytes 0 4)
octets->int32
unix-to-timestamp))
(now (now)))
(is-type obj-id-bytes
'octets-array
"OBJ-ID-BYTES is an OCTETS-ARRAY.")
(is (length obj-id-bytes)
12
"Object id octets is 12 bytes long.")
(ok (timestamp<= obj-id-timestamp
now)
"The generated OBJ-ID-TIMESTAMP has an actual timestamp for now between byte 0 and 4.")
(is (subseq obj-id-bytes 4 7)
(-> (machine-instance)
(string-to-octets :encoding :utf-8)
(subseq 0 3))
:test #'equalp
"MACHINE-INSTANCE identifier is #'EQUALP to bytes 4 to 7 in the generated OBJ-ID-BYTES.")
(is (subseq obj-id-bytes 7 9)
(-> (cl-bson.types::os-process-id)
int32->octets
(subseq 0 2))
:test #'equalp
"OS-PROCESS-ID identifier is #'EQUALP to bytes 7 to 9 in the generated OBJ-ID-BYTES.")))
(subtest "subtest for <OBJECT-ID> behaviour:"
(let ((now (now))
(obj-id (make-instance '<object-id>)))
(is-type (octets obj-id)
'octets-array
"OCTETS of the generated OBJ-ID is an OCTETS-ARRAY.")
(is (length (octets obj-id))
12
"OCTETS of the generated OBJ-ID has 12 bytes.")
(is-type (str obj-id)
'string
"Bytes in the octet of the generated OBJ-ID can be parsed with the (parse-integer byte :radix 16).")
(is (octets (string->object-id (str obj-id)))
(octets obj-id)
:test #'equalp
"Bytes of the OBJ-ID stays the same when coerced to string with #'STR and coerced back to <OBJECT-ID> back with #'STRING->OBJECT-ID.")
(ok (timestamp<= (get-timestamp obj-id)
now)
"Timestamp of the generated OBJ-ID is before LOCAL-TIME:NOW (because it loses nanoseconds precision).")))
(subtest "subtest for <REGEX> behaviour:"
(let ((regex (make-instance '<regex>)))
(ok (slot-boundp regex 'pattern)
"PATTERN slot of the REGEX is bound.")
(ok (slot-boundp regex 'options)
"OPTIONS slot of the REGEX is bound.")
(is (pattern regex)
""
"Default pattern is an empty string.")
(is (options regex)
""
"Default options is an empty string.")
(setf (options regex) "wui")
(is (options regex)
"iuw"
"OPTIONS gets alphabetically sorted at the (SETF OPTIONS).")
(is-error (setf (options regex) "abc")
'simple-error
"Invalid character for OPTIONS raises an ERROR.")
(is (options (make-instance '<regex>
:pattern "pat"
:options "xsm"))
"msx"
"Constructor for <REGEX> correctly sorts the options.")
(is-error (make-instance '<regex>
:pattern "pat"
:options "asdf")
'simple-error
"Constructor for <REGEX> raises an error when :OPTIONS has an invalid character.")))
(subtest "subtest for <BINARY-DATA> behaviour:"
(is-error (make-instance '<binary-data>
:subtype :invalid)
'simple-error
":INVALID :SUBTYPE raises an ERROR.")
(let ((bin-data (make-instance '<binary-data> :octets (fast-io:make-octet-vector 10))))
(is (subtype bin-data)
:generic
"Default SUBTYPE is :GENERIC.")
(setf (subtype bin-data) :uuid)
(is (subtype bin-data)
:uuid
"SUBTYPE can be SETFed to :UUID.")
(is-error (setf (subtype bin-data) :also-invalid)
'simple-error
"(setf (subtype bin-data) :also-invalid) raises an error, too.")
(is-type (octets bin-data)
'octets-array
"OCTETS of BIN-DATA is an OCTETS-ARRAY.")
(is-type (subtype bin-data)
'keyword
"SUBTYPE of BIN-DATA is a KEYWORD.")
(is (octets bin-data)
(fast-io:make-octet-vector 10)
:test #'equalp
"(octets bin-data) has default data assigned in the instanciation.")))
(subtest "subtest for <JAVASCRIPT> behaviour:"
(let ((javascript (make-instance '<javascript>)))
(is-error (code javascript)
'error
"CODE slot of JAVASCRIPT is unbound by default.")
(is (slot-boundp javascript 'scope)
nil
"SCOPE slot of JAVASCRIPT is NIL by default.")))
(subtest "subtest for <MONGO-TIMESTAMP> behaviour:"
(ok (< cl-bson.types::*mongo-timestamp-counter* (expt 2 32))
"The randomly generated *MONGO-TIMESTAMP-COUNTER* is smaller than (expt 2 32).")
(let ((cl-bson.types::*mongo-timestamp-counter* (1- (expt 2 32))))
(cl-bson.types::generate-mongo-timestamp)
(is cl-bson.types::*mongo-timestamp-counter*
0
"*MONGO-TIMESTAMP-COUNTER* is 0 after being the largest value possible (expt 2 32)."))
(let* ((mongo-now (make-instance '<mongo-timestamp>))
(mongo-now-timestamp (-> (mongo-time mongo-now)
(subseq 0 4)
octets->int32
unix-to-timestamp))
(now (now)))
(is-type (mongo-time mongo-now)
'octets-array
"(mongo-time mongo-now) is an OCTETS-ARRAY.")
(is (length (mongo-time mongo-now))
8
"mongo-time octets is 8 bytes long.")
(ok (timestamp<= mongo-now-timestamp
now)
"The generated <MONGO-TIMESTAMP> has an actual timestamp for now located between byte 4 and 8.")))
(subtest "subtest for <document> manipulation and behaviour:"
(let ((empty-doc (make-instance '<document>))
(doc (make-document))
(also-empty-doc (make-document :_id nil)))
(is-type (get-element doc "_id")
'<object-id>
"Document generated with MAKE-DOCUMENT has an <OBJECT-ID> identified by \"_id\".")
(is-values (get-element empty-doc "_id")
'(nil nil)
"Document generated with (make-instance '<document>) has no <OBJECT-ID>.")
(is-type (elements empty-doc)
'hash-table
"(elements empty-doc) is a HASH-TABLE.")
(is (length (keys empty-doc))
0
"EMPTY-DOC has no elements.")
(is (length (keys doc))
1
"DOC (generated with MAKE-DOCUMENT) has 1 element: the \"_id_\".")
(is (length (keys also-empty-doc))
0
"Document generated with (MAKE-DOCUMENT :_id nil) has no keys.")
(is-values (get-element doc :non-existing-key)
'(nil nil)
"Getting a :NON-EXISTING-KEY from a doc returns two values (the same of GETHASH).")
(add-element doc "my-key" "my-value")
(is (get-element doc "my-key")
"my-value"
"#'GET-ELEMENT works with an already bound document.")
(is (get-element (add-element #d() "my-key" "my-value") "my-key")
"my-value"
"#'GET-ELEMENT works with document just created and modified with #'ADD-ELEMENT.")
(is (get-element #d("my-key" "my-value") "my-key")
"my-value"
"#'GET-ELEMENT works with literal documents.")
(remove-element doc "my-key")
(is-values (get-element doc "my-key")
'(nil nil)
"#'REMOVE-ELEMENT works with an already bound document.")
(is-values (get-element (remove-element #d("my-key" "my-value") "my-key") "my-key")
'(nil nil)
"#'REMOVE-ELEMENT works with an just created literal document.")
(is (get-element (remove-element #d("my-key" "my-value") "crazy-key") "my-key")
"my-value"
"#'REMOVE-ELEMENT called with the wrong key leaves the document intact."))))
(deftest readtable-test
(subtest "<DOCUMENT> literal read-macro test:"
(is-type #d()
'<document>
"#d() is of type <DOCUMENT>.")
(is-print (princ #d())
"#d()"
"#d() prints like #d().")
(is-print (princ #d("1" "2" "3" "4"))
"#d(1 2 3 4)"
"#d(\"1\" \"2\" \"3\" \"4\") prints correctly.")
(is-expand #d()
(LET ()
(LET (($DOCUMENT (MAKE-INSTANCE '<DOCUMENT>)))
$DOCUMENT))
"Empty #d() expands correctly.")
(is '#d()
'(cl-bson.readtable::bson-document-literal)
"Expands to the correct empty form.")
(is-expand #d("1" "2" "3" "4")
(LET ()
(LET (($DOCUMENT (MAKE-INSTANCE '<DOCUMENT>)))
(ADD-ELEMENT $DOCUMENT "1" "2")
(ADD-ELEMENT $DOCUMENT "3" "4")
$DOCUMENT))
"#d() empty form expands corretly.")
(is '#d("1" "2")
'(cl-bson.readtable::bson-document-literal "1" "2")
"Expands corretly to the non-empty form.")
(is-error #d(1 2)
'type-error
"Throws an error because 1 is not of type string nor coercible with #'STRING.")
(is-error (macroexpand '#d("1" 2 "3"))
'simple-error
"Throws an error because document literal has an odd number of values.")
(is-error (macroexpand '#d("1" 2 "1" 2))
'simple-error
"Throws an error because document literal has repeated keys.")
(disable-printers)
(isnt (princ-to-string #d())
(not "#d()")
"#d() doesn't print like it with #'DISABLE-PRINTERS.")
(isnt (princ-to-string #d("1" "2" "3" "4"))
(not "#d(1 2 3 4)")
"#d(\"1\" \"2\" \"3\" \"4\") doesn't print like it with #'DISABLE-PRINTERS."))
(subtest "<OBJECT-ID> literal read-macro test:"
(is-error #i()
'error
"Throws error becaus #i() has no <OBJECT-ID> string representation.")
(is-type #i(50ED6E55616E64231C5D2EDF)
'<object-id>
"#i() corretly returns an object of <OBJECT-ID> type.")
(enable-printers)
(is-print (princ #i(50ED6E55616E64231C5D2EDF))
"#i(50ED6E55616E64231C5D2EDF)"
"Corretly prints a valid <OBJECT-ID>.")
(is '#i(50ED6E55616E64231C5D2EDF)
'(STRING->OBJECT-ID "50ED6E55616E64231C5D2EDF")
"Correctly expands a #i(0000....) form.")
(disable-printers)
(isnt (princ-to-string #i(50ED6E55616E64231C5D2EDF))
(not "#i(50ED6E55616E64231C5D2EDF)")
"Doesn't print like #i(...) with #'DISABLE-PRINTERS.") ))
(deftest big-documen-types-test
(let* ((raw-doc #d(:keyword-key :keyword-value
'symbol-key 'symbol-value
"string-key" "string-value"
"will be coerced to double" 1.5
"will stay as double" 1.5d0
"embedded document"
#d("with many"
#d("levels of"
#d("nesting"
#d("with another \"embedded document\": a vector" #(1 2 3)))))
"sequence" #(1 2 3)
"vector" #(1 2 3)
"list" '(1 2 3)
"regex" (make-instance '<regex> :pattern "\\d+" :options "i")
"binary data" (make-instance
'<binary-data>
:octets (fast-io:make-octet-vector 10))
"javascript code" (make-instance '<javascript>
:code "var example = 1;")
"javascript code with scope" (make-instance
'<javascript>
:code "var example = inScope;"
:scope #d("inScope" 10))
"object-id" (make-instance '<object-id>)
"boolean true" t
"boolean false" nil
"null value" nil
"32 bit integer" 123
"64 bit integer" 1234567890987654321
"local-time:timestamp" (local-time:now)))
(doc (decode (encode raw-doc ))))
(is-type (get-element doc "KEYWORD-KEY")
'string
":keyword-key gets coerced to string.")
(is-type (get-element doc "SYMBOL-KEY")
'string
"'symbol-key gets coerced to string.")
(is-type (get-element doc "string-key")
'string
"String value stays as string.")
(is-type (get-element doc "will be coerced to double")
'double-float
"SINGLE-FLOAT gets coerced to double.")
(is-type (get-element doc "will stay as double")
'double-float
"DOUBLE-FLOAT stays as double.")
(is-type (get-element doc "embedded document")
'<document>
"embedded document in document is a <DOCUMENT>.")
(is-type (get-element doc "sequence")
'sequence
"Array in BSON document is a sequence.")
(is-type (get-element doc "vector")
'sequence
"Vector in document is a sequence.")
(is-type (get-element doc "list")
'sequence
"List in document is a sequence")
(is-type (get-element doc "regex")
'<regex>
"regex in document is a <REGEX>.")
(is-type (get-element doc "binary data")
'<binary-data>
"binary data in document is a <BINARY-DATA>.")
(is-type (get-element doc "javascript code")
'<javascript>
"javascript code in document is a <JAVASCRIPT>.")
(is-type (get-element doc "javascript code with scope")
'<javascript>
"javascript code with scope in document is a <JAVASCRIPT>.")
(is-type (get-element doc "object-id")
'<object-id>
"object-id in document is a <OBJECT-ID>.")
(is (get-element doc "boolean true")
t
"boolean true in document is T.")
(is (get-element doc "boolean false")
nil
"boolean false in document is NIL.")
(is (get-element doc "null value")
nil
"null value in document is NIL.")
(is-type (get-element doc "32 bit integer")
'integer
"32 bit integer in document is integer.")
(ok (<= (integer-length (get-element doc "32 bit integer")) 32)
"32 bit integer in document occupies less than 33 bits.")
(is-type (get-element doc "64 bit integer")
'integer
"64 bit integer in document is integer.")
(ok (<= (integer-length (get-element doc "64 bit integer")) 64)
"64 bit integer in document occupies less than 65 bits.")
(is-type (get-element doc "local-time:timestamp")
'timestamp
"local-time:timestamp in document is a TIMESTAMP.")))
(deftest binary-data-subtypes-test
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data>)))
:generic
"Default <BINARY-DATA> subtype is :GENERIC.")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :function)))
:function
"<BINARY-DATA> subtype is :FUNCTION")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :binary-old)))
:binary-old
"<BINARY-DATA> subtype is :BINARY-OLD")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :uuid-old)))
:uuid-old
"<BINARY-DATA> subtype is :UUID-OLD")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :uuid)))
:uuid
"<BINARY-DATA> subtype is :UUID")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :md5)))
:md5
"<BINARY-DATA> subtype is :MD5")
(is (subtype (enc-dec-kv "bin" (make-instance '<binary-data> :subtype :user-defined)))
:user-defined
"<BINARY-DATA> subtype is :USER-DEFINED")
(is-error (make-instance '<binary-data> :subtype :invalid)
'simple-error
"<BINARY-DATA> invalid subtype throws an error."))
(deftest bad-encoded-document-test
(is-error (decode (replace (encode #d("int" 2)) #(99) :start1 4))
'simple-error
"Unvalid BSON type raises an error."))
(run-test-all)
|
22a20f61fb7669534d8c670497a3782f01881fd8f8b70752d5c0c0b373a5f44d | fourmolu/fourmolu | promotion-1-four-out.hs | type S2 = Proxy ('[ '[], '[]])
type S4 = Proxy ('( 'Just, ' T'T))
type S5 = Proxy ('[ 'Just, 'TT'T])
type S6 = Proxy ('( '(), '()))
type S7 = Proxy ('( 'a, 'b))
type S8 = Proxy ('[Int, Bool])
type E = TypeError ('Text "Some text")
type G = '[ '( 'Just, 'Bool)]
type X = () '`PromotedInfix` ()
| null | https://raw.githubusercontent.com/fourmolu/fourmolu/c305baac7a6fc10f27939d101837f717e4e23252/data/examples/declaration/type/promotion-1-four-out.hs | haskell | type S2 = Proxy ('[ '[], '[]])
type S4 = Proxy ('( 'Just, ' T'T))
type S5 = Proxy ('[ 'Just, 'TT'T])
type S6 = Proxy ('( '(), '()))
type S7 = Proxy ('( 'a, 'b))
type S8 = Proxy ('[Int, Bool])
type E = TypeError ('Text "Some text")
type G = '[ '( 'Just, 'Bool)]
type X = () '`PromotedInfix` ()
| |
d8195ae92c953c0096885d9ec895ce9bbcec08c2d03d36f2ac83ad83b15f0b25 | bsansouci/bsb-native | ratio.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../../LICENSE. *)
(* *)
(***********************************************************************)
* Operation on rational numbers .
This module is used to support the implementation of { ! } and
should not be called directly .
This module is used to support the implementation of {!Num} and
should not be called directly. *)
open Nat
open Big_int
Rationals ( type [ ratio ] ) are arbitrary - precision rational numbers ,
plus the special elements [ 1/0 ] ( infinity ) and [ 0/0 ] ( undefined ) .
In constrast with numbers ( type [ num ] ) , the special cases of
small integers and big integers are not optimized specially .
plus the special elements [1/0] (infinity) and [0/0] (undefined).
In constrast with numbers (type [num]), the special cases of
small integers and big integers are not optimized specially. *)
type ratio
(**/**)
val null_denominator : ratio -> bool
val numerator_ratio : ratio -> big_int
val denominator_ratio : ratio -> big_int
val sign_ratio : ratio -> int
val normalize_ratio : ratio -> ratio
val cautious_normalize_ratio : ratio -> ratio
val cautious_normalize_ratio_when_printing : ratio -> ratio
val create_ratio : big_int -> big_int -> ratio (* assumes nothing *)
val create_normalized_ratio : big_int -> big_int -> ratio
(* assumes normalized argument *)
val is_normalized_ratio : ratio -> bool
val report_sign_ratio : ratio -> big_int -> big_int
val abs_ratio : ratio -> ratio
val is_integer_ratio : ratio -> bool
val add_ratio : ratio -> ratio -> ratio
val minus_ratio : ratio -> ratio
val add_int_ratio : int -> ratio -> ratio
val add_big_int_ratio : big_int -> ratio -> ratio
val sub_ratio : ratio -> ratio -> ratio
val mult_ratio : ratio -> ratio -> ratio
val mult_int_ratio : int -> ratio -> ratio
val mult_big_int_ratio : big_int -> ratio -> ratio
val square_ratio : ratio -> ratio
val inverse_ratio : ratio -> ratio
val div_ratio : ratio -> ratio -> ratio
val integer_ratio : ratio -> big_int
val floor_ratio : ratio -> big_int
val round_ratio : ratio -> big_int
val ceiling_ratio : ratio -> big_int
val eq_ratio : ratio -> ratio -> bool
val compare_ratio : ratio -> ratio -> int
val lt_ratio : ratio -> ratio -> bool
val le_ratio : ratio -> ratio -> bool
val gt_ratio : ratio -> ratio -> bool
val ge_ratio : ratio -> ratio -> bool
val max_ratio : ratio -> ratio -> ratio
val min_ratio : ratio -> ratio -> ratio
val eq_big_int_ratio : big_int -> ratio -> bool
val compare_big_int_ratio : big_int -> ratio -> int
val lt_big_int_ratio : big_int -> ratio -> bool
val le_big_int_ratio : big_int -> ratio -> bool
val gt_big_int_ratio : big_int -> ratio -> bool
val ge_big_int_ratio : big_int -> ratio -> bool
val int_of_ratio : ratio -> int
val ratio_of_int : int -> ratio
val ratio_of_nat : nat -> ratio
val nat_of_ratio : ratio -> nat
val ratio_of_big_int : big_int -> ratio
val big_int_of_ratio : ratio -> big_int
val div_int_ratio : int -> ratio -> ratio
val div_ratio_int : ratio -> int -> ratio
val div_big_int_ratio : big_int -> ratio -> ratio
val div_ratio_big_int : ratio -> big_int -> ratio
val approx_ratio_fix : int -> ratio -> string
val approx_ratio_exp : int -> ratio -> string
val float_of_rational_string : ratio -> string
val string_of_ratio : ratio -> string
val ratio_of_string : string -> ratio
val float_of_ratio : ratio -> float
val power_ratio_positive_int : ratio -> int -> ratio
val power_ratio_positive_big_int : ratio -> big_int -> ratio
| null | https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/otherlibs/num/ratio.mli | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../../LICENSE.
*********************************************************************
*/*
assumes nothing
assumes normalized argument | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
* Operation on rational numbers .
This module is used to support the implementation of { ! } and
should not be called directly .
This module is used to support the implementation of {!Num} and
should not be called directly. *)
open Nat
open Big_int
Rationals ( type [ ratio ] ) are arbitrary - precision rational numbers ,
plus the special elements [ 1/0 ] ( infinity ) and [ 0/0 ] ( undefined ) .
In constrast with numbers ( type [ num ] ) , the special cases of
small integers and big integers are not optimized specially .
plus the special elements [1/0] (infinity) and [0/0] (undefined).
In constrast with numbers (type [num]), the special cases of
small integers and big integers are not optimized specially. *)
type ratio
val null_denominator : ratio -> bool
val numerator_ratio : ratio -> big_int
val denominator_ratio : ratio -> big_int
val sign_ratio : ratio -> int
val normalize_ratio : ratio -> ratio
val cautious_normalize_ratio : ratio -> ratio
val cautious_normalize_ratio_when_printing : ratio -> ratio
val create_normalized_ratio : big_int -> big_int -> ratio
val is_normalized_ratio : ratio -> bool
val report_sign_ratio : ratio -> big_int -> big_int
val abs_ratio : ratio -> ratio
val is_integer_ratio : ratio -> bool
val add_ratio : ratio -> ratio -> ratio
val minus_ratio : ratio -> ratio
val add_int_ratio : int -> ratio -> ratio
val add_big_int_ratio : big_int -> ratio -> ratio
val sub_ratio : ratio -> ratio -> ratio
val mult_ratio : ratio -> ratio -> ratio
val mult_int_ratio : int -> ratio -> ratio
val mult_big_int_ratio : big_int -> ratio -> ratio
val square_ratio : ratio -> ratio
val inverse_ratio : ratio -> ratio
val div_ratio : ratio -> ratio -> ratio
val integer_ratio : ratio -> big_int
val floor_ratio : ratio -> big_int
val round_ratio : ratio -> big_int
val ceiling_ratio : ratio -> big_int
val eq_ratio : ratio -> ratio -> bool
val compare_ratio : ratio -> ratio -> int
val lt_ratio : ratio -> ratio -> bool
val le_ratio : ratio -> ratio -> bool
val gt_ratio : ratio -> ratio -> bool
val ge_ratio : ratio -> ratio -> bool
val max_ratio : ratio -> ratio -> ratio
val min_ratio : ratio -> ratio -> ratio
val eq_big_int_ratio : big_int -> ratio -> bool
val compare_big_int_ratio : big_int -> ratio -> int
val lt_big_int_ratio : big_int -> ratio -> bool
val le_big_int_ratio : big_int -> ratio -> bool
val gt_big_int_ratio : big_int -> ratio -> bool
val ge_big_int_ratio : big_int -> ratio -> bool
val int_of_ratio : ratio -> int
val ratio_of_int : int -> ratio
val ratio_of_nat : nat -> ratio
val nat_of_ratio : ratio -> nat
val ratio_of_big_int : big_int -> ratio
val big_int_of_ratio : ratio -> big_int
val div_int_ratio : int -> ratio -> ratio
val div_ratio_int : ratio -> int -> ratio
val div_big_int_ratio : big_int -> ratio -> ratio
val div_ratio_big_int : ratio -> big_int -> ratio
val approx_ratio_fix : int -> ratio -> string
val approx_ratio_exp : int -> ratio -> string
val float_of_rational_string : ratio -> string
val string_of_ratio : ratio -> string
val ratio_of_string : string -> ratio
val float_of_ratio : ratio -> float
val power_ratio_positive_int : ratio -> int -> ratio
val power_ratio_positive_big_int : ratio -> big_int -> ratio
|
2b3e217f64a724c301653ddd135d71ea6acbc32a2a45a86a17613eb0b5ab02e1 | fyquah/hardcaml_zprize | zprize_ntt.ml | module For_vitis = For_vitis
module Load_sm = Load_sm
module Memory_layout = Memory_layout
module Store_sm = Store_sm
module Top = Top
module Top_config = Top_config
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/zprize/ntt/hardcaml/src/zprize_ntt.ml | ocaml | module For_vitis = For_vitis
module Load_sm = Load_sm
module Memory_layout = Memory_layout
module Store_sm = Store_sm
module Top = Top
module Top_config = Top_config
| |
fea893ccc677e0123fa4057bbd27e92b3732965435edfd07df862fcd42f723af | LPCIC/matita | notationEnv.mli | Copyright ( C ) 2004 - 2005 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* 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 HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* HELM 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 HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /
*)
(** {2 Types} *)
type ident_or_var =
Ident of string
| Var of string
type value =
| TermValue of NotationPt.term
| StringValue of ident_or_var
| NumValue of string
| OptValue of value option
| ListValue of value list
type value_type =
| TermType of int (* the level of the expected term *)
| StringType
| NumType
| OptType of value_type
| ListType of value_type
(** looked up value not found in environment *)
exception Value_not_found of string
(** looked up value has the wrong type
* parameters are value name and value type in environment *)
exception Type_mismatch of string * value_type
type declaration = string * value_type
type binding = string * (value_type * value)
type t = binding list
val declaration_of_var: NotationPt.pattern_variable -> declaration
val value_of_term: NotationPt.term -> value
val term_of_value: value -> NotationPt.term
val well_typed: value_type -> value -> bool
val declarations_of_env: t -> declaration list
val declarations_of_term: NotationPt.term -> declaration list
val combine: declaration list -> value list -> t (** @raise Invalid_argument *)
(** {2 Environment lookup} *)
* @raise
* lookup _ * functions below may raise Value_not_found and Type_mismatch
val lookup_term: t -> string -> NotationPt.term
val lookup_string: t -> string -> ident_or_var
val lookup_num: t -> string -> string
val lookup_opt: t -> string -> value option
val lookup_list: t -> string -> value list
val remove_name: t -> string -> t
val remove_names: t -> string list -> t
* { 2 Bindings mangling }
val opt_binding_some: binding -> binding (* v -> Some v *)
val opt_binding_none: binding -> binding (* v -> None *)
val opt_binding_of_name: declaration -> binding (* None binding *)
val list_binding_of_name: declaration -> binding (* [] binding *)
val opt_declaration: declaration -> declaration (* t -> OptType t *)
val list_declaration: declaration -> declaration (* t -> ListType t *)
* given a list of environments bindings a set of names , ... , n_k , returns
* a single environment where n_i is bound to the list of values bound in the
* starting environments
* a single environment where n_i is bound to the list of values bound in the
* starting environments *)
val coalesce_env: declaration list -> t list -> t
| null | https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/content/notationEnv.mli | ocaml | * {2 Types}
the level of the expected term
* looked up value not found in environment
* looked up value has the wrong type
* parameters are value name and value type in environment
* @raise Invalid_argument
* {2 Environment lookup}
v -> Some v
v -> None
None binding
[] binding
t -> OptType t
t -> ListType t | Copyright ( C ) 2004 - 2005 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* 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 HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* HELM 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 HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /
*)
type ident_or_var =
Ident of string
| Var of string
type value =
| TermValue of NotationPt.term
| StringValue of ident_or_var
| NumValue of string
| OptValue of value option
| ListValue of value list
type value_type =
| StringType
| NumType
| OptType of value_type
| ListType of value_type
exception Value_not_found of string
exception Type_mismatch of string * value_type
type declaration = string * value_type
type binding = string * (value_type * value)
type t = binding list
val declaration_of_var: NotationPt.pattern_variable -> declaration
val value_of_term: NotationPt.term -> value
val term_of_value: value -> NotationPt.term
val well_typed: value_type -> value -> bool
val declarations_of_env: t -> declaration list
val declarations_of_term: NotationPt.term -> declaration list
* @raise
* lookup _ * functions below may raise Value_not_found and Type_mismatch
val lookup_term: t -> string -> NotationPt.term
val lookup_string: t -> string -> ident_or_var
val lookup_num: t -> string -> string
val lookup_opt: t -> string -> value option
val lookup_list: t -> string -> value list
val remove_name: t -> string -> t
val remove_names: t -> string list -> t
* { 2 Bindings mangling }
* given a list of environments bindings a set of names , ... , n_k , returns
* a single environment where n_i is bound to the list of values bound in the
* starting environments
* a single environment where n_i is bound to the list of values bound in the
* starting environments *)
val coalesce_env: declaration list -> t list -> t
|
aba36b72c8991d4813414bda117df002c307e97a5073acd29decf1e32d9334d3 | mathinstitut/goemaxima | errortostring.lisp | ;; Custom version of erromsg() to collect the error as
;; a string after it has been formatted
Matti Harjula 2019
(defmfun $errormsgtostring ()
"errormsgtostring() returns the maxima-error message as string."
(apply #'aformat nil (cadr $error) (caddr (process-error-argl (cddr $error))))
)
| null | https://raw.githubusercontent.com/mathinstitut/goemaxima/2850e0d6af503fc8602d80340a0557f6f14affd2/stack/2023010400/maxima/errortostring.lisp | lisp | Custom version of erromsg() to collect the error as
a string after it has been formatted | Matti Harjula 2019
(defmfun $errormsgtostring ()
"errormsgtostring() returns the maxima-error message as string."
(apply #'aformat nil (cadr $error) (caddr (process-error-argl (cddr $error))))
)
|
2e5208d39bae578fbe45c1d367aa3662e917ee349648753ae878d4ea834bbcf5 | monadbobo/ocaml-core | test.mli | (* sample mli showing everything that 'with fields' introduces *)
NOTES :
( 1 ) this file was hand generated and can therefore get out of sync with
the actual interface of the generated code .
( 2 ) The file generated_test.mli does not have this problem as it is
generated by ocamlp4o from the file test.mli
( 3 ) The types we list here are actually more general than those in
generated_test.mli ( see make_creator , for example )
NOTES:
(1) this file was hand generated and can therefore get out of sync with
the actual interface of the generated code.
(2) The file generated_test.mli does not have this problem as it is
generated by ocamlp4o from the file test.mli
(3) The types we list here are actually more general than those in
generated_test.mli (see make_creator, for example)
*)
open Fieldslib
open Printf
open StdLabels
type ('a,'b) t = {
dir : 'a * 'b;
quantity : ('a , 'b) t;
price : int * 'a;
mutable cancelled : bool;
(* symbol : string; *)
} with fields
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/fieldslib/sample/test.mli | ocaml | sample mli showing everything that 'with fields' introduces
symbol : string; |
NOTES :
( 1 ) this file was hand generated and can therefore get out of sync with
the actual interface of the generated code .
( 2 ) The file generated_test.mli does not have this problem as it is
generated by ocamlp4o from the file test.mli
( 3 ) The types we list here are actually more general than those in
generated_test.mli ( see make_creator , for example )
NOTES:
(1) this file was hand generated and can therefore get out of sync with
the actual interface of the generated code.
(2) The file generated_test.mli does not have this problem as it is
generated by ocamlp4o from the file test.mli
(3) The types we list here are actually more general than those in
generated_test.mli (see make_creator, for example)
*)
open Fieldslib
open Printf
open StdLabels
type ('a,'b) t = {
dir : 'a * 'b;
quantity : ('a , 'b) t;
price : int * 'a;
mutable cancelled : bool;
} with fields
|
22ab290b9bccbfb24cc010a044b6cade8ea208a57f5bae5ca1ad685787f88892 | mzp/coq-ide-for-ios | typeclasses_errors.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : typeclasses_errors.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
(*i*)
open Names
open Decl_kinds
open Term
open Sign
open Evd
open Environ
open Nametab
open Mod_subst
open Topconstr
open Util
open Libnames
(*i*)
type contexts = Parameters | Properties
type typeclass_error =
| NotAClass of constr
| UnboundMethod of global_reference * identifier located (* Class name, method *)
| NoInstance of identifier located * constr list
| UnsatisfiableConstraints of evar_map * (existential_key * hole_kind) option
| MismatchedContextInstance of contexts * constr_expr list * rel_context (* found, expected *)
exception TypeClassError of env * typeclass_error
val not_a_class : env -> constr -> 'a
val unbound_method : env -> global_reference -> identifier located -> 'a
val no_instance : env -> identifier located -> constr list -> 'a
val unsatisfiable_constraints : env -> evar_map -> evar option -> 'a
val mismatched_ctx_inst : env -> contexts -> constr_expr list -> rel_context -> 'a
val unsatisfiable_exception : exn -> bool
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/pretyping/typeclasses_errors.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
Class name, method
found, expected | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : typeclasses_errors.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
open Names
open Decl_kinds
open Term
open Sign
open Evd
open Environ
open Nametab
open Mod_subst
open Topconstr
open Util
open Libnames
type contexts = Parameters | Properties
type typeclass_error =
| NotAClass of constr
| NoInstance of identifier located * constr list
| UnsatisfiableConstraints of evar_map * (existential_key * hole_kind) option
exception TypeClassError of env * typeclass_error
val not_a_class : env -> constr -> 'a
val unbound_method : env -> global_reference -> identifier located -> 'a
val no_instance : env -> identifier located -> constr list -> 'a
val unsatisfiable_constraints : env -> evar_map -> evar option -> 'a
val mismatched_ctx_inst : env -> contexts -> constr_expr list -> rel_context -> 'a
val unsatisfiable_exception : exn -> bool
|
95d341e5b6bc776c4e24fc44aefe01ba1e5175166690d13f74015854eb100267 | eigenhombre/clj-org | test_util.clj | (ns clj-org.test-util
(:require [clojure.test :refer [are deftest is]]))
(defn should= [& args]
(is (apply = args)))
(def ^:private counter (atom 0))
(defn test-name-symbol []
(let [ret (format "examples-%d-test" @counter)]
(swap! counter inc)
(symbol ret)))
(defmacro describe-examples [right-fn left-fn & body]
`(deftest ~(test-name-symbol)
(are [~'lhs ~'rhs]
(is (= (~left-fn ~'lhs) (~right-fn ~'rhs)))
~@body)))
| null | https://raw.githubusercontent.com/eigenhombre/clj-org/46a1ead7ec28e931ff489c1d0b2b47d3d4a479be/test/clj_org/test_util.clj | clojure | (ns clj-org.test-util
(:require [clojure.test :refer [are deftest is]]))
(defn should= [& args]
(is (apply = args)))
(def ^:private counter (atom 0))
(defn test-name-symbol []
(let [ret (format "examples-%d-test" @counter)]
(swap! counter inc)
(symbol ret)))
(defmacro describe-examples [right-fn left-fn & body]
`(deftest ~(test-name-symbol)
(are [~'lhs ~'rhs]
(is (= (~left-fn ~'lhs) (~right-fn ~'rhs)))
~@body)))
| |
d20227091616689491ba55c146a141fca096f2cd0740941defead107ee3fadfa | rnons/lord | main.hs | {-# LANGUAGE OverloadedStrings #-}
import Data.Maybe (fromJust)
import Test.Hspec
import Test.HUnit
import Web.Radio (getPlaylist, readToken)
import qualified Web.Radio.Cmd as Cmd
import Web.Radio.EightTracks
import Web.Radio.Douban
import Web.Radio.Jing
import qualified Web.Radio.Reddit as Reddit
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "getPlaylist" $ do
it "cmd: given genre" $ do
ss <- getPlaylist (Cmd.Genre "Dream Pop")
assertNotNull ss
it "douban: given channel id" $ do
ss <- getPlaylist $ douban "6"
assertNotNull ss
it "douban: given album url" $ do
ss <- getPlaylist $ douban "/"
assert $ albumtitle (head ss) == "變形記"
it "douban: given musician url" $ do
ss <- getPlaylist $ douban "/"
assert $ artist (head ss) == "万能青年旅店"
it "douban: given musician name" $ do
ss <- getPlaylist $ douban "Sigur Rós"
assert $ artist (head ss) == "Sigur Rós"
it "douban: given programme url" $ do
ss <- getPlaylist $ douban ""
assertNotNull ss
it "8tracks: given mix id" $ do
tok <- readToken eight "14"
ss <- getPlaylist $ fromJust tok
assertNotNull ss
it "8tracks: given mix url" $ do
mId <- getMixId "-nie/oblitus"
tok <- readToken eight $ show mId
ss <- getPlaylist $ fromJust tok
assertNotNull ss
it "jing: given keywords" $ do
tok <- readToken jing "postrock"
ss <- getPlaylist $ fromJust tok
assertNotNull ss
it "reddit: given genre" $ do
ss <- getPlaylist (Reddit.Genre "indie")
assertNotNull ss
where
assertNotNull = assert . not .null
| null | https://raw.githubusercontent.com/rnons/lord/31d632306c3a972da2c3fd1f5359277543bfa669/test/main.hs | haskell | # LANGUAGE OverloadedStrings # | import Data.Maybe (fromJust)
import Test.Hspec
import Test.HUnit
import Web.Radio (getPlaylist, readToken)
import qualified Web.Radio.Cmd as Cmd
import Web.Radio.EightTracks
import Web.Radio.Douban
import Web.Radio.Jing
import qualified Web.Radio.Reddit as Reddit
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "getPlaylist" $ do
it "cmd: given genre" $ do
ss <- getPlaylist (Cmd.Genre "Dream Pop")
assertNotNull ss
it "douban: given channel id" $ do
ss <- getPlaylist $ douban "6"
assertNotNull ss
it "douban: given album url" $ do
ss <- getPlaylist $ douban "/"
assert $ albumtitle (head ss) == "變形記"
it "douban: given musician url" $ do
ss <- getPlaylist $ douban "/"
assert $ artist (head ss) == "万能青年旅店"
it "douban: given musician name" $ do
ss <- getPlaylist $ douban "Sigur Rós"
assert $ artist (head ss) == "Sigur Rós"
it "douban: given programme url" $ do
ss <- getPlaylist $ douban ""
assertNotNull ss
it "8tracks: given mix id" $ do
tok <- readToken eight "14"
ss <- getPlaylist $ fromJust tok
assertNotNull ss
it "8tracks: given mix url" $ do
mId <- getMixId "-nie/oblitus"
tok <- readToken eight $ show mId
ss <- getPlaylist $ fromJust tok
assertNotNull ss
it "jing: given keywords" $ do
tok <- readToken jing "postrock"
ss <- getPlaylist $ fromJust tok
assertNotNull ss
it "reddit: given genre" $ do
ss <- getPlaylist (Reddit.Genre "indie")
assertNotNull ss
where
assertNotNull = assert . not .null
|
de31a3d0a7406c28c2cef2c15766000fe741516df63eeb7ac942b339f59f8336 | brownplt/Resugarer | macro.rkt | (module macros racket
(provide
define-macro lookup-macro
expand-pattern unexpand-pattern
; testing:
unchecked-unexpand
NotUnexpandable?
Macro Macro-cases MacroCase expand-macro)
(require "utility.rkt")
(require "pattern.rkt")
Defining Macros ; ; ;
(struct MacroCase (left right) #:transparent)
(struct Macro (name cases) #:transparent)
(define global-macro-dictionary (make-hash)) ; { macro-name -> macro }
(define-syntax (compile-macro stx)
(syntax-case stx ()
[(compile-macro name [(_ p ...) q] ...)
(with-syntax ([(pc ...) (generate-temporaries #'((p ...) ...))] ; why (p ...)?
[(qc ...) (generate-temporaries #'(q ...))])
#'(let [[pc (sexpr->pattern '(name p ...) #f #f)] ...]
(let [[qc (sexpr->pattern 'q (set->list (free-vars pc)) #t)] ...]
(validate-macro (Macro 'name (list (MacroCase pc qc) ...))))))]))
(define-syntax-rule (define-macro name case ...)
(hash-set! global-macro-dictionary 'name
(compile-macro name case ...)))
(define (lookup-macro name)
(if (hash-has-key? global-macro-dictionary name)
(hash-ref global-macro-dictionary name)
#f))
Validating Macros ; ; ;
(define (check-wf-macro m)
(define (check-wf-case c)
(define (union-vars vs)
(cond [(empty? vs) (set)]
[(eq? (length vs) 1) (car vs)]
[else (let [[overlap (set-intersect (car vs) (cadr vs))]]
(if (set-empty? overlap)
(union-vars (cons (set-union (car vs) (cadr vs))
(cddr vs)))
(duplicate-var-failure m (first (set->list overlap)) c)))]))
(define (check-wf-lhs p)
(match p
[(pvar v) (set v)]
[(literal _) (set)]
[(constant _) (set)]
[(tag p _) (check-wf-lhs p)]
[(plist _ ps) (union-vars (map check-wf-lhs ps))]
[(ellipsis _ ps r qs)
(let [[fvr (check-wf-lhs r)]]
(if (set-empty? fvr)
(empty-ellipsis-failure m c)
(union-vars (append (map check-wf-lhs ps)
(list fvr)
(map check-wf-lhs qs)))))]))
; TODO: check that each var on the rhs appears under at least as many
ellipses as it does in the lhs .
; TODO: Figure out duplicate rhs variables.
(define (check-wf-rhs p)
(match p
[(pvar v) (set v)]
[(literal _) (set)]
[(constant _) (set)]
[(tag p _) (check-wf-rhs p)]
[(plist _ ps) (set-unions (map check-wf-rhs ps))]
[(ellipsis _ ps r qs)
(let [[fvr (check-wf-rhs r)]]
(if (set-empty? fvr)
(empty-ellipsis-failure m c)
(set-unions (append (map check-wf-rhs ps)
(list fvr)
(map check-wf-rhs qs)))))]))
(begin (check-wf-lhs (MacroCase-left c))
(check-wf-rhs (MacroCase-right c))))
(for-each check-wf-case (Macro-cases m)))
(define (validate-macro m)
(define (validate-pair pair)
(let* [[c1 (car pair)]
[c2 (cdr pair)]
[p1 (MacroCase-left c1)]
[p2 (MacroCase-left c2)]
[q1 (MacroCase-right c1)]
[q2 (MacroCase-right c2)]
[union (attempt-unification (unify p1 p2))]]
(when (not (unification-failure? union))
(validation-failure m c1 c2 union))))
(begin (check-wf-macro m)
(for-each validate-pair (all-distinct-pairs (Macro-cases m)))
m))
(define (show-macro-case c)
(format "[~a => ~a]"
(show-pattern (MacroCase-left c))
(show-pattern (MacroCase-right c))))
(define (validation-failure m c1 c2 p)
(fail "Invalid macro ~a. Cases ~a and ~a overlap on input ~a."
(Macro-name m) (show-macro-case c1) (show-macro-case c2) (show-pattern p)))
(define (duplicate-var-failure m v c)
(fail "Invalid macro ~a. Duplicate variable ~a in case ~a."
(Macro-name m) v (show-macro-case c)))
(define (empty-ellipsis-failure m c)
(fail "Invaid macro ~a. Variableless ellipsis in case ~a."
(Macro-name m) (show-macro-case c)))
;;; Expanding & Unexpanding Macros ;;;
(struct NotUnexpandable (pattern) #:transparent)
(define (expand-macro m x [i 0])
(define (insert-orig-env e p i)
(tag p (o-macro (Macro-name m) i e)))
(match m
[(Macro name (list))
(fail "No matching pattern in macro ~a for ~a" name (show-pattern x))]
[(Macro name (cons (MacroCase p q) cs))
(let* [[e (attempt-unification (minus x p))]]
(if (unification-failure? e)
(expand-macro (Macro name cs) x (+ i 1))
(tag (substitute e q) (o-macro (Macro-name m)
i
(hash-remove-keys e (free-vars q))))))]
[#f (fail "Could not expand: ~a" (show-pattern x))]))
(define (unexpand-macro x origin)
(match origin
[(o-macro m i q)
(let* [[c (list-ref (Macro-cases (lookup-macro m)) i)]
[lhs (MacroCase-left c)]
[rhs (MacroCase-right c)]]
(substitute (hash-union q (minus x rhs (o-branch))) lhs))]))
(define (expand-pattern e)
(match e
[(constant c) (constant c)]
[(literal l) (literal l)]
[(tag p o) (tag (expand-pattern p) o)]
[(plist t ps)
(cond [(t-macro? t)
(expand-pattern (expand-macro (lookup-macro (t-macro-name t)) e))]
[(t-apply? t)
(plist t (map expand-pattern ps))]
[(t-syntax? t)
(fail "expand-pattern: extraneous syntax-parens (^) in ~a" (show-pattern e))])]))
(define (unchecked-unexpand p)
(define (check-unlittered p)
(match p
[(constant c) (constant c)]
[(literal l) (literal l)]
[(plist t ps) (plist t (map check-unlittered ps))]
[(tag p o) (raise (NotUnexpandable (tag p o)))]))
(define (rec p)
(match p
[(constant c) (constant c)]
[(literal l) (literal l)]
[(plist (t-apply) ps) (plist (t-apply) (map rec ps))]
[(tag p2 o) (match o
[(o-macro m i q) (unexpand-macro (rec p2) o)]
[(o-branch)
(match p2
; Fail to unexpand if a macro is tainted
[p2 (tag (rec p2) o)])]
[(o-branch) (tag (rec p2) o)]
[(o-external) (tag (rec p2) o)])]
[_ (raise (NotUnexpandable p))]))
(check-unlittered (rec p)))
(define (unexpand-pattern p)
(with-handlers [[(λ (x) (or (NotUnexpandable? x) (CantMatch? x)))
(λ (x) #f)]]
(unchecked-unexpand p)))
) | null | https://raw.githubusercontent.com/brownplt/Resugarer/1353b4309c101f0f1ac2df2cba7f3cba1f0a3a37/prototype/macro.rkt | racket | testing:
; ;
{ macro-name -> macro }
why (p ...)?
; ;
TODO: check that each var on the rhs appears under at least as many
TODO: Figure out duplicate rhs variables.
Expanding & Unexpanding Macros ;;;
Fail to unexpand if a macro is tainted | (module macros racket
(provide
define-macro lookup-macro
expand-pattern unexpand-pattern
unchecked-unexpand
NotUnexpandable?
Macro Macro-cases MacroCase expand-macro)
(require "utility.rkt")
(require "pattern.rkt")
(struct MacroCase (left right) #:transparent)
(struct Macro (name cases) #:transparent)
(define-syntax (compile-macro stx)
(syntax-case stx ()
[(compile-macro name [(_ p ...) q] ...)
[(qc ...) (generate-temporaries #'(q ...))])
#'(let [[pc (sexpr->pattern '(name p ...) #f #f)] ...]
(let [[qc (sexpr->pattern 'q (set->list (free-vars pc)) #t)] ...]
(validate-macro (Macro 'name (list (MacroCase pc qc) ...))))))]))
(define-syntax-rule (define-macro name case ...)
(hash-set! global-macro-dictionary 'name
(compile-macro name case ...)))
(define (lookup-macro name)
(if (hash-has-key? global-macro-dictionary name)
(hash-ref global-macro-dictionary name)
#f))
(define (check-wf-macro m)
(define (check-wf-case c)
(define (union-vars vs)
(cond [(empty? vs) (set)]
[(eq? (length vs) 1) (car vs)]
[else (let [[overlap (set-intersect (car vs) (cadr vs))]]
(if (set-empty? overlap)
(union-vars (cons (set-union (car vs) (cadr vs))
(cddr vs)))
(duplicate-var-failure m (first (set->list overlap)) c)))]))
(define (check-wf-lhs p)
(match p
[(pvar v) (set v)]
[(literal _) (set)]
[(constant _) (set)]
[(tag p _) (check-wf-lhs p)]
[(plist _ ps) (union-vars (map check-wf-lhs ps))]
[(ellipsis _ ps r qs)
(let [[fvr (check-wf-lhs r)]]
(if (set-empty? fvr)
(empty-ellipsis-failure m c)
(union-vars (append (map check-wf-lhs ps)
(list fvr)
(map check-wf-lhs qs)))))]))
ellipses as it does in the lhs .
(define (check-wf-rhs p)
(match p
[(pvar v) (set v)]
[(literal _) (set)]
[(constant _) (set)]
[(tag p _) (check-wf-rhs p)]
[(plist _ ps) (set-unions (map check-wf-rhs ps))]
[(ellipsis _ ps r qs)
(let [[fvr (check-wf-rhs r)]]
(if (set-empty? fvr)
(empty-ellipsis-failure m c)
(set-unions (append (map check-wf-rhs ps)
(list fvr)
(map check-wf-rhs qs)))))]))
(begin (check-wf-lhs (MacroCase-left c))
(check-wf-rhs (MacroCase-right c))))
(for-each check-wf-case (Macro-cases m)))
(define (validate-macro m)
(define (validate-pair pair)
(let* [[c1 (car pair)]
[c2 (cdr pair)]
[p1 (MacroCase-left c1)]
[p2 (MacroCase-left c2)]
[q1 (MacroCase-right c1)]
[q2 (MacroCase-right c2)]
[union (attempt-unification (unify p1 p2))]]
(when (not (unification-failure? union))
(validation-failure m c1 c2 union))))
(begin (check-wf-macro m)
(for-each validate-pair (all-distinct-pairs (Macro-cases m)))
m))
(define (show-macro-case c)
(format "[~a => ~a]"
(show-pattern (MacroCase-left c))
(show-pattern (MacroCase-right c))))
(define (validation-failure m c1 c2 p)
(fail "Invalid macro ~a. Cases ~a and ~a overlap on input ~a."
(Macro-name m) (show-macro-case c1) (show-macro-case c2) (show-pattern p)))
(define (duplicate-var-failure m v c)
(fail "Invalid macro ~a. Duplicate variable ~a in case ~a."
(Macro-name m) v (show-macro-case c)))
(define (empty-ellipsis-failure m c)
(fail "Invaid macro ~a. Variableless ellipsis in case ~a."
(Macro-name m) (show-macro-case c)))
(struct NotUnexpandable (pattern) #:transparent)
(define (expand-macro m x [i 0])
(define (insert-orig-env e p i)
(tag p (o-macro (Macro-name m) i e)))
(match m
[(Macro name (list))
(fail "No matching pattern in macro ~a for ~a" name (show-pattern x))]
[(Macro name (cons (MacroCase p q) cs))
(let* [[e (attempt-unification (minus x p))]]
(if (unification-failure? e)
(expand-macro (Macro name cs) x (+ i 1))
(tag (substitute e q) (o-macro (Macro-name m)
i
(hash-remove-keys e (free-vars q))))))]
[#f (fail "Could not expand: ~a" (show-pattern x))]))
(define (unexpand-macro x origin)
(match origin
[(o-macro m i q)
(let* [[c (list-ref (Macro-cases (lookup-macro m)) i)]
[lhs (MacroCase-left c)]
[rhs (MacroCase-right c)]]
(substitute (hash-union q (minus x rhs (o-branch))) lhs))]))
(define (expand-pattern e)
(match e
[(constant c) (constant c)]
[(literal l) (literal l)]
[(tag p o) (tag (expand-pattern p) o)]
[(plist t ps)
(cond [(t-macro? t)
(expand-pattern (expand-macro (lookup-macro (t-macro-name t)) e))]
[(t-apply? t)
(plist t (map expand-pattern ps))]
[(t-syntax? t)
(fail "expand-pattern: extraneous syntax-parens (^) in ~a" (show-pattern e))])]))
(define (unchecked-unexpand p)
(define (check-unlittered p)
(match p
[(constant c) (constant c)]
[(literal l) (literal l)]
[(plist t ps) (plist t (map check-unlittered ps))]
[(tag p o) (raise (NotUnexpandable (tag p o)))]))
(define (rec p)
(match p
[(constant c) (constant c)]
[(literal l) (literal l)]
[(plist (t-apply) ps) (plist (t-apply) (map rec ps))]
[(tag p2 o) (match o
[(o-macro m i q) (unexpand-macro (rec p2) o)]
[(o-branch)
(match p2
[p2 (tag (rec p2) o)])]
[(o-branch) (tag (rec p2) o)]
[(o-external) (tag (rec p2) o)])]
[_ (raise (NotUnexpandable p))]))
(check-unlittered (rec p)))
(define (unexpand-pattern p)
(with-handlers [[(λ (x) (or (NotUnexpandable? x) (CantMatch? x)))
(λ (x) #f)]]
(unchecked-unexpand p)))
) |
80b139587b2d47af9df5a767ebef874d49bc13f816ef79eb7374c87e714f1061 | evilmartians/foundry | test_foundry.ml | open OUnit
Collect the tests of different modules into one test suite
let suite = "Foundry" >:::
[Test_big_int_conv.suite]
let _ =
run_test_tt_main suite
| null | https://raw.githubusercontent.com/evilmartians/foundry/ce947c7dcca79ab7a7ce25870e9fc0eb15e9c2bd/unittest/test_foundry.ml | ocaml | open OUnit
Collect the tests of different modules into one test suite
let suite = "Foundry" >:::
[Test_big_int_conv.suite]
let _ =
run_test_tt_main suite
| |
c045a166b5755bb2cad0e59fd83772a35b0207f86c40bed739a596fe0b12b36e | Octachron/babilim | escape.ml | let string s =
(* Escape only C0 control characters (bytes <= 0x1F), DEL(0x7F), '\\' and '"' *)
let n = ref 0 in
for i = 0 to String.length s - 1 do
n := !n +
(match String.unsafe_get s i with
| '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> 2
| '\x00' .. '\x1F'
| '\x7F' -> 4
| _ -> 1)
done;
if !n = String.length s then s else begin
let s' = Bytes.create !n in
n := 0;
for i = 0 to String.length s - 1 do
begin match String.unsafe_get s i with
| ('\"' | '\\') as c ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n c
| '\n' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'n'
| '\t' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 't'
| '\r' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'r'
| '\b' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'b'
| '\x00' .. '\x1F' | '\x7F' as c ->
let a = Char.code c in
Bytes.unsafe_set s' !n '\\';
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a / 100));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + (a / 10) mod 10));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a mod 10));
| c -> Bytes.unsafe_set s' !n c
end;
incr n
done;
Bytes.to_string s'
end
| null | https://raw.githubusercontent.com/Octachron/babilim/46b0412cd6efef5efe26bfd379566688bf7ab571/po/escape.ml | ocaml | Escape only C0 control characters (bytes <= 0x1F), DEL(0x7F), '\\' and '"' | let string s =
let n = ref 0 in
for i = 0 to String.length s - 1 do
n := !n +
(match String.unsafe_get s i with
| '\"' | '\\' | '\n' | '\t' | '\r' | '\b' -> 2
| '\x00' .. '\x1F'
| '\x7F' -> 4
| _ -> 1)
done;
if !n = String.length s then s else begin
let s' = Bytes.create !n in
n := 0;
for i = 0 to String.length s - 1 do
begin match String.unsafe_get s i with
| ('\"' | '\\') as c ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n c
| '\n' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'n'
| '\t' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 't'
| '\r' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'r'
| '\b' ->
Bytes.unsafe_set s' !n '\\'; incr n; Bytes.unsafe_set s' !n 'b'
| '\x00' .. '\x1F' | '\x7F' as c ->
let a = Char.code c in
Bytes.unsafe_set s' !n '\\';
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a / 100));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + (a / 10) mod 10));
incr n;
Bytes.unsafe_set s' !n (Char.chr (48 + a mod 10));
| c -> Bytes.unsafe_set s' !n c
end;
incr n
done;
Bytes.to_string s'
end
|
0c33dd96bdea6e30c7e70565e6cc8230b7dd3d1879814580d6d85b9e30c5fbe1 | kimim/re-echarts | browser.cljs | (ns starter.browser
(:require
[reagent.dom :as rdom]
[re-echarts.core :refer [ECharts]]))
(defn myechart []
[:> ECharts
{:style {:width "800px" :height "600px"}
:theme "dark"
:option
{:title {:text "Echarts is here"}
:dataset {:dimention [:Week :Value]
:source [{:Week "Mon" :Value 820} {:Week "Tue" :Value 932} {:Week "Wed" :Value 901}
{:Week "Thu" :Value 934} {:Week "Fri" :Value 1220} {:Week "Sat" :Value 820}
{:Week "Sun" :Value 990}]}
:xAxis {:type "category"}
:yAxis {:type "value"}
:series [{:type "line"
:smooth true}]}}])
;; start is called by init and after code reloading finishes
(defn ^:dev/after-load start []
(js/console.log "start")
(rdom/render [#'myechart] (.getElementById js/document "app")))
(defn ^:export init []
;; init is called ONCE when the page loads
;; this is called in the index.html and must be exported
;; so it is available even in :advanced release builds
(js/console.log "init")
(start))
;; this is called before any code is reloaded
(defn ^:dev/before-load stop []
(js/console.log "stop"))
| null | https://raw.githubusercontent.com/kimim/re-echarts/c5ee516e222095213be1a50d0139fa140742eb9f/example/src/starter/browser.cljs | clojure | start is called by init and after code reloading finishes
init is called ONCE when the page loads
this is called in the index.html and must be exported
so it is available even in :advanced release builds
this is called before any code is reloaded
| (ns starter.browser
(:require
[reagent.dom :as rdom]
[re-echarts.core :refer [ECharts]]))
(defn myechart []
[:> ECharts
{:style {:width "800px" :height "600px"}
:theme "dark"
:option
{:title {:text "Echarts is here"}
:dataset {:dimention [:Week :Value]
:source [{:Week "Mon" :Value 820} {:Week "Tue" :Value 932} {:Week "Wed" :Value 901}
{:Week "Thu" :Value 934} {:Week "Fri" :Value 1220} {:Week "Sat" :Value 820}
{:Week "Sun" :Value 990}]}
:xAxis {:type "category"}
:yAxis {:type "value"}
:series [{:type "line"
:smooth true}]}}])
(defn ^:dev/after-load start []
(js/console.log "start")
(rdom/render [#'myechart] (.getElementById js/document "app")))
(defn ^:export init []
(js/console.log "init")
(start))
(defn ^:dev/before-load stop []
(js/console.log "stop"))
|
0880df3c482510adcdca7a4de8b6b2ae1d092cc1a1e4bd1d511d11689c624445 | hipsleek/hipsleek | cvpermUtils.ml | #include "xdebug.cppo"
open VarGen
open Gen
open Globals
open Cpure
let remove_dups = Gen.BList.remove_dups_eq eq_spec_var_ident
let check_dups = Gen.BList.check_dups_eq eq_spec_var_ident
let diff = Gen.BList.difference_eq eq_spec_var_ident
let intersect = Gen.BList.intersect_eq eq_spec_var_ident
let overlap = Gen.BList.overlap_eq eq_spec_var_ident
let mem = Gen.BList.mem_eq eq_spec_var_ident
(* To store vperm of variables *)
type vperm_sets = {
vperm_unprimed_flag: bool;
vperm_is_false : bool;
vperm_zero_vars: spec_var list;
vperm_lend_vars: spec_var list;
vperm_value_vars: spec_var list;
vperm_full_vars: spec_var list;
(* vperm_frac_vars: (Frac.frac * spec_var list) list; *)
vperm_frac_vars: (Frac.frac * spec_var) list; (*simpler*)
}
let print_vperm_sets = ref (fun (vps: vperm_sets) -> "vperm_sets printer has not been initialized")
(* unused cos of ivperm? *)
let build_vperm ?zero:(zero=[]) ?lend:(lend=[]) ?value:(value=[])
?frac:(frac=[]) full
=
let cnt = (List.length zero) + (List.length lend) + (List.length value) + (List.length frac) + (List.length full) in
{
vperm_unprimed_flag = if cnt=0 then true else false;
vperm_is_false = false;
vperm_zero_vars = List.map sp_rm_prime zero;
vperm_lend_vars = List.map sp_rm_prime lend;
vperm_value_vars = List.map sp_rm_prime value;
vperm_full_vars = List.map sp_rm_prime full;
vperm_frac_vars = List.map (fun (a,v) -> (a,sp_rm_prime v)) frac;
}
let vperm_unprime vp = { vp with vperm_unprimed_flag = false}
let vperm_rm_prime vp = vp
if vp.vperm_unprimed_flag then vp
(* else *)
(* { vp with *)
(* vperm_unprimed_flag = true; *)
vperm_zero_vars = List.map sp_rm_prime vp.vperm_zero_vars ;
vperm_lend_vars = ;
vperm_value_vars = List.map sp_rm_prime vp.vperm_value_vars ;
vperm_full_vars = List.map sp_rm_prime vp.vperm_full_vars ;
vperm_frac_vars = List.map ( fun ( a , vs ) - > ( a , sp_rm_prime vs ) ) vp.vperm_frac_vars ;
(* } *)
(* let vperm_rm_prime vps = *)
(* let pr = !print_vperm_sets in *)
Debug.no_1 " vperm_rm_prime " pr pr
ZH : it is redundant ?
let vperm_rm_prime vp =
if vp.vperm_unprimed_flag then vp
else vperm_rm_prime vp
let empty_vperm_sets = build_vperm []
let is_empty_frac fr =
let xs = ( fun ( f , _ ) - > not(Frac.is_zero f ) ) fr in
(* is_empty xs *)
List.for_all (fun (f,_) -> Frac.is_zero f) fr
let is_empty_vperm_sets vps =
not (!Globals.ann_vp) ||
((is_empty vps.vperm_full_vars) &&
(is_empty vps.vperm_lend_vars) &&
(is_empty vps.vperm_value_vars) &&
(* (is_empty vps.vperm_zero_vars) && *)
(is_empty_frac vps.vperm_frac_vars))
let is_empty_frac_leak fr =
let xs = ( fun ( f , _ ) - > not(Frac.is_zero f || Frac.is_value f ) ) fr in
(* is_empty xs *)
List.for_all (fun (f,_) -> Frac.is_zero f || Frac.is_value f) fr
WN : need to filter frac list
let is_leak_vperm vps =
match vps with
| { vperm_full_vars = full; vperm_frac_vars = frac } ->
not(is_empty full) || not(is_empty_frac_leak frac)
let rec partition_by_key key_of key_eq ls =
match ls with
| [] -> []
| e::es ->
let ke = key_of e in
let same_es, other_es = List.partition (fun e -> key_eq ke (key_of e)) es in
(ke, e::same_es)::(partition_by_key key_of key_eq other_es)
let is_Zero ann =
match ann with
| VP_Zero -> true
| VP_Frac f -> Frac.is_zero f
| _ -> false
let norm_frac_list xs =
let rec aux xs fr sv =
match xs with
| [] -> [(fr,sv)]
| (fr2,sv2)::xs ->
if eq_spec_var_ident sv sv2 then aux xs (Frac.add fr fr2) sv
else (fr,sv)::(aux xs fr2 sv2)
in match xs with
| [] -> []
| (fr,sv)::xs -> aux xs fr sv
let norm_frac_list frac_vars =
let frac_vars = List.sort (fun (_,sv1) (_,sv2) ->
String.compare (get_unprime sv1) (get_unprime sv2)) frac_vars in
let frac_vars2 = norm_frac_list frac_vars in
frac_vars2
let check_dupl svl =
let rec aux svl p =
match svl with
| [] -> false
| v::vs -> if eq_spec_var_ident p v then true else aux vs v
in match svl with
| [] -> false
| v::vs -> aux vs v
let norm_list svl =
let svl2 = List.sort (fun v1 v2 -> String.compare (get_unprime v1) (get_unprime v2)) svl in
(svl2,check_dupl svl2)
let check_dupl_two s1 s2 =
let rec aux s1 s2 =
match s1,s2 with
| [],_ -> false
| _,[] -> false
| (v1::t1),(v2::t2) ->
let c = String.compare (get_unprime v1) (get_unprime v2) in
if c=0 then true
else if c<0 then aux t1 s2
else aux s1 t2 in
aux s1 s2
let norm_full_value full value =
let svl1,f1 = norm_list full in
let svl2,f2 = norm_list value in
let f = f1||f2 in
if f then (svl1,svl2,f)
else (svl1,svl2,check_dupl_two svl1 svl2)
let is_frac_false xs =
List.exists (Frac.is_false) (List.map fst xs)
let frac_vars =
( fun ( f , v ) - > not(Frac.is_zero f ) ) frac_vars
let is_false_frac_other frac_vars full_vars value_vars =
let vs = full_vars@value_vars in
List.exists (fun (f,v) -> not(Frac.is_zero f) && mem v vs) frac_vars
let norm_vperm_sets vps =
let vps = vperm_rm_prime vps in
let (full_vars,value_vars,flag1) = norm_full_value vps.vperm_full_vars vps.vperm_value_vars in
let zero_vars = remove_dups vps.vperm_zero_vars in (* @zero[x] * @zero[x] -> @zero[x] *)
let lend_vars = remove_dups vps.vperm_lend_vars in (* @lend[x] * @lend[x] -> @lend[x] *)
let full_vars = ( \ * remove_dups * \ ) vps.vperm_full_vars in ( \ * ] * @full[x ] - > false * \ )
let frac_vars2 = norm_frac_list vps.vperm_frac_vars in
let false_flag = flag1 || (is_frac_false frac_vars2)
|| (is_false_frac_other frac_vars2 full_vars value_vars) in
WN : need to check if below correct !
(* let frac_vars_set = List.map (fun (frac, group) -> *)
let m_group = List.concat ( List.map snd group ) in
(* (frac, m_group)) group_frac_vars_sets *)
{ vps with
vperm_full_vars = full_vars;
vperm_is_false = false_flag;
vperm_lend_vars = diff lend_vars full_vars; (* TO FIX Value? *)
vperm_value_vars = value_vars;
vperm_zero_vars = diff zero_vars (full_vars @ lend_vars);
vperm_frac_vars = frac_vars2; }
let norm_vperm_sets vps =
if not (!Globals.ann_vp) then vps
else
let pr = !print_vperm_sets in
Debug.no_1 "norm_vperm_sets" pr pr norm_vperm_sets vps
let quick_is_false vps = vps.vperm_is_false
let merge_vperm_sets vps_list =
if not (!Globals.ann_vp) then empty_vperm_sets
else
let rec helper vps_list =
match vps_list with
| [] -> empty_vperm_sets
| v::vs ->
let mvs = helper vs in
{
vperm_unprimed_flag = (v.vperm_unprimed_flag && mvs.vperm_unprimed_flag);
vperm_is_false = v.vperm_is_false || mvs.vperm_is_false;
vperm_zero_vars = v.vperm_zero_vars @ mvs.vperm_zero_vars;
vperm_lend_vars = v.vperm_lend_vars @ mvs.vperm_lend_vars;
vperm_value_vars = v.vperm_value_vars @ mvs.vperm_value_vars;
vperm_full_vars = v.vperm_full_vars @ mvs.vperm_full_vars;
vperm_frac_vars = v.vperm_frac_vars @ mvs.vperm_frac_vars; }
in norm_vperm_sets (helper vps_list)
let merge_vperm_sets vps_list =
let vps_list = List.filter (fun x -> not (is_empty_vperm_sets x)) vps_list in
if (List.length vps_list)<=1 then merge_vperm_sets vps_list
else
let pr = !print_vperm_sets in
Debug.no_1 "merge_vperm_sets" (pr_list pr) pr merge_vperm_sets vps_list
@full[x ] * ] - > ERR
(* @full[x] * @lend[x] -> ERR *)
(* @full[x] * @zero[x] -> @full[x] *)
(* @lend[x] * @lend[x] -> @lend[x] => remove_dups *)
(* @lend[x] * @zero[x] -> @lend[x] *)
(* @zero[x] * @zero[x] -> @zero[x] => remove_dups *)
let combine_vperm_sets vps_list =
if not (!Globals.ann_vp) then empty_vperm_sets
else
let rec helper vps_list =
match vps_list with
| [] -> empty_vperm_sets
| v::vs ->
let v = vperm_rm_prime v in
let mvs = helper vs in
{
vperm_unprimed_flag = (v.vperm_unprimed_flag && mvs.vperm_unprimed_flag);
vperm_is_false = v.vperm_is_false || mvs.vperm_is_false;
vperm_zero_vars = v.vperm_zero_vars @ mvs.vperm_zero_vars;
vperm_lend_vars = v.vperm_lend_vars @ mvs.vperm_lend_vars;
vperm_value_vars = v.vperm_value_vars @ mvs.vperm_value_vars;
vperm_full_vars = v.vperm_full_vars @ mvs.vperm_full_vars;
vperm_frac_vars = norm_frac_list (v.vperm_frac_vars @ mvs.vperm_frac_vars); }
in
let comb_vps = helper vps_list in
let full_vars = comb_vps.vperm_full_vars in
let lend_vars = comb_vps.vperm_lend_vars in
let zero_vars = comb_vps.vperm_zero_vars in
let msg = "Combination of vperm sets causes contradiction" in
let err = ({ Error.error_loc = proving_loc # get; Error.error_text = msg }) in
let ( ) = x_binfo_pp " inside combine_vperm_sets " no_pos in
if (check_dups full_vars) (* || (overlap full_vars lend_vars) *)
then Error.report_error err
else
{ comb_vps with
vperm_zero_vars = remove_dups (diff zero_vars (full_vars @ lend_vars));
vperm_lend_vars = remove_dups lend_vars; }
let combine_vperm_sets vps_list =
let vps_list = List.filter (fun x -> not (is_empty_vperm_sets x)) vps_list in
if (List.length vps_list)<=1 then combine_vperm_sets vps_list
else
let pr = !print_vperm_sets in
Debug.no_1 "combine_vperm_sets" (pr_list pr) pr combine_vperm_sets vps_list
@full[x ] or ] - > @full[x ]
(* @full[x] or @lend[x] -> @lend[x] *)
(* @full[x] or @zero[x] -> @zero[x] *)
(* @lend[x] or @lend[x] -> @lend[x] *)
(* @lend[x] or @zero[x] -> @zero[x] *)
(* @zero[x] or @zero[x] -> @zero[x] *)
(* this method loses too much information ; it should not be used *)
let combine_or_vperm_sets vps1 vps2 =
let f1, f2 = vps1.vperm_full_vars, vps2.vperm_full_vars in
let l1, l2 = vps1.vperm_lend_vars, vps2.vperm_lend_vars in
let z1, z2 = vps1.vperm_zero_vars, vps2.vperm_zero_vars in
let v1, v2 = f1 @ l1 @ z1, f2 @ l2 @ z2 in
let alone_vars = diff (v1 @ v2) (intersect v1 v2) in
let z = remove_dups (z1 @ z2 @ alone_vars) in
let l = remove_dups (diff (l1 @ l2) z) in
let f = remove_dups (diff (f1 @ f2) (l @ z)) in
{
vperm_unprimed_flag = (vps1.vperm_unprimed_flag && vps2.vperm_unprimed_flag);
vperm_is_false = vps1.vperm_is_false && vps2.vperm_is_false;
vperm_zero_vars = z;
vperm_lend_vars = l;
vperm_full_vars = f;
TODO
TODO
let vperm_sets_of_anns ann_list =
let rec helper ann_list =
match ann_list with
| [] -> empty_vperm_sets
| (ann, svl)::vs ->
let mvs = helper vs in
match ann with
| VP_Zero -> { mvs with vperm_zero_vars = mvs.vperm_zero_vars @ svl; }
| VP_Full -> { mvs with vperm_full_vars = mvs.vperm_full_vars @ svl; }
| VP_Value -> { mvs with vperm_value_vars = mvs.vperm_value_vars @ svl; }
| VP_Lend -> { mvs with vperm_lend_vars = mvs.vperm_lend_vars @ svl; }
| VP_Frac frac -> { mvs with vperm_frac_vars = mvs.vperm_frac_vars @ (List.map (fun v -> (frac, v)) svl); }
in norm_vperm_sets (helper ann_list)
(* This seems to be removing vps of some ids *)
let clear_vperm_sets ann_list vps =
let rec helper ann_list =
match ann_list with
| [] -> vps
| (ann, svl)::vs ->
let cvs = helper vs in
match ann with
| VP_Zero -> { cvs with vperm_zero_vars = diff cvs.vperm_zero_vars svl; }
| VP_Full -> { cvs with vperm_full_vars = diff cvs.vperm_full_vars svl; }
| VP_Value -> { cvs with vperm_value_vars = diff cvs.vperm_value_vars svl; }
| VP_Lend -> { cvs with vperm_lend_vars = diff cvs.vperm_lend_vars svl; }
| VP_Frac frac -> { cvs with vperm_frac_vars =
TODO : WN
let frac_sets , others = List.partition ( fun ( f , _ ) - >
Frac.eq_frac f frac ) cvs.vperm_frac_vars in
let frac_svl = List.concat ( List.map snd frac_sets ) in
(* let frac_svl = (frac, diff frac_svl svl) in *)
{ cvs with vperm_frac_vars = ( frac , svl)::others ; }
in helper ann_list
let fv vps =
remove_dups (vps.vperm_zero_vars @ vps.vperm_full_vars @ vps.vperm_value_vars @
vps.vperm_lend_vars @ (List.map snd vps.vperm_frac_vars))
let subst_f f sst vps =
let f_list vl = List.map (fun v -> f sst v) vl in
{ vps with
vperm_zero_vars = f_list vps.vperm_zero_vars;
vperm_lend_vars = f_list vps.vperm_lend_vars;
vperm_value_vars = f_list vps.vperm_value_vars;
vperm_full_vars = f_list vps.vperm_full_vars;
vperm_frac_vars = List.map (fun (frac, v) -> (frac, f sst v)) vps.vperm_frac_vars; }
let subst_par sst vps =
subst_f subst_var_par sst vps
type : ( Cpure.spec_var * Cpure.spec_var ) list - > vperm_sets - > vperm_sets
let subst_par sst vps =
let pr = pr_list (pr_pair Cpure.string_of_spec_var Cpure.string_of_spec_var) in
let pr2 = !print_vperm_sets in
Debug.no_2 "subst_par" pr pr2 pr2 subst_par sst vps
let subst_one sst vps =
subst_f subst_var sst vps
let subst_one sst vps =
let pr = (pr_pair Cpure.string_of_spec_var Cpure.string_of_spec_var) in
let pr2 = !print_vperm_sets in
Debug.no_2 "subst_one" pr pr2 pr2 subst_one sst vps
let subst_avoid_capture f t vps =
let sst = List.combine f t in
subst_f subs_one sst vps
let is_false_vperm_sets vps =
vps.vperm_is_false
let norm_is_false_vperm_sets vps =
let vps = norm_vperm_sets vps in
(vps,vps.vperm_is_false)
(* let full_vars = vps.vperm_full_vars in *)
(* check_dups full_vars *)
let get_vperm_spec_var sv vps =
if mem sv vps.vperm_full_vars then VP_Full
else if mem sv vps.vperm_lend_vars then VP_Lend
else if mem sv vps.vperm_value_vars then VP_Value
else
try
let frac_perm, _ = List.find (fun (_, s) -> eq_spec_var_ident sv s) vps.vperm_frac_vars in
VP_Frac frac_perm
with _ -> VP_Zero
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/src/cvpermUtils.ml | ocaml | To store vperm of variables
vperm_frac_vars: (Frac.frac * spec_var list) list;
simpler
unused cos of ivperm?
else
{ vp with
vperm_unprimed_flag = true;
}
let vperm_rm_prime vps =
let pr = !print_vperm_sets in
is_empty xs
(is_empty vps.vperm_zero_vars) &&
is_empty xs
@zero[x] * @zero[x] -> @zero[x]
@lend[x] * @lend[x] -> @lend[x]
let frac_vars_set = List.map (fun (frac, group) ->
(frac, m_group)) group_frac_vars_sets
TO FIX Value?
@full[x] * @lend[x] -> ERR
@full[x] * @zero[x] -> @full[x]
@lend[x] * @lend[x] -> @lend[x] => remove_dups
@lend[x] * @zero[x] -> @lend[x]
@zero[x] * @zero[x] -> @zero[x] => remove_dups
|| (overlap full_vars lend_vars)
@full[x] or @lend[x] -> @lend[x]
@full[x] or @zero[x] -> @zero[x]
@lend[x] or @lend[x] -> @lend[x]
@lend[x] or @zero[x] -> @zero[x]
@zero[x] or @zero[x] -> @zero[x]
this method loses too much information ; it should not be used
This seems to be removing vps of some ids
let frac_svl = (frac, diff frac_svl svl) in
let full_vars = vps.vperm_full_vars in
check_dups full_vars | #include "xdebug.cppo"
open VarGen
open Gen
open Globals
open Cpure
let remove_dups = Gen.BList.remove_dups_eq eq_spec_var_ident
let check_dups = Gen.BList.check_dups_eq eq_spec_var_ident
let diff = Gen.BList.difference_eq eq_spec_var_ident
let intersect = Gen.BList.intersect_eq eq_spec_var_ident
let overlap = Gen.BList.overlap_eq eq_spec_var_ident
let mem = Gen.BList.mem_eq eq_spec_var_ident
type vperm_sets = {
vperm_unprimed_flag: bool;
vperm_is_false : bool;
vperm_zero_vars: spec_var list;
vperm_lend_vars: spec_var list;
vperm_value_vars: spec_var list;
vperm_full_vars: spec_var list;
}
let print_vperm_sets = ref (fun (vps: vperm_sets) -> "vperm_sets printer has not been initialized")
let build_vperm ?zero:(zero=[]) ?lend:(lend=[]) ?value:(value=[])
?frac:(frac=[]) full
=
let cnt = (List.length zero) + (List.length lend) + (List.length value) + (List.length frac) + (List.length full) in
{
vperm_unprimed_flag = if cnt=0 then true else false;
vperm_is_false = false;
vperm_zero_vars = List.map sp_rm_prime zero;
vperm_lend_vars = List.map sp_rm_prime lend;
vperm_value_vars = List.map sp_rm_prime value;
vperm_full_vars = List.map sp_rm_prime full;
vperm_frac_vars = List.map (fun (a,v) -> (a,sp_rm_prime v)) frac;
}
let vperm_unprime vp = { vp with vperm_unprimed_flag = false}
let vperm_rm_prime vp = vp
if vp.vperm_unprimed_flag then vp
vperm_zero_vars = List.map sp_rm_prime vp.vperm_zero_vars ;
vperm_lend_vars = ;
vperm_value_vars = List.map sp_rm_prime vp.vperm_value_vars ;
vperm_full_vars = List.map sp_rm_prime vp.vperm_full_vars ;
vperm_frac_vars = List.map ( fun ( a , vs ) - > ( a , sp_rm_prime vs ) ) vp.vperm_frac_vars ;
Debug.no_1 " vperm_rm_prime " pr pr
ZH : it is redundant ?
let vperm_rm_prime vp =
if vp.vperm_unprimed_flag then vp
else vperm_rm_prime vp
let empty_vperm_sets = build_vperm []
let is_empty_frac fr =
let xs = ( fun ( f , _ ) - > not(Frac.is_zero f ) ) fr in
List.for_all (fun (f,_) -> Frac.is_zero f) fr
let is_empty_vperm_sets vps =
not (!Globals.ann_vp) ||
((is_empty vps.vperm_full_vars) &&
(is_empty vps.vperm_lend_vars) &&
(is_empty vps.vperm_value_vars) &&
(is_empty_frac vps.vperm_frac_vars))
let is_empty_frac_leak fr =
let xs = ( fun ( f , _ ) - > not(Frac.is_zero f || Frac.is_value f ) ) fr in
List.for_all (fun (f,_) -> Frac.is_zero f || Frac.is_value f) fr
WN : need to filter frac list
let is_leak_vperm vps =
match vps with
| { vperm_full_vars = full; vperm_frac_vars = frac } ->
not(is_empty full) || not(is_empty_frac_leak frac)
let rec partition_by_key key_of key_eq ls =
match ls with
| [] -> []
| e::es ->
let ke = key_of e in
let same_es, other_es = List.partition (fun e -> key_eq ke (key_of e)) es in
(ke, e::same_es)::(partition_by_key key_of key_eq other_es)
let is_Zero ann =
match ann with
| VP_Zero -> true
| VP_Frac f -> Frac.is_zero f
| _ -> false
let norm_frac_list xs =
let rec aux xs fr sv =
match xs with
| [] -> [(fr,sv)]
| (fr2,sv2)::xs ->
if eq_spec_var_ident sv sv2 then aux xs (Frac.add fr fr2) sv
else (fr,sv)::(aux xs fr2 sv2)
in match xs with
| [] -> []
| (fr,sv)::xs -> aux xs fr sv
let norm_frac_list frac_vars =
let frac_vars = List.sort (fun (_,sv1) (_,sv2) ->
String.compare (get_unprime sv1) (get_unprime sv2)) frac_vars in
let frac_vars2 = norm_frac_list frac_vars in
frac_vars2
let check_dupl svl =
let rec aux svl p =
match svl with
| [] -> false
| v::vs -> if eq_spec_var_ident p v then true else aux vs v
in match svl with
| [] -> false
| v::vs -> aux vs v
let norm_list svl =
let svl2 = List.sort (fun v1 v2 -> String.compare (get_unprime v1) (get_unprime v2)) svl in
(svl2,check_dupl svl2)
let check_dupl_two s1 s2 =
let rec aux s1 s2 =
match s1,s2 with
| [],_ -> false
| _,[] -> false
| (v1::t1),(v2::t2) ->
let c = String.compare (get_unprime v1) (get_unprime v2) in
if c=0 then true
else if c<0 then aux t1 s2
else aux s1 t2 in
aux s1 s2
let norm_full_value full value =
let svl1,f1 = norm_list full in
let svl2,f2 = norm_list value in
let f = f1||f2 in
if f then (svl1,svl2,f)
else (svl1,svl2,check_dupl_two svl1 svl2)
let is_frac_false xs =
List.exists (Frac.is_false) (List.map fst xs)
let frac_vars =
( fun ( f , v ) - > not(Frac.is_zero f ) ) frac_vars
let is_false_frac_other frac_vars full_vars value_vars =
let vs = full_vars@value_vars in
List.exists (fun (f,v) -> not(Frac.is_zero f) && mem v vs) frac_vars
let norm_vperm_sets vps =
let vps = vperm_rm_prime vps in
let (full_vars,value_vars,flag1) = norm_full_value vps.vperm_full_vars vps.vperm_value_vars in
let full_vars = ( \ * remove_dups * \ ) vps.vperm_full_vars in ( \ * ] * @full[x ] - > false * \ )
let frac_vars2 = norm_frac_list vps.vperm_frac_vars in
let false_flag = flag1 || (is_frac_false frac_vars2)
|| (is_false_frac_other frac_vars2 full_vars value_vars) in
WN : need to check if below correct !
let m_group = List.concat ( List.map snd group ) in
{ vps with
vperm_full_vars = full_vars;
vperm_is_false = false_flag;
vperm_value_vars = value_vars;
vperm_zero_vars = diff zero_vars (full_vars @ lend_vars);
vperm_frac_vars = frac_vars2; }
let norm_vperm_sets vps =
if not (!Globals.ann_vp) then vps
else
let pr = !print_vperm_sets in
Debug.no_1 "norm_vperm_sets" pr pr norm_vperm_sets vps
let quick_is_false vps = vps.vperm_is_false
let merge_vperm_sets vps_list =
if not (!Globals.ann_vp) then empty_vperm_sets
else
let rec helper vps_list =
match vps_list with
| [] -> empty_vperm_sets
| v::vs ->
let mvs = helper vs in
{
vperm_unprimed_flag = (v.vperm_unprimed_flag && mvs.vperm_unprimed_flag);
vperm_is_false = v.vperm_is_false || mvs.vperm_is_false;
vperm_zero_vars = v.vperm_zero_vars @ mvs.vperm_zero_vars;
vperm_lend_vars = v.vperm_lend_vars @ mvs.vperm_lend_vars;
vperm_value_vars = v.vperm_value_vars @ mvs.vperm_value_vars;
vperm_full_vars = v.vperm_full_vars @ mvs.vperm_full_vars;
vperm_frac_vars = v.vperm_frac_vars @ mvs.vperm_frac_vars; }
in norm_vperm_sets (helper vps_list)
let merge_vperm_sets vps_list =
let vps_list = List.filter (fun x -> not (is_empty_vperm_sets x)) vps_list in
if (List.length vps_list)<=1 then merge_vperm_sets vps_list
else
let pr = !print_vperm_sets in
Debug.no_1 "merge_vperm_sets" (pr_list pr) pr merge_vperm_sets vps_list
@full[x ] * ] - > ERR
let combine_vperm_sets vps_list =
if not (!Globals.ann_vp) then empty_vperm_sets
else
let rec helper vps_list =
match vps_list with
| [] -> empty_vperm_sets
| v::vs ->
let v = vperm_rm_prime v in
let mvs = helper vs in
{
vperm_unprimed_flag = (v.vperm_unprimed_flag && mvs.vperm_unprimed_flag);
vperm_is_false = v.vperm_is_false || mvs.vperm_is_false;
vperm_zero_vars = v.vperm_zero_vars @ mvs.vperm_zero_vars;
vperm_lend_vars = v.vperm_lend_vars @ mvs.vperm_lend_vars;
vperm_value_vars = v.vperm_value_vars @ mvs.vperm_value_vars;
vperm_full_vars = v.vperm_full_vars @ mvs.vperm_full_vars;
vperm_frac_vars = norm_frac_list (v.vperm_frac_vars @ mvs.vperm_frac_vars); }
in
let comb_vps = helper vps_list in
let full_vars = comb_vps.vperm_full_vars in
let lend_vars = comb_vps.vperm_lend_vars in
let zero_vars = comb_vps.vperm_zero_vars in
let msg = "Combination of vperm sets causes contradiction" in
let err = ({ Error.error_loc = proving_loc # get; Error.error_text = msg }) in
let ( ) = x_binfo_pp " inside combine_vperm_sets " no_pos in
then Error.report_error err
else
{ comb_vps with
vperm_zero_vars = remove_dups (diff zero_vars (full_vars @ lend_vars));
vperm_lend_vars = remove_dups lend_vars; }
let combine_vperm_sets vps_list =
let vps_list = List.filter (fun x -> not (is_empty_vperm_sets x)) vps_list in
if (List.length vps_list)<=1 then combine_vperm_sets vps_list
else
let pr = !print_vperm_sets in
Debug.no_1 "combine_vperm_sets" (pr_list pr) pr combine_vperm_sets vps_list
@full[x ] or ] - > @full[x ]
let combine_or_vperm_sets vps1 vps2 =
let f1, f2 = vps1.vperm_full_vars, vps2.vperm_full_vars in
let l1, l2 = vps1.vperm_lend_vars, vps2.vperm_lend_vars in
let z1, z2 = vps1.vperm_zero_vars, vps2.vperm_zero_vars in
let v1, v2 = f1 @ l1 @ z1, f2 @ l2 @ z2 in
let alone_vars = diff (v1 @ v2) (intersect v1 v2) in
let z = remove_dups (z1 @ z2 @ alone_vars) in
let l = remove_dups (diff (l1 @ l2) z) in
let f = remove_dups (diff (f1 @ f2) (l @ z)) in
{
vperm_unprimed_flag = (vps1.vperm_unprimed_flag && vps2.vperm_unprimed_flag);
vperm_is_false = vps1.vperm_is_false && vps2.vperm_is_false;
vperm_zero_vars = z;
vperm_lend_vars = l;
vperm_full_vars = f;
TODO
TODO
let vperm_sets_of_anns ann_list =
let rec helper ann_list =
match ann_list with
| [] -> empty_vperm_sets
| (ann, svl)::vs ->
let mvs = helper vs in
match ann with
| VP_Zero -> { mvs with vperm_zero_vars = mvs.vperm_zero_vars @ svl; }
| VP_Full -> { mvs with vperm_full_vars = mvs.vperm_full_vars @ svl; }
| VP_Value -> { mvs with vperm_value_vars = mvs.vperm_value_vars @ svl; }
| VP_Lend -> { mvs with vperm_lend_vars = mvs.vperm_lend_vars @ svl; }
| VP_Frac frac -> { mvs with vperm_frac_vars = mvs.vperm_frac_vars @ (List.map (fun v -> (frac, v)) svl); }
in norm_vperm_sets (helper ann_list)
let clear_vperm_sets ann_list vps =
let rec helper ann_list =
match ann_list with
| [] -> vps
| (ann, svl)::vs ->
let cvs = helper vs in
match ann with
| VP_Zero -> { cvs with vperm_zero_vars = diff cvs.vperm_zero_vars svl; }
| VP_Full -> { cvs with vperm_full_vars = diff cvs.vperm_full_vars svl; }
| VP_Value -> { cvs with vperm_value_vars = diff cvs.vperm_value_vars svl; }
| VP_Lend -> { cvs with vperm_lend_vars = diff cvs.vperm_lend_vars svl; }
| VP_Frac frac -> { cvs with vperm_frac_vars =
TODO : WN
let frac_sets , others = List.partition ( fun ( f , _ ) - >
Frac.eq_frac f frac ) cvs.vperm_frac_vars in
let frac_svl = List.concat ( List.map snd frac_sets ) in
{ cvs with vperm_frac_vars = ( frac , svl)::others ; }
in helper ann_list
let fv vps =
remove_dups (vps.vperm_zero_vars @ vps.vperm_full_vars @ vps.vperm_value_vars @
vps.vperm_lend_vars @ (List.map snd vps.vperm_frac_vars))
let subst_f f sst vps =
let f_list vl = List.map (fun v -> f sst v) vl in
{ vps with
vperm_zero_vars = f_list vps.vperm_zero_vars;
vperm_lend_vars = f_list vps.vperm_lend_vars;
vperm_value_vars = f_list vps.vperm_value_vars;
vperm_full_vars = f_list vps.vperm_full_vars;
vperm_frac_vars = List.map (fun (frac, v) -> (frac, f sst v)) vps.vperm_frac_vars; }
let subst_par sst vps =
subst_f subst_var_par sst vps
type : ( Cpure.spec_var * Cpure.spec_var ) list - > vperm_sets - > vperm_sets
let subst_par sst vps =
let pr = pr_list (pr_pair Cpure.string_of_spec_var Cpure.string_of_spec_var) in
let pr2 = !print_vperm_sets in
Debug.no_2 "subst_par" pr pr2 pr2 subst_par sst vps
let subst_one sst vps =
subst_f subst_var sst vps
let subst_one sst vps =
let pr = (pr_pair Cpure.string_of_spec_var Cpure.string_of_spec_var) in
let pr2 = !print_vperm_sets in
Debug.no_2 "subst_one" pr pr2 pr2 subst_one sst vps
let subst_avoid_capture f t vps =
let sst = List.combine f t in
subst_f subs_one sst vps
let is_false_vperm_sets vps =
vps.vperm_is_false
let norm_is_false_vperm_sets vps =
let vps = norm_vperm_sets vps in
(vps,vps.vperm_is_false)
let get_vperm_spec_var sv vps =
if mem sv vps.vperm_full_vars then VP_Full
else if mem sv vps.vperm_lend_vars then VP_Lend
else if mem sv vps.vperm_value_vars then VP_Value
else
try
let frac_perm, _ = List.find (fun (_, s) -> eq_spec_var_ident sv s) vps.vperm_frac_vars in
VP_Frac frac_perm
with _ -> VP_Zero
|
8df8cecd3f0712d26e078220f88b0a17ee50892910635fee7739bc5da3352f05 | hasktorch/hasktorch | Training.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Torch.GraduallyTyped.NN.Training where
import Control.Monad.IO.Class (MonadIO (..))
import qualified Pipes as P
import qualified Pipes.Prelude as P
import Torch.GraduallyTyped.NN.Class (HasForward (..), HasStateDict (..), ModelSpec)
import Torch.GraduallyTyped.Optim (Optimizer, stepWithGenerator)
import Torch.GraduallyTyped.Prelude (Catch)
import Torch.GraduallyTyped.Prelude.List (SList (..))
import Torch.GraduallyTyped.Random (Generator, SGetGeneratorDevice)
import Torch.GraduallyTyped.RequiresGradient (Gradient (..), RequiresGradient (..), SGradient (..), SRequiresGradient (..))
import Torch.GraduallyTyped.Shape.Type (SShape (..), Shape (..))
import Torch.GraduallyTyped.Tensor.MathOperations.Pointwise (divScalar)
import Torch.GraduallyTyped.Tensor.Type (SGetGradient, SGetShape, Tensor, sCheckedGradient, sCheckedShape, withoutGradient)
import Torch.GraduallyTyped.Unify (type (<+>))
| Train the model for one epoch .
train ::
forall m model input generatorDevice lossGradient lossLayout lossDataType lossDevice lossShape generatorOutputDevice.
( MonadIO m,
HasStateDict model,
HasForward model input generatorDevice (Tensor lossGradient lossLayout lossDataType lossDevice lossShape) generatorOutputDevice,
HasForward model input generatorOutputDevice (Tensor lossGradient lossLayout lossDataType lossDevice lossShape) generatorOutputDevice,
SGetGeneratorDevice generatorDevice,
SGetGeneratorDevice generatorOutputDevice,
SGetGradient lossGradient,
SGetShape lossShape,
Catch (lossShape <+> 'Shape '[]),
Catch (lossGradient <+> 'Gradient 'WithGradient)
) =>
-- | optimizer for the model
Optimizer model ->
-- | model specification
ModelSpec model ->
-- | stream of training examples
P.ListT m input ->
-- | random generator
Generator generatorDevice ->
-- | returned is either the original generator or the average training loss and a new generator
m
( Either
(Generator generatorDevice)
(Tensor ('Gradient 'WithoutGradient) lossLayout lossDataType lossDevice ('Shape '[]), Generator generatorOutputDevice)
)
train optim modelSpec examples g = do
let producer = P.zip (P.enumerate examples) (P.each [0 :: Int ..])
x <- P.next producer
case x of
Left _ -> pure . Left $ g
Right ((input, iter), producer') -> do
let step ((loss, _), g') (input', iter') = liftIO $ do
let forward' model g'' = do
(loss', g''') <- forward model input' g''
loss'' <- sCheckedShape (SShape SNil) =<< sCheckedGradient (SGradient SWithGradient) loss'
pure (loss'', g''')
(loss', g'') <- stepWithGenerator optim modelSpec forward' g'
loss'' <- withoutGradient loss'
pure ((loss + loss'', iter'), g'')
init' = liftIO $ do
let forward' model g' = do
(loss, g'') <- forward model input g'
loss' <- sCheckedShape (SShape SNil) =<< sCheckedGradient (SGradient SWithGradient) loss
pure (loss', g'')
(loss, g') <- stepWithGenerator optim modelSpec forward' g
loss' <- withoutGradient loss
pure ((loss', iter), g')
done ((loss, iter'), g'') = pure . Right $ (loss `divScalar` iter', g'')
P.foldM step init' done producer'
-- | Evaluate the model on the given examples.
eval ::
( MonadIO m,
HasStateDict model,
HasForward model input generatorDevice (Tensor lossGradient lossLayout lossDataType lossDevice lossShape) generatorOutputDevice,
HasForward model input generatorOutputDevice (Tensor lossGradient lossLayout lossDataType lossDevice lossShape) generatorOutputDevice,
SGetGradient lossGradient,
SGetShape lossShape,
Catch (lossShape <+> 'Shape '[]),
Catch (lossGradient <+> 'Gradient 'WithoutGradient)
) =>
-- | model
model ->
-- | stream of examples
P.ListT m input ->
-- | random generator
Generator generatorDevice ->
-- | returned is either the original generator or the average evaluation loss and a new generator
m
( Either
(Generator generatorDevice)
(Tensor ('Gradient 'WithoutGradient) lossLayout lossDataType lossDevice ('Shape '[]), Generator generatorOutputDevice)
)
eval model examples g = do
let producer = P.zip (P.enumerate examples) (P.each [0 :: Int ..])
x <- P.next producer
case x of
Left _ -> pure . Left $ g
Right ((input, iter), producer') -> do
let step ((loss, _), g') (input', iter') = liftIO $ do
(loss', g'') <- forward model input' g'
loss'' <- sCheckedShape (SShape SNil) =<< sCheckedGradient (SGradient SWithoutGradient) loss'
pure ((loss + loss'', iter'), g'')
init' = liftIO $ do
(loss, g') <- forward model input g
loss' <- sCheckedShape (SShape SNil) =<< sCheckedGradient (SGradient SWithoutGradient) loss
pure ((loss', iter), g')
done ((loss, iter'), g'') = pure . Right $ (loss `divScalar` iter', g'')
P.foldM step init' done producer'
| null | https://raw.githubusercontent.com/hasktorch/hasktorch/c34996b0a401a5b1b98b5774e892fde88adaa079/experimental/gradually-typed/src/Torch/GraduallyTyped/NN/Training.hs | haskell | # LANGUAGE RankNTypes #
| optimizer for the model
| model specification
| stream of training examples
| random generator
| returned is either the original generator or the average training loss and a new generator
| Evaluate the model on the given examples.
| model
| stream of examples
| random generator
| returned is either the original generator or the average evaluation loss and a new generator | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Torch.GraduallyTyped.NN.Training where
import Control.Monad.IO.Class (MonadIO (..))
import qualified Pipes as P
import qualified Pipes.Prelude as P
import Torch.GraduallyTyped.NN.Class (HasForward (..), HasStateDict (..), ModelSpec)
import Torch.GraduallyTyped.Optim (Optimizer, stepWithGenerator)
import Torch.GraduallyTyped.Prelude (Catch)
import Torch.GraduallyTyped.Prelude.List (SList (..))
import Torch.GraduallyTyped.Random (Generator, SGetGeneratorDevice)
import Torch.GraduallyTyped.RequiresGradient (Gradient (..), RequiresGradient (..), SGradient (..), SRequiresGradient (..))
import Torch.GraduallyTyped.Shape.Type (SShape (..), Shape (..))
import Torch.GraduallyTyped.Tensor.MathOperations.Pointwise (divScalar)
import Torch.GraduallyTyped.Tensor.Type (SGetGradient, SGetShape, Tensor, sCheckedGradient, sCheckedShape, withoutGradient)
import Torch.GraduallyTyped.Unify (type (<+>))
| Train the model for one epoch .
train ::
forall m model input generatorDevice lossGradient lossLayout lossDataType lossDevice lossShape generatorOutputDevice.
( MonadIO m,
HasStateDict model,
HasForward model input generatorDevice (Tensor lossGradient lossLayout lossDataType lossDevice lossShape) generatorOutputDevice,
HasForward model input generatorOutputDevice (Tensor lossGradient lossLayout lossDataType lossDevice lossShape) generatorOutputDevice,
SGetGeneratorDevice generatorDevice,
SGetGeneratorDevice generatorOutputDevice,
SGetGradient lossGradient,
SGetShape lossShape,
Catch (lossShape <+> 'Shape '[]),
Catch (lossGradient <+> 'Gradient 'WithGradient)
) =>
Optimizer model ->
ModelSpec model ->
P.ListT m input ->
Generator generatorDevice ->
m
( Either
(Generator generatorDevice)
(Tensor ('Gradient 'WithoutGradient) lossLayout lossDataType lossDevice ('Shape '[]), Generator generatorOutputDevice)
)
train optim modelSpec examples g = do
let producer = P.zip (P.enumerate examples) (P.each [0 :: Int ..])
x <- P.next producer
case x of
Left _ -> pure . Left $ g
Right ((input, iter), producer') -> do
let step ((loss, _), g') (input', iter') = liftIO $ do
let forward' model g'' = do
(loss', g''') <- forward model input' g''
loss'' <- sCheckedShape (SShape SNil) =<< sCheckedGradient (SGradient SWithGradient) loss'
pure (loss'', g''')
(loss', g'') <- stepWithGenerator optim modelSpec forward' g'
loss'' <- withoutGradient loss'
pure ((loss + loss'', iter'), g'')
init' = liftIO $ do
let forward' model g' = do
(loss, g'') <- forward model input g'
loss' <- sCheckedShape (SShape SNil) =<< sCheckedGradient (SGradient SWithGradient) loss
pure (loss', g'')
(loss, g') <- stepWithGenerator optim modelSpec forward' g
loss' <- withoutGradient loss
pure ((loss', iter), g')
done ((loss, iter'), g'') = pure . Right $ (loss `divScalar` iter', g'')
P.foldM step init' done producer'
eval ::
( MonadIO m,
HasStateDict model,
HasForward model input generatorDevice (Tensor lossGradient lossLayout lossDataType lossDevice lossShape) generatorOutputDevice,
HasForward model input generatorOutputDevice (Tensor lossGradient lossLayout lossDataType lossDevice lossShape) generatorOutputDevice,
SGetGradient lossGradient,
SGetShape lossShape,
Catch (lossShape <+> 'Shape '[]),
Catch (lossGradient <+> 'Gradient 'WithoutGradient)
) =>
model ->
P.ListT m input ->
Generator generatorDevice ->
m
( Either
(Generator generatorDevice)
(Tensor ('Gradient 'WithoutGradient) lossLayout lossDataType lossDevice ('Shape '[]), Generator generatorOutputDevice)
)
eval model examples g = do
let producer = P.zip (P.enumerate examples) (P.each [0 :: Int ..])
x <- P.next producer
case x of
Left _ -> pure . Left $ g
Right ((input, iter), producer') -> do
let step ((loss, _), g') (input', iter') = liftIO $ do
(loss', g'') <- forward model input' g'
loss'' <- sCheckedShape (SShape SNil) =<< sCheckedGradient (SGradient SWithoutGradient) loss'
pure ((loss + loss'', iter'), g'')
init' = liftIO $ do
(loss, g') <- forward model input g
loss' <- sCheckedShape (SShape SNil) =<< sCheckedGradient (SGradient SWithoutGradient) loss
pure ((loss', iter), g')
done ((loss, iter'), g'') = pure . Right $ (loss `divScalar` iter', g'')
P.foldM step init' done producer'
|
92f0ad45640385267d967347752208ffcf1e0aa2c80763e584aa8374a1dc9d59 | TyOverby/mono | hash_queue_intf.ml | open! Import
(** The key is used for the hashtable of queue elements. *)
module type Key = Hashtbl.Key_plain
module type S1 = sig
type 'key create_arg
type 'key create_key
(** A hash-queue, where the values are of type ['data]. *)
type ('key, 'data) t [@@deriving sexp_of]
include Container.S1_phantom_invariant with type ('data, 'key) t := ('key, 'data) t
(** [invariant t] checks the invariants of the queue. *)
val invariant : ('key, 'data) t -> unit
* [ create ( ) ] returns an empty queue . The arguments [ growth_allowed ] and [ size ] are
referring to the underlying hashtable .
@param growth_allowed defaults to true
@param size initial size -- default to 16
referring to the underlying hashtable.
@param growth_allowed defaults to true
@param size initial size -- default to 16
*)
val create
: ?growth_allowed:bool
-> ?size:int
-> 'key create_arg
-> ('key create_key, 'data) t
(** Clears the queue. *)
val clear : ('key, 'data) t -> unit
(** Makes a fresh copy of the queue with identical contents to the original. *)
val copy : ('key, 'data) t -> ('key, 'data) t
* { 2 Finding elements }
(** [mem q k] returns true iff there is some (k, v) in the queue. *)
val mem : ('key, 'data) t -> 'key -> bool
(** [lookup t k] returns the value of the key-value pair in the queue with
key k, if there is one. *)
val lookup : ('key, 'data) t -> 'key -> 'data option
val lookup_exn : ('key, 'data) t -> 'key -> 'data
* { 2 Adding , removing , and replacing elements }
Note that even the non-[*_exn ] versions can raise , but only if there is an ongoing
iteration .
Note that even the non-[*_exn] versions can raise, but only if there is an ongoing
iteration. *)
(** [enqueue t back_or_front k v] adds the key-value pair (k, v) to the front or back of
the queue, returning [`Ok] if the pair was added, or [`Key_already_present] if there
is already a (k, v') in the queue.
*)
val enqueue
: ('key, 'data) t
-> [ `back | `front ]
-> 'key
-> 'data
-> [ `Ok | `Key_already_present ]
(** Like {!enqueue}, but it raises in the [`Key_already_present] case *)
val enqueue_exn : ('key, 'data) t -> [ `back | `front ] -> 'key -> 'data -> unit
(** See {!enqueue}. [enqueue_back t k v] is the same as [enqueue t `back k v] *)
val enqueue_back : ('key, 'data) t -> 'key -> 'data -> [ `Ok | `Key_already_present ]
(** See {!enqueue_exn}. [enqueue_back_exn t k v] is the same as [enqueue_exn t `back k v] *)
val enqueue_back_exn : ('key, 'data) t -> 'key -> 'data -> unit
* See { ! enqueue } . [ enqueue_front t k v ] is the same as [ enqueue t ` front k v ]
val enqueue_front : ('key, 'data) t -> 'key -> 'data -> [ `Ok | `Key_already_present ]
(** See {!enqueue_exn}. [enqueue_front_exn t k v] is the same as [enqueue_exn t `front k
v] *)
val enqueue_front_exn : ('key, 'data) t -> 'key -> 'data -> unit
(** [lookup_and_move_to_back] finds the key-value pair (k, v) and moves it to the
back of the queue if it exists, otherwise returning [None].
The [_exn] versions of these functions raise if key-value pair does not exist.
*)
val lookup_and_move_to_back : ('key, 'data) t -> 'key -> 'data option
(** Like {!lookup_and_move_to_back}, but raises instead of returning an option *)
val lookup_and_move_to_back_exn : ('key, 'data) t -> 'key -> 'data
(** Like {!lookup_and_move_to_back}, but moves element to the front of the queue *)
val lookup_and_move_to_front : ('key, 'data) t -> 'key -> 'data option
* Like { ! } , but raises instead of returning an option
val lookup_and_move_to_front_exn : ('key, 'data) t -> 'key -> 'data
(** [last t] returns the last element of the queue, without removing it. *)
val last : ('key, 'data) t -> 'data option
(** [last_with_key t] returns the last element of the queue and its key, without
removing it. *)
val last_with_key : ('key, 'data) t -> ('key * 'data) option
* [ first t ] returns the front element of the queue , without removing it .
val first : ('key, 'data) t -> 'data option
(** [first_with_key t] returns the front element of the queue and its key, without
removing it. *)
val first_with_key : ('key, 'data) t -> ('key * 'data) option
(** [keys t] returns the keys in the order of the queue. *)
val keys : ('key, 'data) t -> 'key list
(** [dequeue t front_or_back] returns the front or back element of the queue. *)
val dequeue : ('key, 'data) t -> [ `back | `front ] -> 'data option
(** Like {!dequeue}, but it raises if the queue is empty. *)
val dequeue_exn : ('key, 'data) t -> [ `back | `front ] -> 'data
(** [dequeue_back t] returns the back element of the queue. *)
val dequeue_back : ('key, 'data) t -> 'data option
(** Like {!dequeue_back}, but it raises if the queue is empty. *)
val dequeue_back_exn : ('key, 'data) t -> 'data
(** [dequeue_front t] returns the front element of the queue. *)
val dequeue_front : ('key, 'data) t -> 'data option
(** Like {!dequeue_front}, but it raises if the queue is empty. *)
val dequeue_front_exn : ('key, 'data) t -> 'data
(** [dequeue_with_key t] returns the front or back element of the queue and its key. *)
val dequeue_with_key : ('key, 'data) t -> [ `back | `front ] -> ('key * 'data) option
(** Like {!dequeue_with_key}, but it raises if the queue is empty. *)
val dequeue_with_key_exn : ('key, 'data) t -> [ `back | `front ] -> 'key * 'data
(** [dequeue_back_with_key t] returns the back element of the queue and its key. *)
val dequeue_back_with_key : ('key, 'data) t -> ('key * 'data) option
(** Like {!dequeue_back_with_key}, but it raises if the queue is empty. *)
val dequeue_back_with_key_exn : ('key, 'data) t -> 'key * 'data
(** [dequeue_front_with_key t] returns the front element of the queue and its key. *)
val dequeue_front_with_key : ('key, 'data) t -> ('key * 'data) option
(** Like {!dequeue_front_with_key}, but it raises if the queue is empty. *)
val dequeue_front_with_key_exn : ('key, 'data) t -> 'key * 'data
(** [dequeue_all t ~f] dequeues every element of the queue and applies [f] to each one.
The dequeue order is from front to back. *)
val dequeue_all : ('key, 'data) t -> f:('data -> unit) -> unit
(** [remove q k] removes the key-value pair with key [k] from the queue. *)
val remove : ('key, 'data) t -> 'key -> [ `Ok | `No_such_key ]
val remove_exn : ('key, 'data) t -> 'key -> unit
(** like {!remove}, but returns the removed element *)
val lookup_and_remove : ('key, 'data) t -> 'key -> 'data option
(** [replace q k v] changes the value of key [k] in the queue to [v]. *)
val replace : ('key, 'data) t -> 'key -> 'data -> [ `Ok | `No_such_key ]
val replace_exn : ('key, 'data) t -> 'key -> 'data -> unit
* [ drop ? n q back_or_front ] drops [ n ] elements ( default 1 ) from the back or front of
the queue . If the queue has fewer than [ n ] elements then it is cleared .
the queue. If the queue has fewer than [n] elements then it is cleared. *)
val drop : ?n:int -> ('key, 'data) t -> [ `back | `front ] -> unit
(** Equivalent to [drop ?n q `front]. *)
val drop_front : ?n:int -> ('key, 'data) t -> unit
(** Equivalent to [drop ?n q `back]. *)
val drop_back : ?n:int -> ('key, 'data) t -> unit
* { 2 Iterating over elements }
(** [iter t ~f] applies [f] to each key and element of the queue. *)
val iteri : ('key, 'data) t -> f:(key:'key -> data:'data -> unit) -> unit
val foldi : ('key, 'data) t -> init:'b -> f:('b -> key:'key -> data:'data -> 'b) -> 'b
end
module type S0 = sig
type ('key, 'data) hash_queue
type key
include
S1
with type 'key create_key := key
with type 'key create_arg := unit
with type ('key, 'data) t := ('key, 'data) hash_queue
type 'data t = (key, 'data) hash_queue [@@deriving sexp_of]
end
module type S_backend = sig
include
S1
with type 'key create_arg := 'key Hashtbl.Hashable.t
with type 'key create_key := 'key
module type S = S0 with type ('key, 'data) hash_queue := ('key, 'data) t
module Make (Key : Key) : S with type key = Key.t
module Make_with_hashable (T : sig
module Key : Key
val hashable : Key.t Hashtbl.Hashable.t
end) : S with type key = T.Key.t
end
* A hash - queue is a combination of a queue and a hashtable that
supports constant - time lookup and removal of queue elements in addition to
the usual queue operations ( enqueue , dequeue ) . The queue elements are
key - value pairs . The hashtable has one entry for each element of the queue .
Calls to functions that would modify a hash - queue ( e.g. [ enqueue ] , [ dequeue ] ,
[ remove ] , [ replace ] ) detect if a client is in the middle of iterating over the
queue ( e.g. , [ iter ] , [ fold ] , [ for_all ] , [ exists ] ) and if so , raise an exception .
supports constant-time lookup and removal of queue elements in addition to
the usual queue operations (enqueue, dequeue). The queue elements are
key-value pairs. The hashtable has one entry for each element of the queue.
Calls to functions that would modify a hash-queue (e.g. [enqueue], [dequeue],
[remove], [replace]) detect if a client is in the middle of iterating over the
queue (e.g., [iter], [fold], [for_all], [exists]) and if so, raise an exception.
*)
module type Hash_queue = sig
module type Key = Key
module type S_backend = S_backend
module Make_backend (Table : Hashtbl_intf.Hashtbl) : S_backend
* equivalent to [ Make_backend ( ) ]
include S_backend
end
| null | https://raw.githubusercontent.com/TyOverby/mono/7666c0328d194bf9a569fb65babc0486f2aaa40d/vendor/janestreet-core/core/src/hash_queue_intf.ml | ocaml | * The key is used for the hashtable of queue elements.
* A hash-queue, where the values are of type ['data].
* [invariant t] checks the invariants of the queue.
* Clears the queue.
* Makes a fresh copy of the queue with identical contents to the original.
* [mem q k] returns true iff there is some (k, v) in the queue.
* [lookup t k] returns the value of the key-value pair in the queue with
key k, if there is one.
* [enqueue t back_or_front k v] adds the key-value pair (k, v) to the front or back of
the queue, returning [`Ok] if the pair was added, or [`Key_already_present] if there
is already a (k, v') in the queue.
* Like {!enqueue}, but it raises in the [`Key_already_present] case
* See {!enqueue}. [enqueue_back t k v] is the same as [enqueue t `back k v]
* See {!enqueue_exn}. [enqueue_back_exn t k v] is the same as [enqueue_exn t `back k v]
* See {!enqueue_exn}. [enqueue_front_exn t k v] is the same as [enqueue_exn t `front k
v]
* [lookup_and_move_to_back] finds the key-value pair (k, v) and moves it to the
back of the queue if it exists, otherwise returning [None].
The [_exn] versions of these functions raise if key-value pair does not exist.
* Like {!lookup_and_move_to_back}, but raises instead of returning an option
* Like {!lookup_and_move_to_back}, but moves element to the front of the queue
* [last t] returns the last element of the queue, without removing it.
* [last_with_key t] returns the last element of the queue and its key, without
removing it.
* [first_with_key t] returns the front element of the queue and its key, without
removing it.
* [keys t] returns the keys in the order of the queue.
* [dequeue t front_or_back] returns the front or back element of the queue.
* Like {!dequeue}, but it raises if the queue is empty.
* [dequeue_back t] returns the back element of the queue.
* Like {!dequeue_back}, but it raises if the queue is empty.
* [dequeue_front t] returns the front element of the queue.
* Like {!dequeue_front}, but it raises if the queue is empty.
* [dequeue_with_key t] returns the front or back element of the queue and its key.
* Like {!dequeue_with_key}, but it raises if the queue is empty.
* [dequeue_back_with_key t] returns the back element of the queue and its key.
* Like {!dequeue_back_with_key}, but it raises if the queue is empty.
* [dequeue_front_with_key t] returns the front element of the queue and its key.
* Like {!dequeue_front_with_key}, but it raises if the queue is empty.
* [dequeue_all t ~f] dequeues every element of the queue and applies [f] to each one.
The dequeue order is from front to back.
* [remove q k] removes the key-value pair with key [k] from the queue.
* like {!remove}, but returns the removed element
* [replace q k v] changes the value of key [k] in the queue to [v].
* Equivalent to [drop ?n q `front].
* Equivalent to [drop ?n q `back].
* [iter t ~f] applies [f] to each key and element of the queue. | open! Import
module type Key = Hashtbl.Key_plain
module type S1 = sig
type 'key create_arg
type 'key create_key
type ('key, 'data) t [@@deriving sexp_of]
include Container.S1_phantom_invariant with type ('data, 'key) t := ('key, 'data) t
val invariant : ('key, 'data) t -> unit
* [ create ( ) ] returns an empty queue . The arguments [ growth_allowed ] and [ size ] are
referring to the underlying hashtable .
@param growth_allowed defaults to true
@param size initial size -- default to 16
referring to the underlying hashtable.
@param growth_allowed defaults to true
@param size initial size -- default to 16
*)
val create
: ?growth_allowed:bool
-> ?size:int
-> 'key create_arg
-> ('key create_key, 'data) t
val clear : ('key, 'data) t -> unit
val copy : ('key, 'data) t -> ('key, 'data) t
* { 2 Finding elements }
val mem : ('key, 'data) t -> 'key -> bool
val lookup : ('key, 'data) t -> 'key -> 'data option
val lookup_exn : ('key, 'data) t -> 'key -> 'data
* { 2 Adding , removing , and replacing elements }
Note that even the non-[*_exn ] versions can raise , but only if there is an ongoing
iteration .
Note that even the non-[*_exn] versions can raise, but only if there is an ongoing
iteration. *)
val enqueue
: ('key, 'data) t
-> [ `back | `front ]
-> 'key
-> 'data
-> [ `Ok | `Key_already_present ]
val enqueue_exn : ('key, 'data) t -> [ `back | `front ] -> 'key -> 'data -> unit
val enqueue_back : ('key, 'data) t -> 'key -> 'data -> [ `Ok | `Key_already_present ]
val enqueue_back_exn : ('key, 'data) t -> 'key -> 'data -> unit
* See { ! enqueue } . [ enqueue_front t k v ] is the same as [ enqueue t ` front k v ]
val enqueue_front : ('key, 'data) t -> 'key -> 'data -> [ `Ok | `Key_already_present ]
val enqueue_front_exn : ('key, 'data) t -> 'key -> 'data -> unit
val lookup_and_move_to_back : ('key, 'data) t -> 'key -> 'data option
val lookup_and_move_to_back_exn : ('key, 'data) t -> 'key -> 'data
val lookup_and_move_to_front : ('key, 'data) t -> 'key -> 'data option
* Like { ! } , but raises instead of returning an option
val lookup_and_move_to_front_exn : ('key, 'data) t -> 'key -> 'data
val last : ('key, 'data) t -> 'data option
val last_with_key : ('key, 'data) t -> ('key * 'data) option
* [ first t ] returns the front element of the queue , without removing it .
val first : ('key, 'data) t -> 'data option
val first_with_key : ('key, 'data) t -> ('key * 'data) option
val keys : ('key, 'data) t -> 'key list
val dequeue : ('key, 'data) t -> [ `back | `front ] -> 'data option
val dequeue_exn : ('key, 'data) t -> [ `back | `front ] -> 'data
val dequeue_back : ('key, 'data) t -> 'data option
val dequeue_back_exn : ('key, 'data) t -> 'data
val dequeue_front : ('key, 'data) t -> 'data option
val dequeue_front_exn : ('key, 'data) t -> 'data
val dequeue_with_key : ('key, 'data) t -> [ `back | `front ] -> ('key * 'data) option
val dequeue_with_key_exn : ('key, 'data) t -> [ `back | `front ] -> 'key * 'data
val dequeue_back_with_key : ('key, 'data) t -> ('key * 'data) option
val dequeue_back_with_key_exn : ('key, 'data) t -> 'key * 'data
val dequeue_front_with_key : ('key, 'data) t -> ('key * 'data) option
val dequeue_front_with_key_exn : ('key, 'data) t -> 'key * 'data
val dequeue_all : ('key, 'data) t -> f:('data -> unit) -> unit
val remove : ('key, 'data) t -> 'key -> [ `Ok | `No_such_key ]
val remove_exn : ('key, 'data) t -> 'key -> unit
val lookup_and_remove : ('key, 'data) t -> 'key -> 'data option
val replace : ('key, 'data) t -> 'key -> 'data -> [ `Ok | `No_such_key ]
val replace_exn : ('key, 'data) t -> 'key -> 'data -> unit
* [ drop ? n q back_or_front ] drops [ n ] elements ( default 1 ) from the back or front of
the queue . If the queue has fewer than [ n ] elements then it is cleared .
the queue. If the queue has fewer than [n] elements then it is cleared. *)
val drop : ?n:int -> ('key, 'data) t -> [ `back | `front ] -> unit
val drop_front : ?n:int -> ('key, 'data) t -> unit
val drop_back : ?n:int -> ('key, 'data) t -> unit
* { 2 Iterating over elements }
val iteri : ('key, 'data) t -> f:(key:'key -> data:'data -> unit) -> unit
val foldi : ('key, 'data) t -> init:'b -> f:('b -> key:'key -> data:'data -> 'b) -> 'b
end
module type S0 = sig
type ('key, 'data) hash_queue
type key
include
S1
with type 'key create_key := key
with type 'key create_arg := unit
with type ('key, 'data) t := ('key, 'data) hash_queue
type 'data t = (key, 'data) hash_queue [@@deriving sexp_of]
end
module type S_backend = sig
include
S1
with type 'key create_arg := 'key Hashtbl.Hashable.t
with type 'key create_key := 'key
module type S = S0 with type ('key, 'data) hash_queue := ('key, 'data) t
module Make (Key : Key) : S with type key = Key.t
module Make_with_hashable (T : sig
module Key : Key
val hashable : Key.t Hashtbl.Hashable.t
end) : S with type key = T.Key.t
end
* A hash - queue is a combination of a queue and a hashtable that
supports constant - time lookup and removal of queue elements in addition to
the usual queue operations ( enqueue , dequeue ) . The queue elements are
key - value pairs . The hashtable has one entry for each element of the queue .
Calls to functions that would modify a hash - queue ( e.g. [ enqueue ] , [ dequeue ] ,
[ remove ] , [ replace ] ) detect if a client is in the middle of iterating over the
queue ( e.g. , [ iter ] , [ fold ] , [ for_all ] , [ exists ] ) and if so , raise an exception .
supports constant-time lookup and removal of queue elements in addition to
the usual queue operations (enqueue, dequeue). The queue elements are
key-value pairs. The hashtable has one entry for each element of the queue.
Calls to functions that would modify a hash-queue (e.g. [enqueue], [dequeue],
[remove], [replace]) detect if a client is in the middle of iterating over the
queue (e.g., [iter], [fold], [for_all], [exists]) and if so, raise an exception.
*)
module type Hash_queue = sig
module type Key = Key
module type S_backend = S_backend
module Make_backend (Table : Hashtbl_intf.Hashtbl) : S_backend
* equivalent to [ Make_backend ( ) ]
include S_backend
end
|
dc5b6ca479743284f50911b536e4158423f184e12d45246a33cf8bc164c22997 | mbj/stratosphere | RuleActionProperty.hs | module Stratosphere.WAFv2.WebACL.RuleActionProperty (
module Exports, RuleActionProperty(..), mkRuleActionProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.WAFv2.WebACL.AllowActionProperty as Exports
import {-# SOURCE #-} Stratosphere.WAFv2.WebACL.BlockActionProperty as Exports
import {-# SOURCE #-} Stratosphere.WAFv2.WebACL.CaptchaActionProperty as Exports
import {-# SOURCE #-} Stratosphere.WAFv2.WebACL.ChallengeActionProperty as Exports
import {-# SOURCE #-} Stratosphere.WAFv2.WebACL.CountActionProperty as Exports
import Stratosphere.ResourceProperties
data RuleActionProperty
= RuleActionProperty {allow :: (Prelude.Maybe AllowActionProperty),
block :: (Prelude.Maybe BlockActionProperty),
captcha :: (Prelude.Maybe CaptchaActionProperty),
challenge :: (Prelude.Maybe ChallengeActionProperty),
count :: (Prelude.Maybe CountActionProperty)}
mkRuleActionProperty :: RuleActionProperty
mkRuleActionProperty
= RuleActionProperty
{allow = Prelude.Nothing, block = Prelude.Nothing,
captcha = Prelude.Nothing, challenge = Prelude.Nothing,
count = Prelude.Nothing}
instance ToResourceProperties RuleActionProperty where
toResourceProperties RuleActionProperty {..}
= ResourceProperties
{awsType = "AWS::WAFv2::WebACL.RuleAction",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Allow" Prelude.<$> allow,
(JSON..=) "Block" Prelude.<$> block,
(JSON..=) "Captcha" Prelude.<$> captcha,
(JSON..=) "Challenge" Prelude.<$> challenge,
(JSON..=) "Count" Prelude.<$> count])}
instance JSON.ToJSON RuleActionProperty where
toJSON RuleActionProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Allow" Prelude.<$> allow,
(JSON..=) "Block" Prelude.<$> block,
(JSON..=) "Captcha" Prelude.<$> captcha,
(JSON..=) "Challenge" Prelude.<$> challenge,
(JSON..=) "Count" Prelude.<$> count]))
instance Property "Allow" RuleActionProperty where
type PropertyType "Allow" RuleActionProperty = AllowActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {allow = Prelude.pure newValue, ..}
instance Property "Block" RuleActionProperty where
type PropertyType "Block" RuleActionProperty = BlockActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {block = Prelude.pure newValue, ..}
instance Property "Captcha" RuleActionProperty where
type PropertyType "Captcha" RuleActionProperty = CaptchaActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {captcha = Prelude.pure newValue, ..}
instance Property "Challenge" RuleActionProperty where
type PropertyType "Challenge" RuleActionProperty = ChallengeActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {challenge = Prelude.pure newValue, ..}
instance Property "Count" RuleActionProperty where
type PropertyType "Count" RuleActionProperty = CountActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {count = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wafv2/gen/Stratosphere/WAFv2/WebACL/RuleActionProperty.hs | haskell | # SOURCE #
# SOURCE #
# SOURCE #
# SOURCE #
# SOURCE # | module Stratosphere.WAFv2.WebACL.RuleActionProperty (
module Exports, RuleActionProperty(..), mkRuleActionProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
data RuleActionProperty
= RuleActionProperty {allow :: (Prelude.Maybe AllowActionProperty),
block :: (Prelude.Maybe BlockActionProperty),
captcha :: (Prelude.Maybe CaptchaActionProperty),
challenge :: (Prelude.Maybe ChallengeActionProperty),
count :: (Prelude.Maybe CountActionProperty)}
mkRuleActionProperty :: RuleActionProperty
mkRuleActionProperty
= RuleActionProperty
{allow = Prelude.Nothing, block = Prelude.Nothing,
captcha = Prelude.Nothing, challenge = Prelude.Nothing,
count = Prelude.Nothing}
instance ToResourceProperties RuleActionProperty where
toResourceProperties RuleActionProperty {..}
= ResourceProperties
{awsType = "AWS::WAFv2::WebACL.RuleAction",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Allow" Prelude.<$> allow,
(JSON..=) "Block" Prelude.<$> block,
(JSON..=) "Captcha" Prelude.<$> captcha,
(JSON..=) "Challenge" Prelude.<$> challenge,
(JSON..=) "Count" Prelude.<$> count])}
instance JSON.ToJSON RuleActionProperty where
toJSON RuleActionProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "Allow" Prelude.<$> allow,
(JSON..=) "Block" Prelude.<$> block,
(JSON..=) "Captcha" Prelude.<$> captcha,
(JSON..=) "Challenge" Prelude.<$> challenge,
(JSON..=) "Count" Prelude.<$> count]))
instance Property "Allow" RuleActionProperty where
type PropertyType "Allow" RuleActionProperty = AllowActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {allow = Prelude.pure newValue, ..}
instance Property "Block" RuleActionProperty where
type PropertyType "Block" RuleActionProperty = BlockActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {block = Prelude.pure newValue, ..}
instance Property "Captcha" RuleActionProperty where
type PropertyType "Captcha" RuleActionProperty = CaptchaActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {captcha = Prelude.pure newValue, ..}
instance Property "Challenge" RuleActionProperty where
type PropertyType "Challenge" RuleActionProperty = ChallengeActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {challenge = Prelude.pure newValue, ..}
instance Property "Count" RuleActionProperty where
type PropertyType "Count" RuleActionProperty = CountActionProperty
set newValue RuleActionProperty {..}
= RuleActionProperty {count = Prelude.pure newValue, ..} |
ec38242c145ff808d14ee2bf54bb687ae2b58e9b690af64c78eb7b3cfe447350 | WorksHub/client | video_player.cljc | (ns wh.components.video-player
(:require
[clojure.string :as str]
[wh.interop :as interop]))
(defn open-on-click
[youtube-id]
(interop/on-click-fn
(interop/open-video-player youtube-id)))
| null | https://raw.githubusercontent.com/WorksHub/client/a51729585c2b9d7692e57b3edcd5217c228cf47c/common/src/wh/components/video_player.cljc | clojure | (ns wh.components.video-player
(:require
[clojure.string :as str]
[wh.interop :as interop]))
(defn open-on-click
[youtube-id]
(interop/on-click-fn
(interop/open-video-player youtube-id)))
| |
362e816bdecc34aa03f54de27eee81d0e2ca303d12a8153c2d1a22a1b1fd8b68 | janestreet/sexp | located.ml | open Core
module X = Lazy_list
let of_list (xs : 'a list) : 'a X.t = X.of_list xs
type 'a t =
| Stdin of string option * 'a
| Files of (string * 'a) X.t
let map t ~f =
match t with
| Stdin (label, x) -> Stdin (label, f x)
| Files fs -> Files (X.map fs ~f:(fun (label, x) -> label, f x))
;;
let iter t ~f =
match t with
| Stdin (label, x) ->
let label = Option.value ~default:"stdin" label in
f label x
| Files fs -> X.iter fs ~f:(fun (label, x) -> f label x)
;;
let stdin label_opt = Stdin (label_opt, ())
let files fs = Files (X.map (of_list fs) ~f:(fun f -> f, ()))
let channels = function
| Stdin (label, ()) -> Stdin (label, In_channel.stdin)
| Files fs ->
let f (fname, ()) = fname, In_channel.create fname in
Files (X.map fs ~f)
;;
| null | https://raw.githubusercontent.com/janestreet/sexp/56e485b3cbf8a43e1a8d7647b0df31b27053febf/bin/located.ml | ocaml | open Core
module X = Lazy_list
let of_list (xs : 'a list) : 'a X.t = X.of_list xs
type 'a t =
| Stdin of string option * 'a
| Files of (string * 'a) X.t
let map t ~f =
match t with
| Stdin (label, x) -> Stdin (label, f x)
| Files fs -> Files (X.map fs ~f:(fun (label, x) -> label, f x))
;;
let iter t ~f =
match t with
| Stdin (label, x) ->
let label = Option.value ~default:"stdin" label in
f label x
| Files fs -> X.iter fs ~f:(fun (label, x) -> f label x)
;;
let stdin label_opt = Stdin (label_opt, ())
let files fs = Files (X.map (of_list fs) ~f:(fun f -> f, ()))
let channels = function
| Stdin (label, ()) -> Stdin (label, In_channel.stdin)
| Files fs ->
let f (fname, ()) = fname, In_channel.create fname in
Files (X.map fs ~f)
;;
| |
f25875567d9a41ad5359ba586d8b78736345f8f18faf0f7fbfcee34106199437 | janestreet/ppx_css | parser.mli | val parse_stylesheet :
?container_lnum:int -> ?pos:Lexing.position -> string -> Types.Stylesheet.t
val parse_declaration_list :
?container_lnum:int ->
?pos:Lexing.position ->
string ->
Types.Declaration_list.t
| null | https://raw.githubusercontent.com/janestreet/ppx_css/5848e1dc76b0ecf504e3b01d07d05741759cee72/vendor/css_parser/src/parser.mli | ocaml | val parse_stylesheet :
?container_lnum:int -> ?pos:Lexing.position -> string -> Types.Stylesheet.t
val parse_declaration_list :
?container_lnum:int ->
?pos:Lexing.position ->
string ->
Types.Declaration_list.t
| |
6c97e91df9489ef5eb317814f695516d2bc20a7c44422aaf26d43e8310704a61 | metaocaml/ber-metaocaml | ocamlprof.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
and , INRIA Rocquencourt
Ported to Caml Special Light by
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Printf
open Location
open Parsetree
(* User programs must not use identifiers that start with these prefixes. *)
let idprefix = "__ocaml_prof_";;
let modprefix = "OCAML__prof_";;
(* Errors specific to the profiler *)
exception Profiler of string
(* Modes *)
let instr_fun = ref false
and instr_match = ref false
and instr_if = ref false
and instr_loops = ref false
and instr_try = ref false
let cur_point = ref 0
and inchan = ref stdin
and outchan = ref stdout
(* To copy source fragments *)
let copy_buffer = Bytes.create 256
let copy_chars_unix nchars =
let n = ref nchars in
while !n > 0 do
let m = input !inchan copy_buffer 0 (min !n 256) in
if m = 0 then raise End_of_file;
output !outchan copy_buffer 0 m;
n := !n - m
done
let copy_chars_win32 nchars =
for _i = 1 to nchars do
let c = input_char !inchan in
if c <> '\r' then output_char !outchan c
done
let copy_chars =
match Sys.os_type with
"Win32" | "Cygwin" -> copy_chars_win32
| _ -> copy_chars_unix
let copy next =
assert (next >= !cur_point);
seek_in !inchan !cur_point;
copy_chars (next - !cur_point);
cur_point := next;
;;
let prof_counter = ref 0;;
let instr_mode = ref false
type insert = Open | Close;;
let to_insert = ref ([] : (insert * int) list);;
let insert_action st en =
to_insert := (Open, st) :: (Close, en) :: !to_insert
;;
(* Producing instrumented code *)
let add_incr_counter modul (kind,pos) =
copy pos;
match kind with
| Open ->
fprintf !outchan "(%sProfiling.incr %s%s_cnt %d; "
modprefix idprefix modul !prof_counter;
incr prof_counter;
| Close -> fprintf !outchan ")";
;;
let counters = ref (Array.make 0 0)
(* User defined marker *)
let special_id = ref ""
(* Producing results of profile run *)
let add_val_counter (kind,pos) =
if kind = Open then begin
copy pos;
fprintf !outchan "(* %s%d *) " !special_id !counters.(!prof_counter);
incr prof_counter;
end
;;
(* ************* rewrite ************* *)
let insert_profile rw_exp ex =
let st = ex.pexp_loc.loc_start.Lexing.pos_cnum
and en = ex.pexp_loc.loc_end.Lexing.pos_cnum
and gh = ex.pexp_loc.loc_ghost
in
if gh || st = en then
rw_exp true ex
else begin
insert_action st en;
rw_exp false ex;
end
;;
let pos_len = ref 0
let init_rewrite modes mod_name =
cur_point := 0;
if !instr_mode then begin
fprintf !outchan "module %sProfiling = Profiling;; " modprefix;
fprintf !outchan "let %s%s_cnt = Array.make 000000000" idprefix mod_name;
pos_len := pos_out !outchan;
fprintf !outchan
" 0;; Profiling.counters := \
(\"%s\", (\"%s\", %s%s_cnt)) :: !Profiling.counters;; "
mod_name modes idprefix mod_name;
end
let final_rewrite add_function =
to_insert := List.sort (fun x y -> compare (snd x) (snd y)) !to_insert;
prof_counter := 0;
List.iter add_function !to_insert;
copy (in_channel_length !inchan);
if !instr_mode then begin
let len = Int.to_string !prof_counter in
if String.length len > 9 then raise (Profiler "too many counters");
seek_out !outchan (!pos_len - String.length len);
output_string !outchan len
end;
(* Cannot close because outchan is stdout and Format doesn't like
a closed stdout.
close_out !outchan;
*)
;;
let rec rewrite_patexp_list iflag l =
rewrite_exp_list iflag (List.map (fun x -> x.pvb_expr) l)
and rewrite_cases iflag l =
List.iter
(fun pc ->
begin match pc.pc_guard with
| None -> ()
| Some g -> rewrite_exp iflag g
end;
rewrite_exp iflag pc.pc_rhs
)
l
and rewrite_labelexp_list iflag l =
rewrite_exp_list iflag (List.map snd l)
and rewrite_exp_list iflag l =
List.iter (rewrite_exp iflag) l
and rewrite_exp iflag sexp =
if iflag then insert_profile rw_exp sexp
else rw_exp false sexp
and rw_exp iflag sexp =
match sexp.pexp_desc with
Pexp_ident _lid -> ()
| Pexp_constant _cst -> ()
| Pexp_let(_, spat_sexp_list, sbody) ->
rewrite_patexp_list iflag spat_sexp_list;
rewrite_exp iflag sbody
| Pexp_function caselist ->
if !instr_fun then
rewrite_function iflag caselist
else
rewrite_cases iflag caselist
| Pexp_fun (_, _, p, e) ->
let l = [{pc_lhs=p; pc_guard=None; pc_rhs=e}] in
if !instr_fun then
rewrite_function iflag l
else
rewrite_cases iflag l
| Pexp_match(sarg, caselist) ->
rewrite_exp iflag sarg;
if !instr_match && not sexp.pexp_loc.loc_ghost then
rewrite_funmatching caselist
else
rewrite_cases iflag caselist
| Pexp_try(sbody, caselist) ->
rewrite_exp iflag sbody;
if !instr_try && not sexp.pexp_loc.loc_ghost then
rewrite_trymatching caselist
else
rewrite_cases iflag caselist
| Pexp_apply(sfunct, sargs) ->
rewrite_exp iflag sfunct;
rewrite_exp_list iflag (List.map snd sargs)
| Pexp_tuple sexpl ->
rewrite_exp_list iflag sexpl
| Pexp_construct(_, None) -> ()
| Pexp_construct(_, Some sarg) ->
rewrite_exp iflag sarg
| Pexp_variant(_, None) -> ()
| Pexp_variant(_, Some sarg) ->
rewrite_exp iflag sarg
| Pexp_record(lid_sexp_list, None) ->
rewrite_labelexp_list iflag lid_sexp_list
| Pexp_record(lid_sexp_list, Some sexp) ->
rewrite_exp iflag sexp;
rewrite_labelexp_list iflag lid_sexp_list
| Pexp_field(sarg, _) ->
rewrite_exp iflag sarg
| Pexp_setfield(srecord, _, snewval) ->
rewrite_exp iflag srecord;
rewrite_exp iflag snewval
| Pexp_array(sargl) ->
rewrite_exp_list iflag sargl
| Pexp_ifthenelse(scond, sifso, None) ->
rewrite_exp iflag scond;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso
| Pexp_ifthenelse(scond, sifso, Some sifnot) ->
rewrite_exp iflag scond;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifnot
| Pexp_sequence(sexp1, sexp2) ->
rewrite_exp iflag sexp1;
rewrite_exp iflag sexp2
| Pexp_while(scond, sbody) ->
rewrite_exp iflag scond;
if !instr_loops && not sexp.pexp_loc.loc_ghost
then insert_profile rw_exp sbody
else rewrite_exp iflag sbody
| Pexp_for(_, slow, shigh, _, sbody) ->
rewrite_exp iflag slow;
rewrite_exp iflag shigh;
if !instr_loops && not sexp.pexp_loc.loc_ghost
then insert_profile rw_exp sbody
else rewrite_exp iflag sbody
| Pexp_constraint(sarg, _) | Pexp_coerce(sarg, _, _) ->
rewrite_exp iflag sarg
| Pexp_send (sobj, _) ->
rewrite_exp iflag sobj
| Pexp_new _ -> ()
| Pexp_setinstvar (_, sarg) ->
rewrite_exp iflag sarg
| Pexp_override l ->
List.iter (fun (_, sexp) -> rewrite_exp iflag sexp) l
| Pexp_letmodule (_, smod, sexp) ->
rewrite_mod iflag smod;
rewrite_exp iflag sexp
| Pexp_letexception (_cd, exp) ->
rewrite_exp iflag exp
| Pexp_assert (cond) -> rewrite_exp iflag cond
| Pexp_lazy (expr) -> rewrite_exp iflag expr
| Pexp_poly (sexp, _) -> rewrite_exp iflag sexp
| Pexp_object cl ->
List.iter (rewrite_class_field iflag) cl.pcstr_fields
| Pexp_newtype (_, sexp) -> rewrite_exp iflag sexp
| Pexp_open (_, e) -> rewrite_exp iflag e
| Pexp_pack (smod) -> rewrite_mod iflag smod
| Pexp_letop {let_; ands; body; _} ->
rewrite_exp iflag let_.pbop_exp;
List.iter (fun {pbop_exp; _} -> rewrite_exp iflag pbop_exp) ands;
rewrite_exp iflag body
| Pexp_extension _ -> ()
| Pexp_unreachable -> ()
and rewrite_ifbody iflag ghost sifbody =
if !instr_if && not ghost then
insert_profile rw_exp sifbody
else
rewrite_exp iflag sifbody
(* called only when !instr_fun *)
and rewrite_annotate_exp_list l =
List.iter
(function
| {pc_guard=Some scond; pc_rhs=sbody} ->
insert_profile rw_exp scond;
insert_profile rw_exp sbody;
| {pc_rhs={pexp_desc = Pexp_constraint(sbody, _)}} (* let f x : t = e *)
-> insert_profile rw_exp sbody
| {pc_rhs=sexp} -> insert_profile rw_exp sexp)
l
and rewrite_function iflag = function
| [{pc_lhs=_; pc_guard=None;
pc_rhs={pexp_desc = (Pexp_function _|Pexp_fun _)} as sexp}] ->
rewrite_exp iflag sexp
| l -> rewrite_funmatching l
and rewrite_funmatching l =
rewrite_annotate_exp_list l
and rewrite_trymatching l =
rewrite_annotate_exp_list l
(* Rewrite a class definition *)
and rewrite_class_field iflag cf =
match cf.pcf_desc with
Pcf_inherit (_, cexpr, _) -> rewrite_class_expr iflag cexpr
| Pcf_val (_, _, Cfk_concrete (_, sexp)) -> rewrite_exp iflag sexp
| Pcf_method (_, _,
Cfk_concrete (_, ({pexp_desc = (Pexp_function _|Pexp_fun _)}
as sexp))) ->
rewrite_exp iflag sexp
| Pcf_method (_, _, Cfk_concrete(_, sexp)) ->
let loc = cf.pcf_loc in
if !instr_fun && not loc.loc_ghost then insert_profile rw_exp sexp
else rewrite_exp iflag sexp
| Pcf_initializer sexp ->
rewrite_exp iflag sexp
| Pcf_method (_, _, Cfk_virtual _)
| Pcf_val (_, _, Cfk_virtual _)
| Pcf_constraint _ -> ()
| Pcf_attribute _ -> ()
| Pcf_extension _ -> ()
and rewrite_class_expr iflag cexpr =
match cexpr.pcl_desc with
Pcl_constr _ -> ()
| Pcl_structure st ->
List.iter (rewrite_class_field iflag) st.pcstr_fields
| Pcl_fun (_, _, _, cexpr) ->
rewrite_class_expr iflag cexpr
| Pcl_apply (cexpr, exprs) ->
rewrite_class_expr iflag cexpr;
List.iter (rewrite_exp iflag) (List.map snd exprs)
| Pcl_let (_, spat_sexp_list, cexpr) ->
rewrite_patexp_list iflag spat_sexp_list;
rewrite_class_expr iflag cexpr
| Pcl_open (_, cexpr)
| Pcl_constraint (cexpr, _) ->
rewrite_class_expr iflag cexpr
| Pcl_extension _ -> ()
and rewrite_class_declaration iflag cl =
rewrite_class_expr iflag cl.pci_expr
(* Rewrite a module expression or structure expression *)
and rewrite_mod iflag smod =
match smod.pmod_desc with
Pmod_ident _ -> ()
| Pmod_structure sstr -> List.iter (rewrite_str_item iflag) sstr
| Pmod_functor(_param, sbody) -> rewrite_mod iflag sbody
| Pmod_apply(smod1, smod2) -> rewrite_mod iflag smod1; rewrite_mod iflag smod2
| Pmod_constraint(smod, _smty) -> rewrite_mod iflag smod
| Pmod_unpack(sexp) -> rewrite_exp iflag sexp
| Pmod_extension _ -> ()
and rewrite_str_item iflag item =
match item.pstr_desc with
Pstr_eval (exp, _attrs) -> rewrite_exp iflag exp
| Pstr_value(_, exps)
-> List.iter (fun x -> rewrite_exp iflag x.pvb_expr) exps
| Pstr_module x -> rewrite_mod iflag x.pmb_expr
(* todo: Pstr_recmodule?? *)
| Pstr_class classes -> List.iter (rewrite_class_declaration iflag) classes
| _ -> ()
Rewrite a .ml file
let rewrite_file srcfile add_function =
inchan := open_in_bin srcfile;
let lb = Lexing.from_channel !inchan in
Location.input_name := srcfile;
Location.init lb srcfile;
List.iter (rewrite_str_item false) (Parse.implementation lb);
final_rewrite add_function;
close_in !inchan
(* Copy a non-.ml file without change *)
let null_rewrite srcfile =
inchan := open_in_bin srcfile;
copy (in_channel_length !inchan);
close_in !inchan
;;
(* Setting flags from saved config *)
let set_flags s =
for i = 0 to String.length s - 1 do
match String.get s i with
'f' -> instr_fun := true
| 'm' -> instr_match := true
| 'i' -> instr_if := true
| 'l' -> instr_loops := true
| 't' -> instr_try := true
| 'a' -> instr_fun := true; instr_match := true;
instr_if := true; instr_loops := true;
instr_try := true
| _ -> ()
done
(* Command-line options *)
let modes = ref "fm"
let dumpfile = ref "ocamlprof.dump"
(* Process a file *)
let process_intf_file filename = null_rewrite filename;;
let process_impl_file filename =
let modname = Filename.basename(Filename.chop_extension filename) in
FIXME should let = String.capitalize modname
if !instr_mode then begin
(* Instrumentation mode *)
set_flags !modes;
init_rewrite !modes modname;
rewrite_file filename (add_incr_counter modname);
end else begin
(* Results mode *)
let ic = open_in_bin !dumpfile in
let allcounters =
(input_value ic : (string * (string * int array)) list) in
close_in ic;
let (modes, cv) =
try
List.assoc modname allcounters
with Not_found ->
raise(Profiler("Module " ^ modname ^ " not used in this profile."))
in
counters := cv;
set_flags modes;
init_rewrite modes modname;
rewrite_file filename add_val_counter;
end
;;
let process_anon_file filename =
if Filename.check_suffix filename ".ml" then
process_impl_file filename
else
process_intf_file filename
;;
(* Main function *)
open Format
let usage = "Usage: ocamlprof <options> <files>\noptions are:"
let print_version () =
printf "ocamlprof, version %s@." Sys.ocaml_version;
exit 0;
;;
let print_version_num () =
printf "%s@." Sys.ocaml_version;
exit 0;
;;
let main () =
try
Warnings.parse_options false "a";
Arg.parse_expand [
"-f", Arg.String (fun s -> dumpfile := s),
"<file> Use <file> as dump file (default ocamlprof.dump)";
"-F", Arg.String (fun s -> special_id := s),
"<s> Insert string <s> with the counts";
"-impl", Arg.String process_impl_file,
"<file> Process <file> as a .ml file";
"-instrument", Arg.Set instr_mode, " (undocumented)";
"-intf", Arg.String process_intf_file,
"<file> Process <file> as a .mli file";
"-m", Arg.String (fun s -> modes := s), "<flags> (undocumented)";
"-version", Arg.Unit print_version,
" Print version and exit";
"-vnum", Arg.Unit print_version_num,
" Print version number and exit";
"-args", Arg.Expand Arg.read_arg,
"<file> Read additional newline separated command line arguments \n\
\ from <file>";
"-args0", Arg.Expand Arg.read_arg0,
"<file> Read additional NUL separated command line arguments from \n\
\ <file>"
] process_anon_file usage;
exit 0
with
| Profiler msg ->
fprintf Format.err_formatter "@[%s@]@." msg;
exit 2
| exn ->
Location.report_exception Format.err_formatter exn
let _ = main ()
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/tools/ocamlprof.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
User programs must not use identifiers that start with these prefixes.
Errors specific to the profiler
Modes
To copy source fragments
Producing instrumented code
User defined marker
Producing results of profile run
************* rewrite *************
Cannot close because outchan is stdout and Format doesn't like
a closed stdout.
close_out !outchan;
called only when !instr_fun
let f x : t = e
Rewrite a class definition
Rewrite a module expression or structure expression
todo: Pstr_recmodule??
Copy a non-.ml file without change
Setting flags from saved config
Command-line options
Process a file
Instrumentation mode
Results mode
Main function | and , INRIA Rocquencourt
Ported to Caml Special Light by
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Printf
open Location
open Parsetree
let idprefix = "__ocaml_prof_";;
let modprefix = "OCAML__prof_";;
exception Profiler of string
let instr_fun = ref false
and instr_match = ref false
and instr_if = ref false
and instr_loops = ref false
and instr_try = ref false
let cur_point = ref 0
and inchan = ref stdin
and outchan = ref stdout
let copy_buffer = Bytes.create 256
let copy_chars_unix nchars =
let n = ref nchars in
while !n > 0 do
let m = input !inchan copy_buffer 0 (min !n 256) in
if m = 0 then raise End_of_file;
output !outchan copy_buffer 0 m;
n := !n - m
done
let copy_chars_win32 nchars =
for _i = 1 to nchars do
let c = input_char !inchan in
if c <> '\r' then output_char !outchan c
done
let copy_chars =
match Sys.os_type with
"Win32" | "Cygwin" -> copy_chars_win32
| _ -> copy_chars_unix
let copy next =
assert (next >= !cur_point);
seek_in !inchan !cur_point;
copy_chars (next - !cur_point);
cur_point := next;
;;
let prof_counter = ref 0;;
let instr_mode = ref false
type insert = Open | Close;;
let to_insert = ref ([] : (insert * int) list);;
let insert_action st en =
to_insert := (Open, st) :: (Close, en) :: !to_insert
;;
let add_incr_counter modul (kind,pos) =
copy pos;
match kind with
| Open ->
fprintf !outchan "(%sProfiling.incr %s%s_cnt %d; "
modprefix idprefix modul !prof_counter;
incr prof_counter;
| Close -> fprintf !outchan ")";
;;
let counters = ref (Array.make 0 0)
let special_id = ref ""
let add_val_counter (kind,pos) =
if kind = Open then begin
copy pos;
fprintf !outchan "(* %s%d *) " !special_id !counters.(!prof_counter);
incr prof_counter;
end
;;
let insert_profile rw_exp ex =
let st = ex.pexp_loc.loc_start.Lexing.pos_cnum
and en = ex.pexp_loc.loc_end.Lexing.pos_cnum
and gh = ex.pexp_loc.loc_ghost
in
if gh || st = en then
rw_exp true ex
else begin
insert_action st en;
rw_exp false ex;
end
;;
let pos_len = ref 0
let init_rewrite modes mod_name =
cur_point := 0;
if !instr_mode then begin
fprintf !outchan "module %sProfiling = Profiling;; " modprefix;
fprintf !outchan "let %s%s_cnt = Array.make 000000000" idprefix mod_name;
pos_len := pos_out !outchan;
fprintf !outchan
" 0;; Profiling.counters := \
(\"%s\", (\"%s\", %s%s_cnt)) :: !Profiling.counters;; "
mod_name modes idprefix mod_name;
end
let final_rewrite add_function =
to_insert := List.sort (fun x y -> compare (snd x) (snd y)) !to_insert;
prof_counter := 0;
List.iter add_function !to_insert;
copy (in_channel_length !inchan);
if !instr_mode then begin
let len = Int.to_string !prof_counter in
if String.length len > 9 then raise (Profiler "too many counters");
seek_out !outchan (!pos_len - String.length len);
output_string !outchan len
end;
;;
let rec rewrite_patexp_list iflag l =
rewrite_exp_list iflag (List.map (fun x -> x.pvb_expr) l)
and rewrite_cases iflag l =
List.iter
(fun pc ->
begin match pc.pc_guard with
| None -> ()
| Some g -> rewrite_exp iflag g
end;
rewrite_exp iflag pc.pc_rhs
)
l
and rewrite_labelexp_list iflag l =
rewrite_exp_list iflag (List.map snd l)
and rewrite_exp_list iflag l =
List.iter (rewrite_exp iflag) l
and rewrite_exp iflag sexp =
if iflag then insert_profile rw_exp sexp
else rw_exp false sexp
and rw_exp iflag sexp =
match sexp.pexp_desc with
Pexp_ident _lid -> ()
| Pexp_constant _cst -> ()
| Pexp_let(_, spat_sexp_list, sbody) ->
rewrite_patexp_list iflag spat_sexp_list;
rewrite_exp iflag sbody
| Pexp_function caselist ->
if !instr_fun then
rewrite_function iflag caselist
else
rewrite_cases iflag caselist
| Pexp_fun (_, _, p, e) ->
let l = [{pc_lhs=p; pc_guard=None; pc_rhs=e}] in
if !instr_fun then
rewrite_function iflag l
else
rewrite_cases iflag l
| Pexp_match(sarg, caselist) ->
rewrite_exp iflag sarg;
if !instr_match && not sexp.pexp_loc.loc_ghost then
rewrite_funmatching caselist
else
rewrite_cases iflag caselist
| Pexp_try(sbody, caselist) ->
rewrite_exp iflag sbody;
if !instr_try && not sexp.pexp_loc.loc_ghost then
rewrite_trymatching caselist
else
rewrite_cases iflag caselist
| Pexp_apply(sfunct, sargs) ->
rewrite_exp iflag sfunct;
rewrite_exp_list iflag (List.map snd sargs)
| Pexp_tuple sexpl ->
rewrite_exp_list iflag sexpl
| Pexp_construct(_, None) -> ()
| Pexp_construct(_, Some sarg) ->
rewrite_exp iflag sarg
| Pexp_variant(_, None) -> ()
| Pexp_variant(_, Some sarg) ->
rewrite_exp iflag sarg
| Pexp_record(lid_sexp_list, None) ->
rewrite_labelexp_list iflag lid_sexp_list
| Pexp_record(lid_sexp_list, Some sexp) ->
rewrite_exp iflag sexp;
rewrite_labelexp_list iflag lid_sexp_list
| Pexp_field(sarg, _) ->
rewrite_exp iflag sarg
| Pexp_setfield(srecord, _, snewval) ->
rewrite_exp iflag srecord;
rewrite_exp iflag snewval
| Pexp_array(sargl) ->
rewrite_exp_list iflag sargl
| Pexp_ifthenelse(scond, sifso, None) ->
rewrite_exp iflag scond;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso
| Pexp_ifthenelse(scond, sifso, Some sifnot) ->
rewrite_exp iflag scond;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifso;
rewrite_ifbody iflag sexp.pexp_loc.loc_ghost sifnot
| Pexp_sequence(sexp1, sexp2) ->
rewrite_exp iflag sexp1;
rewrite_exp iflag sexp2
| Pexp_while(scond, sbody) ->
rewrite_exp iflag scond;
if !instr_loops && not sexp.pexp_loc.loc_ghost
then insert_profile rw_exp sbody
else rewrite_exp iflag sbody
| Pexp_for(_, slow, shigh, _, sbody) ->
rewrite_exp iflag slow;
rewrite_exp iflag shigh;
if !instr_loops && not sexp.pexp_loc.loc_ghost
then insert_profile rw_exp sbody
else rewrite_exp iflag sbody
| Pexp_constraint(sarg, _) | Pexp_coerce(sarg, _, _) ->
rewrite_exp iflag sarg
| Pexp_send (sobj, _) ->
rewrite_exp iflag sobj
| Pexp_new _ -> ()
| Pexp_setinstvar (_, sarg) ->
rewrite_exp iflag sarg
| Pexp_override l ->
List.iter (fun (_, sexp) -> rewrite_exp iflag sexp) l
| Pexp_letmodule (_, smod, sexp) ->
rewrite_mod iflag smod;
rewrite_exp iflag sexp
| Pexp_letexception (_cd, exp) ->
rewrite_exp iflag exp
| Pexp_assert (cond) -> rewrite_exp iflag cond
| Pexp_lazy (expr) -> rewrite_exp iflag expr
| Pexp_poly (sexp, _) -> rewrite_exp iflag sexp
| Pexp_object cl ->
List.iter (rewrite_class_field iflag) cl.pcstr_fields
| Pexp_newtype (_, sexp) -> rewrite_exp iflag sexp
| Pexp_open (_, e) -> rewrite_exp iflag e
| Pexp_pack (smod) -> rewrite_mod iflag smod
| Pexp_letop {let_; ands; body; _} ->
rewrite_exp iflag let_.pbop_exp;
List.iter (fun {pbop_exp; _} -> rewrite_exp iflag pbop_exp) ands;
rewrite_exp iflag body
| Pexp_extension _ -> ()
| Pexp_unreachable -> ()
and rewrite_ifbody iflag ghost sifbody =
if !instr_if && not ghost then
insert_profile rw_exp sifbody
else
rewrite_exp iflag sifbody
and rewrite_annotate_exp_list l =
List.iter
(function
| {pc_guard=Some scond; pc_rhs=sbody} ->
insert_profile rw_exp scond;
insert_profile rw_exp sbody;
-> insert_profile rw_exp sbody
| {pc_rhs=sexp} -> insert_profile rw_exp sexp)
l
and rewrite_function iflag = function
| [{pc_lhs=_; pc_guard=None;
pc_rhs={pexp_desc = (Pexp_function _|Pexp_fun _)} as sexp}] ->
rewrite_exp iflag sexp
| l -> rewrite_funmatching l
and rewrite_funmatching l =
rewrite_annotate_exp_list l
and rewrite_trymatching l =
rewrite_annotate_exp_list l
and rewrite_class_field iflag cf =
match cf.pcf_desc with
Pcf_inherit (_, cexpr, _) -> rewrite_class_expr iflag cexpr
| Pcf_val (_, _, Cfk_concrete (_, sexp)) -> rewrite_exp iflag sexp
| Pcf_method (_, _,
Cfk_concrete (_, ({pexp_desc = (Pexp_function _|Pexp_fun _)}
as sexp))) ->
rewrite_exp iflag sexp
| Pcf_method (_, _, Cfk_concrete(_, sexp)) ->
let loc = cf.pcf_loc in
if !instr_fun && not loc.loc_ghost then insert_profile rw_exp sexp
else rewrite_exp iflag sexp
| Pcf_initializer sexp ->
rewrite_exp iflag sexp
| Pcf_method (_, _, Cfk_virtual _)
| Pcf_val (_, _, Cfk_virtual _)
| Pcf_constraint _ -> ()
| Pcf_attribute _ -> ()
| Pcf_extension _ -> ()
and rewrite_class_expr iflag cexpr =
match cexpr.pcl_desc with
Pcl_constr _ -> ()
| Pcl_structure st ->
List.iter (rewrite_class_field iflag) st.pcstr_fields
| Pcl_fun (_, _, _, cexpr) ->
rewrite_class_expr iflag cexpr
| Pcl_apply (cexpr, exprs) ->
rewrite_class_expr iflag cexpr;
List.iter (rewrite_exp iflag) (List.map snd exprs)
| Pcl_let (_, spat_sexp_list, cexpr) ->
rewrite_patexp_list iflag spat_sexp_list;
rewrite_class_expr iflag cexpr
| Pcl_open (_, cexpr)
| Pcl_constraint (cexpr, _) ->
rewrite_class_expr iflag cexpr
| Pcl_extension _ -> ()
and rewrite_class_declaration iflag cl =
rewrite_class_expr iflag cl.pci_expr
and rewrite_mod iflag smod =
match smod.pmod_desc with
Pmod_ident _ -> ()
| Pmod_structure sstr -> List.iter (rewrite_str_item iflag) sstr
| Pmod_functor(_param, sbody) -> rewrite_mod iflag sbody
| Pmod_apply(smod1, smod2) -> rewrite_mod iflag smod1; rewrite_mod iflag smod2
| Pmod_constraint(smod, _smty) -> rewrite_mod iflag smod
| Pmod_unpack(sexp) -> rewrite_exp iflag sexp
| Pmod_extension _ -> ()
and rewrite_str_item iflag item =
match item.pstr_desc with
Pstr_eval (exp, _attrs) -> rewrite_exp iflag exp
| Pstr_value(_, exps)
-> List.iter (fun x -> rewrite_exp iflag x.pvb_expr) exps
| Pstr_module x -> rewrite_mod iflag x.pmb_expr
| Pstr_class classes -> List.iter (rewrite_class_declaration iflag) classes
| _ -> ()
Rewrite a .ml file
let rewrite_file srcfile add_function =
inchan := open_in_bin srcfile;
let lb = Lexing.from_channel !inchan in
Location.input_name := srcfile;
Location.init lb srcfile;
List.iter (rewrite_str_item false) (Parse.implementation lb);
final_rewrite add_function;
close_in !inchan
let null_rewrite srcfile =
inchan := open_in_bin srcfile;
copy (in_channel_length !inchan);
close_in !inchan
;;
let set_flags s =
for i = 0 to String.length s - 1 do
match String.get s i with
'f' -> instr_fun := true
| 'm' -> instr_match := true
| 'i' -> instr_if := true
| 'l' -> instr_loops := true
| 't' -> instr_try := true
| 'a' -> instr_fun := true; instr_match := true;
instr_if := true; instr_loops := true;
instr_try := true
| _ -> ()
done
let modes = ref "fm"
let dumpfile = ref "ocamlprof.dump"
let process_intf_file filename = null_rewrite filename;;
let process_impl_file filename =
let modname = Filename.basename(Filename.chop_extension filename) in
FIXME should let = String.capitalize modname
if !instr_mode then begin
set_flags !modes;
init_rewrite !modes modname;
rewrite_file filename (add_incr_counter modname);
end else begin
let ic = open_in_bin !dumpfile in
let allcounters =
(input_value ic : (string * (string * int array)) list) in
close_in ic;
let (modes, cv) =
try
List.assoc modname allcounters
with Not_found ->
raise(Profiler("Module " ^ modname ^ " not used in this profile."))
in
counters := cv;
set_flags modes;
init_rewrite modes modname;
rewrite_file filename add_val_counter;
end
;;
let process_anon_file filename =
if Filename.check_suffix filename ".ml" then
process_impl_file filename
else
process_intf_file filename
;;
open Format
let usage = "Usage: ocamlprof <options> <files>\noptions are:"
let print_version () =
printf "ocamlprof, version %s@." Sys.ocaml_version;
exit 0;
;;
let print_version_num () =
printf "%s@." Sys.ocaml_version;
exit 0;
;;
let main () =
try
Warnings.parse_options false "a";
Arg.parse_expand [
"-f", Arg.String (fun s -> dumpfile := s),
"<file> Use <file> as dump file (default ocamlprof.dump)";
"-F", Arg.String (fun s -> special_id := s),
"<s> Insert string <s> with the counts";
"-impl", Arg.String process_impl_file,
"<file> Process <file> as a .ml file";
"-instrument", Arg.Set instr_mode, " (undocumented)";
"-intf", Arg.String process_intf_file,
"<file> Process <file> as a .mli file";
"-m", Arg.String (fun s -> modes := s), "<flags> (undocumented)";
"-version", Arg.Unit print_version,
" Print version and exit";
"-vnum", Arg.Unit print_version_num,
" Print version number and exit";
"-args", Arg.Expand Arg.read_arg,
"<file> Read additional newline separated command line arguments \n\
\ from <file>";
"-args0", Arg.Expand Arg.read_arg0,
"<file> Read additional NUL separated command line arguments from \n\
\ <file>"
] process_anon_file usage;
exit 0
with
| Profiler msg ->
fprintf Format.err_formatter "@[%s@]@." msg;
exit 2
| exn ->
Location.report_exception Format.err_formatter exn
let _ = main ()
|
0e9ba7ab9e275b54a78736f2a11612a6664bdd6a265280470be4c8c47b6704f3 | RichiH/git-annex | Tor.hs | git - remote - daemon , tor hidden service server and transport
-
- Copyright 2016 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2016 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module RemoteDaemon.Transport.Tor (server, transport) where
import Common
import qualified Annex
import Annex.Concurrent
import Annex.ChangedRefs
import RemoteDaemon.Types
import RemoteDaemon.Common
import Utility.AuthToken
import P2P.Protocol as P2P
import P2P.IO
import P2P.Annex
import P2P.Auth
import P2P.Address
import Annex.UUID
import Types.UUID
import Messages
import Git
import Git.Command
import Control.Concurrent
import System.Log.Logger (debugM)
import Control.Concurrent.STM
import Control.Concurrent.STM.TBMQueue
import Control.Concurrent.Async
-- Run tor hidden service.
server :: Server
server ichan th@(TransportHandle (LocalRepo r) _) = go
where
go = checkstartservice >>= handlecontrol
checkstartservice = do
u <- liftAnnex th getUUID
msock <- liftAnnex th torSocketFile
case msock of
Nothing -> do
debugM "remotedaemon" "Tor hidden service not enabled"
return False
Just sock -> do
void $ async $ startservice sock u
return True
startservice sock u = do
q <- newTBMQueueIO maxConnections
replicateM_ maxConnections $
forkIO $ forever $ serveClient th u r q
debugM "remotedaemon" "Tor hidden service running"
serveUnixSocket sock $ \conn -> do
ok <- atomically $ ifM (isFullTBMQueue q)
( return False
, do
writeTBMQueue q conn
return True
)
unless ok $ do
hClose conn
warningIO "dropped Tor connection, too busy"
handlecontrol servicerunning = do
msg <- atomically $ readTChan ichan
case msg of
-- On reload, the configuration may have changed to
-- enable the tor hidden service. If it was not
-- enabled before, start it,
RELOAD | not servicerunning -> go
-- We can ignore all other messages; no need
-- to restart the hidden service when the network
-- changes as tor takes care of all that.
_ -> handlecontrol servicerunning
-- How many clients to serve at a time, maximum. This is to avoid DOS attacks.
maxConnections :: Int
maxConnections = 100
serveClient :: TransportHandle -> UUID -> Repo -> TBMQueue Handle -> IO ()
serveClient th u r q = bracket setup cleanup start
where
setup = do
h <- atomically $ readTBMQueue q
debugM "remotedaemon" "serving a Tor connection"
return h
cleanup Nothing = return ()
cleanup (Just h) = do
debugM "remotedaemon" "done with Tor connection"
hClose h
start Nothing = return ()
start (Just h) = do
Avoid doing any work in the liftAnnex , since only one
-- can run at a time.
st <- liftAnnex th dupState
((), st') <- Annex.run st $ do
-- Load auth tokens for every connection, to notice
-- when the allowed set is changed.
allowed <- loadP2PAuthTokens
let conn = P2PConnection
{ connRepo = r
, connCheckAuth = (`isAllowedAuthToken` allowed)
, connIhdl = h
, connOhdl = h
}
v <- liftIO $ runNetProto conn $ P2P.serveAuth u
case v of
Right (Just theiruuid) -> authed conn theiruuid
Right Nothing -> liftIO $
debugM "remotedaemon" "Tor connection failed to authenticate"
Left e -> liftIO $
debugM "remotedaemon" ("Tor connection error before authentication: " ++ e)
-- Merge the duplicated state back in.
liftAnnex th $ mergeState st'
authed conn theiruuid =
bracket watchChangedRefs (liftIO . maybe noop stopWatchingChangedRefs) $ \crh -> do
v' <- runFullProto (Serving theiruuid crh) conn $
P2P.serveAuthed u
case v' of
Right () -> return ()
Left e -> liftIO $ debugM "remotedaemon" ("Tor connection error: " ++ e)
Connect to peer 's tor hidden service .
transport :: Transport
transport (RemoteRepo r gc) url@(RemoteURI uri) th ichan ochan =
case unformatP2PAddress (show uri) of
Nothing -> return ()
Just addr -> robustConnection 1 $ do
g <- liftAnnex th Annex.gitRepo
bracket (connectPeer g addr) closeConnection (go addr)
where
go addr conn = do
myuuid <- liftAnnex th getUUID
authtoken <- fromMaybe nullAuthToken
<$> liftAnnex th (loadP2PRemoteAuthToken addr)
res <- runNetProto conn $
P2P.auth myuuid authtoken
case res of
Right (Just theiruuid) -> do
expecteduuid <- liftAnnex th $ getRepoUUID r
if expecteduuid == theiruuid
then do
send (CONNECTED url)
status <- handlecontrol
`race` handlepeer conn
send (DISCONNECTED url)
return $ either id id status
else return ConnectionStopping
_ -> return ConnectionClosed
send msg = atomically $ writeTChan ochan msg
handlecontrol = do
msg <- atomically $ readTChan ichan
case msg of
STOP -> return ConnectionStopping
LOSTNET -> return ConnectionStopping
_ -> handlecontrol
handlepeer conn = do
v <- runNetProto conn P2P.notifyChange
case v of
Right (Just (ChangedRefs shas)) -> do
whenM (checkShouldFetch gc th shas) $
fetch
handlepeer conn
_ -> return ConnectionClosed
fetch = do
send (SYNCING url)
ok <- inLocalRepo th $
runBool [Param "fetch", Param $ Git.repoDescribe r]
send (DONESYNCING url ok)
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/RemoteDaemon/Transport/Tor.hs | haskell | Run tor hidden service.
On reload, the configuration may have changed to
enable the tor hidden service. If it was not
enabled before, start it,
We can ignore all other messages; no need
to restart the hidden service when the network
changes as tor takes care of all that.
How many clients to serve at a time, maximum. This is to avoid DOS attacks.
can run at a time.
Load auth tokens for every connection, to notice
when the allowed set is changed.
Merge the duplicated state back in. | git - remote - daemon , tor hidden service server and transport
-
- Copyright 2016 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2016 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module RemoteDaemon.Transport.Tor (server, transport) where
import Common
import qualified Annex
import Annex.Concurrent
import Annex.ChangedRefs
import RemoteDaemon.Types
import RemoteDaemon.Common
import Utility.AuthToken
import P2P.Protocol as P2P
import P2P.IO
import P2P.Annex
import P2P.Auth
import P2P.Address
import Annex.UUID
import Types.UUID
import Messages
import Git
import Git.Command
import Control.Concurrent
import System.Log.Logger (debugM)
import Control.Concurrent.STM
import Control.Concurrent.STM.TBMQueue
import Control.Concurrent.Async
server :: Server
server ichan th@(TransportHandle (LocalRepo r) _) = go
where
go = checkstartservice >>= handlecontrol
checkstartservice = do
u <- liftAnnex th getUUID
msock <- liftAnnex th torSocketFile
case msock of
Nothing -> do
debugM "remotedaemon" "Tor hidden service not enabled"
return False
Just sock -> do
void $ async $ startservice sock u
return True
startservice sock u = do
q <- newTBMQueueIO maxConnections
replicateM_ maxConnections $
forkIO $ forever $ serveClient th u r q
debugM "remotedaemon" "Tor hidden service running"
serveUnixSocket sock $ \conn -> do
ok <- atomically $ ifM (isFullTBMQueue q)
( return False
, do
writeTBMQueue q conn
return True
)
unless ok $ do
hClose conn
warningIO "dropped Tor connection, too busy"
handlecontrol servicerunning = do
msg <- atomically $ readTChan ichan
case msg of
RELOAD | not servicerunning -> go
_ -> handlecontrol servicerunning
maxConnections :: Int
maxConnections = 100
serveClient :: TransportHandle -> UUID -> Repo -> TBMQueue Handle -> IO ()
serveClient th u r q = bracket setup cleanup start
where
setup = do
h <- atomically $ readTBMQueue q
debugM "remotedaemon" "serving a Tor connection"
return h
cleanup Nothing = return ()
cleanup (Just h) = do
debugM "remotedaemon" "done with Tor connection"
hClose h
start Nothing = return ()
start (Just h) = do
Avoid doing any work in the liftAnnex , since only one
st <- liftAnnex th dupState
((), st') <- Annex.run st $ do
allowed <- loadP2PAuthTokens
let conn = P2PConnection
{ connRepo = r
, connCheckAuth = (`isAllowedAuthToken` allowed)
, connIhdl = h
, connOhdl = h
}
v <- liftIO $ runNetProto conn $ P2P.serveAuth u
case v of
Right (Just theiruuid) -> authed conn theiruuid
Right Nothing -> liftIO $
debugM "remotedaemon" "Tor connection failed to authenticate"
Left e -> liftIO $
debugM "remotedaemon" ("Tor connection error before authentication: " ++ e)
liftAnnex th $ mergeState st'
authed conn theiruuid =
bracket watchChangedRefs (liftIO . maybe noop stopWatchingChangedRefs) $ \crh -> do
v' <- runFullProto (Serving theiruuid crh) conn $
P2P.serveAuthed u
case v' of
Right () -> return ()
Left e -> liftIO $ debugM "remotedaemon" ("Tor connection error: " ++ e)
Connect to peer 's tor hidden service .
transport :: Transport
transport (RemoteRepo r gc) url@(RemoteURI uri) th ichan ochan =
case unformatP2PAddress (show uri) of
Nothing -> return ()
Just addr -> robustConnection 1 $ do
g <- liftAnnex th Annex.gitRepo
bracket (connectPeer g addr) closeConnection (go addr)
where
go addr conn = do
myuuid <- liftAnnex th getUUID
authtoken <- fromMaybe nullAuthToken
<$> liftAnnex th (loadP2PRemoteAuthToken addr)
res <- runNetProto conn $
P2P.auth myuuid authtoken
case res of
Right (Just theiruuid) -> do
expecteduuid <- liftAnnex th $ getRepoUUID r
if expecteduuid == theiruuid
then do
send (CONNECTED url)
status <- handlecontrol
`race` handlepeer conn
send (DISCONNECTED url)
return $ either id id status
else return ConnectionStopping
_ -> return ConnectionClosed
send msg = atomically $ writeTChan ochan msg
handlecontrol = do
msg <- atomically $ readTChan ichan
case msg of
STOP -> return ConnectionStopping
LOSTNET -> return ConnectionStopping
_ -> handlecontrol
handlepeer conn = do
v <- runNetProto conn P2P.notifyChange
case v of
Right (Just (ChangedRefs shas)) -> do
whenM (checkShouldFetch gc th shas) $
fetch
handlepeer conn
_ -> return ConnectionClosed
fetch = do
send (SYNCING url)
ok <- inLocalRepo th $
runBool [Param "fetch", Param $ Git.repoDescribe r]
send (DONESYNCING url ok)
|
0a6b3f7e757e5bcc5d1f64c79d8e5cc43ec75b948fbee0513a2012ecbf735d9c | randomseed-io/bankster | registry.clj | (ns io.randomseed.bankster.registry
^{:doc "Bankster, registry management."
:author "Paweł Wilk"
:added "1.0.0"}
(:refer-clojure :exclude [new get set! update])
(:require [clojure.string :as str]
[io.randomseed.bankster :as bankster]
[io.randomseed.bankster.util.map :as map]
[io.randomseed.bankster.util.fs :as fs]
[io.randomseed.bankster.util :refer :all])
(:import [io.randomseed.bankster Registry]
[io.randomseed.bankster Currency Registry]
[java.time LocalDateTime format.DateTimeFormatter]))
;;
;; Registry version generator.
;;
(defn default-version
{:tag String :added "1.0.0"}
[]
(. (LocalDateTime/now) format (DateTimeFormatter/ofPattern "YYYYMMddHHmmssSS")))
;;
Global , shared registry .
;;
(def ^{:tag clojure.lang.Atom :added "1.0.0"}
R
"Global registry object based on an Atom."
(atom (Registry. {} {} {} {} {} {} (default-version))))
(defn global
"Returns global registry object."
{:tag clojure.lang.Atom :added "1.0.0"}
[]
R)
(defn state
"Returns current state of a global registry."
{:tag Registry :added "1.0.0"}
[]
(deref R))
;;
;; Dynamic registry.
;;
(def ^{:dynamic true :tag Registry :added "1.0.0"}
*default*
"Registry, that if set to a truthy value (not nil and not false), will be used
instead of a global, shared registry."
nil)
;;
;; Registry state getter.
;;
(defmacro get
"Gets the current state of a global registry. If the dynamic variable *default* is
set to a truthy value, it will be used instead."
{:added "1.0.0"}
[]
`(or ^Registry *default* ^Registry (deref R)))
;;
;; Registry constructor.
;;
(defn new-registry
"Creates a new registry."
{:tag Registry :added "1.0.0"}
(^Registry []
(bankster/->Registry {} {} {} {} {} {} (default-version)))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version]
(bankster/->Registry cur-id->cur
cur-nr->cur
ctr-id->cur
cur-id->ctr-ids
cur-id->localized
cur-code->curs
version))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
(new-registry cur-id->cur
cur-nr->cur
ctr-id->cur
cur-id->ctr-ids
cur-code->curs
(default-version)))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version]
(bankster/->Registry cur-id->cur
(map/map-keys-by-v :nr cur-id->cur)
ctr-id->cur
(map/invert-in-sets ctr-id->cur)
cur-id->localized
cur-code->curs
version))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
(new-registry cur-id->cur
ctr-id->cur
cur-id->localized
cur-code->curs
(default-version)))
(^Registry [^clojure.lang.PersistentHashMap m]
(bankster/map->Registry m)))
(def ^{:tag Registry
:added "1.0.0"
:arglists '(^Registry []
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
^Registry [^clojure.lang.PersistentHashMap m])}
new
"Alias for new-registry."
new-registry)
;;
;; Registry operations.
;;
(defn registry?
"Returns true if the given object is a registry."
{:tag Boolean :added "1.0.0"}
[obj]
(instance? Registry obj))
(defn update
"Updates a registry with a function that should take a registry as its first argument
and return the updated one. It is a simple apply-based implementation provided for
the sake of symmetry with update! which operates on a global registry object."
{:tag Registry :added "1.0.0"}
[^Registry r ^clojure.lang.IFn fun & more]
(apply fun r more))
(defn set-state
"Sets current state of a global registry."
{:added "1.0.0" :tag Registry :private true}
(^Registry [^Registry registry]
(if (registry? registry)
(reset! R ^Registry registry)
(reset! R (new-registry ^clojure.lang.PersistentHashMap registry))))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized]
(set-state (new-registry cur-id->cur
cur-nr->cur
ctr-id->cur
cur-id->ctr-ids
cur-id->localized
(default-version))))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^String version]
(set-state (new-registry cur-id->cur
cur-nr->cur
ctr-id->cur
cur-id->ctr-ids
cur-id->localized
version))))
(def ^{:tag Registry :added "1.0.0"
:arglists '(^Registry [^Registry registry]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version])}
set!
"Sets current state of a global registry."
set-state)
(defn update!
"Updates a global registry using a function that should take a registry and return
the updated version of it."
{:tag Registry :added "1.0.0"}
[^clojure.lang.IFn fun & more]
(apply swap! R fun more))
;;
;; Contextual macro.
;;
(defmacro with
"Sets a registry in a lexical context of the body to be used instead of a global one
in functions which require the registry and it was not passed as an argument."
{:added "1.0.0"}
[^Registry registry & body]
`(binding [*default* ^Registry ~registry]
~@body))
;;
;; Getters and helpers.
;;
(defmacro currency-id->currency
"Returns the currency ID to currency map from a registry. If the registry is not
given the dynamic variable *default* is tried. If it is not set, current state of a
global registry is used instead."
{:added "1.0.0"}
([] `(.cur-id->cur (get)))
([registry] `(.cur-id->cur ^Registry ~registry)))
(defmacro currency-nr->currency
"Returns the currency number to currency map from a registry. If the registry is not
given the dynamic variable *default* is tried. If it is not set, current state of a
global registry is used instead."
{:added "1.0.0"}
([] `(.cur-nr->cur (get)))
([registry] `(.cur-nr->cur ^Registry ~registry)))
(defmacro currency-code->currencies
"Returns the currency short-code to currencies map from a registry. If the registry
is not given the dynamic variable *default* is tried. If it is not set, current
state of a global registry is used instead."
{:added "1.0.0"}
([] `(.cur-code->curs (get)))
([registry] `(.cur-code->curs ^Registry ~registry)))
(defmacro country-id->currency
"Returns the country ID to currency map from a registry. If the registry is not given
the dynamic variable *default* is tried. If it is not set, current state of a
global registry is used instead."
{:added "1.0.0"}
([] `(.ctr-id->cur (get)))
([registry] `(.ctr-id->cur ^Registry ~registry)))
(defmacro currency-id->country-ids
"Returns the currency ID to country IDs map from a registry. If the registry is not
given the dynamic variable *default* is tried. If it is not set, current state of a
global registry is used instead."
{:added "1.0.0"}
([] `(.cur-id->ctr-ids (get)))
([registry] `(.cur-id->ctr-ids ^Registry ~registry)))
(defmacro currency-id->localized
"Returns the currency ID to localized propertied map from a registry. If the registry
is not given the dynamic variable *default* is tried. If it is not set, current
state of a global registry is used instead."
{:added "1.0.0"}
([] `(.cur-id->localized (get)))
([registry] `(.cur-id->localized ^Registry ~registry)))
;;
;; Printing.
;;
(defmethod print-method Registry
[r w]
(let [sid (Integer/toHexString (System/identityHashCode r))]
(print-simple
(str "#Registry[{"
":currencies " (count (.cur-id->cur ^Registry r)) ", "
":countries " (count (.ctr-id->cur ^Registry r)) ", "
":version \"" (.version ^Registry r) "\"} 0x" sid "]")
w)))
| null | https://raw.githubusercontent.com/randomseed-io/bankster/15fc1de1889a760a5fc3d1180c91ee5878b81c47/src/io/randomseed/bankster/registry.clj | clojure |
Registry version generator.
Dynamic registry.
Registry state getter.
Registry constructor.
Registry operations.
Contextual macro.
Getters and helpers.
Printing.
| (ns io.randomseed.bankster.registry
^{:doc "Bankster, registry management."
:author "Paweł Wilk"
:added "1.0.0"}
(:refer-clojure :exclude [new get set! update])
(:require [clojure.string :as str]
[io.randomseed.bankster :as bankster]
[io.randomseed.bankster.util.map :as map]
[io.randomseed.bankster.util.fs :as fs]
[io.randomseed.bankster.util :refer :all])
(:import [io.randomseed.bankster Registry]
[io.randomseed.bankster Currency Registry]
[java.time LocalDateTime format.DateTimeFormatter]))
(defn default-version
{:tag String :added "1.0.0"}
[]
(. (LocalDateTime/now) format (DateTimeFormatter/ofPattern "YYYYMMddHHmmssSS")))
Global , shared registry .
(def ^{:tag clojure.lang.Atom :added "1.0.0"}
R
"Global registry object based on an Atom."
(atom (Registry. {} {} {} {} {} {} (default-version))))
(defn global
"Returns global registry object."
{:tag clojure.lang.Atom :added "1.0.0"}
[]
R)
(defn state
"Returns current state of a global registry."
{:tag Registry :added "1.0.0"}
[]
(deref R))
(def ^{:dynamic true :tag Registry :added "1.0.0"}
*default*
"Registry, that if set to a truthy value (not nil and not false), will be used
instead of a global, shared registry."
nil)
(defmacro get
"Gets the current state of a global registry. If the dynamic variable *default* is
set to a truthy value, it will be used instead."
{:added "1.0.0"}
[]
`(or ^Registry *default* ^Registry (deref R)))
(defn new-registry
"Creates a new registry."
{:tag Registry :added "1.0.0"}
(^Registry []
(bankster/->Registry {} {} {} {} {} {} (default-version)))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version]
(bankster/->Registry cur-id->cur
cur-nr->cur
ctr-id->cur
cur-id->ctr-ids
cur-id->localized
cur-code->curs
version))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
(new-registry cur-id->cur
cur-nr->cur
ctr-id->cur
cur-id->ctr-ids
cur-code->curs
(default-version)))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version]
(bankster/->Registry cur-id->cur
(map/map-keys-by-v :nr cur-id->cur)
ctr-id->cur
(map/invert-in-sets ctr-id->cur)
cur-id->localized
cur-code->curs
version))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
(new-registry cur-id->cur
ctr-id->cur
cur-id->localized
cur-code->curs
(default-version)))
(^Registry [^clojure.lang.PersistentHashMap m]
(bankster/map->Registry m)))
(def ^{:tag Registry
:added "1.0.0"
:arglists '(^Registry []
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
^Registry [^clojure.lang.PersistentHashMap m])}
new
"Alias for new-registry."
new-registry)
(defn registry?
"Returns true if the given object is a registry."
{:tag Boolean :added "1.0.0"}
[obj]
(instance? Registry obj))
(defn update
"Updates a registry with a function that should take a registry as its first argument
and return the updated one. It is a simple apply-based implementation provided for
the sake of symmetry with update! which operates on a global registry object."
{:tag Registry :added "1.0.0"}
[^Registry r ^clojure.lang.IFn fun & more]
(apply fun r more))
(defn set-state
"Sets current state of a global registry."
{:added "1.0.0" :tag Registry :private true}
(^Registry [^Registry registry]
(if (registry? registry)
(reset! R ^Registry registry)
(reset! R (new-registry ^clojure.lang.PersistentHashMap registry))))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized]
(set-state (new-registry cur-id->cur
cur-nr->cur
ctr-id->cur
cur-id->ctr-ids
cur-id->localized
(default-version))))
(^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^String version]
(set-state (new-registry cur-id->cur
cur-nr->cur
ctr-id->cur
cur-id->ctr-ids
cur-id->localized
version))))
(def ^{:tag Registry :added "1.0.0"
:arglists '(^Registry [^Registry registry]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs]
^Registry [^clojure.lang.PersistentHashMap cur-id->cur
^clojure.lang.PersistentHashMap cur-nr->cur
^clojure.lang.PersistentHashMap ctr-id->cur
^clojure.lang.PersistentHashMap cur-id->ctr-ids
^clojure.lang.PersistentHashMap cur-id->localized
^clojure.lang.PersistentHashMap cur-code->curs
^String version])}
set!
"Sets current state of a global registry."
set-state)
(defn update!
"Updates a global registry using a function that should take a registry and return
the updated version of it."
{:tag Registry :added "1.0.0"}
[^clojure.lang.IFn fun & more]
(apply swap! R fun more))
(defmacro with
"Sets a registry in a lexical context of the body to be used instead of a global one
in functions which require the registry and it was not passed as an argument."
{:added "1.0.0"}
[^Registry registry & body]
`(binding [*default* ^Registry ~registry]
~@body))
(defmacro currency-id->currency
"Returns the currency ID to currency map from a registry. If the registry is not
given the dynamic variable *default* is tried. If it is not set, current state of a
global registry is used instead."
{:added "1.0.0"}
([] `(.cur-id->cur (get)))
([registry] `(.cur-id->cur ^Registry ~registry)))
(defmacro currency-nr->currency
"Returns the currency number to currency map from a registry. If the registry is not
given the dynamic variable *default* is tried. If it is not set, current state of a
global registry is used instead."
{:added "1.0.0"}
([] `(.cur-nr->cur (get)))
([registry] `(.cur-nr->cur ^Registry ~registry)))
(defmacro currency-code->currencies
"Returns the currency short-code to currencies map from a registry. If the registry
is not given the dynamic variable *default* is tried. If it is not set, current
state of a global registry is used instead."
{:added "1.0.0"}
([] `(.cur-code->curs (get)))
([registry] `(.cur-code->curs ^Registry ~registry)))
(defmacro country-id->currency
"Returns the country ID to currency map from a registry. If the registry is not given
the dynamic variable *default* is tried. If it is not set, current state of a
global registry is used instead."
{:added "1.0.0"}
([] `(.ctr-id->cur (get)))
([registry] `(.ctr-id->cur ^Registry ~registry)))
(defmacro currency-id->country-ids
"Returns the currency ID to country IDs map from a registry. If the registry is not
given the dynamic variable *default* is tried. If it is not set, current state of a
global registry is used instead."
{:added "1.0.0"}
([] `(.cur-id->ctr-ids (get)))
([registry] `(.cur-id->ctr-ids ^Registry ~registry)))
(defmacro currency-id->localized
"Returns the currency ID to localized propertied map from a registry. If the registry
is not given the dynamic variable *default* is tried. If it is not set, current
state of a global registry is used instead."
{:added "1.0.0"}
([] `(.cur-id->localized (get)))
([registry] `(.cur-id->localized ^Registry ~registry)))
(defmethod print-method Registry
[r w]
(let [sid (Integer/toHexString (System/identityHashCode r))]
(print-simple
(str "#Registry[{"
":currencies " (count (.cur-id->cur ^Registry r)) ", "
":countries " (count (.ctr-id->cur ^Registry r)) ", "
":version \"" (.version ^Registry r) "\"} 0x" sid "]")
w)))
|
701cafe1e69b420a0db4c7ecdc56b9e7258e98981b18a95eed875f8f1d778fd1 | Elzair/nazghul | amy.scm | ;;----------------------------------------------------------------------------
;; Constants
;;----------------------------------------------------------------------------
(define amy-lvl 1)
(define amy-species sp_human)
(define amy-occ oc_wright)
;;----------------------------------------------------------------------------
;; Schedule
;;
In the Poor House ( at least until such time as she joins the ) .
;;----------------------------------------------------------------------------
(define amy-bed poorh-bed2)
(define amy-mealplace poorh-sup2)
(define amy-workplace poorh-pasture)
(define amy-leisureplace poorh-dining)
(kern-mk-sched 'sch_amy
(list 0 0 amy-bed "sleeping")
(list 7 0 amy-mealplace "eating")
(list 8 0 amy-workplace "working")
(list 12 0 amy-mealplace "eating")
(list 13 0 amy-workplace "working")
(list 18 0 amy-mealplace "eating")
(list 19 0 amy-leisureplace "idle")
(list 22 0 amy-bed "sleeping")
)
;;----------------------------------------------------------------------------
;; Gob
;;----------------------------------------------------------------------------
(define (amy-mk) nil)
;;----------------------------------------------------------------------------
;; Conv
;;
is a female tinker , fallen upon hard times .
She currently dwells in the Poor House .
is a potential party member .
;;----------------------------------------------------------------------------
;; Basics...
(define (amy-hail knpc kpc)
(meet "You meet a practical-looking tinker woman.")
(say knpc "Hello.")
)
(define (amy-name knpc kpc)
(say knpc "You can call me Amy.")
)
(define (amy-join knpc kpc)
(if (is-player-party-member? knpc)
(say knpc "I already joined you!")
(begin
(say knpc "I thought you'd never ask!")
(join-player knpc)
(kern-conv-end)
)))
(define (amy-job knpc kpc)
(say knpc "Well, I'm a tinker by trade, "
"but I haven't had much luck finding work lately.")
)
(define (amy-bye knpc kpc)
(say knpc "So long.")
)
(define (amy-mean knpc kpc)
(say knpc "He's great. "
"I don't know where I'd go if it weren't for the poor house. "
"He doesn't even stare at my boobs all that much.")
)
(define (amy-tink knpc kpc)
(say knpc "A tinker is a wandering wright. "
"We travel from town to town, fixing things up for people.")
)
(define (amy-luck knpc kpc)
(say knpc "People are nervous of strangers now, "
"what with the Accursed and all.")
)
(define (amy-accu knpc kpc)
(say knpc "The Accursed are a secret cult who "
"follow evil ways.")
)
Quest - related
(define amy-conv
(ifc basic-conv
;; basics
(method 'hail amy-hail)
(method 'bye amy-bye)
(method 'job amy-job)
(method 'name amy-name)
(method 'join amy-join)
(method 'mean amy-mean)
(method 'tink amy-tink)
(method 'luck amy-luck)
(method 'accu amy-accu)
))
(define (mk-amy)
(bind
(kern-mk-char
'ch_amy ; tag
"Amy" ; name
amy-species ; species
amy-occ ; occ
s_companion_tinker ; sprite
faction-men ; starting alignment
str / int / dex
pc-hp-off ; hp bonus
pc-hp-gain ; hp per-level bonus
1 ; mp off
1 ; mp gain
max-health ; hp
-1 ; xp
max-health ; mp
0
amy-lvl
#f ; dead
'amy-conv ; conv
sch_amy ; sched
'townsman-ai ; special ai
nil ; container
(list
t_armor_leather
t_leather_helm
t_sling
t_sword
))
(amy-mk)))
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.002/amy.scm | scheme | ----------------------------------------------------------------------------
Constants
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Schedule
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Gob
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Conv
----------------------------------------------------------------------------
Basics...
basics
tag
name
species
occ
sprite
starting alignment
hp bonus
hp per-level bonus
mp off
mp gain
hp
xp
mp
dead
conv
sched
special ai
container | (define amy-lvl 1)
(define amy-species sp_human)
(define amy-occ oc_wright)
In the Poor House ( at least until such time as she joins the ) .
(define amy-bed poorh-bed2)
(define amy-mealplace poorh-sup2)
(define amy-workplace poorh-pasture)
(define amy-leisureplace poorh-dining)
(kern-mk-sched 'sch_amy
(list 0 0 amy-bed "sleeping")
(list 7 0 amy-mealplace "eating")
(list 8 0 amy-workplace "working")
(list 12 0 amy-mealplace "eating")
(list 13 0 amy-workplace "working")
(list 18 0 amy-mealplace "eating")
(list 19 0 amy-leisureplace "idle")
(list 22 0 amy-bed "sleeping")
)
(define (amy-mk) nil)
is a female tinker , fallen upon hard times .
She currently dwells in the Poor House .
is a potential party member .
(define (amy-hail knpc kpc)
(meet "You meet a practical-looking tinker woman.")
(say knpc "Hello.")
)
(define (amy-name knpc kpc)
(say knpc "You can call me Amy.")
)
(define (amy-join knpc kpc)
(if (is-player-party-member? knpc)
(say knpc "I already joined you!")
(begin
(say knpc "I thought you'd never ask!")
(join-player knpc)
(kern-conv-end)
)))
(define (amy-job knpc kpc)
(say knpc "Well, I'm a tinker by trade, "
"but I haven't had much luck finding work lately.")
)
(define (amy-bye knpc kpc)
(say knpc "So long.")
)
(define (amy-mean knpc kpc)
(say knpc "He's great. "
"I don't know where I'd go if it weren't for the poor house. "
"He doesn't even stare at my boobs all that much.")
)
(define (amy-tink knpc kpc)
(say knpc "A tinker is a wandering wright. "
"We travel from town to town, fixing things up for people.")
)
(define (amy-luck knpc kpc)
(say knpc "People are nervous of strangers now, "
"what with the Accursed and all.")
)
(define (amy-accu knpc kpc)
(say knpc "The Accursed are a secret cult who "
"follow evil ways.")
)
Quest - related
(define amy-conv
(ifc basic-conv
(method 'hail amy-hail)
(method 'bye amy-bye)
(method 'job amy-job)
(method 'name amy-name)
(method 'join amy-join)
(method 'mean amy-mean)
(method 'tink amy-tink)
(method 'luck amy-luck)
(method 'accu amy-accu)
))
(define (mk-amy)
(bind
(kern-mk-char
str / int / dex
0
amy-lvl
(list
t_armor_leather
t_leather_helm
t_sling
t_sword
))
(amy-mk)))
|
8842fe92f9ad4394130b2644ab6651a104a6e0894d0d6f1ae9165441a99e65a0 | Lupino/haskell-periodic | Worker.hs | module Periodic.Worker
( WorkerM
, startWorkerM
, ping
, addFunc
, broadcast
, removeFunc
, work
, close
) where
import Metro.TP.Socket (Socket, socket)
import Periodic.Trans.Worker
type WorkerM = WorkerT Socket IO
startWorkerM :: String -> WorkerM () -> IO ()
startWorkerM h = startWorkerT (socket h)
| null | https://raw.githubusercontent.com/Lupino/haskell-periodic/c04517bb9195b39c8ddc8839d367f9adf219c6bc/periodic-client/src/Periodic/Worker.hs | haskell | module Periodic.Worker
( WorkerM
, startWorkerM
, ping
, addFunc
, broadcast
, removeFunc
, work
, close
) where
import Metro.TP.Socket (Socket, socket)
import Periodic.Trans.Worker
type WorkerM = WorkerT Socket IO
startWorkerM :: String -> WorkerM () -> IO ()
startWorkerM h = startWorkerT (socket h)
| |
07b640617bc635a4f63672e848752bc747cd7d9c046caa36a82a41eb9e66a1b5 | Mesabloo/nihil | MissingFieldsInRecord.hs | module Nihil.TypeChecking.Errors.MissingFieldsInRecord where
import Nihil.Utils.Source
import Text.PrettyPrint.ANSI.Leijen
import Prelude hiding ((<$>))
missingFieldsInRecord :: [String] -> SourcePos -> Doc
missingFieldsInRecord fs pos =
nest 4 (text "> Record is missing fields:" <$> description)
where description =
text "- Missing fields:" <+> semiBraces (fmap text fs) <$>
text "- At: " <> text (show pos) <> line
| null | https://raw.githubusercontent.com/Mesabloo/nihil/3821052ca5691a6492b23bd8a46bfe70567d374f/src/typechecker/Nihil/TypeChecking/Errors/MissingFieldsInRecord.hs | haskell | module Nihil.TypeChecking.Errors.MissingFieldsInRecord where
import Nihil.Utils.Source
import Text.PrettyPrint.ANSI.Leijen
import Prelude hiding ((<$>))
missingFieldsInRecord :: [String] -> SourcePos -> Doc
missingFieldsInRecord fs pos =
nest 4 (text "> Record is missing fields:" <$> description)
where description =
text "- Missing fields:" <+> semiBraces (fmap text fs) <$>
text "- At: " <> text (show pos) <> line
| |
987159117afa288345da8ba9fd6b30ae62c71c1472fd3ce9564cf6b5a7534682 | janestreet/universe | splittable_random.ml | * This module implements " Fast Splittable Pseudorandom Number Generators " by et .
al . ( 1 ) . The paper 's algorithm provides decent randomness for most purposes , but
sacrifices cryptographic - quality randomness in favor of performance . The original
implementation was tested with DieHarder and BigCrush ; see the paper for details .
Our implementation is a port from Java to OCaml of the paper 's algorithm . Other than
the choice of initial seed for [ create ] , our port should be faithful . We have not
re - run the DieHarder or BigCrush tests on our implementation . Our port is also not as
performant as the original ; two factors that hurt us are boxed [ int64 ] values and lack
of a POPCNT primitive .
( 1 ) -fast-splittable-pseudorandom-number-generators
( also mirrored at )
Beware when implementing this interface ; it is easy to implement a [ split ] operation
whose output is not as " independent " as it seems ( 2 ) . This bug caused problems for
Haskell 's Quickcheck library for a long time .
( 2 ) Schaathun , " Evaluation of splittable pseudo - random generators " , 2015 .
al. (1). The paper's algorithm provides decent randomness for most purposes, but
sacrifices cryptographic-quality randomness in favor of performance. The original
implementation was tested with DieHarder and BigCrush; see the paper for details.
Our implementation is a port from Java to OCaml of the paper's algorithm. Other than
the choice of initial seed for [create], our port should be faithful. We have not
re-run the DieHarder or BigCrush tests on our implementation. Our port is also not as
performant as the original; two factors that hurt us are boxed [int64] values and lack
of a POPCNT primitive.
(1) -fast-splittable-pseudorandom-number-generators
(also mirrored at )
Beware when implementing this interface; it is easy to implement a [split] operation
whose output is not as "independent" as it seems (2). This bug caused problems for
Haskell's Quickcheck library for a long time.
(2) Schaathun, "Evaluation of splittable pseudo-random generators", JFP 2015.
*)
open! Base
open Int64.O
let is_odd x = x lor 1L = x
let popcount = Int64.popcount
module State = struct
type t =
{ mutable seed : int64
; odd_gamma : int64
}
let golden_gamma = 0x9e37_79b9_7f4a_7c15L
let of_int seed =
{ seed = Int64.of_int seed
; odd_gamma = golden_gamma
}
let copy { seed ; odd_gamma } = { seed ; odd_gamma }
let mix_bits z n =
z lxor (z lsr n)
let mix64 z =
let z = (mix_bits z 33) * 0xff51_afd7_ed55_8ccdL in
let z = (mix_bits z 33) * 0xc4ce_b9fe_1a85_ec53L in
mix_bits z 33
let mix64_variant13 z =
let z = (mix_bits z 30) * 0xbf58_476d_1ce4_e5b9L in
let z = (mix_bits z 27) * 0x94d0_49bb_1331_11ebL in
mix_bits z 31
let mix_odd_gamma z =
let z = (mix64_variant13 z) lor 1L in
let n = popcount (z lxor (z lsr 1)) in
The original paper uses [ > =] in the conditional immediately below ; however this is
a typo , and we correct it by using [ < ] . This was fixed in response to [ 1 ] and [ 2 ] .
[ 1 ]
[ 2 ] -random.org/posts/bugs-in-splitmix.html
a typo, and we correct it by using [<]. This was fixed in response to [1] and [2].
[1]
[2] -random.org/posts/bugs-in-splitmix.html
*)
if Int.( < ) n 24
then z lxor 0xaaaa_aaaa_aaaa_aaaaL
else z
let%test_unit "odd gamma" =
for input = -1_000_000 to 1_000_000 do
let output = mix_odd_gamma (Int64.of_int input) in
if not (is_odd output) then
Error.raise_s [%message
"gamma value is not odd"
(input : int)
(output : int64)]
done
let next_seed t =
let next = t.seed + t.odd_gamma in
t.seed <- next;
next
let of_seed_and_gamma ~seed ~gamma =
let seed = mix64 seed in
let odd_gamma = mix_odd_gamma gamma in
{ seed; odd_gamma }
let random_int64 random_state =
Random.State.int64_incl random_state Int64.min_value Int64.max_value
let create random_state =
let seed = random_int64 random_state in
let gamma = random_int64 random_state in
of_seed_and_gamma ~seed ~gamma
let split t =
let seed = next_seed t in
let gamma = next_seed t in
of_seed_and_gamma ~seed ~gamma
let next_int64 t = mix64 (next_seed t)
(* [perturb] is not from any external source, but provides a way to mix in external
entropy with a pseudo-random state. *)
let perturb t salt =
let next = t.seed + mix64 (Int64.of_int salt) in
t.seed <- next
end
let bool state = is_odd (State.next_int64 state)
(* We abuse terminology and refer to individual values as biased or unbiased. More
properly, what is unbiased is the sampler that results if we keep only these "unbiased"
values. *)
let remainder_is_unbiased
~draw
~remainder
~draw_maximum
~remainder_maximum
=
let open Int64.O in
draw - remainder <= draw_maximum - remainder_maximum
let%test_unit "remainder_is_unbiased" =
choosing a range of 10 values based on a range of 105 values
let draw_maximum = 104L in
let remainder_maximum = 9L in
let is_unbiased draw =
let remainder = Int64.rem draw (Int64.succ remainder_maximum) in
remainder_is_unbiased ~draw ~remainder ~draw_maximum ~remainder_maximum
in
for i = 0 to 99 do
[%test_result: bool]
(is_unbiased (Int64.of_int i))
~expect:true
~message:(Int.to_string i)
done;
for i = 100 to 104 do
[%test_result: bool]
(is_unbiased (Int64.of_int i))
~expect:false
~message:(Int.to_string i)
done
(* This implementation of bounded randomness is adapted from [Random.State.int*] in the
OCaml standard library. The purpose is to use the minimum number of calls to
[next_int64] to produce a number uniformly chosen within the given range. *)
let int64 =
let open Int64.O in
let rec between state ~lo ~hi =
let draw = State.next_int64 state in
if lo <= draw && draw <= hi
then draw
else between state ~lo ~hi
in
let rec non_negative_up_to state maximum =
let draw = State.next_int64 state land Int64.max_value in
let remainder = Int64.rem draw (Int64.succ maximum) in
if remainder_is_unbiased
~draw
~remainder
~draw_maximum:Int64.max_value
~remainder_maximum:maximum
then remainder
else non_negative_up_to state maximum
in
fun state ~lo ~hi ->
if lo > hi then begin
Error.raise_s [%message "int64: crossed bounds" (lo : int64) (hi : int64)]
end;
let diff = hi - lo in
if diff = Int64.max_value
then ((State.next_int64 state) land Int64.max_value) + lo
else if diff >= 0L
then (non_negative_up_to state diff) + lo
else between state ~lo ~hi
let int state ~lo ~hi =
let lo = Int64.of_int lo in
let hi = Int64.of_int hi in
(* truncate unneeded bits *)
Int64.to_int_trunc (int64 state ~lo ~hi)
let int32 state ~lo ~hi =
let lo = Int64.of_int32 lo in
let hi = Int64.of_int32 hi in
(* truncate unneeded bits *)
Int64.to_int32_trunc (int64 state ~lo ~hi)
let nativeint state ~lo ~hi =
let lo = Int64.of_nativeint lo in
let hi = Int64.of_nativeint hi in
(* truncate unneeded bits *)
Int64.to_nativeint_trunc (int64 state ~lo ~hi)
let int63 state ~lo ~hi =
let lo = Int63.to_int64 lo in
let hi = Int63.to_int64 hi in
(* truncate unneeded bits *)
Int63.of_int64_trunc (int64 state ~lo ~hi)
let double_ulp = 2. **. -53.
let%test_unit "double_ulp" =
let open Float.O in
match Word_size.word_size with
| W64 ->
assert (1.0 -. double_ulp < 1.0);
assert (1.0 -. (double_ulp /. 2.0) = 1.0)
| W32 ->
32 - bit OCaml uses a 64 - bit float representation but 80 - bit float instructions , so
rounding works differently due to the conversion back and forth .
rounding works differently due to the conversion back and forth. *)
assert (1.0 -. double_ulp < 1.0);
assert (1.0 -. (double_ulp /. 2.0) <= 1.0)
let unit_float_from_int64 int64 =
(Int64.to_float (int64 lsr 11)) *. double_ulp
let%test_unit "unit_float_from_int64" = begin
let open Float.O in
assert (unit_float_from_int64 0x0000_0000_0000_0000L = 0.);
assert (unit_float_from_int64 0xffff_ffff_ffff_ffffL < 1.0);
assert (unit_float_from_int64 0xffff_ffff_ffff_ffffL = (1.0 -. double_ulp));
end
let unit_float state =
unit_float_from_int64 (State.next_int64 state)
Note about roundoff error :
Although [ float state ~lo ~hi ] is nominally inclusive of endpoints , we are relying on
the fact that [ unit_float ] never returns 1 . , because there are pairs [ ( lo , hi ) ] for
which [ lo + . 1 . * . ( hi - . lo ) > hi ] . There are also pairs [ ( lo , hi ) ] and values of [ x ]
with [ x < 1 . ] such that [ lo + . x * . ( hi - . lo ) = hi ] , so it would not be correct to
document this as being exclusive of [ hi ] .
Although [float state ~lo ~hi] is nominally inclusive of endpoints, we are relying on
the fact that [unit_float] never returns 1., because there are pairs [(lo,hi)] for
which [lo +. 1. *. (hi -. lo) > hi]. There are also pairs [(lo,hi)] and values of [x]
with [x < 1.] such that [lo +. x *. (hi -. lo) = hi], so it would not be correct to
document this as being exclusive of [hi].
*)
let float =
let rec finite_float state ~lo ~hi =
let range = hi -. lo in
if Float.is_finite range
then (lo +. (unit_float state *. range))
else begin
(* If [hi - lo] is infinite, then [hi + lo] is finite because [hi] and [lo] have
opposite signs. *)
let mid = (hi +. lo) /. 2. in
if bool state
Depending on rounding , the recursion with [ ~hi : mid ] might be inclusive of [ mid ] ,
which would mean the two cases overlap on [ mid ] . The alternative is to increment
or decrement [ mid ] using [ one_ulp ] in either of the calls , but then if the first
case is exclusive we leave a " gap " between the two ranges . There 's no perfectly
uniform solution , so we use the simpler code that does not call [ one_ulp ] .
which would mean the two cases overlap on [mid]. The alternative is to increment
or decrement [mid] using [one_ulp] in either of the calls, but then if the first
case is exclusive we leave a "gap" between the two ranges. There's no perfectly
uniform solution, so we use the simpler code that does not call [one_ulp]. *)
then finite_float state ~lo ~hi:mid
else finite_float state ~lo:mid ~hi
end
in
fun state ~lo ~hi ->
if not (Float.is_finite lo && Float.is_finite hi)
then begin
raise_s [%message
"float: bounds are not finite numbers"
(lo : float)
(hi : float)]
end;
if Float.( > ) lo hi
then begin
raise_s [%message
"float: bounds are crossed"
(lo : float)
(hi : float)]
end;
finite_float state ~lo ~hi
let%bench_fun "unit_float_from_int64" =
let int64 = 1L in
fun () -> unit_float_from_int64 int64
module Log_uniform = struct
module Make (M : sig include Int.S val uniform : State.t -> lo:t -> hi:t -> t end) : sig
val log_uniform : State.t -> lo:M.t -> hi:M.t -> M.t
end = struct
open M
let bits_to_represent t =
assert (t >= zero);
let t = ref t in
let n = ref 0 in
while !t > zero do
t := shift_right !t 1;
Int.incr n;
done;
!n
let%test_unit "bits_to_represent" =
let test n expect = [%test_result: int] (bits_to_represent n) ~expect in
test (M.of_int_exn 0) 0;
test (M.of_int_exn 1) 1;
test (M.of_int_exn 2) 2;
test (M.of_int_exn 3) 2;
test (M.of_int_exn 4) 3;
test (M.of_int_exn 5) 3;
test (M.of_int_exn 6) 3;
test (M.of_int_exn 7) 3;
test (M.of_int_exn 8) 4;
test (M.of_int_exn 100) 7;
test M.max_value (Int.pred M.num_bits);
;;
let min_represented_by_n_bits n =
if Int.equal n 0
then zero
else shift_left one (Int.pred n)
let%test_unit "min_represented_by_n_bits" =
let test n expect = [%test_result: M.t] (min_represented_by_n_bits n) ~expect in
test 0 (M.of_int_exn 0);
test 1 (M.of_int_exn 1);
test 2 (M.of_int_exn 2);
test 3 (M.of_int_exn 4);
test 4 (M.of_int_exn 8);
test 7 (M.of_int_exn 64);
test (Int.pred M.num_bits) (M.shift_right_logical M.min_value 1);
;;
let max_represented_by_n_bits n =
pred (shift_left one n)
let%test_unit "max_represented_by_n_bits" =
let test n expect = [%test_result: M.t] (max_represented_by_n_bits n) ~expect in
test 0 (M.of_int_exn 0);
test 1 (M.of_int_exn 1);
test 2 (M.of_int_exn 3);
test 3 (M.of_int_exn 7);
test 4 (M.of_int_exn 15);
test 7 (M.of_int_exn 127);
test (Int.pred M.num_bits) M.max_value;
;;
let log_uniform state ~lo ~hi =
let min_bits = bits_to_represent lo in
let max_bits = bits_to_represent hi in
let bits = int state ~lo:min_bits ~hi:max_bits in
uniform state
~lo:(min_represented_by_n_bits bits |> max lo)
~hi:(max_represented_by_n_bits bits |> min hi)
end
module For_int = Make (struct include Int let uniform = int end)
module For_int32 = Make (struct include Int32 let uniform = int32 end)
module For_int63 = Make (struct include Int63 let uniform = int63 end)
module For_int64 = Make (struct include Int64 let uniform = int64 end)
module For_nativeint = Make (struct include Nativeint let uniform = nativeint end)
let int = For_int.log_uniform
let int32 = For_int32.log_uniform
let int63 = For_int63.log_uniform
let int64 = For_int64.log_uniform
let nativeint = For_nativeint.log_uniform
end
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/splittable_random/src/splittable_random.ml | ocaml | [perturb] is not from any external source, but provides a way to mix in external
entropy with a pseudo-random state.
We abuse terminology and refer to individual values as biased or unbiased. More
properly, what is unbiased is the sampler that results if we keep only these "unbiased"
values.
This implementation of bounded randomness is adapted from [Random.State.int*] in the
OCaml standard library. The purpose is to use the minimum number of calls to
[next_int64] to produce a number uniformly chosen within the given range.
truncate unneeded bits
truncate unneeded bits
truncate unneeded bits
truncate unneeded bits
If [hi - lo] is infinite, then [hi + lo] is finite because [hi] and [lo] have
opposite signs. | * This module implements " Fast Splittable Pseudorandom Number Generators " by et .
al . ( 1 ) . The paper 's algorithm provides decent randomness for most purposes , but
sacrifices cryptographic - quality randomness in favor of performance . The original
implementation was tested with DieHarder and BigCrush ; see the paper for details .
Our implementation is a port from Java to OCaml of the paper 's algorithm . Other than
the choice of initial seed for [ create ] , our port should be faithful . We have not
re - run the DieHarder or BigCrush tests on our implementation . Our port is also not as
performant as the original ; two factors that hurt us are boxed [ int64 ] values and lack
of a POPCNT primitive .
( 1 ) -fast-splittable-pseudorandom-number-generators
( also mirrored at )
Beware when implementing this interface ; it is easy to implement a [ split ] operation
whose output is not as " independent " as it seems ( 2 ) . This bug caused problems for
Haskell 's Quickcheck library for a long time .
( 2 ) Schaathun , " Evaluation of splittable pseudo - random generators " , 2015 .
al. (1). The paper's algorithm provides decent randomness for most purposes, but
sacrifices cryptographic-quality randomness in favor of performance. The original
implementation was tested with DieHarder and BigCrush; see the paper for details.
Our implementation is a port from Java to OCaml of the paper's algorithm. Other than
the choice of initial seed for [create], our port should be faithful. We have not
re-run the DieHarder or BigCrush tests on our implementation. Our port is also not as
performant as the original; two factors that hurt us are boxed [int64] values and lack
of a POPCNT primitive.
(1) -fast-splittable-pseudorandom-number-generators
(also mirrored at )
Beware when implementing this interface; it is easy to implement a [split] operation
whose output is not as "independent" as it seems (2). This bug caused problems for
Haskell's Quickcheck library for a long time.
(2) Schaathun, "Evaluation of splittable pseudo-random generators", JFP 2015.
*)
open! Base
open Int64.O
let is_odd x = x lor 1L = x
let popcount = Int64.popcount
module State = struct
type t =
{ mutable seed : int64
; odd_gamma : int64
}
let golden_gamma = 0x9e37_79b9_7f4a_7c15L
let of_int seed =
{ seed = Int64.of_int seed
; odd_gamma = golden_gamma
}
let copy { seed ; odd_gamma } = { seed ; odd_gamma }
let mix_bits z n =
z lxor (z lsr n)
let mix64 z =
let z = (mix_bits z 33) * 0xff51_afd7_ed55_8ccdL in
let z = (mix_bits z 33) * 0xc4ce_b9fe_1a85_ec53L in
mix_bits z 33
let mix64_variant13 z =
let z = (mix_bits z 30) * 0xbf58_476d_1ce4_e5b9L in
let z = (mix_bits z 27) * 0x94d0_49bb_1331_11ebL in
mix_bits z 31
let mix_odd_gamma z =
let z = (mix64_variant13 z) lor 1L in
let n = popcount (z lxor (z lsr 1)) in
The original paper uses [ > =] in the conditional immediately below ; however this is
a typo , and we correct it by using [ < ] . This was fixed in response to [ 1 ] and [ 2 ] .
[ 1 ]
[ 2 ] -random.org/posts/bugs-in-splitmix.html
a typo, and we correct it by using [<]. This was fixed in response to [1] and [2].
[1]
[2] -random.org/posts/bugs-in-splitmix.html
*)
if Int.( < ) n 24
then z lxor 0xaaaa_aaaa_aaaa_aaaaL
else z
let%test_unit "odd gamma" =
for input = -1_000_000 to 1_000_000 do
let output = mix_odd_gamma (Int64.of_int input) in
if not (is_odd output) then
Error.raise_s [%message
"gamma value is not odd"
(input : int)
(output : int64)]
done
let next_seed t =
let next = t.seed + t.odd_gamma in
t.seed <- next;
next
let of_seed_and_gamma ~seed ~gamma =
let seed = mix64 seed in
let odd_gamma = mix_odd_gamma gamma in
{ seed; odd_gamma }
let random_int64 random_state =
Random.State.int64_incl random_state Int64.min_value Int64.max_value
let create random_state =
let seed = random_int64 random_state in
let gamma = random_int64 random_state in
of_seed_and_gamma ~seed ~gamma
let split t =
let seed = next_seed t in
let gamma = next_seed t in
of_seed_and_gamma ~seed ~gamma
let next_int64 t = mix64 (next_seed t)
let perturb t salt =
let next = t.seed + mix64 (Int64.of_int salt) in
t.seed <- next
end
let bool state = is_odd (State.next_int64 state)
let remainder_is_unbiased
~draw
~remainder
~draw_maximum
~remainder_maximum
=
let open Int64.O in
draw - remainder <= draw_maximum - remainder_maximum
let%test_unit "remainder_is_unbiased" =
choosing a range of 10 values based on a range of 105 values
let draw_maximum = 104L in
let remainder_maximum = 9L in
let is_unbiased draw =
let remainder = Int64.rem draw (Int64.succ remainder_maximum) in
remainder_is_unbiased ~draw ~remainder ~draw_maximum ~remainder_maximum
in
for i = 0 to 99 do
[%test_result: bool]
(is_unbiased (Int64.of_int i))
~expect:true
~message:(Int.to_string i)
done;
for i = 100 to 104 do
[%test_result: bool]
(is_unbiased (Int64.of_int i))
~expect:false
~message:(Int.to_string i)
done
let int64 =
let open Int64.O in
let rec between state ~lo ~hi =
let draw = State.next_int64 state in
if lo <= draw && draw <= hi
then draw
else between state ~lo ~hi
in
let rec non_negative_up_to state maximum =
let draw = State.next_int64 state land Int64.max_value in
let remainder = Int64.rem draw (Int64.succ maximum) in
if remainder_is_unbiased
~draw
~remainder
~draw_maximum:Int64.max_value
~remainder_maximum:maximum
then remainder
else non_negative_up_to state maximum
in
fun state ~lo ~hi ->
if lo > hi then begin
Error.raise_s [%message "int64: crossed bounds" (lo : int64) (hi : int64)]
end;
let diff = hi - lo in
if diff = Int64.max_value
then ((State.next_int64 state) land Int64.max_value) + lo
else if diff >= 0L
then (non_negative_up_to state diff) + lo
else between state ~lo ~hi
let int state ~lo ~hi =
let lo = Int64.of_int lo in
let hi = Int64.of_int hi in
Int64.to_int_trunc (int64 state ~lo ~hi)
let int32 state ~lo ~hi =
let lo = Int64.of_int32 lo in
let hi = Int64.of_int32 hi in
Int64.to_int32_trunc (int64 state ~lo ~hi)
let nativeint state ~lo ~hi =
let lo = Int64.of_nativeint lo in
let hi = Int64.of_nativeint hi in
Int64.to_nativeint_trunc (int64 state ~lo ~hi)
let int63 state ~lo ~hi =
let lo = Int63.to_int64 lo in
let hi = Int63.to_int64 hi in
Int63.of_int64_trunc (int64 state ~lo ~hi)
let double_ulp = 2. **. -53.
let%test_unit "double_ulp" =
let open Float.O in
match Word_size.word_size with
| W64 ->
assert (1.0 -. double_ulp < 1.0);
assert (1.0 -. (double_ulp /. 2.0) = 1.0)
| W32 ->
32 - bit OCaml uses a 64 - bit float representation but 80 - bit float instructions , so
rounding works differently due to the conversion back and forth .
rounding works differently due to the conversion back and forth. *)
assert (1.0 -. double_ulp < 1.0);
assert (1.0 -. (double_ulp /. 2.0) <= 1.0)
let unit_float_from_int64 int64 =
(Int64.to_float (int64 lsr 11)) *. double_ulp
let%test_unit "unit_float_from_int64" = begin
let open Float.O in
assert (unit_float_from_int64 0x0000_0000_0000_0000L = 0.);
assert (unit_float_from_int64 0xffff_ffff_ffff_ffffL < 1.0);
assert (unit_float_from_int64 0xffff_ffff_ffff_ffffL = (1.0 -. double_ulp));
end
let unit_float state =
unit_float_from_int64 (State.next_int64 state)
Note about roundoff error :
Although [ float state ~lo ~hi ] is nominally inclusive of endpoints , we are relying on
the fact that [ unit_float ] never returns 1 . , because there are pairs [ ( lo , hi ) ] for
which [ lo + . 1 . * . ( hi - . lo ) > hi ] . There are also pairs [ ( lo , hi ) ] and values of [ x ]
with [ x < 1 . ] such that [ lo + . x * . ( hi - . lo ) = hi ] , so it would not be correct to
document this as being exclusive of [ hi ] .
Although [float state ~lo ~hi] is nominally inclusive of endpoints, we are relying on
the fact that [unit_float] never returns 1., because there are pairs [(lo,hi)] for
which [lo +. 1. *. (hi -. lo) > hi]. There are also pairs [(lo,hi)] and values of [x]
with [x < 1.] such that [lo +. x *. (hi -. lo) = hi], so it would not be correct to
document this as being exclusive of [hi].
*)
let float =
let rec finite_float state ~lo ~hi =
let range = hi -. lo in
if Float.is_finite range
then (lo +. (unit_float state *. range))
else begin
let mid = (hi +. lo) /. 2. in
if bool state
Depending on rounding , the recursion with [ ~hi : mid ] might be inclusive of [ mid ] ,
which would mean the two cases overlap on [ mid ] . The alternative is to increment
or decrement [ mid ] using [ one_ulp ] in either of the calls , but then if the first
case is exclusive we leave a " gap " between the two ranges . There 's no perfectly
uniform solution , so we use the simpler code that does not call [ one_ulp ] .
which would mean the two cases overlap on [mid]. The alternative is to increment
or decrement [mid] using [one_ulp] in either of the calls, but then if the first
case is exclusive we leave a "gap" between the two ranges. There's no perfectly
uniform solution, so we use the simpler code that does not call [one_ulp]. *)
then finite_float state ~lo ~hi:mid
else finite_float state ~lo:mid ~hi
end
in
fun state ~lo ~hi ->
if not (Float.is_finite lo && Float.is_finite hi)
then begin
raise_s [%message
"float: bounds are not finite numbers"
(lo : float)
(hi : float)]
end;
if Float.( > ) lo hi
then begin
raise_s [%message
"float: bounds are crossed"
(lo : float)
(hi : float)]
end;
finite_float state ~lo ~hi
let%bench_fun "unit_float_from_int64" =
let int64 = 1L in
fun () -> unit_float_from_int64 int64
module Log_uniform = struct
module Make (M : sig include Int.S val uniform : State.t -> lo:t -> hi:t -> t end) : sig
val log_uniform : State.t -> lo:M.t -> hi:M.t -> M.t
end = struct
open M
let bits_to_represent t =
assert (t >= zero);
let t = ref t in
let n = ref 0 in
while !t > zero do
t := shift_right !t 1;
Int.incr n;
done;
!n
let%test_unit "bits_to_represent" =
let test n expect = [%test_result: int] (bits_to_represent n) ~expect in
test (M.of_int_exn 0) 0;
test (M.of_int_exn 1) 1;
test (M.of_int_exn 2) 2;
test (M.of_int_exn 3) 2;
test (M.of_int_exn 4) 3;
test (M.of_int_exn 5) 3;
test (M.of_int_exn 6) 3;
test (M.of_int_exn 7) 3;
test (M.of_int_exn 8) 4;
test (M.of_int_exn 100) 7;
test M.max_value (Int.pred M.num_bits);
;;
let min_represented_by_n_bits n =
if Int.equal n 0
then zero
else shift_left one (Int.pred n)
let%test_unit "min_represented_by_n_bits" =
let test n expect = [%test_result: M.t] (min_represented_by_n_bits n) ~expect in
test 0 (M.of_int_exn 0);
test 1 (M.of_int_exn 1);
test 2 (M.of_int_exn 2);
test 3 (M.of_int_exn 4);
test 4 (M.of_int_exn 8);
test 7 (M.of_int_exn 64);
test (Int.pred M.num_bits) (M.shift_right_logical M.min_value 1);
;;
let max_represented_by_n_bits n =
pred (shift_left one n)
let%test_unit "max_represented_by_n_bits" =
let test n expect = [%test_result: M.t] (max_represented_by_n_bits n) ~expect in
test 0 (M.of_int_exn 0);
test 1 (M.of_int_exn 1);
test 2 (M.of_int_exn 3);
test 3 (M.of_int_exn 7);
test 4 (M.of_int_exn 15);
test 7 (M.of_int_exn 127);
test (Int.pred M.num_bits) M.max_value;
;;
let log_uniform state ~lo ~hi =
let min_bits = bits_to_represent lo in
let max_bits = bits_to_represent hi in
let bits = int state ~lo:min_bits ~hi:max_bits in
uniform state
~lo:(min_represented_by_n_bits bits |> max lo)
~hi:(max_represented_by_n_bits bits |> min hi)
end
module For_int = Make (struct include Int let uniform = int end)
module For_int32 = Make (struct include Int32 let uniform = int32 end)
module For_int63 = Make (struct include Int63 let uniform = int63 end)
module For_int64 = Make (struct include Int64 let uniform = int64 end)
module For_nativeint = Make (struct include Nativeint let uniform = nativeint end)
let int = For_int.log_uniform
let int32 = For_int32.log_uniform
let int63 = For_int63.log_uniform
let int64 = For_int64.log_uniform
let nativeint = For_nativeint.log_uniform
end
|
ce1021b4de3e650946a948c0ab8a19bb04818a15f566b2560eb779076e7eeedb | stevana/hot-swapping-state-machines | Interpreter.hs | {-# LANGUAGE GADTs #-}
module Interpreter where
import StateMachine
------------------------------------------------------------------------
eval1 :: FreeFunc s i o -> (i -> s -> (s, o))
eval1 func i s = case func of
Id -> (s, i)
Compose g f -> let (s', o) = eval1 f i s in eval1 g o s'
Copy -> (s, (i, i))
Consume -> (s, ())
Par f g -> let
(s', o) = eval1 f (fst i) s
(s'', o') = eval1 g (snd i) s'
in
(s'', (o, o'))
Fst -> (s, fst i)
Snd -> (s, snd i)
Inl -> (s, Left i)
Inr -> (s, Right i)
Case f g -> case i of
Left l -> eval1 f l s
Right r -> eval1 g r s
Embed f -> (s, f i)
Get -> (s, s)
Put -> (i, ())
Const k -> (s, k)
Add -> (s, uncurry (+) i)
eval :: FreeFunc s i o -> [i] -> s -> (s, [o])
eval f = go []
where
go acc [] s = (s, reverse acc)
go acc (i : is) s =
let
(s', o) = eval1 f i s
in
go (o : acc) is s'
| null | https://raw.githubusercontent.com/stevana/hot-swapping-state-machines/c00cf5cb962a436aff92a390e39b406f020e438a/src/Interpreter.hs | haskell | # LANGUAGE GADTs #
---------------------------------------------------------------------- |
module Interpreter where
import StateMachine
eval1 :: FreeFunc s i o -> (i -> s -> (s, o))
eval1 func i s = case func of
Id -> (s, i)
Compose g f -> let (s', o) = eval1 f i s in eval1 g o s'
Copy -> (s, (i, i))
Consume -> (s, ())
Par f g -> let
(s', o) = eval1 f (fst i) s
(s'', o') = eval1 g (snd i) s'
in
(s'', (o, o'))
Fst -> (s, fst i)
Snd -> (s, snd i)
Inl -> (s, Left i)
Inr -> (s, Right i)
Case f g -> case i of
Left l -> eval1 f l s
Right r -> eval1 g r s
Embed f -> (s, f i)
Get -> (s, s)
Put -> (i, ())
Const k -> (s, k)
Add -> (s, uncurry (+) i)
eval :: FreeFunc s i o -> [i] -> s -> (s, [o])
eval f = go []
where
go acc [] s = (s, reverse acc)
go acc (i : is) s =
let
(s', o) = eval1 f i s
in
go (o : acc) is s'
|
0a6331f22853c869959b21d94b01bfae7e797e5917a284239a3c2f375196c02b | zkincaid/duet | transition.mli | (** Transition formulas. *)
open Syntax
module type Var = sig
type t
val pp : Format.formatter -> t -> unit
val show : t -> string
val typ : t -> [ `TyInt | `TyReal ]
val compare : t -> t -> int
val symbol_of : t -> symbol
val of_symbol : symbol -> t option
end
module Make
(C : sig
type t
val context : t context
end)
(Var : Var) : sig
* There are two components in the representation of a transition : its { i
transform}and its { i guard } . The transform maps each variable that is
{ i written } during the transition to a term over its input variables .
The guard is a formula that describes the condition under which the
transition may be executed . The set of variables that appear in the
transform or the guard are called the { i footprint } of the
transition .
transform}and its {i guard}. The transform maps each variable that is
{i written} during the transition to a term over its input variables.
The guard is a formula that describes the condition under which the
transition may be executed. The set of variables that appear in the
transform or the guard are called the {i footprint} of the
transition. *)
type t
type var = Var.t
* Test whether two transitions are equal up to logical equivalence and
renaming skolem constants . The input transitions must be normal in the
sense that ( 1 ) the transform only assigns skolem constants to terms
( e.g. , we may have [ x : = x ' ] with guard [ x ' = x + 1 ] , but may not have
[ x : = x + 1 ] ) and ( 2 ) every skolem constant that appears in the guard
also appears in the transform .
renaming skolem constants. The input transitions must be normal in the
sense that (1) the transform only assigns skolem constants to terms
(e.g., we may have [x := x'] with guard [x' = x + 1], but may not have
[x := x + 1]) and (2) every skolem constant that appears in the guard
also appears in the transform. *)
val equal : t -> t -> bool
* Compare is a purely syntactic comparison . Two transitions [ tr ] and
[ tr ' ] can be equivalent ( [ equal tr tr ' = true ] ) but have [ compare tr tr '
! = 0 ] .
[tr'] can be equivalent ([equal tr tr' = true]) but have [compare tr tr'
!= 0]. *)
val compare : t -> t -> int
val pp : Format.formatter -> t -> unit
val show : t -> string
(** Guarded parallel assignment *)
val construct : C.t formula -> (var * C.t arith_term) list -> t
(** [assume phi] is a transition that doesn't modify any variables, but can
only be executed when [phi] holds *)
val assume : C.t formula -> t
(** [assign v t] is a transition that assigns the term [t] to the variable
[v]. *)
val assign : var -> C.t arith_term -> t
(** Parallel assignment of a list of terms to a list of variables.
If a variable appears multiple times as a target for an
assignment, the rightmost assignment is taken. *)
val parallel_assign : (var * C.t arith_term) list -> t
(** Assign a list of variables non-deterministic values. *)
val havoc : var list -> t
* Sequentially compose two transitions .
val mul : t -> t -> t
* Non - deterministically choose between two transitions
val add : t -> t -> t
(** Unexecutable transition (unit of [add]). *)
val zero : t
* Skip ( unit of [ ] ) .
val one : t
* Widen abstracts both input transitions to the Cube abstract
domain , performs the Cube widening operator , and then converts
back to a transition . The resulting transition is normal in the
sense described in [ equal ] .
domain, performs the Cube widening operator, and then converts
back to a transition. The resulting transition is normal in the
sense described in [equal]. *)
val widen : t -> t -> t
(** [exists ex tr] removes the variables that do not satisfy the predicate
[ex] from the footprint of a transition. For example, projecting a
variable [x] out of a transition [tr] is logically equivalent to
[(exists x. tr) && x' = x]. *)
val exists : (var -> bool) -> t -> t
val is_zero : t -> bool
val is_one : t -> bool
(** Is a variable written to in a transition? *)
val mem_transform : var -> t -> bool
* Retrieve the value of a variable after a transition as a term over input
variables ( and constants )
variables (and Skolem constants) *)
val get_transform : var -> t -> C.t arith_term
(** Enumerate the variables and values assigned in a transition. *)
val transform : t -> (var * C.t arith_term) BatEnum.t
(** The condition under which a transition may be executed. *)
val guard : t -> C.t formula
(** Given a path (list of transitions [tr_1 ... tr_n]) and a post-condition
formula, determine whether the path implies the post-condition. If yes,
return a sequence of intermediate assertions [phi_1 ... phi_n] that
support the proof (for each [i], [{ phi_{i-1} } tr_i { phi_i }] holds,
where [phi_0] is [true] and [phi_n] implies the post-condition). *)
val interpolate : t list -> C.t formula -> [ `Valid of C.t formula list
| `Invalid
| `Unknown ]
* Given a pre - condition [ P ] , a path [ path ] , and a post - condition [ Q ] ,
determine whether the Hoare triple [ { P}path{Q } ] is valid .
determine whether the Hoare triple [{P}path{Q}] is valid. *)
val valid_triple : C.t formula -> t list -> C.t formula -> [ `Valid
| `Invalid
| `Unknown ]
val defines : t -> var list
val uses : t -> var list
val abstract_post : (C.t,'abs) SrkApron.property -> t -> (C.t,'abs) SrkApron.property
(** Compute a representation of a transition as a transition formula. *)
val to_transition_formula : t -> C.t TransitionFormula.t
val domain : (module Iteration.PreDomain) ref
val star : t -> t
val linearize : t -> t
end
| null | https://raw.githubusercontent.com/zkincaid/duet/d204e01acc3662477abe664e8c24ce4e8abc73e9/srk/src/transition.mli | ocaml | * Transition formulas.
* Guarded parallel assignment
* [assume phi] is a transition that doesn't modify any variables, but can
only be executed when [phi] holds
* [assign v t] is a transition that assigns the term [t] to the variable
[v].
* Parallel assignment of a list of terms to a list of variables.
If a variable appears multiple times as a target for an
assignment, the rightmost assignment is taken.
* Assign a list of variables non-deterministic values.
* Unexecutable transition (unit of [add]).
* [exists ex tr] removes the variables that do not satisfy the predicate
[ex] from the footprint of a transition. For example, projecting a
variable [x] out of a transition [tr] is logically equivalent to
[(exists x. tr) && x' = x].
* Is a variable written to in a transition?
* Enumerate the variables and values assigned in a transition.
* The condition under which a transition may be executed.
* Given a path (list of transitions [tr_1 ... tr_n]) and a post-condition
formula, determine whether the path implies the post-condition. If yes,
return a sequence of intermediate assertions [phi_1 ... phi_n] that
support the proof (for each [i], [{ phi_{i-1} } tr_i { phi_i }] holds,
where [phi_0] is [true] and [phi_n] implies the post-condition).
* Compute a representation of a transition as a transition formula. | open Syntax
module type Var = sig
type t
val pp : Format.formatter -> t -> unit
val show : t -> string
val typ : t -> [ `TyInt | `TyReal ]
val compare : t -> t -> int
val symbol_of : t -> symbol
val of_symbol : symbol -> t option
end
module Make
(C : sig
type t
val context : t context
end)
(Var : Var) : sig
* There are two components in the representation of a transition : its { i
transform}and its { i guard } . The transform maps each variable that is
{ i written } during the transition to a term over its input variables .
The guard is a formula that describes the condition under which the
transition may be executed . The set of variables that appear in the
transform or the guard are called the { i footprint } of the
transition .
transform}and its {i guard}. The transform maps each variable that is
{i written} during the transition to a term over its input variables.
The guard is a formula that describes the condition under which the
transition may be executed. The set of variables that appear in the
transform or the guard are called the {i footprint} of the
transition. *)
type t
type var = Var.t
* Test whether two transitions are equal up to logical equivalence and
renaming skolem constants . The input transitions must be normal in the
sense that ( 1 ) the transform only assigns skolem constants to terms
( e.g. , we may have [ x : = x ' ] with guard [ x ' = x + 1 ] , but may not have
[ x : = x + 1 ] ) and ( 2 ) every skolem constant that appears in the guard
also appears in the transform .
renaming skolem constants. The input transitions must be normal in the
sense that (1) the transform only assigns skolem constants to terms
(e.g., we may have [x := x'] with guard [x' = x + 1], but may not have
[x := x + 1]) and (2) every skolem constant that appears in the guard
also appears in the transform. *)
val equal : t -> t -> bool
* Compare is a purely syntactic comparison . Two transitions [ tr ] and
[ tr ' ] can be equivalent ( [ equal tr tr ' = true ] ) but have [ compare tr tr '
! = 0 ] .
[tr'] can be equivalent ([equal tr tr' = true]) but have [compare tr tr'
!= 0]. *)
val compare : t -> t -> int
val pp : Format.formatter -> t -> unit
val show : t -> string
val construct : C.t formula -> (var * C.t arith_term) list -> t
val assume : C.t formula -> t
val assign : var -> C.t arith_term -> t
val parallel_assign : (var * C.t arith_term) list -> t
val havoc : var list -> t
* Sequentially compose two transitions .
val mul : t -> t -> t
* Non - deterministically choose between two transitions
val add : t -> t -> t
val zero : t
* Skip ( unit of [ ] ) .
val one : t
* Widen abstracts both input transitions to the Cube abstract
domain , performs the Cube widening operator , and then converts
back to a transition . The resulting transition is normal in the
sense described in [ equal ] .
domain, performs the Cube widening operator, and then converts
back to a transition. The resulting transition is normal in the
sense described in [equal]. *)
val widen : t -> t -> t
val exists : (var -> bool) -> t -> t
val is_zero : t -> bool
val is_one : t -> bool
val mem_transform : var -> t -> bool
* Retrieve the value of a variable after a transition as a term over input
variables ( and constants )
variables (and Skolem constants) *)
val get_transform : var -> t -> C.t arith_term
val transform : t -> (var * C.t arith_term) BatEnum.t
val guard : t -> C.t formula
val interpolate : t list -> C.t formula -> [ `Valid of C.t formula list
| `Invalid
| `Unknown ]
* Given a pre - condition [ P ] , a path [ path ] , and a post - condition [ Q ] ,
determine whether the Hoare triple [ { P}path{Q } ] is valid .
determine whether the Hoare triple [{P}path{Q}] is valid. *)
val valid_triple : C.t formula -> t list -> C.t formula -> [ `Valid
| `Invalid
| `Unknown ]
val defines : t -> var list
val uses : t -> var list
val abstract_post : (C.t,'abs) SrkApron.property -> t -> (C.t,'abs) SrkApron.property
val to_transition_formula : t -> C.t TransitionFormula.t
val domain : (module Iteration.PreDomain) ref
val star : t -> t
val linearize : t -> t
end
|
1fc80e2686149ec6b5d706dc990a4d25112309d04a8a40913aa6f7c97050da7f | larrychristensen/orcpub | weapons.cljc | (ns orcpub.dnd.e5.weapons
(:require [orcpub.common :as common]))
(def weapons
[{:name "Crossbow, light",
::damage-type :piercing,
::damage-die 8,
::type :simple,
::damage-die-count 1,
::ranged? true,
::range {::min 80, ::max 320},
:key :crossbow-light
::two-handed? true
::ammunition? true
::link ""}
{::ranged? true,
:key :dart,
:name "Dart",
::damage-die-count 1,
::type :simple,
::damage-type :piercing,
::thrown true,
::finesse? true,
::damage-die 4,
::range {::min 20, ::max 60}
::link "(missile)"}
{:name "Shortbow",
::damage-type :piercing,
::damage-die 6,
::type :simple,
::damage-die-count 1,
::ranged? true,
::range {::min 80, ::max 320},
:key :shortbow
::two-handed? true
::ammunition? true
::link ""}
{:name "Sling",
::damage-type :bludgeoning,
::damage-die 4,
::type :simple,
::damage-die-count 1,
::ranged? true,
::range {::min 30, ::max 120},
:key :sling
::ammunition? true
::link "(weapon)"}
{:name "Club",
::damage-type :bludgeoning,
::damage-die 4,
::damage-die-count 1,
::type :simple,
::melee? true,
::light? true
:key :club
::link "(weapon)"}
{::melee? true,
:key :dagger,
:name "Dagger",
::damage-die-count 1,
::type :simple,
::damage-type :piercing,
::thrown true,
::finesse? true,
::damage-die 4,
::light? true
::range {::min 20, ::max 60}
::link ""}
{:name "Greatclub",
::damage-type :bludgeoning,
::damage-die 8,
::damage-die-count 1,
::type :simple,
::melee? true,
:key :greatclub
::two-handed? true
::link "(weapon)"}
{:name "Handaxe",
::damage-type :slashing,
::damage-die 6,
::damage-die-count 1,
::type :simple,
::melee? true,
::thrown true,
::range {::min 20, ::max 60},
:key :handaxe
::light? true
::link ""}
{:name "Javelin",
::damage-type :piercing,
::damage-die 6,
::damage-die-count 1,
::type :simple,
::melee? true,
::thrown true,
::range {::min 30, ::max 120},
:key :javelin
::link ""}
{:name "Light hammer",
::damage-type :bludgeoning,
::damage-die 4,
::damage-die-count 1,
::type :simple,
::melee? true,
::thrown true,
::range {::min 20, ::max 60},
:key :light-hammer
::light? true
::link ""}
{:name "Mace",
::damage-type :bludgeoning,
::type :simple,
::damage-die 6,
::damage-die-count 1,
::melee? true,
:key :mace
::link "(weapon)"}
{:name "Quarterstaff",
::damage-type :bludgeoning,
::type :simple,
::damage-die 6,
::damage-die-count 1,
::versatile {::damage-die 8, ::damage-die-count 1},
::melee? true,
:key :quarterstaff
::link ""}
{:name "Sickle",
::damage-type :slashing,
::damage-die 4,
::type :simple,
::damage-die-count 1,
::melee? true,
:key :sickle
::link ""}
{::melee? true,
::versatile {::damage-die 8, ::damage-die-count 1},
:key :spear,
:name "Spear",
::damage-die-count 1,
::type :simple,
::damage-type :piercing,
::thrown true,
::damage-die 6,
::range {::min 20, ::max 60}
::link ""}
{:name "Battleaxe",
::damage-type :slashing,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::versatile {::damage-die 10, ::damage-die-count 1},
::melee? true,
:key :battleaxe
::link ""}
{:name "Flail",
::damage-type :bludgeoning,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::melee? true,
:key :flail
::link "(weapon)"}
{:name "Glaive",
::damage-type :slashing,
::damage-die 10,
::type :martial,
::damage-die-count 1,
::melee? true,
::heavy? true,
::reach true,
:key :glaive
::two-handed? true
::link ""}
{:name "Greataxe",
::damage-type :slashing,
::damage-die 12,
::type :martial,
::subtype :axe
::damage-die-count 1,
::heavy? true,
::melee? true,
:key :greataxe
::two-handed? true
::link ""}
{:name "Greatsword",
::subtype :sword
::damage-type :slashing,
::damage-die 6,
::type :martial,
::damage-die-count 2,
::heavy? true,
::melee? true,
:key :greatsword
::two-handed? true
::link ""}
{:name "Halberd",
::damage-type :slashing,
::damage-die 10,
::type :martial,
::damage-die-count 1,
::melee? true,
::heavy? true,
::reach true,
:key :halberd
::two-handed? true
::link ""}
{:name "Lance",
::damage-type :piercing,
::damage-die 12,
::type :martial,
::damage-die-count 1,
::melee? true,
::reach true,
:key :lance
::special? true
::link ""}
{:name "Longsword",
::damage-type :slashing,
::damage-die 8,
::type :martial,
::subtype :sword
::damage-die-count 1,
::versatile {::damage-die 10, ::damage-die-count 1},
::melee? true,
:key :longsword
::link ""}
{:name "Maul",
::damage-type :bludgeoning,
::damage-die 6,
::type :martial,
::damage-die-count 2,
::heavy? true,
::melee? true,
:key :maul
::two-handed? true
::link ""}
{:name "Morningstar",
::damage-type :piercing,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::melee? true,
:key :morningstar
::link "(weapon)"}
{:name "Pike",
::damage-type :piercing,
::damage-die 10,
::type :martial,
::damage-die-count 1,
::melee? true,
::heavy? true,
::reach true,
:key :pike
::two-handed? true
::link "(weapon)"}
{:name "Rapier",
::damage-type :piercing,
::damage-die 8,
::type :martial,
::subtype :sword
::damage-die-count 1,
::finesse? true,
::melee? true,
:key :rapier
::link ""}
{:name "Scimitar",
::damage-type :slashing,
::damage-die 6,
::type :martial,
::subtype :sword
::damage-die-count 1,
::finesse? true,
::melee? true,
:key :scimitar
::light? true
::link ""}
{:name "Shortsword",
::damage-type :piercing,
::damage-die 6,
::type :martial,
::subtype :sword
::finesse? true,
::damage-die-count 1,
::melee? true,
:key :shortsword
::light? true
::link ""}
{::melee? true,
::versatile {::damage-die 8, ::damage-die-count 1},
:key :trident,
:name "Trident",
::damage-die-count 1,
::type :martial,
::damage-type :piercing,
::thrown true,
::damage-die 6,
::range {::min 20, ::max 60}
::link ""}
{:name "War pick",
::damage-type :piercing,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::melee? true,
:key :war-pick}
{:name "Warhammer",
::damage-type :bludgeoning,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::versatile {::damage-die 10, ::damage-die-count 1},
::melee? true,
:key :warhammer
::link ""}
{:name "Whip",
::damage-type :slashing,
::damage-die 4,
::type :martial,
::damage-die-count 1,
::melee? true,
::finesse? true,
::reach true,
:key :whip}
{:name "Blowgun",
::damage-type :piercing,
::damage-die 1,
::type :martial,
::damage-die-count 1,
::ranged? true,
::range {::min 25, ::max 100},
::ammunition? true
:key :blowgun}
{:name "Crossbow, hand",
::damage-type :piercing,
::damage-die 6,
::type :martial,
::damage-die-count 1,
::ranged? true,
::range {::min 30, ::max 120},
::ammunition? true
::light? true
:key :crossbow-hand}
{:name "Crossbow, heavy",
::damage-type :piercing,
::damage-die 10,
::type :martial,
::damage-die-count 1,
::ranged? true,
::heavy? true,
::range {::min 100, ::max 400},
:key :crossbow-heavy
::ammunition? true
::two-handed? true}
{:name "Thunder Cannon",
::damage-type :piercing,
::damage-die 6,
::type ::special
::damage-die-count 2,
::ranged? true,
::range {::min 150, ::max 500},
:key :thunder-cannon
::two-handed? true}
{:name "Longbow",
::damage-type :piercing,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::ranged? true,
::heavy? true,
::range {::min 150, ::max 600},
:key :longbow
::two-handed? true}
{:name "Net",
::type :martial,
::ranged? true,
::thrown true,
::range {::min 5, ::max 15},
:key :net
::special? true}])
(def ammunition
(common/add-keys
[{:name "Arrow" ::type :ammunition :sell-qty 20 :cost {:num 1 :type :gp} :weight "1 lb."}
{:name "Blowgun needle" ::type :ammunition :sell-qty 50 :cost {:num 1 :type :gp} :weight "1 lb."}
{:name "Crossbow bolt" ::type :ammunition :sell-qty 20 :cost {:num 1 :type :gp} :weight "1½ lb."}
{:name "Sling bullet" ::type :ammunition :sell-qty 20 :cost {:num 4 :type :cp} :weight "1½ lb."}]))
(def weapons-map
(zipmap (map :key weapons) weapons))
(defn weapons-of-type [weapons type]
(filter #(= type (::type %)) weapons))
(defn martial-weapons [weapons]
(weapons-of-type weapons :martial))
(defn simple-weapons [weapons]
(weapons-of-type weapons :simple))
(defn light-melee-weapon? [{:keys [::light? ::melee?]}]
(and melee? light?))
(defn one-handed-weapon? [{:keys [::two-handed?]}]
(not two-handed?))
| null | https://raw.githubusercontent.com/larrychristensen/orcpub/e83995857f7e64af1798009a45a0b03abcd3a4be/src/cljc/orcpub/dnd/e5/weapons.cljc | clojure | (ns orcpub.dnd.e5.weapons
(:require [orcpub.common :as common]))
(def weapons
[{:name "Crossbow, light",
::damage-type :piercing,
::damage-die 8,
::type :simple,
::damage-die-count 1,
::ranged? true,
::range {::min 80, ::max 320},
:key :crossbow-light
::two-handed? true
::ammunition? true
::link ""}
{::ranged? true,
:key :dart,
:name "Dart",
::damage-die-count 1,
::type :simple,
::damage-type :piercing,
::thrown true,
::finesse? true,
::damage-die 4,
::range {::min 20, ::max 60}
::link "(missile)"}
{:name "Shortbow",
::damage-type :piercing,
::damage-die 6,
::type :simple,
::damage-die-count 1,
::ranged? true,
::range {::min 80, ::max 320},
:key :shortbow
::two-handed? true
::ammunition? true
::link ""}
{:name "Sling",
::damage-type :bludgeoning,
::damage-die 4,
::type :simple,
::damage-die-count 1,
::ranged? true,
::range {::min 30, ::max 120},
:key :sling
::ammunition? true
::link "(weapon)"}
{:name "Club",
::damage-type :bludgeoning,
::damage-die 4,
::damage-die-count 1,
::type :simple,
::melee? true,
::light? true
:key :club
::link "(weapon)"}
{::melee? true,
:key :dagger,
:name "Dagger",
::damage-die-count 1,
::type :simple,
::damage-type :piercing,
::thrown true,
::finesse? true,
::damage-die 4,
::light? true
::range {::min 20, ::max 60}
::link ""}
{:name "Greatclub",
::damage-type :bludgeoning,
::damage-die 8,
::damage-die-count 1,
::type :simple,
::melee? true,
:key :greatclub
::two-handed? true
::link "(weapon)"}
{:name "Handaxe",
::damage-type :slashing,
::damage-die 6,
::damage-die-count 1,
::type :simple,
::melee? true,
::thrown true,
::range {::min 20, ::max 60},
:key :handaxe
::light? true
::link ""}
{:name "Javelin",
::damage-type :piercing,
::damage-die 6,
::damage-die-count 1,
::type :simple,
::melee? true,
::thrown true,
::range {::min 30, ::max 120},
:key :javelin
::link ""}
{:name "Light hammer",
::damage-type :bludgeoning,
::damage-die 4,
::damage-die-count 1,
::type :simple,
::melee? true,
::thrown true,
::range {::min 20, ::max 60},
:key :light-hammer
::light? true
::link ""}
{:name "Mace",
::damage-type :bludgeoning,
::type :simple,
::damage-die 6,
::damage-die-count 1,
::melee? true,
:key :mace
::link "(weapon)"}
{:name "Quarterstaff",
::damage-type :bludgeoning,
::type :simple,
::damage-die 6,
::damage-die-count 1,
::versatile {::damage-die 8, ::damage-die-count 1},
::melee? true,
:key :quarterstaff
::link ""}
{:name "Sickle",
::damage-type :slashing,
::damage-die 4,
::type :simple,
::damage-die-count 1,
::melee? true,
:key :sickle
::link ""}
{::melee? true,
::versatile {::damage-die 8, ::damage-die-count 1},
:key :spear,
:name "Spear",
::damage-die-count 1,
::type :simple,
::damage-type :piercing,
::thrown true,
::damage-die 6,
::range {::min 20, ::max 60}
::link ""}
{:name "Battleaxe",
::damage-type :slashing,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::versatile {::damage-die 10, ::damage-die-count 1},
::melee? true,
:key :battleaxe
::link ""}
{:name "Flail",
::damage-type :bludgeoning,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::melee? true,
:key :flail
::link "(weapon)"}
{:name "Glaive",
::damage-type :slashing,
::damage-die 10,
::type :martial,
::damage-die-count 1,
::melee? true,
::heavy? true,
::reach true,
:key :glaive
::two-handed? true
::link ""}
{:name "Greataxe",
::damage-type :slashing,
::damage-die 12,
::type :martial,
::subtype :axe
::damage-die-count 1,
::heavy? true,
::melee? true,
:key :greataxe
::two-handed? true
::link ""}
{:name "Greatsword",
::subtype :sword
::damage-type :slashing,
::damage-die 6,
::type :martial,
::damage-die-count 2,
::heavy? true,
::melee? true,
:key :greatsword
::two-handed? true
::link ""}
{:name "Halberd",
::damage-type :slashing,
::damage-die 10,
::type :martial,
::damage-die-count 1,
::melee? true,
::heavy? true,
::reach true,
:key :halberd
::two-handed? true
::link ""}
{:name "Lance",
::damage-type :piercing,
::damage-die 12,
::type :martial,
::damage-die-count 1,
::melee? true,
::reach true,
:key :lance
::special? true
::link ""}
{:name "Longsword",
::damage-type :slashing,
::damage-die 8,
::type :martial,
::subtype :sword
::damage-die-count 1,
::versatile {::damage-die 10, ::damage-die-count 1},
::melee? true,
:key :longsword
::link ""}
{:name "Maul",
::damage-type :bludgeoning,
::damage-die 6,
::type :martial,
::damage-die-count 2,
::heavy? true,
::melee? true,
:key :maul
::two-handed? true
::link ""}
{:name "Morningstar",
::damage-type :piercing,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::melee? true,
:key :morningstar
::link "(weapon)"}
{:name "Pike",
::damage-type :piercing,
::damage-die 10,
::type :martial,
::damage-die-count 1,
::melee? true,
::heavy? true,
::reach true,
:key :pike
::two-handed? true
::link "(weapon)"}
{:name "Rapier",
::damage-type :piercing,
::damage-die 8,
::type :martial,
::subtype :sword
::damage-die-count 1,
::finesse? true,
::melee? true,
:key :rapier
::link ""}
{:name "Scimitar",
::damage-type :slashing,
::damage-die 6,
::type :martial,
::subtype :sword
::damage-die-count 1,
::finesse? true,
::melee? true,
:key :scimitar
::light? true
::link ""}
{:name "Shortsword",
::damage-type :piercing,
::damage-die 6,
::type :martial,
::subtype :sword
::finesse? true,
::damage-die-count 1,
::melee? true,
:key :shortsword
::light? true
::link ""}
{::melee? true,
::versatile {::damage-die 8, ::damage-die-count 1},
:key :trident,
:name "Trident",
::damage-die-count 1,
::type :martial,
::damage-type :piercing,
::thrown true,
::damage-die 6,
::range {::min 20, ::max 60}
::link ""}
{:name "War pick",
::damage-type :piercing,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::melee? true,
:key :war-pick}
{:name "Warhammer",
::damage-type :bludgeoning,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::versatile {::damage-die 10, ::damage-die-count 1},
::melee? true,
:key :warhammer
::link ""}
{:name "Whip",
::damage-type :slashing,
::damage-die 4,
::type :martial,
::damage-die-count 1,
::melee? true,
::finesse? true,
::reach true,
:key :whip}
{:name "Blowgun",
::damage-type :piercing,
::damage-die 1,
::type :martial,
::damage-die-count 1,
::ranged? true,
::range {::min 25, ::max 100},
::ammunition? true
:key :blowgun}
{:name "Crossbow, hand",
::damage-type :piercing,
::damage-die 6,
::type :martial,
::damage-die-count 1,
::ranged? true,
::range {::min 30, ::max 120},
::ammunition? true
::light? true
:key :crossbow-hand}
{:name "Crossbow, heavy",
::damage-type :piercing,
::damage-die 10,
::type :martial,
::damage-die-count 1,
::ranged? true,
::heavy? true,
::range {::min 100, ::max 400},
:key :crossbow-heavy
::ammunition? true
::two-handed? true}
{:name "Thunder Cannon",
::damage-type :piercing,
::damage-die 6,
::type ::special
::damage-die-count 2,
::ranged? true,
::range {::min 150, ::max 500},
:key :thunder-cannon
::two-handed? true}
{:name "Longbow",
::damage-type :piercing,
::damage-die 8,
::type :martial,
::damage-die-count 1,
::ranged? true,
::heavy? true,
::range {::min 150, ::max 600},
:key :longbow
::two-handed? true}
{:name "Net",
::type :martial,
::ranged? true,
::thrown true,
::range {::min 5, ::max 15},
:key :net
::special? true}])
(def ammunition
(common/add-keys
[{:name "Arrow" ::type :ammunition :sell-qty 20 :cost {:num 1 :type :gp} :weight "1 lb."}
{:name "Blowgun needle" ::type :ammunition :sell-qty 50 :cost {:num 1 :type :gp} :weight "1 lb."}
{:name "Crossbow bolt" ::type :ammunition :sell-qty 20 :cost {:num 1 :type :gp} :weight "1½ lb."}
{:name "Sling bullet" ::type :ammunition :sell-qty 20 :cost {:num 4 :type :cp} :weight "1½ lb."}]))
(def weapons-map
(zipmap (map :key weapons) weapons))
(defn weapons-of-type [weapons type]
(filter #(= type (::type %)) weapons))
(defn martial-weapons [weapons]
(weapons-of-type weapons :martial))
(defn simple-weapons [weapons]
(weapons-of-type weapons :simple))
(defn light-melee-weapon? [{:keys [::light? ::melee?]}]
(and melee? light?))
(defn one-handed-weapon? [{:keys [::two-handed?]}]
(not two-handed?))
| |
e72b942744885f9ddf5722d5d591481a7892f97a5bb4df000284da2ae5437681 | danoctavian/bit-smuggler | Server.hs | {-# LANGUAGE RecordWildCards, TupleSections #-}
module Network.BitSmuggler.Server where
import Prelude as P hiding (read)
import Network.BitSmuggler.Crypto as Crypto
import System.Log.Logger
import Data.Word
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Lazy as BSL
import Data.ByteString as BS
import Control.Monad.IO.Class
import Control.Applicative
import Data.IP
import Control.Monad as CM
import Control.Exception
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import Control.Concurrent.STM.TMVar
import Control.Concurrent.STM.TQueue
import Data.Time.Clock
import Data.Conduit as DC
import Data.Conduit.List as DC
import Data.Serialize as DS
import Data.LargeWord
import Crypto.Random
import Data.Tuple as Tup
import Data.Maybe
import System.Timeout
import Network.BitTorrent.ClientControl
import Network.TCP.Proxy.Server as Proxy hiding (UnsupportedFeature, logger)
import Network.TCP.Proxy.Socks4 as Socks4
import Network.BitSmuggler.Common hiding (contactFiles)
import Network.BitSmuggler.Utils
import Network.BitSmuggler.Protocol
import Network.BitSmuggler.ARQ as ARQ
import Data.Map.Strict as Map
import Data.Set as Set
{-
SERVER.
run single torrent client - running many potentially blows the cover
a normal peer in the bittorrent network runs a single instance of
some torrent client
-}
data ServerConfig = ServerConfig {
serverSecretKey :: Key
, btClientConfig :: BTClientConfig
-- the files on which the server is "listening"
, contactFiles :: [ContactFile]
, fileCachePath :: FilePath
}
data ServerState = ServerState {
activeConns :: Map SessionToken Connection
}
data Connection = Conn {
onHoldSince :: Maybe UTCTime
, handlerTask :: Async ()
, dataPipes :: DataPipes ClientMessage ServerMessage
, pieceProxy :: Async ()
}
--
listen :: ServerConfig -> (ConnData -> IO ()) -> IO ()
listen config handle = runResourceT $ do
liftIO $ debugM logger "started bit-smuggler server..."
let btConf = btClientConfig config
-- start torrent client (with config)
(btProc, btClientConn) <- setupBTClient $ btClientConfig config
-- setup the files on which the client is working in a temp dir
files <- setupContactFiles (contactFiles config) (fileCachePath config)
serverState <- liftIO $ newTVarIO $ ServerState {activeConns = Map.empty}
register $ cleanState serverState
let fileFixer = findPieceLoader files
let onConn = serverConnInit (serverSecretKey config) serverState handle fileFixer
-- setup proxies
(reverseProxy, forwardProxy) <- startProxies (btClientConfig config) onConn
liftIO $ debugM logger "finished initialization"
-- tell bittorrent client to use the files
-- TODO: implement
liftIO $ addTorrents btClientConn (fst btProc) files
-- make sure that when files are used up (they get completed)
-- they are shrinked back to their original size
TODO : reenable this
allocLinkedAsync $ async $ replenishFiles btClientConn ( fst btProc ) files
-- wait for it...
liftIO $ waitBoth (snd reverseProxy) (snd forwardProxy)
return ()
-- server cleanup
cleanState stateVar = do
state <- atomically $ readTVar stateVar
forM (P.map snd $ Map.toList $ activeConns state) $ killConn
return ()
killConn = cancel . handlerTask
serverConnInit secretKey stateVar handleConn fileFix direction local remote = do
pieceHs <- makePieceHooks
liftIO $ debugM logger $ "handling a connection to or from remote address "
P.++ (show remote)
disconnectGate <- newGate
-- don't keep the proxy waiting and fork a worker
-- to handle the connection
forkIO $ handleConnection stateVar pieceHs secretKey handleConn disconnectGate
streams <- fmap (if direction == Reverse then Tup.swap else P.id) $
makeStreams pieceHs fileFix
return $ DataHooks { incoming = P.fst streams
, outgoing = P.snd streams
-- TODO: implement
, onDisconnect = do
debugM logger "!! DISCONNECT"
atomically $ openGate disconnectGate -- signal the disconnect
return ()
}
modActives f s = modifyTVar s (\s -> s {activeConns = f $ activeConns s})
-- TODO: this has become a huge-ass function - please break it down
handleConnection stateVar pieceHs secretKey userHandle disconnectGate = do
-- classify connection
let noarq = noARQ -- there's no ARQ right now
liftIO $ debugM logger $ "waiting for handshake message"
-- a task to forward outgoing pieces without changing them
-- until the initial message stage finishes
kill <- newEmptyTMVarIO
forwardPieces <- async $ forwardUntilKilled (read (sendGetPiece pieceHs))
(write (sendPutBack pieceHs))
kill
wait 5 secs
$ runConduit $ (readSource (liftIO $ atomically $ read $ recvPiece pieceHs))
=$ (recvPipe (recvARQ noarq) $ handshakeDecrypt secretKey) =$ DC.take 1
case maybeFstMsg of
Nothing -> do
-- timedout - just proxy the traffic
-- those threads just suck
debugM logger "turns out it's not a bit-smuggler connection"
drainIncoming <- async $ forever $ atomically $ read $ recvPiece pieceHs
-- wait for the disconnect..
atomically $ goThroughGate disconnectGate
-- kill the threads meant to simply move the outgoing/incoming pieces
cancel drainIncoming
atomically $ putTMVar kill ()
Just [fstClientMessage] -> do
-- stop moving pieces after the connection has been recognized as bitsmuggler
atomically $ putTMVar kill ()
liftIO $ debugM logger $ "received first message from client !"
case fstClientMessage of
(Control (ConnRequest keyRepr Nothing)) -> do
-- client is requesting the creation of a new session
liftIO $ debugM logger $ "client requests new session "
let crypto = makeServerEncryption secretKey keyRepr
initCprg <- liftIO $ makeCPRG
let (token, cprg) = cprgGenerate tokenLen initCprg
let serverEncrypt = encrypter (encrypt crypto) cprg
-- control messages
controlSend <-liftIO $ (newTQueueIO :: IO (TQueue ServerMessage))
controlRecv <- liftIO $ (newTQueueIO :: IO (TQueue ClientMessage))
let controlPipe = Pipe controlRecv controlSend
-- to handle the connection
dataGate <- liftIO $ newGate
-- make some hooks specific to this particular connection
connPieceHooks <- makePieceHooks
let dataPipes = DataPipes controlPipe connPieceHooks dataGate
pieceProxyTask <- async $ runPieceProxy pieceHs connPieceHooks
task <- async $ runResourceT $ do
-- schedule removal when this thread finishes
register $ atomically $ modActives (Map.delete token) stateVar
runConnection packetSize initGoBackNARQ
serverEncrypt (decrypt crypto) token
userHandle dataPipes
atomically $ modActives (Map.insert token
(Conn Nothing task dataPipes pieceProxyTask)) stateVar
-- schedule disconnect cleanup
forkIO $ disconnectCleanup disconnectGate token stateVar
return ()
Control (ConnRequest keyRepr (Just token)) -> do
-- client is requesting session recovery using token
maybeConn <- atomically $ fmap (Map.lookup token . activeConns)
$ readTVar stateVar
case maybeConn of
Just conn -> do
-- TODO: implement session loading
-- hint: use a proxy for incoming and out going bt pieces
debugM logger $ "reloading client session with token " P.++ (show token)
pieceProxyTask <- async $ runPieceProxy pieceHs (pieceHooks $ dataPipes conn)
atomically $ modActives
(Map.adjust (\conn -> conn {pieceProxy = pieceProxyTask}) token)
stateVar
-- schedule disconnect cleanup
forkIO $ disconnectCleanup disconnectGate token stateVar
return ()
Nothing -> do
errorM logger "session token not found"
throwIO ClientProtocolError
_ -> do
errorM logger "The first client message should always be a conn request"
throwIO ClientProtocolError
return ()
runConnection packetSize arq encrypter decrypt token userHandle ps@(DataPipes {..}) = do
user <- launchPipes packetSize arq encrypter decrypt ps
-- reply to handshake
-- accept. we don't discriminate.. for now
liftIO $ debugM logger $ "sending accept message to client"
liftIO $ atomically $ writeTQueue (pipeSend controlPipe) $ AcceptConn token
-- allowing data to flow
liftIO $ atomically $ openGate dataGate
liftIO $ debugM logger $ "running the user conn handler"
-- run conn handler
userResult <- liftIO $ try' (userHandle $ pipeToConnData user)
case userResult of
Left e -> liftIO $ errorM logger "user handle terminated with exception "
Right _ -> liftIO $ debugM logger "user handle terminated gracefully "
-- termination handling
liftIO $ flushMsgQueue (pipeSend user)
return ()
replenishWorkerCount = 2
replenishFiles btClientConn btProc files = runResourceT $ do
jobQueue <- liftIO $ newTQueueIO
setVar <- liftIO $ newTVarIO Set.empty
CM.replicateM replenishWorkerCount $ allocLinkedAsync $ async
$ replenishWorker btClientConn btProc files jobQueue setVar
forever $ do
liftIO $ threadDelay $ 5 * milli
ts <- liftIO $ listTorrents btClientConn
forM ts $ \t -> when (isUsedUp t && noSwarm t) $ do
let ih = torrentID t
liftIO $ atomically $ do
underWork <- fmap (Set.member ih) $ readTVar setVar
when (not underWork) $ modifyTVar setVar (Set.insert ih) >> writeTQueue jobQueue ih
replenishWorker btClientConn btProc files jobQueue underWork = forever $ do
infoHash <- atomically $ readTQueue jobQueue
replenishFile btClientConn btProc files infoHash
-- once it's done it's no longer under work
atomically $ modifyTVar underWork (Set.delete infoHash)
disconnectCleanup disconnectGate token stateVar = do
-- wait at the gate till the disconnect is signalled
atomically $ goThroughGate disconnectGate
now <- getCurrentTime
maybeConn <- atomically $ do
modActives (Map.adjust (\conn -> conn {onHoldSince = Just now}) token) stateVar
state <- readTVar stateVar
return $ Map.lookup token . activeConns $ state
case maybeConn of
(Just conn) -> cancel $ pieceProxy conn -- stop the piece proxy
Nothing -> return () -- it's just not there anymore
handshakeDecrypt sk bs = fmap P.snd $ tryReadHandshake sk $ bs
-- this proxy runs on every connect until disconnect
-- it terminates when its thread is killed off
runPieceProxy src dest = runResourceT $ do
-- clear up any leftover in the putback var
liftIO $ atomically $ tryRead (sendPutBack dest)
r <- runProxy recvPiece src dest
sg <- runProxy sendGetPiece src dest
sp <-runProxy sendPutBack dest src -- put back goes in the reverse direction
forM (P.map snd [r, sg, sp]) $ liftIO . wait -- just block
return ()
runProxy op src dest =
allocLinkedAsync $ async $ forever $ (atomically $ read (op src))
>>= (atomically . write (op dest))
forwardUntilKilled read write kill = do
res <- atomically $ (fmap Left $ takeTMVar kill) `orElse` (fmap Right read)
case res of
Left () -> return () -- terminate now
Right v -> (atomically $ write v) >> forwardUntilKilled read write kill
| null | https://raw.githubusercontent.com/danoctavian/bit-smuggler/4385ed67f1fec4ed441832fc9a119de632b796aa/BitSmuggler/src/Network/BitSmuggler/Server.hs | haskell | # LANGUAGE RecordWildCards, TupleSections #
SERVER.
run single torrent client - running many potentially blows the cover
a normal peer in the bittorrent network runs a single instance of
some torrent client
the files on which the server is "listening"
start torrent client (with config)
setup the files on which the client is working in a temp dir
setup proxies
tell bittorrent client to use the files
TODO: implement
make sure that when files are used up (they get completed)
they are shrinked back to their original size
wait for it...
server cleanup
don't keep the proxy waiting and fork a worker
to handle the connection
TODO: implement
signal the disconnect
TODO: this has become a huge-ass function - please break it down
classify connection
there's no ARQ right now
a task to forward outgoing pieces without changing them
until the initial message stage finishes
timedout - just proxy the traffic
those threads just suck
wait for the disconnect..
kill the threads meant to simply move the outgoing/incoming pieces
stop moving pieces after the connection has been recognized as bitsmuggler
client is requesting the creation of a new session
control messages
to handle the connection
make some hooks specific to this particular connection
schedule removal when this thread finishes
schedule disconnect cleanup
client is requesting session recovery using token
TODO: implement session loading
hint: use a proxy for incoming and out going bt pieces
schedule disconnect cleanup
reply to handshake
accept. we don't discriminate.. for now
allowing data to flow
run conn handler
termination handling
once it's done it's no longer under work
wait at the gate till the disconnect is signalled
stop the piece proxy
it's just not there anymore
this proxy runs on every connect until disconnect
it terminates when its thread is killed off
clear up any leftover in the putback var
put back goes in the reverse direction
just block
terminate now | module Network.BitSmuggler.Server where
import Prelude as P hiding (read)
import Network.BitSmuggler.Crypto as Crypto
import System.Log.Logger
import Data.Word
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Lazy as BSL
import Data.ByteString as BS
import Control.Monad.IO.Class
import Control.Applicative
import Data.IP
import Control.Monad as CM
import Control.Exception
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import Control.Concurrent.STM.TMVar
import Control.Concurrent.STM.TQueue
import Data.Time.Clock
import Data.Conduit as DC
import Data.Conduit.List as DC
import Data.Serialize as DS
import Data.LargeWord
import Crypto.Random
import Data.Tuple as Tup
import Data.Maybe
import System.Timeout
import Network.BitTorrent.ClientControl
import Network.TCP.Proxy.Server as Proxy hiding (UnsupportedFeature, logger)
import Network.TCP.Proxy.Socks4 as Socks4
import Network.BitSmuggler.Common hiding (contactFiles)
import Network.BitSmuggler.Utils
import Network.BitSmuggler.Protocol
import Network.BitSmuggler.ARQ as ARQ
import Data.Map.Strict as Map
import Data.Set as Set
data ServerConfig = ServerConfig {
serverSecretKey :: Key
, btClientConfig :: BTClientConfig
, contactFiles :: [ContactFile]
, fileCachePath :: FilePath
}
data ServerState = ServerState {
activeConns :: Map SessionToken Connection
}
data Connection = Conn {
onHoldSince :: Maybe UTCTime
, handlerTask :: Async ()
, dataPipes :: DataPipes ClientMessage ServerMessage
, pieceProxy :: Async ()
}
listen :: ServerConfig -> (ConnData -> IO ()) -> IO ()
listen config handle = runResourceT $ do
liftIO $ debugM logger "started bit-smuggler server..."
let btConf = btClientConfig config
(btProc, btClientConn) <- setupBTClient $ btClientConfig config
files <- setupContactFiles (contactFiles config) (fileCachePath config)
serverState <- liftIO $ newTVarIO $ ServerState {activeConns = Map.empty}
register $ cleanState serverState
let fileFixer = findPieceLoader files
let onConn = serverConnInit (serverSecretKey config) serverState handle fileFixer
(reverseProxy, forwardProxy) <- startProxies (btClientConfig config) onConn
liftIO $ debugM logger "finished initialization"
liftIO $ addTorrents btClientConn (fst btProc) files
TODO : reenable this
allocLinkedAsync $ async $ replenishFiles btClientConn ( fst btProc ) files
liftIO $ waitBoth (snd reverseProxy) (snd forwardProxy)
return ()
cleanState stateVar = do
state <- atomically $ readTVar stateVar
forM (P.map snd $ Map.toList $ activeConns state) $ killConn
return ()
killConn = cancel . handlerTask
serverConnInit secretKey stateVar handleConn fileFix direction local remote = do
pieceHs <- makePieceHooks
liftIO $ debugM logger $ "handling a connection to or from remote address "
P.++ (show remote)
disconnectGate <- newGate
forkIO $ handleConnection stateVar pieceHs secretKey handleConn disconnectGate
streams <- fmap (if direction == Reverse then Tup.swap else P.id) $
makeStreams pieceHs fileFix
return $ DataHooks { incoming = P.fst streams
, outgoing = P.snd streams
, onDisconnect = do
debugM logger "!! DISCONNECT"
return ()
}
modActives f s = modifyTVar s (\s -> s {activeConns = f $ activeConns s})
handleConnection stateVar pieceHs secretKey userHandle disconnectGate = do
liftIO $ debugM logger $ "waiting for handshake message"
kill <- newEmptyTMVarIO
forwardPieces <- async $ forwardUntilKilled (read (sendGetPiece pieceHs))
(write (sendPutBack pieceHs))
kill
wait 5 secs
$ runConduit $ (readSource (liftIO $ atomically $ read $ recvPiece pieceHs))
=$ (recvPipe (recvARQ noarq) $ handshakeDecrypt secretKey) =$ DC.take 1
case maybeFstMsg of
Nothing -> do
debugM logger "turns out it's not a bit-smuggler connection"
drainIncoming <- async $ forever $ atomically $ read $ recvPiece pieceHs
atomically $ goThroughGate disconnectGate
cancel drainIncoming
atomically $ putTMVar kill ()
Just [fstClientMessage] -> do
atomically $ putTMVar kill ()
liftIO $ debugM logger $ "received first message from client !"
case fstClientMessage of
(Control (ConnRequest keyRepr Nothing)) -> do
liftIO $ debugM logger $ "client requests new session "
let crypto = makeServerEncryption secretKey keyRepr
initCprg <- liftIO $ makeCPRG
let (token, cprg) = cprgGenerate tokenLen initCprg
let serverEncrypt = encrypter (encrypt crypto) cprg
controlSend <-liftIO $ (newTQueueIO :: IO (TQueue ServerMessage))
controlRecv <- liftIO $ (newTQueueIO :: IO (TQueue ClientMessage))
let controlPipe = Pipe controlRecv controlSend
dataGate <- liftIO $ newGate
connPieceHooks <- makePieceHooks
let dataPipes = DataPipes controlPipe connPieceHooks dataGate
pieceProxyTask <- async $ runPieceProxy pieceHs connPieceHooks
task <- async $ runResourceT $ do
register $ atomically $ modActives (Map.delete token) stateVar
runConnection packetSize initGoBackNARQ
serverEncrypt (decrypt crypto) token
userHandle dataPipes
atomically $ modActives (Map.insert token
(Conn Nothing task dataPipes pieceProxyTask)) stateVar
forkIO $ disconnectCleanup disconnectGate token stateVar
return ()
Control (ConnRequest keyRepr (Just token)) -> do
maybeConn <- atomically $ fmap (Map.lookup token . activeConns)
$ readTVar stateVar
case maybeConn of
Just conn -> do
debugM logger $ "reloading client session with token " P.++ (show token)
pieceProxyTask <- async $ runPieceProxy pieceHs (pieceHooks $ dataPipes conn)
atomically $ modActives
(Map.adjust (\conn -> conn {pieceProxy = pieceProxyTask}) token)
stateVar
forkIO $ disconnectCleanup disconnectGate token stateVar
return ()
Nothing -> do
errorM logger "session token not found"
throwIO ClientProtocolError
_ -> do
errorM logger "The first client message should always be a conn request"
throwIO ClientProtocolError
return ()
runConnection packetSize arq encrypter decrypt token userHandle ps@(DataPipes {..}) = do
user <- launchPipes packetSize arq encrypter decrypt ps
liftIO $ debugM logger $ "sending accept message to client"
liftIO $ atomically $ writeTQueue (pipeSend controlPipe) $ AcceptConn token
liftIO $ atomically $ openGate dataGate
liftIO $ debugM logger $ "running the user conn handler"
userResult <- liftIO $ try' (userHandle $ pipeToConnData user)
case userResult of
Left e -> liftIO $ errorM logger "user handle terminated with exception "
Right _ -> liftIO $ debugM logger "user handle terminated gracefully "
liftIO $ flushMsgQueue (pipeSend user)
return ()
replenishWorkerCount = 2
replenishFiles btClientConn btProc files = runResourceT $ do
jobQueue <- liftIO $ newTQueueIO
setVar <- liftIO $ newTVarIO Set.empty
CM.replicateM replenishWorkerCount $ allocLinkedAsync $ async
$ replenishWorker btClientConn btProc files jobQueue setVar
forever $ do
liftIO $ threadDelay $ 5 * milli
ts <- liftIO $ listTorrents btClientConn
forM ts $ \t -> when (isUsedUp t && noSwarm t) $ do
let ih = torrentID t
liftIO $ atomically $ do
underWork <- fmap (Set.member ih) $ readTVar setVar
when (not underWork) $ modifyTVar setVar (Set.insert ih) >> writeTQueue jobQueue ih
replenishWorker btClientConn btProc files jobQueue underWork = forever $ do
infoHash <- atomically $ readTQueue jobQueue
replenishFile btClientConn btProc files infoHash
atomically $ modifyTVar underWork (Set.delete infoHash)
disconnectCleanup disconnectGate token stateVar = do
atomically $ goThroughGate disconnectGate
now <- getCurrentTime
maybeConn <- atomically $ do
modActives (Map.adjust (\conn -> conn {onHoldSince = Just now}) token) stateVar
state <- readTVar stateVar
return $ Map.lookup token . activeConns $ state
case maybeConn of
handshakeDecrypt sk bs = fmap P.snd $ tryReadHandshake sk $ bs
runPieceProxy src dest = runResourceT $ do
liftIO $ atomically $ tryRead (sendPutBack dest)
r <- runProxy recvPiece src dest
sg <- runProxy sendGetPiece src dest
return ()
runProxy op src dest =
allocLinkedAsync $ async $ forever $ (atomically $ read (op src))
>>= (atomically . write (op dest))
forwardUntilKilled read write kill = do
res <- atomically $ (fmap Left $ takeTMVar kill) `orElse` (fmap Right read)
case res of
Right v -> (atomically $ write v) >> forwardUntilKilled read write kill
|
909a46db5ffab29601fe95dab053a45d9465598b29cf6238b7dd4f8639eeceb0 | clojure-interop/google-cloud-clients | core.clj | (ns core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.google.cloud.spanner.core])
(require '[com.google.cloud.spanner.admin.database.v1.core])
(require '[com.google.cloud.spanner.admin.database.v1.stub.core])
(require '[com.google.cloud.spanner.admin.instance.v1.core])
(require '[com.google.cloud.spanner.admin.instance.v1.stub.core])
(require '[com.google.cloud.spanner.spi.core])
(require '[com.google.cloud.spanner.spi.v1.core])
(require '[com.google.cloud.spanner.testing.core])
(require '[com.google.cloud.spanner.v1.core])
(require '[com.google.cloud.spanner.v1.stub.core])
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.spanner/src/core.clj | clojure | (ns core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.google.cloud.spanner.core])
(require '[com.google.cloud.spanner.admin.database.v1.core])
(require '[com.google.cloud.spanner.admin.database.v1.stub.core])
(require '[com.google.cloud.spanner.admin.instance.v1.core])
(require '[com.google.cloud.spanner.admin.instance.v1.stub.core])
(require '[com.google.cloud.spanner.spi.core])
(require '[com.google.cloud.spanner.spi.v1.core])
(require '[com.google.cloud.spanner.testing.core])
(require '[com.google.cloud.spanner.v1.core])
(require '[com.google.cloud.spanner.v1.stub.core])
| |
445f0ef548e4256ed3e76bbd806a44fb2f36364a00eacf19bc4b98cd7531fa5d | hopv/MoCHi | BRA_state.ml | open BRA_types
let rec default_val t = {Syntax.desc = default_val' t; Syntax.typ = t; attr=[]}
and default_val' =
let open Syntax in
let open Type in function
| TBase TUnit -> Const Unit
| TBase TBool -> Const False
| TBase TInt -> Const (Int 0)
| TBase (TPrim _) -> invalid_arg "default_val: not yet implemented syntax(TPrim)"
| TFun ({Id.typ = t1}, t2) -> Fun (Id.new_var ~name:"_" t1, default_val t2)
| TAttr(_, typ) -> default_val' typ
| TData _ -> invalid_arg "default_val: not yet implemented syntax(TData)"
| TApp _ -> invalid_arg "default_val: not yet implemented syntax(TApp)"
| TTuple _ -> invalid_arg "default_val: not yet implemented syntax(TTuple)"
| TVar(t,_) ->
begin
match !t with
| None -> raise (Invalid_argument "default_val: not yet implemented syntax(TVar None)")
| Some t' -> default_val' t'
end
| TFuns _ -> invalid_arg "default_val: not yet implemented syntax(TFuns)"
| TRecord _ -> invalid_arg "default_val: not yet implemented syntax(TRecord)"
| TVariant _ -> invalid_arg "default_val: not yet implemented syntax(TVariant)"
| TModule _ -> invalid_arg "default_val: not yet implemented syntax(TModule)"
let state_transducer trans_prev_statevar trans_statevar trans_argvars state =
{state with
prev_statevars = trans_prev_statevar state.prev_statevars
; statevars = trans_statevar state.statevars
; argvars = trans_argvars state.argvars}
let is_basetype_variable = function
| {Syntax.typ = Type.TFun (_, _)} -> false
| _ -> true
(* remove variables of functional type *)
let remove_functional_vars = state_transducer (List.filter is_basetype_variable) (List.filter is_basetype_variable) (List.filter is_basetype_variable)
let filter_non_integer =
let is_integer = function
| {Syntax.typ = Type.TBase Type.TInt} -> true
| _ -> false
in
state_transducer (List.filter is_integer) (List.filter is_integer) (List.filter is_integer)
let build_var name typ = Term_util.make_var (Id.new_var ~name typ)
let make_prev_statevar_name function_name baseId = "s_prev_" ^ function_name ^ "_" ^ baseId.Id.name
let make_prev_statevar_id function_name baseId = Id.new_var ~name:(make_prev_statevar_name function_name baseId) baseId.Id.typ
let make_prev_statevar function_name baseId = build_var (make_prev_statevar_name function_name baseId) baseId.Id.typ
let make_statevar_name function_name baseId = "s_" ^ function_name ^ "_" ^ baseId.Id.name
let make_statevar_id function_name baseId = Id.new_var ~name:(make_statevar_name function_name baseId) baseId.Id.typ
let make_statevar function_name baseId = build_var (make_statevar_name function_name baseId) baseId.Id.typ
let build_record {id = {Id.name = f_name}; args = f_args} =
let open Type in
let record =
ref { update_flag = build_var "update_flag" Ty.bool
; set_flag = build_var ("set_flag_" ^ f_name) Ty.bool
; prev_set_flag = build_var ("prev_set_flag_" ^ f_name) Ty.bool
; prev_statevars = List.map (make_prev_statevar f_name) f_args
; statevars = List.map (make_statevar f_name) f_args
; argvars = List.map Term_util.make_var f_args
} in
let _ = record := filter_non_integer !record in
!record
let build_state function_infos target =
{ initial_state = Term_util.false_term :: List.map (fun {Syntax.typ = t} -> default_val t) (build_record target).argvars
; statetable = List.fold_left (fun map function_info -> InnerState.add function_info.id (build_record function_info) map) InnerState.empty function_infos
}
let get_update_flag state f = (InnerState.find f.id state.statetable).update_flag
let get_set_flag state f = (InnerState.find f.id state.statetable).set_flag
let get_prev_set_flag state f = (InnerState.find f.id state.statetable).prev_set_flag
let get_prev_statevars state f = (InnerState.find f.id state.statetable).prev_statevars
let get_statevars state f = (InnerState.find f.id state.statetable).statevars
let get_argvars state f = (InnerState.find f.id state.statetable).argvars
let passed_statevars {BRA_types.verified = verified; BRA_types.state = state} f =
let table = InnerState.find verified.id state.statetable in
if f = verified.id then
table.prev_set_flag :: table.prev_statevars
else
table.set_flag :: table.statevars
let propagated_statevars {BRA_types.verified = verified; BRA_types.state = state} =
let table = InnerState.find verified.id state.statetable in
table.set_flag :: table.statevars
let find_state {BRA_types.state = state} f = InnerState.find f.id state.statetable
let type_of_state {BRA_types.state = {BRA_types.initial_state = inits}} = List.map (fun {Syntax.typ = t} -> t) inits
| null | https://raw.githubusercontent.com/hopv/MoCHi/b0ac0d626d64b1e3c779d8e98cb232121cc3196a/src/BRA_state.ml | ocaml | remove variables of functional type | open BRA_types
let rec default_val t = {Syntax.desc = default_val' t; Syntax.typ = t; attr=[]}
and default_val' =
let open Syntax in
let open Type in function
| TBase TUnit -> Const Unit
| TBase TBool -> Const False
| TBase TInt -> Const (Int 0)
| TBase (TPrim _) -> invalid_arg "default_val: not yet implemented syntax(TPrim)"
| TFun ({Id.typ = t1}, t2) -> Fun (Id.new_var ~name:"_" t1, default_val t2)
| TAttr(_, typ) -> default_val' typ
| TData _ -> invalid_arg "default_val: not yet implemented syntax(TData)"
| TApp _ -> invalid_arg "default_val: not yet implemented syntax(TApp)"
| TTuple _ -> invalid_arg "default_val: not yet implemented syntax(TTuple)"
| TVar(t,_) ->
begin
match !t with
| None -> raise (Invalid_argument "default_val: not yet implemented syntax(TVar None)")
| Some t' -> default_val' t'
end
| TFuns _ -> invalid_arg "default_val: not yet implemented syntax(TFuns)"
| TRecord _ -> invalid_arg "default_val: not yet implemented syntax(TRecord)"
| TVariant _ -> invalid_arg "default_val: not yet implemented syntax(TVariant)"
| TModule _ -> invalid_arg "default_val: not yet implemented syntax(TModule)"
let state_transducer trans_prev_statevar trans_statevar trans_argvars state =
{state with
prev_statevars = trans_prev_statevar state.prev_statevars
; statevars = trans_statevar state.statevars
; argvars = trans_argvars state.argvars}
let is_basetype_variable = function
| {Syntax.typ = Type.TFun (_, _)} -> false
| _ -> true
let remove_functional_vars = state_transducer (List.filter is_basetype_variable) (List.filter is_basetype_variable) (List.filter is_basetype_variable)
let filter_non_integer =
let is_integer = function
| {Syntax.typ = Type.TBase Type.TInt} -> true
| _ -> false
in
state_transducer (List.filter is_integer) (List.filter is_integer) (List.filter is_integer)
let build_var name typ = Term_util.make_var (Id.new_var ~name typ)
let make_prev_statevar_name function_name baseId = "s_prev_" ^ function_name ^ "_" ^ baseId.Id.name
let make_prev_statevar_id function_name baseId = Id.new_var ~name:(make_prev_statevar_name function_name baseId) baseId.Id.typ
let make_prev_statevar function_name baseId = build_var (make_prev_statevar_name function_name baseId) baseId.Id.typ
let make_statevar_name function_name baseId = "s_" ^ function_name ^ "_" ^ baseId.Id.name
let make_statevar_id function_name baseId = Id.new_var ~name:(make_statevar_name function_name baseId) baseId.Id.typ
let make_statevar function_name baseId = build_var (make_statevar_name function_name baseId) baseId.Id.typ
let build_record {id = {Id.name = f_name}; args = f_args} =
let open Type in
let record =
ref { update_flag = build_var "update_flag" Ty.bool
; set_flag = build_var ("set_flag_" ^ f_name) Ty.bool
; prev_set_flag = build_var ("prev_set_flag_" ^ f_name) Ty.bool
; prev_statevars = List.map (make_prev_statevar f_name) f_args
; statevars = List.map (make_statevar f_name) f_args
; argvars = List.map Term_util.make_var f_args
} in
let _ = record := filter_non_integer !record in
!record
let build_state function_infos target =
{ initial_state = Term_util.false_term :: List.map (fun {Syntax.typ = t} -> default_val t) (build_record target).argvars
; statetable = List.fold_left (fun map function_info -> InnerState.add function_info.id (build_record function_info) map) InnerState.empty function_infos
}
let get_update_flag state f = (InnerState.find f.id state.statetable).update_flag
let get_set_flag state f = (InnerState.find f.id state.statetable).set_flag
let get_prev_set_flag state f = (InnerState.find f.id state.statetable).prev_set_flag
let get_prev_statevars state f = (InnerState.find f.id state.statetable).prev_statevars
let get_statevars state f = (InnerState.find f.id state.statetable).statevars
let get_argvars state f = (InnerState.find f.id state.statetable).argvars
let passed_statevars {BRA_types.verified = verified; BRA_types.state = state} f =
let table = InnerState.find verified.id state.statetable in
if f = verified.id then
table.prev_set_flag :: table.prev_statevars
else
table.set_flag :: table.statevars
let propagated_statevars {BRA_types.verified = verified; BRA_types.state = state} =
let table = InnerState.find verified.id state.statetable in
table.set_flag :: table.statevars
let find_state {BRA_types.state = state} f = InnerState.find f.id state.statetable
let type_of_state {BRA_types.state = {BRA_types.initial_state = inits}} = List.map (fun {Syntax.typ = t} -> t) inits
|
1f79f0c4b121b1e95c6cdecbbe500becabb56ff8135d64d393aa9954d8a668ee | haskell-opengl/GLUT | BezMesh.hs |
( adapted from bezmesh.c which is ( c ) Silicon Graphics , Inc )
Copyright ( c ) 2002 - 2018 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
This program renders a lighted , filled surface , using two - dimensional
evaluators .
BezMesh.hs (adapted from bezmesh.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2018 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program renders a lighted, filled Bezier surface, using two-dimensional
evaluators.
-}
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Data.List ( transpose )
import Graphics.UI.GLUT
ctrlPoints :: [[Vertex3 GLfloat]]
ctrlPoints = [
[ Vertex3 (-1.5) (-1.5) 4.0, Vertex3 (-0.5) (-1.5) 2.0,
Vertex3 0.5 (-1.5) (-1.0), Vertex3 1.5 (-1.5) 2.0 ],
[ Vertex3 (-1.5) (-0.5) 1.0, Vertex3 (-0.5) (-0.5) 3.0,
Vertex3 0.5 (-0.5) 0.0, Vertex3 1.5 (-0.5) (-1.0) ],
[ Vertex3 (-1.5) 0.5 4.0, Vertex3 (-0.5) 0.5 0.0,
Vertex3 0.5 0.5 3.0, Vertex3 1.5 0.5 4.0 ],
[ Vertex3 (-1.5) 1.5 (-2.0), Vertex3 (-0.5) 1.5 (-2.0),
Vertex3 0.5 1.5 0.0, Vertex3 1.5 1.5 (-1.0) ]]
initlights :: IO ()
initlights = do
lighting $= Enabled
light (Light 0) $= Enabled
ambient (Light 0) $= Color4 0.2 0.2 0.2 1.0
position (Light 0) $= Vertex4 0 0 2 1
materialDiffuse Front $= Color4 0.6 0.6 0.6 1.0
materialSpecular Front $= Color4 1.0 1.0 1.0 1.0
materialShininess Front $= 50
display :: DisplayCallback
display = do
clear [ ColorBuffer, DepthBuffer ]
preservingMatrix $ do
rotate (85 :: GLfloat) (Vector3 1 1 1)
evalMesh2 Fill (0, 20) (0, 20)
flush
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
depthFunc $= Just Less
m <- newMap2 (0, 1) (0, 1) (transpose ctrlPoints)
map2 $= Just (m :: GLmap2 Vertex3 GLfloat)
autoNormal $= Enabled
mapGrid2 $= ((20, (0, 1)), (20, (0, 1 :: GLfloat)))
initlights -- for lighted version only
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
let wf = fromIntegral w
hf = fromIntegral h
if w <= h
then ortho (-4.0) 4.0 (-4.0*hf/wf) (4.0*hf/wf) (-4.0) 4.0
else ortho (-4.0*wf/hf) (4.0*wf/hf) (-4.0) 4.0 (-4.0) 4.0
matrixMode $= Modelview 0
loadIdentity
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ]
initialWindowSize $= Size 500 500
initialWindowPosition $= Position 100 100
_ <- createWindow progName
myInit
reshapeCallback $= Just reshape
displayCallback $= display
keyboardMouseCallback $= Just keyboard
mainLoop
| null | https://raw.githubusercontent.com/haskell-opengl/GLUT/36207fa51e4c1ea1e5512aeaa373198a4a56cad0/examples/RedBook4/BezMesh.hs | haskell | for lighted version only |
( adapted from bezmesh.c which is ( c ) Silicon Graphics , Inc )
Copyright ( c ) 2002 - 2018 < >
This file is part of HOpenGL and distributed under a BSD - style license
See the file libraries / GLUT / LICENSE
This program renders a lighted , filled surface , using two - dimensional
evaluators .
BezMesh.hs (adapted from bezmesh.c which is (c) Silicon Graphics, Inc)
Copyright (c) Sven Panne 2002-2018 <>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
This program renders a lighted, filled Bezier surface, using two-dimensional
evaluators.
-}
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import Data.List ( transpose )
import Graphics.UI.GLUT
ctrlPoints :: [[Vertex3 GLfloat]]
ctrlPoints = [
[ Vertex3 (-1.5) (-1.5) 4.0, Vertex3 (-0.5) (-1.5) 2.0,
Vertex3 0.5 (-1.5) (-1.0), Vertex3 1.5 (-1.5) 2.0 ],
[ Vertex3 (-1.5) (-0.5) 1.0, Vertex3 (-0.5) (-0.5) 3.0,
Vertex3 0.5 (-0.5) 0.0, Vertex3 1.5 (-0.5) (-1.0) ],
[ Vertex3 (-1.5) 0.5 4.0, Vertex3 (-0.5) 0.5 0.0,
Vertex3 0.5 0.5 3.0, Vertex3 1.5 0.5 4.0 ],
[ Vertex3 (-1.5) 1.5 (-2.0), Vertex3 (-0.5) 1.5 (-2.0),
Vertex3 0.5 1.5 0.0, Vertex3 1.5 1.5 (-1.0) ]]
initlights :: IO ()
initlights = do
lighting $= Enabled
light (Light 0) $= Enabled
ambient (Light 0) $= Color4 0.2 0.2 0.2 1.0
position (Light 0) $= Vertex4 0 0 2 1
materialDiffuse Front $= Color4 0.6 0.6 0.6 1.0
materialSpecular Front $= Color4 1.0 1.0 1.0 1.0
materialShininess Front $= 50
display :: DisplayCallback
display = do
clear [ ColorBuffer, DepthBuffer ]
preservingMatrix $ do
rotate (85 :: GLfloat) (Vector3 1 1 1)
evalMesh2 Fill (0, 20) (0, 20)
flush
myInit :: IO ()
myInit = do
clearColor $= Color4 0 0 0 0
depthFunc $= Just Less
m <- newMap2 (0, 1) (0, 1) (transpose ctrlPoints)
map2 $= Just (m :: GLmap2 Vertex3 GLfloat)
autoNormal $= Enabled
mapGrid2 $= ((20, (0, 1)), (20, (0, 1 :: GLfloat)))
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
let wf = fromIntegral w
hf = fromIntegral h
if w <= h
then ortho (-4.0) 4.0 (-4.0*hf/wf) (4.0*hf/wf) (-4.0) 4.0
else ortho (-4.0*wf/hf) (4.0*wf/hf) (-4.0) 4.0 (-4.0) 4.0
matrixMode $= Modelview 0
loadIdentity
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
main :: IO ()
main = do
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ]
initialWindowSize $= Size 500 500
initialWindowPosition $= Position 100 100
_ <- createWindow progName
myInit
reshapeCallback $= Just reshape
displayCallback $= display
keyboardMouseCallback $= Just keyboard
mainLoop
|
1994bae3674563b659b0c7d9d869180c77e5a2b46e830fec0d10f33697a34ea9 | PureIso/ErlangCodes | server_supervisor.erl | %% Copyright
-module(server_supervisor).
-author("LAB314").
%% Supervisor restarts the process that fails
-behaviour(supervisor).
%% API
-export([start_link_shell/0,start_link/0]).
%% supervisor
-export([init/1]).
%%% convenience method for startup
start_link_shell() ->
%%% supervisor process is linked to the shell process.
%%% When gen_server process crashes the exit signal is propagated
%%% up to the shell which crashes and get restarted.
{ok, Pid} = supervisor:start_link({global, ?MODULE}, ?MODULE, []),
unlink(Pid).
start_link() ->
supervisor:start_link({global,?MODULE}, ?MODULE, []).
%%% supervisor callback
init([]) ->
process_flag(trap_exit, true),
%%% supervisor:which_children(server_supervisor).
%%% supervisor:terminate_child(server_supervisor,serverId).
io:format("~p (~p) starting...~n", [{global,?MODULE}, self()]),
If MaxRestarts restarts occur in MaxSecondsBetweenRestarts seconds
%%% supervisor and child processes are killed
RestartStrategy = one_for_one,
3 restart within
five seconds
Flags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
%%% permanent - always restart
%%% temporary - never restart
%%% transient - restart if abnormally ends
Restart = permanent,
%%%brutal_kill - use exit(Child, kill) to terminate
%%%integer - use exit(Child, shutdown) - milliseconds
Shutdown = infinity,
%%% worker
%%% supervisor
Type = worker,
%% Modules ones supervisor uses
{ ChildId , { StartFunc - { module , function , arg } , Restart , Shutdown , Type , Modules } .
Server = {serverId, {server, start_link, []},
Restart, Shutdown, Type, [server]},
tuple of restart strategy , max restart and max time
%%% child specification
{ok, {Flags, [Server]}}. | null | https://raw.githubusercontent.com/PureIso/ErlangCodes/20066f54079946fcb469dde975d79e8923e8ed96/gen_server/src/server_supervisor.erl | erlang | Copyright
Supervisor restarts the process that fails
API
supervisor
convenience method for startup
supervisor process is linked to the shell process.
When gen_server process crashes the exit signal is propagated
up to the shell which crashes and get restarted.
supervisor callback
supervisor:which_children(server_supervisor).
supervisor:terminate_child(server_supervisor,serverId).
supervisor and child processes are killed
permanent - always restart
temporary - never restart
transient - restart if abnormally ends
brutal_kill - use exit(Child, kill) to terminate
integer - use exit(Child, shutdown) - milliseconds
worker
supervisor
Modules ones supervisor uses
child specification | -module(server_supervisor).
-author("LAB314").
-behaviour(supervisor).
-export([start_link_shell/0,start_link/0]).
-export([init/1]).
start_link_shell() ->
{ok, Pid} = supervisor:start_link({global, ?MODULE}, ?MODULE, []),
unlink(Pid).
start_link() ->
supervisor:start_link({global,?MODULE}, ?MODULE, []).
init([]) ->
process_flag(trap_exit, true),
io:format("~p (~p) starting...~n", [{global,?MODULE}, self()]),
If MaxRestarts restarts occur in MaxSecondsBetweenRestarts seconds
RestartStrategy = one_for_one,
3 restart within
five seconds
Flags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
Restart = permanent,
Shutdown = infinity,
Type = worker,
{ ChildId , { StartFunc - { module , function , arg } , Restart , Shutdown , Type , Modules } .
Server = {serverId, {server, start_link, []},
Restart, Shutdown, Type, [server]},
tuple of restart strategy , max restart and max time
{ok, {Flags, [Server]}}. |
908e69ee2d471161aa4876c80a58cbedae88c62b74b65d22f88dda26ccd2d567 | henrygarner/glittering | pregel.clj | (ns glittering.pregel
(:require [glittering.core :as g]
[t6.from-scala.core :refer [$] :as $])
(:import [org.apache.spark.graphx EdgeDirection]))
(defn pregel [{:keys [initial-message max-iterations
vertex-fn message-fn combiner
direction]
:or {direction :either
max-iterations Long/MAX_VALUE}}
g]
(let [dir (g/edge-directions direction)
g (if initial-message
(g/map-vertices
(fn [vid attr] (vertex-fn vid attr initial-message)) g)
g)]
(loop [g g
messages (g/aggregate-messages message-fn combiner g)
i 0]
(if (and (> (.count messages) 0)
(< i max-iterations))
(let [new-verts (.cache (g/inner-join vertex-fn messages (g/vertices g)))
old-g g
g (.cache (g/outer-join-vertices (fn [vid old new-opt]
(or new-opt old))
new-verts g))
old-messages messages
messages (.cache (g/aggregate-messages message-fn combiner g))]
#_(println "Pregel iteration: " i "messages count: " (.count messages))
(.count messages) ;; We must realise the messages
(.unpersist old-messages false)
(.unpersist new-verts false)
(.unpersistVertices old-g false)
(.unpersist (g/edges old-g) false)
(recur g messages (inc i)))
g))))
| null | https://raw.githubusercontent.com/henrygarner/glittering/09ec9b6e29ae92154ec2421e86ce380c90d7b90f/src/clojure/glittering/pregel.clj | clojure | We must realise the messages | (ns glittering.pregel
(:require [glittering.core :as g]
[t6.from-scala.core :refer [$] :as $])
(:import [org.apache.spark.graphx EdgeDirection]))
(defn pregel [{:keys [initial-message max-iterations
vertex-fn message-fn combiner
direction]
:or {direction :either
max-iterations Long/MAX_VALUE}}
g]
(let [dir (g/edge-directions direction)
g (if initial-message
(g/map-vertices
(fn [vid attr] (vertex-fn vid attr initial-message)) g)
g)]
(loop [g g
messages (g/aggregate-messages message-fn combiner g)
i 0]
(if (and (> (.count messages) 0)
(< i max-iterations))
(let [new-verts (.cache (g/inner-join vertex-fn messages (g/vertices g)))
old-g g
g (.cache (g/outer-join-vertices (fn [vid old new-opt]
(or new-opt old))
new-verts g))
old-messages messages
messages (.cache (g/aggregate-messages message-fn combiner g))]
#_(println "Pregel iteration: " i "messages count: " (.count messages))
(.unpersist old-messages false)
(.unpersist new-verts false)
(.unpersistVertices old-g false)
(.unpersist (g/edges old-g) false)
(recur g messages (inc i)))
g))))
|
963d43a148fb01d09b87537a482e2292f579330cecc1a33184d96fbc622522fb | bomberstudios/mtasc | swfZip.ml |
* This file is part of SwfLib
* Copyright ( c)2004
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 2 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* This file is part of SwfLib
* Copyright (c)2004 Nicolas Cannasse
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
let inflate i =
IO.input_string (Extc.unzip (IO.read_all i))
let deflate o =
let buf = Buffer.create 0 in
let flush() =
let data = Buffer.contents buf in
IO.nwrite o (Extc.zip data);
IO.flush o;
Buffer.reset buf;
in
IO.create_out
~write:(Buffer.add_char buf)
~output:(fun s p l -> Buffer.add_substring buf s p l; l)
~flush
~close:(fun () -> flush(); IO.close_out o)
;;
Swf.__inflate := inflate;
Swf.__deflate := deflate; | null | https://raw.githubusercontent.com/bomberstudios/mtasc/d7c2441310248776aa89d60f9c8f98d539bfe8de/src/swflib/swfZip.ml | ocaml |
* This file is part of SwfLib
* Copyright ( c)2004
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 2 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* This file is part of SwfLib
* Copyright (c)2004 Nicolas Cannasse
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
let inflate i =
IO.input_string (Extc.unzip (IO.read_all i))
let deflate o =
let buf = Buffer.create 0 in
let flush() =
let data = Buffer.contents buf in
IO.nwrite o (Extc.zip data);
IO.flush o;
Buffer.reset buf;
in
IO.create_out
~write:(Buffer.add_char buf)
~output:(fun s p l -> Buffer.add_substring buf s p l; l)
~flush
~close:(fun () -> flush(); IO.close_out o)
;;
Swf.__inflate := inflate;
Swf.__deflate := deflate; | |
9f09c17a7cf75e624f4d600356768843e5632970a7da80a2984a85f58b4e3e6e | dinosaure/ocaml-maildir | maildir_unix.ml | module IO : Maildir.IO with type +'a t = 'a = struct
type +'a t = 'a
let bind v f = f v
let map f v = f v
let return v = v
let (>>=) = bind
let (>>|) v f = map f v
end
module FS : Maildir.FS
with type +'a io = 'a IO.t
and type t = unit
and type key = Fpath.t = struct
type key = Fpath.t
type t = unit
type +'a io = 'a IO.t
let mtime () path =
let unix_path = Fpath.to_string path in
let stat = Unix.stat unix_path in
Int64.of_float stat.Unix.st_mtime
let fold () path computation acc =
match Bos.OS.Dir.fold_contents
~elements:`Files computation acc path with
| Ok v -> v
| Error (`Msg err) ->
Fmt.epr "Retrieve an error when we want to scan %a: %s.\n%!"
Fpath.pp path err ;
Fmt.invalid_arg "%s" err
let rename () a b =
match Bos.OS.Path.move ~force:true a b with
| Ok v -> v
| Error _ -> assert false (* should never occur. *)
let remove () path =
match Bos.OS.File.delete path with
| Ok v -> v
| Error (`Msg err) ->
Fmt.epr "Retrieve an error when we remove %a: %s.\n%!"
Fpath.pp path err
let exists () path =
match Bos.OS.Path.exists path with
| Ok v -> v
| Error (`Msg err) ->
Fmt.epr "Retrieve an error when we want to access to %a: %s.\n%!"
Fpath.pp path err ;
Fmt.invalid_arg "%s" err
end
module Maildir = Maildir.Make (IO) (FS)
type fs = FS.t
let fs : fs = ()
let transmit () a b =
let input rd buf =
let rec go () = match rd () with
| Some (raw, off, len) ->
Buffer.add_subbytes buf raw off len ; go ()
| None -> Buffer.contents buf in
go ()
in
let output wr (raw, chunk) : (int, _) result =
let len = String.length raw in
let rec go pos =
if pos < len
then let len' = min (len - pos) chunk in
wr (Some (Bytes.unsafe_of_string raw, pos, len')) ; go (pos + len')
else ( wr None ; Ok pos ) in
go 0
in
let buf = Buffer.create 0x800 in
let open Rresult.R in
Bos.OS.File.with_input a input buf >>= fun contents ->
Bos.OS.File.with_output b output (contents, 0x100) >>= function
| Ok write ->
Buffer.clear buf ;
Fmt.epr "Transmit %d byte(s) from %a to %a.\n%!" write Fpath.pp a Fpath.pp b ;
Ok ()
| Error _ -> assert false
include Maildir
| null | https://raw.githubusercontent.com/dinosaure/ocaml-maildir/8b408f35854d1be5d15f09413a11c104d6438058/lib-unix/maildir_unix.ml | ocaml | should never occur. | module IO : Maildir.IO with type +'a t = 'a = struct
type +'a t = 'a
let bind v f = f v
let map f v = f v
let return v = v
let (>>=) = bind
let (>>|) v f = map f v
end
module FS : Maildir.FS
with type +'a io = 'a IO.t
and type t = unit
and type key = Fpath.t = struct
type key = Fpath.t
type t = unit
type +'a io = 'a IO.t
let mtime () path =
let unix_path = Fpath.to_string path in
let stat = Unix.stat unix_path in
Int64.of_float stat.Unix.st_mtime
let fold () path computation acc =
match Bos.OS.Dir.fold_contents
~elements:`Files computation acc path with
| Ok v -> v
| Error (`Msg err) ->
Fmt.epr "Retrieve an error when we want to scan %a: %s.\n%!"
Fpath.pp path err ;
Fmt.invalid_arg "%s" err
let rename () a b =
match Bos.OS.Path.move ~force:true a b with
| Ok v -> v
let remove () path =
match Bos.OS.File.delete path with
| Ok v -> v
| Error (`Msg err) ->
Fmt.epr "Retrieve an error when we remove %a: %s.\n%!"
Fpath.pp path err
let exists () path =
match Bos.OS.Path.exists path with
| Ok v -> v
| Error (`Msg err) ->
Fmt.epr "Retrieve an error when we want to access to %a: %s.\n%!"
Fpath.pp path err ;
Fmt.invalid_arg "%s" err
end
module Maildir = Maildir.Make (IO) (FS)
type fs = FS.t
let fs : fs = ()
let transmit () a b =
let input rd buf =
let rec go () = match rd () with
| Some (raw, off, len) ->
Buffer.add_subbytes buf raw off len ; go ()
| None -> Buffer.contents buf in
go ()
in
let output wr (raw, chunk) : (int, _) result =
let len = String.length raw in
let rec go pos =
if pos < len
then let len' = min (len - pos) chunk in
wr (Some (Bytes.unsafe_of_string raw, pos, len')) ; go (pos + len')
else ( wr None ; Ok pos ) in
go 0
in
let buf = Buffer.create 0x800 in
let open Rresult.R in
Bos.OS.File.with_input a input buf >>= fun contents ->
Bos.OS.File.with_output b output (contents, 0x100) >>= function
| Ok write ->
Buffer.clear buf ;
Fmt.epr "Transmit %d byte(s) from %a to %a.\n%!" write Fpath.pp a Fpath.pp b ;
Ok ()
| Error _ -> assert false
include Maildir
|
854d0168d07e39473a4f7969cf8a79f76c2d21a81fd64aaab7d1ac81b9307d96 | songyahui/AlgebraicEffect | files.ml |
effect Open : int
effect Close : int -> unit
let open_file ()
(*@ requires _^* @*)
(*@ ensures Open @*)
= perform Open
let close_file s
(*@ requires (_^* ) .Open . ((~Close)^* ) @*)
(*@ ensures Close(s) @*)
= perform (Close s)
let file ()
(*@ requires emp @*)
(*@ ensures Open.Close @*)
= let fd = open_file () in
let fd = open_file () in
close_file fd
let main ()
(*@ requires emp @*)
(*@ ensures Open.Close @*)
=
match file () with
| r -> ()
| effect (Close s1) k ->
continue k ()
| effect Open k ->
continue k 1
let file1 ()
(*@ requires emp @*)
(*@ ensures _^* @*)
= let fd = open_file () in
let fd = open_file () in
close_file fd
let file2 ()
(*@ requires emp @*)
(*@ ensures _^* @*)
= let fd = open_file () in
close_file fd
(* fails as expected *)
(* ; close_file fd *)
let file3 ()
(*@ requires emp @*)
(*@ ensures _^* @*)
= let fd = open_file () in
let fd = open_file () in
close_file fd
(* fails? *)
(* ; close_file fd *)
(* but this is ok *)
let file4 ()
(*@ requires emp @*)
(*@ ensures _^* @*)
= let fd = open_file () in
close_file fd;
let fd = open_file () in
close_file fd
| null | https://raw.githubusercontent.com/songyahui/AlgebraicEffect/27688952b598a101a27523be796e8011d70b02de/src/programs.t/files.ml | ocaml | @ requires _^* @
@ ensures Open @
@ requires (_^* ) .Open . ((~Close)^* ) @
@ ensures Close(s) @
@ requires emp @
@ ensures Open.Close @
@ requires emp @
@ ensures Open.Close @
@ requires emp @
@ ensures _^* @
@ requires emp @
@ ensures _^* @
fails as expected
; close_file fd
@ requires emp @
@ ensures _^* @
fails?
; close_file fd
but this is ok
@ requires emp @
@ ensures _^* @ |
effect Open : int
effect Close : int -> unit
let open_file ()
= perform Open
let close_file s
= perform (Close s)
let file ()
= let fd = open_file () in
let fd = open_file () in
close_file fd
let main ()
=
match file () with
| r -> ()
| effect (Close s1) k ->
continue k ()
| effect Open k ->
continue k 1
let file1 ()
= let fd = open_file () in
let fd = open_file () in
close_file fd
let file2 ()
= let fd = open_file () in
close_file fd
let file3 ()
= let fd = open_file () in
let fd = open_file () in
close_file fd
let file4 ()
= let fd = open_file () in
close_file fd;
let fd = open_file () in
close_file fd
|
ecdf5dab25c07a6afe4c174fcdb2db4c1f13cdb73c7516ced38429243c7a571a | skanev/playground | 03.scm | EOPL exercise 2.03
;
; Define a representation of all the integers (negative and nonnegative) as
; diff-trees, where a diff-tree is a list defined by the grammar
;
Diff - tree : : = ( one ) | ( diff Diff - tree Diff - tree )
;
The list ( one ) represents 1 . If t₁ represents n₁ and t₂ represents n₂ , then
( diff t₁ t₂ ) is a representation of n₁ - n₂.
;
So both ( one ) and ( diff ( one ) ( diff ( one ) ( one ) ) ) are representations of 1 ;
; (diff (diff (one) (one)) (one)) is a representation of -1.
;
1 . Show that every number has infinitely many representations in this
; system.
2 . Turn this representation of the integers into an implementation by
writing zero , is - zero ? , successor and predecessor , as specified on
page 32 , except that now the negative integers are also represented . Your
; procedures should take as input any of the multiple legal representations
; of an integer in this scheme. For example, if your successor procedure is
given any of the infinitely many legal representations of 1 , it should
produce one of the legal representations of 2 . It is permissible for
different legal representations of 1 to yield different representations
of 2 .
3 . Write a proedure diff - tree - plus that does addition in this
; representation. Your procedure should be optimized for the diff-tree
; representation, and should do its work in a constant amount of time
; (independent of the size of its inputs). In particular, it should not be
; recursive.
1 . It 's rather obvious that a number has infinitelly many representations .
;
Anyway , if n is represented as ( diff M S ) , then we can also represent it as
; (diff (diff M (one)) (diff S (one))). It will be the same number. We can
; apply this infinitely many times. This is not the only way to modify the
; representation of the number, but it is the simplest.
;
2 . Let 's take a nice layered approach .
;
First , here are constructors for the representation :
(define (one) '(one))
(define (diff left right) `(diff ,left ,right))
; Here are some observers:
(define (one? diff-tree) (eqv? (car diff-tree) 'one))
(define (diff? diff-tree) (eqv? (car diff-tree) 'diff))
(define (diff-first diff-tree) (cadr diff-tree))
(define (diff-second diff-tree) (caddr diff-tree))
; Here are a few higher-level observers minuend and subtrahend tread (one)
; as (diff (one) (diff (one) (one))).
(define (minuend diff-tree)
(if (one? diff-tree)
(one)
(diff-first diff-tree)))
(define (subtrahend diff-tree)
(if (one? diff-tree)
(diff (one) (one))
(diff-second diff-tree)))
Here are the four operations we have to implement . Note that is - zero ?
; explicitly converts the diff-tree to an integer and compares it with 0.
; Since we know how successor and predecessor work, there is probably a more
; interesting way to check (without conversion), but I don't care enough to
; figure it out.
(define (zero)
(diff (one) (one)))
(define (is-zero? n)
(define (to-int n)
(if (one? n)
1
(- (to-int (minuend n))
(to-int (subtrahend n)))))
(zero? (to-int n)))
(define (successor n)
(diff (minuend n)
(diff (subtrahend n) (one))))
(define (predecessor n)
(diff n (one)))
3 . diff - tree - plus
(define (diff-tree-plus diff-tree-1 diff-tree-2)
(diff diff-tree-1
(diff (subtrahend diff-tree-2)
(minuend diff-tree-2))))
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/eopl/02/03.scm | scheme |
Define a representation of all the integers (negative and nonnegative) as
diff-trees, where a diff-tree is a list defined by the grammar
(diff (diff (one) (one)) (one)) is a representation of -1.
system.
procedures should take as input any of the multiple legal representations
of an integer in this scheme. For example, if your successor procedure is
representation. Your procedure should be optimized for the diff-tree
representation, and should do its work in a constant amount of time
(independent of the size of its inputs). In particular, it should not be
recursive.
(diff (diff M (one)) (diff S (one))). It will be the same number. We can
apply this infinitely many times. This is not the only way to modify the
representation of the number, but it is the simplest.
Here are some observers:
Here are a few higher-level observers minuend and subtrahend tread (one)
as (diff (one) (diff (one) (one))).
explicitly converts the diff-tree to an integer and compares it with 0.
Since we know how successor and predecessor work, there is probably a more
interesting way to check (without conversion), but I don't care enough to
figure it out. | EOPL exercise 2.03
Diff - tree : : = ( one ) | ( diff Diff - tree Diff - tree )
The list ( one ) represents 1 . If t₁ represents n₁ and t₂ represents n₂ , then
( diff t₁ t₂ ) is a representation of n₁ - n₂.
1 . Show that every number has infinitely many representations in this
2 . Turn this representation of the integers into an implementation by
writing zero , is - zero ? , successor and predecessor , as specified on
page 32 , except that now the negative integers are also represented . Your
given any of the infinitely many legal representations of 1 , it should
produce one of the legal representations of 2 . It is permissible for
different legal representations of 1 to yield different representations
of 2 .
3 . Write a proedure diff - tree - plus that does addition in this
1 . It 's rather obvious that a number has infinitelly many representations .
Anyway , if n is represented as ( diff M S ) , then we can also represent it as
2 . Let 's take a nice layered approach .
First , here are constructors for the representation :
(define (one) '(one))
(define (diff left right) `(diff ,left ,right))
(define (one? diff-tree) (eqv? (car diff-tree) 'one))
(define (diff? diff-tree) (eqv? (car diff-tree) 'diff))
(define (diff-first diff-tree) (cadr diff-tree))
(define (diff-second diff-tree) (caddr diff-tree))
(define (minuend diff-tree)
(if (one? diff-tree)
(one)
(diff-first diff-tree)))
(define (subtrahend diff-tree)
(if (one? diff-tree)
(diff (one) (one))
(diff-second diff-tree)))
Here are the four operations we have to implement . Note that is - zero ?
(define (zero)
(diff (one) (one)))
(define (is-zero? n)
(define (to-int n)
(if (one? n)
1
(- (to-int (minuend n))
(to-int (subtrahend n)))))
(zero? (to-int n)))
(define (successor n)
(diff (minuend n)
(diff (subtrahend n) (one))))
(define (predecessor n)
(diff n (one)))
3 . diff - tree - plus
(define (diff-tree-plus diff-tree-1 diff-tree-2)
(diff diff-tree-1
(diff (subtrahend diff-tree-2)
(minuend diff-tree-2))))
|
453f037099b8cbaca937b9fea4e51e456f963eb6b793ca7aa8a3891ede750f04 | scymtym/architecture.builder-protocol | mixins.lisp | ;;;; mixins.lisp --- Unit tests for builder mixins.
;;;;
Copyright ( C ) 2016 - 2022 Jan Moringen
;;;;
Author : < >
(cl:in-package #:architecture.builder-protocol.test)
(in-suite :architecture.builder-protocol)
(test forwarding-mixin.smoke
"Smoke test for the `forwarding-mixin' class."
(let* ((target 'list)
(delegating (make-instance 'forwarding-mixin :target target)))
(is (equalp (multiple-value-list
(with-builder (target)
(node* (:foo :bar 1)
(* :baz (list (node* (:fez)))))))
(multiple-value-list
(with-builder (delegating)
(node* (:foo :bar 1)
(* :baz (list (node* (:fez)))))))))))
(test delaying-mixin.smoke
"Smoke test for the `delaying-mixin' class."
(let* ((builder (make-instance 'delaying-mixin))
(node2 (finish-node builder :foo (make-node builder :foo)))
(node1 (finish-node builder :bar (make-node builder :bar)))
(expected1 (make-delayed-node :bar '()))
(expected2 (make-delayed-node :foo '()))
(relation (make-delayed-relation :child expected2 '())))
(push relation (delayed-node-relations expected1))
;; Test return value, i.e. produce tree plus additional return
;; values.
(is (equalp (values expected1 2)
(finish builder
(wrap builder
(lambda (builder)
(values (relate builder :child node1 node2)
2))))))))
| null | https://raw.githubusercontent.com/scymtym/architecture.builder-protocol/294c45debf8908d8c83b7d09320d4e82960a343b/test/mixins.lisp | lisp | mixins.lisp --- Unit tests for builder mixins.
Test return value, i.e. produce tree plus additional return
values. | Copyright ( C ) 2016 - 2022 Jan Moringen
Author : < >
(cl:in-package #:architecture.builder-protocol.test)
(in-suite :architecture.builder-protocol)
(test forwarding-mixin.smoke
"Smoke test for the `forwarding-mixin' class."
(let* ((target 'list)
(delegating (make-instance 'forwarding-mixin :target target)))
(is (equalp (multiple-value-list
(with-builder (target)
(node* (:foo :bar 1)
(* :baz (list (node* (:fez)))))))
(multiple-value-list
(with-builder (delegating)
(node* (:foo :bar 1)
(* :baz (list (node* (:fez)))))))))))
(test delaying-mixin.smoke
"Smoke test for the `delaying-mixin' class."
(let* ((builder (make-instance 'delaying-mixin))
(node2 (finish-node builder :foo (make-node builder :foo)))
(node1 (finish-node builder :bar (make-node builder :bar)))
(expected1 (make-delayed-node :bar '()))
(expected2 (make-delayed-node :foo '()))
(relation (make-delayed-relation :child expected2 '())))
(push relation (delayed-node-relations expected1))
(is (equalp (values expected1 2)
(finish builder
(wrap builder
(lambda (builder)
(values (relate builder :child node1 node2)
2))))))))
|
485d8782ac90d65a7fecffc90205be6d6d3b67b82183f0429ddc2de3d1148b34 | josephburnett/hive-jam | core.cljs | (ns hive-jam.core
(:require-macros [cljs.core.async.macros :refer [go-loop]]
[cljs.core.async.macros :refer [go]])
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[cljs.core.async :refer [chan put! <! >!]]
[chord.client :refer [ws-ch]]
[goog.dom :as gdom]
[goog.events :as gevents])
(:import [goog.ui Button Menu MenuItem PopupMenu SubMenu Component
FlatMenuButtonRenderer FlatButtonRenderer]
[goog.positioning Corner]))
(enable-console-print!)
;; Solarized Dark
(def pallette {:yellow "#b58900"
:orange "#cb4b16"
:red "#dc322f"
:magenta "#d33682"
:violet "#6c71c4"
:blue "#268bd2"
:faded-blue "#134569" ; custom color
:cyan "#2aa198"
:green "#859900"
:base03 "#002b36"
:base02 "#073642"
custom color : between base01 and base02
:base01 "#586e75"
:base00 "#657b83"
:base0 "#839496"
:base1 "#93a1a1"
:base2 "#eee8d5"
:base3 "#fdf6e3"})
(def theme {:background (:base03 pallette)
:foreground (:base1 pallette)
:cursorOn (:red pallette)
:cursorOff (:base0102 pallette)
:on (:green pallette)
:off (:base02 pallette)
:link (:blue pallette)
:link-bar (:faded-blue pallette)
:bar (:base02 pallette)})
(defonce app-state (atom {:grids {}
:samples []
:synths []
:grid-types ["synth" "sample"]
:bpc-values ["1/32" "1/16" "1/8" "1/4" "1/2"
"1" "2" "4" "8" "16" "32"]
:errors []
:console []
:beat-cursors []
:audio {:play true}
:hive {}}))
(defn config [key]
(get (js->clj js/HJ_CONFIG) key))
(defn grids []
(om/ref-cursor (:grids (om/root-cursor app-state))))
(defn grid-types []
(om/ref-cursor (:grid-types (om/root-cursor app-state))))
(defn samples []
(om/ref-cursor (:samples (om/root-cursor app-state))))
(defn synths []
(om/ref-cursor (:synths (om/root-cursor app-state))))
(defn bpc-values []
(om/ref-cursor (:bpc-values (om/root-cursor app-state))))
(defn handle-change [e owner state key]
(om/set-state! owner key (.. e -target -value)))
(defn cell-view [{:keys [cursor id cursor-on track-on]} _]
(reify
om/IRenderState
(render-state [_ state]
(let [cell-on (not (= 0 (first cursor)))
color (if (not cursor-on) ; cursor is not on this cell
(if (and cell-on track-on)
(:on theme)
(:off theme))
(if (and cell-on track-on)
(:cursorOn theme)
(:cursorOff theme)))]
(dom/td #js {:onClick #(do
(om/update! cursor [(if (= 0 (first cursor)) 1 0)])
(go (>! (:set-state-ch state) id)))
:onContextMenu #(do
(om/update! cursor [(inc (first cursor))])
(go (>! (:set-state-ch state) id))
false)
:style #js {:width "20px"
:fontSize "20px"
:fontWeight (if (and cursor-on cell-on)
"bold" "normal")
:color color}}
(str " " (first cursor)))))))
(def style-grey #js {:style #js {:color (:foreground theme)}})
(defn new-id []
(let [letters (map char (range 97 123))]
(apply str (take 8 (repeatedly #(rand-nth letters))))))
(declare grid-view)
(defn param-editor-builder [key]
(fn [{:keys [cursor id set-state-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:state :init})
om/IRenderState
(render-state [this state]
(let [cursor (get cursor key)]
(let [commit #(do
(om/update-state! owner (fn [s] (merge s {:state :open})))
(om/transact! cursor (fn [c] (assoc c (:field state) (:text state))))
(go (>! set-state-ch id)))
closer #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :init})))
:style #js {:color (:link theme)}}
canceller #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :open})))
:style #js {:color (:link theme)}}
delete #(do
(om/transact! cursor (fn [c] (dissoc c %)))
(go (>! set-state-ch id)))]
(condp = (:state state)
:init (dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :open})))
:style #js {:color (:link theme)}} "{..}")
:open (dom/table nil
(apply dom/tbody nil
(concat
[(dom/tr nil
(dom/td closer "{")
(dom/td nil nil)
(dom/td nil nil))]
(map (fn [k v] (dom/tr nil
(dom/td #js {:onClick #(delete k)
:style #js {:color (:link theme)}} "X")
(dom/td nil (str k ":"))
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :editing
:text v
:field k})))
:style #js {:color (:link theme)}}
v)))
(keys cursor)
(vals cursor))
[(dom/tr nil
(dom/td nil nil)
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :adding-field
:text nil
:field ""})))
:style #js {:color (:link theme)}}
"[+]")
(dom/td nil nil))
(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))])))
:editing (dom/table nil
(apply dom/tbody nil
(concat
[(dom/tr closer
(dom/td closer "{")
(dom/td nil nil)
(dom/td nil nil))]
(map (fn [k v] (dom/tr nil
(dom/td #js {:onClick #(delete k)
:style #js {:color (:link theme)}} "X")
(dom/td nil (str k ":"))
(if (= k (:field state))
(dom/td nil
(dom/input #js {:type "text" :value (:text state)
:onChange #(handle-change % owner state :text)
:onKeyDown #(when (= 13 (.-which %))
(commit))}))
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :editing
:text v
:field k})))
:style #js {:color (:link theme)}}
v))))
(keys cursor)
(vals cursor))
[(dom/tr nil
(dom/td nil nil)
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :adding-field
:text nil
:field ""})))
:style #js {:color (:link theme)}}
"[+]")
(dom/td nil nil))
(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))])))
:adding-field (dom/table nil
(concat
[(dom/tr nil
(dom/td closer "{")
(dom/td nil nil)
(dom/td nil nil))]
(map (fn [k v] (dom/tr nil
(dom/td #js {:onClick #(delete k)
:style #js {:color (:link theme)}} "X")
(dom/td nil (str k ":"))
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :editing
:text v
:field k})))
:style #js {:color (:link theme)}}
v)))
(keys cursor)
(vals cursor))
[(dom/tr nil
(dom/td nil nil)
(dom/td nil
(dom/span canceller "[- ")
(dom/input #js {:type "text" :value (:field state)
:onChange #(handle-change % owner state :field)
:onKeyDown #(when (= 13 (.-which %))
(om/update-state! owner
(fn [s] (merge {:state :adding-value
:field (:field state)}))))}))
(dom/td nil " ]"))
(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))]))
:adding-value (dom/table nil
(concat
[(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))]
(map (fn [k v] (dom/tr nil
(dom/td #js {:onClick #(delete k)
:style #js {:color (:link theme)}} "X")
(dom/td nil (str k ":"))
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :editing
:text v
:field k})))
:style #js {:color (:link theme)}}
v)))
(keys cursor)
(vals cursor))
[(dom/tr nil
(dom/td nil nil)
(dom/td nil
(dom/span canceller "[- ")
(dom/span nil (str (:field state) ":")))
(dom/td nil
(dom/input #js {:type "text" :value (:text state)
:onChange #(handle-change % owner state :text)
:onKeyDown #(when (= 13 (.-which %))
(commit))})
(dom/span nil " ]")))
(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))])))))))))
(def param-editor
(param-editor-builder "params"))
(def synth-param-editor
(param-editor-builder "synth-params"))
(def sample-param-editor
(param-editor-builder "sample-params"))
(defn text-editor-builder [key]
(fn [{:keys [cursor id set-state-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:state (if (and (contains? cursor key)
(not (= "" (get cursor key))))
:init :editing)
:value (get cursor key)})
om/IRenderState
(render-state [_ state]
(condp = (:state state)
:init
(dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :editing})))
:style #js {:color (:link theme)}}
(get cursor key))
:editing
(dom/input #js {:type "text" :value (:value state)
:onChange #(handle-change % owner state :value)
:onKeyDown #(when (= 13 (.-which %))
(om/update-state! owner (fn [s] (merge s {:state :init})))
(om/transact! cursor (fn [c] (assoc c key (:value state))))
(go (>! set-state-ch id)))}))))))
(def name-editor
(text-editor-builder "name"))
(defn select-editor-builder
([key options-ref]
(fn [{:keys [cursor id set-state-ch]} owner]
(let [render-menu #(let [node (om/get-node owner)
menu (PopupMenu.)
options (om/observe owner (options-ref))
click-fn (fn [value]
(om/transact! cursor (fn [c] (assoc c key value)))
(go (>! set-state-ch id)))]
(.attach menu node Corner.BOTTOM_START)
(doall (map (fn [o] (.addItem menu (MenuItem. o))) options))
(.render menu)
(gevents/listen menu Component.EventType.ACTION
(fn [e] (let [value (.getValue e.target)]
(om/update-state! owner (fn [s] (merge s {:state :init})))
(click-fn value)))))]
(reify
om/IInitState
(init-state [_]
{:state :init
:id (new-id)})
om/IDidMount
(did-mount [_] (render-menu))
om/IDidUpdate
(did-update [_ _ _] (render-menu))
om/IRenderState
(render-state [_ state]
(if (and (= :init (:state state))
(contains? cursor key)
(not (= "none" (get cursor key))))
(dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :selecting})))
:style #js {:color (:link theme)}}
(get cursor key))
(dom/div #js {:className "goog-flat-menu-button"}
(str "Choose a " key)))))))))
(def grid-type-editor
(select-editor-builder "grid-type" grid-types))
(def synth-editor
(select-editor-builder "synth" synths))
(def sample-editor
(select-editor-builder "sample" samples))
(def bpc-editor
(select-editor-builder "bpc" bpc-values))
(defn deep-copy [grids-cursor copy-id set-state-ch]
(let [grid (get grids-cursor copy-id)
copy-id (new-id)
copy (assoc grid
"tracks" (clj->js (map #(if (= "grid" (get % "type"))
(let [grid-id (get % "grid-id")]
(assoc % "grid-id" (deep-copy grids-cursor grid-id set-state-ch)))
%)
(get grid "tracks")))
"id" copy-id)]
(om/transact! grids-cursor #(assoc % copy-id copy))
(go (>! set-state-ch copy-id))
copy-id))
(defn type-editor [{:keys [cursor id set-state-ch]} owner]
(let [render-menu #(let [node (om/get-node owner)
grid-copy-menu (:grid-copy-menu (om/get-state owner))
menu (PopupMenu.)
sub-menu (SubMenu. "grid")
click-fn (fn [value]
(cond
(contains? grid-copy-menu value)
(let [grid-id (get grid-copy-menu value)
copy-id (deep-copy (om/observe owner (grids)) grid-id set-state-ch)]
(om/transact! cursor (fn [c] (assoc c
"type" "grid"
"synth-params" {}
"sample-params" {}
"grid-id" copy-id))))
(= "new" value)
(let [grid-id (new-id)
grid {"name" ""
"id" grid-id
"bpc" "1"
"tracks" []}]
(om/transact! cursor (fn [c] (assoc c
"type" "grid"
"synth-params" {}
"sample-params" {}
"grid-id" grid-id)))
(om/transact! (om/observe owner (grids))
(fn [c] (assoc c (get grid "id") grid)))
(go (>! set-state-ch grid-id)))
(= "sample" value)
(om/transact! cursor (fn [c] (assoc c
"type" value
"sample-params" {})))
(= "synth" value)
(om/transact! cursor (fn [c] (assoc c
"type" value
"synth-params" {})))
:else (print (str "Could not find: " value ". Was it renamed?")))
(go (>! set-state-ch id)))]
(.attach menu node Corner.BOTTOM_START)
(.addItem menu (MenuItem. "synth"))
(.addItem menu (MenuItem. "sample"))
(.addItem menu sub-menu)
(.addItem sub-menu (MenuItem. "new"))
(doall (map (fn [o] (.addItem sub-menu (MenuItem. o))) (keys grid-copy-menu)))
(.render menu)
(gevents/listen menu Component.EventType.ACTION
(fn [e] (let [value (.getValue e.target)]
(om/update-state! owner (fn [s] (merge s {:state :init})))
(click-fn value)))))]
(reify
om/IInitState
(init-state [_]
{:state :init
:id (new-id)
:grid-copy-menu {}})
om/IDidMount
(did-mount [_] (render-menu))
om/IDidUpdate
(did-update [_ _ _] (render-menu))
om/IRenderState
(render-state [_ state]
(let [grid-copy-menu (apply hash-map
(apply concat (map #(let [id (first %)
grid (second %)]
(if (and (contains? grid "name")
(not (= "" (get grid "name"))))
[(str "copy of " (get grid "name") " (" id ")") id]
[(str "copy of " id) id]))
(om/observe owner (grids)))))]
(om/set-state! owner :grid-copy-menu grid-copy-menu))
(if (and (= :init (:state state))
(contains? cursor "type")
(not (= "none" (get cursor "type"))))
(dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :selecting})))
:style #js {:color (:link theme)}}
(get cursor "type"))
(dom/div #js {:className "goog-flat-menu-button"}
(str "Choose a type")))))))
(defn fx-editor [{:keys [cursor id set-state-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:state :init})
om/IRenderState
(render-state [_ state]
(let [transition #(om/update-state! owner (fn [s] (merge {:state %})))
closing-row #(dom/tr nil
(dom/td #js {:onClick (fn [] (transition :init))
:style #js {:color (:link theme)}} %)
(dom/td nil nil)
(dom/td nil nil))
remove #(do
(om/transact! cursor (fn [c] (vec (into (subvec c 0 %)
(subvec c (+ 1 %))))))
(go (>! set-state-ch id)))
body-rows (map #(dom/tr nil
(dom/td #js {:onClick (fn [] (remove %2))
:style #js {:color (:link theme)}} "X")
(dom/td nil (get %1 "fx"))
(dom/td nil (om/build param-editor
{:cursor %1
:id id
:set-state-ch set-state-ch}
{:key :id})))
cursor
(range))
commit #(let [new-fx {:fx (:fx state)
:id (new-id)
:params {}}]
(transition :open)
(om/transact! cursor (fn [c] (clj->js (into c [new-fx]))))
(go (>! set-state-ch id)))]
(condp = (:state state)
:init (dom/span #js {:onClick #(transition :open)
:style #js {:color (:link theme)}}
"{..}")
:open (dom/table nil
(apply dom/tbody nil
(concat
[(closing-row "{")]
body-rows
[(dom/tr nil
(dom/td nil nil)
(dom/td #js {:onClick #(transition :adding)
:style #js {:color (:link theme)}} "[+]")
(dom/td nil nil))
(closing-row "}")])))
:adding (dom/table nil
(apply dom/tbody nil
(concat
[(closing-row "{")]
body-rows
[(dom/tr nil
(dom/td nil nil)
(dom/td nil
(dom/input #js {:type "text" :value (:fx state)
:onChange #(handle-change % owner state :fx)
:onKeyDown #(when (= 13 (.-which %)) (commit))}))
(dom/td nil nil))
(closing-row "}")]))))))))
(defn track-editor [{:keys [cursor id delete-ch set-state-ch] :as input} owner]
(reify
om/IInitState
(init-state [_]
{:state :init})
om/IRenderState
(render-state [this state]
(let [closer #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :init})))
:style #js {:color (:link theme)}}
turn-on #(do
(om/transact! cursor (fn [c] (assoc c "on" true)))
(go (>! set-state-ch id)))
turn-off #(do
(om/transact! cursor (fn [c] (assoc c "on" false)))
(go (>! set-state-ch id)))]
(condp = (:state state)
:init (dom/p style-grey
(dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :open})))
:style #js {:color (:link theme)}} "{..}"))
:open (let [fx-row (dom/tr nil
(dom/td nil nil)
(dom/td nil "fx:")
(dom/td nil (om/build fx-editor {:cursor (get cursor "fx")
:id id
:set-state-ch set-state-ch})))]
(dom/p style-grey
(dom/table nil
(apply dom/tbody nil
(concat
[(dom/tr nil
(dom/td nil nil)
(dom/td nil nil)
(dom/td nil (dom/span #js {:onClick #(go (>! delete-ch cursor))
:style #js {:color (:link theme)
:float "right"}} "X")))
(dom/tr nil
(dom/td closer "{")
(dom/td nil nil)
(dom/td nil nil))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "track:")
(dom/td nil (if (get cursor "on")
(dom/span #js {:onClick turn-off
:style #js {:color (:link theme)}} "on")
(dom/span #js {:onClick turn-on
:style #js {:color (:link theme)}} "off"))))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "type:")
(dom/td nil (om/build type-editor input)))]
(condp = (get cursor "type")
"synth" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "synth:")
(dom/td nil (om/build synth-editor input)))]
"sample" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "sample:")
(dom/td nil (om/build sample-editor input)))]
"play" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "note:")
(dom/td nil (get cursor "note")))]
[])
(condp = (get cursor "type")
"none" []
"grid" (condp = (get cursor "grid-type")
"synth" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "grid-type:")
(dom/td nil (om/build grid-type-editor input)))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "synth:")
(dom/td nil (om/build synth-editor input)))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "params:")
(dom/td nil (om/build synth-param-editor input)))
fx-row]
"sample" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "grid-type:")
(dom/td nil (om/build grid-type-editor input)))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "sample:")
(dom/td nil (om/build sample-editor input)))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "params:")
(dom/td nil (om/build sample-param-editor input)))
fx-row]
[(dom/tr nil
(dom/td nil nil)
(dom/td nil "grid-type:")
(dom/td nil (om/build grid-type-editor input)))
fx-row])
"sample" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "params:")
(dom/td nil (om/build sample-param-editor input)))
fx-row]
"synth" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "params:")
(dom/td nil (om/build synth-param-editor input)))
fx-row])
[(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil))]))))))))))
(defn track-builder [{:keys [cursor id set-state-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:state :init})
om/IRenderState
(render-state [_ state]
(let [transition #(om/update-state! owner (fn [s] (merge s %)))
set-width #(om/transact!
cursor (fn [s]
(clj->js
(conj s {"type" "none"
"id" (new-id)
"on" true
"beats" (repeat % [0])
"fx" []}))))
width-selection (fn [w s]
(dom/span #js {:onClick
#(do
(set-width w)
(transition {:state :init})
(go (>! set-state-ch id)))
:style #js {:color (:link theme)}} s))]
(condp = (:state state)
:init (let [width (apply max (map #(count (get % "beats")) cursor))]
(if (= 0 (count cursor))
(dom/p style-grey
(dom/span #js {:onClick #(transition {:state :open})
:style #js {:color (:link theme)}} "[+]"))
(dom/p style-grey
(dom/span #js {:onClick #(transition {:state :open})
:style #js {:color (:link theme)}} "[+")
(width-selection width (str " " width))
(dom/span nil "]"))))
:open (dom/p style-grey
(dom/span #js {:onClick #(transition {:state :init})
:style #js {:color (:link theme)}} "[- ")
(width-selection 1 " 1")
(width-selection 2 " 2")
(width-selection 4 " 4")
(width-selection 8 " 8")
(width-selection 16 " 16")
(dom/span nil "]")))))))
(defn track-view [{:keys [cursor id beat-cursors delete-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:track-expanded true})
om/IWillMount
(will-mount [_]
(when (= "grid" (get cursor "type"))
(go (>! (om/get-state owner :get-state-ch) (get cursor "grid-id")))))
om/IRenderState
(render-state [_ state]
(if-not (:track-expanded state)
(dom/tr nil
(dom/td #js {:onClick #(om/set-state! owner :track-expanded true)
:style #js {:color (:link theme)}} ">"))
(dom/tr nil
(dom/td nil
(dom/table nil
(apply dom/tr nil
(let [cursors (map #(hash-map :cursor %1 :id %2 :cursor-on (= %3 %4) :track-on %5)
(get cursor "beats")
(repeat id)
(repeat (first beat-cursors))
(range)
(repeat (get cursor "on")))]
(om/build-all cell-view cursors {:state state})))))
(dom/td #js {:style #js {:color "#999" :paddingRight "10px"}}
(om/build track-editor {:cursor cursor :id id :delete-ch delete-ch
:set-state-ch (:set-state-ch state)}))
(dom/td nil
(when (= "grid" (get cursor "type"))
(let [id (get cursor "grid-id")
sub-state {:set-state-ch (:set-state-ch state)
:get-state-ch (:get-state-ch state)}]
(om/build grid-view {:id id :beat-cursors (second beat-cursors)} {:state sub-state})))))))))
(defn grid-editor [{:keys [name id cursor set-state-ch], :as inputs} owner]
(reify
om/IInitState
(init-state [_]
{:state :init
:bpc (get cursor "bpc")})
om/IRenderState
(render-state [_ state]
(let [transition #(om/update-state! owner (fn [s] (merge s %)))
closer #(dom/span #js {:onClick (fn [] (transition {:state :init}))
:style #js {:color (:link theme)}} %)
double-width #(let [tracks (get cursor "tracks")
doubled-tracks (map (fn [t]
(let [beats (get t "beats")]
(assoc t "beats"
(take (* 2 (count beats))
(cycle beats)))))
tracks)]
(om/transact! cursor (fn [c] (assoc cursor "tracks" (clj->js doubled-tracks))))
(go (>! set-state-ch id)))
half-width #(let [tracks (get cursor "tracks")
halved-tracks (map (fn [t]
(let [beats (get t "beats")]
(assoc t "beats"
(take (max (int (/ (count beats) 2)) 1) beats))))
tracks)]
(om/transact! cursor (fn [c] (assoc cursor "tracks" (clj->js halved-tracks))))
(go (>! set-state-ch id)))
bpc-list (om/observe owner (bpc-values))
double-res #(when-not (= (first bpc-list) (get cursor "bpc"))
(let [current-bpc (get cursor "bpc")
bpc (last (take-while (fn [v] (not (= current-bpc v))) bpc-list))
tracks (get cursor "tracks")
doubled-tracks (map (fn [t]
(let [beats (get t "beats")
doubled-beats (interleave (map (fn [b] (vector (* 2 (first b)))) beats)
(repeat [0]))]
(assoc t "beats" doubled-beats)))
tracks)]
(om/transact! cursor (fn [c] (assoc c
"tracks" (clj->js doubled-tracks)
"bpc" bpc)))
(go (>! set-state-ch id))))
half-res #(when-not (= (last bpc-list) (get cursor "bpc"))
(let [current-bpc (get cursor "bpc")
bpc (second (drop-while (fn [v] (not (= current-bpc v))) bpc-list))
tracks (get cursor "tracks")
halved-tracks (map (fn [t]
(let [beats (get t "beats")
halved-beats (filter some?
(map-indexed (fn [i b] (if (even? i) (vector (if (= 0 (first b)) 0
(max (/ (first b) 2) 1))) nil))
beats))]
(assoc t "beats" halved-beats)))
tracks)]
(om/transact! cursor (fn [c] (assoc c
"tracks" (clj->js halved-tracks)
"bpc" bpc)))
(go (>! set-state-ch id))))]
(condp = (:state state)
:init (dom/table nil
(dom/tbody nil
(dom/tr nil
(dom/td nil (str name " "))
(dom/td #js {:onClick #(transition {:state :open})
:style #js {:color (:link theme)}}
"{..}"))))
:open (dom/table nil
(dom/tbody nil
(dom/tr nil
(dom/td nil (closer "{"))
(dom/td nil " name: ")
(dom/td nil (om/build name-editor inputs))
(dom/td nil (str " (" id ")"))
(dom/td nil " ")
(dom/td nil " bpc: ")
(dom/td nil (om/build bpc-editor inputs))
(dom/td nil " ")
(dom/td nil " width: ")
(dom/td #js {:onClick double-width
:style #js {:color (:link theme)}} "+")
(dom/td nil "/")
(dom/td #js {:onClick half-width
:style #js {:color (:link theme)}} "-")
(dom/td nil " ")
(dom/td nil " resolution: ")
(dom/td #js {:onClick double-res
:style #js {:color (:link theme)}} "+")
(dom/td nil "/")
(dom/td #js {:onClick half-res
:style #js {:color (:link theme)}} "-")
(dom/td nil " }")))))))))
(defn grid-view [{:keys [id beat-cursors]} owner]
(reify
om/IInitState
(init-state [_]
(let [delete-ch (chan)]
{:grid-expanded false
:delete-ch delete-ch}))
om/IWillMount
(will-mount [this]
(let [delete-ch (:delete-ch (om/get-state owner))
set-state-ch (:set-state-ch (om/get-state owner))]
(go-loop []
(let [track (<! delete-ch)
cursor (get-in (om/observe owner (grids)) [id "tracks"])]
(om/update! cursor (vec (remove (partial = track) cursor)))
(put! set-state-ch id)
(recur)))))
om/IRenderState
(render-state [_ state]
(let [cursor (get (om/observe owner (grids)) id)
name (get cursor "name")]
(dom/table nil
(dom/tbody nil
(dom/td #js {:onClick #(om/set-state! owner :grid-expanded
(not (:grid-expanded state)))
:style #js {:background (:link-bar theme)
:color (:link theme)}}
(if (:grid-expanded state) " - " " + "))
(dom/td #js {:style #js {:padding "0 0 0 10px"}}
(if-not (:grid-expanded state)
(dom/div style-grey name)
(dom/div nil
(dom/div style-grey
(om/build grid-editor {:name name
:id id
:set-state-ch (:set-state-ch state)
:cursor cursor}))
(dom/table nil
(apply dom/tbody nil
(let [cursors (map #(hash-map :cursor %1 :track-id (get %1 "id")
:id %2 :delete-ch %3 :beat-cursors %4)
(get cursor "tracks")
(repeat id)
(repeat (:delete-ch state))
(if (nil? beat-cursors) (repeat nil) beat-cursors))]
(om/build-all track-view cursors {:state state :key :track-id}))))
(when (> (config "MaxTrackCount") (count (get cursor "tracks")))
(om/build track-builder {:cursor (get cursor "tracks")
:id id
:set-state-ch (:set-state-ch state)})))))))))))
(defn error-view [cursor]
(reify
om/IRender
(render [_]
(dom/div #js {:style #js {:color "#FF0000"}}
(apply dom/ul nil
(map (partial dom/li nil) cursor))))))
(defn button [{:keys [text click-chan]} owner]
(let [render (fn [] (let [node (om/get-node owner)
b (Button. text (.getInstance FlatButtonRenderer))]
(om/update-state! owner #(merge % {:button b}))
(.render b node)
(gevents/listen b Component.EventType.ACTION
#(go (>! click-chan true)))))]
(reify
om/IInitState
(init-state [_] {})
om/IRenderState
(render-state [_ state] (dom/div nil nil))
om/IDidMount
(did-mount [_]
(render))
om/IWillUpdate
(will-update [_ next _]
(let [b (:button (om/get-state owner))
prev (om/get-props owner)]
(when-not (= next prev)
(.dispose b))))
om/IDidUpdate
(did-update [_ prev _]
(when-not (= text (:text prev))
(render))))))
(defn hive-view [{:keys [cursor save-state-ch load-state-ch]}]
(reify
om/IRender
(render [_]
(dom/div #js {:style #js {:float "right"}}
(om/build button {:text "Save state"
:click-chan save-state-ch})
(om/build button {:text "Load state"
:click-chan load-state-ch})))))
(defn audio-view [cursor owner]
(reify
om/IInitState
(init-state [_]
(let [play-ch (chan)
stop-ch (chan)]
(go-loop []
(<! play-ch)
(.play (. js/document (getElementById "audio")))
(om/transact! cursor #(merge % {:play true}))
(recur))
(go-loop []
(<! stop-ch)
(.pause (. js/document (getElementById "audio")))
(om/transact! cursor #(merge % {:play false}))
(recur))
{:play-ch play-ch
:stop-ch stop-ch}))
om/IRenderState
(render-state [_ state]
(dom/div #js {:style #js {:float "right"}}
(dom/audio #js {:id "audio"
:autoplay true}
(dom/source #js {:src (str "http://" js/window.location.hostname
":" (config "UiAudioPort") "/hivejam")
:type "audio/mpeg"}))
(if (:play cursor)
(om/build button {:text "Stop"
:click-chan (:stop-ch state)})
(om/build button {:text "Play"
:click-chan (:play-ch state)}))))
om/IDidMount
(did-mount [_]
(let [play-ch (:play-ch (om/get-state owner))]
(go (>! play-ch true))))))
(defn console-view [cursor]
(reify
om/IRender
(render [_]
(dom/div #js {:style #js {:color (:foreground theme)}}
(apply dom/ul nil
(map (partial dom/li nil) cursor))))))
(defn app-view [cursor _]
(reify
om/IInitState
(init-state [_]
(let [set-state-ch (chan)
get-state-ch (chan)
save-state-ch (chan)
load-state-ch (chan)]
(go
(let [addr (str "ws://" (config "UiExternalIp") ":" (config "UiBridgePort") "/oscbridge")
{:keys [ws-channel error]} (<! (ws-ch addr {:format :json}))]
(>! ws-channel {:Address "/get-state" :Params ["root"]})
(>! ws-channel {:Address "/get-samples" :Params []})
(>! ws-channel {:Address "/get-synths" :Params []})
(go-loop []
(let [ns (<! set-state-ch)
grid (get-in @cursor [:grids ns])
json (js/JSON.stringify (clj->js grid))
update #js {:Address "/set-state" :Params #js [ns json]}]
(go (>! ws-channel update)))
(recur))
(go-loop []
(let [ns (<! get-state-ch)
request #js {:Address "/get-state" :Params #js [ns]}]
(go (>! ws-channel request)))
(recur))
(go-loop []
(<! save-state-ch)
(let [request #js {:Address "/save-state"}]
(go (>! ws-channel request)))
(recur))
(go-loop []
(<! load-state-ch)
(let [request #js {:Address "/load-state"}]
(go (>! ws-channel request)))
(recur))
(go-loop []
(let [{:keys [message error] :as msg} (<! ws-channel)
params (get message "Params")]
(cond
(= "/state" (get message "Address"))
(let [grid (js->clj (js/JSON.parse (second params)))]
(om/transact! cursor :grids #(assoc % (first params) grid)))
(= "/samples" (get message "Address"))
(let [samples (js->clj (js/JSON.parse (first params)))]
(om/transact! cursor :samples #(sort (into % samples))))
(= "/synths" (get message "Address"))
(let [synths (js->clj (js/JSON.parse (first params)))]
(om/transact! cursor :synths #(sort (into % synths))))
(= "/errors" (get message "Address"))
(let [errors (js->clj (js/JSON.parse (first params)))]
(om/update! cursor :errors errors))
(= "/console" (get message "Address"))
(let [console (js->clj (js/JSON.parse (first params)))]
(om/update! cursor :console console))
(= "/cursors" (get message "Address"))
(let [beat-cursors (js->clj (js/JSON.parse (first params)))]
(om/update! cursor :beat-cursors beat-cursors)))
(when message
(recur))))))
{:set-state-ch set-state-ch
:get-state-ch get-state-ch
:save-state-ch save-state-ch
:load-state-ch load-state-ch
:grid-expanded true}))
om/IRenderState
(render-state [_ state]
(dom/div #js {:style #js {:fontFamily "monospace"
:background (:background theme)}}
(om/build error-view (:errors cursor))
(when-not (empty? (config "StateFile"))
(om/build hive-view {:cursor (:hive cursor)
:save-state-ch (:save-state-ch state)
:load-state-ch (:load-state-ch state)}))
(when (config "EnableUiAudio")
(om/build audio-view (:audio cursor)))
(om/build grid-view {:id "root" :beat-cursors (:beat-cursors cursor)} {:state state})
(om/build console-view (:console cursor))))))
(om/root app-view app-state
{:target (. js/document (getElementById "app"))})
| null | https://raw.githubusercontent.com/josephburnett/hive-jam/67f21e13f4af92be791f4b16d31f04827a467747/cljs/src/hive_jam/core.cljs | clojure | Solarized Dark
custom color
cursor is not on this cell | (ns hive-jam.core
(:require-macros [cljs.core.async.macros :refer [go-loop]]
[cljs.core.async.macros :refer [go]])
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[cljs.core.async :refer [chan put! <! >!]]
[chord.client :refer [ws-ch]]
[goog.dom :as gdom]
[goog.events :as gevents])
(:import [goog.ui Button Menu MenuItem PopupMenu SubMenu Component
FlatMenuButtonRenderer FlatButtonRenderer]
[goog.positioning Corner]))
(enable-console-print!)
(def pallette {:yellow "#b58900"
:orange "#cb4b16"
:red "#dc322f"
:magenta "#d33682"
:violet "#6c71c4"
:blue "#268bd2"
:cyan "#2aa198"
:green "#859900"
:base03 "#002b36"
:base02 "#073642"
custom color : between base01 and base02
:base01 "#586e75"
:base00 "#657b83"
:base0 "#839496"
:base1 "#93a1a1"
:base2 "#eee8d5"
:base3 "#fdf6e3"})
(def theme {:background (:base03 pallette)
:foreground (:base1 pallette)
:cursorOn (:red pallette)
:cursorOff (:base0102 pallette)
:on (:green pallette)
:off (:base02 pallette)
:link (:blue pallette)
:link-bar (:faded-blue pallette)
:bar (:base02 pallette)})
(defonce app-state (atom {:grids {}
:samples []
:synths []
:grid-types ["synth" "sample"]
:bpc-values ["1/32" "1/16" "1/8" "1/4" "1/2"
"1" "2" "4" "8" "16" "32"]
:errors []
:console []
:beat-cursors []
:audio {:play true}
:hive {}}))
(defn config [key]
(get (js->clj js/HJ_CONFIG) key))
(defn grids []
(om/ref-cursor (:grids (om/root-cursor app-state))))
(defn grid-types []
(om/ref-cursor (:grid-types (om/root-cursor app-state))))
(defn samples []
(om/ref-cursor (:samples (om/root-cursor app-state))))
(defn synths []
(om/ref-cursor (:synths (om/root-cursor app-state))))
(defn bpc-values []
(om/ref-cursor (:bpc-values (om/root-cursor app-state))))
(defn handle-change [e owner state key]
(om/set-state! owner key (.. e -target -value)))
(defn cell-view [{:keys [cursor id cursor-on track-on]} _]
(reify
om/IRenderState
(render-state [_ state]
(let [cell-on (not (= 0 (first cursor)))
(if (and cell-on track-on)
(:on theme)
(:off theme))
(if (and cell-on track-on)
(:cursorOn theme)
(:cursorOff theme)))]
(dom/td #js {:onClick #(do
(om/update! cursor [(if (= 0 (first cursor)) 1 0)])
(go (>! (:set-state-ch state) id)))
:onContextMenu #(do
(om/update! cursor [(inc (first cursor))])
(go (>! (:set-state-ch state) id))
false)
:style #js {:width "20px"
:fontSize "20px"
:fontWeight (if (and cursor-on cell-on)
"bold" "normal")
:color color}}
(str " " (first cursor)))))))
(def style-grey #js {:style #js {:color (:foreground theme)}})
(defn new-id []
(let [letters (map char (range 97 123))]
(apply str (take 8 (repeatedly #(rand-nth letters))))))
(declare grid-view)
(defn param-editor-builder [key]
(fn [{:keys [cursor id set-state-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:state :init})
om/IRenderState
(render-state [this state]
(let [cursor (get cursor key)]
(let [commit #(do
(om/update-state! owner (fn [s] (merge s {:state :open})))
(om/transact! cursor (fn [c] (assoc c (:field state) (:text state))))
(go (>! set-state-ch id)))
closer #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :init})))
:style #js {:color (:link theme)}}
canceller #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :open})))
:style #js {:color (:link theme)}}
delete #(do
(om/transact! cursor (fn [c] (dissoc c %)))
(go (>! set-state-ch id)))]
(condp = (:state state)
:init (dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :open})))
:style #js {:color (:link theme)}} "{..}")
:open (dom/table nil
(apply dom/tbody nil
(concat
[(dom/tr nil
(dom/td closer "{")
(dom/td nil nil)
(dom/td nil nil))]
(map (fn [k v] (dom/tr nil
(dom/td #js {:onClick #(delete k)
:style #js {:color (:link theme)}} "X")
(dom/td nil (str k ":"))
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :editing
:text v
:field k})))
:style #js {:color (:link theme)}}
v)))
(keys cursor)
(vals cursor))
[(dom/tr nil
(dom/td nil nil)
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :adding-field
:text nil
:field ""})))
:style #js {:color (:link theme)}}
"[+]")
(dom/td nil nil))
(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))])))
:editing (dom/table nil
(apply dom/tbody nil
(concat
[(dom/tr closer
(dom/td closer "{")
(dom/td nil nil)
(dom/td nil nil))]
(map (fn [k v] (dom/tr nil
(dom/td #js {:onClick #(delete k)
:style #js {:color (:link theme)}} "X")
(dom/td nil (str k ":"))
(if (= k (:field state))
(dom/td nil
(dom/input #js {:type "text" :value (:text state)
:onChange #(handle-change % owner state :text)
:onKeyDown #(when (= 13 (.-which %))
(commit))}))
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :editing
:text v
:field k})))
:style #js {:color (:link theme)}}
v))))
(keys cursor)
(vals cursor))
[(dom/tr nil
(dom/td nil nil)
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :adding-field
:text nil
:field ""})))
:style #js {:color (:link theme)}}
"[+]")
(dom/td nil nil))
(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))])))
:adding-field (dom/table nil
(concat
[(dom/tr nil
(dom/td closer "{")
(dom/td nil nil)
(dom/td nil nil))]
(map (fn [k v] (dom/tr nil
(dom/td #js {:onClick #(delete k)
:style #js {:color (:link theme)}} "X")
(dom/td nil (str k ":"))
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :editing
:text v
:field k})))
:style #js {:color (:link theme)}}
v)))
(keys cursor)
(vals cursor))
[(dom/tr nil
(dom/td nil nil)
(dom/td nil
(dom/span canceller "[- ")
(dom/input #js {:type "text" :value (:field state)
:onChange #(handle-change % owner state :field)
:onKeyDown #(when (= 13 (.-which %))
(om/update-state! owner
(fn [s] (merge {:state :adding-value
:field (:field state)}))))}))
(dom/td nil " ]"))
(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))]))
:adding-value (dom/table nil
(concat
[(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))]
(map (fn [k v] (dom/tr nil
(dom/td #js {:onClick #(delete k)
:style #js {:color (:link theme)}} "X")
(dom/td nil (str k ":"))
(dom/td #js {:onClick #(om/update-state! owner
(fn [s] (merge s {:state :editing
:text v
:field k})))
:style #js {:color (:link theme)}}
v)))
(keys cursor)
(vals cursor))
[(dom/tr nil
(dom/td nil nil)
(dom/td nil
(dom/span canceller "[- ")
(dom/span nil (str (:field state) ":")))
(dom/td nil
(dom/input #js {:type "text" :value (:text state)
:onChange #(handle-change % owner state :text)
:onKeyDown #(when (= 13 (.-which %))
(commit))})
(dom/span nil " ]")))
(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil nil))])))))))))
(def param-editor
(param-editor-builder "params"))
(def synth-param-editor
(param-editor-builder "synth-params"))
(def sample-param-editor
(param-editor-builder "sample-params"))
(defn text-editor-builder [key]
(fn [{:keys [cursor id set-state-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:state (if (and (contains? cursor key)
(not (= "" (get cursor key))))
:init :editing)
:value (get cursor key)})
om/IRenderState
(render-state [_ state]
(condp = (:state state)
:init
(dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :editing})))
:style #js {:color (:link theme)}}
(get cursor key))
:editing
(dom/input #js {:type "text" :value (:value state)
:onChange #(handle-change % owner state :value)
:onKeyDown #(when (= 13 (.-which %))
(om/update-state! owner (fn [s] (merge s {:state :init})))
(om/transact! cursor (fn [c] (assoc c key (:value state))))
(go (>! set-state-ch id)))}))))))
(def name-editor
(text-editor-builder "name"))
(defn select-editor-builder
([key options-ref]
(fn [{:keys [cursor id set-state-ch]} owner]
(let [render-menu #(let [node (om/get-node owner)
menu (PopupMenu.)
options (om/observe owner (options-ref))
click-fn (fn [value]
(om/transact! cursor (fn [c] (assoc c key value)))
(go (>! set-state-ch id)))]
(.attach menu node Corner.BOTTOM_START)
(doall (map (fn [o] (.addItem menu (MenuItem. o))) options))
(.render menu)
(gevents/listen menu Component.EventType.ACTION
(fn [e] (let [value (.getValue e.target)]
(om/update-state! owner (fn [s] (merge s {:state :init})))
(click-fn value)))))]
(reify
om/IInitState
(init-state [_]
{:state :init
:id (new-id)})
om/IDidMount
(did-mount [_] (render-menu))
om/IDidUpdate
(did-update [_ _ _] (render-menu))
om/IRenderState
(render-state [_ state]
(if (and (= :init (:state state))
(contains? cursor key)
(not (= "none" (get cursor key))))
(dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :selecting})))
:style #js {:color (:link theme)}}
(get cursor key))
(dom/div #js {:className "goog-flat-menu-button"}
(str "Choose a " key)))))))))
(def grid-type-editor
(select-editor-builder "grid-type" grid-types))
(def synth-editor
(select-editor-builder "synth" synths))
(def sample-editor
(select-editor-builder "sample" samples))
(def bpc-editor
(select-editor-builder "bpc" bpc-values))
(defn deep-copy [grids-cursor copy-id set-state-ch]
(let [grid (get grids-cursor copy-id)
copy-id (new-id)
copy (assoc grid
"tracks" (clj->js (map #(if (= "grid" (get % "type"))
(let [grid-id (get % "grid-id")]
(assoc % "grid-id" (deep-copy grids-cursor grid-id set-state-ch)))
%)
(get grid "tracks")))
"id" copy-id)]
(om/transact! grids-cursor #(assoc % copy-id copy))
(go (>! set-state-ch copy-id))
copy-id))
(defn type-editor [{:keys [cursor id set-state-ch]} owner]
(let [render-menu #(let [node (om/get-node owner)
grid-copy-menu (:grid-copy-menu (om/get-state owner))
menu (PopupMenu.)
sub-menu (SubMenu. "grid")
click-fn (fn [value]
(cond
(contains? grid-copy-menu value)
(let [grid-id (get grid-copy-menu value)
copy-id (deep-copy (om/observe owner (grids)) grid-id set-state-ch)]
(om/transact! cursor (fn [c] (assoc c
"type" "grid"
"synth-params" {}
"sample-params" {}
"grid-id" copy-id))))
(= "new" value)
(let [grid-id (new-id)
grid {"name" ""
"id" grid-id
"bpc" "1"
"tracks" []}]
(om/transact! cursor (fn [c] (assoc c
"type" "grid"
"synth-params" {}
"sample-params" {}
"grid-id" grid-id)))
(om/transact! (om/observe owner (grids))
(fn [c] (assoc c (get grid "id") grid)))
(go (>! set-state-ch grid-id)))
(= "sample" value)
(om/transact! cursor (fn [c] (assoc c
"type" value
"sample-params" {})))
(= "synth" value)
(om/transact! cursor (fn [c] (assoc c
"type" value
"synth-params" {})))
:else (print (str "Could not find: " value ". Was it renamed?")))
(go (>! set-state-ch id)))]
(.attach menu node Corner.BOTTOM_START)
(.addItem menu (MenuItem. "synth"))
(.addItem menu (MenuItem. "sample"))
(.addItem menu sub-menu)
(.addItem sub-menu (MenuItem. "new"))
(doall (map (fn [o] (.addItem sub-menu (MenuItem. o))) (keys grid-copy-menu)))
(.render menu)
(gevents/listen menu Component.EventType.ACTION
(fn [e] (let [value (.getValue e.target)]
(om/update-state! owner (fn [s] (merge s {:state :init})))
(click-fn value)))))]
(reify
om/IInitState
(init-state [_]
{:state :init
:id (new-id)
:grid-copy-menu {}})
om/IDidMount
(did-mount [_] (render-menu))
om/IDidUpdate
(did-update [_ _ _] (render-menu))
om/IRenderState
(render-state [_ state]
(let [grid-copy-menu (apply hash-map
(apply concat (map #(let [id (first %)
grid (second %)]
(if (and (contains? grid "name")
(not (= "" (get grid "name"))))
[(str "copy of " (get grid "name") " (" id ")") id]
[(str "copy of " id) id]))
(om/observe owner (grids)))))]
(om/set-state! owner :grid-copy-menu grid-copy-menu))
(if (and (= :init (:state state))
(contains? cursor "type")
(not (= "none" (get cursor "type"))))
(dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :selecting})))
:style #js {:color (:link theme)}}
(get cursor "type"))
(dom/div #js {:className "goog-flat-menu-button"}
(str "Choose a type")))))))
(defn fx-editor [{:keys [cursor id set-state-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:state :init})
om/IRenderState
(render-state [_ state]
(let [transition #(om/update-state! owner (fn [s] (merge {:state %})))
closing-row #(dom/tr nil
(dom/td #js {:onClick (fn [] (transition :init))
:style #js {:color (:link theme)}} %)
(dom/td nil nil)
(dom/td nil nil))
remove #(do
(om/transact! cursor (fn [c] (vec (into (subvec c 0 %)
(subvec c (+ 1 %))))))
(go (>! set-state-ch id)))
body-rows (map #(dom/tr nil
(dom/td #js {:onClick (fn [] (remove %2))
:style #js {:color (:link theme)}} "X")
(dom/td nil (get %1 "fx"))
(dom/td nil (om/build param-editor
{:cursor %1
:id id
:set-state-ch set-state-ch}
{:key :id})))
cursor
(range))
commit #(let [new-fx {:fx (:fx state)
:id (new-id)
:params {}}]
(transition :open)
(om/transact! cursor (fn [c] (clj->js (into c [new-fx]))))
(go (>! set-state-ch id)))]
(condp = (:state state)
:init (dom/span #js {:onClick #(transition :open)
:style #js {:color (:link theme)}}
"{..}")
:open (dom/table nil
(apply dom/tbody nil
(concat
[(closing-row "{")]
body-rows
[(dom/tr nil
(dom/td nil nil)
(dom/td #js {:onClick #(transition :adding)
:style #js {:color (:link theme)}} "[+]")
(dom/td nil nil))
(closing-row "}")])))
:adding (dom/table nil
(apply dom/tbody nil
(concat
[(closing-row "{")]
body-rows
[(dom/tr nil
(dom/td nil nil)
(dom/td nil
(dom/input #js {:type "text" :value (:fx state)
:onChange #(handle-change % owner state :fx)
:onKeyDown #(when (= 13 (.-which %)) (commit))}))
(dom/td nil nil))
(closing-row "}")]))))))))
(defn track-editor [{:keys [cursor id delete-ch set-state-ch] :as input} owner]
(reify
om/IInitState
(init-state [_]
{:state :init})
om/IRenderState
(render-state [this state]
(let [closer #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :init})))
:style #js {:color (:link theme)}}
turn-on #(do
(om/transact! cursor (fn [c] (assoc c "on" true)))
(go (>! set-state-ch id)))
turn-off #(do
(om/transact! cursor (fn [c] (assoc c "on" false)))
(go (>! set-state-ch id)))]
(condp = (:state state)
:init (dom/p style-grey
(dom/span #js {:onClick #(om/update-state! owner (fn [s] (merge s {:state :open})))
:style #js {:color (:link theme)}} "{..}"))
:open (let [fx-row (dom/tr nil
(dom/td nil nil)
(dom/td nil "fx:")
(dom/td nil (om/build fx-editor {:cursor (get cursor "fx")
:id id
:set-state-ch set-state-ch})))]
(dom/p style-grey
(dom/table nil
(apply dom/tbody nil
(concat
[(dom/tr nil
(dom/td nil nil)
(dom/td nil nil)
(dom/td nil (dom/span #js {:onClick #(go (>! delete-ch cursor))
:style #js {:color (:link theme)
:float "right"}} "X")))
(dom/tr nil
(dom/td closer "{")
(dom/td nil nil)
(dom/td nil nil))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "track:")
(dom/td nil (if (get cursor "on")
(dom/span #js {:onClick turn-off
:style #js {:color (:link theme)}} "on")
(dom/span #js {:onClick turn-on
:style #js {:color (:link theme)}} "off"))))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "type:")
(dom/td nil (om/build type-editor input)))]
(condp = (get cursor "type")
"synth" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "synth:")
(dom/td nil (om/build synth-editor input)))]
"sample" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "sample:")
(dom/td nil (om/build sample-editor input)))]
"play" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "note:")
(dom/td nil (get cursor "note")))]
[])
(condp = (get cursor "type")
"none" []
"grid" (condp = (get cursor "grid-type")
"synth" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "grid-type:")
(dom/td nil (om/build grid-type-editor input)))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "synth:")
(dom/td nil (om/build synth-editor input)))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "params:")
(dom/td nil (om/build synth-param-editor input)))
fx-row]
"sample" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "grid-type:")
(dom/td nil (om/build grid-type-editor input)))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "sample:")
(dom/td nil (om/build sample-editor input)))
(dom/tr nil
(dom/td nil nil)
(dom/td nil "params:")
(dom/td nil (om/build sample-param-editor input)))
fx-row]
[(dom/tr nil
(dom/td nil nil)
(dom/td nil "grid-type:")
(dom/td nil (om/build grid-type-editor input)))
fx-row])
"sample" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "params:")
(dom/td nil (om/build sample-param-editor input)))
fx-row]
"synth" [(dom/tr nil
(dom/td nil nil)
(dom/td nil "params:")
(dom/td nil (om/build synth-param-editor input)))
fx-row])
[(dom/tr nil
(dom/td closer "}")
(dom/td nil nil)
(dom/td nil))]))))))))))
(defn track-builder [{:keys [cursor id set-state-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:state :init})
om/IRenderState
(render-state [_ state]
(let [transition #(om/update-state! owner (fn [s] (merge s %)))
set-width #(om/transact!
cursor (fn [s]
(clj->js
(conj s {"type" "none"
"id" (new-id)
"on" true
"beats" (repeat % [0])
"fx" []}))))
width-selection (fn [w s]
(dom/span #js {:onClick
#(do
(set-width w)
(transition {:state :init})
(go (>! set-state-ch id)))
:style #js {:color (:link theme)}} s))]
(condp = (:state state)
:init (let [width (apply max (map #(count (get % "beats")) cursor))]
(if (= 0 (count cursor))
(dom/p style-grey
(dom/span #js {:onClick #(transition {:state :open})
:style #js {:color (:link theme)}} "[+]"))
(dom/p style-grey
(dom/span #js {:onClick #(transition {:state :open})
:style #js {:color (:link theme)}} "[+")
(width-selection width (str " " width))
(dom/span nil "]"))))
:open (dom/p style-grey
(dom/span #js {:onClick #(transition {:state :init})
:style #js {:color (:link theme)}} "[- ")
(width-selection 1 " 1")
(width-selection 2 " 2")
(width-selection 4 " 4")
(width-selection 8 " 8")
(width-selection 16 " 16")
(dom/span nil "]")))))))
(defn track-view [{:keys [cursor id beat-cursors delete-ch]} owner]
(reify
om/IInitState
(init-state [_]
{:track-expanded true})
om/IWillMount
(will-mount [_]
(when (= "grid" (get cursor "type"))
(go (>! (om/get-state owner :get-state-ch) (get cursor "grid-id")))))
om/IRenderState
(render-state [_ state]
(if-not (:track-expanded state)
(dom/tr nil
(dom/td #js {:onClick #(om/set-state! owner :track-expanded true)
:style #js {:color (:link theme)}} ">"))
(dom/tr nil
(dom/td nil
(dom/table nil
(apply dom/tr nil
(let [cursors (map #(hash-map :cursor %1 :id %2 :cursor-on (= %3 %4) :track-on %5)
(get cursor "beats")
(repeat id)
(repeat (first beat-cursors))
(range)
(repeat (get cursor "on")))]
(om/build-all cell-view cursors {:state state})))))
(dom/td #js {:style #js {:color "#999" :paddingRight "10px"}}
(om/build track-editor {:cursor cursor :id id :delete-ch delete-ch
:set-state-ch (:set-state-ch state)}))
(dom/td nil
(when (= "grid" (get cursor "type"))
(let [id (get cursor "grid-id")
sub-state {:set-state-ch (:set-state-ch state)
:get-state-ch (:get-state-ch state)}]
(om/build grid-view {:id id :beat-cursors (second beat-cursors)} {:state sub-state})))))))))
(defn grid-editor [{:keys [name id cursor set-state-ch], :as inputs} owner]
(reify
om/IInitState
(init-state [_]
{:state :init
:bpc (get cursor "bpc")})
om/IRenderState
(render-state [_ state]
(let [transition #(om/update-state! owner (fn [s] (merge s %)))
closer #(dom/span #js {:onClick (fn [] (transition {:state :init}))
:style #js {:color (:link theme)}} %)
double-width #(let [tracks (get cursor "tracks")
doubled-tracks (map (fn [t]
(let [beats (get t "beats")]
(assoc t "beats"
(take (* 2 (count beats))
(cycle beats)))))
tracks)]
(om/transact! cursor (fn [c] (assoc cursor "tracks" (clj->js doubled-tracks))))
(go (>! set-state-ch id)))
half-width #(let [tracks (get cursor "tracks")
halved-tracks (map (fn [t]
(let [beats (get t "beats")]
(assoc t "beats"
(take (max (int (/ (count beats) 2)) 1) beats))))
tracks)]
(om/transact! cursor (fn [c] (assoc cursor "tracks" (clj->js halved-tracks))))
(go (>! set-state-ch id)))
bpc-list (om/observe owner (bpc-values))
double-res #(when-not (= (first bpc-list) (get cursor "bpc"))
(let [current-bpc (get cursor "bpc")
bpc (last (take-while (fn [v] (not (= current-bpc v))) bpc-list))
tracks (get cursor "tracks")
doubled-tracks (map (fn [t]
(let [beats (get t "beats")
doubled-beats (interleave (map (fn [b] (vector (* 2 (first b)))) beats)
(repeat [0]))]
(assoc t "beats" doubled-beats)))
tracks)]
(om/transact! cursor (fn [c] (assoc c
"tracks" (clj->js doubled-tracks)
"bpc" bpc)))
(go (>! set-state-ch id))))
half-res #(when-not (= (last bpc-list) (get cursor "bpc"))
(let [current-bpc (get cursor "bpc")
bpc (second (drop-while (fn [v] (not (= current-bpc v))) bpc-list))
tracks (get cursor "tracks")
halved-tracks (map (fn [t]
(let [beats (get t "beats")
halved-beats (filter some?
(map-indexed (fn [i b] (if (even? i) (vector (if (= 0 (first b)) 0
(max (/ (first b) 2) 1))) nil))
beats))]
(assoc t "beats" halved-beats)))
tracks)]
(om/transact! cursor (fn [c] (assoc c
"tracks" (clj->js halved-tracks)
"bpc" bpc)))
(go (>! set-state-ch id))))]
(condp = (:state state)
:init (dom/table nil
(dom/tbody nil
(dom/tr nil
(dom/td nil (str name " "))
(dom/td #js {:onClick #(transition {:state :open})
:style #js {:color (:link theme)}}
"{..}"))))
:open (dom/table nil
(dom/tbody nil
(dom/tr nil
(dom/td nil (closer "{"))
(dom/td nil " name: ")
(dom/td nil (om/build name-editor inputs))
(dom/td nil (str " (" id ")"))
(dom/td nil " ")
(dom/td nil " bpc: ")
(dom/td nil (om/build bpc-editor inputs))
(dom/td nil " ")
(dom/td nil " width: ")
(dom/td #js {:onClick double-width
:style #js {:color (:link theme)}} "+")
(dom/td nil "/")
(dom/td #js {:onClick half-width
:style #js {:color (:link theme)}} "-")
(dom/td nil " ")
(dom/td nil " resolution: ")
(dom/td #js {:onClick double-res
:style #js {:color (:link theme)}} "+")
(dom/td nil "/")
(dom/td #js {:onClick half-res
:style #js {:color (:link theme)}} "-")
(dom/td nil " }")))))))))
(defn grid-view [{:keys [id beat-cursors]} owner]
(reify
om/IInitState
(init-state [_]
(let [delete-ch (chan)]
{:grid-expanded false
:delete-ch delete-ch}))
om/IWillMount
(will-mount [this]
(let [delete-ch (:delete-ch (om/get-state owner))
set-state-ch (:set-state-ch (om/get-state owner))]
(go-loop []
(let [track (<! delete-ch)
cursor (get-in (om/observe owner (grids)) [id "tracks"])]
(om/update! cursor (vec (remove (partial = track) cursor)))
(put! set-state-ch id)
(recur)))))
om/IRenderState
(render-state [_ state]
(let [cursor (get (om/observe owner (grids)) id)
name (get cursor "name")]
(dom/table nil
(dom/tbody nil
(dom/td #js {:onClick #(om/set-state! owner :grid-expanded
(not (:grid-expanded state)))
:style #js {:background (:link-bar theme)
:color (:link theme)}}
(if (:grid-expanded state) " - " " + "))
(dom/td #js {:style #js {:padding "0 0 0 10px"}}
(if-not (:grid-expanded state)
(dom/div style-grey name)
(dom/div nil
(dom/div style-grey
(om/build grid-editor {:name name
:id id
:set-state-ch (:set-state-ch state)
:cursor cursor}))
(dom/table nil
(apply dom/tbody nil
(let [cursors (map #(hash-map :cursor %1 :track-id (get %1 "id")
:id %2 :delete-ch %3 :beat-cursors %4)
(get cursor "tracks")
(repeat id)
(repeat (:delete-ch state))
(if (nil? beat-cursors) (repeat nil) beat-cursors))]
(om/build-all track-view cursors {:state state :key :track-id}))))
(when (> (config "MaxTrackCount") (count (get cursor "tracks")))
(om/build track-builder {:cursor (get cursor "tracks")
:id id
:set-state-ch (:set-state-ch state)})))))))))))
(defn error-view [cursor]
(reify
om/IRender
(render [_]
(dom/div #js {:style #js {:color "#FF0000"}}
(apply dom/ul nil
(map (partial dom/li nil) cursor))))))
(defn button [{:keys [text click-chan]} owner]
(let [render (fn [] (let [node (om/get-node owner)
b (Button. text (.getInstance FlatButtonRenderer))]
(om/update-state! owner #(merge % {:button b}))
(.render b node)
(gevents/listen b Component.EventType.ACTION
#(go (>! click-chan true)))))]
(reify
om/IInitState
(init-state [_] {})
om/IRenderState
(render-state [_ state] (dom/div nil nil))
om/IDidMount
(did-mount [_]
(render))
om/IWillUpdate
(will-update [_ next _]
(let [b (:button (om/get-state owner))
prev (om/get-props owner)]
(when-not (= next prev)
(.dispose b))))
om/IDidUpdate
(did-update [_ prev _]
(when-not (= text (:text prev))
(render))))))
(defn hive-view [{:keys [cursor save-state-ch load-state-ch]}]
(reify
om/IRender
(render [_]
(dom/div #js {:style #js {:float "right"}}
(om/build button {:text "Save state"
:click-chan save-state-ch})
(om/build button {:text "Load state"
:click-chan load-state-ch})))))
(defn audio-view [cursor owner]
(reify
om/IInitState
(init-state [_]
(let [play-ch (chan)
stop-ch (chan)]
(go-loop []
(<! play-ch)
(.play (. js/document (getElementById "audio")))
(om/transact! cursor #(merge % {:play true}))
(recur))
(go-loop []
(<! stop-ch)
(.pause (. js/document (getElementById "audio")))
(om/transact! cursor #(merge % {:play false}))
(recur))
{:play-ch play-ch
:stop-ch stop-ch}))
om/IRenderState
(render-state [_ state]
(dom/div #js {:style #js {:float "right"}}
(dom/audio #js {:id "audio"
:autoplay true}
(dom/source #js {:src (str "http://" js/window.location.hostname
":" (config "UiAudioPort") "/hivejam")
:type "audio/mpeg"}))
(if (:play cursor)
(om/build button {:text "Stop"
:click-chan (:stop-ch state)})
(om/build button {:text "Play"
:click-chan (:play-ch state)}))))
om/IDidMount
(did-mount [_]
(let [play-ch (:play-ch (om/get-state owner))]
(go (>! play-ch true))))))
(defn console-view [cursor]
(reify
om/IRender
(render [_]
(dom/div #js {:style #js {:color (:foreground theme)}}
(apply dom/ul nil
(map (partial dom/li nil) cursor))))))
(defn app-view [cursor _]
(reify
om/IInitState
(init-state [_]
(let [set-state-ch (chan)
get-state-ch (chan)
save-state-ch (chan)
load-state-ch (chan)]
(go
(let [addr (str "ws://" (config "UiExternalIp") ":" (config "UiBridgePort") "/oscbridge")
{:keys [ws-channel error]} (<! (ws-ch addr {:format :json}))]
(>! ws-channel {:Address "/get-state" :Params ["root"]})
(>! ws-channel {:Address "/get-samples" :Params []})
(>! ws-channel {:Address "/get-synths" :Params []})
(go-loop []
(let [ns (<! set-state-ch)
grid (get-in @cursor [:grids ns])
json (js/JSON.stringify (clj->js grid))
update #js {:Address "/set-state" :Params #js [ns json]}]
(go (>! ws-channel update)))
(recur))
(go-loop []
(let [ns (<! get-state-ch)
request #js {:Address "/get-state" :Params #js [ns]}]
(go (>! ws-channel request)))
(recur))
(go-loop []
(<! save-state-ch)
(let [request #js {:Address "/save-state"}]
(go (>! ws-channel request)))
(recur))
(go-loop []
(<! load-state-ch)
(let [request #js {:Address "/load-state"}]
(go (>! ws-channel request)))
(recur))
(go-loop []
(let [{:keys [message error] :as msg} (<! ws-channel)
params (get message "Params")]
(cond
(= "/state" (get message "Address"))
(let [grid (js->clj (js/JSON.parse (second params)))]
(om/transact! cursor :grids #(assoc % (first params) grid)))
(= "/samples" (get message "Address"))
(let [samples (js->clj (js/JSON.parse (first params)))]
(om/transact! cursor :samples #(sort (into % samples))))
(= "/synths" (get message "Address"))
(let [synths (js->clj (js/JSON.parse (first params)))]
(om/transact! cursor :synths #(sort (into % synths))))
(= "/errors" (get message "Address"))
(let [errors (js->clj (js/JSON.parse (first params)))]
(om/update! cursor :errors errors))
(= "/console" (get message "Address"))
(let [console (js->clj (js/JSON.parse (first params)))]
(om/update! cursor :console console))
(= "/cursors" (get message "Address"))
(let [beat-cursors (js->clj (js/JSON.parse (first params)))]
(om/update! cursor :beat-cursors beat-cursors)))
(when message
(recur))))))
{:set-state-ch set-state-ch
:get-state-ch get-state-ch
:save-state-ch save-state-ch
:load-state-ch load-state-ch
:grid-expanded true}))
om/IRenderState
(render-state [_ state]
(dom/div #js {:style #js {:fontFamily "monospace"
:background (:background theme)}}
(om/build error-view (:errors cursor))
(when-not (empty? (config "StateFile"))
(om/build hive-view {:cursor (:hive cursor)
:save-state-ch (:save-state-ch state)
:load-state-ch (:load-state-ch state)}))
(when (config "EnableUiAudio")
(om/build audio-view (:audio cursor)))
(om/build grid-view {:id "root" :beat-cursors (:beat-cursors cursor)} {:state state})
(om/build console-view (:console cursor))))))
(om/root app-view app-state
{:target (. js/document (getElementById "app"))})
|
ac65d5698336b260b7b3d6ba2d63fe5830fa2f33a7f2707be8c68022a4aca1cd | mikelevins/folio2 | maps-types.lisp | ;;;; ***********************************************************************
;;;;
Name :
;;;; Project: folio2 - Functional idioms for Common Lisp
;;;; Purpose: map type definitions
;;;; Author: mikel evins
Copyright : 2015 by mikel evins
;;;;
;;;; ***********************************************************************
(in-package :net.bardcode.folio2.maps)
;;; ---------------------------------------------------------------------
;;; alist
;;; ---------------------------------------------------------------------
for the purposes of , an alist is a list all of whose
;;; elements are lists
(defmethod alist? (thing)
(declare (ignore thing))
nil)
(defmethod alist? ((thing cons))
(and thing
(every 'consp thing)))
(deftype alist ()
`(and list
(satisfies alist?)))
;;; ---------------------------------------------------------------------
;;; plist
;;; ---------------------------------------------------------------------
for the purposes of , a plist is a list with an even number of
;;; elements whose even-indexed elements are atoms
(defmethod plist? (thing)
(declare (ignore thing))
nil)
(defmethod plist? ((thing cons))
(and thing
(block testing
(loop for tail on thing by #'cddr
do (unless (and (cdr tail)
(atom (car tail)))
(return-from testing nil)))
t)))
(deftype plist ()
`(and list
(satisfies plist?)))
| null | https://raw.githubusercontent.com/mikelevins/folio2/a96052f78f0e0358376a498c6351342ece6a9b7b/src/maps-types.lisp | lisp | ***********************************************************************
Project: folio2 - Functional idioms for Common Lisp
Purpose: map type definitions
Author: mikel evins
***********************************************************************
---------------------------------------------------------------------
alist
---------------------------------------------------------------------
elements are lists
---------------------------------------------------------------------
plist
---------------------------------------------------------------------
elements whose even-indexed elements are atoms | Name :
Copyright : 2015 by mikel evins
(in-package :net.bardcode.folio2.maps)
for the purposes of , an alist is a list all of whose
(defmethod alist? (thing)
(declare (ignore thing))
nil)
(defmethod alist? ((thing cons))
(and thing
(every 'consp thing)))
(deftype alist ()
`(and list
(satisfies alist?)))
for the purposes of , a plist is a list with an even number of
(defmethod plist? (thing)
(declare (ignore thing))
nil)
(defmethod plist? ((thing cons))
(and thing
(block testing
(loop for tail on thing by #'cddr
do (unless (and (cdr tail)
(atom (car tail)))
(return-from testing nil)))
t)))
(deftype plist ()
`(and list
(satisfies plist?)))
|
102a0ed16790b4113ad2ce68c632a857be6a88ee27bb649afadcbc116e12bb7c | soegaard/sketching | sketch-mandelbrot.rkt | #lang sketching
(define xmin -2.5)
(define xmax 1.0)
(define ymin -1.0)
(define ymax 1.0)
(define dx (- xmax xmin))
(define dy (- ymax ymin))
(define aspect (/ dx dy))
(define max-iterations 50) ; what is reasonable here?
(define (setup)
(define h 200)
(size (int (* h aspect)) h)
(color-mode 'hsb 360 100 100)
(frame-rate 1)
(no-loop))
(define (on-mouse-pressed)
(displayln "pressed")
(define x0 (remap mouse-x 0. width xmin xmax))
(define y0 (remap mouse-y 0. height ymin ymax))
(define zoom 0.6)
(define dx (- xmax xmin))
(define dy (- ymax ymin))
(:= xmin (- x0 (* zoom (/ dx 2.))))
(:= xmax (+ x0 (* zoom (/ dx 2.))))
(:= ymin (- y0 (* zoom (/ dy 2.))))
(:= ymax (+ y0 (* zoom (/ dy 2.))))
(loop)) ; make sure draw updates the image
(define (iterations x0 y0)
(let loop ([iteration 0] [x 0.] [y 0.])
(cond
[(and (<= (+ (* x x) (* y y)) 4.)
(< iteration max-iterations))
(let ([xt (+ (* x x) (* -1. y y) x0)])
(loop (+ iteration 1)
xt (+ (* 2. x y) y0)))]
[else
iteration])))
(define (draw)
(stroke-weight 1)
(background 255)
(smoothing 'unsmoothed)
(no-loop)
(time
(for ([py (in-range 0 height)])
(for ([px (in-range 0 width)])
(define x0 (remap px 0. width xmin xmax))
(define y0 (remap py 0. height ymin ymax))
(define n (iterations x0 y0))
(define c (palette n))
(stroke c)
(point px py)))))
(define (palette n)
(define hue (int (remap n 0. max-iterations 0 360)))
(if (= n max-iterations)
"black"
(color hue 100 100 100)))
| null | https://raw.githubusercontent.com/soegaard/sketching/99892486efad866eabe6ab34515fb3951b2a7858/sketching-examples/examples/sketch-mandelbrot.rkt | racket | what is reasonable here?
make sure draw updates the image | #lang sketching
(define xmin -2.5)
(define xmax 1.0)
(define ymin -1.0)
(define ymax 1.0)
(define dx (- xmax xmin))
(define dy (- ymax ymin))
(define aspect (/ dx dy))
(define (setup)
(define h 200)
(size (int (* h aspect)) h)
(color-mode 'hsb 360 100 100)
(frame-rate 1)
(no-loop))
(define (on-mouse-pressed)
(displayln "pressed")
(define x0 (remap mouse-x 0. width xmin xmax))
(define y0 (remap mouse-y 0. height ymin ymax))
(define zoom 0.6)
(define dx (- xmax xmin))
(define dy (- ymax ymin))
(:= xmin (- x0 (* zoom (/ dx 2.))))
(:= xmax (+ x0 (* zoom (/ dx 2.))))
(:= ymin (- y0 (* zoom (/ dy 2.))))
(:= ymax (+ y0 (* zoom (/ dy 2.))))
(define (iterations x0 y0)
(let loop ([iteration 0] [x 0.] [y 0.])
(cond
[(and (<= (+ (* x x) (* y y)) 4.)
(< iteration max-iterations))
(let ([xt (+ (* x x) (* -1. y y) x0)])
(loop (+ iteration 1)
xt (+ (* 2. x y) y0)))]
[else
iteration])))
(define (draw)
(stroke-weight 1)
(background 255)
(smoothing 'unsmoothed)
(no-loop)
(time
(for ([py (in-range 0 height)])
(for ([px (in-range 0 width)])
(define x0 (remap px 0. width xmin xmax))
(define y0 (remap py 0. height ymin ymax))
(define n (iterations x0 y0))
(define c (palette n))
(stroke c)
(point px py)))))
(define (palette n)
(define hue (int (remap n 0. max-iterations 0 360)))
(if (= n max-iterations)
"black"
(color hue 100 100 100)))
|
172ab01f0d4dd742cc9204127992eab9dacf31d9c37c0b7418a37574808afbda | quil-lang/magicl | complex-single-float.lisp | ;;;; complex-single-float.lisp
;;;;
Author :
(in-package #:magicl)
(deftensor tensor/complex-single-float (complex single-float))
(defmatrix matrix/complex-single-float (complex single-float) tensor/complex-single-float)
(defvector vector/complex-single-float (complex single-float) tensor/complex-single-float)
(defcompatible
(lambda (tensor)
(case (order tensor)
(1 '(vector/complex-single-float
tensor/complex-single-float))
(2 '(matrix/complex-single-float
tensor/complex-single-float))
(t '(tensor/complex-single-float))))
tensor/complex-single-float
matrix/complex-single-float
vector/complex-single-float)
(defmethod .realpart-lisp ((m matrix/complex-single-float))
(let ((re-m (zeros (shape m) :type 'single-float)))
(map-to #'realpart m re-m)
re-m))
(defmethod .imagpart-lisp ((m matrix/complex-single-float))
(let ((im-m (zeros (shape m) :type 'single-float)))
(map-to #'imagpart m im-m)
im-m))
(defmethod =-lisp ((tensor1 tensor/complex-single-float) (tensor2 tensor/complex-single-float) &optional (epsilon *float-comparison-threshold*))
(unless (equal (shape tensor1) (shape tensor2))
(return-from =-lisp nil))
(map-indexes
(shape tensor1)
(lambda (&rest pos)
(unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos))
(realpart (apply #'tref tensor2 pos))))
epsilon)
(<= (abs (- (imagpart (apply #'tref tensor1 pos))
(imagpart (apply #'tref tensor2 pos))))
epsilon))
(return-from =-lisp nil))))
t)
(defmethod =-lisp ((tensor1 matrix/complex-single-float) (tensor2 matrix/complex-single-float) &optional (epsilon *float-comparison-threshold*))
(unless (equal (shape tensor1) (shape tensor2))
(return-from =-lisp nil))
(map-indexes
(shape tensor1)
(lambda (&rest pos)
(unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos))
(realpart (apply #'tref tensor2 pos))))
epsilon)
(<= (abs (- (imagpart (apply #'tref tensor1 pos))
(imagpart (apply #'tref tensor2 pos))))
epsilon))
(return-from =-lisp nil))))
t)
(defmethod =-lisp ((tensor1 vector/complex-single-float) (tensor2 vector/complex-single-float) &optional (epsilon *float-comparison-threshold*))
(unless (equal (shape tensor1) (shape tensor2))
(return-from =-lisp nil))
(map-indexes
(shape tensor1)
(lambda (&rest pos)
(unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos))
(realpart (apply #'tref tensor2 pos))))
epsilon)
(<= (abs (- (imagpart (apply #'tref tensor1 pos))
(imagpart (apply #'tref tensor2 pos))))
epsilon))
(return-from =-lisp nil))))
t)
| null | https://raw.githubusercontent.com/quil-lang/magicl/a10a6c8ce7c7910029d247bbc170c09d3a1e79fd/src/high-level/types/complex-single-float.lisp | lisp | complex-single-float.lisp
| Author :
(in-package #:magicl)
(deftensor tensor/complex-single-float (complex single-float))
(defmatrix matrix/complex-single-float (complex single-float) tensor/complex-single-float)
(defvector vector/complex-single-float (complex single-float) tensor/complex-single-float)
(defcompatible
(lambda (tensor)
(case (order tensor)
(1 '(vector/complex-single-float
tensor/complex-single-float))
(2 '(matrix/complex-single-float
tensor/complex-single-float))
(t '(tensor/complex-single-float))))
tensor/complex-single-float
matrix/complex-single-float
vector/complex-single-float)
(defmethod .realpart-lisp ((m matrix/complex-single-float))
(let ((re-m (zeros (shape m) :type 'single-float)))
(map-to #'realpart m re-m)
re-m))
(defmethod .imagpart-lisp ((m matrix/complex-single-float))
(let ((im-m (zeros (shape m) :type 'single-float)))
(map-to #'imagpart m im-m)
im-m))
(defmethod =-lisp ((tensor1 tensor/complex-single-float) (tensor2 tensor/complex-single-float) &optional (epsilon *float-comparison-threshold*))
(unless (equal (shape tensor1) (shape tensor2))
(return-from =-lisp nil))
(map-indexes
(shape tensor1)
(lambda (&rest pos)
(unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos))
(realpart (apply #'tref tensor2 pos))))
epsilon)
(<= (abs (- (imagpart (apply #'tref tensor1 pos))
(imagpart (apply #'tref tensor2 pos))))
epsilon))
(return-from =-lisp nil))))
t)
(defmethod =-lisp ((tensor1 matrix/complex-single-float) (tensor2 matrix/complex-single-float) &optional (epsilon *float-comparison-threshold*))
(unless (equal (shape tensor1) (shape tensor2))
(return-from =-lisp nil))
(map-indexes
(shape tensor1)
(lambda (&rest pos)
(unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos))
(realpart (apply #'tref tensor2 pos))))
epsilon)
(<= (abs (- (imagpart (apply #'tref tensor1 pos))
(imagpart (apply #'tref tensor2 pos))))
epsilon))
(return-from =-lisp nil))))
t)
(defmethod =-lisp ((tensor1 vector/complex-single-float) (tensor2 vector/complex-single-float) &optional (epsilon *float-comparison-threshold*))
(unless (equal (shape tensor1) (shape tensor2))
(return-from =-lisp nil))
(map-indexes
(shape tensor1)
(lambda (&rest pos)
(unless (and (<= (abs (- (realpart (apply #'tref tensor1 pos))
(realpart (apply #'tref tensor2 pos))))
epsilon)
(<= (abs (- (imagpart (apply #'tref tensor1 pos))
(imagpart (apply #'tref tensor2 pos))))
epsilon))
(return-from =-lisp nil))))
t)
|
2e7ae302c7f85509fa63c2e8549d4cf81beede60c52c2ecd5842f327a8b10f60 | xtdb/xtdb | bench.clj | (ns xtdb.bench
(:require [clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.string :as string]
[clojure.tools.logging :as log]
[juxt.clojars-mirrors.clj-http.v3v12v2.clj-http.client :as client]
[xtdb.api :as xt]
[xtdb.bench.cloudwatch :as cw]
[xtdb.bus :as bus]
[xtdb.fixtures :as f]
[xtdb.jdbc :as j]
[xtdb.kafka :as k]
[xtdb.kafka.embedded :as ek]
[xtdb.kv :as kv]
[xtdb.lmdb :as lmdb]
[xtdb.rocksdb :as rocks])
(:import (com.amazonaws.services.logs AWSLogsClient AWSLogsClientBuilder)
(com.amazonaws.services.logs.model GetQueryResultsRequest ResultField StartQueryRequest)
(com.amazonaws.services.simpleemail AmazonSimpleEmailServiceClient AmazonSimpleEmailServiceClientBuilder)
(com.amazonaws.services.simpleemail.model Body Content Destination Message SendEmailRequest)
(java.io File)
(java.time Duration)
(java.util Date List UUID)
(java.util.concurrent Executors ExecutorService)
(software.amazon.awssdk.core.exception SdkClientException)
(software.amazon.awssdk.core.sync RequestBody)
(software.amazon.awssdk.services.s3 S3Client)
(software.amazon.awssdk.services.s3.model GetObjectRequest PutObjectRequest)))
(def commit-hash
(System/getenv "COMMIT_HASH"))
(def ^:dynamic ^:private *bench-ns*)
(def ^:dynamic ^:private *bench-dimensions* {})
(def ^:dynamic ^:private *!bench-results*)
(defn with-dimensions* [dims f]
(binding [*bench-dimensions* (merge *bench-dimensions* dims)]
(f)))
(defmacro with-dimensions [dims & body]
`(with-dimensions* ~dims (fn [] ~@body)))
(defmacro with-xtdb-dimensions [& body]
`(with-dimensions {:xtdb-commit commit-hash}
~@body))
(defn with-timing* [f]
(let [start-time-ms (System/currentTimeMillis)
ret (try
(f)
(catch Exception e
(log/errorf e "caught exception during '%s':" *bench-ns*)
{:error (str e)}))]
(merge (when (map? ret) ret)
{:time-taken-ms (- (System/currentTimeMillis) start-time-ms)})))
(defmacro with-timing [& body]
`(with-timing* (fn [] ~@body)))
(defn with-additional-index-metrics* [node f]
(let [!index-metrics (atom {:av-count 0
:bytes-indexed 0
:doc-count 0})]
(bus/listen (:bus node)
{::xt/event-types #{:xtdb.tx/indexed-tx}}
(fn [{:keys [doc-ids av-count bytes-indexed]}]
(swap! !index-metrics (fn [index-metrics-map]
(-> index-metrics-map
(update :av-count + av-count)
(update :bytes-indexed + bytes-indexed)
(update :doc-count + (count doc-ids)))))))
(let [results (f)]
(assoc results
:av-count (:av-count @!index-metrics)
:bytes-indexed (:bytes-indexed @!index-metrics)
:doc-count (:doc-count @!index-metrics)))))
(defmacro with-additional-index-metrics [node & body]
`(with-additional-index-metrics* ~node (fn [] ~@body)))
(defn run-bench* [bench-type f]
(log/infof "running bench '%s/%s'..." *bench-ns* (name bench-type))
(let [ret (with-timing (f))
res (merge (when (map? ret) ret)
*bench-dimensions*
{:bench-type bench-type})]
(log/infof "finished bench '%s/%s'." *bench-ns* (name bench-type))
(swap! *!bench-results* conj res)
res))
(defmacro run-bench {:style/indent 1} [bench-type & body]
`(run-bench* ~bench-type (fn [] ~@body)))
(defn compact-node [node]
(run-bench :compaction
(let [pre-compact-bytes (:xtdb.kv/size (xt/status node))]
(kv/compact (get-in node [:index-store :kv-store]))
{:bytes-on-disk pre-compact-bytes
:compacted-bytes-on-disk (:xtdb.kv/size (xt/status node))})))
(defn post-to-slack [message]
(if-let [slack-url (System/getenv "BENCH_SECRETS")]
(try
(client/post (-> slack-url
(json/read-str)
(get "slack-url"))
{:body (json/write-str {:text message})
:content-type :json})
(catch Exception e
(println "Failed to post to slack, error: " e)))
(println "Would post to Slack:\n" message)))
;; From #Clojure
(defn sparkline [nums]
(let [sparks "▁▂▃▄▅▆▇█"
high (apply max nums)
low (apply min nums)
spread (- high low)
quantize #(Math/round (* 7.0 (/ (- % low) (max spread 1))))]
(apply str (map #(nth sparks (quantize %)) nums))))
(defn- result->slack-message [{:keys [time-taken-ms error bench-type percentage-difference-since-last-run
minimum-time-taken-this-week maximum-time-taken-this-week times-taken
doc-count av-count bytes-indexed]
:as bench-map}]
(->> (concat [(format "*%s* (%s, *%s%%*. 7D Min: %s, 7D Max: %s, Trend: %s): `%s`"
(name bench-type)
(Duration/ofMillis time-taken-ms)
(if (neg? percentage-difference-since-last-run)
(format "%.2f" percentage-difference-since-last-run)
(format "+%.2f" percentage-difference-since-last-run))
(Duration/ofMillis minimum-time-taken-this-week)
(Duration/ofMillis maximum-time-taken-this-week)
(sparkline times-taken)
(pr-str (dissoc bench-map :bench-ns :bench-type :xtdb-node-type :xtdb-commit :time-taken-ms
:percentage-difference-since-last-run :minimum-time-taken-this-week :maximum-time-taken-this-week :times-taken)))]
(when (and (= bench-type :ingest) doc-count av-count bytes-indexed)
(->> (let [time-taken-seconds (/ time-taken-ms 1000)]
{:docs-per-second (int (/ doc-count time-taken-seconds))
:avs-per-second (int (/ av-count time-taken-seconds))
:bytes-indexed-per-second (int (/ bytes-indexed time-taken-seconds))})
(map (fn [[k v]] (format "*%s*: %s" (name k) v))))))
(string/join "\n")))
(defn results->slack-message [results]
(format "*%s* (%s)\n========\n%s\n"
(:bench-ns (first results))
(:xtdb-node-type (first results))
(->> results
(map result->slack-message)
(string/join "\n"))))
(defn- result->html [{:keys [time-taken-ms bench-type percentage-difference-since-last-run
minimum-time-taken-this-week maximum-time-taken-this-week times-taken
doc-count av-count bytes-indexed] :as bench-map}]
(->> (concat [(format "<p> <b>%s</b> (%s, %s. 7D Min: %s, 7D Max: %s, Trend: %s): <code>%s</code></p>"
(name bench-type)
(Duration/ofMillis time-taken-ms)
(if (neg? percentage-difference-since-last-run)
(format "<b style=\"color: green\">%.2f%%</b>" percentage-difference-since-last-run)
(format "<b style=\"color: red\">+%.2f%%</b>" percentage-difference-since-last-run))
(Duration/ofMillis minimum-time-taken-this-week)
(Duration/ofMillis maximum-time-taken-this-week)
(sparkline times-taken)
(pr-str (dissoc bench-map :bench-ns :bench-type :xtdb-node-type :xtdb-commit :time-taken-ms
:percentage-difference-since-last-run :minimum-time-taken-this-week :maximum-time-taken-this-week :times-taken)))]
(when (= bench-type :ingest)
(->> (let [time-taken-seconds (/ time-taken-ms 1000)]
{:docs-per-second (int (/ doc-count time-taken-seconds))
:avs-per-second (int (/ av-count time-taken-seconds))
:bytes-indexed-per-second (int (/ bytes-indexed time-taken-seconds))})
(map (fn [[k v]] (format "<p><b>%s</b>: <code>%s</code></p>" (name k) v))))))
(string/join " ")))
(defn results->email [bench-results]
(str "<h1>XTDB bench results</h1>"
(->> (for [[bench-ns results] (group-by :bench-ns bench-results)]
(str (format "<h2>%s</h2>" bench-ns)
(->> (for [[xtdb-node-type results] (group-by :xtdb-node-type results)]
(format "<h3>%s</h3> %s"
xtdb-node-type
(->> results
(map result->html)
(string/join " "))))
(string/join))))
(string/join))))
(defn with-bench-ns* [bench-ns f]
(log/infof "running bench-ns '%s'..." bench-ns)
(binding [*bench-ns* bench-ns
*!bench-results* (atom [])]
(with-dimensions {:bench-ns bench-ns}
(f))
(log/infof "finished bench-ns '%s'." bench-ns)
(doto @*!bench-results*
(->> (run! (comp println json/write-str)))
(cw/put-cw-metrics!))))
(defmacro with-bench-ns [bench-ns & body]
`(with-bench-ns* ~bench-ns (fn [] ~@body)))
(def cw-reporter-opts
{:jvm-metrics? true
:dry-run-report-frequency (Duration/ofMinutes 1)})
(def nodes
{"standalone-rocksdb"
(fn [data-dir]
{:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "tx-log")}}
:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "doc-store")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"rocksdb-lucene"
(fn [data-dir]
{:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "tx-log")}}
:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "doc-store")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.lucene/lucene-store {:db-dir (io/file data-dir "lucene")}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"standalone-rocksdb-with-metrics"
(fn [data-dir]
{:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "tx-log")}}
:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "doc-store")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store
:db-dir (io/file data-dir "indexes")
:metrics `xtdb.rocksdb.metrics/->metrics}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"h2-rocksdb"
(fn [data-dir]
{::j/connection-pool {:dialect 'xtdb.jdbc.h2/->dialect
:db-spec {:dbname (str (io/file data-dir "h2"))}}
:xtdb/tx-log {:xtdb/module `j/->tx-log, :connection-pool ::j/connection-pool}
:xtdb/document-store {:xtdb/module `j/->document-store, :connection-pool ::j/connection-pool}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"sqlite-rocksdb"
(fn [data-dir]
{::j/connection-pool {:dialect 'xtdb.jdbc.sqlite/->dialect
:db-spec {:dbname (str (io/file data-dir "sqlite"))}}
:xtdb/tx-log {:xtdb/module `j/->tx-log, :connection-pool ::j/connection-pool}
:xtdb/document-store {:xtdb/module `j/->document-store, :connection-pool ::j/connection-pool}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"kafka-rocksdb"
(fn [data-dir]
(let [uuid (UUID/randomUUID)]
{::k/kafka-config {:bootstrap-servers "localhost:9092"}
:xtdb/tx-log {:xtdb/module `k/->tx-log
:kafka-config ::k/kafka-config
:tx-topic-opts {:topic-name (str "kafka-rocksdb-tx-" uuid)}}
:xtdb/document-store {:xtdb/module `k/->document-store,
:kafka-config ::k/kafka-config
:doc-topic-opts {:topic-name (str "kafka-rocksdb-doc-" uuid)}
:local-document-store {:kv-store {:xtdb/module `rocks/->kv-store
:db-dir (io/file data-dir "doc-store")}}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "index-store")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts}))
"embedded-kafka-rocksdb"
(fn [data-dir]
(let [uuid (UUID/randomUUID)]
{::k/kafka-config {:bootstrap-servers "localhost:9091"}
:xtdb/tx-log {:xtdb/module `k/->tx-log
:kafka-config ::k/kafka-config
:tx-topic-opts {:topic-name (str "kafka-rocksdb-tx-" uuid)}}
:xtdb/document-store {:xtdb/module `k/->document-store
:kafka-config ::k/kafka-config
:doc-topic-opts {:topic-name (str "kafka-rocksdb-doc-" uuid)}
:local-document-store {:kv-store {:xtdb/module `rocks/->kv-store
:db-dir (io/file data-dir "doc-store")}}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "index-store")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts}))
"postgres-rocksdb"
(fn [^File data-dir]
{:xtdb.jdbc/connection-pool {:dialect {:xtdb/module 'xtdb.jdbc.psql/->dialect
:drop-table? true}
:db-spec {:dbname "postgres",
:user "postgres",
:password "postgres"}}
:xtdb/tx-log {:xtdb/module 'xtdb.jdbc/->tx-log
:connection-pool :xtdb.jdbc/connection-pool}
:xtdb/document-store {:xtdb/module 'xtdb.jdbc/->document-store
:connection-pool :xtdb.jdbc/connection-pool}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "index-store")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"standalone-lmdb"
(fn [data-dir]
{:xtdb/tx-log {:kv-store {:xtdb/module `lmdb/->kv-store, :db-dir (io/file data-dir "tx-log")}}
:xtdb/document-store {:kv-store {:xtdb/module `lmdb/->kv-store, :db-dir (io/file data-dir "doc-store")}}
:xtdb/index-store {:kv-store {:xtdb/module `lmdb/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"kafka-lmdb"
(fn [data-dir]
(let [uuid (UUID/randomUUID)]
{::k/kafka-config {:bootstrap-servers "localhost:9092"}
:xtdb/tx-log {:xtdb/module `k/->tx-log
:kafka-config ::k/kafka-config
:tx-topic-opts {:topic-name (str "kafka-lmdb-tx-" uuid)}}
:xtdb/document-store {:xtdb/module `k/->document-store
:kafka-config ::k/kafka-config
:doc-topic-opts {:topic-name (str "kafka-lmdb-doc-" uuid)}
:local-document-store {:kv-store {:xtdb/module `lmdb/->kv-store
:db-dir (io/file data-dir "doc-store")}}}
:xtdb/index-store {:kv-store {:xtdb/module `lmdb/->kv-store, :db-dir (io/file data-dir "index-store")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts}))})
(defn with-embedded-kafka* [f]
(f/with-tmp-dir "embedded-kafka" [data-dir]
(with-open [_emb (ek/start-embedded-kafka
#::ek{:zookeeper-data-dir (str (io/file data-dir "zookeeper"))
:kafka-log-dir (str (io/file data-dir "kafka-log"))
:kafka-port 9091})]
(f))))
(defmacro with-embedded-kafka [& body]
`(with-embedded-kafka* (fn [] ~@body)))
(defn with-nodes* [nodes f]
(->> (for [[node-type ->node] nodes]
(f/with-tmp-dir "xtdb-node" [data-dir]
(with-open [node (xt/start-node (->node data-dir))]
(with-dimensions {:xtdb-node-type node-type}
(log/infof "Running bench on %s node." node-type)
(f node)))))
(apply concat)
(vec)))
(defmacro with-nodes [[node-binding nodes] & body]
`(with-nodes* ~nodes (fn [~node-binding] ~@body)))
(def ^:private num-processors
(.availableProcessors (Runtime/getRuntime)))
(defn with-thread-pool [{:keys [num-threads], :or {num-threads num-processors}} f args]
(let [^ExecutorService pool (Executors/newFixedThreadPool num-threads)]
(with-dimensions {:num-threads num-threads}
(try
(let [futures (->> (for [arg args]
(let [^Callable job (bound-fn [] (f arg))]
(.submit pool job)))
doall)]
(mapv deref futures))
(finally
(.shutdownNow pool))))))
(defn save-to-file [file results]
(with-open [w (io/writer file)]
(doseq [res results]
(.write w (prn-str res)))))
(defn- generate-s3-filename [database version]
(let [formatted-date (->> (java.util.Date.)
(.format (java.text.SimpleDateFormat. "yyyyMMdd-HHmmss")))]
(format "%s-%s/%s-%sZ.edn" database version database formatted-date)))
(def s3-client
(delay
(-> (S3Client/builder)
(.build))))
(defn save-to-s3 [{:keys [database version]} ^File file]
(try
(.putObject ^S3Client @s3-client
(-> (PutObjectRequest/builder)
(.bucket "xtdb-bench")
(.key (generate-s3-filename database version))
^PutObjectRequest (.build))
(RequestBody/fromFile file))
(catch SdkClientException _
"AWS credentials not found! Results file not saved.")))
(defn load-from-s3 [key]
(try
(.getObject ^S3Client @s3-client
(-> (GetObjectRequest/builder)
(.bucket "xtdb-bench")
(.key key)
^GetObjectRequest (.build)))
(catch SdkClientException _
(log/warn (format "AWS credentials not found! File %s not loaded" key)))))
(def log-client
(delay
(try
(AWSLogsClientBuilder/defaultClient)
(catch com.amazonaws.SdkClientException _
(log/info "AWS credentials not found! Cannot get comparison times.")))))
(defn get-comparison-times [results]
(let [^AWSLogsClient log-client @log-client
query-requests (for [{:keys [xtdb-node-type bench-type bench-ns]} results]
(let [query-id (-> (.startQuery log-client
(-> (StartQueryRequest.)
(.withLogGroupName "xtdb-bench")
(.withQueryString (format "fields `time-taken-ms` | filter `xtdb-node-type` = '%s' | filter `bench-type` = '%s' | filter `bench-ns` = '%s' | sort @timestamp desc"
xtdb-node-type (name bench-type) (name bench-ns)))
(.withStartTime (-> (Date.)
(.toInstant)
(.minus (Duration/ofDays 7))
(.toEpochMilli)))
(.withEndTime (.getTime (Date.)))))
(.getQueryId))]
(-> (GetQueryResultsRequest.)
(.withQueryId query-id))))]
(while (not-any? (fn [query-request]
(= "Complete"
(->> (.getQueryResults log-client query-request)
(.getStatus))))
query-requests)
(Thread/sleep 100))
(mapv (fn [query-request]
(->> (map first (-> (.getQueryResults log-client query-request)
(.getResults)))
(map #(.getValue ^ResultField %))
(map #(Integer/parseInt %))))
query-requests)))
(defn with-comparison-times [results]
(map (fn [{:keys [time-taken-ms] :as result} times-taken]
(if (empty? times-taken)
(assoc
result
:percentage-difference-since-last-run 0.0
:minimum-time-taken-this-week 0
:maximum-time-taken-this-week 0
:times-taken [time-taken-ms])
(assoc
result
:percentage-difference-since-last-run (-> time-taken-ms
(- (first times-taken))
(/ (double (first times-taken)))
(* 100)
(double))
:minimum-time-taken-this-week (apply min times-taken)
:maximum-time-taken-this-week (apply max times-taken)
:times-taken (conj (vec (reverse times-taken)) time-taken-ms))))
results
(try
(get-comparison-times results)
(catch Exception e
TODO something about the above is triggering AWS Logs rate limits , # 1693
(log/warn e "error getting comparison times: " (.getMessage e))
(vec (repeat (count results) nil))))))
(defn send-email-via-ses [message]
(try
(let [client (-> (AmazonSimpleEmailServiceClientBuilder/standard)
(.withRegion "eu-west-1")
^AmazonSimpleEmailServiceClient (.build))
email (-> (SendEmailRequest.)
(.withDestination (let [^List to-addresses [(string/replace "xtdb-bench at juxt.pro" " at " "@")]]
(-> (Destination.)
(.withToAddresses to-addresses))))
(.withMessage
(-> (Message.)
(.withBody (-> (Body.)
(.withHtml (-> (Content.)
(.withCharset "UTF-8")
(.withData message)))))
(.withSubject (-> (Content.)
(.withCharset "UTF-8")
(.withData (str "Bench Results"))))))
(.withSource ""))]
(.sendEmail client email))
(catch Exception e
(log/warn "Email failed to send! Error: " e))))
| null | https://raw.githubusercontent.com/xtdb/xtdb/b038f2e215b2c74898930056859162ab3c3fad03/bench/src/xtdb/bench.clj | clojure | From #Clojure | (ns xtdb.bench
(:require [clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.string :as string]
[clojure.tools.logging :as log]
[juxt.clojars-mirrors.clj-http.v3v12v2.clj-http.client :as client]
[xtdb.api :as xt]
[xtdb.bench.cloudwatch :as cw]
[xtdb.bus :as bus]
[xtdb.fixtures :as f]
[xtdb.jdbc :as j]
[xtdb.kafka :as k]
[xtdb.kafka.embedded :as ek]
[xtdb.kv :as kv]
[xtdb.lmdb :as lmdb]
[xtdb.rocksdb :as rocks])
(:import (com.amazonaws.services.logs AWSLogsClient AWSLogsClientBuilder)
(com.amazonaws.services.logs.model GetQueryResultsRequest ResultField StartQueryRequest)
(com.amazonaws.services.simpleemail AmazonSimpleEmailServiceClient AmazonSimpleEmailServiceClientBuilder)
(com.amazonaws.services.simpleemail.model Body Content Destination Message SendEmailRequest)
(java.io File)
(java.time Duration)
(java.util Date List UUID)
(java.util.concurrent Executors ExecutorService)
(software.amazon.awssdk.core.exception SdkClientException)
(software.amazon.awssdk.core.sync RequestBody)
(software.amazon.awssdk.services.s3 S3Client)
(software.amazon.awssdk.services.s3.model GetObjectRequest PutObjectRequest)))
(def commit-hash
(System/getenv "COMMIT_HASH"))
(def ^:dynamic ^:private *bench-ns*)
(def ^:dynamic ^:private *bench-dimensions* {})
(def ^:dynamic ^:private *!bench-results*)
(defn with-dimensions* [dims f]
(binding [*bench-dimensions* (merge *bench-dimensions* dims)]
(f)))
(defmacro with-dimensions [dims & body]
`(with-dimensions* ~dims (fn [] ~@body)))
(defmacro with-xtdb-dimensions [& body]
`(with-dimensions {:xtdb-commit commit-hash}
~@body))
(defn with-timing* [f]
(let [start-time-ms (System/currentTimeMillis)
ret (try
(f)
(catch Exception e
(log/errorf e "caught exception during '%s':" *bench-ns*)
{:error (str e)}))]
(merge (when (map? ret) ret)
{:time-taken-ms (- (System/currentTimeMillis) start-time-ms)})))
(defmacro with-timing [& body]
`(with-timing* (fn [] ~@body)))
(defn with-additional-index-metrics* [node f]
(let [!index-metrics (atom {:av-count 0
:bytes-indexed 0
:doc-count 0})]
(bus/listen (:bus node)
{::xt/event-types #{:xtdb.tx/indexed-tx}}
(fn [{:keys [doc-ids av-count bytes-indexed]}]
(swap! !index-metrics (fn [index-metrics-map]
(-> index-metrics-map
(update :av-count + av-count)
(update :bytes-indexed + bytes-indexed)
(update :doc-count + (count doc-ids)))))))
(let [results (f)]
(assoc results
:av-count (:av-count @!index-metrics)
:bytes-indexed (:bytes-indexed @!index-metrics)
:doc-count (:doc-count @!index-metrics)))))
(defmacro with-additional-index-metrics [node & body]
`(with-additional-index-metrics* ~node (fn [] ~@body)))
(defn run-bench* [bench-type f]
(log/infof "running bench '%s/%s'..." *bench-ns* (name bench-type))
(let [ret (with-timing (f))
res (merge (when (map? ret) ret)
*bench-dimensions*
{:bench-type bench-type})]
(log/infof "finished bench '%s/%s'." *bench-ns* (name bench-type))
(swap! *!bench-results* conj res)
res))
(defmacro run-bench {:style/indent 1} [bench-type & body]
`(run-bench* ~bench-type (fn [] ~@body)))
(defn compact-node [node]
(run-bench :compaction
(let [pre-compact-bytes (:xtdb.kv/size (xt/status node))]
(kv/compact (get-in node [:index-store :kv-store]))
{:bytes-on-disk pre-compact-bytes
:compacted-bytes-on-disk (:xtdb.kv/size (xt/status node))})))
(defn post-to-slack [message]
(if-let [slack-url (System/getenv "BENCH_SECRETS")]
(try
(client/post (-> slack-url
(json/read-str)
(get "slack-url"))
{:body (json/write-str {:text message})
:content-type :json})
(catch Exception e
(println "Failed to post to slack, error: " e)))
(println "Would post to Slack:\n" message)))
(defn sparkline [nums]
(let [sparks "▁▂▃▄▅▆▇█"
high (apply max nums)
low (apply min nums)
spread (- high low)
quantize #(Math/round (* 7.0 (/ (- % low) (max spread 1))))]
(apply str (map #(nth sparks (quantize %)) nums))))
(defn- result->slack-message [{:keys [time-taken-ms error bench-type percentage-difference-since-last-run
minimum-time-taken-this-week maximum-time-taken-this-week times-taken
doc-count av-count bytes-indexed]
:as bench-map}]
(->> (concat [(format "*%s* (%s, *%s%%*. 7D Min: %s, 7D Max: %s, Trend: %s): `%s`"
(name bench-type)
(Duration/ofMillis time-taken-ms)
(if (neg? percentage-difference-since-last-run)
(format "%.2f" percentage-difference-since-last-run)
(format "+%.2f" percentage-difference-since-last-run))
(Duration/ofMillis minimum-time-taken-this-week)
(Duration/ofMillis maximum-time-taken-this-week)
(sparkline times-taken)
(pr-str (dissoc bench-map :bench-ns :bench-type :xtdb-node-type :xtdb-commit :time-taken-ms
:percentage-difference-since-last-run :minimum-time-taken-this-week :maximum-time-taken-this-week :times-taken)))]
(when (and (= bench-type :ingest) doc-count av-count bytes-indexed)
(->> (let [time-taken-seconds (/ time-taken-ms 1000)]
{:docs-per-second (int (/ doc-count time-taken-seconds))
:avs-per-second (int (/ av-count time-taken-seconds))
:bytes-indexed-per-second (int (/ bytes-indexed time-taken-seconds))})
(map (fn [[k v]] (format "*%s*: %s" (name k) v))))))
(string/join "\n")))
(defn results->slack-message [results]
(format "*%s* (%s)\n========\n%s\n"
(:bench-ns (first results))
(:xtdb-node-type (first results))
(->> results
(map result->slack-message)
(string/join "\n"))))
(defn- result->html [{:keys [time-taken-ms bench-type percentage-difference-since-last-run
minimum-time-taken-this-week maximum-time-taken-this-week times-taken
doc-count av-count bytes-indexed] :as bench-map}]
(->> (concat [(format "<p> <b>%s</b> (%s, %s. 7D Min: %s, 7D Max: %s, Trend: %s): <code>%s</code></p>"
(name bench-type)
(Duration/ofMillis time-taken-ms)
(if (neg? percentage-difference-since-last-run)
(format "<b style=\"color: green\">%.2f%%</b>" percentage-difference-since-last-run)
(format "<b style=\"color: red\">+%.2f%%</b>" percentage-difference-since-last-run))
(Duration/ofMillis minimum-time-taken-this-week)
(Duration/ofMillis maximum-time-taken-this-week)
(sparkline times-taken)
(pr-str (dissoc bench-map :bench-ns :bench-type :xtdb-node-type :xtdb-commit :time-taken-ms
:percentage-difference-since-last-run :minimum-time-taken-this-week :maximum-time-taken-this-week :times-taken)))]
(when (= bench-type :ingest)
(->> (let [time-taken-seconds (/ time-taken-ms 1000)]
{:docs-per-second (int (/ doc-count time-taken-seconds))
:avs-per-second (int (/ av-count time-taken-seconds))
:bytes-indexed-per-second (int (/ bytes-indexed time-taken-seconds))})
(map (fn [[k v]] (format "<p><b>%s</b>: <code>%s</code></p>" (name k) v))))))
(string/join " ")))
(defn results->email [bench-results]
(str "<h1>XTDB bench results</h1>"
(->> (for [[bench-ns results] (group-by :bench-ns bench-results)]
(str (format "<h2>%s</h2>" bench-ns)
(->> (for [[xtdb-node-type results] (group-by :xtdb-node-type results)]
(format "<h3>%s</h3> %s"
xtdb-node-type
(->> results
(map result->html)
(string/join " "))))
(string/join))))
(string/join))))
(defn with-bench-ns* [bench-ns f]
(log/infof "running bench-ns '%s'..." bench-ns)
(binding [*bench-ns* bench-ns
*!bench-results* (atom [])]
(with-dimensions {:bench-ns bench-ns}
(f))
(log/infof "finished bench-ns '%s'." bench-ns)
(doto @*!bench-results*
(->> (run! (comp println json/write-str)))
(cw/put-cw-metrics!))))
(defmacro with-bench-ns [bench-ns & body]
`(with-bench-ns* ~bench-ns (fn [] ~@body)))
(def cw-reporter-opts
{:jvm-metrics? true
:dry-run-report-frequency (Duration/ofMinutes 1)})
(def nodes
{"standalone-rocksdb"
(fn [data-dir]
{:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "tx-log")}}
:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "doc-store")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"rocksdb-lucene"
(fn [data-dir]
{:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "tx-log")}}
:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "doc-store")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.lucene/lucene-store {:db-dir (io/file data-dir "lucene")}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"standalone-rocksdb-with-metrics"
(fn [data-dir]
{:xtdb/tx-log {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "tx-log")}}
:xtdb/document-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "doc-store")}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store
:db-dir (io/file data-dir "indexes")
:metrics `xtdb.rocksdb.metrics/->metrics}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"h2-rocksdb"
(fn [data-dir]
{::j/connection-pool {:dialect 'xtdb.jdbc.h2/->dialect
:db-spec {:dbname (str (io/file data-dir "h2"))}}
:xtdb/tx-log {:xtdb/module `j/->tx-log, :connection-pool ::j/connection-pool}
:xtdb/document-store {:xtdb/module `j/->document-store, :connection-pool ::j/connection-pool}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"sqlite-rocksdb"
(fn [data-dir]
{::j/connection-pool {:dialect 'xtdb.jdbc.sqlite/->dialect
:db-spec {:dbname (str (io/file data-dir "sqlite"))}}
:xtdb/tx-log {:xtdb/module `j/->tx-log, :connection-pool ::j/connection-pool}
:xtdb/document-store {:xtdb/module `j/->document-store, :connection-pool ::j/connection-pool}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"kafka-rocksdb"
(fn [data-dir]
(let [uuid (UUID/randomUUID)]
{::k/kafka-config {:bootstrap-servers "localhost:9092"}
:xtdb/tx-log {:xtdb/module `k/->tx-log
:kafka-config ::k/kafka-config
:tx-topic-opts {:topic-name (str "kafka-rocksdb-tx-" uuid)}}
:xtdb/document-store {:xtdb/module `k/->document-store,
:kafka-config ::k/kafka-config
:doc-topic-opts {:topic-name (str "kafka-rocksdb-doc-" uuid)}
:local-document-store {:kv-store {:xtdb/module `rocks/->kv-store
:db-dir (io/file data-dir "doc-store")}}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "index-store")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts}))
"embedded-kafka-rocksdb"
(fn [data-dir]
(let [uuid (UUID/randomUUID)]
{::k/kafka-config {:bootstrap-servers "localhost:9091"}
:xtdb/tx-log {:xtdb/module `k/->tx-log
:kafka-config ::k/kafka-config
:tx-topic-opts {:topic-name (str "kafka-rocksdb-tx-" uuid)}}
:xtdb/document-store {:xtdb/module `k/->document-store
:kafka-config ::k/kafka-config
:doc-topic-opts {:topic-name (str "kafka-rocksdb-doc-" uuid)}
:local-document-store {:kv-store {:xtdb/module `rocks/->kv-store
:db-dir (io/file data-dir "doc-store")}}}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "index-store")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts}))
"postgres-rocksdb"
(fn [^File data-dir]
{:xtdb.jdbc/connection-pool {:dialect {:xtdb/module 'xtdb.jdbc.psql/->dialect
:drop-table? true}
:db-spec {:dbname "postgres",
:user "postgres",
:password "postgres"}}
:xtdb/tx-log {:xtdb/module 'xtdb.jdbc/->tx-log
:connection-pool :xtdb.jdbc/connection-pool}
:xtdb/document-store {:xtdb/module 'xtdb.jdbc/->document-store
:connection-pool :xtdb.jdbc/connection-pool}
:xtdb/index-store {:kv-store {:xtdb/module `rocks/->kv-store, :db-dir (io/file data-dir "index-store")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"standalone-lmdb"
(fn [data-dir]
{:xtdb/tx-log {:kv-store {:xtdb/module `lmdb/->kv-store, :db-dir (io/file data-dir "tx-log")}}
:xtdb/document-store {:kv-store {:xtdb/module `lmdb/->kv-store, :db-dir (io/file data-dir "doc-store")}}
:xtdb/index-store {:kv-store {:xtdb/module `lmdb/->kv-store, :db-dir (io/file data-dir "indexes")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts})
"kafka-lmdb"
(fn [data-dir]
(let [uuid (UUID/randomUUID)]
{::k/kafka-config {:bootstrap-servers "localhost:9092"}
:xtdb/tx-log {:xtdb/module `k/->tx-log
:kafka-config ::k/kafka-config
:tx-topic-opts {:topic-name (str "kafka-lmdb-tx-" uuid)}}
:xtdb/document-store {:xtdb/module `k/->document-store
:kafka-config ::k/kafka-config
:doc-topic-opts {:topic-name (str "kafka-lmdb-doc-" uuid)}
:local-document-store {:kv-store {:xtdb/module `lmdb/->kv-store
:db-dir (io/file data-dir "doc-store")}}}
:xtdb/index-store {:kv-store {:xtdb/module `lmdb/->kv-store, :db-dir (io/file data-dir "index-store")}}
:xtdb.metrics.cloudwatch/reporter cw-reporter-opts}))})
(defn with-embedded-kafka* [f]
(f/with-tmp-dir "embedded-kafka" [data-dir]
(with-open [_emb (ek/start-embedded-kafka
#::ek{:zookeeper-data-dir (str (io/file data-dir "zookeeper"))
:kafka-log-dir (str (io/file data-dir "kafka-log"))
:kafka-port 9091})]
(f))))
(defmacro with-embedded-kafka [& body]
`(with-embedded-kafka* (fn [] ~@body)))
(defn with-nodes* [nodes f]
(->> (for [[node-type ->node] nodes]
(f/with-tmp-dir "xtdb-node" [data-dir]
(with-open [node (xt/start-node (->node data-dir))]
(with-dimensions {:xtdb-node-type node-type}
(log/infof "Running bench on %s node." node-type)
(f node)))))
(apply concat)
(vec)))
(defmacro with-nodes [[node-binding nodes] & body]
`(with-nodes* ~nodes (fn [~node-binding] ~@body)))
(def ^:private num-processors
(.availableProcessors (Runtime/getRuntime)))
(defn with-thread-pool [{:keys [num-threads], :or {num-threads num-processors}} f args]
(let [^ExecutorService pool (Executors/newFixedThreadPool num-threads)]
(with-dimensions {:num-threads num-threads}
(try
(let [futures (->> (for [arg args]
(let [^Callable job (bound-fn [] (f arg))]
(.submit pool job)))
doall)]
(mapv deref futures))
(finally
(.shutdownNow pool))))))
(defn save-to-file [file results]
(with-open [w (io/writer file)]
(doseq [res results]
(.write w (prn-str res)))))
(defn- generate-s3-filename [database version]
(let [formatted-date (->> (java.util.Date.)
(.format (java.text.SimpleDateFormat. "yyyyMMdd-HHmmss")))]
(format "%s-%s/%s-%sZ.edn" database version database formatted-date)))
(def s3-client
(delay
(-> (S3Client/builder)
(.build))))
(defn save-to-s3 [{:keys [database version]} ^File file]
(try
(.putObject ^S3Client @s3-client
(-> (PutObjectRequest/builder)
(.bucket "xtdb-bench")
(.key (generate-s3-filename database version))
^PutObjectRequest (.build))
(RequestBody/fromFile file))
(catch SdkClientException _
"AWS credentials not found! Results file not saved.")))
(defn load-from-s3 [key]
(try
(.getObject ^S3Client @s3-client
(-> (GetObjectRequest/builder)
(.bucket "xtdb-bench")
(.key key)
^GetObjectRequest (.build)))
(catch SdkClientException _
(log/warn (format "AWS credentials not found! File %s not loaded" key)))))
(def log-client
(delay
(try
(AWSLogsClientBuilder/defaultClient)
(catch com.amazonaws.SdkClientException _
(log/info "AWS credentials not found! Cannot get comparison times.")))))
(defn get-comparison-times [results]
(let [^AWSLogsClient log-client @log-client
query-requests (for [{:keys [xtdb-node-type bench-type bench-ns]} results]
(let [query-id (-> (.startQuery log-client
(-> (StartQueryRequest.)
(.withLogGroupName "xtdb-bench")
(.withQueryString (format "fields `time-taken-ms` | filter `xtdb-node-type` = '%s' | filter `bench-type` = '%s' | filter `bench-ns` = '%s' | sort @timestamp desc"
xtdb-node-type (name bench-type) (name bench-ns)))
(.withStartTime (-> (Date.)
(.toInstant)
(.minus (Duration/ofDays 7))
(.toEpochMilli)))
(.withEndTime (.getTime (Date.)))))
(.getQueryId))]
(-> (GetQueryResultsRequest.)
(.withQueryId query-id))))]
(while (not-any? (fn [query-request]
(= "Complete"
(->> (.getQueryResults log-client query-request)
(.getStatus))))
query-requests)
(Thread/sleep 100))
(mapv (fn [query-request]
(->> (map first (-> (.getQueryResults log-client query-request)
(.getResults)))
(map #(.getValue ^ResultField %))
(map #(Integer/parseInt %))))
query-requests)))
(defn with-comparison-times [results]
(map (fn [{:keys [time-taken-ms] :as result} times-taken]
(if (empty? times-taken)
(assoc
result
:percentage-difference-since-last-run 0.0
:minimum-time-taken-this-week 0
:maximum-time-taken-this-week 0
:times-taken [time-taken-ms])
(assoc
result
:percentage-difference-since-last-run (-> time-taken-ms
(- (first times-taken))
(/ (double (first times-taken)))
(* 100)
(double))
:minimum-time-taken-this-week (apply min times-taken)
:maximum-time-taken-this-week (apply max times-taken)
:times-taken (conj (vec (reverse times-taken)) time-taken-ms))))
results
(try
(get-comparison-times results)
(catch Exception e
TODO something about the above is triggering AWS Logs rate limits , # 1693
(log/warn e "error getting comparison times: " (.getMessage e))
(vec (repeat (count results) nil))))))
(defn send-email-via-ses [message]
(try
(let [client (-> (AmazonSimpleEmailServiceClientBuilder/standard)
(.withRegion "eu-west-1")
^AmazonSimpleEmailServiceClient (.build))
email (-> (SendEmailRequest.)
(.withDestination (let [^List to-addresses [(string/replace "xtdb-bench at juxt.pro" " at " "@")]]
(-> (Destination.)
(.withToAddresses to-addresses))))
(.withMessage
(-> (Message.)
(.withBody (-> (Body.)
(.withHtml (-> (Content.)
(.withCharset "UTF-8")
(.withData message)))))
(.withSubject (-> (Content.)
(.withCharset "UTF-8")
(.withData (str "Bench Results"))))))
(.withSource ""))]
(.sendEmail client email))
(catch Exception e
(log/warn "Email failed to send! Error: " e))))
|
e75d30c271deb04917d04f68e7487f75ee67146d9de95c27f2c575ee3a011434 | thlack/surfs | input.clj | (ns ^:no-doc thlack.surfs.blocks.spec.input
(:require [clojure.spec.alpha :as s]
[thlack.surfs.composition.spec :as comp.spec]
[thlack.surfs.elements.spec :as elements.spec]
[thlack.surfs.strings.spec :refer [deftext]]))
(s/def ::type #{:input})
(deftext ::label ::comp.spec/plain-text 2000)
(s/def ::element
(s/or :plain-text-input ::elements.spec/plain-text-input
:checkboxes ::elements.spec/checkboxes
:radio-buttons ::elements.spec/radio-buttons
:datepicker ::elements.spec/datepicker
:timepicker ::elements.spec/timepicker
:multi-static-select ::elements.spec/multi-static-select
:multi-external-select ::elements.spec/multi-external-select
:multi-users-select ::elements.spec/multi-users-select
:multi-conversations-select ::elements.spec/multi-conversations-select
:multi-channels-select ::elements.spec/multi-channels-select
:plain-text-input ::elements.spec/plain-text-input
:radio-buttons ::elements.spec/radio-buttons
:static-select ::elements.spec/static-select
:external-select ::elements.spec/external-select
:users-select ::elements.spec/users-select
:conversations-select ::elements.spec/conversations-select
:channels-select ::elements.spec/channels-select))
(s/def ::dispatch_action boolean?)
(deftext ::hint ::comp.spec/plain-text 2000)
(s/def ::optional boolean?)
| null | https://raw.githubusercontent.com/thlack/surfs/e03d137d6d43c4b73a45a71984cf084d2904c4b0/src/thlack/surfs/blocks/spec/input.clj | clojure | (ns ^:no-doc thlack.surfs.blocks.spec.input
(:require [clojure.spec.alpha :as s]
[thlack.surfs.composition.spec :as comp.spec]
[thlack.surfs.elements.spec :as elements.spec]
[thlack.surfs.strings.spec :refer [deftext]]))
(s/def ::type #{:input})
(deftext ::label ::comp.spec/plain-text 2000)
(s/def ::element
(s/or :plain-text-input ::elements.spec/plain-text-input
:checkboxes ::elements.spec/checkboxes
:radio-buttons ::elements.spec/radio-buttons
:datepicker ::elements.spec/datepicker
:timepicker ::elements.spec/timepicker
:multi-static-select ::elements.spec/multi-static-select
:multi-external-select ::elements.spec/multi-external-select
:multi-users-select ::elements.spec/multi-users-select
:multi-conversations-select ::elements.spec/multi-conversations-select
:multi-channels-select ::elements.spec/multi-channels-select
:plain-text-input ::elements.spec/plain-text-input
:radio-buttons ::elements.spec/radio-buttons
:static-select ::elements.spec/static-select
:external-select ::elements.spec/external-select
:users-select ::elements.spec/users-select
:conversations-select ::elements.spec/conversations-select
:channels-select ::elements.spec/channels-select))
(s/def ::dispatch_action boolean?)
(deftext ::hint ::comp.spec/plain-text 2000)
(s/def ::optional boolean?)
| |
cc3775ec60c8323ea23c535d9deb7fece650a4f56963be7852df5fa60be709f5 | ds-wizard/engine-backend | LocaleList.hs | module Wizard.Database.Mapping.Locale.LocaleList where
import Database.PostgreSQL.Simple
import Wizard.Database.Mapping.Locale.LocaleState ()
import Wizard.Model.Locale.LocaleList
instance FromRow LocaleList
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/0ec94a4b0545f2de8a4e59686a4376023719d5e7/engine-wizard/src/Wizard/Database/Mapping/Locale/LocaleList.hs | haskell | module Wizard.Database.Mapping.Locale.LocaleList where
import Database.PostgreSQL.Simple
import Wizard.Database.Mapping.Locale.LocaleState ()
import Wizard.Model.Locale.LocaleList
instance FromRow LocaleList
| |
4cd95175bf66ce4a09c77913ac2128b4b0fd865058bf6c91ba31bbd5630fae5f | arttuka/reagent-material-ui | no_adult_content_sharp.cljs | (ns reagent-mui.icons.no-adult-content-sharp
"Imports @mui/icons-material/NoAdultContentSharp 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 no-adult-content-sharp (create-svg-icon [(e "path" #js {"d" "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-1.85.63-3.54 1.69-4.9L7.59 9h2.83L7.1 5.69C8.46 4.63 10.15 4 12 4c4.41 0 8 3.59 8 8 0 1.85-.63 3.54-1.69 4.9l-1.9-1.9h-2.83l3.31 3.31C15.54 19.37 13.85 20 12 20c-4.41 0-8-3.59-8-8z"}) (e "path" #js {"d" "m14.25 14-1.5-2 1.5-2h-1.5L12 11l-.75-1h-1.5l1.5 2-1.5 2h1.5l.75-1 .75 1zM8 10l-.75 1-.75-1H5l1.5 2L5 14h1.5l.75-1L8 14h1.5L8 12l1.5-2zm8 4 .75-1 .75 1H19l-1.5-2 1.5-2h-1.5l-.75 1-.75-1h-1.5l1.5 2-1.5 2z"})]
"NoAdultContentSharp"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/icons/reagent_mui/icons/no_adult_content_sharp.cljs | clojure | (ns reagent-mui.icons.no-adult-content-sharp
"Imports @mui/icons-material/NoAdultContentSharp 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 no-adult-content-sharp (create-svg-icon [(e "path" #js {"d" "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-1.85.63-3.54 1.69-4.9L7.59 9h2.83L7.1 5.69C8.46 4.63 10.15 4 12 4c4.41 0 8 3.59 8 8 0 1.85-.63 3.54-1.69 4.9l-1.9-1.9h-2.83l3.31 3.31C15.54 19.37 13.85 20 12 20c-4.41 0-8-3.59-8-8z"}) (e "path" #js {"d" "m14.25 14-1.5-2 1.5-2h-1.5L12 11l-.75-1h-1.5l1.5 2-1.5 2h1.5l.75-1 .75 1zM8 10l-.75 1-.75-1H5l1.5 2L5 14h1.5l.75-1L8 14h1.5L8 12l1.5-2zm8 4 .75-1 .75 1H19l-1.5-2 1.5-2h-1.5l-.75 1-.75-1h-1.5l1.5 2-1.5 2z"})]
"NoAdultContentSharp"))
| |
43c036b17bd7b6abafe4869dfb20ef7fdc8cfe03252563ddbeb9457b67977ea6 | clojure/clojurescript | node.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns cljs.server.node
(:require [cljs.env :as env]
[cljs.repl :as repl]
[cljs.repl.node :as node]
[cljs.core.server :as server])
(:import [java.net Socket]))
(defonce envs (atom {}))
(defn env-opts->key [{:keys [host port]}]
[host port])
(defn stale? [{:keys [socket] :as repl-env}]
(if-let [sock (:socket @socket)]
(.isClosed ^Socket sock)
false))
(defn get-envs [env-opts]
(let [env-opts (merge {:host "localhost" :port 49001} env-opts)
k (env-opts->key env-opts)]
(swap! envs
#(cond-> %
(or (not (contains? % k))
(stale? (get-in % [k 0])))
(assoc k
[(node/repl-env* env-opts)
(env/default-compiler-env)])))
(get @envs k)))
(defn repl
([]
(repl nil))
([{:keys [opts env-opts]}]
(let [[env cenv] (get-envs env-opts)]
(env/with-compiler-env cenv
(repl/repl* env opts)))))
(defn prepl
([]
(prepl nil))
([{:keys [opts env-opts]}]
(let [[env cenv] (get-envs env-opts)]
(env/with-compiler-env cenv
(apply server/io-prepl
(mapcat identity
{:repl-env env :opts opts}))))))
| null | https://raw.githubusercontent.com/clojure/clojurescript/a4673b880756531ac5690f7b4721ad76c0810327/src/main/clojure/cljs/server/node.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) . All rights reserved .
(ns cljs.server.node
(:require [cljs.env :as env]
[cljs.repl :as repl]
[cljs.repl.node :as node]
[cljs.core.server :as server])
(:import [java.net Socket]))
(defonce envs (atom {}))
(defn env-opts->key [{:keys [host port]}]
[host port])
(defn stale? [{:keys [socket] :as repl-env}]
(if-let [sock (:socket @socket)]
(.isClosed ^Socket sock)
false))
(defn get-envs [env-opts]
(let [env-opts (merge {:host "localhost" :port 49001} env-opts)
k (env-opts->key env-opts)]
(swap! envs
#(cond-> %
(or (not (contains? % k))
(stale? (get-in % [k 0])))
(assoc k
[(node/repl-env* env-opts)
(env/default-compiler-env)])))
(get @envs k)))
(defn repl
([]
(repl nil))
([{:keys [opts env-opts]}]
(let [[env cenv] (get-envs env-opts)]
(env/with-compiler-env cenv
(repl/repl* env opts)))))
(defn prepl
([]
(prepl nil))
([{:keys [opts env-opts]}]
(let [[env cenv] (get-envs env-opts)]
(env/with-compiler-env cenv
(apply server/io-prepl
(mapcat identity
{:repl-env env :opts opts}))))))
|
d954256ebc748f49cdd80d6f78bf773e08f04c9bcdec0dbc723586f42805cd86 | YoEight/lambda-database-experiment | Main.hs | -- Tasty makes it easy to test your code. It is a test framework that can
combine many different types of tests into one suite . See its website for
-- help: <>.
import qualified Test.Tasty
Hspec is one of the providers for Tasty . It provides a nice syntax for
-- writing tests. Its website has more info: <>.
import Test.Tasty.Hspec
main :: IO ()
main = do
test <- testSpec "lambda-bus" spec
Test.Tasty.defaultMain test
spec :: Spec
spec = parallel $ do
it "is trivially true" $ do
True `shouldBe` True | null | https://raw.githubusercontent.com/YoEight/lambda-database-experiment/da4fab8bd358fb8fb78412c805d6f5bc05854432/lambda-bus/test-suite/Main.hs | haskell | Tasty makes it easy to test your code. It is a test framework that can
help: <>.
writing tests. Its website has more info: <>. | combine many different types of tests into one suite . See its website for
import qualified Test.Tasty
Hspec is one of the providers for Tasty . It provides a nice syntax for
import Test.Tasty.Hspec
main :: IO ()
main = do
test <- testSpec "lambda-bus" spec
Test.Tasty.defaultMain test
spec :: Spec
spec = parallel $ do
it "is trivially true" $ do
True `shouldBe` True |
1099fedac301b1c6e1d41711e42f9823ad6f6c84bbe3c9d747e07840d51f0bd1 | TeMPOraL/alice | frequencies.lisp | (in-package #:alice)
(defvar *frequencies* '(("467.550" . "Taxi Barbakan, to z Jedyneczką :).")
("145.650" . "Pokój i dobro, wita przemiennik na Koskowej Górze.")
("145.550" . "Krakowska wywoławcza.")))
(define-constant +freq-extraction-regexp+ "(\\d{3}\\.\\d{3})" :test #'string=)
(register-matcher :random-frequency
(list (match-score (lambda (input)
(and (directedp input)
(or (mentions "ciekaw" (unquoted-part input))
(mentions "fajn" (unquoted-part input))
(mentions "dawaj jakąś" (unquoted-part input)))))
0.4)
(match-score (lambda (input)
(and (directedp input)
(mentions "częstotliwość" (unquoted-part input))))
0.75)
(match-score (lambda (input)
(and (directedp input)
(mentions +freq-extraction-regexp+ (unquoted-part input))))
-1))
(lambda (input)
(say (reply-to input) (describe-random-frequency) :to (author input))))
(register-matcher :whats-the-frequency
(list (match-score (lambda (input)
(and (directedp input)
(or (mentions "co to" (unquoted-part input))
(mentions "jaka" (unquoted-part input))
(mentions "co jest" (unquoted-part input)))))
0.5)
(match-score (lambda (input)
(and (directedp input)
(mentions "częstotliwoś" (unquoted-part input))))
0.7)
(match-score (lambda (input)
(and (directedp input)
(mentions +freq-extraction-regexp+ (unquoted-part input))))
1.25))
(lambda (input)
(say (reply-to input) (describe-frequency (extract-frequency (unquoted-part input))) :to (author input))))
(provide-output :unknown-frequency '("Nie znam tej częstotliwości."
"Nie kojarzę..."
"Nie wiem."
"No clue."))
(defun extract-frequency (text)
(cl-ppcre:scan-to-strings +freq-extraction-regexp+ text))
(defun describe-frequency (freq)
(if-let ((freq-data (assoc freq *frequencies* :test #'string=)))
(cdr freq-data)
:unknown-frequency))
(defun describe-random-frequency ()
(let ((freq (random-elt *frequencies*)))
(concatenate 'string (car freq) " → " (cdr freq))))
| null | https://raw.githubusercontent.com/TeMPOraL/alice/4621a53ccd459bebf0b34c531dab49f7b42f35c7/grimoire/frequencies.lisp | lisp | (in-package #:alice)
(defvar *frequencies* '(("467.550" . "Taxi Barbakan, to z Jedyneczką :).")
("145.650" . "Pokój i dobro, wita przemiennik na Koskowej Górze.")
("145.550" . "Krakowska wywoławcza.")))
(define-constant +freq-extraction-regexp+ "(\\d{3}\\.\\d{3})" :test #'string=)
(register-matcher :random-frequency
(list (match-score (lambda (input)
(and (directedp input)
(or (mentions "ciekaw" (unquoted-part input))
(mentions "fajn" (unquoted-part input))
(mentions "dawaj jakąś" (unquoted-part input)))))
0.4)
(match-score (lambda (input)
(and (directedp input)
(mentions "częstotliwość" (unquoted-part input))))
0.75)
(match-score (lambda (input)
(and (directedp input)
(mentions +freq-extraction-regexp+ (unquoted-part input))))
-1))
(lambda (input)
(say (reply-to input) (describe-random-frequency) :to (author input))))
(register-matcher :whats-the-frequency
(list (match-score (lambda (input)
(and (directedp input)
(or (mentions "co to" (unquoted-part input))
(mentions "jaka" (unquoted-part input))
(mentions "co jest" (unquoted-part input)))))
0.5)
(match-score (lambda (input)
(and (directedp input)
(mentions "częstotliwoś" (unquoted-part input))))
0.7)
(match-score (lambda (input)
(and (directedp input)
(mentions +freq-extraction-regexp+ (unquoted-part input))))
1.25))
(lambda (input)
(say (reply-to input) (describe-frequency (extract-frequency (unquoted-part input))) :to (author input))))
(provide-output :unknown-frequency '("Nie znam tej częstotliwości."
"Nie kojarzę..."
"Nie wiem."
"No clue."))
(defun extract-frequency (text)
(cl-ppcre:scan-to-strings +freq-extraction-regexp+ text))
(defun describe-frequency (freq)
(if-let ((freq-data (assoc freq *frequencies* :test #'string=)))
(cdr freq-data)
:unknown-frequency))
(defun describe-random-frequency ()
(let ((freq (random-elt *frequencies*)))
(concatenate 'string (car freq) " → " (cdr freq))))
| |
700e89c4cd6003605fd40209f58c6d5b1ec7fa18d0fff0e11832ec92b3117aa7 | OCamlPro/ocp-build | ocpCompat.ml | (**************************************************************************)
(* *)
(* Typerex Tools *)
(* *)
Copyright 2011 - 2017 OCamlPro SAS
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU General Public License version 3 described in the file
(* LICENSE. *)
(* *)
(**************************************************************************)
type bytes = string
module Bytes = struct
include String
let to_string t = String.copy t
let of_string t = String.copy t
let unsafe_to_string t = t
let unsafe_of_string t = t
let sub_string = String.sub
let blit_string = String.blit
end
module Buffer = struct
include Buffer
let to_bytes b = contents b
let add_subbytes = add_substring
end
module Marshal = struct
include Marshal
let from_bytes = from_string
end
let print_bytes = print_string
let prerr_bytes = prerr_string
let output_bytes = output_string
let output_substring = output
let really_input_string ic len =
let s = String.create len in
really_input ic s 0 len;
s
module StringSet = Set.Make(String)
module StringMap = struct
module M = Map.Make(String)
include M
let of_list list =
let map = ref empty in
List.iter (fun (x,y) -> map := add x y !map) list;
!map
let to_list map =
let list = ref [] in
iter (fun x y -> list := (x,y) :: !list) map;
List.rev !list
let to_list_of_keys map =
let list = ref [] in
iter (fun x y -> list := x :: !list) map;
List.rev !list
end
| null | https://raw.githubusercontent.com/OCamlPro/ocp-build/56aff560bb438c12b2929feaf8379bc6f31b9840/tools/ocp-pp/compat/4.00.0/ocpCompat.ml | ocaml | ************************************************************************
Typerex Tools
All rights reserved. This file is distributed under the terms of
LICENSE.
************************************************************************ | Copyright 2011 - 2017 OCamlPro SAS
the GNU General Public License version 3 described in the file
type bytes = string
module Bytes = struct
include String
let to_string t = String.copy t
let of_string t = String.copy t
let unsafe_to_string t = t
let unsafe_of_string t = t
let sub_string = String.sub
let blit_string = String.blit
end
module Buffer = struct
include Buffer
let to_bytes b = contents b
let add_subbytes = add_substring
end
module Marshal = struct
include Marshal
let from_bytes = from_string
end
let print_bytes = print_string
let prerr_bytes = prerr_string
let output_bytes = output_string
let output_substring = output
let really_input_string ic len =
let s = String.create len in
really_input ic s 0 len;
s
module StringSet = Set.Make(String)
module StringMap = struct
module M = Map.Make(String)
include M
let of_list list =
let map = ref empty in
List.iter (fun (x,y) -> map := add x y !map) list;
!map
let to_list map =
let list = ref [] in
iter (fun x y -> list := (x,y) :: !list) map;
List.rev !list
let to_list_of_keys map =
let list = ref [] in
iter (fun x y -> list := x :: !list) map;
List.rev !list
end
|
5db8aa847f96b61090c2fd140064fa6b1dffc4fbf216bf4be6744b76dfbfaaf9 | kowainik/stan | Pretty.hs | |
Copyright : ( c ) 2020 Kowainik
SPDX - License - Identifier : MPL-2.0
Maintainer : < >
Pretty printing of 's analysis .
Copyright: (c) 2020 Kowainik
SPDX-License-Identifier: MPL-2.0
Maintainer: Kowainik <>
Pretty printing of Stan's analysis.
-}
module Stan.Analysis.Pretty
( prettyShowAnalysis
-- * Numbers
, AnalysisNumbers (..)
, ProjectHealth (..)
, analysisToNumbers
, prettyHealth
, toProjectHealth
) where
import Colourista.Short (b, i)
import Extensions (ExtensionsError, ParsedExtensions)
import Text.Printf (printf)
import Stan.Analysis (Analysis (..))
import Stan.Core.ModuleName (ModuleName (..))
import Stan.FileInfo (FileInfo (..), extensionsToText)
import Stan.Observation (Observation (..), prettyShowObservation)
import Stan.Report.Settings (OutputSettings (..), Verbosity (..))
import qualified Data.HashSet as HS
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Slist as S
| Shows analysed output of work .
This functions groups ' Observation 's by ' FilePath ' they are found in .
This functions groups 'Observation's by 'FilePath' they are found in.
-}
prettyShowAnalysis :: Analysis -> OutputSettings -> Text
prettyShowAnalysis an rs@OutputSettings{..} = case outputSettingsVerbosity of
Verbose -> groupedObservations <> summary (analysisToNumbers an)
NonVerbose -> unlines $ toList $ prettyShowObservation rs <$> analysisObservations an
where
groupedObservations :: Text
groupedObservations =
Text.intercalate "\n\n"
$ filter (/= "")
$ map (showByFile rs)
$ Map.elems
$ analysisFileMap an
data AnalysisNumbers = AnalysisNumbers
{ anModules :: !Int
, anLoc :: !Int
, anExts :: !Int
, anSafeExts :: !Int
, anIns :: !Int
, anFoundObs :: !Int
, anIgnoredObs :: !Int
, anHealth :: !Double
}
analysisToNumbers :: Analysis -> AnalysisNumbers
analysisToNumbers Analysis{..} = AnalysisNumbers
{ anModules = analysisModulesNum
, anLoc = analysisLinesOfCode
, anExts = Set.size $ fst analysisUsedExtensions
, anSafeExts = Set.size $ snd analysisUsedExtensions
, anIns = HS.size analysisInspections
, anFoundObs = length analysisObservations
, anIgnoredObs = length analysisIgnoredObservations
, anHealth = calculatedHealth
}
where
calculatedHealth :: Double
calculatedHealth =
-- all inspections ignored or no observations
if null analysisInspections || null analysisObservations
then 100
else
let totalInspections = fromIntegral $ HS.size analysisInspections
triggeredInspections =
fromIntegral
$ Set.size
$ Set.fromList
$ map observationInspectionId
$ toList analysisObservations
in 100 * (1 - triggeredInspections / totalInspections)
| Show project health as pretty text with 2 digits after dot .
-}
prettyHealth :: Double -> Text
prettyHealth health =
if fromIntegral (floor health :: Int) == health -- display without decimal part
then toText (printf "%.0f" health :: String) <> "%"
else toText (printf "%.2f" health :: String) <> "%"
{- | Enum to describe project health depending on the value of
'anHealth'.
-}
data ProjectHealth
= Unhealthy
| LowHealth
| MediumHealth
| Healthy
| Calculate ' ProjectHealth ' .
toProjectHealth :: Double -> ProjectHealth
toProjectHealth health
| health >= 100 = Healthy
| health >= 80 = MediumHealth
| health >= 40 = LowHealth
| otherwise = Unhealthy
summary :: AnalysisNumbers -> Text
summary AnalysisNumbers{..} = unlines
[ ""
, b " Stan's Summary:"
, top
, alignText "Analysed modules" <> alignNum anModules
, mid
, alignText "Analysed Lines of Code" <> alignNum anLoc
, mid
, alignText "Total Haskell2010 extensions" <> alignNum anExts
, mid
, alignText "Total SafeHaskell extensions" <> alignNum anSafeExts
, mid
, alignText "Total checked inspections" <> alignNum anIns
, mid
, alignText "Total found observations" <> alignNum anFoundObs
, mid
, alignText "Total ignored observations" <> alignNum anIgnoredObs
, mid
, alignText "Project health" <> alignVal (prettyHealth anHealth)
, bot
]
where
alignNum :: Int -> Text
alignNum = alignVal . show
alignVal :: Text -> Text
alignVal x = " ┃ " <> Text.justifyLeft 6 ' ' x <> " ┃"
alignText :: Text -> Text
alignText txt ="┃ " <> Text.justifyLeft 28 ' ' txt
separator :: Text -> Text -> Text -> Text
separator l c r = l <> Text.replicate 30 "━" <> c <> Text.replicate 8 "━" <> r
top, mid, bot :: Text
top = separator "┏" "┳" "┓"
mid = separator "┣" "╋" "┫"
bot = separator "┗" "┻" "┛"
showByFile :: OutputSettings -> FileInfo -> Text
showByFile outputSettings FileInfo{..} = if len == 0 then "" else unlines
[ i " File: " <> b (toText fileInfoPath)
, i " Module: " <> b (unModuleName fileInfoModuleName)
, i " LoC: " <> b (show fileInfoLoc)
, i " Observations: " <> b (show len)
, i " Extensions from .cabal: " <> b (showExts fileInfoCabalExtensions)
, i " Extensions from module: " <> b (showExts fileInfoExtensions)
, " ┏" <> Text.replicate 78 "━"
]
<> Text.intercalate (" ┃\n ┃" <> Text.replicate 78 "~" <> "\n ┃\n")
(toList $ prettyShowObservation outputSettings <$> S.sortOn observationSrcSpan fileInfoObservations)
where
len :: Int
len = length fileInfoObservations
showExts :: Either ExtensionsError ParsedExtensions -> Text
showExts = Text.intercalate ", " . extensionsToText
| null | https://raw.githubusercontent.com/kowainik/stan/da36eac741466fe6f46dc3e56fca7806f8b41816/src/Stan/Analysis/Pretty.hs | haskell | * Numbers
all inspections ignored or no observations
display without decimal part
| Enum to describe project health depending on the value of
'anHealth'.
| |
Copyright : ( c ) 2020 Kowainik
SPDX - License - Identifier : MPL-2.0
Maintainer : < >
Pretty printing of 's analysis .
Copyright: (c) 2020 Kowainik
SPDX-License-Identifier: MPL-2.0
Maintainer: Kowainik <>
Pretty printing of Stan's analysis.
-}
module Stan.Analysis.Pretty
( prettyShowAnalysis
, AnalysisNumbers (..)
, ProjectHealth (..)
, analysisToNumbers
, prettyHealth
, toProjectHealth
) where
import Colourista.Short (b, i)
import Extensions (ExtensionsError, ParsedExtensions)
import Text.Printf (printf)
import Stan.Analysis (Analysis (..))
import Stan.Core.ModuleName (ModuleName (..))
import Stan.FileInfo (FileInfo (..), extensionsToText)
import Stan.Observation (Observation (..), prettyShowObservation)
import Stan.Report.Settings (OutputSettings (..), Verbosity (..))
import qualified Data.HashSet as HS
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Slist as S
| Shows analysed output of work .
This functions groups ' Observation 's by ' FilePath ' they are found in .
This functions groups 'Observation's by 'FilePath' they are found in.
-}
prettyShowAnalysis :: Analysis -> OutputSettings -> Text
prettyShowAnalysis an rs@OutputSettings{..} = case outputSettingsVerbosity of
Verbose -> groupedObservations <> summary (analysisToNumbers an)
NonVerbose -> unlines $ toList $ prettyShowObservation rs <$> analysisObservations an
where
groupedObservations :: Text
groupedObservations =
Text.intercalate "\n\n"
$ filter (/= "")
$ map (showByFile rs)
$ Map.elems
$ analysisFileMap an
data AnalysisNumbers = AnalysisNumbers
{ anModules :: !Int
, anLoc :: !Int
, anExts :: !Int
, anSafeExts :: !Int
, anIns :: !Int
, anFoundObs :: !Int
, anIgnoredObs :: !Int
, anHealth :: !Double
}
analysisToNumbers :: Analysis -> AnalysisNumbers
analysisToNumbers Analysis{..} = AnalysisNumbers
{ anModules = analysisModulesNum
, anLoc = analysisLinesOfCode
, anExts = Set.size $ fst analysisUsedExtensions
, anSafeExts = Set.size $ snd analysisUsedExtensions
, anIns = HS.size analysisInspections
, anFoundObs = length analysisObservations
, anIgnoredObs = length analysisIgnoredObservations
, anHealth = calculatedHealth
}
where
calculatedHealth :: Double
calculatedHealth =
if null analysisInspections || null analysisObservations
then 100
else
let totalInspections = fromIntegral $ HS.size analysisInspections
triggeredInspections =
fromIntegral
$ Set.size
$ Set.fromList
$ map observationInspectionId
$ toList analysisObservations
in 100 * (1 - triggeredInspections / totalInspections)
| Show project health as pretty text with 2 digits after dot .
-}
prettyHealth :: Double -> Text
prettyHealth health =
then toText (printf "%.0f" health :: String) <> "%"
else toText (printf "%.2f" health :: String) <> "%"
data ProjectHealth
= Unhealthy
| LowHealth
| MediumHealth
| Healthy
| Calculate ' ProjectHealth ' .
toProjectHealth :: Double -> ProjectHealth
toProjectHealth health
| health >= 100 = Healthy
| health >= 80 = MediumHealth
| health >= 40 = LowHealth
| otherwise = Unhealthy
summary :: AnalysisNumbers -> Text
summary AnalysisNumbers{..} = unlines
[ ""
, b " Stan's Summary:"
, top
, alignText "Analysed modules" <> alignNum anModules
, mid
, alignText "Analysed Lines of Code" <> alignNum anLoc
, mid
, alignText "Total Haskell2010 extensions" <> alignNum anExts
, mid
, alignText "Total SafeHaskell extensions" <> alignNum anSafeExts
, mid
, alignText "Total checked inspections" <> alignNum anIns
, mid
, alignText "Total found observations" <> alignNum anFoundObs
, mid
, alignText "Total ignored observations" <> alignNum anIgnoredObs
, mid
, alignText "Project health" <> alignVal (prettyHealth anHealth)
, bot
]
where
alignNum :: Int -> Text
alignNum = alignVal . show
alignVal :: Text -> Text
alignVal x = " ┃ " <> Text.justifyLeft 6 ' ' x <> " ┃"
alignText :: Text -> Text
alignText txt ="┃ " <> Text.justifyLeft 28 ' ' txt
separator :: Text -> Text -> Text -> Text
separator l c r = l <> Text.replicate 30 "━" <> c <> Text.replicate 8 "━" <> r
top, mid, bot :: Text
top = separator "┏" "┳" "┓"
mid = separator "┣" "╋" "┫"
bot = separator "┗" "┻" "┛"
showByFile :: OutputSettings -> FileInfo -> Text
showByFile outputSettings FileInfo{..} = if len == 0 then "" else unlines
[ i " File: " <> b (toText fileInfoPath)
, i " Module: " <> b (unModuleName fileInfoModuleName)
, i " LoC: " <> b (show fileInfoLoc)
, i " Observations: " <> b (show len)
, i " Extensions from .cabal: " <> b (showExts fileInfoCabalExtensions)
, i " Extensions from module: " <> b (showExts fileInfoExtensions)
, " ┏" <> Text.replicate 78 "━"
]
<> Text.intercalate (" ┃\n ┃" <> Text.replicate 78 "~" <> "\n ┃\n")
(toList $ prettyShowObservation outputSettings <$> S.sortOn observationSrcSpan fileInfoObservations)
where
len :: Int
len = length fileInfoObservations
showExts :: Either ExtensionsError ParsedExtensions -> Text
showExts = Text.intercalate ", " . extensionsToText
|
4430c31fca947ddabe61059ab1992bf5a12c5d55e896c222e0cd05a091e96722 | lisp-mirror/clpm | package.lisp | The CLPM client
;;;;
This software is part of CLPM . See README.org for more information . See
;;;; LICENSE for license information.
(uiop:define-package #:clpm-client
(:use #:cl)
(:export #:*activate-asdf-integration*
#:*asdf-system-not-found-behavior*
#:*cleanup-on-dump-p*
#:*clpm-dribble*
#:*clpm-dribble-input-prefix*
#:*clpm-dribble-output-prefix*
#:*clpm-error-dribble*
#:*clpm-error-dribble-prefix*
#:*clpm-executable*
#:*context-diff-approval-method*
#:*default-context*
#:asdf-integration-active-p
#:activate-asdf-integration
#:activate-context
#:active-context
#:approve-diff
#:bundle-init
#:cleanup-clpm-client
#:clpm-client-version
#:clpm-error
#:clpm-error-error-output
#:clpm-error-wrapped-condition
#:clpm-system-definition-pre-search
#:clpm-system-definition-search
#:clpm-version
#:context-diff
#:context-diff-empty-p
#:context-diff-needs-approval
#:context-diff-needs-approval-diff
#:context-diff-release-diffs
#:context-source-registry
#:deactivate-asdf-integration
#:default-context
#:inside-bundle-exec-p
#:install
#:install-and-reload-config
#:install-without-dependencies-and-reload-config
#:maybe-cleanup-clpm-client
#:missing-system
#:missing-system-name
#:print-context-diff-to-stream
#:reject-diff
#:release-diff
#:release-diff-new-source
#:release-diff-new-version
#:release-diff-old-source
#:release-diff-old-version
#:release-diff-project-name
#:reload-config
#:reresolve-requirements-and-reload-config
#:sync
#:update))
(in-package #:clpm-client)
;; Register the fact that the clpm client is available by adding :clpm-client to
;; *FEATURES*.
(pushnew :clpm-client *features*)
| null | https://raw.githubusercontent.com/lisp-mirror/clpm/ad9a704fcdd0df5ce30ead106706ab6cc5fb3e5b/clpm-client/package.lisp | lisp |
LICENSE for license information.
Register the fact that the clpm client is available by adding :clpm-client to
*FEATURES*. | The CLPM client
This software is part of CLPM . See README.org for more information . See
(uiop:define-package #:clpm-client
(:use #:cl)
(:export #:*activate-asdf-integration*
#:*asdf-system-not-found-behavior*
#:*cleanup-on-dump-p*
#:*clpm-dribble*
#:*clpm-dribble-input-prefix*
#:*clpm-dribble-output-prefix*
#:*clpm-error-dribble*
#:*clpm-error-dribble-prefix*
#:*clpm-executable*
#:*context-diff-approval-method*
#:*default-context*
#:asdf-integration-active-p
#:activate-asdf-integration
#:activate-context
#:active-context
#:approve-diff
#:bundle-init
#:cleanup-clpm-client
#:clpm-client-version
#:clpm-error
#:clpm-error-error-output
#:clpm-error-wrapped-condition
#:clpm-system-definition-pre-search
#:clpm-system-definition-search
#:clpm-version
#:context-diff
#:context-diff-empty-p
#:context-diff-needs-approval
#:context-diff-needs-approval-diff
#:context-diff-release-diffs
#:context-source-registry
#:deactivate-asdf-integration
#:default-context
#:inside-bundle-exec-p
#:install
#:install-and-reload-config
#:install-without-dependencies-and-reload-config
#:maybe-cleanup-clpm-client
#:missing-system
#:missing-system-name
#:print-context-diff-to-stream
#:reject-diff
#:release-diff
#:release-diff-new-source
#:release-diff-new-version
#:release-diff-old-source
#:release-diff-old-version
#:release-diff-project-name
#:reload-config
#:reresolve-requirements-and-reload-config
#:sync
#:update))
(in-package #:clpm-client)
(pushnew :clpm-client *features*)
|
5f738767c9f50ac3d10471a4aa1465e8e4467fc08ca68c0485a3b50fa69e2b16 | haskell-gi/haskell-gi | Struct.hs | -- | Parsing of structs.
module Data.GI.GIR.Struct
( Struct(..)
, parseStruct
) where
import Data.Text (Text)
import Data.GI.GIR.Allocation (AllocationInfo(..), unknownAllocationInfo)
import Data.GI.GIR.Field (Field, parseFields)
import Data.GI.GIR.Method (Method, MethodType(..), parseMethod)
import Data.GI.GIR.Parser
import Data.GI.GIR.Type (queryCType)
data Struct = Struct {
structIsBoxed :: Bool,
structAllocationInfo :: AllocationInfo,
structTypeInit :: Maybe Text,
structCType :: Maybe Text,
structSize :: Int,
gtypeStructFor :: Maybe Name,
--
structIsDisguised :: Bool,
structForceVisible :: Bool,
structFields :: [Field],
structMethods :: [Method],
structDeprecated :: Maybe DeprecationInfo,
structDocumentation :: Documentation }
deriving Show
parseStruct :: Parser (Name, Struct)
parseStruct = do
name <- parseName
deprecated <- parseDeprecation
doc <- parseDocumentation
structFor <- queryAttrWithNamespace GLibGIRNS "is-gtype-struct-for" >>= \case
Just t -> (fmap Just . qualifyName) t
Nothing -> return Nothing
typeInit <- queryAttrWithNamespace GLibGIRNS "get-type"
maybeCType <- queryCType
disguised <- optionalAttr "disguised" False parseBool
forceVisible <- optionalAttr "haskell-gi-force-visible" False parseBool
fields <- parseFields
constructors <- parseChildrenWithLocalName "constructor" (parseMethod Constructor)
methods <- parseChildrenWithLocalName "method" (parseMethod OrdinaryMethod)
functions <- parseChildrenWithLocalName "function" (parseMethod MemberFunction)
return (name,
Struct {
structIsBoxed = error ("[boxed] unfixed struct " ++ show name)
, structAllocationInfo = unknownAllocationInfo
, structTypeInit = typeInit
, structCType = maybeCType
, structSize = error ("[size] unfixed struct " ++ show name)
, gtypeStructFor = structFor
, structIsDisguised = disguised
, structForceVisible = forceVisible
, structFields = fields
, structMethods = constructors ++ methods ++ functions
, structDeprecated = deprecated
, structDocumentation = doc
})
| null | https://raw.githubusercontent.com/haskell-gi/haskell-gi/bff8f3b92bf2594ea3d6745c346a8de594fc3709/lib/Data/GI/GIR/Struct.hs | haskell | | Parsing of structs.
| module Data.GI.GIR.Struct
( Struct(..)
, parseStruct
) where
import Data.Text (Text)
import Data.GI.GIR.Allocation (AllocationInfo(..), unknownAllocationInfo)
import Data.GI.GIR.Field (Field, parseFields)
import Data.GI.GIR.Method (Method, MethodType(..), parseMethod)
import Data.GI.GIR.Parser
import Data.GI.GIR.Type (queryCType)
data Struct = Struct {
structIsBoxed :: Bool,
structAllocationInfo :: AllocationInfo,
structTypeInit :: Maybe Text,
structCType :: Maybe Text,
structSize :: Int,
gtypeStructFor :: Maybe Name,
structIsDisguised :: Bool,
structForceVisible :: Bool,
structFields :: [Field],
structMethods :: [Method],
structDeprecated :: Maybe DeprecationInfo,
structDocumentation :: Documentation }
deriving Show
parseStruct :: Parser (Name, Struct)
parseStruct = do
name <- parseName
deprecated <- parseDeprecation
doc <- parseDocumentation
structFor <- queryAttrWithNamespace GLibGIRNS "is-gtype-struct-for" >>= \case
Just t -> (fmap Just . qualifyName) t
Nothing -> return Nothing
typeInit <- queryAttrWithNamespace GLibGIRNS "get-type"
maybeCType <- queryCType
disguised <- optionalAttr "disguised" False parseBool
forceVisible <- optionalAttr "haskell-gi-force-visible" False parseBool
fields <- parseFields
constructors <- parseChildrenWithLocalName "constructor" (parseMethod Constructor)
methods <- parseChildrenWithLocalName "method" (parseMethod OrdinaryMethod)
functions <- parseChildrenWithLocalName "function" (parseMethod MemberFunction)
return (name,
Struct {
structIsBoxed = error ("[boxed] unfixed struct " ++ show name)
, structAllocationInfo = unknownAllocationInfo
, structTypeInit = typeInit
, structCType = maybeCType
, structSize = error ("[size] unfixed struct " ++ show name)
, gtypeStructFor = structFor
, structIsDisguised = disguised
, structForceVisible = forceVisible
, structFields = fields
, structMethods = constructors ++ methods ++ functions
, structDeprecated = deprecated
, structDocumentation = doc
})
|
9ab5caa67f3550e82d379aa03e01e19e0d4bdbacc3bca165106336b64af46f25 | static-analysis-engineering/codehawk | jCHIntervalArray.mli | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
open Big_int_Z
chlib
open CHIntervals
open CHLanguage
open CHPretty
class interval_array_t :
int ->
object ('a)
method augment : int -> int -> interval_t -> 'a
method get_arrays : interval_t array array
method clone : 'a
method copy : 'a
method copy_set : int -> interval_t -> 'a
method copy_set_typed : int -> interval_t -> 'a
method get : int -> interval_t
method get_type_interval : int -> interval_t
method get_singletons : (int * big_int) list
method get_singletons_that_changed : 'a ->
(int * interval_t) list * (int * interval_t) list
method is_discrete : int -> bool
method iteri : (int -> interval_t -> unit) -> unit
method join' : int -> 'a -> 'a
method join : 'a -> 'a
method make : int -> interval_t -> 'a
method make_from_types : int -> 'a
method make_bottom_intervals : int -> 'a
method make_top_intervals : int -> 'a
method meet : 'a -> bool -> 'a
method project_out : int list -> 'a
method pr__debug_large_interval_array :
JCHNumericInfo.numeric_info_t -> string -> variable_t list -> unit
method remap : int -> (int * int) list -> 'a
method remove : int list -> 'a
method remove_entries : int -> int list -> 'a
method restrict_to_type :int list -> 'a
method set : int -> interval_t -> unit
method set_type_intervals :
JCHProcInfo.jproc_info_t -> variable_t list -> 'a
method set_type_intervals_and_restrict :
JCHProcInfo.jproc_info_t -> variable_t list -> 'a
method to_pretty : variable_t list -> pretty_t
method toPretty : pretty_t
method widening' : 'a -> 'a
method widening : 'a -> 'a
end
val make_top_intervals : int -> interval_array_t
val make_from_types : JCHProcInfo.jproc_info_t -> variable_t list -> interval_array_t
val dbg : bool ref
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchpoly/jCHIntervalArray.mli | ocaml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
open Big_int_Z
chlib
open CHIntervals
open CHLanguage
open CHPretty
class interval_array_t :
int ->
object ('a)
method augment : int -> int -> interval_t -> 'a
method get_arrays : interval_t array array
method clone : 'a
method copy : 'a
method copy_set : int -> interval_t -> 'a
method copy_set_typed : int -> interval_t -> 'a
method get : int -> interval_t
method get_type_interval : int -> interval_t
method get_singletons : (int * big_int) list
method get_singletons_that_changed : 'a ->
(int * interval_t) list * (int * interval_t) list
method is_discrete : int -> bool
method iteri : (int -> interval_t -> unit) -> unit
method join' : int -> 'a -> 'a
method join : 'a -> 'a
method make : int -> interval_t -> 'a
method make_from_types : int -> 'a
method make_bottom_intervals : int -> 'a
method make_top_intervals : int -> 'a
method meet : 'a -> bool -> 'a
method project_out : int list -> 'a
method pr__debug_large_interval_array :
JCHNumericInfo.numeric_info_t -> string -> variable_t list -> unit
method remap : int -> (int * int) list -> 'a
method remove : int list -> 'a
method remove_entries : int -> int list -> 'a
method restrict_to_type :int list -> 'a
method set : int -> interval_t -> unit
method set_type_intervals :
JCHProcInfo.jproc_info_t -> variable_t list -> 'a
method set_type_intervals_and_restrict :
JCHProcInfo.jproc_info_t -> variable_t list -> 'a
method to_pretty : variable_t list -> pretty_t
method toPretty : pretty_t
method widening' : 'a -> 'a
method widening : 'a -> 'a
end
val make_top_intervals : int -> interval_array_t
val make_from_types : JCHProcInfo.jproc_info_t -> variable_t list -> interval_array_t
val dbg : bool ref
| |
18ba04f48f588e44702f394ad33af547294bd1a9a88b2ccb66e05cc71322f235 | haskell/lsp | Simple.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE LambdaCase #
import Language.LSP.Server
import Language.LSP.Types
import Control.Monad.IO.Class
import qualified Data.Text as T
handlers :: Handlers (LspM ())
handlers = mconcat
[ notificationHandler SInitialized $ \_not -> do
let params = ShowMessageRequestParams MtInfo "Turn on code lenses?"
(Just [MessageActionItem "Turn on", MessageActionItem "Don't"])
_ <- sendRequest SWindowShowMessageRequest params $ \case
Right (Just (MessageActionItem "Turn on")) -> do
let regOpts = CodeLensRegistrationOptions Nothing Nothing (Just False)
_ <- registerCapability STextDocumentCodeLens regOpts $ \_req responder -> do
let cmd = Command "Say hello" "lsp-hello-command" Nothing
rsp = List [CodeLens (mkRange 0 0 0 100) (Just cmd) Nothing]
responder (Right rsp)
pure ()
Right _ ->
sendNotification SWindowShowMessage (ShowMessageParams MtInfo "Not turning on code lenses")
Left err ->
sendNotification SWindowShowMessage (ShowMessageParams MtError $ "Something went wrong!\n" <> T.pack (show err))
pure ()
, requestHandler STextDocumentHover $ \req responder -> do
let RequestMessage _ _ _ (HoverParams _doc pos _workDone) = req
Position _l _c' = pos
rsp = Hover ms (Just range)
ms = HoverContents $ markedUpContent "lsp-demo-simple-server" "Hello world"
range = Range pos pos
responder (Right $ Just rsp)
]
main :: IO Int
main = runServer $ ServerDefinition
{ onConfigurationChange = const $ const $ Right ()
, defaultConfig = ()
, doInitialize = \env _req -> pure $ Right env
, staticHandlers = handlers
, interpretHandler = \env -> Iso (runLspT env) liftIO
, options = defaultOptions
}
| null | https://raw.githubusercontent.com/haskell/lsp/51a04d9bb660b5ca69e9bb4ba6f2e45e2cb129fe/lsp/example/Simple.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE LambdaCase #
import Language.LSP.Server
import Language.LSP.Types
import Control.Monad.IO.Class
import qualified Data.Text as T
handlers :: Handlers (LspM ())
handlers = mconcat
[ notificationHandler SInitialized $ \_not -> do
let params = ShowMessageRequestParams MtInfo "Turn on code lenses?"
(Just [MessageActionItem "Turn on", MessageActionItem "Don't"])
_ <- sendRequest SWindowShowMessageRequest params $ \case
Right (Just (MessageActionItem "Turn on")) -> do
let regOpts = CodeLensRegistrationOptions Nothing Nothing (Just False)
_ <- registerCapability STextDocumentCodeLens regOpts $ \_req responder -> do
let cmd = Command "Say hello" "lsp-hello-command" Nothing
rsp = List [CodeLens (mkRange 0 0 0 100) (Just cmd) Nothing]
responder (Right rsp)
pure ()
Right _ ->
sendNotification SWindowShowMessage (ShowMessageParams MtInfo "Not turning on code lenses")
Left err ->
sendNotification SWindowShowMessage (ShowMessageParams MtError $ "Something went wrong!\n" <> T.pack (show err))
pure ()
, requestHandler STextDocumentHover $ \req responder -> do
let RequestMessage _ _ _ (HoverParams _doc pos _workDone) = req
Position _l _c' = pos
rsp = Hover ms (Just range)
ms = HoverContents $ markedUpContent "lsp-demo-simple-server" "Hello world"
range = Range pos pos
responder (Right $ Just rsp)
]
main :: IO Int
main = runServer $ ServerDefinition
{ onConfigurationChange = const $ const $ Right ()
, defaultConfig = ()
, doInitialize = \env _req -> pure $ Right env
, staticHandlers = handlers
, interpretHandler = \env -> Iso (runLspT env) liftIO
, options = defaultOptions
}
|
b0c5b1baf2be414de66f796fad3568bb43d9f612c197ae1c4b93db2911fec37d | iokasimov/pandora | Morphism.hs | module Pandora.Pattern.Morphism (module Exports, Opposite) where
import Pandora.Pattern.Morphism.Trip as Exports
import Pandora.Pattern.Morphism.Flip as Exports
import Pandora.Pattern.Morphism.Tensor as Exports
import Pandora.Pattern.Morphism.Tensor as Exports
import Pandora.Pattern.Morphism.Lifted as Exports
import Pandora.Pattern.Morphism.Kleisli as Exports
import Pandora.Pattern.Morphism.Straight as Exports
type family Opposite m where
Opposite Straight = Flip
Opposite Flip = Straight
| null | https://raw.githubusercontent.com/iokasimov/pandora/dc0a50cb02f3fd77e8ab523582011a53d325f852/Pandora/Pattern/Morphism.hs | haskell | module Pandora.Pattern.Morphism (module Exports, Opposite) where
import Pandora.Pattern.Morphism.Trip as Exports
import Pandora.Pattern.Morphism.Flip as Exports
import Pandora.Pattern.Morphism.Tensor as Exports
import Pandora.Pattern.Morphism.Tensor as Exports
import Pandora.Pattern.Morphism.Lifted as Exports
import Pandora.Pattern.Morphism.Kleisli as Exports
import Pandora.Pattern.Morphism.Straight as Exports
type family Opposite m where
Opposite Straight = Flip
Opposite Flip = Straight
| |
3df4379adb8db4df4c6946a5ba611ccaaf548a3f0822a887761bc961d6628488 | thumphries/hgrep | Data.hs | # LANGUAGE ExistentialQuantification #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE CPP #
module Language.Haskell.HGrep.Internal.Data (
ParsedSource (..)
, ParseError (..)
, Query (..)
, Regex (..)
, compileRegex
, SearchResult (..)
, PrintOpts (..)
, defaultPrintOpts
, ColourOpts (..)
, LineNumOpts (..)
) where
import qualified Data.ByteString.Char8 as B8
import Language.Haskell.HGrep.Prelude
import qualified Language.Haskell.GHC.ExactPrint.Annotater as EA
import qualified Language.Haskell.GHC.ExactPrint.Types as ET
import qualified Text.Regex.PCRE.Heavy as PCRE
import qualified GHC
import qualified SrcLoc
newtype ParsedSource = ParsedSource {
#if !MIN_VERSION_base(4,11,0)
unParsedSource :: (ET.Anns, GHC.Located (GHC.HsModule GHC.RdrName))
#else
unParsedSource :: (ET.Anns, GHC.Located (GHC.HsModule GHC.GhcPs))
#endif
}
data ParseError =
ExactPrintParseError (SrcLoc.SrcSpan, [Char])
| ExactPrintException
data Query =
MatchSimple [Char]
| MatchRegex Regex
deriving (Eq, Ord, Show)
newtype Regex = Regex {
unRegex :: PCRE.Regex
} deriving (Eq, Ord, Show)
compileRegex :: [Char] -> Either [Char] Regex
compileRegex str =
fmap Regex (PCRE.compileM (B8.pack str) [])
data SearchResult =
forall ast. EA.Annotate ast =>
SearchResult ET.Anns (SrcLoc.Located ast)
data PrintOpts = PrintOpts {
poColourOpts :: ColourOpts
, poLineNumOpts :: LineNumOpts
} deriving (Eq, Ord, Show)
data ColourOpts =
DefaultColours
| NoColours
deriving (Eq, Ord, Show)
data LineNumOpts =
PrintLineNums
| NoLineNums
deriving (Eq, Ord, Show)
defaultPrintOpts :: PrintOpts
defaultPrintOpts =
PrintOpts {
poColourOpts = DefaultColours
, poLineNumOpts = PrintLineNums
}
| null | https://raw.githubusercontent.com/thumphries/hgrep/1d3e49724ef6fba545762bc9c5d5d2cf03455e49/src/Language/Haskell/HGrep/Internal/Data.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes # | # LANGUAGE ExistentialQuantification #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE CPP #
module Language.Haskell.HGrep.Internal.Data (
ParsedSource (..)
, ParseError (..)
, Query (..)
, Regex (..)
, compileRegex
, SearchResult (..)
, PrintOpts (..)
, defaultPrintOpts
, ColourOpts (..)
, LineNumOpts (..)
) where
import qualified Data.ByteString.Char8 as B8
import Language.Haskell.HGrep.Prelude
import qualified Language.Haskell.GHC.ExactPrint.Annotater as EA
import qualified Language.Haskell.GHC.ExactPrint.Types as ET
import qualified Text.Regex.PCRE.Heavy as PCRE
import qualified GHC
import qualified SrcLoc
newtype ParsedSource = ParsedSource {
#if !MIN_VERSION_base(4,11,0)
unParsedSource :: (ET.Anns, GHC.Located (GHC.HsModule GHC.RdrName))
#else
unParsedSource :: (ET.Anns, GHC.Located (GHC.HsModule GHC.GhcPs))
#endif
}
data ParseError =
ExactPrintParseError (SrcLoc.SrcSpan, [Char])
| ExactPrintException
data Query =
MatchSimple [Char]
| MatchRegex Regex
deriving (Eq, Ord, Show)
newtype Regex = Regex {
unRegex :: PCRE.Regex
} deriving (Eq, Ord, Show)
compileRegex :: [Char] -> Either [Char] Regex
compileRegex str =
fmap Regex (PCRE.compileM (B8.pack str) [])
data SearchResult =
forall ast. EA.Annotate ast =>
SearchResult ET.Anns (SrcLoc.Located ast)
data PrintOpts = PrintOpts {
poColourOpts :: ColourOpts
, poLineNumOpts :: LineNumOpts
} deriving (Eq, Ord, Show)
data ColourOpts =
DefaultColours
| NoColours
deriving (Eq, Ord, Show)
data LineNumOpts =
PrintLineNums
| NoLineNums
deriving (Eq, Ord, Show)
defaultPrintOpts :: PrintOpts
defaultPrintOpts =
PrintOpts {
poColourOpts = DefaultColours
, poLineNumOpts = PrintLineNums
}
|
02e3196c364a88427fd762aff0b96e2faaf0eaff13371e9ed2e7d85dcc27b097 | McCLIM/McCLIM | simple-draw.lisp | (cl:eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload :mcclim))
(cl:in-package #:clim-user)
(define-application-frame hello-frame () ()
(:pane (make-instance 'hello-data-pane
:hs 200 :hs+ +fill+ :vs 200 :vs+ +fill+))
(:settings :title "Hello from Lisp"))
(define-application-pane hello-data-pane ());; inherits basic-clim-pane
;; by default ())
Behavior defined via CLOS class specialization
(defmethod handle-repaint ((pane hello-data-pane) region &key &allow-other-keys)
(declare (ignore region))
(let* ((w (bounding-rectangle-width pane))
(h (bounding-rectangle-height pane)))
Blank the pane out
(draw-rectangle* pane 0 0 w h :filled t :ink (pane-background pane))
;; Center the label
(draw-text* pane "Hello" (floor w 2) (floor h 2) :align-x :center :align-y :center)))
(defmethod button-release ((pane hello-data-pane)
(button-name (eql :right))
&key x y &allow-other-keys)
(draw-point* pane x y))
| null | https://raw.githubusercontent.com/McCLIM/McCLIM/7c890f1ac79f0c6f36866c47af89398e2f05b343/Documentation/Guided-Tour/simple-draw.lisp | lisp | inherits basic-clim-pane
by default ())
Center the label | (cl:eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload :mcclim))
(cl:in-package #:clim-user)
(define-application-frame hello-frame () ()
(:pane (make-instance 'hello-data-pane
:hs 200 :hs+ +fill+ :vs 200 :vs+ +fill+))
(:settings :title "Hello from Lisp"))
Behavior defined via CLOS class specialization
(defmethod handle-repaint ((pane hello-data-pane) region &key &allow-other-keys)
(declare (ignore region))
(let* ((w (bounding-rectangle-width pane))
(h (bounding-rectangle-height pane)))
Blank the pane out
(draw-rectangle* pane 0 0 w h :filled t :ink (pane-background pane))
(draw-text* pane "Hello" (floor w 2) (floor h 2) :align-x :center :align-y :center)))
(defmethod button-release ((pane hello-data-pane)
(button-name (eql :right))
&key x y &allow-other-keys)
(draw-point* pane x y))
|
45bb82cd6a45ee0e5c40199e83bddea0988e430947b08c78532a1f90a65aee8e | McCLIM/McCLIM | text-style.lisp | ;;; ---------------------------------------------------------------------------
;;; License: LGPL-2.1+ (See file 'Copyright' for details).
;;; ---------------------------------------------------------------------------
;;;
( c ) copyright 1998 - 2000 by < >
( c ) copyright 2002 - 2003 by < >
( c ) copyright 2014 by < >
( c ) copyright 2020 by < >
;;;
;;; ---------------------------------------------------------------------------
;;;
Implementation of the 11.1 Text Styles .
;;;
(in-package #:clim-internals)
TODO
;;; - *UNDEFINED-TEXT-STYLE* is missing
- Why is ( EQ ( MAKE - TEXT - STYLE NIL NIL 10 ) ( MAKE - TEXT - STYLE NIL NIL 10.0005 ) ) = T ?
;;; Does it matter?
;;; - Don't we want a weak hash-table for *TEXT-STYLE-HASH-TABLE*
;;;
--GB 2002 - 02 - 26
Notes
;;; The text-style protocol is kind of useless for now. How is an
;;; application programmer expected to implement new text-styles? I
;;; think we would need something like:
;;;
TEXT - STYLE - CHARACTER - text - style character[1 ]
;;; -> width, ascent, descent, left-bearing, right-bearing
;;;
;;; TEXT-STYLE-DRAW-TEXT text-style medium string x y
;;; Or even better:
;;; DESIGN-FROM-TEXT-STYLE-CHARACTER text-style character
;;;
;;;
;;; And when you start to think about it, text-styles are not fonts. So
we need two protocols : A text style protocol and a font protocol .
;;;
;;; A text style is then something, which maps a sequence of characters
;;; into a couple of drawing commands, while probably using some font.
;;;
;;; While a font is something, which maps a _glyph index_ into a design.
;;;
;;; Example: Underlined with extra word spacing is a text style, while
Adobe Times Roman 12pt is a font .
;;;
;;; And [it can't be said too often] unicode is not a glyph encoding
;;; but more a kind of text formating.
;;;
[ 1 ] or even a code position
;;; --GB
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod text-style-equalp ((style1 text-style) (style2 text-style))
(eq style1 style2))
(defclass standard-text-style (text-style)
((family :initarg :text-family
:initform :fix
:reader text-style-family)
(face :initarg :text-face
:initform :roman
:reader text-style-face)
(size :initarg :text-size
:initform :normal
:reader text-style-size)))
(defmethod make-load-form ((obj standard-text-style) &optional env)
(declare (ignore env))
(with-slots (family face size) obj
`(make-text-style ',family ',face ',size)))
(defun family-key (family)
(case family
((nil) 0)
((:fix) 1)
((:serif) 2)
((:sans-serif) 3)))
(defun face-key (face)
(typecase face
(null 0)
((eql :roman) 1)
((eql :bold) 2)
((eql :italic) 3)
((cons (eql :bold) (cons (eql :italic))) 4)
((cons (eql :italic) (cons (eql :bold))) 4)))
(defun size-key (size)
(if (numberp size)
(+ 10 (round (* 256 size)))
(case size
((nil) 0)
((:tiny) 1)
((:very-small) 2)
((:small) 3)
((:normal) 4)
((:large) 5)
((:very-large) 6)
((:huge) 7)
((:smaller) 8)
((:larger) 9))))
(defun text-style-key (family face size)
(when-let ((size-key (size-key size))
(face-key (face-key face))
(family-key (family-key family)))
(logior (ash size-key 8)
(ash face-key 4)
(ash family-key 0))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *text-style-hash-table* (make-hash-table :test #'eql))
(defvar *extended-text-style-hash-table* (make-hash-table :test #'equal)))
(defun make-text-style (family face size)
(if-let ((key (text-style-key family face size)))
Portable text styles have always been cached in McCLIM like
this : ( as permitted by the CLIM spec for immutable objects ,
section 2.4 )
A 32 - bit key has 24 - bit for the output of ` size - key ' . That 's
around font size 100000 .
(locally (declare (type (unsigned-byte 32) key))
(ensure-gethash key *text-style-hash-table*
(make-text-style-1 family face size)))
;; Extended text styles using custom components is cached using
an appropriate hash table to ensure ` EQL ' of the same
;; extended text styles
(ensure-gethash (list family face size) *extended-text-style-hash-table*
(make-text-style-1 family face size))))
(defun make-text-style-1 (family face size)
(make-instance 'standard-text-style
:text-family family
:text-face face
:text-size size)))
(defmethod print-object ((self standard-text-style) stream)
(print-unreadable-object (self stream :type t :identity nil)
(format stream "~{~S~^ ~}" (multiple-value-list (text-style-components self)))))
(defmethod text-style-equalp ((style1 standard-text-style)
(style2 standard-text-style))
(and (equal (text-style-family style1) (text-style-family style2))
(equal (text-style-face style1) (text-style-face style2))
(eql (text-style-size style1) (text-style-size style2))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *default-text-style* (make-text-style :sans-serif :roman :normal))
(defvar *undefined-text-style* *default-text-style*)
(defconstant +smaller-sizes+ '(:huge :very-large :large :normal
:small :very-small :tiny :tiny))
(defconstant +larger-sizes+ '(:tiny :very-small :small :normal
:large :very-large :huge :huge))
(defconstant +font-scaling-factor+ 4/3)
(defconstant +font-min-size+ 6)
(defconstant +font-max-size+ 48)
(defconstant +font-sizes+
'(:normal 14 :tiny 8 :very-small 10 :small 12 :large 18 :very-large 20 :huge 24)
"Mapping between keyword and a font size."))
(declaim (inline normalize-font-size))
(defun normalize-font-size (size)
(cond ((null size)
(let ((size* (text-style-size *default-text-style*)))
(etypecase size*
(number size*)
(symbol (getf +font-sizes+ size* nil)))))
((eq size :smaller)
(getf +font-sizes+ (text-style-size *default-text-style*) nil))
((eq size :larger)
(getf +font-sizes+ (text-style-size *default-text-style*) nil))
((realp size)
(round (max size 2)))
((getf +font-sizes+ size nil))
(t
(error "~s is not a valid text style size!" size))))
(defun parse-text-style* (style)
"Returns complete text-style without NIL components and with numeric size."
(handler-case (flet ((new-text-style (family face size)
(let ((default *default-text-style*))
(make-text-style (or family (text-style-family default))
(or face (text-style-face default))
(normalize-font-size size)))))
(cond ((device-font-text-style-p style)
style)
((text-style-p style)
(multiple-value-bind (family face size)
(text-style-components style)
(if (and (realp size)
(text-style-components-fully-specified-p family face size))
style
(new-text-style family face size))))
((null style)
(parse-text-style* *default-text-style*))
((and (listp style) (alexandria:length= 3 style))
(destructuring-bind (family face size) style
(new-text-style family face size)))
(t (error "Invalid text style specification ~S." style))))
(error (c)
(warn (format nil "~a" c))
*undefined-text-style*)))
(defun text-style-components-fully-specified-p (family face size)
(and family
face
size
(or (realp size)
(member size (load-time-value
(remove-if-not #'keywordp +font-sizes+) t)))))
(defun text-style-fully-specified-p (text-style)
(multiple-value-bind (family face size) (text-style-components text-style)
(text-style-components-fully-specified-p family face size)))
(defun find-smaller-size (size)
(if (numberp size)
(max (round (/ size +font-scaling-factor+)) +font-min-size+)
(cadr (member size +smaller-sizes+))))
(defun find-larger-size (size)
(if (numberp size)
(min (round (* size +font-scaling-factor+)) +font-max-size+)
(cadr (member size +larger-sizes+))))
(defmethod text-style-components ((text-style standard-text-style))
(values (text-style-family text-style)
(text-style-face text-style)
(text-style-size text-style)))
;;; Device-Font-Text-Style class
(defclass device-font-text-style (text-style)
((display-device :initarg :display-device :accessor display-device)
(device-font-name :initarg :device-font-name :accessor device-font-name)))
(defmethod print-object ((self device-font-text-style) stream)
(print-unreadable-object (self stream :type t :identity nil)
(format stream "~S on ~S" (device-font-name self) (display-device self))))
(defun device-font-text-style-p (s)
(typep s 'device-font-text-style))
(defmethod text-style-components ((text-style device-font-text-style))
(values :device :device :device))
(defmethod text-style-mapping
((port port) (text-style text-style) &optional character-set)
(declare (ignore port character-set))
;; INV the around method looks up the cache for the mapping. If we
;; end up here it is a game over. For consistency we return the
text - style like other methods . -- jd 2020 - 01 - 15
text-style)
(defmethod text-style-mapping ((port port) text-style &optional character-set)
(text-style-mapping port (parse-text-style text-style) character-set))
(defmethod text-style-mapping :around
((port port) (text-style text-style) &optional character-set)
(declare (ignore character-set))
;; Cache mappings only for fully specified text styles.
(let ((mappings (port-text-style-mappings port)))
(if (or (device-font-text-style-p text-style)
(text-style-fully-specified-p text-style))
(ensure-gethash text-style mappings (call-next-method))
(or (gethash text-style mappings) (call-next-method)))))
(defmethod (setf text-style-mapping)
(mapping (port port) text-style &optional character-set)
(declare (ignore character-set))
(setf (text-style-mapping port (parse-text-style text-style)) mapping))
(defmethod (setf text-style-mapping)
(mapping (port port) (text-style text-style) &optional character-set)
(declare (ignore character-set))
(when (listp mapping)
FIXME
(setf (gethash text-style (port-text-style-mappings port))
mapping))
(defmethod make-device-font-text-style (port font-name)
(let ((text-style (make-instance 'device-font-text-style
:display-device port
:device-font-name font-name)))
text-style))
;;; Text-style utilities
(defmethod merge-text-styles (s1 s2)
(when (and (typep s1 'text-style)
(eq s1 s2))
(return-from merge-text-styles s1))
(setq s1 (parse-text-style s1))
(setq s2 (parse-text-style s2))
(if (and (not (device-font-text-style-p s1))
(not (device-font-text-style-p s2)))
(let* ((family (or (text-style-family s1) (text-style-family s2)))
(face1 (text-style-face s1))
(face2 (text-style-face s2))
(face (if (or (and (eq face1 :bold) (eq face2 :italic))
(and (eq face1 :italic) (eq face2 :bold)))
'(:bold :italic)
(or face1 face2)))
(size1 (text-style-size s1))
(size2 (text-style-size s2))
(size (case size1
((nil) size2)
(:smaller (find-smaller-size size2))
(:larger (find-larger-size size2))
(t size1))))
(make-text-style family face size))
s1))
(defun parse-text-style (style)
(cond ((text-style-p style) style)
((null style) (make-text-style nil nil nil)) ; ?
((and (listp style) (alexandria:length= 3 style))
(destructuring-bind (family face size) style
(make-text-style family face size)))
(t (error "Invalid text style specification ~S." style))))
(defmacro with-text-style ((medium text-style) &body body)
(when (eq medium t)
(setq medium '*standard-output*))
(check-type medium symbol)
(with-gensyms (cont)
`(flet ((,cont (,medium)
,(declare-ignorable-form* medium)
,@body))
(declare (dynamic-extent #',cont))
(invoke-with-text-style ,medium #',cont
(parse-text-style ,text-style)))))
(defmethod invoke-with-text-style ((sheet sheet) continuation text-style)
(let ((medium (sheet-medium sheet))) ; FIXME: WITH-SHEET-MEDIUM
(with-text-style (medium text-style)
(funcall continuation sheet))))
(defmethod invoke-with-text-style ((medium medium) continuation text-style)
(invoke-with-drawing-options
medium continuation
:text-style (merge-text-styles text-style (medium-merged-text-style medium))))
For compatibility with real CLIM , which apparently lets you call this
on non - CLIM streams .
(defmethod invoke-with-text-style ((medium t) continuation text-style)
(declare (ignore text-style))
(funcall continuation medium))
(defmacro with-text-family ((medium family) &body body)
(declare (type symbol medium))
(when (eq medium t)
(setq medium '*standard-output*))
(with-gensyms (cont)
`(flet ((,cont (,medium)
,(declare-ignorable-form* medium)
,@body))
(declare (dynamic-extent #',cont))
(invoke-with-text-style ,medium #',cont
(make-text-style ,family nil nil)))))
(defmacro with-text-face ((medium face) &body body)
(declare (type symbol medium))
(when (eq medium t)
(setq medium '*standard-output*))
(with-gensyms (cont)
`(flet ((,cont (,medium)
,(declare-ignorable-form* medium)
,@body))
(declare (dynamic-extent #',cont))
(invoke-with-text-style ,medium #',cont
(make-text-style nil ,face nil)))))
(defmacro with-text-size ((medium size) &body body)
(declare (type symbol medium))
(when (eq medium t) (setq medium '*standard-output*))
(with-gensyms (cont)
`(flet ((,cont (,medium)
,(declare-ignorable-form* medium)
,@body))
(declare (dynamic-extent #',cont))
(invoke-with-text-style ,medium #',cont
(make-text-style nil nil ,size)))))
;;; These below were just hot fixes, are there still needed? Are even
half - way correct ? --GB
;;;
;;; These are needed, and are correct. "Implementations should also
;;; provide a ``trampoline'' for this generic function for output sheets; the
trampoline will simply call the method for the medium . --
;;;
;;; Thanks! --GB
(defmethod text-size ((sheet sheet) string &rest more)
(apply #'text-size (sheet-medium sheet) string more))
(defmethod text-style-ascent (ts (sheet sheet))
(text-style-ascent ts (sheet-medium sheet)))
(defmethod text-style-descent (ts (sheet sheet))
(text-style-descent ts (sheet-medium sheet)))
(defmethod text-style-height (ts (sheet sheet))
(text-style-height ts (sheet-medium sheet)))
(defmethod text-style-width (ts (sheet sheet))
(text-style-width ts (sheet-medium sheet)))
Fallback methods for the text style metrics .
(defmethod text-style-height (text-style medium)
(+ (text-style-ascent text-style medium)
(text-style-descent text-style medium)))
(defmethod text-style-width (text-style medium)
(text-style-character-width text-style medium #\M))
(defmethod text-style-fixed-width-p (text-style medium)
(declare (ignore medium))
(eql (text-style-family text-style) :fix))
| null | https://raw.githubusercontent.com/McCLIM/McCLIM/d49fef5c2bb1307a006cdadfc4061e0a6b0fff79/Core/drawing/text-style.lisp | lisp | ---------------------------------------------------------------------------
License: LGPL-2.1+ (See file 'Copyright' for details).
---------------------------------------------------------------------------
---------------------------------------------------------------------------
- *UNDEFINED-TEXT-STYLE* is missing
Does it matter?
- Don't we want a weak hash-table for *TEXT-STYLE-HASH-TABLE*
The text-style protocol is kind of useless for now. How is an
application programmer expected to implement new text-styles? I
think we would need something like:
-> width, ascent, descent, left-bearing, right-bearing
TEXT-STYLE-DRAW-TEXT text-style medium string x y
Or even better:
DESIGN-FROM-TEXT-STYLE-CHARACTER text-style character
And when you start to think about it, text-styles are not fonts. So
A text style is then something, which maps a sequence of characters
into a couple of drawing commands, while probably using some font.
While a font is something, which maps a _glyph index_ into a design.
Example: Underlined with extra word spacing is a text style, while
And [it can't be said too often] unicode is not a glyph encoding
but more a kind of text formating.
--GB
Extended text styles using custom components is cached using
extended text styles
Device-Font-Text-Style class
INV the around method looks up the cache for the mapping. If we
end up here it is a game over. For consistency we return the
Cache mappings only for fully specified text styles.
Text-style utilities
?
FIXME: WITH-SHEET-MEDIUM
These below were just hot fixes, are there still needed? Are even
These are needed, and are correct. "Implementations should also
provide a ``trampoline'' for this generic function for output sheets; the
Thanks! --GB | ( c ) copyright 1998 - 2000 by < >
( c ) copyright 2002 - 2003 by < >
( c ) copyright 2014 by < >
( c ) copyright 2020 by < >
Implementation of the 11.1 Text Styles .
(in-package #:clim-internals)
TODO
- Why is ( EQ ( MAKE - TEXT - STYLE NIL NIL 10 ) ( MAKE - TEXT - STYLE NIL NIL 10.0005 ) ) = T ?
--GB 2002 - 02 - 26
Notes
TEXT - STYLE - CHARACTER - text - style character[1 ]
we need two protocols : A text style protocol and a font protocol .
Adobe Times Roman 12pt is a font .
[ 1 ] or even a code position
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod text-style-equalp ((style1 text-style) (style2 text-style))
(eq style1 style2))
(defclass standard-text-style (text-style)
((family :initarg :text-family
:initform :fix
:reader text-style-family)
(face :initarg :text-face
:initform :roman
:reader text-style-face)
(size :initarg :text-size
:initform :normal
:reader text-style-size)))
(defmethod make-load-form ((obj standard-text-style) &optional env)
(declare (ignore env))
(with-slots (family face size) obj
`(make-text-style ',family ',face ',size)))
(defun family-key (family)
(case family
((nil) 0)
((:fix) 1)
((:serif) 2)
((:sans-serif) 3)))
(defun face-key (face)
(typecase face
(null 0)
((eql :roman) 1)
((eql :bold) 2)
((eql :italic) 3)
((cons (eql :bold) (cons (eql :italic))) 4)
((cons (eql :italic) (cons (eql :bold))) 4)))
(defun size-key (size)
(if (numberp size)
(+ 10 (round (* 256 size)))
(case size
((nil) 0)
((:tiny) 1)
((:very-small) 2)
((:small) 3)
((:normal) 4)
((:large) 5)
((:very-large) 6)
((:huge) 7)
((:smaller) 8)
((:larger) 9))))
(defun text-style-key (family face size)
(when-let ((size-key (size-key size))
(face-key (face-key face))
(family-key (family-key family)))
(logior (ash size-key 8)
(ash face-key 4)
(ash family-key 0))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *text-style-hash-table* (make-hash-table :test #'eql))
(defvar *extended-text-style-hash-table* (make-hash-table :test #'equal)))
(defun make-text-style (family face size)
(if-let ((key (text-style-key family face size)))
Portable text styles have always been cached in McCLIM like
this : ( as permitted by the CLIM spec for immutable objects ,
section 2.4 )
A 32 - bit key has 24 - bit for the output of ` size - key ' . That 's
around font size 100000 .
(locally (declare (type (unsigned-byte 32) key))
(ensure-gethash key *text-style-hash-table*
(make-text-style-1 family face size)))
an appropriate hash table to ensure ` EQL ' of the same
(ensure-gethash (list family face size) *extended-text-style-hash-table*
(make-text-style-1 family face size))))
(defun make-text-style-1 (family face size)
(make-instance 'standard-text-style
:text-family family
:text-face face
:text-size size)))
(defmethod print-object ((self standard-text-style) stream)
(print-unreadable-object (self stream :type t :identity nil)
(format stream "~{~S~^ ~}" (multiple-value-list (text-style-components self)))))
(defmethod text-style-equalp ((style1 standard-text-style)
(style2 standard-text-style))
(and (equal (text-style-family style1) (text-style-family style2))
(equal (text-style-face style1) (text-style-face style2))
(eql (text-style-size style1) (text-style-size style2))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *default-text-style* (make-text-style :sans-serif :roman :normal))
(defvar *undefined-text-style* *default-text-style*)
(defconstant +smaller-sizes+ '(:huge :very-large :large :normal
:small :very-small :tiny :tiny))
(defconstant +larger-sizes+ '(:tiny :very-small :small :normal
:large :very-large :huge :huge))
(defconstant +font-scaling-factor+ 4/3)
(defconstant +font-min-size+ 6)
(defconstant +font-max-size+ 48)
(defconstant +font-sizes+
'(:normal 14 :tiny 8 :very-small 10 :small 12 :large 18 :very-large 20 :huge 24)
"Mapping between keyword and a font size."))
(declaim (inline normalize-font-size))
(defun normalize-font-size (size)
(cond ((null size)
(let ((size* (text-style-size *default-text-style*)))
(etypecase size*
(number size*)
(symbol (getf +font-sizes+ size* nil)))))
((eq size :smaller)
(getf +font-sizes+ (text-style-size *default-text-style*) nil))
((eq size :larger)
(getf +font-sizes+ (text-style-size *default-text-style*) nil))
((realp size)
(round (max size 2)))
((getf +font-sizes+ size nil))
(t
(error "~s is not a valid text style size!" size))))
(defun parse-text-style* (style)
"Returns complete text-style without NIL components and with numeric size."
(handler-case (flet ((new-text-style (family face size)
(let ((default *default-text-style*))
(make-text-style (or family (text-style-family default))
(or face (text-style-face default))
(normalize-font-size size)))))
(cond ((device-font-text-style-p style)
style)
((text-style-p style)
(multiple-value-bind (family face size)
(text-style-components style)
(if (and (realp size)
(text-style-components-fully-specified-p family face size))
style
(new-text-style family face size))))
((null style)
(parse-text-style* *default-text-style*))
((and (listp style) (alexandria:length= 3 style))
(destructuring-bind (family face size) style
(new-text-style family face size)))
(t (error "Invalid text style specification ~S." style))))
(error (c)
(warn (format nil "~a" c))
*undefined-text-style*)))
(defun text-style-components-fully-specified-p (family face size)
(and family
face
size
(or (realp size)
(member size (load-time-value
(remove-if-not #'keywordp +font-sizes+) t)))))
(defun text-style-fully-specified-p (text-style)
(multiple-value-bind (family face size) (text-style-components text-style)
(text-style-components-fully-specified-p family face size)))
(defun find-smaller-size (size)
(if (numberp size)
(max (round (/ size +font-scaling-factor+)) +font-min-size+)
(cadr (member size +smaller-sizes+))))
(defun find-larger-size (size)
(if (numberp size)
(min (round (* size +font-scaling-factor+)) +font-max-size+)
(cadr (member size +larger-sizes+))))
(defmethod text-style-components ((text-style standard-text-style))
(values (text-style-family text-style)
(text-style-face text-style)
(text-style-size text-style)))
(defclass device-font-text-style (text-style)
((display-device :initarg :display-device :accessor display-device)
(device-font-name :initarg :device-font-name :accessor device-font-name)))
(defmethod print-object ((self device-font-text-style) stream)
(print-unreadable-object (self stream :type t :identity nil)
(format stream "~S on ~S" (device-font-name self) (display-device self))))
(defun device-font-text-style-p (s)
(typep s 'device-font-text-style))
(defmethod text-style-components ((text-style device-font-text-style))
(values :device :device :device))
(defmethod text-style-mapping
((port port) (text-style text-style) &optional character-set)
(declare (ignore port character-set))
text - style like other methods . -- jd 2020 - 01 - 15
text-style)
(defmethod text-style-mapping ((port port) text-style &optional character-set)
(text-style-mapping port (parse-text-style text-style) character-set))
(defmethod text-style-mapping :around
((port port) (text-style text-style) &optional character-set)
(declare (ignore character-set))
(let ((mappings (port-text-style-mappings port)))
(if (or (device-font-text-style-p text-style)
(text-style-fully-specified-p text-style))
(ensure-gethash text-style mappings (call-next-method))
(or (gethash text-style mappings) (call-next-method)))))
(defmethod (setf text-style-mapping)
(mapping (port port) text-style &optional character-set)
(declare (ignore character-set))
(setf (text-style-mapping port (parse-text-style text-style)) mapping))
(defmethod (setf text-style-mapping)
(mapping (port port) (text-style text-style) &optional character-set)
(declare (ignore character-set))
(when (listp mapping)
FIXME
(setf (gethash text-style (port-text-style-mappings port))
mapping))
(defmethod make-device-font-text-style (port font-name)
(let ((text-style (make-instance 'device-font-text-style
:display-device port
:device-font-name font-name)))
text-style))
(defmethod merge-text-styles (s1 s2)
(when (and (typep s1 'text-style)
(eq s1 s2))
(return-from merge-text-styles s1))
(setq s1 (parse-text-style s1))
(setq s2 (parse-text-style s2))
(if (and (not (device-font-text-style-p s1))
(not (device-font-text-style-p s2)))
(let* ((family (or (text-style-family s1) (text-style-family s2)))
(face1 (text-style-face s1))
(face2 (text-style-face s2))
(face (if (or (and (eq face1 :bold) (eq face2 :italic))
(and (eq face1 :italic) (eq face2 :bold)))
'(:bold :italic)
(or face1 face2)))
(size1 (text-style-size s1))
(size2 (text-style-size s2))
(size (case size1
((nil) size2)
(:smaller (find-smaller-size size2))
(:larger (find-larger-size size2))
(t size1))))
(make-text-style family face size))
s1))
(defun parse-text-style (style)
(cond ((text-style-p style) style)
((and (listp style) (alexandria:length= 3 style))
(destructuring-bind (family face size) style
(make-text-style family face size)))
(t (error "Invalid text style specification ~S." style))))
(defmacro with-text-style ((medium text-style) &body body)
(when (eq medium t)
(setq medium '*standard-output*))
(check-type medium symbol)
(with-gensyms (cont)
`(flet ((,cont (,medium)
,(declare-ignorable-form* medium)
,@body))
(declare (dynamic-extent #',cont))
(invoke-with-text-style ,medium #',cont
(parse-text-style ,text-style)))))
(defmethod invoke-with-text-style ((sheet sheet) continuation text-style)
(with-text-style (medium text-style)
(funcall continuation sheet))))
(defmethod invoke-with-text-style ((medium medium) continuation text-style)
(invoke-with-drawing-options
medium continuation
:text-style (merge-text-styles text-style (medium-merged-text-style medium))))
For compatibility with real CLIM , which apparently lets you call this
on non - CLIM streams .
(defmethod invoke-with-text-style ((medium t) continuation text-style)
(declare (ignore text-style))
(funcall continuation medium))
(defmacro with-text-family ((medium family) &body body)
(declare (type symbol medium))
(when (eq medium t)
(setq medium '*standard-output*))
(with-gensyms (cont)
`(flet ((,cont (,medium)
,(declare-ignorable-form* medium)
,@body))
(declare (dynamic-extent #',cont))
(invoke-with-text-style ,medium #',cont
(make-text-style ,family nil nil)))))
(defmacro with-text-face ((medium face) &body body)
(declare (type symbol medium))
(when (eq medium t)
(setq medium '*standard-output*))
(with-gensyms (cont)
`(flet ((,cont (,medium)
,(declare-ignorable-form* medium)
,@body))
(declare (dynamic-extent #',cont))
(invoke-with-text-style ,medium #',cont
(make-text-style nil ,face nil)))))
(defmacro with-text-size ((medium size) &body body)
(declare (type symbol medium))
(when (eq medium t) (setq medium '*standard-output*))
(with-gensyms (cont)
`(flet ((,cont (,medium)
,(declare-ignorable-form* medium)
,@body))
(declare (dynamic-extent #',cont))
(invoke-with-text-style ,medium #',cont
(make-text-style nil nil ,size)))))
half - way correct ? --GB
trampoline will simply call the method for the medium . --
(defmethod text-size ((sheet sheet) string &rest more)
(apply #'text-size (sheet-medium sheet) string more))
(defmethod text-style-ascent (ts (sheet sheet))
(text-style-ascent ts (sheet-medium sheet)))
(defmethod text-style-descent (ts (sheet sheet))
(text-style-descent ts (sheet-medium sheet)))
(defmethod text-style-height (ts (sheet sheet))
(text-style-height ts (sheet-medium sheet)))
(defmethod text-style-width (ts (sheet sheet))
(text-style-width ts (sheet-medium sheet)))
Fallback methods for the text style metrics .
(defmethod text-style-height (text-style medium)
(+ (text-style-ascent text-style medium)
(text-style-descent text-style medium)))
(defmethod text-style-width (text-style medium)
(text-style-character-width text-style medium #\M))
(defmethod text-style-fixed-width-p (text-style medium)
(declare (ignore medium))
(eql (text-style-family text-style) :fix))
|
ed4e547db7787c6faf219be85c81a4020f028bb67fafa731efac5ab9790788ea | fragnix/fragnix | GHC.Integer.Compat.hs | {-# LANGUAGE Haskell2010 #-}
# LINE 1 " src / GHC / Integer / Compat.hs " #
# LANGUAGE CPP #
module GHC.Integer.Compat (divInteger) where
import GHC.Integer (divInteger)
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/scotty/GHC.Integer.Compat.hs | haskell | # LANGUAGE Haskell2010 # | # LINE 1 " src / GHC / Integer / Compat.hs " #
# LANGUAGE CPP #
module GHC.Integer.Compat (divInteger) where
import GHC.Integer (divInteger)
|
819a3a49a4f76a351ee7bba7c3fe2a26b44aa263e96424bb268a1deb06e7b970 | sgbj/MaximaSharp | dmzsol.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 1.221 2010/05/26 19:25:52 "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.204 2010/02/23 05:21:30 "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.114 2010/05/17 01:42:14 " )
Using Lisp CMU Common Lisp CVS Head 2010 - 05 - 25 18:21:07 ( 20A Unicode )
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :colnew)
(defun dmzsol (kd mstar n v z dmz)
(declare (type (array double-float (*)) z)
(type (array double-float (*)) dmz v)
(type (f2cl-lib:integer4) n mstar kd))
(f2cl-lib:with-multi-array-data
((v double-float v-%data% v-%offset%)
(dmz double-float dmz-%data% dmz-%offset%)
(z double-float z-%data% z-%offset%))
(prog ((l 0) (fact 0.0) (j 0) (i 0) (jz 0))
(declare (type double-float fact) (type (f2cl-lib:integer4) jz i j l))
(setf jz 1)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j mstar) nil)
(tagbody
(setf fact (f2cl-lib:fref z-%data% (jz) ((1 1)) z-%offset%))
(f2cl-lib:fdo (l 1 (f2cl-lib:int-add l 1))
((> l kd) nil)
(tagbody
(setf (f2cl-lib:fref dmz-%data%
(l i)
((1 kd) (1 1))
dmz-%offset%)
(+
(f2cl-lib:fref dmz-%data%
(l i)
((1 kd) (1 1))
dmz-%offset%)
(* fact
(f2cl-lib:fref v-%data%
(l jz)
((1 kd) (1 1))
v-%offset%))))
label10))
(setf jz (f2cl-lib:int-add jz 1))
label20))
label30))
(go end_label)
end_label
(return (values nil nil nil nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dmzsol
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (array double-float (*))
(array double-float (1)) (array double-float (*)))
:return-values '(nil nil nil nil nil nil)
:calls 'nil)))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/colnew/lisp/dmzsol.lisp | lisp | Compiled by f2cl version:
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 1.221 2010/05/26 19:25:52 "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.204 2010/02/23 05:21:30 "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.114 2010/05/17 01:42:14 " )
Using Lisp CMU Common Lisp CVS Head 2010 - 05 - 25 18:21:07 ( 20A Unicode )
(in-package :colnew)
(defun dmzsol (kd mstar n v z dmz)
(declare (type (array double-float (*)) z)
(type (array double-float (*)) dmz v)
(type (f2cl-lib:integer4) n mstar kd))
(f2cl-lib:with-multi-array-data
((v double-float v-%data% v-%offset%)
(dmz double-float dmz-%data% dmz-%offset%)
(z double-float z-%data% z-%offset%))
(prog ((l 0) (fact 0.0) (j 0) (i 0) (jz 0))
(declare (type double-float fact) (type (f2cl-lib:integer4) jz i j l))
(setf jz 1)
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1))
((> j mstar) nil)
(tagbody
(setf fact (f2cl-lib:fref z-%data% (jz) ((1 1)) z-%offset%))
(f2cl-lib:fdo (l 1 (f2cl-lib:int-add l 1))
((> l kd) nil)
(tagbody
(setf (f2cl-lib:fref dmz-%data%
(l i)
((1 kd) (1 1))
dmz-%offset%)
(+
(f2cl-lib:fref dmz-%data%
(l i)
((1 kd) (1 1))
dmz-%offset%)
(* fact
(f2cl-lib:fref v-%data%
(l jz)
((1 kd) (1 1))
v-%offset%))))
label10))
(setf jz (f2cl-lib:int-add jz 1))
label20))
label30))
(go end_label)
end_label
(return (values nil nil nil nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dmzsol
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (array double-float (*))
(array double-float (1)) (array double-float (*)))
:return-values '(nil nil nil nil nil nil)
:calls 'nil)))
|
d047dccf3b66c483a20114930bed424666ef5e248d7e21fd20cdcd860acec583 | den1k/vimsical | handlers.cljc | (ns vimsical.frontend.vims.handlers
(:require
[vimsical.subgraph :as sg]
[re-frame.core :as re-frame]
[vimsical.common.util.core :as util]
[vimsical.common.uuid :refer [uuid]]
[vimsical.frontend.util.subgraph :as util.sg]
[vimsical.frontend.util.re-frame :as util.re-frame]
[vimsical.frontend.vcs.subs :as vcs.subs]
[vimsical.frontend.vcs.handlers :as vcs.handlers]
[vimsical.frontend.vcs.sync.handlers :as vcs.sync.handlers]
[vimsical.frontend.vims.db :as db]
[vimsical.remotes.backend.vims.commands :as vims.commands]
[vimsical.remotes.backend.vims.queries :as vims.queries]
[vimsical.frontend.router.handlers :as router.handlers]
[vimsical.frontend.router.routes :as router.routes]
[vimsical.vcs.file :as vcs.file]
[vimsical.vcs.snapshot :as vcs.snapshot]
[vimsical.vims :as vims]
[vimsical.user :as user]
[vimsical.frontend.vims.db :as vims.db]))
;;
;; * New vims
;;
;; Could parametrize the user prefs here?
(defn- default-files
([] (default-files (uuid) (uuid) (uuid)))
([html-uid css-uid javascript-uid]
[(vcs.file/new-file html-uid :text :html)
(vcs.file/new-file css-uid :text :css)
(vcs.file/new-file javascript-uid :text :javascript)]))
(defn new-event-fx
[{:keys [db]} [_ owner status-key opts]]
(let [new-files (vims/default-files)
owner' (select-keys owner [:db/uid])
{vims-uid :db/uid :as new-vims} (vims/new-vims owner' nil new-files opts)
;; This is a bit low-level, we could just conj the vims onto the owner
;; and add that, but we'd have to make sure we're passed the full
;; app/user, not sure if that'd be inconvenient.
db' (util.sg/add-join db owner' ::user/vimsae new-vims)]
{:db db'
:remote
{:id :backend
:event [::vims.commands/new new-vims]
:dispatch-success (fn [_] [::new-success vims-uid new-vims])
:dispatch-error (fn [error] [::new-error vims-uid new-vims error])
:status-key status-key}}))
(re-frame/reg-event-fx ::new new-event-fx)
(re-frame/reg-event-fx ::new-success (fn [_ _] (re-frame.loggers/console :log "New vims success")))
(re-frame/reg-event-fx ::new-error (fn [_ e] (re-frame.loggers/console :log "Vims error" e)))
;;
;; * Delete vims
;;
(defn delete-event-fx
[{:keys [db]} [_ vims status-key]]
(let [vims-uid (util.sg/->uid db vims)
db' (util.sg/remove db vims)]
{:db db'
:remote
{:id :backend
:event [::vims.commands/delete vims-uid]
:dispatch-success (fn [_] [::delete-success vims-uid])
:dispatch-error (fn [_] [::delete-error vims-uid])
:status-key status-key}}))
(re-frame/reg-event-fx ::delete delete-event-fx)
(re-frame/reg-event-fx ::delete-success (fn [_ _] (re-frame.loggers/console :log "Delete success")))
(re-frame/reg-event-fx ::delete-error (fn [_ e] (re-frame.loggers/console :log "Delete error" e)))
;;
;; * Title
;;
(defn title-event-fx
[{:keys [db]} [_ vims title status-key]]
(let [vims' (assoc vims ::vims/title title)
remote (select-keys vims' [:db/uid ::vims/title])
db' (util.sg/add db vims')]
{:db db'
:remote
{:id :backend
:event [::vims.commands/title remote]
:dispatch-success (fn [_] [::title-success vims'])
:dispatch-error (fn [error] [::title-error vims error])
:status-key status-key}}))
(re-frame/reg-event-fx ::title title-event-fx)
(re-frame/reg-event-fx ::title-success (fn [_ _] (re-frame.loggers/console :log "title success")))
;;
;; * Snapshots
;;
(re-frame/reg-event-fx
::update-snapshots
[(util.re-frame/inject-sub
(fn [[_ vims]] [::vcs.subs/files vims]))]
(fn [{:keys [db] ::vcs.subs/keys [files]} [_ vims status-key]]
;; Dispatch an event per file to update their state, then upload
{:dispatch-n
(conj (mapv (fn [file] [::update-snapshot vims file]) files)
[::update-snapshots-remote vims status-key])}))
(re-frame/reg-event-fx
::update-snapshot
[(util.re-frame/inject-sub
(fn [[_ vims file]]
[::vcs.subs/preprocessed-file-string vims file]))]
(fn [{:keys [db]
::vcs.subs/keys [preprocessed-file-string]}
[_ vims file]]
(when preprocessed-file-string
(let [[_ vims-uid :as vims-ref] (util.sg/->ref db vims)
{:as vims' {user-uid :db/uid} ::vims/owner} (sg/pull db [:db/uid {::vims/owner [:db/uid]} {::vims/snapshots ['*]}] vims-ref)
snapshot (vcs.snapshot/new-frontend-snapshot (uuid) user-uid vims-uid file preprocessed-file-string)
vims'' (update vims' ::vims/snapshots (fnil util/replace-by-or-conj []) ::vcs.snapshot/file-uid snapshot)]
{:db (util.sg/add db vims'')}))))
(re-frame/reg-event-fx
::update-snapshots-remote
(fn upload-snapshots-event-fx
[{:keys [db]} [_ vims status-key]]
;; Pull the vims again since we know it is now stale
(let [vims-ref (util.sg/->ref db vims)
{::vims/keys [snapshots]} (sg/pull db [{::vims/snapshots ['*]}] vims-ref)
remote-snapshots (mapv vcs.snapshot/->remote-snapshot snapshots)]
(when (seq remote-snapshots)
{:remote
{:id :backend
:event [::vims.commands/update-snapshots remote-snapshots]
:dispatch-success (fn [resp] (re-frame.loggers/console :log "SNAPSHOTS success"))
:dispatch-error (fn [e] (re-frame.loggers/console :log "SNAPSHOTS error" e))
:status-key status-key}}))))
;;
;; * Remote queries
;;
;;
* * Vims
;;
(defn vims-handler
[{:keys [db]} [_ vims-uid status-key]]
{:remote
{:id :backend
:status-key status-key
:event [::vims.queries/vims vims-uid]
:dispatch-success (fn [vims] [::vims-success vims-uid vims])
:dispatch-error (fn [e] [::vims-error vims-uid e])}})
(defn vims-success-event-fx
[{:keys [db]} [_ _ vims]]
{:db (util.sg/add db vims)})
(defn vims-error-event-fx
[{:keys [db]} [_ _ {:keys [status]}]]
(when (== 404 status)
{:dispatch [::router.handlers/route ::router.routes/landing]}))
(re-frame/reg-event-fx ::vims vims-handler)
(re-frame/reg-event-fx ::vims-success vims-success-event-fx)
(re-frame/reg-event-fx ::vims-error vims-error-event-fx)
;;
;; * Async loading flow
;;
(defn load-vims-async-flow
[vims-uid {:keys [uuid-fn first-dispatch] :or {uuid-fn uuid} :as options}]
{:pre [(uuid? vims-uid)]}
(letfn [(event+uuid [[id uuid]] [id uuid])]
{:id [::load-vims-async vims-uid]
:first-dispatch [::load-vims-async-did-start vims-uid]
:event-id->seen-fn {::deltas-success event+uuid
::vims-success event+uuid}
:rules [{:when :seen-all-of?
:events [[::deltas-success vims-uid]
[::vims-success vims-uid]]
:dispatch [::load-vims-async-did-complete vims-uid options]}]
:halt? true}))
(re-frame/reg-event-fx
::load-vims-async-did-start
(fn [{:keys [db]} [_ vims-uid]]
{:dispatch-n
[[::vims vims-uid]
[::deltas vims-uid]]}))
(re-frame/reg-event-fx
::load-vims-async-did-complete
(fn [{:keys [db]} [_ vims-uid {:keys [uuid-fn] :or {uuid-fn uuid} :as options} ]]
(let [deltas (vims.db/get-deltas db vims-uid)]
{:dispatch-n
[[::vcs.handlers/init vims-uid deltas options]
[::vcs.sync.handlers/start vims-uid]]})))
(re-frame/reg-event-fx
::load-vims
(fn [{:keys [db]} [_ vims {:keys [uuid-fn] :or {uuid-fn uuid} :as options}]]
{:pre [vims]}
(when vims
(let [[_ vims-uid] (util.sg/->ref db vims)]
(when (not (vims.db/loaded? db vims))
{:async-flow (load-vims-async-flow vims-uid options)})))))
;;
;; ** Deltas
;;
(defn deltas-handler
[{:keys [db]} [_ vims-uid status-key]]
{:remote
{:id :backend
:status-key status-key
:event [::vims.queries/deltas vims-uid]
:dispatch-success (fn [deltas] [::deltas-success vims-uid deltas])}})
(defn deltas-success-handler
[{:keys [db]} [_ vims-uid deltas]]
{:db (db/set-deltas db vims-uid deltas)})
(re-frame/reg-event-fx ::deltas deltas-handler)
(re-frame/reg-event-fx ::deltas-success deltas-success-handler)
| null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/frontend/vimsical/frontend/vims/handlers.cljc | clojure |
* New vims
Could parametrize the user prefs here?
This is a bit low-level, we could just conj the vims onto the owner
and add that, but we'd have to make sure we're passed the full
app/user, not sure if that'd be inconvenient.
* Delete vims
* Title
* Snapshots
Dispatch an event per file to update their state, then upload
Pull the vims again since we know it is now stale
* Remote queries
* Async loading flow
** Deltas
| (ns vimsical.frontend.vims.handlers
(:require
[vimsical.subgraph :as sg]
[re-frame.core :as re-frame]
[vimsical.common.util.core :as util]
[vimsical.common.uuid :refer [uuid]]
[vimsical.frontend.util.subgraph :as util.sg]
[vimsical.frontend.util.re-frame :as util.re-frame]
[vimsical.frontend.vcs.subs :as vcs.subs]
[vimsical.frontend.vcs.handlers :as vcs.handlers]
[vimsical.frontend.vcs.sync.handlers :as vcs.sync.handlers]
[vimsical.frontend.vims.db :as db]
[vimsical.remotes.backend.vims.commands :as vims.commands]
[vimsical.remotes.backend.vims.queries :as vims.queries]
[vimsical.frontend.router.handlers :as router.handlers]
[vimsical.frontend.router.routes :as router.routes]
[vimsical.vcs.file :as vcs.file]
[vimsical.vcs.snapshot :as vcs.snapshot]
[vimsical.vims :as vims]
[vimsical.user :as user]
[vimsical.frontend.vims.db :as vims.db]))
(defn- default-files
([] (default-files (uuid) (uuid) (uuid)))
([html-uid css-uid javascript-uid]
[(vcs.file/new-file html-uid :text :html)
(vcs.file/new-file css-uid :text :css)
(vcs.file/new-file javascript-uid :text :javascript)]))
(defn new-event-fx
[{:keys [db]} [_ owner status-key opts]]
(let [new-files (vims/default-files)
owner' (select-keys owner [:db/uid])
{vims-uid :db/uid :as new-vims} (vims/new-vims owner' nil new-files opts)
db' (util.sg/add-join db owner' ::user/vimsae new-vims)]
{:db db'
:remote
{:id :backend
:event [::vims.commands/new new-vims]
:dispatch-success (fn [_] [::new-success vims-uid new-vims])
:dispatch-error (fn [error] [::new-error vims-uid new-vims error])
:status-key status-key}}))
(re-frame/reg-event-fx ::new new-event-fx)
(re-frame/reg-event-fx ::new-success (fn [_ _] (re-frame.loggers/console :log "New vims success")))
(re-frame/reg-event-fx ::new-error (fn [_ e] (re-frame.loggers/console :log "Vims error" e)))
(defn delete-event-fx
[{:keys [db]} [_ vims status-key]]
(let [vims-uid (util.sg/->uid db vims)
db' (util.sg/remove db vims)]
{:db db'
:remote
{:id :backend
:event [::vims.commands/delete vims-uid]
:dispatch-success (fn [_] [::delete-success vims-uid])
:dispatch-error (fn [_] [::delete-error vims-uid])
:status-key status-key}}))
(re-frame/reg-event-fx ::delete delete-event-fx)
(re-frame/reg-event-fx ::delete-success (fn [_ _] (re-frame.loggers/console :log "Delete success")))
(re-frame/reg-event-fx ::delete-error (fn [_ e] (re-frame.loggers/console :log "Delete error" e)))
(defn title-event-fx
[{:keys [db]} [_ vims title status-key]]
(let [vims' (assoc vims ::vims/title title)
remote (select-keys vims' [:db/uid ::vims/title])
db' (util.sg/add db vims')]
{:db db'
:remote
{:id :backend
:event [::vims.commands/title remote]
:dispatch-success (fn [_] [::title-success vims'])
:dispatch-error (fn [error] [::title-error vims error])
:status-key status-key}}))
(re-frame/reg-event-fx ::title title-event-fx)
(re-frame/reg-event-fx ::title-success (fn [_ _] (re-frame.loggers/console :log "title success")))
(re-frame/reg-event-fx
::update-snapshots
[(util.re-frame/inject-sub
(fn [[_ vims]] [::vcs.subs/files vims]))]
(fn [{:keys [db] ::vcs.subs/keys [files]} [_ vims status-key]]
{:dispatch-n
(conj (mapv (fn [file] [::update-snapshot vims file]) files)
[::update-snapshots-remote vims status-key])}))
(re-frame/reg-event-fx
::update-snapshot
[(util.re-frame/inject-sub
(fn [[_ vims file]]
[::vcs.subs/preprocessed-file-string vims file]))]
(fn [{:keys [db]
::vcs.subs/keys [preprocessed-file-string]}
[_ vims file]]
(when preprocessed-file-string
(let [[_ vims-uid :as vims-ref] (util.sg/->ref db vims)
{:as vims' {user-uid :db/uid} ::vims/owner} (sg/pull db [:db/uid {::vims/owner [:db/uid]} {::vims/snapshots ['*]}] vims-ref)
snapshot (vcs.snapshot/new-frontend-snapshot (uuid) user-uid vims-uid file preprocessed-file-string)
vims'' (update vims' ::vims/snapshots (fnil util/replace-by-or-conj []) ::vcs.snapshot/file-uid snapshot)]
{:db (util.sg/add db vims'')}))))
(re-frame/reg-event-fx
::update-snapshots-remote
(fn upload-snapshots-event-fx
[{:keys [db]} [_ vims status-key]]
(let [vims-ref (util.sg/->ref db vims)
{::vims/keys [snapshots]} (sg/pull db [{::vims/snapshots ['*]}] vims-ref)
remote-snapshots (mapv vcs.snapshot/->remote-snapshot snapshots)]
(when (seq remote-snapshots)
{:remote
{:id :backend
:event [::vims.commands/update-snapshots remote-snapshots]
:dispatch-success (fn [resp] (re-frame.loggers/console :log "SNAPSHOTS success"))
:dispatch-error (fn [e] (re-frame.loggers/console :log "SNAPSHOTS error" e))
:status-key status-key}}))))
* * Vims
(defn vims-handler
[{:keys [db]} [_ vims-uid status-key]]
{:remote
{:id :backend
:status-key status-key
:event [::vims.queries/vims vims-uid]
:dispatch-success (fn [vims] [::vims-success vims-uid vims])
:dispatch-error (fn [e] [::vims-error vims-uid e])}})
(defn vims-success-event-fx
[{:keys [db]} [_ _ vims]]
{:db (util.sg/add db vims)})
(defn vims-error-event-fx
[{:keys [db]} [_ _ {:keys [status]}]]
(when (== 404 status)
{:dispatch [::router.handlers/route ::router.routes/landing]}))
(re-frame/reg-event-fx ::vims vims-handler)
(re-frame/reg-event-fx ::vims-success vims-success-event-fx)
(re-frame/reg-event-fx ::vims-error vims-error-event-fx)
(defn load-vims-async-flow
[vims-uid {:keys [uuid-fn first-dispatch] :or {uuid-fn uuid} :as options}]
{:pre [(uuid? vims-uid)]}
(letfn [(event+uuid [[id uuid]] [id uuid])]
{:id [::load-vims-async vims-uid]
:first-dispatch [::load-vims-async-did-start vims-uid]
:event-id->seen-fn {::deltas-success event+uuid
::vims-success event+uuid}
:rules [{:when :seen-all-of?
:events [[::deltas-success vims-uid]
[::vims-success vims-uid]]
:dispatch [::load-vims-async-did-complete vims-uid options]}]
:halt? true}))
(re-frame/reg-event-fx
::load-vims-async-did-start
(fn [{:keys [db]} [_ vims-uid]]
{:dispatch-n
[[::vims vims-uid]
[::deltas vims-uid]]}))
(re-frame/reg-event-fx
::load-vims-async-did-complete
(fn [{:keys [db]} [_ vims-uid {:keys [uuid-fn] :or {uuid-fn uuid} :as options} ]]
(let [deltas (vims.db/get-deltas db vims-uid)]
{:dispatch-n
[[::vcs.handlers/init vims-uid deltas options]
[::vcs.sync.handlers/start vims-uid]]})))
(re-frame/reg-event-fx
::load-vims
(fn [{:keys [db]} [_ vims {:keys [uuid-fn] :or {uuid-fn uuid} :as options}]]
{:pre [vims]}
(when vims
(let [[_ vims-uid] (util.sg/->ref db vims)]
(when (not (vims.db/loaded? db vims))
{:async-flow (load-vims-async-flow vims-uid options)})))))
(defn deltas-handler
[{:keys [db]} [_ vims-uid status-key]]
{:remote
{:id :backend
:status-key status-key
:event [::vims.queries/deltas vims-uid]
:dispatch-success (fn [deltas] [::deltas-success vims-uid deltas])}})
(defn deltas-success-handler
[{:keys [db]} [_ vims-uid deltas]]
{:db (db/set-deltas db vims-uid deltas)})
(re-frame/reg-event-fx ::deltas deltas-handler)
(re-frame/reg-event-fx ::deltas-success deltas-success-handler)
|
37f42efc26f654eeb997e9a86a2ee3c9d48fe64ebedc0962ac9fec47d8cdabf4 | vydd/sketch | sketch.lisp | ;;;; sketch.lisp
(in-package #:sketch)
;;; "sketch" goes here. Hacks and glory await!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
;;; _|_|_| _| _| _|_|_|_| _|_|_|_|_| _|_|_| _| _| ;;;
;;; _| _| _| _| _| _| _| _| ;;;
;;; _|_| _|_| _|_|_| _| _| _|_|_|_| ;;;
;;; _| _| _| _| _| _| _| _| ;;;
;;; _|_|_| _| _| _|_|_|_| _| _|_|_| _| _| ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Sketch class
(defparameter *sketch* nil
"The current sketch instance.")
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *default-slots*
'((title :initform "Sketch" :reader sketch-title :initarg :title)
(width :initform 400 :reader sketch-width :initarg :width)
(height :initform 400 :reader sketch-height :initarg :height)
(fullscreen :initform nil :reader sketch-fullscreen :initarg :fullscreen)
(copy-pixels :initform nil :accessor sketch-copy-pixels :initarg :copy-pixels)
(y-axis :initform :down :reader sketch-y-axis :initarg :y-axis))))
(defmacro define-sketch-class ()
`(defclass sketch (kit.sdl2:gl-window)
((%env :initform (make-env))
(%restart :initform t)
,@*default-slots*)))
(define-sketch-class)
;;; Non trivial sketch writers
(defmacro define-sketch-writer (slot &body body)
`(defmethod (setf ,(alexandria:symbolicate 'sketch- slot)) (value (instance sketch))
(setf (slot-value instance ',slot) value)
(let ((win (kit.sdl2:sdl-window instance)))
,@body)))
(defgeneric (setf sketch-title) (value instance))
(defgeneric (setf sketch-width) (value instance))
(defgeneric (setf sketch-height) (value instance))
(defgeneric (setf sketch-fullscreen) (value instance))
(defgeneric (setf sketch-y-axis) (value instance))
(define-sketch-writer title
(sdl2:set-window-title win (slot-value instance 'title)))
(define-sketch-writer width
(sdl2:set-window-size win (slot-value instance 'width)
(slot-value instance 'height)))
(define-sketch-writer height
(sdl2:set-window-size win (slot-value instance 'width)
(slot-value instance 'height)))
(define-sketch-writer fullscreen
(sdl2:set-window-fullscreen win (slot-value instance 'fullscreen)))
(define-sketch-writer y-axis
(declare (ignore win))
(with-slots ((env %env) width height y-axis) instance
(setf (env-view-matrix env)
(if (eq y-axis :down)
(kit.glm:ortho-matrix 0 width height 0 -1 1)
(kit.glm:ortho-matrix 0 width 0 height -1 1)))
(kit.gl.shader:uniform-matrix
(env-programs env) :view-m 4 (vector (env-view-matrix env)))))
Generic functions
(defgeneric prepare (instance &key &allow-other-keys)
(:documentation "Generated by DEFSKETCH.")
(:method-combination progn :most-specific-last))
(defgeneric setup (instance &key &allow-other-keys)
(:documentation "Called before creating the sketch window.")
(:method ((instance sketch) &key &allow-other-keys) ()))
(defgeneric draw (instance &key &allow-other-keys)
(:documentation "Called repeatedly after creating the sketch window,
used for drawing, 60fps.")
(:method ((instance sketch) &key &allow-other-keys) ()))
;;; Initialization
(defparameter *initialized* nil)
(defun initialize-sketch ()
(unless *initialized*
(setf *initialized* t)
(kit.sdl2:init)
(sdl2-ttf:init)
(sdl2:in-main-thread ()
(sdl2:gl-set-attr :multisamplebuffers 1)
(sdl2:gl-set-attr :multisamplesamples 4)
(sdl2:gl-set-attr :context-major-version 3)
(sdl2:gl-set-attr :context-minor-version 3)
(sdl2:gl-set-attr :context-profile-mask 1))))
(defmethod initialize-instance :around ((instance sketch) &key &allow-other-keys)
(initialize-sketch)
(call-next-method)
(kit.sdl2:start))
(defmethod initialize-instance :after ((instance sketch) &rest initargs &key &allow-other-keys)
(initialize-environment instance)
(apply #'prepare (list* instance initargs))
(initialize-gl instance))
(defmethod update-instance-for-redefined-class :after
((instance sketch) added-slots discarded-slots property-list &rest initargs)
(declare (ignore added-slots discarded-slots property-list))
(apply #'prepare (list* instance initargs)))
;;; Rendering
(defmacro gl-catch (error-color &body body)
`(handler-case
(progn
,@body)
(error (e)
(progn
(background ,error-color)
(with-font (make-error-font)
(with-identity-matrix
(text (format nil "ERROR~%---~%~a~%---~%Click for restarts." e) 20 20)))
(setf %restart t
(env-red-screen *env*) t)))))
(defun draw-window (window)
(start-draw)
(draw window)
(end-draw))
(defmethod kit.sdl2:render ((instance sketch))
(with-slots (%env %restart width height copy-pixels) instance
(with-environment %env
(with-pen (make-default-pen)
(with-font (make-default-font)
(with-identity-matrix
(unless copy-pixels
(background (gray 0.4)))
Restart sketch on setup and when recovering from an error .
(when %restart
(gl-catch (rgb 1 1 0.3)
(setup instance))
(setf (slot-value instance '%restart) nil))
;; If we're in the debug mode, we exit from it immediately,
;; so that the restarts are shown only once. Afterwards, we
;; continue presenting the user with the red screen, waiting for
;; the error to be fixed, or for the debug key to be pressed again.
(if (debug-mode-p)
(progn
(exit-debug-mode)
(draw-window instance))
(gl-catch (rgb 0.7 0 0)
(draw-window instance)))))))))
;;; Support for resizable windows
(defmethod kit.sdl2:window-event :before ((instance sketch) (type (eql :size-changed)) timestamp data1 data2)
(with-slots ((env %env) width height y-axis) instance
(setf width data1
height data2
(env-view-matrix env)
(if (eq y-axis :down)
(kit.glm:ortho-matrix 0 width height 0 -1 1)
(kit.glm:ortho-matrix 0 width 0 height -1 1)))
(gl:viewport 0 0 width height)
(kit.gl.shader:uniform-matrix
(env-programs env) :view-m 4 (vector (env-view-matrix env)))))
;;; Default events
(defmethod kit.sdl2:keyboard-event :before ((instance sketch) state timestamp repeatp keysym)
(declare (ignorable timestamp repeatp))
(when (and (eql state :keydown)
(sdl2:scancode= (sdl2:scancode-value keysym) :scancode-escape))
(kit.sdl2:close-window instance)))
(defmethod close-window :before ((instance sketch))
(with-environment (slot-value instance '%env)
(loop for resource being the hash-values of (env-resources *env*)
do (free-resource resource))))
(defmethod close-window :after ((instance sketch))
(when (and *build* (not (kit.sdl2:all-windows)))
(sdl2-ttf:quit)
(kit.sdl2:quit)))
DEFSKETCH helpers
(defun first-two (list)
(list (first list) (second list)))
(defun default-slot-p (slot-or-binding)
(let ((defaults (mapcar #'car *default-slots*)))
(typecase slot-or-binding
(list (member (car slot-or-binding) defaults))
(t (member slot-or-binding defaults)))))
(defun custom-bindings (&optional bindings)
(remove-if (lambda (binding)
(member (car binding) (mapcar #'car *default-slots*)))
bindings))
(defun intern-accessor (name)
(intern (string (alexandria:symbolicate 'sketch- name)) :sketch))
(defun binding-accessor (sketch binding)
(if (default-slot-p binding)
(intern-accessor (car binding))
(or (cadr (member :accessor (cddr binding)))
(alexandria:symbolicate sketch '- (car binding)))))
(defun make-slot-form (sketch binding)
`(,(car binding)
:initarg ,(alexandria:make-keyword (car binding))
:accessor ,(binding-accessor sketch binding)))
DEFSKETCH channels
(defun channel-binding-p (binding)
(and (consp (cadr binding)) (eql 'in (caadr binding))))
(defun make-channel-observer (sketch binding)
`(define-channel-observer
(let ((win (kit.sdl2:last-window)))
(when win
(setf (,(binding-accessor sketch binding) win) ,(cadr binding))))))
(defun make-channel-observers (sketch bindings)
(mapcar (lambda (binding)
(when (channel-binding-p binding)
(make-channel-observer sketch binding)))
bindings))
(defun replace-channels-with-values (bindings)
(loop for binding in bindings
collect (list (car binding)
(if (channel-binding-p binding)
(caddr (cadr binding))
(cadr binding)))))
DEFSKETCH bindings
(defun sketch-bindings-to-slots (sketch bindings)
(mapcar (lambda (x) (make-slot-form sketch x))
(remove-if (lambda (x)
(member (car x) (mapcar #'car *default-slots*)))
bindings)))
DEFSKETCH setf instructions
(defun make-window-parameter-setf ()
`(setf ,@(mapcan (lambda (slot)
`((,(intern-accessor (car slot)) instance) ,(car slot)))
*default-slots*)))
(defun make-custom-slots-setf (sketch bindings)
`(setf ,@(mapcan (lambda (binding)
`((slot-value instance ',(car binding)) ,(car binding)))
bindings)))
(defun make-reinitialize-setf ()
`(setf ,@(mapcan (lambda (slot)
`((,(intern-accessor (car slot)) instance)
(,(intern-accessor (car slot)) instance)))
*default-slots*)))
(defun custom-slots (bindings)
(loop
for b in (mapcar #'car bindings)
if (not (member b *default-slots*))
collect b))
DEFSKETCH macro
(defmacro defsketch (sketch-name bindings &body body)
(let ((default-not-overridden
(remove-if (lambda (x) (find x bindings :key #'car))
(mapcar #'car *default-slots*))))
`(progn
(defclass ,sketch-name (sketch)
,(sketch-bindings-to-slots `,sketch-name bindings))
,@(remove-if-not #'identity (make-channel-observers sketch-name bindings))
(defmethod prepare progn ((instance ,sketch-name) &rest initargs &key &allow-other-keys)
(declare (ignorable initargs))
(let* (,@(loop for slot in default-not-overridden
collect `(,slot (slot-value instance ',slot)))
,@(mapcar (lambda (binding)
(destructuring-bind (name value)
(first-two binding)
(list name (if (default-slot-p name)
`(if (getf initargs ,(alexandria:make-keyword name))
(slot-value instance ',name)
,value)
`(or (getf initargs ,(alexandria:make-keyword name)) ,value)))))
(replace-channels-with-values bindings)))
(declare (ignorable ,@(mapcar #'car *default-slots*) ,@(custom-slots bindings)))
,(make-window-parameter-setf)
,(make-custom-slots-setf sketch-name (custom-bindings bindings)))
(setf (env-y-axis-sgn (slot-value instance '%env))
(if (eq (slot-value instance 'y-axis) :down) +1 -1)))
(defmethod draw ((instance ,sketch-name) &key &allow-other-keys)
(let ((*sketch* instance))
(with-accessors ,(mapcar (lambda (x) (list (car x) (intern-accessor (car x))))
*default-slots*) instance
(with-slots ,(mapcar #'car bindings) instance
,@body))))
(make-instances-obsolete ',sketch-name)
(find-class ',sketch-name))))
| null | https://raw.githubusercontent.com/vydd/sketch/aea3f9509182749fa80bcc993dc0f284559b2392/src/sketch.lisp | lisp | sketch.lisp
"sketch" goes here. Hacks and glory await!
;;;
_|_|_| _| _| _|_|_|_| _|_|_|_|_| _|_|_| _| _| ;;;
_| _| _| _| _| _| _| _| ;;;
_|_| _|_| _|_|_| _| _| _|_|_|_| ;;;
_| _| _| _| _| _| _| _| ;;;
_|_|_| _| _| _|_|_|_| _| _|_|_| _| _| ;;;
;;;
Sketch class
Non trivial sketch writers
Initialization
Rendering
If we're in the debug mode, we exit from it immediately,
so that the restarts are shown only once. Afterwards, we
continue presenting the user with the red screen, waiting for
the error to be fixed, or for the debug key to be pressed again.
Support for resizable windows
Default events |
(in-package #:sketch)
(defparameter *sketch* nil
"The current sketch instance.")
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *default-slots*
'((title :initform "Sketch" :reader sketch-title :initarg :title)
(width :initform 400 :reader sketch-width :initarg :width)
(height :initform 400 :reader sketch-height :initarg :height)
(fullscreen :initform nil :reader sketch-fullscreen :initarg :fullscreen)
(copy-pixels :initform nil :accessor sketch-copy-pixels :initarg :copy-pixels)
(y-axis :initform :down :reader sketch-y-axis :initarg :y-axis))))
(defmacro define-sketch-class ()
`(defclass sketch (kit.sdl2:gl-window)
((%env :initform (make-env))
(%restart :initform t)
,@*default-slots*)))
(define-sketch-class)
(defmacro define-sketch-writer (slot &body body)
`(defmethod (setf ,(alexandria:symbolicate 'sketch- slot)) (value (instance sketch))
(setf (slot-value instance ',slot) value)
(let ((win (kit.sdl2:sdl-window instance)))
,@body)))
(defgeneric (setf sketch-title) (value instance))
(defgeneric (setf sketch-width) (value instance))
(defgeneric (setf sketch-height) (value instance))
(defgeneric (setf sketch-fullscreen) (value instance))
(defgeneric (setf sketch-y-axis) (value instance))
(define-sketch-writer title
(sdl2:set-window-title win (slot-value instance 'title)))
(define-sketch-writer width
(sdl2:set-window-size win (slot-value instance 'width)
(slot-value instance 'height)))
(define-sketch-writer height
(sdl2:set-window-size win (slot-value instance 'width)
(slot-value instance 'height)))
(define-sketch-writer fullscreen
(sdl2:set-window-fullscreen win (slot-value instance 'fullscreen)))
(define-sketch-writer y-axis
(declare (ignore win))
(with-slots ((env %env) width height y-axis) instance
(setf (env-view-matrix env)
(if (eq y-axis :down)
(kit.glm:ortho-matrix 0 width height 0 -1 1)
(kit.glm:ortho-matrix 0 width 0 height -1 1)))
(kit.gl.shader:uniform-matrix
(env-programs env) :view-m 4 (vector (env-view-matrix env)))))
Generic functions
(defgeneric prepare (instance &key &allow-other-keys)
(:documentation "Generated by DEFSKETCH.")
(:method-combination progn :most-specific-last))
(defgeneric setup (instance &key &allow-other-keys)
(:documentation "Called before creating the sketch window.")
(:method ((instance sketch) &key &allow-other-keys) ()))
(defgeneric draw (instance &key &allow-other-keys)
(:documentation "Called repeatedly after creating the sketch window,
used for drawing, 60fps.")
(:method ((instance sketch) &key &allow-other-keys) ()))
(defparameter *initialized* nil)
(defun initialize-sketch ()
(unless *initialized*
(setf *initialized* t)
(kit.sdl2:init)
(sdl2-ttf:init)
(sdl2:in-main-thread ()
(sdl2:gl-set-attr :multisamplebuffers 1)
(sdl2:gl-set-attr :multisamplesamples 4)
(sdl2:gl-set-attr :context-major-version 3)
(sdl2:gl-set-attr :context-minor-version 3)
(sdl2:gl-set-attr :context-profile-mask 1))))
(defmethod initialize-instance :around ((instance sketch) &key &allow-other-keys)
(initialize-sketch)
(call-next-method)
(kit.sdl2:start))
(defmethod initialize-instance :after ((instance sketch) &rest initargs &key &allow-other-keys)
(initialize-environment instance)
(apply #'prepare (list* instance initargs))
(initialize-gl instance))
(defmethod update-instance-for-redefined-class :after
((instance sketch) added-slots discarded-slots property-list &rest initargs)
(declare (ignore added-slots discarded-slots property-list))
(apply #'prepare (list* instance initargs)))
(defmacro gl-catch (error-color &body body)
`(handler-case
(progn
,@body)
(error (e)
(progn
(background ,error-color)
(with-font (make-error-font)
(with-identity-matrix
(text (format nil "ERROR~%---~%~a~%---~%Click for restarts." e) 20 20)))
(setf %restart t
(env-red-screen *env*) t)))))
(defun draw-window (window)
(start-draw)
(draw window)
(end-draw))
(defmethod kit.sdl2:render ((instance sketch))
(with-slots (%env %restart width height copy-pixels) instance
(with-environment %env
(with-pen (make-default-pen)
(with-font (make-default-font)
(with-identity-matrix
(unless copy-pixels
(background (gray 0.4)))
Restart sketch on setup and when recovering from an error .
(when %restart
(gl-catch (rgb 1 1 0.3)
(setup instance))
(setf (slot-value instance '%restart) nil))
(if (debug-mode-p)
(progn
(exit-debug-mode)
(draw-window instance))
(gl-catch (rgb 0.7 0 0)
(draw-window instance)))))))))
(defmethod kit.sdl2:window-event :before ((instance sketch) (type (eql :size-changed)) timestamp data1 data2)
(with-slots ((env %env) width height y-axis) instance
(setf width data1
height data2
(env-view-matrix env)
(if (eq y-axis :down)
(kit.glm:ortho-matrix 0 width height 0 -1 1)
(kit.glm:ortho-matrix 0 width 0 height -1 1)))
(gl:viewport 0 0 width height)
(kit.gl.shader:uniform-matrix
(env-programs env) :view-m 4 (vector (env-view-matrix env)))))
(defmethod kit.sdl2:keyboard-event :before ((instance sketch) state timestamp repeatp keysym)
(declare (ignorable timestamp repeatp))
(when (and (eql state :keydown)
(sdl2:scancode= (sdl2:scancode-value keysym) :scancode-escape))
(kit.sdl2:close-window instance)))
(defmethod close-window :before ((instance sketch))
(with-environment (slot-value instance '%env)
(loop for resource being the hash-values of (env-resources *env*)
do (free-resource resource))))
(defmethod close-window :after ((instance sketch))
(when (and *build* (not (kit.sdl2:all-windows)))
(sdl2-ttf:quit)
(kit.sdl2:quit)))
DEFSKETCH helpers
(defun first-two (list)
(list (first list) (second list)))
(defun default-slot-p (slot-or-binding)
(let ((defaults (mapcar #'car *default-slots*)))
(typecase slot-or-binding
(list (member (car slot-or-binding) defaults))
(t (member slot-or-binding defaults)))))
(defun custom-bindings (&optional bindings)
(remove-if (lambda (binding)
(member (car binding) (mapcar #'car *default-slots*)))
bindings))
(defun intern-accessor (name)
(intern (string (alexandria:symbolicate 'sketch- name)) :sketch))
(defun binding-accessor (sketch binding)
(if (default-slot-p binding)
(intern-accessor (car binding))
(or (cadr (member :accessor (cddr binding)))
(alexandria:symbolicate sketch '- (car binding)))))
(defun make-slot-form (sketch binding)
`(,(car binding)
:initarg ,(alexandria:make-keyword (car binding))
:accessor ,(binding-accessor sketch binding)))
DEFSKETCH channels
(defun channel-binding-p (binding)
(and (consp (cadr binding)) (eql 'in (caadr binding))))
(defun make-channel-observer (sketch binding)
`(define-channel-observer
(let ((win (kit.sdl2:last-window)))
(when win
(setf (,(binding-accessor sketch binding) win) ,(cadr binding))))))
(defun make-channel-observers (sketch bindings)
(mapcar (lambda (binding)
(when (channel-binding-p binding)
(make-channel-observer sketch binding)))
bindings))
(defun replace-channels-with-values (bindings)
(loop for binding in bindings
collect (list (car binding)
(if (channel-binding-p binding)
(caddr (cadr binding))
(cadr binding)))))
DEFSKETCH bindings
(defun sketch-bindings-to-slots (sketch bindings)
(mapcar (lambda (x) (make-slot-form sketch x))
(remove-if (lambda (x)
(member (car x) (mapcar #'car *default-slots*)))
bindings)))
DEFSKETCH setf instructions
(defun make-window-parameter-setf ()
`(setf ,@(mapcan (lambda (slot)
`((,(intern-accessor (car slot)) instance) ,(car slot)))
*default-slots*)))
(defun make-custom-slots-setf (sketch bindings)
`(setf ,@(mapcan (lambda (binding)
`((slot-value instance ',(car binding)) ,(car binding)))
bindings)))
(defun make-reinitialize-setf ()
`(setf ,@(mapcan (lambda (slot)
`((,(intern-accessor (car slot)) instance)
(,(intern-accessor (car slot)) instance)))
*default-slots*)))
(defun custom-slots (bindings)
(loop
for b in (mapcar #'car bindings)
if (not (member b *default-slots*))
collect b))
DEFSKETCH macro
(defmacro defsketch (sketch-name bindings &body body)
(let ((default-not-overridden
(remove-if (lambda (x) (find x bindings :key #'car))
(mapcar #'car *default-slots*))))
`(progn
(defclass ,sketch-name (sketch)
,(sketch-bindings-to-slots `,sketch-name bindings))
,@(remove-if-not #'identity (make-channel-observers sketch-name bindings))
(defmethod prepare progn ((instance ,sketch-name) &rest initargs &key &allow-other-keys)
(declare (ignorable initargs))
(let* (,@(loop for slot in default-not-overridden
collect `(,slot (slot-value instance ',slot)))
,@(mapcar (lambda (binding)
(destructuring-bind (name value)
(first-two binding)
(list name (if (default-slot-p name)
`(if (getf initargs ,(alexandria:make-keyword name))
(slot-value instance ',name)
,value)
`(or (getf initargs ,(alexandria:make-keyword name)) ,value)))))
(replace-channels-with-values bindings)))
(declare (ignorable ,@(mapcar #'car *default-slots*) ,@(custom-slots bindings)))
,(make-window-parameter-setf)
,(make-custom-slots-setf sketch-name (custom-bindings bindings)))
(setf (env-y-axis-sgn (slot-value instance '%env))
(if (eq (slot-value instance 'y-axis) :down) +1 -1)))
(defmethod draw ((instance ,sketch-name) &key &allow-other-keys)
(let ((*sketch* instance))
(with-accessors ,(mapcar (lambda (x) (list (car x) (intern-accessor (car x))))
*default-slots*) instance
(with-slots ,(mapcar #'car bindings) instance
,@body))))
(make-instances-obsolete ',sketch-name)
(find-class ',sketch-name))))
|
8fb114a11783e74935844d821d2dbb846f6505405da9a1180b2723e7b0cfac9a | Dept24c/vivo | commands.cljc | (ns com.dept24c.vivo.commands
(:require
[com.dept24c.vivo.utils :as u]
[deercreeklabs.async-utils :as au]
[deercreeklabs.capsule.logging :as log]))
(defn throw-bad-path-key [path k]
(let [disp-k (or k "nil")]
(throw (ex-info
(str "Illegal key `" disp-k "` in path `" path "`. Only integers, "
"keywords, symbols, and strings are valid path keys.")
(u/sym-map k path)))))
(defn normalize-neg-k
"Return the normalized key and the associated value or nil if key does not
exist in value."
[k v]
(if (map? v)
[k (v k)]
(let [len (count v)
norm-k (+ len k)]
[norm-k (when (and (pos? len) (nat-int? norm-k) (< norm-k len))
(v norm-k))])))
(defn get-in-state
"Custom get-in fn that checks types and normalizes negative keys.
Returns a map with :norm-path and :val keys."
([state path]
(get-in-state state path nil))
([state path prefixes*]
(let [prefixes (cond
(nil? prefixes*) #{}
(set? prefixes*) prefixes*
:else (set [prefixes*]))
[path-head & path-tail] path]
(when (and (seq prefixes)
(not (prefixes path-head)))
(throw (ex-info (str "Illegal path. Path must start with one of "
prefixes ". Got `" path "`.")
(u/sym-map path prefixes path-head))))
(reduce (fn [{:keys [val] :as acc} k]
(let [[k* val*] (cond
(or (keyword? k) (nat-int? k) (string? k))
[k (when val
(get val k))]
(and (int? k) (neg? k))
(normalize-neg-k k val)
(nil? k)
[nil nil]
:else
(throw-bad-path-key path k))]
(-> acc
(update :norm-path conj k*)
(assoc :val val*))))
{:norm-path (if (seq prefixes)
[path-head]
[])
:val state}
(if (seq prefixes)
path-tail
path)))))
(defmulti eval-cmd (fn [state {:keys [op]} prefix]
op))
(defmethod eval-cmd :set
[state {:keys [path op arg]} prefix]
(let [{:keys [norm-path]} (get-in-state state path prefix)
state-path (if prefix
(rest norm-path)
norm-path)
new-state (if (seq state-path)
(assoc-in state state-path arg)
arg)]
{:state new-state
:update-info {:norm-path norm-path
:op op
:value arg}}))
(defmethod eval-cmd :remove
[state {:keys [path op]} prefix]
(let [parent-path (butlast path)
k (last path)
{:keys [norm-path val]} (get-in-state state parent-path prefix)
[new-parent path-k] (cond
(nil? val)
[nil k]
(map? val)
[(dissoc val k) k]
:else
(let [norm-i (if (nat-int? k)
k
(+ (count val) k))
[h t] (split-at norm-i val)]
(if (nat-int? norm-i)
[(vec (concat h (rest t))) norm-i]
(throw (ex-info "Path index out of range."
(u/sym-map norm-i path
norm-path))))))
state-path (if prefix
(rest norm-path)
norm-path)
new-state (cond
(nil? new-parent)
state
(empty? state-path)
new-parent
:else
(assoc-in state state-path new-parent))]
{:state new-state
:update-info {:norm-path (conj norm-path path-k)
:op op
:value nil}}))
(defn insert* [state path prefix op arg]
(let [parent-path (butlast path)
i (last path)
_ (when-not (int? i)
(throw (ex-info
(str "In " op " update expressions, the last element "
"of the path must be an integer, e.g. [:x :y -1] "
" or [:a :b :c 12]. Got: `" i "`.")
(u/sym-map parent-path i path op arg))))
{:keys [norm-path val]} (get-in-state state parent-path prefix)
_ (when-not (or (sequential? val) (nil? val))
(throw (ex-info (str "Bad path in " op ". Path `" path "` does not "
"point to a sequence. Got: `" val "`.")
(u/sym-map op path val norm-path))))
norm-i (if (nat-int? i)
i
(+ (count val) i))
split-i (if (= :insert-before op)
norm-i
(inc norm-i))
[h t] (split-at split-i val)
new-t (cons arg t)
new-parent (vec (concat h new-t))
state-path (if prefix
(rest norm-path)
norm-path)
new-state (if (empty? state-path)
new-parent
(assoc-in state state-path new-parent))]
{:state new-state
:update-info {:norm-path (conj norm-path split-i)
:op op
:value arg}}))
(defmethod eval-cmd :insert-before
[state {:keys [path op arg]} prefix]
(insert* state path prefix op arg))
(defmethod eval-cmd :insert-after
[state {:keys [path op arg]} prefix]
(insert* state path prefix op arg))
(defn eval-math-cmd [state cmd prefix op-fn]
(let [{:keys [path op arg]} cmd
{:keys [norm-path val]} (get-in-state state path prefix)
_ (when-not (number? val)
(throw (ex-info (str "Can't do math on non-numeric type. "
"Value in state at path `"
path "` is not a number. Got: " val ".")
(u/sym-map path cmd))))
_ (when-not (number? arg)
(throw (ex-info (str "Can't do math on non-numeric type. "
"Arg `" arg "` in update command `"
cmd "` is not a number.")
(u/sym-map path cmd op))))
new-val (op-fn val arg)
state-path (if prefix
(rest norm-path)
norm-path)]
{:state (assoc-in state state-path new-val)
:update-info {:norm-path norm-path
:op op
:value new-val}}))
(defmethod eval-cmd :+
[state cmd prefix]
(eval-math-cmd state cmd prefix +))
(defmethod eval-cmd :-
[state cmd prefix]
(eval-math-cmd state cmd prefix -))
(defmethod eval-cmd :*
[state cmd prefix]
(eval-math-cmd state cmd prefix *))
(defmethod eval-cmd :/
[state cmd prefix]
(eval-math-cmd state cmd prefix /))
(defmethod eval-cmd :mod
[state cmd prefix]
(eval-math-cmd state cmd prefix mod))
| null | https://raw.githubusercontent.com/Dept24c/vivo/89e2533883641a711d9bcbd5c3f54df09b509095/src/com/dept24c/vivo/commands.cljc | clojure | (ns com.dept24c.vivo.commands
(:require
[com.dept24c.vivo.utils :as u]
[deercreeklabs.async-utils :as au]
[deercreeklabs.capsule.logging :as log]))
(defn throw-bad-path-key [path k]
(let [disp-k (or k "nil")]
(throw (ex-info
(str "Illegal key `" disp-k "` in path `" path "`. Only integers, "
"keywords, symbols, and strings are valid path keys.")
(u/sym-map k path)))))
(defn normalize-neg-k
"Return the normalized key and the associated value or nil if key does not
exist in value."
[k v]
(if (map? v)
[k (v k)]
(let [len (count v)
norm-k (+ len k)]
[norm-k (when (and (pos? len) (nat-int? norm-k) (< norm-k len))
(v norm-k))])))
(defn get-in-state
"Custom get-in fn that checks types and normalizes negative keys.
Returns a map with :norm-path and :val keys."
([state path]
(get-in-state state path nil))
([state path prefixes*]
(let [prefixes (cond
(nil? prefixes*) #{}
(set? prefixes*) prefixes*
:else (set [prefixes*]))
[path-head & path-tail] path]
(when (and (seq prefixes)
(not (prefixes path-head)))
(throw (ex-info (str "Illegal path. Path must start with one of "
prefixes ". Got `" path "`.")
(u/sym-map path prefixes path-head))))
(reduce (fn [{:keys [val] :as acc} k]
(let [[k* val*] (cond
(or (keyword? k) (nat-int? k) (string? k))
[k (when val
(get val k))]
(and (int? k) (neg? k))
(normalize-neg-k k val)
(nil? k)
[nil nil]
:else
(throw-bad-path-key path k))]
(-> acc
(update :norm-path conj k*)
(assoc :val val*))))
{:norm-path (if (seq prefixes)
[path-head]
[])
:val state}
(if (seq prefixes)
path-tail
path)))))
(defmulti eval-cmd (fn [state {:keys [op]} prefix]
op))
(defmethod eval-cmd :set
[state {:keys [path op arg]} prefix]
(let [{:keys [norm-path]} (get-in-state state path prefix)
state-path (if prefix
(rest norm-path)
norm-path)
new-state (if (seq state-path)
(assoc-in state state-path arg)
arg)]
{:state new-state
:update-info {:norm-path norm-path
:op op
:value arg}}))
(defmethod eval-cmd :remove
[state {:keys [path op]} prefix]
(let [parent-path (butlast path)
k (last path)
{:keys [norm-path val]} (get-in-state state parent-path prefix)
[new-parent path-k] (cond
(nil? val)
[nil k]
(map? val)
[(dissoc val k) k]
:else
(let [norm-i (if (nat-int? k)
k
(+ (count val) k))
[h t] (split-at norm-i val)]
(if (nat-int? norm-i)
[(vec (concat h (rest t))) norm-i]
(throw (ex-info "Path index out of range."
(u/sym-map norm-i path
norm-path))))))
state-path (if prefix
(rest norm-path)
norm-path)
new-state (cond
(nil? new-parent)
state
(empty? state-path)
new-parent
:else
(assoc-in state state-path new-parent))]
{:state new-state
:update-info {:norm-path (conj norm-path path-k)
:op op
:value nil}}))
(defn insert* [state path prefix op arg]
(let [parent-path (butlast path)
i (last path)
_ (when-not (int? i)
(throw (ex-info
(str "In " op " update expressions, the last element "
"of the path must be an integer, e.g. [:x :y -1] "
" or [:a :b :c 12]. Got: `" i "`.")
(u/sym-map parent-path i path op arg))))
{:keys [norm-path val]} (get-in-state state parent-path prefix)
_ (when-not (or (sequential? val) (nil? val))
(throw (ex-info (str "Bad path in " op ". Path `" path "` does not "
"point to a sequence. Got: `" val "`.")
(u/sym-map op path val norm-path))))
norm-i (if (nat-int? i)
i
(+ (count val) i))
split-i (if (= :insert-before op)
norm-i
(inc norm-i))
[h t] (split-at split-i val)
new-t (cons arg t)
new-parent (vec (concat h new-t))
state-path (if prefix
(rest norm-path)
norm-path)
new-state (if (empty? state-path)
new-parent
(assoc-in state state-path new-parent))]
{:state new-state
:update-info {:norm-path (conj norm-path split-i)
:op op
:value arg}}))
(defmethod eval-cmd :insert-before
[state {:keys [path op arg]} prefix]
(insert* state path prefix op arg))
(defmethod eval-cmd :insert-after
[state {:keys [path op arg]} prefix]
(insert* state path prefix op arg))
(defn eval-math-cmd [state cmd prefix op-fn]
(let [{:keys [path op arg]} cmd
{:keys [norm-path val]} (get-in-state state path prefix)
_ (when-not (number? val)
(throw (ex-info (str "Can't do math on non-numeric type. "
"Value in state at path `"
path "` is not a number. Got: " val ".")
(u/sym-map path cmd))))
_ (when-not (number? arg)
(throw (ex-info (str "Can't do math on non-numeric type. "
"Arg `" arg "` in update command `"
cmd "` is not a number.")
(u/sym-map path cmd op))))
new-val (op-fn val arg)
state-path (if prefix
(rest norm-path)
norm-path)]
{:state (assoc-in state state-path new-val)
:update-info {:norm-path norm-path
:op op
:value new-val}}))
(defmethod eval-cmd :+
[state cmd prefix]
(eval-math-cmd state cmd prefix +))
(defmethod eval-cmd :-
[state cmd prefix]
(eval-math-cmd state cmd prefix -))
(defmethod eval-cmd :*
[state cmd prefix]
(eval-math-cmd state cmd prefix *))
(defmethod eval-cmd :/
[state cmd prefix]
(eval-math-cmd state cmd prefix /))
(defmethod eval-cmd :mod
[state cmd prefix]
(eval-math-cmd state cmd prefix mod))
| |
6c5c3723fb9d7435842f5352ce93ef49b93fce8d2a6cc64b86632b8bc86dd20e | rtoy/cmucl | clxcom.lisp | ;;; -*- Package: USER -*-
;;;
;;; **********************************************************************
;;;
(ext:file-comment
"$Header: src/tools/clxcom.lisp $")
;;;
;;; **********************************************************************
;;;
(in-package "CL-USER")
#+bootstrap
(unless (find-package "OLD-XLIB")
(when (find-package "XLIB")
(rename-package (find-package "XLIB") "OLD-XLIB"))
(make-package "XLIB" :use '("COMMON-LISP")))
#+(and (not pcl) (not no-pcl-clx))
(progn
(load "target:pcl/pclload")
#+gencgc (gc :full t)
#-gencgc (ext:purify))
(pushnew :clx-ansi-common-lisp *features*)
I ( ) think we need this so the condition accessors are defined .
setup.lisp sets this to NIL , and the Pierre Mai 's build scripts
;; load setup.lisp before clxcom.lisp.
#+pcl
(setf conditions::*make-condition-accessor-methods* t)
(with-compiler-log-file
("target:compile-clx.log"
:optimize
'(optimize (debug #-small 2 #+small .5)
(speed 2) (inhibit-warnings 2)
(safety #-small 1 #+small 0))
:optimize-interface
'(optimize-interface (debug .5))
:context-declarations
'(((:and :external :global)
(declare (optimize-interface (safety 2) (debug 1))))
((:and :external :macro)
(declare (optimize (safety 2))))
(:macro (declare (optimize (speed 0))))))
(let ((c::*suppress-values-declaration* t))
(comf "target:clx/package" :load t)
; (comf "target:clx/defsystem" :load t)
(comf "target:clx/depdefs" :load t)
(comf "target:clx/clx" :load t)
(comf "target:clx/dependent" :load t)
(comf "target:clx/macros") ; these are just macros
(load "target:clx/macros")
(comf "target:clx/bufmac") ; these are just macros
(load "target:clx/bufmac")
(comf "target:clx/buffer" :load t)
(comf "target:clx/display" :load t)
(comf "target:clx/gcontext" :load t)
(comf "target:clx/input" :load t)
(comf "target:clx/requests" :load t)
(comf "target:clx/fonts" :load t)
(comf "target:clx/graphics" :load t)
(comf "target:clx/text" :load t)
(comf "target:clx/attributes" :load t)
(comf "target:clx/translate" :load t)
(comf "target:clx/keysyms" :load t)
(comf "target:clx/manager" :load t)
(comf "target:clx/image" :load t)
(comf "target:clx/resource" :load t)
(comf "target:clx/extensions/shape" :load t)
(comf "target:clx/extensions/big-requests" :load t)
(comf "target:clx/extensions/xvidmode" :load t)
(comf "target:clx/extensions/xrender" :load t)
(comf "target:clx/extensions/glx" :load t)
(comf "target:clx/extensions/gl" :load t)
(comf "target:clx/extensions/dpms" :load t)
(comf "target:clx/extensions/xtest" :load t)
(comf "target:clx/extensions/screensaver" :load t)
(comf "target:clx/extensions/randr" :load t)
(comf "target:clx/extensions/xinerama" :load t)
(comf "target:clx/extensions/dbe" :load t)
(comf "target:clx/extensions/xc-misc" :load t)
(comf "target:clx/extensions/dri2" :load t)
(comf "target:clx/extensions/composite" :load t)
)
(comf "target:code/clx-ext")
(comf "target:hemlock/charmacs" :load t)
(comf "target:hemlock/key-event" :load t)
(comf "target:hemlock/keysym-defs" :load t)
(comf "target:clx/provide")
#+nil
(comf "target:code/inspect"))
(cat-if-anything-changed
"target:clx/clx-library"
"target:clx/package"
"target:clx/depdefs"
"target:clx/clx"
"target:clx/dependent"
"target:clx/macros"
"target:clx/bufmac"
"target:clx/buffer"
"target:clx/display"
"target:clx/gcontext"
"target:clx/input"
"target:clx/requests"
"target:clx/fonts"
"target:clx/graphics"
"target:clx/text"
"target:clx/attributes"
"target:clx/translate"
"target:clx/keysyms"
"target:clx/manager"
"target:clx/image"
"target:clx/resource"
"target:clx/extensions/shape"
"target:clx/extensions/big-requests"
"target:clx/extensions/xvidmode"
"target:clx/extensions/xrender"
"target:clx/extensions/glx"
"target:clx/extensions/gl"
"target:clx/extensions/dpms"
"target:clx/extensions/screensaver"
"target:clx/extensions/xinerama"
"target:clx/extensions/xtest"
"target:code/clx-ext"
"target:hemlock/charmacs"
"target:hemlock/key-event"
"target:hemlock/keysym-defs"
"target:clx/provide")
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/tools/clxcom.lisp | lisp | -*- Package: USER -*-
**********************************************************************
**********************************************************************
load setup.lisp before clxcom.lisp.
(comf "target:clx/defsystem" :load t)
these are just macros
these are just macros | (ext:file-comment
"$Header: src/tools/clxcom.lisp $")
(in-package "CL-USER")
#+bootstrap
(unless (find-package "OLD-XLIB")
(when (find-package "XLIB")
(rename-package (find-package "XLIB") "OLD-XLIB"))
(make-package "XLIB" :use '("COMMON-LISP")))
#+(and (not pcl) (not no-pcl-clx))
(progn
(load "target:pcl/pclload")
#+gencgc (gc :full t)
#-gencgc (ext:purify))
(pushnew :clx-ansi-common-lisp *features*)
I ( ) think we need this so the condition accessors are defined .
setup.lisp sets this to NIL , and the Pierre Mai 's build scripts
#+pcl
(setf conditions::*make-condition-accessor-methods* t)
(with-compiler-log-file
("target:compile-clx.log"
:optimize
'(optimize (debug #-small 2 #+small .5)
(speed 2) (inhibit-warnings 2)
(safety #-small 1 #+small 0))
:optimize-interface
'(optimize-interface (debug .5))
:context-declarations
'(((:and :external :global)
(declare (optimize-interface (safety 2) (debug 1))))
((:and :external :macro)
(declare (optimize (safety 2))))
(:macro (declare (optimize (speed 0))))))
(let ((c::*suppress-values-declaration* t))
(comf "target:clx/package" :load t)
(comf "target:clx/depdefs" :load t)
(comf "target:clx/clx" :load t)
(comf "target:clx/dependent" :load t)
(load "target:clx/macros")
(load "target:clx/bufmac")
(comf "target:clx/buffer" :load t)
(comf "target:clx/display" :load t)
(comf "target:clx/gcontext" :load t)
(comf "target:clx/input" :load t)
(comf "target:clx/requests" :load t)
(comf "target:clx/fonts" :load t)
(comf "target:clx/graphics" :load t)
(comf "target:clx/text" :load t)
(comf "target:clx/attributes" :load t)
(comf "target:clx/translate" :load t)
(comf "target:clx/keysyms" :load t)
(comf "target:clx/manager" :load t)
(comf "target:clx/image" :load t)
(comf "target:clx/resource" :load t)
(comf "target:clx/extensions/shape" :load t)
(comf "target:clx/extensions/big-requests" :load t)
(comf "target:clx/extensions/xvidmode" :load t)
(comf "target:clx/extensions/xrender" :load t)
(comf "target:clx/extensions/glx" :load t)
(comf "target:clx/extensions/gl" :load t)
(comf "target:clx/extensions/dpms" :load t)
(comf "target:clx/extensions/xtest" :load t)
(comf "target:clx/extensions/screensaver" :load t)
(comf "target:clx/extensions/randr" :load t)
(comf "target:clx/extensions/xinerama" :load t)
(comf "target:clx/extensions/dbe" :load t)
(comf "target:clx/extensions/xc-misc" :load t)
(comf "target:clx/extensions/dri2" :load t)
(comf "target:clx/extensions/composite" :load t)
)
(comf "target:code/clx-ext")
(comf "target:hemlock/charmacs" :load t)
(comf "target:hemlock/key-event" :load t)
(comf "target:hemlock/keysym-defs" :load t)
(comf "target:clx/provide")
#+nil
(comf "target:code/inspect"))
(cat-if-anything-changed
"target:clx/clx-library"
"target:clx/package"
"target:clx/depdefs"
"target:clx/clx"
"target:clx/dependent"
"target:clx/macros"
"target:clx/bufmac"
"target:clx/buffer"
"target:clx/display"
"target:clx/gcontext"
"target:clx/input"
"target:clx/requests"
"target:clx/fonts"
"target:clx/graphics"
"target:clx/text"
"target:clx/attributes"
"target:clx/translate"
"target:clx/keysyms"
"target:clx/manager"
"target:clx/image"
"target:clx/resource"
"target:clx/extensions/shape"
"target:clx/extensions/big-requests"
"target:clx/extensions/xvidmode"
"target:clx/extensions/xrender"
"target:clx/extensions/glx"
"target:clx/extensions/gl"
"target:clx/extensions/dpms"
"target:clx/extensions/screensaver"
"target:clx/extensions/xinerama"
"target:clx/extensions/xtest"
"target:code/clx-ext"
"target:hemlock/charmacs"
"target:hemlock/key-event"
"target:hemlock/keysym-defs"
"target:clx/provide")
|
ac1e4c68f9bb46435b71775c0f4d41d3edf9022d3f52b0f29ac36341ddea0a4b | cdfa/frugel | Model.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
module Frugel.Web.Model
( module Frugel.Web.Model
, Model(Model)
, EvaluationStatus(..)
, EvaluationOutput(EvaluationOutput)
) where
import qualified Data.MultiSet as MultiSet
import qualified Frugel
import Frugel.Web.Internal.Model
import Optics.Extra.Scout
import Scout hiding ( Evaluated, EvaluationStatus )
initialModel :: Program -> Model
initialModel p
= Model { editableDataVersion = 0
, fuelLimit = 20
, limitEvaluationByDefault = False
, selectedNodeEvaluationIndex = 0
, errors = []
, showHelp = True
, evaluationStatus = PartiallyEvaluated
, mainExpressionRenderDepth = 20
, selectedNodeValueRenderDepth = 10
, contextRenderDepth = 5
, definitionsViewCollapsed = True
, evaluationOutput
= EvaluationOutput { evaluated = program'
evaluationPlaceHolder
Nothing
, focusedNodeEvaluations = mempty
}
, ..
}
where
Frugel.Model{..}
= Frugel.prettyPrint -- pretty print twice, because program may not be fully parsed (and then it's only parsed but not pretty-printed)
. Frugel.prettyPrint
$ Frugel.initialModel p
setWithFrugelModel :: Frugel.Model Program -> Model -> Model
setWithFrugelModel Frugel.Model{..}
Model{program = _, cursorOffset = _, errors = _, ..}
= Model { editableDataVersion = editableDataVersion + 1
, program
, cursorOffset
, errors = map fromFrugelError errors
, ..
}
-- Assumes program terminates
fromFrugelModel :: Model -> Frugel.Model Program -> IO Model
fromFrugelModel = partialFromFrugelModel Infinity
partialFromFrugelModel :: Limit -> Model -> Frugel.Model Program -> IO Model
partialFromFrugelModel fuel
Model{program = _, cursorOffset = _, errors = _, ..}
Frugel.Model{..} = do
(evaluated, (evalErrors, focusedNodeEvaluations)) <- runEval
(Just cursorOffset)
limitEvaluationByDefault
fuel
evalProgram
program
pure
$ Model { editableDataVersion = editableDataVersion + 1
, errors = map fromFrugelError errors
++ map (uncurry $ flip EvaluationError)
(MultiSet.toOccurList evalErrors)
, evaluationStatus = if limitEvaluationByDefault
then Evaluated
else case fuel of
Only _ -> PartiallyEvaluated
Infinity -> Evaluated
, evaluationOutput = EvaluationOutput { .. }
, ..
}
setFrugelErrors :: [Frugel.Error Program] -> Model -> Model
setFrugelErrors newErrors
= chain [ #editableDataVersion +~ 1, #errors %~ \oldErrors ->
rights (map matchFrugelError oldErrors) ++ map fromFrugelError newErrors ]
toFrugelModel :: Model -> Frugel.Model Program
toFrugelModel Model{..}
= Frugel.Model { errors = toListOf (folded % _FrugelError) errors, .. }
contextInView :: Model -> Bool
contextInView model = definitionsInView model || variablesInView model
definitionsInView :: Model -> Bool
definitionsInView model
= not (view #definitionsViewCollapsed model)
&& has (#selectedNodeEvaluation % #definitions % folded) model
variablesInView :: Model -> Bool
variablesInView = has $ #selectedNodeEvaluation % #variables % folded
-- force errors to force full evaluation
forceMainExpression :: Model -> Model
forceMainExpression model@Model{..} = seq (length errors) model
forceSelectedNodeValue :: Model -> Model
forceSelectedNodeValue = forceSelectedNodeField SelectedNodeValue #value
forceSelectedNodeContext :: Model -> Model
forceSelectedNodeContext model
= applyWhen (not $ view #definitionsViewCollapsed model)
forceSelectedNodeDefinitions
$ forceSelectedNodeVariables model
forceSelectedNodeDefinitions :: Model -> Model
forceSelectedNodeDefinitions
= forceSelectedNodeField SelectedNodeContext
$ #definitions % folded % to ExprNode
forceSelectedNodeVariables :: Model -> Model
forceSelectedNodeVariables
= forceSelectedNodeField SelectedNodeContext
$ #variables % folded % to ExprNode
forceSelectedNodeField :: Is k A_Fold
=> RenderDepthField
-> Optic' k is FocusedNodeEvaluation Node
-> Model
-> Model
forceSelectedNodeField field fieldNodes model
= seq (lengthOf (#selectedNodeEvaluation
% castOptic @A_Fold fieldNodes
% to (truncate $ view (renderDepthFieldLens field) model)
% allEvaluatedChildren)
model)
model
hideMainExpression :: Model -> Model
hideMainExpression
= hideEvaluationOutputField $ #evaluationOutput % #evaluated % #expr
hideSelectedNodeEvaluation :: Model -> Model
hideSelectedNodeEvaluation = hideSelectedNodeValue . hideSelectedNodeContext
hideSelectedNodeValue :: Model -> Model
hideSelectedNodeValue
= hideEvaluationOutputField $ #selectedNodeEvaluation % #value % _ExprNode
hideSelectedNodeContext :: Model -> Model
hideSelectedNodeContext
= hideSelectedNodeDefinitions . hideSelectedNodeVariables
hideSelectedNodeDefinitions :: Model -> Model
hideSelectedNodeDefinitions
= hideEvaluationOutputField
$ #selectedNodeEvaluation % #definitions % traversed
hideSelectedNodeVariables :: Model -> Model
hideSelectedNodeVariables
= hideEvaluationOutputField
$ #selectedNodeEvaluation % #variables % traversed
hideEvaluationOutputField
:: Is k A_Traversal => Optic' k is Model Expr -> Model -> Model
hideEvaluationOutputField (castOptic @A_Traversal -> fieldNodes) model
= model
& fieldNodes .~ evaluationPlaceHolder
& #evaluationStatus
.~ if has fieldNodes model then PartiallyEvaluated else Evaluated
evaluationPlaceHolder :: Expr
evaluationPlaceHolder = exprCstrSite' . toCstrSite . one $ Left "Evaluating..."
data RenderDepthField
= MainExpression | SelectedNodeValue | SelectedNodeContext
deriving ( Show, Eq )
renderDepthFieldLens :: RenderDepthField -> Lens' Model Int
renderDepthFieldLens MainExpression = #mainExpressionRenderDepth
renderDepthFieldLens SelectedNodeValue = #selectedNodeValueRenderDepth
renderDepthFieldLens SelectedNodeContext = #contextRenderDepth
forceFieldValues :: RenderDepthField -> Model -> Model
forceFieldValues MainExpression = forceMainExpression
forceFieldValues SelectedNodeValue = forceSelectedNodeValue
forceFieldValues SelectedNodeContext = forceSelectedNodeContext
hideFieldValues :: RenderDepthField -> Model -> Model
hideFieldValues MainExpression = hideMainExpression
hideFieldValues SelectedNodeValue = hideSelectedNodeValue
hideFieldValues SelectedNodeContext = hideSelectedNodeContext
| null | https://raw.githubusercontent.com/cdfa/frugel/9c59f2281c06bfa5e13bd575866d165dbc0ce411/app/Frugel/Web/Model.hs | haskell | pretty print twice, because program may not be fully parsed (and then it's only parsed but not pretty-printed)
Assumes program terminates
force errors to force full evaluation | # LANGUAGE FlexibleContexts #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
# LANGUAGE ViewPatterns #
module Frugel.Web.Model
( module Frugel.Web.Model
, Model(Model)
, EvaluationStatus(..)
, EvaluationOutput(EvaluationOutput)
) where
import qualified Data.MultiSet as MultiSet
import qualified Frugel
import Frugel.Web.Internal.Model
import Optics.Extra.Scout
import Scout hiding ( Evaluated, EvaluationStatus )
initialModel :: Program -> Model
initialModel p
= Model { editableDataVersion = 0
, fuelLimit = 20
, limitEvaluationByDefault = False
, selectedNodeEvaluationIndex = 0
, errors = []
, showHelp = True
, evaluationStatus = PartiallyEvaluated
, mainExpressionRenderDepth = 20
, selectedNodeValueRenderDepth = 10
, contextRenderDepth = 5
, definitionsViewCollapsed = True
, evaluationOutput
= EvaluationOutput { evaluated = program'
evaluationPlaceHolder
Nothing
, focusedNodeEvaluations = mempty
}
, ..
}
where
Frugel.Model{..}
. Frugel.prettyPrint
$ Frugel.initialModel p
setWithFrugelModel :: Frugel.Model Program -> Model -> Model
setWithFrugelModel Frugel.Model{..}
Model{program = _, cursorOffset = _, errors = _, ..}
= Model { editableDataVersion = editableDataVersion + 1
, program
, cursorOffset
, errors = map fromFrugelError errors
, ..
}
fromFrugelModel :: Model -> Frugel.Model Program -> IO Model
fromFrugelModel = partialFromFrugelModel Infinity
partialFromFrugelModel :: Limit -> Model -> Frugel.Model Program -> IO Model
partialFromFrugelModel fuel
Model{program = _, cursorOffset = _, errors = _, ..}
Frugel.Model{..} = do
(evaluated, (evalErrors, focusedNodeEvaluations)) <- runEval
(Just cursorOffset)
limitEvaluationByDefault
fuel
evalProgram
program
pure
$ Model { editableDataVersion = editableDataVersion + 1
, errors = map fromFrugelError errors
++ map (uncurry $ flip EvaluationError)
(MultiSet.toOccurList evalErrors)
, evaluationStatus = if limitEvaluationByDefault
then Evaluated
else case fuel of
Only _ -> PartiallyEvaluated
Infinity -> Evaluated
, evaluationOutput = EvaluationOutput { .. }
, ..
}
setFrugelErrors :: [Frugel.Error Program] -> Model -> Model
setFrugelErrors newErrors
= chain [ #editableDataVersion +~ 1, #errors %~ \oldErrors ->
rights (map matchFrugelError oldErrors) ++ map fromFrugelError newErrors ]
toFrugelModel :: Model -> Frugel.Model Program
toFrugelModel Model{..}
= Frugel.Model { errors = toListOf (folded % _FrugelError) errors, .. }
contextInView :: Model -> Bool
contextInView model = definitionsInView model || variablesInView model
definitionsInView :: Model -> Bool
definitionsInView model
= not (view #definitionsViewCollapsed model)
&& has (#selectedNodeEvaluation % #definitions % folded) model
variablesInView :: Model -> Bool
variablesInView = has $ #selectedNodeEvaluation % #variables % folded
forceMainExpression :: Model -> Model
forceMainExpression model@Model{..} = seq (length errors) model
forceSelectedNodeValue :: Model -> Model
forceSelectedNodeValue = forceSelectedNodeField SelectedNodeValue #value
forceSelectedNodeContext :: Model -> Model
forceSelectedNodeContext model
= applyWhen (not $ view #definitionsViewCollapsed model)
forceSelectedNodeDefinitions
$ forceSelectedNodeVariables model
forceSelectedNodeDefinitions :: Model -> Model
forceSelectedNodeDefinitions
= forceSelectedNodeField SelectedNodeContext
$ #definitions % folded % to ExprNode
forceSelectedNodeVariables :: Model -> Model
forceSelectedNodeVariables
= forceSelectedNodeField SelectedNodeContext
$ #variables % folded % to ExprNode
forceSelectedNodeField :: Is k A_Fold
=> RenderDepthField
-> Optic' k is FocusedNodeEvaluation Node
-> Model
-> Model
forceSelectedNodeField field fieldNodes model
= seq (lengthOf (#selectedNodeEvaluation
% castOptic @A_Fold fieldNodes
% to (truncate $ view (renderDepthFieldLens field) model)
% allEvaluatedChildren)
model)
model
hideMainExpression :: Model -> Model
hideMainExpression
= hideEvaluationOutputField $ #evaluationOutput % #evaluated % #expr
hideSelectedNodeEvaluation :: Model -> Model
hideSelectedNodeEvaluation = hideSelectedNodeValue . hideSelectedNodeContext
hideSelectedNodeValue :: Model -> Model
hideSelectedNodeValue
= hideEvaluationOutputField $ #selectedNodeEvaluation % #value % _ExprNode
hideSelectedNodeContext :: Model -> Model
hideSelectedNodeContext
= hideSelectedNodeDefinitions . hideSelectedNodeVariables
hideSelectedNodeDefinitions :: Model -> Model
hideSelectedNodeDefinitions
= hideEvaluationOutputField
$ #selectedNodeEvaluation % #definitions % traversed
hideSelectedNodeVariables :: Model -> Model
hideSelectedNodeVariables
= hideEvaluationOutputField
$ #selectedNodeEvaluation % #variables % traversed
hideEvaluationOutputField
:: Is k A_Traversal => Optic' k is Model Expr -> Model -> Model
hideEvaluationOutputField (castOptic @A_Traversal -> fieldNodes) model
= model
& fieldNodes .~ evaluationPlaceHolder
& #evaluationStatus
.~ if has fieldNodes model then PartiallyEvaluated else Evaluated
evaluationPlaceHolder :: Expr
evaluationPlaceHolder = exprCstrSite' . toCstrSite . one $ Left "Evaluating..."
data RenderDepthField
= MainExpression | SelectedNodeValue | SelectedNodeContext
deriving ( Show, Eq )
renderDepthFieldLens :: RenderDepthField -> Lens' Model Int
renderDepthFieldLens MainExpression = #mainExpressionRenderDepth
renderDepthFieldLens SelectedNodeValue = #selectedNodeValueRenderDepth
renderDepthFieldLens SelectedNodeContext = #contextRenderDepth
forceFieldValues :: RenderDepthField -> Model -> Model
forceFieldValues MainExpression = forceMainExpression
forceFieldValues SelectedNodeValue = forceSelectedNodeValue
forceFieldValues SelectedNodeContext = forceSelectedNodeContext
hideFieldValues :: RenderDepthField -> Model -> Model
hideFieldValues MainExpression = hideMainExpression
hideFieldValues SelectedNodeValue = hideSelectedNodeValue
hideFieldValues SelectedNodeContext = hideSelectedNodeContext
|
156b81ed07522966cc977c2393c95910784dc05097aa7fdf53e80e18dc91065b | ghilesZ/picasso | hello.ml | open Picasso
open Colors
open Apronext
let env = Environmentext.make_s [||] [|"x1"; "x2"; "x3"; "x4"|]
let gens =
[ Generatorext.of_float_point env [120.; 0.; 100.; 88.]
; Generatorext.of_float_point env [105.; 100.; 150.; 55.]
; Generatorext.of_float_point env [150.; 200.; 220.; 11.]
; Generatorext.of_float_point env [200.; 0.; 250.; 55.] ]
let polyhedron = Apol.of_generator_list gens |> Drawable.of_pol
let octagon = Aoct.of_generator_list gens |> Drawable.of_oct
let box = Abox.of_generator_list gens |> Drawable.of_box
let _ =
let r =
Rendering.create ~abciss:"x1" ~ordinate:"x2" ~title:"Test" 800. 800.
in
let r =
Rendering.add_l r [(blue, polyhedron); (red, octagon); (green, box)]
in
to_svg ~filename:"hello.svg" r ;
to_latex ~filename:"hello.tex" ~tikz_only:false r ;
let r3 = Rendering3d.create ~abciss:"x1" ~ordinate:"x2" ~height:"x3" () in
let r3 = Rendering3d.add_l r3 [(blue, polyhedron)] in
to_obj ~filename:"hello.obj" r3 ;
show r
| null | https://raw.githubusercontent.com/ghilesZ/picasso/e3f6e32d79552157be3f7853a82e2afd8d90c266/examples/hello.ml | ocaml | open Picasso
open Colors
open Apronext
let env = Environmentext.make_s [||] [|"x1"; "x2"; "x3"; "x4"|]
let gens =
[ Generatorext.of_float_point env [120.; 0.; 100.; 88.]
; Generatorext.of_float_point env [105.; 100.; 150.; 55.]
; Generatorext.of_float_point env [150.; 200.; 220.; 11.]
; Generatorext.of_float_point env [200.; 0.; 250.; 55.] ]
let polyhedron = Apol.of_generator_list gens |> Drawable.of_pol
let octagon = Aoct.of_generator_list gens |> Drawable.of_oct
let box = Abox.of_generator_list gens |> Drawable.of_box
let _ =
let r =
Rendering.create ~abciss:"x1" ~ordinate:"x2" ~title:"Test" 800. 800.
in
let r =
Rendering.add_l r [(blue, polyhedron); (red, octagon); (green, box)]
in
to_svg ~filename:"hello.svg" r ;
to_latex ~filename:"hello.tex" ~tikz_only:false r ;
let r3 = Rendering3d.create ~abciss:"x1" ~ordinate:"x2" ~height:"x3" () in
let r3 = Rendering3d.add_l r3 [(blue, polyhedron)] in
to_obj ~filename:"hello.obj" r3 ;
show r
| |
fe4d40ebd63ee5df9c0d981bce4310b621e7cfddd55f62d1f6ede778235111de | dgiot/dgiot | dgiot_tdengine_handler.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(dgiot_tdengine_handler).
-author("dgiot").
-behavior(dgiot_rest).
-dgiot_rest(all).
-include_lib("dgiot_tdengine/include/dgiot_tdengine.hrl").
-include_lib("dgiot/include/logger.hrl").
%% API
-export([swagger_tdengine/0]).
-export([handle/4]).
%% API描述
%% 支持二种方式导入
%% 示例:
1 . Metadata为map表示的JSON ,
%% dgiot_http_server:bind(<<"/tdengine">>, ?MODULE, [], Metadata)
2 . 从模块的priv / swagger / 下导入
%% dgiot_http_server:bind(<<"/swagger_tdengine.json">>, ?MODULE, [], priv)
swagger_tdengine() ->
[
dgiot_http_server:bind(<<"/swagger_tdengine.json">>, ?MODULE, [], priv)
].
%%%===================================================================
%%% 请求处理
%%% 如果登录, Context 内有 <<"user">>, version
%%%===================================================================
-spec handle(OperationID :: atom(), Args :: map(), Context :: map(), Req :: dgiot_req:req()) ->
{Status :: dgiot_req:http_status(), Body :: map()} |
{Status :: dgiot_req:http_status(), Headers :: map(), Body :: map()} |
{Status :: dgiot_req:http_status(), Headers :: map(), Body :: map(), Req :: dgiot_req:req()}.
handle(OperationID, Args, Context, Req) ->
Headers = #{},
case catch do_request(OperationID, Args, Context, Req) of
{ErrType, Reason} when ErrType == 'EXIT'; ErrType == error ->
?LOG(info, "do request: ~p, ~p, ~p~n", [OperationID, Args, Reason]),
Err = case is_binary(Reason) of
true -> Reason;
false -> list_to_binary(io_lib:format("~p", [Reason]))
end,
{500, Headers, #{<<"error">> => Err}};
ok ->
?LOG(debug, "do request: ~p, ~p ->ok ~n", [OperationID, Args]),
{200, Headers, #{}, Req};
{ok, Res} ->
? LOG(info,"do request : ~p , ~p ->~p ~ n " , [ OperationID , , Res ] ) ,
{200, Headers, Res, Req};
{Status, Res} ->
?LOG(info, "do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
{Status, Headers, Res, Req};
{Status, NewHeaders, Res} ->
?LOG(info, "do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
{Status, maps:merge(Headers, NewHeaders), Res, Req};
{Status, NewHeaders, Res, NewReq} ->
?LOG(debug, "do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
{Status, maps:merge(Headers, NewHeaders), Res, NewReq}
end.
%%%===================================================================
%%% 内部函数 Version:API版本
%%%===================================================================
TDengine 概要 : 获取当前产品下的所有设备数据 描述 : 获取当前产品下的所有设备数据
%% OperationId:get_td_cid_pid
%% 请求:GET /iotapi/td/prodcut/:productId
do_request(get_product_pid, #{
<<"pid">> := ProductId,
<<"where">> := Where,
<<"keys">> := _Keys
} = Args, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
Fun =
fun(ChannelId) ->
TableName = ?Table(ProductId),
Query = maps:without([<<"pid">>], Args),
case jsx:is_json(Where) of
true ->
case dgiot_tdengine:query_object(ChannelId, TableName, Query#{
<<"db">> => ProductId,
<<"where">> => jsx:decode(Where, [{labels, binary}, return_maps])
}) of
{ok, Data} ->
{ok, Data};
{error, Reason} ->
{400, Reason}
end;
false ->
{400, <<"where is not json">>}
end
end,
dgiot_product_tdengine:do_channel(ProductId, SessionToken, Fun);
TDengine 概要 : 获取当前产品下的所有设备数据 描述 : 获取当前产品下的所有设备数据
%% OperationId:get_td_productid_channelid_addr_productid
%% 请求:GET /iotapi/td/:ProductId/:channelId/:addr/:productId
do_request(get_device_deviceid, #{<<"deviceid">> := DeviceId} = Args, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} -> {error, Error};
{ok, Channel} ->
?LOG(info, "DeviceId ~p", [DeviceId]),
case dgiot_parse:get_object(<<"Device">>, DeviceId) of
{ok, #{<<"objectId">> := DeviceId, <<"product">> := #{<<"objectId">> := ProductId}}} ->
dgiot_product_tdengine:get_product_data(Channel, ProductId, DeviceId, Args);
_ ->
{error, <<"not find device">>}
end
end;
概要 : 描述 :
do_request(get_echart_deviceid, #{<<"deviceid">> := DeviceId, <<"style">> := Style} = Args, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} -> {error, Error};
{ok, Channel} ->
case dgiot_parse:get_object(<<"Device">>, DeviceId) of
{ok, #{<<"objectId">> := DeviceId, <<"product">> := #{<<"objectId">> := ProductId}}} ->
case Style of
<<"amis_table">> ->
dgiot_device_echart:get_data_by_month(Channel, ProductId, DeviceId, Args);
<<"echart_category">> ->
dgiot_device_echart:get_data_by_echart_category(Channel, ProductId, DeviceId, Args);
_ ->
dgiot_device_echart:get_echart_data(Channel, ProductId, DeviceId, Args)
end;
_ ->
{error, <<"not find device">>}
end
end;
概要 : 获取当前设备最新时序数据卡片
do_request(get_devicecard_deviceid, #{<<"deviceid">> := DeviceId} = Args, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} ->
{error, Error};
{ok, Channel} ->
%% ?LOG(info,"DeviceId ~p", [DeviceId]),
case dgiot_parse:get_object(<<"Device">>, DeviceId) of
{ok, #{<<"objectId">> := DeviceId, <<"product">> := #{<<"objectId">> := ProductId}}} ->
dgiot_mqtt:subscribe_route_key([<<"$dg/user/realtimecard/", DeviceId/binary, "/#">>], SessionToken),
dgiot_device_card:get_device_card(Channel, ProductId, DeviceId, Args);
_ ->
{error, <<"not find device">>}
end
end;
TDengine 概要 :
do_request(get_gps_track_deviceid, #{<<"deviceid">> := DeviceId}, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
case DeviceId of
<<"all">> ->
case dgiot_parse:query_object(<<"Device">>, #{}, [{"X-Parse-Session-Token", SessionToken}], [{from, rest}]) of
{ok, #{<<"results">> := Results}} ->
NewResults =
lists:foldl(fun(#{<<"objectId">> := ObjectId, <<"name">> := Name}, Acc) ->
LineList =
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} -> {error, Error};
{ok, Channel} ->
case dgiot_device:lookup(ObjectId) of
{ok, #{<<"productid">> := ProductId}} ->
{ok, #{<<"results">> := Results1}} = dgiot_device_tdengine:get_gps_track(Channel, ProductId, ObjectId),
Results1;
_ ->
[]
end
end,
Acc ++ [#{<<"objectId">> => ObjectId, <<"name">> => Name, <<"lineList">> => LineList}]
end, [], Results),
{ok, #{<<"results">> => NewResults}};
_ ->
{ok, #{<<"results">> => []}}
end;
_ ->
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} -> {error, Error};
{ok, Channel} ->
case dgiot_device:lookup(DeviceId) of
{ok, #{<<"productid">> := ProductId}} ->
dgiot_device_tdengine:get_gps_track(Channel, ProductId, DeviceId);
_ ->
{ok, #{<<"results">> => []}}
end
end
end;
概要 : save_td
do_request(post_save_td, #{<<"productid">> := ProductId, <<"devaddr">> := DevAddr, <<"data">> := Ack} = _Args, _Context, _Req) ->
R = dgiot_task:save_td(ProductId, DevAddr, Ack, #{}),
%% io:format("~s ~p R = ~p.~n", [?FILE, ?LINE, R]),
{ok, #{<<"data">> => R}};
%% 服务器不支持的API接口
do_request(_OperationId, _Args, _Context, _Req) ->
{error, <<"Not Allowed.">>}.
| null | https://raw.githubusercontent.com/dgiot/dgiot/b74f33aa83a36ca07aabf3c2c890905ea324c661/apps/dgiot_device/src/handler/dgiot_tdengine_handler.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.
--------------------------------------------------------------------
API
API描述
支持二种方式导入
示例:
dgiot_http_server:bind(<<"/tdengine">>, ?MODULE, [], Metadata)
dgiot_http_server:bind(<<"/swagger_tdengine.json">>, ?MODULE, [], priv)
===================================================================
请求处理
如果登录, Context 内有 <<"user">>, version
===================================================================
===================================================================
内部函数 Version:API版本
===================================================================
OperationId:get_td_cid_pid
请求:GET /iotapi/td/prodcut/:productId
OperationId:get_td_productid_channelid_addr_productid
请求:GET /iotapi/td/:ProductId/:channelId/:addr/:productId
?LOG(info,"DeviceId ~p", [DeviceId]),
io:format("~s ~p R = ~p.~n", [?FILE, ?LINE, R]),
服务器不支持的API接口 | Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(dgiot_tdengine_handler).
-author("dgiot").
-behavior(dgiot_rest).
-dgiot_rest(all).
-include_lib("dgiot_tdengine/include/dgiot_tdengine.hrl").
-include_lib("dgiot/include/logger.hrl").
-export([swagger_tdengine/0]).
-export([handle/4]).
1 . Metadata为map表示的JSON ,
2 . 从模块的priv / swagger / 下导入
swagger_tdengine() ->
[
dgiot_http_server:bind(<<"/swagger_tdengine.json">>, ?MODULE, [], priv)
].
-spec handle(OperationID :: atom(), Args :: map(), Context :: map(), Req :: dgiot_req:req()) ->
{Status :: dgiot_req:http_status(), Body :: map()} |
{Status :: dgiot_req:http_status(), Headers :: map(), Body :: map()} |
{Status :: dgiot_req:http_status(), Headers :: map(), Body :: map(), Req :: dgiot_req:req()}.
handle(OperationID, Args, Context, Req) ->
Headers = #{},
case catch do_request(OperationID, Args, Context, Req) of
{ErrType, Reason} when ErrType == 'EXIT'; ErrType == error ->
?LOG(info, "do request: ~p, ~p, ~p~n", [OperationID, Args, Reason]),
Err = case is_binary(Reason) of
true -> Reason;
false -> list_to_binary(io_lib:format("~p", [Reason]))
end,
{500, Headers, #{<<"error">> => Err}};
ok ->
?LOG(debug, "do request: ~p, ~p ->ok ~n", [OperationID, Args]),
{200, Headers, #{}, Req};
{ok, Res} ->
? LOG(info,"do request : ~p , ~p ->~p ~ n " , [ OperationID , , Res ] ) ,
{200, Headers, Res, Req};
{Status, Res} ->
?LOG(info, "do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
{Status, Headers, Res, Req};
{Status, NewHeaders, Res} ->
?LOG(info, "do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
{Status, maps:merge(Headers, NewHeaders), Res, Req};
{Status, NewHeaders, Res, NewReq} ->
?LOG(debug, "do request: ~p, ~p ->~p~n", [OperationID, Args, Res]),
{Status, maps:merge(Headers, NewHeaders), Res, NewReq}
end.
TDengine 概要 : 获取当前产品下的所有设备数据 描述 : 获取当前产品下的所有设备数据
do_request(get_product_pid, #{
<<"pid">> := ProductId,
<<"where">> := Where,
<<"keys">> := _Keys
} = Args, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
Fun =
fun(ChannelId) ->
TableName = ?Table(ProductId),
Query = maps:without([<<"pid">>], Args),
case jsx:is_json(Where) of
true ->
case dgiot_tdengine:query_object(ChannelId, TableName, Query#{
<<"db">> => ProductId,
<<"where">> => jsx:decode(Where, [{labels, binary}, return_maps])
}) of
{ok, Data} ->
{ok, Data};
{error, Reason} ->
{400, Reason}
end;
false ->
{400, <<"where is not json">>}
end
end,
dgiot_product_tdengine:do_channel(ProductId, SessionToken, Fun);
TDengine 概要 : 获取当前产品下的所有设备数据 描述 : 获取当前产品下的所有设备数据
do_request(get_device_deviceid, #{<<"deviceid">> := DeviceId} = Args, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} -> {error, Error};
{ok, Channel} ->
?LOG(info, "DeviceId ~p", [DeviceId]),
case dgiot_parse:get_object(<<"Device">>, DeviceId) of
{ok, #{<<"objectId">> := DeviceId, <<"product">> := #{<<"objectId">> := ProductId}}} ->
dgiot_product_tdengine:get_product_data(Channel, ProductId, DeviceId, Args);
_ ->
{error, <<"not find device">>}
end
end;
概要 : 描述 :
do_request(get_echart_deviceid, #{<<"deviceid">> := DeviceId, <<"style">> := Style} = Args, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} -> {error, Error};
{ok, Channel} ->
case dgiot_parse:get_object(<<"Device">>, DeviceId) of
{ok, #{<<"objectId">> := DeviceId, <<"product">> := #{<<"objectId">> := ProductId}}} ->
case Style of
<<"amis_table">> ->
dgiot_device_echart:get_data_by_month(Channel, ProductId, DeviceId, Args);
<<"echart_category">> ->
dgiot_device_echart:get_data_by_echart_category(Channel, ProductId, DeviceId, Args);
_ ->
dgiot_device_echart:get_echart_data(Channel, ProductId, DeviceId, Args)
end;
_ ->
{error, <<"not find device">>}
end
end;
概要 : 获取当前设备最新时序数据卡片
do_request(get_devicecard_deviceid, #{<<"deviceid">> := DeviceId} = Args, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} ->
{error, Error};
{ok, Channel} ->
case dgiot_parse:get_object(<<"Device">>, DeviceId) of
{ok, #{<<"objectId">> := DeviceId, <<"product">> := #{<<"objectId">> := ProductId}}} ->
dgiot_mqtt:subscribe_route_key([<<"$dg/user/realtimecard/", DeviceId/binary, "/#">>], SessionToken),
dgiot_device_card:get_device_card(Channel, ProductId, DeviceId, Args);
_ ->
{error, <<"not find device">>}
end
end;
TDengine 概要 :
do_request(get_gps_track_deviceid, #{<<"deviceid">> := DeviceId}, #{<<"sessionToken">> := SessionToken} = _Context, _Req) ->
case DeviceId of
<<"all">> ->
case dgiot_parse:query_object(<<"Device">>, #{}, [{"X-Parse-Session-Token", SessionToken}], [{from, rest}]) of
{ok, #{<<"results">> := Results}} ->
NewResults =
lists:foldl(fun(#{<<"objectId">> := ObjectId, <<"name">> := Name}, Acc) ->
LineList =
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} -> {error, Error};
{ok, Channel} ->
case dgiot_device:lookup(ObjectId) of
{ok, #{<<"productid">> := ProductId}} ->
{ok, #{<<"results">> := Results1}} = dgiot_device_tdengine:get_gps_track(Channel, ProductId, ObjectId),
Results1;
_ ->
[]
end
end,
Acc ++ [#{<<"objectId">> => ObjectId, <<"name">> => Name, <<"lineList">> => LineList}]
end, [], Results),
{ok, #{<<"results">> => NewResults}};
_ ->
{ok, #{<<"results">> => []}}
end;
_ ->
case dgiot_product_tdengine:get_channel(SessionToken) of
{error, Error} -> {error, Error};
{ok, Channel} ->
case dgiot_device:lookup(DeviceId) of
{ok, #{<<"productid">> := ProductId}} ->
dgiot_device_tdengine:get_gps_track(Channel, ProductId, DeviceId);
_ ->
{ok, #{<<"results">> => []}}
end
end
end;
概要 : save_td
do_request(post_save_td, #{<<"productid">> := ProductId, <<"devaddr">> := DevAddr, <<"data">> := Ack} = _Args, _Context, _Req) ->
R = dgiot_task:save_td(ProductId, DevAddr, Ack, #{}),
{ok, #{<<"data">> => R}};
do_request(_OperationId, _Args, _Context, _Req) ->
{error, <<"Not Allowed.">>}.
|
615b7dc0f888bc65b13c7439dbae1b97e18809ef110b3eb8ee2ec36a5c525341 | haskell-tools/haskell-tools | Mode.hs | -- | Defines different working modes for the daemon. It can work by using a socket connection
-- or channels to communicate with the client. When the daemon is used by CLI, it uses channel if
-- it communicates with an editor plugin it uses the socket connection.
module Language.Haskell.Tools.Daemon.Mode where
import Control.Concurrent.Chan
import qualified Data.Aeson as A ()
import Data.Aeson hiding ((.=))
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.ByteString.Lazy.Char8 (unpack)
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe (Maybe(..), catMaybes)
import Network.Socket hiding (send, sendTo, recv, recvFrom, KeepAlive)
import Network.Socket.ByteString.Lazy (sendAll, recv)
import Language.Haskell.Tools.Daemon.Protocol (ResponseMsg, ClientMessage)
-- | An abstraction over the connection to the client.
data WorkingMode a = WorkingMode { daemonConnect :: Int -> IO a -- TODO: could we generalize this Int parameter nicely?
, daemonDisconnect :: a -> IO ()
, daemonSend :: a -> ResponseMsg -> IO ()
, daemonReceive :: a -> IO [Either String ClientMessage]
}
-- | Connect to the client running in a separate process using socket connection
socketMode :: WorkingMode (Socket,Socket)
socketMode = WorkingMode sockConn sockDisconnect sockSend sockReceive
where
sockConn portNumber = do
sock <- socket AF_INET Stream 0
setSocketOption sock ReuseAddr 1
addr:_ <- getAddrInfo Nothing Nothing (Just $ show portNumber)
bind sock (addrAddress addr)
listen sock 1
(conn, _) <- accept sock
return (sock,conn)
sockDisconnect (sock,conn) = close conn >> close sock
sockSend (_,conn) = sendAll conn . (`BS.snoc` '\n') . encode
sockReceive (_,conn) = do
msg <- recv conn 2048
if not $ BS.null msg -- null on TCP means closed connection
when ( not isSilent ) $ putStrLn $ " message received : " + + show ( unpack msg )
let msgs = BS.split '\n' msg
in return $ catMaybes $ map decodeMsg msgs
else return []
where decodeMsg :: ByteString -> Maybe (Either String ClientMessage)
decodeMsg mess
| BS.null mess = Nothing
| otherwise = case decode mess of
Nothing -> Just $ Left $ "MALFORMED MESSAGE: " ++ unpack mess
Just req -> Just $ Right req
-- | Connect to the client running in the same process using a channel
channelMode :: WorkingMode (Chan ResponseMsg, Chan ClientMessage)
channelMode = WorkingMode chanConn chanDisconnect chanSend chanReceive
where
chanConn _ = (,) <$> newChan <*> newChan
chanDisconnect _ = return ()
chanSend (send,_) resp = writeChan send resp
chanReceive (_,recv) = (:[]) . Right <$> readChan recv
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/daemon/Language/Haskell/Tools/Daemon/Mode.hs | haskell | | Defines different working modes for the daemon. It can work by using a socket connection
or channels to communicate with the client. When the daemon is used by CLI, it uses channel if
it communicates with an editor plugin it uses the socket connection.
| An abstraction over the connection to the client.
TODO: could we generalize this Int parameter nicely?
| Connect to the client running in a separate process using socket connection
null on TCP means closed connection
| Connect to the client running in the same process using a channel | module Language.Haskell.Tools.Daemon.Mode where
import Control.Concurrent.Chan
import qualified Data.Aeson as A ()
import Data.Aeson hiding ((.=))
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.ByteString.Lazy.Char8 (unpack)
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe (Maybe(..), catMaybes)
import Network.Socket hiding (send, sendTo, recv, recvFrom, KeepAlive)
import Network.Socket.ByteString.Lazy (sendAll, recv)
import Language.Haskell.Tools.Daemon.Protocol (ResponseMsg, ClientMessage)
, daemonDisconnect :: a -> IO ()
, daemonSend :: a -> ResponseMsg -> IO ()
, daemonReceive :: a -> IO [Either String ClientMessage]
}
socketMode :: WorkingMode (Socket,Socket)
socketMode = WorkingMode sockConn sockDisconnect sockSend sockReceive
where
sockConn portNumber = do
sock <- socket AF_INET Stream 0
setSocketOption sock ReuseAddr 1
addr:_ <- getAddrInfo Nothing Nothing (Just $ show portNumber)
bind sock (addrAddress addr)
listen sock 1
(conn, _) <- accept sock
return (sock,conn)
sockDisconnect (sock,conn) = close conn >> close sock
sockSend (_,conn) = sendAll conn . (`BS.snoc` '\n') . encode
sockReceive (_,conn) = do
msg <- recv conn 2048
when ( not isSilent ) $ putStrLn $ " message received : " + + show ( unpack msg )
let msgs = BS.split '\n' msg
in return $ catMaybes $ map decodeMsg msgs
else return []
where decodeMsg :: ByteString -> Maybe (Either String ClientMessage)
decodeMsg mess
| BS.null mess = Nothing
| otherwise = case decode mess of
Nothing -> Just $ Left $ "MALFORMED MESSAGE: " ++ unpack mess
Just req -> Just $ Right req
channelMode :: WorkingMode (Chan ResponseMsg, Chan ClientMessage)
channelMode = WorkingMode chanConn chanDisconnect chanSend chanReceive
where
chanConn _ = (,) <$> newChan <*> newChan
chanDisconnect _ = return ()
chanSend (send,_) resp = writeChan send resp
chanReceive (_,recv) = (:[]) . Right <$> readChan recv
|
0b3d21cd7191a8c55c5f5e20ff9dd5f7e549979615458d80f86d5b940cb76c61 | ocaml-flambda/ocaml-jst | pr10338.ml | (* TEST *)
(* exercise push_defaults *)
let s = 42;;
let f ?(s="hello") = function x when (print_endline s; true) -> x;;
let () = f ();;
let f ?(y = assert false) (lazy e) = () in
try f (lazy (print_endline "hello")) with _ -> print_endline "failed";;
type empty = |;;
let f : empty -> int = function _ -> .;;
let f ?y : empty -> int = function _ -> .;;
let f ?(y=1) : empty -> int = function _ -> .;;
module type E = sig exception Ex end;;
let f ((module M) : (module E)) (M.Ex | _) = "42";;
print_endline (f (module struct exception Ex end) Exit);;
(* push_defaults should push past the module pattern *)
let f ?(x = assert false) ((module M) : (module E)) () = 1;;
(* so partial application of the module doesn't raise *)
let partial = f (module struct exception Ex end);;
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/1bb6c797df7c63ddae1fc2e6f403a0ee9896cc8e/testsuite/tests/basic-more/pr10338.ml | ocaml | TEST
exercise push_defaults
push_defaults should push past the module pattern
so partial application of the module doesn't raise |
let s = 42;;
let f ?(s="hello") = function x when (print_endline s; true) -> x;;
let () = f ();;
let f ?(y = assert false) (lazy e) = () in
try f (lazy (print_endline "hello")) with _ -> print_endline "failed";;
type empty = |;;
let f : empty -> int = function _ -> .;;
let f ?y : empty -> int = function _ -> .;;
let f ?(y=1) : empty -> int = function _ -> .;;
module type E = sig exception Ex end;;
let f ((module M) : (module E)) (M.Ex | _) = "42";;
print_endline (f (module struct exception Ex end) Exit);;
let f ?(x = assert false) ((module M) : (module E)) () = 1;;
let partial = f (module struct exception Ex end);;
|
eb30a134c27b18b77cdb219b24136e1209879764f04ea13a9553f7ffd9c4119c | korya/efuns | ebuffer.ml | (***********************************************************************)
(* *)
xlib for
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open Utils
open Efuns
open Text
let create_buf_hook = Local.create_abstr "create_buf_hook"
let modes_alist = Local.create_abstr "modes_alist"
let create_syntax_table () =
let table = Array.create 256 false
in
for i = Char.code 'a' to Char.code 'z' do
table.(i) <- true;
done;
for i = Char.code 'A' to Char.code 'Z' do
table.(i) <- true;
done;
for i = Char.code '0' to Char.code '9' do
table.(i) <- true;
done;
table
let default_syntax_table = create_syntax_table ()
let get_name location filename =
let basename = Filename.basename filename in
let name =
if basename = "" then
(Filename.basename (Filename.dirname filename)) ^ "/"
else
basename
in
let i = ref 0 in
let compute_name () =
if !i = 0 then name else
Printf.sprintf "%s<%d>" name !i
in
try
while true do
let _ = Hashtbl.find location.loc_buffers (compute_name ()) in
incr i
done; assert false
with
Not_found ->
compute_name ()
let new_minor_mode name = {
min_name = name;
min_map = Keymap.create ();
min_hooks = [];
min_vars = Local.vars ()
}
let new_minor_mode name hooks = {
min_name = name;
min_map = Keymap.create ();
min_hooks = hooks;
min_vars = Local.vars ()
}
let new_major_mode name hooks = {
maj_name = name;
maj_map = Keymap.create ();
maj_hooks = hooks;
maj_vars = Local.vars ();
}
let fondamental_mode = new_major_mode "Fondamental" []
let tab_size = ref 9
let create location name filename text local_map =
let name = get_name location name in
let buf =
{
buf_modified = 0;
buf_text = text;
buf_name = name;
buf_filename = filename;
buf_last_saved = version text;
buf_history = [];
buf_charreprs = Array.init 256 (fun i -> String.make 1 (Char.chr i));
buf_map_partial = true;
buf_map = local_map;
buf_sync = false;
buf_mark = None;
buf_point = Text.add_point text;
buf_start = Text.add_point text;
buf_shared = 0;
buf_syntax_table = default_syntax_table;
buf_finalizers = [];
buf_vars = Local.vars ();
buf_location = location;
buf_minor_modes = [];
buf_major_mode = fondamental_mode;
} in
Hashtbl.add location.loc_buffers name buf;
for i=0 to 25 do
let s = String.make 2 '^' in
s.[1] <- Char.chr (97+i);
buf.buf_charreprs.(i) <- s
done;
buf.buf_charreprs.(9) <- String.make !tab_size ' ';
let hooks = try
get_global location create_buf_hook
with Not_found -> []
in
exec_hooks hooks buf;
buf
let kill location buf =
Hashtbl.remove location.loc_buffers buf.buf_name;
begin
match buf.buf_filename with
None -> ()
| Some filename ->
Hashtbl.remove location.loc_files filename
end;
List.iter (fun f -> f () ) buf.buf_finalizers;
Gc.compact ();
buf.buf_shared <- -1
open Options
let save_buffer_hooks = define_option ["save_buffer_hooks"] ""
(list_option string_option)
[ ]
let saved_buffer_hooks = define_option ["saved_buffer_hooks"] ""
(list_option string_option)
["update_time" ]
let rec exec_named_buf_hooks hooks frame =
match hooks with
[] -> ()
| action :: hooks ->
exec_named_buf_hooks hooks frame;
try execute_buffer_action action frame with _ -> ()
let rec exec_named_buf_hooks_with_abort hooks frame =
match hooks with
[] -> ()
| action :: hooks ->
exec_named_buf_hooks_with_abort hooks frame;
execute_buffer_action action frame
let save buf =
exec_named_buf_hooks_with_abort !!saved_buffer_hooks buf;
let filename =
match buf.buf_filename with
None -> raise Not_found
| Some name -> name
in
let outc = open_out filename in
Text.save buf.buf_text outc;
close_out outc;
buf.buf_last_saved <- version buf.buf_text;
exec_named_buf_hooks !!saved_buffer_hooks buf
exception Found of buffer
let read location filename local_map =
try
let filename = Utils.normal_name location.loc_dirname filename in
try
Hashtbl.find location.loc_files filename
with
Not_found ->
let text =
try
let inc = open_in filename in
let text = Text.read inc in
close_in inc;
text
with
_ -> Text.create ""
in
let buf = create location filename (Some filename) text local_map in
Hashtbl.add location.loc_files filename buf;
buf
with
Found buf -> buf
let default location name =
try
Hashtbl.find location.loc_buffers name
with
Not_found ->
let str =
if name = "*help*" then
"Welcome to Efuns, a small demo editor written in Ocaml.
Version is " ^ Version.efuns_version ^"
built by "^ Version.builder ^ " " ^ Version.date ^ "
with
Efuns installation directory : " ^ Version.efuns_lib ^ "
Ocaml installation directory : " ^ Version.ocamllib ^ "
Fabrice Le Fessant
PARA/SOR Project
INRIA Rocquencourt
Help for Key Bindings: C-h K
See changes in "^ Version.efuns_lib ^"/Changes
"
else ""
in
create location name None (Text.create str) (Keymap.create ())
let compute_representation buf n =
Text.compute_representation buf.buf_text buf.buf_charreprs n
exception BufferAlreadyOpened
let change_name location buf filename =
Hashtbl.remove location.loc_buffers buf.buf_name;
(match buf.buf_filename with
None -> ()
| Some filename ->
Hashtbl.remove location.loc_files filename);
let filename =
if Filename.is_relative filename then
Filename.concat location.loc_dirname filename
else
filename
in
if hashtbl_mem location.loc_files filename then
raise BufferAlreadyOpened;
let filename = Utils.normal_name location.loc_dirname filename in
let name = get_name location filename in
Hashtbl.add location.loc_buffers name buf;
Hashtbl.add location.loc_files filename buf;
buf.buf_filename <- Some filename;
buf.buf_name <- name
let set_mark buf point =
let text = buf.buf_text in
buf.buf_modified <- buf.buf_modified + 1;
match buf.buf_mark with
None ->
let mark = dup_point text point in
buf.buf_mark <- Some mark
| Some mark ->
goto_point text mark point
let rec get_mark buf point =
match buf.buf_mark with
None ->
set_mark buf point;
get_mark buf point
| Some mark -> mark
let remove_mark buf =
match buf.buf_mark with
None -> ()
| Some mark ->
buf.buf_mark <- None;
remove_point buf.buf_text mark;
buf.buf_modified <- buf.buf_modified + 1
let modes_old = ref []
let regexp_alist = ref []
let set_major_mode buf mode =
buf.buf_modified <- buf.buf_modified + 1;
buf.buf_major_mode <- mode;
List.iter (fun f ->
try f buf with _ -> ()) mode.maj_hooks
let set_minor_mode buf mode =
buf.buf_minor_modes <- mode :: buf.buf_minor_modes;
buf.buf_modified <- buf.buf_modified + 1;
List.iter (fun f ->
try f buf with _ -> ()) mode.min_hooks
let del_minor_mode buf minor =
buf.buf_minor_modes <-
List.fold_right
(fun mode list ->
if mode == minor then
begin
buf.buf_modified <- buf.buf_modified + 1;
list
end
else (mode :: list)) buf.buf_minor_modes []
let modep buf minor =
List.memq minor buf.buf_minor_modes
let suffix_reg = Str.regexp "\(.*\)<[0-9]+>$"
let set_buffer_mode buf =
let buf_name =
match buf.buf_filename with
None ->
(try
if Str.string_match suffix_reg buf.buf_name 0 then
Str.matched_group 1 buf.buf_name else buf.buf_name
with
_ -> buf.buf_name)
| Some file_name -> file_name
in
let modes_alist = get_var buf modes_alist in
if not (!modes_old == modes_alist) then
begin
regexp_alist :=
List.map
(fun (file_reg, major) ->
Str.regexp file_reg, major) modes_alist;
modes_old := modes_alist;
end;
try
List.iter (fun (regexp, major) ->
if Str.string_match regexp buf_name 0 then
try
set_major_mode buf major;
raise Exit
with
_ -> raise Exit
) !regexp_alist
with
Exit -> ()
let get_binding buf keylist =
let binding = ref Unbound in
try
List.iter (fun minor ->
let b = Keymap.get_binding minor.min_map keylist in
match b with
Prefix map -> binding := b
| Function f -> binding := b; raise Exit
| Unbound -> ()
) buf.buf_minor_modes;
(let b = Keymap.get_binding buf.buf_major_mode.maj_map keylist in
match b with
Prefix map -> binding := b
| Function f -> binding := b; raise Exit
| Unbound -> ());
(let b = Keymap.get_binding buf.buf_map keylist in
match b with
Prefix map -> binding := b;
| Function f -> binding := b; raise Exit
| Unbound -> ());
if buf.buf_map_partial then
(let b = Keymap.get_binding buf.buf_location.loc_map keylist in
match b with
Prefix map -> binding := b;
| Function f -> binding := b; raise Exit
| Unbound -> ());
!binding
with
Exit -> !binding
let message buf m =
let location = buf.buf_location in
let name = "*Messages*" in
try
let buf = Hashtbl.find location.loc_buffers name in
Text.insert_at_end buf.buf_text (m ^ "\n");
with
Not_found ->
let buf = create location name None (Text.create (m^"\n")) (
Keymap.create ())
in ()
let catch format buf f =
try
f ()
with e ->
let location = buf.buf_location in
let name = "*Messages*" in
let m = Printf.sprintf format (Utils.printexn e) in
try
let buf = Hashtbl.find location.loc_buffers name in
Text.insert_at_end buf.buf_text (m ^ "\n");
with
Not_found ->
let buf = create location name None (Text.create (m^"\n")) (
Keymap.create ())
in ()
let _ =
Efuns.add_start_hook
(fun location ->
set_global location create_buf_hook [set_buffer_mode];
set_global location modes_alist []
)
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/efuns/ebuffer.ml | ocaml | *********************************************************************
********************************************************************* | xlib for
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Utils
open Efuns
open Text
let create_buf_hook = Local.create_abstr "create_buf_hook"
let modes_alist = Local.create_abstr "modes_alist"
let create_syntax_table () =
let table = Array.create 256 false
in
for i = Char.code 'a' to Char.code 'z' do
table.(i) <- true;
done;
for i = Char.code 'A' to Char.code 'Z' do
table.(i) <- true;
done;
for i = Char.code '0' to Char.code '9' do
table.(i) <- true;
done;
table
let default_syntax_table = create_syntax_table ()
let get_name location filename =
let basename = Filename.basename filename in
let name =
if basename = "" then
(Filename.basename (Filename.dirname filename)) ^ "/"
else
basename
in
let i = ref 0 in
let compute_name () =
if !i = 0 then name else
Printf.sprintf "%s<%d>" name !i
in
try
while true do
let _ = Hashtbl.find location.loc_buffers (compute_name ()) in
incr i
done; assert false
with
Not_found ->
compute_name ()
let new_minor_mode name = {
min_name = name;
min_map = Keymap.create ();
min_hooks = [];
min_vars = Local.vars ()
}
let new_minor_mode name hooks = {
min_name = name;
min_map = Keymap.create ();
min_hooks = hooks;
min_vars = Local.vars ()
}
let new_major_mode name hooks = {
maj_name = name;
maj_map = Keymap.create ();
maj_hooks = hooks;
maj_vars = Local.vars ();
}
let fondamental_mode = new_major_mode "Fondamental" []
let tab_size = ref 9
let create location name filename text local_map =
let name = get_name location name in
let buf =
{
buf_modified = 0;
buf_text = text;
buf_name = name;
buf_filename = filename;
buf_last_saved = version text;
buf_history = [];
buf_charreprs = Array.init 256 (fun i -> String.make 1 (Char.chr i));
buf_map_partial = true;
buf_map = local_map;
buf_sync = false;
buf_mark = None;
buf_point = Text.add_point text;
buf_start = Text.add_point text;
buf_shared = 0;
buf_syntax_table = default_syntax_table;
buf_finalizers = [];
buf_vars = Local.vars ();
buf_location = location;
buf_minor_modes = [];
buf_major_mode = fondamental_mode;
} in
Hashtbl.add location.loc_buffers name buf;
for i=0 to 25 do
let s = String.make 2 '^' in
s.[1] <- Char.chr (97+i);
buf.buf_charreprs.(i) <- s
done;
buf.buf_charreprs.(9) <- String.make !tab_size ' ';
let hooks = try
get_global location create_buf_hook
with Not_found -> []
in
exec_hooks hooks buf;
buf
let kill location buf =
Hashtbl.remove location.loc_buffers buf.buf_name;
begin
match buf.buf_filename with
None -> ()
| Some filename ->
Hashtbl.remove location.loc_files filename
end;
List.iter (fun f -> f () ) buf.buf_finalizers;
Gc.compact ();
buf.buf_shared <- -1
open Options
let save_buffer_hooks = define_option ["save_buffer_hooks"] ""
(list_option string_option)
[ ]
let saved_buffer_hooks = define_option ["saved_buffer_hooks"] ""
(list_option string_option)
["update_time" ]
let rec exec_named_buf_hooks hooks frame =
match hooks with
[] -> ()
| action :: hooks ->
exec_named_buf_hooks hooks frame;
try execute_buffer_action action frame with _ -> ()
let rec exec_named_buf_hooks_with_abort hooks frame =
match hooks with
[] -> ()
| action :: hooks ->
exec_named_buf_hooks_with_abort hooks frame;
execute_buffer_action action frame
let save buf =
exec_named_buf_hooks_with_abort !!saved_buffer_hooks buf;
let filename =
match buf.buf_filename with
None -> raise Not_found
| Some name -> name
in
let outc = open_out filename in
Text.save buf.buf_text outc;
close_out outc;
buf.buf_last_saved <- version buf.buf_text;
exec_named_buf_hooks !!saved_buffer_hooks buf
exception Found of buffer
let read location filename local_map =
try
let filename = Utils.normal_name location.loc_dirname filename in
try
Hashtbl.find location.loc_files filename
with
Not_found ->
let text =
try
let inc = open_in filename in
let text = Text.read inc in
close_in inc;
text
with
_ -> Text.create ""
in
let buf = create location filename (Some filename) text local_map in
Hashtbl.add location.loc_files filename buf;
buf
with
Found buf -> buf
let default location name =
try
Hashtbl.find location.loc_buffers name
with
Not_found ->
let str =
if name = "*help*" then
"Welcome to Efuns, a small demo editor written in Ocaml.
Version is " ^ Version.efuns_version ^"
built by "^ Version.builder ^ " " ^ Version.date ^ "
with
Efuns installation directory : " ^ Version.efuns_lib ^ "
Ocaml installation directory : " ^ Version.ocamllib ^ "
Fabrice Le Fessant
PARA/SOR Project
INRIA Rocquencourt
Help for Key Bindings: C-h K
See changes in "^ Version.efuns_lib ^"/Changes
"
else ""
in
create location name None (Text.create str) (Keymap.create ())
let compute_representation buf n =
Text.compute_representation buf.buf_text buf.buf_charreprs n
exception BufferAlreadyOpened
let change_name location buf filename =
Hashtbl.remove location.loc_buffers buf.buf_name;
(match buf.buf_filename with
None -> ()
| Some filename ->
Hashtbl.remove location.loc_files filename);
let filename =
if Filename.is_relative filename then
Filename.concat location.loc_dirname filename
else
filename
in
if hashtbl_mem location.loc_files filename then
raise BufferAlreadyOpened;
let filename = Utils.normal_name location.loc_dirname filename in
let name = get_name location filename in
Hashtbl.add location.loc_buffers name buf;
Hashtbl.add location.loc_files filename buf;
buf.buf_filename <- Some filename;
buf.buf_name <- name
let set_mark buf point =
let text = buf.buf_text in
buf.buf_modified <- buf.buf_modified + 1;
match buf.buf_mark with
None ->
let mark = dup_point text point in
buf.buf_mark <- Some mark
| Some mark ->
goto_point text mark point
let rec get_mark buf point =
match buf.buf_mark with
None ->
set_mark buf point;
get_mark buf point
| Some mark -> mark
let remove_mark buf =
match buf.buf_mark with
None -> ()
| Some mark ->
buf.buf_mark <- None;
remove_point buf.buf_text mark;
buf.buf_modified <- buf.buf_modified + 1
let modes_old = ref []
let regexp_alist = ref []
let set_major_mode buf mode =
buf.buf_modified <- buf.buf_modified + 1;
buf.buf_major_mode <- mode;
List.iter (fun f ->
try f buf with _ -> ()) mode.maj_hooks
let set_minor_mode buf mode =
buf.buf_minor_modes <- mode :: buf.buf_minor_modes;
buf.buf_modified <- buf.buf_modified + 1;
List.iter (fun f ->
try f buf with _ -> ()) mode.min_hooks
let del_minor_mode buf minor =
buf.buf_minor_modes <-
List.fold_right
(fun mode list ->
if mode == minor then
begin
buf.buf_modified <- buf.buf_modified + 1;
list
end
else (mode :: list)) buf.buf_minor_modes []
let modep buf minor =
List.memq minor buf.buf_minor_modes
let suffix_reg = Str.regexp "\(.*\)<[0-9]+>$"
let set_buffer_mode buf =
let buf_name =
match buf.buf_filename with
None ->
(try
if Str.string_match suffix_reg buf.buf_name 0 then
Str.matched_group 1 buf.buf_name else buf.buf_name
with
_ -> buf.buf_name)
| Some file_name -> file_name
in
let modes_alist = get_var buf modes_alist in
if not (!modes_old == modes_alist) then
begin
regexp_alist :=
List.map
(fun (file_reg, major) ->
Str.regexp file_reg, major) modes_alist;
modes_old := modes_alist;
end;
try
List.iter (fun (regexp, major) ->
if Str.string_match regexp buf_name 0 then
try
set_major_mode buf major;
raise Exit
with
_ -> raise Exit
) !regexp_alist
with
Exit -> ()
let get_binding buf keylist =
let binding = ref Unbound in
try
List.iter (fun minor ->
let b = Keymap.get_binding minor.min_map keylist in
match b with
Prefix map -> binding := b
| Function f -> binding := b; raise Exit
| Unbound -> ()
) buf.buf_minor_modes;
(let b = Keymap.get_binding buf.buf_major_mode.maj_map keylist in
match b with
Prefix map -> binding := b
| Function f -> binding := b; raise Exit
| Unbound -> ());
(let b = Keymap.get_binding buf.buf_map keylist in
match b with
Prefix map -> binding := b;
| Function f -> binding := b; raise Exit
| Unbound -> ());
if buf.buf_map_partial then
(let b = Keymap.get_binding buf.buf_location.loc_map keylist in
match b with
Prefix map -> binding := b;
| Function f -> binding := b; raise Exit
| Unbound -> ());
!binding
with
Exit -> !binding
let message buf m =
let location = buf.buf_location in
let name = "*Messages*" in
try
let buf = Hashtbl.find location.loc_buffers name in
Text.insert_at_end buf.buf_text (m ^ "\n");
with
Not_found ->
let buf = create location name None (Text.create (m^"\n")) (
Keymap.create ())
in ()
let catch format buf f =
try
f ()
with e ->
let location = buf.buf_location in
let name = "*Messages*" in
let m = Printf.sprintf format (Utils.printexn e) in
try
let buf = Hashtbl.find location.loc_buffers name in
Text.insert_at_end buf.buf_text (m ^ "\n");
with
Not_found ->
let buf = create location name None (Text.create (m^"\n")) (
Keymap.create ())
in ()
let _ =
Efuns.add_start_hook
(fun location ->
set_global location create_buf_hook [set_buffer_mode];
set_global location modes_alist []
)
|
57ac04804f6c2bfc36edce1fb998ef7fdf5721b78836e6f59990594a14230bdf | ublubu/shapes | Double.hs | # LANGUAGE TemplateHaskell #
# LANGUAGE MagicHash #
module Shapes.Linear.Double where
import GHC.Prim
import GHC.Types (Double(..))
import Shapes.Linear.Template
import Shapes.Linear.MatrixTemplate
import Shapes.Linear.ValueInfos (doubleInfo)
$(makeVectorType doubleInfo 2)
$(makeMatrixType doubleInfo (2, 2))
$(defineMatrixMul doubleInfo (2, 2, 2))
$(makeVectorType doubleInfo 6)
$(makeVectorType doubleInfo 3)
$(defineJoinSplit doubleInfo (3, 3))
testV2 :: V2
testV2 = V2 0.0## 1.0##
testV2' :: V2
testV2' = liftV2 (+## 1.0##) testV2
testV2'' :: V2
testV2'' = lift2V2 (+##) testV2 testV2
testDot :: Double
testDot = D# (testV2 `dotV2` testV2')
testM2x2 :: M2x2
testM2x2 = M2x2 0.0## 1.0## 2.0## 3.0##
idM2x2 :: M2x2
idM2x2 = fromListM2x2 [1, 0, 0, 1]
| null | https://raw.githubusercontent.com/ublubu/shapes/fa5d959c17224a851d517826deeae097f1583392/shapes-math/src/Shapes/Linear/Double.hs | haskell | # LANGUAGE TemplateHaskell #
# LANGUAGE MagicHash #
module Shapes.Linear.Double where
import GHC.Prim
import GHC.Types (Double(..))
import Shapes.Linear.Template
import Shapes.Linear.MatrixTemplate
import Shapes.Linear.ValueInfos (doubleInfo)
$(makeVectorType doubleInfo 2)
$(makeMatrixType doubleInfo (2, 2))
$(defineMatrixMul doubleInfo (2, 2, 2))
$(makeVectorType doubleInfo 6)
$(makeVectorType doubleInfo 3)
$(defineJoinSplit doubleInfo (3, 3))
testV2 :: V2
testV2 = V2 0.0## 1.0##
testV2' :: V2
testV2' = liftV2 (+## 1.0##) testV2
testV2'' :: V2
testV2'' = lift2V2 (+##) testV2 testV2
testDot :: Double
testDot = D# (testV2 `dotV2` testV2')
testM2x2 :: M2x2
testM2x2 = M2x2 0.0## 1.0## 2.0## 3.0##
idM2x2 :: M2x2
idM2x2 = fromListM2x2 [1, 0, 0, 1]
| |
e7048545a9602ae04724edf47644d428817d134fc08f460aa326df2284f5c0d1 | K2InformaticsGmbH/egambo | egambo_tictac_win_3_3_3_p.erl | -module(egambo_tictac_win_3_3_3_p).
-export([win/2]).
% generated in egambo_tictac_wip
win(<<P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<P:8, _:16, P:8, _:16, P:8, _/binary>>, P) -> true;
win(<<P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<P:8, _:32, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:8, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:16, P:8, _:16, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:24, P:8, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:16, P:8, _:16, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, P:8, P:8, _/binary>>, P) -> true;
win(_, _) -> false.
| null | https://raw.githubusercontent.com/K2InformaticsGmbH/egambo/e8bdf971f188a2139db52712ab5b9d87b2f11520/src/egambo_tictac_win_3_3_3_p.erl | erlang | generated in egambo_tictac_wip | -module(egambo_tictac_win_3_3_3_p).
-export([win/2]).
win(<<P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<P:8, _:16, P:8, _:16, P:8, _/binary>>, P) -> true;
win(<<P:8, _:24, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<P:8, _:32, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:8, P:8, _:32, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:16, P:8, _:16, P:8, _/binary>>, P) -> true;
win(<<_:8, P:8, _:24, P:8, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, P:8, _:24, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:8, P:8, _:8, P:8, _/binary>>, P) -> true;
win(<<_:16, P:8, _:16, P:8, _:16, P:8, _/binary>>, P) -> true;
win(<<_:24, P:8, P:8, P:8, _/binary>>, P) -> true;
win(<<_:48, P:8, P:8, P:8, _/binary>>, P) -> true;
win(_, _) -> false.
|
0f7941b49409795cef5f7e86abf0cb50622b77acaa163adfcfe508349fdf0995 | GumTreeDiff/cgum | commands.ml |
* Copyright 2014 , INRIA
*
* This file is part of Cgen . Much of it comes from Coccinelle , which is
* also available under the GPLv2 license
*
* Cgen 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 , according to version 2 of the License .
*
* Cgen 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 Cgen . If not , see < / > .
*
* The authors reserve the right to distribute this or future versions of
* Cgen under other licenses .
* Copyright 2014, INRIA
* Julia Lawall
* This file is part of Cgen. Much of it comes from Coccinelle, which is
* also available under the GPLv2 license
*
* Cgen 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, according to version 2 of the License.
*
* Cgen 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 Cgen. If not, see </>.
*
* The authors reserve the right to distribute this or future versions of
* Cgen under other licenses.
*)
# 0 "./commands.ml"
(* configured default commands *)
let ocamlfind_cmd = "ocamlfind"
let ocamlc_cmd = "ocamlc"
let ocamlopt_cmd = "ocamlopt"
let ocamldep_cmd = "ocamldep"
let camlp4_cmd = "camlp4"
let camlp4o_cmd = "camlp4o"
| null | https://raw.githubusercontent.com/GumTreeDiff/cgum/8521aa80fcf4873a19e60ce8c846c886aaefb41b/commons/commands.ml | ocaml | configured default commands |
* Copyright 2014 , INRIA
*
* This file is part of Cgen . Much of it comes from Coccinelle , which is
* also available under the GPLv2 license
*
* Cgen 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 , according to version 2 of the License .
*
* Cgen 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 Cgen . If not , see < / > .
*
* The authors reserve the right to distribute this or future versions of
* Cgen under other licenses .
* Copyright 2014, INRIA
* Julia Lawall
* This file is part of Cgen. Much of it comes from Coccinelle, which is
* also available under the GPLv2 license
*
* Cgen 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, according to version 2 of the License.
*
* Cgen 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 Cgen. If not, see </>.
*
* The authors reserve the right to distribute this or future versions of
* Cgen under other licenses.
*)
# 0 "./commands.ml"
let ocamlfind_cmd = "ocamlfind"
let ocamlc_cmd = "ocamlc"
let ocamlopt_cmd = "ocamlopt"
let ocamldep_cmd = "ocamldep"
let camlp4_cmd = "camlp4"
let camlp4o_cmd = "camlp4o"
|
c162483c8da9c071dd752297b535723f90a0630c8fa589c91238a8065289f2a0 | jordwalke/rehp | test_dynlink.ml | let _ = print_endline "Dynlink OK"
let f () = print_endline "Test_dynlink.f Ok"
| null | https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/toplevel/examples/lwt_toplevel/test_dynlink.ml | ocaml | let _ = print_endline "Dynlink OK"
let f () = print_endline "Test_dynlink.f Ok"
| |
3e0b34d56317753a1339d3e10b14483e051d72ab63e844ffe54b60286d78f4c2 | cedlemo/OCaml-GI-ctypes-bindings-generator | Window_position.ml | open Ctypes
open Foreign
type t = None | Center | Mouse | Center_always | Center_on_parent
let of_value v =
if v = Unsigned.UInt32.of_int 0 then None
else if v = Unsigned.UInt32.of_int 1 then Center
else if v = Unsigned.UInt32.of_int 2 then Mouse
else if v = Unsigned.UInt32.of_int 3 then Center_always
else if v = Unsigned.UInt32.of_int 4 then Center_on_parent
else raise (Invalid_argument "Unexpected Window_position value")
let to_value = function
| None -> Unsigned.UInt32.of_int 0
| Center -> Unsigned.UInt32.of_int 1
| Mouse -> Unsigned.UInt32.of_int 2
| Center_always -> Unsigned.UInt32.of_int 3
| Center_on_parent -> Unsigned.UInt32.of_int 4
let t_view = view ~read:of_value ~write:to_value uint32_t
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Window_position.ml | ocaml | open Ctypes
open Foreign
type t = None | Center | Mouse | Center_always | Center_on_parent
let of_value v =
if v = Unsigned.UInt32.of_int 0 then None
else if v = Unsigned.UInt32.of_int 1 then Center
else if v = Unsigned.UInt32.of_int 2 then Mouse
else if v = Unsigned.UInt32.of_int 3 then Center_always
else if v = Unsigned.UInt32.of_int 4 then Center_on_parent
else raise (Invalid_argument "Unexpected Window_position value")
let to_value = function
| None -> Unsigned.UInt32.of_int 0
| Center -> Unsigned.UInt32.of_int 1
| Mouse -> Unsigned.UInt32.of_int 2
| Center_always -> Unsigned.UInt32.of_int 3
| Center_on_parent -> Unsigned.UInt32.of_int 4
let t_view = view ~read:of_value ~write:to_value uint32_t
| |
a8cee4f1b6ee89efc46096df79f139fe334d4c4eaa5b5c52408da728215295f5 | michaelw/cl-dot | sb-c-example.lisp | (in-package cl-dot)
(defun list-no-nil (&rest args)
(remove nil args))
;; COMPONENT
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (object sb-c:component))
nil)
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c:component))
(list* (sb-c::component-head c)
(sb-c::component-lambdas c)))
CBLOCK
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::cblock))
(make-instance 'node
:attributes `(:label ,(format nil "Block ~A" (sb-c::block-number c)))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::cblock))
(sb-c::block-succ c))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::cblock))
(sb-c::block-pred c))
CLAMBDA
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::clambda))
(make-instance 'node
:attributes `(:label ,(format nil "Lambda ~A"
(sb-c::lambda-%source-name c)))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::clambda))
(sb-c::lambda-vars c))
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::lambda-var))
(make-instance 'node
:attributes `(:label ,(format nil "Var ~A"
(sb-c::lambda-var-%source-name c)))))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::lambda-var))
(sb-c::lambda-var-refs c))
REF
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::ref))
(make-instance 'node
:attributes (list :label "REF"
:fillcolor "#ddffbb"
:style :filled
:shape :diamond)))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::ref))
(list-no-nil (sb-c::ref-leaf c)
(sb-c::ref-next c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::ref))
(list-no-nil (sb-c::ref-prev c)
(sb-c::ref-lvar c)))
;; CTRAN
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::ctran))
(make-instance 'node
:attributes `(:label ,(format nil "CTRAN ~A"
(sb-c::ctran-kind c)))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::ctran))
(list-no-nil (sb-c::ctran-next c)
(sb-c::ctran-use c)))
BIND
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::bind))
(make-instance 'node
:attributes `(:label ,(format nil "BIND"))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::bind))
(list-no-nil (sb-c::bind-next c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::bind))
(list-no-nil (sb-c::bind-prev c)))
GLOBAL - VAR
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::global-var))
(make-instance 'node
:attributes (list :label (format nil "GLOBAL-VAR\\n~A\\n~A"
(sb-c::global-var-%source-name c)
(sb-c::global-var-kind c))
:shape :box)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::global-var))
(sb-c::global-var-refs c))
;; CONSTANT
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::constant))
(make-instance 'node
:attributes (list :label (format nil "CONSTANT ~A"
(sb-c::constant-%source-name c)
#+nil (sb-c::constant-value c))
:style :filled
:fillcolor "#ffffee"
:shape :box)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::constant))
(sb-c::constant-refs c))
;; ENTRY
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::entry))
(make-instance 'node
:attributes `(:label ,(format nil "ENTRY"))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::entry))
;; cleanup
(list-no-nil (sb-c::entry-next c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::entry))
(list-no-nil (sb-c::entry-prev c)))
;; COMBINATION
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::combination))
(make-instance 'node
:attributes (list :label (format nil "COMBINATION")
:shape :octagon
:style :filled
:fillcolor "#eeeeff")))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::combination))
(list-no-nil (sb-c::combination-next c)
(sb-c::combination-lvar c)
(sb-c::combination-fun c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::combination))
(list* (sb-c::combination-prev c)
(sb-c::combination-args c)))
LVAR
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::lvar))
(make-instance 'node
:attributes (list :label (format nil "LVAR"
#+nil (sb-c::lvar-derived-type c))
:style :filled
:fillcolor "#ffeeff"
:shape :octagon)))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::lvar))
(list-no-nil (sb-c::lvar-dest c)))
(defmethod graph-object-pointed-to-by ((graph (eql 'sb-c-example)) (c sb-c::lvar))
(let ((uses (sb-c::lvar-uses c)))
(if (listp uses)
uses
(list-no-nil uses))))
CIF
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::cif))
(make-instance 'node
:attributes `(:label ,(format nil "CIF"))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::cif))
(list-no-nil (sb-c::if-next c)
(sb-c::if-test c)
(sb-c::if-consequent c)
(sb-c::if-alternative c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::cif))
(list-no-nil (sb-c::if-prev c)))
CRETURN
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::creturn))
(make-instance 'node
:attributes `(:label ,(format nil "CRETURN"))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::creturn))
(list-no-nil (sb-c::return-next c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::creturn))
(list-no-nil (sb-c::return-prev c)
(sb-c::return-result c)))
| null | https://raw.githubusercontent.com/michaelw/cl-dot/d32808109952faf8e4d342c0ff4f5a2587b315cb/examples/sb-c-example.lisp | lisp | COMPONENT
CTRAN
CONSTANT
ENTRY
cleanup
COMBINATION | (in-package cl-dot)
(defun list-no-nil (&rest args)
(remove nil args))
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (object sb-c:component))
nil)
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c:component))
(list* (sb-c::component-head c)
(sb-c::component-lambdas c)))
CBLOCK
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::cblock))
(make-instance 'node
:attributes `(:label ,(format nil "Block ~A" (sb-c::block-number c)))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::cblock))
(sb-c::block-succ c))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::cblock))
(sb-c::block-pred c))
CLAMBDA
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::clambda))
(make-instance 'node
:attributes `(:label ,(format nil "Lambda ~A"
(sb-c::lambda-%source-name c)))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::clambda))
(sb-c::lambda-vars c))
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::lambda-var))
(make-instance 'node
:attributes `(:label ,(format nil "Var ~A"
(sb-c::lambda-var-%source-name c)))))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::lambda-var))
(sb-c::lambda-var-refs c))
REF
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::ref))
(make-instance 'node
:attributes (list :label "REF"
:fillcolor "#ddffbb"
:style :filled
:shape :diamond)))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::ref))
(list-no-nil (sb-c::ref-leaf c)
(sb-c::ref-next c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::ref))
(list-no-nil (sb-c::ref-prev c)
(sb-c::ref-lvar c)))
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::ctran))
(make-instance 'node
:attributes `(:label ,(format nil "CTRAN ~A"
(sb-c::ctran-kind c)))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::ctran))
(list-no-nil (sb-c::ctran-next c)
(sb-c::ctran-use c)))
BIND
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::bind))
(make-instance 'node
:attributes `(:label ,(format nil "BIND"))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::bind))
(list-no-nil (sb-c::bind-next c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::bind))
(list-no-nil (sb-c::bind-prev c)))
GLOBAL - VAR
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::global-var))
(make-instance 'node
:attributes (list :label (format nil "GLOBAL-VAR\\n~A\\n~A"
(sb-c::global-var-%source-name c)
(sb-c::global-var-kind c))
:shape :box)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::global-var))
(sb-c::global-var-refs c))
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::constant))
(make-instance 'node
:attributes (list :label (format nil "CONSTANT ~A"
(sb-c::constant-%source-name c)
#+nil (sb-c::constant-value c))
:style :filled
:fillcolor "#ffffee"
:shape :box)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::constant))
(sb-c::constant-refs c))
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::entry))
(make-instance 'node
:attributes `(:label ,(format nil "ENTRY"))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::entry))
(list-no-nil (sb-c::entry-next c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::entry))
(list-no-nil (sb-c::entry-prev c)))
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::combination))
(make-instance 'node
:attributes (list :label (format nil "COMBINATION")
:shape :octagon
:style :filled
:fillcolor "#eeeeff")))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::combination))
(list-no-nil (sb-c::combination-next c)
(sb-c::combination-lvar c)
(sb-c::combination-fun c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::combination))
(list* (sb-c::combination-prev c)
(sb-c::combination-args c)))
LVAR
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::lvar))
(make-instance 'node
:attributes (list :label (format nil "LVAR"
#+nil (sb-c::lvar-derived-type c))
:style :filled
:fillcolor "#ffeeff"
:shape :octagon)))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::lvar))
(list-no-nil (sb-c::lvar-dest c)))
(defmethod graph-object-pointed-to-by ((graph (eql 'sb-c-example)) (c sb-c::lvar))
(let ((uses (sb-c::lvar-uses c)))
(if (listp uses)
uses
(list-no-nil uses))))
CIF
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::cif))
(make-instance 'node
:attributes `(:label ,(format nil "CIF"))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::cif))
(list-no-nil (sb-c::if-next c)
(sb-c::if-test c)
(sb-c::if-consequent c)
(sb-c::if-alternative c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::cif))
(list-no-nil (sb-c::if-prev c)))
CRETURN
(defmethod graph-object-node ((graph (eql 'sb-c-example)) (c sb-c::creturn))
(make-instance 'node
:attributes `(:label ,(format nil "CRETURN"))))
(defmethod graph-object-points-to ((graph (eql 'sb-c-example)) (c sb-c::creturn))
(list-no-nil (sb-c::return-next c)))
(defmethod graph-object-knows-of ((graph (eql 'sb-c-example)) (c sb-c::creturn))
(list-no-nil (sb-c::return-prev c)
(sb-c::return-result c)))
|
5d4115b588aaf92debf9be52e2d6f7a16642378a7d30b54a2f3caf6414b3f402 | ghcjs/jsaddle-dom | ApplePayPaymentMethodSelectedEvent.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.ApplePayPaymentMethodSelectedEvent
(getPaymentMethod, ApplePayPaymentMethodSelectedEvent(..),
gTypeApplePayPaymentMethodSelectedEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/ApplePayPaymentMethodSelectedEvent.paymentMethod Mozilla ApplePayPaymentMethodSelectedEvent.paymentMethod documentation >
getPaymentMethod ::
(MonadDOM m) =>
ApplePayPaymentMethodSelectedEvent -> m ApplePayPaymentMethod
getPaymentMethod self
= liftDOM ((self ^. js "paymentMethod") >>= fromJSValUnchecked)
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/ApplePayPaymentMethodSelectedEvent.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.ApplePayPaymentMethodSelectedEvent
(getPaymentMethod, ApplePayPaymentMethodSelectedEvent(..),
gTypeApplePayPaymentMethodSelectedEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/ApplePayPaymentMethodSelectedEvent.paymentMethod Mozilla ApplePayPaymentMethodSelectedEvent.paymentMethod documentation >
getPaymentMethod ::
(MonadDOM m) =>
ApplePayPaymentMethodSelectedEvent -> m ApplePayPaymentMethod
getPaymentMethod self
= liftDOM ((self ^. js "paymentMethod") >>= fromJSValUnchecked)
|
14c03a5fdf2ca57a5d075b97937b77c286d95ef06a4f4965b22e2086753bcdbe | dterei/SafeHaskellExamples | Main.hs | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
module Main where
-- import Sub ( T() )
import Sub ( T(..) )
import Data.Coerce
class Default a where
def :: a
instance Default Int where
def = 0
> Can only derive ( i.e. , coerce : : Int - > T ) when ` MkT ` constructor is in
-- > scope.
deriving instance Default T
instance where
-- def = coerce (def :: Int)
-- -- coerce :: Int -> T
main :: IO ()
main = do
print (def :: Int)
print (def :: T)
| null | https://raw.githubusercontent.com/dterei/SafeHaskellExamples/0f7bbb53cf1cbb8419ce3a4aa4258b84be30ffcc/gnd1/Main.hs | haskell | import Sub ( T() )
> scope.
def = coerce (def :: Int)
-- coerce :: Int -> T | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE StandaloneDeriving #
module Main where
import Sub ( T(..) )
import Data.Coerce
class Default a where
def :: a
instance Default Int where
def = 0
> Can only derive ( i.e. , coerce : : Int - > T ) when ` MkT ` constructor is in
deriving instance Default T
instance where
main :: IO ()
main = do
print (def :: Int)
print (def :: T)
|
68aafda9b646984b9d01332b0fdd3cf5a1e8190bf5725c08ff29afefc6fe53f5 | squaresLab/genprog-code | asm_test.ml | open Global
Load and compile an ASM .s file , return 0 on success
let main () = begin
let rep = new Asmrep.asmRep in
rep#from_source "gcd.s";
rep#output_source "temp.s" ;
let compile_success = rep#compile "temp.s" "gcd" in
if compile_success then exit 0 else exit 1;
end ;;
main () ;;
| null | https://raw.githubusercontent.com/squaresLab/genprog-code/7982415b347529efee02190ab9ba6bd7eda6195e/test/asm_test.ml | ocaml | open Global
Load and compile an ASM .s file , return 0 on success
let main () = begin
let rep = new Asmrep.asmRep in
rep#from_source "gcd.s";
rep#output_source "temp.s" ;
let compile_success = rep#compile "temp.s" "gcd" in
if compile_success then exit 0 else exit 1;
end ;;
main () ;;
| |
904242df2c02f3b42893c93d740b43e0d1b24bb15aad2613f14850e6b8816ad3 | axelarge/advent-of-code | day06_test.clj | (ns advent-of-code.y2019.day06-test
(:require [clojure.test :refer :all]
[advent-of-code.y2019.day06 :refer :all]))
(def test-input "COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L")
(def test-input2 "COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L\nK)YOU\nI)SAN")
(deftest test-solve1
(is (= 42 (solve1 test-input)))
(is (= 150150 (solve1 input))))
(deftest test-solve2
(is (= (solve-path (parse test-input2)) ["K" "J" "E" "D" "I"]))
(is (= (solve2 test-input2) 4))
(is (= (solve2 input) 352)))
| null | https://raw.githubusercontent.com/axelarge/advent-of-code/4c62a53ef71605780a22cf8219029453d8e1b977/test/advent_of_code/y2019/day06_test.clj | clojure | (ns advent-of-code.y2019.day06-test
(:require [clojure.test :refer :all]
[advent-of-code.y2019.day06 :refer :all]))
(def test-input "COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L")
(def test-input2 "COM)B\nB)C\nC)D\nD)E\nE)F\nB)G\nG)H\nD)I\nE)J\nJ)K\nK)L\nK)YOU\nI)SAN")
(deftest test-solve1
(is (= 42 (solve1 test-input)))
(is (= 150150 (solve1 input))))
(deftest test-solve2
(is (= (solve-path (parse test-input2)) ["K" "J" "E" "D" "I"]))
(is (= (solve2 test-input2) 4))
(is (= (solve2 input) 352)))
| |
33bbd6190b65b4ca72abfcb305e3a8c4108dfa5ea8b325fa862b16ee01a4e3a3 | locusmath/locus | lattice_equation.clj | (ns locus.order.lattice.term.lattice-equation
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.order.general.core.object :refer :all]
[locus.order.lattice.core.object :refer :all]
[locus.order.lattice.term.lattice-term :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all])
(:import (locus.order.lattice.core.object Lattice)
(locus.order.lattice.term.lattice_term LatticeTerm)))
; A lattice equation consists of a pair of lattice terms that are equated
to one another . The lattice terms can be represented symbolically . The point of
; this lattice equation class is to represent some of the individual equations
; that togethe make up a system of lattice equations.
(deftype LatticeEquation [left right]
Object
(toString [this]
(str "(= " left " " right ")")))
(defmethod print-method LatticeEquation [^LatticeEquation v ^java.io.Writer w]
(.write w (.toString v)))
(defn left-term
[^LatticeEquation lattice-equation]
(LatticeTerm. (.left lattice-equation)))
(defn right-term
[^LatticeEquation lattice-equation]
(LatticeTerm. (.right lattice-equation)))
; Distributive laws for lattices
(defn meet-distribution-equation
[[a b c]]
(LatticeEquation.
(list '* a (list '+ b c))
(list '+ (list '* a b) (list '* a c))))
(defn join-distribution-equation
[[a b c]]
(LatticeEquation.
(list '+ a (list '* b c))
(list '* (list '+ a b) (list '+ a c))))
Modular laws for lattices
(defn modular-identity
[[a b c]]
(LatticeEquation.
(list '+ (list '* a b) (list '* c b))
(list
'*
(list
'+
(list '* a b)
c)
b)))
(defn modular-predecessor-identity
[[a b c]]
(LatticeEquation.
(list '+ a (list '* c b))
(list '* (list '+ a c) b)))
; Determine equality using joins and meets with a fixed element
(defn join-equality-with
[[a b c]]
(LatticeEquation.
(list '+ a c)
(list '+ b c)))
(defn meet-equality-with
[[a b c]]
(LatticeEquation.
(list '* a c)
(list '* b c)))
; Lattice inequalities as equations
a < = b means that a*b = a and a + b = b
; a >= b means that a*b = b and a + b = a
(defn lattice-predecessor-inequality
[a b]
(LatticeEquation.
(.data (product (LatticeTerm. a) (LatticeTerm. b)))
a))
(defn lattice-successor-inequality
[a b]
(LatticeEquation.
(.data (product (LatticeTerm. a) (LatticeTerm. b)))
b))
; Test if a given lattice equation is satisfied with respect to an environment mapping
(defn satisfies-lattice-equation?
[join meet equation env]
(= (apply-lattice-expression join meet (.left equation) env)
(apply-lattice-expression join meet (.right equation) env)))
| null | https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/order/lattice/term/lattice_equation.clj | clojure | A lattice equation consists of a pair of lattice terms that are equated
this lattice equation class is to represent some of the individual equations
that togethe make up a system of lattice equations.
Distributive laws for lattices
Determine equality using joins and meets with a fixed element
Lattice inequalities as equations
a >= b means that a*b = b and a + b = a
Test if a given lattice equation is satisfied with respect to an environment mapping | (ns locus.order.lattice.term.lattice-equation
(:require [locus.set.logic.core.set :refer :all]
[locus.set.logic.limit.product :refer :all]
[locus.set.mapping.general.core.object :refer :all]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.order.general.core.object :refer :all]
[locus.order.lattice.core.object :refer :all]
[locus.order.lattice.term.lattice-term :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all])
(:import (locus.order.lattice.core.object Lattice)
(locus.order.lattice.term.lattice_term LatticeTerm)))
to one another . The lattice terms can be represented symbolically . The point of
(deftype LatticeEquation [left right]
Object
(toString [this]
(str "(= " left " " right ")")))
(defmethod print-method LatticeEquation [^LatticeEquation v ^java.io.Writer w]
(.write w (.toString v)))
(defn left-term
[^LatticeEquation lattice-equation]
(LatticeTerm. (.left lattice-equation)))
(defn right-term
[^LatticeEquation lattice-equation]
(LatticeTerm. (.right lattice-equation)))
(defn meet-distribution-equation
[[a b c]]
(LatticeEquation.
(list '* a (list '+ b c))
(list '+ (list '* a b) (list '* a c))))
(defn join-distribution-equation
[[a b c]]
(LatticeEquation.
(list '+ a (list '* b c))
(list '* (list '+ a b) (list '+ a c))))
Modular laws for lattices
(defn modular-identity
[[a b c]]
(LatticeEquation.
(list '+ (list '* a b) (list '* c b))
(list
'*
(list
'+
(list '* a b)
c)
b)))
(defn modular-predecessor-identity
[[a b c]]
(LatticeEquation.
(list '+ a (list '* c b))
(list '* (list '+ a c) b)))
(defn join-equality-with
[[a b c]]
(LatticeEquation.
(list '+ a c)
(list '+ b c)))
(defn meet-equality-with
[[a b c]]
(LatticeEquation.
(list '* a c)
(list '* b c)))
a < = b means that a*b = a and a + b = b
(defn lattice-predecessor-inequality
[a b]
(LatticeEquation.
(.data (product (LatticeTerm. a) (LatticeTerm. b)))
a))
(defn lattice-successor-inequality
[a b]
(LatticeEquation.
(.data (product (LatticeTerm. a) (LatticeTerm. b)))
b))
(defn satisfies-lattice-equation?
[join meet equation env]
(= (apply-lattice-expression join meet (.left equation) env)
(apply-lattice-expression join meet (.right equation) env)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.