_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 |
|---|---|---|---|---|---|---|---|---|
8974feea26ea1feab8b5fadf9debf2afe0f7f2216312c9fd50b7cfa7e30609e6 | fhur/regie | core_test.clj | (ns regie.core-test
(:require [clojure.test :refer :all]
[regie.core :refer [regie matches? regie-digits regie-lower-case-english-letters n-or-more]]))
(def random-seed 0xc0de)
(def random-string
"random-string [size]
Returns a random string of the given size. If no size is
given then a random size will be picked from 1 to 20"
TODO this only creates base64 strings , make it return a random unicode string
XXX that ^ is tedious since not every byte array is a valid UTF-8 string :(
(let [random (new java.util.Random random-seed)]
(fn random-string
([size]
(let [byte-array1 (byte-array size)]
(.nextBytes random byte-array1)
(-> (java.util.Base64/getEncoder)
(.encodeToString byte-array1))))
([]
(-> random
(.nextInt 20)
inc
(random-string))))))
(defn assert-matches [regex string]
(is (matches? (regie regex) string)
(str "Expected regex " regex " to match string '" string "'")))
(defn assert-not-matches [regex string]
(is (not (matches? (regie regex) string))
(str "Expected regex " regex " NOT to match string '" string "'")))
(deftest simple-string-regexes
(testing "Every non-empty string regex should match itself"
(let [string (random-string)
regex string]
(assert-not-matches regex "")
(assert-not-matches regex (str "a" string))
(assert-not-matches regex (str string "b"))
(assert-matches regex string)))
(testing ":cat => Concatenation"
(let [string-left (random-string)
string-right (random-string)
regex [:cat string-left string-right]]
(assert-not-matches regex "")
(assert-not-matches regex string-left)
(assert-not-matches regex string-right)
(assert-matches regex (str string-left string-right))))
(testing ":or => Alternation"
(let [string-left (random-string)
string-right (random-string)
regex [:or string-left string-right]]
(assert-not-matches regex "")
(assert-not-matches regex (str string-left string-right))
(assert-matches regex string-left)
(assert-matches regex string-right)))
(testing ":* => Kleen Star"
(let [string (random-string)
regex [:* string]]
(assert-matches regex "")
(assert-matches regex string)
(assert-matches regex (str string string))
(assert-matches regex (str string string string string))))
(testing ":? => Option"
(let [string (random-string)
regex [:? string]]
(assert-not-matches regex (str string string))
(assert-not-matches regex (str string "."))
(assert-not-matches regex (str "x" string))
(assert-matches regex "")
(assert-matches regex string)))
(testing ":+ => Multiple"
(let [string (random-string)
regex [:+ string]]
(assert-not-matches regex "")
(assert-matches regex string)
(assert-matches regex (str string string))
(assert-matches regex (str string string string string))))
(testing "Digit support"
(let [regex [:cat 1 2 3 123]]
(assert-matches regex "123123")))
(testing "Composing Regexes: 01+0"
(let [regex [:cat "0" [:+ "1"] "0"]]
(assert-not-matches regex "1")
(assert-not-matches regex "01")
(assert-not-matches regex "01111111")
(assert-matches regex "010")
(assert-matches regex "0110")
(assert-matches regex "01111111111111111110")))
(testing "Composing Regexes: 0+1+2?3*"
(let [regex [:cat [:+ "0"]
[:+ "1"]
[:? "2"]
[:? [:cat regie-digits regie-lower-case-english-letters]]
[:* "3"]]]
(assert-matches regex "01")
(assert-matches regex "012")
(assert-matches regex "013")
(assert-matches regex "0123")
(assert-matches regex "00000000123")
(assert-matches regex "000000001113")
(assert-matches regex "00000000111")
(assert-matches regex "000000001113333333")
(assert-matches regex "000000001117a3333333")
(assert-matches regex "000000001118b3333333"))))
(deftest test-regie-transformers
(testing "n-or-more: should match the given regex n or more times"
(testing "Matching 0 or more"
(let [regex-0-or-more (n-or-more 0 "bar")]
(assert-matches regex-0-or-more "")
(assert-matches regex-0-or-more "bar")
(assert-matches regex-0-or-more "barbar")
(assert-matches regex-0-or-more "barbarbar")))
(testing "Matching 2 or more"
(let [regex-2-or-more (n-or-more 2 "bar")]
(assert-not-matches regex-2-or-more "")
(assert-not-matches regex-2-or-more "bar")
(assert-matches regex-2-or-more "barbar")
(assert-matches regex-2-or-more "barbarbar")
(assert-matches regex-2-or-more "barbarbarbar")))))
(deftest test-builtin-regexes
(testing "regie-digits should match any digit"
(assert-matches regie-digits "0")
(assert-matches regie-digits "1")
(assert-matches regie-digits "2")
(assert-matches regie-digits "3")
(assert-matches regie-digits "4")
(assert-matches regie-digits "5")
(assert-matches regie-digits "6")
(assert-matches regie-digits "7")
(assert-matches regie-digits "8")
(assert-matches regie-digits "9")
(assert-not-matches regie-digits "10")))
| null | https://raw.githubusercontent.com/fhur/regie/965cdae8ae63423ed5bea59fe267da949193d47a/test/regie/core_test.clj | clojure | (ns regie.core-test
(:require [clojure.test :refer :all]
[regie.core :refer [regie matches? regie-digits regie-lower-case-english-letters n-or-more]]))
(def random-seed 0xc0de)
(def random-string
"random-string [size]
Returns a random string of the given size. If no size is
given then a random size will be picked from 1 to 20"
TODO this only creates base64 strings , make it return a random unicode string
XXX that ^ is tedious since not every byte array is a valid UTF-8 string :(
(let [random (new java.util.Random random-seed)]
(fn random-string
([size]
(let [byte-array1 (byte-array size)]
(.nextBytes random byte-array1)
(-> (java.util.Base64/getEncoder)
(.encodeToString byte-array1))))
([]
(-> random
(.nextInt 20)
inc
(random-string))))))
(defn assert-matches [regex string]
(is (matches? (regie regex) string)
(str "Expected regex " regex " to match string '" string "'")))
(defn assert-not-matches [regex string]
(is (not (matches? (regie regex) string))
(str "Expected regex " regex " NOT to match string '" string "'")))
(deftest simple-string-regexes
(testing "Every non-empty string regex should match itself"
(let [string (random-string)
regex string]
(assert-not-matches regex "")
(assert-not-matches regex (str "a" string))
(assert-not-matches regex (str string "b"))
(assert-matches regex string)))
(testing ":cat => Concatenation"
(let [string-left (random-string)
string-right (random-string)
regex [:cat string-left string-right]]
(assert-not-matches regex "")
(assert-not-matches regex string-left)
(assert-not-matches regex string-right)
(assert-matches regex (str string-left string-right))))
(testing ":or => Alternation"
(let [string-left (random-string)
string-right (random-string)
regex [:or string-left string-right]]
(assert-not-matches regex "")
(assert-not-matches regex (str string-left string-right))
(assert-matches regex string-left)
(assert-matches regex string-right)))
(testing ":* => Kleen Star"
(let [string (random-string)
regex [:* string]]
(assert-matches regex "")
(assert-matches regex string)
(assert-matches regex (str string string))
(assert-matches regex (str string string string string))))
(testing ":? => Option"
(let [string (random-string)
regex [:? string]]
(assert-not-matches regex (str string string))
(assert-not-matches regex (str string "."))
(assert-not-matches regex (str "x" string))
(assert-matches regex "")
(assert-matches regex string)))
(testing ":+ => Multiple"
(let [string (random-string)
regex [:+ string]]
(assert-not-matches regex "")
(assert-matches regex string)
(assert-matches regex (str string string))
(assert-matches regex (str string string string string))))
(testing "Digit support"
(let [regex [:cat 1 2 3 123]]
(assert-matches regex "123123")))
(testing "Composing Regexes: 01+0"
(let [regex [:cat "0" [:+ "1"] "0"]]
(assert-not-matches regex "1")
(assert-not-matches regex "01")
(assert-not-matches regex "01111111")
(assert-matches regex "010")
(assert-matches regex "0110")
(assert-matches regex "01111111111111111110")))
(testing "Composing Regexes: 0+1+2?3*"
(let [regex [:cat [:+ "0"]
[:+ "1"]
[:? "2"]
[:? [:cat regie-digits regie-lower-case-english-letters]]
[:* "3"]]]
(assert-matches regex "01")
(assert-matches regex "012")
(assert-matches regex "013")
(assert-matches regex "0123")
(assert-matches regex "00000000123")
(assert-matches regex "000000001113")
(assert-matches regex "00000000111")
(assert-matches regex "000000001113333333")
(assert-matches regex "000000001117a3333333")
(assert-matches regex "000000001118b3333333"))))
(deftest test-regie-transformers
(testing "n-or-more: should match the given regex n or more times"
(testing "Matching 0 or more"
(let [regex-0-or-more (n-or-more 0 "bar")]
(assert-matches regex-0-or-more "")
(assert-matches regex-0-or-more "bar")
(assert-matches regex-0-or-more "barbar")
(assert-matches regex-0-or-more "barbarbar")))
(testing "Matching 2 or more"
(let [regex-2-or-more (n-or-more 2 "bar")]
(assert-not-matches regex-2-or-more "")
(assert-not-matches regex-2-or-more "bar")
(assert-matches regex-2-or-more "barbar")
(assert-matches regex-2-or-more "barbarbar")
(assert-matches regex-2-or-more "barbarbarbar")))))
(deftest test-builtin-regexes
(testing "regie-digits should match any digit"
(assert-matches regie-digits "0")
(assert-matches regie-digits "1")
(assert-matches regie-digits "2")
(assert-matches regie-digits "3")
(assert-matches regie-digits "4")
(assert-matches regie-digits "5")
(assert-matches regie-digits "6")
(assert-matches regie-digits "7")
(assert-matches regie-digits "8")
(assert-matches regie-digits "9")
(assert-not-matches regie-digits "10")))
| |
8762519bc4027e2aff744aaf54614259483bed3cc2c453b01a1cd63f2c142b27 | avsm/mirage-duniverse | handshake_client.ml | open Nocrypto
open Utils
open Core
open State
open Handshake_common
open Config
let (<+>) = Cs.(<+>)
let default_client_hello config =
let host = match config.peer_name with
| None -> []
| Some x -> [`Hostname x]
in
let version = max_protocol_version config.protocol_versions in
let signature_algos = match version with
| TLS_1_0 | TLS_1_1 -> []
| TLS_1_2 ->
let supported = List.map (fun h -> (h, Packet.RSA)) config.hashes in
[`SignatureAlgorithms supported]
in
let alpn = match config.alpn_protocols with
| [] -> []
| protocols -> [`ALPN protocols]
in
let ciphers =
let cs = config.ciphers in
match version with
| TLS_1_0 | TLS_1_1 -> List.filter (o not Ciphersuite.ciphersuite_tls12_only) cs
| TLS_1_2 -> cs
and sessionid =
match config.use_reneg, config.cached_session with
| _, Some { session_id ; extended_ms ; _ } when extended_ms = true -> Some session_id
| false, Some { session_id ; _ } -> Some session_id
| _ -> None
in
let ch = {
client_version = Supported version ;
client_random = Rng.generate 32 ;
sessionid = sessionid ;
ciphersuites = List.map Ciphersuite.ciphersuite_to_any_ciphersuite ciphers ;
extensions = `ExtendedMasterSecret :: host @ signature_algos @ alpn
}
in
(ch , version)
let common_server_hello_validation config reneg (sh : server_hello) (ch : client_hello) =
let validate_reneg data =
match reneg, data with
| Some (cvd, svd), Some x -> guard (Cs.equal (cvd <+> svd) x) (`Fatal `InvalidRenegotiation)
| Some _, None -> fail (`Fatal `NoSecureRenegotiation)
| None, Some x -> guard (Cs.null x) (`Fatal `InvalidRenegotiation)
| None, None -> return ()
in
guard (List.mem sh.ciphersuite config.ciphers)
(`Error (`NoConfiguredCiphersuite [sh.ciphersuite])) >>= fun () ->
guard (server_hello_valid sh &&
server_exts_subset_of_client sh.extensions ch.extensions)
(`Fatal `InvalidServerHello) >>= fun () ->
(match get_alpn_protocol sh with
| None -> return ()
| Some x ->
guard (List.mem x config.alpn_protocols) (`Fatal `InvalidServerHello)) >>= fun () ->
validate_reneg (get_secure_renegotiation sh.extensions)
let common_server_hello_machina state (sh : server_hello) (ch : client_hello) raw log =
let machina =
let cipher = sh.ciphersuite in
let session_id = match sh.sessionid with None -> Cstruct.create 0 | Some x -> x in
let extended_ms =
List.mem `ExtendedMasterSecret ch.extensions &&
List.mem `ExtendedMasterSecret sh.extensions
in
let alpn_protocol = get_alpn_protocol sh in
let session = { empty_session with
client_random = ch.client_random ;
client_version = ch.client_version ;
server_random = sh.server_random ;
ciphersuite = cipher ;
session_id ;
extended_ms ;
alpn_protocol ;
}
in
Ciphersuite.(match ciphersuite_kex cipher with
| RSA -> AwaitCertificate_RSA (session, log @ [raw])
| DHE_RSA -> AwaitCertificate_DHE_RSA (session, log @ [raw]))
in
({ state with protocol_version = sh.server_version ; machina = Client machina }, [])
let answer_server_hello state (ch : client_hello) sh raw log =
let validate_version requested (lo, _) server_version =
guard (version_ge requested server_version && server_version >= lo)
(`Error (`NoConfiguredVersion server_version))
in
let cfg = state.config in
common_server_hello_validation cfg None sh ch >>= fun () ->
validate_version ch.client_version state.config.protocol_versions sh.server_version >|= fun () ->
let epoch_matches (epoch : epoch_data) =
epoch.ciphersuite = sh.ciphersuite &&
epoch.protocol_version = sh.server_version &&
option false (SessionID.equal epoch.session_id) sh.sessionid &&
(not cfg.use_reneg ||
(List.mem `ExtendedMasterSecret sh.extensions && epoch.extended_ms))
in
match state.config.cached_session with
| Some epoch when epoch_matches epoch ->
let session = session_of_epoch epoch in
let session = { session with
client_random = ch.client_random ;
server_random = sh.server_random ;
client_version = ch.client_version ;
client_auth = List.length epoch.own_certificate > 0 ;
}
in
let client_ctx, server_ctx =
Handshake_crypto.initialise_crypto_ctx sh.server_version session
in
let machina = AwaitServerChangeCipherSpecResume (session, client_ctx, server_ctx, log @ [raw]) in
({ state with protocol_version = sh.server_version ; machina = Client machina }, [])
| _ -> common_server_hello_machina state sh ch raw log
let answer_server_hello_renegotiate state session (ch : client_hello) sh raw log =
common_server_hello_validation state.config (Some session.renegotiation) sh ch >>= fun () ->
guard (state.protocol_version = sh.server_version)
(`Fatal (`InvalidRenegotiationVersion sh.server_version)) >|= fun () ->
common_server_hello_machina state sh ch raw log
let validate_keytype_usage certificate ciphersuite =
let keytype, usage =
Ciphersuite.(o required_keytype_and_usage ciphersuite_kex ciphersuite)
in
match certificate with
| None -> fail (`Fatal `NoCertificateReceived)
| Some cert ->
let open X509 in
guard (supports_keytype cert keytype)
(`Fatal `NotRSACertificate) >>= fun () ->
guard (Extension.supports_usage ~not_present:true cert usage)
(`Fatal `InvalidCertificateUsage) >>= fun () ->
guard
(Extension.supports_extended_usage cert `Server_auth ||
Extension.supports_extended_usage ~not_present:true cert `Any)
(`Fatal `InvalidCertificateExtendedUsage)
let answer_certificate_RSA state session cs raw log =
let cfg = state.config in
let peer_name = match cfg.peer_name with
| None -> None
| Some x -> Some (`Wildcard x)
in
validate_chain cfg.authenticator cs peer_name >>= fun (peer_certificate, received_certificates, peer_certificate_chain, trust_anchor) ->
validate_keytype_usage peer_certificate session.ciphersuite >>= fun () ->
let session = { session with received_certificates ; peer_certificate ; peer_certificate_chain ; trust_anchor } in
( match session.client_version with
| Supported v -> return v
| x -> fail (`Fatal (`NoVersion x)) (* TODO: get rid of this... *)
) >>= fun version ->
let ver = Writer.assemble_protocol_version version in
let premaster = ver <+> Rng.generate 46 in
peer_rsa_key peer_certificate >|= fun pubkey ->
let kex = Rsa.PKCS1.encrypt ~key:pubkey premaster
in
let machina =
AwaitCertificateRequestOrServerHelloDone
(session, kex, premaster, log @ [raw])
in
({ state with machina = Client machina }, [])
let answer_certificate_DHE_RSA state session cs raw log =
let peer_name = match state.config.peer_name with
| None -> None
| Some x -> Some (`Wildcard x)
in
validate_chain state.config.authenticator cs peer_name >>= fun (peer_certificate, received_certificates, peer_certificate_chain, trust_anchor) ->
validate_keytype_usage peer_certificate session.ciphersuite >|= fun () ->
let session = { session with received_certificates ; peer_certificate ; peer_certificate_chain ; trust_anchor } in
let machina = AwaitServerKeyExchange_DHE_RSA (session, log @ [raw]) in
({ state with machina = Client machina }, [])
let answer_server_key_exchange_DHE_RSA state session kex raw log =
let dh_params kex =
match Reader.parse_dh_parameters kex with
| Ok data -> return data
| Error re -> fail (`Fatal (`ReaderError re))
in
dh_params kex >>= fun (dh_params, raw_dh_params, leftover) ->
let sigdata = session.client_random <+> session.server_random <+> raw_dh_params in
verify_digitally_signed state.protocol_version state.config.hashes leftover sigdata session.peer_certificate >>= fun () ->
let group, shared = Crypto.dh_params_unpack dh_params in
guard (Dh.modulus_size group >= Config.min_dh_size) (`Fatal `InvalidDH)
>>= fun () ->
let secret, kex = Dh.gen_key group in
match Dh.shared group secret shared with
| None -> fail (`Fatal `InvalidDH)
| Some pms -> let machina =
AwaitCertificateRequestOrServerHelloDone
(session, kex, pms, log @ [raw])
in
return ({ state with machina = Client machina }, [])
let answer_certificate_request state session cr kex pms raw log =
let cfg = state.config in
( match state.protocol_version with
| TLS_1_0 | TLS_1_1 ->
( match Reader.parse_certificate_request cr with
| Ok (types, cas) -> return (types, None, cas)
| Error re -> fail (`Fatal (`ReaderError re)) )
| TLS_1_2 ->
( match Reader.parse_certificate_request_1_2 cr with
| Ok (types, sigalgs, cas) -> return (types, Some sigalgs, cas)
| Error re -> fail (`Fatal (`ReaderError re)) )
) >|= fun (types, sigalgs, _cas) ->
(* TODO: respect cas, maybe multiple client certificates? *)
let own_certificate, own_private_key =
match
List.mem Packet.RSA_SIGN types,
cfg.own_certificates
with
| true, `Single (chain, priv) -> (chain, Some priv)
| _ -> ([], None)
in
let session = {
session with
own_certificate ;
own_private_key ;
client_auth = true
} in
let machina = AwaitServerHelloDone (session, sigalgs, kex, pms, log @ [raw]) in
({ state with machina = Client machina }, [])
let answer_server_hello_done state session sigalgs kex premaster raw log =
let kex = ClientKeyExchange kex in
let ckex = Writer.assemble_handshake kex in
( match session.client_auth, session.own_private_key with
| true, Some p ->
let cert = Certificate (List.map X509.Encoding.cs_of_cert session.own_certificate) in
let ccert = Writer.assemble_handshake cert in
let to_sign = log @ [ raw ; ccert ; ckex ] in
let data = Cs.appends to_sign in
let ver = state.protocol_version
and my_sigalgs = state.config.hashes in
signature ver data sigalgs my_sigalgs p >|= fun (signature) ->
let cert_verify = CertificateVerify signature in
let ccert_verify = Writer.assemble_handshake cert_verify in
([ cert ; kex ; cert_verify ],
[ ccert ; ckex ; ccert_verify ],
to_sign, Some ccert_verify)
| true, None ->
let cert = Certificate [] in
let ccert = Writer.assemble_handshake cert in
return ([cert ; kex], [ccert ; ckex], log @ [ raw ; ccert ; ckex ], None)
| false, _ ->
return ([kex], [ckex], log @ [ raw ; ckex ], None) )
>|= fun (_msgs, raw_msgs, raws, cert_verify) ->
let to_fin = raws @ option [] (fun x -> [x]) cert_verify in
let master_secret =
Handshake_crypto.derive_master_secret state.protocol_version session premaster raws
in
let session = { session with master_secret } in
let client_ctx, server_ctx =
Handshake_crypto.initialise_crypto_ctx state.protocol_version session
in
let checksum = Handshake_crypto.finished state.protocol_version session.ciphersuite master_secret "client finished" to_fin in
let fin = Finished checksum in
let raw_fin = Writer.assemble_handshake fin in
let ps = to_fin @ [raw_fin] in
let session = { session with master_secret = master_secret } in
let machina = AwaitServerChangeCipherSpec (session, server_ctx, checksum, ps)
and ccst, ccs = change_cipher_spec in
List.iter ( Tracing.sexpf ~tag:"handshake - out " ~f : sexp_of_tls_handshake ) msgs ;
Tracing.cs ~tag:"change-cipher-spec-out" ccs ;
(* Tracing.cs ~tag:"master-secret" master_secret; *)
Tracing.sexpf ~tag:"handshake - out " ~f : sexp_of_tls_handshake fin ;
({ state with machina = Client machina },
List.map (fun x -> `Record (Packet.HANDSHAKE, x)) raw_msgs @
[ `Record (ccst, ccs);
`Change_enc (Some client_ctx);
`Record (Packet.HANDSHAKE, raw_fin)])
let answer_server_finished state session client_verify fin log =
let computed =
Handshake_crypto.finished state.protocol_version session.ciphersuite session.master_secret "server finished" log
in
guard (Cs.equal computed fin) (`Fatal `BadFinished) >>= fun () ->
guard (Cs.null state.hs_fragment) (`Fatal `HandshakeFragmentsNotEmpty) >|= fun () ->
let machina = Established
and session = { session with renegotiation = (client_verify, computed) } in
({ state with machina = Client machina ; session = session :: state.session }, [])
let answer_server_finished_resume state session fin raw log =
let client, server =
let checksum = Handshake_crypto.finished state.protocol_version session.ciphersuite session.master_secret in
(checksum "client finished" (log @ [raw]), checksum "server finished" log)
in
guard (Cs.equal server fin) (`Fatal `BadFinished) >>= fun () ->
guard (Cs.null state.hs_fragment) (`Fatal `HandshakeFragmentsNotEmpty) >|= fun () ->
let machina = Established
and session = { session with renegotiation = (client, server) }
in
let finished = Finished client in
let raw_finished = Writer.assemble_handshake finished in
({ state with machina = Client machina ; session = session :: state.session },
[`Record (Packet.HANDSHAKE, raw_finished)])
let answer_hello_request state =
let produce_client_hello session config exts =
let dch, _ = default_client_hello config in
let ch = { dch with extensions = dch.extensions @ exts ; sessionid = None } in
let raw = Writer.assemble_handshake (ClientHello ch) in
let machina = AwaitServerHelloRenegotiate (session, ch, [raw]) in
Tracing.sexpf ~tag:"handshake - out " ~f : sexp_of_tls_handshake ( ClientHello ch ) ;
({ state with machina = Client machina }, [`Record (Packet.HANDSHAKE, raw)])
in
match state.config.use_reneg, state.session with
| true , x :: _ ->
let ext = `SecureRenegotiation (fst x.renegotiation) in
return (produce_client_hello x state.config [ext])
| true , _ -> fail (`Fatal `InvalidSession) (* I'm pretty sure this can be an assert false *)
| false, _ ->
let no_reneg = Writer.assemble_alert ~level:Packet.WARNING Packet.NO_RENEGOTIATION in
return (state, [`Record (Packet.ALERT, no_reneg)])
let handle_change_cipher_spec cs state packet =
match Reader.parse_change_cipher_spec packet, cs with
| Ok (), AwaitServerChangeCipherSpec (session, server_ctx, client_verify, log) ->
guard (Cs.null state.hs_fragment) (`Fatal `HandshakeFragmentsNotEmpty) >|= fun () ->
let machina = AwaitServerFinished (session, client_verify, log) in
Tracing.cs ~tag:"change-cipher-spec-in" packet ;
({ state with machina = Client machina }, [`Change_dec (Some server_ctx)])
| Ok (), AwaitServerChangeCipherSpecResume (session, client_ctx, server_ctx, log) ->
guard (Cs.null state.hs_fragment) (`Fatal `HandshakeFragmentsNotEmpty) >|= fun () ->
let ccs = change_cipher_spec in
let machina = AwaitServerFinishedResume (session, log) in
Tracing.cs ~tag:"change-cipher-spec-in" packet ;
Tracing.cs ~tag:"change-cipher-spec-out" packet ;
({ state with machina = Client machina },
[`Record ccs ; `Change_enc (Some client_ctx); `Change_dec (Some server_ctx)])
| Error re, _ -> fail (`Fatal (`ReaderError re))
| _ -> fail (`Fatal `UnexpectedCCS)
let handle_handshake cs hs buf =
let open Reader in
match parse_handshake buf with
| Ok handshake ->
Tracing.sexpf ~tag:"handshake - in " ~f : sexp_of_tls_handshake handshake ;
( match cs, handshake with
| AwaitServerHello (ch, log), ServerHello sh ->
answer_server_hello hs ch sh buf log
| AwaitServerHelloRenegotiate (session, ch, log), ServerHello sh ->
answer_server_hello_renegotiate hs session ch sh buf log
| AwaitCertificate_RSA (session, log), Certificate cs ->
answer_certificate_RSA hs session cs buf log
| AwaitCertificate_DHE_RSA (session, log), Certificate cs ->
answer_certificate_DHE_RSA hs session cs buf log
| AwaitServerKeyExchange_DHE_RSA (session, log), ServerKeyExchange kex ->
answer_server_key_exchange_DHE_RSA hs session kex buf log
| AwaitCertificateRequestOrServerHelloDone (session, kex, pms, log), CertificateRequest cr ->
answer_certificate_request hs session cr kex pms buf log
| AwaitCertificateRequestOrServerHelloDone (session, kex, pms, log), ServerHelloDone ->
answer_server_hello_done hs session None kex pms buf log
| AwaitServerHelloDone (session, sigalgs, kex, pms, log), ServerHelloDone ->
answer_server_hello_done hs session sigalgs kex pms buf log
| AwaitServerFinished (session, client_verify, log), Finished fin ->
answer_server_finished hs session client_verify fin log
| AwaitServerFinishedResume (session, log), Finished fin ->
answer_server_finished_resume hs session fin buf log
| Established, HelloRequest ->
answer_hello_request hs
| _, hs -> fail (`Fatal (`UnexpectedHandshake hs)) )
| Error re -> fail (`Fatal (`ReaderError re))
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tls/lib/handshake_client.ml | ocaml | TODO: get rid of this...
TODO: respect cas, maybe multiple client certificates?
Tracing.cs ~tag:"master-secret" master_secret;
I'm pretty sure this can be an assert false | open Nocrypto
open Utils
open Core
open State
open Handshake_common
open Config
let (<+>) = Cs.(<+>)
let default_client_hello config =
let host = match config.peer_name with
| None -> []
| Some x -> [`Hostname x]
in
let version = max_protocol_version config.protocol_versions in
let signature_algos = match version with
| TLS_1_0 | TLS_1_1 -> []
| TLS_1_2 ->
let supported = List.map (fun h -> (h, Packet.RSA)) config.hashes in
[`SignatureAlgorithms supported]
in
let alpn = match config.alpn_protocols with
| [] -> []
| protocols -> [`ALPN protocols]
in
let ciphers =
let cs = config.ciphers in
match version with
| TLS_1_0 | TLS_1_1 -> List.filter (o not Ciphersuite.ciphersuite_tls12_only) cs
| TLS_1_2 -> cs
and sessionid =
match config.use_reneg, config.cached_session with
| _, Some { session_id ; extended_ms ; _ } when extended_ms = true -> Some session_id
| false, Some { session_id ; _ } -> Some session_id
| _ -> None
in
let ch = {
client_version = Supported version ;
client_random = Rng.generate 32 ;
sessionid = sessionid ;
ciphersuites = List.map Ciphersuite.ciphersuite_to_any_ciphersuite ciphers ;
extensions = `ExtendedMasterSecret :: host @ signature_algos @ alpn
}
in
(ch , version)
let common_server_hello_validation config reneg (sh : server_hello) (ch : client_hello) =
let validate_reneg data =
match reneg, data with
| Some (cvd, svd), Some x -> guard (Cs.equal (cvd <+> svd) x) (`Fatal `InvalidRenegotiation)
| Some _, None -> fail (`Fatal `NoSecureRenegotiation)
| None, Some x -> guard (Cs.null x) (`Fatal `InvalidRenegotiation)
| None, None -> return ()
in
guard (List.mem sh.ciphersuite config.ciphers)
(`Error (`NoConfiguredCiphersuite [sh.ciphersuite])) >>= fun () ->
guard (server_hello_valid sh &&
server_exts_subset_of_client sh.extensions ch.extensions)
(`Fatal `InvalidServerHello) >>= fun () ->
(match get_alpn_protocol sh with
| None -> return ()
| Some x ->
guard (List.mem x config.alpn_protocols) (`Fatal `InvalidServerHello)) >>= fun () ->
validate_reneg (get_secure_renegotiation sh.extensions)
let common_server_hello_machina state (sh : server_hello) (ch : client_hello) raw log =
let machina =
let cipher = sh.ciphersuite in
let session_id = match sh.sessionid with None -> Cstruct.create 0 | Some x -> x in
let extended_ms =
List.mem `ExtendedMasterSecret ch.extensions &&
List.mem `ExtendedMasterSecret sh.extensions
in
let alpn_protocol = get_alpn_protocol sh in
let session = { empty_session with
client_random = ch.client_random ;
client_version = ch.client_version ;
server_random = sh.server_random ;
ciphersuite = cipher ;
session_id ;
extended_ms ;
alpn_protocol ;
}
in
Ciphersuite.(match ciphersuite_kex cipher with
| RSA -> AwaitCertificate_RSA (session, log @ [raw])
| DHE_RSA -> AwaitCertificate_DHE_RSA (session, log @ [raw]))
in
({ state with protocol_version = sh.server_version ; machina = Client machina }, [])
let answer_server_hello state (ch : client_hello) sh raw log =
let validate_version requested (lo, _) server_version =
guard (version_ge requested server_version && server_version >= lo)
(`Error (`NoConfiguredVersion server_version))
in
let cfg = state.config in
common_server_hello_validation cfg None sh ch >>= fun () ->
validate_version ch.client_version state.config.protocol_versions sh.server_version >|= fun () ->
let epoch_matches (epoch : epoch_data) =
epoch.ciphersuite = sh.ciphersuite &&
epoch.protocol_version = sh.server_version &&
option false (SessionID.equal epoch.session_id) sh.sessionid &&
(not cfg.use_reneg ||
(List.mem `ExtendedMasterSecret sh.extensions && epoch.extended_ms))
in
match state.config.cached_session with
| Some epoch when epoch_matches epoch ->
let session = session_of_epoch epoch in
let session = { session with
client_random = ch.client_random ;
server_random = sh.server_random ;
client_version = ch.client_version ;
client_auth = List.length epoch.own_certificate > 0 ;
}
in
let client_ctx, server_ctx =
Handshake_crypto.initialise_crypto_ctx sh.server_version session
in
let machina = AwaitServerChangeCipherSpecResume (session, client_ctx, server_ctx, log @ [raw]) in
({ state with protocol_version = sh.server_version ; machina = Client machina }, [])
| _ -> common_server_hello_machina state sh ch raw log
let answer_server_hello_renegotiate state session (ch : client_hello) sh raw log =
common_server_hello_validation state.config (Some session.renegotiation) sh ch >>= fun () ->
guard (state.protocol_version = sh.server_version)
(`Fatal (`InvalidRenegotiationVersion sh.server_version)) >|= fun () ->
common_server_hello_machina state sh ch raw log
let validate_keytype_usage certificate ciphersuite =
let keytype, usage =
Ciphersuite.(o required_keytype_and_usage ciphersuite_kex ciphersuite)
in
match certificate with
| None -> fail (`Fatal `NoCertificateReceived)
| Some cert ->
let open X509 in
guard (supports_keytype cert keytype)
(`Fatal `NotRSACertificate) >>= fun () ->
guard (Extension.supports_usage ~not_present:true cert usage)
(`Fatal `InvalidCertificateUsage) >>= fun () ->
guard
(Extension.supports_extended_usage cert `Server_auth ||
Extension.supports_extended_usage ~not_present:true cert `Any)
(`Fatal `InvalidCertificateExtendedUsage)
let answer_certificate_RSA state session cs raw log =
let cfg = state.config in
let peer_name = match cfg.peer_name with
| None -> None
| Some x -> Some (`Wildcard x)
in
validate_chain cfg.authenticator cs peer_name >>= fun (peer_certificate, received_certificates, peer_certificate_chain, trust_anchor) ->
validate_keytype_usage peer_certificate session.ciphersuite >>= fun () ->
let session = { session with received_certificates ; peer_certificate ; peer_certificate_chain ; trust_anchor } in
( match session.client_version with
| Supported v -> return v
) >>= fun version ->
let ver = Writer.assemble_protocol_version version in
let premaster = ver <+> Rng.generate 46 in
peer_rsa_key peer_certificate >|= fun pubkey ->
let kex = Rsa.PKCS1.encrypt ~key:pubkey premaster
in
let machina =
AwaitCertificateRequestOrServerHelloDone
(session, kex, premaster, log @ [raw])
in
({ state with machina = Client machina }, [])
let answer_certificate_DHE_RSA state session cs raw log =
let peer_name = match state.config.peer_name with
| None -> None
| Some x -> Some (`Wildcard x)
in
validate_chain state.config.authenticator cs peer_name >>= fun (peer_certificate, received_certificates, peer_certificate_chain, trust_anchor) ->
validate_keytype_usage peer_certificate session.ciphersuite >|= fun () ->
let session = { session with received_certificates ; peer_certificate ; peer_certificate_chain ; trust_anchor } in
let machina = AwaitServerKeyExchange_DHE_RSA (session, log @ [raw]) in
({ state with machina = Client machina }, [])
let answer_server_key_exchange_DHE_RSA state session kex raw log =
let dh_params kex =
match Reader.parse_dh_parameters kex with
| Ok data -> return data
| Error re -> fail (`Fatal (`ReaderError re))
in
dh_params kex >>= fun (dh_params, raw_dh_params, leftover) ->
let sigdata = session.client_random <+> session.server_random <+> raw_dh_params in
verify_digitally_signed state.protocol_version state.config.hashes leftover sigdata session.peer_certificate >>= fun () ->
let group, shared = Crypto.dh_params_unpack dh_params in
guard (Dh.modulus_size group >= Config.min_dh_size) (`Fatal `InvalidDH)
>>= fun () ->
let secret, kex = Dh.gen_key group in
match Dh.shared group secret shared with
| None -> fail (`Fatal `InvalidDH)
| Some pms -> let machina =
AwaitCertificateRequestOrServerHelloDone
(session, kex, pms, log @ [raw])
in
return ({ state with machina = Client machina }, [])
let answer_certificate_request state session cr kex pms raw log =
let cfg = state.config in
( match state.protocol_version with
| TLS_1_0 | TLS_1_1 ->
( match Reader.parse_certificate_request cr with
| Ok (types, cas) -> return (types, None, cas)
| Error re -> fail (`Fatal (`ReaderError re)) )
| TLS_1_2 ->
( match Reader.parse_certificate_request_1_2 cr with
| Ok (types, sigalgs, cas) -> return (types, Some sigalgs, cas)
| Error re -> fail (`Fatal (`ReaderError re)) )
) >|= fun (types, sigalgs, _cas) ->
let own_certificate, own_private_key =
match
List.mem Packet.RSA_SIGN types,
cfg.own_certificates
with
| true, `Single (chain, priv) -> (chain, Some priv)
| _ -> ([], None)
in
let session = {
session with
own_certificate ;
own_private_key ;
client_auth = true
} in
let machina = AwaitServerHelloDone (session, sigalgs, kex, pms, log @ [raw]) in
({ state with machina = Client machina }, [])
let answer_server_hello_done state session sigalgs kex premaster raw log =
let kex = ClientKeyExchange kex in
let ckex = Writer.assemble_handshake kex in
( match session.client_auth, session.own_private_key with
| true, Some p ->
let cert = Certificate (List.map X509.Encoding.cs_of_cert session.own_certificate) in
let ccert = Writer.assemble_handshake cert in
let to_sign = log @ [ raw ; ccert ; ckex ] in
let data = Cs.appends to_sign in
let ver = state.protocol_version
and my_sigalgs = state.config.hashes in
signature ver data sigalgs my_sigalgs p >|= fun (signature) ->
let cert_verify = CertificateVerify signature in
let ccert_verify = Writer.assemble_handshake cert_verify in
([ cert ; kex ; cert_verify ],
[ ccert ; ckex ; ccert_verify ],
to_sign, Some ccert_verify)
| true, None ->
let cert = Certificate [] in
let ccert = Writer.assemble_handshake cert in
return ([cert ; kex], [ccert ; ckex], log @ [ raw ; ccert ; ckex ], None)
| false, _ ->
return ([kex], [ckex], log @ [ raw ; ckex ], None) )
>|= fun (_msgs, raw_msgs, raws, cert_verify) ->
let to_fin = raws @ option [] (fun x -> [x]) cert_verify in
let master_secret =
Handshake_crypto.derive_master_secret state.protocol_version session premaster raws
in
let session = { session with master_secret } in
let client_ctx, server_ctx =
Handshake_crypto.initialise_crypto_ctx state.protocol_version session
in
let checksum = Handshake_crypto.finished state.protocol_version session.ciphersuite master_secret "client finished" to_fin in
let fin = Finished checksum in
let raw_fin = Writer.assemble_handshake fin in
let ps = to_fin @ [raw_fin] in
let session = { session with master_secret = master_secret } in
let machina = AwaitServerChangeCipherSpec (session, server_ctx, checksum, ps)
and ccst, ccs = change_cipher_spec in
List.iter ( Tracing.sexpf ~tag:"handshake - out " ~f : sexp_of_tls_handshake ) msgs ;
Tracing.cs ~tag:"change-cipher-spec-out" ccs ;
Tracing.sexpf ~tag:"handshake - out " ~f : sexp_of_tls_handshake fin ;
({ state with machina = Client machina },
List.map (fun x -> `Record (Packet.HANDSHAKE, x)) raw_msgs @
[ `Record (ccst, ccs);
`Change_enc (Some client_ctx);
`Record (Packet.HANDSHAKE, raw_fin)])
let answer_server_finished state session client_verify fin log =
let computed =
Handshake_crypto.finished state.protocol_version session.ciphersuite session.master_secret "server finished" log
in
guard (Cs.equal computed fin) (`Fatal `BadFinished) >>= fun () ->
guard (Cs.null state.hs_fragment) (`Fatal `HandshakeFragmentsNotEmpty) >|= fun () ->
let machina = Established
and session = { session with renegotiation = (client_verify, computed) } in
({ state with machina = Client machina ; session = session :: state.session }, [])
let answer_server_finished_resume state session fin raw log =
let client, server =
let checksum = Handshake_crypto.finished state.protocol_version session.ciphersuite session.master_secret in
(checksum "client finished" (log @ [raw]), checksum "server finished" log)
in
guard (Cs.equal server fin) (`Fatal `BadFinished) >>= fun () ->
guard (Cs.null state.hs_fragment) (`Fatal `HandshakeFragmentsNotEmpty) >|= fun () ->
let machina = Established
and session = { session with renegotiation = (client, server) }
in
let finished = Finished client in
let raw_finished = Writer.assemble_handshake finished in
({ state with machina = Client machina ; session = session :: state.session },
[`Record (Packet.HANDSHAKE, raw_finished)])
let answer_hello_request state =
let produce_client_hello session config exts =
let dch, _ = default_client_hello config in
let ch = { dch with extensions = dch.extensions @ exts ; sessionid = None } in
let raw = Writer.assemble_handshake (ClientHello ch) in
let machina = AwaitServerHelloRenegotiate (session, ch, [raw]) in
Tracing.sexpf ~tag:"handshake - out " ~f : sexp_of_tls_handshake ( ClientHello ch ) ;
({ state with machina = Client machina }, [`Record (Packet.HANDSHAKE, raw)])
in
match state.config.use_reneg, state.session with
| true , x :: _ ->
let ext = `SecureRenegotiation (fst x.renegotiation) in
return (produce_client_hello x state.config [ext])
| false, _ ->
let no_reneg = Writer.assemble_alert ~level:Packet.WARNING Packet.NO_RENEGOTIATION in
return (state, [`Record (Packet.ALERT, no_reneg)])
let handle_change_cipher_spec cs state packet =
match Reader.parse_change_cipher_spec packet, cs with
| Ok (), AwaitServerChangeCipherSpec (session, server_ctx, client_verify, log) ->
guard (Cs.null state.hs_fragment) (`Fatal `HandshakeFragmentsNotEmpty) >|= fun () ->
let machina = AwaitServerFinished (session, client_verify, log) in
Tracing.cs ~tag:"change-cipher-spec-in" packet ;
({ state with machina = Client machina }, [`Change_dec (Some server_ctx)])
| Ok (), AwaitServerChangeCipherSpecResume (session, client_ctx, server_ctx, log) ->
guard (Cs.null state.hs_fragment) (`Fatal `HandshakeFragmentsNotEmpty) >|= fun () ->
let ccs = change_cipher_spec in
let machina = AwaitServerFinishedResume (session, log) in
Tracing.cs ~tag:"change-cipher-spec-in" packet ;
Tracing.cs ~tag:"change-cipher-spec-out" packet ;
({ state with machina = Client machina },
[`Record ccs ; `Change_enc (Some client_ctx); `Change_dec (Some server_ctx)])
| Error re, _ -> fail (`Fatal (`ReaderError re))
| _ -> fail (`Fatal `UnexpectedCCS)
let handle_handshake cs hs buf =
let open Reader in
match parse_handshake buf with
| Ok handshake ->
Tracing.sexpf ~tag:"handshake - in " ~f : sexp_of_tls_handshake handshake ;
( match cs, handshake with
| AwaitServerHello (ch, log), ServerHello sh ->
answer_server_hello hs ch sh buf log
| AwaitServerHelloRenegotiate (session, ch, log), ServerHello sh ->
answer_server_hello_renegotiate hs session ch sh buf log
| AwaitCertificate_RSA (session, log), Certificate cs ->
answer_certificate_RSA hs session cs buf log
| AwaitCertificate_DHE_RSA (session, log), Certificate cs ->
answer_certificate_DHE_RSA hs session cs buf log
| AwaitServerKeyExchange_DHE_RSA (session, log), ServerKeyExchange kex ->
answer_server_key_exchange_DHE_RSA hs session kex buf log
| AwaitCertificateRequestOrServerHelloDone (session, kex, pms, log), CertificateRequest cr ->
answer_certificate_request hs session cr kex pms buf log
| AwaitCertificateRequestOrServerHelloDone (session, kex, pms, log), ServerHelloDone ->
answer_server_hello_done hs session None kex pms buf log
| AwaitServerHelloDone (session, sigalgs, kex, pms, log), ServerHelloDone ->
answer_server_hello_done hs session sigalgs kex pms buf log
| AwaitServerFinished (session, client_verify, log), Finished fin ->
answer_server_finished hs session client_verify fin log
| AwaitServerFinishedResume (session, log), Finished fin ->
answer_server_finished_resume hs session fin buf log
| Established, HelloRequest ->
answer_hello_request hs
| _, hs -> fail (`Fatal (`UnexpectedHandshake hs)) )
| Error re -> fail (`Fatal (`ReaderError re))
|
c26b22ee7c0e01d4c4b354f8eea654c4bb16ec94a5a2e6d32d0b9c532a09d22e | igrishaev/pact | comp_future.clj | (ns pact.comp-future
(:refer-clojure :exclude [future])
(:require
[pact.core :as p])
(:import
java.util.function.Function
java.util.function.Supplier
java.util.concurrent.CompletableFuture))
(extend-protocol p/IPact
CompletableFuture
(-then [this func]
(.thenApply this (reify Function
(apply [_ x]
(func x)))))
(-error [this func]
(.exceptionally this (reify Function
(apply [_ e]
(func (ex-cause e)))))))
(defmacro future [& body]
`(CompletableFuture/supplyAsync (reify Supplier
(get [_]
~@body))))
| null | https://raw.githubusercontent.com/igrishaev/pact/fe084b86bfb0d3d1f6bcfdff8fc3e5217d046fe9/src/pact/comp_future.clj | clojure | (ns pact.comp-future
(:refer-clojure :exclude [future])
(:require
[pact.core :as p])
(:import
java.util.function.Function
java.util.function.Supplier
java.util.concurrent.CompletableFuture))
(extend-protocol p/IPact
CompletableFuture
(-then [this func]
(.thenApply this (reify Function
(apply [_ x]
(func x)))))
(-error [this func]
(.exceptionally this (reify Function
(apply [_ e]
(func (ex-cause e)))))))
(defmacro future [& body]
`(CompletableFuture/supplyAsync (reify Supplier
(get [_]
~@body))))
| |
4a5d3132ead879cf2808048844806e47e1568a19d21bce8f88a48632269d4281 | kumarshantanu/quiddity | core.cljc | 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 LICENSE 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 quiddity.core
"Core evaluation functions."
(:require
[quiddity.internal :as i])
#?(:clj (:import
[clojure.lang IDeref])))
(defn env-get
"Look up the given key in a collection of supplied maps, and return the value. Absence of the key in all maps amounts
to an error."
[k maps]
(let [r (some (fn [m]
(or (and (symbol? k)
(let [kw (keyword k)]
(and (contains? m kw) [(get m kw)])))
(and (contains? m k) [(get m k)])))
maps)]
(if r (first r)
(i/*error-handler* (i/sformat "No such key '%s' in env keys %s" (str k)
(pr-str (map keys maps)))))))
(defn evaluator?
"Return `true` if given argument is an evaluator, `false` otherwise."
[f]
(and (vector? f)
(true? (:quiddity-evaluator? (meta f)))))
(defn make-evaluator
"Create a tagged evaluator."
[x]
(if (evaluator? x) x
(->> {:quiddity-evaluator? true}
(with-meta [x]))))
(defn evaluate
"Evaluate S-expression using specified env maps. Options:
| Kwargs | Value type | Description |
|-------------------|------------------|-------------------------|
|`:error-handler` |`(fn [msg])` | Error handler function |
|`:stop-evaluation?`|deref'able boolean| Whether stop evaluation |"
([form maps]
{:pre [(every? map? maps)]}
(or
(i/stop-if-requested)
(cond
;; symbol, hence lookup in env
(symbol? form) (env-get form maps)
;; function call
(and (or (list? form)
(seq? form))
(seq form)) (let [func (evaluate (first form) maps)
tail (rest form)]
(if (evaluator? func)
(apply (first func) maps tail)
(apply func (i/realize-coll tail maps evaluate))))
;; any collection
(coll? form) (i/realize-coll form maps evaluate)
;; constant
:otherwise form)))
([form maps {:keys [error-handler
stop-evaluation?]
:as options}]
(cond
error-handler (binding [i/*error-handler* error-handler]
(evaluate form maps (dissoc options :error-handler)))
stop-evaluation? (binding [i/*stop-evaluation?* stop-evaluation?]
(evaluate form maps (dissoc options :stop-evaluation?)))
:otherwise (evaluate form maps))))
| null | https://raw.githubusercontent.com/kumarshantanu/quiddity/834f8fe18194f1038909211e0e55464535f68c47/src/quiddity/core.cljc | 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 LICENSE 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.
symbol, hence lookup in env
function call
any collection
constant | Copyright ( c ) . All rights reserved .
(ns quiddity.core
"Core evaluation functions."
(:require
[quiddity.internal :as i])
#?(:clj (:import
[clojure.lang IDeref])))
(defn env-get
"Look up the given key in a collection of supplied maps, and return the value. Absence of the key in all maps amounts
to an error."
[k maps]
(let [r (some (fn [m]
(or (and (symbol? k)
(let [kw (keyword k)]
(and (contains? m kw) [(get m kw)])))
(and (contains? m k) [(get m k)])))
maps)]
(if r (first r)
(i/*error-handler* (i/sformat "No such key '%s' in env keys %s" (str k)
(pr-str (map keys maps)))))))
(defn evaluator?
"Return `true` if given argument is an evaluator, `false` otherwise."
[f]
(and (vector? f)
(true? (:quiddity-evaluator? (meta f)))))
(defn make-evaluator
"Create a tagged evaluator."
[x]
(if (evaluator? x) x
(->> {:quiddity-evaluator? true}
(with-meta [x]))))
(defn evaluate
"Evaluate S-expression using specified env maps. Options:
| Kwargs | Value type | Description |
|-------------------|------------------|-------------------------|
|`:error-handler` |`(fn [msg])` | Error handler function |
|`:stop-evaluation?`|deref'able boolean| Whether stop evaluation |"
([form maps]
{:pre [(every? map? maps)]}
(or
(i/stop-if-requested)
(cond
(symbol? form) (env-get form maps)
(and (or (list? form)
(seq? form))
(seq form)) (let [func (evaluate (first form) maps)
tail (rest form)]
(if (evaluator? func)
(apply (first func) maps tail)
(apply func (i/realize-coll tail maps evaluate))))
(coll? form) (i/realize-coll form maps evaluate)
:otherwise form)))
([form maps {:keys [error-handler
stop-evaluation?]
:as options}]
(cond
error-handler (binding [i/*error-handler* error-handler]
(evaluate form maps (dissoc options :error-handler)))
stop-evaluation? (binding [i/*stop-evaluation?* stop-evaluation?]
(evaluate form maps (dissoc options :stop-evaluation?)))
:otherwise (evaluate form maps))))
|
123c7dfe4a85a5716fe50e4b6c943cd8554ca58ce08c7f81fa230e7cb65f7dd6 | litaocheng/erl-test | msgflood.erl | %%%
%%% server start:
$ erl -sname srv
%%% > msgflood:server(flood).
%%%
%%% client start:
%%% $ erl -sname client
> msgflood : client(srv@litao , flood ) .
%%%
-module(msgflood).
-compile([export_all]).
%% 启动server
server(Server) ->
true = is_alive(),
register(Server, spawn_link(?MODULE, srv_loop, [self()])),
io:format("Server ~p is running (from ~p)...~n", [Server, self()]),
receive
complete ->
ok
end,
init:stop().
srv_loop(Parent) ->
process_flag(trap_exit, true),
receive
{'EXIT', _, shutdown} ->
ok;
first msg
T1 = now(),
N = srv_loop1(1),
T2 = now(),
T = timer:now_diff(T2, T1),
io:format("receive msg : ~p~ntime:~p (micro sec)~nspeed:~p~n",
[N, T, N * 1000000 / T]),
Parent ! complete
end.
srv_loop1(N) ->
receive
{'EXIT', _, shutdown} ->
N;
stop ->
N;
{From, _Msg} ->
From ! {ack, _Msg},
srv_loop1(N+1)
end.
%% 启动client(节点内)
client(Server) ->
client(none, Server).
%% 启动client(节点间)
client(Node, Server) ->
case Node of
none ->
Dest = Server;
_ ->
true = is_alive(),
true = net_kernel:connect_node(Node),
Dest = {Server, Node}
end,
Pid = spawn_link(?MODULE, send_loop, [self(), Dest]),
io:get_line("press any key stop..."),
exit(Pid, shutdown),
receive
complete ->
ok
after 5000 ->
ok
end,
init:stop().
send_loop(Parent, Server) ->
process_flag(trap_exit, true),
T1 = now(),
N = send_loop1(Server, 0),
T2 = now(),
T = timer:now_diff(T2, T1),
io:format("send msg : ~p~ntime:~p (micro sec)~nspeed:~p~n",
[N, T, N * 1000000 / T]),
Parent ! complete.
send_loop1(Server, N) ->
%Server ! <<"hello">>,
Server ! {self(), <<"hello">>},
receive
{ack, _} ->
send_loop1(Server, N+1);
{'EXIT', _, shutdown} ->
Server ! stop,
N
after 0 ->
send_loop1(Server, N+1)
end.
| null | https://raw.githubusercontent.com/litaocheng/erl-test/893679fccb1c16dda45d40d2b9e12d78db991b8a/msgflood/msgflood.erl | erlang |
server start:
> msgflood:server(flood).
client start:
$ erl -sname client
启动server
启动client(节点内)
启动client(节点间)
Server ! <<"hello">>, | $ erl -sname srv
> msgflood : client(srv@litao , flood ) .
-module(msgflood).
-compile([export_all]).
server(Server) ->
true = is_alive(),
register(Server, spawn_link(?MODULE, srv_loop, [self()])),
io:format("Server ~p is running (from ~p)...~n", [Server, self()]),
receive
complete ->
ok
end,
init:stop().
srv_loop(Parent) ->
process_flag(trap_exit, true),
receive
{'EXIT', _, shutdown} ->
ok;
first msg
T1 = now(),
N = srv_loop1(1),
T2 = now(),
T = timer:now_diff(T2, T1),
io:format("receive msg : ~p~ntime:~p (micro sec)~nspeed:~p~n",
[N, T, N * 1000000 / T]),
Parent ! complete
end.
srv_loop1(N) ->
receive
{'EXIT', _, shutdown} ->
N;
stop ->
N;
{From, _Msg} ->
From ! {ack, _Msg},
srv_loop1(N+1)
end.
client(Server) ->
client(none, Server).
client(Node, Server) ->
case Node of
none ->
Dest = Server;
_ ->
true = is_alive(),
true = net_kernel:connect_node(Node),
Dest = {Server, Node}
end,
Pid = spawn_link(?MODULE, send_loop, [self(), Dest]),
io:get_line("press any key stop..."),
exit(Pid, shutdown),
receive
complete ->
ok
after 5000 ->
ok
end,
init:stop().
send_loop(Parent, Server) ->
process_flag(trap_exit, true),
T1 = now(),
N = send_loop1(Server, 0),
T2 = now(),
T = timer:now_diff(T2, T1),
io:format("send msg : ~p~ntime:~p (micro sec)~nspeed:~p~n",
[N, T, N * 1000000 / T]),
Parent ! complete.
send_loop1(Server, N) ->
Server ! {self(), <<"hello">>},
receive
{ack, _} ->
send_loop1(Server, N+1);
{'EXIT', _, shutdown} ->
Server ! stop,
N
after 0 ->
send_loop1(Server, N+1)
end.
|
40b0f46a5dd1d7a8f322fe0a4090b010189001b0a52070b4404d96fa22cb4abe | haskell/hackage-server | Parsers.hs | # , OverloadedStrings , TupleSections #
module Distribution.Server.Features.Browse.Parsers
( Condition(..)
, DeprecatedOption(..)
, Filter(..)
, Operator(..)
, conditions
, condsToFiltersAndTerms
, filterOrSearchTerms
, operatorToFunction
, searchTerms
) where
import Prelude hiding (Ordering(..), filter)
import Control.Applicative ((<|>))
import Control.Monad (guard, join)
import Data.Foldable (asum)
import Data.Time (Day, NominalDiffTime, nominalDay)
import GHC.Float (double2Float)
import Data.Attoparsec.Text
import Data.Attoparsec.Time (day)
import Data.Text (Text)
data DeprecatedOption
= OnlyDeprecated
| ExcludeDeprecated
| Don'tCareAboutDeprecated
deriving (Show, Eq)
data Filter
= DownloadsFilter (Operator, Word)
| RatingFilter (Operator, Float)
| LastUploadFilter (Operator, Day)
| AgeLastULFilter (Operator, NominalDiffTime)
| TagFilter String
| MaintainerFilter String
| DeprecatedFilter DeprecatedOption
| DistroFilter String
| Not Filter
deriving (Show, Eq)
data Operator = LT | LTE | GT | GTE | EQ | NEQ
deriving (Show, Eq)
deprecatedOption :: Parser DeprecatedOption
deprecatedOption =
asum
[ "any" *> pure Don'tCareAboutDeprecated
, ("false" <|> "no") *> pure ExcludeDeprecated
, ("true" <|> "yes") *> pure OnlyDeprecated
]
operatorToFunction :: Ord a => Operator -> a -> (a -> Bool)
operatorToFunction LT a = (a <)
operatorToFunction LTE a = (a <=)
operatorToFunction GT a = (a >)
operatorToFunction GTE a = (a >=)
operatorToFunction EQ a = (a ==)
operatorToFunction NEQ a = (a /=)
data Condition = FilterCond Filter | SearchTermCond String
deriving (Show, Eq)
condsToFiltersAndTerms :: [Condition] -> ([Filter], [String])
condsToFiltersAndTerms conds =
([x | FilterCond x <- conds], [x | SearchTermCond x <- conds])
opAndSndParam :: Ord a => Parser a -> Parser (Operator, a)
opAndSndParam parser = do
let mkParser op = skipSpace *> fmap (op,) parser
lt = "<" *> mkParser LT
gt = ">" *> mkParser GT
gte = ">=" *> mkParser GTE
lte = "<=" *> mkParser LTE
eq = "=" *> mkParser EQ
longEq = "==" *> mkParser EQ
neq = "/=" *> mkParser NEQ
cStyleNeq = "!=" *> mkParser NEQ
in asum [lt, gt, gte, lte, eq, longEq, neq, cStyleNeq]
allowedAfterOpeningBrace :: AllowNot -> Parser Text
allowedAfterOpeningBrace AllowNot = "not " <|> allowedAfterOpeningBrace DisallowNot
allowedAfterOpeningBrace _ =
asum
[ "downloads", "rating", "lastUpload" , "ageOfLastUpload"
, "tag:", "maintainer:", "deprecated:", "distro:"
]
-- Whether the 'not' operator can be used.
-- (used to prevent recursive parsing)
data AllowNot = AllowNot | DisallowNot
filterWith :: AllowNot -> Parser Filter
filterWith allowNot = do
fieldName <- allowedAfterOpeningBrace allowNot
if fieldName == "not "
then Not <$> filterWith DisallowNot
else do
skipSpace
let nonNegativeFloat :: Parser Float
nonNegativeFloat = do
float <- double2Float <$> double
guard $ float >= 0
pure float
filt <- case fieldName of
"downloads" -> DownloadsFilter <$> opAndSndParam decimal
"rating" -> RatingFilter <$> opAndSndParam nonNegativeFloat
"lastUpload" -> LastUploadFilter <$> opAndSndParam day
"ageOfLastUpload" -> AgeLastULFilter <$> opAndSndParam nominalDiffTime
"tag:" -> TagFilter <$> wordWoSpaceOrParens
"maintainer:" -> MaintainerFilter <$> wordWoSpaceOrParens
"deprecated:" -> DeprecatedFilter <$> deprecatedOption
"distro:" -> DistroFilter <$> wordWoSpaceOrParens
_ -> fail "Impossible since fieldName possibilities are known at compile time"
pure filt
filter :: Parser [Condition]
filter = do
filt <- filterWith AllowNot
pure [FilterCond filt]
filterOrSearchTerms :: Parser [Condition]
filterOrSearchTerms =
asum
[ do
_ <- "("
skipSpace
filt <- filter <|> searchTerms <|> pure []
skipSpace
_ <- ")"
pure filt
, searchTerms
]
searchTerms :: Parser [Condition]
searchTerms = sepBy1 searchTerm (many1 space)
-- The search engine accepts terms with spaces or parenthesis in them also but
-- we do not allow that, just to keep this parser simple.
searchTerm :: Parser Condition
searchTerm = fmap SearchTermCond wordWoSpaceOrParens
wordWoSpaceOrParens :: Parser String
wordWoSpaceOrParens = many1 . satisfy $ notInClass " ()"
conditions :: Parser [Condition]
conditions = fmap join . many' $ skipSpace *> filterOrSearchTerms
nominalDiffTime :: Parser NominalDiffTime
nominalDiffTime = do
num <- double
guard (num > 0)
skipSpace
lengthSpecifier <- "d" <|> "w" <|> "m" <|> "y"
let days = realToFrac num * nominalDay
case lengthSpecifier of
"d" -> pure days
"w" -> pure (days * 7)
"m" -> pure (days * 30.437) -- Average month length
"y" -> pure (days * 365.25) -- Average year length
_ -> fail "Impossible since lengthSpecifier possibilities are known at compile time"
| null | https://raw.githubusercontent.com/haskell/hackage-server/a22f92d8df358707d7755630e61df9ab8ae7bba8/src/Distribution/Server/Features/Browse/Parsers.hs | haskell | Whether the 'not' operator can be used.
(used to prevent recursive parsing)
The search engine accepts terms with spaces or parenthesis in them also but
we do not allow that, just to keep this parser simple.
Average month length
Average year length | # , OverloadedStrings , TupleSections #
module Distribution.Server.Features.Browse.Parsers
( Condition(..)
, DeprecatedOption(..)
, Filter(..)
, Operator(..)
, conditions
, condsToFiltersAndTerms
, filterOrSearchTerms
, operatorToFunction
, searchTerms
) where
import Prelude hiding (Ordering(..), filter)
import Control.Applicative ((<|>))
import Control.Monad (guard, join)
import Data.Foldable (asum)
import Data.Time (Day, NominalDiffTime, nominalDay)
import GHC.Float (double2Float)
import Data.Attoparsec.Text
import Data.Attoparsec.Time (day)
import Data.Text (Text)
data DeprecatedOption
= OnlyDeprecated
| ExcludeDeprecated
| Don'tCareAboutDeprecated
deriving (Show, Eq)
data Filter
= DownloadsFilter (Operator, Word)
| RatingFilter (Operator, Float)
| LastUploadFilter (Operator, Day)
| AgeLastULFilter (Operator, NominalDiffTime)
| TagFilter String
| MaintainerFilter String
| DeprecatedFilter DeprecatedOption
| DistroFilter String
| Not Filter
deriving (Show, Eq)
data Operator = LT | LTE | GT | GTE | EQ | NEQ
deriving (Show, Eq)
deprecatedOption :: Parser DeprecatedOption
deprecatedOption =
asum
[ "any" *> pure Don'tCareAboutDeprecated
, ("false" <|> "no") *> pure ExcludeDeprecated
, ("true" <|> "yes") *> pure OnlyDeprecated
]
operatorToFunction :: Ord a => Operator -> a -> (a -> Bool)
operatorToFunction LT a = (a <)
operatorToFunction LTE a = (a <=)
operatorToFunction GT a = (a >)
operatorToFunction GTE a = (a >=)
operatorToFunction EQ a = (a ==)
operatorToFunction NEQ a = (a /=)
data Condition = FilterCond Filter | SearchTermCond String
deriving (Show, Eq)
condsToFiltersAndTerms :: [Condition] -> ([Filter], [String])
condsToFiltersAndTerms conds =
([x | FilterCond x <- conds], [x | SearchTermCond x <- conds])
opAndSndParam :: Ord a => Parser a -> Parser (Operator, a)
opAndSndParam parser = do
let mkParser op = skipSpace *> fmap (op,) parser
lt = "<" *> mkParser LT
gt = ">" *> mkParser GT
gte = ">=" *> mkParser GTE
lte = "<=" *> mkParser LTE
eq = "=" *> mkParser EQ
longEq = "==" *> mkParser EQ
neq = "/=" *> mkParser NEQ
cStyleNeq = "!=" *> mkParser NEQ
in asum [lt, gt, gte, lte, eq, longEq, neq, cStyleNeq]
allowedAfterOpeningBrace :: AllowNot -> Parser Text
allowedAfterOpeningBrace AllowNot = "not " <|> allowedAfterOpeningBrace DisallowNot
allowedAfterOpeningBrace _ =
asum
[ "downloads", "rating", "lastUpload" , "ageOfLastUpload"
, "tag:", "maintainer:", "deprecated:", "distro:"
]
data AllowNot = AllowNot | DisallowNot
filterWith :: AllowNot -> Parser Filter
filterWith allowNot = do
fieldName <- allowedAfterOpeningBrace allowNot
if fieldName == "not "
then Not <$> filterWith DisallowNot
else do
skipSpace
let nonNegativeFloat :: Parser Float
nonNegativeFloat = do
float <- double2Float <$> double
guard $ float >= 0
pure float
filt <- case fieldName of
"downloads" -> DownloadsFilter <$> opAndSndParam decimal
"rating" -> RatingFilter <$> opAndSndParam nonNegativeFloat
"lastUpload" -> LastUploadFilter <$> opAndSndParam day
"ageOfLastUpload" -> AgeLastULFilter <$> opAndSndParam nominalDiffTime
"tag:" -> TagFilter <$> wordWoSpaceOrParens
"maintainer:" -> MaintainerFilter <$> wordWoSpaceOrParens
"deprecated:" -> DeprecatedFilter <$> deprecatedOption
"distro:" -> DistroFilter <$> wordWoSpaceOrParens
_ -> fail "Impossible since fieldName possibilities are known at compile time"
pure filt
filter :: Parser [Condition]
filter = do
filt <- filterWith AllowNot
pure [FilterCond filt]
filterOrSearchTerms :: Parser [Condition]
filterOrSearchTerms =
asum
[ do
_ <- "("
skipSpace
filt <- filter <|> searchTerms <|> pure []
skipSpace
_ <- ")"
pure filt
, searchTerms
]
searchTerms :: Parser [Condition]
searchTerms = sepBy1 searchTerm (many1 space)
searchTerm :: Parser Condition
searchTerm = fmap SearchTermCond wordWoSpaceOrParens
wordWoSpaceOrParens :: Parser String
wordWoSpaceOrParens = many1 . satisfy $ notInClass " ()"
conditions :: Parser [Condition]
conditions = fmap join . many' $ skipSpace *> filterOrSearchTerms
nominalDiffTime :: Parser NominalDiffTime
nominalDiffTime = do
num <- double
guard (num > 0)
skipSpace
lengthSpecifier <- "d" <|> "w" <|> "m" <|> "y"
let days = realToFrac num * nominalDay
case lengthSpecifier of
"d" -> pure days
"w" -> pure (days * 7)
_ -> fail "Impossible since lengthSpecifier possibilities are known at compile time"
|
6f7a9395cb1cefd50886a1de3f43af0ddf8b800017ade004f3fd484203e03b02 | huangz1990/SICP-answers | assertions.scm | ;;; ----------------------------------------------------------------------
Copyright 2007 - 2009 .
;;; ----------------------------------------------------------------------
;;; This file is part of Test Manager.
;;;
;;; Test Manager is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;; (at your option) any later version.
;;;
;;; Test Manager 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 Test Manager. If not, see </>.
;;; ----------------------------------------------------------------------
(define (ensure-forced object)
(if (promise? object)
(force object)
object))
(define (instantiate-template template arguments)
(if (not (= (length arguments) (- (length template) 1)))
(error "Template and argument lists are length-mismatched: "
template arguments))
(let loop ((result (car template))
(template (cdr template))
(arguments arguments))
(if (null? template)
result
(loop (string-append result (car arguments) (car template))
(cdr template)
(cdr arguments)))))
(define (messagify object)
(with-output-to-string (lambda () (display object))))
(define (build-message header template . arguments)
(delay
(let ((body (instantiate-template template (map messagify arguments))))
(if header
(string-append (messagify (ensure-forced header)) "\n" body)
(string-append "\n" body)))))
(define (assert-proc message proc)
(if (proc)
'ok
(test-fail (messagify (ensure-forced message)))))
(define (assert-equivalent predicate . opt-pred-name)
(define (full-message message expected actual)
(if (null? opt-pred-name)
(build-message message
'("<" "> expected but was\n<" ">.")
expected actual)
(build-message message
'("<" "> expected to be " " to\n<"
">.")
expected (car opt-pred-name) actual)))
(lambda (expected actual . opt-message)
(let-optional
opt-message ((message #f))
(assert-proc (full-message message expected actual)
(lambda () (predicate expected actual))))))
(define assert-eq (assert-equivalent eq? "eq?"))
(define assert-eqv (assert-equivalent eqv? "eqv?"))
(define assert-equal (assert-equivalent equal? "equal?"))
(define assert-= (assert-equivalent = "="))
(define assert-equals assert-equal)
(define assert= assert-=)
(define assert-< (assert-equivalent < "<"))
(define assert-> (assert-equivalent > ">"))
(define assert-<= (assert-equivalent <= "<="))
(define assert->= (assert-equivalent >= ">="))
(define (assert-in-delta expected actual delta . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> and\n<" "> expected to be within\n<"
"> of each other.")
expected actual delta)))
(assert-proc full-message (lambda () (<= (abs (- expected actual)) delta))))))
(define (assert-matches regexp string . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> expected to match <" ">")
string regexp)))
(assert-proc full-message
(lambda ()
(generic-match regexp string))))))
;; TODO how repetitive!
(define (assert-no-match regexp string . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> expected not to match <" ">")
string regexp)))
(assert-proc full-message
(lambda ()
(not (generic-match regexp string)))))))
(define (assert-true thing . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> expected to be a true value.")
thing)))
(assert-proc full-message (lambda () thing)))))
(define (assert-false thing . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> expected to be a false value.")
thing)))
(assert-proc full-message (lambda () (not thing))))))
| null | https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/test-manager/assertions.scm | scheme | ----------------------------------------------------------------------
----------------------------------------------------------------------
This file is part of Test Manager.
Test Manager is free software; you can redistribute it and/or modify
(at your option) any later version.
Test Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with Test Manager. If not, see </>.
----------------------------------------------------------------------
TODO how repetitive! | Copyright 2007 - 2009 .
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(define (ensure-forced object)
(if (promise? object)
(force object)
object))
(define (instantiate-template template arguments)
(if (not (= (length arguments) (- (length template) 1)))
(error "Template and argument lists are length-mismatched: "
template arguments))
(let loop ((result (car template))
(template (cdr template))
(arguments arguments))
(if (null? template)
result
(loop (string-append result (car arguments) (car template))
(cdr template)
(cdr arguments)))))
(define (messagify object)
(with-output-to-string (lambda () (display object))))
(define (build-message header template . arguments)
(delay
(let ((body (instantiate-template template (map messagify arguments))))
(if header
(string-append (messagify (ensure-forced header)) "\n" body)
(string-append "\n" body)))))
(define (assert-proc message proc)
(if (proc)
'ok
(test-fail (messagify (ensure-forced message)))))
(define (assert-equivalent predicate . opt-pred-name)
(define (full-message message expected actual)
(if (null? opt-pred-name)
(build-message message
'("<" "> expected but was\n<" ">.")
expected actual)
(build-message message
'("<" "> expected to be " " to\n<"
">.")
expected (car opt-pred-name) actual)))
(lambda (expected actual . opt-message)
(let-optional
opt-message ((message #f))
(assert-proc (full-message message expected actual)
(lambda () (predicate expected actual))))))
(define assert-eq (assert-equivalent eq? "eq?"))
(define assert-eqv (assert-equivalent eqv? "eqv?"))
(define assert-equal (assert-equivalent equal? "equal?"))
(define assert-= (assert-equivalent = "="))
(define assert-equals assert-equal)
(define assert= assert-=)
(define assert-< (assert-equivalent < "<"))
(define assert-> (assert-equivalent > ">"))
(define assert-<= (assert-equivalent <= "<="))
(define assert->= (assert-equivalent >= ">="))
(define (assert-in-delta expected actual delta . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> and\n<" "> expected to be within\n<"
"> of each other.")
expected actual delta)))
(assert-proc full-message (lambda () (<= (abs (- expected actual)) delta))))))
(define (assert-matches regexp string . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> expected to match <" ">")
string regexp)))
(assert-proc full-message
(lambda ()
(generic-match regexp string))))))
(define (assert-no-match regexp string . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> expected not to match <" ">")
string regexp)))
(assert-proc full-message
(lambda ()
(not (generic-match regexp string)))))))
(define (assert-true thing . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> expected to be a true value.")
thing)))
(assert-proc full-message (lambda () thing)))))
(define (assert-false thing . opt-message)
(let-optional opt-message ((message #f))
(let ((full-message
(build-message message '("<" "> expected to be a false value.")
thing)))
(assert-proc full-message (lambda () (not thing))))))
|
7b96a925904e84c9eb58222995e4bcece536a9e9701fc3f3270e089083228d4f | mwmitchell/flux | cloud.clj | (ns flux.cloud
(:import [org.apache.solr.client.solrj.impl CloudSolrClient$Builder]))
(defn create
([zk-hosts]
(CloudSolrClient$Builder. zk-hosts))
([zk-hosts default-collection]
(let [client (create zk-hosts)]
(.setDefaultCollection client default-collection)
client))) | null | https://raw.githubusercontent.com/mwmitchell/flux/855101681cf3c8953cd9607c2287a5b4c282a84e/src/flux/cloud.clj | clojure | (ns flux.cloud
(:import [org.apache.solr.client.solrj.impl CloudSolrClient$Builder]))
(defn create
([zk-hosts]
(CloudSolrClient$Builder. zk-hosts))
([zk-hosts default-collection]
(let [client (create zk-hosts)]
(.setDefaultCollection client default-collection)
client))) | |
eba384fee99614083a8502e55ceb735c033bb4f102fd129bf73e0b37c05a8aae | morpheusgraphql/morpheus-graphql | UnionType.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeFamilies #
module Feature.Inference.UnionType
( api,
)
where
import Data.Morpheus.Server (interpreter)
import Data.Morpheus.Server.Resolvers (ResolverQ)
import Data.Morpheus.Server.Types
( GQLRequest,
GQLResponse,
GQLType (..),
RootResolver (..),
Undefined,
defaultRootResolver,
)
import Data.Text (Text)
import GHC.Generics (Generic)
data A = A
{ aText :: Text,
aInt :: Int
}
deriving (Generic, GQLType)
data B = B
{ bText :: Text,
bInt :: Int
}
deriving (Generic, GQLType)
data C = C
{ cText :: Text,
cInt :: Int
}
deriving (Generic, GQLType)
data Sum
= SumA A
| SumB B
deriving (Generic, GQLType)
data Query m = Query
{ union :: m [Sum],
fc :: C
}
deriving (Generic, GQLType)
resolveUnion :: ResolverQ () IO [Sum]
resolveUnion =
return [SumA A {aText = "at", aInt = 1}, SumB B {bText = "bt", bInt = 2}]
rootResolver :: RootResolver IO () Query Undefined Undefined
rootResolver =
defaultRootResolver
{ queryResolver =
Query
{ union = resolveUnion,
fc = C {cText = "", cInt = 3}
}
}
api :: GQLRequest -> IO GQLResponse
api = interpreter rootResolver
| null | https://raw.githubusercontent.com/morpheusgraphql/morpheus-graphql/0d7ec120df4ea3b1e030f64ed9820a8a66de7d6a/morpheus-graphql-server/test/Feature/Inference/UnionType.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings # | # LANGUAGE DeriveGeneric #
# LANGUAGE TypeFamilies #
module Feature.Inference.UnionType
( api,
)
where
import Data.Morpheus.Server (interpreter)
import Data.Morpheus.Server.Resolvers (ResolverQ)
import Data.Morpheus.Server.Types
( GQLRequest,
GQLResponse,
GQLType (..),
RootResolver (..),
Undefined,
defaultRootResolver,
)
import Data.Text (Text)
import GHC.Generics (Generic)
data A = A
{ aText :: Text,
aInt :: Int
}
deriving (Generic, GQLType)
data B = B
{ bText :: Text,
bInt :: Int
}
deriving (Generic, GQLType)
data C = C
{ cText :: Text,
cInt :: Int
}
deriving (Generic, GQLType)
data Sum
= SumA A
| SumB B
deriving (Generic, GQLType)
data Query m = Query
{ union :: m [Sum],
fc :: C
}
deriving (Generic, GQLType)
resolveUnion :: ResolverQ () IO [Sum]
resolveUnion =
return [SumA A {aText = "at", aInt = 1}, SumB B {bText = "bt", bInt = 2}]
rootResolver :: RootResolver IO () Query Undefined Undefined
rootResolver =
defaultRootResolver
{ queryResolver =
Query
{ union = resolveUnion,
fc = C {cText = "", cInt = 3}
}
}
api :: GQLRequest -> IO GQLResponse
api = interpreter rootResolver
|
909cf2668114ffbe979aefe59b39f0ca6c471c5d3825bfbf55d60f84ab77fd2d | eholk/harlan | M9.scm | (library
(harlan middle languages M9)
(export M9 unparse-M9
M9.1 unparse-M9.1
M9.2 unparse-M9.2
M9.2.1 unparse-M9.2.1
M9.2.2 unparse-M9.2.2
M9.3 unparse-M9.3)
(import
(rnrs)
(nanopass)
(only (elegant-weapons helpers) binop? scalar-type? relop?)
(harlan middle languages M8))
(define-language M9
(extends M8)
(entry Module)
(Stmt
(stmt)
(- (apply-kernel x (e1* ...) e* ...))))
(define (any? x) (lambda _ #t))
(define (address-space? x) (memq x '(local global private)))
(define-language M9.1
(extends M9)
(entry Module)
(terminals
(+ (any (?))))
(Decl
(decl)
(- (gpu-module k* ...))
(+ (gpu-module cg k* ...)))
(CallGraph
(cg)
(+ (call-graph ?0 ?1))))
(define-language M9.2
(extends M9.1)
(entry Module)
(terminals
(- (any (?))))
(Decl
(decl)
(+ (gpu-module k* ...))
(- (gpu-module cg k* ...)))
(Body
(body)
(+ (with-labels (lbl ...) stmt)))
(CommonDecl
(cdecl)
(- (fn x (x* ...) t stmt))
(+ (fn x (x* ...) t body)))
(LabeledBlock
(lbl)
(+ (name ((x t) ...) stmt)))
(CallGraph
(cg)
(- (call-graph ?0 ?1)))
(Expr
(e)
(+ (call-label name t e* ...))))
(define-language M9.2.1
(extends M9.2)
(entry Module)
(Expr
(e)
(- (call-label name t e* ...))
(+ (call-label name t ((x* t*) ...) e* ...))))
(define-language M9.2.2
(extends M9.2.1)
(entry Module)
(Rho-Type
(t)
(+ (fixed-array t i)))
(Stmt
(stmt)
(+ (push! e0 e1 t e2) ;; push e2 with type t onto e0 + e1
(pop! e0 e1 t e2)))
(Body
(body)
;; like begin, bit doesn't conflict with the existing
( begin stmt * ... stmt )
(+ (seq stmt* ... body)))
(Expr
(e)
(+ (call-label name e* ...))
(- (call-label name t ((x* t*) ...) e* ...))))
(define-language M9.3
(extends M9.2.2)
(entry Module)
(terminals
(+ (address-space (space))))
(Body
(body)
(- (with-labels (lbl ...) stmt)
(seq stmt* ... body)))
(Stmt
(stmt)
(- (push! e0 e1 t e2)
(pop! e0 e1 t e2)))
(Expr
(e)
(- (call-label name e* ...)))
(Rho-Type
(t)
(+ (ptr space t)))
(LabeledBlock
(lbl)
(- (name ((x t) ...) stmt)))))
| null | https://raw.githubusercontent.com/eholk/harlan/3afd95b1c3ad02a354481774585e866857a687b8/harlan/middle/languages/M9.scm | scheme | push e2 with type t onto e0 + e1
like begin, bit doesn't conflict with the existing | (library
(harlan middle languages M9)
(export M9 unparse-M9
M9.1 unparse-M9.1
M9.2 unparse-M9.2
M9.2.1 unparse-M9.2.1
M9.2.2 unparse-M9.2.2
M9.3 unparse-M9.3)
(import
(rnrs)
(nanopass)
(only (elegant-weapons helpers) binop? scalar-type? relop?)
(harlan middle languages M8))
(define-language M9
(extends M8)
(entry Module)
(Stmt
(stmt)
(- (apply-kernel x (e1* ...) e* ...))))
(define (any? x) (lambda _ #t))
(define (address-space? x) (memq x '(local global private)))
(define-language M9.1
(extends M9)
(entry Module)
(terminals
(+ (any (?))))
(Decl
(decl)
(- (gpu-module k* ...))
(+ (gpu-module cg k* ...)))
(CallGraph
(cg)
(+ (call-graph ?0 ?1))))
(define-language M9.2
(extends M9.1)
(entry Module)
(terminals
(- (any (?))))
(Decl
(decl)
(+ (gpu-module k* ...))
(- (gpu-module cg k* ...)))
(Body
(body)
(+ (with-labels (lbl ...) stmt)))
(CommonDecl
(cdecl)
(- (fn x (x* ...) t stmt))
(+ (fn x (x* ...) t body)))
(LabeledBlock
(lbl)
(+ (name ((x t) ...) stmt)))
(CallGraph
(cg)
(- (call-graph ?0 ?1)))
(Expr
(e)
(+ (call-label name t e* ...))))
(define-language M9.2.1
(extends M9.2)
(entry Module)
(Expr
(e)
(- (call-label name t e* ...))
(+ (call-label name t ((x* t*) ...) e* ...))))
(define-language M9.2.2
(extends M9.2.1)
(entry Module)
(Rho-Type
(t)
(+ (fixed-array t i)))
(Stmt
(stmt)
(pop! e0 e1 t e2)))
(Body
(body)
( begin stmt * ... stmt )
(+ (seq stmt* ... body)))
(Expr
(e)
(+ (call-label name e* ...))
(- (call-label name t ((x* t*) ...) e* ...))))
(define-language M9.3
(extends M9.2.2)
(entry Module)
(terminals
(+ (address-space (space))))
(Body
(body)
(- (with-labels (lbl ...) stmt)
(seq stmt* ... body)))
(Stmt
(stmt)
(- (push! e0 e1 t e2)
(pop! e0 e1 t e2)))
(Expr
(e)
(- (call-label name e* ...)))
(Rho-Type
(t)
(+ (ptr space t)))
(LabeledBlock
(lbl)
(- (name ((x t) ...) stmt)))))
|
aeabfdb2bc9dda970161edae76d4e73bc99214442f8e8e4e6c64a01fd6048f90 | nasa/Common-Metadata-Repository | config.clj | (ns cmr.metadata-db.config
"Contains functions to retrieve metadata db specific configuration"
(:require
[cmr.common.concepts :as concepts]
[cmr.common.config :as cfg :refer [defconfig]]
[cmr.oracle.config :as oracle-config]
[cmr.oracle.connection :as conn]
[cmr.message-queue.config :as rmq-conf]))
(defconfig metadata-db-username
"The database username"
{:default "METADATA_DB"})
;; This value is set via profiles.clj in dev-system
(defconfig metadata-db-password
"The database password"
{})
(defconfig catalog-rest-db-username
"The catalog rest db username"
{:default "DEV_52_CATALOG_REST"})
(defn db-spec
"Returns a db spec populated with config information that can be used to connect to oracle"
[connection-pool-name]
(conn/db-spec
connection-pool-name
(oracle-config/db-url)
(oracle-config/db-fcf-enabled)
(oracle-config/db-ons-config)
(metadata-db-username)
(metadata-db-password)))
(defconfig parallel-chunk-size
"Gets the number of concepts that should be processed in each thread of get-concepts."
{:default 200
:type Long})
(defconfig result-set-fetch-size
"Gets the setting for query fetch-size (number of rows to fetch at once)"
{:default 200
:type Long})
(defconfig metadata-db-nrepl-port
"Port to listen for nREPL connections"
{:default nil
:parser cfg/maybe-long})
(defconfig ingest-exchange-name
"The ingest exchange to which concept update/save messages are published."
{:default "cmr_ingest.exchange"})
(defconfig access-control-exchange-name
"The access control exchange to which update/save messages are published for access control data."
{:default "cmr_access_control.exchange"})
(def concept-type->exchange-name-fn
"Maps concept types to a function that returns the name of the exchange to publish the message to."
(merge
{:granule ingest-exchange-name
:collection ingest-exchange-name
:tag ingest-exchange-name
:tag-association ingest-exchange-name
:service ingest-exchange-name
:service-association ingest-exchange-name
:access-group access-control-exchange-name
:acl access-control-exchange-name
:humanizer ingest-exchange-name
:variable ingest-exchange-name
:variable-association ingest-exchange-name
:tool ingest-exchange-name
:tool-association ingest-exchange-name
:subscription ingest-exchange-name
:generic-association ingest-exchange-name}
(zipmap (concepts/get-generic-concept-types-array) (repeat ingest-exchange-name))))
(defconfig deleted-concept-revision-exchange-name
"An exchange that will have messages passed to it whenever a concept revision is removed from
metadata db. This was originally only intended for collections and it is messy to change the
exchange name after it is in use, so we keep the old name even though it is no longer correct."
{:default "cmr_deleted_collection_revision.exchange"})
(defconfig deleted-granule-exchange-name
"An exchange that will have messages passed to it whenever a granule revision is removed
from metadata db."
{:default "cmr_deleted_granule.exchange"})
(defconfig publish-messages
"This indicates whether or not messages be published to the exchange"
{:default true :type Boolean})
(defn queue-config
"Returns the queue configuration for the metadata db application."
[]
(assoc (rmq-conf/default-config)
:exchanges [(deleted-concept-revision-exchange-name)
(ingest-exchange-name)
(access-control-exchange-name)
(deleted-granule-exchange-name)]))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/ef1fdf1dd6e90a5e686a324a4c905e04ba0b8cad/metadata-db-app/src/cmr/metadata_db/config.clj | clojure | This value is set via profiles.clj in dev-system | (ns cmr.metadata-db.config
"Contains functions to retrieve metadata db specific configuration"
(:require
[cmr.common.concepts :as concepts]
[cmr.common.config :as cfg :refer [defconfig]]
[cmr.oracle.config :as oracle-config]
[cmr.oracle.connection :as conn]
[cmr.message-queue.config :as rmq-conf]))
(defconfig metadata-db-username
"The database username"
{:default "METADATA_DB"})
(defconfig metadata-db-password
"The database password"
{})
(defconfig catalog-rest-db-username
"The catalog rest db username"
{:default "DEV_52_CATALOG_REST"})
(defn db-spec
"Returns a db spec populated with config information that can be used to connect to oracle"
[connection-pool-name]
(conn/db-spec
connection-pool-name
(oracle-config/db-url)
(oracle-config/db-fcf-enabled)
(oracle-config/db-ons-config)
(metadata-db-username)
(metadata-db-password)))
(defconfig parallel-chunk-size
"Gets the number of concepts that should be processed in each thread of get-concepts."
{:default 200
:type Long})
(defconfig result-set-fetch-size
"Gets the setting for query fetch-size (number of rows to fetch at once)"
{:default 200
:type Long})
(defconfig metadata-db-nrepl-port
"Port to listen for nREPL connections"
{:default nil
:parser cfg/maybe-long})
(defconfig ingest-exchange-name
"The ingest exchange to which concept update/save messages are published."
{:default "cmr_ingest.exchange"})
(defconfig access-control-exchange-name
"The access control exchange to which update/save messages are published for access control data."
{:default "cmr_access_control.exchange"})
(def concept-type->exchange-name-fn
"Maps concept types to a function that returns the name of the exchange to publish the message to."
(merge
{:granule ingest-exchange-name
:collection ingest-exchange-name
:tag ingest-exchange-name
:tag-association ingest-exchange-name
:service ingest-exchange-name
:service-association ingest-exchange-name
:access-group access-control-exchange-name
:acl access-control-exchange-name
:humanizer ingest-exchange-name
:variable ingest-exchange-name
:variable-association ingest-exchange-name
:tool ingest-exchange-name
:tool-association ingest-exchange-name
:subscription ingest-exchange-name
:generic-association ingest-exchange-name}
(zipmap (concepts/get-generic-concept-types-array) (repeat ingest-exchange-name))))
(defconfig deleted-concept-revision-exchange-name
"An exchange that will have messages passed to it whenever a concept revision is removed from
metadata db. This was originally only intended for collections and it is messy to change the
exchange name after it is in use, so we keep the old name even though it is no longer correct."
{:default "cmr_deleted_collection_revision.exchange"})
(defconfig deleted-granule-exchange-name
"An exchange that will have messages passed to it whenever a granule revision is removed
from metadata db."
{:default "cmr_deleted_granule.exchange"})
(defconfig publish-messages
"This indicates whether or not messages be published to the exchange"
{:default true :type Boolean})
(defn queue-config
"Returns the queue configuration for the metadata db application."
[]
(assoc (rmq-conf/default-config)
:exchanges [(deleted-concept-revision-exchange-name)
(ingest-exchange-name)
(access-control-exchange-name)
(deleted-granule-exchange-name)]))
|
314c91dfae84221f9ed1773d6912989377d2ae3864ec98c734dbc99014167a65 | purescript/purescript | Layout.hs | -- |
-- ## High-Level Summary
--
-- This section provides a high-level summary of this file. For those who
-- know more about compiler-development, the below explanation is likely enough.
-- For everyone else, see the next section.
--
-- The parser itself is unaware of indentation, and instead only parses explicit
delimiters which are inserted by this layout algorithm ( much like ) .
-- This is convenient because the actual grammar can be specified apart from the
indentation rules . has a few problematic productions which make it
-- impossible to implement a purely lexical layout algorithm, so it also has an
additional ( and somewhat contentious ) parser error side condition . PureScript
-- does not have these problematic productions (particularly foo, bar ::
SomeType syntax in declarations ) , but it does have a few gotchas of it 's own .
-- The algorithm is "non-trivial" to say the least, but it is implemented as a
-- purely lexical delimiter parser on a token-by-token basis, which is highly
-- convenient, since it can be replicated in any language or toolchain. There is
-- likely room to simplify it, but there are some seemingly innocuous things
-- that complicate it.
--
-- "Naked" commas (case, patterns, guards, fundeps) are a constant source of
complexity , and indeed too much of this is what prevents from having
such an algorithm . Unquoted properties for layout keywords introduce a domino
-- effect of complexity since we have to mask and unmask any usage of . (also in
-- foralls!) or labels in record literals.
--
-- ## Detailed Summary
--
# # # The Problem
--
-- The parser itself is unaware of indentation or other such layout concerns.
-- Rather than dealing with it explicitly, the parser and its
grammar rules are only aware of normal tokens ( e.g. @TokLowerName@ ) and
three special zero - width tokens , @TokLayoutStart@ , ,
-- and @TokLayoutEnd@. This is convenient because the actual grammar
-- can be specified apart from the indentation rules and other such
-- layout concerns.
--
For a simple example , the parser parses all three examples of the code below
using the exact same grammar rules for the keyword despite
-- each example using different indentations levels:
--
-- @
-- Example 1
let foo = 5
x = 2 in foo
--
-- Example 2
-- let
bar = 5
y = 2
-- in bar
--
-- Example 3
-- let baz
-- =
5
z= 2 in baz
-- @
--
-- Each block of code might appear to the parser as a stream of the
-- following source tokens where the @\{@ sequence represents
@TokLayoutStart@ , the @\;@ sequence represents ,
and the @\}@ sequence represents :
- @let \{foo = 5\;x = 2\ } in foo@
- @let \{bar = 5\;y = 2\ } in bar@
- @let \{baz = 5\;z = 2\ } in baz@
--
--
-- For a more complex example, consider commas:
--
-- @
-- case one, { twoA, twoB }, [ three1
-- , three2
-- , do
{ three3 , } < - case arg1 , of
Nothing , _ - > { three3 : 1 , : 2 }
Just _ , Nothing - > { three3 : 2 , : 3 }
_ , _ - > { three3 : 3 , : 4 }
-- pure $ three3 + three4
-- ] of
-- @
--
Which of the above 13 commas function as the separators between the
-- case binders (e.g. @one@) in the outermost @case ... of@ context?
--
# # # The Solution
--
-- The parser doesn't have to care about layout concerns (e.g. indentation
-- or what starts and ends a context, such as a case binder) because the
-- lexer solves that problem instead.
--
-- So, how does the lexer solve this problem? It follows this general algorithm:
1 . Lex the source code text into an initial stream of ` SourceToken`s
that do not have any of the three special tokens mentioned previously .
2 . On a token - by - token basis , determine whether the lexer should
1 . insert one of the three special tokens ,
-- 2. modify the current context (e.g. are we within a case binder?
-- Are we in a record expression?)
--
Step 2 is handled via ' ' and is essentially a state machine .
The layout delimiters , ( e.g. ' LytCase ' , ' LytBrace ' , ' LytProperty ' ,
-- and 'LytOf' in the next section's example) either stop certain "rules"
-- from applying or ensure that certain "rules" now apply. By "rules",
we mean whether and where one of the three special tokens are added .
-- The comments in the source code for the 'insertLayout' algorithm call
-- pushing these delimiters onto the stack "masking" and popping them off
-- as "unmasking". Seeing when a layout delimiter is pushed and popped
-- are the keys to understanding this algorithm.
--
# # # Walking Through an Example
--
-- Before showing an example, let's remember a few things.
-- 1. The @TokLowerName "case"@ token (i.e. a "case" keyword) indicates the start
-- of a @case ... of@ context. That context includes case binders (like the
-- example shown previously) that can get quite complex. When encountered,
we may need to insert one or more of the three special tokens here
-- until we encounter the terminating @TokLowerName "of"@ token that
-- signifies its end.
-- 2. "case" and "of" can also appear as a record field's name. In such a context,
-- they would not start or end a @case ... of@ block.
--
-- Given the below source code...
--
-- @
-- case { case: "foo", of: "bar" } of
-- @
--
-- the lexer would go through something like the following states:
1 . Encountered @TokLowerName " case"@. Update current context to
-- "within a case of expression" by pushing the 'LytCase' delimiter
-- onto the layout delimiter stack. Insert the @case@ token
-- into the stream of source tokens.
2 . Encountered @TokLeftBrace@. Update current context to
" within a record expression " by pushing the ' LytBrace ' delimiter .
-- Since we expect a field name to be the next token we see,
-- which may include a reserved keyword, update the current context again to
" expecting a field name " by pushing the ` LytProperty ` .
-- delimiter. Insert the @{@ token into the stream of source tokens.
3 . Encountered @TokLowerName " case"@. Check the current context .
Since it 's a ` LytProperty ` , this is a field name and we should n't
-- assume that the next few tokens will be case binders. However,
-- since this might be a record with no more fields, update the
-- current context back to "within a record expression" by popping
the ` LytProperty ` off the layout delimiter stack . Insert the @case@ token
4 . Encountered @TokColon@. Insert the @:@ token
5 . Encountered @TokLowerName " foo"@. Insert the @foo@ token .
6 . Encountered @TokComma@. Check the current context . Since it 's a ` LytBrace ` ,
-- we're in a record expression and there is another field. Update the
current context by pushing ` LytProperty ` as we expect a field name again .
7 . Encountered @TokLowerName " of"@. Check the current context .
Since it 's a ` LytProperty ` , this is a field name rather
-- than the end of a case binder. Thus, we don't expect the next tokens
-- to be the @body@ in a @case ... of body@ expression. However, since
-- this might be a record with no more fields, update the current context
back to " within a record expression " by popping the ` LytProperty `
-- off the stack. Insert the @of@ token.
8 . Encountered @TokRightBrace@. Check the current context .
Since it 's a ` LytBrace ` , this is the end of a record expression .
-- Update the current context to "within a case of expression"
by popping the ` LytBrace ` off the stack . Insert the @}@ token .
9 . Encountered @TokLowername " of"@. Check the current context .
-- Since it's a 'LytCase', this is the end of a @case ... of@ expression
-- and the body will follow. Update the current context to
-- "body of a case of expression" by pushing 'LytOf' onto the layout stack.
-- Insert the @of@ token into the stream of tokens.
--
module Language.PureScript.CST.Layout where
import Prelude
import Data.DList (snoc)
import qualified Data.DList as DList
import Data.Foldable (find)
import Data.Function ((&))
import Language.PureScript.CST.Types
type LayoutStack = [(SourcePos, LayoutDelim)]
data LayoutDelim
= LytRoot
| LytTopDecl
| LytTopDeclHead
| LytDeclGuard
| LytCase
| LytCaseBinders
| LytCaseGuard
| LytLambdaBinders
| LytParen
| LytBrace
| LytSquare
| LytIf
| LytThen
| LytProperty
| LytForall
| LytTick
| LytLet
| LytLetStmt
| LytWhere
| LytOf
| LytDo
| LytAdo
deriving (Show, Eq, Ord)
isIndented :: LayoutDelim -> Bool
isIndented = \case
LytLet -> True
LytLetStmt -> True
LytWhere -> True
LytOf -> True
LytDo -> True
LytAdo -> True
_ -> False
isTopDecl :: SourcePos -> LayoutStack -> Bool
isTopDecl tokPos = \case
[(lytPos, LytWhere), (_, LytRoot)]
| srcColumn tokPos == srcColumn lytPos -> True
_ -> False
lytToken :: SourcePos -> Token -> SourceToken
lytToken pos = SourceToken ann
where
ann = TokenAnn
{ tokRange = SourceRange pos pos
, tokLeadingComments = []
, tokTrailingComments = []
}
insertLayout :: SourceToken -> SourcePos -> LayoutStack -> (LayoutStack, [SourceToken])
insertLayout src@(SourceToken tokAnn tok) nextPos stack =
DList.toList <$> insert (stack, mempty)
where
tokPos =
srcStart $ tokRange tokAnn
insert state@(stk, acc) = case tok of
` data ` declarations need masking ( ) because the usage of ` | `
-- should not introduce a LytDeclGard context.
TokLowerName [] "data" ->
case state & insertDefault of
state'@(stk', _) | isTopDecl tokPos stk' ->
state' & pushStack tokPos LytTopDecl
state' ->
state' & popStack (== LytProperty)
` class ` declaration heads need masking ( ) because the
-- usage of commas in functional dependencies.
TokLowerName [] "class" ->
case state & insertDefault of
state'@(stk', _) | isTopDecl tokPos stk' ->
state' & pushStack tokPos LytTopDeclHead
state' ->
state' & popStack (== LytProperty)
TokLowerName [] "where" ->
case stk of
(_, LytTopDeclHead) : stk' ->
(stk', acc) & insertToken src & insertStart LytWhere
(_, LytProperty) : stk' ->
(stk', acc) & insertToken src
_ ->
state & collapse whereP & insertToken src & insertStart LytWhere
where
-- `where` always closes do blocks:
-- example = do do do do foo where foo = ...
--
-- `where` closes layout contexts even when indented at the same level:
-- example = case
-- Foo -> ...
-- Bar -> ...
-- where foo = ...
whereP _ LytDo = True
whereP lytPos lyt = offsideEndP lytPos lyt
TokLowerName [] "in" ->
case collapse inP state of
-- `let/in` is not allowed in `ado` syntax. `in` is treated as a
-- delimiter and must always close the `ado`.
-- example = ado
-- foo <- ...
-- let bar = ...
-- in ...
((_, LytLetStmt) : (_, LytAdo) : stk', acc') ->
(stk', acc') & insertEnd & insertEnd & insertToken src
((_, lyt) : stk', acc') | isIndented lyt ->
(stk', acc') & insertEnd & insertToken src
_ ->
state & insertDefault & popStack (== LytProperty)
where
inP _ LytLet = False
inP _ LytAdo = False
inP _ lyt = isIndented lyt
TokLowerName [] "let" ->
state & insertKwProperty next
where
next state'@(stk', _) = case stk' of
(p, LytDo) : _ | srcColumn p == srcColumn tokPos ->
state' & insertStart LytLetStmt
(p, LytAdo) : _ | srcColumn p == srcColumn tokPos ->
state' & insertStart LytLetStmt
_ ->
state' & insertStart LytLet
TokLowerName _ "do" ->
state & insertKwProperty (insertStart LytDo)
TokLowerName _ "ado" ->
state & insertKwProperty (insertStart LytAdo)
-- `case` heads need masking due to commas.
TokLowerName [] "case" ->
state & insertKwProperty (pushStack tokPos LytCase)
TokLowerName [] "of" ->
case collapse indentedP state of
-- When `of` is matched with a `case`, we are in a case block, and we
need to mask additional contexts ( LytCaseBinders , LytCaseGuards )
-- due to commas.
((_, LytCase) : stk', acc') ->
(stk', acc') & insertToken src & insertStart LytOf & pushStack nextPos LytCaseBinders
state' ->
state' & insertDefault & popStack (== LytProperty)
-- `if/then/else` is considered a delimiter context. This allows us to
-- write chained expressions in `do` blocks without stair-stepping:
-- example = do
-- foo
-- if ... then
-- ...
-- else if ... then
-- ...
-- else
-- ...
TokLowerName [] "if" ->
state & insertKwProperty (pushStack tokPos LytIf)
TokLowerName [] "then" ->
case state & collapse indentedP of
((_, LytIf) : stk', acc') ->
(stk', acc') & insertToken src & pushStack tokPos LytThen
_ ->
state & insertDefault & popStack (== LytProperty)
TokLowerName [] "else" ->
case state & collapse indentedP of
((_, LytThen) : stk', acc') ->
(stk', acc') & insertToken src
_ ->
-- We don't want to insert a layout separator for top-level `else` in
-- instance chains.
case state & collapse offsideP of
state'@(stk', _) | isTopDecl tokPos stk' ->
state' & insertToken src
state' ->
state' & insertSep & insertToken src & popStack (== LytProperty)
-- `forall` binders need masking because the usage of `.` should not
introduce a LytProperty context .
TokForall _ ->
state & insertKwProperty (pushStack tokPos LytForall)
Lambdas need masking because the usage of ` - > ` should not close a
-- LytDeclGuard or LytCaseGuard context.
TokBackslash ->
state & insertDefault & pushStack tokPos LytLambdaBinders
TokRightArrow _ ->
state & collapse arrowP & popStack guardP & insertToken src
where
arrowP _ LytDo = True
arrowP _ LytOf = False
arrowP lytPos lyt = offsideEndP lytPos lyt
guardP LytCaseBinders = True
guardP LytCaseGuard = True
guardP LytLambdaBinders = True
guardP _ = False
TokEquals ->
case state & collapse equalsP of
((_, LytDeclGuard) : stk', acc') ->
(stk', acc') & insertToken src
_ ->
state & insertDefault
where
equalsP _ LytWhere = True
equalsP _ LytLet = True
equalsP _ LytLetStmt = True
equalsP _ _ = False
-- Guards need masking because of commas.
TokPipe ->
case collapse offsideEndP state of
state'@((_, LytOf) : _, _) ->
state' & pushStack tokPos LytCaseGuard & insertToken src
state'@((_, LytLet) : _, _) ->
state' & pushStack tokPos LytDeclGuard & insertToken src
state'@((_, LytLetStmt) : _, _) ->
state' & pushStack tokPos LytDeclGuard & insertToken src
state'@((_, LytWhere) : _, _) ->
state' & pushStack tokPos LytDeclGuard & insertToken src
_ ->
state & insertDefault
-- Ticks can either start or end an infix expression. We preemptively
-- collapse all indentation contexts in search of a starting delimiter,
-- and backtrack if we don't find one.
TokTick ->
case state & collapse indentedP of
((_, LytTick) : stk', acc') ->
(stk', acc') & insertToken src
_ ->
state & collapse offsideEndP & insertSep & insertToken src & pushStack tokPos LytTick
-- In general, commas should close all indented contexts.
-- example = [ do foo
-- bar, baz ]
TokComma ->
case state & collapse indentedP of
If we see a LytBrace , then we are in a record type or literal .
-- Record labels need masking so we can use unquoted keywords as labels
-- without accidentally littering layout delimiters.
state'@((_, LytBrace) : _, _) ->
state' & insertToken src & pushStack tokPos LytProperty
state' ->
state' & insertToken src
-- TokDot tokens usually entail property access, which need masking so we
-- can use unquoted keywords as labels.
TokDot ->
case state & insertDefault of
((_, LytForall) : stk', acc') ->
(stk', acc')
state' ->
state' & pushStack tokPos LytProperty
TokLeftParen ->
state & insertDefault & pushStack tokPos LytParen
TokLeftBrace ->
state & insertDefault & pushStack tokPos LytBrace & pushStack tokPos LytProperty
TokLeftSquare ->
state & insertDefault & pushStack tokPos LytSquare
TokRightParen ->
state & collapse indentedP & popStack (== LytParen) & insertToken src
TokRightBrace ->
state & collapse indentedP & popStack (== LytProperty) & popStack (== LytBrace) & insertToken src
TokRightSquare ->
state & collapse indentedP & popStack (== LytSquare) & insertToken src
TokString _ _ ->
state & insertDefault & popStack (== LytProperty)
TokLowerName [] _ ->
state & insertDefault & popStack (== LytProperty)
TokOperator _ _ ->
state & collapse offsideEndP & insertSep & insertToken src
_ ->
state & insertDefault
insertDefault state =
state & collapse offsideP & insertSep & insertToken src
insertStart lyt state@(stk, _) =
-- We only insert a new layout start when it's going to increase indentation.
-- This prevents things like the following from parsing:
instance foo : : where
foo = 42
case find (isIndented . snd) stk of
Just (pos, _) | srcColumn nextPos <= srcColumn pos -> state
_ -> state & pushStack nextPos lyt & insertToken (lytToken nextPos TokLayoutStart)
insertSep state@(stk, acc) = case stk of
is closed by a separator .
(lytPos, LytTopDecl) : stk' | sepP lytPos ->
(stk', acc) & insertToken sepTok
-- LytTopDeclHead can be closed by a separator if there is no `where`.
(lytPos, LytTopDeclHead) : stk' | sepP lytPos ->
(stk', acc) & insertToken sepTok
(lytPos, lyt) : _ | indentSepP lytPos lyt ->
case lyt of
-- If a separator is inserted in a case block, we need to push an
additional LytCaseBinders context for comma masking .
LytOf -> state & insertToken sepTok & pushStack tokPos LytCaseBinders
_ -> state & insertToken sepTok
_ -> state
where
sepTok = lytToken tokPos TokLayoutSep
insertKwProperty k state =
case state & insertDefault of
((_, LytProperty) : stk', acc') ->
(stk', acc')
state' ->
k state'
insertEnd =
insertToken (lytToken tokPos TokLayoutEnd)
insertToken token (stk, acc) =
(stk, acc `snoc` token)
pushStack lytPos lyt (stk, acc) =
((lytPos, lyt) : stk, acc)
popStack p ((_, lyt) : stk', acc)
| p lyt = (stk', acc)
popStack _ state = state
collapse p = uncurry go
where
go ((lytPos, lyt) : stk) acc
| p lytPos lyt =
go stk $ if isIndented lyt
then acc `snoc` lytToken tokPos TokLayoutEnd
else acc
go stk acc = (stk, acc)
indentedP =
const isIndented
offsideP lytPos lyt =
isIndented lyt && srcColumn tokPos < srcColumn lytPos
offsideEndP lytPos lyt =
isIndented lyt && srcColumn tokPos <= srcColumn lytPos
indentSepP lytPos lyt =
isIndented lyt && sepP lytPos
sepP lytPos =
srcColumn tokPos == srcColumn lytPos && srcLine tokPos /= srcLine lytPos
unwindLayout :: SourcePos -> [Comment LineFeed] -> LayoutStack -> [SourceToken]
unwindLayout pos leading = go
where
go [] = []
go ((_, LytRoot) : _) = [SourceToken (TokenAnn (SourceRange pos pos) leading []) TokEof]
go ((_, lyt) : stk) | isIndented lyt = lytToken pos TokLayoutEnd : go stk
go (_ : stk) = go stk
| null | https://raw.githubusercontent.com/purescript/purescript/10609242a269b4409fb7d4571fc905cd9fc999cb/src/Language/PureScript/CST/Layout.hs | haskell | |
## High-Level Summary
This section provides a high-level summary of this file. For those who
know more about compiler-development, the below explanation is likely enough.
For everyone else, see the next section.
The parser itself is unaware of indentation, and instead only parses explicit
This is convenient because the actual grammar can be specified apart from the
impossible to implement a purely lexical layout algorithm, so it also has an
does not have these problematic productions (particularly foo, bar ::
The algorithm is "non-trivial" to say the least, but it is implemented as a
purely lexical delimiter parser on a token-by-token basis, which is highly
convenient, since it can be replicated in any language or toolchain. There is
likely room to simplify it, but there are some seemingly innocuous things
that complicate it.
"Naked" commas (case, patterns, guards, fundeps) are a constant source of
effect of complexity since we have to mask and unmask any usage of . (also in
foralls!) or labels in record literals.
## Detailed Summary
The parser itself is unaware of indentation or other such layout concerns.
Rather than dealing with it explicitly, the parser and its
and @TokLayoutEnd@. This is convenient because the actual grammar
can be specified apart from the indentation rules and other such
layout concerns.
each example using different indentations levels:
@
Example 1
Example 2
let
in bar
Example 3
let baz
=
@
Each block of code might appear to the parser as a stream of the
following source tokens where the @\{@ sequence represents
For a more complex example, consider commas:
@
case one, { twoA, twoB }, [ three1
, three2
, do
pure $ three3 + three4
] of
@
case binders (e.g. @one@) in the outermost @case ... of@ context?
The parser doesn't have to care about layout concerns (e.g. indentation
or what starts and ends a context, such as a case binder) because the
lexer solves that problem instead.
So, how does the lexer solve this problem? It follows this general algorithm:
2. modify the current context (e.g. are we within a case binder?
Are we in a record expression?)
and 'LytOf' in the next section's example) either stop certain "rules"
from applying or ensure that certain "rules" now apply. By "rules",
The comments in the source code for the 'insertLayout' algorithm call
pushing these delimiters onto the stack "masking" and popping them off
as "unmasking". Seeing when a layout delimiter is pushed and popped
are the keys to understanding this algorithm.
Before showing an example, let's remember a few things.
1. The @TokLowerName "case"@ token (i.e. a "case" keyword) indicates the start
of a @case ... of@ context. That context includes case binders (like the
example shown previously) that can get quite complex. When encountered,
until we encounter the terminating @TokLowerName "of"@ token that
signifies its end.
2. "case" and "of" can also appear as a record field's name. In such a context,
they would not start or end a @case ... of@ block.
Given the below source code...
@
case { case: "foo", of: "bar" } of
@
the lexer would go through something like the following states:
"within a case of expression" by pushing the 'LytCase' delimiter
onto the layout delimiter stack. Insert the @case@ token
into the stream of source tokens.
Since we expect a field name to be the next token we see,
which may include a reserved keyword, update the current context again to
delimiter. Insert the @{@ token into the stream of source tokens.
assume that the next few tokens will be case binders. However,
since this might be a record with no more fields, update the
current context back to "within a record expression" by popping
we're in a record expression and there is another field. Update the
than the end of a case binder. Thus, we don't expect the next tokens
to be the @body@ in a @case ... of body@ expression. However, since
this might be a record with no more fields, update the current context
off the stack. Insert the @of@ token.
Update the current context to "within a case of expression"
Since it's a 'LytCase', this is the end of a @case ... of@ expression
and the body will follow. Update the current context to
"body of a case of expression" by pushing 'LytOf' onto the layout stack.
Insert the @of@ token into the stream of tokens.
should not introduce a LytDeclGard context.
usage of commas in functional dependencies.
`where` always closes do blocks:
example = do do do do foo where foo = ...
`where` closes layout contexts even when indented at the same level:
example = case
Foo -> ...
Bar -> ...
where foo = ...
`let/in` is not allowed in `ado` syntax. `in` is treated as a
delimiter and must always close the `ado`.
example = ado
foo <- ...
let bar = ...
in ...
`case` heads need masking due to commas.
When `of` is matched with a `case`, we are in a case block, and we
due to commas.
`if/then/else` is considered a delimiter context. This allows us to
write chained expressions in `do` blocks without stair-stepping:
example = do
foo
if ... then
...
else if ... then
...
else
...
We don't want to insert a layout separator for top-level `else` in
instance chains.
`forall` binders need masking because the usage of `.` should not
LytDeclGuard or LytCaseGuard context.
Guards need masking because of commas.
Ticks can either start or end an infix expression. We preemptively
collapse all indentation contexts in search of a starting delimiter,
and backtrack if we don't find one.
In general, commas should close all indented contexts.
example = [ do foo
bar, baz ]
Record labels need masking so we can use unquoted keywords as labels
without accidentally littering layout delimiters.
TokDot tokens usually entail property access, which need masking so we
can use unquoted keywords as labels.
We only insert a new layout start when it's going to increase indentation.
This prevents things like the following from parsing:
LytTopDeclHead can be closed by a separator if there is no `where`.
If a separator is inserted in a case block, we need to push an | delimiters which are inserted by this layout algorithm ( much like ) .
indentation rules . has a few problematic productions which make it
additional ( and somewhat contentious ) parser error side condition . PureScript
SomeType syntax in declarations ) , but it does have a few gotchas of it 's own .
complexity , and indeed too much of this is what prevents from having
such an algorithm . Unquoted properties for layout keywords introduce a domino
# # # The Problem
grammar rules are only aware of normal tokens ( e.g. @TokLowerName@ ) and
three special zero - width tokens , @TokLayoutStart@ , ,
For a simple example , the parser parses all three examples of the code below
using the exact same grammar rules for the keyword despite
let foo = 5
x = 2 in foo
bar = 5
y = 2
5
z= 2 in baz
@TokLayoutStart@ , the @\;@ sequence represents ,
and the @\}@ sequence represents :
- @let \{foo = 5\;x = 2\ } in foo@
- @let \{bar = 5\;y = 2\ } in bar@
- @let \{baz = 5\;z = 2\ } in baz@
{ three3 , } < - case arg1 , of
Nothing , _ - > { three3 : 1 , : 2 }
Just _ , Nothing - > { three3 : 2 , : 3 }
_ , _ - > { three3 : 3 , : 4 }
Which of the above 13 commas function as the separators between the
# # # The Solution
1 . Lex the source code text into an initial stream of ` SourceToken`s
that do not have any of the three special tokens mentioned previously .
2 . On a token - by - token basis , determine whether the lexer should
1 . insert one of the three special tokens ,
Step 2 is handled via ' ' and is essentially a state machine .
The layout delimiters , ( e.g. ' LytCase ' , ' LytBrace ' , ' LytProperty ' ,
we mean whether and where one of the three special tokens are added .
# # # Walking Through an Example
we may need to insert one or more of the three special tokens here
1 . Encountered @TokLowerName " case"@. Update current context to
2 . Encountered @TokLeftBrace@. Update current context to
" within a record expression " by pushing the ' LytBrace ' delimiter .
" expecting a field name " by pushing the ` LytProperty ` .
3 . Encountered @TokLowerName " case"@. Check the current context .
Since it 's a ` LytProperty ` , this is a field name and we should n't
the ` LytProperty ` off the layout delimiter stack . Insert the @case@ token
4 . Encountered @TokColon@. Insert the @:@ token
5 . Encountered @TokLowerName " foo"@. Insert the @foo@ token .
6 . Encountered @TokComma@. Check the current context . Since it 's a ` LytBrace ` ,
current context by pushing ` LytProperty ` as we expect a field name again .
7 . Encountered @TokLowerName " of"@. Check the current context .
Since it 's a ` LytProperty ` , this is a field name rather
back to " within a record expression " by popping the ` LytProperty `
8 . Encountered @TokRightBrace@. Check the current context .
Since it 's a ` LytBrace ` , this is the end of a record expression .
by popping the ` LytBrace ` off the stack . Insert the @}@ token .
9 . Encountered @TokLowername " of"@. Check the current context .
module Language.PureScript.CST.Layout where
import Prelude
import Data.DList (snoc)
import qualified Data.DList as DList
import Data.Foldable (find)
import Data.Function ((&))
import Language.PureScript.CST.Types
type LayoutStack = [(SourcePos, LayoutDelim)]
data LayoutDelim
= LytRoot
| LytTopDecl
| LytTopDeclHead
| LytDeclGuard
| LytCase
| LytCaseBinders
| LytCaseGuard
| LytLambdaBinders
| LytParen
| LytBrace
| LytSquare
| LytIf
| LytThen
| LytProperty
| LytForall
| LytTick
| LytLet
| LytLetStmt
| LytWhere
| LytOf
| LytDo
| LytAdo
deriving (Show, Eq, Ord)
isIndented :: LayoutDelim -> Bool
isIndented = \case
LytLet -> True
LytLetStmt -> True
LytWhere -> True
LytOf -> True
LytDo -> True
LytAdo -> True
_ -> False
isTopDecl :: SourcePos -> LayoutStack -> Bool
isTopDecl tokPos = \case
[(lytPos, LytWhere), (_, LytRoot)]
| srcColumn tokPos == srcColumn lytPos -> True
_ -> False
lytToken :: SourcePos -> Token -> SourceToken
lytToken pos = SourceToken ann
where
ann = TokenAnn
{ tokRange = SourceRange pos pos
, tokLeadingComments = []
, tokTrailingComments = []
}
insertLayout :: SourceToken -> SourcePos -> LayoutStack -> (LayoutStack, [SourceToken])
insertLayout src@(SourceToken tokAnn tok) nextPos stack =
DList.toList <$> insert (stack, mempty)
where
tokPos =
srcStart $ tokRange tokAnn
insert state@(stk, acc) = case tok of
` data ` declarations need masking ( ) because the usage of ` | `
TokLowerName [] "data" ->
case state & insertDefault of
state'@(stk', _) | isTopDecl tokPos stk' ->
state' & pushStack tokPos LytTopDecl
state' ->
state' & popStack (== LytProperty)
` class ` declaration heads need masking ( ) because the
TokLowerName [] "class" ->
case state & insertDefault of
state'@(stk', _) | isTopDecl tokPos stk' ->
state' & pushStack tokPos LytTopDeclHead
state' ->
state' & popStack (== LytProperty)
TokLowerName [] "where" ->
case stk of
(_, LytTopDeclHead) : stk' ->
(stk', acc) & insertToken src & insertStart LytWhere
(_, LytProperty) : stk' ->
(stk', acc) & insertToken src
_ ->
state & collapse whereP & insertToken src & insertStart LytWhere
where
whereP _ LytDo = True
whereP lytPos lyt = offsideEndP lytPos lyt
TokLowerName [] "in" ->
case collapse inP state of
((_, LytLetStmt) : (_, LytAdo) : stk', acc') ->
(stk', acc') & insertEnd & insertEnd & insertToken src
((_, lyt) : stk', acc') | isIndented lyt ->
(stk', acc') & insertEnd & insertToken src
_ ->
state & insertDefault & popStack (== LytProperty)
where
inP _ LytLet = False
inP _ LytAdo = False
inP _ lyt = isIndented lyt
TokLowerName [] "let" ->
state & insertKwProperty next
where
next state'@(stk', _) = case stk' of
(p, LytDo) : _ | srcColumn p == srcColumn tokPos ->
state' & insertStart LytLetStmt
(p, LytAdo) : _ | srcColumn p == srcColumn tokPos ->
state' & insertStart LytLetStmt
_ ->
state' & insertStart LytLet
TokLowerName _ "do" ->
state & insertKwProperty (insertStart LytDo)
TokLowerName _ "ado" ->
state & insertKwProperty (insertStart LytAdo)
TokLowerName [] "case" ->
state & insertKwProperty (pushStack tokPos LytCase)
TokLowerName [] "of" ->
case collapse indentedP state of
need to mask additional contexts ( LytCaseBinders , LytCaseGuards )
((_, LytCase) : stk', acc') ->
(stk', acc') & insertToken src & insertStart LytOf & pushStack nextPos LytCaseBinders
state' ->
state' & insertDefault & popStack (== LytProperty)
TokLowerName [] "if" ->
state & insertKwProperty (pushStack tokPos LytIf)
TokLowerName [] "then" ->
case state & collapse indentedP of
((_, LytIf) : stk', acc') ->
(stk', acc') & insertToken src & pushStack tokPos LytThen
_ ->
state & insertDefault & popStack (== LytProperty)
TokLowerName [] "else" ->
case state & collapse indentedP of
((_, LytThen) : stk', acc') ->
(stk', acc') & insertToken src
_ ->
case state & collapse offsideP of
state'@(stk', _) | isTopDecl tokPos stk' ->
state' & insertToken src
state' ->
state' & insertSep & insertToken src & popStack (== LytProperty)
introduce a LytProperty context .
TokForall _ ->
state & insertKwProperty (pushStack tokPos LytForall)
Lambdas need masking because the usage of ` - > ` should not close a
TokBackslash ->
state & insertDefault & pushStack tokPos LytLambdaBinders
TokRightArrow _ ->
state & collapse arrowP & popStack guardP & insertToken src
where
arrowP _ LytDo = True
arrowP _ LytOf = False
arrowP lytPos lyt = offsideEndP lytPos lyt
guardP LytCaseBinders = True
guardP LytCaseGuard = True
guardP LytLambdaBinders = True
guardP _ = False
TokEquals ->
case state & collapse equalsP of
((_, LytDeclGuard) : stk', acc') ->
(stk', acc') & insertToken src
_ ->
state & insertDefault
where
equalsP _ LytWhere = True
equalsP _ LytLet = True
equalsP _ LytLetStmt = True
equalsP _ _ = False
TokPipe ->
case collapse offsideEndP state of
state'@((_, LytOf) : _, _) ->
state' & pushStack tokPos LytCaseGuard & insertToken src
state'@((_, LytLet) : _, _) ->
state' & pushStack tokPos LytDeclGuard & insertToken src
state'@((_, LytLetStmt) : _, _) ->
state' & pushStack tokPos LytDeclGuard & insertToken src
state'@((_, LytWhere) : _, _) ->
state' & pushStack tokPos LytDeclGuard & insertToken src
_ ->
state & insertDefault
TokTick ->
case state & collapse indentedP of
((_, LytTick) : stk', acc') ->
(stk', acc') & insertToken src
_ ->
state & collapse offsideEndP & insertSep & insertToken src & pushStack tokPos LytTick
TokComma ->
case state & collapse indentedP of
If we see a LytBrace , then we are in a record type or literal .
state'@((_, LytBrace) : _, _) ->
state' & insertToken src & pushStack tokPos LytProperty
state' ->
state' & insertToken src
TokDot ->
case state & insertDefault of
((_, LytForall) : stk', acc') ->
(stk', acc')
state' ->
state' & pushStack tokPos LytProperty
TokLeftParen ->
state & insertDefault & pushStack tokPos LytParen
TokLeftBrace ->
state & insertDefault & pushStack tokPos LytBrace & pushStack tokPos LytProperty
TokLeftSquare ->
state & insertDefault & pushStack tokPos LytSquare
TokRightParen ->
state & collapse indentedP & popStack (== LytParen) & insertToken src
TokRightBrace ->
state & collapse indentedP & popStack (== LytProperty) & popStack (== LytBrace) & insertToken src
TokRightSquare ->
state & collapse indentedP & popStack (== LytSquare) & insertToken src
TokString _ _ ->
state & insertDefault & popStack (== LytProperty)
TokLowerName [] _ ->
state & insertDefault & popStack (== LytProperty)
TokOperator _ _ ->
state & collapse offsideEndP & insertSep & insertToken src
_ ->
state & insertDefault
insertDefault state =
state & collapse offsideP & insertSep & insertToken src
insertStart lyt state@(stk, _) =
instance foo : : where
foo = 42
case find (isIndented . snd) stk of
Just (pos, _) | srcColumn nextPos <= srcColumn pos -> state
_ -> state & pushStack nextPos lyt & insertToken (lytToken nextPos TokLayoutStart)
insertSep state@(stk, acc) = case stk of
is closed by a separator .
(lytPos, LytTopDecl) : stk' | sepP lytPos ->
(stk', acc) & insertToken sepTok
(lytPos, LytTopDeclHead) : stk' | sepP lytPos ->
(stk', acc) & insertToken sepTok
(lytPos, lyt) : _ | indentSepP lytPos lyt ->
case lyt of
additional LytCaseBinders context for comma masking .
LytOf -> state & insertToken sepTok & pushStack tokPos LytCaseBinders
_ -> state & insertToken sepTok
_ -> state
where
sepTok = lytToken tokPos TokLayoutSep
insertKwProperty k state =
case state & insertDefault of
((_, LytProperty) : stk', acc') ->
(stk', acc')
state' ->
k state'
insertEnd =
insertToken (lytToken tokPos TokLayoutEnd)
insertToken token (stk, acc) =
(stk, acc `snoc` token)
pushStack lytPos lyt (stk, acc) =
((lytPos, lyt) : stk, acc)
popStack p ((_, lyt) : stk', acc)
| p lyt = (stk', acc)
popStack _ state = state
collapse p = uncurry go
where
go ((lytPos, lyt) : stk) acc
| p lytPos lyt =
go stk $ if isIndented lyt
then acc `snoc` lytToken tokPos TokLayoutEnd
else acc
go stk acc = (stk, acc)
indentedP =
const isIndented
offsideP lytPos lyt =
isIndented lyt && srcColumn tokPos < srcColumn lytPos
offsideEndP lytPos lyt =
isIndented lyt && srcColumn tokPos <= srcColumn lytPos
indentSepP lytPos lyt =
isIndented lyt && sepP lytPos
sepP lytPos =
srcColumn tokPos == srcColumn lytPos && srcLine tokPos /= srcLine lytPos
unwindLayout :: SourcePos -> [Comment LineFeed] -> LayoutStack -> [SourceToken]
unwindLayout pos leading = go
where
go [] = []
go ((_, LytRoot) : _) = [SourceToken (TokenAnn (SourceRange pos pos) leading []) TokEof]
go ((_, lyt) : stk) | isIndented lyt = lytToken pos TokLayoutEnd : go stk
go (_ : stk) = go stk
|
a0d88160250a032892e875cb21501191c916e42314fe3209eff62055ad021e7e | astrada/ocaml-extjs | ext_Error.ml | class type t =
object('self)
method toString : Js.js_string Js.t Js.meth
end
class type configs =
object('self)
end
class type events =
object
end
class type statics =
object
method ignore : bool Js.t Js.prop
method notify : bool Js.t Js.prop
method handle : 'self Js.t -> unit Js.meth
method _raise : _ Js.t -> unit Js.meth
end
let get_static () = Js.Unsafe.variable "Ext.Error"
let static = get_static ()
let handle err =
Js.Unsafe.meth_call
static
(Js.Unsafe.variable "handle")
[|Js.Unsafe.inject err; |]
let _raise err =
Js.Unsafe.meth_call
static
(Js.Unsafe.variable "raise")
[|Js.Unsafe.inject err; |]
let of_configs c = Js.Unsafe.coerce c
let to_configs o = Js.Unsafe.coerce o
| null | https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_Error.ml | ocaml | class type t =
object('self)
method toString : Js.js_string Js.t Js.meth
end
class type configs =
object('self)
end
class type events =
object
end
class type statics =
object
method ignore : bool Js.t Js.prop
method notify : bool Js.t Js.prop
method handle : 'self Js.t -> unit Js.meth
method _raise : _ Js.t -> unit Js.meth
end
let get_static () = Js.Unsafe.variable "Ext.Error"
let static = get_static ()
let handle err =
Js.Unsafe.meth_call
static
(Js.Unsafe.variable "handle")
[|Js.Unsafe.inject err; |]
let _raise err =
Js.Unsafe.meth_call
static
(Js.Unsafe.variable "raise")
[|Js.Unsafe.inject err; |]
let of_configs c = Js.Unsafe.coerce c
let to_configs o = Js.Unsafe.coerce o
| |
7035b9eb615077cab7a95f406d87ffd396a74d5638ebc9f4a37dd535f8521fce | KMahoney/kuljet | QueryBuilder.hs | module Database.QueryBuilder
( Expression(..)
, Source(..)
, Query(..)
, Settings(..)
, Order(..)
, buildSqLite
, buildSqLiteExpression
, queryTable
, collectPlaceholders
, columnNames
, applyFilter
, applyOrder
, applyProject
, applyNatJoin
, applyJoin
, applyLimit
, toSql
) where
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Text (Text)
import Control.Monad.Reader
import Database.Sql
data Expression
= EField Text
| EQualifiedField Text Text
| EBinOp Text Expression Expression
| EString Text
| EInt Integer
| ECast Expression Text
| EPlaceholder Integer
| EFn Text [Expression]
| ERaw Text
deriving (Show)
data Source
= SourceTable Text
| SourceQuery Query
deriving (Show)
data Join
= NatJoin Source
| JoinOn Expression Source
deriving (Show)
data Query
= Query
{ columns :: [(Text, Expression)]
, querySource :: Source
, queryJoins :: [Join]
, queryFilter :: Maybe Expression
, queryOrder :: Maybe (Expression, Order)
, queryLimit :: Maybe Expression
}
deriving (Show)
data Order
= OrderAscending
| OrderDescending
deriving (Show)
data Settings
= Settings { placeholderFormat :: Integer -> Sql }
type Build a = Reader Settings a
sqLitePlaceholder :: Integer -> Sql
sqLitePlaceholder =
(\i -> Sql ("?" <> T.pack (show i)))
buildSqLite :: Query -> Sql
buildSqLite =
buildSqlWithPlaceholder sqLitePlaceholder
buildSqLiteExpression :: Expression -> Sql
buildSqLiteExpression =
buildSqlExpressionWithPlaceholder sqLitePlaceholder
buildSqlWithPlaceholder :: (Integer -> Sql) -> Query -> Sql
buildSqlWithPlaceholder f query = runReader (toSql query) (Settings f)
buildSqlExpressionWithPlaceholder :: (Integer -> Sql) -> Expression -> Sql
buildSqlExpressionWithPlaceholder f e = runReader (expressionToSql e) (Settings f)
queryTable :: Text -> [Text] -> Query
queryTable tableName tableColumns =
Query { columns = map (\name -> (name, EField name)) tableColumns
, querySource = SourceTable tableName
, queryJoins = []
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
expandQuery :: Query -> Query
expandQuery query =
Query { columns = columns query
, querySource = SourceQuery query
, queryJoins = []
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
collectPlaceholders :: Query -> [Integer]
collectPlaceholders (Query { columns, querySource, queryJoins, queryFilter }) =
concatMap colPlaceholders columns ++
sourcePlaceholders querySource ++
concatMap joinPlaceholders queryJoins ++
maybe [] expressionPlaceholders queryFilter
where
colPlaceholders (_, e) = expressionPlaceholders e
sourcePlaceholders = \case
SourceTable _ -> []
SourceQuery query -> collectPlaceholders query
joinPlaceholders = \case
NatJoin source -> sourcePlaceholders source
JoinOn e source -> sourcePlaceholders source ++ expressionPlaceholders e
expressionPlaceholders =
\case
EBinOp _ e1 e2 -> expressionPlaceholders e1 ++ expressionPlaceholders e2
ECast e _ -> expressionPlaceholders e
EPlaceholder i -> [i]
_ -> []
columnNames :: Query -> [Text]
columnNames = map fst . columns
applyFilter :: Expression -> Query -> Query
applyFilter expression query@(Query { queryFilter }) =
query { queryFilter = maybe (Just expression) (Just . EBinOp "AND" expression) queryFilter }
applyOrder :: Expression -> Order -> Query -> Query
applyOrder expression order query =
q' { queryOrder = Just (expression, order) }
where
q' =
case queryOrder query of
Just _ -> expandQuery query
Nothing -> query
applyProject :: M.Map Text Expression -> Query -> Query
applyProject newColumns query =
Query { columns = M.toList newColumns
, querySource = SourceQuery query
, queryJoins = []
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
applyNatJoin :: Query -> Query -> Query
applyNatJoin a b =
Query { columns = map selectColumn (S.toList (S.fromList (columnNames a) `S.union` S.fromList (columnNames b)))
, querySource = SourceQuery a
, queryJoins = [NatJoin (SourceQuery b)]
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
where
selectColumn name = (name, EField name)
applyJoin :: Expression -> M.Map Text Expression -> Query -> Query -> Query
applyJoin cond merge a b =
Query { columns = M.toList merge
, querySource = SourceQuery a
, queryJoins = [JoinOn cond (SourceQuery b)]
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
applyLimit :: Expression -> Query -> Query
applyLimit n query =
q' { queryLimit = Just n }
where
q' =
case queryLimit query of
Just _ -> expandQuery query
Nothing -> query
fieldExpressionToSql :: (Text, Expression) -> Build Sql
fieldExpressionToSql (columnName, EField f)
| columnName == f =
return (quoteName columnName)
fieldExpressionToSql (columnName, e) = do
e' <- expressionToSql e
return $ e' <+> "AS" <+> quoteName columnName
expressionToSql :: Expression -> Build Sql
expressionToSql = \case
EField name ->
return (quoteName name)
EQualifiedField table name ->
return $ quoteName table <> "." <> quoteName name
EBinOp op e1 e2 -> do
e1' <- expressionToSql e1
e2' <- expressionToSql e2
return $ parens e1' <+> Sql op <+> parens e2'
EString s ->
return (quoteString s)
EInt i ->
return $ Sql $ T.pack $ show i
ECast e t -> do
e' <- expressionToSql e
return $ "(" <> e' <> ")::" <> Sql t
EPlaceholder i -> do
f <- asks placeholderFormat
return (f i)
EFn name args -> do
args' <- mapM expressionToSql args
return $ Sql name <> "(" <> intercalate ", " args' <> ")"
ERaw x ->
return (Sql x)
sourceToSql :: Source -> Build Sql
sourceToSql (SourceTable name) = return $ quoteName name
sourceToSql (SourceQuery query) = parens <$> toSql query
joinToSql :: Int -> Join -> Build Sql
joinToSql i = \case
NatJoin source -> do
source' <- sourceToSql source
return $ " NATURAL JOIN" <+> source' <+> name
JoinOn e source -> do
e' <- expressionToSql e
source' <- sourceToSql source
return $ " INNER JOIN" <+> source' <+> name <+> "ON (" <> e' <> ")"
where
name = "AS _j" <> Sql (T.pack (show i))
parens :: Sql -> Sql
parens e = "(" <> e <> ")"
toSql :: Query -> Build Sql
toSql (Query { columns, querySource, queryJoins, queryFilter, queryOrder, queryLimit }) = do
columns' <- mapM fieldExpressionToSql columns
querySource' <- sourceToSql querySource
queryJoins' <- joinSql
queryFilter' <- filterSql
queryOrder' <- orderSql
limitSql' <- limitSql
return $
"SELECT" <+> intercalate "," columns' <+>
"FROM" <+> querySource' <> " AS _t" <> queryJoins' <> queryFilter' <> queryOrder' <> limitSql'
where
joinSql =
mconcat <$> mapM (uncurry joinToSql) (zip [(0::Int)..] queryJoins)
filterSql =
case queryFilter of
Nothing -> return ""
Just e -> (" WHERE" <+>) <$> expressionToSql e
orderSql =
case queryOrder of
Nothing -> return ""
Just (e, orderDir) -> (\e' -> " ORDER BY" <+> e' <+> orderDirSql orderDir) <$> expressionToSql e
orderDirSql =
\case
OrderAscending -> "ASC"
OrderDescending -> "DESC"
limitSql =
case queryLimit of
Nothing -> return ""
Just n -> (" LIMIT" <+>) <$> expressionToSql n
| null | https://raw.githubusercontent.com/KMahoney/kuljet/01e32aefd9e59a914c87bde52d5d6660bdea283d/kuljet/src/Database/QueryBuilder.hs | haskell | module Database.QueryBuilder
( Expression(..)
, Source(..)
, Query(..)
, Settings(..)
, Order(..)
, buildSqLite
, buildSqLiteExpression
, queryTable
, collectPlaceholders
, columnNames
, applyFilter
, applyOrder
, applyProject
, applyNatJoin
, applyJoin
, applyLimit
, toSql
) where
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Text (Text)
import Control.Monad.Reader
import Database.Sql
data Expression
= EField Text
| EQualifiedField Text Text
| EBinOp Text Expression Expression
| EString Text
| EInt Integer
| ECast Expression Text
| EPlaceholder Integer
| EFn Text [Expression]
| ERaw Text
deriving (Show)
data Source
= SourceTable Text
| SourceQuery Query
deriving (Show)
data Join
= NatJoin Source
| JoinOn Expression Source
deriving (Show)
data Query
= Query
{ columns :: [(Text, Expression)]
, querySource :: Source
, queryJoins :: [Join]
, queryFilter :: Maybe Expression
, queryOrder :: Maybe (Expression, Order)
, queryLimit :: Maybe Expression
}
deriving (Show)
data Order
= OrderAscending
| OrderDescending
deriving (Show)
data Settings
= Settings { placeholderFormat :: Integer -> Sql }
type Build a = Reader Settings a
sqLitePlaceholder :: Integer -> Sql
sqLitePlaceholder =
(\i -> Sql ("?" <> T.pack (show i)))
buildSqLite :: Query -> Sql
buildSqLite =
buildSqlWithPlaceholder sqLitePlaceholder
buildSqLiteExpression :: Expression -> Sql
buildSqLiteExpression =
buildSqlExpressionWithPlaceholder sqLitePlaceholder
buildSqlWithPlaceholder :: (Integer -> Sql) -> Query -> Sql
buildSqlWithPlaceholder f query = runReader (toSql query) (Settings f)
buildSqlExpressionWithPlaceholder :: (Integer -> Sql) -> Expression -> Sql
buildSqlExpressionWithPlaceholder f e = runReader (expressionToSql e) (Settings f)
queryTable :: Text -> [Text] -> Query
queryTable tableName tableColumns =
Query { columns = map (\name -> (name, EField name)) tableColumns
, querySource = SourceTable tableName
, queryJoins = []
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
expandQuery :: Query -> Query
expandQuery query =
Query { columns = columns query
, querySource = SourceQuery query
, queryJoins = []
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
collectPlaceholders :: Query -> [Integer]
collectPlaceholders (Query { columns, querySource, queryJoins, queryFilter }) =
concatMap colPlaceholders columns ++
sourcePlaceholders querySource ++
concatMap joinPlaceholders queryJoins ++
maybe [] expressionPlaceholders queryFilter
where
colPlaceholders (_, e) = expressionPlaceholders e
sourcePlaceholders = \case
SourceTable _ -> []
SourceQuery query -> collectPlaceholders query
joinPlaceholders = \case
NatJoin source -> sourcePlaceholders source
JoinOn e source -> sourcePlaceholders source ++ expressionPlaceholders e
expressionPlaceholders =
\case
EBinOp _ e1 e2 -> expressionPlaceholders e1 ++ expressionPlaceholders e2
ECast e _ -> expressionPlaceholders e
EPlaceholder i -> [i]
_ -> []
columnNames :: Query -> [Text]
columnNames = map fst . columns
applyFilter :: Expression -> Query -> Query
applyFilter expression query@(Query { queryFilter }) =
query { queryFilter = maybe (Just expression) (Just . EBinOp "AND" expression) queryFilter }
applyOrder :: Expression -> Order -> Query -> Query
applyOrder expression order query =
q' { queryOrder = Just (expression, order) }
where
q' =
case queryOrder query of
Just _ -> expandQuery query
Nothing -> query
applyProject :: M.Map Text Expression -> Query -> Query
applyProject newColumns query =
Query { columns = M.toList newColumns
, querySource = SourceQuery query
, queryJoins = []
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
applyNatJoin :: Query -> Query -> Query
applyNatJoin a b =
Query { columns = map selectColumn (S.toList (S.fromList (columnNames a) `S.union` S.fromList (columnNames b)))
, querySource = SourceQuery a
, queryJoins = [NatJoin (SourceQuery b)]
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
where
selectColumn name = (name, EField name)
applyJoin :: Expression -> M.Map Text Expression -> Query -> Query -> Query
applyJoin cond merge a b =
Query { columns = M.toList merge
, querySource = SourceQuery a
, queryJoins = [JoinOn cond (SourceQuery b)]
, queryFilter = Nothing
, queryOrder = Nothing
, queryLimit = Nothing
}
applyLimit :: Expression -> Query -> Query
applyLimit n query =
q' { queryLimit = Just n }
where
q' =
case queryLimit query of
Just _ -> expandQuery query
Nothing -> query
fieldExpressionToSql :: (Text, Expression) -> Build Sql
fieldExpressionToSql (columnName, EField f)
| columnName == f =
return (quoteName columnName)
fieldExpressionToSql (columnName, e) = do
e' <- expressionToSql e
return $ e' <+> "AS" <+> quoteName columnName
expressionToSql :: Expression -> Build Sql
expressionToSql = \case
EField name ->
return (quoteName name)
EQualifiedField table name ->
return $ quoteName table <> "." <> quoteName name
EBinOp op e1 e2 -> do
e1' <- expressionToSql e1
e2' <- expressionToSql e2
return $ parens e1' <+> Sql op <+> parens e2'
EString s ->
return (quoteString s)
EInt i ->
return $ Sql $ T.pack $ show i
ECast e t -> do
e' <- expressionToSql e
return $ "(" <> e' <> ")::" <> Sql t
EPlaceholder i -> do
f <- asks placeholderFormat
return (f i)
EFn name args -> do
args' <- mapM expressionToSql args
return $ Sql name <> "(" <> intercalate ", " args' <> ")"
ERaw x ->
return (Sql x)
sourceToSql :: Source -> Build Sql
sourceToSql (SourceTable name) = return $ quoteName name
sourceToSql (SourceQuery query) = parens <$> toSql query
joinToSql :: Int -> Join -> Build Sql
joinToSql i = \case
NatJoin source -> do
source' <- sourceToSql source
return $ " NATURAL JOIN" <+> source' <+> name
JoinOn e source -> do
e' <- expressionToSql e
source' <- sourceToSql source
return $ " INNER JOIN" <+> source' <+> name <+> "ON (" <> e' <> ")"
where
name = "AS _j" <> Sql (T.pack (show i))
parens :: Sql -> Sql
parens e = "(" <> e <> ")"
toSql :: Query -> Build Sql
toSql (Query { columns, querySource, queryJoins, queryFilter, queryOrder, queryLimit }) = do
columns' <- mapM fieldExpressionToSql columns
querySource' <- sourceToSql querySource
queryJoins' <- joinSql
queryFilter' <- filterSql
queryOrder' <- orderSql
limitSql' <- limitSql
return $
"SELECT" <+> intercalate "," columns' <+>
"FROM" <+> querySource' <> " AS _t" <> queryJoins' <> queryFilter' <> queryOrder' <> limitSql'
where
joinSql =
mconcat <$> mapM (uncurry joinToSql) (zip [(0::Int)..] queryJoins)
filterSql =
case queryFilter of
Nothing -> return ""
Just e -> (" WHERE" <+>) <$> expressionToSql e
orderSql =
case queryOrder of
Nothing -> return ""
Just (e, orderDir) -> (\e' -> " ORDER BY" <+> e' <+> orderDirSql orderDir) <$> expressionToSql e
orderDirSql =
\case
OrderAscending -> "ASC"
OrderDescending -> "DESC"
limitSql =
case queryLimit of
Nothing -> return ""
Just n -> (" LIMIT" <+>) <$> expressionToSql n
| |
d6fc2723934f9fd1da7b37613e0ee50372935adaa6ff2d7d6175774686b54e0e | haskell/win32 | Win32.hs | # LANGUAGE CPP #
|
Module : Media . Win32
Copyright : 2012 shelarcy
License : BSD - style
Maintainer :
Stability : Provisional
Portability : Non - portable ( Win32 API )
Multimedia API . TODO : provide more functions ...
Module : Media.Win32
Copyright : 2012 shelarcy
License : BSD-style
Maintainer :
Stability : Provisional
Portability : Non-portable (Win32 API)
Multimedia API. TODO: provide more functions ...
-}
module Media.Win32
( module Media.Win32
) where
import Control.Monad ( unless )
import Prelude hiding ( ioError, userError )
import System.IO.Error ( ioError, userError )
import System.Win32.Encoding ( encodeMultiByte, getCurrentCodePage )
import System.Win32.Types
import System.Win32.String ( withTStringBufferLen )
type MCIERROR = DWORD
#include "windows_cconv.h"
mciSendString :: String -> IO ()
mciSendString cmd
= withTString cmd $ \sendCmd -> do
err <- c_mciSendString sendCmd nullPtr 0 nullPtr
unless (err == 0)
$ mciGetErrorString err
foreign import WINDOWS_CCONV safe "windows.h mciSendStringW"
c_mciSendString :: LPCTSTR -> LPTSTR -> UINT -> HANDLE -> IO MCIERROR
mciGetErrorString :: MCIERROR -> IO ()
mciGetErrorString err
= withTStringBufferLen 256 $ \(cstr, len) -> do
failIfFalse_ (unwords ["mciGetErrorString", show err]) $
c_mciGetErrorString err cstr $ fromIntegral len
msg <- peekTString cstr
cp <- getCurrentCodePage
ioError $ userError $ encodeMultiByte cp msg
foreign import WINDOWS_CCONV unsafe "windows.h mciGetErrorStringW"
c_mciGetErrorString :: MCIERROR -> LPTSTR -> UINT -> IO BOOL
| null | https://raw.githubusercontent.com/haskell/win32/e6c0c0f44f6dfc2f8255fc4a5017f4ab67cd0242/Media/Win32.hs | haskell | # LANGUAGE CPP #
|
Module : Media . Win32
Copyright : 2012 shelarcy
License : BSD - style
Maintainer :
Stability : Provisional
Portability : Non - portable ( Win32 API )
Multimedia API . TODO : provide more functions ...
Module : Media.Win32
Copyright : 2012 shelarcy
License : BSD-style
Maintainer :
Stability : Provisional
Portability : Non-portable (Win32 API)
Multimedia API. TODO: provide more functions ...
-}
module Media.Win32
( module Media.Win32
) where
import Control.Monad ( unless )
import Prelude hiding ( ioError, userError )
import System.IO.Error ( ioError, userError )
import System.Win32.Encoding ( encodeMultiByte, getCurrentCodePage )
import System.Win32.Types
import System.Win32.String ( withTStringBufferLen )
type MCIERROR = DWORD
#include "windows_cconv.h"
mciSendString :: String -> IO ()
mciSendString cmd
= withTString cmd $ \sendCmd -> do
err <- c_mciSendString sendCmd nullPtr 0 nullPtr
unless (err == 0)
$ mciGetErrorString err
foreign import WINDOWS_CCONV safe "windows.h mciSendStringW"
c_mciSendString :: LPCTSTR -> LPTSTR -> UINT -> HANDLE -> IO MCIERROR
mciGetErrorString :: MCIERROR -> IO ()
mciGetErrorString err
= withTStringBufferLen 256 $ \(cstr, len) -> do
failIfFalse_ (unwords ["mciGetErrorString", show err]) $
c_mciGetErrorString err cstr $ fromIntegral len
msg <- peekTString cstr
cp <- getCurrentCodePage
ioError $ userError $ encodeMultiByte cp msg
foreign import WINDOWS_CCONV unsafe "windows.h mciGetErrorStringW"
c_mciGetErrorString :: MCIERROR -> LPTSTR -> UINT -> IO BOOL
| |
3bc01c9af418aabbb626a9cb1dc2d0a4556298d75845a8e58c076a1af9d432fb | haskell/cabal | Lib.hs | module Lib where
foreign import javascript foo :: IO ()
| null | https://raw.githubusercontent.com/haskell/cabal/78be2d51faf70f84d30e660af367c25ac23ed1c8/cabal-testsuite/PackageTests/JS/JsSources/srcJS/Lib.hs | haskell | module Lib where
foreign import javascript foo :: IO ()
| |
5d14cdc12135261d81aca15da7ffbbb52c9f44a940a38978504191c4857aac48 | ragkousism/Guix-on-Hurd | fpga.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2016 < >
Copyright © 2016 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages fpga)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix build-system gnu)
#:use-module (guix build-system cmake)
#:use-module (gnu packages)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages tcl)
#:use-module (gnu packages readline)
#:use-module (gnu packages python)
#:use-module (gnu packages bison)
#:use-module (gnu packages flex)
#:use-module (gnu packages gtk)
#:use-module (gnu packages graphviz)
#:use-module (gnu packages libffi)
#:use-module (gnu packages linux)
#:use-module (gnu packages zip)
#:use-module (gnu packages perl)
#:use-module (gnu packages ghostscript)
#:use-module (gnu packages gperf)
#:use-module (gnu packages gawk)
#:use-module (gnu packages version-control)
#:use-module (gnu packages libftdi))
(define-public abc
(let ((commit "5ae4b975c49c")
(revision "1"))
(package
(name "abc")
(version (string-append "0.0-" revision "-" (string-take commit 9)))
(source (origin
(method url-fetch)
(uri
(string-append "/" commit ".zip"))
(file-name (string-append name "-" version "-checkout.zip"))
(sha256
(base32
"1syygi1x40rdryih3galr4q8yg1w5bvdzl75hd27v1xq0l5bz3d0"))))
(build-system gnu-build-system)
(native-inputs
`(("unzip" ,unzip)))
(inputs
`(("readline" ,readline)))
(arguments
`(#:tests? #f ; no check target
#:phases
(modify-phases %standard-phases
(delete 'configure)
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(out-bin (string-append out "/bin")))
(install-file "abc" out-bin)))))))
(home-page "/~alanmi/abc/")
(synopsis "Sequential logic synthesis and formal verification")
(description "ABC is a program for sequential logic synthesis and
formal verification.")
(license
(license:non-copyleft ":MIT#Modern_Variants")))))
(define-public iverilog
(package
(name "iverilog")
(version "10.1.1")
(source (origin
(method url-fetch)
(uri
(string-append "ftp/"
"verilog-" version ".tar.gz"))
(sha256
(base32
"1nnassxvq30rnn0r2p85rkb2zwxk97p109y13x3vr365wzgpbapx"))))
(build-system gnu-build-system)
(native-inputs
`(("flex" ,flex)
("bison" ,bison)
("ghostscript" ,ghostscript))) ; ps2pdf
(home-page "/")
(synopsis "FPGA Verilog simulation and synthesis tool")
(description "Icarus Verilog is a Verilog simulation and synthesis tool.
It operates as a compiler, compiling source code written in Verilog
(IEEE-1364) into some target format.
For batch simulation, the compiler can generate an intermediate form
called vvp assembly.
This intermediate form is executed by the ``vvp'' command.
For synthesis, the compiler generates netlists in the desired format.")
;; GPL2 only because of:
;; - ./driver/iverilog.man.in
;; - ./iverilog-vpi.man.in
;; - ./tgt-fpga/iverilog-fpga.man
;; - ./vvp/vvp.man.in
Otherwise would be + .
You have to accept both and LGPL2.1 + .
(license (list license:gpl2 license:lgpl2.1+))))
(define-public yosys
(package
(name "yosys")
(version "0.7")
(source (origin
(method url-fetch)
(uri
(string-append "/"
name "-" version ".tar.gz"))
(sha256
(base32
"0vkfdn4phvkjqlnpqlr6q5f97bgjc3312vj5jf0vf85zqv88dy9x"))
(file-name (string-append name "-" version "-checkout.tar.gz"))
(modules '((guix build utils)))
(snippet
'(substitute* "Makefile"
(("ABCREV = .*") "ABCREV = default\n")))))
(build-system gnu-build-system)
(arguments
`(#:test-target "test"
#:make-flags (list "CC=gcc"
"CXX=g++"
(string-append "PREFIX=" %output))
#:phases
(modify-phases %standard-phases
(add-before 'configure 'fix-paths
(lambda _
(substitute* "./passes/cmds/show.cc"
(("exec xdot") (string-append "exec " (which "xdot")))
(("dot -") (string-append (which "dot") " -"))
(("fuser") (which "fuser")))
#t))
(replace 'configure
(lambda* (#:key inputs (make-flags '()) #:allow-other-keys)
(zero? (apply system* "make" "config-gcc" make-flags))))
(add-after 'configure 'prepare-abc
(lambda* (#:key inputs #:allow-other-keys)
(let* ((sourceabc (assoc-ref inputs "abc"))
(sourcebin (string-append sourceabc "/bin"))
(source (string-append sourcebin "/abc")))
(mkdir-p "abc")
(call-with-output-file "abc/Makefile"
(lambda (port)
(format port ".PHONY: all\nall:\n\tcp -f abc abc-default\n")))
(copy-file source "abc/abc")
(zero? (system* "chmod" "+w" "abc/abc")))))
(add-before 'check 'fix-iverilog-references
(lambda* (#:key inputs native-inputs #:allow-other-keys)
(let* ((xinputs (or native-inputs inputs))
(xdirname (assoc-ref xinputs "iverilog"))
(iverilog (string-append xdirname "/bin/iverilog")))
(substitute* '("./manual/CHAPTER_StateOfTheArt/synth.sh"
"./manual/CHAPTER_StateOfTheArt/validate_tb.sh"
"./techlibs/ice40/tests/test_bram.sh"
"./techlibs/ice40/tests/test_ffs.sh"
"./techlibs/xilinx/tests/bram1.sh"
"./techlibs/xilinx/tests/bram2.sh"
"./tests/bram/run-single.sh"
"./tests/realmath/run-test.sh"
"./tests/simple/run-test.sh"
"./tests/techmap/mem_simple_4x1_runtest.sh"
"./tests/tools/autotest.sh"
"./tests/vloghtb/common.sh")
(("if ! which iverilog") "if ! true")
(("iverilog ") (string-append iverilog " "))
(("iverilog_bin=\".*\"") (string-append "iverilog_bin=\""
iverilog "\"")))
#t))))))
(native-inputs
`(("pkg-config" ,pkg-config)
("python" ,python)
("bison" ,bison)
("flex" ,flex)
("gawk" , gawk) ; for the tests and "make" progress pretty-printing
("tcl" ,tcl) ; tclsh for the tests
("iverilog" ,iverilog))) ; for the tests
(inputs
`(("tcl" ,tcl)
("readline" ,readline)
("libffi" ,libffi)
("graphviz" ,graphviz)
("psmisc" ,psmisc)
("xdot" ,xdot)
("abc" ,abc)))
(home-page "/")
(synopsis "FPGA Verilog RTL synthesizer")
(description "Yosys synthesizes Verilog-2005.")
(license license:isc)))
(define-public icestorm
(let ((commit "12b2295c9087d94b75e374bb205ae4d76cf17e2f")
(revision "1"))
(package
(name "icestorm")
(version (string-append "0.0-" revision "-" (string-take commit 9)))
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit commit)))
(file-name (string-append name "-" version "-checkout"))
(sha256
(base32
"1mmzlqvap6w8n4qzv3idvy51arkgn03692ssplwncy3akjrbsd2b"))))
(build-system gnu-build-system)
(arguments
`(#:tests? #f ; no unit tests that don't need an FPGA exist.
#:make-flags (list "CC=gcc" "CXX=g++"
(string-append "PREFIX=" (assoc-ref %outputs "out")))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'remove-usr-local
(lambda _
(substitute* "iceprog/Makefile"
(("-I/usr/local/include") "")
(("-L/usr/local/lib") ""))
#t))
(delete 'configure))))
(inputs
`(("libftdi" ,libftdi)))
(native-inputs
`(("python-3" ,python)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Project IceStorm - Lattice iCE40 FPGAs bitstream tools")
(description "Project IceStorm - Lattice iCE40 FPGAs Bitstream Tools.
Includes the actual FTDI connector.")
(license license:isc))))
(define-public arachne-pnr
(let ((commit "52e69ed207342710080d85c7c639480e74a021d7")
(revision "1"))
(package
(name "arachne-pnr")
(version (string-append "0.0-" revision "-" (string-take commit 9)))
(source (origin
(method git-fetch)
(uri (git-reference
(url "-pnr.git")
(commit commit)))
(file-name (string-append name "-" version "-checkout"))
(sha256
(base32
"15bdw5yxj76lxrwksp6liwmr6l1x77isf4bs50ys9rsnmiwh8c3w"))))
(build-system gnu-build-system)
(arguments
`(#:test-target "test"
#:phases (modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs inputs #:allow-other-keys)
(substitute* '("Makefile")
(("DESTDIR = .*") (string-append "DESTDIR = "
(assoc-ref outputs "out")
"\n"))
(("ICEBOX = .*") (string-append "ICEBOX = "
(assoc-ref inputs "icestorm")
"/share/icebox\n")))
(substitute* '("./tests/fsm/generate.py"
"./tests/combinatorial/generate.py")
(("#!/usr/bin/python") "#!/usr/bin/python2"))
#t)))))
(inputs
`(("icestorm" ,icestorm)))
(native-inputs
`(("git" ,git) ; for determining its own version string
("yosys" ,yosys) ; for tests
for shasum
("python-2" ,python-2))) ; for tests
(home-page "-pnr")
(synopsis "Place-and-Route tool for FPGAs")
(description "Arachne-PNR is a Place-and-Route Tool For FPGAs.")
(license license:gpl2))))
(define-public gtkwave
(package
(name "gtkwave")
(version "3.3.76")
(source (origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.gz"))
(sha256
(base32
"1vlvavszb1jwwiixiagld88agjrjg0ix8qa4xnxj4ziw0q87jbmn"))))
(build-system gnu-build-system)
(native-inputs
`(("gperf" ,gperf)
("pkg-config" ,pkg-config)))
(inputs
`(("tcl" ,tcl)
("tk" ,tk)
("gtk+-2" ,gtk+-2)))
(arguments
`(#:configure-flags
(list (string-append "--with-tcl="
(assoc-ref %build-inputs "tcl")
"/lib")
(string-append "--with-tk="
(assoc-ref %build-inputs "tk")
"/lib"))))
(synopsis "Waveform viewer for FPGA simulator trace files")
(description "This package is a waveform viewer for FPGA
simulator trace files (FST).")
(home-page "/")
Exception against free government use in tcl_np.c and tcl_np.h
(license (list license:gpl2+ license:expat license:tcl/tk))))
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/fpga.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
no check target
ps2pdf
GPL2 only because of:
- ./driver/iverilog.man.in
- ./iverilog-vpi.man.in
- ./tgt-fpga/iverilog-fpga.man
- ./vvp/vvp.man.in
for the tests and "make" progress pretty-printing
tclsh for the tests
for the tests
no unit tests that don't need an FPGA exist.
for determining its own version string
for tests
for tests | Copyright © 2016 < >
Copyright © 2016 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages fpga)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix git-download)
#:use-module (guix build-system gnu)
#:use-module (guix build-system cmake)
#:use-module (gnu packages)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages tcl)
#:use-module (gnu packages readline)
#:use-module (gnu packages python)
#:use-module (gnu packages bison)
#:use-module (gnu packages flex)
#:use-module (gnu packages gtk)
#:use-module (gnu packages graphviz)
#:use-module (gnu packages libffi)
#:use-module (gnu packages linux)
#:use-module (gnu packages zip)
#:use-module (gnu packages perl)
#:use-module (gnu packages ghostscript)
#:use-module (gnu packages gperf)
#:use-module (gnu packages gawk)
#:use-module (gnu packages version-control)
#:use-module (gnu packages libftdi))
(define-public abc
(let ((commit "5ae4b975c49c")
(revision "1"))
(package
(name "abc")
(version (string-append "0.0-" revision "-" (string-take commit 9)))
(source (origin
(method url-fetch)
(uri
(string-append "/" commit ".zip"))
(file-name (string-append name "-" version "-checkout.zip"))
(sha256
(base32
"1syygi1x40rdryih3galr4q8yg1w5bvdzl75hd27v1xq0l5bz3d0"))))
(build-system gnu-build-system)
(native-inputs
`(("unzip" ,unzip)))
(inputs
`(("readline" ,readline)))
(arguments
#:phases
(modify-phases %standard-phases
(delete 'configure)
(replace 'install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(out-bin (string-append out "/bin")))
(install-file "abc" out-bin)))))))
(home-page "/~alanmi/abc/")
(synopsis "Sequential logic synthesis and formal verification")
(description "ABC is a program for sequential logic synthesis and
formal verification.")
(license
(license:non-copyleft ":MIT#Modern_Variants")))))
(define-public iverilog
(package
(name "iverilog")
(version "10.1.1")
(source (origin
(method url-fetch)
(uri
(string-append "ftp/"
"verilog-" version ".tar.gz"))
(sha256
(base32
"1nnassxvq30rnn0r2p85rkb2zwxk97p109y13x3vr365wzgpbapx"))))
(build-system gnu-build-system)
(native-inputs
`(("flex" ,flex)
("bison" ,bison)
(home-page "/")
(synopsis "FPGA Verilog simulation and synthesis tool")
(description "Icarus Verilog is a Verilog simulation and synthesis tool.
It operates as a compiler, compiling source code written in Verilog
(IEEE-1364) into some target format.
For batch simulation, the compiler can generate an intermediate form
called vvp assembly.
This intermediate form is executed by the ``vvp'' command.
For synthesis, the compiler generates netlists in the desired format.")
Otherwise would be + .
You have to accept both and LGPL2.1 + .
(license (list license:gpl2 license:lgpl2.1+))))
(define-public yosys
(package
(name "yosys")
(version "0.7")
(source (origin
(method url-fetch)
(uri
(string-append "/"
name "-" version ".tar.gz"))
(sha256
(base32
"0vkfdn4phvkjqlnpqlr6q5f97bgjc3312vj5jf0vf85zqv88dy9x"))
(file-name (string-append name "-" version "-checkout.tar.gz"))
(modules '((guix build utils)))
(snippet
'(substitute* "Makefile"
(("ABCREV = .*") "ABCREV = default\n")))))
(build-system gnu-build-system)
(arguments
`(#:test-target "test"
#:make-flags (list "CC=gcc"
"CXX=g++"
(string-append "PREFIX=" %output))
#:phases
(modify-phases %standard-phases
(add-before 'configure 'fix-paths
(lambda _
(substitute* "./passes/cmds/show.cc"
(("exec xdot") (string-append "exec " (which "xdot")))
(("dot -") (string-append (which "dot") " -"))
(("fuser") (which "fuser")))
#t))
(replace 'configure
(lambda* (#:key inputs (make-flags '()) #:allow-other-keys)
(zero? (apply system* "make" "config-gcc" make-flags))))
(add-after 'configure 'prepare-abc
(lambda* (#:key inputs #:allow-other-keys)
(let* ((sourceabc (assoc-ref inputs "abc"))
(sourcebin (string-append sourceabc "/bin"))
(source (string-append sourcebin "/abc")))
(mkdir-p "abc")
(call-with-output-file "abc/Makefile"
(lambda (port)
(format port ".PHONY: all\nall:\n\tcp -f abc abc-default\n")))
(copy-file source "abc/abc")
(zero? (system* "chmod" "+w" "abc/abc")))))
(add-before 'check 'fix-iverilog-references
(lambda* (#:key inputs native-inputs #:allow-other-keys)
(let* ((xinputs (or native-inputs inputs))
(xdirname (assoc-ref xinputs "iverilog"))
(iverilog (string-append xdirname "/bin/iverilog")))
(substitute* '("./manual/CHAPTER_StateOfTheArt/synth.sh"
"./manual/CHAPTER_StateOfTheArt/validate_tb.sh"
"./techlibs/ice40/tests/test_bram.sh"
"./techlibs/ice40/tests/test_ffs.sh"
"./techlibs/xilinx/tests/bram1.sh"
"./techlibs/xilinx/tests/bram2.sh"
"./tests/bram/run-single.sh"
"./tests/realmath/run-test.sh"
"./tests/simple/run-test.sh"
"./tests/techmap/mem_simple_4x1_runtest.sh"
"./tests/tools/autotest.sh"
"./tests/vloghtb/common.sh")
(("if ! which iverilog") "if ! true")
(("iverilog ") (string-append iverilog " "))
(("iverilog_bin=\".*\"") (string-append "iverilog_bin=\""
iverilog "\"")))
#t))))))
(native-inputs
`(("pkg-config" ,pkg-config)
("python" ,python)
("bison" ,bison)
("flex" ,flex)
(inputs
`(("tcl" ,tcl)
("readline" ,readline)
("libffi" ,libffi)
("graphviz" ,graphviz)
("psmisc" ,psmisc)
("xdot" ,xdot)
("abc" ,abc)))
(home-page "/")
(synopsis "FPGA Verilog RTL synthesizer")
(description "Yosys synthesizes Verilog-2005.")
(license license:isc)))
(define-public icestorm
(let ((commit "12b2295c9087d94b75e374bb205ae4d76cf17e2f")
(revision "1"))
(package
(name "icestorm")
(version (string-append "0.0-" revision "-" (string-take commit 9)))
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit commit)))
(file-name (string-append name "-" version "-checkout"))
(sha256
(base32
"1mmzlqvap6w8n4qzv3idvy51arkgn03692ssplwncy3akjrbsd2b"))))
(build-system gnu-build-system)
(arguments
#:make-flags (list "CC=gcc" "CXX=g++"
(string-append "PREFIX=" (assoc-ref %outputs "out")))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'remove-usr-local
(lambda _
(substitute* "iceprog/Makefile"
(("-I/usr/local/include") "")
(("-L/usr/local/lib") ""))
#t))
(delete 'configure))))
(inputs
`(("libftdi" ,libftdi)))
(native-inputs
`(("python-3" ,python)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Project IceStorm - Lattice iCE40 FPGAs bitstream tools")
(description "Project IceStorm - Lattice iCE40 FPGAs Bitstream Tools.
Includes the actual FTDI connector.")
(license license:isc))))
(define-public arachne-pnr
(let ((commit "52e69ed207342710080d85c7c639480e74a021d7")
(revision "1"))
(package
(name "arachne-pnr")
(version (string-append "0.0-" revision "-" (string-take commit 9)))
(source (origin
(method git-fetch)
(uri (git-reference
(url "-pnr.git")
(commit commit)))
(file-name (string-append name "-" version "-checkout"))
(sha256
(base32
"15bdw5yxj76lxrwksp6liwmr6l1x77isf4bs50ys9rsnmiwh8c3w"))))
(build-system gnu-build-system)
(arguments
`(#:test-target "test"
#:phases (modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs inputs #:allow-other-keys)
(substitute* '("Makefile")
(("DESTDIR = .*") (string-append "DESTDIR = "
(assoc-ref outputs "out")
"\n"))
(("ICEBOX = .*") (string-append "ICEBOX = "
(assoc-ref inputs "icestorm")
"/share/icebox\n")))
(substitute* '("./tests/fsm/generate.py"
"./tests/combinatorial/generate.py")
(("#!/usr/bin/python") "#!/usr/bin/python2"))
#t)))))
(inputs
`(("icestorm" ,icestorm)))
(native-inputs
for shasum
(home-page "-pnr")
(synopsis "Place-and-Route tool for FPGAs")
(description "Arachne-PNR is a Place-and-Route Tool For FPGAs.")
(license license:gpl2))))
(define-public gtkwave
(package
(name "gtkwave")
(version "3.3.76")
(source (origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.gz"))
(sha256
(base32
"1vlvavszb1jwwiixiagld88agjrjg0ix8qa4xnxj4ziw0q87jbmn"))))
(build-system gnu-build-system)
(native-inputs
`(("gperf" ,gperf)
("pkg-config" ,pkg-config)))
(inputs
`(("tcl" ,tcl)
("tk" ,tk)
("gtk+-2" ,gtk+-2)))
(arguments
`(#:configure-flags
(list (string-append "--with-tcl="
(assoc-ref %build-inputs "tcl")
"/lib")
(string-append "--with-tk="
(assoc-ref %build-inputs "tk")
"/lib"))))
(synopsis "Waveform viewer for FPGA simulator trace files")
(description "This package is a waveform viewer for FPGA
simulator trace files (FST).")
(home-page "/")
Exception against free government use in tcl_np.c and tcl_np.h
(license (list license:gpl2+ license:expat license:tcl/tk))))
|
84219ad534f7381311e034b4be49b5fdcfa332ef30ae0f5fab8b16af505c3d07 | clojupyter/clojupyter | unlink_actions.clj | (ns clojupyter.install.conda.unlink-actions
"The functions in this namespace are used to remove Clojupyter from an end-user machine on which
it is installed using `conda install`. Under normal circumstances it is never used by the user
directly, but is called by the Conda installer as part of the removal procedure.
Functions whose name begins with 's*' return a single-argument function accepting and returning
a state map."
(:require [clojupyter.install.conda.env :as env]
[clojupyter.install.conda.link-actions :as link!]
[clojupyter.install.filemap :as fm]
[clojupyter.install.conda.conda-specs :as csp]
[clojupyter.install.local-specs :as lsp]
[clojupyter.util-actions :as u!]
[clojure.spec.alpha :as s]))
(def LSP-DEPEND [csp/DEPEND-DUMMY lsp/DEPEND-DUMMY])
(use 'clojure.pprint)
;;; ----------------------------------------------------------------------------------------------------
EXTERNAL
;;; ----------------------------------------------------------------------------------------------------
(defn get-unlink-environment
"Action returning the data about the environment needed to remove the Conda-installed Clojupyter
kernel."
([] (get-unlink-environment (env/PREFIX)))
([prefix]
(let [prefix (or prefix (env/PREFIX))
kernel-dir (link!/conda-clojupyter-kernel-dir prefix)
env {:conda-link/prefix prefix
:conda-unlink/kernel-dir kernel-dir
:local/filemap (fm/filemap prefix kernel-dir)}]
(if (s/valid? :conda-unlink/env env)
env
(u!/throw-info "get-unlink-environment: internal error"
{:prefix prefix, :env env,
:explain-str (s/explain-str :conda-unlink/env env)})))))
| null | https://raw.githubusercontent.com/clojupyter/clojupyter/b54b30b5efa115937b7a85e708a7402bd9efa0ab/src/clojupyter/install/conda/unlink_actions.clj | clojure | ----------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------- | (ns clojupyter.install.conda.unlink-actions
"The functions in this namespace are used to remove Clojupyter from an end-user machine on which
it is installed using `conda install`. Under normal circumstances it is never used by the user
directly, but is called by the Conda installer as part of the removal procedure.
Functions whose name begins with 's*' return a single-argument function accepting and returning
a state map."
(:require [clojupyter.install.conda.env :as env]
[clojupyter.install.conda.link-actions :as link!]
[clojupyter.install.filemap :as fm]
[clojupyter.install.conda.conda-specs :as csp]
[clojupyter.install.local-specs :as lsp]
[clojupyter.util-actions :as u!]
[clojure.spec.alpha :as s]))
(def LSP-DEPEND [csp/DEPEND-DUMMY lsp/DEPEND-DUMMY])
(use 'clojure.pprint)
EXTERNAL
(defn get-unlink-environment
"Action returning the data about the environment needed to remove the Conda-installed Clojupyter
kernel."
([] (get-unlink-environment (env/PREFIX)))
([prefix]
(let [prefix (or prefix (env/PREFIX))
kernel-dir (link!/conda-clojupyter-kernel-dir prefix)
env {:conda-link/prefix prefix
:conda-unlink/kernel-dir kernel-dir
:local/filemap (fm/filemap prefix kernel-dir)}]
(if (s/valid? :conda-unlink/env env)
env
(u!/throw-info "get-unlink-environment: internal error"
{:prefix prefix, :env env,
:explain-str (s/explain-str :conda-unlink/env env)})))))
|
9fd3a6670c61fb44aa2fe115bb9757c3f4b74424395f9bc83231a35a1f846417 | alanforr/complex | bms.clj | (ns bms
(:require [criterium.core :as c])
(:use [complex.core]
[clojure.test]))
(def c1 (complex 1 2))
(def c2 (complex 2 4))
c1
c2
(c/bench (dotimes [_ 1000] (+ c1 c2)))
(c/bench (dotimes [_ 1000] (+ c1 c2 2)))
(c/bench (dotimes [_ 1000] (+ c1 c2 2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (+ c1 c2 2 c1 c1 c1 c2 c2 c2)))
(c/bench (dotimes [_ 1000] (+ c1 c2 2 c1 c1 c1 c2 c2 c2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (* c1 c2)))
(c/bench (dotimes [_ 1000] (* c1 c2 2)))
(c/bench (dotimes [_ 1000] (* c1 c2 2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (* c1 c2 2 c1 c1 c1 c2 c2 c2)))
(c/bench (dotimes [_ 1000] (* c1 c2 2 c1 c1 c1 c2 c2 c2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (- c1 c2)))
(c/bench (dotimes [_ 1000] (- c1 c2 2)))
(c/bench (dotimes [_ 1000] (- c1 c2 2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (- c1 c2 2 c1 c1 c1 c2 c2 c2)))
(c/bench (dotimes [_ 1000] (- c1 c2 2 c1 c1 c1 c2 c2 c2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (/ c1 c2)))
(c/bench (dotimes [_ 1000] (/ c1 c2 2)))
(c/bench (dotimes [_ 1000] (/ c1 c2 2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (/ c1 c2 2 c1 c1 c1 c2 c2 c2)))
(c/bench (dotimes [_ 1000] (/ c1 c2 2 c1 c1 c1 c2 c2 c2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (sin c1)))
(c/bench (dotimes [_ 1000] (sin 1)))
| null | https://raw.githubusercontent.com/alanforr/complex/3cdd2d5c9c95454cc549b217acc368cc76f2416b/test/bms.clj | clojure | (ns bms
(:require [criterium.core :as c])
(:use [complex.core]
[clojure.test]))
(def c1 (complex 1 2))
(def c2 (complex 2 4))
c1
c2
(c/bench (dotimes [_ 1000] (+ c1 c2)))
(c/bench (dotimes [_ 1000] (+ c1 c2 2)))
(c/bench (dotimes [_ 1000] (+ c1 c2 2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (+ c1 c2 2 c1 c1 c1 c2 c2 c2)))
(c/bench (dotimes [_ 1000] (+ c1 c2 2 c1 c1 c1 c2 c2 c2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (* c1 c2)))
(c/bench (dotimes [_ 1000] (* c1 c2 2)))
(c/bench (dotimes [_ 1000] (* c1 c2 2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (* c1 c2 2 c1 c1 c1 c2 c2 c2)))
(c/bench (dotimes [_ 1000] (* c1 c2 2 c1 c1 c1 c2 c2 c2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (- c1 c2)))
(c/bench (dotimes [_ 1000] (- c1 c2 2)))
(c/bench (dotimes [_ 1000] (- c1 c2 2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (- c1 c2 2 c1 c1 c1 c2 c2 c2)))
(c/bench (dotimes [_ 1000] (- c1 c2 2 c1 c1 c1 c2 c2 c2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (/ c1 c2)))
(c/bench (dotimes [_ 1000] (/ c1 c2 2)))
(c/bench (dotimes [_ 1000] (/ c1 c2 2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (/ c1 c2 2 c1 c1 c1 c2 c2 c2)))
(c/bench (dotimes [_ 1000] (/ c1 c2 2 c1 c1 c1 c2 c2 c2 c1 c1 c1)))
(c/bench (dotimes [_ 1000] (sin c1)))
(c/bench (dotimes [_ 1000] (sin 1)))
| |
c30058c0e08a2ecfb71688084bd66919ec53f8719f91d0e0019a30aa944442de | input-output-hk/cardano-sl | CLI.hs | {- | The module which contains parsing facilities for
the CLI options passed to this edge node.
-}
module Cardano.Wallet.Server.CLI where
import Universum
import Data.Time.Units (Minute)
import Data.Version (showVersion)
import Options.Applicative (Parser, auto, execParser, footerDoc,
fullDesc, header, help, helper, info, infoOption, long,
metavar, option, progDesc, strOption, switch, value)
import Paths_cardano_sl (version)
import Pos.Client.CLI (CommonNodeArgs (..))
import qualified Pos.Client.CLI as CLI
import Pos.Core.NetworkAddress (NetworkAddress, localhost)
import Pos.Util.CompileInfo (CompileTimeInfo (..), HasCompileInfo,
compileInfo)
import Pos.Web (TlsParams (..))
-- | The options parsed from the CLI when starting up this wallet node.
-- This umbrella data type includes the node-specific options for this edge node
-- plus the wallet backend specific options.
data WalletStartupOptions = WalletStartupOptions {
wsoNodeArgs :: !CommonNodeArgs
, wsoWalletBackendParams :: !WalletBackendParams
} deriving Show
-- | DB-specific options.
data WalletDBOptions = WalletDBOptions {
walletDbPath :: !FilePath
^ The path for the wallet - backend DB .
, walletRebuildDb :: !Bool
-- ^ Whether or not to wipe and rebuild the DB.
, walletAcidInterval :: !Minute
^ The delay between one operation on the acid - state DB and the other .
-- Such @operation@ entails things like checkpointing the DB.
, walletFlushDb :: !Bool
} deriving Show
-- | The startup parameters for the legacy wallet backend.
-- Named with the suffix `Params` to honour other types of
parameters like ` NodeParams ` or ` SscParams ` .
data WalletBackendParams = WalletBackendParams
{ enableMonitoringApi :: !Bool
-- ^ Whether or not to run the monitoring API.
, monitoringApiPort :: !Word16
-- ^ The port the monitoring API should listen to.
, walletTLSParams :: !(Maybe TlsParams)
-- ^ The TLS parameters.
, walletAddress :: !NetworkAddress
-- ^ The wallet address.
, walletDocAddress :: !(Maybe NetworkAddress)
-- ^ The wallet documentation address.
, walletRunMode :: !RunMode
-- ^ The mode this node is running in.
, walletDbOptions :: !WalletDBOptions
-- ^ DB-specific options.
, forceFullMigration :: !Bool
} deriving Show
getWalletDbOptions :: WalletBackendParams -> WalletDBOptions
getWalletDbOptions WalletBackendParams{..} =
walletDbOptions
getFullMigrationFlag :: WalletBackendParams -> Bool
getFullMigrationFlag WalletBackendParams{..} =
forceFullMigration
-- | A richer type to specify in which mode we are running this node.
data RunMode = ProductionMode
-- ^ Run in production mode
| DebugMode
-- ^ Run in debug mode
deriving Show
-- | Converts a @GenesisKeysInclusion@ into a @Bool@.
isDebugMode :: RunMode -> Bool
isDebugMode ProductionMode = False
isDebugMode DebugMode = True
-- | Parses and returns the @WalletStartupOptions@ from the command line.
getWalletNodeOptions :: HasCompileInfo => IO WalletStartupOptions
getWalletNodeOptions = execParser programInfo
where
programInfo = info (helper <*> versionOption <*> walletStartupOptionsParser) $
fullDesc <> progDesc "Cardano SL edge node w/ wallet."
<> header "Cardano SL edge node."
<> footerDoc CLI.usageExample
versionOption = infoOption
("cardano-node-" <> showVersion version <>
", git revision " <> toString (ctiGitRevision compileInfo))
(long "version" <> help "Show version.")
-- | The main @Parser@ for the @WalletStartupOptions@
walletStartupOptionsParser :: Parser WalletStartupOptions
walletStartupOptionsParser = WalletStartupOptions <$> CLI.commonNodeArgsParser
<*> walletBackendParamsParser
-- | The @Parser@ for the @WalletBackendParams@.
walletBackendParamsParser :: Parser WalletBackendParams
walletBackendParamsParser = WalletBackendParams <$> enableMonitoringApiParser
<*> monitoringApiPortParser
<*> tlsParamsParser
<*> addressParser
<*> docAddressParser
<*> runModeParser
<*> dbOptionsParser
<*> forceFullMigrationParser
where
enableMonitoringApiParser :: Parser Bool
enableMonitoringApiParser = switch (long "monitoring-api" <>
help "Activate the node monitoring API."
)
monitoringApiPortParser :: Parser Word16
monitoringApiPortParser = CLI.webPortOption 8080 "Port for the monitoring API."
addressParser :: Parser NetworkAddress
addressParser = CLI.walletAddressOption $ Just (localhost, 8090)
docAddressParser :: Parser (Maybe NetworkAddress)
docAddressParser = CLI.docAddressOption Nothing
runModeParser :: Parser RunMode
runModeParser = (\debugMode -> if debugMode then DebugMode else ProductionMode) <$>
switch (long "wallet-debug" <>
help "Run wallet with debug params (e.g. include \
\all the genesis keys in the set of secret keys)."
)
forceFullMigrationParser :: Parser Bool
forceFullMigrationParser = switch $
long "force-full-wallet-migration" <>
help "Enforces a non-lenient migration. \
\If something fails (for example a wallet fails to decode from the old format) \
\migration will stop and the node will crash, \
\instead of just logging the error."
tlsParamsParser :: Parser (Maybe TlsParams)
tlsParamsParser = constructTlsParams <$> certPathParser
<*> keyPathParser
<*> caPathParser
<*> (not <$> noClientAuthParser)
<*> disabledParser
where
constructTlsParams tpCertPath tpKeyPath tpCaPath tpClientAuth disabled =
guard (not disabled) $> TlsParams{..}
certPathParser :: Parser FilePath
certPathParser = strOption (CLI.templateParser
"tlscert"
"FILEPATH"
"Path to file with TLS certificate"
<> value "scripts/tls-files/server.crt"
)
keyPathParser :: Parser FilePath
keyPathParser = strOption (CLI.templateParser
"tlskey"
"FILEPATH"
"Path to file with TLS key"
<> value "scripts/tls-files/server.key"
)
caPathParser :: Parser FilePath
caPathParser = strOption (CLI.templateParser
"tlsca"
"FILEPATH"
"Path to file with TLS certificate authority"
<> value "scripts/tls-files/ca.crt"
)
noClientAuthParser :: Parser Bool
noClientAuthParser = switch $
long "no-client-auth" <>
help "Disable TLS client verification. If turned on, \
\no client certificate is required to talk to \
\the API."
disabledParser :: Parser Bool
disabledParser = switch $
long "no-tls" <>
help "Disable tls. If set, 'tlscert', 'tlskey' \
\and 'tlsca' options are ignored"
-- | The parser for the @WalletDBOptions@.
dbOptionsParser :: Parser WalletDBOptions
dbOptionsParser = WalletDBOptions <$> dbPathParser
<*> rebuildDbParser
<*> acidIntervalParser
<*> flushDbParser
where
dbPathParser :: Parser FilePath
dbPathParser = strOption (long "wallet-db-path" <>
help "Path to the wallet's database." <>
value "wallet-db"
)
rebuildDbParser :: Parser Bool
rebuildDbParser = switch (long "wallet-rebuild-db" <>
help "If wallet's database already exists, discard \
\its contents and create a new one from scratch."
)
acidIntervalParser :: Parser Minute
acidIntervalParser = fromInteger <$>
option auto (long "wallet-acid-cleanup-interval" <>
help "Interval on which to execute wallet cleanup \
\action (create checkpoint and archive and \
\cleanup archive partially)" <>
metavar "MINUTES" <>
value 5
)
flushDbParser :: Parser Bool
flushDbParser = switch (long "flush-wallet-db" <>
help "Flushes all blockchain-recoverable data from DB \
\(everything excluding wallets/accounts/addresses, \
\metadata)"
)
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/wallet/src/Cardano/Wallet/Server/CLI.hs | haskell | | The module which contains parsing facilities for
the CLI options passed to this edge node.
| The options parsed from the CLI when starting up this wallet node.
This umbrella data type includes the node-specific options for this edge node
plus the wallet backend specific options.
| DB-specific options.
^ Whether or not to wipe and rebuild the DB.
Such @operation@ entails things like checkpointing the DB.
| The startup parameters for the legacy wallet backend.
Named with the suffix `Params` to honour other types of
^ Whether or not to run the monitoring API.
^ The port the monitoring API should listen to.
^ The TLS parameters.
^ The wallet address.
^ The wallet documentation address.
^ The mode this node is running in.
^ DB-specific options.
| A richer type to specify in which mode we are running this node.
^ Run in production mode
^ Run in debug mode
| Converts a @GenesisKeysInclusion@ into a @Bool@.
| Parses and returns the @WalletStartupOptions@ from the command line.
| The main @Parser@ for the @WalletStartupOptions@
| The @Parser@ for the @WalletBackendParams@.
| The parser for the @WalletDBOptions@. | module Cardano.Wallet.Server.CLI where
import Universum
import Data.Time.Units (Minute)
import Data.Version (showVersion)
import Options.Applicative (Parser, auto, execParser, footerDoc,
fullDesc, header, help, helper, info, infoOption, long,
metavar, option, progDesc, strOption, switch, value)
import Paths_cardano_sl (version)
import Pos.Client.CLI (CommonNodeArgs (..))
import qualified Pos.Client.CLI as CLI
import Pos.Core.NetworkAddress (NetworkAddress, localhost)
import Pos.Util.CompileInfo (CompileTimeInfo (..), HasCompileInfo,
compileInfo)
import Pos.Web (TlsParams (..))
data WalletStartupOptions = WalletStartupOptions {
wsoNodeArgs :: !CommonNodeArgs
, wsoWalletBackendParams :: !WalletBackendParams
} deriving Show
data WalletDBOptions = WalletDBOptions {
walletDbPath :: !FilePath
^ The path for the wallet - backend DB .
, walletRebuildDb :: !Bool
, walletAcidInterval :: !Minute
^ The delay between one operation on the acid - state DB and the other .
, walletFlushDb :: !Bool
} deriving Show
parameters like ` NodeParams ` or ` SscParams ` .
data WalletBackendParams = WalletBackendParams
{ enableMonitoringApi :: !Bool
, monitoringApiPort :: !Word16
, walletTLSParams :: !(Maybe TlsParams)
, walletAddress :: !NetworkAddress
, walletDocAddress :: !(Maybe NetworkAddress)
, walletRunMode :: !RunMode
, walletDbOptions :: !WalletDBOptions
, forceFullMigration :: !Bool
} deriving Show
getWalletDbOptions :: WalletBackendParams -> WalletDBOptions
getWalletDbOptions WalletBackendParams{..} =
walletDbOptions
getFullMigrationFlag :: WalletBackendParams -> Bool
getFullMigrationFlag WalletBackendParams{..} =
forceFullMigration
data RunMode = ProductionMode
| DebugMode
deriving Show
isDebugMode :: RunMode -> Bool
isDebugMode ProductionMode = False
isDebugMode DebugMode = True
getWalletNodeOptions :: HasCompileInfo => IO WalletStartupOptions
getWalletNodeOptions = execParser programInfo
where
programInfo = info (helper <*> versionOption <*> walletStartupOptionsParser) $
fullDesc <> progDesc "Cardano SL edge node w/ wallet."
<> header "Cardano SL edge node."
<> footerDoc CLI.usageExample
versionOption = infoOption
("cardano-node-" <> showVersion version <>
", git revision " <> toString (ctiGitRevision compileInfo))
(long "version" <> help "Show version.")
walletStartupOptionsParser :: Parser WalletStartupOptions
walletStartupOptionsParser = WalletStartupOptions <$> CLI.commonNodeArgsParser
<*> walletBackendParamsParser
walletBackendParamsParser :: Parser WalletBackendParams
walletBackendParamsParser = WalletBackendParams <$> enableMonitoringApiParser
<*> monitoringApiPortParser
<*> tlsParamsParser
<*> addressParser
<*> docAddressParser
<*> runModeParser
<*> dbOptionsParser
<*> forceFullMigrationParser
where
enableMonitoringApiParser :: Parser Bool
enableMonitoringApiParser = switch (long "monitoring-api" <>
help "Activate the node monitoring API."
)
monitoringApiPortParser :: Parser Word16
monitoringApiPortParser = CLI.webPortOption 8080 "Port for the monitoring API."
addressParser :: Parser NetworkAddress
addressParser = CLI.walletAddressOption $ Just (localhost, 8090)
docAddressParser :: Parser (Maybe NetworkAddress)
docAddressParser = CLI.docAddressOption Nothing
runModeParser :: Parser RunMode
runModeParser = (\debugMode -> if debugMode then DebugMode else ProductionMode) <$>
switch (long "wallet-debug" <>
help "Run wallet with debug params (e.g. include \
\all the genesis keys in the set of secret keys)."
)
forceFullMigrationParser :: Parser Bool
forceFullMigrationParser = switch $
long "force-full-wallet-migration" <>
help "Enforces a non-lenient migration. \
\If something fails (for example a wallet fails to decode from the old format) \
\migration will stop and the node will crash, \
\instead of just logging the error."
tlsParamsParser :: Parser (Maybe TlsParams)
tlsParamsParser = constructTlsParams <$> certPathParser
<*> keyPathParser
<*> caPathParser
<*> (not <$> noClientAuthParser)
<*> disabledParser
where
constructTlsParams tpCertPath tpKeyPath tpCaPath tpClientAuth disabled =
guard (not disabled) $> TlsParams{..}
certPathParser :: Parser FilePath
certPathParser = strOption (CLI.templateParser
"tlscert"
"FILEPATH"
"Path to file with TLS certificate"
<> value "scripts/tls-files/server.crt"
)
keyPathParser :: Parser FilePath
keyPathParser = strOption (CLI.templateParser
"tlskey"
"FILEPATH"
"Path to file with TLS key"
<> value "scripts/tls-files/server.key"
)
caPathParser :: Parser FilePath
caPathParser = strOption (CLI.templateParser
"tlsca"
"FILEPATH"
"Path to file with TLS certificate authority"
<> value "scripts/tls-files/ca.crt"
)
noClientAuthParser :: Parser Bool
noClientAuthParser = switch $
long "no-client-auth" <>
help "Disable TLS client verification. If turned on, \
\no client certificate is required to talk to \
\the API."
disabledParser :: Parser Bool
disabledParser = switch $
long "no-tls" <>
help "Disable tls. If set, 'tlscert', 'tlskey' \
\and 'tlsca' options are ignored"
dbOptionsParser :: Parser WalletDBOptions
dbOptionsParser = WalletDBOptions <$> dbPathParser
<*> rebuildDbParser
<*> acidIntervalParser
<*> flushDbParser
where
dbPathParser :: Parser FilePath
dbPathParser = strOption (long "wallet-db-path" <>
help "Path to the wallet's database." <>
value "wallet-db"
)
rebuildDbParser :: Parser Bool
rebuildDbParser = switch (long "wallet-rebuild-db" <>
help "If wallet's database already exists, discard \
\its contents and create a new one from scratch."
)
acidIntervalParser :: Parser Minute
acidIntervalParser = fromInteger <$>
option auto (long "wallet-acid-cleanup-interval" <>
help "Interval on which to execute wallet cleanup \
\action (create checkpoint and archive and \
\cleanup archive partially)" <>
metavar "MINUTES" <>
value 5
)
flushDbParser :: Parser Bool
flushDbParser = switch (long "flush-wallet-db" <>
help "Flushes all blockchain-recoverable data from DB \
\(everything excluding wallets/accounts/addresses, \
\metadata)"
)
|
a72e30c4199fab76b223b23e317260ff42b751b019b6a813d85919e33cbc4882 | mirage/xentropyd | writeBufferStream.mli |
* Copyright ( C ) Citrix Systems Inc.
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (C) Citrix Systems Inc.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module Make(Space: S.READABLE
with type position = int64
and type item = Cstruct.t) : sig
* Create a buffered STREAM intended for Writing on top of an unbuffered
one
one *)
include S.READABLE
with type position = int64
and type item = Cstruct.t
val attach: Space.stream -> Cstruct.t -> stream
(** [attach stream buffer] return a buffered READABLE layered on top of
[stream]. Data buffers read from here will be buffered, and only flushed
to the underlying stream when [advance] is called.
This call does not initialise [buffer]. *)
val create: Space.stream -> Cstruct.t -> stream
(** [create stream buffer] return a buffered READABLE layered on top of
[stream]. Initialises the [buffer]. *)
end
| null | https://raw.githubusercontent.com/mirage/xentropyd/4705bb2f6c10ae84f842a5c39cd8a513ea8c761a/core/writeBufferStream.mli | ocaml | * [attach stream buffer] return a buffered READABLE layered on top of
[stream]. Data buffers read from here will be buffered, and only flushed
to the underlying stream when [advance] is called.
This call does not initialise [buffer].
* [create stream buffer] return a buffered READABLE layered on top of
[stream]. Initialises the [buffer]. |
* Copyright ( C ) Citrix Systems Inc.
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (C) Citrix Systems Inc.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module Make(Space: S.READABLE
with type position = int64
and type item = Cstruct.t) : sig
* Create a buffered STREAM intended for Writing on top of an unbuffered
one
one *)
include S.READABLE
with type position = int64
and type item = Cstruct.t
val attach: Space.stream -> Cstruct.t -> stream
val create: Space.stream -> Cstruct.t -> stream
end
|
faab82f228a12cb5158037d16645efea3f5824c57beb54dccbb112c084730ef1 | nitrogen/NitrogenProject.com | website_config_handler.erl | Nitrogen Web Framework for Erlang
Copyright ( c ) 2008 - 2010
See MIT - LICENSE for licensing information .
-module (website_config_handler).
-include_lib ("nitrogen_core/include/wf.hrl").
-behaviour (config_handler).
-export ([
init/2,
finish/2,
get_value/4,
get_values/4
]).
init(_Config, _State) ->
{ok, []}.
finish(_Config, _State) ->
{ok, []}.
get_value(Key, DefaultValue, Config, State) ->
case get_values(Key, [DefaultValue], Config, State) of
[Value] ->
Value;
Values ->
error_logger:error_msg("Too many matching config values for key: ~p~n", [Key]),
throw({nitrogen_error, too_many_matching_values, Key, Values})
end.
get_values(Key, DefaultValue, _Config, _State) ->
case application:get_env(nitrogen_website, Key) of
{ok, Value} ->
[Value];
undefined ->
DefaultValue
end.
| null | https://raw.githubusercontent.com/nitrogen/NitrogenProject.com/b4b3a0dbe17394608d2ee6eaa089e3ece1285075/src/website_config_handler.erl | erlang | Nitrogen Web Framework for Erlang
Copyright ( c ) 2008 - 2010
See MIT - LICENSE for licensing information .
-module (website_config_handler).
-include_lib ("nitrogen_core/include/wf.hrl").
-behaviour (config_handler).
-export ([
init/2,
finish/2,
get_value/4,
get_values/4
]).
init(_Config, _State) ->
{ok, []}.
finish(_Config, _State) ->
{ok, []}.
get_value(Key, DefaultValue, Config, State) ->
case get_values(Key, [DefaultValue], Config, State) of
[Value] ->
Value;
Values ->
error_logger:error_msg("Too many matching config values for key: ~p~n", [Key]),
throw({nitrogen_error, too_many_matching_values, Key, Values})
end.
get_values(Key, DefaultValue, _Config, _State) ->
case application:get_env(nitrogen_website, Key) of
{ok, Value} ->
[Value];
undefined ->
DefaultValue
end.
| |
8c79099bac6f7fa1c9ed77b3112a58f3581e5977fda8602da9cb46acf83cfe39 | tek/chiasma | TmuxClient.hs | module Chiasma.Interpreter.TmuxClient where
import Conc (interpretAtomic)
import Data.Sequence ((|>))
import qualified Data.Text as Text
import Exon (exon)
import qualified Log as Log
import Path (Abs, File, Path, relfile, toFilePath)
import Polysemy.Process.Interpreter.Process (ProcessQueues)
import qualified Process as Process
import Process (
OutputPipe (Stderr, Stdout),
Process,
ProcessError,
SystemProcess,
SystemProcessError,
SystemProcessScopeError,
interpretProcessInputId,
interpretProcessOutputLeft,
interpretProcessOutputTextLines,
interpretProcess_,
interpretSystemProcessNative_,
resolveExecutable,
withProcess_,
)
import System.Process.Typed (ProcessConfig, proc)
import qualified Chiasma.Data.TmuxError as TmuxError
import Chiasma.Data.TmuxError (TmuxError (NoExe))
import Chiasma.Data.TmuxNative (TmuxNative (TmuxNative))
import qualified Chiasma.Data.TmuxOutputBlock as TmuxOutputBlock
import Chiasma.Data.TmuxOutputBlock (TmuxOutputBlock)
import qualified Chiasma.Data.TmuxRequest as TmuxRequest
import Chiasma.Data.TmuxRequest (TmuxRequest (TmuxRequest))
import Chiasma.Data.TmuxResponse (TmuxResponse (TmuxResponse))
import qualified Chiasma.Effect.TmuxClient as TmuxClient
import Chiasma.Effect.TmuxClient (TmuxClient)
import Chiasma.Interpreter.ProcessOutput (interpretProcessOutputTmuxBlock)
type TmuxQueues =
ProcessQueues (Either Text TmuxOutputBlock) Text
type TmuxProc =
Process ByteString (Either Text TmuxOutputBlock)
validate :: TmuxRequest -> TmuxOutputBlock -> Either TmuxError TmuxResponse
validate request = \case
TmuxOutputBlock.Success a ->
Right (TmuxResponse a)
TmuxOutputBlock.Error a ->
Left (TmuxError.RequestFailed request a)
tmuxRequest ::
Members [Process ByteString (Either Text TmuxOutputBlock), Log, Stop TmuxError] r =>
TmuxRequest ->
Sem r TmuxResponse
tmuxRequest request = do
Log.trace [exon|tmux request: #{Text.stripEnd (decodeUtf8 cmdline)}|]
Process.send cmdline
Process.recv >>= \case
Left err -> stop (TmuxError.RequestFailed request [err])
Right block -> do
Log.trace [exon|tmux response: #{show block}|]
stopEither (validate request block)
where
cmdline =
TmuxRequest.encode request
socketArg :: Path Abs File -> [String]
socketArg socket =
["-S", toFilePath socket]
tmuxProc ::
TmuxNative ->
ProcessConfig () () ()
tmuxProc (TmuxNative exe socket) =
proc (toFilePath exe) (foldMap socketArg socket <> ["-C", "-u", "attach-session", "-f", "ignore-size"])
interpretSystemProcessTmux ::
Members [Reader TmuxNative, Resource, Race, Async, Embed IO] r =>
InterpreterFor (Scoped_ (SystemProcess !! SystemProcessError) !! SystemProcessScopeError) r
interpretSystemProcessTmux sem = do
conf <- tmuxProc <$> ask
interpretSystemProcessNative_ conf sem
interpretProcessTmux ::
Member (Scoped_ (SystemProcess !! SystemProcessError) !! SystemProcessScopeError) r =>
Members [Resource, Race, Async, Embed IO] r =>
InterpreterFor (Scoped_ TmuxProc !! ProcessError) r
interpretProcessTmux sem = do
interpretProcessOutputTmuxBlock @'Stdout $
interpretProcessOutputTextLines @'Stderr $
interpretProcessOutputLeft @'Stderr $
interpretProcessInputId $
interpretProcess_ def $
insertAt @1 sem
# inline interpretProcessTmux #
flush ::
Members [TmuxProc, AtomicState (Seq TmuxRequest), Log, Stop TmuxError] r =>
Sem r ()
flush =
traverse_ tmuxRequest =<< atomicState' (mempty,)
tmuxSession ::
∀ r a .
Members [Scoped_ TmuxProc !! ProcessError, AtomicState (Seq TmuxRequest), Log, Stop TmuxError] r =>
Sem (TmuxProc : r) a ->
Sem r a
tmuxSession action =
resumeHoist @ProcessError @(Scoped_ TmuxProc) TmuxError.ProcessFailed $ withProcess_ do
void Process.recv
tmuxRequest (TmuxRequest "refresh-client" ["-C", "10000x10000"] Nothing)
raiseUnder action <* flush
interpretTmuxProcessBuffered ::
Members [AtomicState (Seq TmuxRequest), Scoped_ TmuxProc !! ProcessError, Log, Embed IO] r =>
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxProcessBuffered =
interpretScopedResumableWith_ @'[TmuxProc] (const tmuxSession) \case
TmuxClient.Schedule request ->
atomicModify' (|> request)
TmuxClient.Send cmd -> do
flush
tmuxRequest cmd
# inline interpretTmuxProcessBuffered #
interpretTmuxWithProcess ::
Members [Scoped_ TmuxProc !! ProcessError, Log, Embed IO] r =>
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxWithProcess =
interpretAtomic mempty .
interpretTmuxProcessBuffered .
raiseUnder
# inline interpretTmuxWithProcess #
interpretTmuxNative ::
∀ r .
Members [Reader TmuxNative, Log, Resource, Race, Async, Embed IO] r =>
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxNative =
interpretSystemProcessTmux .
interpretProcessTmux .
interpretTmuxWithProcess .
raiseUnder2
# inline interpretTmuxNative #
interpretTmuxFailing ::
TmuxError ->
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxFailing err =
interpretScopedResumable_ mempty \ () -> \case
TmuxClient.Schedule _ ->
stop err
TmuxClient.Send _ ->
stop err
withTmuxNativeEnv ::
Member (Embed IO) r =>
Maybe (Path Abs File) ->
(Maybe TmuxNative -> Sem r a) ->
Sem r a
withTmuxNativeEnv socket use =
use . fmap (flip TmuxNative socket) . rightToMaybe =<< resolveExecutable [relfile|tmux|] Nothing
runReaderTmuxNativeEnv ::
Members [Error TmuxError, Embed IO] r =>
Maybe (Path Abs File) ->
InterpreterFor (Reader TmuxNative) r
runReaderTmuxNativeEnv socket sem = do
tn <- withTmuxNativeEnv socket (note NoExe)
runReader tn sem
# inline runReaderTmuxNativeEnv #
interpretTmuxNativeEnv ::
Members [Error TmuxError, Log, Resource, Race, Async, Embed IO] r =>
Maybe (Path Abs File) ->
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxNativeEnv socket =
runReaderTmuxNativeEnv socket . interpretTmuxNative . raiseUnder
# inline interpretTmuxNativeEnv #
interpretTmuxNativeEnvGraceful ::
Members [Log, Resource, Race, Async, Embed IO] r =>
Maybe (Path Abs File) ->
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxNativeEnvGraceful socket sem =
withTmuxNativeEnv socket \case
Just tn -> runReader tn (interpretTmuxNative (raiseUnder sem))
Nothing -> interpretTmuxFailing NoExe sem
# inline interpretTmuxNativeEnvGraceful #
interpretTmuxClientNull ::
InterpreterFor (Scoped_ (TmuxClient i ()) !! TmuxError) r
interpretTmuxClientNull =
interpretScopedResumable_ mempty \ () -> \case
TmuxClient.Schedule _ ->
unit
TmuxClient.Send _ ->
unit
# inline interpretTmuxClientNull #
| null | https://raw.githubusercontent.com/tek/chiasma/777e53aa081b8db02ffc0b1442666def7561a59f/packages/chiasma/lib/Chiasma/Interpreter/TmuxClient.hs | haskell | module Chiasma.Interpreter.TmuxClient where
import Conc (interpretAtomic)
import Data.Sequence ((|>))
import qualified Data.Text as Text
import Exon (exon)
import qualified Log as Log
import Path (Abs, File, Path, relfile, toFilePath)
import Polysemy.Process.Interpreter.Process (ProcessQueues)
import qualified Process as Process
import Process (
OutputPipe (Stderr, Stdout),
Process,
ProcessError,
SystemProcess,
SystemProcessError,
SystemProcessScopeError,
interpretProcessInputId,
interpretProcessOutputLeft,
interpretProcessOutputTextLines,
interpretProcess_,
interpretSystemProcessNative_,
resolveExecutable,
withProcess_,
)
import System.Process.Typed (ProcessConfig, proc)
import qualified Chiasma.Data.TmuxError as TmuxError
import Chiasma.Data.TmuxError (TmuxError (NoExe))
import Chiasma.Data.TmuxNative (TmuxNative (TmuxNative))
import qualified Chiasma.Data.TmuxOutputBlock as TmuxOutputBlock
import Chiasma.Data.TmuxOutputBlock (TmuxOutputBlock)
import qualified Chiasma.Data.TmuxRequest as TmuxRequest
import Chiasma.Data.TmuxRequest (TmuxRequest (TmuxRequest))
import Chiasma.Data.TmuxResponse (TmuxResponse (TmuxResponse))
import qualified Chiasma.Effect.TmuxClient as TmuxClient
import Chiasma.Effect.TmuxClient (TmuxClient)
import Chiasma.Interpreter.ProcessOutput (interpretProcessOutputTmuxBlock)
type TmuxQueues =
ProcessQueues (Either Text TmuxOutputBlock) Text
type TmuxProc =
Process ByteString (Either Text TmuxOutputBlock)
validate :: TmuxRequest -> TmuxOutputBlock -> Either TmuxError TmuxResponse
validate request = \case
TmuxOutputBlock.Success a ->
Right (TmuxResponse a)
TmuxOutputBlock.Error a ->
Left (TmuxError.RequestFailed request a)
tmuxRequest ::
Members [Process ByteString (Either Text TmuxOutputBlock), Log, Stop TmuxError] r =>
TmuxRequest ->
Sem r TmuxResponse
tmuxRequest request = do
Log.trace [exon|tmux request: #{Text.stripEnd (decodeUtf8 cmdline)}|]
Process.send cmdline
Process.recv >>= \case
Left err -> stop (TmuxError.RequestFailed request [err])
Right block -> do
Log.trace [exon|tmux response: #{show block}|]
stopEither (validate request block)
where
cmdline =
TmuxRequest.encode request
socketArg :: Path Abs File -> [String]
socketArg socket =
["-S", toFilePath socket]
tmuxProc ::
TmuxNative ->
ProcessConfig () () ()
tmuxProc (TmuxNative exe socket) =
proc (toFilePath exe) (foldMap socketArg socket <> ["-C", "-u", "attach-session", "-f", "ignore-size"])
interpretSystemProcessTmux ::
Members [Reader TmuxNative, Resource, Race, Async, Embed IO] r =>
InterpreterFor (Scoped_ (SystemProcess !! SystemProcessError) !! SystemProcessScopeError) r
interpretSystemProcessTmux sem = do
conf <- tmuxProc <$> ask
interpretSystemProcessNative_ conf sem
interpretProcessTmux ::
Member (Scoped_ (SystemProcess !! SystemProcessError) !! SystemProcessScopeError) r =>
Members [Resource, Race, Async, Embed IO] r =>
InterpreterFor (Scoped_ TmuxProc !! ProcessError) r
interpretProcessTmux sem = do
interpretProcessOutputTmuxBlock @'Stdout $
interpretProcessOutputTextLines @'Stderr $
interpretProcessOutputLeft @'Stderr $
interpretProcessInputId $
interpretProcess_ def $
insertAt @1 sem
# inline interpretProcessTmux #
flush ::
Members [TmuxProc, AtomicState (Seq TmuxRequest), Log, Stop TmuxError] r =>
Sem r ()
flush =
traverse_ tmuxRequest =<< atomicState' (mempty,)
tmuxSession ::
∀ r a .
Members [Scoped_ TmuxProc !! ProcessError, AtomicState (Seq TmuxRequest), Log, Stop TmuxError] r =>
Sem (TmuxProc : r) a ->
Sem r a
tmuxSession action =
resumeHoist @ProcessError @(Scoped_ TmuxProc) TmuxError.ProcessFailed $ withProcess_ do
void Process.recv
tmuxRequest (TmuxRequest "refresh-client" ["-C", "10000x10000"] Nothing)
raiseUnder action <* flush
interpretTmuxProcessBuffered ::
Members [AtomicState (Seq TmuxRequest), Scoped_ TmuxProc !! ProcessError, Log, Embed IO] r =>
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxProcessBuffered =
interpretScopedResumableWith_ @'[TmuxProc] (const tmuxSession) \case
TmuxClient.Schedule request ->
atomicModify' (|> request)
TmuxClient.Send cmd -> do
flush
tmuxRequest cmd
# inline interpretTmuxProcessBuffered #
interpretTmuxWithProcess ::
Members [Scoped_ TmuxProc !! ProcessError, Log, Embed IO] r =>
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxWithProcess =
interpretAtomic mempty .
interpretTmuxProcessBuffered .
raiseUnder
# inline interpretTmuxWithProcess #
interpretTmuxNative ::
∀ r .
Members [Reader TmuxNative, Log, Resource, Race, Async, Embed IO] r =>
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxNative =
interpretSystemProcessTmux .
interpretProcessTmux .
interpretTmuxWithProcess .
raiseUnder2
# inline interpretTmuxNative #
interpretTmuxFailing ::
TmuxError ->
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxFailing err =
interpretScopedResumable_ mempty \ () -> \case
TmuxClient.Schedule _ ->
stop err
TmuxClient.Send _ ->
stop err
withTmuxNativeEnv ::
Member (Embed IO) r =>
Maybe (Path Abs File) ->
(Maybe TmuxNative -> Sem r a) ->
Sem r a
withTmuxNativeEnv socket use =
use . fmap (flip TmuxNative socket) . rightToMaybe =<< resolveExecutable [relfile|tmux|] Nothing
runReaderTmuxNativeEnv ::
Members [Error TmuxError, Embed IO] r =>
Maybe (Path Abs File) ->
InterpreterFor (Reader TmuxNative) r
runReaderTmuxNativeEnv socket sem = do
tn <- withTmuxNativeEnv socket (note NoExe)
runReader tn sem
# inline runReaderTmuxNativeEnv #
interpretTmuxNativeEnv ::
Members [Error TmuxError, Log, Resource, Race, Async, Embed IO] r =>
Maybe (Path Abs File) ->
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxNativeEnv socket =
runReaderTmuxNativeEnv socket . interpretTmuxNative . raiseUnder
# inline interpretTmuxNativeEnv #
interpretTmuxNativeEnvGraceful ::
Members [Log, Resource, Race, Async, Embed IO] r =>
Maybe (Path Abs File) ->
InterpreterFor (Scoped_ (TmuxClient TmuxRequest TmuxResponse) !! TmuxError) r
interpretTmuxNativeEnvGraceful socket sem =
withTmuxNativeEnv socket \case
Just tn -> runReader tn (interpretTmuxNative (raiseUnder sem))
Nothing -> interpretTmuxFailing NoExe sem
# inline interpretTmuxNativeEnvGraceful #
interpretTmuxClientNull ::
InterpreterFor (Scoped_ (TmuxClient i ()) !! TmuxError) r
interpretTmuxClientNull =
interpretScopedResumable_ mempty \ () -> \case
TmuxClient.Schedule _ ->
unit
TmuxClient.Send _ ->
unit
# inline interpretTmuxClientNull #
| |
5183566ed92b4129e6ea6e099a07426591c0a6473f11f9c427f1c8ebfdc1f631 | funkywork/nightmare | parser.ml | MIT License
Copyright ( c ) 2023 funkywork
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 .
Copyright (c) 2023 funkywork
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. *)
module Href = struct
type t =
{ fragments : string list
; query_string : string option
; anchor : string option
}
let make ?query_string ?anchor fragments = { fragments; query_string; anchor }
let fragments { fragments; _ } = fragments
let query_string { query_string; _ } = query_string
let anchor { anchor; _ } = anchor
let extract_at chr str =
match String.split_on_char chr str with
| [ ""; "" ] -> None, None
| [ ""; x ] -> None, Some x
| [ x; "" ] -> Some x, None
| [ x; y ] -> Some x, Some y
| [ "" ] -> None, None
| [ x ] -> Some x, None
| _ -> None, None
;;
let extract_anchor = extract_at '#'
let extract_query_string = function
| None -> None, None
| Some tl -> extract_at '?' tl
;;
let split_fragments str =
match String.split_on_char '/' str with
| "" :: "" :: fragments | "" :: fragments | fragments -> fragments
;;
let extract_fragments = function
| None -> []
| Some x -> split_fragments x
;;
let from_string str =
let tl, anchor = extract_anchor str in
let tl, query_string = extract_query_string tl in
let fragments = extract_fragments tl in
make ?query_string ?anchor fragments
;;
let pp ppf { fragments; query_string; anchor } =
let anchor = Option.fold ~none:"" ~some:(fun x -> "#" ^ x) anchor
and querys = Option.fold ~none:"" ~some:(fun x -> "?" ^ x) query_string
and fragmt = String.concat "/" fragments in
Format.fprintf ppf "/%s%s%s" fragmt querys anchor
;;
let equal
{ fragments = f_a; query_string = q_a; anchor = a_a }
{ fragments = f_b; query_string = q_b; anchor = a_b }
=
List.equal String.equal f_a f_b
&& Option.equal String.equal q_a q_b
&& Option.equal String.equal a_a a_b
;;
end
| null | https://raw.githubusercontent.com/funkywork/nightmare/05858823d01925cb8cb02a6b29ed8a223822a0e8/lib/service/parser.ml | ocaml | MIT License
Copyright ( c ) 2023 funkywork
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 .
Copyright (c) 2023 funkywork
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. *)
module Href = struct
type t =
{ fragments : string list
; query_string : string option
; anchor : string option
}
let make ?query_string ?anchor fragments = { fragments; query_string; anchor }
let fragments { fragments; _ } = fragments
let query_string { query_string; _ } = query_string
let anchor { anchor; _ } = anchor
let extract_at chr str =
match String.split_on_char chr str with
| [ ""; "" ] -> None, None
| [ ""; x ] -> None, Some x
| [ x; "" ] -> Some x, None
| [ x; y ] -> Some x, Some y
| [ "" ] -> None, None
| [ x ] -> Some x, None
| _ -> None, None
;;
let extract_anchor = extract_at '#'
let extract_query_string = function
| None -> None, None
| Some tl -> extract_at '?' tl
;;
let split_fragments str =
match String.split_on_char '/' str with
| "" :: "" :: fragments | "" :: fragments | fragments -> fragments
;;
let extract_fragments = function
| None -> []
| Some x -> split_fragments x
;;
let from_string str =
let tl, anchor = extract_anchor str in
let tl, query_string = extract_query_string tl in
let fragments = extract_fragments tl in
make ?query_string ?anchor fragments
;;
let pp ppf { fragments; query_string; anchor } =
let anchor = Option.fold ~none:"" ~some:(fun x -> "#" ^ x) anchor
and querys = Option.fold ~none:"" ~some:(fun x -> "?" ^ x) query_string
and fragmt = String.concat "/" fragments in
Format.fprintf ppf "/%s%s%s" fragmt querys anchor
;;
let equal
{ fragments = f_a; query_string = q_a; anchor = a_a }
{ fragments = f_b; query_string = q_b; anchor = a_b }
=
List.equal String.equal f_a f_b
&& Option.equal String.equal q_a q_b
&& Option.equal String.equal a_a a_b
;;
end
| |
7ad5c099e7bdd5378f62cc4580ffe0d7d6ea1dfebed6cacd7b0fd0bf0c205cbf | xapi-project/xen-api | test_bios_strings.ml | (** This module tests the dmidecode processing
*)
open Bios_strings
let load_test_data file =
Xapi_stdext_unix.Unixext.string_of_file @@ "test_data/" ^ file
let baseboard_two_string = load_test_data "bios_baseboard_two.dmidecode"
let baseboard_two_record =
[
{
name= "Base Board Information"
; values=
[
("Manufacturer", "TestA Inc.")
; ("Product Name", "Not Specified")
; ("Version", "A0")
; ("Serial Number", " .DEADBEEF")
; ("Asset Tag", " ")
; ( "Features"
, "Board is a hosting board\n\
Board is removable\n\
Board is replaceable\n\
Board is hot swappable"
)
; ("Location In Chassis", "Slot 00")
; ("Type", "Server Blade")
]
}
; {
name= "Base Board Information"
; values=
[
("Manufacturer", "TestB Inc.")
; ("Product Name", " ")
; ("Version", " ")
; ("Serial Number", "FOOBAR")
; ("Asset Tag", " ")
; ( "Features"
, "Board is removable\nBoard is replaceable\nBoard is hot swappable"
)
; ("Location In Chassis", "Slot 00")
; ("Type", "Interconnect Board")
]
}
]
let baseboard_two =
[
("baseboard-manufacturer", "TestA Inc.")
; ("baseboard-product-name", "")
; ("baseboard-version", "A0")
; ("baseboard-serial-number", ".DEADBEEF")
]
let baseboard_empty =
[
("baseboard-manufacturer", "")
; ("baseboard-product-name", "")
; ("baseboard-version", "")
; ("baseboard-serial-number", "")
]
let oem_string = load_test_data "bios_oem.dmidecode"
let oem_empty =
[
("oem-1", "Xen")
; ("oem-2", "MS_VM_CERT/SHA1/bdbeb6e0a816d43fa6d3fe8aaef04c2bad9d3e3d")
]
let oem =
oem_empty
@ [
("oem-3", "Test System")
; ("oem-4", "1[087C]")
; ("oem-5", "3[1.0]")
; ("oem-6", "12[www.test.com]")
; ("oem-7", "14[1]")
; ("oem-8", "15[0]")
; ("oem-9", "27[10567471934]")
]
let invalid_string = load_test_data "bios_invalid.dmidecode"
let with_array_string = load_test_data "bios_with_array.dmidecode"
let with_array =
[
{
name= "BIOS Language Information"
; values=
[
("Installable Languages", "en|US|iso8859-1\n<BAD INDEX>")
; ("Currently Installed Language", "en|US|iso8859-1")
]
}
]
let pp_record fmt {name; values} =
Format.fprintf fmt "{name=%s; values=%a}" name
Fmt.(Dump.list @@ pair ~sep:comma string string)
values
let alco_record = Alcotest.testable pp_record ( = )
let check_values = Alcotest.(check @@ list @@ pair string string)
let check_records = Alcotest.(check @@ result (list alco_record) string)
let parse_string = Angstrom.parse_string ~consume:Prefix P.records
let values_from_string str =
match parse_string str with
| Ok (r :: _) ->
r.values
| Ok [] ->
[]
| Error _ ->
[]
let test_parser () =
check_records "Empty string produces an empty list" (Ok []) (parse_string "") ;
check_records "Invalid records must be discarded and stop the parser" (Ok [])
(parse_string invalid_string) ;
check_records "Two records with same name is valid input"
(Ok baseboard_two_record)
(parse_string baseboard_two_string) ;
check_records "Arrays must be parsed as multi-line values" (Ok with_array)
(parse_string with_array_string)
let test_baseboard () =
check_values "Baseboard values must have empty values when input is empty"
baseboard_empty
(get_baseboard_strings @@ fun _ _ -> []) ;
check_values "Second baseboard values must be discarded" baseboard_two
(get_baseboard_strings @@ fun _ _ -> values_from_string baseboard_two_string)
let test_oem () =
check_values "OEM default values must be used when input is empty" oem_empty
(get_oem_strings @@ fun _ _ -> []) ;
check_values "OEM default values must be listed first" oem
(get_oem_strings @@ fun _ _ -> values_from_string oem_string)
let test =
[
("Test baseboard strings", `Quick, test_baseboard)
; ("Test oem strings", `Quick, test_oem)
; ("Test parser", `Quick, test_parser)
]
| null | https://raw.githubusercontent.com/xapi-project/xen-api/e984d34bd9ff60d7224a841270db0fe1dfe42e7a/ocaml/tests/test_bios_strings.ml | ocaml | * This module tests the dmidecode processing
| open Bios_strings
let load_test_data file =
Xapi_stdext_unix.Unixext.string_of_file @@ "test_data/" ^ file
let baseboard_two_string = load_test_data "bios_baseboard_two.dmidecode"
let baseboard_two_record =
[
{
name= "Base Board Information"
; values=
[
("Manufacturer", "TestA Inc.")
; ("Product Name", "Not Specified")
; ("Version", "A0")
; ("Serial Number", " .DEADBEEF")
; ("Asset Tag", " ")
; ( "Features"
, "Board is a hosting board\n\
Board is removable\n\
Board is replaceable\n\
Board is hot swappable"
)
; ("Location In Chassis", "Slot 00")
; ("Type", "Server Blade")
]
}
; {
name= "Base Board Information"
; values=
[
("Manufacturer", "TestB Inc.")
; ("Product Name", " ")
; ("Version", " ")
; ("Serial Number", "FOOBAR")
; ("Asset Tag", " ")
; ( "Features"
, "Board is removable\nBoard is replaceable\nBoard is hot swappable"
)
; ("Location In Chassis", "Slot 00")
; ("Type", "Interconnect Board")
]
}
]
let baseboard_two =
[
("baseboard-manufacturer", "TestA Inc.")
; ("baseboard-product-name", "")
; ("baseboard-version", "A0")
; ("baseboard-serial-number", ".DEADBEEF")
]
let baseboard_empty =
[
("baseboard-manufacturer", "")
; ("baseboard-product-name", "")
; ("baseboard-version", "")
; ("baseboard-serial-number", "")
]
let oem_string = load_test_data "bios_oem.dmidecode"
let oem_empty =
[
("oem-1", "Xen")
; ("oem-2", "MS_VM_CERT/SHA1/bdbeb6e0a816d43fa6d3fe8aaef04c2bad9d3e3d")
]
let oem =
oem_empty
@ [
("oem-3", "Test System")
; ("oem-4", "1[087C]")
; ("oem-5", "3[1.0]")
; ("oem-6", "12[www.test.com]")
; ("oem-7", "14[1]")
; ("oem-8", "15[0]")
; ("oem-9", "27[10567471934]")
]
let invalid_string = load_test_data "bios_invalid.dmidecode"
let with_array_string = load_test_data "bios_with_array.dmidecode"
let with_array =
[
{
name= "BIOS Language Information"
; values=
[
("Installable Languages", "en|US|iso8859-1\n<BAD INDEX>")
; ("Currently Installed Language", "en|US|iso8859-1")
]
}
]
let pp_record fmt {name; values} =
Format.fprintf fmt "{name=%s; values=%a}" name
Fmt.(Dump.list @@ pair ~sep:comma string string)
values
let alco_record = Alcotest.testable pp_record ( = )
let check_values = Alcotest.(check @@ list @@ pair string string)
let check_records = Alcotest.(check @@ result (list alco_record) string)
let parse_string = Angstrom.parse_string ~consume:Prefix P.records
let values_from_string str =
match parse_string str with
| Ok (r :: _) ->
r.values
| Ok [] ->
[]
| Error _ ->
[]
let test_parser () =
check_records "Empty string produces an empty list" (Ok []) (parse_string "") ;
check_records "Invalid records must be discarded and stop the parser" (Ok [])
(parse_string invalid_string) ;
check_records "Two records with same name is valid input"
(Ok baseboard_two_record)
(parse_string baseboard_two_string) ;
check_records "Arrays must be parsed as multi-line values" (Ok with_array)
(parse_string with_array_string)
let test_baseboard () =
check_values "Baseboard values must have empty values when input is empty"
baseboard_empty
(get_baseboard_strings @@ fun _ _ -> []) ;
check_values "Second baseboard values must be discarded" baseboard_two
(get_baseboard_strings @@ fun _ _ -> values_from_string baseboard_two_string)
let test_oem () =
check_values "OEM default values must be used when input is empty" oem_empty
(get_oem_strings @@ fun _ _ -> []) ;
check_values "OEM default values must be listed first" oem
(get_oem_strings @@ fun _ _ -> values_from_string oem_string)
let test =
[
("Test baseboard strings", `Quick, test_baseboard)
; ("Test oem strings", `Quick, test_oem)
; ("Test parser", `Quick, test_parser)
]
|
dee228fad4bfc68731e24629da4ddd9a0b8ac7faecc4967a0fe513a16ff86b51 | racket/racket7 | search.rkt | #lang racket/base
(require "../common/range.rkt"
"regexp.rkt"
"lazy-bytes.rkt"
"interp.rkt"
"../analyze/must-string.rkt")
(provide search-match)
;; ------------------------------------------------------------
;; The driver iterates through the input (unless the pattern is
;; anchored) to find a match
(define (search-match rx in pos start-pos end-pos state)
(define must-string (rx:regexp-must-string rx))
(cond
[(not (check-must-string must-string in pos end-pos))
(values #f #f)]
[else
(define matcher (rx:regexp-matcher rx))
(define anchored? (rx:regexp-anchored? rx))
(define start-range (rx:regexp-start-range rx))
(let loop ([pos pos])
(cond
[(and anchored? (not (= pos start-pos)))
(values #f #f)]
[(and start-range
(if (bytes? in)
(= pos end-pos)
(not (lazy-bytes-before-end? in pos end-pos))))
(values #f #f)]
[(and start-range
(not (check-start-range start-range in pos end-pos)))
(loop (add1 pos))]
[else
(define pos2 (interp matcher in pos start-pos end-pos state))
(cond
[pos2 (values pos pos2)]
[start-range (loop (add1 pos))]
[(if (bytes? in)
(pos . < . end-pos)
(lazy-bytes-before-end? in pos end-pos))
(define pos2 (add1 pos))
(unless (bytes? in)
(lazy-bytes-advance! in pos2 #f))
(loop pos2)]
[else (values #f #f)])]))]))
;; ------------------------------------------------------------------
;; Checking for a must string (before iterating though the input) can
;; speed up a match failure by avoiding backtracking:
(define (check-must-string must-string in pos end-pos)
(cond
[(not must-string) #t]
[(not (bytes? in)) #t]
[(bytes? must-string)
(cond
[(= 1 (bytes-length must-string))
;; Check for a single byte
(define mc (bytes-ref must-string 0))
(for/or ([c (in-bytes in pos end-pos)])
(= c mc))]
[else
;; Check for a byte string
(define mc1 (bytes-ref must-string 0))
(for/or ([i (in-range pos (- end-pos (sub1 (bytes-length must-string))))])
(and (= mc1 (bytes-ref in i))
(for/and ([c (in-bytes in (add1 i))]
[mc (in-bytes must-string 1)])
(= c mc))))])]
[else
;; Check against a sequence of ranges
(for/or ([i (in-range pos (- end-pos (sub1 (length must-string))))])
(let loop ([i i] [l must-string])
(cond
[(null? l) #t]
[else
(define e (car l))
(and (rng-in? e (bytes-ref in i))
(loop (add1 i) (cdr l)))])))]))
;; ------------------------------------------------------------------
;; Checking for a startup byte can speed up a match failure by
;; avoiding the general pattern checker:
(define (check-start-range start-range in pos end-pos)
(rng-in? start-range
(if (bytes? in)
(bytes-ref in pos)
(lazy-bytes-ref in pos))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/regexp/match/search.rkt | racket | ------------------------------------------------------------
The driver iterates through the input (unless the pattern is
anchored) to find a match
------------------------------------------------------------------
Checking for a must string (before iterating though the input) can
speed up a match failure by avoiding backtracking:
Check for a single byte
Check for a byte string
Check against a sequence of ranges
------------------------------------------------------------------
Checking for a startup byte can speed up a match failure by
avoiding the general pattern checker: | #lang racket/base
(require "../common/range.rkt"
"regexp.rkt"
"lazy-bytes.rkt"
"interp.rkt"
"../analyze/must-string.rkt")
(provide search-match)
(define (search-match rx in pos start-pos end-pos state)
(define must-string (rx:regexp-must-string rx))
(cond
[(not (check-must-string must-string in pos end-pos))
(values #f #f)]
[else
(define matcher (rx:regexp-matcher rx))
(define anchored? (rx:regexp-anchored? rx))
(define start-range (rx:regexp-start-range rx))
(let loop ([pos pos])
(cond
[(and anchored? (not (= pos start-pos)))
(values #f #f)]
[(and start-range
(if (bytes? in)
(= pos end-pos)
(not (lazy-bytes-before-end? in pos end-pos))))
(values #f #f)]
[(and start-range
(not (check-start-range start-range in pos end-pos)))
(loop (add1 pos))]
[else
(define pos2 (interp matcher in pos start-pos end-pos state))
(cond
[pos2 (values pos pos2)]
[start-range (loop (add1 pos))]
[(if (bytes? in)
(pos . < . end-pos)
(lazy-bytes-before-end? in pos end-pos))
(define pos2 (add1 pos))
(unless (bytes? in)
(lazy-bytes-advance! in pos2 #f))
(loop pos2)]
[else (values #f #f)])]))]))
(define (check-must-string must-string in pos end-pos)
(cond
[(not must-string) #t]
[(not (bytes? in)) #t]
[(bytes? must-string)
(cond
[(= 1 (bytes-length must-string))
(define mc (bytes-ref must-string 0))
(for/or ([c (in-bytes in pos end-pos)])
(= c mc))]
[else
(define mc1 (bytes-ref must-string 0))
(for/or ([i (in-range pos (- end-pos (sub1 (bytes-length must-string))))])
(and (= mc1 (bytes-ref in i))
(for/and ([c (in-bytes in (add1 i))]
[mc (in-bytes must-string 1)])
(= c mc))))])]
[else
(for/or ([i (in-range pos (- end-pos (sub1 (length must-string))))])
(let loop ([i i] [l must-string])
(cond
[(null? l) #t]
[else
(define e (car l))
(and (rng-in? e (bytes-ref in i))
(loop (add1 i) (cdr l)))])))]))
(define (check-start-range start-range in pos end-pos)
(rng-in? start-range
(if (bytes? in)
(bytes-ref in pos)
(lazy-bytes-ref in pos))))
|
ab22f382c1861f609400cd5b5841502fc3dda14c3eda4f4193955727e5a0962f | robert-stuttaford/bridge | edit.clj | (ns bridge.data.edit
(:require [bridge.data.datomic :as datomic]
[bridge.data.string :as data.string]
[clojure.spec.alpha :as s]
[clojure.string :as str]))
(require 'bridge.data.edit.spec)
(defmulti check-custom-validation
(fn [db {:field/keys [attr]}]
attr))
(defmethod check-custom-validation :default [_ _] nil)
(defn check-custom-validation*
"So that defmethod doesn't find instrumentation output"
[db field]
(check-custom-validation db field))
(s/fdef check-custom-validation*
:args (s/cat :db :bridge.datomic/db
:edit-field :bridge/field-update)
:ret (s/or :valid nil?
:invalid :bridge/error-result))
(defn check-field-update:invalid-edit-key [db attr-whitelist {:field/keys [attr]}]
(when-not (contains? attr-whitelist attr)
{:error :bridge.error/invalid-edit-key
:field/attr attr}))
(defn check-field-update:invalid-edit-value [db {:field/keys [attr value]}]
(when (and (s/get-spec attr) (not (s/valid? attr value)))
{:error :bridge.error/invalid-edit-value
:field/attr attr
:field/value value
:spec-error (s/explain-data attr value)}))
(defn check-field-update:uniqueness-conflict [db {:field/keys [attr value]}]
(when (and (datomic/attr-is-unique? db attr)
(some? (datomic/entid db [attr value])))
{:error :bridge.error/uniqueness-conflict
:field/attr attr
:field/value value}))
(defn check-field-update:missing-referent [db {:field/keys [attr value]}]
(when (and (datomic/attr-is-ref? db attr)
(nil? (datomic/entid db value)))
{:error :bridge.error/missing-referent
:field/attr attr
:field/value value}))
(defn check-field-update
"Returns `{:error :bridge.error/*}` or `nil` if validation succeeds."
[db attr-whitelist field]
(or (check-field-update:invalid-edit-key db attr-whitelist field)
(check-field-update:invalid-edit-value db field)
(check-field-update:uniqueness-conflict db field)
(check-field-update:missing-referent db field)
(check-custom-validation* db field)))
(s/fdef check-field-update
:args (s/cat :db :bridge.datomic/db
:whitelist (s/coll-of keyword? :kind set?)
:edit-field :bridge/field-update)
:ret (s/or :valid nil?
:invalid :bridge/error-result))
(defn update-field-value-tx [db {:field/keys [entity-id attr value retract?]}]
(if (and (= (datomic/attr-type db attr) :db.type/string)
(str/blank? value))
(when-some [existing-value (-> (datomic/attr db entity-id attr)
data.string/not-blank)]
[:db/retract entity-id attr existing-value])
[(if retract? :db/retract :db/add) entity-id attr value]))
(s/fdef update-field-value-tx
:args (s/cat :db :bridge.datomic/db
:edit-field :bridge/field-update)
:ret (s/tuple #{:db/add :db/retract}
:bridge.datomic/stored-id
keyword?
:bridge.datomic/scalar-value))
(defn update-field-value! [conn db attr-whitelist field]
(or (check-field-update db attr-whitelist field)
(datomic/transact! conn [(update-field-value-tx db field)])))
| null | https://raw.githubusercontent.com/robert-stuttaford/bridge/867d81354457c600cc5c25917de267a8e267c853/src/bridge/data/edit.clj | clojure | (ns bridge.data.edit
(:require [bridge.data.datomic :as datomic]
[bridge.data.string :as data.string]
[clojure.spec.alpha :as s]
[clojure.string :as str]))
(require 'bridge.data.edit.spec)
(defmulti check-custom-validation
(fn [db {:field/keys [attr]}]
attr))
(defmethod check-custom-validation :default [_ _] nil)
(defn check-custom-validation*
"So that defmethod doesn't find instrumentation output"
[db field]
(check-custom-validation db field))
(s/fdef check-custom-validation*
:args (s/cat :db :bridge.datomic/db
:edit-field :bridge/field-update)
:ret (s/or :valid nil?
:invalid :bridge/error-result))
(defn check-field-update:invalid-edit-key [db attr-whitelist {:field/keys [attr]}]
(when-not (contains? attr-whitelist attr)
{:error :bridge.error/invalid-edit-key
:field/attr attr}))
(defn check-field-update:invalid-edit-value [db {:field/keys [attr value]}]
(when (and (s/get-spec attr) (not (s/valid? attr value)))
{:error :bridge.error/invalid-edit-value
:field/attr attr
:field/value value
:spec-error (s/explain-data attr value)}))
(defn check-field-update:uniqueness-conflict [db {:field/keys [attr value]}]
(when (and (datomic/attr-is-unique? db attr)
(some? (datomic/entid db [attr value])))
{:error :bridge.error/uniqueness-conflict
:field/attr attr
:field/value value}))
(defn check-field-update:missing-referent [db {:field/keys [attr value]}]
(when (and (datomic/attr-is-ref? db attr)
(nil? (datomic/entid db value)))
{:error :bridge.error/missing-referent
:field/attr attr
:field/value value}))
(defn check-field-update
"Returns `{:error :bridge.error/*}` or `nil` if validation succeeds."
[db attr-whitelist field]
(or (check-field-update:invalid-edit-key db attr-whitelist field)
(check-field-update:invalid-edit-value db field)
(check-field-update:uniqueness-conflict db field)
(check-field-update:missing-referent db field)
(check-custom-validation* db field)))
(s/fdef check-field-update
:args (s/cat :db :bridge.datomic/db
:whitelist (s/coll-of keyword? :kind set?)
:edit-field :bridge/field-update)
:ret (s/or :valid nil?
:invalid :bridge/error-result))
(defn update-field-value-tx [db {:field/keys [entity-id attr value retract?]}]
(if (and (= (datomic/attr-type db attr) :db.type/string)
(str/blank? value))
(when-some [existing-value (-> (datomic/attr db entity-id attr)
data.string/not-blank)]
[:db/retract entity-id attr existing-value])
[(if retract? :db/retract :db/add) entity-id attr value]))
(s/fdef update-field-value-tx
:args (s/cat :db :bridge.datomic/db
:edit-field :bridge/field-update)
:ret (s/tuple #{:db/add :db/retract}
:bridge.datomic/stored-id
keyword?
:bridge.datomic/scalar-value))
(defn update-field-value! [conn db attr-whitelist field]
(or (check-field-update db attr-whitelist field)
(datomic/transact! conn [(update-field-value-tx db field)])))
| |
d116818bbc674df152eaff122867d819683a7dcbfb46d1361c6e912d6560d4e3 | OCamlPro/alt-ergo | arith.ml | (******************************************************************************)
(* *)
(* The Alt-Ergo theorem prover *)
Copyright ( C ) 2006 - 2013
(* *)
(* *)
(* *)
CNRS - INRIA - Universite Paris Sud
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(* ------------------------------------------------------------------------ *)
(* *)
Alt - Ergo : The SMT Solver For Software Verification
Copyright ( C ) 2013 - 2018
(* *)
This file is distributed under the terms of the Apache Software
(* License version 2.0 *)
(* *)
(******************************************************************************)
module Sy = Symbols
module E = Expr
module Z = Numbers.Z
module Q = Numbers.Q
let is_mult h = Sy.equal (Sy.Op Sy.Mult) h
let mod_symb = Sy.name "@mod"
let calc_power (c : Q.t) (d : Q.t) (ty : Ty.t) =
(* d must be integral and if we work on integer exponentation,
d must be positive*)
if not (Q.is_int d) then raise Exit;
if Ty.Tint == ty && Q.sign d < 0 then raise Exit;
let n = match Z.to_machine_int (Q.to_z d) with
| Some n -> n
| None -> raise Exit
in
(* This lines prevent overflow from computation *)
let sz = Z.numbits (Q.num c) + Z.numbits (Q.den c) in
if sz <> 0 && Stdlib.abs n > 100_000 / sz then raise Exit;
let res = Q.power c n in
assert (ty != Ty.Tint || Q.is_int c);
res
let calc_power_opt (c : Q.t) (d : Q.t) (ty : Ty.t) =
try Some (calc_power c d ty)
with Exit -> None
module Type (X:Sig.X) : Polynome.T with type r = X.r = struct
include
Polynome.Make(struct
include X
module Ac = Ac.Make(X)
let mult v1 v2 =
X.ac_embed
{
distribute = true;
h = Sy.Op Sy.Mult;
t = X.type_info v1;
l = let l2 = match X.ac_extract v1 with
| Some { h; l; _ } when Sy.equal h (Sy.Op Sy.Mult) -> l
| _ -> [v1, 1]
in Ac.add (Sy.Op Sy.Mult) (v2,1) l2
}
end)
end
module Shostak
(X : Sig.X)
(P : Polynome.EXTENDED_Polynome with type r = X.r) = struct
type t = P.t
type r = P.r
let name = "arith"
(*BISECT-IGNORE-BEGIN*)
module Debug = struct
let solve_aux r1 r2 =
if Options.get_debug_arith () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"solve_aux"
"we solve %a=%a" X.print r1 X.print r2
let solve_one r1 r2 sbs =
let c = ref 0 in
let print fmt (p,v) =
incr c;
Format.fprintf fmt "%d) %a |-> %a@." !c X.print p X.print v
in
if Options.get_debug_arith () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"solve_one"
"solving %a = %a yields:@,%a"
X.print r1 X.print r2
(Printer.pp_list_no_space print) sbs
end
(*BISECT-IGNORE-END*)
let is_mine_symb sy _ty =
let open Sy in
match sy with
| Int _ | Real _ -> true
| Op (Plus | Minus | Mult | Div | Modulo
| Float | Fixed | Abs_int | Abs_real | Sqrt_real
| Sqrt_real_default | Sqrt_real_excess
| Real_of_int | Int_floor | Int_ceil
| Max_int | Max_real | Min_int | Min_real
| Pow | Integer_log2
| Integer_round) -> true
| _ -> false
let empty_polynome ty = P.create [] Q.zero ty
let is_mine p = match P.is_monomial p with
| Some (a,x,b) when Q.equal a Q.one && Q.sign b = 0 -> x
| _ -> P.embed p
let embed r = match P.extract r with
| Some p -> p
| _ -> P.create [Q.one, r] Q.zero (X.type_info r)
t1 % t2 =
c1 . 0 < = c2 . t2 ;
c3 . exists k + t ;
c4 . t2 < > 0 ( already checked )
c1. 0 <= md ;
c2. md < t2 ;
c3. exists k. t1 = t2 * k + t ;
c4. t2 <> 0 (already checked) *)
let mk_modulo md t1 t2 p2 ctx =
let zero = E.int "0" in
let c1 = E.mk_builtin ~is_pos:true Symbols.LE [zero; md] in
let c2 =
match P.is_const p2 with
| Some n2 ->
let an2 = Q.abs n2 in
assert (Q.is_int an2);
let t2 = E.int (Q.to_string an2) in
E.mk_builtin ~is_pos:true Symbols.LT [md; t2]
| None ->
E.mk_builtin ~is_pos:true Symbols.LT [md; t2]
in
let k = E.fresh_name Ty.Tint in
let t3 = E.mk_term (Sy.Op Sy.Mult) [t2;k] Ty.Tint in
let t3 = E.mk_term (Sy.Op Sy.Plus) [t3;md] Ty.Tint in
let c3 = E.mk_eq ~iff:false t1 t3 in
c3 :: c2 :: c1 :: ctx
let mk_euc_division p p2 t1 t2 ctx =
match P.to_list p2 with
| [], coef_p2 ->
let md = E.mk_term (Sy.Op Sy.Modulo) [t1;t2] Ty.Tint in
let r, ctx' = X.make md in
let rp =
P.mult_const (Q.div Q.one coef_p2) (embed r) in
P.sub p rp, ctx' @ ctx
| _ -> assert false
let exact_sqrt_or_Exit q =
(* this function is probably not accurate because it
works on Z.t to compute eventual exact sqrt *)
let c = Q.sign q in
if c < 0 then raise Exit;
let n = Q.num q in
let d = Q.den q in
let s_n, _ = Z.sqrt_rem n in
assert (Z.sign s_n >= 0);
if not (Z.equal (Z.mult s_n s_n) n) then raise Exit;
let s_d, _ = Z.sqrt_rem d in
assert (Z.sign s_d >= 0);
if not (Z.equal (Z.mult s_d s_d) d) then raise Exit;
let res = Q.from_zz s_n s_d in
assert (Q.equal (Q.mult res res) q);
res
let default_sqrt_or_Exit q =
let c = Q.sign q in
if c < 0 then raise Exit;
match Q.sqrt_default q with
| None -> raise Exit
| Some res -> assert (Q.compare (Q.mult res res) q <= 0); res
let excess_sqrt_or_Exit q =
let c = Q.sign q in
if c < 0 then raise Exit;
match Q.sqrt_excess q with
| None -> raise Exit
| Some res -> assert (Q.compare (Q.mult res res) q >= 0); res
let mk_partial_interpretation_1 aux_func coef p_acc ty t x =
let r_x, _ = X.make x in
try
match P.to_list (embed r_x) with
| [], d ->
let d = aux_func d in (* may raise Exit *)
P.add_const (Q.mult coef d) p_acc
| _ -> raise Exit
with Exit ->
let a = X.term_embed t in
P.add (P.create [coef, a] Q.zero ty) p_acc
let mk_partial_interpretation_2 aux_func coef p_acc ty t x y =
let px = embed (fst (X.make x)) in
let py = embed (fst (X.make y)) in
try
match P.is_const px, P.is_const py with
| Some c_x, Some c_y ->
P.add_const (Q.mult coef (aux_func c_x c_y)) p_acc
| _ ->
P.add (P.create [coef, (X.term_embed t)] Q.zero ty) p_acc
with Exit ->
P.add (P.create [coef, (X.term_embed t)] Q.zero ty) p_acc
let rec mke coef p t ctx =
let { E.f = sb ; xs; ty; _ } = E.term_view t in
match sb, xs with
| (Sy.Int n | Sy.Real n) , _ ->
let c = Q.mult coef (Q.from_string (Hstring.view n)) in
P.add_const c p, ctx
| Sy.Op Sy.Mult, [t1;t2] ->
let p1, ctx = mke coef (empty_polynome ty) t1 ctx in
let p2, ctx = mke Q.one (empty_polynome ty) t2 ctx in
if Options.get_no_nla() && P.is_const p1 == None && P.is_const p2 == None
then
(* becomes uninterpreted *)
let tau = E.mk_term (Sy.name ~kind:Sy.Ac "@*") [t1; t2] ty in
let xtau, ctx' = X.make tau in
P.add p (P.create [coef, xtau] Q.zero ty), List.rev_append ctx' ctx
else
P.add p (P.mult p1 p2), ctx
| Sy.Op Sy.Div, [t1;t2] ->
let p1, ctx = mke Q.one (empty_polynome ty) t1 ctx in
let p2, ctx = mke Q.one (empty_polynome ty) t2 ctx in
if Options.get_no_nla() &&
(P.is_const p2 == None ||
(ty == Ty.Tint && P.is_const p1 == None)) then
(* becomes uninterpreted *)
let tau = E.mk_term (Sy.name "@/") [t1; t2] ty in
let xtau, ctx' = X.make tau in
P.add p (P.create [coef, xtau] Q.zero ty), List.rev_append ctx' ctx
else
let p3, ctx =
try
let p, approx = P.div p1 p2 in
if approx then mk_euc_division p p2 t1 t2 ctx
else p, ctx
with Division_by_zero | Polynome.Maybe_zero ->
P.create [Q.one, X.term_embed t] Q.zero ty, ctx
in
P.add p (P.mult_const coef p3), ctx
| Sy.Op Sy.Plus , l ->
List.fold_left (fun (p, ctx) u -> mke coef p u ctx )(p, ctx) l
| Sy.Op Sy.Minus , [t1;t2] ->
let p2, ctx = mke (Q.minus coef) p t2 ctx in
mke coef p2 t1 ctx
| Sy.Op Sy.Modulo , [t1;t2] ->
let p1, ctx = mke Q.one (empty_polynome ty) t1 ctx in
let p2, ctx = mke Q.one (empty_polynome ty) t2 ctx in
if Options.get_no_nla() &&
(P.is_const p1 == None || P.is_const p2 == None)
then
(* becomes uninterpreted *)
let tau = E.mk_term (Sy.name "@%") [t1; t2] ty in
let xtau, ctx' = X.make tau in
P.add p (P.create [coef, xtau] Q.zero ty), List.rev_append ctx' ctx
else
let p3, ctx =
try P.modulo p1 p2, ctx
with e ->
let t = E.mk_term mod_symb [t1; t2] Ty.Tint in
let ctx = match e with
| Division_by_zero | Polynome.Maybe_zero -> ctx
| Polynome.Not_a_num -> mk_modulo t t1 t2 p2 ctx
| _ -> assert false
in
P.create [Q.one, X.term_embed t] Q.zero ty, ctx
in
P.add p (P.mult_const coef p3), ctx
* * < begin > : partial handling of some arith / FPA operators *
| Sy.Op Sy.Float, [prec; exp; mode; x] ->
let aux_func e =
let res, _, _ = Fpa_rounding.float_of_rational prec exp mode e in
res
in
mk_partial_interpretation_1 aux_func coef p ty t x, ctx
| Sy.Op Sy.Integer_round, [mode; x] ->
let aux_func = Fpa_rounding.round_to_integer mode in
mk_partial_interpretation_1 aux_func coef p ty t x, ctx
| Sy.Op (Sy.Abs_int | Sy.Abs_real) , [x] ->
mk_partial_interpretation_1 Q.abs coef p ty t x, ctx
| Sy.Op Sy.Sqrt_real, [x] ->
mk_partial_interpretation_1 exact_sqrt_or_Exit coef p ty t x, ctx
| Sy.Op Sy.Sqrt_real_default, [x] ->
mk_partial_interpretation_1 default_sqrt_or_Exit coef p ty t x, ctx
| Sy.Op Sy.Sqrt_real_excess, [x] ->
mk_partial_interpretation_1 excess_sqrt_or_Exit coef p ty t x, ctx
| Sy.Op Sy.Real_of_int, [x] ->
mk_partial_interpretation_1 (fun d -> d) coef p ty t x, ctx
| Sy.Op Sy.Int_floor, [x] ->
mk_partial_interpretation_1 Q.floor coef p ty t x, ctx
| Sy.Op Sy.Int_ceil, [x] ->
mk_partial_interpretation_1 Q.ceiling coef p ty t x, ctx
| Sy.Op (Sy.Max_int | Sy.Max_real), [x;y] ->
let aux_func c d = if Q.compare c d >= 0 then c else d in
mk_partial_interpretation_2 aux_func coef p ty t x y, ctx
| Sy.Op (Sy.Min_int | Sy.Min_real), [x;y] ->
let aux_func c d = if Q.compare c d <= 0 then c else d in
mk_partial_interpretation_2 aux_func coef p ty t x y, ctx
| Sy.Op Sy.Integer_log2, [x] ->
let aux_func q =
if Q.compare_to_0 q <= 0 then raise Exit;
Q.from_int (Fpa_rounding.integer_log_2 q)
in
mk_partial_interpretation_1 aux_func coef p ty t x, ctx
| Sy.Op Sy.Pow, [x; y] ->
mk_partial_interpretation_2
(fun x y -> calc_power x y ty) coef p ty t x y, ctx
| Sy.Op Sy.Fixed, _ ->
(* Fixed-Point arithmetic currently not implemented *)
assert false
* * < end > : partial handling of some arith / FPA operators *
| _ ->
let a, ctx' = X.make t in
let ctx = ctx' @ ctx in
match P.extract a with
| Some p' -> P.add p (P.mult_const coef p'), ctx
| _ -> P.add p (P.create [coef, a] Q.zero ty), ctx
let make t =
Options.tool_req 4 "TR-Arith-Make";
let ty = E.type_info t in
let p, ctx = mke Q.one (empty_polynome ty) t [] in
is_mine p, ctx
let rec expand p n acc =
assert (n >=0);
if n = 0 then acc else expand p (n-1) (p::acc)
let unsafe_ac_to_arith Sig.{ l = rl; t = ty; _ } =
let mlt = List.fold_left (fun l (r,n) -> expand (embed r)n l) [] rl in
List.fold_left P.mult (P.create [] Q.one ty) mlt
let rec number_of_vars l =
List.fold_left (fun acc (r, n) -> acc + n * nb_vars_in_alien r) 0 l
and nb_vars_in_alien r =
match P.extract r with
| Some p ->
let l, _ = P.to_list p in
List.fold_left (fun acc (_, x) -> max acc (nb_vars_in_alien x)) 0 l
| None ->
begin
match X.ac_extract r with
| Some ac when is_mult ac.h ->
number_of_vars ac.l
| _ -> 1
end
let max_list_ = function
| [] -> 0
| [ _, x ] -> nb_vars_in_alien x
| (_, x) :: l ->
let acc = nb_vars_in_alien x in
List.fold_left (fun acc (_, x) -> max acc (nb_vars_in_alien x)) acc l
let contains_a_fresh_alien xp =
List.exists
(fun x ->
match X.term_extract x with
| Some t, _ -> E.is_fresh t
| _ -> false
) (X.leaves xp)
let has_ac p kind =
List.exists
(fun (_, x) ->
match X.ac_extract x with Some ac -> kind ac | _ -> false)
(fst (P.to_list p))
let color ac =
match ac.Sig.l with
| [(_, 1)] -> assert false
| _ ->
let p = unsafe_ac_to_arith ac in
if not ac.distribute then
if has_ac p (fun ac -> is_mult ac.h) then X.ac_embed ac
else is_mine p
else
let xp = is_mine p in
if contains_a_fresh_alien xp then
let l, _ = P.to_list p in
let mx = max_list_ l in
if mx = 0 || mx = 1 || number_of_vars ac.l > mx then is_mine p
else X.ac_embed ac
else xp
let type_info p = P.type_info p
module SX = Set.Make(struct type t = r let compare = X.hash_cmp end)
let leaves p = P.leaves p
let subst x t p =
let p = P.subst x (embed t) p in
let ty = P.type_info p in
let l, c = P.to_list p in
let p =
List.fold_left
(fun p (ai, xi) ->
let xi' = X.subst x t xi in
let p' = match P.extract xi' with
| Some p' -> P.mult_const ai p'
| _ -> P.create [ai, xi'] Q.zero ty
in
P.add p p')
(P.create [] c ty) l
in
is_mine p
let compare x y = P.compare (embed x) (embed y)
let equal p1 p2 = P.equal p1 p2
let hash = P.hash
symmetric modulo p 131
let mod_sym a b =
let m = Q.modulo a b in
let m =
if Q.sign m < 0 then
if Q.compare m (Q.minus b) >= 0 then Q.add m b else assert false
else
if Q.compare m b <= 0 then m else assert false
in
if Q.compare m (Q.div b (Q.from_int 2)) < 0 then m else Q.sub m b
let map_monomes f l ax =
List.fold_left
(fun acc (a,x) ->
let a = f a in if Q.sign a = 0 then acc else (a, x) :: acc)
[ax] l
let apply_subst sb v =
is_mine (List.fold_left (fun v (x, p) -> embed (subst x p v)) v sb)
substituer toutes variables plus grandes que x
let subst_bigger x l =
List.fold_left
(fun (l, sb) (b, y) ->
if X.ac_extract y != None && X.str_cmp y x > 0 then
let k = X.term_embed (E.fresh_name Ty.Tint) in
(b, k) :: l, (y, embed k)::sb
else (b, y) :: l, sb)
([], []) l
let is_mine_p = List.map (fun (x,p) -> x, is_mine p)
let extract_min = function
| [] -> assert false
| [c] -> c, []
| (a, x) :: s ->
List.fold_left
(fun ((a, x), l) (b, y) ->
if Q.compare (Q.abs a) (Q.abs b) <= 0 then
(a, x), ((b, y) :: l)
else (b, y), ((a, x):: l)) ((a, x),[]) s
Decision Procedures . Page 131
let rec omega l b =
1 . choix d'une variable le |coef| est minimal
let (a, x), l = extract_min l in
2 . substituer les aliens plus grand que x pour
assurer
assurer l'invariant sur l'ordre AC *)
let l, sbs = subst_bigger x l in
let p = P.create l b Ty.Tint in
assert (Q.sign a <> 0);
if Q.equal a Q.one then
3.1 . si a = 1 alors on a une substitution entiere pour x
let p = P.mult_const Q.m_one p in
(x, is_mine p) :: (is_mine_p sbs)
else if Q.equal a Q.m_one then
3.2 . si a = -1 alors on a une subst entiere pour x
(x,is_mine p) :: (is_mine_p sbs)
else
4 . sinon , ( |a| < > 1 ) et a < > 0
4.1 . on rend a positif s'il ne l'est pas deja
let a, l, b =
if Q.sign a < 0 then
(Q.minus a,
List.map (fun (a,x) -> Q.minus a,x) l, (Q.minus b))
else (a, l, b)
in
4.2 . on reduit le systeme
omega_sigma sbs a x l b
and omega_sigma sbs a x l b =
1 . on definie m a + 1
let m = Q.add a Q.one in
2 . on introduit une variable fraiche
let sigma = X.term_embed (E.fresh_name Ty.Tint) in
3 . l'application de la formule ( 5.63 ) nous pivot x
let mm_sigma = (Q.minus m, sigma) in
let l_mod = map_monomes (fun a -> mod_sym a m) l mm_sigma in
3.1 . Attention au signe de b :
on le passe a droite avant de faire mod_sym , d'ou Q.minus
on le passe a droite avant de faire mod_sym, d'ou Q.minus *)
let b_mod = Q.minus (mod_sym (Q.minus b) m) in
let p = P.create l_mod b_mod Ty.Tint in
let sbs = (x, p) :: sbs in
4 . on substitue x par sa valeur dans l'equation de depart .
Voir la formule ( 5.64 )
Voir la formule (5.64) *)
let p' = P.add (P.mult_const a p) (P.create l b Ty.Tint) in
5 . on resoud sur l'equation simplifiee
let sbs2 = solve_int p' in
6 . on normalise sbs par sbs2
let sbs = List.map (fun (x, v) -> x, apply_subst sbs2 v) sbs in
7 . on les liaisons inutiles de sbs2 et on merge avec sbs
let sbs2 = List.filter (fun (y, _) -> not (X.equal y sigma)) sbs2 in
List.rev_append sbs sbs2
and solve_int p =
Steps.incr (Steps.Omega);
if P.is_empty p then raise Not_found;
let pgcd = P.pgcd_numerators p in
let ppmc = P.ppmc_denominators p in
let p = P.mult_const (Q.div ppmc pgcd) p in
let l, b = P.to_list p in
if not (Q.is_int b) then raise Util.Unsolvable;
omega l b
let is_null p =
if Q.sign (snd (P.separate_constant p)) <> 0 then
raise Util.Unsolvable;
[]
let solve_int p =
try solve_int p with Not_found -> is_null p
let solve_real p =
Steps.incr (Steps.Omega);
try
let a, x = P.choose p in
let p = P.mult_const (Q.div Q.m_one a) (P.remove x p) in
[x, is_mine p]
with Not_found -> is_null p
let unsafe_ac_to_arith Sig.{ l = rl; t = ty; _ } =
let mlt = List.fold_left (fun l (r, n) -> expand (embed r) n l) [] rl in
List.fold_left P.mult (P.create [] Q.one ty) mlt
let polynome_distribution p unsafe_mode =
let l, c = P.to_list p in
let ty = P.type_info p in
let pp =
List.fold_left
(fun p (coef, x) ->
match X.ac_extract x with
| Some ac when is_mult ac.h ->
P.add p (P.mult_const coef (unsafe_ac_to_arith ac))
| _ ->
P.add p (P.create [coef,x] Q.zero ty)
) (P.create [] c ty) l
in
if not unsafe_mode && has_ac pp (fun ac -> is_mult ac.h) then p
else pp
let solve_aux r1 r2 unsafe_mode =
Options.tool_req 4 "TR-Arith-Solve";
Debug.solve_aux r1 r2;
let p = P.sub (embed r1) (embed r2) in
let pp = polynome_distribution p unsafe_mode in
let ty = P.type_info p in
let sbs = if ty == Ty.Treal then solve_real pp else solve_int pp in
let sbs = List.fast_sort (fun (a,_) (x,_) -> X.str_cmp x a)sbs in
sbs
let apply_subst r l = List.fold_left (fun r (p,v) -> X.subst p v r) r l
exception Unsafe
let check_pivot_safety p nsbs unsafe_mode =
let q = apply_subst p nsbs in
if X.equal p q then p
else
match X.ac_extract p with
| Some _ when unsafe_mode -> raise Unsafe
| Some ac -> X.ac_embed {ac with distribute = false}
| None -> assert false (* p is a leaf and not interpreted *)
let triangular_down sbs unsafe_mode =
List.fold_right
(fun (p,v) nsbs ->
(check_pivot_safety p nsbs unsafe_mode, apply_subst v nsbs) :: nsbs)
sbs []
let is_non_lin pv = match X.ac_extract pv with
| Some { Sig.h; _ } -> is_mult h
| _ -> false
let make_idemp _ _ sbs lvs unsafe_mode =
let sbs = triangular_down sbs unsafe_mode in
let sbs = triangular_down (List.rev sbs) unsafe_mode in (*triangular up*)
let sbs = List.filter (fun (p,_) -> SX.mem p lvs || is_non_lin p) sbs in
(*
This assert is not TRUE because of AC and distributivity of '*'
assert (not (get_enable_assertions ()) ||
X.equal (apply_subst a sbs) (apply_subst b sbs));
*)
List.iter
(fun (p, _) ->
if not (SX.mem p lvs) then (assert (is_non_lin p); raise Unsafe)
)sbs;
sbs
let solve_one pb r1 r2 lvs unsafe_mode =
let sbt = solve_aux r1 r2 unsafe_mode in
let sbt = make_idemp r1 r2 sbt lvs unsafe_mode in (*may raise Unsafe*)
Debug.solve_one r1 r2 sbt;
Sig.{pb with sbt = List.rev_append sbt pb.sbt}
let solve r1 r2 pb =
let lvs = List.fold_right SX.add (X.leaves r1) SX.empty in
let lvs = List.fold_right SX.add (X.leaves r2) lvs in
try
if Options.get_debug_arith () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"solve"
"Try solving with unsafe mode.";
solve_one pb r1 r2 lvs true (* true == unsafe mode *)
with Unsafe ->
try
if Options.get_debug_arith () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"solve"
"Cancel unsafe solving mode. Try safe mode";
solve_one pb r1 r2 lvs false (* false == safe mode *)
with Unsafe ->
assert false
let make t =
if Options.get_timers() then
try
Timers.exec_timer_start Timers.M_Arith Timers.F_make;
let res = make t in
Timers.exec_timer_pause Timers.M_Arith Timers.F_make;
res
with e ->
Timers.exec_timer_pause Timers.M_Arith Timers.F_make;
raise e
else make t
let solve r1 r2 pb =
if Options.get_timers() then
try
Timers.exec_timer_start Timers.M_Arith Timers.F_solve;
let res = solve r1 r2 pb in
Timers.exec_timer_pause Timers.M_Arith Timers.F_solve;
res
with e ->
Timers.exec_timer_pause Timers.M_Arith Timers.F_solve;
raise e
else solve r1 r2 pb
let print = P.print
let fully_interpreted sb =
match sb with
| Sy.Op (Sy.Plus | Sy.Minus) -> true
| _ -> false
let term_extract _ = None, false
let abstract_selectors p acc =
let p, acc = P.abstract_selectors p acc in
is_mine p, acc
(* this function is only called when some arithmetic values do not yet
appear in IntervalCalculus. Otherwise, the simplex with try to
assign a value
*)
let assign_value =
let cpt_int = ref Q.m_one in
let cpt_real = ref Q.m_one in
let max_constant distincts acc =
List.fold_left
(fun acc x ->
match P.is_const (embed x) with None -> acc | Some c -> Q.max c acc)
acc distincts
in
fun r distincts eq ->
if P.is_const (embed r) != None then None
else
if List.exists
(fun (t,x) ->
let E.{f; ty; _} = E.term_view t in
is_mine_symb f ty && X.leaves x == []
) eq
then None
else
let term_of_cst, cpt = match X.type_info r with
| Ty.Tint -> E.int, cpt_int
| Ty.Treal -> E.real, cpt_real
| _ -> assert false
in
cpt := Q.add Q.one (max_constant distincts !cpt);
Some (term_of_cst (Q.to_string !cpt), true)
let pprint_const_for_model =
let pprint_positive_const c =
let num = Q.num c in
let den = Q.den c in
if Z.is_one den then Z.to_string num
else Format.sprintf "(/ %s %s)" (Z.to_string num) (Z.to_string den)
in
fun r ->
match P.is_const (embed r) with
| None -> assert false
| Some c ->
let sg = Q.sign c in
if sg = 0 then "0"
else if sg > 0 then pprint_positive_const c
else Format.sprintf "(- %s)" (pprint_positive_const (Q.abs c))
let choose_adequate_model t r l =
if Options.get_debug_interpretation () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"choose_adequate_model"
"choose_adequate_model for %a" E.print t;
let l = List.filter (fun (_, r) -> P.is_const (embed r) != None) l in
let r =
match l with
| [] ->
We do this , because terms of some semantic values created
by CS are not created and added to UF
by CS are not created and added to UF *)
assert (P.is_const (embed r) != None);
r
| (_,r)::l ->
List.iter (fun (_,x) -> assert (X.equal x r)) l;
r
in
r, pprint_const_for_model r
end
| null | https://raw.githubusercontent.com/OCamlPro/alt-ergo/695466427b5c3d48e92e90485b12c130c2bce2c1/src/lib/reasoners/arith.ml | ocaml | ****************************************************************************
The Alt-Ergo theorem prover
License version 2.0
------------------------------------------------------------------------
License version 2.0
****************************************************************************
d must be integral and if we work on integer exponentation,
d must be positive
This lines prevent overflow from computation
BISECT-IGNORE-BEGIN
BISECT-IGNORE-END
this function is probably not accurate because it
works on Z.t to compute eventual exact sqrt
may raise Exit
becomes uninterpreted
becomes uninterpreted
becomes uninterpreted
Fixed-Point arithmetic currently not implemented
p is a leaf and not interpreted
triangular up
This assert is not TRUE because of AC and distributivity of '*'
assert (not (get_enable_assertions ()) ||
X.equal (apply_subst a sbs) (apply_subst b sbs));
may raise Unsafe
true == unsafe mode
false == safe mode
this function is only called when some arithmetic values do not yet
appear in IntervalCalculus. Otherwise, the simplex with try to
assign a value
| Copyright ( C ) 2006 - 2013
CNRS - INRIA - Universite Paris Sud
This file is distributed under the terms of the Apache Software
Alt - Ergo : The SMT Solver For Software Verification
Copyright ( C ) 2013 - 2018
This file is distributed under the terms of the Apache Software
module Sy = Symbols
module E = Expr
module Z = Numbers.Z
module Q = Numbers.Q
let is_mult h = Sy.equal (Sy.Op Sy.Mult) h
let mod_symb = Sy.name "@mod"
let calc_power (c : Q.t) (d : Q.t) (ty : Ty.t) =
if not (Q.is_int d) then raise Exit;
if Ty.Tint == ty && Q.sign d < 0 then raise Exit;
let n = match Z.to_machine_int (Q.to_z d) with
| Some n -> n
| None -> raise Exit
in
let sz = Z.numbits (Q.num c) + Z.numbits (Q.den c) in
if sz <> 0 && Stdlib.abs n > 100_000 / sz then raise Exit;
let res = Q.power c n in
assert (ty != Ty.Tint || Q.is_int c);
res
let calc_power_opt (c : Q.t) (d : Q.t) (ty : Ty.t) =
try Some (calc_power c d ty)
with Exit -> None
module Type (X:Sig.X) : Polynome.T with type r = X.r = struct
include
Polynome.Make(struct
include X
module Ac = Ac.Make(X)
let mult v1 v2 =
X.ac_embed
{
distribute = true;
h = Sy.Op Sy.Mult;
t = X.type_info v1;
l = let l2 = match X.ac_extract v1 with
| Some { h; l; _ } when Sy.equal h (Sy.Op Sy.Mult) -> l
| _ -> [v1, 1]
in Ac.add (Sy.Op Sy.Mult) (v2,1) l2
}
end)
end
module Shostak
(X : Sig.X)
(P : Polynome.EXTENDED_Polynome with type r = X.r) = struct
type t = P.t
type r = P.r
let name = "arith"
module Debug = struct
let solve_aux r1 r2 =
if Options.get_debug_arith () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"solve_aux"
"we solve %a=%a" X.print r1 X.print r2
let solve_one r1 r2 sbs =
let c = ref 0 in
let print fmt (p,v) =
incr c;
Format.fprintf fmt "%d) %a |-> %a@." !c X.print p X.print v
in
if Options.get_debug_arith () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"solve_one"
"solving %a = %a yields:@,%a"
X.print r1 X.print r2
(Printer.pp_list_no_space print) sbs
end
let is_mine_symb sy _ty =
let open Sy in
match sy with
| Int _ | Real _ -> true
| Op (Plus | Minus | Mult | Div | Modulo
| Float | Fixed | Abs_int | Abs_real | Sqrt_real
| Sqrt_real_default | Sqrt_real_excess
| Real_of_int | Int_floor | Int_ceil
| Max_int | Max_real | Min_int | Min_real
| Pow | Integer_log2
| Integer_round) -> true
| _ -> false
let empty_polynome ty = P.create [] Q.zero ty
let is_mine p = match P.is_monomial p with
| Some (a,x,b) when Q.equal a Q.one && Q.sign b = 0 -> x
| _ -> P.embed p
let embed r = match P.extract r with
| Some p -> p
| _ -> P.create [Q.one, r] Q.zero (X.type_info r)
t1 % t2 =
c1 . 0 < = c2 . t2 ;
c3 . exists k + t ;
c4 . t2 < > 0 ( already checked )
c1. 0 <= md ;
c2. md < t2 ;
c3. exists k. t1 = t2 * k + t ;
c4. t2 <> 0 (already checked) *)
let mk_modulo md t1 t2 p2 ctx =
let zero = E.int "0" in
let c1 = E.mk_builtin ~is_pos:true Symbols.LE [zero; md] in
let c2 =
match P.is_const p2 with
| Some n2 ->
let an2 = Q.abs n2 in
assert (Q.is_int an2);
let t2 = E.int (Q.to_string an2) in
E.mk_builtin ~is_pos:true Symbols.LT [md; t2]
| None ->
E.mk_builtin ~is_pos:true Symbols.LT [md; t2]
in
let k = E.fresh_name Ty.Tint in
let t3 = E.mk_term (Sy.Op Sy.Mult) [t2;k] Ty.Tint in
let t3 = E.mk_term (Sy.Op Sy.Plus) [t3;md] Ty.Tint in
let c3 = E.mk_eq ~iff:false t1 t3 in
c3 :: c2 :: c1 :: ctx
let mk_euc_division p p2 t1 t2 ctx =
match P.to_list p2 with
| [], coef_p2 ->
let md = E.mk_term (Sy.Op Sy.Modulo) [t1;t2] Ty.Tint in
let r, ctx' = X.make md in
let rp =
P.mult_const (Q.div Q.one coef_p2) (embed r) in
P.sub p rp, ctx' @ ctx
| _ -> assert false
let exact_sqrt_or_Exit q =
let c = Q.sign q in
if c < 0 then raise Exit;
let n = Q.num q in
let d = Q.den q in
let s_n, _ = Z.sqrt_rem n in
assert (Z.sign s_n >= 0);
if not (Z.equal (Z.mult s_n s_n) n) then raise Exit;
let s_d, _ = Z.sqrt_rem d in
assert (Z.sign s_d >= 0);
if not (Z.equal (Z.mult s_d s_d) d) then raise Exit;
let res = Q.from_zz s_n s_d in
assert (Q.equal (Q.mult res res) q);
res
let default_sqrt_or_Exit q =
let c = Q.sign q in
if c < 0 then raise Exit;
match Q.sqrt_default q with
| None -> raise Exit
| Some res -> assert (Q.compare (Q.mult res res) q <= 0); res
let excess_sqrt_or_Exit q =
let c = Q.sign q in
if c < 0 then raise Exit;
match Q.sqrt_excess q with
| None -> raise Exit
| Some res -> assert (Q.compare (Q.mult res res) q >= 0); res
let mk_partial_interpretation_1 aux_func coef p_acc ty t x =
let r_x, _ = X.make x in
try
match P.to_list (embed r_x) with
| [], d ->
P.add_const (Q.mult coef d) p_acc
| _ -> raise Exit
with Exit ->
let a = X.term_embed t in
P.add (P.create [coef, a] Q.zero ty) p_acc
let mk_partial_interpretation_2 aux_func coef p_acc ty t x y =
let px = embed (fst (X.make x)) in
let py = embed (fst (X.make y)) in
try
match P.is_const px, P.is_const py with
| Some c_x, Some c_y ->
P.add_const (Q.mult coef (aux_func c_x c_y)) p_acc
| _ ->
P.add (P.create [coef, (X.term_embed t)] Q.zero ty) p_acc
with Exit ->
P.add (P.create [coef, (X.term_embed t)] Q.zero ty) p_acc
let rec mke coef p t ctx =
let { E.f = sb ; xs; ty; _ } = E.term_view t in
match sb, xs with
| (Sy.Int n | Sy.Real n) , _ ->
let c = Q.mult coef (Q.from_string (Hstring.view n)) in
P.add_const c p, ctx
| Sy.Op Sy.Mult, [t1;t2] ->
let p1, ctx = mke coef (empty_polynome ty) t1 ctx in
let p2, ctx = mke Q.one (empty_polynome ty) t2 ctx in
if Options.get_no_nla() && P.is_const p1 == None && P.is_const p2 == None
then
let tau = E.mk_term (Sy.name ~kind:Sy.Ac "@*") [t1; t2] ty in
let xtau, ctx' = X.make tau in
P.add p (P.create [coef, xtau] Q.zero ty), List.rev_append ctx' ctx
else
P.add p (P.mult p1 p2), ctx
| Sy.Op Sy.Div, [t1;t2] ->
let p1, ctx = mke Q.one (empty_polynome ty) t1 ctx in
let p2, ctx = mke Q.one (empty_polynome ty) t2 ctx in
if Options.get_no_nla() &&
(P.is_const p2 == None ||
(ty == Ty.Tint && P.is_const p1 == None)) then
let tau = E.mk_term (Sy.name "@/") [t1; t2] ty in
let xtau, ctx' = X.make tau in
P.add p (P.create [coef, xtau] Q.zero ty), List.rev_append ctx' ctx
else
let p3, ctx =
try
let p, approx = P.div p1 p2 in
if approx then mk_euc_division p p2 t1 t2 ctx
else p, ctx
with Division_by_zero | Polynome.Maybe_zero ->
P.create [Q.one, X.term_embed t] Q.zero ty, ctx
in
P.add p (P.mult_const coef p3), ctx
| Sy.Op Sy.Plus , l ->
List.fold_left (fun (p, ctx) u -> mke coef p u ctx )(p, ctx) l
| Sy.Op Sy.Minus , [t1;t2] ->
let p2, ctx = mke (Q.minus coef) p t2 ctx in
mke coef p2 t1 ctx
| Sy.Op Sy.Modulo , [t1;t2] ->
let p1, ctx = mke Q.one (empty_polynome ty) t1 ctx in
let p2, ctx = mke Q.one (empty_polynome ty) t2 ctx in
if Options.get_no_nla() &&
(P.is_const p1 == None || P.is_const p2 == None)
then
let tau = E.mk_term (Sy.name "@%") [t1; t2] ty in
let xtau, ctx' = X.make tau in
P.add p (P.create [coef, xtau] Q.zero ty), List.rev_append ctx' ctx
else
let p3, ctx =
try P.modulo p1 p2, ctx
with e ->
let t = E.mk_term mod_symb [t1; t2] Ty.Tint in
let ctx = match e with
| Division_by_zero | Polynome.Maybe_zero -> ctx
| Polynome.Not_a_num -> mk_modulo t t1 t2 p2 ctx
| _ -> assert false
in
P.create [Q.one, X.term_embed t] Q.zero ty, ctx
in
P.add p (P.mult_const coef p3), ctx
* * < begin > : partial handling of some arith / FPA operators *
| Sy.Op Sy.Float, [prec; exp; mode; x] ->
let aux_func e =
let res, _, _ = Fpa_rounding.float_of_rational prec exp mode e in
res
in
mk_partial_interpretation_1 aux_func coef p ty t x, ctx
| Sy.Op Sy.Integer_round, [mode; x] ->
let aux_func = Fpa_rounding.round_to_integer mode in
mk_partial_interpretation_1 aux_func coef p ty t x, ctx
| Sy.Op (Sy.Abs_int | Sy.Abs_real) , [x] ->
mk_partial_interpretation_1 Q.abs coef p ty t x, ctx
| Sy.Op Sy.Sqrt_real, [x] ->
mk_partial_interpretation_1 exact_sqrt_or_Exit coef p ty t x, ctx
| Sy.Op Sy.Sqrt_real_default, [x] ->
mk_partial_interpretation_1 default_sqrt_or_Exit coef p ty t x, ctx
| Sy.Op Sy.Sqrt_real_excess, [x] ->
mk_partial_interpretation_1 excess_sqrt_or_Exit coef p ty t x, ctx
| Sy.Op Sy.Real_of_int, [x] ->
mk_partial_interpretation_1 (fun d -> d) coef p ty t x, ctx
| Sy.Op Sy.Int_floor, [x] ->
mk_partial_interpretation_1 Q.floor coef p ty t x, ctx
| Sy.Op Sy.Int_ceil, [x] ->
mk_partial_interpretation_1 Q.ceiling coef p ty t x, ctx
| Sy.Op (Sy.Max_int | Sy.Max_real), [x;y] ->
let aux_func c d = if Q.compare c d >= 0 then c else d in
mk_partial_interpretation_2 aux_func coef p ty t x y, ctx
| Sy.Op (Sy.Min_int | Sy.Min_real), [x;y] ->
let aux_func c d = if Q.compare c d <= 0 then c else d in
mk_partial_interpretation_2 aux_func coef p ty t x y, ctx
| Sy.Op Sy.Integer_log2, [x] ->
let aux_func q =
if Q.compare_to_0 q <= 0 then raise Exit;
Q.from_int (Fpa_rounding.integer_log_2 q)
in
mk_partial_interpretation_1 aux_func coef p ty t x, ctx
| Sy.Op Sy.Pow, [x; y] ->
mk_partial_interpretation_2
(fun x y -> calc_power x y ty) coef p ty t x y, ctx
| Sy.Op Sy.Fixed, _ ->
assert false
* * < end > : partial handling of some arith / FPA operators *
| _ ->
let a, ctx' = X.make t in
let ctx = ctx' @ ctx in
match P.extract a with
| Some p' -> P.add p (P.mult_const coef p'), ctx
| _ -> P.add p (P.create [coef, a] Q.zero ty), ctx
let make t =
Options.tool_req 4 "TR-Arith-Make";
let ty = E.type_info t in
let p, ctx = mke Q.one (empty_polynome ty) t [] in
is_mine p, ctx
let rec expand p n acc =
assert (n >=0);
if n = 0 then acc else expand p (n-1) (p::acc)
let unsafe_ac_to_arith Sig.{ l = rl; t = ty; _ } =
let mlt = List.fold_left (fun l (r,n) -> expand (embed r)n l) [] rl in
List.fold_left P.mult (P.create [] Q.one ty) mlt
let rec number_of_vars l =
List.fold_left (fun acc (r, n) -> acc + n * nb_vars_in_alien r) 0 l
and nb_vars_in_alien r =
match P.extract r with
| Some p ->
let l, _ = P.to_list p in
List.fold_left (fun acc (_, x) -> max acc (nb_vars_in_alien x)) 0 l
| None ->
begin
match X.ac_extract r with
| Some ac when is_mult ac.h ->
number_of_vars ac.l
| _ -> 1
end
let max_list_ = function
| [] -> 0
| [ _, x ] -> nb_vars_in_alien x
| (_, x) :: l ->
let acc = nb_vars_in_alien x in
List.fold_left (fun acc (_, x) -> max acc (nb_vars_in_alien x)) acc l
let contains_a_fresh_alien xp =
List.exists
(fun x ->
match X.term_extract x with
| Some t, _ -> E.is_fresh t
| _ -> false
) (X.leaves xp)
let has_ac p kind =
List.exists
(fun (_, x) ->
match X.ac_extract x with Some ac -> kind ac | _ -> false)
(fst (P.to_list p))
let color ac =
match ac.Sig.l with
| [(_, 1)] -> assert false
| _ ->
let p = unsafe_ac_to_arith ac in
if not ac.distribute then
if has_ac p (fun ac -> is_mult ac.h) then X.ac_embed ac
else is_mine p
else
let xp = is_mine p in
if contains_a_fresh_alien xp then
let l, _ = P.to_list p in
let mx = max_list_ l in
if mx = 0 || mx = 1 || number_of_vars ac.l > mx then is_mine p
else X.ac_embed ac
else xp
let type_info p = P.type_info p
module SX = Set.Make(struct type t = r let compare = X.hash_cmp end)
let leaves p = P.leaves p
let subst x t p =
let p = P.subst x (embed t) p in
let ty = P.type_info p in
let l, c = P.to_list p in
let p =
List.fold_left
(fun p (ai, xi) ->
let xi' = X.subst x t xi in
let p' = match P.extract xi' with
| Some p' -> P.mult_const ai p'
| _ -> P.create [ai, xi'] Q.zero ty
in
P.add p p')
(P.create [] c ty) l
in
is_mine p
let compare x y = P.compare (embed x) (embed y)
let equal p1 p2 = P.equal p1 p2
let hash = P.hash
symmetric modulo p 131
let mod_sym a b =
let m = Q.modulo a b in
let m =
if Q.sign m < 0 then
if Q.compare m (Q.minus b) >= 0 then Q.add m b else assert false
else
if Q.compare m b <= 0 then m else assert false
in
if Q.compare m (Q.div b (Q.from_int 2)) < 0 then m else Q.sub m b
let map_monomes f l ax =
List.fold_left
(fun acc (a,x) ->
let a = f a in if Q.sign a = 0 then acc else (a, x) :: acc)
[ax] l
let apply_subst sb v =
is_mine (List.fold_left (fun v (x, p) -> embed (subst x p v)) v sb)
substituer toutes variables plus grandes que x
let subst_bigger x l =
List.fold_left
(fun (l, sb) (b, y) ->
if X.ac_extract y != None && X.str_cmp y x > 0 then
let k = X.term_embed (E.fresh_name Ty.Tint) in
(b, k) :: l, (y, embed k)::sb
else (b, y) :: l, sb)
([], []) l
let is_mine_p = List.map (fun (x,p) -> x, is_mine p)
let extract_min = function
| [] -> assert false
| [c] -> c, []
| (a, x) :: s ->
List.fold_left
(fun ((a, x), l) (b, y) ->
if Q.compare (Q.abs a) (Q.abs b) <= 0 then
(a, x), ((b, y) :: l)
else (b, y), ((a, x):: l)) ((a, x),[]) s
Decision Procedures . Page 131
let rec omega l b =
1 . choix d'une variable le |coef| est minimal
let (a, x), l = extract_min l in
2 . substituer les aliens plus grand que x pour
assurer
assurer l'invariant sur l'ordre AC *)
let l, sbs = subst_bigger x l in
let p = P.create l b Ty.Tint in
assert (Q.sign a <> 0);
if Q.equal a Q.one then
3.1 . si a = 1 alors on a une substitution entiere pour x
let p = P.mult_const Q.m_one p in
(x, is_mine p) :: (is_mine_p sbs)
else if Q.equal a Q.m_one then
3.2 . si a = -1 alors on a une subst entiere pour x
(x,is_mine p) :: (is_mine_p sbs)
else
4 . sinon , ( |a| < > 1 ) et a < > 0
4.1 . on rend a positif s'il ne l'est pas deja
let a, l, b =
if Q.sign a < 0 then
(Q.minus a,
List.map (fun (a,x) -> Q.minus a,x) l, (Q.minus b))
else (a, l, b)
in
4.2 . on reduit le systeme
omega_sigma sbs a x l b
and omega_sigma sbs a x l b =
1 . on definie m a + 1
let m = Q.add a Q.one in
2 . on introduit une variable fraiche
let sigma = X.term_embed (E.fresh_name Ty.Tint) in
3 . l'application de la formule ( 5.63 ) nous pivot x
let mm_sigma = (Q.minus m, sigma) in
let l_mod = map_monomes (fun a -> mod_sym a m) l mm_sigma in
3.1 . Attention au signe de b :
on le passe a droite avant de faire mod_sym , d'ou Q.minus
on le passe a droite avant de faire mod_sym, d'ou Q.minus *)
let b_mod = Q.minus (mod_sym (Q.minus b) m) in
let p = P.create l_mod b_mod Ty.Tint in
let sbs = (x, p) :: sbs in
4 . on substitue x par sa valeur dans l'equation de depart .
Voir la formule ( 5.64 )
Voir la formule (5.64) *)
let p' = P.add (P.mult_const a p) (P.create l b Ty.Tint) in
5 . on resoud sur l'equation simplifiee
let sbs2 = solve_int p' in
6 . on normalise sbs par sbs2
let sbs = List.map (fun (x, v) -> x, apply_subst sbs2 v) sbs in
7 . on les liaisons inutiles de sbs2 et on merge avec sbs
let sbs2 = List.filter (fun (y, _) -> not (X.equal y sigma)) sbs2 in
List.rev_append sbs sbs2
and solve_int p =
Steps.incr (Steps.Omega);
if P.is_empty p then raise Not_found;
let pgcd = P.pgcd_numerators p in
let ppmc = P.ppmc_denominators p in
let p = P.mult_const (Q.div ppmc pgcd) p in
let l, b = P.to_list p in
if not (Q.is_int b) then raise Util.Unsolvable;
omega l b
let is_null p =
if Q.sign (snd (P.separate_constant p)) <> 0 then
raise Util.Unsolvable;
[]
let solve_int p =
try solve_int p with Not_found -> is_null p
let solve_real p =
Steps.incr (Steps.Omega);
try
let a, x = P.choose p in
let p = P.mult_const (Q.div Q.m_one a) (P.remove x p) in
[x, is_mine p]
with Not_found -> is_null p
let unsafe_ac_to_arith Sig.{ l = rl; t = ty; _ } =
let mlt = List.fold_left (fun l (r, n) -> expand (embed r) n l) [] rl in
List.fold_left P.mult (P.create [] Q.one ty) mlt
let polynome_distribution p unsafe_mode =
let l, c = P.to_list p in
let ty = P.type_info p in
let pp =
List.fold_left
(fun p (coef, x) ->
match X.ac_extract x with
| Some ac when is_mult ac.h ->
P.add p (P.mult_const coef (unsafe_ac_to_arith ac))
| _ ->
P.add p (P.create [coef,x] Q.zero ty)
) (P.create [] c ty) l
in
if not unsafe_mode && has_ac pp (fun ac -> is_mult ac.h) then p
else pp
let solve_aux r1 r2 unsafe_mode =
Options.tool_req 4 "TR-Arith-Solve";
Debug.solve_aux r1 r2;
let p = P.sub (embed r1) (embed r2) in
let pp = polynome_distribution p unsafe_mode in
let ty = P.type_info p in
let sbs = if ty == Ty.Treal then solve_real pp else solve_int pp in
let sbs = List.fast_sort (fun (a,_) (x,_) -> X.str_cmp x a)sbs in
sbs
let apply_subst r l = List.fold_left (fun r (p,v) -> X.subst p v r) r l
exception Unsafe
let check_pivot_safety p nsbs unsafe_mode =
let q = apply_subst p nsbs in
if X.equal p q then p
else
match X.ac_extract p with
| Some _ when unsafe_mode -> raise Unsafe
| Some ac -> X.ac_embed {ac with distribute = false}
let triangular_down sbs unsafe_mode =
List.fold_right
(fun (p,v) nsbs ->
(check_pivot_safety p nsbs unsafe_mode, apply_subst v nsbs) :: nsbs)
sbs []
let is_non_lin pv = match X.ac_extract pv with
| Some { Sig.h; _ } -> is_mult h
| _ -> false
let make_idemp _ _ sbs lvs unsafe_mode =
let sbs = triangular_down sbs unsafe_mode in
let sbs = List.filter (fun (p,_) -> SX.mem p lvs || is_non_lin p) sbs in
List.iter
(fun (p, _) ->
if not (SX.mem p lvs) then (assert (is_non_lin p); raise Unsafe)
)sbs;
sbs
let solve_one pb r1 r2 lvs unsafe_mode =
let sbt = solve_aux r1 r2 unsafe_mode in
Debug.solve_one r1 r2 sbt;
Sig.{pb with sbt = List.rev_append sbt pb.sbt}
let solve r1 r2 pb =
let lvs = List.fold_right SX.add (X.leaves r1) SX.empty in
let lvs = List.fold_right SX.add (X.leaves r2) lvs in
try
if Options.get_debug_arith () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"solve"
"Try solving with unsafe mode.";
with Unsafe ->
try
if Options.get_debug_arith () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"solve"
"Cancel unsafe solving mode. Try safe mode";
with Unsafe ->
assert false
let make t =
if Options.get_timers() then
try
Timers.exec_timer_start Timers.M_Arith Timers.F_make;
let res = make t in
Timers.exec_timer_pause Timers.M_Arith Timers.F_make;
res
with e ->
Timers.exec_timer_pause Timers.M_Arith Timers.F_make;
raise e
else make t
let solve r1 r2 pb =
if Options.get_timers() then
try
Timers.exec_timer_start Timers.M_Arith Timers.F_solve;
let res = solve r1 r2 pb in
Timers.exec_timer_pause Timers.M_Arith Timers.F_solve;
res
with e ->
Timers.exec_timer_pause Timers.M_Arith Timers.F_solve;
raise e
else solve r1 r2 pb
let print = P.print
let fully_interpreted sb =
match sb with
| Sy.Op (Sy.Plus | Sy.Minus) -> true
| _ -> false
let term_extract _ = None, false
let abstract_selectors p acc =
let p, acc = P.abstract_selectors p acc in
is_mine p, acc
let assign_value =
let cpt_int = ref Q.m_one in
let cpt_real = ref Q.m_one in
let max_constant distincts acc =
List.fold_left
(fun acc x ->
match P.is_const (embed x) with None -> acc | Some c -> Q.max c acc)
acc distincts
in
fun r distincts eq ->
if P.is_const (embed r) != None then None
else
if List.exists
(fun (t,x) ->
let E.{f; ty; _} = E.term_view t in
is_mine_symb f ty && X.leaves x == []
) eq
then None
else
let term_of_cst, cpt = match X.type_info r with
| Ty.Tint -> E.int, cpt_int
| Ty.Treal -> E.real, cpt_real
| _ -> assert false
in
cpt := Q.add Q.one (max_constant distincts !cpt);
Some (term_of_cst (Q.to_string !cpt), true)
let pprint_const_for_model =
let pprint_positive_const c =
let num = Q.num c in
let den = Q.den c in
if Z.is_one den then Z.to_string num
else Format.sprintf "(/ %s %s)" (Z.to_string num) (Z.to_string den)
in
fun r ->
match P.is_const (embed r) with
| None -> assert false
| Some c ->
let sg = Q.sign c in
if sg = 0 then "0"
else if sg > 0 then pprint_positive_const c
else Format.sprintf "(- %s)" (pprint_positive_const (Q.abs c))
let choose_adequate_model t r l =
if Options.get_debug_interpretation () then
Printer.print_dbg
~module_name:"Arith" ~function_name:"choose_adequate_model"
"choose_adequate_model for %a" E.print t;
let l = List.filter (fun (_, r) -> P.is_const (embed r) != None) l in
let r =
match l with
| [] ->
We do this , because terms of some semantic values created
by CS are not created and added to UF
by CS are not created and added to UF *)
assert (P.is_const (embed r) != None);
r
| (_,r)::l ->
List.iter (fun (_,x) -> assert (X.equal x r)) l;
r
in
r, pprint_const_for_model r
end
|
898f380ae8acf5ce1531f02d5bd584772645b09883855d6df2581f80bf293f0a | ftovagliari/ocamleditor | editor_dialog.ml |
OCamlEditor
Copyright ( C ) 2010 - 2014
This file is part of OCamlEditor .
OCamlEditor is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
OCamlEditor 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 , see < / > .
OCamlEditor
Copyright (C) 2010-2014 Francesco Tovagliari
This file is part of OCamlEditor.
OCamlEditor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCamlEditor 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, see </>.
*)
open Printf
open Miscellanea
(** file_select *)
let file_select ~editor () =
let window = GWindow.window ~title:"Switch"
~width:600 ~height:400 ~modal:true
~position:`CENTER ~border_width:5 ~show:false () in
Gmisclib.Window.GeometryMemo.add ~key:"dialog-switch-window" ~window Preferences.geometry_memo;
Gaux.may (GWindow.toplevel editor) ~f:(fun x -> window#set_transient_for x#as_window);
let vbox = GPack.vbox ~spacing:0 ~packing:window#add () in
let cols = new GTree.column_list in
let col_icon = cols#add Gobject.Data.string in
let col_name = cols#add Gobject.Data.string in
let col_path = cols#add Gobject.Data.string in
let model = GTree.list_store cols in
let renderer = GTree.cell_renderer_text [] in
let renderer_bold = GTree.cell_renderer_text [] in
let renderer_icon = GTree.cell_renderer_pixbuf [] in
renderer_bold#set_properties [`WEIGHT `BOLD];
let vc_name = GTree.view_column ~title:"File" ~renderer:(renderer_bold, ["text", col_name]) () in
let vc_path = GTree.view_column ~title:"Path" ~renderer:(renderer, ["text", col_path]) () in
let vc_icon = GTree.view_column ~title:"" ~renderer:(renderer_icon, ["stock-id", col_icon]) () in
let sw = GBin.scrolled_window ~shadow_type:`IN ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
~packing:vbox#add () in
let view = GTree.view ~model:model ~headers_visible:false ~reorderable:true ~width:130 ~packing:sw#add () in
view#append_column vc_icon;
view#append_column vc_name;
view#append_column vc_path;
view#selection#set_mode `MULTIPLE;
view#set_search_column 1;
List.iter begin fun p ->
let row = model#append() in
let _, _, label = p#tab_widget in
model#set ~row ~column:col_name label#text;
model#set ~row ~column:col_path p#get_filename;
let opened, changed =
match editor#get_page (`FILENAME p#get_filename) with
| None -> false, false
| Some page -> true, page#view#buffer#modified
in
model#set ~row ~column:col_icon (if changed then "gtk-floppy" else "");
end editor#pages;
let bbox = GPack.button_box `HORIZONTAL ~layout:`END ~border_width:8 ~spacing:8
~packing:(vbox#pack ~expand:false) () in
let button_close = GButton.button ~label:"Close files" ~packing:bbox#add () in
let button_cancel = GButton.button ~label:"Done" ~packing:bbox#add () in
button_cancel#connect#clicked ~callback:window#destroy;
let activate () =
List.iter begin fun path ->
let row = model#get_iter path in
let filename = model#get ~row ~column:col_path in
ignore (editor#open_file ~active:true ~scroll_offset:0 ~offset:0 ?remote:None filename)
end view#selection#get_selected_rows;
window#destroy()
in
ignore (view#connect#row_activated ~callback:(fun _ _ -> activate ()));
ignore (button_close#connect#clicked ~callback:begin fun () ->
let closing = ref [] in
List.iter begin fun path ->
let row = model#get_iter path in
let filename = model#get ~row ~column:col_path in
let page = editor#open_file ~active:true ~scroll_offset:0 ~offset:0 ?remote:None filename in
Gaux.may (editor#get_page `ACTIVE) ~f:(fun p -> ignore (editor#dialog_confirm_close p));
closing := row :: !closing;
end view#selection#get_selected_rows;
ignore (List.map model#remove !closing)
end);
ignore (window#event#connect#key_release ~callback:begin fun ev ->
let key = GdkEvent.Key.keyval ev in
if key = GdkKeysyms._Escape then (window#destroy(); true)
else begin
window#present();
false
end
end);
editor#with_current_page begin fun page ->
model#foreach begin fun _ row ->
let filename = model#get ~row ~column:col_path in
if filename = page#get_filename then begin
view#selection#select_iter row;
false
end else false
end;
window#misc#set_can_focus true;
window#misc#grab_focus();
view#misc#grab_focus();
window#present()
end
(** confirm_close *)
let confirm_close ~editor (page : Editor_page.page) =
if page#buffer#modified then begin
let message = sprintf "File modified: \xC2\xAB%s\xC2\xBB. Do you wish to save changes?"
(Filename.basename page#get_filename) in
let response = Dialog.confirm
~title:"Close Modified File"
~message ~image:(GMisc.image ~stock:`SAVE ~icon_size:`DIALOG ())#coerce
~yes:("Save", begin fun () ->
editor#save page;
editor#close page;
end)
~no:("Do Not Save", begin fun () ->
editor#close page;
end) page
in response <> `CANCEL
end else (editor#close page; true)
(** save_modified *)
let save_modified ~editor ~close ~callback pages =
if pages <> [] then begin
let dialog = GWindow.dialog ~position:`CENTER ~border_width:5 ~no_separator:true
~icon:Icons.oe ~modal:true ~title:"Save Modified" () in
let checklist = new Checklist.checklist
~packing:dialog#vbox#add
(List.map (fun (x, p) -> x, p#get_filename) pages) in
dialog#add_button_stock `OK `OK;
dialog#add_button_stock `CANCEL `CANCEL;
dialog#action_area#add checklist#button_all#coerce;
dialog#action_area#add checklist#button_none#coerce;
dialog#action_area#set_child_secondary checklist#button_all#coerce true;
dialog#action_area#set_child_secondary checklist#button_none#coerce true;
match dialog#run () with
| `OK ->
checklist#iter begin fun save filename ->
let _, page = List.find (fun (_, p) -> p#get_filename = filename) pages in
if save then (editor#save page) else (Autosave.delete ~filename ());
if close then editor#close page;
end;
dialog#destroy();
callback();
| _ -> dialog#destroy()
end else (callback())
(** file_open *)
let file_open ~editor () =
let path = editor#project.Prj.root // Prj.default_dir_src in
let filters = [
("Source files", ["*.ml*"; "README*"; "INSTALL*"; "META";
"ChangeLog"; "CHANGES"; "NEWS*"; "TODO*"; "BUGS*"; "CONTRIB*";
"Makefile*"; "*.sh"; "*.bat"; "*.cmd"]);
("All files", ["*"])]
in
let dialog = GWindow.file_chooser_dialog ~action:`OPEN ~width:600 ~height:600
~title:"Open file..." ~icon:Icons.oe ~position:`CENTER ~show:false () in
List.iter begin fun (name, patterns) ->
dialog#add_filter (GFile.filter ~name ~patterns ())
end filters;
dialog#add_select_button_stock `OK `OK;
dialog#add_button_stock `CANCEL `CANCEL;
dialog#set_current_folder path;
dialog#set_select_multiple true;
match dialog#run () with
| `OK ->
List.iter (fun filename ->
ignore (editor#open_file ~active:true ~scroll_offset:0 ~offset:0 ?remote:None filename)) dialog#get_filenames;
dialog#destroy()
| _ -> dialog#destroy()
| null | https://raw.githubusercontent.com/ftovagliari/ocamleditor/53284253cf7603b96051e7425e85a731f09abcd1/src/editor_dialog.ml | ocaml | * file_select
* confirm_close
* save_modified
* file_open |
OCamlEditor
Copyright ( C ) 2010 - 2014
This file is part of OCamlEditor .
OCamlEditor is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
OCamlEditor 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 , see < / > .
OCamlEditor
Copyright (C) 2010-2014 Francesco Tovagliari
This file is part of OCamlEditor.
OCamlEditor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OCamlEditor 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, see </>.
*)
open Printf
open Miscellanea
let file_select ~editor () =
let window = GWindow.window ~title:"Switch"
~width:600 ~height:400 ~modal:true
~position:`CENTER ~border_width:5 ~show:false () in
Gmisclib.Window.GeometryMemo.add ~key:"dialog-switch-window" ~window Preferences.geometry_memo;
Gaux.may (GWindow.toplevel editor) ~f:(fun x -> window#set_transient_for x#as_window);
let vbox = GPack.vbox ~spacing:0 ~packing:window#add () in
let cols = new GTree.column_list in
let col_icon = cols#add Gobject.Data.string in
let col_name = cols#add Gobject.Data.string in
let col_path = cols#add Gobject.Data.string in
let model = GTree.list_store cols in
let renderer = GTree.cell_renderer_text [] in
let renderer_bold = GTree.cell_renderer_text [] in
let renderer_icon = GTree.cell_renderer_pixbuf [] in
renderer_bold#set_properties [`WEIGHT `BOLD];
let vc_name = GTree.view_column ~title:"File" ~renderer:(renderer_bold, ["text", col_name]) () in
let vc_path = GTree.view_column ~title:"Path" ~renderer:(renderer, ["text", col_path]) () in
let vc_icon = GTree.view_column ~title:"" ~renderer:(renderer_icon, ["stock-id", col_icon]) () in
let sw = GBin.scrolled_window ~shadow_type:`IN ~hpolicy:`AUTOMATIC ~vpolicy:`AUTOMATIC
~packing:vbox#add () in
let view = GTree.view ~model:model ~headers_visible:false ~reorderable:true ~width:130 ~packing:sw#add () in
view#append_column vc_icon;
view#append_column vc_name;
view#append_column vc_path;
view#selection#set_mode `MULTIPLE;
view#set_search_column 1;
List.iter begin fun p ->
let row = model#append() in
let _, _, label = p#tab_widget in
model#set ~row ~column:col_name label#text;
model#set ~row ~column:col_path p#get_filename;
let opened, changed =
match editor#get_page (`FILENAME p#get_filename) with
| None -> false, false
| Some page -> true, page#view#buffer#modified
in
model#set ~row ~column:col_icon (if changed then "gtk-floppy" else "");
end editor#pages;
let bbox = GPack.button_box `HORIZONTAL ~layout:`END ~border_width:8 ~spacing:8
~packing:(vbox#pack ~expand:false) () in
let button_close = GButton.button ~label:"Close files" ~packing:bbox#add () in
let button_cancel = GButton.button ~label:"Done" ~packing:bbox#add () in
button_cancel#connect#clicked ~callback:window#destroy;
let activate () =
List.iter begin fun path ->
let row = model#get_iter path in
let filename = model#get ~row ~column:col_path in
ignore (editor#open_file ~active:true ~scroll_offset:0 ~offset:0 ?remote:None filename)
end view#selection#get_selected_rows;
window#destroy()
in
ignore (view#connect#row_activated ~callback:(fun _ _ -> activate ()));
ignore (button_close#connect#clicked ~callback:begin fun () ->
let closing = ref [] in
List.iter begin fun path ->
let row = model#get_iter path in
let filename = model#get ~row ~column:col_path in
let page = editor#open_file ~active:true ~scroll_offset:0 ~offset:0 ?remote:None filename in
Gaux.may (editor#get_page `ACTIVE) ~f:(fun p -> ignore (editor#dialog_confirm_close p));
closing := row :: !closing;
end view#selection#get_selected_rows;
ignore (List.map model#remove !closing)
end);
ignore (window#event#connect#key_release ~callback:begin fun ev ->
let key = GdkEvent.Key.keyval ev in
if key = GdkKeysyms._Escape then (window#destroy(); true)
else begin
window#present();
false
end
end);
editor#with_current_page begin fun page ->
model#foreach begin fun _ row ->
let filename = model#get ~row ~column:col_path in
if filename = page#get_filename then begin
view#selection#select_iter row;
false
end else false
end;
window#misc#set_can_focus true;
window#misc#grab_focus();
view#misc#grab_focus();
window#present()
end
let confirm_close ~editor (page : Editor_page.page) =
if page#buffer#modified then begin
let message = sprintf "File modified: \xC2\xAB%s\xC2\xBB. Do you wish to save changes?"
(Filename.basename page#get_filename) in
let response = Dialog.confirm
~title:"Close Modified File"
~message ~image:(GMisc.image ~stock:`SAVE ~icon_size:`DIALOG ())#coerce
~yes:("Save", begin fun () ->
editor#save page;
editor#close page;
end)
~no:("Do Not Save", begin fun () ->
editor#close page;
end) page
in response <> `CANCEL
end else (editor#close page; true)
let save_modified ~editor ~close ~callback pages =
if pages <> [] then begin
let dialog = GWindow.dialog ~position:`CENTER ~border_width:5 ~no_separator:true
~icon:Icons.oe ~modal:true ~title:"Save Modified" () in
let checklist = new Checklist.checklist
~packing:dialog#vbox#add
(List.map (fun (x, p) -> x, p#get_filename) pages) in
dialog#add_button_stock `OK `OK;
dialog#add_button_stock `CANCEL `CANCEL;
dialog#action_area#add checklist#button_all#coerce;
dialog#action_area#add checklist#button_none#coerce;
dialog#action_area#set_child_secondary checklist#button_all#coerce true;
dialog#action_area#set_child_secondary checklist#button_none#coerce true;
match dialog#run () with
| `OK ->
checklist#iter begin fun save filename ->
let _, page = List.find (fun (_, p) -> p#get_filename = filename) pages in
if save then (editor#save page) else (Autosave.delete ~filename ());
if close then editor#close page;
end;
dialog#destroy();
callback();
| _ -> dialog#destroy()
end else (callback())
let file_open ~editor () =
let path = editor#project.Prj.root // Prj.default_dir_src in
let filters = [
("Source files", ["*.ml*"; "README*"; "INSTALL*"; "META";
"ChangeLog"; "CHANGES"; "NEWS*"; "TODO*"; "BUGS*"; "CONTRIB*";
"Makefile*"; "*.sh"; "*.bat"; "*.cmd"]);
("All files", ["*"])]
in
let dialog = GWindow.file_chooser_dialog ~action:`OPEN ~width:600 ~height:600
~title:"Open file..." ~icon:Icons.oe ~position:`CENTER ~show:false () in
List.iter begin fun (name, patterns) ->
dialog#add_filter (GFile.filter ~name ~patterns ())
end filters;
dialog#add_select_button_stock `OK `OK;
dialog#add_button_stock `CANCEL `CANCEL;
dialog#set_current_folder path;
dialog#set_select_multiple true;
match dialog#run () with
| `OK ->
List.iter (fun filename ->
ignore (editor#open_file ~active:true ~scroll_offset:0 ~offset:0 ?remote:None filename)) dialog#get_filenames;
dialog#destroy()
| _ -> dialog#destroy()
|
cd4821f9a22ed1b075c67b3e8d724b441a5079b6810cceb9fcb99fc6b0af5e46 | ocsigen/eliomlang | el_desugar.ml | open Parsetree
open Ast_helper
module AM = Ast_mapper
module AC = Ast_convenience
open El_utils
(**
Replace shared expression by the equivalent pair.
[ [%share
let x = ... %s ... in
[%client ... %x ... ]
] ]
≡
[ let x = ... s ... in
[%client ... %x ... ]
,
[%client
let x = ... %s ... in
... x ...
]
]
*)
module Shared = struct
type 'a t = { client : 'a ; server : 'a }
let server = object
inherit [_] Ppx_core.Ast_traverse.map_with_context as super
method! expression ctx expr = match expr with
| [%expr [%client [%e? fragment_expr ]]] ->
[%expr [%client [%e super#expression `Client fragment_expr ]]]
| [%expr ~% [%e? injection_expr ]] ->
begin match ctx with
| `Shared -> injection_expr
| `Client -> expr
end
| _ -> super#expression ctx expr
method! structure c l =
let f s = match s.pstr_desc with
| Pstr_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "server"] ->
get_str_payload ~loc:s.pstr_loc txt payload
| Pstr_extension (({txt}, _), _)
when is_annotation txt ["client"] -> []
| _ -> [s]
in
super#structure c @@ flatmap f l
method! signature c l =
let f s = match s.psig_desc with
| Psig_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "server"] ->
get_sig_payload ~loc:s.psig_loc txt payload
| Psig_extension (({txt}, _), _)
when is_annotation txt ["client"] -> []
| _ -> [s]
in
super#signature c @@ flatmap f l
end
let client = object
inherit [_] Ppx_core.Ast_traverse.map_with_context as super
method! expression ctx expr = match expr with
| [%expr [%client [%e? fragment_expr ]]] ->
super#expression `Client fragment_expr
| [%expr ~% [%e? injection_expr ]] ->
begin match ctx with
| `Shared -> expr
| `Client -> injection_expr
end
| _ -> super#expression ctx expr
method! structure c l =
let f s = match s.pstr_desc with
| Pstr_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "client"] ->
get_str_payload ~loc:s.pstr_loc txt payload
| Pstr_extension (({txt}, _), _)
when is_annotation txt ["server"] -> []
| _ -> [s]
in
super#structure c @@ flatmap f l
method! signature c l =
let f s = match s.psig_desc with
| Psig_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "client"] ->
get_sig_payload ~loc:s.psig_loc txt payload
| Psig_extension (({txt}, _), _)
when is_annotation txt ["server"] -> []
| _ -> [s]
in
super#signature c @@ flatmap f l
end
let expression ~loc expr =
let server_expr = server#expression `Shared expr in
let client_expr = client#expression `Shared expr in
[%expr
Eliom_lib.create_shared_value
[%e server_expr]
[%client [%e client_expr]]
] [@metaloc loc]
let structure_item stri =
let server = server#structure_item `Shared stri in
let client = client#structure_item `Shared stri in
{ client ; server }
let signature_item sigi =
let server = server#signature_item `Shared sigi in
let client = client#signature_item `Shared sigi in
{ client ; server }
end
module Section = struct
let attribute side = match (side : Context.t) with
| Side Client -> Some "eliom.client"
| Side Server -> Some "eliom.server"
| Shared -> Some "eliom.shared"
| Base -> None
let structure ~side str =
let loc = str.pstr_loc in
match attribute side with
| Some txt -> Str.extension ~loc ({txt;loc}, PStr [str])
| None -> str
let signature ~side si =
let loc = si.psig_loc in
match attribute side with
| Some txt -> Sig.extension ~loc ({txt; loc}, PSig [si])
| None -> si
end
let _possible_annotations =
["shared.start"; "client.start" ;"server.start";
"shared"; "client"; "server"]
let expression_mapper = object (self)
inherit [ Eliom_base.side ] Ppx_core.Ast_traverse.map_with_context as super
method! expression context expr =
let loc = expr.pexp_loc in
let attrs = expr.pexp_attributes in
match expr with
(* [%shared ... ] *)
| {pexp_desc = Pexp_extension ({txt}, payload)}
when is_annotation txt ["shared"] ->
begin match context, payload with
| Loc Server, PStr [{pstr_desc = Pstr_eval (frag_exp,attrs')}] ->
let e = Shared.expression ~loc frag_exp in
self#expression context @@ exp_add_attrs (attrs@attrs') e
| Loc Server, _ ->
exp_error ~loc
"Wrong content for a shared fragment. It should be an expression."
| Loc Client, _ ->
exp_error ~loc
"Shared fragments are only in a server context, \
but it is used in a client context."
| Poly, _ ->
exp_error ~loc
"Shared fragments are only in a server context, \
but it is used in an ocaml context."
end
| _ -> super#expression context expr
end
let should_dup_str x = match x.pstr_desc with
(* | Pstr_module _ *)
(* | Pstr_recmodule _ *)
(* | Pstr_modtype _ *)
(* -> false *)
| _ -> false
let should_dup_sig x = match x.psig_desc with
(* | Psig_module _ *)
(* | Psig_recmodule _ *)
(* | Psig_modtype _ *)
(* -> false *)
| _ -> false
* Toplevel dispatch mechanisms
let dispatch
This three parameters are used to parametrized over str / sig .
annotate (* add %server annotation *)
self recursion on str / sig
exprrec (* call to expression_mapper *)
classify (* figure out if something is a module decl *)
shared_duplication (* duplicate shared expressions *)
(context : Context.t) item =
if classify item
then begin match context with
| Shared | Side _ as side ->
[ annotate ~side @@ selfrec side item ]
| Base ->
[ selfrec context item ]
end
else begin match context with
| Shared ->
let x : _ Shared.t = shared_duplication item in
[ annotate ~side:(Side Client) @@
selfrec (Side Client) x.client ;
annotate ~side:(Side Server) @@
selfrec (Side Server) x.server ;
]
| Side side ->
[ annotate ~side:context @@
exprrec (Eliom_base.Loc side) item ]
| Base ->
[ exprrec Poly item ]
end
let mapper = object (self)
inherit [ Context.t ] Ppx_core.Ast_traverse.map_with_context as super
(* This avoid issues with structure and signature triggering on payloads. *)
method! payload c = function
| PStr s -> PStr (super#structure c s)
| PSig s -> PSig (super#signature c s)
| PTyp t -> PTyp (super#core_type c t)
| PPat (p, None) -> PPat (super#pattern c p, None)
| PPat (p, Some e) -> PPat (super#pattern c p, Some (super#expression c e))
method! structure =
let dispatch_str =
dispatch
Section.structure
self#structure_item
expression_mapper#structure_item
should_dup_str
Shared.structure_item
in
let f c pstr =
let loc = pstr.pstr_loc in
match pstr.pstr_desc with
| Pstr_extension (({txt}, payload), _)
when is_annotation txt ["shared.start"; "client.start" ;"server.start"] ->
(Context.of_string txt, get_empty_str_payload ~loc txt payload)
| Pstr_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "client" ; "server"] ->
let item =
flatmap (dispatch_str (Context.of_string txt)) @@
get_str_payload ~loc txt payload
in
(c, item)
| _ ->
(c, dispatch_str c pstr)
in
fun ctx item -> fold_accum f item ctx
method! signature =
let dispatch_sig =
dispatch
Section.signature
self#signature_item
expression_mapper#signature_item
should_dup_sig
Shared.signature_item
in
let f c psig : (_ * signature) =
let loc = psig.psig_loc in
match psig.psig_desc with
| Psig_extension (({txt}, payload), _)
when is_annotation txt ["shared.start"; "client.start" ;"server.start"] ->
(Context.of_string txt, get_empty_sig_payload ~loc txt payload)
| Psig_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "client" ; "server"] ->
let item =
flatmap (dispatch_sig (Context.of_string txt)) @@
get_sig_payload ~loc txt payload
in
(c, item)
| _ ->
(c, dispatch_sig c psig)
in
fun ctx item -> fold_accum f item ctx
end
let mapper' _args =
let c = Context.Base in
{AM.default_mapper
with
structure = (fun _ -> mapper#structure c) ;
signature = (fun _ -> mapper#signature c) ;
}
| null | https://raw.githubusercontent.com/ocsigen/eliomlang/42e55856574e058caca191e50edcb0023900b664/lib/el_desugar.ml | ocaml | *
Replace shared expression by the equivalent pair.
[ [%share
let x = ... %s ... in
[%client ... %x ... ]
] ]
≡
[ let x = ... s ... in
[%client ... %x ... ]
,
[%client
let x = ... %s ... in
... x ...
]
]
[%shared ... ]
| Pstr_module _
| Pstr_recmodule _
| Pstr_modtype _
-> false
| Psig_module _
| Psig_recmodule _
| Psig_modtype _
-> false
add %server annotation
call to expression_mapper
figure out if something is a module decl
duplicate shared expressions
This avoid issues with structure and signature triggering on payloads. | open Parsetree
open Ast_helper
module AM = Ast_mapper
module AC = Ast_convenience
open El_utils
module Shared = struct
type 'a t = { client : 'a ; server : 'a }
let server = object
inherit [_] Ppx_core.Ast_traverse.map_with_context as super
method! expression ctx expr = match expr with
| [%expr [%client [%e? fragment_expr ]]] ->
[%expr [%client [%e super#expression `Client fragment_expr ]]]
| [%expr ~% [%e? injection_expr ]] ->
begin match ctx with
| `Shared -> injection_expr
| `Client -> expr
end
| _ -> super#expression ctx expr
method! structure c l =
let f s = match s.pstr_desc with
| Pstr_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "server"] ->
get_str_payload ~loc:s.pstr_loc txt payload
| Pstr_extension (({txt}, _), _)
when is_annotation txt ["client"] -> []
| _ -> [s]
in
super#structure c @@ flatmap f l
method! signature c l =
let f s = match s.psig_desc with
| Psig_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "server"] ->
get_sig_payload ~loc:s.psig_loc txt payload
| Psig_extension (({txt}, _), _)
when is_annotation txt ["client"] -> []
| _ -> [s]
in
super#signature c @@ flatmap f l
end
let client = object
inherit [_] Ppx_core.Ast_traverse.map_with_context as super
method! expression ctx expr = match expr with
| [%expr [%client [%e? fragment_expr ]]] ->
super#expression `Client fragment_expr
| [%expr ~% [%e? injection_expr ]] ->
begin match ctx with
| `Shared -> expr
| `Client -> injection_expr
end
| _ -> super#expression ctx expr
method! structure c l =
let f s = match s.pstr_desc with
| Pstr_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "client"] ->
get_str_payload ~loc:s.pstr_loc txt payload
| Pstr_extension (({txt}, _), _)
when is_annotation txt ["server"] -> []
| _ -> [s]
in
super#structure c @@ flatmap f l
method! signature c l =
let f s = match s.psig_desc with
| Psig_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "client"] ->
get_sig_payload ~loc:s.psig_loc txt payload
| Psig_extension (({txt}, _), _)
when is_annotation txt ["server"] -> []
| _ -> [s]
in
super#signature c @@ flatmap f l
end
let expression ~loc expr =
let server_expr = server#expression `Shared expr in
let client_expr = client#expression `Shared expr in
[%expr
Eliom_lib.create_shared_value
[%e server_expr]
[%client [%e client_expr]]
] [@metaloc loc]
let structure_item stri =
let server = server#structure_item `Shared stri in
let client = client#structure_item `Shared stri in
{ client ; server }
let signature_item sigi =
let server = server#signature_item `Shared sigi in
let client = client#signature_item `Shared sigi in
{ client ; server }
end
module Section = struct
let attribute side = match (side : Context.t) with
| Side Client -> Some "eliom.client"
| Side Server -> Some "eliom.server"
| Shared -> Some "eliom.shared"
| Base -> None
let structure ~side str =
let loc = str.pstr_loc in
match attribute side with
| Some txt -> Str.extension ~loc ({txt;loc}, PStr [str])
| None -> str
let signature ~side si =
let loc = si.psig_loc in
match attribute side with
| Some txt -> Sig.extension ~loc ({txt; loc}, PSig [si])
| None -> si
end
let _possible_annotations =
["shared.start"; "client.start" ;"server.start";
"shared"; "client"; "server"]
let expression_mapper = object (self)
inherit [ Eliom_base.side ] Ppx_core.Ast_traverse.map_with_context as super
method! expression context expr =
let loc = expr.pexp_loc in
let attrs = expr.pexp_attributes in
match expr with
| {pexp_desc = Pexp_extension ({txt}, payload)}
when is_annotation txt ["shared"] ->
begin match context, payload with
| Loc Server, PStr [{pstr_desc = Pstr_eval (frag_exp,attrs')}] ->
let e = Shared.expression ~loc frag_exp in
self#expression context @@ exp_add_attrs (attrs@attrs') e
| Loc Server, _ ->
exp_error ~loc
"Wrong content for a shared fragment. It should be an expression."
| Loc Client, _ ->
exp_error ~loc
"Shared fragments are only in a server context, \
but it is used in a client context."
| Poly, _ ->
exp_error ~loc
"Shared fragments are only in a server context, \
but it is used in an ocaml context."
end
| _ -> super#expression context expr
end
let should_dup_str x = match x.pstr_desc with
| _ -> false
let should_dup_sig x = match x.psig_desc with
| _ -> false
* Toplevel dispatch mechanisms
let dispatch
This three parameters are used to parametrized over str / sig .
self recursion on str / sig
(context : Context.t) item =
if classify item
then begin match context with
| Shared | Side _ as side ->
[ annotate ~side @@ selfrec side item ]
| Base ->
[ selfrec context item ]
end
else begin match context with
| Shared ->
let x : _ Shared.t = shared_duplication item in
[ annotate ~side:(Side Client) @@
selfrec (Side Client) x.client ;
annotate ~side:(Side Server) @@
selfrec (Side Server) x.server ;
]
| Side side ->
[ annotate ~side:context @@
exprrec (Eliom_base.Loc side) item ]
| Base ->
[ exprrec Poly item ]
end
let mapper = object (self)
inherit [ Context.t ] Ppx_core.Ast_traverse.map_with_context as super
method! payload c = function
| PStr s -> PStr (super#structure c s)
| PSig s -> PSig (super#signature c s)
| PTyp t -> PTyp (super#core_type c t)
| PPat (p, None) -> PPat (super#pattern c p, None)
| PPat (p, Some e) -> PPat (super#pattern c p, Some (super#expression c e))
method! structure =
let dispatch_str =
dispatch
Section.structure
self#structure_item
expression_mapper#structure_item
should_dup_str
Shared.structure_item
in
let f c pstr =
let loc = pstr.pstr_loc in
match pstr.pstr_desc with
| Pstr_extension (({txt}, payload), _)
when is_annotation txt ["shared.start"; "client.start" ;"server.start"] ->
(Context.of_string txt, get_empty_str_payload ~loc txt payload)
| Pstr_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "client" ; "server"] ->
let item =
flatmap (dispatch_str (Context.of_string txt)) @@
get_str_payload ~loc txt payload
in
(c, item)
| _ ->
(c, dispatch_str c pstr)
in
fun ctx item -> fold_accum f item ctx
method! signature =
let dispatch_sig =
dispatch
Section.signature
self#signature_item
expression_mapper#signature_item
should_dup_sig
Shared.signature_item
in
let f c psig : (_ * signature) =
let loc = psig.psig_loc in
match psig.psig_desc with
| Psig_extension (({txt}, payload), _)
when is_annotation txt ["shared.start"; "client.start" ;"server.start"] ->
(Context.of_string txt, get_empty_sig_payload ~loc txt payload)
| Psig_extension (({txt}, payload), _)
when is_annotation txt ["shared" ; "client" ; "server"] ->
let item =
flatmap (dispatch_sig (Context.of_string txt)) @@
get_sig_payload ~loc txt payload
in
(c, item)
| _ ->
(c, dispatch_sig c psig)
in
fun ctx item -> fold_accum f item ctx
end
let mapper' _args =
let c = Context.Base in
{AM.default_mapper
with
structure = (fun _ -> mapper#structure c) ;
signature = (fun _ -> mapper#signature c) ;
}
|
732756f6b28695cc12553d6a3e384d823742d2b94eb450e783dc2a8d20f8e044 | FreeProving/free-compiler | DefineDeclPass.hs | -- | This module contains passes for inserting data type, constructor and
-- type synonym declarations as well as function declarations into the
-- environment.
--
-- Subsequent passes can still modify entries added by this pass.
-- For example, which effects are used by which functions is determined
after this pass ( see " . EffectAnalysisPass " ) .
--
-- = Specification
--
-- = Preconditions
--
-- The argument and return types and type arguments of function declarations
-- are annotated.
--
-- = Translation
--
-- No changes are made to the declarations.
--
-- = Postconditions
--
-- There are entries for the given declarations in the environment.
--
-- = Error cases
--
-- * The user is informed if a different name is assigned to an entry.
module FreeC.Pass.DefineDeclPass ( defineTypeDeclsPass, defineFuncDeclsPass ) where
import Data.Maybe ( fromJust )
import FreeC.Environment.Entry
import FreeC.Environment.Renamer
import FreeC.IR.DependencyGraph
import qualified FreeC.IR.Syntax as IR
import FreeC.Monad.Converter
import FreeC.Pass.DependencyAnalysisPass
-- | Inserts all data type declarations and type synonyms in the given strongly
-- connected component into the environment.
defineTypeDeclsPass :: DependencyAwarePass IR.TypeDecl
defineTypeDeclsPass component = do
mapComponentM_ (mapM defineTypeDecl) component
return component
-- | Inserts all function declarations in the given strongly connected
-- component into the environment.
--
-- If any function in the component uses a partial function, all of the
-- functions in the component are marked as partial.
defineFuncDeclsPass :: DependencyAwarePass IR.FuncDecl
defineFuncDeclsPass component = do
mapComponentM_ (mapM defineFuncDecl) component
return component
-------------------------------------------------------------------------------
-- Type Declarations --
-------------------------------------------------------------------------------
-- | Inserts the given data type (including its constructors) or type synonym
-- declaration into the current environment.
defineTypeDecl :: IR.TypeDecl -> Converter ()
defineTypeDecl (IR.TypeSynDecl srcSpan declIdent typeArgs typeExpr) = do
_ <- renameAndAddEntry TypeSynEntry
{ entrySrcSpan = srcSpan
, entryArity = length typeArgs
, entryTypeArgs = map IR.typeVarDeclIdent typeArgs
, entryTypeSyn = typeExpr
, entryName = IR.declIdentName declIdent
, entryIdent = undefined -- filled by renamer
, entryAgdaIdent = undefined -- filled by renamer
}
return ()
defineTypeDecl (IR.DataDecl srcSpan declIdent typeArgs conDecls) = do
_ <- renameAndAddEntry DataEntry
{ entrySrcSpan = srcSpan
, entryArity = length typeArgs
, entryName = IR.declIdentName declIdent
, entryConsNames = map IR.conDeclQName conDecls
, entryIdent = undefined -- filled by renamer
, entryAgdaIdent = undefined -- filled by renamer
}
mapM_ defineConDecl conDecls
where
-- | The type produced by all constructors of the data type.
returnType :: IR.Type
returnType = IR.typeConApp srcSpan (IR.declIdentName declIdent)
(map IR.typeVarDeclToType typeArgs)
-- | Inserts the given data constructor declaration and its smart constructor
-- into the current environment.
defineConDecl :: IR.ConDecl -> Converter ()
defineConDecl (IR.ConDecl conSrcSpan conDeclIdent argTypes) = do
_ <- renameAndAddEntry ConEntry
{ entrySrcSpan = conSrcSpan
, entryArity = length argTypes
, entryTypeArgs = map IR.typeVarDeclIdent typeArgs
, entryArgTypes = argTypes
, entryReturnType = returnType
, entryName = IR.declIdentName conDeclIdent
, entryIdent = undefined -- filled by renamer
, entryAgdaIdent = undefined -- filled by renamer
, entrySmartIdent = undefined -- filled by renamer
, entryAgdaSmartIdent = undefined -- filled by renamer
}
return ()
-------------------------------------------------------------------------------
-- Function Declarations --
-------------------------------------------------------------------------------
-- | Inserts the given function declaration into the current environment.
--
The ' entryEffects ' may be updated by the " FreeC.Pass . EffectAnalysisPass " .
defineFuncDecl :: IR.FuncDecl -> Converter ()
defineFuncDecl funcDecl = do
_ <- renameAndAddEntry FuncEntry
{ entrySrcSpan = IR.funcDeclSrcSpan funcDecl
, entryArity = length (IR.funcDeclArgs funcDecl)
, entryTypeArgs = map IR.typeVarDeclIdent
(IR.funcDeclTypeArgs funcDecl)
, entryArgTypes = map (fromJust . IR.varPatType)
(IR.funcDeclArgs funcDecl)
, entryStrictArgs = map IR.varPatIsStrict
(IR.funcDeclArgs funcDecl)
, entryReturnType = fromJust (IR.funcDeclReturnType funcDecl)
, entryNeedsFreeArgs = True
, entryEncapsulatesEffects = False
, entryEffects = []
, entryName = IR.funcDeclQName funcDecl
, entryIdent = undefined -- filled by renamer
, entryAgdaIdent = undefined -- filled by renamer
}
return ()
| null | https://raw.githubusercontent.com/FreeProving/free-compiler/6931b9ca652a185a92dd824373f092823aea4ea9/src/lib/FreeC/Pass/DefineDeclPass.hs | haskell | | This module contains passes for inserting data type, constructor and
type synonym declarations as well as function declarations into the
environment.
Subsequent passes can still modify entries added by this pass.
For example, which effects are used by which functions is determined
= Specification
= Preconditions
The argument and return types and type arguments of function declarations
are annotated.
= Translation
No changes are made to the declarations.
= Postconditions
There are entries for the given declarations in the environment.
= Error cases
* The user is informed if a different name is assigned to an entry.
| Inserts all data type declarations and type synonyms in the given strongly
connected component into the environment.
| Inserts all function declarations in the given strongly connected
component into the environment.
If any function in the component uses a partial function, all of the
functions in the component are marked as partial.
-----------------------------------------------------------------------------
Type Declarations --
-----------------------------------------------------------------------------
| Inserts the given data type (including its constructors) or type synonym
declaration into the current environment.
filled by renamer
filled by renamer
filled by renamer
filled by renamer
| The type produced by all constructors of the data type.
| Inserts the given data constructor declaration and its smart constructor
into the current environment.
filled by renamer
filled by renamer
filled by renamer
filled by renamer
-----------------------------------------------------------------------------
Function Declarations --
-----------------------------------------------------------------------------
| Inserts the given function declaration into the current environment.
filled by renamer
filled by renamer | after this pass ( see " . EffectAnalysisPass " ) .
module FreeC.Pass.DefineDeclPass ( defineTypeDeclsPass, defineFuncDeclsPass ) where
import Data.Maybe ( fromJust )
import FreeC.Environment.Entry
import FreeC.Environment.Renamer
import FreeC.IR.DependencyGraph
import qualified FreeC.IR.Syntax as IR
import FreeC.Monad.Converter
import FreeC.Pass.DependencyAnalysisPass
defineTypeDeclsPass :: DependencyAwarePass IR.TypeDecl
defineTypeDeclsPass component = do
mapComponentM_ (mapM defineTypeDecl) component
return component
defineFuncDeclsPass :: DependencyAwarePass IR.FuncDecl
defineFuncDeclsPass component = do
mapComponentM_ (mapM defineFuncDecl) component
return component
defineTypeDecl :: IR.TypeDecl -> Converter ()
defineTypeDecl (IR.TypeSynDecl srcSpan declIdent typeArgs typeExpr) = do
_ <- renameAndAddEntry TypeSynEntry
{ entrySrcSpan = srcSpan
, entryArity = length typeArgs
, entryTypeArgs = map IR.typeVarDeclIdent typeArgs
, entryTypeSyn = typeExpr
, entryName = IR.declIdentName declIdent
}
return ()
defineTypeDecl (IR.DataDecl srcSpan declIdent typeArgs conDecls) = do
_ <- renameAndAddEntry DataEntry
{ entrySrcSpan = srcSpan
, entryArity = length typeArgs
, entryName = IR.declIdentName declIdent
, entryConsNames = map IR.conDeclQName conDecls
}
mapM_ defineConDecl conDecls
where
returnType :: IR.Type
returnType = IR.typeConApp srcSpan (IR.declIdentName declIdent)
(map IR.typeVarDeclToType typeArgs)
defineConDecl :: IR.ConDecl -> Converter ()
defineConDecl (IR.ConDecl conSrcSpan conDeclIdent argTypes) = do
_ <- renameAndAddEntry ConEntry
{ entrySrcSpan = conSrcSpan
, entryArity = length argTypes
, entryTypeArgs = map IR.typeVarDeclIdent typeArgs
, entryArgTypes = argTypes
, entryReturnType = returnType
, entryName = IR.declIdentName conDeclIdent
}
return ()
The ' entryEffects ' may be updated by the " FreeC.Pass . EffectAnalysisPass " .
defineFuncDecl :: IR.FuncDecl -> Converter ()
defineFuncDecl funcDecl = do
_ <- renameAndAddEntry FuncEntry
{ entrySrcSpan = IR.funcDeclSrcSpan funcDecl
, entryArity = length (IR.funcDeclArgs funcDecl)
, entryTypeArgs = map IR.typeVarDeclIdent
(IR.funcDeclTypeArgs funcDecl)
, entryArgTypes = map (fromJust . IR.varPatType)
(IR.funcDeclArgs funcDecl)
, entryStrictArgs = map IR.varPatIsStrict
(IR.funcDeclArgs funcDecl)
, entryReturnType = fromJust (IR.funcDeclReturnType funcDecl)
, entryNeedsFreeArgs = True
, entryEncapsulatesEffects = False
, entryEffects = []
, entryName = IR.funcDeclQName funcDecl
}
return ()
|
e63dbe758b91670d3af518cef6ab555484cb02529b4f4a22fd7022aea2fe588c | markus-git/co-feldspar | Monad.hs | # language GADTs #
# language TypeOperators #
# language DataKinds #
{-# language ScopedTypeVariables #-}
{-# language TypeFamilies #-}
# language FlexibleInstances #
{-# language FlexibleContexts #-}
# language MultiParamTypeClasses #
# language PolyKinds #
# language GeneralizedNewtypeDeriving #
# language BangPatterns #
module Feldspar.Verify.Monad where
import Control.Monad.RWS.Strict
import Control.Monad.Exception
import Control.Monad.Operational.Higher (Program)
import Data.List hiding (break)
import Data.Map (Map)
import qualified Data.Map.Strict as Map
import Data.Ord
import Data.Function
import Data.Typeable
import Data.Constraint (Constraint, Dict(..))
import Data.Maybe
import Data.Array
import Data.ALaCarte
import Feldspar.Verify.SMT hiding (not, ite, stack, concat)
import qualified Feldspar.Verify.SMT as SMT
import qualified Feldspar.Verify.Abstract as Abstract
import GHC.Stack
import Debug.Trace (traceShowM, traceShow)
import Prelude hiding (break)
--------------------------------------------------------------------------------
-- * Verification monad.
--------------------------------------------------------------------------------
-- Based on -edsl/blob/master/src/Language/Embedded/Verify.hs
--
-- Our verification algorithm looks a lot like symbolic execution. The
difference is that we use an SMT solver to do the symbolic reasoning .
--
We model the state of the program as the state of the SMT solver plus a
context , which is a map from variable name to SMT value . Symbolically
-- executing a statement modifies this state to become the state after executing
-- the statement. Typically, this modifies the context (when a variable has
changed ) or adds new axioms to the SMT solver .
--
The verification monad allows us to easily manipulate the SMT solver and the
context . It also provides three other features :
--
First , it supports branching on the value of a formula , executing one branch
-- if the formula is true and the other if the formula is false. The monad takes
care of merging the contexts from the two branches afterwards , as well as
-- making sure that any axiom we add inside a branch is only assumed
-- conditionally.
--
Second , it supports break statements in a rudimentary way . We can record when
-- we reach a break statement, and ask the monad for a symbolic expression that
-- tells us whether a given statement breaks. However, skipping past statements
-- after a break is the responsibility of the user of the monad.
--
-- Finally, we can emit warnings during verification, for example when we detect
-- a read of an uninitialised reference.
--
--------------------------------------------------------------------------------
-- | The Verify monad itself is a reader/writer/state monad with the following
-- components:
--
-- Read: list of formulas which are true in the current branch;
-- "chattiness level" (if > 0 then tracing messages are printed);
-- whether to try to prove anything or just evaluate the program.
--
-- Write: disjunction which is true if the program has called break;
-- list of warnings generated;
-- list of hints given;
-- list of names generated (must not appear in hints).
--
State : the context , a map from variables to SMT values .
--
type Verify = RWST ([SExpr], Int, Mode) ([SExpr], Warns, [HintBody], [String]) Context SMT
-- | The verification monad can prove (with and without warnings) or simply
-- execute a computation.
data Mode = Prove | ProveAndWarn | Execute deriving Eq
-- | Warnings are either local warnings for a branch or global.
data Warns = Warns {
warns_here :: [String]
, warns_all :: [String] }
instance Semigroup Warns
where
(<>) = mappend
instance Monoid Warns
where
mempty = Warns [] []
w1 `mappend` w2 = Warns
(warns_here w1 `mappend` warns_here w2)
(warns_all w1 `mappend` warns_all w2)
--------------------------------------------------------------------------------
-- | Run and prove a computation and record all warnings.
runVerify :: Verify a -> IO (a, [String])
runVerify m = runZ3 [] $ do
SMT.setOption ":produce-models" "false"
(x, (_, warns, _, _)) <- evalRWST m ([], 0, ProveAndWarn) Map.empty
return (x, warns_all warns)
-- | Run a computation without proving anything.
quickly :: Verify a -> Verify a
quickly = local (\(branch, chat, _) -> (branch, chat, Execute))
-- | Only run a computation if we are supposed to be proving.
proving :: a -> Verify a -> Verify a
proving def mx = do
(_, _, mode) <- ask
case mode of
Prove -> mx
ProveAndWarn -> mx
Execute -> return def
-- | Only run a computation if we are supposed to be warning.
warning :: a -> Verify a -> Verify a
warning x mx = do
(_, _, mode) <- ask
if (mode == ProveAndWarn) then mx else return x
--------------------------------------------------------------------------------
-- | Assume that a given formula is true.
assume :: String -> SExpr -> Verify ()
assume msg p = proving () $ do
branch <- branch
trace msg "Asserted" p
lift (assert (disj (p:map SMT.not branch)))
-- | Check if a given formula holds.
provable :: String -> SExpr -> Verify Bool
provable msg p = proving False $ do
branch <- branch
stack $ do
res <- lift $ do
mapM_ assert branch
assert (SMT.not p)
check
chat $
case res of
Sat -> stack $ do
trace msg "Failed to prove" p
lift $ setOption ":produce-models" "true"
lift $ check
context <- get
model <- showModel context
liftIO $ putStrLn (" (countermodel is " ++ model ++ ")")
Unsat -> trace msg "Proved" p
Unknown -> trace msg "Couldn't solve" p
return (res == Unsat)
-- | Run a computation but undo its effects afterwards.
stack :: Verify a -> Verify a
stack mx = do
state <- get
read <- ask
fmap fst $ lift $ SMT.stack $ evalRWST mx read state
-- | Branch on the value of a formula.
ite :: SExpr -> Verify a -> Verify b -> Verify (a, b)
ite p mx my = do
ctx <- get
read <- ask
let
withBranch p
| p == bool True = local id
| p == bool False = local (\(_, x, y) -> ([p], x, y))
| otherwise = local (\(xs, x, y) -> (p:xs, x, y))
(x, ctx1, (break1, warns1, hints1, decls1)) <-
lift $ runRWST (withBranch p mx) read ctx
(y, ctx2, (break2, warns2, hints2, decls2)) <-
lift $ runRWST (withBranch (SMT.not p) my) read ctx
mergeContext p ctx1 ctx2 >>= put
let
break
| null break1 && null break2 = []
| otherwise = [SMT.ite p (disj break1) (disj break2)]
tell (break, warns1 `mappend` warns2, hints1 ++ hints2, decls1 ++ decls2)
return (x, y)
--------------------------------------------------------------------------------
-- | Read the current branch.
branch :: Verify [SExpr]
branch = asks (\(branch, _, _) -> branch)
-- | Read the context.
peek :: forall a. (Typeable a, Ord a, Mergeable a, Show a, ShowModel a, Invariant a, Exprs a, HasCallStack) => String -> Verify a
peek name = do
ctx <- get
return (lookupContext name ctx)
-- | Write to the context.
poke :: (Typeable a, Ord a, Mergeable a, Show a, ShowModel a, Invariant a, Exprs a) => String -> a -> Verify ()
poke name val = modify (insertContext name val)
-- | Record that execution has broken here.
break :: Verify ()
break = do
branch <- branch
tell ([conj branch], mempty, [], [])
-- | Check if execution of a statement can break.
withBreaks :: Verify a -> Verify (a, SExpr)
withBreaks mx = do
(x, (exits, _, _, _)) <- listen mx
return (x, disj exits)
-- | Check if execution of a statement can break, discarding the statement's
-- result.
breaks :: Verify a -> Verify SExpr
breaks mx = fmap snd (withBreaks mx)
-- | Prevent a statement from breaking.
noBreak :: Verify a -> Verify a
noBreak = censor (\(_, warns, hints, decls) -> ([], warns, hints, decls))
-- | Add a warning to the output.
warn :: String -> Verify ()
warn msg = warning () $ tell ([], Warns [msg] [msg], [], [])
-- | Add a hint to the output.
hint :: TypedSExpr a => a -> Verify ()
hint exp = do
smt <- lift $ simplify (toSMT exp)
tell ([], mempty, [HintBody smt (smtType exp)], [])
| Add a hint for a ` SExpr ` to the output .
hintFormula :: SExpr -> Verify ()
hintFormula exp = do
smt <- lift $ simplify exp
tell ([], mempty, [HintBody smt tBool],[])
-- | Run a computation but ignoring its warnings.
noWarn :: Verify a -> Verify a
noWarn = local (\(x, y, mode) -> (x, y, f mode))
where
f ProveAndWarn = Prove
f x = x
-- | Run a computation but ignoring its local warnings.
swallowWarns :: Verify a -> Verify a
swallowWarns = censor (\(x, ws, y, z) -> (x, ws { warns_here = [] }, y, z))
-- | Run a computation and get its warnings.
getWarns :: Verify a -> Verify (a, [String])
getWarns mx = do
(x, (_, warns, _, _)) <- listen mx
return (x, warns_here warns)
--------------------------------------------------------------------------------
-- ** The API for verifying programs.
--------------------------------------------------------------------------------
-- | A typeclass for things which can be symbolically executed.
class Verifiable prog
where
-- Returns the transformed program (in which e.g. proved assertions
-- may have been removed), together with the result.
verifyWithResult :: prog a -> Verify (prog a, a)
-- | Symbolically execute a program, ignoring the result.
verify :: Verifiable prog => prog a -> Verify (prog a)
verify = fmap fst . verifyWithResult
--------------------------------------------------------------------------------
-- | A typeclass for instructions which can be symbolically executed.
class VerifyInstr instr exp pred
where
verifyInstr :: Verifiable prog => instr '(prog, Param2 exp pred) a -> a ->
Verify (instr '(prog, Param2 exp pred) a)
verifyInstr instr _ = return instr
instance (VerifyInstr f exp pred, VerifyInstr g exp pred) => VerifyInstr (f :+: g) exp pred
where
verifyInstr (Inl m) x = fmap Inl (verifyInstr m x)
verifyInstr (Inr m) x = fmap Inr (verifyInstr m x)
--------------------------------------------------------------------------------
-- ** Expressions and invariants.
--------------------------------------------------------------------------------
-- | A typeclass for expressions which can be evaluated under a context.
class Typeable exp => SMTEval1 exp
where
-- The result type of evaluating the expression.
data SMTExpr exp a
-- A predicate which must be true of the expression type.
type Pred exp :: * -> Constraint
Evaluate an expression to its SMT expression .
eval :: HasCallStack => exp a -> Verify (SMTExpr exp a)
Witness the fact that ( SMTEval1 exp , Pred exp a ) = > SMTEval exp a.
witnessPred :: Pred exp a => exp a -> Dict (SMTEval exp a)
--------------------------------------------------------------------------------
-- | A typeclass for expressions of a particular type.
class (SMTEval1 exp, TypedSExpr (SMTExpr exp a), Typeable a) => SMTEval exp a
where
Lift a typed constant into a SMT expression .
fromConstant :: a -> SMTExpr exp a
-- Witness the numerical type of an expression.
witnessNum :: Num a => exp a -> Dict (Num (SMTExpr exp a))
witnessNum = error "witnessNum"
-- Witness the ordered type of an expression.
witnessOrd :: Ord a => exp a -> Dict (SMTOrd (SMTExpr exp a))
witnessOrd = error "witnessOrd"
-- Produce an index for a type.
skolemIndex :: Ix a => SMTExpr exp a
skolemIndex = error "skolemIndex"
--------------------------------------------------------------------------------
| A typeclass for values with a representation as an SMT expression .
class Fresh a => TypedSExpr a
where
smtType :: a -> SExpr
toSMT :: a -> SExpr
fromSMT :: SExpr -> a
-- | Spawn a new expression, the string is a hint for making a pretty name.
freshSExpr :: forall a. TypedSExpr a => String -> Verify a
freshSExpr name = fmap fromSMT (freshVar name (smtType (undefined :: a)))
--------------------------------------------------------------------------------
-- | A typeclass for values that support uninitialised creation.
class Fresh a
where
Create an uninitialised value . The argument is a hint for making
-- pretty names.
fresh :: String -> Verify a
-- | Create a fresh variable and initialize it.
freshVar :: String -> SExpr -> Verify SExpr
freshVar name ty = do
n <- lift freshNum
let x = name ++ "." ++ show n
tell ([], mempty, [], [x])
lift $ declare x ty
--------------------------------------------------------------------------------
-- | A typeclass for values that can undergo predicate abstraction.
class (IsLiteral (Literal a), Fresh a) => Invariant a
where
data Literal a
-- Forget the value of a binding.
havoc :: String -> a -> Verify a
havoc name _ = fresh name
-- Return a list of candidate literals for a value.
literals :: String -> a -> [Literal a]
literals _ _ = []
warns1, warns2 :: Context -> String -> a -> a
warns1 _ _ x = x
warns2 _ _ x = x
warnLiterals :: String -> a -> [(Literal a, SExpr)]
warnLiterals _ _ = []
warnLiterals2 :: String -> a -> [Literal a]
warnLiterals2 _ _ = []
--------------------------------------------------------------------------------
class (Ord a, Typeable a, Show a) => IsLiteral a
where
Evaluate a literal . The two context arguments are the old and new
-- contexts (on entry to the loop and now).
smtLit :: Context -> Context -> a -> SExpr
smtLit = error "smtLit not defined"
-- What phase is the literal in? Literals from different phases cannot be
combined in one clause .
phase :: a -> Int
phase _ = 0
--------------------------------------------------------------------------------
data HintBody = HintBody {
hb_exp :: SExpr
, hb_type :: SExpr }
deriving (Eq, Ord)
instance Show HintBody
where
show = showSExpr . hb_exp
data Hint = Hint {
hint_ctx :: Context
, hint_body :: HintBody }
deriving (Eq, Ord)
instance Show Hint
where
show = show . hint_body
instance IsLiteral Hint
where
smtLit _ ctx hint = subst (hb_exp (hint_body hint))
where
subst x | Just y <- lookup x sub = y
subst (Atom xs) = Atom xs
subst (List xs) = List (map subst xs)
sub = equalise (hint_ctx hint) ctx
equalise ctx1 ctx2 = zip (exprs (fmap fst m)) (exprs (fmap snd m))
where
m = Map.intersectionWith (,) ctx1 ctx2
--------------------------------------------------------------------------------
| A typeclass for values that contain SMT expressions .
class Exprs a
where
List SMT expressions contained inside a value .
exprs :: a -> [SExpr]
instance Exprs SExpr
where
exprs x = [x]
instance Exprs Entry
where
exprs (Entry x) = exprs x
instance Exprs Context
where
exprs = concatMap exprs . Map.elems
----------------------------------------------------------------------
-- ** The context.
----------------------------------------------------------------------
data Name = forall a. Typeable a => Name String a
instance Eq Name
where
x == y = compare x y == EQ
instance Ord Name
where
compare = comparing (\(Name name x) -> (name, typeOf x))
instance Show Name
where
show (Name name x) = name
data Entry = forall a .
( Ord a
, Show a
, Typeable a
, Mergeable a
, ShowModel a
, Invariant a
, Exprs a
) =>
Entry a
instance Eq Entry
where
Entry x == Entry y = typeOf x == typeOf y && cast x == Just y
instance Ord Entry
where
compare (Entry x) (Entry y) =
compare (typeOf x) (typeOf y) `mappend` compare (Just x) (cast y)
instance Show Entry
where
showsPrec n (Entry x) = showsPrec n x
type Context = Map Name Entry
-- | Look up a value in the context.
lookupContext :: forall a . (Typeable a, HasCallStack) => String -> Context -> a
lookupContext name ctx =
case maybeLookupContext name ctx of
Nothing -> error $ "variable " ++ name ++ " not found in context" ++
"\nctx:" ++ unlines (map (show) (Map.toList ctx)) ++
"\ntype: " ++ show (typeOf (undefined :: a))
Just x -> x
-- | ...
maybeLookupContext :: forall a . Typeable a => String -> Context -> Maybe a
maybeLookupContext name ctx = do
Entry x <- Map.lookup (Name name (undefined :: a)) ctx
case cast x of
Nothing -> error "type mismatch in lookup"
Just x -> return x
-- | Add a value to the context or modify an existing binding.
insertContext :: forall a . (Typeable a, Ord a, Mergeable a, Show a, ShowModel a, Invariant a, Exprs a) => String -> a -> Context -> Context
insertContext name !x ctx = Map.insert (Name name (undefined :: a)) (Entry x) ctx
| Modified returns a subset of ctx2 that contains only the values
that have been changed from ctx1 .
modified :: Context -> Context -> Context
modified ctx1 ctx2 =
Map.mergeWithKey f (const Map.empty) (const Map.empty) ctx1 ctx2
where
f _ x y
| x == y = Nothing
| otherwise = Just y
--------------------------------------------------------------------------------
-- | A typeclass for values that support if-then-else.
class Mergeable a
where
merge :: SExpr -> a -> a -> a
mergeContext :: SExpr -> Context -> Context -> Verify Context
mergeContext cond ctx1 ctx2 =
-- If a variable is bound conditionally, put it in the result
-- context, but only define it conditionally.
sequence $ Map.mergeWithKey
(const combine)
(fmap (definedWhen cond))
(fmap (definedWhen (SMT.not cond)))
ctx1
ctx2
where
combine :: Entry -> Entry -> Maybe (Verify Entry)
combine x y = Just (return (merge cond x y))
definedWhen :: SExpr -> Entry -> Verify Entry
definedWhen cond (Entry x) = do
y <- fresh "unbound"
return (Entry (merge cond x y))
instance Mergeable Entry
where
merge cond (Entry x) (Entry y) = case cast y of
Just y -> Entry (merge cond x y)
Nothing -> error "incompatible types in merge"
instance Mergeable SExpr
where
merge cond t e
| t == e = t
| cond == bool True = t
| cond == bool False = e
| otherwise = SMT.ite cond t e
--------------------------------------------------------------------------------
| A typeclass for values that can be shown given a model from the SMT solver .
class ShowModel a
where
showModel :: a -> Verify String
instance ShowModel Context
where
showModel ctx = do
let (keys, values) = unzip (Map.toList ctx)
values' <- mapM showModel values
return $ intercalate ", "
$ zipWith (\(Name k _) v -> k ++ " = " ++ v)
keys
values'
instance ShowModel Entry
where
showModel (Entry x) = showModel x
instance ShowModel SExpr
where
showModel x = lift (getExpr x) >>= return . showValue
--------------------------------------------------------------------------------
-- *** A replacement for the SMTOrd class.
--------------------------------------------------------------------------------
class SMTOrd a
where
(.<.) :: a -> a -> SExpr
(.<=.) :: a -> a -> SExpr
(.>.) :: a -> a -> SExpr
(.>=.) :: a -> a -> SExpr
instance SMTEval exp a => Eq (SMTExpr exp a)
where
x == y = toSMT x == toSMT y
instance SMTEval exp a => Ord (SMTExpr exp a)
where
compare = comparing toSMT
instance SMTEval exp a => Show (SMTExpr exp a)
where
showsPrec n x = showsPrec n (toSMT x)
instance SMTEval exp a => Mergeable (SMTExpr exp a)
where
merge cond x y = fromSMT (merge cond (toSMT x) (toSMT y))
instance SMTEval exp a => ShowModel (SMTExpr exp a)
where
showModel x = showModel (toSMT x)
instance SMTEval exp a => Fresh (SMTExpr exp a)
where
fresh name = fmap fromSMT (freshVar name (smtType (undefined :: SMTExpr exp a)))
(.==.) :: TypedSExpr a => a -> a -> SExpr
x .==. y = toSMT x `eq` toSMT y
smtIte :: TypedSExpr a => SExpr -> a -> a -> a
smtIte cond x y = fromSMT (SMT.ite cond (toSMT x) (toSMT y))
--------------------------------------------------------------------------------
-- | Run a computation more chattily.
chattily :: Verify a -> Verify a
chattily = local (\(ctx, n, prove) -> (ctx, n+1, prove))
-- | Run a computation more quietly.
quietly :: Verify a -> Verify a
quietly = local (\(ctx, n, prove) -> (ctx, n-1, prove))
-- | Produce debug output.
chat :: Verify () -> Verify ()
chat mx = do
(_, chatty, _) <- ask
when (chatty > 0) mx
-- | Print a formula for debugging purposes.
trace :: String -> String -> SExpr -> Verify ()
trace msg kind p = chat $ do
branch <- branch >>= mapM (lift . simplify)
p <- lift $ simplify p
liftIO $ do
putStr (kind ++ " " ++ showSExpr p ++ " (" ++ msg ++ ")")
case branch of
[] -> putStrLn ""
[x] -> putStrLn (" assuming " ++ showSExpr x)
_ -> do
putStrLn " assuming:"
sequence_ [ putStrLn (" " ++ showSExpr x) | x <- branch ]
-- | Print the context for debugging purposes.
printContext :: String -> Verify ()
printContext msg = do
ctx <- get
liftIO $ do
putStrLn (msg ++ ":")
forM_ (Map.toList ctx) $ \(name, val) -> putStrLn (" " ++ show name ++ " -> " ++ show val)
putStrLn ""
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/markus-git/co-feldspar/bf598c803d41e03ed894bbcb490da855cce9250e/src/Feldspar/Verify/Monad.hs | haskell | # language ScopedTypeVariables #
# language TypeFamilies #
# language FlexibleContexts #
------------------------------------------------------------------------------
* Verification monad.
------------------------------------------------------------------------------
Based on -edsl/blob/master/src/Language/Embedded/Verify.hs
Our verification algorithm looks a lot like symbolic execution. The
executing a statement modifies this state to become the state after executing
the statement. Typically, this modifies the context (when a variable has
if the formula is true and the other if the formula is false. The monad takes
making sure that any axiom we add inside a branch is only assumed
conditionally.
we reach a break statement, and ask the monad for a symbolic expression that
tells us whether a given statement breaks. However, skipping past statements
after a break is the responsibility of the user of the monad.
Finally, we can emit warnings during verification, for example when we detect
a read of an uninitialised reference.
------------------------------------------------------------------------------
| The Verify monad itself is a reader/writer/state monad with the following
components:
Read: list of formulas which are true in the current branch;
"chattiness level" (if > 0 then tracing messages are printed);
whether to try to prove anything or just evaluate the program.
Write: disjunction which is true if the program has called break;
list of warnings generated;
list of hints given;
list of names generated (must not appear in hints).
| The verification monad can prove (with and without warnings) or simply
execute a computation.
| Warnings are either local warnings for a branch or global.
------------------------------------------------------------------------------
| Run and prove a computation and record all warnings.
| Run a computation without proving anything.
| Only run a computation if we are supposed to be proving.
| Only run a computation if we are supposed to be warning.
------------------------------------------------------------------------------
| Assume that a given formula is true.
| Check if a given formula holds.
| Run a computation but undo its effects afterwards.
| Branch on the value of a formula.
------------------------------------------------------------------------------
| Read the current branch.
| Read the context.
| Write to the context.
| Record that execution has broken here.
| Check if execution of a statement can break.
| Check if execution of a statement can break, discarding the statement's
result.
| Prevent a statement from breaking.
| Add a warning to the output.
| Add a hint to the output.
| Run a computation but ignoring its warnings.
| Run a computation but ignoring its local warnings.
| Run a computation and get its warnings.
------------------------------------------------------------------------------
** The API for verifying programs.
------------------------------------------------------------------------------
| A typeclass for things which can be symbolically executed.
Returns the transformed program (in which e.g. proved assertions
may have been removed), together with the result.
| Symbolically execute a program, ignoring the result.
------------------------------------------------------------------------------
| A typeclass for instructions which can be symbolically executed.
------------------------------------------------------------------------------
** Expressions and invariants.
------------------------------------------------------------------------------
| A typeclass for expressions which can be evaluated under a context.
The result type of evaluating the expression.
A predicate which must be true of the expression type.
------------------------------------------------------------------------------
| A typeclass for expressions of a particular type.
Witness the numerical type of an expression.
Witness the ordered type of an expression.
Produce an index for a type.
------------------------------------------------------------------------------
| Spawn a new expression, the string is a hint for making a pretty name.
------------------------------------------------------------------------------
| A typeclass for values that support uninitialised creation.
pretty names.
| Create a fresh variable and initialize it.
------------------------------------------------------------------------------
| A typeclass for values that can undergo predicate abstraction.
Forget the value of a binding.
Return a list of candidate literals for a value.
------------------------------------------------------------------------------
contexts (on entry to the loop and now).
What phase is the literal in? Literals from different phases cannot be
------------------------------------------------------------------------------
------------------------------------------------------------------------------
--------------------------------------------------------------------
** The context.
--------------------------------------------------------------------
| Look up a value in the context.
| ...
| Add a value to the context or modify an existing binding.
------------------------------------------------------------------------------
| A typeclass for values that support if-then-else.
If a variable is bound conditionally, put it in the result
context, but only define it conditionally.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
*** A replacement for the SMTOrd class.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Run a computation more chattily.
| Run a computation more quietly.
| Produce debug output.
| Print a formula for debugging purposes.
| Print the context for debugging purposes.
------------------------------------------------------------------------------ | # language GADTs #
# language TypeOperators #
# language DataKinds #
# language FlexibleInstances #
# language MultiParamTypeClasses #
# language PolyKinds #
# language GeneralizedNewtypeDeriving #
# language BangPatterns #
module Feldspar.Verify.Monad where
import Control.Monad.RWS.Strict
import Control.Monad.Exception
import Control.Monad.Operational.Higher (Program)
import Data.List hiding (break)
import Data.Map (Map)
import qualified Data.Map.Strict as Map
import Data.Ord
import Data.Function
import Data.Typeable
import Data.Constraint (Constraint, Dict(..))
import Data.Maybe
import Data.Array
import Data.ALaCarte
import Feldspar.Verify.SMT hiding (not, ite, stack, concat)
import qualified Feldspar.Verify.SMT as SMT
import qualified Feldspar.Verify.Abstract as Abstract
import GHC.Stack
import Debug.Trace (traceShowM, traceShow)
import Prelude hiding (break)
difference is that we use an SMT solver to do the symbolic reasoning .
We model the state of the program as the state of the SMT solver plus a
context , which is a map from variable name to SMT value . Symbolically
changed ) or adds new axioms to the SMT solver .
The verification monad allows us to easily manipulate the SMT solver and the
context . It also provides three other features :
First , it supports branching on the value of a formula , executing one branch
care of merging the contexts from the two branches afterwards , as well as
Second , it supports break statements in a rudimentary way . We can record when
State : the context , a map from variables to SMT values .
type Verify = RWST ([SExpr], Int, Mode) ([SExpr], Warns, [HintBody], [String]) Context SMT
data Mode = Prove | ProveAndWarn | Execute deriving Eq
data Warns = Warns {
warns_here :: [String]
, warns_all :: [String] }
instance Semigroup Warns
where
(<>) = mappend
instance Monoid Warns
where
mempty = Warns [] []
w1 `mappend` w2 = Warns
(warns_here w1 `mappend` warns_here w2)
(warns_all w1 `mappend` warns_all w2)
runVerify :: Verify a -> IO (a, [String])
runVerify m = runZ3 [] $ do
SMT.setOption ":produce-models" "false"
(x, (_, warns, _, _)) <- evalRWST m ([], 0, ProveAndWarn) Map.empty
return (x, warns_all warns)
quickly :: Verify a -> Verify a
quickly = local (\(branch, chat, _) -> (branch, chat, Execute))
proving :: a -> Verify a -> Verify a
proving def mx = do
(_, _, mode) <- ask
case mode of
Prove -> mx
ProveAndWarn -> mx
Execute -> return def
warning :: a -> Verify a -> Verify a
warning x mx = do
(_, _, mode) <- ask
if (mode == ProveAndWarn) then mx else return x
assume :: String -> SExpr -> Verify ()
assume msg p = proving () $ do
branch <- branch
trace msg "Asserted" p
lift (assert (disj (p:map SMT.not branch)))
provable :: String -> SExpr -> Verify Bool
provable msg p = proving False $ do
branch <- branch
stack $ do
res <- lift $ do
mapM_ assert branch
assert (SMT.not p)
check
chat $
case res of
Sat -> stack $ do
trace msg "Failed to prove" p
lift $ setOption ":produce-models" "true"
lift $ check
context <- get
model <- showModel context
liftIO $ putStrLn (" (countermodel is " ++ model ++ ")")
Unsat -> trace msg "Proved" p
Unknown -> trace msg "Couldn't solve" p
return (res == Unsat)
stack :: Verify a -> Verify a
stack mx = do
state <- get
read <- ask
fmap fst $ lift $ SMT.stack $ evalRWST mx read state
ite :: SExpr -> Verify a -> Verify b -> Verify (a, b)
ite p mx my = do
ctx <- get
read <- ask
let
withBranch p
| p == bool True = local id
| p == bool False = local (\(_, x, y) -> ([p], x, y))
| otherwise = local (\(xs, x, y) -> (p:xs, x, y))
(x, ctx1, (break1, warns1, hints1, decls1)) <-
lift $ runRWST (withBranch p mx) read ctx
(y, ctx2, (break2, warns2, hints2, decls2)) <-
lift $ runRWST (withBranch (SMT.not p) my) read ctx
mergeContext p ctx1 ctx2 >>= put
let
break
| null break1 && null break2 = []
| otherwise = [SMT.ite p (disj break1) (disj break2)]
tell (break, warns1 `mappend` warns2, hints1 ++ hints2, decls1 ++ decls2)
return (x, y)
branch :: Verify [SExpr]
branch = asks (\(branch, _, _) -> branch)
peek :: forall a. (Typeable a, Ord a, Mergeable a, Show a, ShowModel a, Invariant a, Exprs a, HasCallStack) => String -> Verify a
peek name = do
ctx <- get
return (lookupContext name ctx)
poke :: (Typeable a, Ord a, Mergeable a, Show a, ShowModel a, Invariant a, Exprs a) => String -> a -> Verify ()
poke name val = modify (insertContext name val)
break :: Verify ()
break = do
branch <- branch
tell ([conj branch], mempty, [], [])
withBreaks :: Verify a -> Verify (a, SExpr)
withBreaks mx = do
(x, (exits, _, _, _)) <- listen mx
return (x, disj exits)
breaks :: Verify a -> Verify SExpr
breaks mx = fmap snd (withBreaks mx)
noBreak :: Verify a -> Verify a
noBreak = censor (\(_, warns, hints, decls) -> ([], warns, hints, decls))
warn :: String -> Verify ()
warn msg = warning () $ tell ([], Warns [msg] [msg], [], [])
hint :: TypedSExpr a => a -> Verify ()
hint exp = do
smt <- lift $ simplify (toSMT exp)
tell ([], mempty, [HintBody smt (smtType exp)], [])
| Add a hint for a ` SExpr ` to the output .
hintFormula :: SExpr -> Verify ()
hintFormula exp = do
smt <- lift $ simplify exp
tell ([], mempty, [HintBody smt tBool],[])
noWarn :: Verify a -> Verify a
noWarn = local (\(x, y, mode) -> (x, y, f mode))
where
f ProveAndWarn = Prove
f x = x
swallowWarns :: Verify a -> Verify a
swallowWarns = censor (\(x, ws, y, z) -> (x, ws { warns_here = [] }, y, z))
getWarns :: Verify a -> Verify (a, [String])
getWarns mx = do
(x, (_, warns, _, _)) <- listen mx
return (x, warns_here warns)
class Verifiable prog
where
verifyWithResult :: prog a -> Verify (prog a, a)
verify :: Verifiable prog => prog a -> Verify (prog a)
verify = fmap fst . verifyWithResult
class VerifyInstr instr exp pred
where
verifyInstr :: Verifiable prog => instr '(prog, Param2 exp pred) a -> a ->
Verify (instr '(prog, Param2 exp pred) a)
verifyInstr instr _ = return instr
instance (VerifyInstr f exp pred, VerifyInstr g exp pred) => VerifyInstr (f :+: g) exp pred
where
verifyInstr (Inl m) x = fmap Inl (verifyInstr m x)
verifyInstr (Inr m) x = fmap Inr (verifyInstr m x)
class Typeable exp => SMTEval1 exp
where
data SMTExpr exp a
type Pred exp :: * -> Constraint
Evaluate an expression to its SMT expression .
eval :: HasCallStack => exp a -> Verify (SMTExpr exp a)
Witness the fact that ( SMTEval1 exp , Pred exp a ) = > SMTEval exp a.
witnessPred :: Pred exp a => exp a -> Dict (SMTEval exp a)
class (SMTEval1 exp, TypedSExpr (SMTExpr exp a), Typeable a) => SMTEval exp a
where
Lift a typed constant into a SMT expression .
fromConstant :: a -> SMTExpr exp a
witnessNum :: Num a => exp a -> Dict (Num (SMTExpr exp a))
witnessNum = error "witnessNum"
witnessOrd :: Ord a => exp a -> Dict (SMTOrd (SMTExpr exp a))
witnessOrd = error "witnessOrd"
skolemIndex :: Ix a => SMTExpr exp a
skolemIndex = error "skolemIndex"
| A typeclass for values with a representation as an SMT expression .
class Fresh a => TypedSExpr a
where
smtType :: a -> SExpr
toSMT :: a -> SExpr
fromSMT :: SExpr -> a
freshSExpr :: forall a. TypedSExpr a => String -> Verify a
freshSExpr name = fmap fromSMT (freshVar name (smtType (undefined :: a)))
class Fresh a
where
Create an uninitialised value . The argument is a hint for making
fresh :: String -> Verify a
freshVar :: String -> SExpr -> Verify SExpr
freshVar name ty = do
n <- lift freshNum
let x = name ++ "." ++ show n
tell ([], mempty, [], [x])
lift $ declare x ty
class (IsLiteral (Literal a), Fresh a) => Invariant a
where
data Literal a
havoc :: String -> a -> Verify a
havoc name _ = fresh name
literals :: String -> a -> [Literal a]
literals _ _ = []
warns1, warns2 :: Context -> String -> a -> a
warns1 _ _ x = x
warns2 _ _ x = x
warnLiterals :: String -> a -> [(Literal a, SExpr)]
warnLiterals _ _ = []
warnLiterals2 :: String -> a -> [Literal a]
warnLiterals2 _ _ = []
class (Ord a, Typeable a, Show a) => IsLiteral a
where
Evaluate a literal . The two context arguments are the old and new
smtLit :: Context -> Context -> a -> SExpr
smtLit = error "smtLit not defined"
combined in one clause .
phase :: a -> Int
phase _ = 0
data HintBody = HintBody {
hb_exp :: SExpr
, hb_type :: SExpr }
deriving (Eq, Ord)
instance Show HintBody
where
show = showSExpr . hb_exp
data Hint = Hint {
hint_ctx :: Context
, hint_body :: HintBody }
deriving (Eq, Ord)
instance Show Hint
where
show = show . hint_body
instance IsLiteral Hint
where
smtLit _ ctx hint = subst (hb_exp (hint_body hint))
where
subst x | Just y <- lookup x sub = y
subst (Atom xs) = Atom xs
subst (List xs) = List (map subst xs)
sub = equalise (hint_ctx hint) ctx
equalise ctx1 ctx2 = zip (exprs (fmap fst m)) (exprs (fmap snd m))
where
m = Map.intersectionWith (,) ctx1 ctx2
| A typeclass for values that contain SMT expressions .
class Exprs a
where
List SMT expressions contained inside a value .
exprs :: a -> [SExpr]
instance Exprs SExpr
where
exprs x = [x]
instance Exprs Entry
where
exprs (Entry x) = exprs x
instance Exprs Context
where
exprs = concatMap exprs . Map.elems
data Name = forall a. Typeable a => Name String a
instance Eq Name
where
x == y = compare x y == EQ
instance Ord Name
where
compare = comparing (\(Name name x) -> (name, typeOf x))
instance Show Name
where
show (Name name x) = name
data Entry = forall a .
( Ord a
, Show a
, Typeable a
, Mergeable a
, ShowModel a
, Invariant a
, Exprs a
) =>
Entry a
instance Eq Entry
where
Entry x == Entry y = typeOf x == typeOf y && cast x == Just y
instance Ord Entry
where
compare (Entry x) (Entry y) =
compare (typeOf x) (typeOf y) `mappend` compare (Just x) (cast y)
instance Show Entry
where
showsPrec n (Entry x) = showsPrec n x
type Context = Map Name Entry
lookupContext :: forall a . (Typeable a, HasCallStack) => String -> Context -> a
lookupContext name ctx =
case maybeLookupContext name ctx of
Nothing -> error $ "variable " ++ name ++ " not found in context" ++
"\nctx:" ++ unlines (map (show) (Map.toList ctx)) ++
"\ntype: " ++ show (typeOf (undefined :: a))
Just x -> x
maybeLookupContext :: forall a . Typeable a => String -> Context -> Maybe a
maybeLookupContext name ctx = do
Entry x <- Map.lookup (Name name (undefined :: a)) ctx
case cast x of
Nothing -> error "type mismatch in lookup"
Just x -> return x
insertContext :: forall a . (Typeable a, Ord a, Mergeable a, Show a, ShowModel a, Invariant a, Exprs a) => String -> a -> Context -> Context
insertContext name !x ctx = Map.insert (Name name (undefined :: a)) (Entry x) ctx
| Modified returns a subset of ctx2 that contains only the values
that have been changed from ctx1 .
modified :: Context -> Context -> Context
modified ctx1 ctx2 =
Map.mergeWithKey f (const Map.empty) (const Map.empty) ctx1 ctx2
where
f _ x y
| x == y = Nothing
| otherwise = Just y
class Mergeable a
where
merge :: SExpr -> a -> a -> a
mergeContext :: SExpr -> Context -> Context -> Verify Context
mergeContext cond ctx1 ctx2 =
sequence $ Map.mergeWithKey
(const combine)
(fmap (definedWhen cond))
(fmap (definedWhen (SMT.not cond)))
ctx1
ctx2
where
combine :: Entry -> Entry -> Maybe (Verify Entry)
combine x y = Just (return (merge cond x y))
definedWhen :: SExpr -> Entry -> Verify Entry
definedWhen cond (Entry x) = do
y <- fresh "unbound"
return (Entry (merge cond x y))
instance Mergeable Entry
where
merge cond (Entry x) (Entry y) = case cast y of
Just y -> Entry (merge cond x y)
Nothing -> error "incompatible types in merge"
instance Mergeable SExpr
where
merge cond t e
| t == e = t
| cond == bool True = t
| cond == bool False = e
| otherwise = SMT.ite cond t e
| A typeclass for values that can be shown given a model from the SMT solver .
class ShowModel a
where
showModel :: a -> Verify String
instance ShowModel Context
where
showModel ctx = do
let (keys, values) = unzip (Map.toList ctx)
values' <- mapM showModel values
return $ intercalate ", "
$ zipWith (\(Name k _) v -> k ++ " = " ++ v)
keys
values'
instance ShowModel Entry
where
showModel (Entry x) = showModel x
instance ShowModel SExpr
where
showModel x = lift (getExpr x) >>= return . showValue
class SMTOrd a
where
(.<.) :: a -> a -> SExpr
(.<=.) :: a -> a -> SExpr
(.>.) :: a -> a -> SExpr
(.>=.) :: a -> a -> SExpr
instance SMTEval exp a => Eq (SMTExpr exp a)
where
x == y = toSMT x == toSMT y
instance SMTEval exp a => Ord (SMTExpr exp a)
where
compare = comparing toSMT
instance SMTEval exp a => Show (SMTExpr exp a)
where
showsPrec n x = showsPrec n (toSMT x)
instance SMTEval exp a => Mergeable (SMTExpr exp a)
where
merge cond x y = fromSMT (merge cond (toSMT x) (toSMT y))
instance SMTEval exp a => ShowModel (SMTExpr exp a)
where
showModel x = showModel (toSMT x)
instance SMTEval exp a => Fresh (SMTExpr exp a)
where
fresh name = fmap fromSMT (freshVar name (smtType (undefined :: SMTExpr exp a)))
(.==.) :: TypedSExpr a => a -> a -> SExpr
x .==. y = toSMT x `eq` toSMT y
smtIte :: TypedSExpr a => SExpr -> a -> a -> a
smtIte cond x y = fromSMT (SMT.ite cond (toSMT x) (toSMT y))
chattily :: Verify a -> Verify a
chattily = local (\(ctx, n, prove) -> (ctx, n+1, prove))
quietly :: Verify a -> Verify a
quietly = local (\(ctx, n, prove) -> (ctx, n-1, prove))
chat :: Verify () -> Verify ()
chat mx = do
(_, chatty, _) <- ask
when (chatty > 0) mx
trace :: String -> String -> SExpr -> Verify ()
trace msg kind p = chat $ do
branch <- branch >>= mapM (lift . simplify)
p <- lift $ simplify p
liftIO $ do
putStr (kind ++ " " ++ showSExpr p ++ " (" ++ msg ++ ")")
case branch of
[] -> putStrLn ""
[x] -> putStrLn (" assuming " ++ showSExpr x)
_ -> do
putStrLn " assuming:"
sequence_ [ putStrLn (" " ++ showSExpr x) | x <- branch ]
printContext :: String -> Verify ()
printContext msg = do
ctx <- get
liftIO $ do
putStrLn (msg ++ ":")
forM_ (Map.toList ctx) $ \(name, val) -> putStrLn (" " ++ show name ++ " -> " ++ show val)
putStrLn ""
|
778a6cebfa623e9ee83567561872de0b20027997749352693b264d3375dafc6b | sonyxperiadev/dataflow | RendererSpec.hs | module DataFlow.Graphviz.RendererSpec where
import Test.Hspec
import DataFlow.Graphviz
import DataFlow.Graphviz.Renderer
spec :: Spec
spec =
describe "renderGraphviz" $ do
it "renders digraph id" $
renderGraphviz (Digraph "g" []) `shouldBe` "digraph g {\n}\n"
it "renders digraph with a node stmt" $
renderGraphviz (Digraph "g" [
NodeStmt "n" []
]) `shouldBe` "digraph g {\n n\n}\n"
it "renders digraph with an edge stmt" $
renderGraphviz (Digraph "g" [
EdgeStmt (EdgeExpr
(IDOperand $ NodeID "n1" Nothing)
Arrow
(IDOperand $ NodeID "n2" Nothing))
[]
]) `shouldBe` "digraph g {\n n1 -> n2;\n}\n"
it "renders digraph with an attr stmt" $
renderGraphviz (Digraph "g" [
AttrStmt Graph []
]) `shouldBe` "digraph g {\n graph []\n}\n"
it "renders digraph with an equals stmt" $
renderGraphviz (Digraph "g" [
EqualsStmt "i1" "i2"
]) `shouldBe` "digraph g {\n i1 = i2;\n}\n"
it "renders digraph with a subgraph stmt" $
renderGraphviz (Digraph "g" [
SubgraphStmt $ Subgraph "sg" []
]) `shouldBe` "digraph g {\n subgraph sg {}\n}\n"
it "converts newlines to <br/>" $
renderGraphviz (Digraph "g" [
AttrStmt Graph [
Attr "hello" "foo\nbar"
]
]) `shouldBe` "digraph g {\n graph [\n hello = foo<br/>bar;\n ]\n}\n"
| null | https://raw.githubusercontent.com/sonyxperiadev/dataflow/8bef5bd6bf96a918197e66ad9d675ff8cd2a4e33/test/DataFlow/Graphviz/RendererSpec.hs | haskell | module DataFlow.Graphviz.RendererSpec where
import Test.Hspec
import DataFlow.Graphviz
import DataFlow.Graphviz.Renderer
spec :: Spec
spec =
describe "renderGraphviz" $ do
it "renders digraph id" $
renderGraphviz (Digraph "g" []) `shouldBe` "digraph g {\n}\n"
it "renders digraph with a node stmt" $
renderGraphviz (Digraph "g" [
NodeStmt "n" []
]) `shouldBe` "digraph g {\n n\n}\n"
it "renders digraph with an edge stmt" $
renderGraphviz (Digraph "g" [
EdgeStmt (EdgeExpr
(IDOperand $ NodeID "n1" Nothing)
Arrow
(IDOperand $ NodeID "n2" Nothing))
[]
]) `shouldBe` "digraph g {\n n1 -> n2;\n}\n"
it "renders digraph with an attr stmt" $
renderGraphviz (Digraph "g" [
AttrStmt Graph []
]) `shouldBe` "digraph g {\n graph []\n}\n"
it "renders digraph with an equals stmt" $
renderGraphviz (Digraph "g" [
EqualsStmt "i1" "i2"
]) `shouldBe` "digraph g {\n i1 = i2;\n}\n"
it "renders digraph with a subgraph stmt" $
renderGraphviz (Digraph "g" [
SubgraphStmt $ Subgraph "sg" []
]) `shouldBe` "digraph g {\n subgraph sg {}\n}\n"
it "converts newlines to <br/>" $
renderGraphviz (Digraph "g" [
AttrStmt Graph [
Attr "hello" "foo\nbar"
]
]) `shouldBe` "digraph g {\n graph [\n hello = foo<br/>bar;\n ]\n}\n"
| |
496ea4df42ddcc28e187145932606041551b62423db0a7cf3b5f4e840d1bb345 | pjotrp/guix | ebook.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages ebook)
#:use-module ((guix licenses) #:select (gpl3 lgpl2.1+))
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages)
#:use-module (guix build-system python)
#:use-module (gnu packages)
#:use-module (gnu packages databases)
#:use-module (gnu packages fontutils)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages glib)
#:use-module (gnu packages icu4c)
#:use-module (gnu packages image)
#:use-module (gnu packages imagemagick)
#:use-module (gnu packages libusb)
#:use-module (gnu packages pdf)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages qt)
#:use-module (gnu packages tls)
#:use-module (gnu packages xorg))
(define-public chmlib
(package
(name "chmlib")
(version "0.40")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"18zzb4x3z0d7fjh1x5439bs62dmgsi4c1pg3qyr7h5gp1i5xcj9l"))
(patches (list (search-patch "chmlib-inttypes.patch")))))
(build-system gnu-build-system)
(home-page "/")
(synopsis "Library for CHM files")
(description "CHMLIB is a library for dealing with ITSS/CHM format files.")
(license lgpl2.1+)))
(define-public calibre
(package
(name "calibre")
(version "2.41.0")
(source
(origin
(method url-fetch)
(uri (string-append "-ebook.com/"
version "/calibre-"
version ".tar.xz"))
(sha256
(base32
"069fkcsx7kaazs7f095nkz4jw9jrm0k9zq16ayx41lxjbd1r97ik"))
;; Remove non-free or doubtful code, see
;; -devel/2015-02/msg00478.html
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively "src/unrar")
(delete-file "src/odf/thumbnail.py")))
(patches (list (search-patch "calibre-drop-unrar.patch")
(search-patch "calibre-no-updates-dialog.patch")))))
(build-system python-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)
("qt" ,qt) ; for qmake
;; xdg-utils is supposed to be used for desktop integration, but it
;; also creates lots of messages
;; mkdir: cannot create directory '/homeless-shelter': Permission denied
("xdg-utils" ,xdg-utils)))
;; FIXME: The following are missing inputs according to the documentation,
;; but the package can apparently be used without them,
;; They may need to be added if a deficiency is detected.
BeautifulSoup > = 3.0.5
dnspython > = 1.6.0
poppler > = 0.20.2
libwmf > = 0.2.8
psutil > = 0.6.1
python - pygments > = 2.0.1 ; used for ebook editing
(inputs
`(("chmlib" ,chmlib)
("fontconfig" ,fontconfig)
("glib" ,glib)
("icu4c" ,icu4c)
("imagemagick" ,imagemagick)
("libmtp" ,libmtp)
("libpng" ,libpng)
("libusb" ,libusb)
("libxrender" ,libxrender)
("openssl" ,openssl)
("podofo" ,podofo)
("python" ,python-2)
("python2-apsw" ,python2-apsw)
("python2-cssselect" ,python2-cssselect)
("python2-cssutils" ,python2-cssutils)
("python2-dateutil" ,python2-dateutil)
("python2-dbus" ,python2-dbus)
("python2-lxml" ,python2-lxml)
("python2-mechanize" ,python2-mechanize)
("python2-netifaces" ,python2-netifaces)
("python2-pillow" ,python2-pillow)
("python2-pyqt" ,python2-pyqt)
("python2-sip" ,python2-sip)
("qt" ,qt)
("sqlite" ,sqlite)))
(arguments
`(#:python ,python-2
#:test-target "check"
#:tests? #f ; FIXME: enable once flake8 is packaged
#:phases
(alist-cons-before
'build 'configure
(lambda* (#:key inputs #:allow-other-keys)
(let ((podofo (assoc-ref inputs "podofo"))
(pyqt (assoc-ref inputs "python2-pyqt")))
(substitute* "setup/build_environment.py"
(("sys.prefix") (string-append "'" pyqt "'")))
(setenv "PODOFO_INC_DIR" (string-append podofo "/include/podofo"))
(setenv "PODOFO_LIB_DIR" (string-append podofo "/lib"))))
%standard-phases)))
(home-page "-ebook.com/")
(synopsis "E-book library management software")
(description "Calibre is an ebook library manager. It can view, convert
and catalog ebooks in most of the major ebook formats. It can also talk
to many ebook reader devices. It can go out to the Internet and fetch
metadata for books. It can download newspapers and convert them into
ebooks for convenient reading.")
(license gpl3))) ; some files are under various other licenses, see COPYRIGHT
| null | https://raw.githubusercontent.com/pjotrp/guix/96250294012c2f1520b67f12ea80bfd6b98075a2/gnu/packages/ebook.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Remove non-free or doubtful code, see
-devel/2015-02/msg00478.html
for qmake
xdg-utils is supposed to be used for desktop integration, but it
also creates lots of messages
mkdir: cannot create directory '/homeless-shelter': Permission denied
FIXME: The following are missing inputs according to the documentation,
but the package can apparently be used without them,
They may need to be added if a deficiency is detected.
used for ebook editing
FIXME: enable once flake8 is packaged
some files are under various other licenses, see COPYRIGHT | Copyright © 2015 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages ebook)
#:use-module ((guix licenses) #:select (gpl3 lgpl2.1+))
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages)
#:use-module (guix build-system python)
#:use-module (gnu packages)
#:use-module (gnu packages databases)
#:use-module (gnu packages fontutils)
#:use-module (gnu packages freedesktop)
#:use-module (gnu packages glib)
#:use-module (gnu packages icu4c)
#:use-module (gnu packages image)
#:use-module (gnu packages imagemagick)
#:use-module (gnu packages libusb)
#:use-module (gnu packages pdf)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages qt)
#:use-module (gnu packages tls)
#:use-module (gnu packages xorg))
(define-public chmlib
(package
(name "chmlib")
(version "0.40")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"18zzb4x3z0d7fjh1x5439bs62dmgsi4c1pg3qyr7h5gp1i5xcj9l"))
(patches (list (search-patch "chmlib-inttypes.patch")))))
(build-system gnu-build-system)
(home-page "/")
(synopsis "Library for CHM files")
(description "CHMLIB is a library for dealing with ITSS/CHM format files.")
(license lgpl2.1+)))
(define-public calibre
(package
(name "calibre")
(version "2.41.0")
(source
(origin
(method url-fetch)
(uri (string-append "-ebook.com/"
version "/calibre-"
version ".tar.xz"))
(sha256
(base32
"069fkcsx7kaazs7f095nkz4jw9jrm0k9zq16ayx41lxjbd1r97ik"))
(modules '((guix build utils)))
(snippet
'(begin
(delete-file-recursively "src/unrar")
(delete-file "src/odf/thumbnail.py")))
(patches (list (search-patch "calibre-drop-unrar.patch")
(search-patch "calibre-no-updates-dialog.patch")))))
(build-system python-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)
("xdg-utils" ,xdg-utils)))
BeautifulSoup > = 3.0.5
dnspython > = 1.6.0
poppler > = 0.20.2
libwmf > = 0.2.8
psutil > = 0.6.1
(inputs
`(("chmlib" ,chmlib)
("fontconfig" ,fontconfig)
("glib" ,glib)
("icu4c" ,icu4c)
("imagemagick" ,imagemagick)
("libmtp" ,libmtp)
("libpng" ,libpng)
("libusb" ,libusb)
("libxrender" ,libxrender)
("openssl" ,openssl)
("podofo" ,podofo)
("python" ,python-2)
("python2-apsw" ,python2-apsw)
("python2-cssselect" ,python2-cssselect)
("python2-cssutils" ,python2-cssutils)
("python2-dateutil" ,python2-dateutil)
("python2-dbus" ,python2-dbus)
("python2-lxml" ,python2-lxml)
("python2-mechanize" ,python2-mechanize)
("python2-netifaces" ,python2-netifaces)
("python2-pillow" ,python2-pillow)
("python2-pyqt" ,python2-pyqt)
("python2-sip" ,python2-sip)
("qt" ,qt)
("sqlite" ,sqlite)))
(arguments
`(#:python ,python-2
#:test-target "check"
#:phases
(alist-cons-before
'build 'configure
(lambda* (#:key inputs #:allow-other-keys)
(let ((podofo (assoc-ref inputs "podofo"))
(pyqt (assoc-ref inputs "python2-pyqt")))
(substitute* "setup/build_environment.py"
(("sys.prefix") (string-append "'" pyqt "'")))
(setenv "PODOFO_INC_DIR" (string-append podofo "/include/podofo"))
(setenv "PODOFO_LIB_DIR" (string-append podofo "/lib"))))
%standard-phases)))
(home-page "-ebook.com/")
(synopsis "E-book library management software")
(description "Calibre is an ebook library manager. It can view, convert
and catalog ebooks in most of the major ebook formats. It can also talk
to many ebook reader devices. It can go out to the Internet and fetch
metadata for books. It can download newspapers and convert them into
ebooks for convenient reading.")
|
dcbc2e8af52718e09b03fbb23366bddc029afa5d09fda727c03ecbf73cf7db55 | project-oak/hafnium-verification | cMethod_trans.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
* Methods for creating a procdesc from a method or function declaration and for resolving a method
call and finding the right callee
call and finding the right callee *)
module L = Logging
* When the methoc call is MCStatic , means that it is a class method . When it is MCVirtual , it
means that it is an instance method and that the method to be called will be determined at
runtime . If it is MCNoVirtual it means that it is an instance method but that the method to be
called will be determined at compile time
means that it is an instance method and that the method to be called will be determined at
runtime. If it is MCNoVirtual it means that it is an instance method but that the method to be
called will be determined at compile time *)
type method_call_type = MCVirtual | MCNoVirtual | MCStatic [@@deriving compare]
let equal_method_call_type = [%compare.equal: method_call_type]
let method_signature_of_pointer tenv pointer =
try
match CAst_utils.get_decl pointer with
| Some meth_decl ->
let procname = CType_decl.CProcname.from_decl ~tenv meth_decl in
let ms = CType_decl.method_signature_of_decl tenv meth_decl procname in
Some ms
| None ->
None
with CFrontend_errors.Invalid_declaration -> None
let get_method_name_from_clang tenv ms_opt =
match ms_opt with
| Some ms -> (
match CAst_utils.get_decl_opt ms.CMethodSignature.pointer_to_parent with
| Some decl -> (
ignore (CType_decl.add_types_from_decl_to_tenv tenv decl) ;
match ObjcCategory_decl.get_base_class_name_from_category decl with
| Some class_typename ->
let procname = ms.CMethodSignature.name in
let new_procname = Procname.replace_class procname class_typename in
Some new_procname
| None ->
Some ms.CMethodSignature.name )
| None ->
Some ms.CMethodSignature.name )
| None ->
None
let get_superclass_curr_class_objc context =
let open Clang_ast_t in
let decl_ref =
match CContext.get_curr_class context with
| CContext.ContextClsDeclPtr ptr -> (
match CAst_utils.get_decl ptr with
| Some decl ->
CAst_utils.get_superclass_curr_class_objc_from_decl decl
| None ->
Logging.die InternalError
"Expected that the current class ptr in the context is a valid pointer to class decl, \
but didn't find declaration, ptr is %d "
ptr )
| CContext.ContextNoCls ->
Logging.die InternalError
"This should only be called in the context of a class, but got CContext.ContextNoCls"
in
match decl_ref |> Option.value_map ~f:(fun dr -> dr.dr_name) ~default:None with
| Some name ->
Typ.Name.Objc.from_qual_name (CAst_utils.get_qualified_name name)
| None ->
Logging.die InternalError "Expected to always find a superclass, but found none"
(* Gets the class name from a method signature found by clang, if search is successful *)
let get_class_name_method_call_from_clang tenv obj_c_message_expr_info =
match obj_c_message_expr_info.Clang_ast_t.omei_decl_pointer with
| Some pointer -> (
match method_signature_of_pointer tenv pointer with
| Some ms -> (
match ms.CMethodSignature.name with
| Procname.ObjC_Cpp objc_cpp ->
Some (Procname.ObjC_Cpp.get_class_type_name objc_cpp)
| _ ->
None )
| None ->
None )
| None ->
None
(* Get class name from a method call accorsing to the info given by the receiver kind *)
let get_class_name_method_call_from_receiver_kind context obj_c_message_expr_info act_params =
match obj_c_message_expr_info.Clang_ast_t.omei_receiver_kind with
| `Class qt ->
let sil_type = CType_decl.qual_type_to_sil_type context.CContext.tenv qt in
CType.objc_classname_of_type sil_type
| `Instance -> (
match act_params with
| (_, {Typ.desc= Tptr (t, _)}) :: _ | (_, t) :: _ ->
CType.objc_classname_of_type t
| _ ->
assert false )
| `SuperInstance ->
get_superclass_curr_class_objc context
| `SuperClass ->
get_superclass_curr_class_objc context
let get_objc_method_data obj_c_message_expr_info =
let selector = obj_c_message_expr_info.Clang_ast_t.omei_selector in
let pointer = obj_c_message_expr_info.Clang_ast_t.omei_decl_pointer in
match obj_c_message_expr_info.Clang_ast_t.omei_receiver_kind with
| `Instance ->
(selector, pointer, MCVirtual)
| `SuperInstance ->
(selector, pointer, MCNoVirtual)
| `Class _ | `SuperClass ->
(selector, pointer, MCStatic)
let should_create_procdesc cfg procname ~defined ~set_objc_accessor_attr =
match Procname.Hash.find cfg procname with
| previous_procdesc ->
let is_defined_previous = Procdesc.is_defined previous_procdesc in
if (defined || set_objc_accessor_attr) && not is_defined_previous then (
Procname.Hash.remove cfg procname ; true )
else false
| exception Caml.Not_found ->
true
(** Returns a list of the indices of expressions in [args] which point to const-typed values. Each
index is offset by [shift]. *)
let get_const_params_indices ~shift params =
let i = ref shift in
let rec aux result = function
| [] ->
List.rev result
| ({is_pointer_to_const} : CMethodSignature.param_type) :: tl ->
incr i ;
if is_pointer_to_const then aux ((!i - 1) :: result) tl else aux result tl
in
aux [] params
let get_objc_property_accessor tenv ms =
let open Clang_ast_t in
match CAst_utils.get_decl_opt ms.CMethodSignature.pointer_to_property_opt with
| Some (ObjCPropertyDecl (_, _, obj_c_property_decl_info)) -> (
let ivar_decl_ref = obj_c_property_decl_info.Clang_ast_t.opdi_ivar_decl in
match CAst_utils.get_decl_opt_with_decl_ref_opt ivar_decl_ref with
| Some (ObjCIvarDecl (_, name_decl_info, _, _, _)) -> (
let class_tname =
Typ.Name.Objc.from_qual_name
(QualifiedCppName.from_field_qualified_name
(QualifiedCppName.of_rev_list name_decl_info.ni_qual_name))
in
let field_name = CGeneral_utils.mk_class_field_name class_tname name_decl_info.ni_name in
match Tenv.lookup tenv class_tname with
| Some {fields} -> (
let field_opt =
List.find ~f:(fun (name, _, _) -> Fieldname.equal name field_name) fields
in
match field_opt with
| Some field when CMethodSignature.is_getter ms ->
Some (ProcAttributes.Objc_getter field)
| Some field when CMethodSignature.is_setter ms ->
Some (ProcAttributes.Objc_setter field)
| _ ->
None )
| None ->
None )
| _ ->
None )
| _ ->
None
let find_sentinel_attribute attrs =
List.find_map attrs ~f:(function
| `SentinelAttr (_attr_info, {Clang_ast_t.sai_sentinel= sentinel; sai_null_pos= null_pos}) ->
Some (sentinel, null_pos)
| _ ->
None )
(** Creates a procedure description. *)
let create_local_procdesc ?(set_objc_accessor_attr = false) trans_unit_ctx cfg tenv ms fbody
captured =
let defined = not (List.is_empty fbody) in
let proc_name = ms.CMethodSignature.name in
let clang_method_kind = ms.CMethodSignature.method_kind in
let is_cpp_nothrow = ms.CMethodSignature.is_cpp_nothrow in
let access =
match ms.CMethodSignature.access with
| `None ->
PredSymb.Default
| `Private ->
PredSymb.Private
| `Protected ->
PredSymb.Protected
| `Public ->
PredSymb.Protected
in
let create_new_procdesc () =
let all_params = Option.to_list ms.CMethodSignature.class_param @ ms.CMethodSignature.params in
let has_added_return_param = ms.CMethodSignature.has_added_return_param in
let method_annotation =
let return = snd ms.CMethodSignature.ret_type in
let params = List.map ~f:(fun ({annot} : CMethodSignature.param_type) -> annot) all_params in
Annot.Method.{return; params}
in
let formals =
List.map ~f:(fun ({name; typ} : CMethodSignature.param_type) -> (name, typ)) all_params
in
let captured_mangled = List.map ~f:(fun (var, t) -> (Pvar.get_name var, t)) captured in
(* Captured variables for blocks are treated as parameters *)
let formals = captured_mangled @ formals in
let const_formals = get_const_params_indices ~shift:(List.length captured_mangled) all_params in
let source_range = ms.CMethodSignature.loc in
L.(debug Capture Verbose)
"@\nCreating a new procdesc for function: '%a'@\n@." Procname.pp proc_name ;
L.(debug Capture Verbose) "@\nms = %a@\n@." CMethodSignature.pp ms ;
let loc_start =
CLocation.location_of_source_range trans_unit_ctx.CFrontend_config.source_file source_range
in
let loc_exit =
CLocation.location_of_source_range ~pick_location:`End
trans_unit_ctx.CFrontend_config.source_file source_range
in
let ret_type = fst ms.CMethodSignature.ret_type in
let objc_property_accessor =
if set_objc_accessor_attr then get_objc_property_accessor tenv ms else None
in
let translation_unit = trans_unit_ctx.CFrontend_config.source_file in
let procdesc =
let proc_attributes =
{ (ProcAttributes.default translation_unit proc_name) with
ProcAttributes.captured= captured_mangled
; formals
; const_formals
; has_added_return_param
; access
; is_defined= defined
; is_cpp_noexcept_method= is_cpp_nothrow
; is_biabduction_model= Config.biabduction_models_mode
; is_no_return= ms.CMethodSignature.is_no_return
; is_variadic= ms.CMethodSignature.is_variadic
; sentinel_attr= find_sentinel_attribute ms.CMethodSignature.attributes
; loc= loc_start
; clang_method_kind
; objc_accessor= objc_property_accessor
; method_annotation
; ret_type }
in
Cfg.create_proc_desc cfg proc_attributes
in
if defined then (
let start_node = Procdesc.create_node procdesc loc_start Procdesc.Node.Start_node [] in
let exit_node = Procdesc.create_node procdesc loc_exit Procdesc.Node.Exit_node [] in
Procdesc.set_start_node procdesc start_node ;
Procdesc.set_exit_node procdesc exit_node )
in
if should_create_procdesc cfg proc_name ~defined ~set_objc_accessor_attr then (
create_new_procdesc () ; true )
else false
(** Create a procdesc for objc methods whose signature cannot be found. *)
let create_external_procdesc trans_unit_ctx cfg proc_name clang_method_kind type_opt =
if not (Procname.Hash.mem cfg proc_name) then
let ret_type, formals =
match type_opt with
| Some (ret_type, arg_types) ->
(ret_type, List.map ~f:(fun typ -> (Mangled.from_string "x", typ)) arg_types)
| None ->
(Typ.mk Typ.Tvoid, [])
in
let proc_attributes =
{ (ProcAttributes.default trans_unit_ctx.CFrontend_config.source_file proc_name) with
ProcAttributes.formals
; clang_method_kind
; ret_type }
in
ignore (Cfg.create_proc_desc cfg proc_attributes)
let create_procdesc_with_pointer context pointer class_name_opt name =
let open CContext in
match method_signature_of_pointer context.tenv pointer with
| Some callee_ms ->
ignore
(create_local_procdesc context.translation_unit_context context.cfg context.tenv callee_ms
[] []) ;
callee_ms.CMethodSignature.name
| None ->
let callee_name, method_kind =
match class_name_opt with
| Some class_name ->
( CType_decl.CProcname.NoAstDecl.cpp_method_of_string context.tenv class_name name
, ClangMethodKind.CPP_INSTANCE )
| None ->
( CType_decl.CProcname.NoAstDecl.c_function_of_string context.tenv name
, ClangMethodKind.C_FUNCTION )
in
create_external_procdesc context.translation_unit_context context.cfg callee_name method_kind
None ;
callee_name
let get_procname_from_cpp_lambda context dec =
match dec with
| Clang_ast_t.CXXRecordDecl (_, _, _, _, _, _, _, cxx_rdi) -> (
match cxx_rdi.xrdi_lambda_call_operator with
| Some dr ->
let name_info, decl_ptr, _ = CAst_utils.get_info_from_decl_ref dr in
create_procdesc_with_pointer context decl_ptr None name_info.ni_name
| _ ->
assert false )
| _ ->
assert false
let get_captures_from_cpp_lambda dec =
match dec with
| Clang_ast_t.CXXRecordDecl (_, _, _, _, _, _, _, cxx_rdi) ->
cxx_rdi.xrdi_lambda_captures
| _ ->
assert false
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/clang/cMethod_trans.ml | ocaml | Gets the class name from a method signature found by clang, if search is successful
Get class name from a method call accorsing to the info given by the receiver kind
* Returns a list of the indices of expressions in [args] which point to const-typed values. Each
index is offset by [shift].
* Creates a procedure description.
Captured variables for blocks are treated as parameters
* Create a procdesc for objc methods whose signature cannot be found. |
* 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
* Methods for creating a procdesc from a method or function declaration and for resolving a method
call and finding the right callee
call and finding the right callee *)
module L = Logging
* When the methoc call is MCStatic , means that it is a class method . When it is MCVirtual , it
means that it is an instance method and that the method to be called will be determined at
runtime . If it is MCNoVirtual it means that it is an instance method but that the method to be
called will be determined at compile time
means that it is an instance method and that the method to be called will be determined at
runtime. If it is MCNoVirtual it means that it is an instance method but that the method to be
called will be determined at compile time *)
type method_call_type = MCVirtual | MCNoVirtual | MCStatic [@@deriving compare]
let equal_method_call_type = [%compare.equal: method_call_type]
let method_signature_of_pointer tenv pointer =
try
match CAst_utils.get_decl pointer with
| Some meth_decl ->
let procname = CType_decl.CProcname.from_decl ~tenv meth_decl in
let ms = CType_decl.method_signature_of_decl tenv meth_decl procname in
Some ms
| None ->
None
with CFrontend_errors.Invalid_declaration -> None
let get_method_name_from_clang tenv ms_opt =
match ms_opt with
| Some ms -> (
match CAst_utils.get_decl_opt ms.CMethodSignature.pointer_to_parent with
| Some decl -> (
ignore (CType_decl.add_types_from_decl_to_tenv tenv decl) ;
match ObjcCategory_decl.get_base_class_name_from_category decl with
| Some class_typename ->
let procname = ms.CMethodSignature.name in
let new_procname = Procname.replace_class procname class_typename in
Some new_procname
| None ->
Some ms.CMethodSignature.name )
| None ->
Some ms.CMethodSignature.name )
| None ->
None
let get_superclass_curr_class_objc context =
let open Clang_ast_t in
let decl_ref =
match CContext.get_curr_class context with
| CContext.ContextClsDeclPtr ptr -> (
match CAst_utils.get_decl ptr with
| Some decl ->
CAst_utils.get_superclass_curr_class_objc_from_decl decl
| None ->
Logging.die InternalError
"Expected that the current class ptr in the context is a valid pointer to class decl, \
but didn't find declaration, ptr is %d "
ptr )
| CContext.ContextNoCls ->
Logging.die InternalError
"This should only be called in the context of a class, but got CContext.ContextNoCls"
in
match decl_ref |> Option.value_map ~f:(fun dr -> dr.dr_name) ~default:None with
| Some name ->
Typ.Name.Objc.from_qual_name (CAst_utils.get_qualified_name name)
| None ->
Logging.die InternalError "Expected to always find a superclass, but found none"
let get_class_name_method_call_from_clang tenv obj_c_message_expr_info =
match obj_c_message_expr_info.Clang_ast_t.omei_decl_pointer with
| Some pointer -> (
match method_signature_of_pointer tenv pointer with
| Some ms -> (
match ms.CMethodSignature.name with
| Procname.ObjC_Cpp objc_cpp ->
Some (Procname.ObjC_Cpp.get_class_type_name objc_cpp)
| _ ->
None )
| None ->
None )
| None ->
None
let get_class_name_method_call_from_receiver_kind context obj_c_message_expr_info act_params =
match obj_c_message_expr_info.Clang_ast_t.omei_receiver_kind with
| `Class qt ->
let sil_type = CType_decl.qual_type_to_sil_type context.CContext.tenv qt in
CType.objc_classname_of_type sil_type
| `Instance -> (
match act_params with
| (_, {Typ.desc= Tptr (t, _)}) :: _ | (_, t) :: _ ->
CType.objc_classname_of_type t
| _ ->
assert false )
| `SuperInstance ->
get_superclass_curr_class_objc context
| `SuperClass ->
get_superclass_curr_class_objc context
let get_objc_method_data obj_c_message_expr_info =
let selector = obj_c_message_expr_info.Clang_ast_t.omei_selector in
let pointer = obj_c_message_expr_info.Clang_ast_t.omei_decl_pointer in
match obj_c_message_expr_info.Clang_ast_t.omei_receiver_kind with
| `Instance ->
(selector, pointer, MCVirtual)
| `SuperInstance ->
(selector, pointer, MCNoVirtual)
| `Class _ | `SuperClass ->
(selector, pointer, MCStatic)
let should_create_procdesc cfg procname ~defined ~set_objc_accessor_attr =
match Procname.Hash.find cfg procname with
| previous_procdesc ->
let is_defined_previous = Procdesc.is_defined previous_procdesc in
if (defined || set_objc_accessor_attr) && not is_defined_previous then (
Procname.Hash.remove cfg procname ; true )
else false
| exception Caml.Not_found ->
true
let get_const_params_indices ~shift params =
let i = ref shift in
let rec aux result = function
| [] ->
List.rev result
| ({is_pointer_to_const} : CMethodSignature.param_type) :: tl ->
incr i ;
if is_pointer_to_const then aux ((!i - 1) :: result) tl else aux result tl
in
aux [] params
let get_objc_property_accessor tenv ms =
let open Clang_ast_t in
match CAst_utils.get_decl_opt ms.CMethodSignature.pointer_to_property_opt with
| Some (ObjCPropertyDecl (_, _, obj_c_property_decl_info)) -> (
let ivar_decl_ref = obj_c_property_decl_info.Clang_ast_t.opdi_ivar_decl in
match CAst_utils.get_decl_opt_with_decl_ref_opt ivar_decl_ref with
| Some (ObjCIvarDecl (_, name_decl_info, _, _, _)) -> (
let class_tname =
Typ.Name.Objc.from_qual_name
(QualifiedCppName.from_field_qualified_name
(QualifiedCppName.of_rev_list name_decl_info.ni_qual_name))
in
let field_name = CGeneral_utils.mk_class_field_name class_tname name_decl_info.ni_name in
match Tenv.lookup tenv class_tname with
| Some {fields} -> (
let field_opt =
List.find ~f:(fun (name, _, _) -> Fieldname.equal name field_name) fields
in
match field_opt with
| Some field when CMethodSignature.is_getter ms ->
Some (ProcAttributes.Objc_getter field)
| Some field when CMethodSignature.is_setter ms ->
Some (ProcAttributes.Objc_setter field)
| _ ->
None )
| None ->
None )
| _ ->
None )
| _ ->
None
let find_sentinel_attribute attrs =
List.find_map attrs ~f:(function
| `SentinelAttr (_attr_info, {Clang_ast_t.sai_sentinel= sentinel; sai_null_pos= null_pos}) ->
Some (sentinel, null_pos)
| _ ->
None )
let create_local_procdesc ?(set_objc_accessor_attr = false) trans_unit_ctx cfg tenv ms fbody
captured =
let defined = not (List.is_empty fbody) in
let proc_name = ms.CMethodSignature.name in
let clang_method_kind = ms.CMethodSignature.method_kind in
let is_cpp_nothrow = ms.CMethodSignature.is_cpp_nothrow in
let access =
match ms.CMethodSignature.access with
| `None ->
PredSymb.Default
| `Private ->
PredSymb.Private
| `Protected ->
PredSymb.Protected
| `Public ->
PredSymb.Protected
in
let create_new_procdesc () =
let all_params = Option.to_list ms.CMethodSignature.class_param @ ms.CMethodSignature.params in
let has_added_return_param = ms.CMethodSignature.has_added_return_param in
let method_annotation =
let return = snd ms.CMethodSignature.ret_type in
let params = List.map ~f:(fun ({annot} : CMethodSignature.param_type) -> annot) all_params in
Annot.Method.{return; params}
in
let formals =
List.map ~f:(fun ({name; typ} : CMethodSignature.param_type) -> (name, typ)) all_params
in
let captured_mangled = List.map ~f:(fun (var, t) -> (Pvar.get_name var, t)) captured in
let formals = captured_mangled @ formals in
let const_formals = get_const_params_indices ~shift:(List.length captured_mangled) all_params in
let source_range = ms.CMethodSignature.loc in
L.(debug Capture Verbose)
"@\nCreating a new procdesc for function: '%a'@\n@." Procname.pp proc_name ;
L.(debug Capture Verbose) "@\nms = %a@\n@." CMethodSignature.pp ms ;
let loc_start =
CLocation.location_of_source_range trans_unit_ctx.CFrontend_config.source_file source_range
in
let loc_exit =
CLocation.location_of_source_range ~pick_location:`End
trans_unit_ctx.CFrontend_config.source_file source_range
in
let ret_type = fst ms.CMethodSignature.ret_type in
let objc_property_accessor =
if set_objc_accessor_attr then get_objc_property_accessor tenv ms else None
in
let translation_unit = trans_unit_ctx.CFrontend_config.source_file in
let procdesc =
let proc_attributes =
{ (ProcAttributes.default translation_unit proc_name) with
ProcAttributes.captured= captured_mangled
; formals
; const_formals
; has_added_return_param
; access
; is_defined= defined
; is_cpp_noexcept_method= is_cpp_nothrow
; is_biabduction_model= Config.biabduction_models_mode
; is_no_return= ms.CMethodSignature.is_no_return
; is_variadic= ms.CMethodSignature.is_variadic
; sentinel_attr= find_sentinel_attribute ms.CMethodSignature.attributes
; loc= loc_start
; clang_method_kind
; objc_accessor= objc_property_accessor
; method_annotation
; ret_type }
in
Cfg.create_proc_desc cfg proc_attributes
in
if defined then (
let start_node = Procdesc.create_node procdesc loc_start Procdesc.Node.Start_node [] in
let exit_node = Procdesc.create_node procdesc loc_exit Procdesc.Node.Exit_node [] in
Procdesc.set_start_node procdesc start_node ;
Procdesc.set_exit_node procdesc exit_node )
in
if should_create_procdesc cfg proc_name ~defined ~set_objc_accessor_attr then (
create_new_procdesc () ; true )
else false
let create_external_procdesc trans_unit_ctx cfg proc_name clang_method_kind type_opt =
if not (Procname.Hash.mem cfg proc_name) then
let ret_type, formals =
match type_opt with
| Some (ret_type, arg_types) ->
(ret_type, List.map ~f:(fun typ -> (Mangled.from_string "x", typ)) arg_types)
| None ->
(Typ.mk Typ.Tvoid, [])
in
let proc_attributes =
{ (ProcAttributes.default trans_unit_ctx.CFrontend_config.source_file proc_name) with
ProcAttributes.formals
; clang_method_kind
; ret_type }
in
ignore (Cfg.create_proc_desc cfg proc_attributes)
let create_procdesc_with_pointer context pointer class_name_opt name =
let open CContext in
match method_signature_of_pointer context.tenv pointer with
| Some callee_ms ->
ignore
(create_local_procdesc context.translation_unit_context context.cfg context.tenv callee_ms
[] []) ;
callee_ms.CMethodSignature.name
| None ->
let callee_name, method_kind =
match class_name_opt with
| Some class_name ->
( CType_decl.CProcname.NoAstDecl.cpp_method_of_string context.tenv class_name name
, ClangMethodKind.CPP_INSTANCE )
| None ->
( CType_decl.CProcname.NoAstDecl.c_function_of_string context.tenv name
, ClangMethodKind.C_FUNCTION )
in
create_external_procdesc context.translation_unit_context context.cfg callee_name method_kind
None ;
callee_name
let get_procname_from_cpp_lambda context dec =
match dec with
| Clang_ast_t.CXXRecordDecl (_, _, _, _, _, _, _, cxx_rdi) -> (
match cxx_rdi.xrdi_lambda_call_operator with
| Some dr ->
let name_info, decl_ptr, _ = CAst_utils.get_info_from_decl_ref dr in
create_procdesc_with_pointer context decl_ptr None name_info.ni_name
| _ ->
assert false )
| _ ->
assert false
let get_captures_from_cpp_lambda dec =
match dec with
| Clang_ast_t.CXXRecordDecl (_, _, _, _, _, _, _, cxx_rdi) ->
cxx_rdi.xrdi_lambda_captures
| _ ->
assert false
|
54e0a9d4d771fbb96811beb01269b9934e63f03cb369de8cd02659ade7eb63ba | awslabs/s2n-bignum | bignum_double_sm2.ml |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
(* ========================================================================= *)
(* Doubling modulo p_sm2, the field characteristic for the CC SM2 curve. *)
(* ========================================================================= *)
(**** print_literal_from_elf "arm/sm2/bignum_double_sm2.o";;
****)
let bignum_double_sm2_mc = define_assert_from_elf "bignum_double_sm2_mc" "arm/sm2/bignum_double_sm2.o"
[
arm_LDP X2 X3 X1 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_LDP X4 X5 X1 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_ADDS X2 X2 X2
arm_ADCS X3 X3 X3
arm_ADCS X4 X4 X4
arm_ADCS X5 X5 X5
arm_ADC
arm_ADDS X7 X2 ( rvalue ( word 1 ) )
arm_MOV X8 ( rvalue ( word 18446744069414584320 ) )
arm_SBCS X8 X3 X8
arm_ADCS XZR
arm_MOVN X10 ( word 1 ) 32
arm_SBCS X10 X5 X10
arm_SBCS X6 X6 XZR
arm_CSEL X2 X2 X7 Condition_CC
arm_CSEL X3 X3 X8 Condition_CC
arm_CSEL X4 X4 X9 Condition_CC
arm_CSEL X5 X5 X10 Condition_CC
arm_STP X2 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_STP X4 X5 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_RET X30
];;
let BIGNUM_DOUBLE_SM2_EXEC = ARM_MK_EXEC_RULE bignum_double_sm2_mc;;
(* ------------------------------------------------------------------------- *)
(* Proof. *)
(* ------------------------------------------------------------------------- *)
let p_sm2 = new_definition `p_sm2 = 0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF`;;
let BIGNUM_DOUBLE_SM2_CORRECT = time prove
(`!z x n pc.
nonoverlapping (word pc,0x54) (z,8 * 4)
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_double_sm2_mc /\
read PC s = word pc /\
C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,4) s = n)
(\s. read PC s = word (pc + 0x50) /\
(n < p_sm2
==> bignum_from_memory (z,4) s = (2 * n) MOD p_sm2))
(MAYCHANGE [PC; X2; X3; X4; X5; X6; X7; X8; X9; X10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,4)])`,
MAP_EVERY X_GEN_TAC
[`z:int64`; `x:int64`; `n:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
BIGNUM_DIGITIZE_TAC "n_" `read (memory :> bytes (x,8 * 4)) s0` THEN
ARM_ACCSTEPS_TAC BIGNUM_DOUBLE_SM2_EXEC (1--20) (1--20) THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_CLAUSES; VAL_WORD_BITVAL]) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN DISCH_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[REAL_BITVAL_NOT]) THEN
SUBGOAL_THEN
`carry_s14 <=> 2 * n < p_sm2`
SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `320` THEN
EXPAND_TAC "n" THEN REWRITE_TAC[p_sm2; GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
ALL_TAC] THEN
CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN
ASM_REWRITE_TAC[] THEN DISCARD_STATE_TAC "s20" THEN
ASM_SIMP_TAC[MOD_CASES; ARITH_RULE `n < p ==> 2 * n < 2 * p`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_EQ] THEN ONCE_REWRITE_TAC[COND_RAND] THEN
SIMP_TAC[GSYM REAL_OF_NUM_SUB; GSYM NOT_LT] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_ADD; GSYM REAL_OF_NUM_MUL;
GSYM REAL_OF_NUM_POW] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`256`; `&0:real`] THEN
ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL
[COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN BOUNDER_TAC[];
ALL_TAC] THEN
CONJ_TAC THENL
[UNDISCH_TAC `n < p_sm2` THEN
REWRITE_TAC[p_sm2; GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC;
ALL_TAC] THEN
CONJ_TAC THENL [REAL_INTEGER_TAC; ALL_TAC] THEN
FIRST_X_ASSUM(SUBST1_TAC o MATCH_MP (MESON[REAL_OF_NUM_ADD; REAL_OF_NUM_EQ]
`a + b:num = n ==> &n = &a + &b`)) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES; p_sm2] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN REAL_INTEGER_TAC);;
let BIGNUM_DOUBLE_SM2_SUBROUTINE_CORRECT = time prove
(`!z x n pc returnaddress.
nonoverlapping (word pc,0x54) (z,8 * 4)
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_double_sm2_mc /\
read PC s = word pc /\
read X30 s = returnaddress /\
C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,4) s = n)
(\s. read PC s = returnaddress /\
(n < p_sm2
==> bignum_from_memory (z,4) s = (2 * n) MOD p_sm2))
(MAYCHANGE [PC; X2; X3; X4; X5; X6; X7; X8; X9; X10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,4)])`,
ARM_ADD_RETURN_NOSTACK_TAC
BIGNUM_DOUBLE_SM2_EXEC BIGNUM_DOUBLE_SM2_CORRECT);;
| null | https://raw.githubusercontent.com/awslabs/s2n-bignum/6b53f075a0e28e6b89db12301de5f59ec788855c/arm/proofs/bignum_double_sm2.ml | ocaml | =========================================================================
Doubling modulo p_sm2, the field characteristic for the CC SM2 curve.
=========================================================================
*** print_literal_from_elf "arm/sm2/bignum_double_sm2.o";;
***
-------------------------------------------------------------------------
Proof.
------------------------------------------------------------------------- |
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved .
* SPDX - License - Identifier : Apache-2.0 OR ISC
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0 OR ISC
*)
let bignum_double_sm2_mc = define_assert_from_elf "bignum_double_sm2_mc" "arm/sm2/bignum_double_sm2.o"
[
arm_LDP X2 X3 X1 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_LDP X4 X5 X1 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_ADDS X2 X2 X2
arm_ADCS X3 X3 X3
arm_ADCS X4 X4 X4
arm_ADCS X5 X5 X5
arm_ADC
arm_ADDS X7 X2 ( rvalue ( word 1 ) )
arm_MOV X8 ( rvalue ( word 18446744069414584320 ) )
arm_SBCS X8 X3 X8
arm_ADCS XZR
arm_MOVN X10 ( word 1 ) 32
arm_SBCS X10 X5 X10
arm_SBCS X6 X6 XZR
arm_CSEL X2 X2 X7 Condition_CC
arm_CSEL X3 X3 X8 Condition_CC
arm_CSEL X4 X4 X9 Condition_CC
arm_CSEL X5 X5 X10 Condition_CC
arm_STP X2 ( Immediate_Offset ( iword ( & 0 ) ) )
arm_STP X4 X5 ( Immediate_Offset ( iword ( & 16 ) ) )
arm_RET X30
];;
let BIGNUM_DOUBLE_SM2_EXEC = ARM_MK_EXEC_RULE bignum_double_sm2_mc;;
let p_sm2 = new_definition `p_sm2 = 0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF`;;
let BIGNUM_DOUBLE_SM2_CORRECT = time prove
(`!z x n pc.
nonoverlapping (word pc,0x54) (z,8 * 4)
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_double_sm2_mc /\
read PC s = word pc /\
C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,4) s = n)
(\s. read PC s = word (pc + 0x50) /\
(n < p_sm2
==> bignum_from_memory (z,4) s = (2 * n) MOD p_sm2))
(MAYCHANGE [PC; X2; X3; X4; X5; X6; X7; X8; X9; X10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,4)])`,
MAP_EVERY X_GEN_TAC
[`z:int64`; `x:int64`; `n:num`; `pc:num`] THEN
REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN
DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN
REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN
BIGNUM_DIGITIZE_TAC "n_" `read (memory :> bytes (x,8 * 4)) s0` THEN
ARM_ACCSTEPS_TAC BIGNUM_DOUBLE_SM2_EXEC (1--20) (1--20) THEN
RULE_ASSUM_TAC(REWRITE_RULE[ADD_CLAUSES; VAL_WORD_BITVAL]) THEN
ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN DISCH_TAC THEN
RULE_ASSUM_TAC(REWRITE_RULE[REAL_BITVAL_NOT]) THEN
SUBGOAL_THEN
`carry_s14 <=> 2 * n < p_sm2`
SUBST_ALL_TAC THENL
[MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `320` THEN
EXPAND_TAC "n" THEN REWRITE_TAC[p_sm2; GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[];
ALL_TAC] THEN
CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN
ASM_REWRITE_TAC[] THEN DISCARD_STATE_TAC "s20" THEN
ASM_SIMP_TAC[MOD_CASES; ARITH_RULE `n < p ==> 2 * n < 2 * p`] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_EQ] THEN ONCE_REWRITE_TAC[COND_RAND] THEN
SIMP_TAC[GSYM REAL_OF_NUM_SUB; GSYM NOT_LT] THEN
REWRITE_TAC[GSYM REAL_OF_NUM_ADD; GSYM REAL_OF_NUM_MUL;
GSYM REAL_OF_NUM_POW] THEN
MATCH_MP_TAC EQUAL_FROM_CONGRUENT_REAL THEN
MAP_EVERY EXISTS_TAC [`256`; `&0:real`] THEN
ASM_REWRITE_TAC[] THEN
CONJ_TAC THENL
[COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN BOUNDER_TAC[];
ALL_TAC] THEN
CONJ_TAC THENL
[UNDISCH_TAC `n < p_sm2` THEN
REWRITE_TAC[p_sm2; GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC;
ALL_TAC] THEN
CONJ_TAC THENL [REAL_INTEGER_TAC; ALL_TAC] THEN
FIRST_X_ASSUM(SUBST1_TAC o MATCH_MP (MESON[REAL_OF_NUM_ADD; REAL_OF_NUM_EQ]
`a + b:num = n ==> &n = &a + &b`)) THEN
REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN
ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN
COND_CASES_TAC THEN ASM_REWRITE_TAC[BITVAL_CLAUSES; p_sm2] THEN
DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN
CONV_TAC(RAND_CONV REAL_POLY_CONV) THEN REAL_INTEGER_TAC);;
let BIGNUM_DOUBLE_SM2_SUBROUTINE_CORRECT = time prove
(`!z x n pc returnaddress.
nonoverlapping (word pc,0x54) (z,8 * 4)
==> ensures arm
(\s. aligned_bytes_loaded s (word pc) bignum_double_sm2_mc /\
read PC s = word pc /\
read X30 s = returnaddress /\
C_ARGUMENTS [z; x] s /\
bignum_from_memory (x,4) s = n)
(\s. read PC s = returnaddress /\
(n < p_sm2
==> bignum_from_memory (z,4) s = (2 * n) MOD p_sm2))
(MAYCHANGE [PC; X2; X3; X4; X5; X6; X7; X8; X9; X10] ,,
MAYCHANGE SOME_FLAGS ,,
MAYCHANGE [memory :> bignum(z,4)])`,
ARM_ADD_RETURN_NOSTACK_TAC
BIGNUM_DOUBLE_SM2_EXEC BIGNUM_DOUBLE_SM2_CORRECT);;
|
133ddb15fd65302d9c05898d1548cfa385c9a428ac365bc3b1322394631edbe1 | ocaml-multicore/reagents | offer.ml |
* Copyright ( c ) 2015 , < >
* Copyright ( c ) 2015 , < >
*
* Permission to use , copy , modify , and/or distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015, Théo Laurent <>
* Copyright (c) 2015, KC Sivaramakrishnan <>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module type S = Offer_intf.S
module Make (Sched : Scheduler.S) : S = struct
module Loc = Kcas.Loc
type 'a status =
| Empty
| Waiting of unit Sched.cont
| Catalyst
| Rescinded
| Completed of 'a
type 'a t = 'a status Loc.t
let make () = Loc.make Empty
let get_id r = Offer_id.make (Loc.get_id r)
let equal o1 o2 = Loc.get_id o1 = Loc.get_id o2
let is_active o =
match Loc.get o with
| Empty | Waiting _ | Catalyst -> true
| Rescinded | Completed _ -> false
let wait r =
Sched.suspend (fun k ->
match
Loc.update r (fun v ->
match v with
| Empty -> Waiting k
| Waiting _ | Catalyst -> failwith "Offer.wait(1)"
| Completed _ | Rescinded -> raise Exit)
with
If CAS was a success , then it is no longer this thread 's responsibiliy to
* resume itself .
* resume itself. *)
| _ -> None
If the CAS failed , then another thread has already changed the offer from
* [ Empty ] to [ Completed ] or [ ] . In this case , thread should n't
* wait .
* [Empty] to [Completed] or [Rescinded]. In this case, thread shouldn't
* wait. *)
| exception Exit -> Some ())
let complete r new_v =
let old_v = Loc.get r in
match old_v with
| Waiting k ->
PostCommitCas.cas r old_v (Completed new_v) (fun () ->
Sched.resume k ())
| Catalyst -> PostCommitCas.return true (fun () -> ())
| Empty -> PostCommitCas.cas r old_v (Completed new_v) (fun () -> ())
| Rescinded | Completed _ -> PostCommitCas.return false (fun () -> ())
let rescind r =
(match
Loc.update r (fun v ->
match v with
| Empty | Waiting _ -> Rescinded
| Rescinded | Completed _ | Catalyst -> raise Exit)
with
| Waiting t -> Sched.resume t ()
| _ | (exception Exit) -> ());
match Loc.get r with
| Rescinded | Catalyst -> None
| Completed v -> Some v
| _ -> failwith "Offer.rescind"
let get_result r = match Loc.get r with Completed v -> Some v | _ -> None
type catalyst = unit -> unit
let make_catalyst () =
let offer = Loc.make Catalyst in
let cancel () = Loc.set offer Rescinded in
(offer, cancel)
let cancel_catalyst f = f ()
end
| null | https://raw.githubusercontent.com/ocaml-multicore/reagents/6721db78b21028c807fb13d0af0aaf9407c662b5/lib/offer.ml | ocaml |
* Copyright ( c ) 2015 , < >
* Copyright ( c ) 2015 , < >
*
* Permission to use , copy , modify , and/or distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2015, Théo Laurent <>
* Copyright (c) 2015, KC Sivaramakrishnan <>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module type S = Offer_intf.S
module Make (Sched : Scheduler.S) : S = struct
module Loc = Kcas.Loc
type 'a status =
| Empty
| Waiting of unit Sched.cont
| Catalyst
| Rescinded
| Completed of 'a
type 'a t = 'a status Loc.t
let make () = Loc.make Empty
let get_id r = Offer_id.make (Loc.get_id r)
let equal o1 o2 = Loc.get_id o1 = Loc.get_id o2
let is_active o =
match Loc.get o with
| Empty | Waiting _ | Catalyst -> true
| Rescinded | Completed _ -> false
let wait r =
Sched.suspend (fun k ->
match
Loc.update r (fun v ->
match v with
| Empty -> Waiting k
| Waiting _ | Catalyst -> failwith "Offer.wait(1)"
| Completed _ | Rescinded -> raise Exit)
with
If CAS was a success , then it is no longer this thread 's responsibiliy to
* resume itself .
* resume itself. *)
| _ -> None
If the CAS failed , then another thread has already changed the offer from
* [ Empty ] to [ Completed ] or [ ] . In this case , thread should n't
* wait .
* [Empty] to [Completed] or [Rescinded]. In this case, thread shouldn't
* wait. *)
| exception Exit -> Some ())
let complete r new_v =
let old_v = Loc.get r in
match old_v with
| Waiting k ->
PostCommitCas.cas r old_v (Completed new_v) (fun () ->
Sched.resume k ())
| Catalyst -> PostCommitCas.return true (fun () -> ())
| Empty -> PostCommitCas.cas r old_v (Completed new_v) (fun () -> ())
| Rescinded | Completed _ -> PostCommitCas.return false (fun () -> ())
let rescind r =
(match
Loc.update r (fun v ->
match v with
| Empty | Waiting _ -> Rescinded
| Rescinded | Completed _ | Catalyst -> raise Exit)
with
| Waiting t -> Sched.resume t ()
| _ | (exception Exit) -> ());
match Loc.get r with
| Rescinded | Catalyst -> None
| Completed v -> Some v
| _ -> failwith "Offer.rescind"
let get_result r = match Loc.get r with Completed v -> Some v | _ -> None
type catalyst = unit -> unit
let make_catalyst () =
let offer = Loc.make Catalyst in
let cancel () = Loc.set offer Rescinded in
(offer, cancel)
let cancel_catalyst f = f ()
end
| |
1ba9eda564e54c70f216ea422045b6740a55e9ddd38aad85a9b55ada3b9f0799 | callum-oakley/advent-of-code | 16.clj | (ns aoc.2016.16
(:require
[clojure.test :refer [deftest is]]))
(defn grow [data]
(into (conj data \0) (map {\0 \1 \1 \0}) (rseq data)))
(defn checksum [data]
(if (even? (count data))
(recur (mapv (fn [[a b]] (if (= a b) \1 \0)) (partition 2 data)))
data))
(defn part-* [disk seed]
(apply str
(checksum
(subvec (first (filter #(<= disk (count %))
(iterate grow (vec seed))))
0
disk))))
(defn part-1 [s]
(part-* 272 s))
(defn part-2 [s]
(part-* 35651584 s))
(deftest test-grow
(is (= (vec "100") (grow (vec "1"))))
(is (= (vec "001") (grow (vec "0"))))
(is (= (vec "11111000000") (grow (vec "11111"))))
(is (= (vec "1111000010100101011110000") (grow (vec "111100001010")))))
(deftest test-checksum
(is (= (vec "100") (checksum (vec "110010110100")))))
(deftest test-part-*
(is (= "01100" (part-* 20 "10000"))))
| null | https://raw.githubusercontent.com/callum-oakley/advent-of-code/da5233fc0fd3d3773d35ee747fd837c59c2b1c04/src/aoc/2016/16.clj | clojure | (ns aoc.2016.16
(:require
[clojure.test :refer [deftest is]]))
(defn grow [data]
(into (conj data \0) (map {\0 \1 \1 \0}) (rseq data)))
(defn checksum [data]
(if (even? (count data))
(recur (mapv (fn [[a b]] (if (= a b) \1 \0)) (partition 2 data)))
data))
(defn part-* [disk seed]
(apply str
(checksum
(subvec (first (filter #(<= disk (count %))
(iterate grow (vec seed))))
0
disk))))
(defn part-1 [s]
(part-* 272 s))
(defn part-2 [s]
(part-* 35651584 s))
(deftest test-grow
(is (= (vec "100") (grow (vec "1"))))
(is (= (vec "001") (grow (vec "0"))))
(is (= (vec "11111000000") (grow (vec "11111"))))
(is (= (vec "1111000010100101011110000") (grow (vec "111100001010")))))
(deftest test-checksum
(is (= (vec "100") (checksum (vec "110010110100")))))
(deftest test-part-*
(is (= "01100" (part-* 20 "10000"))))
| |
3836668860adabf68cef265a77aa378d772be18c2110876b82c75e0652265d20 | Holworth/SICP_Solutions | exercise2-36.rkt | #lang sicp
(define (reduce op init items)
(cond ((null? items) init)
(else (op (car items)
(reduce op init (cdr items))))))
(define (reduce-n op init seqs)
(if (null? (car seqs))
nil
(cons (reduce op (car init) (map (lambda (x) (car x)) seqs))
(reduce-n op (cdr init) (map (lambda (x) (cdr x)) seqs)))))
(define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12)))
(reduce-n + (list 0 0 0) s) | null | https://raw.githubusercontent.com/Holworth/SICP_Solutions/da4041d4c48a04df7c17ea840458d8044ae6c9fb/solutions/chap2/code/exercise2-36.rkt | racket | #lang sicp
(define (reduce op init items)
(cond ((null? items) init)
(else (op (car items)
(reduce op init (cdr items))))))
(define (reduce-n op init seqs)
(if (null? (car seqs))
nil
(cons (reduce op (car init) (map (lambda (x) (car x)) seqs))
(reduce-n op (cdr init) (map (lambda (x) (cdr x)) seqs)))))
(define s (list (list 1 2 3) (list 4 5 6) (list 7 8 9) (list 10 11 12)))
(reduce-n + (list 0 0 0) s) | |
0d8418a9a012a7b4f892d214dbb140334d508657aa282931a192ccbc9be4af5d | AdRoll/rebar3_format | m1.erl | %%
%% File: m1.erl
Author : Björn - Egil Dahlberg
Created : 2014 - 10 - 24
%%
-module(m1).
-export([foo/0,bar/1,baz/2]).
foo() ->
[m2:foo(),
m2:bar()].
bar(A) ->
[m2:foo(A),
m2:bar(A),
m2:record_update(3,m2:record())].
baz(A,B) ->
[m2:foo(A,B),
m2:bar(A,B)].
| null | https://raw.githubusercontent.com/AdRoll/rebar3_format/5ffb11341796173317ae094d4e165b85fad6aa19/test_app/src/otp_samples/m1.erl | erlang |
File: m1.erl
| Author : Björn - Egil Dahlberg
Created : 2014 - 10 - 24
-module(m1).
-export([foo/0,bar/1,baz/2]).
foo() ->
[m2:foo(),
m2:bar()].
bar(A) ->
[m2:foo(A),
m2:bar(A),
m2:record_update(3,m2:record())].
baz(A,B) ->
[m2:foo(A,B),
m2:bar(A,B)].
|
0294b17c588ad77ea353bdb967aebcc24af93f44c25550096d810b46a53656bf | EmileTrotignon/embedded_ocaml_templates | transform.mli | val force_mutual_recursion : Ast.struct_ -> Ast.struct_
| null | https://raw.githubusercontent.com/EmileTrotignon/embedded_ocaml_templates/1ddee779f0410820d9e9f03150e4ae73e1deb835/src/common/mocaml/transform.mli | ocaml | val force_mutual_recursion : Ast.struct_ -> Ast.struct_
| |
e5e6778667de29d50d7433d6cb3ca969feda38f8119979a99ddb4558bc2cd16a | facebookincubator/hsthrift | SocketChannel.hs | Copyright ( c ) Facebook , Inc. and its affiliates .
-- |
An implementation of a Thrift channel in Haskell using
-- 'Network.Socket'. Note that the wire format of messages is not
-- necessarily compatible with other transports, in particular you
ca n't mix and match SocketChannel clients / servers with
HeaderChannel clients / servers .
# LANGUAGE CPP #
module Thrift.Channel.SocketChannel
( -- * Socket channel types and API
SocketChannel(..)
, SocketConfig(..)
, withSocketChannel
, withSocketChannelIO
, -- * Utilities used by test servers
sendBS
, teardownSock
, threadWaitRecv
, recvBlockBytes
, localhost
) where
import Control.Concurrent
import Control.Exception
import Data.Proxy
import Network.Socket
import Network.Socket.ByteString
import System.Posix.Types (Fd(..))
import qualified Data.ByteString as BS
import qualified Data.Text as T
import Thrift.Channel
import Thrift.Monad
import Thrift.Protocol
import Thrift.Protocol.Id
newtype SocketChannel t = SocketChannel Socket
instance ClientChannel SocketChannel where
sendRequest ch@(SocketChannel sock) req sendcb recvcb = do
sendOnewayRequest ch req sendcb
recvRes <- try (threadWaitRecv sock recvBlockBytes)
case recvRes of
Right s -> recvcb (Right $ Response s mempty)
Left (e :: SomeException) ->
recvcb (Left $ ChannelException $ T.pack (show e))
sendOnewayRequest (SocketChannel sock) req sendcb = do
res <- sendBS sock (reqMsg req)
sendcb res
data SocketConfig a = SocketConfig
{ socketHost :: HostName
, socketPortNum :: PortNumber
, socketProtocolId :: ProtocolId
}
deriving instance Show (SocketConfig a)
-- | Given a 'SocketConfig' that specifies where to find the
-- server we want to reach and what protocol it uses,
-- connect to the server and run the given client
-- computation with it.
withSocketChannel
:: SocketConfig t
-> (forall p . Protocol p => ThriftM p SocketChannel t a)
-> IO a
withSocketChannel SocketConfig{..} f =
withSocketChannelIO socketHost socketPortNum $ \ch -> do
withProxy socketProtocolId (go ch f)
where go :: Protocol p
=> SocketChannel t
-> ThriftM p SocketChannel t a
-> Proxy p
-> IO a
go ch f _proxy = runThrift f ch
-- | A lower level variant of 'withSocketChannel' that connects
-- to the server at the given host and port and passes the
resulting ' SocketChannel ' to the third argument .
withSocketChannelIO
:: HostName
-> PortNumber
-> (SocketChannel t -> IO a)
-> IO a
withSocketChannelIO host port f = withSocketClient host port $ \sock _ ->
f (SocketChannel sock)
sendBS :: Socket -> BS.ByteString -> IO (Maybe ChannelException)
sendBS sock bs = try (sendAll sock bs) >>= \res -> case res of
Left e -> return (Just e)
Right _ -> return Nothing
-- | Block (using 'threadWaitRead') until some data is available,
and then call ' ' to grab it .
threadWaitRecv
:: Socket
-> Int -- ^ max. number of bytes we want to receive
-> IO BS.ByteString
threadWaitRecv sock numBytes = withFdSocket sock $ \fd ->
threadWaitRead (Fd fd) >> recv sock numBytes
withSocketClient
:: HostName
-> PortNumber
-> (Socket -> AddrInfo -> IO a)
-> IO a
withSocketClient host port f = withSocketsDo $ do
addr <- resolveClient host port
bracket (setupClientSock addr) teardownSock $ \sock ->
f sock addr
setupClientSock :: AddrInfo -> IO Socket
setupClientSock addr = do
s <- openSocket addr
connect s (addrAddress addr)
return s
teardownSock :: Socket -> IO ()
teardownSock sock = shutdown sock ShutdownBoth `finally` close sock
resolveClient :: HostName -> PortNumber -> IO AddrInfo
resolveClient host port = do
results <- getAddrInfo (Just hints) (Just host) (Just $ show port)
case results of
[] -> error $ "SocketChannel.resolveClient: " <>
"getAddrInfo returned an empty list"
(a:_) -> return a
where hints = defaultHints { addrSocketType = Stream }
localhost :: HostName
localhost =
#ifdef IPV4
"127.0.0.1"
#else
"::1"
#endif
recvBlockBytes :: Int
recvBlockBytes = 4096
#if !MIN_VERSION_network(3,1,2)
openSocket :: AddrInfo -> IO Socket
openSocket addr =
socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
#endif
| null | https://raw.githubusercontent.com/facebookincubator/hsthrift/d3ff75d487e9d0c2904d18327373b603456e7a01/lib/Thrift/Channel/SocketChannel.hs | haskell | |
'Network.Socket'. Note that the wire format of messages is not
necessarily compatible with other transports, in particular you
* Socket channel types and API
* Utilities used by test servers
| Given a 'SocketConfig' that specifies where to find the
server we want to reach and what protocol it uses,
connect to the server and run the given client
computation with it.
| A lower level variant of 'withSocketChannel' that connects
to the server at the given host and port and passes the
| Block (using 'threadWaitRead') until some data is available,
^ max. number of bytes we want to receive | Copyright ( c ) Facebook , Inc. and its affiliates .
An implementation of a Thrift channel in Haskell using
ca n't mix and match SocketChannel clients / servers with
HeaderChannel clients / servers .
# LANGUAGE CPP #
module Thrift.Channel.SocketChannel
SocketChannel(..)
, SocketConfig(..)
, withSocketChannel
, withSocketChannelIO
sendBS
, teardownSock
, threadWaitRecv
, recvBlockBytes
, localhost
) where
import Control.Concurrent
import Control.Exception
import Data.Proxy
import Network.Socket
import Network.Socket.ByteString
import System.Posix.Types (Fd(..))
import qualified Data.ByteString as BS
import qualified Data.Text as T
import Thrift.Channel
import Thrift.Monad
import Thrift.Protocol
import Thrift.Protocol.Id
newtype SocketChannel t = SocketChannel Socket
instance ClientChannel SocketChannel where
sendRequest ch@(SocketChannel sock) req sendcb recvcb = do
sendOnewayRequest ch req sendcb
recvRes <- try (threadWaitRecv sock recvBlockBytes)
case recvRes of
Right s -> recvcb (Right $ Response s mempty)
Left (e :: SomeException) ->
recvcb (Left $ ChannelException $ T.pack (show e))
sendOnewayRequest (SocketChannel sock) req sendcb = do
res <- sendBS sock (reqMsg req)
sendcb res
data SocketConfig a = SocketConfig
{ socketHost :: HostName
, socketPortNum :: PortNumber
, socketProtocolId :: ProtocolId
}
deriving instance Show (SocketConfig a)
withSocketChannel
:: SocketConfig t
-> (forall p . Protocol p => ThriftM p SocketChannel t a)
-> IO a
withSocketChannel SocketConfig{..} f =
withSocketChannelIO socketHost socketPortNum $ \ch -> do
withProxy socketProtocolId (go ch f)
where go :: Protocol p
=> SocketChannel t
-> ThriftM p SocketChannel t a
-> Proxy p
-> IO a
go ch f _proxy = runThrift f ch
resulting ' SocketChannel ' to the third argument .
withSocketChannelIO
:: HostName
-> PortNumber
-> (SocketChannel t -> IO a)
-> IO a
withSocketChannelIO host port f = withSocketClient host port $ \sock _ ->
f (SocketChannel sock)
sendBS :: Socket -> BS.ByteString -> IO (Maybe ChannelException)
sendBS sock bs = try (sendAll sock bs) >>= \res -> case res of
Left e -> return (Just e)
Right _ -> return Nothing
and then call ' ' to grab it .
threadWaitRecv
:: Socket
-> IO BS.ByteString
threadWaitRecv sock numBytes = withFdSocket sock $ \fd ->
threadWaitRead (Fd fd) >> recv sock numBytes
withSocketClient
:: HostName
-> PortNumber
-> (Socket -> AddrInfo -> IO a)
-> IO a
withSocketClient host port f = withSocketsDo $ do
addr <- resolveClient host port
bracket (setupClientSock addr) teardownSock $ \sock ->
f sock addr
setupClientSock :: AddrInfo -> IO Socket
setupClientSock addr = do
s <- openSocket addr
connect s (addrAddress addr)
return s
teardownSock :: Socket -> IO ()
teardownSock sock = shutdown sock ShutdownBoth `finally` close sock
resolveClient :: HostName -> PortNumber -> IO AddrInfo
resolveClient host port = do
results <- getAddrInfo (Just hints) (Just host) (Just $ show port)
case results of
[] -> error $ "SocketChannel.resolveClient: " <>
"getAddrInfo returned an empty list"
(a:_) -> return a
where hints = defaultHints { addrSocketType = Stream }
localhost :: HostName
localhost =
#ifdef IPV4
"127.0.0.1"
#else
"::1"
#endif
recvBlockBytes :: Int
recvBlockBytes = 4096
#if !MIN_VERSION_network(3,1,2)
openSocket :: AddrInfo -> IO Socket
openSocket addr =
socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
#endif
|
97d5420368737aa98311861f4b40e92db0ca0eb38c03dd8875e8a63be7d9bfcc | ninjudd/cake | version_test.clj | (ns cake.tasks.version-test
(:use clojure.test helpers
[cake.file :only [file]])
(:require [clojure.java.io :as io]))
(comment
(defn version-wrap [f]
(cake "version" "0.1.0-SNAPSHOT")
(f)
(cake "version" "0.1.0-SNAPSHOT"))
(use-fixtures :once in-test-project)
(use-fixtures :each version-wrap)
(defn assert-version [expected & [task-output]]
(let [results (cake "version")]
(testing "in current results from 'cake version'"
(is (= (str "test-example " expected "\n")
(:out results))))
(testing "in defproject contents"
(is (= (str "(defproject test-example \"" expected "\"")
(first (line-seq (io/reader (file "project.clj")))))))
(when task-output
(testing "in output of called task"
(is (re-matches (re-pattern (str ".*-> test-example " expected "\n"))
(:out task-output)))))))
(deftest initial-version
(testing "initial version is set to 0.1.0-SNAPSHOT by fixture"
(assert-version "0.1.0-SNAPSHOT")))
(deftest explicit-version
(testing "version set to 2.0.0"
(let [results (cake "version" "2.0.0")]
(assert-version "2.0.0"))))
(deftest version-bumping-test
(testing "version set with cake version bump"
(let [results (cake "version" "bump")]
(assert-version "0.1.0" results)))
(testing "version set with cake version bump --major"
(let [results (cake "version" "bump" "--major")]
(assert-version "1.1.0" results)))
(testing "version set with cake version bump --minor"
(let [results (cake "version" "bump" "--minor")]
(assert-version "1.2.0" results)))
(testing "version set with cake version bump --patch"
(let [results (cake "version" "bump" "--patch")]
(assert-version "1.2.1" results)))
(testing "version set with cake version bump --major --patch"
(let [results (cake "version" "bump" "--major" "--patch")]
(assert-version "2.2.2" results)))
(testing "version set with cake version bump --snapshot"
(let [results (cake "version" "bump" "--snapshot")]
(assert-version "2.2.2-SNAPSHOT" results)))
(testing "version set with cake version bump --major --snapshot"
(let [results (cake "version" "bump" "--major" "--snapshot")]
(assert-version "3.2.2-SNAPSHOT" results)))))
| null | https://raw.githubusercontent.com/ninjudd/cake/3a1627120b74e425ab21aa4d1b263be09e945cfd/test/old/cake/tasks/version_test.clj | clojure | (ns cake.tasks.version-test
(:use clojure.test helpers
[cake.file :only [file]])
(:require [clojure.java.io :as io]))
(comment
(defn version-wrap [f]
(cake "version" "0.1.0-SNAPSHOT")
(f)
(cake "version" "0.1.0-SNAPSHOT"))
(use-fixtures :once in-test-project)
(use-fixtures :each version-wrap)
(defn assert-version [expected & [task-output]]
(let [results (cake "version")]
(testing "in current results from 'cake version'"
(is (= (str "test-example " expected "\n")
(:out results))))
(testing "in defproject contents"
(is (= (str "(defproject test-example \"" expected "\"")
(first (line-seq (io/reader (file "project.clj")))))))
(when task-output
(testing "in output of called task"
(is (re-matches (re-pattern (str ".*-> test-example " expected "\n"))
(:out task-output)))))))
(deftest initial-version
(testing "initial version is set to 0.1.0-SNAPSHOT by fixture"
(assert-version "0.1.0-SNAPSHOT")))
(deftest explicit-version
(testing "version set to 2.0.0"
(let [results (cake "version" "2.0.0")]
(assert-version "2.0.0"))))
(deftest version-bumping-test
(testing "version set with cake version bump"
(let [results (cake "version" "bump")]
(assert-version "0.1.0" results)))
(testing "version set with cake version bump --major"
(let [results (cake "version" "bump" "--major")]
(assert-version "1.1.0" results)))
(testing "version set with cake version bump --minor"
(let [results (cake "version" "bump" "--minor")]
(assert-version "1.2.0" results)))
(testing "version set with cake version bump --patch"
(let [results (cake "version" "bump" "--patch")]
(assert-version "1.2.1" results)))
(testing "version set with cake version bump --major --patch"
(let [results (cake "version" "bump" "--major" "--patch")]
(assert-version "2.2.2" results)))
(testing "version set with cake version bump --snapshot"
(let [results (cake "version" "bump" "--snapshot")]
(assert-version "2.2.2-SNAPSHOT" results)))
(testing "version set with cake version bump --major --snapshot"
(let [results (cake "version" "bump" "--major" "--snapshot")]
(assert-version "3.2.2-SNAPSHOT" results)))))
| |
c93ff235ecd1afe233096671415c34399f5a3b07b92dfdedaa5a272bc6f15c74 | GaloisInc/daedalus | Results.hs | {-# Language ImplicitParams #-}
module Results where
import Control.Monad(forM_)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Data.Text.Encoding as Text
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List.NonEmpty(toList)
import System.Console.ANSI
import System.IO(withBinaryFile, IOMode(WriteMode))
import qualified System.Directory as Dir
import System.FilePath((</>))
import Hexdump
import AlexTools
import qualified RTS.Annot as RTS
import qualified RTS.ParseError as RTS
import qualified RTS.ParserAPI as RTS
import qualified Daedalus.RTS.JSON as RTS
import qualified Daedalus.RTS.HasInputs as RTS
import qualified Daedalus.RTS.Input as RTS
import Daedalus.PP
import Daedalus.Parser.Lexer
import Daedalus.Value
import Daedalus.Interp.ErrorTrie(parseErrorTrieToJSON)
import Daedalus.Interp.DebugAnnot
import Templates
import CommandLine
-- | Show the results of running the interpreter.
-- Returns `True` if successful, or `False` on parse error
dumpResult ::
(?opts :: Options, GroupedErr e) => (a -> Doc) -> RTS.ResultG e a -> Doc
dumpResult ppVal r =
case r of
RTS.NoResults err -> dumpErr err
RTS.Results as -> dumpValues ppVal' (toList as)
where
ppVal' (a,x) = ppVal a -- $$ "----" $$ RTS.ppInputTrace x
-- | Show some parsed values
dumpValues :: (?opts :: Options) => (a -> Doc) -> [a] -> Doc
dumpValues ppVal as
| optShowJS ?opts = brackets (vcat $ punctuate comma $ map ppVal as)
| otherwise =
vcat [ "--- Found" <+> int (length as) <+> "results:"
, vcat' (map ppVal as)
]
-- | Show the value of the interpreter either pretty printed or in JSON
dumpInterpVal :: (?opts :: Options) => Value -> Doc
dumpInterpVal = if optShowJS ?opts then valueToJS else pp
{- | Show the errors either pretty printed or in JSON
Note that the detailed error directory is handed in `saveDetailedError`,
not here. -}
dumpErr ::
(?opts :: Options, GroupedErr e) =>
RTS.ParseErrorG e -> Doc
dumpErr err
| optShowJS ?opts = RTS.jsToDoc (RTS.toJSON err)
| otherwise =
vcat
[ "--- Parse error: "
, text (show (RTS.ppParseError err))
, "File context:"
, text (prettyHexCfg cfg ctx)
]
where
ctxtAmt = 32
bs = RTS.inputTopBytes (RTS.peInput err)
errLoc = RTS.peOffset err
start = max 0 (errLoc - ctxtAmt)
end = errLoc + 10
len = end - start
ctx = BS.take len (BS.drop start bs)
startErr =
setSGRCode [ SetConsoleIntensity
BoldIntensity
, SetColor Foreground Vivid Red ]
endErr = setSGRCode [ Reset ]
cfg = defaultCfg { startByte = start
, transformByte =
wrapRange startErr endErr
errLoc errLoc }
--------------------------------------------------------------------------------
-- Package up detailed errors
-- | Create an output directory with details about a failed parse.
saveDetailedError ::
(?opts :: Options, GroupedErr e) => [FilePath] -> RTS.ParseErrorG e -> IO ()
saveDetailedError srcs err =
case optDetailedErrors ?opts of
Nothing -> pure ()
Just dir ->
do Dir.createDirectoryIfMissing True dir
doFiles dir srcs
doDetailedErr dir err
forM_ error_viewer_files \(name,bytes) ->
BS.writeFile (dir </> name) bytes
--------------------------------------------------------------------------------
-- Make error file
doDetailedErr :: (GroupedErr e) => FilePath -> RTS.ParseErrorG e -> IO ()
doDetailedErr outDir err =
do let outFile = outDir </> "parse_error.js"
withBinaryFile outFile WriteMode \h ->
do BS8.hPutStrLn h "const parseError ="
BS8.hPutStrLn h (RTS.jsonToBytes (jsGrouped err))
class (RTS.HasInputs e, RTS.IsAnnotation e) => GroupedErr e where
jsGrouped :: RTS.ParseErrorG e -> RTS.JSON
instance GroupedErr DebugAnnot where
jsGrouped = parseErrorTrieToJSON
instance GroupedErr RTS.Annotation where
jsGrouped = RTS.toJSON
--------------------------------------------------------------------------------
-- Syntax highlighting
-- | Save syntax highlighted source files in `source_files.json`
doFiles :: FilePath -> [FilePath] -> IO ()
doFiles outDir filePaths =
do fs <- mapM doFile filePaths
let norm = RTS.normalizePathFun (Set.fromList (map fst fs))
key = Text.encodeUtf8 . Text.pack . norm
let mp = RTS.jsObject [ (key f, j) | (f,j) <- fs ]
let outFile = outDir </> "source_files.js"
withBinaryFile outFile WriteMode \h ->
do BS8.hPutStrLn h "const files ="
BS8.hPutStrLn h (RTS.jsonToBytes mp)
| Synatx highlighting for a file .
doFile :: FilePath -> IO (FilePath, RTS.JSON)
doFile file =
do txt <- Text.readFile file
let nm = Text.pack file
let ts = lexer nm txt
a <- Dir.canonicalizePath file
pure ( a
, RTS.jsObject [ ("text", RTS.toJSON txt)
, ("syntax", jsLexemes ts)
]
)
jsLexemes :: [Lexeme Token] -> RTS.JSON
jsLexemes ls =
RTS.jsObject
[ (BS8.pack k, RTS.jsArray v)
| (k,v) <- Map.toList $ Map.delete "" $ Map.fromListWith (++) $ map toMap ls
]
where
rng p = RTS.jsArray [ RTS.toJSON (sourceLine p)
, RTS.toJSON (sourceColumn p) ]
toMap l =
let t = lexemeToken l
r = lexemeRange l
in (tokenClass t, [ RTS.jsArray [ rng (sourceFrom r), rng (sourceTo r) ]])
type Class = String
clIdent, clLiteral, clPunct, clOp, clKW, clType, clNone :: Class
clIdent = "identifier"
clLiteral = "literal"
clPunct = "punctuation"
clOp = "operator"
clKW = "keyword"
clType = "type"
clNone = ""
tokenClass :: Token -> Class
tokenClass tok =
case tok of
BigIdent -> clIdent
SmallIdent -> clIdent
SetIdent -> clIdent
SmallIdentI -> clIdent
BigIdentI -> clIdent
SetIdentI -> clIdent
Number {} -> clLiteral
Bytes {} -> clLiteral
Byte {} -> clLiteral
OpenBrace -> clPunct
CloseBrace -> clPunct
OpenBraceBar -> clPunct
CloseBraceBar -> clPunct
OpenParen -> clPunct
CloseParen -> clPunct
OpenBracket -> clPunct
CloseBracket -> clPunct
OpenTri -> clPunct
CloseTri -> clPunct
VOpen -> clNone
VSemi -> clNone
VClose -> clNone
Semi -> clPunct
Colon -> clPunct
Dot -> clPunct
DotDot -> clPunct
Comma -> clPunct
AtSign -> clPunct
Equals -> clPunct
DoubleEquals -> clOp
BangEquals -> clOp
Bang -> clOp
Hat -> clOp
Bar -> clOp
DotBarDot -> clOp
DotAmpDot -> clOp
DotHatDot -> clOp
BarBar -> clOp
AmpAmp -> clOp
LtBar -> clOp
Dollar -> clPunct
DollarDollar -> clPunct
Plus -> clOp
Minus -> clOp
Star -> clOp
ForwardSlash -> clOp
Percent -> clOp
TokLeq -> clOp
TokGeq -> clOp
Hash -> clOp
LeftHash -> clOp
ShiftL -> clOp
ShiftR -> clOp
RightArrow -> clPunct
Underscore -> clPunct
BitwiseComplementT -> clOp
KWstruct -> clKW
KWunion -> clKW
KWChoose -> clKW
KWFirst -> clKW
KWAccept -> clKW
KWblock -> clKW
KWlet -> clKW
KWTry -> clKW
KWMatch -> clKW
KWMany -> clKW
KWManyQuestion -> clKW
KWmany -> clKW
KWmanyQuestion -> clKW
KWOptional -> clKW
KWOptionalQuestion -> clKW
KWUInt8 -> clKW
KWTrue -> clKW -- or literal?
KWFalse -> clKW -- or literal?
KWFor -> clKW
KWMap -> clKW
KWIn -> clKW
KWIs -> clKW
KWOf -> clKW
KWInt -> clType
KWUInt -> clType
KWSInt -> clType
KWFloat -> clType
KWDouble -> clType
KWBool -> clType
KWMaybe -> clType
KWStream -> clType
KWIf -> clKW
KWThen -> clKW
KWElse -> clKW
KWImport -> clKW
KWExtern -> clKW
KWAs -> clKW
KWAsBang -> clKW
KWAsQuestion -> clKW
KWConcat -> clIdent
KWEND -> clKW
KWCOMMIT -> clKW
KWMapEmpty -> clIdent
KWMapInsert -> clIdent
KWMapinsert -> clIdent
KWMapLookup -> clIdent
KWMaplookup -> clIdent
KWArrayLength -> clIdent
KWArrayIndex -> clIdent
KWRangeUp -> clIdent
KWRangeDown -> clIdent
KWOffset -> clIdent
KWDollarAny -> clIdent
KWGetStream -> clIdent
KWSetStream -> clIdent
KWTake -> clIdent
KWDrop -> clIdent
KWJust -> clKW
KWNothing -> clKW
KWBuilderbuild -> clIdent
KWBuilderemit -> clIdent
KWBuilderemitArray -> clIdent
KWBuilderemitBuilder -> clIdent
KWBuilderbuilder -> clIdent
KWDef -> clKW
KWArrayStream -> clIdent
KWBytesOfStream -> clIdent
KWFail -> clKW
KWCase -> clKW
KWBitData -> clKW
KWWhere -> clKW
KWpi -> clLiteral
KWWordToFloat -> clIdent
KWWordToDouble -> clIdent
KWIsNaN -> clIdent
KWIsInfinite -> clIdent
KWIsDenormalized -> clIdent
KWIsNegativeZero -> clIdent
TokError {} -> clNone
TokEOF -> clNone
| null | https://raw.githubusercontent.com/GaloisInc/daedalus/3f180d29441960e35386654ec79a2b205bddc157/exe/Results.hs | haskell | # Language ImplicitParams #
| Show the results of running the interpreter.
Returns `True` if successful, or `False` on parse error
$$ "----" $$ RTS.ppInputTrace x
| Show some parsed values
| Show the value of the interpreter either pretty printed or in JSON
| Show the errors either pretty printed or in JSON
Note that the detailed error directory is handed in `saveDetailedError`,
not here.
------------------------------------------------------------------------------
Package up detailed errors
| Create an output directory with details about a failed parse.
------------------------------------------------------------------------------
Make error file
------------------------------------------------------------------------------
Syntax highlighting
| Save syntax highlighted source files in `source_files.json`
or literal?
or literal? | module Results where
import Control.Monad(forM_)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Data.Text.Encoding as Text
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List.NonEmpty(toList)
import System.Console.ANSI
import System.IO(withBinaryFile, IOMode(WriteMode))
import qualified System.Directory as Dir
import System.FilePath((</>))
import Hexdump
import AlexTools
import qualified RTS.Annot as RTS
import qualified RTS.ParseError as RTS
import qualified RTS.ParserAPI as RTS
import qualified Daedalus.RTS.JSON as RTS
import qualified Daedalus.RTS.HasInputs as RTS
import qualified Daedalus.RTS.Input as RTS
import Daedalus.PP
import Daedalus.Parser.Lexer
import Daedalus.Value
import Daedalus.Interp.ErrorTrie(parseErrorTrieToJSON)
import Daedalus.Interp.DebugAnnot
import Templates
import CommandLine
dumpResult ::
(?opts :: Options, GroupedErr e) => (a -> Doc) -> RTS.ResultG e a -> Doc
dumpResult ppVal r =
case r of
RTS.NoResults err -> dumpErr err
RTS.Results as -> dumpValues ppVal' (toList as)
where
dumpValues :: (?opts :: Options) => (a -> Doc) -> [a] -> Doc
dumpValues ppVal as
| optShowJS ?opts = brackets (vcat $ punctuate comma $ map ppVal as)
| otherwise =
vcat [ "--- Found" <+> int (length as) <+> "results:"
, vcat' (map ppVal as)
]
dumpInterpVal :: (?opts :: Options) => Value -> Doc
dumpInterpVal = if optShowJS ?opts then valueToJS else pp
dumpErr ::
(?opts :: Options, GroupedErr e) =>
RTS.ParseErrorG e -> Doc
dumpErr err
| optShowJS ?opts = RTS.jsToDoc (RTS.toJSON err)
| otherwise =
vcat
[ "--- Parse error: "
, text (show (RTS.ppParseError err))
, "File context:"
, text (prettyHexCfg cfg ctx)
]
where
ctxtAmt = 32
bs = RTS.inputTopBytes (RTS.peInput err)
errLoc = RTS.peOffset err
start = max 0 (errLoc - ctxtAmt)
end = errLoc + 10
len = end - start
ctx = BS.take len (BS.drop start bs)
startErr =
setSGRCode [ SetConsoleIntensity
BoldIntensity
, SetColor Foreground Vivid Red ]
endErr = setSGRCode [ Reset ]
cfg = defaultCfg { startByte = start
, transformByte =
wrapRange startErr endErr
errLoc errLoc }
saveDetailedError ::
(?opts :: Options, GroupedErr e) => [FilePath] -> RTS.ParseErrorG e -> IO ()
saveDetailedError srcs err =
case optDetailedErrors ?opts of
Nothing -> pure ()
Just dir ->
do Dir.createDirectoryIfMissing True dir
doFiles dir srcs
doDetailedErr dir err
forM_ error_viewer_files \(name,bytes) ->
BS.writeFile (dir </> name) bytes
doDetailedErr :: (GroupedErr e) => FilePath -> RTS.ParseErrorG e -> IO ()
doDetailedErr outDir err =
do let outFile = outDir </> "parse_error.js"
withBinaryFile outFile WriteMode \h ->
do BS8.hPutStrLn h "const parseError ="
BS8.hPutStrLn h (RTS.jsonToBytes (jsGrouped err))
class (RTS.HasInputs e, RTS.IsAnnotation e) => GroupedErr e where
jsGrouped :: RTS.ParseErrorG e -> RTS.JSON
instance GroupedErr DebugAnnot where
jsGrouped = parseErrorTrieToJSON
instance GroupedErr RTS.Annotation where
jsGrouped = RTS.toJSON
doFiles :: FilePath -> [FilePath] -> IO ()
doFiles outDir filePaths =
do fs <- mapM doFile filePaths
let norm = RTS.normalizePathFun (Set.fromList (map fst fs))
key = Text.encodeUtf8 . Text.pack . norm
let mp = RTS.jsObject [ (key f, j) | (f,j) <- fs ]
let outFile = outDir </> "source_files.js"
withBinaryFile outFile WriteMode \h ->
do BS8.hPutStrLn h "const files ="
BS8.hPutStrLn h (RTS.jsonToBytes mp)
| Synatx highlighting for a file .
doFile :: FilePath -> IO (FilePath, RTS.JSON)
doFile file =
do txt <- Text.readFile file
let nm = Text.pack file
let ts = lexer nm txt
a <- Dir.canonicalizePath file
pure ( a
, RTS.jsObject [ ("text", RTS.toJSON txt)
, ("syntax", jsLexemes ts)
]
)
jsLexemes :: [Lexeme Token] -> RTS.JSON
jsLexemes ls =
RTS.jsObject
[ (BS8.pack k, RTS.jsArray v)
| (k,v) <- Map.toList $ Map.delete "" $ Map.fromListWith (++) $ map toMap ls
]
where
rng p = RTS.jsArray [ RTS.toJSON (sourceLine p)
, RTS.toJSON (sourceColumn p) ]
toMap l =
let t = lexemeToken l
r = lexemeRange l
in (tokenClass t, [ RTS.jsArray [ rng (sourceFrom r), rng (sourceTo r) ]])
type Class = String
clIdent, clLiteral, clPunct, clOp, clKW, clType, clNone :: Class
clIdent = "identifier"
clLiteral = "literal"
clPunct = "punctuation"
clOp = "operator"
clKW = "keyword"
clType = "type"
clNone = ""
tokenClass :: Token -> Class
tokenClass tok =
case tok of
BigIdent -> clIdent
SmallIdent -> clIdent
SetIdent -> clIdent
SmallIdentI -> clIdent
BigIdentI -> clIdent
SetIdentI -> clIdent
Number {} -> clLiteral
Bytes {} -> clLiteral
Byte {} -> clLiteral
OpenBrace -> clPunct
CloseBrace -> clPunct
OpenBraceBar -> clPunct
CloseBraceBar -> clPunct
OpenParen -> clPunct
CloseParen -> clPunct
OpenBracket -> clPunct
CloseBracket -> clPunct
OpenTri -> clPunct
CloseTri -> clPunct
VOpen -> clNone
VSemi -> clNone
VClose -> clNone
Semi -> clPunct
Colon -> clPunct
Dot -> clPunct
DotDot -> clPunct
Comma -> clPunct
AtSign -> clPunct
Equals -> clPunct
DoubleEquals -> clOp
BangEquals -> clOp
Bang -> clOp
Hat -> clOp
Bar -> clOp
DotBarDot -> clOp
DotAmpDot -> clOp
DotHatDot -> clOp
BarBar -> clOp
AmpAmp -> clOp
LtBar -> clOp
Dollar -> clPunct
DollarDollar -> clPunct
Plus -> clOp
Minus -> clOp
Star -> clOp
ForwardSlash -> clOp
Percent -> clOp
TokLeq -> clOp
TokGeq -> clOp
Hash -> clOp
LeftHash -> clOp
ShiftL -> clOp
ShiftR -> clOp
RightArrow -> clPunct
Underscore -> clPunct
BitwiseComplementT -> clOp
KWstruct -> clKW
KWunion -> clKW
KWChoose -> clKW
KWFirst -> clKW
KWAccept -> clKW
KWblock -> clKW
KWlet -> clKW
KWTry -> clKW
KWMatch -> clKW
KWMany -> clKW
KWManyQuestion -> clKW
KWmany -> clKW
KWmanyQuestion -> clKW
KWOptional -> clKW
KWOptionalQuestion -> clKW
KWUInt8 -> clKW
KWFor -> clKW
KWMap -> clKW
KWIn -> clKW
KWIs -> clKW
KWOf -> clKW
KWInt -> clType
KWUInt -> clType
KWSInt -> clType
KWFloat -> clType
KWDouble -> clType
KWBool -> clType
KWMaybe -> clType
KWStream -> clType
KWIf -> clKW
KWThen -> clKW
KWElse -> clKW
KWImport -> clKW
KWExtern -> clKW
KWAs -> clKW
KWAsBang -> clKW
KWAsQuestion -> clKW
KWConcat -> clIdent
KWEND -> clKW
KWCOMMIT -> clKW
KWMapEmpty -> clIdent
KWMapInsert -> clIdent
KWMapinsert -> clIdent
KWMapLookup -> clIdent
KWMaplookup -> clIdent
KWArrayLength -> clIdent
KWArrayIndex -> clIdent
KWRangeUp -> clIdent
KWRangeDown -> clIdent
KWOffset -> clIdent
KWDollarAny -> clIdent
KWGetStream -> clIdent
KWSetStream -> clIdent
KWTake -> clIdent
KWDrop -> clIdent
KWJust -> clKW
KWNothing -> clKW
KWBuilderbuild -> clIdent
KWBuilderemit -> clIdent
KWBuilderemitArray -> clIdent
KWBuilderemitBuilder -> clIdent
KWBuilderbuilder -> clIdent
KWDef -> clKW
KWArrayStream -> clIdent
KWBytesOfStream -> clIdent
KWFail -> clKW
KWCase -> clKW
KWBitData -> clKW
KWWhere -> clKW
KWpi -> clLiteral
KWWordToFloat -> clIdent
KWWordToDouble -> clIdent
KWIsNaN -> clIdent
KWIsInfinite -> clIdent
KWIsDenormalized -> clIdent
KWIsNegativeZero -> clIdent
TokError {} -> clNone
TokEOF -> clNone
|
dc7adccd53754d6ddf521b42fac92b2a37b29374b668b2fc291c74a772ad6515 | escherize/data-desk | config.cljs | (ns data-desk.config)
(def debug?
^boolean goog.DEBUG)
| null | https://raw.githubusercontent.com/escherize/data-desk/db3a27ed7f63bbbaa573ae7ea103e35044a0625a/src/data_desk/config.cljs | clojure | (ns data-desk.config)
(def debug?
^boolean goog.DEBUG)
| |
eb1e09f967d65900c3a00880702aecf81b30cc323c90f713a6272e0425c44bb7 | williamleferrand/accretio | ys_react.ml |
* Accretio is an API , a sandbox and a runtime for social playbooks
*
* Copyright ( C ) 2015
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation , either version 3 of the
* License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Affero General Public License for more details .
*
* You should have received a copy of the GNU Affero General Public License
* along with this program . If not , see < / > .
* Accretio is an API, a sandbox and a runtime for social playbooks
*
* Copyright (C) 2015 William Le Ferrand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see </>.
*)
open Lwt
open React
open Eliom_content.Html5
open Eliom_content.Html5.D
module RInt =
struct
type t =
{
s : int S.t ;
update : int -> unit ;
}
let create () =
let s, update = S.create 0 in
{ s; update }
let init i =
let s, update = S.create i in
{ s; update }
let incr t =
t.update (S.value t.s + 1)
let update t =
t.update
let decr t =
t.update (S.value t.s - 1)
let map t f =
S.map f t.s
let iter t f =
(* I still don't have a clear understanding of what happens here, gc-wise *)
ignore (map f t)
let map_in_div ?(a=[]) f t =
R.node (S.map (fun i -> div ~a [ f i ]) t.s)
let channel t = t.s
let to_pcdata t =
R.node (S.map (fun i -> pcdata (string_of_int i)) t.s)
end
module RListUnique =
struct
type ('a, 'b) t =
{
s: 'a list S.t ;
update : 'a list -> unit ;
extract : 'a -> 'b ;
keys : ('b, unit) Hashtbl.t ;
}
let create ~extract () =
let s, update = S.create [] in
{
s ; update ; extract ; keys = Hashtbl.create 0
}
let init ~extract l =
let s, update = S.create l in
let keys = Hashtbl.create 0 in
List.iter (fun e -> Hashtbl.add keys (extract e) ()) l ;
{
s ; update ; extract ; keys ;
}
let mem t key =
Hashtbl.mem t.keys key
let add t e =
let key = t.extract e in
if not (Hashtbl.mem t.keys key) then
begin
Hashtbl.add t.keys key () ;
t.update (e :: S.value t.s)
end
let replace t l =
Hashtbl.clear t.keys ;
List.iter (fun e -> Hashtbl.add t.keys (t.extract e) ()) l ;
t.update l
let clear t =
Hashtbl.clear t.keys ;
t.update []
let append t l =
let l = List.filter (fun e -> not (Hashtbl.mem t.keys (t.extract e))) l in
List.iter (fun e -> Hashtbl.add t.keys (t.extract e) ()) l ;
t.update (l @ S.value t.s)
let remove t key =
Hashtbl.remove t.keys key ;
t.update (List.filter (fun e -> t.extract e <> key) (S.value t.s))
let map_l f t =
S.map (List.map f) t.s
let channel t = t.s
let length t = List.length (S.value t.s)
let fold_left_in_div ?(hook=(fun () -> ())) ?(a=[]) t f acc =
R.node
(S.map
(function
| [] -> pcdata ""
| _ as l ->
(* hook (); *)
div ~a (List.fold_left f acc l))
t.s)
let map_in_div ?(a=[]) ?(empty_placeholder=[]) f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l -> div ~a (List.map f l)) t.s)
let map_in_div_head ?(a=[]) ?(empty_placeholder=[]) head f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l -> div ~a (head :: List.map f l)) t.s)
let map_in_div_ ?(a=[]) ?(empty_placeholder=[]) f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l -> div ~a (List.map (f (mem t)) l)) t.s)
let map_in_div_with_hook ?(a=[]) ?(empty_placeholder=[]) hook f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l ->
let d = div ~a (List.map f l) in
(* hook d; *)
d)
t.s)
let to_list t =
S.value t.s
end
module RList =
struct
type 'a t =
{
s : 'a list S.t ;
update : 'a list -> unit ;
}
let create ?eq () =
let s, update = S.create ?eq [] in
{ s; update }
let init l =
let s, update = S.create l in
{ s; update }
let reset t =
t.update []
let is_empty_signal t =
S.map (function [] -> true | _ -> false) t.s
let channel t = t.s
let add t e =
t.update (e :: S.value t.s)
let add_all t e =
t.update (e @ S.value t.s)
let add_all_unique noteq t e =
t.update
(List.fold_left
(fun acc e -> e :: (List.filter (noteq e) acc))
(S.value t.s)
e)
let append t e =
t.update (e :: S.value t.s)
let append_end t e =
t.update (S.value t.s @ [ e ])
let append_unique neq t e =
t.update (e :: List.filter neq (S.value t.s))
let append_all t e =
t.update (S.value t.s @ e)
let fill t l =
t.update l
let update t l =
t.update l
let remove t e =
t.update (List.filter ((<>) e) (S.value t.s))
let filter t f =
t.update (List.filter f (S.value t.s))
let insert cmp t e =
let rec insert = function
| [] -> [ e ]
| t::q when cmp t e < 0 -> t :: insert q
| t::q -> e :: t :: q
in
t.update (insert (S.value t.s))
let map_in_div ?(a=[]) ?(empty_placeholder=[]) f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l -> div ~a (List.map f l)) t.s)
let map_in_div_ordered ?(a=[]) ?(empty_placeholder=[]) f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l ->
let l = List.fast_sort (fun a b -> compare (fst a) (fst b)) l in
div ~a (List.map f l)) t.s)
let fold_in_div ?(a=[]) f acc t =
R.node (S.map (fun l -> div ~a (List.fold_left f acc l)) t.s)
let map_in_div_hd ?(a=[]) hd f t =
R.node (S.map (fun l -> div ~a (hd :: List.map f l)) t.s)
let map_in_div_tl ?(a=[]) tl f t =
R.node (S.map (fun l -> div ~a (List.map f l @ [ tl ])) t.s)
let map_in_div_rev ?(a=[]) f t =
R.node (S.map (fun l -> div ~a (List.fold_left (fun acc v -> f v :: acc) [] l)) t.s)
let map_in_div2 ?(a=[]) f s t =
R.node (S.l2 (fun l2 l -> div ~a (List.map (f l2) l)) s t.s)
let is_empty t =
match S.value t.s with
| [] -> true
| _ -> false
let to_list t = S.value t.s
let flatten f t =
List.fold_left
(fun acc e ->
match f e with
None -> acc
| Some b -> b :: acc)
[]
(S.value t.s)
(* mappers, experimental, will change **)
let iter_s_without_first_update f t =
let is_start = ref true in
Lwt_react.S.map_s
(fun l -> match !is_start with
true -> is_start := false; return_unit
| false -> f l) t.s
>>= fun r -> Lwt_react.S.keep r; return_unit
let map_s f t = Lwt_react.S.map_s f t.s
let iter_s f t = Lwt_react.S.map_s f t.s
>>= fun r -> Lwt_react.S.keep r; return_unit
let map f t =
S.map f t.s
let map_l f t =
S.map (List.map f) t.s
end
module R =
struct
let node_s s =
let content, update_content = S.create (div []) in
Lwt.ignore_result
(s >>= fun s ->
Lwt_react.S.map_s
(fun c -> update_content c; return_unit)
s);
R.node content
include R
end
open Lwt_stream
open Lwt_react
module Down =
struct
type 'a t = 'a Lwt_stream.result React.E.t
let internal_unwrap ( channel, unwrapper ) =
E.of_stream (Lwt_stream.map_exn channel)
(* super unsafe ... *)
let () =
Eliom_unwrap.register_unwrapper
(Eliom_unwrap.id_of_int Ys_bandaid.react_down_unwrap_id_int)
internal_unwrap
end
| null | https://raw.githubusercontent.com/williamleferrand/accretio/394f855e9c2a6a18f0c2da35058d5a01aacf6586/library/client/ys_react.ml | ocaml | I still don't have a clear understanding of what happens here, gc-wise
hook ();
hook d;
mappers, experimental, will change *
super unsafe ... |
* Accretio is an API , a sandbox and a runtime for social playbooks
*
* Copyright ( C ) 2015
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation , either version 3 of the
* License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Affero General Public License for more details .
*
* You should have received a copy of the GNU Affero General Public License
* along with this program . If not , see < / > .
* Accretio is an API, a sandbox and a runtime for social playbooks
*
* Copyright (C) 2015 William Le Ferrand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see </>.
*)
open Lwt
open React
open Eliom_content.Html5
open Eliom_content.Html5.D
module RInt =
struct
type t =
{
s : int S.t ;
update : int -> unit ;
}
let create () =
let s, update = S.create 0 in
{ s; update }
let init i =
let s, update = S.create i in
{ s; update }
let incr t =
t.update (S.value t.s + 1)
let update t =
t.update
let decr t =
t.update (S.value t.s - 1)
let map t f =
S.map f t.s
let iter t f =
ignore (map f t)
let map_in_div ?(a=[]) f t =
R.node (S.map (fun i -> div ~a [ f i ]) t.s)
let channel t = t.s
let to_pcdata t =
R.node (S.map (fun i -> pcdata (string_of_int i)) t.s)
end
module RListUnique =
struct
type ('a, 'b) t =
{
s: 'a list S.t ;
update : 'a list -> unit ;
extract : 'a -> 'b ;
keys : ('b, unit) Hashtbl.t ;
}
let create ~extract () =
let s, update = S.create [] in
{
s ; update ; extract ; keys = Hashtbl.create 0
}
let init ~extract l =
let s, update = S.create l in
let keys = Hashtbl.create 0 in
List.iter (fun e -> Hashtbl.add keys (extract e) ()) l ;
{
s ; update ; extract ; keys ;
}
let mem t key =
Hashtbl.mem t.keys key
let add t e =
let key = t.extract e in
if not (Hashtbl.mem t.keys key) then
begin
Hashtbl.add t.keys key () ;
t.update (e :: S.value t.s)
end
let replace t l =
Hashtbl.clear t.keys ;
List.iter (fun e -> Hashtbl.add t.keys (t.extract e) ()) l ;
t.update l
let clear t =
Hashtbl.clear t.keys ;
t.update []
let append t l =
let l = List.filter (fun e -> not (Hashtbl.mem t.keys (t.extract e))) l in
List.iter (fun e -> Hashtbl.add t.keys (t.extract e) ()) l ;
t.update (l @ S.value t.s)
let remove t key =
Hashtbl.remove t.keys key ;
t.update (List.filter (fun e -> t.extract e <> key) (S.value t.s))
let map_l f t =
S.map (List.map f) t.s
let channel t = t.s
let length t = List.length (S.value t.s)
let fold_left_in_div ?(hook=(fun () -> ())) ?(a=[]) t f acc =
R.node
(S.map
(function
| [] -> pcdata ""
| _ as l ->
div ~a (List.fold_left f acc l))
t.s)
let map_in_div ?(a=[]) ?(empty_placeholder=[]) f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l -> div ~a (List.map f l)) t.s)
let map_in_div_head ?(a=[]) ?(empty_placeholder=[]) head f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l -> div ~a (head :: List.map f l)) t.s)
let map_in_div_ ?(a=[]) ?(empty_placeholder=[]) f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l -> div ~a (List.map (f (mem t)) l)) t.s)
let map_in_div_with_hook ?(a=[]) ?(empty_placeholder=[]) hook f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l ->
let d = div ~a (List.map f l) in
d)
t.s)
let to_list t =
S.value t.s
end
module RList =
struct
type 'a t =
{
s : 'a list S.t ;
update : 'a list -> unit ;
}
let create ?eq () =
let s, update = S.create ?eq [] in
{ s; update }
let init l =
let s, update = S.create l in
{ s; update }
let reset t =
t.update []
let is_empty_signal t =
S.map (function [] -> true | _ -> false) t.s
let channel t = t.s
let add t e =
t.update (e :: S.value t.s)
let add_all t e =
t.update (e @ S.value t.s)
let add_all_unique noteq t e =
t.update
(List.fold_left
(fun acc e -> e :: (List.filter (noteq e) acc))
(S.value t.s)
e)
let append t e =
t.update (e :: S.value t.s)
let append_end t e =
t.update (S.value t.s @ [ e ])
let append_unique neq t e =
t.update (e :: List.filter neq (S.value t.s))
let append_all t e =
t.update (S.value t.s @ e)
let fill t l =
t.update l
let update t l =
t.update l
let remove t e =
t.update (List.filter ((<>) e) (S.value t.s))
let filter t f =
t.update (List.filter f (S.value t.s))
let insert cmp t e =
let rec insert = function
| [] -> [ e ]
| t::q when cmp t e < 0 -> t :: insert q
| t::q -> e :: t :: q
in
t.update (insert (S.value t.s))
let map_in_div ?(a=[]) ?(empty_placeholder=[]) f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l -> div ~a (List.map f l)) t.s)
let map_in_div_ordered ?(a=[]) ?(empty_placeholder=[]) f t =
R.node
(S.map
(function
[] -> div ~a empty_placeholder
| _ as l ->
let l = List.fast_sort (fun a b -> compare (fst a) (fst b)) l in
div ~a (List.map f l)) t.s)
let fold_in_div ?(a=[]) f acc t =
R.node (S.map (fun l -> div ~a (List.fold_left f acc l)) t.s)
let map_in_div_hd ?(a=[]) hd f t =
R.node (S.map (fun l -> div ~a (hd :: List.map f l)) t.s)
let map_in_div_tl ?(a=[]) tl f t =
R.node (S.map (fun l -> div ~a (List.map f l @ [ tl ])) t.s)
let map_in_div_rev ?(a=[]) f t =
R.node (S.map (fun l -> div ~a (List.fold_left (fun acc v -> f v :: acc) [] l)) t.s)
let map_in_div2 ?(a=[]) f s t =
R.node (S.l2 (fun l2 l -> div ~a (List.map (f l2) l)) s t.s)
let is_empty t =
match S.value t.s with
| [] -> true
| _ -> false
let to_list t = S.value t.s
let flatten f t =
List.fold_left
(fun acc e ->
match f e with
None -> acc
| Some b -> b :: acc)
[]
(S.value t.s)
let iter_s_without_first_update f t =
let is_start = ref true in
Lwt_react.S.map_s
(fun l -> match !is_start with
true -> is_start := false; return_unit
| false -> f l) t.s
>>= fun r -> Lwt_react.S.keep r; return_unit
let map_s f t = Lwt_react.S.map_s f t.s
let iter_s f t = Lwt_react.S.map_s f t.s
>>= fun r -> Lwt_react.S.keep r; return_unit
let map f t =
S.map f t.s
let map_l f t =
S.map (List.map f) t.s
end
module R =
struct
let node_s s =
let content, update_content = S.create (div []) in
Lwt.ignore_result
(s >>= fun s ->
Lwt_react.S.map_s
(fun c -> update_content c; return_unit)
s);
R.node content
include R
end
open Lwt_stream
open Lwt_react
module Down =
struct
type 'a t = 'a Lwt_stream.result React.E.t
let internal_unwrap ( channel, unwrapper ) =
E.of_stream (Lwt_stream.map_exn channel)
let () =
Eliom_unwrap.register_unwrapper
(Eliom_unwrap.id_of_int Ys_bandaid.react_down_unwrap_id_int)
internal_unwrap
end
|
1728344148e7d6e06dfd79f6f594c8ce96845457ec9930d2dc19534c5e78ce60 | McCLIM/McCLIM | menu-frame.lisp | ;;; ---------------------------------------------------------------------------
;;; License: LGPL-2.1+ (See file 'Copyright' for details).
;;; ---------------------------------------------------------------------------
;;;
( c ) copyright 1998,1999,2000 by ( )
( c ) copyright 2000 by Iban Hatchondo ( )
( c ) copyright 2000 by ( )
( c ) copyright 2000 , 2014 by ( )
( c ) copyright 2004 by < >
( c ) copyright 2019 , 2020 Jan Moringen < >
( c ) copyright 2021 < >
;;;
;;; ---------------------------------------------------------------------------
;;;
;;; Menu frame class. This class does not implement fully the application frame
;;; protocol.
;;;
(in-package #:clim-internals)
(defclass menu-frame (application-frame)
((left :initform 0 :initarg :left)
(top :initform 0 :initarg :top)
(min-width :initform nil :initarg :min-width)
(top-level-sheet :initform nil :reader frame-top-level-sheet)
(panes :reader frame-panes :initarg :panes)
(graft :initform nil :accessor graft)
(state :initarg :state
:initform :disowned
:reader frame-state)
(manager :initform nil
:reader frame-manager
:accessor %frame-manager)))
(defclass menu-unmanaged-top-level-sheet-pane (unmanaged-top-level-sheet-pane)
())
(defmethod enable-frame ((frame menu-frame))
(setf (sheet-enabled-p (frame-top-level-sheet frame)) t)
(setf (slot-value frame 'state) :enabled)
(note-frame-enabled (frame-manager frame) frame))
(defmethod disable-frame ((frame menu-frame))
(setf (sheet-enabled-p (frame-top-level-sheet frame)) nil)
(setf (slot-value frame 'state) :disabled)
(note-frame-disabled (frame-manager frame) frame))
(defmethod shrink-frame ((frame menu-frame))
(declare (ignore frame))
(warn "MENU-FRAME can't be shrunk."))
(defun make-menu-frame (pane &key (left 0) (top 0) (min-width 1))
(make-instance 'menu-frame :panes pane :left left :top top :min-width min-width))
| null | https://raw.githubusercontent.com/McCLIM/McCLIM/7c890f1ac79f0c6f36866c47af89398e2f05b343/Core/clim-core/frames/menu-frame.lisp | lisp | ---------------------------------------------------------------------------
License: LGPL-2.1+ (See file 'Copyright' for details).
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Menu frame class. This class does not implement fully the application frame
protocol.
| ( c ) copyright 1998,1999,2000 by ( )
( c ) copyright 2000 by Iban Hatchondo ( )
( c ) copyright 2000 by ( )
( c ) copyright 2000 , 2014 by ( )
( c ) copyright 2004 by < >
( c ) copyright 2019 , 2020 Jan Moringen < >
( c ) copyright 2021 < >
(in-package #:clim-internals)
(defclass menu-frame (application-frame)
((left :initform 0 :initarg :left)
(top :initform 0 :initarg :top)
(min-width :initform nil :initarg :min-width)
(top-level-sheet :initform nil :reader frame-top-level-sheet)
(panes :reader frame-panes :initarg :panes)
(graft :initform nil :accessor graft)
(state :initarg :state
:initform :disowned
:reader frame-state)
(manager :initform nil
:reader frame-manager
:accessor %frame-manager)))
(defclass menu-unmanaged-top-level-sheet-pane (unmanaged-top-level-sheet-pane)
())
(defmethod enable-frame ((frame menu-frame))
(setf (sheet-enabled-p (frame-top-level-sheet frame)) t)
(setf (slot-value frame 'state) :enabled)
(note-frame-enabled (frame-manager frame) frame))
(defmethod disable-frame ((frame menu-frame))
(setf (sheet-enabled-p (frame-top-level-sheet frame)) nil)
(setf (slot-value frame 'state) :disabled)
(note-frame-disabled (frame-manager frame) frame))
(defmethod shrink-frame ((frame menu-frame))
(declare (ignore frame))
(warn "MENU-FRAME can't be shrunk."))
(defun make-menu-frame (pane &key (left 0) (top 0) (min-width 1))
(make-instance 'menu-frame :panes pane :left left :top top :min-width min-width))
|
884c39dee5ca27d81f68edc3b31ea05c2c1cfd169c27e21cdf953e1b95165064 | melhadad/fuf | html.lisp | ;;; -*- Mode:Lisp; Syntax:Common-Lisp; Package: FUG5 -*-
;;; -----------------------------------------------------------------------
;;; File: html.l
;;; Description: Examples for using the HTML attribute
Author :
Created : 2 Jul 1996
;;; Modified:
Package : FUG5
;;; -----------------------------------------------------------------------
(in-package "FUG5")
(format t "~%These examples should only work with SURGE 2.0.~%~
They show how to use the HTML attribute in FUF.")
;; This is all very straightforward except for the use of html-alt instead
of the HTML tag alt to avoid confusion with FUF 's reserved keyword alt .
;; ============================================================
;; HTML examples
;; ============================================================
;; HTML tags go around constituents.
;; HTML tags can have parameters (like the A tag).
(def-test t422
"<A HREF=\"\">I am not a smart man</a>, but I know <B>what love is</B>."
((cat ds)
(subordinate ((cat clause)
(html ((a ((href "")))))
(process ((type ascriptive)))
(polarity negative)
(partic ((carrier ((cat personal-pronoun)
(person first)))
(attribute ((cat common)
(definite no)
(describer === "smart")
(lex "man")))))))
(connective ((lex "but")))
(directive ((cat clause)
(process ((type mental)
(lex "know")))
(partic ((processor ((cat personal-pronoun)
(person first)))
(phenomenon ((cat clause)
(html ((b +)))
(mood bound-nominal)
(binder ((lex "what")))
(controlled {^ partic attribute})
(process ((type ascriptive)))
(partic ((carrier ((cat common)
(lex "love")
(countable no)))))))))))))
(def-test t423-a
"The recipe has 3 steps:"
((cat clause)
(punctuation ((after ":")))
(process ((type possessive)))
(partic
((possessor ((cat common) (lex "recipe") (definite yes)))
(possessed ((cat common) (lex "step") (definite no)
(cardinal ((value 3) (digit yes)))))))))
(def-test t423
"The recipe has 3 steps: <OL><LI>start the fire </LI><LI>burn the olives </LI><LI>eat the pits </LI></OL>."
((cat list)
(distinct
~(
((cat clause)
(punctuation ((after ":")))
(process ((type possessive)))
(partic
((possessor ((cat common) (lex "recipe") (definite yes)))
(possessed ((cat common) (lex "step") (definite no)
(cardinal ((value 3))))))))
((cat list)
(html ((ol +)))
(distinct
~(
((cat clause)
(html ((li +)))
(mood imperative)
(process ((type material) (lex "start")))
(partic ((agent ((cat personal-pronoun) (person second)))
(affected ((cat common) (lex "fire"))))))
((cat clause)
(html ((li +)))
(mood imperative)
(process ((type material) (lex "burn")))
(partic ((agent ((cat personal-pronoun) (person second)))
(affected ((cat common) (lex "olive") (number plural))))))
((cat clause)
(html ((li +)))
(mood imperative)
(process ((type material) (lex "eat")))
(partic
((agent ((cat personal-pronoun) (person second)))
(affected ((cat common) (lex "pit") (number plural)))))))))))))
(def-test t424
"This picture contains the secret <B>for a <I>happy </I> life </B>: <IMG
SRC=\"happy.gif\" ALT=\"HAPPY LIFE SECRET\">."
((cat list)
(distinct
~(
((cat clause)
(proc ((type locative) (mode equative) (lex "contain")))
(partic
((identified ((cat common) (lex "picture") (distance near)))
(identifier ((cat common) (lex "secret")
(qualifier ((cat pp)
(prep ((lex "for")))
(html ((b +)))
(np ((cat common)
(definite no)
(lex "life")
(describer ((html ((i +)))
(lex "happy")))))))))))
(punctuation ((after ":"))))
((cat phrase)
(html ((img ((src "happy.gif")
(end-tag none)
(html-alt "HAPPY LIFE SECRET")))))
(lex ""))))))
| null | https://raw.githubusercontent.com/melhadad/fuf/57bd0e31afc6aaa03b85f45f4c7195af701508b8/examples/html.lisp | lisp | -*- Mode:Lisp; Syntax:Common-Lisp; Package: FUG5 -*-
-----------------------------------------------------------------------
File: html.l
Description: Examples for using the HTML attribute
Modified:
-----------------------------------------------------------------------
This is all very straightforward except for the use of html-alt instead
============================================================
HTML examples
============================================================
HTML tags go around constituents.
HTML tags can have parameters (like the A tag). | Author :
Created : 2 Jul 1996
Package : FUG5
(in-package "FUG5")
(format t "~%These examples should only work with SURGE 2.0.~%~
They show how to use the HTML attribute in FUF.")
of the HTML tag alt to avoid confusion with FUF 's reserved keyword alt .
(def-test t422
"<A HREF=\"\">I am not a smart man</a>, but I know <B>what love is</B>."
((cat ds)
(subordinate ((cat clause)
(html ((a ((href "")))))
(process ((type ascriptive)))
(polarity negative)
(partic ((carrier ((cat personal-pronoun)
(person first)))
(attribute ((cat common)
(definite no)
(describer === "smart")
(lex "man")))))))
(connective ((lex "but")))
(directive ((cat clause)
(process ((type mental)
(lex "know")))
(partic ((processor ((cat personal-pronoun)
(person first)))
(phenomenon ((cat clause)
(html ((b +)))
(mood bound-nominal)
(binder ((lex "what")))
(controlled {^ partic attribute})
(process ((type ascriptive)))
(partic ((carrier ((cat common)
(lex "love")
(countable no)))))))))))))
(def-test t423-a
"The recipe has 3 steps:"
((cat clause)
(punctuation ((after ":")))
(process ((type possessive)))
(partic
((possessor ((cat common) (lex "recipe") (definite yes)))
(possessed ((cat common) (lex "step") (definite no)
(cardinal ((value 3) (digit yes)))))))))
(def-test t423
"The recipe has 3 steps: <OL><LI>start the fire </LI><LI>burn the olives </LI><LI>eat the pits </LI></OL>."
((cat list)
(distinct
~(
((cat clause)
(punctuation ((after ":")))
(process ((type possessive)))
(partic
((possessor ((cat common) (lex "recipe") (definite yes)))
(possessed ((cat common) (lex "step") (definite no)
(cardinal ((value 3))))))))
((cat list)
(html ((ol +)))
(distinct
~(
((cat clause)
(html ((li +)))
(mood imperative)
(process ((type material) (lex "start")))
(partic ((agent ((cat personal-pronoun) (person second)))
(affected ((cat common) (lex "fire"))))))
((cat clause)
(html ((li +)))
(mood imperative)
(process ((type material) (lex "burn")))
(partic ((agent ((cat personal-pronoun) (person second)))
(affected ((cat common) (lex "olive") (number plural))))))
((cat clause)
(html ((li +)))
(mood imperative)
(process ((type material) (lex "eat")))
(partic
((agent ((cat personal-pronoun) (person second)))
(affected ((cat common) (lex "pit") (number plural)))))))))))))
(def-test t424
"This picture contains the secret <B>for a <I>happy </I> life </B>: <IMG
SRC=\"happy.gif\" ALT=\"HAPPY LIFE SECRET\">."
((cat list)
(distinct
~(
((cat clause)
(proc ((type locative) (mode equative) (lex "contain")))
(partic
((identified ((cat common) (lex "picture") (distance near)))
(identifier ((cat common) (lex "secret")
(qualifier ((cat pp)
(prep ((lex "for")))
(html ((b +)))
(np ((cat common)
(definite no)
(lex "life")
(describer ((html ((i +)))
(lex "happy")))))))))))
(punctuation ((after ":"))))
((cat phrase)
(html ((img ((src "happy.gif")
(end-tag none)
(html-alt "HAPPY LIFE SECRET")))))
(lex ""))))))
|
ea8d6b31d898ce4dc28ea6a687dfb202617aa394d8bb8bed4563e266cd035e86 | soegaard/web-tutorial | control.rkt | #lang racket/base
;;;
;;; CONTROL
;;;
; The interface between the web-server in "server.rkt" and the control
; is the function `dispatch`. Each time the web-server receives an request
; it is passes on to `dispatch`.
(provide dispatch)
;; Imports
(require (for-syntax racket/base)
racket/match
racket/promise
racket/runtime-path
web-server/dispatch/extend
web-server/servlet-env
web-server/servlet
web-server/http/redirect
web-server/http/cookie
web-server/http/id-cookie ; authenticated cookies
" config.rkt "
"def.rkt" "exn.rkt" "parameters.rkt" "structs.rkt"
"validation.rkt"
"model.rkt" "view.rkt")
;;;
Utils
;;;
(define (bytes->number b)
(string->number (bytes->string/utf-8 b)))
;;;
;;; Bindings
;;;
; get-binding
; Extract a binding from the request if present and then
; apply convert to the extracted value.
; Typical use: (get-binding #"username" bytes->string-utf/8)
(define (get-binding binding-name [convert values] #:request [req (current-request)])
(match (bindings-assq binding-name (request-bindings/raw req))
[(? binding:form? b) (convert (binding:form-value b))]
[_ #f]))
;;;
;;; Cookies
;;;
; We are going to store session information (such as login status)
; on the client in cookies. To make these tamper proof, we need
; a way to verify, that they haven't been changed by the user.
; In order to store `authored-seconds&data` we send
; `digest&authored-seconds&data` where digest is a
; cryptographics hash of authored-seconds&data and, very important,
; a secret salt only known to the server(s).
; If using multiple servers, they need to share the secret salt.
; In short: we are not encrypting the data, we are merely
; associating it with a digest, so it can't be altered.
(define-runtime-path cookie-salt.bin "cookie-salt.bin")
(def cookie-salt (make-secret-salt/file cookie-salt.bin))
(define (make-logged-in-cookie)
(make-id-cookie "login-status" "in"
#:key cookie-salt
; only for http/https (not client side javascript)
#:http-only? #t
; #:expires ...
; #:max-age ...
; #:secure? #t ; instructs client only to send cookie via https
))
(define (make-logged-out-cookie)
(make-id-cookie "login-status" "out"
#:key cookie-salt
#:http-only? #t))
(define (make-username-cookie username)
(make-id-cookie "username" username
#:key cookie-salt
#:http-only? #t))
(define (get-cookie-value req name)
(request-id-cookie req #:name name #:key cookie-salt
; #:timeout ...
; #:shelf-life ...
))
(define (get-login-status req)
(match (get-cookie-value req "login-status")
["in" #t]
[_ #f]))
;;;
;;; DISPATCH
;;;
; from web-server/dispatch/url-patterns
(define-syntax define-bidi-match-expander/coercions
(syntax-rules ()
[(_ id in-test? in out-test? out)
(begin (define-coercion-match-expander in/m in-test? in)
(define-coercion-match-expander out/m out-test? out)
(define-bidi-match-expander id in/m out/m))]))
;; (define string->integer? (make-coerce-safe? string->integer))
;; (define-bidi-match-expander/coercions integer-arg
string->integer ?
;; integer? number->string)
(define (vote-direction? x) (or (equal? x "up") (equal? x "down")))
(define-bidi-match-expander/coercions vote-direction-arg
vote-direction? values vote-direction? values)
(define (t who f) (λ xs (displayln who) (apply f xs)))
(define (dispatch req)
(current-request req)
(def login-status (get-login-status req))
(def username (and login-status (get-cookie-value req "username")))
(def user (and username (get-user #:username username)))
(parameterize ([current-login-status (and user login-status)]
[current-user (and login-status user)])
(dispatch-on-url req)))
(defv (dispatch-on-url generate-url)
; pages: show a given html page (generated by the view)
; actions: performs action, then redirects to a page
(dispatch-rules
; pages
[("") do-home]
[("home") do-home]
[("about") do-about]
[("login") do-login/create-account]
[("submit") do-submit] ; new entry page
; actions
[("vote" (vote-direction-arg) (integer-arg)) #:method "post" do-vote]
; form submissions
[("logout-submitted") #:method "post" do-logout-submitted] ; logout, then show front page
[("entry-submitted") #:method "post" do-entry-submitted]
[("login-submitted") #:method "post" do-login-submitted]
[("create-account-submitted") #:method "post" do-create-account-submitted]
[else
(λ (req)
(displayln "!!!")
(displayln (url->string (request-uri req)))
(displayln (request-method req))
(do-home req))]))
;;;
PAGES
;;;
(define (do-about req)
(def result (html-about-page))
(response/output (λ (out) (display result out))))
(define (do-home req . xs)
(def result (html-home-page 0 1 (page 0)))
(response/output (λ (out) (display result out))))
(define (do-login/create-account req)
(def result (html-login-page))
(response/output (λ (out) (display result out))))
(define (do-logout-submitted req)
(displayln "logging out")
(def result (html-login-page))
(redirect-to "/" temporarily
#:headers (map cookie->header
(list (make-logged-out-cookie)))))
(define (do-login-submitted req)
(displayln 'do-login-submitted)
(def u (get-binding #"username" bytes->string/utf-8))
(def p (get-binding #"password"))
(displayln (list 'u u 'p p))
(cond
[(and u p) (match (authenticate-user u p)
; On a successful login we generate a logged-in cookie,
; and redirect to the frontpage.
; The redirection prevents the form data being submitted
; twice due to reloads in the browser.
[#t
(displayln (list 'do-submit-login "login ok"))
(redirect-to
"/" temporarily
#:headers (map cookie->header
(list (make-username-cookie u)
(make-logged-in-cookie))))]
; If the login failed, the user must try again.
[(authentication-error msg)
(displayln (list 'do-submit-login msg))
(redirect-to "/login" temporarily)])]
[else (displayln (list 'do-submit-login 'u u 'p p))
(redirect-to "/login" temporarily)]))
(define (do-create-account-submitted req)
(def u (bytes->string/utf-8 (get-binding #"username")))
(def p (get-binding #"password"))
(def e (bytes->string/utf-8 (get-binding #"email")))
(with-handlers ([exn:fail:user:bad?
(λ (e)
(def msg (exn-message e))
(displayln msg) ; todo: show user
(redirect-to "/login" temporarily))])
(create-user u p e)
(redirect-to "/" temporarily
#:headers (map cookie->header
(list (make-username-cookie u)
(make-logged-in-cookie))))))
(define (do-vote req direction id) ; an arrow was clicked
(displayln (list 'do-vote direction id))
(match direction
["up" (when id (increase-score id))]
["down" (when id (decrease-score id))]
[else 'do-nothing])
; to make sure a reload doesn't resubmit, we redirect to the front page
(redirect-to "/home" temporarily))
(define (do-submit req)
(def result (html-submit-page))
(response/output (λ (out) (display result out))))
;;;
;;; do-submit
;;;
(define (do-entry-submitted req)
; We get here when the form on the "Submit new entry" page is submitted.
(def url (get-binding #"url" bytes->string/utf-8))
(def title (get-binding #"title" bytes->string/utf-8))
; If the submitted url and title are valid, we will insert an
; entry in the databas and redirect to the database.
; If the data is invalid, we need to show the submit page again,
; this time with validation results.
(define vu (validate-url url)) ; see "validation.rkt" for definition
(define vt (validate-title title))
(cond
[(all-valid? vu vt) (insert-entry (make-entry #:title title #:url url #:score 10))
; to make sure a reload doesn't resubmit, we redirect to the front page
(redirect-to "/" temporarily)]
[else
(def result (html-submit-page #:validation (list vu vt)))
(response/output
#:headers (list (header #"Location" #"foo"))
(λ (out) (display result out)))]))
#;(dispatch-on-url
(make-request #"GET" (string->url "")
'()
(delay '())
#f
"1.2.3.4"
80
"4.3.2.1"))
| null | https://raw.githubusercontent.com/soegaard/web-tutorial/511a03410a440ed32475484ae93483f4ddd6656c/listit3/control.rkt | racket |
CONTROL
The interface between the web-server in "server.rkt" and the control
is the function `dispatch`. Each time the web-server receives an request
it is passes on to `dispatch`.
Imports
authenticated cookies
Bindings
get-binding
Extract a binding from the request if present and then
apply convert to the extracted value.
Typical use: (get-binding #"username" bytes->string-utf/8)
Cookies
We are going to store session information (such as login status)
on the client in cookies. To make these tamper proof, we need
a way to verify, that they haven't been changed by the user.
In order to store `authored-seconds&data` we send
`digest&authored-seconds&data` where digest is a
cryptographics hash of authored-seconds&data and, very important,
a secret salt only known to the server(s).
If using multiple servers, they need to share the secret salt.
In short: we are not encrypting the data, we are merely
associating it with a digest, so it can't be altered.
only for http/https (not client side javascript)
#:expires ...
#:max-age ...
#:secure? #t ; instructs client only to send cookie via https
#:timeout ...
#:shelf-life ...
DISPATCH
from web-server/dispatch/url-patterns
(define string->integer? (make-coerce-safe? string->integer))
(define-bidi-match-expander/coercions integer-arg
integer? number->string)
pages: show a given html page (generated by the view)
actions: performs action, then redirects to a page
pages
new entry page
actions
form submissions
logout, then show front page
On a successful login we generate a logged-in cookie,
and redirect to the frontpage.
The redirection prevents the form data being submitted
twice due to reloads in the browser.
If the login failed, the user must try again.
todo: show user
an arrow was clicked
to make sure a reload doesn't resubmit, we redirect to the front page
do-submit
We get here when the form on the "Submit new entry" page is submitted.
If the submitted url and title are valid, we will insert an
entry in the databas and redirect to the database.
If the data is invalid, we need to show the submit page again,
this time with validation results.
see "validation.rkt" for definition
to make sure a reload doesn't resubmit, we redirect to the front page
(dispatch-on-url | #lang racket/base
(provide dispatch)
(require (for-syntax racket/base)
racket/match
racket/promise
racket/runtime-path
web-server/dispatch/extend
web-server/servlet-env
web-server/servlet
web-server/http/redirect
web-server/http/cookie
" config.rkt "
"def.rkt" "exn.rkt" "parameters.rkt" "structs.rkt"
"validation.rkt"
"model.rkt" "view.rkt")
Utils
(define (bytes->number b)
(string->number (bytes->string/utf-8 b)))
(define (get-binding binding-name [convert values] #:request [req (current-request)])
(match (bindings-assq binding-name (request-bindings/raw req))
[(? binding:form? b) (convert (binding:form-value b))]
[_ #f]))
(define-runtime-path cookie-salt.bin "cookie-salt.bin")
(def cookie-salt (make-secret-salt/file cookie-salt.bin))
(define (make-logged-in-cookie)
(make-id-cookie "login-status" "in"
#:key cookie-salt
#:http-only? #t
))
(define (make-logged-out-cookie)
(make-id-cookie "login-status" "out"
#:key cookie-salt
#:http-only? #t))
(define (make-username-cookie username)
(make-id-cookie "username" username
#:key cookie-salt
#:http-only? #t))
(define (get-cookie-value req name)
(request-id-cookie req #:name name #:key cookie-salt
))
(define (get-login-status req)
(match (get-cookie-value req "login-status")
["in" #t]
[_ #f]))
(define-syntax define-bidi-match-expander/coercions
(syntax-rules ()
[(_ id in-test? in out-test? out)
(begin (define-coercion-match-expander in/m in-test? in)
(define-coercion-match-expander out/m out-test? out)
(define-bidi-match-expander id in/m out/m))]))
string->integer ?
(define (vote-direction? x) (or (equal? x "up") (equal? x "down")))
(define-bidi-match-expander/coercions vote-direction-arg
vote-direction? values vote-direction? values)
(define (t who f) (λ xs (displayln who) (apply f xs)))
(define (dispatch req)
(current-request req)
(def login-status (get-login-status req))
(def username (and login-status (get-cookie-value req "username")))
(def user (and username (get-user #:username username)))
(parameterize ([current-login-status (and user login-status)]
[current-user (and login-status user)])
(dispatch-on-url req)))
(defv (dispatch-on-url generate-url)
(dispatch-rules
[("") do-home]
[("home") do-home]
[("about") do-about]
[("login") do-login/create-account]
[("vote" (vote-direction-arg) (integer-arg)) #:method "post" do-vote]
[("entry-submitted") #:method "post" do-entry-submitted]
[("login-submitted") #:method "post" do-login-submitted]
[("create-account-submitted") #:method "post" do-create-account-submitted]
[else
(λ (req)
(displayln "!!!")
(displayln (url->string (request-uri req)))
(displayln (request-method req))
(do-home req))]))
PAGES
(define (do-about req)
(def result (html-about-page))
(response/output (λ (out) (display result out))))
(define (do-home req . xs)
(def result (html-home-page 0 1 (page 0)))
(response/output (λ (out) (display result out))))
(define (do-login/create-account req)
(def result (html-login-page))
(response/output (λ (out) (display result out))))
(define (do-logout-submitted req)
(displayln "logging out")
(def result (html-login-page))
(redirect-to "/" temporarily
#:headers (map cookie->header
(list (make-logged-out-cookie)))))
(define (do-login-submitted req)
(displayln 'do-login-submitted)
(def u (get-binding #"username" bytes->string/utf-8))
(def p (get-binding #"password"))
(displayln (list 'u u 'p p))
(cond
[(and u p) (match (authenticate-user u p)
[#t
(displayln (list 'do-submit-login "login ok"))
(redirect-to
"/" temporarily
#:headers (map cookie->header
(list (make-username-cookie u)
(make-logged-in-cookie))))]
[(authentication-error msg)
(displayln (list 'do-submit-login msg))
(redirect-to "/login" temporarily)])]
[else (displayln (list 'do-submit-login 'u u 'p p))
(redirect-to "/login" temporarily)]))
(define (do-create-account-submitted req)
(def u (bytes->string/utf-8 (get-binding #"username")))
(def p (get-binding #"password"))
(def e (bytes->string/utf-8 (get-binding #"email")))
(with-handlers ([exn:fail:user:bad?
(λ (e)
(def msg (exn-message e))
(redirect-to "/login" temporarily))])
(create-user u p e)
(redirect-to "/" temporarily
#:headers (map cookie->header
(list (make-username-cookie u)
(make-logged-in-cookie))))))
(displayln (list 'do-vote direction id))
(match direction
["up" (when id (increase-score id))]
["down" (when id (decrease-score id))]
[else 'do-nothing])
(redirect-to "/home" temporarily))
(define (do-submit req)
(def result (html-submit-page))
(response/output (λ (out) (display result out))))
(define (do-entry-submitted req)
(def url (get-binding #"url" bytes->string/utf-8))
(def title (get-binding #"title" bytes->string/utf-8))
(define vt (validate-title title))
(cond
[(all-valid? vu vt) (insert-entry (make-entry #:title title #:url url #:score 10))
(redirect-to "/" temporarily)]
[else
(def result (html-submit-page #:validation (list vu vt)))
(response/output
#:headers (list (header #"Location" #"foo"))
(λ (out) (display result out)))]))
(make-request #"GET" (string->url "")
'()
(delay '())
#f
"1.2.3.4"
80
"4.3.2.1"))
|
4e56b43457358f792fbb310dff80f3f72e4997dbedb5cf5fa9d6fdf33badf610 | jdan/ocaml-web-framework | framework.ml | type req = Http.Request.request * Router.params
type res = Http.Response.response
type route = { meth: string ;
pattern: string ;
handler: req -> res -> res ;
}
type server = { routes: route list }
let create_server () = { routes = [] }
let not_found req res =
res
|> Http.Response.set_status 404
|> Http.Response.set_body
(Printf.sprintf "Unknown path %s" (Http.Request.req_path req))
let route server req =
let rec inner routes =
match routes with
| [] -> not_found req
| item :: rest -> begin
if item.meth = Http.Request.req_method req then
match Router.match_pattern item.pattern (Http.Request.req_path req) with
| None -> inner rest
| Some params -> item.handler (req, params)
else
not_found req
end
in inner (List.rev server.routes)
let get pattern handler server =
{ routes = { meth = "GET" ;
pattern = pattern ;
handler = handler ;
}
:: server.routes
}
let post pattern handler server =
{ routes = { meth = "POST" ;
pattern = pattern ;
handler = handler ;
}
:: server.routes
}
let respond str res =
res
|> Http.Response.set_header "Content-Type" "text/html"
|> Http.Response.set_body str
let param (_, params) key = List.assoc key params
let listen port server =
Http.create_server
port
(fun req res -> route server req res |> Http.Response.send)
| null | https://raw.githubusercontent.com/jdan/ocaml-web-framework/bfa2f240a9aecc4edbf02ab87a73cfd20da482a4/src/framework.ml | ocaml | type req = Http.Request.request * Router.params
type res = Http.Response.response
type route = { meth: string ;
pattern: string ;
handler: req -> res -> res ;
}
type server = { routes: route list }
let create_server () = { routes = [] }
let not_found req res =
res
|> Http.Response.set_status 404
|> Http.Response.set_body
(Printf.sprintf "Unknown path %s" (Http.Request.req_path req))
let route server req =
let rec inner routes =
match routes with
| [] -> not_found req
| item :: rest -> begin
if item.meth = Http.Request.req_method req then
match Router.match_pattern item.pattern (Http.Request.req_path req) with
| None -> inner rest
| Some params -> item.handler (req, params)
else
not_found req
end
in inner (List.rev server.routes)
let get pattern handler server =
{ routes = { meth = "GET" ;
pattern = pattern ;
handler = handler ;
}
:: server.routes
}
let post pattern handler server =
{ routes = { meth = "POST" ;
pattern = pattern ;
handler = handler ;
}
:: server.routes
}
let respond str res =
res
|> Http.Response.set_header "Content-Type" "text/html"
|> Http.Response.set_body str
let param (_, params) key = List.assoc key params
let listen port server =
Http.create_server
port
(fun req res -> route server req res |> Http.Response.send)
| |
9e68caf6fc9f95e0ae66b2c5e74037a54e71e8fb70b119865627510d053cb5a5 | nachivpn/nbe-edsl | GExp.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE FlexibleInstances #
module GExp where
import Prelude hiding ((<>))
import Data.Constraint (Constraint)
import Text.PrettyPrint
import Text.PrettyPrint.HughesPJClass hiding (pPrintList)
import Control.Monad.State.Lazy
import Control.Monad.Except (Except)
import Data.Array ( Array )
--------------
-- Expressions
--------------
-- Type aliases
type Err = Except String
type Arr = Data.Array.Array Int
-- Primitive types
class Eq a => PrimTy a where
pTypeRep :: PTypeRep a
instance PrimTy Int where
pTypeRep = PTInt
instance PrimTy String where
pTypeRep = PTString
-- Primitive operations
data GPrim (c :: * -> Constraint) a where
Mul :: GExp c Int -> GExp c Int -> GPrim c Int
Add :: GExp c Int -> GExp c Int -> GPrim c Int
Rec :: (c a) => GExp c Int -> GExp c (Int -> a -> a) -> GExp c a -> GPrim c a
-- Higher-order abstract syntax for expressions
--
-- `GExp c a` is an expression of type a, where
-- `c` is the constraint that all type variables in the def. are subject to
-- e.g., `GExp Reifiable Int` denotes integer expressions where
all " intermediate " type variables are subject to the contraint ` Reifiable ` .
--
data GExp (c :: * -> Constraint) a where
-- Variables/Unknowns
Var :: c a
=> String -> GExp c a
-- Constants and primitives
Lift :: PrimTy a
=> a -> GExp c a
Prim :: ()
=> GPrim c a -> GExp c a
-- Functions
Lam :: (c a, c b)
=> (GExp c a -> GExp c b) -> GExp c (a -> b)
App :: (c a)
=> GExp c (a -> b) -> GExp c a -> GExp c b
-- Products
Unit :: ()
=> GExp c ()
Pair :: (c a, c b)
=> GExp c a -> GExp c b -> GExp c (a,b)
Fst :: (c b)
=> GExp c (a,b) -> GExp c a
Snd :: (c a)
=> GExp c (a,b) -> GExp c b
-- Sums
Inl :: (c a)
=> GExp c a -> GExp c (Either a b)
Inr :: (c b)
=> GExp c b -> GExp c (Either a b)
Case :: (c a, c b, c d)
=> GExp c (Either a b) -> GExp c (a -> d) -> GExp c (b -> d) -> GExp c d
-- Exceptions
RetErr :: (c a)
=> GExp c a -> GExp c (Err a)
BindErr :: (c a)
=> GExp c (Err a) -> GExp c (a -> Err b) -> GExp c (Err b)
Throw :: ()
=> GExp c String -> GExp c (Err a)
Catch :: ()
=> GExp c (Err a) -> GExp c (String -> Err a) -> GExp c (Err a)
State
Get :: (c a, c s)
=> GExp c (s -> State s a) -> GExp c (State s a)
Put :: (c s)
=> GExp c s -> GExp c (State s ())
RetSt :: (c a)
=> GExp c a -> GExp c (State s a)
BindSt :: (c a, c b , c s)
=> GExp c (State s a) -> GExp c (a -> State s b) -> GExp c (State s b)
-- Arrays
Arr :: (c a)
=> GExp c Int -> GExp c (Int -> a) -> GExp c (Arr a)
ArrLen :: (c a)
=> GExp c (Arr a) -> GExp c Int
ArrIx :: ()
=> GExp c (Arr a) -> GExp c Int -> GExp c a
-- Primitives to manually tame code explosion
Let :: (c a, c b)
=> GExp c a -> GExp c (a -> b) -> GExp c b
Save :: (c a)
=> GExp c a -> GExp c a
-----------------------------------
-- Type reps for induction on types
-----------------------------------
-- Rep. of "primitive" types
data PTypeRep a where
PTInt :: PTypeRep Int
PTString :: PTypeRep String
-- Rep. of "reifiable" types
data RTypeRep c a where
RTUnit :: (c ()) => RTypeRep c ()
RTInt :: (c Int) => RTypeRep c Int
RTString :: (c String) => RTypeRep c String
RTProd :: (c a, c b) => RTypeRep c a -> RTypeRep c b -> RTypeRep c (a , b)
RTSum :: (c a, c b) => RTypeRep c a -> RTypeRep c b -> RTypeRep c (Either a b)
RTFun :: (c a, c b) => RTypeRep c a -> RTypeRep c b -> RTypeRep c (a -> b)
RTErr :: (c a) => RTypeRep c a -> RTypeRep c (Err a)
RTState :: (c a, c s) => RTypeRep c s -> RTypeRep c a -> RTypeRep c (State s a)
RTArr :: (c a) => RTypeRep c a -> RTypeRep c (Arr a)
------------------
-- Pretty printing
------------------
pPrintPrimTy :: PrimTy a => a -> Doc
pPrintPrimTy x = go pTypeRep x
where
go :: PTypeRep a -> a -> Doc
go PTInt x = pPrint x
go PTString x = pPrint x
type St = State Int
fresh :: String -> St String
fresh x = do
n <- get
put (n + 1)
return (x ++ show n)
freshPrint :: St String
freshPrint = fresh "x"
pPrintPrim :: GPrim c a -> St Doc
pPrintPrim (Mul t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ lparen
<> t' <+> char '*' <+> u'
<> rparen
pPrintPrim (Add t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ lparen
<> t' <+> char '+' <+> u'
<> rparen
pPrintPrim (Rec n f t) = do
n' <- pPrintExp n
f' <- pPrintExp f
t' <- pPrintExp t
return $ lparen <> text "rec" <+> n' <+> f' <+> t' <> rparen
pPrintExp :: GExp c a -> St Doc
pPrintExp (Var s) = return (text s)
pPrintExp (Lift x) = return (pPrintPrimTy x)
pPrintExp (Prim p) = pPrintPrim p
pPrintExp Unit = return (pPrint ())
pPrintExp (Lam f) = do
x <- freshPrint
fx' <- pPrintExp (f (Var x))
return $ lparen
<> (text "\\") <> text x <> char '.' <+> fx'
<> rparen
pPrintExp (App f u) = do
f' <- pPrintExp f
u' <- pPrintExp u
return $ f' <+> u'
pPrintExp (Pair t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $
lparen
<> t' <> comma <> u'
<> rparen
pPrintExp (Fst t) =
(text "fst" <+>) <$> pPrintExp t
pPrintExp (Snd t) =
(text "snd" <+>) <$> pPrintExp t
pPrintExp (Inl t) =
(text "inl" <+>) <$> pPrintExp t
pPrintExp (Inr t) =
(text "inr" <+>) <$> pPrintExp t
pPrintExp (Case s f g) = do
s' <- pPrintExp s
f' <- pPrintExp f
g' <- pPrintExp g
return $ text "Case" <+> (lparen <> s' <> rparen) <+> text "of"
$$ nest 2 (text "inl ->" <+> f')
$$ nest 2 (text "inr ->" <+> g')
pPrintExp (RetErr t) =
(text "return" <+>) <$> pPrintExp t
pPrintExp (BindErr t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ t' <+> text ">>=" <+> u'
pPrintExp (Throw t) =
(text "throw" <+>) <$> pPrintExp t
pPrintExp (Catch t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ text "catch"
$$ nest 2 (lparen <> t' <> rparen)
$$ nest 2 u'
pPrintExp (RetSt t) =
(text "return" <+>) <$> pPrintExp t
pPrintExp (BindSt t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ t' <+> text ">>=" <+> u'
pPrintExp (Get t) =do
t' <- pPrintExp t
return $ text "get >>=" <+> t'
pPrintExp (Put t) = do
t' <- pPrintExp t
-- u' <- pPrintExp u
return $ text "put" <+> t'
pPrintExp (Arr t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ text "newArr" <+> t' <+> u'
pPrintExp (ArrLen t) = do
t' <- pPrintExp t
return $ text "length" <> lparen <> t' <> rparen
pPrintExp (ArrIx t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ lparen <> t' <+> text "!" <+> u' <> rparen
pPrintExp (Let t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ text "Let" <+> t' <+> text "in" <+> u'
pPrintExp (Save t) = do
t' <- pPrintExp t
return $ text "Save" <> lparen <> t' <> rparen
instance Pretty (GExp c a) where
pPrint e = evalState (pPrintExp e) 0
instance Show (GExp c a) where
show = show . pPrint
--------------------
-- Equality checking
--------------------
-- Hack alert: we'll pretend that variables beg. with "_" are fresh
freshCmp :: St String
freshCmp = fresh "_"
eqGPrim :: GPrim c a -> GPrim c b -> St Bool
eqGPrim (Mul t u) (Mul t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGPrim (Add t u) (Add t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGPrim (Rec n f t) (Rec n' f' t')
= do
b1 <- eqGExpSt n n'
b2 <- eqGExpSt f' f'
b3 <- eqGExpSt t t'
return $ b1 && b2 && b3
eqGPrim _ _
= return False
eqGExpSt :: GExp c a -> GExp c b -> St Bool
eqGExpSt (Var s) (Var s')
= return $ s == s'
eqGExpSt (Lift x) (Lift x')
= return $ go pTypeRep pTypeRep x x'
where
go :: PTypeRep a -> PTypeRep b -> a -> b -> Bool
go PTInt PTInt x x' = x == x'
go PTString PTString x x' = x == x'
go _ _ _ _ = False
eqGExpSt (Prim p) (Prim p')
= eqGPrim p p'
eqGExpSt Unit Unit
= return True
eqGExpSt (Lam f) (Lam f')
= do
x <- freshCmp
eqGExpSt (f (Var x)) (f' (Var x))
eqGExpSt (App f u) (App f' u')
= do
b1 <- eqGExpSt f f'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Pair t u) (Pair t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Fst t) (Fst t')
= eqGExpSt t t'
eqGExpSt (Snd t) (Snd t')
= eqGExpSt t t'
eqGExpSt (Inl t) (Inl t')
= eqGExpSt t t'
eqGExpSt (Inr t) (Inr t')
= eqGExpSt t t'
eqGExpSt (Case s f g) (Case s' f' g')
= do
b1 <- eqGExpSt s s'
b2 <- eqGExpSt f f'
b3 <- eqGExpSt g g'
return $ b1 && b2 && b3
eqGExpSt (RetErr t) (RetErr t')
= eqGExpSt t t'
eqGExpSt (BindErr t u) (BindErr t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Throw t) (Throw t')
= eqGExpSt t t'
eqGExpSt (Catch t u) (Catch t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (RetSt t) (RetSt t')
= eqGExpSt t t'
eqGExpSt (BindSt t u) (BindSt t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Get t) (Get t')
= eqGExpSt t t'
eqGExpSt (Put t) (Put t')
= eqGExpSt t t'
eqGExpSt (Arr t u) (Arr t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (ArrLen t) (ArrLen t')
= eqGExpSt t t'
eqGExpSt (ArrIx t u) (ArrIx t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Let t u) (Let t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Save t) (Save t')
= eqGExpSt t t'
eqGExpSt _ _
= return False
eqGExp :: GExp c a -> GExp c b -> Bool
eqGExp e e' = evalState (eqGExpSt e e') 0
------------
Utilities
------------
mapTup :: (a -> c) -> (b -> d) -> (a , b) -> (c, d)
mapTup f g (x,y) = (f x, g y)
comp :: (c a, c b, c d)
=> GExp c (b -> d) -> GExp c (a -> b) -> GExp c (a -> d)
comp g f = Lam $ App g . App f
(*.) :: (c a, c b, c d)
=> GExp c (b -> d) -> GExp c (a -> b) -> GExp c (a -> d)
(*.) = undefined
rec :: (c a, c Int)
=> GExp c Int -> GExp c (Int -> a -> a) -> GExp c a -> GExp c a
rec n f m = Prim (Rec n f m)
seqSt :: (c a, c b, c s, c (State s b))
=> GExp c (State s a) -> GExp c (State s b) -> GExp c (State s b)
seqSt m m' = BindSt m (Lam $ const $ m')
unknown :: c a => String -> GExp c a
unknown = Var
unit :: GExp c ()
unit = Unit
lam :: (c a, c b) => (GExp c a -> GExp c b) -> GExp c (a -> b)
lam = Lam
app :: (c a, c b) => GExp c (a -> b) -> GExp c a -> GExp c b
app = App
(*$) :: (c a, c b) => GExp c (a -> b) -> GExp c a -> GExp c b
(*$) = app
lam2 :: (c a, c b, c d, c (b -> d))
=> (GExp c a -> GExp c b -> GExp c d) -> GExp c (a -> b -> d)
lam2 f = lam $ \ x -> (lam $ \ y -> f x y)
app2 :: (c a, c b, c d, c (b -> d))
=> GExp c (a -> b -> d) -> GExp c a -> GExp c b -> GExp c d
app2 f x y = app (app f x) y
case' :: (c a, c b, c d)
=> GExp c (Either a b) -> GExp c (a -> d) -> GExp c (b -> d) -> GExp c d
case' = Case
instance Num (GExp c Int) where
x + y = Prim (Add x y)
x * y = Prim (Mul x y)
abs = undefined
signum = undefined
fromInteger = Lift . fromIntegral
negate x = Prim (Mul (Lift (-1)) x)
type BoolE = Either () ()
pattern TrueE :: Either () b
pattern TrueE = Left ()
pattern FalseE :: Either a ()
pattern FalseE = Right ()
| null | https://raw.githubusercontent.com/nachivpn/nbe-edsl/f7fdec9e1b25c3d28c9dff9ddbd2294e479e4a34/src/GExp.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE ConstraintKinds #
------------
Expressions
------------
Type aliases
Primitive types
Primitive operations
Higher-order abstract syntax for expressions
`GExp c a` is an expression of type a, where
`c` is the constraint that all type variables in the def. are subject to
e.g., `GExp Reifiable Int` denotes integer expressions where
Variables/Unknowns
Constants and primitives
Functions
Products
Sums
Exceptions
Arrays
Primitives to manually tame code explosion
---------------------------------
Type reps for induction on types
---------------------------------
Rep. of "primitive" types
Rep. of "reifiable" types
----------------
Pretty printing
----------------
u' <- pPrintExp u
------------------
Equality checking
------------------
Hack alert: we'll pretend that variables beg. with "_" are fresh
----------
---------- | # LANGUAGE TypeFamilies #
# LANGUAGE PatternSynonyms #
# LANGUAGE FlexibleInstances #
module GExp where
import Prelude hiding ((<>))
import Data.Constraint (Constraint)
import Text.PrettyPrint
import Text.PrettyPrint.HughesPJClass hiding (pPrintList)
import Control.Monad.State.Lazy
import Control.Monad.Except (Except)
import Data.Array ( Array )
type Err = Except String
type Arr = Data.Array.Array Int
class Eq a => PrimTy a where
pTypeRep :: PTypeRep a
instance PrimTy Int where
pTypeRep = PTInt
instance PrimTy String where
pTypeRep = PTString
data GPrim (c :: * -> Constraint) a where
Mul :: GExp c Int -> GExp c Int -> GPrim c Int
Add :: GExp c Int -> GExp c Int -> GPrim c Int
Rec :: (c a) => GExp c Int -> GExp c (Int -> a -> a) -> GExp c a -> GPrim c a
all " intermediate " type variables are subject to the contraint ` Reifiable ` .
data GExp (c :: * -> Constraint) a where
Var :: c a
=> String -> GExp c a
Lift :: PrimTy a
=> a -> GExp c a
Prim :: ()
=> GPrim c a -> GExp c a
Lam :: (c a, c b)
=> (GExp c a -> GExp c b) -> GExp c (a -> b)
App :: (c a)
=> GExp c (a -> b) -> GExp c a -> GExp c b
Unit :: ()
=> GExp c ()
Pair :: (c a, c b)
=> GExp c a -> GExp c b -> GExp c (a,b)
Fst :: (c b)
=> GExp c (a,b) -> GExp c a
Snd :: (c a)
=> GExp c (a,b) -> GExp c b
Inl :: (c a)
=> GExp c a -> GExp c (Either a b)
Inr :: (c b)
=> GExp c b -> GExp c (Either a b)
Case :: (c a, c b, c d)
=> GExp c (Either a b) -> GExp c (a -> d) -> GExp c (b -> d) -> GExp c d
RetErr :: (c a)
=> GExp c a -> GExp c (Err a)
BindErr :: (c a)
=> GExp c (Err a) -> GExp c (a -> Err b) -> GExp c (Err b)
Throw :: ()
=> GExp c String -> GExp c (Err a)
Catch :: ()
=> GExp c (Err a) -> GExp c (String -> Err a) -> GExp c (Err a)
State
Get :: (c a, c s)
=> GExp c (s -> State s a) -> GExp c (State s a)
Put :: (c s)
=> GExp c s -> GExp c (State s ())
RetSt :: (c a)
=> GExp c a -> GExp c (State s a)
BindSt :: (c a, c b , c s)
=> GExp c (State s a) -> GExp c (a -> State s b) -> GExp c (State s b)
Arr :: (c a)
=> GExp c Int -> GExp c (Int -> a) -> GExp c (Arr a)
ArrLen :: (c a)
=> GExp c (Arr a) -> GExp c Int
ArrIx :: ()
=> GExp c (Arr a) -> GExp c Int -> GExp c a
Let :: (c a, c b)
=> GExp c a -> GExp c (a -> b) -> GExp c b
Save :: (c a)
=> GExp c a -> GExp c a
data PTypeRep a where
PTInt :: PTypeRep Int
PTString :: PTypeRep String
data RTypeRep c a where
RTUnit :: (c ()) => RTypeRep c ()
RTInt :: (c Int) => RTypeRep c Int
RTString :: (c String) => RTypeRep c String
RTProd :: (c a, c b) => RTypeRep c a -> RTypeRep c b -> RTypeRep c (a , b)
RTSum :: (c a, c b) => RTypeRep c a -> RTypeRep c b -> RTypeRep c (Either a b)
RTFun :: (c a, c b) => RTypeRep c a -> RTypeRep c b -> RTypeRep c (a -> b)
RTErr :: (c a) => RTypeRep c a -> RTypeRep c (Err a)
RTState :: (c a, c s) => RTypeRep c s -> RTypeRep c a -> RTypeRep c (State s a)
RTArr :: (c a) => RTypeRep c a -> RTypeRep c (Arr a)
pPrintPrimTy :: PrimTy a => a -> Doc
pPrintPrimTy x = go pTypeRep x
where
go :: PTypeRep a -> a -> Doc
go PTInt x = pPrint x
go PTString x = pPrint x
type St = State Int
fresh :: String -> St String
fresh x = do
n <- get
put (n + 1)
return (x ++ show n)
freshPrint :: St String
freshPrint = fresh "x"
pPrintPrim :: GPrim c a -> St Doc
pPrintPrim (Mul t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ lparen
<> t' <+> char '*' <+> u'
<> rparen
pPrintPrim (Add t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ lparen
<> t' <+> char '+' <+> u'
<> rparen
pPrintPrim (Rec n f t) = do
n' <- pPrintExp n
f' <- pPrintExp f
t' <- pPrintExp t
return $ lparen <> text "rec" <+> n' <+> f' <+> t' <> rparen
pPrintExp :: GExp c a -> St Doc
pPrintExp (Var s) = return (text s)
pPrintExp (Lift x) = return (pPrintPrimTy x)
pPrintExp (Prim p) = pPrintPrim p
pPrintExp Unit = return (pPrint ())
pPrintExp (Lam f) = do
x <- freshPrint
fx' <- pPrintExp (f (Var x))
return $ lparen
<> (text "\\") <> text x <> char '.' <+> fx'
<> rparen
pPrintExp (App f u) = do
f' <- pPrintExp f
u' <- pPrintExp u
return $ f' <+> u'
pPrintExp (Pair t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $
lparen
<> t' <> comma <> u'
<> rparen
pPrintExp (Fst t) =
(text "fst" <+>) <$> pPrintExp t
pPrintExp (Snd t) =
(text "snd" <+>) <$> pPrintExp t
pPrintExp (Inl t) =
(text "inl" <+>) <$> pPrintExp t
pPrintExp (Inr t) =
(text "inr" <+>) <$> pPrintExp t
pPrintExp (Case s f g) = do
s' <- pPrintExp s
f' <- pPrintExp f
g' <- pPrintExp g
return $ text "Case" <+> (lparen <> s' <> rparen) <+> text "of"
$$ nest 2 (text "inl ->" <+> f')
$$ nest 2 (text "inr ->" <+> g')
pPrintExp (RetErr t) =
(text "return" <+>) <$> pPrintExp t
pPrintExp (BindErr t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ t' <+> text ">>=" <+> u'
pPrintExp (Throw t) =
(text "throw" <+>) <$> pPrintExp t
pPrintExp (Catch t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ text "catch"
$$ nest 2 (lparen <> t' <> rparen)
$$ nest 2 u'
pPrintExp (RetSt t) =
(text "return" <+>) <$> pPrintExp t
pPrintExp (BindSt t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ t' <+> text ">>=" <+> u'
pPrintExp (Get t) =do
t' <- pPrintExp t
return $ text "get >>=" <+> t'
pPrintExp (Put t) = do
t' <- pPrintExp t
return $ text "put" <+> t'
pPrintExp (Arr t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ text "newArr" <+> t' <+> u'
pPrintExp (ArrLen t) = do
t' <- pPrintExp t
return $ text "length" <> lparen <> t' <> rparen
pPrintExp (ArrIx t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ lparen <> t' <+> text "!" <+> u' <> rparen
pPrintExp (Let t u) = do
t' <- pPrintExp t
u' <- pPrintExp u
return $ text "Let" <+> t' <+> text "in" <+> u'
pPrintExp (Save t) = do
t' <- pPrintExp t
return $ text "Save" <> lparen <> t' <> rparen
instance Pretty (GExp c a) where
pPrint e = evalState (pPrintExp e) 0
instance Show (GExp c a) where
show = show . pPrint
freshCmp :: St String
freshCmp = fresh "_"
eqGPrim :: GPrim c a -> GPrim c b -> St Bool
eqGPrim (Mul t u) (Mul t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGPrim (Add t u) (Add t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGPrim (Rec n f t) (Rec n' f' t')
= do
b1 <- eqGExpSt n n'
b2 <- eqGExpSt f' f'
b3 <- eqGExpSt t t'
return $ b1 && b2 && b3
eqGPrim _ _
= return False
eqGExpSt :: GExp c a -> GExp c b -> St Bool
eqGExpSt (Var s) (Var s')
= return $ s == s'
eqGExpSt (Lift x) (Lift x')
= return $ go pTypeRep pTypeRep x x'
where
go :: PTypeRep a -> PTypeRep b -> a -> b -> Bool
go PTInt PTInt x x' = x == x'
go PTString PTString x x' = x == x'
go _ _ _ _ = False
eqGExpSt (Prim p) (Prim p')
= eqGPrim p p'
eqGExpSt Unit Unit
= return True
eqGExpSt (Lam f) (Lam f')
= do
x <- freshCmp
eqGExpSt (f (Var x)) (f' (Var x))
eqGExpSt (App f u) (App f' u')
= do
b1 <- eqGExpSt f f'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Pair t u) (Pair t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Fst t) (Fst t')
= eqGExpSt t t'
eqGExpSt (Snd t) (Snd t')
= eqGExpSt t t'
eqGExpSt (Inl t) (Inl t')
= eqGExpSt t t'
eqGExpSt (Inr t) (Inr t')
= eqGExpSt t t'
eqGExpSt (Case s f g) (Case s' f' g')
= do
b1 <- eqGExpSt s s'
b2 <- eqGExpSt f f'
b3 <- eqGExpSt g g'
return $ b1 && b2 && b3
eqGExpSt (RetErr t) (RetErr t')
= eqGExpSt t t'
eqGExpSt (BindErr t u) (BindErr t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Throw t) (Throw t')
= eqGExpSt t t'
eqGExpSt (Catch t u) (Catch t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (RetSt t) (RetSt t')
= eqGExpSt t t'
eqGExpSt (BindSt t u) (BindSt t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Get t) (Get t')
= eqGExpSt t t'
eqGExpSt (Put t) (Put t')
= eqGExpSt t t'
eqGExpSt (Arr t u) (Arr t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (ArrLen t) (ArrLen t')
= eqGExpSt t t'
eqGExpSt (ArrIx t u) (ArrIx t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Let t u) (Let t' u')
= do
b1 <- eqGExpSt t t'
b2 <- eqGExpSt u u'
return $ b1 && b2
eqGExpSt (Save t) (Save t')
= eqGExpSt t t'
eqGExpSt _ _
= return False
eqGExp :: GExp c a -> GExp c b -> Bool
eqGExp e e' = evalState (eqGExpSt e e') 0
Utilities
mapTup :: (a -> c) -> (b -> d) -> (a , b) -> (c, d)
mapTup f g (x,y) = (f x, g y)
comp :: (c a, c b, c d)
=> GExp c (b -> d) -> GExp c (a -> b) -> GExp c (a -> d)
comp g f = Lam $ App g . App f
(*.) :: (c a, c b, c d)
=> GExp c (b -> d) -> GExp c (a -> b) -> GExp c (a -> d)
(*.) = undefined
rec :: (c a, c Int)
=> GExp c Int -> GExp c (Int -> a -> a) -> GExp c a -> GExp c a
rec n f m = Prim (Rec n f m)
seqSt :: (c a, c b, c s, c (State s b))
=> GExp c (State s a) -> GExp c (State s b) -> GExp c (State s b)
seqSt m m' = BindSt m (Lam $ const $ m')
unknown :: c a => String -> GExp c a
unknown = Var
unit :: GExp c ()
unit = Unit
lam :: (c a, c b) => (GExp c a -> GExp c b) -> GExp c (a -> b)
lam = Lam
app :: (c a, c b) => GExp c (a -> b) -> GExp c a -> GExp c b
app = App
(*$) :: (c a, c b) => GExp c (a -> b) -> GExp c a -> GExp c b
(*$) = app
lam2 :: (c a, c b, c d, c (b -> d))
=> (GExp c a -> GExp c b -> GExp c d) -> GExp c (a -> b -> d)
lam2 f = lam $ \ x -> (lam $ \ y -> f x y)
app2 :: (c a, c b, c d, c (b -> d))
=> GExp c (a -> b -> d) -> GExp c a -> GExp c b -> GExp c d
app2 f x y = app (app f x) y
case' :: (c a, c b, c d)
=> GExp c (Either a b) -> GExp c (a -> d) -> GExp c (b -> d) -> GExp c d
case' = Case
instance Num (GExp c Int) where
x + y = Prim (Add x y)
x * y = Prim (Mul x y)
abs = undefined
signum = undefined
fromInteger = Lift . fromIntegral
negate x = Prim (Mul (Lift (-1)) x)
type BoolE = Either () ()
pattern TrueE :: Either () b
pattern TrueE = Left ()
pattern FalseE :: Either a ()
pattern FalseE = Right ()
|
02941840c8e60b52df342d342ed538230414e1932cc739efcab2cfdfe6bd1972 | ephemient/aoc2018 | Day16.hs | |
Module : Day16
Description : < Day 16 : Chronal Classification >
Module: Day16
Description: < Day 16: Chronal Classification>
-}
# LANGUAGE FlexibleContexts , RecordWildCards , TypeApplications #
module Day16 (day16a, day16b) where
import Control.Arrow ((&&&))
import Control.Monad (foldM)
import Data.Array.Unboxed (IArray, UArray, Ix, (!), (//), listArray)
import Data.Bits (Bits, (.&.), (.|.))
import Data.Bool (bool)
import Data.List (genericLength)
import Data.Map.Lazy ((!?), elems, fromListWith, union)
import qualified Data.Map.Lazy as M (empty, null, partition)
import Data.Set (difference, findMin, fromList, intersection, size, unions)
import Text.Megaparsec (MonadParsec, between, count, many, parseMaybe, sepBy, sepEndBy1)
import Text.Megaparsec.Char (char, newline, string)
import Text.Megaparsec.Char.Lexer (decimal)
data Op
= ADDR | ADDI | MULR | MULI | BANR | BANI | BORR | BORI
| SETR | SETI | GTIR | GTRI | GTRR | EQIR | EQRI | EQRR
deriving (Bounded, Enum, Eq, Ord)
data Sample a op i = Sample
{ sampleOp :: op
, sampleA :: i
, sampleB :: i
, sampleC :: i
, sampleR0 :: a i i
, sampleR1 :: a i i
}
unknownInstructionParser :: (MonadParsec e String m, Integral op, Integral i) => m (op, i, i, i)
unknownInstructionParser = do
op <- decimal
[a, b, c] <- count 3 $ char ' ' *> decimal
return (op, a, b, c)
sampleParser :: (MonadParsec e String m, Integral op, Integral i, Ix i, IArray a i) => m (Sample a op i)
sampleParser = do
r0 <- between (string "Before: [") (string "]") (sepBy decimal (string ", ")) <* newline
(sampleOp, sampleA, sampleB, sampleC) <- unknownInstructionParser <* newline
r1 <- between (string "After: [") (string "]") (sepBy decimal (string ", ")) <* newline
return Sample
{ sampleR0 = listArray (0, genericLength r0 - 1) r0
, sampleR1 = listArray (0, genericLength r1 - 1) r1
, ..
}
parser :: (MonadParsec e String m, Integral op, Integral i, Ix i, IArray a i) => m ([Sample a op i], [(op, i, i, i)])
parser = (,)
<$> (sepEndBy1 sampleParser newline <* many newline)
<*> sepEndBy1 unknownInstructionParser newline
doOp :: (IArray a i, Bits i, Ix i, Num i) => Op -> i -> i -> i -> a i i -> a i i
doOp ADDR a b c r = r // [(c, r ! a + r ! b)]
doOp ADDI a b c r = r // [(c, r ! a + b)]
doOp MULR a b c r = r // [(c, r ! a * r ! b)]
doOp MULI a b c r = r // [(c, r ! a * b)]
doOp BANR a b c r = r // [(c, r ! a .&. r ! b)]
doOp BANI a b c r = r // [(c, r ! a .&. b)]
doOp BORR a b c r = r // [(c, r ! a .|. r ! b)]
doOp BORI a b c r = r // [(c, r ! a .|. b)]
doOp SETR a _ c r = r // [(c, r ! a)]
doOp SETI a _ c r = r // [(c, a)]
doOp GTIR a b c r = r // [(c, bool 0 1 $ a > r ! b)]
doOp GTRI a b c r = r // [(c, bool 0 1 $ r ! a > b)]
doOp GTRR a b c r = r // [(c, bool 0 1 $ r ! a > r ! b)]
doOp EQIR a b c r = r // [(c, bool 0 1 $ a == r ! b)]
doOp EQRI a b c r = r // [(c, bool 0 1 $ r ! a == b)]
doOp EQRR a b c r = r // [(c, bool 0 1 $ r ! a == r ! b)]
validOps :: (IArray a i, Eq (a i i), Bits i, Ix i, Num i) => Sample a op i -> [Op]
validOps Sample {..} =
[op | op <- [minBound..maxBound], doOp op sampleA sampleB sampleC sampleR0 == sampleR1]
day16a :: String -> Maybe Int
day16a input = do
(samples, _) <- parseMaybe @() parser input
return $ length $ filter ambiguous samples
where ambiguous sample = case validOps @UArray @Int @Int sample of
_:_:_:_ -> True
_ -> False
day16b :: String -> Maybe Int
day16b input = do
(samples, instructions) <- parseMaybe @() parser input
codings <- re M.empty $ fromListWith intersection $
(sampleOp &&& fromList . validOps @UArray @Int @Int) <$> samples
(! 0) <$> foldM (doOp' codings) (listArray @UArray @Int @Int (0, 3) [0, 0, 0, 0]) instructions
where re done pending
| M.null pending = return done
| (done', pending') <- M.partition ((== 1) . size) pending, not $ M.null done' =
re (union done $ findMin <$> done') $
flip difference (unions $ elems done') <$> pending'
| otherwise = fail "can not reverse engineer instruction encoding"
doOp' codings r (op, a, b, c) = do
op' <- codings !? op
return $ doOp op' a b c r
| null | https://raw.githubusercontent.com/ephemient/aoc2018/eb0d04193ccb6ad98ed8ad2253faeb3d503a5938/src/Day16.hs | haskell | |
Module : Day16
Description : < Day 16 : Chronal Classification >
Module: Day16
Description: < Day 16: Chronal Classification>
-}
# LANGUAGE FlexibleContexts , RecordWildCards , TypeApplications #
module Day16 (day16a, day16b) where
import Control.Arrow ((&&&))
import Control.Monad (foldM)
import Data.Array.Unboxed (IArray, UArray, Ix, (!), (//), listArray)
import Data.Bits (Bits, (.&.), (.|.))
import Data.Bool (bool)
import Data.List (genericLength)
import Data.Map.Lazy ((!?), elems, fromListWith, union)
import qualified Data.Map.Lazy as M (empty, null, partition)
import Data.Set (difference, findMin, fromList, intersection, size, unions)
import Text.Megaparsec (MonadParsec, between, count, many, parseMaybe, sepBy, sepEndBy1)
import Text.Megaparsec.Char (char, newline, string)
import Text.Megaparsec.Char.Lexer (decimal)
data Op
= ADDR | ADDI | MULR | MULI | BANR | BANI | BORR | BORI
| SETR | SETI | GTIR | GTRI | GTRR | EQIR | EQRI | EQRR
deriving (Bounded, Enum, Eq, Ord)
data Sample a op i = Sample
{ sampleOp :: op
, sampleA :: i
, sampleB :: i
, sampleC :: i
, sampleR0 :: a i i
, sampleR1 :: a i i
}
unknownInstructionParser :: (MonadParsec e String m, Integral op, Integral i) => m (op, i, i, i)
unknownInstructionParser = do
op <- decimal
[a, b, c] <- count 3 $ char ' ' *> decimal
return (op, a, b, c)
sampleParser :: (MonadParsec e String m, Integral op, Integral i, Ix i, IArray a i) => m (Sample a op i)
sampleParser = do
r0 <- between (string "Before: [") (string "]") (sepBy decimal (string ", ")) <* newline
(sampleOp, sampleA, sampleB, sampleC) <- unknownInstructionParser <* newline
r1 <- between (string "After: [") (string "]") (sepBy decimal (string ", ")) <* newline
return Sample
{ sampleR0 = listArray (0, genericLength r0 - 1) r0
, sampleR1 = listArray (0, genericLength r1 - 1) r1
, ..
}
parser :: (MonadParsec e String m, Integral op, Integral i, Ix i, IArray a i) => m ([Sample a op i], [(op, i, i, i)])
parser = (,)
<$> (sepEndBy1 sampleParser newline <* many newline)
<*> sepEndBy1 unknownInstructionParser newline
doOp :: (IArray a i, Bits i, Ix i, Num i) => Op -> i -> i -> i -> a i i -> a i i
doOp ADDR a b c r = r // [(c, r ! a + r ! b)]
doOp ADDI a b c r = r // [(c, r ! a + b)]
doOp MULR a b c r = r // [(c, r ! a * r ! b)]
doOp MULI a b c r = r // [(c, r ! a * b)]
doOp BANR a b c r = r // [(c, r ! a .&. r ! b)]
doOp BANI a b c r = r // [(c, r ! a .&. b)]
doOp BORR a b c r = r // [(c, r ! a .|. r ! b)]
doOp BORI a b c r = r // [(c, r ! a .|. b)]
doOp SETR a _ c r = r // [(c, r ! a)]
doOp SETI a _ c r = r // [(c, a)]
doOp GTIR a b c r = r // [(c, bool 0 1 $ a > r ! b)]
doOp GTRI a b c r = r // [(c, bool 0 1 $ r ! a > b)]
doOp GTRR a b c r = r // [(c, bool 0 1 $ r ! a > r ! b)]
doOp EQIR a b c r = r // [(c, bool 0 1 $ a == r ! b)]
doOp EQRI a b c r = r // [(c, bool 0 1 $ r ! a == b)]
doOp EQRR a b c r = r // [(c, bool 0 1 $ r ! a == r ! b)]
validOps :: (IArray a i, Eq (a i i), Bits i, Ix i, Num i) => Sample a op i -> [Op]
validOps Sample {..} =
[op | op <- [minBound..maxBound], doOp op sampleA sampleB sampleC sampleR0 == sampleR1]
day16a :: String -> Maybe Int
day16a input = do
(samples, _) <- parseMaybe @() parser input
return $ length $ filter ambiguous samples
where ambiguous sample = case validOps @UArray @Int @Int sample of
_:_:_:_ -> True
_ -> False
day16b :: String -> Maybe Int
day16b input = do
(samples, instructions) <- parseMaybe @() parser input
codings <- re M.empty $ fromListWith intersection $
(sampleOp &&& fromList . validOps @UArray @Int @Int) <$> samples
(! 0) <$> foldM (doOp' codings) (listArray @UArray @Int @Int (0, 3) [0, 0, 0, 0]) instructions
where re done pending
| M.null pending = return done
| (done', pending') <- M.partition ((== 1) . size) pending, not $ M.null done' =
re (union done $ findMin <$> done') $
flip difference (unions $ elems done') <$> pending'
| otherwise = fail "can not reverse engineer instruction encoding"
doOp' codings r (op, a, b, c) = do
op' <- codings !? op
return $ doOp op' a b c r
| |
d0d772ee998d90afb05c0451635b3cf485e28365c4b0d675adf6559083c158fe | ocaml-multicore/parafuzz | constpromote.ml | (* TEST
* hasunix
include unix
** bytecode
** native
*)
when run with the bytecode debug runtime , this test
used to trigger a bug where the constant [ 13 ]
remained unpromoted
used to trigger a bug where the constant [13]
remained unpromoted *)
let rec burn l =
if List.hd l > 14 then ()
else burn (l @ l |> List.map (fun x -> x + 1))
let () =
ignore (Domain.spawn (fun () -> burn [13]));
burn [0];
Printf.printf "all done\n%!"
| null | https://raw.githubusercontent.com/ocaml-multicore/parafuzz/6a92906f1ba03287ffcb433063bded831a644fd5/testsuite/tests/parallel/constpromote.ml | ocaml | TEST
* hasunix
include unix
** bytecode
** native
|
when run with the bytecode debug runtime , this test
used to trigger a bug where the constant [ 13 ]
remained unpromoted
used to trigger a bug where the constant [13]
remained unpromoted *)
let rec burn l =
if List.hd l > 14 then ()
else burn (l @ l |> List.map (fun x -> x + 1))
let () =
ignore (Domain.spawn (fun () -> burn [13]));
burn [0];
Printf.printf "all done\n%!"
|
60d1a9b43674e8e4c5f754a8eb41bad3b8ce934a1fc12ee162699a74172b1558 | braidchat/braid | helpers.clj | (ns braid.core.server.routes.helpers
(:require
[braid.chat.db.user :as user]
[ring.middleware.anti-forgery :as anti-forgery]))
(defn logged-in? [req]
(when-let [user-id (get-in req [:session :user-id])]
(user/user-id-exists? user-id)))
(defn current-user [req]
(when-let [user-id (get-in req [:session :user-id])]
(when (user/user-id-exists? user-id)
(user/user-by-id user-id))))
(defn current-user-id [req]
(when-let [user-id (get-in req [:session :user-id])]
(when (user/user-id-exists? user-id)
user-id)))
(defn session-token []
anti-forgery/*anti-forgery-token*)
(defn error-response [status msg]
{:status status
:headers {"Content-Type" "application/edn; charset=utf-8"}
:body (pr-str {:error msg})})
(defn edn-response [clj-body]
{:headers {"Content-Type" "application/edn; charset=utf-8"}
:body (pr-str clj-body)})
| null | https://raw.githubusercontent.com/braidchat/braid/2e44eb6e77f1d203115f9b9c529bd865fa3d7302/src/braid/core/server/routes/helpers.clj | clojure | (ns braid.core.server.routes.helpers
(:require
[braid.chat.db.user :as user]
[ring.middleware.anti-forgery :as anti-forgery]))
(defn logged-in? [req]
(when-let [user-id (get-in req [:session :user-id])]
(user/user-id-exists? user-id)))
(defn current-user [req]
(when-let [user-id (get-in req [:session :user-id])]
(when (user/user-id-exists? user-id)
(user/user-by-id user-id))))
(defn current-user-id [req]
(when-let [user-id (get-in req [:session :user-id])]
(when (user/user-id-exists? user-id)
user-id)))
(defn session-token []
anti-forgery/*anti-forgery-token*)
(defn error-response [status msg]
{:status status
:headers {"Content-Type" "application/edn; charset=utf-8"}
:body (pr-str {:error msg})})
(defn edn-response [clj-body]
{:headers {"Content-Type" "application/edn; charset=utf-8"}
:body (pr-str clj-body)})
| |
26e41911dcce772b1c03b91077bc31ba963716e0ef9d17bba141710a46cde1dc | input-output-hk/ouroboros-network | PeerGraph.hs | # LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -Wno - orphans #
# OPTIONS_GHC -Wno - incomplete - uni - patterns #
module Test.Ouroboros.Network.PeerSelection.PeerGraph
( PeerGraph (..)
, validPeerGraph
, allPeers
, firstGossipReachablePeers
, GovernorScripts (..)
, GossipScript
, ConnectionScript
, AsyncDemotion (..)
, GossipTime (..)
, interpretGossipTime
, prop_shrink_GovernorScripts
, prop_arbitrary_PeerGraph
, prop_shrink_PeerGraph
, prop_shrinkCarefully_PeerGraph
, prop_shrinkCarefully_GovernorScripts
) where
import Data.Graph (Graph)
import qualified Data.Graph as Graph
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Tree as Tree
import Control.Monad.Class.MonadTime
import Ouroboros.Network.Testing.Data.Script (Script (..),
ScriptDelay (NoDelay), TimedScript, arbitraryScriptOf)
import Ouroboros.Network.Testing.Utils (prop_shrink_nonequal,
prop_shrink_valid, renderRanges)
import Test.Ouroboros.Network.PeerSelection.Instances
import Test.Ouroboros.Network.ShrinkCarefully
import Test.QuickCheck
--
-- Mock environment types
--
| The peer graph is the graph of all the peers in the mock p2p network , in
-- traditional adjacency representation.
--
newtype PeerGraph = PeerGraph [(PeerAddr, [PeerAddr], PeerInfo)]
deriving (Eq, Show)
-- | For now the information associated with each node is just the gossip
-- script and connection script.
--
type PeerInfo = GovernorScripts
data GovernorScripts = GovernorScripts {
gossipScript :: GossipScript,
connectionScript :: ConnectionScript
}
deriving (Eq, Show)
-- | The gossip script is the script we interpret to provide answers to gossip
-- requests that the governor makes. After each gossip request to a peer we
-- move on to the next entry in the script, unless we get to the end in which
-- case that becomes the reply for all remaining gossips.
--
-- A @Nothing@ indicates failure. The @[PeerAddr]@ is the list of peers to
-- return which must always be a subset of the actual edges in the p2p graph.
--
-- This representation was chosen because it allows easy shrinking.
--
type GossipScript = Script (Maybe ([PeerAddr], GossipTime))
-- | The gossp time is our simulation of elapsed time to respond to gossip
-- requests. This is important because the governor uses timeouts and behaves
differently in these three cases .
--
data GossipTime = GossipTimeQuick | GossipTimeSlow | GossipTimeTimeout
deriving (Eq, Show)
interpretGossipTime :: GossipTime -> DiffTime
interpretGossipTime GossipTimeQuick = 1
interpretGossipTime GossipTimeSlow = 5
interpretGossipTime GossipTimeTimeout = 25
-- | Connection script is the script which provides asynchronous demotions
-- either to cold or warm peer.
--
type ConnectionScript = TimedScript AsyncDemotion
data AsyncDemotion = ToWarm
| ToCold
| Noop
deriving (Eq, Show)
-- | Invariant. Used to check the QC generator and shrinker.
--
validPeerGraph :: PeerGraph -> Bool
validPeerGraph g@(PeerGraph adjacency) =
and [ edgesSet `Set.isSubsetOf` allpeersSet &&
gossipSet `Set.isSubsetOf` edgesSet
| let allpeersSet = allPeers g
, (_, outedges, GovernorScripts { gossipScript = Script script }) <- adjacency
, let edgesSet = Set.fromList outedges
gossipSet = Set.fromList
[ x | Just (xs, _) <- NonEmpty.toList script
, x <- xs ]
]
--
-- Utils for properties
--
allPeers :: PeerGraph -> Set PeerAddr
allPeers (PeerGraph g) = Set.fromList [ addr | (addr, _, _) <- g ]
-- | The peers that are notionally reachable from the root set. It is notional
-- in the sense that it only takes account of the connectivity graph and not
the ' GossipScript 's which determine what subset of edges the governor
-- actually sees when it tries to gossip.
--
_notionallyReachablePeers :: PeerGraph -> Set PeerAddr -> Set PeerAddr
_notionallyReachablePeers pg roots =
Set.fromList
. map vertexToAddr
. concatMap Tree.flatten
. Graph.dfs graph
. map addrToVertex
$ Set.toList roots
where
(graph, vertexToAddr, addrToVertex) = peerGraphAsGraph pg
firstGossipReachablePeers :: PeerGraph -> Set PeerAddr -> Set PeerAddr
firstGossipReachablePeers pg roots =
Set.fromList
. map vertexToAddr
. concatMap Tree.flatten
. Graph.dfs graph
. map addrToVertex
$ Set.toList roots
where
(graph, vertexToAddr, addrToVertex) = firstGossipGraph pg
peerGraphAsGraph :: PeerGraph
-> (Graph, Graph.Vertex -> PeerAddr, PeerAddr -> Graph.Vertex)
peerGraphAsGraph (PeerGraph adjacency) =
simpleGraphRep $
Graph.graphFromEdges [ ((), node, edges) | (node, edges, _) <- adjacency ]
firstGossipGraph :: PeerGraph
-> (Graph, Graph.Vertex -> PeerAddr, PeerAddr -> Graph.Vertex)
firstGossipGraph (PeerGraph adjacency) =
simpleGraphRep $
Graph.graphFromEdges
[ ((), node, gossipScriptEdges gossipScript)
| (node, _edges, GovernorScripts { gossipScript }) <- adjacency ]
where
gossipScriptEdges :: GossipScript -> [PeerAddr]
gossipScriptEdges (Script (script :| _)) =
case script of
Nothing -> []
Just (_, GossipTimeTimeout) -> []
Just (edges, _) -> edges
simpleGraphRep :: forall a n.
(Graph, Graph.Vertex -> (a, n, [n]), n -> Maybe Graph.Vertex)
-> (Graph, Graph.Vertex -> n, n -> Graph.Vertex)
simpleGraphRep (graph, vertexInfo, lookupVertex) =
(graph, vertexToAddr, addrToVertex)
where
vertexToAddr :: Graph.Vertex -> n
vertexToAddr v = addr where (_,addr,_) = vertexInfo v
addrToVertex :: n -> Graph.Vertex
addrToVertex addr = v where Just v = lookupVertex addr
--
QuickCheck instances
--
instance Arbitrary AsyncDemotion where
arbitrary = frequency [ (2, pure ToWarm)
, (2, pure ToCold)
, (6, pure Noop)
]
shrink ToWarm = [ToCold, Noop]
shrink ToCold = [Noop]
shrink Noop = []
instance Arbitrary GovernorScripts where
arbitrary = GovernorScripts
<$> arbitrary
<*> (fixConnectionScript <$> arbitrary)
shrink GovernorScripts { gossipScript, connectionScript } =
[ GovernorScripts gossipScript' connectionScript
| gossipScript' <- shrink gossipScript
]
++
[ GovernorScripts gossipScript connectionScript'
| connectionScript' <- map fixConnectionScript (shrink connectionScript)
-- fixConnectionScript can result in re-creating the same script
-- which would cause shrinking to loop. Filter out such cases.
, connectionScript' /= connectionScript
]
-- | We ensure that eventually the connection script will allow to connect to
-- a given peer. This simplifies test conditions.
--
fixConnectionScript :: ConnectionScript -> ConnectionScript
fixConnectionScript (Script script) =
case NonEmpty.last script of
(Noop, _) -> Script script
_ -> Script $ script <> ((Noop, NoDelay) :| [])
instance Arbitrary PeerGraph where
arbitrary = sized $ \sz -> do
numNodes <- choose (0, sz)
numEdges <- choose (numNodes, numNodes * numNodes `div` 2)
edges <- vectorOf numEdges $
(,) <$> choose (0, numNodes-1)
<*> choose (0, numNodes-1)
let adjacency = Map.fromListWith (<>)
[ (from, Set.singleton (PeerAddr to))
| (from, to) <- edges ]
graph <- sequence [ do gossipScript <- arbitraryGossipScript outedges
connectionScript <- fixConnectionScript <$> arbitrary
let node = GovernorScripts { gossipScript, connectionScript }
return (PeerAddr n, outedges, node)
| n <- [0..numNodes-1]
, let outedges = maybe [] Set.toList
(Map.lookup n adjacency) ]
return (PeerGraph graph)
shrink (PeerGraph graph) =
[ PeerGraph (prunePeerGraphEdges graph')
| graph' <- shrinkList shrinkNode graph ]
where
shrinkNode (nodeaddr, edges, script) =
-- shrink edges before gossip script, and addr does not shrink
[ (nodeaddr, edges', script)
| edges' <- shrinkList shrinkNothing edges ]
++ [ (nodeaddr, edges, script')
| script' <- shrink script ]
arbitraryGossipScript :: [PeerAddr] -> Gen GossipScript
arbitraryGossipScript peers =
sized $ \sz ->
arbitraryScriptOf (isqrt sz) gossipResult
where
gossipResult :: Gen (Maybe ([PeerAddr], GossipTime))
gossipResult =
frequency [ (1, pure Nothing)
, (4, Just <$> ((,) <$> selectHalfRandomly peers
<*> arbitrary)) ]
selectHalfRandomly :: [a] -> Gen [a]
selectHalfRandomly xs = do
picked <- vectorOf (length xs) arbitrary
return [ x | (x, True) <- zip xs picked ]
isqrt :: Int -> Int
isqrt = floor . sqrt . (fromIntegral :: Int -> Double)
-- | Remove dangling graph edges and gossip results.
--
prunePeerGraphEdges :: [(PeerAddr, [PeerAddr], PeerInfo)]
-> [(PeerAddr, [PeerAddr], PeerInfo)]
prunePeerGraphEdges graph =
[ (nodeaddr, edges', node)
| let nodes = Set.fromList [ nodeaddr | (nodeaddr, _, _) <- graph ]
, (nodeaddr, edges, GovernorScripts { gossipScript = Script gossip, connectionScript }) <- graph
, let edges' = pruneEdgeList nodes edges
gossip' = pruneGossipScript (Set.fromList edges') gossip
node = GovernorScripts {
gossipScript = Script gossip',
connectionScript
}
]
where
pruneEdgeList :: Set PeerAddr -> [PeerAddr] -> [PeerAddr]
pruneEdgeList nodes = filter (`Set.member` nodes)
pruneGossipScript :: Set PeerAddr
-> NonEmpty (Maybe ([PeerAddr], GossipTime))
-> NonEmpty (Maybe ([PeerAddr], GossipTime))
pruneGossipScript nodes =
NonEmpty.map (fmap (\(es, t) -> (pruneEdgeList nodes es, t)))
instance Arbitrary GossipTime where
arbitrary = frequency [ (2, pure GossipTimeQuick)
, (2, pure GossipTimeSlow)
, (1, pure GossipTimeTimeout) ]
shrink GossipTimeTimeout = [GossipTimeQuick, GossipTimeSlow]
shrink GossipTimeSlow = [GossipTimeQuick]
shrink GossipTimeQuick = []
--
-- Tests for the QC Arbitrary instances
--
prop_shrink_GovernorScripts :: Fixed GovernorScripts -> Property
prop_shrink_GovernorScripts =
prop_shrink_nonequal
prop_arbitrary_PeerGraph :: PeerGraph -> Property
prop_arbitrary_PeerGraph pg =
-- We are interested in the distribution of the graph size (in nodes)
-- and the number of separate components so that we can see that we
-- get some coverage of graphs that are not fully connected.
tabulate "graph size" [graphSize] $
tabulate "graph components" [graphComponents] $
validPeerGraph pg
where
graphSize = renderGraphSize (length g) where PeerGraph g = pg
graphComponents = renderNumComponents
(peerGraphNumStronglyConnectedComponents pg)
renderGraphSize n
| n == 0 = "0"
| n <= 9 = "1 -- 9"
| otherwise = renderRanges 10 n
renderNumComponents n
| n <= 4 = show n
| otherwise = renderRanges 5 n
peerGraphNumStronglyConnectedComponents :: PeerGraph -> Int
peerGraphNumStronglyConnectedComponents pg =
length (Graph.scc g)
where
(g,_,_) = peerGraphAsGraph pg
prop_shrink_PeerGraph :: Fixed PeerGraph -> Property
prop_shrink_PeerGraph x =
prop_shrink_valid validPeerGraph x
.&&. prop_shrink_nonequal x
prop_shrinkCarefully_PeerGraph :: ShrinkCarefully PeerGraph -> Property
prop_shrinkCarefully_PeerGraph = prop_shrinkCarefully
prop_shrinkCarefully_GovernorScripts :: ShrinkCarefully GovernorScripts -> Property
prop_shrinkCarefully_GovernorScripts = prop_shrinkCarefully
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/679c7da2079a5e9972a1c502b6a4d6af3eb76945/ouroboros-network/test/Test/Ouroboros/Network/PeerSelection/PeerGraph.hs | haskell |
Mock environment types
traditional adjacency representation.
| For now the information associated with each node is just the gossip
script and connection script.
| The gossip script is the script we interpret to provide answers to gossip
requests that the governor makes. After each gossip request to a peer we
move on to the next entry in the script, unless we get to the end in which
case that becomes the reply for all remaining gossips.
A @Nothing@ indicates failure. The @[PeerAddr]@ is the list of peers to
return which must always be a subset of the actual edges in the p2p graph.
This representation was chosen because it allows easy shrinking.
| The gossp time is our simulation of elapsed time to respond to gossip
requests. This is important because the governor uses timeouts and behaves
| Connection script is the script which provides asynchronous demotions
either to cold or warm peer.
| Invariant. Used to check the QC generator and shrinker.
Utils for properties
| The peers that are notionally reachable from the root set. It is notional
in the sense that it only takes account of the connectivity graph and not
actually sees when it tries to gossip.
fixConnectionScript can result in re-creating the same script
which would cause shrinking to loop. Filter out such cases.
| We ensure that eventually the connection script will allow to connect to
a given peer. This simplifies test conditions.
shrink edges before gossip script, and addr does not shrink
| Remove dangling graph edges and gossip results.
Tests for the QC Arbitrary instances
We are interested in the distribution of the graph size (in nodes)
and the number of separate components so that we can see that we
get some coverage of graphs that are not fully connected. | # LANGUAGE NamedFieldPuns #
# LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -Wno - orphans #
# OPTIONS_GHC -Wno - incomplete - uni - patterns #
module Test.Ouroboros.Network.PeerSelection.PeerGraph
( PeerGraph (..)
, validPeerGraph
, allPeers
, firstGossipReachablePeers
, GovernorScripts (..)
, GossipScript
, ConnectionScript
, AsyncDemotion (..)
, GossipTime (..)
, interpretGossipTime
, prop_shrink_GovernorScripts
, prop_arbitrary_PeerGraph
, prop_shrink_PeerGraph
, prop_shrinkCarefully_PeerGraph
, prop_shrinkCarefully_GovernorScripts
) where
import Data.Graph (Graph)
import qualified Data.Graph as Graph
import Data.List.NonEmpty (NonEmpty ((:|)))
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Tree as Tree
import Control.Monad.Class.MonadTime
import Ouroboros.Network.Testing.Data.Script (Script (..),
ScriptDelay (NoDelay), TimedScript, arbitraryScriptOf)
import Ouroboros.Network.Testing.Utils (prop_shrink_nonequal,
prop_shrink_valid, renderRanges)
import Test.Ouroboros.Network.PeerSelection.Instances
import Test.Ouroboros.Network.ShrinkCarefully
import Test.QuickCheck
| The peer graph is the graph of all the peers in the mock p2p network , in
newtype PeerGraph = PeerGraph [(PeerAddr, [PeerAddr], PeerInfo)]
deriving (Eq, Show)
type PeerInfo = GovernorScripts
data GovernorScripts = GovernorScripts {
gossipScript :: GossipScript,
connectionScript :: ConnectionScript
}
deriving (Eq, Show)
type GossipScript = Script (Maybe ([PeerAddr], GossipTime))
differently in these three cases .
data GossipTime = GossipTimeQuick | GossipTimeSlow | GossipTimeTimeout
deriving (Eq, Show)
interpretGossipTime :: GossipTime -> DiffTime
interpretGossipTime GossipTimeQuick = 1
interpretGossipTime GossipTimeSlow = 5
interpretGossipTime GossipTimeTimeout = 25
type ConnectionScript = TimedScript AsyncDemotion
data AsyncDemotion = ToWarm
| ToCold
| Noop
deriving (Eq, Show)
validPeerGraph :: PeerGraph -> Bool
validPeerGraph g@(PeerGraph adjacency) =
and [ edgesSet `Set.isSubsetOf` allpeersSet &&
gossipSet `Set.isSubsetOf` edgesSet
| let allpeersSet = allPeers g
, (_, outedges, GovernorScripts { gossipScript = Script script }) <- adjacency
, let edgesSet = Set.fromList outedges
gossipSet = Set.fromList
[ x | Just (xs, _) <- NonEmpty.toList script
, x <- xs ]
]
allPeers :: PeerGraph -> Set PeerAddr
allPeers (PeerGraph g) = Set.fromList [ addr | (addr, _, _) <- g ]
the ' GossipScript 's which determine what subset of edges the governor
_notionallyReachablePeers :: PeerGraph -> Set PeerAddr -> Set PeerAddr
_notionallyReachablePeers pg roots =
Set.fromList
. map vertexToAddr
. concatMap Tree.flatten
. Graph.dfs graph
. map addrToVertex
$ Set.toList roots
where
(graph, vertexToAddr, addrToVertex) = peerGraphAsGraph pg
firstGossipReachablePeers :: PeerGraph -> Set PeerAddr -> Set PeerAddr
firstGossipReachablePeers pg roots =
Set.fromList
. map vertexToAddr
. concatMap Tree.flatten
. Graph.dfs graph
. map addrToVertex
$ Set.toList roots
where
(graph, vertexToAddr, addrToVertex) = firstGossipGraph pg
peerGraphAsGraph :: PeerGraph
-> (Graph, Graph.Vertex -> PeerAddr, PeerAddr -> Graph.Vertex)
peerGraphAsGraph (PeerGraph adjacency) =
simpleGraphRep $
Graph.graphFromEdges [ ((), node, edges) | (node, edges, _) <- adjacency ]
firstGossipGraph :: PeerGraph
-> (Graph, Graph.Vertex -> PeerAddr, PeerAddr -> Graph.Vertex)
firstGossipGraph (PeerGraph adjacency) =
simpleGraphRep $
Graph.graphFromEdges
[ ((), node, gossipScriptEdges gossipScript)
| (node, _edges, GovernorScripts { gossipScript }) <- adjacency ]
where
gossipScriptEdges :: GossipScript -> [PeerAddr]
gossipScriptEdges (Script (script :| _)) =
case script of
Nothing -> []
Just (_, GossipTimeTimeout) -> []
Just (edges, _) -> edges
simpleGraphRep :: forall a n.
(Graph, Graph.Vertex -> (a, n, [n]), n -> Maybe Graph.Vertex)
-> (Graph, Graph.Vertex -> n, n -> Graph.Vertex)
simpleGraphRep (graph, vertexInfo, lookupVertex) =
(graph, vertexToAddr, addrToVertex)
where
vertexToAddr :: Graph.Vertex -> n
vertexToAddr v = addr where (_,addr,_) = vertexInfo v
addrToVertex :: n -> Graph.Vertex
addrToVertex addr = v where Just v = lookupVertex addr
QuickCheck instances
instance Arbitrary AsyncDemotion where
arbitrary = frequency [ (2, pure ToWarm)
, (2, pure ToCold)
, (6, pure Noop)
]
shrink ToWarm = [ToCold, Noop]
shrink ToCold = [Noop]
shrink Noop = []
instance Arbitrary GovernorScripts where
arbitrary = GovernorScripts
<$> arbitrary
<*> (fixConnectionScript <$> arbitrary)
shrink GovernorScripts { gossipScript, connectionScript } =
[ GovernorScripts gossipScript' connectionScript
| gossipScript' <- shrink gossipScript
]
++
[ GovernorScripts gossipScript connectionScript'
| connectionScript' <- map fixConnectionScript (shrink connectionScript)
, connectionScript' /= connectionScript
]
fixConnectionScript :: ConnectionScript -> ConnectionScript
fixConnectionScript (Script script) =
case NonEmpty.last script of
(Noop, _) -> Script script
_ -> Script $ script <> ((Noop, NoDelay) :| [])
instance Arbitrary PeerGraph where
arbitrary = sized $ \sz -> do
numNodes <- choose (0, sz)
numEdges <- choose (numNodes, numNodes * numNodes `div` 2)
edges <- vectorOf numEdges $
(,) <$> choose (0, numNodes-1)
<*> choose (0, numNodes-1)
let adjacency = Map.fromListWith (<>)
[ (from, Set.singleton (PeerAddr to))
| (from, to) <- edges ]
graph <- sequence [ do gossipScript <- arbitraryGossipScript outedges
connectionScript <- fixConnectionScript <$> arbitrary
let node = GovernorScripts { gossipScript, connectionScript }
return (PeerAddr n, outedges, node)
| n <- [0..numNodes-1]
, let outedges = maybe [] Set.toList
(Map.lookup n adjacency) ]
return (PeerGraph graph)
shrink (PeerGraph graph) =
[ PeerGraph (prunePeerGraphEdges graph')
| graph' <- shrinkList shrinkNode graph ]
where
shrinkNode (nodeaddr, edges, script) =
[ (nodeaddr, edges', script)
| edges' <- shrinkList shrinkNothing edges ]
++ [ (nodeaddr, edges, script')
| script' <- shrink script ]
arbitraryGossipScript :: [PeerAddr] -> Gen GossipScript
arbitraryGossipScript peers =
sized $ \sz ->
arbitraryScriptOf (isqrt sz) gossipResult
where
gossipResult :: Gen (Maybe ([PeerAddr], GossipTime))
gossipResult =
frequency [ (1, pure Nothing)
, (4, Just <$> ((,) <$> selectHalfRandomly peers
<*> arbitrary)) ]
selectHalfRandomly :: [a] -> Gen [a]
selectHalfRandomly xs = do
picked <- vectorOf (length xs) arbitrary
return [ x | (x, True) <- zip xs picked ]
isqrt :: Int -> Int
isqrt = floor . sqrt . (fromIntegral :: Int -> Double)
prunePeerGraphEdges :: [(PeerAddr, [PeerAddr], PeerInfo)]
-> [(PeerAddr, [PeerAddr], PeerInfo)]
prunePeerGraphEdges graph =
[ (nodeaddr, edges', node)
| let nodes = Set.fromList [ nodeaddr | (nodeaddr, _, _) <- graph ]
, (nodeaddr, edges, GovernorScripts { gossipScript = Script gossip, connectionScript }) <- graph
, let edges' = pruneEdgeList nodes edges
gossip' = pruneGossipScript (Set.fromList edges') gossip
node = GovernorScripts {
gossipScript = Script gossip',
connectionScript
}
]
where
pruneEdgeList :: Set PeerAddr -> [PeerAddr] -> [PeerAddr]
pruneEdgeList nodes = filter (`Set.member` nodes)
pruneGossipScript :: Set PeerAddr
-> NonEmpty (Maybe ([PeerAddr], GossipTime))
-> NonEmpty (Maybe ([PeerAddr], GossipTime))
pruneGossipScript nodes =
NonEmpty.map (fmap (\(es, t) -> (pruneEdgeList nodes es, t)))
instance Arbitrary GossipTime where
arbitrary = frequency [ (2, pure GossipTimeQuick)
, (2, pure GossipTimeSlow)
, (1, pure GossipTimeTimeout) ]
shrink GossipTimeTimeout = [GossipTimeQuick, GossipTimeSlow]
shrink GossipTimeSlow = [GossipTimeQuick]
shrink GossipTimeQuick = []
prop_shrink_GovernorScripts :: Fixed GovernorScripts -> Property
prop_shrink_GovernorScripts =
prop_shrink_nonequal
prop_arbitrary_PeerGraph :: PeerGraph -> Property
prop_arbitrary_PeerGraph pg =
tabulate "graph size" [graphSize] $
tabulate "graph components" [graphComponents] $
validPeerGraph pg
where
graphSize = renderGraphSize (length g) where PeerGraph g = pg
graphComponents = renderNumComponents
(peerGraphNumStronglyConnectedComponents pg)
renderGraphSize n
| n == 0 = "0"
| n <= 9 = "1 -- 9"
| otherwise = renderRanges 10 n
renderNumComponents n
| n <= 4 = show n
| otherwise = renderRanges 5 n
peerGraphNumStronglyConnectedComponents :: PeerGraph -> Int
peerGraphNumStronglyConnectedComponents pg =
length (Graph.scc g)
where
(g,_,_) = peerGraphAsGraph pg
prop_shrink_PeerGraph :: Fixed PeerGraph -> Property
prop_shrink_PeerGraph x =
prop_shrink_valid validPeerGraph x
.&&. prop_shrink_nonequal x
prop_shrinkCarefully_PeerGraph :: ShrinkCarefully PeerGraph -> Property
prop_shrinkCarefully_PeerGraph = prop_shrinkCarefully
prop_shrinkCarefully_GovernorScripts :: ShrinkCarefully GovernorScripts -> Property
prop_shrinkCarefully_GovernorScripts = prop_shrinkCarefully
|
4319949c7e006d18465741078a9e94d3715e44a49751f35e5cfbc609d7099668 | TypedLambda/eresye | relatives.erl | %
% relatives.erl
%
% -------------------------------------------------------------------------
%
%%
ERESYE , an ERlang Expert SYstem Engine
%%
Copyright ( c ) 2005 - 2010 , ,
%% All rights reserved.
%%
%% Redistribution and use in source and binary forms, with or without
%% modification, are permitted provided that the following conditions are met:
%% * Redistributions of source code must retain the above copyright
%% notice, this list of conditions and the following disclaimer.
%% * Redistributions in binary form must reproduce the above copyright
%% notice, this list of conditions and the following disclaimer in the
%% documentation and/or other materials provided with the distribution.
* Neither the name of , may be used
%% to endorse or promote products derived from this software without
%% specific prior written permission.
%%
%%
THIS SOFTWARE IS PROVIDED BY AND ` ` AS
%% IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
%% THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
%% PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR
ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
%% OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
%% SUCH DAMAGE.
%%
-module (relatives).
-compile ([export_all]).
%%
%% if (X is female) and (X is Y's parent) then (X is Y's mother)
%%
mother (Engine, {female, X}, {parent, X, Y}) ->
eresye:assert (Engine, {mother, X, Y}).
%%
%% if (X is male) and (X is Y's parent) then (X is Y's father)
%%
father (Engine, {male, X}, {parent, X, Y}) ->
eresye:assert (Engine, {father, X, Y}).
%%
%% if (Y and Z have the same parent X) and (Z is female)
%% then (Z is Y's sister)
%%
sister (Engine, {parent, X, Y}, {parent, X, Z}, {female, Z}) when Y =/= Z ->
eresye:assert (Engine, {sister, Z, Y}).
%%
%% if (Y and Z have the same parent X) and (Z is male)
%% then (Z is Y's brother)
%%
brother (Engine, {parent, X, Y}, {parent, X, Z}, {male, Z}) when Y =/= Z ->
eresye:assert (Engine, {brother, Z, Y}).
%%
if ( X is Y 's father ) and ( Y is Z 's parent )
%% then (X is Z's grandfather)
%%
grandfather (Engine, {father, X, Y}, {parent, Y, Z}) ->
eresye:assert (Engine, {grandfather, X, Z}).
%%
if ( X is Y 's mother ) and ( Y is Z 's parent )
%% then (X is Z's grandmother)
%%
grandmother (Engine, {mother, X, Y}, {parent, Y, Z}) ->
eresye:assert (Engine, {grandmother, X, Z}).
start () ->
eresye:start (relatives),
lists:foreach (fun (X) ->
eresye:add_rule (relatives, {?MODULE, X})
end,
[mother, father,
brother, sister,
grandfather, grandmother]),
eresye:assert (relatives,
[{male, bob},
{male, corrado},
{male, mark},
{male, caesar},
{female, alice},
{female, sara},
{female, jane},
{female, anna},
{parent, jane, bob},
{parent, corrado, bob},
{parent, jane, mark},
{parent, corrado, mark},
{parent, jane, alice},
{parent, corrado, alice},
{parent, bob, caesar},
{parent, bob, anna},
{parent, sara, casear},
{parent, sara, anna}]),
ok.
| null | https://raw.githubusercontent.com/TypedLambda/eresye/58c159e7fbe8ebaed52018b1a7761d534b4d6119/examples/relatives.erl | erlang |
relatives.erl
-------------------------------------------------------------------------
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
to endorse or promote products derived from this software without
specific prior written permission.
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
if (X is female) and (X is Y's parent) then (X is Y's mother)
if (X is male) and (X is Y's parent) then (X is Y's father)
if (Y and Z have the same parent X) and (Z is female)
then (Z is Y's sister)
if (Y and Z have the same parent X) and (Z is male)
then (Z is Y's brother)
then (X is Z's grandfather)
then (X is Z's grandmother)
| ERESYE , an ERlang Expert SYstem Engine
Copyright ( c ) 2005 - 2010 , ,
* Neither the name of , may be used
THIS SOFTWARE IS PROVIDED BY AND ` ` AS
ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
-module (relatives).
-compile ([export_all]).
mother (Engine, {female, X}, {parent, X, Y}) ->
eresye:assert (Engine, {mother, X, Y}).
father (Engine, {male, X}, {parent, X, Y}) ->
eresye:assert (Engine, {father, X, Y}).
sister (Engine, {parent, X, Y}, {parent, X, Z}, {female, Z}) when Y =/= Z ->
eresye:assert (Engine, {sister, Z, Y}).
brother (Engine, {parent, X, Y}, {parent, X, Z}, {male, Z}) when Y =/= Z ->
eresye:assert (Engine, {brother, Z, Y}).
if ( X is Y 's father ) and ( Y is Z 's parent )
grandfather (Engine, {father, X, Y}, {parent, Y, Z}) ->
eresye:assert (Engine, {grandfather, X, Z}).
if ( X is Y 's mother ) and ( Y is Z 's parent )
grandmother (Engine, {mother, X, Y}, {parent, Y, Z}) ->
eresye:assert (Engine, {grandmother, X, Z}).
start () ->
eresye:start (relatives),
lists:foreach (fun (X) ->
eresye:add_rule (relatives, {?MODULE, X})
end,
[mother, father,
brother, sister,
grandfather, grandmother]),
eresye:assert (relatives,
[{male, bob},
{male, corrado},
{male, mark},
{male, caesar},
{female, alice},
{female, sara},
{female, jane},
{female, anna},
{parent, jane, bob},
{parent, corrado, bob},
{parent, jane, mark},
{parent, corrado, mark},
{parent, jane, alice},
{parent, corrado, alice},
{parent, bob, caesar},
{parent, bob, anna},
{parent, sara, casear},
{parent, sara, anna}]),
ok.
|
a056533822535f8ae5320536916a072f8afaaafddede4c72b5965075c74b3ae9 | walkable-server/realworld-fulcro | article.clj | (ns conduit.boundary.article
(:require [clojure.java.jdbc :as jdbc]
[clojure.set :refer [rename-keys]]
[clojure.string :as str]
[conduit.util :as util]
[duct.database.sql]))
(def remove-article-namespace
(util/remove-namespace "article" [:title :body :slug :description :tags]))
(defprotocol Article
(article-by-slug [db article])
(create-article [db author-id article])
(destroy-article [db author-id article-id])
(update-article [db author-id id article])
(like [db user-id article-id])
(unlike [db user-id article-id]))
(defprotocol Comment
(create-comment [db author-id article-id comment])
(update-comment [db author-id comment-id comment])
(destroy-comment [db author-id comment-id]))
(defprotocol Tag
(add-tag [db author-id article-id tag])
(remove-tag [db author-id article-id tag]))
(defn delete-non-existing-where-clause [article-id existing]
(concat
[(str "article_id = ? and tag not in ("
(str/join ", " (repeat (count existing) \?))
")")
article-id]
(vec existing)))
(comment
(= (delete-non-existing-where-clause 1 #{"foo" "bar"})
["article_id = ? and tag not in (?, ?)" 1 "foo" "bar"]))
(extend-protocol Article
duct.database.sql.Boundary
(article-by-slug [{db :spec} article-slug]
(:id (first (jdbc/find-by-keys db "\"article\"" {:slug article-slug}))))
(create-article [{db :spec} author-id article]
(let [tags (:article/tags article)
article (-> (rename-keys article remove-article-namespace)
(select-keys [:title :slug :description :body])
(assoc :author_id author-id))
results (jdbc/insert! db "\"article\"" article)
new-article-id (-> results first :id)]
(when new-article-id
(when (seq tags)
(jdbc/insert-multi! db "\"tag\""
(mapv (fn [{:tag/keys [tag]}] {:article_id new-article-id :tag tag}) tags)))
new-article-id)))
(destroy-article [db author-id article-id]
(jdbc/delete! (:spec db) "\"article\"" ["author_id = ? AND id = ?" author-id article-id]))
(update-article [db author-id id article]
(let [results (jdbc/query (:spec db)
["select id, article_id, tag from \"article\" left join \"tag\" on tag.article_id = article.id where author_id = ? and id = ?"
author-id id])]
(when (seq results)
(let [new-article (-> (rename-keys article remove-article-namespace)
(select-keys [:slug :title :description :body]))]
(when (seq new-article)
(jdbc/update! (:spec db) "\"article\"" new-article ["id = ?" id])))
(when (:article/tags article)
(let [old-tags (->> (filter :article_id results)
(map :tag) set)
new-tags (->> (:article/tags article)
(map :tag/tag) set)
existing (clojure.set/intersection old-tags new-tags)]
(jdbc/delete! (:spec db) "\"tag\"" (delete-non-existing-where-clause id existing))
(jdbc/insert-multi! (:spec db) "\"tag\""
(->> (clojure.set/difference new-tags existing)
(mapv (fn [tag] {:article_id id :tag tag}))))
{})))))
(like [db user-id article-id]
(jdbc/execute! (:spec db)
[(str "INSERT INTO \"favorite\" (user_id, article_id)"
" SELECT ?, ?"
" WHERE NOT EXISTS (SELECT * FROM \"favorite\""
" WHERE user_id = ? AND article_id = ?)")
user-id article-id user-id article-id]))
(unlike [db user-id article-id]
(jdbc/delete! (:spec db) "\"favorite\"" ["user_id = ? AND article_id = ?" user-id article-id]))
)
(extend-protocol Comment
duct.database.sql.Boundary
(create-comment [db author-id article-id comment-item]
(let [comment-item (-> comment-item
(select-keys [:body])
(assoc :author_id author-id)
(assoc :article_id article-id))
results (jdbc/insert! (:spec db) "\"comment\"" comment-item)]
(-> results first :id)))
(update-comment [db author-id comment-id comment-item]
(jdbc/update! (:spec db) "\"comment\"" (select-keys comment-item [:body])
["author_id = ? AND id = ?" author-id comment-id]))
(destroy-comment [{db :spec} author-id comment-id]
(jdbc/delete! db "\"comment\"" ["author_id = ? AND id = ?" author-id comment-id])))
(extend-protocol Tag
duct.database.sql.Boundary
(add-tag [db author-id article-id tag]
(let [results (jdbc/query (:spec db)
["select id from \"article\" where author_id = ? and id = ?"
author-id article-id])]
(when (seq results)
(jdbc/execute! (:spec db)
[(str "INSERT INTO \"tag\" (tag, article_id)"
" SELECT ?, ?"
" WHERE NOT EXISTS (SELECT * FROM \"tag\""
" WHERE tag = ? AND article_id = ?)")
tag article-id tag article-id]))))
(remove-tag [db author-id article-id tag]
(let [results (jdbc/query (:spec db)
["select id from \"article\" where author_id = ? and id = ?"
author-id article-id])]
(when (seq results)
(jdbc/delete! (:spec db) "\"tag\"" ["tag = ? AND article_id = ?" tag article-id])))))
| null | https://raw.githubusercontent.com/walkable-server/realworld-fulcro/91c73e3a27621b528906d12bc22971caa9ea8d13/src/conduit/boundary/article.clj | clojure | (ns conduit.boundary.article
(:require [clojure.java.jdbc :as jdbc]
[clojure.set :refer [rename-keys]]
[clojure.string :as str]
[conduit.util :as util]
[duct.database.sql]))
(def remove-article-namespace
(util/remove-namespace "article" [:title :body :slug :description :tags]))
(defprotocol Article
(article-by-slug [db article])
(create-article [db author-id article])
(destroy-article [db author-id article-id])
(update-article [db author-id id article])
(like [db user-id article-id])
(unlike [db user-id article-id]))
(defprotocol Comment
(create-comment [db author-id article-id comment])
(update-comment [db author-id comment-id comment])
(destroy-comment [db author-id comment-id]))
(defprotocol Tag
(add-tag [db author-id article-id tag])
(remove-tag [db author-id article-id tag]))
(defn delete-non-existing-where-clause [article-id existing]
(concat
[(str "article_id = ? and tag not in ("
(str/join ", " (repeat (count existing) \?))
")")
article-id]
(vec existing)))
(comment
(= (delete-non-existing-where-clause 1 #{"foo" "bar"})
["article_id = ? and tag not in (?, ?)" 1 "foo" "bar"]))
(extend-protocol Article
duct.database.sql.Boundary
(article-by-slug [{db :spec} article-slug]
(:id (first (jdbc/find-by-keys db "\"article\"" {:slug article-slug}))))
(create-article [{db :spec} author-id article]
(let [tags (:article/tags article)
article (-> (rename-keys article remove-article-namespace)
(select-keys [:title :slug :description :body])
(assoc :author_id author-id))
results (jdbc/insert! db "\"article\"" article)
new-article-id (-> results first :id)]
(when new-article-id
(when (seq tags)
(jdbc/insert-multi! db "\"tag\""
(mapv (fn [{:tag/keys [tag]}] {:article_id new-article-id :tag tag}) tags)))
new-article-id)))
(destroy-article [db author-id article-id]
(jdbc/delete! (:spec db) "\"article\"" ["author_id = ? AND id = ?" author-id article-id]))
(update-article [db author-id id article]
(let [results (jdbc/query (:spec db)
["select id, article_id, tag from \"article\" left join \"tag\" on tag.article_id = article.id where author_id = ? and id = ?"
author-id id])]
(when (seq results)
(let [new-article (-> (rename-keys article remove-article-namespace)
(select-keys [:slug :title :description :body]))]
(when (seq new-article)
(jdbc/update! (:spec db) "\"article\"" new-article ["id = ?" id])))
(when (:article/tags article)
(let [old-tags (->> (filter :article_id results)
(map :tag) set)
new-tags (->> (:article/tags article)
(map :tag/tag) set)
existing (clojure.set/intersection old-tags new-tags)]
(jdbc/delete! (:spec db) "\"tag\"" (delete-non-existing-where-clause id existing))
(jdbc/insert-multi! (:spec db) "\"tag\""
(->> (clojure.set/difference new-tags existing)
(mapv (fn [tag] {:article_id id :tag tag}))))
{})))))
(like [db user-id article-id]
(jdbc/execute! (:spec db)
[(str "INSERT INTO \"favorite\" (user_id, article_id)"
" SELECT ?, ?"
" WHERE NOT EXISTS (SELECT * FROM \"favorite\""
" WHERE user_id = ? AND article_id = ?)")
user-id article-id user-id article-id]))
(unlike [db user-id article-id]
(jdbc/delete! (:spec db) "\"favorite\"" ["user_id = ? AND article_id = ?" user-id article-id]))
)
(extend-protocol Comment
duct.database.sql.Boundary
(create-comment [db author-id article-id comment-item]
(let [comment-item (-> comment-item
(select-keys [:body])
(assoc :author_id author-id)
(assoc :article_id article-id))
results (jdbc/insert! (:spec db) "\"comment\"" comment-item)]
(-> results first :id)))
(update-comment [db author-id comment-id comment-item]
(jdbc/update! (:spec db) "\"comment\"" (select-keys comment-item [:body])
["author_id = ? AND id = ?" author-id comment-id]))
(destroy-comment [{db :spec} author-id comment-id]
(jdbc/delete! db "\"comment\"" ["author_id = ? AND id = ?" author-id comment-id])))
(extend-protocol Tag
duct.database.sql.Boundary
(add-tag [db author-id article-id tag]
(let [results (jdbc/query (:spec db)
["select id from \"article\" where author_id = ? and id = ?"
author-id article-id])]
(when (seq results)
(jdbc/execute! (:spec db)
[(str "INSERT INTO \"tag\" (tag, article_id)"
" SELECT ?, ?"
" WHERE NOT EXISTS (SELECT * FROM \"tag\""
" WHERE tag = ? AND article_id = ?)")
tag article-id tag article-id]))))
(remove-tag [db author-id article-id tag]
(let [results (jdbc/query (:spec db)
["select id from \"article\" where author_id = ? and id = ?"
author-id article-id])]
(when (seq results)
(jdbc/delete! (:spec db) "\"tag\"" ["tag = ? AND article_id = ?" tag article-id])))))
| |
8a11d79971a742f0dbe02b175195e02dae3d4d4a1964a1a61c4f2518a18447bb | sbcl/sbcl | print.lisp | ;;;; the printer
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-IMPL")
;;;; exported printer control variables
(defvar *print-readably* nil
"If true, all objects will be printed readably. If readable printing
is impossible, an error will be signalled. This overrides the value of
*PRINT-ESCAPE*.")
(defvar *print-escape* t
"Should we print in a reasonably machine-readable way? (possibly
overridden by *PRINT-READABLY*)")
(defvar *print-pretty* nil ; (set later when pretty-printer is initialized)
"Should pretty printing be used?")
(defvar *print-base* 10.
"The output base for RATIONALs (including integers).")
(defvar *print-radix* nil
"Should base be verified when printing RATIONALs?")
(defvar *print-level* nil
"How many levels should be printed before abbreviating with \"#\"?")
(defvar *print-length* nil
"How many elements at any level should be printed before abbreviating
with \"...\"?")
(defvar *print-vector-length* nil
"Like *PRINT-LENGTH* but works on strings and bit-vectors.
Does not affect the cases that are already controlled by *PRINT-LENGTH*")
(defvar *print-circle* nil
"Should we use #n= and #n# notation to preserve uniqueness in general (and
circularity in particular) when printing?")
(defvar *print-case* :upcase
"What case should the printer should use default?")
(defvar *print-array* t
"Should the contents of arrays be printed?")
(defvar *print-gensym* t
"Should #: prefixes be used when printing symbols with null SYMBOL-PACKAGE?")
(defvar *print-lines* nil
"The maximum number of lines to print per object.")
(defvar *print-right-margin* nil
"The position of the right margin in ems (for pretty-printing).")
(defvar *print-miser-width* nil
"If the remaining space between the current column and the right margin
is less than this, then print using ``miser-style'' output. Miser
style conditional newlines are turned on, and all indentations are
turned off. If NIL, never use miser mode.")
(defvar *print-pprint-dispatch*
(sb-pretty::make-pprint-dispatch-table #() nil nil)
"The pprint-dispatch-table that controls how to pretty-print objects.")
(defvar *suppress-print-errors* nil
"Suppress printer errors when the condition is of the type designated by this
variable: an unreadable object representing the error is printed instead.")
duplicate defglobal because this file is compiled before " reader "
(define-load-time-global *standard-readtable* nil)
(define-load-time-global sb-pretty::*standard-pprint-dispatch-table* nil)
(defun %with-standard-io-syntax (function)
(declare (type function function))
(declare (dynamic-extent function))
(let ((*package* #.(find-package "COMMON-LISP-USER"))
(*print-array* t)
(*print-base* 10)
(*print-case* :upcase)
(*print-circle* nil)
(*print-escape* t)
(*print-gensym* t)
(*print-length* nil)
(*print-level* nil)
(*print-lines* nil)
(*print-miser-width* nil)
(*print-pprint-dispatch* sb-pretty::*standard-pprint-dispatch-table*)
(*print-pretty* nil)
(*print-radix* nil)
(*print-readably* t)
(*print-right-margin* nil)
(*read-base* 10)
(*read-default-float-format* 'single-float)
(*read-eval* t)
(*read-suppress* nil)
(*readtable* *standard-readtable*)
(*suppress-print-errors* nil)
(*print-vector-length* nil))
(funcall function)))
;;;; routines to print objects
(macrolet ((def (fn doc &rest forms)
`(defun ,fn
(object
&key
,@(if (eq fn 'write) '(stream))
((:escape *print-escape*) *print-escape*)
((:radix *print-radix*) *print-radix*)
((:base *print-base*) *print-base*)
((:circle *print-circle*) *print-circle*)
((:pretty *print-pretty*) *print-pretty*)
((:level *print-level*) *print-level*)
((:length *print-length*) *print-length*)
((:case *print-case*) *print-case*)
((:array *print-array*) *print-array*)
((:gensym *print-gensym*) *print-gensym*)
((:readably *print-readably*) *print-readably*)
((:right-margin *print-right-margin*)
*print-right-margin*)
((:miser-width *print-miser-width*)
*print-miser-width*)
((:lines *print-lines*) *print-lines*)
((:pprint-dispatch *print-pprint-dispatch*)
*print-pprint-dispatch*)
((:suppress-errors *suppress-print-errors*)
*suppress-print-errors*))
,doc
(declare (explicit-check))
,@forms)))
(def write
"Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*."
(output-object object (out-stream-from-designator stream))
object)
(def write-to-string
"Return the printed representation of OBJECT as a string."
(stringify-object object)))
;;; Same as a call to (WRITE OBJECT :STREAM STREAM), but returning OBJECT.
(defun %write (object stream)
(declare (explicit-check))
(output-object object (out-stream-from-designator stream))
object)
(defun prin1 (object &optional stream)
"Output a mostly READable printed representation of OBJECT on the specified
STREAM."
(declare (explicit-check))
(let ((*print-escape* t))
(output-object object (out-stream-from-designator stream)))
object)
(defun princ (object &optional stream)
"Output an aesthetic but not necessarily READable printed representation
of OBJECT on the specified STREAM."
(declare (explicit-check))
(let ((*print-escape* nil)
(*print-readably* nil))
(output-object object (out-stream-from-designator stream)))
object)
(defun print (object &optional stream)
"Output a newline, the mostly READable printed representation of OBJECT, and
space to the specified STREAM."
(declare (explicit-check))
(let ((stream (out-stream-from-designator stream)))
(terpri stream)
(prin1 object stream)
(write-char #\space stream)
object))
(defun pprint (object &optional stream)
"Prettily output OBJECT preceded by a newline."
(declare (explicit-check))
(let ((*print-pretty* t)
(*print-escape* t)
(stream (out-stream-from-designator stream)))
(terpri stream)
(output-object object stream))
(values))
(defun prin1-to-string (object)
"Return the printed representation of OBJECT as a string with
slashification on."
(let ((*print-escape* t))
(stringify-object object)))
(defun princ-to-string (object)
"Return the printed representation of OBJECT as a string with
slashification off."
(let ((*print-escape* nil)
(*print-readably* nil))
(stringify-object object)))
;;; This produces the printed representation of an object as a string.
;;; The few ...-TO-STRING functions above call this.
(defun stringify-object (object)
(typecase object
(integer
(multiple-value-bind (fun pretty)
(and *print-pretty* (pprint-dispatch object))
(if pretty
(%with-output-to-string (stream)
(sb-pretty:output-pretty-object stream fun object))
(let ((buffer-size (approx-chars-in-repr object)))
(let* ((string (make-string buffer-size :element-type 'base-char))
(stream (%make-finite-base-string-output-stream string)))
(declare (inline %make-finite-base-string-output-stream))
(declare (truly-dynamic-extent stream))
(output-integer object stream *print-base* *print-radix*)
(%shrink-vector string
(finite-base-string-output-stream-pointer stream)))))))
;; Could do something for other numeric types, symbols, ...
(t
(%with-output-to-string (stream)
(output-object object stream)))))
;;; Estimate the number of chars in the printed representation of OBJECT.
;;; The answer must be an overestimate or exact; never an underestimate.
(defun approx-chars-in-repr (object)
(declare (integer object))
;; Round *PRINT-BASE* down to the nearest lower power-of-2, call that N,
and " guess " that the one character can represent N bits .
;; This is exact for bases which are exactly a power-of-2, or an overestimate
;; otherwise, as mandated by the finite output stream.
(let ((bits-per-char
(aref #.(coerce
base 2 or base 3 = 1 bit per character
base 4 .. base 7 = 2 bits per character
base 8 .. base 15 = 3 bits per character , etc
#(1 1 2 2 2 2 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5)
'(vector (unsigned-byte 8)))
(- *print-base* 2))))
(+ (if (minusp object) 1 0) ; leading sign
(if *print-radix* 4 0) ; #rNN or trailing decimal
(ceiling (if (fixnump object)
sb-vm:n-positive-fixnum-bits
(* (%bignum-length object) sb-bignum::digit-size))
bits-per-char))))
;;;; support for the PRINT-UNREADABLE-OBJECT macro
(defun print-not-readable-error (object stream)
(restart-case
(error 'print-not-readable :object object)
(print-unreadably ()
:report "Print unreadably."
(let ((*print-readably* nil))
(output-object object stream)
object))
(use-value (o)
:report "Supply an object to be printed instead."
:interactive
(lambda ()
(read-evaluated-form "~@<Enter an object (evaluated): ~@:>"))
(output-object o stream)
o)))
;;; guts of PRINT-UNREADABLE-OBJECT
(defun %print-unreadable-object (object stream flags &optional body)
(declare (type (or null function) body))
(if *print-readably*
(print-not-readable-error object stream)
(flet ((print-description (&aux (type (logbitp 0 (truly-the (mod 4) flags)))
(identity (logbitp 1 flags)))
(when type
(write (type-of object) :stream stream :circle nil
:level nil :length nil)
;; Do NOT insert a pprint-newline here.
;; See ba34717602d80e5fd74d10e61f4729fb0d019a0c
(write-char #\space stream))
(when body
(funcall body))
(when identity
(when (or body (not type))
(write-char #\space stream))
;; Nor here.
(write-char #\{ stream)
(%output-integer-in-base (get-lisp-obj-address object) 16 stream)
(write-char #\} stream))))
(cond ((print-pretty-on-stream-p stream)
;; Since we're printing prettily on STREAM, format the
object within a logical block . PPRINT - LOGICAL - BLOCK does
;; not rebind the stream when it is already a pretty stream,
;; so output from the body will go to the same stream.
(pprint-logical-block (stream nil :prefix "#<" :suffix ">")
(print-description)))
(t
(write-string "#<" stream)
(print-description)
(write-char #\> stream)))))
nil)
;;;; circularity detection stuff
;;; When *PRINT-CIRCLE* is T, this gets bound to a hash table that
;;; (eventually) ends up with entries for every object printed. When
;;; we are initially looking for circularities, we enter a T when we
find an object for the first time , and a 0 when we encounter an
object a second time around . When we are actually printing , the 0
entries get changed to the actual marker value when they are first
;;; printed.
(defvar *circularity-hash-table* nil)
When NIL , we are just looking for circularities . After we have
;;; found them all, this gets bound to 0. Then whenever we need a new
;;; marker, it is incremented.
(defvar *circularity-counter* nil)
;;; Check to see whether OBJECT is a circular reference, and return
;;; something non-NIL if it is. If ASSIGN is true, reference
;;; bookkeeping will only be done for existing entries, no new
;;; references will be recorded. If ASSIGN is true, then the number to
use in the # n= and # n # noise is assigned at this time .
;;;
;;; Note: CHECK-FOR-CIRCULARITY must be called *exactly* once with
;;; ASSIGN true, or the circularity detection noise will get confused
about when to use # n= and when to use # n # . If this returns non - NIL
when is true , then you must call HANDLE - CIRCULARITY on it .
If CHECK - FOR - CIRCULARITY returns : INITIATE as the second value ,
;;; you need to initiate the circularity detection noise, e.g. bind
;;; *CIRCULARITY-HASH-TABLE* and *CIRCULARITY-COUNTER* to suitable values
;;; (see #'OUTPUT-OBJECT for an example).
;;;
Circularity detection is done in two places , OUTPUT - OBJECT and
WITH - CIRCULARITY - DETECTION ( which is used from PPRINT - LOGICAL - BLOCK ) .
;;; These checks aren't really redundant (at least I can't really see
a clean way of getting by with the checks in only one of the places ) .
;;; This causes problems when mixed with pprint-dispatching; an object is
;;; marked as visited in OUTPUT-OBJECT, dispatched to a pretty printer
that uses PPRINT - LOGICAL - BLOCK ( directly or indirectly ) , leading to
;;; output like #1=#1#. The MODE parameter is used for detecting and
;;; correcting this problem.
(defun check-for-circularity (object &optional assign (mode t))
(when (null *print-circle*)
;; Don't bother, nobody cares.
(return-from check-for-circularity nil))
(let ((circularity-hash-table *circularity-hash-table*))
(cond
((null circularity-hash-table)
(values nil :initiate))
((null *circularity-counter*)
(ecase (gethash object circularity-hash-table)
((nil)
;; first encounter
(setf (gethash object circularity-hash-table) mode)
;; We need to keep looking.
nil)
((:logical-block)
(setf (gethash object circularity-hash-table)
:logical-block-circular)
t)
((t)
(cond ((eq mode :logical-block)
;; We've seen the object before in output-object, and now
a second time in a PPRINT - LOGICAL - BLOCK ( for example
;; via pprint-dispatch). Don't mark it as circular yet.
(setf (gethash object circularity-hash-table)
:logical-block)
nil)
(t
second encounter
(setf (gethash object circularity-hash-table) 0)
;; It's a circular reference.
t)))
((0 :logical-block-circular)
;; It's a circular reference.
t)))
(t
(let ((value (gethash object circularity-hash-table)))
(case value
((nil t :logical-block)
If NIL , we found an object that was n't there the
first time around . If T or : LOGICAL - BLOCK , this
;; object appears exactly once. Either way, just print
;; the thing without any special processing. Note: you
;; might argue that finding a new object means that
;; something is broken, but this can happen. If someone
;; uses the ~@<...~:> format directive, it conses a new
;; list each time though format (i.e. the &REST list),
;; so we will have different cdrs.
nil)
;; A circular reference to something that will be printed
;; as a logical block. Wait until we're called from
PPRINT - LOGICAL - BLOCK with ASSIGN true before assigning the
;; number.
;;
;; If mode is :LOGICAL-BLOCK and assign is false, return true
;; to indicate that this object is circular, but don't assign
;; it a number yet. This is necessary for cases like
# 1=(#2=(#2 # . # 3=(#1 # . # 3 # ) ) ) ) ) .
(:logical-block-circular
(cond ((and (not assign)
(eq mode :logical-block))
t)
((and assign
(eq mode :logical-block))
(let ((value (incf *circularity-counter*)))
;; first occurrence of this object: Set the counter.
(setf (gethash object circularity-hash-table) value)
value))
(t
nil)))
(0
(if (eq assign t)
(let ((value (incf *circularity-counter*)))
;; first occurrence of this object: Set the counter.
(setf (gethash object circularity-hash-table) value)
value)
t))
(t
second or later occurrence
(- value))))))))
;;; Handle the results of CHECK-FOR-CIRCULARITY. If this returns T then
you should go ahead and print the object . If it returns NIL , then
;;; you should blow it off.
(defun handle-circularity (marker stream)
(case marker
(:initiate
;; Someone forgot to initiate circularity detection.
(let ((*print-circle* nil))
(error "trying to use CHECK-FOR-CIRCULARITY when ~
circularity checking isn't initiated")))
((t :logical-block)
It 's a second ( or later ) reference to the object while we are
;; just looking. So don't bother groveling it again.
nil)
(t
(write-char #\# stream)
(output-integer (abs marker) stream 10 nil)
(cond ((minusp marker)
(write-char #\# stream)
nil)
(t
(write-char #\= stream)
t)))))
(defmacro with-circularity-detection ((object stream) &body body)
(with-unique-names (marker body-name)
`(labels ((,body-name ()
,@body))
(cond ((or (not *print-circle*)
(uniquely-identified-by-print-p ,object))
(,body-name))
(*circularity-hash-table*
(let ((,marker (check-for-circularity ,object t :logical-block)))
(if ,marker
(when (handle-circularity ,marker ,stream)
(,body-name))
(,body-name))))
(t
(let ((*circularity-hash-table* (make-hash-table :test 'eq)))
(output-object ,object *null-broadcast-stream*)
(let ((*circularity-counter* 0))
(let ((,marker (check-for-circularity ,object t
:logical-block)))
(when ,marker
(handle-circularity ,marker ,stream)))
(,body-name))))))))
;;;; level and length abbreviations
;;; The current level we are printing at, to be compared against
* PRINT - LEVEL * . See the macro DESCEND - INTO for a handy interface to
;;; depth abbreviation.
(defvar *current-level-in-print* 0)
(declaim (index *current-level-in-print*))
;;; Automatically handle *PRINT-LEVEL* abbreviation. If we are too
deep , then a # \ # is printed to STREAM and BODY is ignored .
(defmacro descend-into ((stream) &body body)
(let ((flet-name (gensym "DESCEND")))
`(flet ((,flet-name ()
,@body))
(cond ((and (null *print-readably*)
(let ((level *print-level*))
(and level (>= *current-level-in-print* level))))
(write-char #\# ,stream))
(t
(let ((*current-level-in-print* (1+ *current-level-in-print*)))
(,flet-name)))))))
;;; Punt if INDEX is equal or larger then *PRINT-LENGTH* (and
;;; *PRINT-READABLY* is NIL) by outputting \"...\" and returning from
the block named NIL .
(defmacro punt-print-if-too-long (index stream)
`(when (and (not *print-readably*)
(let ((len *print-length*))
(and len (>= ,index len))))
(write-string "..." ,stream)
(return)))
;;;; OUTPUT-OBJECT -- the main entry point
Objects whose print representation identifies them EQLly do n't
;;; need to be checked for circularity.
(defun uniquely-identified-by-print-p (x)
(or (numberp x)
(characterp x)
(and (symbolp x)
(sb-xc:symbol-package x))))
(defvar *in-print-error* nil)
;;; Output OBJECT to STREAM observing all printer control variables.
(defun output-object (object stream)
;; FIXME: this function is declared EXPLICIT-CHECK, so it allows STREAM
;; to be T or NIL (a stream-designator), which is not really right
;; if eventually the call will be to a PRINT-OBJECT method,
;; since the generic function should always receive a stream.
(declare (explicit-check))
(labels ((print-it (stream)
(multiple-value-bind (fun pretty)
(and *print-pretty* (pprint-dispatch object))
(if pretty
(sb-pretty:output-pretty-object stream fun object)
(output-ugly-object stream object))))
(handle-it (stream)
(if *suppress-print-errors*
(handler-bind
((condition
(lambda (condition)
(when (typep condition *suppress-print-errors*)
(cond (*in-print-error*
(write-string "(error printing " stream)
(write-string *in-print-error* stream)
(write-string ")" stream))
(t
(let ((*print-readably* nil)
(*print-escape* t))
(write-string
"#<error printing a " stream)
(let ((*in-print-error* "type"))
(output-object (type-of object) stream))
(write-string ": " stream)
(let ((*in-print-error* "condition"))
(output-object condition stream))
(write-string ">" stream))))
(return-from handle-it object)))))
(print-it stream))
(print-it stream)))
(check-it (stream)
(multiple-value-bind (marker initiate)
(check-for-circularity object t)
(if (eq initiate :initiate)
(let ((*circularity-hash-table*
(make-hash-table :test 'eq)))
(check-it *null-broadcast-stream*)
(let ((*circularity-counter* 0))
(check-it stream)))
;; otherwise
(if marker
(when (handle-circularity marker stream)
(handle-it stream))
(handle-it stream))))))
(cond (;; Maybe we don't need to bother with circularity detection.
(or (not *print-circle*)
(uniquely-identified-by-print-p object))
(handle-it stream))
(;; If we have already started circularity detection, this
;; object might be a shared reference. If we have not, then
;; if it is a compound object it might contain a circular
;; reference to itself or multiple shared references.
(or *circularity-hash-table*
(compound-object-p object))
(check-it stream))
(t
(handle-it stream)))))
;;; Output OBJECT to STREAM observing all printer control variables
;;; except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
;;; then the pretty printer will be used for any components of OBJECT,
;;; just not for OBJECT itself.
(defun output-ugly-object (stream object)
(when (%instancep object)
(let ((layout (%instance-layout object)))
;; If an instance has no layout, do something sensible. Can't compare layout
to 0 using EQ or EQL because that would be tautologically NIL as per fndb .
This is better than declaring EQ or % INSTANCE - LAYOUT notinline .
(unless (logtest (get-lisp-obj-address layout) sb-vm:widetag-mask)
(return-from output-ugly-object
(print-unreadable-object (object stream :identity t)
(prin1 'instance stream))))
(let* ((wrapper (layout-friend layout))
(classoid (wrapper-classoid wrapper)))
;; Additionally, don't crash if the object is an obsolete thing with
;; no update protocol.
(when (or (sb-kernel::undefined-classoid-p classoid)
(and (wrapper-invalid wrapper)
(logtest (layout-flags layout)
(logior +structure-layout-flag+
+condition-layout-flag+))))
(return-from output-ugly-object
(print-unreadable-object (object stream :identity t)
(format stream "UNPRINTABLE instance of ~W" classoid)))))))
(when (funcallable-instance-p object)
(let ((layout (%fun-layout object)))
(unless (logtest (get-lisp-obj-address layout) sb-vm:widetag-mask)
(return-from output-ugly-object
(print-unreadable-object (object stream :identity t)
(prin1 'funcallable-instance stream))))))
(print-object object stream))
;;;; symbols
(defmethod print-object ((object symbol) stream)
(if (or *print-escape* *print-readably*)
;; Write so that reading back works
(output-symbol object (sb-xc:symbol-package object) stream)
;; Write only the characters of the name, never the package
(let ((rt *readtable*))
(output-symbol-case-dispatch *print-case* (readtable-case rt)
(symbol-name object) stream rt))))
(defun output-symbol (symbol package stream)
(let* ((readably *print-readably*)
(readtable (if readably *standard-readtable* *readtable*))
(print-case *print-case*)
(readtable-case (readtable-case readtable)))
(flet ((output-token (name)
(declare (type simple-string name))
(cond ((or (and (readtable-normalization readtable)
(not (sb-unicode:normalized-p name :nfkc)))
(symbol-quotep name readtable))
;; Output NAME surrounded with |'s,
;; and with any embedded |'s or \'s escaped.
(write-char #\| stream)
(dotimes (index (length name))
(let ((char (char name index)))
;; Hmm. Should these depend on what characters
;; are actually escapes in the readtable ?
( See similar remark at DEFUN QUOTE - STRING )
(when (or (char= char #\\) (char= char #\|))
(write-char #\\ stream))
(write-char char stream)))
(write-char #\| stream))
(t
(output-symbol-case-dispatch print-case readtable-case
name stream readtable)))))
(let ((name (symbol-name symbol))
(current (sane-package)))
(cond
;; The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
;; requires that keywords be printed with preceding colons
;; always, regardless of the value of *PACKAGE*.
((eq package *keyword-package*)
(write-char #\: stream))
;; Otherwise, if the symbol's home package is the current
;; one, then a prefix is never necessary.
((eq package current))
Uninterned symbols print with a leading # : .
((null package)
(when (or *print-gensym* readably)
(write-string "#:" stream)))
(t
(multiple-value-bind (found accessible) (find-symbol name current)
;; If we can find the symbol by looking it up, it need not
;; be qualified. This can happen if the symbol has been
;; inherited from a package other than its home package.
;;
;; To preserve print-read consistency, use the local nickname if
;; one exists.
(unless (and accessible (eq found symbol))
(output-token (or (package-local-nickname package current)
(package-name package)))
(write-string (if (symbol-externalp symbol package) ":" "::")
stream)))))
(output-token name)))))
;;;; escaping symbols
;;; When we print symbols we have to figure out if they need to be
;;; printed with escape characters. This isn't a whole lot easier than
reading symbols in the first place .
;;;
;;; For each character, the value of the corresponding element is a
;;; fixnum with bits set corresponding to attributes that the
character has . All characters have at least one bit set , so we can
;;; search for any character with a positive test.
;;; constants which are a bit-mask for each interesting character attribute
(defconstant other-attribute (ash 1 0)) ; Anything else legal.
(defconstant number-attribute (ash 1 1)) ; A numeric digit.
(defconstant uppercase-attribute (ash 1 2)) ; An uppercase letter.
(defconstant lowercase-attribute (ash 1 3)) ; A lowercase letter.
(defconstant sign-attribute (ash 1 4)) ; +-
(defconstant extension-attribute (ash 1 5)) ; ^_
(defconstant dot-attribute (ash 1 6)) ; .
(defconstant slash-attribute (ash 1 7)) ; /
(defconstant funny-attribute (ash 1 8)) ; Anything illegal.
LETTER - ATTRIBUTE is a local of SYMBOL - QUOTEP . It matches letters
;;; that don't need to be escaped (according to READTABLE-CASE.)
(defconstant-eqx +attribute-names+
'((number . number-attribute) (lowercase . lowercase-attribute)
(uppercase . uppercase-attribute) (letter . letter-attribute)
(sign . sign-attribute) (extension . extension-attribute)
(dot . dot-attribute) (slash . slash-attribute)
(other . other-attribute) (funny . funny-attribute))
#'equal)
;;; For each character, the value of the corresponding element is the
;;; lowest base in which that character is a digit.
(defconstant-eqx +digit-bases+
#.(let ((a (sb-xc:make-array base-char-code-limit
:retain-specialization-for-after-xc-core t
:element-type '(unsigned-byte 8)
:initial-element 36)))
(dotimes (i 36 a)
(let ((char (digit-char i 36)))
(setf (aref a (char-code char)) i))))
#'equalp)
(defconstant-eqx +character-attributes+
FIXME
:retain-specialization-for-after-xc-core t
:element-type '(unsigned-byte 16)
:initial-element 0)))
(flet ((set-bit (char bit)
(let ((code (char-code char)))
(setf (aref a code) (logior bit (aref a code))))))
(dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
#\? #\< #\>))
(set-bit char other-attribute))
(dotimes (i 10)
(set-bit (digit-char i) number-attribute))
(do ((code (char-code #\A) (1+ code))
(end (char-code #\Z)))
((> code end))
(declare (fixnum code end))
(set-bit (code-char code) uppercase-attribute)
(set-bit (char-downcase (code-char code)) lowercase-attribute))
(set-bit #\- sign-attribute)
(set-bit #\+ sign-attribute)
(set-bit #\^ extension-attribute)
(set-bit #\_ extension-attribute)
(set-bit #\. dot-attribute)
(set-bit #\/ slash-attribute)
;; Mark anything not explicitly allowed as funny.
FIXME
(when (zerop (aref a i))
(setf (aref a i) funny-attribute))))
a)
#'equalp)
A FSM - like thingie that determines whether a symbol is a potential
;;; number or has evil characters in it.
(defun symbol-quotep (name readtable)
(declare (simple-string name))
(macrolet ((advance (tag &optional (at-end t))
`(progn
(when (= index len)
,(if at-end '(go TEST-SIGN) '(return nil)))
(setq current (schar name index)
code (char-code current)
FIXME
((< code 160) (aref attributes code))
((upper-case-p current) uppercase-attribute)
((lower-case-p current) lowercase-attribute)
(t other-attribute)))
(incf index)
(go ,tag)))
(test (&rest attributes)
`(not (zerop
(the fixnum
(logand
(logior ,@(mapcar
(lambda (x)
(or (cdr (assoc x
+attribute-names+))
(error "Blast!")))
attributes))
bits)))))
(digitp ()
FIXME
(< (the fixnum (aref bases code)) base))))
(prog ((len (length name))
(attributes #.+character-attributes+)
(bases #.+digit-bases+)
(base *print-base*)
(letter-attribute
(case (readtable-case readtable)
(:upcase uppercase-attribute)
(:downcase lowercase-attribute)
(t (logior lowercase-attribute uppercase-attribute))))
(index 0)
(bits 0)
(code 0)
current)
(declare (fixnum len base index bits code))
(advance START t)
TEST-SIGN ; At end, see whether it is a sign...
(return (not (test sign)))
OTHER ; not potential number, see whether funny chars...
(let ((mask (logxor (logior lowercase-attribute uppercase-attribute
funny-attribute)
letter-attribute)))
(do ((i (1- index) (1+ i)))
((= i len) (return-from symbol-quotep nil))
(unless (zerop (logand (let* ((char (schar name i))
(code (char-code char)))
(cond
((< code 160) (aref attributes code))
((upper-case-p char) uppercase-attribute)
((lower-case-p char) lowercase-attribute)
(t other-attribute)))
mask))
(return-from symbol-quotep t))))
START
(when (digitp)
(if (test letter)
(advance LAST-DIGIT-ALPHA)
(advance DIGIT)))
(when (test letter number other slash) (advance OTHER nil))
(when (char= current #\.) (advance DOT-FOUND))
(when (test sign extension) (advance START-STUFF nil))
(return t)
DOT-FOUND ; leading dots...
(when (test letter) (advance START-DOT-MARKER nil))
(when (digitp) (advance DOT-DIGIT))
(when (test number other) (advance OTHER nil))
(when (test extension slash sign) (advance START-DOT-STUFF nil))
(when (char= current #\.) (advance DOT-FOUND))
(return t)
START-STUFF ; leading stuff before any dot or digit
(when (digitp)
(if (test letter)
(advance LAST-DIGIT-ALPHA)
(advance DIGIT)))
(when (test number other) (advance OTHER nil))
(when (test letter) (advance START-MARKER nil))
(when (char= current #\.) (advance START-DOT-STUFF nil))
(when (test sign extension slash) (advance START-STUFF nil))
(return t)
START-MARKER ; number marker in leading stuff...
(when (test letter) (advance OTHER nil))
(go START-STUFF)
START-DOT-STUFF ; leading stuff containing dot without digit...
(when (test letter) (advance START-DOT-STUFF nil))
(when (digitp) (advance DOT-DIGIT))
(when (test sign extension dot slash) (advance START-DOT-STUFF nil))
(when (test number other) (advance OTHER nil))
(return t)
START-DOT-MARKER ; number marker in leading stuff with dot..
;; leading stuff containing dot without digit followed by letter...
(when (test letter) (advance OTHER nil))
(go START-DOT-STUFF)
DOT-DIGIT ; in a thing with dots...
(when (test letter) (advance DOT-MARKER))
(when (digitp) (advance DOT-DIGIT))
(when (test number other) (advance OTHER nil))
(when (test sign extension dot slash) (advance DOT-DIGIT))
(return t)
DOT-MARKER ; number marker in number with dot...
(when (test letter) (advance OTHER nil))
(go DOT-DIGIT)
LAST-DIGIT-ALPHA ; previous char is a letter digit...
(when (or (digitp) (test sign slash))
(advance ALPHA-DIGIT))
(when (test letter number other dot) (advance OTHER nil))
(return t)
ALPHA-DIGIT ; seen a digit which is a letter...
(when (or (digitp) (test sign slash))
(if (test letter)
(advance LAST-DIGIT-ALPHA)
(advance ALPHA-DIGIT)))
(when (test letter) (advance ALPHA-MARKER))
(when (test number other dot) (advance OTHER nil))
(return t)
ALPHA-MARKER ; number marker in number with alpha digit...
(when (test letter) (advance OTHER nil))
(go ALPHA-DIGIT)
DIGIT ; seen only ordinary (non-alphabetic) numeric digits...
(when (digitp)
(if (test letter)
(advance ALPHA-DIGIT)
(advance DIGIT)))
(when (test number other) (advance OTHER nil))
(when (test letter) (advance MARKER))
(when (test extension slash sign) (advance DIGIT))
(when (char= current #\.) (advance DOT-DIGIT))
(return t)
MARKER ; number marker in a numeric number...
;; ("What," you may ask, "is a 'number marker'?" It's something
;; that a conforming implementation might use in number syntax.
See ANSI 2.3.1.1 " Potential Numbers as Tokens " . )
(when (test letter) (advance OTHER nil))
(go DIGIT))))
case hackery : One of these functions is chosen to output symbol
;;;; names according to the values of *PRINT-CASE* and READTABLE-CASE.
(declaim (start-block output-symbol-case-dispatch))
;;; called when:
;;; READTABLE-CASE *PRINT-CASE*
;;; :UPCASE :UPCASE
: DOWNCASE : DOWNCASE
;;; :PRESERVE any
(defun output-preserve-symbol (pname stream readtable)
(declare (ignore readtable))
(write-string pname stream))
;;; called when:
;;; READTABLE-CASE *PRINT-CASE*
: UPCASE : DOWNCASE
(defun output-lowercase-symbol (pname stream readtable)
(declare (simple-string pname) (ignore readtable))
(dotimes (index (length pname))
(let ((char (schar pname index)))
(write-char (char-downcase char) stream))))
;;; called when:
;;; READTABLE-CASE *PRINT-CASE*
;;; :DOWNCASE :UPCASE
(defun output-uppercase-symbol (pname stream readtable)
(declare (simple-string pname) (ignore readtable))
(dotimes (index (length pname))
(let ((char (schar pname index)))
(write-char (char-upcase char) stream))))
;;; called when:
;;; READTABLE-CASE *PRINT-CASE*
: UPCASE : CAPITALIZE
: DOWNCASE : CAPITALIZE
(defun output-capitalize-symbol (pname stream readtable)
(declare (simple-string pname))
(let ((prev-not-alphanum t)
(up (eq (readtable-case readtable) :upcase)))
(dotimes (i (length pname))
(let ((char (char pname i)))
(write-char (if up
(if (or prev-not-alphanum (lower-case-p char))
char
(char-downcase char))
(if prev-not-alphanum
(char-upcase char)
char))
stream)
(setq prev-not-alphanum (not (alphanumericp char)))))))
;;; called when:
;;; READTABLE-CASE *PRINT-CASE*
;;; :INVERT any
(defun output-invert-symbol (pname stream readtable)
(declare (simple-string pname) (ignore readtable))
(let ((all-upper t)
(all-lower t))
(dotimes (i (length pname))
(let ((ch (schar pname i)))
(when (both-case-p ch)
(if (upper-case-p ch)
(setq all-lower nil)
(setq all-upper nil)))))
(cond (all-upper (output-lowercase-symbol pname stream nil))
(all-lower (output-uppercase-symbol pname stream nil))
(t
(write-string pname stream)))))
;;; Call an output function based on PRINT-CASE and READTABLE-CASE.
(defun output-symbol-case-dispatch (print-case readtable-case name stream readtable)
(ecase readtable-case
(:upcase
(ecase print-case
(:upcase (output-preserve-symbol name stream readtable))
(:downcase (output-lowercase-symbol name stream readtable))
(:capitalize (output-capitalize-symbol name stream readtable))))
(:downcase
(ecase print-case
(:upcase (output-uppercase-symbol name stream readtable))
(:downcase (output-preserve-symbol name stream readtable))
(:capitalize (output-capitalize-symbol name stream readtable))))
(:preserve (output-preserve-symbol name stream readtable))
(:invert (output-invert-symbol name stream readtable))))
(declaim (end-block))
;;;; recursive objects
(defmethod print-object ((list cons) stream)
(descend-into (stream)
(write-char #\( stream)
(let ((length 0)
(list list))
(loop
(punt-print-if-too-long length stream)
(output-object (pop list) stream)
(unless list
(return))
(when (or (atom list)
(check-for-circularity list))
(write-string " . " stream)
(output-object list stream)
(return))
(write-char #\space stream)
(incf length)))
(write-char #\) stream)))
(defmethod print-object ((vector vector) stream)
(let ((readably *print-readably*))
(flet ((cut-length ()
(when (and (not readably)
*print-vector-length*
(> (length vector) *print-vector-length*))
(print-unreadable-object (vector stream :type t :identity t)
(format stream "~A..."
(make-array *print-vector-length*
:element-type (array-element-type vector)
:displaced-to vector)))
t)))
(cond ((stringp vector)
(cond ((and readably (not (typep vector '(vector character))))
(output-unreadable-array-readably vector stream))
((and *print-escape*
(cut-length)))
((or *print-escape* readably)
(write-char #\" stream)
(quote-string vector stream)
(write-char #\" stream))
(t
(write-string vector stream))))
((or (null (array-element-type vector))
(not (or *print-array* readably)))
(output-terse-array vector stream))
((bit-vector-p vector)
(cond ((cut-length))
(t
(write-string "#*" stream)
(dovector (bit vector)
;; (Don't use OUTPUT-OBJECT here, since this code
;; has to work for all possible *PRINT-BASE* values.)
(write-char (if (zerop bit) #\0 #\1) stream)))))
((or (not readably) (array-readably-printable-p vector))
(descend-into (stream)
(write-string "#(" stream)
(dotimes (i (length vector))
(unless (zerop i)
(write-char #\space stream))
(punt-print-if-too-long i stream)
(output-object (aref vector i) stream))
(write-string ")" stream)))
(t
(output-unreadable-array-readably vector stream))))))
;;; Output a string, quoting characters to be readable by putting a slash in front
;;; of any character satisfying NEEDS-SLASH-P.
(defun quote-string (string stream)
(macrolet ((needs-slash-p (char)
: We probably should look at the readtable , but just do
;; this for now. [noted by anonymous long ago] -- WHN 19991130
`(let ((c ,char)) (or (char= c #\\) (char= c #\"))))
(scan (type)
;; Pre-test for any escaping, and if needed, do char-at-a-time output.
For 1 or 0 characters , always take the WRITE - CHAR branch .
`(let ((data (truly-the ,type data)))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(when (or (<= (- end start) 1)
(do ((index start (1+ index)))
((>= index end))
(when (needs-slash-p (schar data index)) (return t))))
(do ((index start (1+ index)))
((>= index end) (return-from quote-string))
(let ((char (schar data index)))
(when (needs-slash-p char) (write-char #\\ stream))
(write-char char stream)))))))
(with-array-data ((data string) (start) (end)
:check-fill-pointer t)
(if (simple-base-string-p data)
(scan simple-base-string)
#+sb-unicode (scan simple-character-string)))
;; If no escaping needed, WRITE-STRING is way faster, up to 2x in my testing,
;; than WRITE-CHAR because the stream layer will get so many fewer calls.
(write-string string stream)))
(defun array-readably-printable-p (array)
(and (eq (array-element-type array) t)
(let ((zero (position 0 (array-dimensions array)))
(number (position 0 (array-dimensions array)
:test (complement #'eql)
:from-end t)))
(or (null zero) (null number) (> zero number)))))
;;; Output the printed representation of any array in either the #< or #A
;;; form.
(defmethod print-object ((array array) stream)
(if (and (or *print-array* *print-readably*) (array-element-type array))
(output-array-guts array stream)
(output-terse-array array stream)))
;;; Output the abbreviated #< form of an array.
(defun output-terse-array (array stream)
(let ((*print-level* nil)
(*print-length* nil))
(if (and (not (array-element-type array)) *print-readably* *read-eval*)
(format stream "#.(~S '~D :ELEMENT-TYPE ~S)"
'make-array (array-dimensions array) nil)
(print-unreadable-object (array stream :type t :identity t)))))
;;; Convert an array into a list that can be used with MAKE-ARRAY's
;;; :INITIAL-CONTENTS keyword argument.
(defun listify-array (array)
(flet ((compact (seq)
(typecase array
(string
(coerce seq '(simple-array character (*))))
((array bit)
(coerce seq 'bit-vector))
(t
seq))))
(if (typep array '(or string bit-vector))
(compact array)
(with-array-data ((data array) (start) (end))
(declare (ignore end))
(labels ((listify (dimensions index)
(if (null dimensions)
(aref data index)
(let* ((dimension (car dimensions))
(dimensions (cdr dimensions))
(count (reduce #'* dimensions)))
(loop for i below dimension
for list = (listify dimensions index)
collect (if (and dimensions
(null (cdr dimensions)))
(compact list)
list)
do (incf index count))))))
(listify (array-dimensions array) start))))))
;;; Use nonstandard #A(dimensions element-type contents)
;;; to avoid using #.
(defun output-unreadable-array-readably (array stream)
(let ((array (list* (array-dimensions array)
(array-element-type array)
(listify-array array))))
(write-string "#A" stream)
(write array :stream stream)
nil))
;;; Output the readable #A form of an array.
(defun output-array-guts (array stream)
(cond ((or (not *print-readably*)
(array-readably-printable-p array))
(write-char #\# stream)
(output-integer (array-rank array) stream 10 nil)
(write-char #\A stream)
(with-array-data ((data array) (start) (end))
(declare (ignore end))
(sub-output-array-guts data (array-dimensions array) stream start)))
(t
(output-unreadable-array-readably array stream))))
(defun sub-output-array-guts (array dimensions stream index)
(declare (type (simple-array * (*)) array) (fixnum index))
(cond ((null dimensions)
(output-object (aref array index) stream))
(t
(descend-into (stream)
(write-char #\( stream)
(let* ((dimension (car dimensions))
(dimensions (cdr dimensions))
(count (reduce #'* dimensions)))
(dotimes (i dimension)
(unless (zerop i)
(write-char #\space stream))
(punt-print-if-too-long i stream)
(sub-output-array-guts array dimensions stream index)
(incf index count)))
(write-char #\) stream)))))
;;;; integer, ratio, and complex printing (i.e. everything but floats)
(defun %output-radix (base stream)
(write-char #\# stream)
(write-char (case base
(2 #\b)
(8 #\o)
(16 #\x)
(t (%output-integer-in-base base 10 stream) #\r))
stream))
;;; *POWER-CACHE* is an alist mapping bases to power-vectors. It is
;;; filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
always prior a GC to drop overly large bignums from the cache .
;;;
;;; It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
;;; POWERS-FOR-BASE, see that you don't break the assumptions!
(define-load-time-global *power-cache* (make-array 37 :initial-element nil))
(declaim (type (simple-vector 37) *power-cache*))
(defconstant +power-cache-integer-length-limit+ 2048)
(defun scrub-power-cache (&aux (cache *power-cache*))
(dotimes (i (length cache))
(let ((powers (aref cache i)))
(when powers
(let ((too-big (position-if
(lambda (x)
(>= (integer-length x)
+power-cache-integer-length-limit+))
(the simple-vector powers))))
(when too-big
(setf (aref cache i) (subseq powers 0 too-big))))))))
;;; Compute (and cache) a power vector for a BASE and LIMIT:
;;; the vector holds integers for which
;;; (aref powers k) == (expt base (expt 2 k))
;;; holds.
(defun powers-for-base (base limit)
(flet ((compute-powers (from)
(let (powers)
(do ((p from (* p p)))
((> p limit)
;; We don't actually need this, but we also
prefer not to cons it up a second time ...
(push p powers))
(push p powers))
(nreverse powers))))
(let* ((cache *power-cache*)
(powers (aref cache base)))
(setf (aref cache base)
(concatenate 'vector powers
(compute-powers
(if powers
(let* ((len (length powers))
(max (svref powers (1- len))))
(if (> max limit)
(return-from powers-for-base powers)
(* max max)))
base)))))))
Algorithm by , sbcl - devel 2005 - 02 - 05
(defun %output-huge-integer-in-base (n base stream)
(declare (type bignum n) (type fixnum base))
;; POWER is a vector for which the following holds:
;; (aref power k) == (expt base (expt 2 k))
(let* ((power (powers-for-base base n))
(k-start (or (position-if (lambda (x) (> x n)) power)
(bug "power-vector too short"))))
(labels ((bisect (n k exactp)
(declare (fixnum k))
;; N is the number to bisect
;; K on initial entry BASE^(2^K) > N
EXACTP is true if is the exact number of digits
(cond ((zerop n)
(when exactp
(loop repeat (ash 1 k) do (write-char #\0 stream))))
((zerop k)
(write-char
(schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
stream))
(t
(setf k (1- k))
(multiple-value-bind (q r) (truncate n (aref power k))
EXACTP is NIL only at the head of the
;; initial number, as we don't know the number
;; of digits there, but we do know that it
does n't get any leading zeros .
(bisect q k exactp)
(bisect r k (or exactp (plusp q))))))))
(bisect n k-start nil))))
;;; Not all architectures can stack-allocate lisp strings,
;;; but we can fake it using aliens.
% output - integer - in - base always needs 8 lispwords :
if n - word - bytes = 4 then 8 * 4 = 32 characters
if n - word - bytes = 8 then 8 * 8 = 64 characters
This allows for output in base 2 worst case .
;;; We don't need a trailing null.
(defmacro with-lisp-string-on-alien-stack ((string size-in-chars) &body body)
(let ((size-in-lispwords ; +2 words for lisp string header
(+ 2 (align-up (ceiling (symbol-value size-in-chars) sb-vm:n-word-bytes)
2)))
(alien '#:a)
(sap '#:sap))
;; +1 is for alignment if needed
`(with-alien ((,alien (array unsigned ,(1+ size-in-lispwords))))
(let ((,sap (alien-sap ,alien)))
(when (logtest (sap-int ,sap) sb-vm:lowtag-mask)
(setq ,sap (sap+ ,sap sb-vm:n-word-bytes)))
(setf (sap-ref-word ,sap 0) sb-vm:simple-base-string-widetag
(sap-ref-word ,sap sb-vm:n-word-bytes) (ash sb-vm:n-word-bits
sb-vm:n-fixnum-tag-bits))
(let ((,string
(truly-the simple-base-string
(%make-lisp-obj (logior (sap-int ,sap)
sb-vm:other-pointer-lowtag)))))
,@body)))))
;;; Using specialized routines for the various cases seems to work nicely.
;;;
Testing with 100,000 random integers , output to a sink stream , x86 - 64 :
word - sized integers , base > = 10
old=.062 sec , 4MiB consed ; new=.031 sec , 0 bytes consed
word - sized integers , base < 10
old=.104 sec , 4MiB consed ; new=.075 sec , 0 bytes consed
bignums in base 16 :
old=.125 sec , 20 MiB consed ; new=.08 sec , 0 bytes consed
;;;
Not sure why this did n't reduce consing on when I tried it .
(defun %output-integer-in-base (integer base stream)
(declare (type (integer 2 36) base))
(when (minusp integer)
(write-char #\- stream)
(setf integer (- integer)))
;; Grrr - a LET binding here causes a constant-folding problem
;; "The function SB-KERNEL:SIMPLE-CHARACTER-STRING-P is undefined."
;; but a symbol-macrolet is ok. This is a FIXME except I don't care.
(symbol-macrolet ((chars "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
(declare (optimize (sb-c:insert-array-bounds-checks 0) speed))
(macrolet ((iterative-algorithm ()
`(loop (multiple-value-bind (q r)
(truncate (truly-the word integer) base)
(decf ptr)
(setf (aref buffer ptr) (schar chars r))
(when (zerop (setq integer q)) (return)))))
(recursive-algorithm (dividend-type)
`(named-let recurse ((n integer))
(multiple-value-bind (q r) (truncate (truly-the ,dividend-type n) base)
;; Recurse until you have all the digits pushed on
;; the stack.
(unless (zerop q) (recurse q))
;; Then as each recursive call unwinds, turn the
;; digit (in remainder) into a character and output
;; the character.
(write-char (schar chars r) stream)))))
(cond ((typep integer 'word) ; Division vops can handle this all inline.
strings can be DX
For bases exceeding 10 we know how many characters ( at most )
;; will be output. This allows for a single %WRITE-STRING call.
;; There's diminishing payback for other bases because the fixed array
;; size increases, and we don't have a way to elide initial 0-fill.
;; Calling APPROX-CHARS-IN-REPL doesn't help much - we still 0-fill.
(if (< base 10)
(recursive-algorithm word)
(let* ((ptr #.(length (write-to-string sb-ext:most-positive-word
:base 10)))
(buffer (make-array ptr :element-type 'base-char)))
(declare (truly-dynamic-extent buffer))
(iterative-algorithm)
(%write-string buffer stream ptr (length buffer))))
strings can not be DX
;; Use the alien stack, which is not as fast as using the control stack
;; (when we can). Even the absence of 0-fill doesn't make up for it.
;; Since we've no choice in the matter, might as well allow
;; any value of BASE - it's just a few more words of storage.
(let ((ptr sb-vm:n-word-bits))
(with-lisp-string-on-alien-stack (buffer sb-vm:n-word-bits)
(iterative-algorithm)
(%write-string buffer stream ptr sb-vm:n-word-bits))))
((eql base 16)
;; No division is involved at all.
could also specialize for bases 32 , 8 , 4 , and 2 if desired
(loop for pos from (* 4 (1- (ceiling (integer-length integer) 4)))
downto 0 by 4
do (write-char (schar chars (sb-bignum::ldb-bignum=>fixnum 4 pos
integer))
stream)))
;; The ideal cutoff point between this and the "huge" algorithm
;; might be platform-specific, and it also could depend on the output base.
Nobody has cared to tweak it in so many years that I think we can
arbitrarily say 3 bigdigits is fine .
((<= (sb-bignum:%bignum-length (truly-the bignum integer)) 3)
(recursive-algorithm integer))
(t
(%output-huge-integer-in-base integer base stream)))))
nil)
;;; This gets both a method and a specifically named function
;;; since the latter is called from a few places.
(defmethod print-object ((object integer) stream)
(output-integer object stream *print-base* *print-radix*))
(defun output-integer (integer stream base radixp)
(cond (radixp
(unless (= base 10) (%output-radix base stream))
(%output-integer-in-base integer base stream)
(when (= base 10) (write-char #\. stream)))
(t
(%output-integer-in-base integer base stream))))
(defmethod print-object ((ratio ratio) stream)
(let ((base *print-base*))
(when *print-radix*
(%output-radix base stream))
(%output-integer-in-base (numerator ratio) base stream)
(write-char #\/ stream)
(%output-integer-in-base (denominator ratio) base stream)))
(defmethod print-object ((complex complex) stream)
(write-string "#C(" stream)
(output-object (realpart complex) stream)
(write-char #\space stream)
(output-object (imagpart complex) stream)
(write-char #\) stream))
;;;; float printing
;;; FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
;;; most of the work for all printing of floating point numbers in
;;; FORMAT. It converts a floating point number to a string in a free
;;; or fixed format with no exponent. The interpretation of the
;;; arguments is as follows:
;;;
;;; X - The floating point number to convert, which must not be
;;; negative.
;;; WIDTH - The preferred field width, used to determine the number
of fraction digits to produce if the FDIGITS parameter
is unspecified or NIL . If the non - fraction digits and the
;;; decimal point alone exceed this width, no fraction digits
will be produced unless a non - NIL value of FDIGITS has been
;;; specified. Field overflow is not considerd an error at this
;;; level.
FDIGITS - The number of fractional digits to produce . Insignificant
trailing zeroes may be introduced as needed . May be
unspecified or NIL , in which case as many digits as possible
;;; are generated, subject to the constraint that there are no
;;; trailing zeroes.
;;; SCALE - If this parameter is specified or non-NIL, then the number
printed is ( * x ( expt 10 scale ) ) . This scaling is exact ,
;;; and cannot lose precision.
;;; FMIN - This parameter, if specified or non-NIL, is the minimum
;;; number of fraction digits which will be produced, regardless
of the value of WIDTH or FDIGITS . This feature is used by
;;; the ~E format directive to prevent complete loss of
;;; significance in the printed value due to a bogus choice of
;;; scale factor.
;;;
;;; Returns:
;;; (VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
;;; where the results have the following interpretation:
;;;
;;; DIGIT-STRING - The decimal representation of X, with decimal point.
;;; DIGIT-LENGTH - The length of the string DIGIT-STRING.
LEADING - POINT - True if the first character of DIGIT - STRING is the
;;; decimal point.
;;; TRAILING-POINT - True if the last character of DIGIT-STRING is the
;;; decimal point.
;;; POINT-POS - The position of the digit preceding the decimal
point . Zero indicates point before first digit .
;;;
;;; NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
;;; accuracy. Specifically, the decimal number printed is the closest
;;; possible approximation to the true value of the binary number to
;;; be printed from among all decimal representations with the same
;;; number of digits. In free-format output, i.e. with the number of
;;; digits unconstrained, it is guaranteed that all the information is
;;; preserved, so that a properly- rounding reader can reconstruct the
;;; original binary number, bit-for-bit, from its printed decimal
;;; representation. Furthermore, only as many digits as necessary to
;;; satisfy this condition will be printed.
;;;
FLOAT - DIGITS actually generates the digits for positive numbers ;
;;; see below for comments.
(defun flonum-to-string (x &optional width fdigits scale fmin)
(declare (type float x))
(multiple-value-bind (e string)
(if fdigits
(flonum-to-digits x (min (- (+ fdigits (or scale 0)))
(- (or fmin 0))))
(if (and width (> width 1))
(let ((w (multiple-value-list
(flonum-to-digits x
(max 1
(+ (1- width)
(if (and scale (minusp scale))
scale 0)))
t)))
(f (multiple-value-list
(flonum-to-digits x (- (+ (or fmin 0)
(if scale scale 0)))))))
(cond
((>= (length (cadr w)) (length (cadr f)))
(values-list w))
(t (values-list f))))
(flonum-to-digits x)))
(let ((e (if (zerop x)
e
(+ e (or scale 0))))
(stream (make-string-output-stream)))
(if (plusp e)
(progn
(write-string string stream :end (min (length string) e))
(dotimes (i (- e (length string)))
(write-char #\0 stream))
(write-char #\. stream)
(write-string string stream :start (min (length string) e))
(when fdigits
(dotimes (i (- fdigits
(- (length string)
(min (length string) e))))
(write-char #\0 stream))))
(progn
(write-string "." stream)
(dotimes (i (- e))
(write-char #\0 stream))
(write-string string stream :end (when fdigits
(min (length string)
(max (or fmin 0)
(+ fdigits e)))))
(when fdigits
(dotimes (i (+ fdigits e (- (length string))))
(write-char #\0 stream)))))
(let ((string (get-output-stream-string stream)))
(values string (length string)
(char= (char string 0) #\.)
(char= (char string (1- (length string))) #\.)
(position #\. string))))))
implementation of figure 1 from Burger and Dybvig , 1996 . It is
;;; extended in order to handle rounding.
;;;
As the implementation of the Dragon from Classic CMUCL ( and
previously in SBCL above FLONUM - TO - STRING ) says : " DO NOT EVEN
;;; THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
;;; PAPER!", and in this case we have to add that even reading the
;;; paper might not bring immediate illumination as CSR has attempted
;;; to turn idiomatic Scheme into idiomatic Lisp.
;;;
FIXME : figure 1 from Burger and Dybvig is the unoptimized
algorithm , noticeably slow at finding the exponent . Figure 2 has
an improved algorithm , but CSR ran out of energy .
;;;
;;; possible extension for the enthusiastic: printing floats in bases
other than base 10 .
(defconstant single-float-min-e
(- 2 sb-vm:single-float-bias sb-vm:single-float-digits))
(defconstant double-float-min-e
(- 2 sb-vm:double-float-bias sb-vm:double-float-digits))
#+long-float
(defconstant long-float-min-e
(nth-value 1 (decode-float least-positive-long-float)))
;;; Call CHAR-FUN with the digits of FLOAT
PROLOGUE - FUN and EPILOGUE - FUN are called with the exponent before
;;; and after printing to set up the state.
(declaim (inline %flonum-to-digits))
(defun %flonum-to-digits (char-fun
prologue-fun
epilogue-fun
float &optional position relativep)
(let ((print-base 10) ; B
(float-radix 2) ; b
(float-digits (float-digits float)) ; p
(min-e
(etypecase float
(single-float single-float-min-e)
(double-float double-float-min-e)
#+long-float
(long-float long-float-min-e))))
(multiple-value-bind (f e) (integer-decode-float float)
;; An extra step became necessary here for subnormals because the
;; algorithm assumes that the fraction is left-aligned in a field
;; that is FLOAT-DIGITS wide.
(when (< (float-precision float) float-digits)
(let ((shift (- float-digits (integer-length f))))
(setq f (ash f shift)
e (- e shift))))
FIXME : these even tests assume normal IEEE rounding
;; mode. I wonder if we should cater for non-normal?
(high-ok (evenp f))
(low-ok (evenp f)))
(labels ((scale (r s m+ m-)
(do ((r+m+ (+ r m+))
(k 0 (1+ k))
(s s (* s print-base)))
((not (or (> r+m+ s)
(and high-ok (= r+m+ s))))
(do ((k k (1- k))
(r r (* r print-base))
(m+ m+ (* m+ print-base))
(m- m- (* m- print-base)))
Extension to handle zero
(let ((x (* (+ r m+) print-base)))
(or (< x s)
(and (not high-ok)
(= x s))))))
(funcall prologue-fun k)
(generate r s m+ m-)
(funcall epilogue-fun k))))))
(generate (r s m+ m-)
(let (d tc1 tc2)
(tagbody
loop
(setf (values d r) (truncate (* r print-base) s))
(setf m+ (* m+ print-base))
(setf m- (* m- print-base))
(setf tc1 (or (< r m-) (and low-ok (= r m-))))
(setf tc2 (let ((r+m+ (+ r m+)))
(or (> r+m+ s)
(and high-ok (= r+m+ s)))))
(when (or tc1 tc2)
(go end))
(funcall char-fun d)
(go loop)
end
(let ((d (cond
((and (not tc1) tc2) (1+ d))
((and tc1 (not tc2)) d)
((< (* r 2) s)
d)
(t
(1+ d)))))
(funcall char-fun d)))))
(initialize ()
(let (r s m+ m-)
(cond ((>= e 0)
(let ((be (expt float-radix e)))
(if (/= f (expt float-radix (1- float-digits)))
multiply F by 2 first , two bignums
(setf r (* f 2 be)
s 2
m+ be
m- be)
(setf m- be
m+ (* be float-radix)
r (* f 2 m+)
s (* float-radix 2)))))
((or (= e min-e)
(/= f (expt float-radix (1- float-digits))))
(setf r (* f 2)
s (expt float-radix (- 1 e))
m+ 1
m- 1))
(t
(setf r (* f float-radix 2)
s (expt float-radix (- 2 e))
m+ float-radix
m- 1)))
(when position
(when relativep
(aver (> position 0))
(do ((k 0 (1+ k))
;; running out of letters here
(l 1 (* l print-base)))
((>= (* s l) (+ r m+))
k is now }
(if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
(* s l))
(setf position (- k position))
(setf position (- k position 1))))))
(let* ((x (/ (* s (expt print-base position)) 2))
(low (max m- x))
(high (max m+ x)))
(when (<= m- low)
(setf m- low)
(setf low-ok t))
(when (<= m+ high)
(setf m+ high)
(setf high-ok t))))
(values r s m+ m-))))
(multiple-value-bind (r s m+ m-) (initialize)
(scale r s m+ m-)))))))
(defun flonum-to-digits (float &optional position relativep)
(let ((digit-characters "0123456789"))
(with-push-char (:element-type base-char)
(%flonum-to-digits
(lambda (d)
(push-char (char digit-characters d)))
(lambda (k) k)
(lambda (k) (values k (get-pushed-string)))
float position relativep))))
(defun print-float (float stream)
(let ((position 0)
(dot-position 0)
(digit-characters "0123456789")
(e-min -3)
(e-max 8))
(%flonum-to-digits
(lambda (d)
(when (= position dot-position)
(write-char #\. stream))
(write-char (char digit-characters d) stream)
(incf position))
(lambda (k)
(cond ((not (< e-min k e-max))
(setf dot-position 1))
((plusp k)
(setf dot-position k))
(t
(setf dot-position -1)
(write-char #\0 stream)
(write-char #\. stream)
(loop for i below (- k)
do (write-char #\0 stream)))))
(lambda (k)
(when (<= position dot-position)
(loop for i below (- dot-position position)
do (write-char #\0 stream))
(write-char #\. stream)
(write-char #\0 stream))
(if (< e-min k e-max)
(print-float-exponent float 0 stream)
(print-float-exponent float (1- k) stream)))
float)))
Given a non - negative floating point number , SCALE - EXPONENT returns
a new floating point number Z in the range ( 0.1 , 1.0 ] and an
exponent E such that Z * 10^E is ( approximately ) equal to the
;;; original number. There may be some loss of precision due the
;;; floating point representation. The scaling is always done with
;;; long float arithmetic, which helps printing of lesser precisions
;;; as well as avoiding generic arithmetic.
;;;
;;; When computing our initial scale factor using EXPT, we pull out
;;; part of the computation to avoid over/under flow. When
;;; denormalized, we must pull out a large factor, since there is more
;;; negative exponent range than positive range.
(eval-when (:compile-toplevel :execute)
(setf *read-default-float-format*
#+long-float 'cl:long-float #-long-float 'cl:double-float))
(defun scale-exponent (original-x)
(let* ((x (coerce original-x 'long-float)))
(multiple-value-bind (sig exponent) (decode-float x)
(declare (ignore sig))
(if (= x $0.0e0)
(values (float $0.0e0 original-x) 1)
(let* ((ex (locally (declare (optimize (safety 0)))
(the fixnum
(round (* exponent
;; this is the closest double float
to ( log 2 10 ) , but expressed so
;; that we're not vulnerable to the
;; host lisp's interpretation of
arithmetic . ( FIXME : it turns
out that sbcl itself is off by 1
;; ulp in this value, which is a
;; little unfortunate.)
#-long-float
(make-double-float 1070810131 1352628735)
#+long-float
(error "(log 2 10) not computed"))))))
(x (if (minusp ex)
(if (float-denormalized-p x)
#-long-float
(* x $1.0e16 (expt $10.0e0 (- (- ex) 16)))
#+long-float
(* x $1.0e18 (expt $10.0e0 (- (- ex) 18)))
(* x $10.0e0 (expt $10.0e0 (- (- ex) 1))))
(/ x $10.0e0 (expt $10.0e0 (1- ex))))))
(do ((d $10.0e0 (* d $10.0e0))
(y x (/ x d))
(ex ex (1+ ex)))
((< y $1.0e0)
(do ((m $10.0e0 (* m $10.0e0))
(z y (* y m))
(ex ex (1- ex)))
((>= z $0.1e0)
(values (float z original-x) ex))
(declare (long-float m) (integer ex))))
(declare (long-float d))))))))
(eval-when (:compile-toplevel :execute)
(setf *read-default-float-format* 'cl:single-float))
;;;; entry point for the float printer
the float printer as called by PRINT , PRIN1 , PRINC , etc . The
;;; argument is printed free-format, in either exponential or
;;; non-exponential notation, depending on its magnitude.
;;;
;;; NOTE: When a number is to be printed in exponential format, it is
;;; scaled in floating point. Since precision may be lost in this
;;; process, the guaranteed accuracy properties of FLONUM-TO-STRING
;;; are lost. The difficulty is that FLONUM-TO-STRING performs
;;; extensive computations with integers of similar magnitude to that
;;; of the number being printed. For large exponents, the bignums
;;; really get out of hand. If bignum arithmetic becomes reasonably
;;; fast and the exponent range is not too large, then it might become
;;; attractive to handle exponential notation with the same accuracy
;;; as non-exponential notation, using the method described in the
Steele and White paper .
;;;
NOTE II : this has been bypassed slightly by implementing Burger
and Dybvig , 1996 . When someone has time ( ) they can
probably ( a ) implement the optimizations suggested by Burger and
Dyvbig , and ( b ) remove all vestiges of Dragon4 , including from
;;; fixed-format printing.
;;; Print the appropriate exponent marker for X and the specified exponent.
(defun print-float-exponent (x exp stream)
(declare (type float x) (type integer exp) (type stream stream))
(cond ((case *read-default-float-format*
((short-float single-float)
(typep x 'single-float))
((double-float #-long-float long-float)
(typep x 'double-float))
#+long-float
(long-float
(typep x 'long-float)))
(unless (eql exp 0)
(write-char #\e stream)
(%output-integer-in-base exp 10 stream)))
(t
(write-char
(etypecase x
(single-float #\f)
(double-float #\d)
(short-float #\s)
(long-float #\L))
stream)
(%output-integer-in-base exp 10 stream))))
(defmethod print-object ((x float) stream)
(cond
((float-infinity-or-nan-p x)
(if (float-infinity-p x)
(let ((symbol (etypecase x
(single-float (if (minusp x)
'single-float-negative-infinity
'single-float-positive-infinity))
(double-float (if (minusp x)
'double-float-negative-infinity
'double-float-positive-infinity)))))
(cond (*read-eval*
(write-string "#." stream)
(output-symbol symbol (sb-xc:symbol-package symbol) stream))
(t
(print-unreadable-object (x stream)
(output-symbol symbol (sb-xc:symbol-package symbol) stream)))))
(print-unreadable-object (x stream)
(princ (float-format-name x) stream)
(write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
(write-string " NaN" stream))))
(t
(let ((x (cond ((minusp (float-sign x))
(write-char #\- stream)
(- x))
(t
x))))
(cond
((zerop x)
(write-string "0.0" stream)
(print-float-exponent x 0 stream))
(t
(print-float x stream)))))))
;;;; other leaf objects
;;; If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
the character name or the character in the # \char format .
(defmethod print-object ((char character) stream)
(if (or *print-escape* *print-readably*)
(let ((graphicp (and (graphic-char-p char)
(standard-char-p char)))
(name (char-name char)))
(write-string "#\\" stream)
(if (and name (or (not graphicp) *print-readably*))
(quote-string name stream)
(write-char char stream)))
(write-char char stream)))
(defmethod print-object ((sap system-area-pointer) stream)
(cond (*read-eval*
(format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
(t
(print-unreadable-object (sap stream)
(format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
(defmethod print-object ((weak-pointer weak-pointer) stream)
(print-unreadable-object (weak-pointer stream)
(multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
(cond (validp
(write-string "weak pointer: " stream)
(write value :stream stream))
(t
(write-string "broken weak pointer" stream))))))
(defmethod print-object ((component code-component) stream)
(print-unreadable-object (component stream :identity t)
(let (dinfo)
(cond ((eq (setq dinfo (%code-debug-info component)) :bpt-lra)
(write-string "bpt-trap-return" stream))
((functionp dinfo)
(format stream "trampoline ~S" dinfo))
(t
(format stream "code~@[ id=~x~] [~D]"
(%code-serialno component)
(code-n-entries component))
(let ((fun-name (awhen (%code-entry-point component 0)
(%simple-fun-name it))))
(when fun-name
(write-char #\Space stream)
(write fun-name :stream stream))
(cond ((not (typep dinfo 'sb-c::debug-info)))
((neq (sb-c::debug-info-name dinfo) fun-name)
(write-string ", " stream)
(output-object (sb-c::debug-info-name dinfo) stream)))))))))
#-(or x86 x86-64 arm64 riscv)
(defmethod print-object ((lra lra) stream)
(print-unreadable-object (lra stream :identity t)
(write-string "return PC object" stream)))
(defmethod print-object ((fdefn fdefn) stream)
(print-unreadable-object (fdefn stream :type t)
;; As fdefn names are particularly relevant to those hacking on the compiler
and disassembler , be maximally helpful by neither abbreviating ( SETF ... )
;; due to length cutoff, nor failing to print a package if needed.
;; Some folks seem to love same-named symbols way too much.
(let ((*print-length* 20)) ; arbitrary
(prin1 (fdefn-name fdefn) stream))))
#+sb-simd-pack
(defmethod print-object ((pack simd-pack) stream)
(cond ((and *print-readably* *read-eval*)
(format stream "#.(~S #b~3,'0b #x~16,'0X #x~16,'0X)"
'%make-simd-pack
(%simd-pack-tag pack)
(%simd-pack-low pack)
(%simd-pack-high pack)))
(*print-readably*
(print-not-readable-error pack stream))
(t
(print-unreadable-object (pack stream)
(etypecase pack
((simd-pack double-float)
(multiple-value-call #'format stream "~S~@{ ~,13E~}" 'simd-pack
(%simd-pack-doubles pack)))
((simd-pack single-float)
(multiple-value-call #'format stream "~S~@{ ~,7E~}" 'simd-pack
(%simd-pack-singles pack)))
((simd-pack (unsigned-byte 8))
(multiple-value-call #'format stream "~S~@{ ~3D~}" 'simd-pack
(%simd-pack-ub8s pack)))
((simd-pack (unsigned-byte 16))
(multiple-value-call #'format stream "~S~@{ ~5D~}" 'simd-pack
(%simd-pack-ub16s pack)))
((simd-pack (unsigned-byte 32))
(multiple-value-call #'format stream "~S~@{ ~10D~}" 'simd-pack
(%simd-pack-ub32s pack)))
((simd-pack (unsigned-byte 64))
(multiple-value-call #'format stream "~S~@{ ~20D~}" 'simd-pack
(%simd-pack-ub64s pack)))
((simd-pack (signed-byte 8))
(multiple-value-call #'format stream "~S~@{ ~4,@D~}" 'simd-pack
(%simd-pack-sb8s pack)))
((simd-pack (signed-byte 16))
(multiple-value-call #'format stream "~S~@{ ~6,@D~}" 'simd-pack
(%simd-pack-sb16s pack)))
((simd-pack (signed-byte 32))
(multiple-value-call #'format stream "~S~@{ ~11@D~}" 'simd-pack
(%simd-pack-sb32s pack)))
((simd-pack (signed-byte 64))
(multiple-value-call #'format stream "~S~@{ ~20@D~}" 'simd-pack
(%simd-pack-sb64s pack))))))))
#+sb-simd-pack-256
(defmethod print-object ((pack simd-pack-256) stream)
(cond ((and *print-readably* *read-eval*)
(format stream "#.(~S #b~3,'0B #x~16,'0D #x~16,'0D #x~16,'0D #x~16,'0D)"
'%make-simd-pack-256
(%simd-pack-256-tag pack)
(%simd-pack-256-0 pack)
(%simd-pack-256-1 pack)
(%simd-pack-256-2 pack)
(%simd-pack-256-3 pack)))
(*print-readably*
(print-not-readable-error pack stream))
(t
(print-unreadable-object (pack stream)
(etypecase pack
((simd-pack-256 double-float)
(multiple-value-call #'format stream "~S~@{ ~,13E~}" 'simd-pack-256
(%simd-pack-256-doubles pack)))
((simd-pack-256 single-float)
(multiple-value-call #'format stream "~S~@{ ~,7E~}" 'simd-pack-256
(%simd-pack-256-singles pack)))
((simd-pack-256 (unsigned-byte 8))
(multiple-value-call #'format stream "~S~@{ ~3D~}" 'simd-pack-256
(%simd-pack-256-ub8s pack)))
((simd-pack-256 (unsigned-byte 16))
(multiple-value-call #'format stream "~S~@{ ~5D~}" 'simd-pack-256
(%simd-pack-256-ub16s pack)))
((simd-pack-256 (unsigned-byte 32))
(multiple-value-call #'format stream "~S~@{ ~10D~}" 'simd-pack-256
(%simd-pack-256-ub32s pack)))
((simd-pack-256 (unsigned-byte 64))
(multiple-value-call #'format stream "~S~@{ ~20D~}" 'simd-pack-256
(%simd-pack-256-ub64s pack)))
((simd-pack-256 (signed-byte 8))
(multiple-value-call #'format stream "~S~@{ ~4@D~}" 'simd-pack-256
(%simd-pack-256-sb8s pack)))
((simd-pack-256 (signed-byte 16))
(multiple-value-call #'format stream "~S~@{ ~6@D~}" 'simd-pack-256
(%simd-pack-256-sb16s pack)))
((simd-pack-256 (signed-byte 32))
(multiple-value-call #'format stream "~S~@{ ~11@D~}" 'simd-pack-256
(%simd-pack-256-sb32s pack)))
((simd-pack-256 (signed-byte 64))
(multiple-value-call #'format stream "~S~@{ ~20@D~}" 'simd-pack-256
(%simd-pack-256-sb64s pack))))))))
;;;; functions
(defmethod print-object ((object function) stream)
(macrolet ((unprintable-instance-p (x)
Guard against calling % FUN - FUN if it would return 0 .
;; %FUNCALLABLE-INSTANCE-FUN is known to return FUNCTION so determining
;; whether it is actually assigned requires a low-level trick.
(let ((s (sb-vm::primitive-object-slot
(sb-vm:primitive-object 'funcallable-instance)
'function)))
`(and (funcallable-instance-p ,x)
(eql 0 (%primitive sb-alien:slot ,x 'function ,(sb-vm:slot-offset s)
,sb-vm:fun-pointer-lowtag))))))
(when (unprintable-instance-p object)
(return-from print-object
(print-unreadable-object (object stream :type t :identity t)))))
(let* ((name (%fun-name object))
(proper-name-p (and (legal-fun-name-p name) (fboundp name)
(eq (fdefinition name) object))))
;; ":TYPE T" is no good, since CLOSURE doesn't have full-fledged status.
(print-unreadable-object (object stream :identity (not proper-name-p))
(format stream "~A~@[ ~S~]"
;; CLOSURE and SIMPLE-FUN should print as #<FUNCTION>
;; but anything else prints as its exact type.
(if (funcallable-instance-p object) (type-of object) 'function)
name))))
;;;; catch-all for unknown things
(defmethod print-object ((object t) stream)
(when (eq object sb-pcl:+slot-unbound+)
;; If specifically the unbound marker with 0 data,
;; as opposed to any other unbound marker.
(print-unreadable-object (object stream) (write-string "unbound" stream))
(return-from print-object))
NO - TLS - VALUE was added here as a printable object type for # + ubsan which ,
;; among other things, detects read-before-write on a per-array-element basis.
Git rev 22d8038118 caused uninitialized SIMPLE - VECTORs to get prefilled
with NO_TLS_VALUE_MARKER , but a better choice would be
;; (logior (mask-field (byte (- n-word-bits 8) 8) -1) unbound-marker-widetag).
;; #+ubsan has probably bitrotted for other reasons, so this is untested.
#+ubsan
(when (eql (get-lisp-obj-address object) unwritten-vector-element-marker)
(print-unreadable-object (object stream) (write-string "novalue" stream))
(return-from print-object))
(print-unreadable-object (object stream :identity t)
(let ((lowtag (lowtag-of object)))
(case lowtag
(#.sb-vm:other-pointer-lowtag
(let ((widetag (widetag-of object)))
(case widetag
(#.sb-vm:value-cell-widetag
(write-string "value cell " stream)
(output-object (value-cell-ref object) stream))
#+nil
(#.sb-vm:filler-widetag
(write-string "pad " stream)
(write (1+ (get-header-data object)) :stream stream)
(write-string "w" stream)) ; words
(t
(write-string "unknown pointer object, widetag=" stream)
(output-integer widetag stream 16 t)))))
((#.sb-vm:fun-pointer-lowtag
#.sb-vm:instance-pointer-lowtag
#.sb-vm:list-pointer-lowtag)
(write-string "unknown pointer object, lowtag=" stream)
(output-integer lowtag stream 16 t))
(t
(case (widetag-of object)
(#.sb-vm:unbound-marker-widetag
(write-string "unbound marker" stream))
(t
(write-string "unknown immediate object, lowtag=" stream)
(output-integer lowtag stream 2 t)
(write-string ", widetag=" stream)
(output-integer (widetag-of object) stream 16 t))))))))
| null | https://raw.githubusercontent.com/sbcl/sbcl/99687ae5df60f2a273ae9f6af281ef9e0b97bd0a/src/code/print.lisp | lisp | the printer
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
exported printer control variables
(set later when pretty-printer is initialized)
routines to print objects
Same as a call to (WRITE OBJECT :STREAM STREAM), but returning OBJECT.
This produces the printed representation of an object as a string.
The few ...-TO-STRING functions above call this.
Could do something for other numeric types, symbols, ...
Estimate the number of chars in the printed representation of OBJECT.
The answer must be an overestimate or exact; never an underestimate.
Round *PRINT-BASE* down to the nearest lower power-of-2, call that N,
This is exact for bases which are exactly a power-of-2, or an overestimate
otherwise, as mandated by the finite output stream.
leading sign
#rNN or trailing decimal
support for the PRINT-UNREADABLE-OBJECT macro
guts of PRINT-UNREADABLE-OBJECT
Do NOT insert a pprint-newline here.
See ba34717602d80e5fd74d10e61f4729fb0d019a0c
Nor here.
Since we're printing prettily on STREAM, format the
not rebind the stream when it is already a pretty stream,
so output from the body will go to the same stream.
circularity detection stuff
When *PRINT-CIRCLE* is T, this gets bound to a hash table that
(eventually) ends up with entries for every object printed. When
we are initially looking for circularities, we enter a T when we
printed.
found them all, this gets bound to 0. Then whenever we need a new
marker, it is incremented.
Check to see whether OBJECT is a circular reference, and return
something non-NIL if it is. If ASSIGN is true, reference
bookkeeping will only be done for existing entries, no new
references will be recorded. If ASSIGN is true, then the number to
Note: CHECK-FOR-CIRCULARITY must be called *exactly* once with
ASSIGN true, or the circularity detection noise will get confused
you need to initiate the circularity detection noise, e.g. bind
*CIRCULARITY-HASH-TABLE* and *CIRCULARITY-COUNTER* to suitable values
(see #'OUTPUT-OBJECT for an example).
These checks aren't really redundant (at least I can't really see
This causes problems when mixed with pprint-dispatching; an object is
marked as visited in OUTPUT-OBJECT, dispatched to a pretty printer
output like #1=#1#. The MODE parameter is used for detecting and
correcting this problem.
Don't bother, nobody cares.
first encounter
We need to keep looking.
We've seen the object before in output-object, and now
via pprint-dispatch). Don't mark it as circular yet.
It's a circular reference.
It's a circular reference.
object appears exactly once. Either way, just print
the thing without any special processing. Note: you
might argue that finding a new object means that
something is broken, but this can happen. If someone
uses the ~@<...~:> format directive, it conses a new
list each time though format (i.e. the &REST list),
so we will have different cdrs.
A circular reference to something that will be printed
as a logical block. Wait until we're called from
number.
If mode is :LOGICAL-BLOCK and assign is false, return true
to indicate that this object is circular, but don't assign
it a number yet. This is necessary for cases like
first occurrence of this object: Set the counter.
first occurrence of this object: Set the counter.
Handle the results of CHECK-FOR-CIRCULARITY. If this returns T then
you should blow it off.
Someone forgot to initiate circularity detection.
just looking. So don't bother groveling it again.
level and length abbreviations
The current level we are printing at, to be compared against
depth abbreviation.
Automatically handle *PRINT-LEVEL* abbreviation. If we are too
Punt if INDEX is equal or larger then *PRINT-LENGTH* (and
*PRINT-READABLY* is NIL) by outputting \"...\" and returning from
OUTPUT-OBJECT -- the main entry point
need to be checked for circularity.
Output OBJECT to STREAM observing all printer control variables.
FIXME: this function is declared EXPLICIT-CHECK, so it allows STREAM
to be T or NIL (a stream-designator), which is not really right
if eventually the call will be to a PRINT-OBJECT method,
since the generic function should always receive a stream.
otherwise
Maybe we don't need to bother with circularity detection.
If we have already started circularity detection, this
object might be a shared reference. If we have not, then
if it is a compound object it might contain a circular
reference to itself or multiple shared references.
Output OBJECT to STREAM observing all printer control variables
except for *PRINT-PRETTY*. Note: if *PRINT-PRETTY* is non-NIL,
then the pretty printer will be used for any components of OBJECT,
just not for OBJECT itself.
If an instance has no layout, do something sensible. Can't compare layout
Additionally, don't crash if the object is an obsolete thing with
no update protocol.
symbols
Write so that reading back works
Write only the characters of the name, never the package
Output NAME surrounded with |'s,
and with any embedded |'s or \'s escaped.
Hmm. Should these depend on what characters
are actually escapes in the readtable ?
The ANSI spec "22.1.3.3.1 Package Prefixes for Symbols"
requires that keywords be printed with preceding colons
always, regardless of the value of *PACKAGE*.
Otherwise, if the symbol's home package is the current
one, then a prefix is never necessary.
If we can find the symbol by looking it up, it need not
be qualified. This can happen if the symbol has been
inherited from a package other than its home package.
To preserve print-read consistency, use the local nickname if
one exists.
escaping symbols
When we print symbols we have to figure out if they need to be
printed with escape characters. This isn't a whole lot easier than
For each character, the value of the corresponding element is a
fixnum with bits set corresponding to attributes that the
search for any character with a positive test.
constants which are a bit-mask for each interesting character attribute
Anything else legal.
A numeric digit.
An uppercase letter.
A lowercase letter.
+-
^_
.
/
Anything illegal.
that don't need to be escaped (according to READTABLE-CASE.)
For each character, the value of the corresponding element is the
lowest base in which that character is a digit.
Mark anything not explicitly allowed as funny.
number or has evil characters in it.
At end, see whether it is a sign...
not potential number, see whether funny chars...
leading dots...
leading stuff before any dot or digit
number marker in leading stuff...
leading stuff containing dot without digit...
number marker in leading stuff with dot..
leading stuff containing dot without digit followed by letter...
in a thing with dots...
number marker in number with dot...
previous char is a letter digit...
seen a digit which is a letter...
number marker in number with alpha digit...
seen only ordinary (non-alphabetic) numeric digits...
number marker in a numeric number...
("What," you may ask, "is a 'number marker'?" It's something
that a conforming implementation might use in number syntax.
names according to the values of *PRINT-CASE* and READTABLE-CASE.
called when:
READTABLE-CASE *PRINT-CASE*
:UPCASE :UPCASE
:PRESERVE any
called when:
READTABLE-CASE *PRINT-CASE*
called when:
READTABLE-CASE *PRINT-CASE*
:DOWNCASE :UPCASE
called when:
READTABLE-CASE *PRINT-CASE*
called when:
READTABLE-CASE *PRINT-CASE*
:INVERT any
Call an output function based on PRINT-CASE and READTABLE-CASE.
recursive objects
(Don't use OUTPUT-OBJECT here, since this code
has to work for all possible *PRINT-BASE* values.)
Output a string, quoting characters to be readable by putting a slash in front
of any character satisfying NEEDS-SLASH-P.
this for now. [noted by anonymous long ago] -- WHN 19991130
Pre-test for any escaping, and if needed, do char-at-a-time output.
If no escaping needed, WRITE-STRING is way faster, up to 2x in my testing,
than WRITE-CHAR because the stream layer will get so many fewer calls.
Output the printed representation of any array in either the #< or #A
form.
Output the abbreviated #< form of an array.
Convert an array into a list that can be used with MAKE-ARRAY's
:INITIAL-CONTENTS keyword argument.
Use nonstandard #A(dimensions element-type contents)
to avoid using #.
Output the readable #A form of an array.
integer, ratio, and complex printing (i.e. everything but floats)
*POWER-CACHE* is an alist mapping bases to power-vectors. It is
filled and probed by POWERS-FOR-BASE. SCRUB-POWER-CACHE is called
It doesn't need a lock, but if you work on SCRUB-POWER-CACHE or
POWERS-FOR-BASE, see that you don't break the assumptions!
Compute (and cache) a power vector for a BASE and LIMIT:
the vector holds integers for which
(aref powers k) == (expt base (expt 2 k))
holds.
We don't actually need this, but we also
POWER is a vector for which the following holds:
(aref power k) == (expt base (expt 2 k))
N is the number to bisect
K on initial entry BASE^(2^K) > N
initial number, as we don't know the number
of digits there, but we do know that it
Not all architectures can stack-allocate lisp strings,
but we can fake it using aliens.
We don't need a trailing null.
+2 words for lisp string header
+1 is for alignment if needed
Using specialized routines for the various cases seems to work nicely.
new=.031 sec , 0 bytes consed
new=.075 sec , 0 bytes consed
new=.08 sec , 0 bytes consed
Grrr - a LET binding here causes a constant-folding problem
"The function SB-KERNEL:SIMPLE-CHARACTER-STRING-P is undefined."
but a symbol-macrolet is ok. This is a FIXME except I don't care.
Recurse until you have all the digits pushed on
the stack.
Then as each recursive call unwinds, turn the
digit (in remainder) into a character and output
the character.
Division vops can handle this all inline.
will be output. This allows for a single %WRITE-STRING call.
There's diminishing payback for other bases because the fixed array
size increases, and we don't have a way to elide initial 0-fill.
Calling APPROX-CHARS-IN-REPL doesn't help much - we still 0-fill.
Use the alien stack, which is not as fast as using the control stack
(when we can). Even the absence of 0-fill doesn't make up for it.
Since we've no choice in the matter, might as well allow
any value of BASE - it's just a few more words of storage.
No division is involved at all.
The ideal cutoff point between this and the "huge" algorithm
might be platform-specific, and it also could depend on the output base.
This gets both a method and a specifically named function
since the latter is called from a few places.
float printing
FLONUM-TO-STRING (and its subsidiary function FLOAT-STRING) does
most of the work for all printing of floating point numbers in
FORMAT. It converts a floating point number to a string in a free
or fixed format with no exponent. The interpretation of the
arguments is as follows:
X - The floating point number to convert, which must not be
negative.
WIDTH - The preferred field width, used to determine the number
decimal point alone exceed this width, no fraction digits
specified. Field overflow is not considerd an error at this
level.
are generated, subject to the constraint that there are no
trailing zeroes.
SCALE - If this parameter is specified or non-NIL, then the number
and cannot lose precision.
FMIN - This parameter, if specified or non-NIL, is the minimum
number of fraction digits which will be produced, regardless
the ~E format directive to prevent complete loss of
significance in the printed value due to a bogus choice of
scale factor.
Returns:
(VALUES DIGIT-STRING DIGIT-LENGTH LEADING-POINT TRAILING-POINT DECPNT)
where the results have the following interpretation:
DIGIT-STRING - The decimal representation of X, with decimal point.
DIGIT-LENGTH - The length of the string DIGIT-STRING.
decimal point.
TRAILING-POINT - True if the last character of DIGIT-STRING is the
decimal point.
POINT-POS - The position of the digit preceding the decimal
NOTE: FLONUM-TO-STRING goes to a lot of trouble to guarantee
accuracy. Specifically, the decimal number printed is the closest
possible approximation to the true value of the binary number to
be printed from among all decimal representations with the same
number of digits. In free-format output, i.e. with the number of
digits unconstrained, it is guaranteed that all the information is
preserved, so that a properly- rounding reader can reconstruct the
original binary number, bit-for-bit, from its printed decimal
representation. Furthermore, only as many digits as necessary to
satisfy this condition will be printed.
see below for comments.
extended in order to handle rounding.
THINK OF ATTEMPTING TO UNDERSTAND THIS CODE WITHOUT READING THE
PAPER!", and in this case we have to add that even reading the
paper might not bring immediate illumination as CSR has attempted
to turn idiomatic Scheme into idiomatic Lisp.
possible extension for the enthusiastic: printing floats in bases
Call CHAR-FUN with the digits of FLOAT
and after printing to set up the state.
B
b
p
An extra step became necessary here for subnormals because the
algorithm assumes that the fraction is left-aligned in a field
that is FLOAT-DIGITS wide.
mode. I wonder if we should cater for non-normal?
running out of letters here
original number. There may be some loss of precision due the
floating point representation. The scaling is always done with
long float arithmetic, which helps printing of lesser precisions
as well as avoiding generic arithmetic.
When computing our initial scale factor using EXPT, we pull out
part of the computation to avoid over/under flow. When
denormalized, we must pull out a large factor, since there is more
negative exponent range than positive range.
this is the closest double float
that we're not vulnerable to the
host lisp's interpretation of
ulp in this value, which is a
little unfortunate.)
entry point for the float printer
argument is printed free-format, in either exponential or
non-exponential notation, depending on its magnitude.
NOTE: When a number is to be printed in exponential format, it is
scaled in floating point. Since precision may be lost in this
process, the guaranteed accuracy properties of FLONUM-TO-STRING
are lost. The difficulty is that FLONUM-TO-STRING performs
extensive computations with integers of similar magnitude to that
of the number being printed. For large exponents, the bignums
really get out of hand. If bignum arithmetic becomes reasonably
fast and the exponent range is not too large, then it might become
attractive to handle exponential notation with the same accuracy
as non-exponential notation, using the method described in the
fixed-format printing.
Print the appropriate exponent marker for X and the specified exponent.
other leaf objects
If *PRINT-ESCAPE* is false, just do a WRITE-CHAR, otherwise output
As fdefn names are particularly relevant to those hacking on the compiler
due to length cutoff, nor failing to print a package if needed.
Some folks seem to love same-named symbols way too much.
arbitrary
functions
%FUNCALLABLE-INSTANCE-FUN is known to return FUNCTION so determining
whether it is actually assigned requires a low-level trick.
":TYPE T" is no good, since CLOSURE doesn't have full-fledged status.
CLOSURE and SIMPLE-FUN should print as #<FUNCTION>
but anything else prints as its exact type.
catch-all for unknown things
If specifically the unbound marker with 0 data,
as opposed to any other unbound marker.
among other things, detects read-before-write on a per-array-element basis.
(logior (mask-field (byte (- n-word-bits 8) 8) -1) unbound-marker-widetag).
#+ubsan has probably bitrotted for other reasons, so this is untested.
words |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB-IMPL")
(defvar *print-readably* nil
"If true, all objects will be printed readably. If readable printing
is impossible, an error will be signalled. This overrides the value of
*PRINT-ESCAPE*.")
(defvar *print-escape* t
"Should we print in a reasonably machine-readable way? (possibly
overridden by *PRINT-READABLY*)")
"Should pretty printing be used?")
(defvar *print-base* 10.
"The output base for RATIONALs (including integers).")
(defvar *print-radix* nil
"Should base be verified when printing RATIONALs?")
(defvar *print-level* nil
"How many levels should be printed before abbreviating with \"#\"?")
(defvar *print-length* nil
"How many elements at any level should be printed before abbreviating
with \"...\"?")
(defvar *print-vector-length* nil
"Like *PRINT-LENGTH* but works on strings and bit-vectors.
Does not affect the cases that are already controlled by *PRINT-LENGTH*")
(defvar *print-circle* nil
"Should we use #n= and #n# notation to preserve uniqueness in general (and
circularity in particular) when printing?")
(defvar *print-case* :upcase
"What case should the printer should use default?")
(defvar *print-array* t
"Should the contents of arrays be printed?")
(defvar *print-gensym* t
"Should #: prefixes be used when printing symbols with null SYMBOL-PACKAGE?")
(defvar *print-lines* nil
"The maximum number of lines to print per object.")
(defvar *print-right-margin* nil
"The position of the right margin in ems (for pretty-printing).")
(defvar *print-miser-width* nil
"If the remaining space between the current column and the right margin
is less than this, then print using ``miser-style'' output. Miser
style conditional newlines are turned on, and all indentations are
turned off. If NIL, never use miser mode.")
(defvar *print-pprint-dispatch*
(sb-pretty::make-pprint-dispatch-table #() nil nil)
"The pprint-dispatch-table that controls how to pretty-print objects.")
(defvar *suppress-print-errors* nil
"Suppress printer errors when the condition is of the type designated by this
variable: an unreadable object representing the error is printed instead.")
duplicate defglobal because this file is compiled before " reader "
(define-load-time-global *standard-readtable* nil)
(define-load-time-global sb-pretty::*standard-pprint-dispatch-table* nil)
(defun %with-standard-io-syntax (function)
(declare (type function function))
(declare (dynamic-extent function))
(let ((*package* #.(find-package "COMMON-LISP-USER"))
(*print-array* t)
(*print-base* 10)
(*print-case* :upcase)
(*print-circle* nil)
(*print-escape* t)
(*print-gensym* t)
(*print-length* nil)
(*print-level* nil)
(*print-lines* nil)
(*print-miser-width* nil)
(*print-pprint-dispatch* sb-pretty::*standard-pprint-dispatch-table*)
(*print-pretty* nil)
(*print-radix* nil)
(*print-readably* t)
(*print-right-margin* nil)
(*read-base* 10)
(*read-default-float-format* 'single-float)
(*read-eval* t)
(*read-suppress* nil)
(*readtable* *standard-readtable*)
(*suppress-print-errors* nil)
(*print-vector-length* nil))
(funcall function)))
(macrolet ((def (fn doc &rest forms)
`(defun ,fn
(object
&key
,@(if (eq fn 'write) '(stream))
((:escape *print-escape*) *print-escape*)
((:radix *print-radix*) *print-radix*)
((:base *print-base*) *print-base*)
((:circle *print-circle*) *print-circle*)
((:pretty *print-pretty*) *print-pretty*)
((:level *print-level*) *print-level*)
((:length *print-length*) *print-length*)
((:case *print-case*) *print-case*)
((:array *print-array*) *print-array*)
((:gensym *print-gensym*) *print-gensym*)
((:readably *print-readably*) *print-readably*)
((:right-margin *print-right-margin*)
*print-right-margin*)
((:miser-width *print-miser-width*)
*print-miser-width*)
((:lines *print-lines*) *print-lines*)
((:pprint-dispatch *print-pprint-dispatch*)
*print-pprint-dispatch*)
((:suppress-errors *suppress-print-errors*)
*suppress-print-errors*))
,doc
(declare (explicit-check))
,@forms)))
(def write
"Output OBJECT to the specified stream, defaulting to *STANDARD-OUTPUT*."
(output-object object (out-stream-from-designator stream))
object)
(def write-to-string
"Return the printed representation of OBJECT as a string."
(stringify-object object)))
(defun %write (object stream)
(declare (explicit-check))
(output-object object (out-stream-from-designator stream))
object)
(defun prin1 (object &optional stream)
"Output a mostly READable printed representation of OBJECT on the specified
STREAM."
(declare (explicit-check))
(let ((*print-escape* t))
(output-object object (out-stream-from-designator stream)))
object)
(defun princ (object &optional stream)
"Output an aesthetic but not necessarily READable printed representation
of OBJECT on the specified STREAM."
(declare (explicit-check))
(let ((*print-escape* nil)
(*print-readably* nil))
(output-object object (out-stream-from-designator stream)))
object)
(defun print (object &optional stream)
"Output a newline, the mostly READable printed representation of OBJECT, and
space to the specified STREAM."
(declare (explicit-check))
(let ((stream (out-stream-from-designator stream)))
(terpri stream)
(prin1 object stream)
(write-char #\space stream)
object))
(defun pprint (object &optional stream)
"Prettily output OBJECT preceded by a newline."
(declare (explicit-check))
(let ((*print-pretty* t)
(*print-escape* t)
(stream (out-stream-from-designator stream)))
(terpri stream)
(output-object object stream))
(values))
(defun prin1-to-string (object)
"Return the printed representation of OBJECT as a string with
slashification on."
(let ((*print-escape* t))
(stringify-object object)))
(defun princ-to-string (object)
"Return the printed representation of OBJECT as a string with
slashification off."
(let ((*print-escape* nil)
(*print-readably* nil))
(stringify-object object)))
(defun stringify-object (object)
(typecase object
(integer
(multiple-value-bind (fun pretty)
(and *print-pretty* (pprint-dispatch object))
(if pretty
(%with-output-to-string (stream)
(sb-pretty:output-pretty-object stream fun object))
(let ((buffer-size (approx-chars-in-repr object)))
(let* ((string (make-string buffer-size :element-type 'base-char))
(stream (%make-finite-base-string-output-stream string)))
(declare (inline %make-finite-base-string-output-stream))
(declare (truly-dynamic-extent stream))
(output-integer object stream *print-base* *print-radix*)
(%shrink-vector string
(finite-base-string-output-stream-pointer stream)))))))
(t
(%with-output-to-string (stream)
(output-object object stream)))))
(defun approx-chars-in-repr (object)
(declare (integer object))
and " guess " that the one character can represent N bits .
(let ((bits-per-char
(aref #.(coerce
base 2 or base 3 = 1 bit per character
base 4 .. base 7 = 2 bits per character
base 8 .. base 15 = 3 bits per character , etc
#(1 1 2 2 2 2 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5)
'(vector (unsigned-byte 8)))
(- *print-base* 2))))
(ceiling (if (fixnump object)
sb-vm:n-positive-fixnum-bits
(* (%bignum-length object) sb-bignum::digit-size))
bits-per-char))))
(defun print-not-readable-error (object stream)
(restart-case
(error 'print-not-readable :object object)
(print-unreadably ()
:report "Print unreadably."
(let ((*print-readably* nil))
(output-object object stream)
object))
(use-value (o)
:report "Supply an object to be printed instead."
:interactive
(lambda ()
(read-evaluated-form "~@<Enter an object (evaluated): ~@:>"))
(output-object o stream)
o)))
(defun %print-unreadable-object (object stream flags &optional body)
(declare (type (or null function) body))
(if *print-readably*
(print-not-readable-error object stream)
(flet ((print-description (&aux (type (logbitp 0 (truly-the (mod 4) flags)))
(identity (logbitp 1 flags)))
(when type
(write (type-of object) :stream stream :circle nil
:level nil :length nil)
(write-char #\space stream))
(when body
(funcall body))
(when identity
(when (or body (not type))
(write-char #\space stream))
(write-char #\{ stream)
(%output-integer-in-base (get-lisp-obj-address object) 16 stream)
(write-char #\} stream))))
(cond ((print-pretty-on-stream-p stream)
object within a logical block . PPRINT - LOGICAL - BLOCK does
(pprint-logical-block (stream nil :prefix "#<" :suffix ">")
(print-description)))
(t
(write-string "#<" stream)
(print-description)
(write-char #\> stream)))))
nil)
find an object for the first time , and a 0 when we encounter an
object a second time around . When we are actually printing , the 0
entries get changed to the actual marker value when they are first
(defvar *circularity-hash-table* nil)
When NIL , we are just looking for circularities . After we have
(defvar *circularity-counter* nil)
use in the # n= and # n # noise is assigned at this time .
about when to use # n= and when to use # n # . If this returns non - NIL
when is true , then you must call HANDLE - CIRCULARITY on it .
If CHECK - FOR - CIRCULARITY returns : INITIATE as the second value ,
Circularity detection is done in two places , OUTPUT - OBJECT and
WITH - CIRCULARITY - DETECTION ( which is used from PPRINT - LOGICAL - BLOCK ) .
a clean way of getting by with the checks in only one of the places ) .
that uses PPRINT - LOGICAL - BLOCK ( directly or indirectly ) , leading to
(defun check-for-circularity (object &optional assign (mode t))
(when (null *print-circle*)
(return-from check-for-circularity nil))
(let ((circularity-hash-table *circularity-hash-table*))
(cond
((null circularity-hash-table)
(values nil :initiate))
((null *circularity-counter*)
(ecase (gethash object circularity-hash-table)
((nil)
(setf (gethash object circularity-hash-table) mode)
nil)
((:logical-block)
(setf (gethash object circularity-hash-table)
:logical-block-circular)
t)
((t)
(cond ((eq mode :logical-block)
a second time in a PPRINT - LOGICAL - BLOCK ( for example
(setf (gethash object circularity-hash-table)
:logical-block)
nil)
(t
second encounter
(setf (gethash object circularity-hash-table) 0)
t)))
((0 :logical-block-circular)
t)))
(t
(let ((value (gethash object circularity-hash-table)))
(case value
((nil t :logical-block)
If NIL , we found an object that was n't there the
first time around . If T or : LOGICAL - BLOCK , this
nil)
PPRINT - LOGICAL - BLOCK with ASSIGN true before assigning the
# 1=(#2=(#2 # . # 3=(#1 # . # 3 # ) ) ) ) ) .
(:logical-block-circular
(cond ((and (not assign)
(eq mode :logical-block))
t)
((and assign
(eq mode :logical-block))
(let ((value (incf *circularity-counter*)))
(setf (gethash object circularity-hash-table) value)
value))
(t
nil)))
(0
(if (eq assign t)
(let ((value (incf *circularity-counter*)))
(setf (gethash object circularity-hash-table) value)
value)
t))
(t
second or later occurrence
(- value))))))))
you should go ahead and print the object . If it returns NIL , then
(defun handle-circularity (marker stream)
(case marker
(:initiate
(let ((*print-circle* nil))
(error "trying to use CHECK-FOR-CIRCULARITY when ~
circularity checking isn't initiated")))
((t :logical-block)
It 's a second ( or later ) reference to the object while we are
nil)
(t
(write-char #\# stream)
(output-integer (abs marker) stream 10 nil)
(cond ((minusp marker)
(write-char #\# stream)
nil)
(t
(write-char #\= stream)
t)))))
(defmacro with-circularity-detection ((object stream) &body body)
(with-unique-names (marker body-name)
`(labels ((,body-name ()
,@body))
(cond ((or (not *print-circle*)
(uniquely-identified-by-print-p ,object))
(,body-name))
(*circularity-hash-table*
(let ((,marker (check-for-circularity ,object t :logical-block)))
(if ,marker
(when (handle-circularity ,marker ,stream)
(,body-name))
(,body-name))))
(t
(let ((*circularity-hash-table* (make-hash-table :test 'eq)))
(output-object ,object *null-broadcast-stream*)
(let ((*circularity-counter* 0))
(let ((,marker (check-for-circularity ,object t
:logical-block)))
(when ,marker
(handle-circularity ,marker ,stream)))
(,body-name))))))))
* PRINT - LEVEL * . See the macro DESCEND - INTO for a handy interface to
(defvar *current-level-in-print* 0)
(declaim (index *current-level-in-print*))
deep , then a # \ # is printed to STREAM and BODY is ignored .
(defmacro descend-into ((stream) &body body)
(let ((flet-name (gensym "DESCEND")))
`(flet ((,flet-name ()
,@body))
(cond ((and (null *print-readably*)
(let ((level *print-level*))
(and level (>= *current-level-in-print* level))))
(write-char #\# ,stream))
(t
(let ((*current-level-in-print* (1+ *current-level-in-print*)))
(,flet-name)))))))
the block named NIL .
(defmacro punt-print-if-too-long (index stream)
`(when (and (not *print-readably*)
(let ((len *print-length*))
(and len (>= ,index len))))
(write-string "..." ,stream)
(return)))
Objects whose print representation identifies them EQLly do n't
(defun uniquely-identified-by-print-p (x)
(or (numberp x)
(characterp x)
(and (symbolp x)
(sb-xc:symbol-package x))))
(defvar *in-print-error* nil)
(defun output-object (object stream)
(declare (explicit-check))
(labels ((print-it (stream)
(multiple-value-bind (fun pretty)
(and *print-pretty* (pprint-dispatch object))
(if pretty
(sb-pretty:output-pretty-object stream fun object)
(output-ugly-object stream object))))
(handle-it (stream)
(if *suppress-print-errors*
(handler-bind
((condition
(lambda (condition)
(when (typep condition *suppress-print-errors*)
(cond (*in-print-error*
(write-string "(error printing " stream)
(write-string *in-print-error* stream)
(write-string ")" stream))
(t
(let ((*print-readably* nil)
(*print-escape* t))
(write-string
"#<error printing a " stream)
(let ((*in-print-error* "type"))
(output-object (type-of object) stream))
(write-string ": " stream)
(let ((*in-print-error* "condition"))
(output-object condition stream))
(write-string ">" stream))))
(return-from handle-it object)))))
(print-it stream))
(print-it stream)))
(check-it (stream)
(multiple-value-bind (marker initiate)
(check-for-circularity object t)
(if (eq initiate :initiate)
(let ((*circularity-hash-table*
(make-hash-table :test 'eq)))
(check-it *null-broadcast-stream*)
(let ((*circularity-counter* 0))
(check-it stream)))
(if marker
(when (handle-circularity marker stream)
(handle-it stream))
(handle-it stream))))))
(or (not *print-circle*)
(uniquely-identified-by-print-p object))
(handle-it stream))
(or *circularity-hash-table*
(compound-object-p object))
(check-it stream))
(t
(handle-it stream)))))
(defun output-ugly-object (stream object)
(when (%instancep object)
(let ((layout (%instance-layout object)))
to 0 using EQ or EQL because that would be tautologically NIL as per fndb .
This is better than declaring EQ or % INSTANCE - LAYOUT notinline .
(unless (logtest (get-lisp-obj-address layout) sb-vm:widetag-mask)
(return-from output-ugly-object
(print-unreadable-object (object stream :identity t)
(prin1 'instance stream))))
(let* ((wrapper (layout-friend layout))
(classoid (wrapper-classoid wrapper)))
(when (or (sb-kernel::undefined-classoid-p classoid)
(and (wrapper-invalid wrapper)
(logtest (layout-flags layout)
(logior +structure-layout-flag+
+condition-layout-flag+))))
(return-from output-ugly-object
(print-unreadable-object (object stream :identity t)
(format stream "UNPRINTABLE instance of ~W" classoid)))))))
(when (funcallable-instance-p object)
(let ((layout (%fun-layout object)))
(unless (logtest (get-lisp-obj-address layout) sb-vm:widetag-mask)
(return-from output-ugly-object
(print-unreadable-object (object stream :identity t)
(prin1 'funcallable-instance stream))))))
(print-object object stream))
(defmethod print-object ((object symbol) stream)
(if (or *print-escape* *print-readably*)
(output-symbol object (sb-xc:symbol-package object) stream)
(let ((rt *readtable*))
(output-symbol-case-dispatch *print-case* (readtable-case rt)
(symbol-name object) stream rt))))
(defun output-symbol (symbol package stream)
(let* ((readably *print-readably*)
(readtable (if readably *standard-readtable* *readtable*))
(print-case *print-case*)
(readtable-case (readtable-case readtable)))
(flet ((output-token (name)
(declare (type simple-string name))
(cond ((or (and (readtable-normalization readtable)
(not (sb-unicode:normalized-p name :nfkc)))
(symbol-quotep name readtable))
(write-char #\| stream)
(dotimes (index (length name))
(let ((char (char name index)))
( See similar remark at DEFUN QUOTE - STRING )
(when (or (char= char #\\) (char= char #\|))
(write-char #\\ stream))
(write-char char stream)))
(write-char #\| stream))
(t
(output-symbol-case-dispatch print-case readtable-case
name stream readtable)))))
(let ((name (symbol-name symbol))
(current (sane-package)))
(cond
((eq package *keyword-package*)
(write-char #\: stream))
((eq package current))
Uninterned symbols print with a leading # : .
((null package)
(when (or *print-gensym* readably)
(write-string "#:" stream)))
(t
(multiple-value-bind (found accessible) (find-symbol name current)
(unless (and accessible (eq found symbol))
(output-token (or (package-local-nickname package current)
(package-name package)))
(write-string (if (symbol-externalp symbol package) ":" "::")
stream)))))
(output-token name)))))
reading symbols in the first place .
character has . All characters have at least one bit set , so we can
LETTER - ATTRIBUTE is a local of SYMBOL - QUOTEP . It matches letters
(defconstant-eqx +attribute-names+
'((number . number-attribute) (lowercase . lowercase-attribute)
(uppercase . uppercase-attribute) (letter . letter-attribute)
(sign . sign-attribute) (extension . extension-attribute)
(dot . dot-attribute) (slash . slash-attribute)
(other . other-attribute) (funny . funny-attribute))
#'equal)
(defconstant-eqx +digit-bases+
#.(let ((a (sb-xc:make-array base-char-code-limit
:retain-specialization-for-after-xc-core t
:element-type '(unsigned-byte 8)
:initial-element 36)))
(dotimes (i 36 a)
(let ((char (digit-char i 36)))
(setf (aref a (char-code char)) i))))
#'equalp)
(defconstant-eqx +character-attributes+
FIXME
:retain-specialization-for-after-xc-core t
:element-type '(unsigned-byte 16)
:initial-element 0)))
(flet ((set-bit (char bit)
(let ((code (char-code char)))
(setf (aref a code) (logior bit (aref a code))))))
(dolist (char '(#\! #\@ #\$ #\% #\& #\* #\= #\~ #\[ #\] #\{ #\}
#\? #\< #\>))
(set-bit char other-attribute))
(dotimes (i 10)
(set-bit (digit-char i) number-attribute))
(do ((code (char-code #\A) (1+ code))
(end (char-code #\Z)))
((> code end))
(declare (fixnum code end))
(set-bit (code-char code) uppercase-attribute)
(set-bit (char-downcase (code-char code)) lowercase-attribute))
(set-bit #\- sign-attribute)
(set-bit #\+ sign-attribute)
(set-bit #\^ extension-attribute)
(set-bit #\_ extension-attribute)
(set-bit #\. dot-attribute)
(set-bit #\/ slash-attribute)
FIXME
(when (zerop (aref a i))
(setf (aref a i) funny-attribute))))
a)
#'equalp)
A FSM - like thingie that determines whether a symbol is a potential
(defun symbol-quotep (name readtable)
(declare (simple-string name))
(macrolet ((advance (tag &optional (at-end t))
`(progn
(when (= index len)
,(if at-end '(go TEST-SIGN) '(return nil)))
(setq current (schar name index)
code (char-code current)
FIXME
((< code 160) (aref attributes code))
((upper-case-p current) uppercase-attribute)
((lower-case-p current) lowercase-attribute)
(t other-attribute)))
(incf index)
(go ,tag)))
(test (&rest attributes)
`(not (zerop
(the fixnum
(logand
(logior ,@(mapcar
(lambda (x)
(or (cdr (assoc x
+attribute-names+))
(error "Blast!")))
attributes))
bits)))))
(digitp ()
FIXME
(< (the fixnum (aref bases code)) base))))
(prog ((len (length name))
(attributes #.+character-attributes+)
(bases #.+digit-bases+)
(base *print-base*)
(letter-attribute
(case (readtable-case readtable)
(:upcase uppercase-attribute)
(:downcase lowercase-attribute)
(t (logior lowercase-attribute uppercase-attribute))))
(index 0)
(bits 0)
(code 0)
current)
(declare (fixnum len base index bits code))
(advance START t)
(return (not (test sign)))
(let ((mask (logxor (logior lowercase-attribute uppercase-attribute
funny-attribute)
letter-attribute)))
(do ((i (1- index) (1+ i)))
((= i len) (return-from symbol-quotep nil))
(unless (zerop (logand (let* ((char (schar name i))
(code (char-code char)))
(cond
((< code 160) (aref attributes code))
((upper-case-p char) uppercase-attribute)
((lower-case-p char) lowercase-attribute)
(t other-attribute)))
mask))
(return-from symbol-quotep t))))
START
(when (digitp)
(if (test letter)
(advance LAST-DIGIT-ALPHA)
(advance DIGIT)))
(when (test letter number other slash) (advance OTHER nil))
(when (char= current #\.) (advance DOT-FOUND))
(when (test sign extension) (advance START-STUFF nil))
(return t)
(when (test letter) (advance START-DOT-MARKER nil))
(when (digitp) (advance DOT-DIGIT))
(when (test number other) (advance OTHER nil))
(when (test extension slash sign) (advance START-DOT-STUFF nil))
(when (char= current #\.) (advance DOT-FOUND))
(return t)
(when (digitp)
(if (test letter)
(advance LAST-DIGIT-ALPHA)
(advance DIGIT)))
(when (test number other) (advance OTHER nil))
(when (test letter) (advance START-MARKER nil))
(when (char= current #\.) (advance START-DOT-STUFF nil))
(when (test sign extension slash) (advance START-STUFF nil))
(return t)
(when (test letter) (advance OTHER nil))
(go START-STUFF)
(when (test letter) (advance START-DOT-STUFF nil))
(when (digitp) (advance DOT-DIGIT))
(when (test sign extension dot slash) (advance START-DOT-STUFF nil))
(when (test number other) (advance OTHER nil))
(return t)
(when (test letter) (advance OTHER nil))
(go START-DOT-STUFF)
(when (test letter) (advance DOT-MARKER))
(when (digitp) (advance DOT-DIGIT))
(when (test number other) (advance OTHER nil))
(when (test sign extension dot slash) (advance DOT-DIGIT))
(return t)
(when (test letter) (advance OTHER nil))
(go DOT-DIGIT)
(when (or (digitp) (test sign slash))
(advance ALPHA-DIGIT))
(when (test letter number other dot) (advance OTHER nil))
(return t)
(when (or (digitp) (test sign slash))
(if (test letter)
(advance LAST-DIGIT-ALPHA)
(advance ALPHA-DIGIT)))
(when (test letter) (advance ALPHA-MARKER))
(when (test number other dot) (advance OTHER nil))
(return t)
(when (test letter) (advance OTHER nil))
(go ALPHA-DIGIT)
(when (digitp)
(if (test letter)
(advance ALPHA-DIGIT)
(advance DIGIT)))
(when (test number other) (advance OTHER nil))
(when (test letter) (advance MARKER))
(when (test extension slash sign) (advance DIGIT))
(when (char= current #\.) (advance DOT-DIGIT))
(return t)
See ANSI 2.3.1.1 " Potential Numbers as Tokens " . )
(when (test letter) (advance OTHER nil))
(go DIGIT))))
case hackery : One of these functions is chosen to output symbol
(declaim (start-block output-symbol-case-dispatch))
: DOWNCASE : DOWNCASE
(defun output-preserve-symbol (pname stream readtable)
(declare (ignore readtable))
(write-string pname stream))
: UPCASE : DOWNCASE
(defun output-lowercase-symbol (pname stream readtable)
(declare (simple-string pname) (ignore readtable))
(dotimes (index (length pname))
(let ((char (schar pname index)))
(write-char (char-downcase char) stream))))
(defun output-uppercase-symbol (pname stream readtable)
(declare (simple-string pname) (ignore readtable))
(dotimes (index (length pname))
(let ((char (schar pname index)))
(write-char (char-upcase char) stream))))
: UPCASE : CAPITALIZE
: DOWNCASE : CAPITALIZE
(defun output-capitalize-symbol (pname stream readtable)
(declare (simple-string pname))
(let ((prev-not-alphanum t)
(up (eq (readtable-case readtable) :upcase)))
(dotimes (i (length pname))
(let ((char (char pname i)))
(write-char (if up
(if (or prev-not-alphanum (lower-case-p char))
char
(char-downcase char))
(if prev-not-alphanum
(char-upcase char)
char))
stream)
(setq prev-not-alphanum (not (alphanumericp char)))))))
(defun output-invert-symbol (pname stream readtable)
(declare (simple-string pname) (ignore readtable))
(let ((all-upper t)
(all-lower t))
(dotimes (i (length pname))
(let ((ch (schar pname i)))
(when (both-case-p ch)
(if (upper-case-p ch)
(setq all-lower nil)
(setq all-upper nil)))))
(cond (all-upper (output-lowercase-symbol pname stream nil))
(all-lower (output-uppercase-symbol pname stream nil))
(t
(write-string pname stream)))))
(defun output-symbol-case-dispatch (print-case readtable-case name stream readtable)
(ecase readtable-case
(:upcase
(ecase print-case
(:upcase (output-preserve-symbol name stream readtable))
(:downcase (output-lowercase-symbol name stream readtable))
(:capitalize (output-capitalize-symbol name stream readtable))))
(:downcase
(ecase print-case
(:upcase (output-uppercase-symbol name stream readtable))
(:downcase (output-preserve-symbol name stream readtable))
(:capitalize (output-capitalize-symbol name stream readtable))))
(:preserve (output-preserve-symbol name stream readtable))
(:invert (output-invert-symbol name stream readtable))))
(declaim (end-block))
(defmethod print-object ((list cons) stream)
(descend-into (stream)
(write-char #\( stream)
(let ((length 0)
(list list))
(loop
(punt-print-if-too-long length stream)
(output-object (pop list) stream)
(unless list
(return))
(when (or (atom list)
(check-for-circularity list))
(write-string " . " stream)
(output-object list stream)
(return))
(write-char #\space stream)
(incf length)))
(write-char #\) stream)))
(defmethod print-object ((vector vector) stream)
(let ((readably *print-readably*))
(flet ((cut-length ()
(when (and (not readably)
*print-vector-length*
(> (length vector) *print-vector-length*))
(print-unreadable-object (vector stream :type t :identity t)
(format stream "~A..."
(make-array *print-vector-length*
:element-type (array-element-type vector)
:displaced-to vector)))
t)))
(cond ((stringp vector)
(cond ((and readably (not (typep vector '(vector character))))
(output-unreadable-array-readably vector stream))
((and *print-escape*
(cut-length)))
((or *print-escape* readably)
(write-char #\" stream)
(quote-string vector stream)
(write-char #\" stream))
(t
(write-string vector stream))))
((or (null (array-element-type vector))
(not (or *print-array* readably)))
(output-terse-array vector stream))
((bit-vector-p vector)
(cond ((cut-length))
(t
(write-string "#*" stream)
(dovector (bit vector)
(write-char (if (zerop bit) #\0 #\1) stream)))))
((or (not readably) (array-readably-printable-p vector))
(descend-into (stream)
(write-string "#(" stream)
(dotimes (i (length vector))
(unless (zerop i)
(write-char #\space stream))
(punt-print-if-too-long i stream)
(output-object (aref vector i) stream))
(write-string ")" stream)))
(t
(output-unreadable-array-readably vector stream))))))
(defun quote-string (string stream)
(macrolet ((needs-slash-p (char)
: We probably should look at the readtable , but just do
`(let ((c ,char)) (or (char= c #\\) (char= c #\"))))
(scan (type)
For 1 or 0 characters , always take the WRITE - CHAR branch .
`(let ((data (truly-the ,type data)))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(when (or (<= (- end start) 1)
(do ((index start (1+ index)))
((>= index end))
(when (needs-slash-p (schar data index)) (return t))))
(do ((index start (1+ index)))
((>= index end) (return-from quote-string))
(let ((char (schar data index)))
(when (needs-slash-p char) (write-char #\\ stream))
(write-char char stream)))))))
(with-array-data ((data string) (start) (end)
:check-fill-pointer t)
(if (simple-base-string-p data)
(scan simple-base-string)
#+sb-unicode (scan simple-character-string)))
(write-string string stream)))
(defun array-readably-printable-p (array)
(and (eq (array-element-type array) t)
(let ((zero (position 0 (array-dimensions array)))
(number (position 0 (array-dimensions array)
:test (complement #'eql)
:from-end t)))
(or (null zero) (null number) (> zero number)))))
(defmethod print-object ((array array) stream)
(if (and (or *print-array* *print-readably*) (array-element-type array))
(output-array-guts array stream)
(output-terse-array array stream)))
(defun output-terse-array (array stream)
(let ((*print-level* nil)
(*print-length* nil))
(if (and (not (array-element-type array)) *print-readably* *read-eval*)
(format stream "#.(~S '~D :ELEMENT-TYPE ~S)"
'make-array (array-dimensions array) nil)
(print-unreadable-object (array stream :type t :identity t)))))
(defun listify-array (array)
(flet ((compact (seq)
(typecase array
(string
(coerce seq '(simple-array character (*))))
((array bit)
(coerce seq 'bit-vector))
(t
seq))))
(if (typep array '(or string bit-vector))
(compact array)
(with-array-data ((data array) (start) (end))
(declare (ignore end))
(labels ((listify (dimensions index)
(if (null dimensions)
(aref data index)
(let* ((dimension (car dimensions))
(dimensions (cdr dimensions))
(count (reduce #'* dimensions)))
(loop for i below dimension
for list = (listify dimensions index)
collect (if (and dimensions
(null (cdr dimensions)))
(compact list)
list)
do (incf index count))))))
(listify (array-dimensions array) start))))))
(defun output-unreadable-array-readably (array stream)
(let ((array (list* (array-dimensions array)
(array-element-type array)
(listify-array array))))
(write-string "#A" stream)
(write array :stream stream)
nil))
(defun output-array-guts (array stream)
(cond ((or (not *print-readably*)
(array-readably-printable-p array))
(write-char #\# stream)
(output-integer (array-rank array) stream 10 nil)
(write-char #\A stream)
(with-array-data ((data array) (start) (end))
(declare (ignore end))
(sub-output-array-guts data (array-dimensions array) stream start)))
(t
(output-unreadable-array-readably array stream))))
(defun sub-output-array-guts (array dimensions stream index)
(declare (type (simple-array * (*)) array) (fixnum index))
(cond ((null dimensions)
(output-object (aref array index) stream))
(t
(descend-into (stream)
(write-char #\( stream)
(let* ((dimension (car dimensions))
(dimensions (cdr dimensions))
(count (reduce #'* dimensions)))
(dotimes (i dimension)
(unless (zerop i)
(write-char #\space stream))
(punt-print-if-too-long i stream)
(sub-output-array-guts array dimensions stream index)
(incf index count)))
(write-char #\) stream)))))
(defun %output-radix (base stream)
(write-char #\# stream)
(write-char (case base
(2 #\b)
(8 #\o)
(16 #\x)
(t (%output-integer-in-base base 10 stream) #\r))
stream))
always prior a GC to drop overly large bignums from the cache .
(define-load-time-global *power-cache* (make-array 37 :initial-element nil))
(declaim (type (simple-vector 37) *power-cache*))
(defconstant +power-cache-integer-length-limit+ 2048)
(defun scrub-power-cache (&aux (cache *power-cache*))
(dotimes (i (length cache))
(let ((powers (aref cache i)))
(when powers
(let ((too-big (position-if
(lambda (x)
(>= (integer-length x)
+power-cache-integer-length-limit+))
(the simple-vector powers))))
(when too-big
(setf (aref cache i) (subseq powers 0 too-big))))))))
(defun powers-for-base (base limit)
(flet ((compute-powers (from)
(let (powers)
(do ((p from (* p p)))
((> p limit)
prefer not to cons it up a second time ...
(push p powers))
(push p powers))
(nreverse powers))))
(let* ((cache *power-cache*)
(powers (aref cache base)))
(setf (aref cache base)
(concatenate 'vector powers
(compute-powers
(if powers
(let* ((len (length powers))
(max (svref powers (1- len))))
(if (> max limit)
(return-from powers-for-base powers)
(* max max)))
base)))))))
Algorithm by , sbcl - devel 2005 - 02 - 05
(defun %output-huge-integer-in-base (n base stream)
(declare (type bignum n) (type fixnum base))
(let* ((power (powers-for-base base n))
(k-start (or (position-if (lambda (x) (> x n)) power)
(bug "power-vector too short"))))
(labels ((bisect (n k exactp)
(declare (fixnum k))
EXACTP is true if is the exact number of digits
(cond ((zerop n)
(when exactp
(loop repeat (ash 1 k) do (write-char #\0 stream))))
((zerop k)
(write-char
(schar "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" n)
stream))
(t
(setf k (1- k))
(multiple-value-bind (q r) (truncate n (aref power k))
EXACTP is NIL only at the head of the
does n't get any leading zeros .
(bisect q k exactp)
(bisect r k (or exactp (plusp q))))))))
(bisect n k-start nil))))
% output - integer - in - base always needs 8 lispwords :
if n - word - bytes = 4 then 8 * 4 = 32 characters
if n - word - bytes = 8 then 8 * 8 = 64 characters
This allows for output in base 2 worst case .
(defmacro with-lisp-string-on-alien-stack ((string size-in-chars) &body body)
(+ 2 (align-up (ceiling (symbol-value size-in-chars) sb-vm:n-word-bytes)
2)))
(alien '#:a)
(sap '#:sap))
`(with-alien ((,alien (array unsigned ,(1+ size-in-lispwords))))
(let ((,sap (alien-sap ,alien)))
(when (logtest (sap-int ,sap) sb-vm:lowtag-mask)
(setq ,sap (sap+ ,sap sb-vm:n-word-bytes)))
(setf (sap-ref-word ,sap 0) sb-vm:simple-base-string-widetag
(sap-ref-word ,sap sb-vm:n-word-bytes) (ash sb-vm:n-word-bits
sb-vm:n-fixnum-tag-bits))
(let ((,string
(truly-the simple-base-string
(%make-lisp-obj (logior (sap-int ,sap)
sb-vm:other-pointer-lowtag)))))
,@body)))))
Testing with 100,000 random integers , output to a sink stream , x86 - 64 :
word - sized integers , base > = 10
word - sized integers , base < 10
bignums in base 16 :
Not sure why this did n't reduce consing on when I tried it .
(defun %output-integer-in-base (integer base stream)
(declare (type (integer 2 36) base))
(when (minusp integer)
(write-char #\- stream)
(setf integer (- integer)))
(symbol-macrolet ((chars "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
(declare (optimize (sb-c:insert-array-bounds-checks 0) speed))
(macrolet ((iterative-algorithm ()
`(loop (multiple-value-bind (q r)
(truncate (truly-the word integer) base)
(decf ptr)
(setf (aref buffer ptr) (schar chars r))
(when (zerop (setq integer q)) (return)))))
(recursive-algorithm (dividend-type)
`(named-let recurse ((n integer))
(multiple-value-bind (q r) (truncate (truly-the ,dividend-type n) base)
(unless (zerop q) (recurse q))
(write-char (schar chars r) stream)))))
strings can be DX
For bases exceeding 10 we know how many characters ( at most )
(if (< base 10)
(recursive-algorithm word)
(let* ((ptr #.(length (write-to-string sb-ext:most-positive-word
:base 10)))
(buffer (make-array ptr :element-type 'base-char)))
(declare (truly-dynamic-extent buffer))
(iterative-algorithm)
(%write-string buffer stream ptr (length buffer))))
strings can not be DX
(let ((ptr sb-vm:n-word-bits))
(with-lisp-string-on-alien-stack (buffer sb-vm:n-word-bits)
(iterative-algorithm)
(%write-string buffer stream ptr sb-vm:n-word-bits))))
((eql base 16)
could also specialize for bases 32 , 8 , 4 , and 2 if desired
(loop for pos from (* 4 (1- (ceiling (integer-length integer) 4)))
downto 0 by 4
do (write-char (schar chars (sb-bignum::ldb-bignum=>fixnum 4 pos
integer))
stream)))
Nobody has cared to tweak it in so many years that I think we can
arbitrarily say 3 bigdigits is fine .
((<= (sb-bignum:%bignum-length (truly-the bignum integer)) 3)
(recursive-algorithm integer))
(t
(%output-huge-integer-in-base integer base stream)))))
nil)
(defmethod print-object ((object integer) stream)
(output-integer object stream *print-base* *print-radix*))
(defun output-integer (integer stream base radixp)
(cond (radixp
(unless (= base 10) (%output-radix base stream))
(%output-integer-in-base integer base stream)
(when (= base 10) (write-char #\. stream)))
(t
(%output-integer-in-base integer base stream))))
(defmethod print-object ((ratio ratio) stream)
(let ((base *print-base*))
(when *print-radix*
(%output-radix base stream))
(%output-integer-in-base (numerator ratio) base stream)
(write-char #\/ stream)
(%output-integer-in-base (denominator ratio) base stream)))
(defmethod print-object ((complex complex) stream)
(write-string "#C(" stream)
(output-object (realpart complex) stream)
(write-char #\space stream)
(output-object (imagpart complex) stream)
(write-char #\) stream))
of fraction digits to produce if the FDIGITS parameter
is unspecified or NIL . If the non - fraction digits and the
will be produced unless a non - NIL value of FDIGITS has been
FDIGITS - The number of fractional digits to produce . Insignificant
trailing zeroes may be introduced as needed . May be
unspecified or NIL , in which case as many digits as possible
printed is ( * x ( expt 10 scale ) ) . This scaling is exact ,
of the value of WIDTH or FDIGITS . This feature is used by
LEADING - POINT - True if the first character of DIGIT - STRING is the
point . Zero indicates point before first digit .
(defun flonum-to-string (x &optional width fdigits scale fmin)
(declare (type float x))
(multiple-value-bind (e string)
(if fdigits
(flonum-to-digits x (min (- (+ fdigits (or scale 0)))
(- (or fmin 0))))
(if (and width (> width 1))
(let ((w (multiple-value-list
(flonum-to-digits x
(max 1
(+ (1- width)
(if (and scale (minusp scale))
scale 0)))
t)))
(f (multiple-value-list
(flonum-to-digits x (- (+ (or fmin 0)
(if scale scale 0)))))))
(cond
((>= (length (cadr w)) (length (cadr f)))
(values-list w))
(t (values-list f))))
(flonum-to-digits x)))
(let ((e (if (zerop x)
e
(+ e (or scale 0))))
(stream (make-string-output-stream)))
(if (plusp e)
(progn
(write-string string stream :end (min (length string) e))
(dotimes (i (- e (length string)))
(write-char #\0 stream))
(write-char #\. stream)
(write-string string stream :start (min (length string) e))
(when fdigits
(dotimes (i (- fdigits
(- (length string)
(min (length string) e))))
(write-char #\0 stream))))
(progn
(write-string "." stream)
(dotimes (i (- e))
(write-char #\0 stream))
(write-string string stream :end (when fdigits
(min (length string)
(max (or fmin 0)
(+ fdigits e)))))
(when fdigits
(dotimes (i (+ fdigits e (- (length string))))
(write-char #\0 stream)))))
(let ((string (get-output-stream-string stream)))
(values string (length string)
(char= (char string 0) #\.)
(char= (char string (1- (length string))) #\.)
(position #\. string))))))
implementation of figure 1 from Burger and Dybvig , 1996 . It is
As the implementation of the Dragon from Classic CMUCL ( and
previously in SBCL above FLONUM - TO - STRING ) says : " DO NOT EVEN
FIXME : figure 1 from Burger and Dybvig is the unoptimized
algorithm , noticeably slow at finding the exponent . Figure 2 has
an improved algorithm , but CSR ran out of energy .
other than base 10 .
(defconstant single-float-min-e
(- 2 sb-vm:single-float-bias sb-vm:single-float-digits))
(defconstant double-float-min-e
(- 2 sb-vm:double-float-bias sb-vm:double-float-digits))
#+long-float
(defconstant long-float-min-e
(nth-value 1 (decode-float least-positive-long-float)))
PROLOGUE - FUN and EPILOGUE - FUN are called with the exponent before
(declaim (inline %flonum-to-digits))
(defun %flonum-to-digits (char-fun
prologue-fun
epilogue-fun
float &optional position relativep)
(min-e
(etypecase float
(single-float single-float-min-e)
(double-float double-float-min-e)
#+long-float
(long-float long-float-min-e))))
(multiple-value-bind (f e) (integer-decode-float float)
(when (< (float-precision float) float-digits)
(let ((shift (- float-digits (integer-length f))))
(setq f (ash f shift)
e (- e shift))))
FIXME : these even tests assume normal IEEE rounding
(high-ok (evenp f))
(low-ok (evenp f)))
(labels ((scale (r s m+ m-)
(do ((r+m+ (+ r m+))
(k 0 (1+ k))
(s s (* s print-base)))
((not (or (> r+m+ s)
(and high-ok (= r+m+ s))))
(do ((k k (1- k))
(r r (* r print-base))
(m+ m+ (* m+ print-base))
(m- m- (* m- print-base)))
Extension to handle zero
(let ((x (* (+ r m+) print-base)))
(or (< x s)
(and (not high-ok)
(= x s))))))
(funcall prologue-fun k)
(generate r s m+ m-)
(funcall epilogue-fun k))))))
(generate (r s m+ m-)
(let (d tc1 tc2)
(tagbody
loop
(setf (values d r) (truncate (* r print-base) s))
(setf m+ (* m+ print-base))
(setf m- (* m- print-base))
(setf tc1 (or (< r m-) (and low-ok (= r m-))))
(setf tc2 (let ((r+m+ (+ r m+)))
(or (> r+m+ s)
(and high-ok (= r+m+ s)))))
(when (or tc1 tc2)
(go end))
(funcall char-fun d)
(go loop)
end
(let ((d (cond
((and (not tc1) tc2) (1+ d))
((and tc1 (not tc2)) d)
((< (* r 2) s)
d)
(t
(1+ d)))))
(funcall char-fun d)))))
(initialize ()
(let (r s m+ m-)
(cond ((>= e 0)
(let ((be (expt float-radix e)))
(if (/= f (expt float-radix (1- float-digits)))
multiply F by 2 first , two bignums
(setf r (* f 2 be)
s 2
m+ be
m- be)
(setf m- be
m+ (* be float-radix)
r (* f 2 m+)
s (* float-radix 2)))))
((or (= e min-e)
(/= f (expt float-radix (1- float-digits))))
(setf r (* f 2)
s (expt float-radix (- 1 e))
m+ 1
m- 1))
(t
(setf r (* f float-radix 2)
s (expt float-radix (- 2 e))
m+ float-radix
m- 1)))
(when position
(when relativep
(aver (> position 0))
(do ((k 0 (1+ k))
(l 1 (* l print-base)))
((>= (* s l) (+ r m+))
k is now }
(if (< (+ r (* s (/ (expt print-base (- k position)) 2)))
(* s l))
(setf position (- k position))
(setf position (- k position 1))))))
(let* ((x (/ (* s (expt print-base position)) 2))
(low (max m- x))
(high (max m+ x)))
(when (<= m- low)
(setf m- low)
(setf low-ok t))
(when (<= m+ high)
(setf m+ high)
(setf high-ok t))))
(values r s m+ m-))))
(multiple-value-bind (r s m+ m-) (initialize)
(scale r s m+ m-)))))))
(defun flonum-to-digits (float &optional position relativep)
(let ((digit-characters "0123456789"))
(with-push-char (:element-type base-char)
(%flonum-to-digits
(lambda (d)
(push-char (char digit-characters d)))
(lambda (k) k)
(lambda (k) (values k (get-pushed-string)))
float position relativep))))
(defun print-float (float stream)
(let ((position 0)
(dot-position 0)
(digit-characters "0123456789")
(e-min -3)
(e-max 8))
(%flonum-to-digits
(lambda (d)
(when (= position dot-position)
(write-char #\. stream))
(write-char (char digit-characters d) stream)
(incf position))
(lambda (k)
(cond ((not (< e-min k e-max))
(setf dot-position 1))
((plusp k)
(setf dot-position k))
(t
(setf dot-position -1)
(write-char #\0 stream)
(write-char #\. stream)
(loop for i below (- k)
do (write-char #\0 stream)))))
(lambda (k)
(when (<= position dot-position)
(loop for i below (- dot-position position)
do (write-char #\0 stream))
(write-char #\. stream)
(write-char #\0 stream))
(if (< e-min k e-max)
(print-float-exponent float 0 stream)
(print-float-exponent float (1- k) stream)))
float)))
Given a non - negative floating point number , SCALE - EXPONENT returns
a new floating point number Z in the range ( 0.1 , 1.0 ] and an
exponent E such that Z * 10^E is ( approximately ) equal to the
(eval-when (:compile-toplevel :execute)
(setf *read-default-float-format*
#+long-float 'cl:long-float #-long-float 'cl:double-float))
(defun scale-exponent (original-x)
(let* ((x (coerce original-x 'long-float)))
(multiple-value-bind (sig exponent) (decode-float x)
(declare (ignore sig))
(if (= x $0.0e0)
(values (float $0.0e0 original-x) 1)
(let* ((ex (locally (declare (optimize (safety 0)))
(the fixnum
(round (* exponent
to ( log 2 10 ) , but expressed so
arithmetic . ( FIXME : it turns
out that sbcl itself is off by 1
#-long-float
(make-double-float 1070810131 1352628735)
#+long-float
(error "(log 2 10) not computed"))))))
(x (if (minusp ex)
(if (float-denormalized-p x)
#-long-float
(* x $1.0e16 (expt $10.0e0 (- (- ex) 16)))
#+long-float
(* x $1.0e18 (expt $10.0e0 (- (- ex) 18)))
(* x $10.0e0 (expt $10.0e0 (- (- ex) 1))))
(/ x $10.0e0 (expt $10.0e0 (1- ex))))))
(do ((d $10.0e0 (* d $10.0e0))
(y x (/ x d))
(ex ex (1+ ex)))
((< y $1.0e0)
(do ((m $10.0e0 (* m $10.0e0))
(z y (* y m))
(ex ex (1- ex)))
((>= z $0.1e0)
(values (float z original-x) ex))
(declare (long-float m) (integer ex))))
(declare (long-float d))))))))
(eval-when (:compile-toplevel :execute)
(setf *read-default-float-format* 'cl:single-float))
the float printer as called by PRINT , PRIN1 , PRINC , etc . The
Steele and White paper .
NOTE II : this has been bypassed slightly by implementing Burger
and Dybvig , 1996 . When someone has time ( ) they can
probably ( a ) implement the optimizations suggested by Burger and
Dyvbig , and ( b ) remove all vestiges of Dragon4 , including from
(defun print-float-exponent (x exp stream)
(declare (type float x) (type integer exp) (type stream stream))
(cond ((case *read-default-float-format*
((short-float single-float)
(typep x 'single-float))
((double-float #-long-float long-float)
(typep x 'double-float))
#+long-float
(long-float
(typep x 'long-float)))
(unless (eql exp 0)
(write-char #\e stream)
(%output-integer-in-base exp 10 stream)))
(t
(write-char
(etypecase x
(single-float #\f)
(double-float #\d)
(short-float #\s)
(long-float #\L))
stream)
(%output-integer-in-base exp 10 stream))))
(defmethod print-object ((x float) stream)
(cond
((float-infinity-or-nan-p x)
(if (float-infinity-p x)
(let ((symbol (etypecase x
(single-float (if (minusp x)
'single-float-negative-infinity
'single-float-positive-infinity))
(double-float (if (minusp x)
'double-float-negative-infinity
'double-float-positive-infinity)))))
(cond (*read-eval*
(write-string "#." stream)
(output-symbol symbol (sb-xc:symbol-package symbol) stream))
(t
(print-unreadable-object (x stream)
(output-symbol symbol (sb-xc:symbol-package symbol) stream)))))
(print-unreadable-object (x stream)
(princ (float-format-name x) stream)
(write-string (if (float-trapping-nan-p x) " trapping" " quiet") stream)
(write-string " NaN" stream))))
(t
(let ((x (cond ((minusp (float-sign x))
(write-char #\- stream)
(- x))
(t
x))))
(cond
((zerop x)
(write-string "0.0" stream)
(print-float-exponent x 0 stream))
(t
(print-float x stream)))))))
the character name or the character in the # \char format .
(defmethod print-object ((char character) stream)
(if (or *print-escape* *print-readably*)
(let ((graphicp (and (graphic-char-p char)
(standard-char-p char)))
(name (char-name char)))
(write-string "#\\" stream)
(if (and name (or (not graphicp) *print-readably*))
(quote-string name stream)
(write-char char stream)))
(write-char char stream)))
(defmethod print-object ((sap system-area-pointer) stream)
(cond (*read-eval*
(format stream "#.(~S #X~8,'0X)" 'int-sap (sap-int sap)))
(t
(print-unreadable-object (sap stream)
(format stream "system area pointer: #X~8,'0X" (sap-int sap))))))
(defmethod print-object ((weak-pointer weak-pointer) stream)
(print-unreadable-object (weak-pointer stream)
(multiple-value-bind (value validp) (weak-pointer-value weak-pointer)
(cond (validp
(write-string "weak pointer: " stream)
(write value :stream stream))
(t
(write-string "broken weak pointer" stream))))))
(defmethod print-object ((component code-component) stream)
(print-unreadable-object (component stream :identity t)
(let (dinfo)
(cond ((eq (setq dinfo (%code-debug-info component)) :bpt-lra)
(write-string "bpt-trap-return" stream))
((functionp dinfo)
(format stream "trampoline ~S" dinfo))
(t
(format stream "code~@[ id=~x~] [~D]"
(%code-serialno component)
(code-n-entries component))
(let ((fun-name (awhen (%code-entry-point component 0)
(%simple-fun-name it))))
(when fun-name
(write-char #\Space stream)
(write fun-name :stream stream))
(cond ((not (typep dinfo 'sb-c::debug-info)))
((neq (sb-c::debug-info-name dinfo) fun-name)
(write-string ", " stream)
(output-object (sb-c::debug-info-name dinfo) stream)))))))))
#-(or x86 x86-64 arm64 riscv)
(defmethod print-object ((lra lra) stream)
(print-unreadable-object (lra stream :identity t)
(write-string "return PC object" stream)))
(defmethod print-object ((fdefn fdefn) stream)
(print-unreadable-object (fdefn stream :type t)
and disassembler , be maximally helpful by neither abbreviating ( SETF ... )
(prin1 (fdefn-name fdefn) stream))))
#+sb-simd-pack
(defmethod print-object ((pack simd-pack) stream)
(cond ((and *print-readably* *read-eval*)
(format stream "#.(~S #b~3,'0b #x~16,'0X #x~16,'0X)"
'%make-simd-pack
(%simd-pack-tag pack)
(%simd-pack-low pack)
(%simd-pack-high pack)))
(*print-readably*
(print-not-readable-error pack stream))
(t
(print-unreadable-object (pack stream)
(etypecase pack
((simd-pack double-float)
(multiple-value-call #'format stream "~S~@{ ~,13E~}" 'simd-pack
(%simd-pack-doubles pack)))
((simd-pack single-float)
(multiple-value-call #'format stream "~S~@{ ~,7E~}" 'simd-pack
(%simd-pack-singles pack)))
((simd-pack (unsigned-byte 8))
(multiple-value-call #'format stream "~S~@{ ~3D~}" 'simd-pack
(%simd-pack-ub8s pack)))
((simd-pack (unsigned-byte 16))
(multiple-value-call #'format stream "~S~@{ ~5D~}" 'simd-pack
(%simd-pack-ub16s pack)))
((simd-pack (unsigned-byte 32))
(multiple-value-call #'format stream "~S~@{ ~10D~}" 'simd-pack
(%simd-pack-ub32s pack)))
((simd-pack (unsigned-byte 64))
(multiple-value-call #'format stream "~S~@{ ~20D~}" 'simd-pack
(%simd-pack-ub64s pack)))
((simd-pack (signed-byte 8))
(multiple-value-call #'format stream "~S~@{ ~4,@D~}" 'simd-pack
(%simd-pack-sb8s pack)))
((simd-pack (signed-byte 16))
(multiple-value-call #'format stream "~S~@{ ~6,@D~}" 'simd-pack
(%simd-pack-sb16s pack)))
((simd-pack (signed-byte 32))
(multiple-value-call #'format stream "~S~@{ ~11@D~}" 'simd-pack
(%simd-pack-sb32s pack)))
((simd-pack (signed-byte 64))
(multiple-value-call #'format stream "~S~@{ ~20@D~}" 'simd-pack
(%simd-pack-sb64s pack))))))))
#+sb-simd-pack-256
(defmethod print-object ((pack simd-pack-256) stream)
(cond ((and *print-readably* *read-eval*)
(format stream "#.(~S #b~3,'0B #x~16,'0D #x~16,'0D #x~16,'0D #x~16,'0D)"
'%make-simd-pack-256
(%simd-pack-256-tag pack)
(%simd-pack-256-0 pack)
(%simd-pack-256-1 pack)
(%simd-pack-256-2 pack)
(%simd-pack-256-3 pack)))
(*print-readably*
(print-not-readable-error pack stream))
(t
(print-unreadable-object (pack stream)
(etypecase pack
((simd-pack-256 double-float)
(multiple-value-call #'format stream "~S~@{ ~,13E~}" 'simd-pack-256
(%simd-pack-256-doubles pack)))
((simd-pack-256 single-float)
(multiple-value-call #'format stream "~S~@{ ~,7E~}" 'simd-pack-256
(%simd-pack-256-singles pack)))
((simd-pack-256 (unsigned-byte 8))
(multiple-value-call #'format stream "~S~@{ ~3D~}" 'simd-pack-256
(%simd-pack-256-ub8s pack)))
((simd-pack-256 (unsigned-byte 16))
(multiple-value-call #'format stream "~S~@{ ~5D~}" 'simd-pack-256
(%simd-pack-256-ub16s pack)))
((simd-pack-256 (unsigned-byte 32))
(multiple-value-call #'format stream "~S~@{ ~10D~}" 'simd-pack-256
(%simd-pack-256-ub32s pack)))
((simd-pack-256 (unsigned-byte 64))
(multiple-value-call #'format stream "~S~@{ ~20D~}" 'simd-pack-256
(%simd-pack-256-ub64s pack)))
((simd-pack-256 (signed-byte 8))
(multiple-value-call #'format stream "~S~@{ ~4@D~}" 'simd-pack-256
(%simd-pack-256-sb8s pack)))
((simd-pack-256 (signed-byte 16))
(multiple-value-call #'format stream "~S~@{ ~6@D~}" 'simd-pack-256
(%simd-pack-256-sb16s pack)))
((simd-pack-256 (signed-byte 32))
(multiple-value-call #'format stream "~S~@{ ~11@D~}" 'simd-pack-256
(%simd-pack-256-sb32s pack)))
((simd-pack-256 (signed-byte 64))
(multiple-value-call #'format stream "~S~@{ ~20@D~}" 'simd-pack-256
(%simd-pack-256-sb64s pack))))))))
(defmethod print-object ((object function) stream)
(macrolet ((unprintable-instance-p (x)
Guard against calling % FUN - FUN if it would return 0 .
(let ((s (sb-vm::primitive-object-slot
(sb-vm:primitive-object 'funcallable-instance)
'function)))
`(and (funcallable-instance-p ,x)
(eql 0 (%primitive sb-alien:slot ,x 'function ,(sb-vm:slot-offset s)
,sb-vm:fun-pointer-lowtag))))))
(when (unprintable-instance-p object)
(return-from print-object
(print-unreadable-object (object stream :type t :identity t)))))
(let* ((name (%fun-name object))
(proper-name-p (and (legal-fun-name-p name) (fboundp name)
(eq (fdefinition name) object))))
(print-unreadable-object (object stream :identity (not proper-name-p))
(format stream "~A~@[ ~S~]"
(if (funcallable-instance-p object) (type-of object) 'function)
name))))
(defmethod print-object ((object t) stream)
(when (eq object sb-pcl:+slot-unbound+)
(print-unreadable-object (object stream) (write-string "unbound" stream))
(return-from print-object))
NO - TLS - VALUE was added here as a printable object type for # + ubsan which ,
Git rev 22d8038118 caused uninitialized SIMPLE - VECTORs to get prefilled
with NO_TLS_VALUE_MARKER , but a better choice would be
#+ubsan
(when (eql (get-lisp-obj-address object) unwritten-vector-element-marker)
(print-unreadable-object (object stream) (write-string "novalue" stream))
(return-from print-object))
(print-unreadable-object (object stream :identity t)
(let ((lowtag (lowtag-of object)))
(case lowtag
(#.sb-vm:other-pointer-lowtag
(let ((widetag (widetag-of object)))
(case widetag
(#.sb-vm:value-cell-widetag
(write-string "value cell " stream)
(output-object (value-cell-ref object) stream))
#+nil
(#.sb-vm:filler-widetag
(write-string "pad " stream)
(write (1+ (get-header-data object)) :stream stream)
(t
(write-string "unknown pointer object, widetag=" stream)
(output-integer widetag stream 16 t)))))
((#.sb-vm:fun-pointer-lowtag
#.sb-vm:instance-pointer-lowtag
#.sb-vm:list-pointer-lowtag)
(write-string "unknown pointer object, lowtag=" stream)
(output-integer lowtag stream 16 t))
(t
(case (widetag-of object)
(#.sb-vm:unbound-marker-widetag
(write-string "unbound marker" stream))
(t
(write-string "unknown immediate object, lowtag=" stream)
(output-integer lowtag stream 2 t)
(write-string ", widetag=" stream)
(output-integer (widetag-of object) stream 16 t))))))))
|
fde6baee80dc402918f87e3680693b0410a391343cbae3892e61e2a40796a557 | xapi-project/message-switch | storage_skeleton_test.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
(* if this type-checks then the storage_skeleton is complete *)
module Test = Storage_interface.Server (Storage_skeleton)
| null | https://raw.githubusercontent.com/xapi-project/message-switch/1d0d1aa45c01eba144ac2826d0d88bb663e33101/xapi-idl/storage/storage_skeleton_test.ml | ocaml | if this type-checks then the storage_skeleton is complete |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
module Test = Storage_interface.Server (Storage_skeleton)
|
6b4d2369f3b642fee262108830d9fd6b30d11d56af85bcb02038c3cdfc55cea2 | crategus/cl-cffi-gtk | rtest-gtk-builder.lisp | (def-suite gtk-builder :in gtk-suite)
(in-suite gtk-builder)
(defvar *menus*
"<interface>
<menu id='app-menu'>
<section>
<item>
<attribute name='label' translatable='yes'>_New Window</attribute>
<attribute name='action'>app.new</attribute>
<attribute name='accel'><Primary>n</attribute>
</item>
</section>
<section>
<item>
<attribute name='label' translatable='yes'>_About Bloatpad</attribute>
<attribute name='action'>app.about</attribute>
</item>
</section>
<section>
<item>
<attribute name='label' translatable='yes'>_Quit</attribute>
<attribute name='action'>app.quit</attribute>
<attribute name='accel'><Primary>q</attribute>
</item>
</section>
</menu>
<menu id='menubar'>
<submenu>
<attribute name='label' translatable='yes'>_Edit</attribute>
<section>
<item>
<attribute name='label' translatable='yes'>_Copy</attribute>
<attribute name='action'>win.copy</attribute>
<attribute name='accel'><Primary>c</attribute>
</item>
<item>
<attribute name='label' translatable='yes'>_Paste</attribute>
<attribute name='action'>win.paste</attribute>
<attribute name='accel'><Primary>v</attribute>
</item>
</section>
</submenu>
<submenu>
<attribute name='label' translatable='yes'>_View</attribute>
<section>
<item>
<attribute name='label' translatable='yes'>_Fullscreen</attribute>
<attribute name='action'>win.fullscreen</attribute>
<attribute name='accel'>F11</attribute>
</item>
</section>
</submenu>
</menu>
</interface>")
(defvar *dialog*
"<interface>
<object class='GtkDialog' id='dialog1'>
<child internal-child='vbox'>
<object class='GtkVBox' id='vbox1'>
<property name='border-width'>10</property>
<child internal-child='action_area'>
<object class='GtkHButtonBox' id='hbuttonbox1'>
<property name='border-width'>20</property>
<child>
<object class='GtkButton' id='ok_button'>
<property name='label'>gtk-ok</property>
<property name='use-stock'>TRUE</property>
<signal name='clicked' handler='ok_button_clicked'/>
</object>
</child>
</object>
</child>
</object>
</child>
</object>
</interface>")
;;; --- Types and Values -------------------------------------------------------
;;; GtkBuilderError
GtkBuilder
(test gtk-builder-class
;; Type check
(is (g-type-is-object "GtkBuilder"))
;; Check the registered name
(is (eq 'gtk-builder
(registered-object-type-by-name "GtkBuilder")))
;; Check the type initializer
(is (eq (gtype "GtkBuilder")
(gtype (foreign-funcall "gtk_builder_get_type" g-size))))
;; Check the parent
(is (eq (gtype "GObject") (g-type-parent "GtkBuilder")))
;; Check the children
(is (equal '()
(mapcar #'g-type-name (g-type-children "GtkBuilder"))))
;; Check the interfaces
(is (equal '()
(mapcar #'g-type-name (g-type-interfaces "GtkBuilder"))))
;; Check the class properties
(is (equal '("translation-domain")
(list-class-property-names "GtkBuilder")))
;; Check the class definition
(is (equal '(DEFINE-G-OBJECT-CLASS "GtkBuilder" GTK-BUILDER
(:SUPERCLASS G-OBJECT :EXPORT T :INTERFACES NIL
:TYPE-INITIALIZER "gtk_builder_get_type")
((TRANSLATION-DOMAIN GTK-BUILDER-TRANSLATION-DOMAIN
"translation-domain" "gchararray" T T)))
(get-g-type-definition "GtkBuilder"))))
;;; --- Properties ------------------------------------------------------------
(test gtk-builder-properties
(let ((builder (make-instance 'gtk-builder :from-string *dialog*)))
(is-false (gtk-builder-translation-domain builder))))
;;; --- gtk-builder-new --------------------------------------------------------
(test gtk-builder-new
;; gtk-builder-new is implemented with make-instance
(is (typep (gtk-builder-new) 'gtk-builder))
;; Check Lisp extension for initializing gtk-builder
(let ((builder (make-instance 'gtk-builder :from-string *dialog*)))
(is (typep (gtk-builder-object builder "dialog1") 'gtk-dialog)))
(let ((builder (make-instance 'gtk-builder
:from-file "rtest-application.ui")))
(is (typep (gtk-builder-object builder "menubar") 'g-menu))))
;;; --- gtk-builder-new-from-file ----------------------------------------------
(test gtk-builder-new-from-file
(is (typep (gtk-builder-new-from-file "rtest-application.ui") 'gtk-builder)))
;;; gtk_builder_new_from_resource
(test gtk-builder-new-from-resource
(let ((resource (g-resource-load "rtest-gio-resource.gresource")))
(is-false (g-resources-register resource))
(is (typep (gtk-builder-new-from-resource "/com/crategus/test/rtest-dialog.ui")
'gtk-builder))
(is-false (g-resources-unregister resource))))
;;; --- gtk-builder-new-from-string --------------------------------------------
(test gtk-builder-new-from-string
(is (typep (gtk-builder-new-from-string *menus*) 'gtk-builder)))
;;; gtk_builder_add_callback_symbol
;;; gtk_builder_add_callback_symbols
;;; gtk_builder_lookup_callback_symbol
;;; --- gtk-builder-add-from-file ----------------------------------------------
(test gtk-builder-add-from-file
(let ((builder (gtk-builder-new)))
(is-true (gtk-builder-add-from-file builder "rtest-application.ui"))))
gtk_builder_add_from_resource
(test gtk-builder-add-from-resource
(let ((resource (g-resource-load "rtest-gio-resource.gresource"))
(builder (gtk-builder-new)))
(is-false (g-resources-register resource))
(is-true (gtk-builder-add-from-resource builder
"/com/crategus/test/rtest-dialog.ui"))
(is-false (g-resources-unregister resource))))
;;; --- gtk-builder-add-from-string --------------------------------------------
(test gtk-builder-add-from-string
(let ((builder (gtk-builder-new)))
(is-true (gtk-builder-add-from-string builder *menus*))))
;;; --- gtk-builder-add-objects-from-file --------------------------------------
(test gtk-builder-add-objects-from-file
(let ((builder (gtk-builder-new)))
(is-true (gtk-builder-add-objects-from-file builder
"rtest-dialog.ui" '("dialog1")))
(is (typep (gtk-builder-object builder "dialog1") 'gtk-dialog))
(is (equal '(GTK-DIALOG GTK-BOX GTK-BUTTON-BOX GTK-BUTTON)
(mapcar 'type-of (gtk-builder-objects builder))))))
;;; --- gtk-builder-add-objects-from-string ------------------------------------
(test gtk-builder-add-objects-from-string
(let ((builder (gtk-builder-new)))
(is-true (gtk-builder-add-objects-from-string builder *dialog* '("dialog1")))
(is (typep (gtk-builder-object builder "dialog1") 'gtk-dialog))
(is (equal '(GTK-DIALOG GTK-BOX GTK-BUTTON-BOX GTK-BUTTON)
(mapcar 'type-of (gtk-builder-objects builder))))))
;;; gtk_builder_add_objects_from_resource
;;; gtk_builder_extend_with_template
;;; --- gtk-builder-object -----------------------------------------------------
(test gtk-builder-object
(let ((builder (gtk-builder-new-from-string *dialog*)))
(is (typep (gtk-builder-object builder "dialog1") 'gtk-dialog))
(is (typep (gtk-builder-object builder "ok_button") 'gtk-button))))
;;; --- gtk-builder-objects ----------------------------------------------------
(test gtk-builder-objects
(let ((builder (gtk-builder-new)))
(is (typep builder 'gtk-builder))
(is (equal '() (gtk-builder-objects builder)))
(is-true (gtk-builder-add-from-string builder *menus*))
(is (equal '(g-menu g-menu)
(mapcar 'type-of (gtk-builder-objects builder))))
(is-true (gtk-builder-add-from-string builder *dialog*))
(is (equal '(GTK-DIALOG G-MENU G-MENU GTK-BOX GTK-BUTTON-BOX GTK-BUTTON)
(mapcar 'type-of (gtk-builder-objects builder))))))
;;; gtk_builder_expose_object
;;; gtk_builder_connect_signals
gtk_builder_connect_signals_full
;;; gtk_builder_get_type_from_name
;;; gtk_builder_value_from_string
gtk_builder_value_from_string_type
2021 - 10 - 21
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/7f5a09f78d8004a71efa82794265f2587fff98ab/test/rtest-gtk-builder.lisp | lisp | Primary>n</attribute>
Primary>q</attribute>
Primary>c</attribute>
Primary>v</attribute>
--- Types and Values -------------------------------------------------------
GtkBuilderError
Type check
Check the registered name
Check the type initializer
Check the parent
Check the children
Check the interfaces
Check the class properties
Check the class definition
--- Properties ------------------------------------------------------------
--- gtk-builder-new --------------------------------------------------------
gtk-builder-new is implemented with make-instance
Check Lisp extension for initializing gtk-builder
--- gtk-builder-new-from-file ----------------------------------------------
gtk_builder_new_from_resource
--- gtk-builder-new-from-string --------------------------------------------
gtk_builder_add_callback_symbol
gtk_builder_add_callback_symbols
gtk_builder_lookup_callback_symbol
--- gtk-builder-add-from-file ----------------------------------------------
--- gtk-builder-add-from-string --------------------------------------------
--- gtk-builder-add-objects-from-file --------------------------------------
--- gtk-builder-add-objects-from-string ------------------------------------
gtk_builder_add_objects_from_resource
gtk_builder_extend_with_template
--- gtk-builder-object -----------------------------------------------------
--- gtk-builder-objects ----------------------------------------------------
gtk_builder_expose_object
gtk_builder_connect_signals
gtk_builder_get_type_from_name
gtk_builder_value_from_string | (def-suite gtk-builder :in gtk-suite)
(in-suite gtk-builder)
(defvar *menus*
"<interface>
<menu id='app-menu'>
<section>
<item>
<attribute name='label' translatable='yes'>_New Window</attribute>
<attribute name='action'>app.new</attribute>
</item>
</section>
<section>
<item>
<attribute name='label' translatable='yes'>_About Bloatpad</attribute>
<attribute name='action'>app.about</attribute>
</item>
</section>
<section>
<item>
<attribute name='label' translatable='yes'>_Quit</attribute>
<attribute name='action'>app.quit</attribute>
</item>
</section>
</menu>
<menu id='menubar'>
<submenu>
<attribute name='label' translatable='yes'>_Edit</attribute>
<section>
<item>
<attribute name='label' translatable='yes'>_Copy</attribute>
<attribute name='action'>win.copy</attribute>
</item>
<item>
<attribute name='label' translatable='yes'>_Paste</attribute>
<attribute name='action'>win.paste</attribute>
</item>
</section>
</submenu>
<submenu>
<attribute name='label' translatable='yes'>_View</attribute>
<section>
<item>
<attribute name='label' translatable='yes'>_Fullscreen</attribute>
<attribute name='action'>win.fullscreen</attribute>
<attribute name='accel'>F11</attribute>
</item>
</section>
</submenu>
</menu>
</interface>")
(defvar *dialog*
"<interface>
<object class='GtkDialog' id='dialog1'>
<child internal-child='vbox'>
<object class='GtkVBox' id='vbox1'>
<property name='border-width'>10</property>
<child internal-child='action_area'>
<object class='GtkHButtonBox' id='hbuttonbox1'>
<property name='border-width'>20</property>
<child>
<object class='GtkButton' id='ok_button'>
<property name='label'>gtk-ok</property>
<property name='use-stock'>TRUE</property>
<signal name='clicked' handler='ok_button_clicked'/>
</object>
</child>
</object>
</child>
</object>
</child>
</object>
</interface>")
GtkBuilder
(test gtk-builder-class
(is (g-type-is-object "GtkBuilder"))
(is (eq 'gtk-builder
(registered-object-type-by-name "GtkBuilder")))
(is (eq (gtype "GtkBuilder")
(gtype (foreign-funcall "gtk_builder_get_type" g-size))))
(is (eq (gtype "GObject") (g-type-parent "GtkBuilder")))
(is (equal '()
(mapcar #'g-type-name (g-type-children "GtkBuilder"))))
(is (equal '()
(mapcar #'g-type-name (g-type-interfaces "GtkBuilder"))))
(is (equal '("translation-domain")
(list-class-property-names "GtkBuilder")))
(is (equal '(DEFINE-G-OBJECT-CLASS "GtkBuilder" GTK-BUILDER
(:SUPERCLASS G-OBJECT :EXPORT T :INTERFACES NIL
:TYPE-INITIALIZER "gtk_builder_get_type")
((TRANSLATION-DOMAIN GTK-BUILDER-TRANSLATION-DOMAIN
"translation-domain" "gchararray" T T)))
(get-g-type-definition "GtkBuilder"))))
(test gtk-builder-properties
(let ((builder (make-instance 'gtk-builder :from-string *dialog*)))
(is-false (gtk-builder-translation-domain builder))))
(test gtk-builder-new
(is (typep (gtk-builder-new) 'gtk-builder))
(let ((builder (make-instance 'gtk-builder :from-string *dialog*)))
(is (typep (gtk-builder-object builder "dialog1") 'gtk-dialog)))
(let ((builder (make-instance 'gtk-builder
:from-file "rtest-application.ui")))
(is (typep (gtk-builder-object builder "menubar") 'g-menu))))
(test gtk-builder-new-from-file
(is (typep (gtk-builder-new-from-file "rtest-application.ui") 'gtk-builder)))
(test gtk-builder-new-from-resource
(let ((resource (g-resource-load "rtest-gio-resource.gresource")))
(is-false (g-resources-register resource))
(is (typep (gtk-builder-new-from-resource "/com/crategus/test/rtest-dialog.ui")
'gtk-builder))
(is-false (g-resources-unregister resource))))
(test gtk-builder-new-from-string
(is (typep (gtk-builder-new-from-string *menus*) 'gtk-builder)))
(test gtk-builder-add-from-file
(let ((builder (gtk-builder-new)))
(is-true (gtk-builder-add-from-file builder "rtest-application.ui"))))
gtk_builder_add_from_resource
(test gtk-builder-add-from-resource
(let ((resource (g-resource-load "rtest-gio-resource.gresource"))
(builder (gtk-builder-new)))
(is-false (g-resources-register resource))
(is-true (gtk-builder-add-from-resource builder
"/com/crategus/test/rtest-dialog.ui"))
(is-false (g-resources-unregister resource))))
(test gtk-builder-add-from-string
(let ((builder (gtk-builder-new)))
(is-true (gtk-builder-add-from-string builder *menus*))))
(test gtk-builder-add-objects-from-file
(let ((builder (gtk-builder-new)))
(is-true (gtk-builder-add-objects-from-file builder
"rtest-dialog.ui" '("dialog1")))
(is (typep (gtk-builder-object builder "dialog1") 'gtk-dialog))
(is (equal '(GTK-DIALOG GTK-BOX GTK-BUTTON-BOX GTK-BUTTON)
(mapcar 'type-of (gtk-builder-objects builder))))))
(test gtk-builder-add-objects-from-string
(let ((builder (gtk-builder-new)))
(is-true (gtk-builder-add-objects-from-string builder *dialog* '("dialog1")))
(is (typep (gtk-builder-object builder "dialog1") 'gtk-dialog))
(is (equal '(GTK-DIALOG GTK-BOX GTK-BUTTON-BOX GTK-BUTTON)
(mapcar 'type-of (gtk-builder-objects builder))))))
(test gtk-builder-object
(let ((builder (gtk-builder-new-from-string *dialog*)))
(is (typep (gtk-builder-object builder "dialog1") 'gtk-dialog))
(is (typep (gtk-builder-object builder "ok_button") 'gtk-button))))
(test gtk-builder-objects
(let ((builder (gtk-builder-new)))
(is (typep builder 'gtk-builder))
(is (equal '() (gtk-builder-objects builder)))
(is-true (gtk-builder-add-from-string builder *menus*))
(is (equal '(g-menu g-menu)
(mapcar 'type-of (gtk-builder-objects builder))))
(is-true (gtk-builder-add-from-string builder *dialog*))
(is (equal '(GTK-DIALOG G-MENU G-MENU GTK-BOX GTK-BUTTON-BOX GTK-BUTTON)
(mapcar 'type-of (gtk-builder-objects builder))))))
gtk_builder_connect_signals_full
gtk_builder_value_from_string_type
2021 - 10 - 21
|
ddb982c07e783867a4922850cd690f2a8c16cdf5fcf8a0df792c34a28695f1bc | nandor/llir-ocaml | printlinear.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Pretty-printing of linearized machine code *)
open Format
open Mach
open Printmach
open Linear
let label ppf l =
Format.fprintf ppf "L%i" l
let instr ppf i =
begin match i.desc with
| Lend -> ()
| Lprologue ->
fprintf ppf "prologue"
| Lop (op, _) ->
begin match op with
| Ialloc _ | Icall_ind _ | Icall_imm _ | Iextcall _ ->
fprintf ppf "@[<1>{%a}@]@," regsetaddr i.live
| _ -> ()
end;
operation op i.arg ppf i.res
| Lreloadretaddr ->
fprintf ppf "reload retaddr"
| Lreturn ->
fprintf ppf "return %a" regs i.arg
| Llabel lbl ->
fprintf ppf "%a:" label lbl
| Lbranch lbl ->
fprintf ppf "goto %a" label lbl
| Lcondbranch(tst, _p, lbl) ->
fprintf ppf "if %a goto %a" (test tst) i.arg label lbl
| Lcondbranch3(lbl0, lbl1, lbl2) ->
fprintf ppf "switch3 %a" reg i.arg.(0);
let case n = function
| None -> ()
| Some lbl ->
fprintf ppf "@,case %i: goto %a" n label lbl in
case 0 lbl0; case 1 lbl1; case 2 lbl2;
fprintf ppf "@,endswitch"
| Lswitch lblv ->
fprintf ppf "switch %a" reg i.arg.(0);
for i = 0 to Array.length lblv - 1 do
fprintf ppf "case %i: goto %a" i label lblv.(i)
done;
fprintf ppf "@,endswitch"
| Lentertrap ->
fprintf ppf "enter trap"
| Ladjust_trap_depth { delta_traps } ->
fprintf ppf "adjust trap depth by %d traps" delta_traps
| Lpushtrap { lbl_handler; } ->
fprintf ppf "push trap %a" label lbl_handler
| Lpoptrap _ ->
fprintf ppf "pop trap"
| Lraise { kind } ->
fprintf ppf "%s %a" (Lambda.raise_kind kind) reg i.arg.(0)
end;
if not (Debuginfo.is_none i.dbg) && !Clflags.locations then
fprintf ppf " %s" (Debuginfo.to_string i.dbg)
let rec all_instr ppf i =
match i.desc with
| Lend -> ()
| _ -> fprintf ppf "%a@,%a" instr i all_instr i.next
let fundecl ppf f =
let dbg =
if Debuginfo.is_none f.fun_dbg || not !Clflags.locations then
""
else
" " ^ Debuginfo.to_string f.fun_dbg in
fprintf ppf "@[<v 2>%s:%s@,%a@]" f.fun_name dbg all_instr f.fun_body
| null | https://raw.githubusercontent.com/nandor/llir-ocaml/9c019f15c444e30c825b1673cbe827e0497868fe/asmcomp/printlinear.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.
************************************************************************
Pretty-printing of linearized machine code | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Format
open Mach
open Printmach
open Linear
let label ppf l =
Format.fprintf ppf "L%i" l
let instr ppf i =
begin match i.desc with
| Lend -> ()
| Lprologue ->
fprintf ppf "prologue"
| Lop (op, _) ->
begin match op with
| Ialloc _ | Icall_ind _ | Icall_imm _ | Iextcall _ ->
fprintf ppf "@[<1>{%a}@]@," regsetaddr i.live
| _ -> ()
end;
operation op i.arg ppf i.res
| Lreloadretaddr ->
fprintf ppf "reload retaddr"
| Lreturn ->
fprintf ppf "return %a" regs i.arg
| Llabel lbl ->
fprintf ppf "%a:" label lbl
| Lbranch lbl ->
fprintf ppf "goto %a" label lbl
| Lcondbranch(tst, _p, lbl) ->
fprintf ppf "if %a goto %a" (test tst) i.arg label lbl
| Lcondbranch3(lbl0, lbl1, lbl2) ->
fprintf ppf "switch3 %a" reg i.arg.(0);
let case n = function
| None -> ()
| Some lbl ->
fprintf ppf "@,case %i: goto %a" n label lbl in
case 0 lbl0; case 1 lbl1; case 2 lbl2;
fprintf ppf "@,endswitch"
| Lswitch lblv ->
fprintf ppf "switch %a" reg i.arg.(0);
for i = 0 to Array.length lblv - 1 do
fprintf ppf "case %i: goto %a" i label lblv.(i)
done;
fprintf ppf "@,endswitch"
| Lentertrap ->
fprintf ppf "enter trap"
| Ladjust_trap_depth { delta_traps } ->
fprintf ppf "adjust trap depth by %d traps" delta_traps
| Lpushtrap { lbl_handler; } ->
fprintf ppf "push trap %a" label lbl_handler
| Lpoptrap _ ->
fprintf ppf "pop trap"
| Lraise { kind } ->
fprintf ppf "%s %a" (Lambda.raise_kind kind) reg i.arg.(0)
end;
if not (Debuginfo.is_none i.dbg) && !Clflags.locations then
fprintf ppf " %s" (Debuginfo.to_string i.dbg)
let rec all_instr ppf i =
match i.desc with
| Lend -> ()
| _ -> fprintf ppf "%a@,%a" instr i all_instr i.next
let fundecl ppf f =
let dbg =
if Debuginfo.is_none f.fun_dbg || not !Clflags.locations then
""
else
" " ^ Debuginfo.to_string f.fun_dbg in
fprintf ppf "@[<v 2>%s:%s@,%a@]" f.fun_name dbg all_instr f.fun_body
|
f40c69b1b0dda1ab6511325bd4f782571d9335eadf4064b9b1f36d8a4a760f2c | clojure-interop/google-cloud-clients | CompletionStubSettings.clj | (ns com.google.cloud.talent.v4beta1.stub.CompletionStubSettings
"Settings class to configure an instance of CompletionStub.
The default instance has everything set to sensible defaults:
The default service address (jobs.googleapis.com) and default port (443) are used.
Credentials are acquired automatically through Application Default Credentials.
Retries are configured for idempotent methods but not for non-idempotent methods.
The builder of this class is recursive, so contained classes are themselves builders. When
build() is called, the tree of builders is called to create the complete settings object. For
example, to set the total timeout of completeQuery to 30 seconds:
CompletionStubSettings.Builder completionSettingsBuilder =
CompletionStubSettings.newBuilder();
completionSettingsBuilder.completeQuerySettings().getRetrySettings().toBuilder()
.setTotalTimeout(Duration.ofSeconds(30));
CompletionStubSettings completionSettings = completionSettingsBuilder.build();"
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1.stub CompletionStubSettings]))
(defn *default-executor-provider-builder
"Returns a builder for the default ExecutorProvider for this service.
returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`"
(^com.google.api.gax.core.InstantiatingExecutorProvider.Builder []
(CompletionStubSettings/defaultExecutorProviderBuilder )))
(defn *get-default-endpoint
"Returns the default service endpoint.
returns: `java.lang.String`"
(^java.lang.String []
(CompletionStubSettings/getDefaultEndpoint )))
(defn *get-default-service-scopes
"Returns the default service scopes.
returns: `java.util.List<java.lang.String>`"
(^java.util.List []
(CompletionStubSettings/getDefaultServiceScopes )))
(defn *default-credentials-provider-builder
"Returns a builder for the default credentials for this service.
returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`"
(^com.google.api.gax.core.GoogleCredentialsProvider.Builder []
(CompletionStubSettings/defaultCredentialsProviderBuilder )))
(defn *default-grpc-transport-provider-builder
"Returns a builder for the default ChannelProvider for this service.
returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`"
(^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder []
(CompletionStubSettings/defaultGrpcTransportProviderBuilder )))
(defn *default-transport-channel-provider
"returns: `com.google.api.gax.rpc.TransportChannelProvider`"
(^com.google.api.gax.rpc.TransportChannelProvider []
(CompletionStubSettings/defaultTransportChannelProvider )))
(defn *default-api-client-header-provider-builder
"returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`"
([]
(CompletionStubSettings/defaultApiClientHeaderProviderBuilder )))
(defn *new-builder
"Returns a new builder for this class.
client-context - `com.google.api.gax.rpc.ClientContext`
returns: `com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder`"
(^com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context]
(CompletionStubSettings/newBuilder client-context))
(^com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder []
(CompletionStubSettings/newBuilder )))
(defn complete-query-settings
"Returns the object with the settings used for calls to completeQuery.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.CompleteQueryRequest,com.google.cloud.talent.v4beta1.CompleteQueryResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^CompletionStubSettings this]
(-> this (.completeQuerySettings))))
(defn create-stub
"returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.talent.v4beta1.stub.CompletionStub`
throws: java.io.IOException"
([^CompletionStubSettings this]
(-> this (.createStub))))
(defn to-builder
"Returns a builder containing all the values of this settings class.
returns: `com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder`"
(^com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder [^CompletionStubSettings this]
(-> this (.toBuilder))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.talent/src/com/google/cloud/talent/v4beta1/stub/CompletionStubSettings.clj | clojure |
" | (ns com.google.cloud.talent.v4beta1.stub.CompletionStubSettings
"Settings class to configure an instance of CompletionStub.
The default instance has everything set to sensible defaults:
The default service address (jobs.googleapis.com) and default port (443) are used.
Credentials are acquired automatically through Application Default Credentials.
Retries are configured for idempotent methods but not for non-idempotent methods.
The builder of this class is recursive, so contained classes are themselves builders. When
build() is called, the tree of builders is called to create the complete settings object. For
example, to set the total timeout of completeQuery to 30 seconds:
CompletionStubSettings.Builder completionSettingsBuilder =
completionSettingsBuilder.completeQuerySettings().getRetrySettings().toBuilder()
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1.stub CompletionStubSettings]))
(defn *default-executor-provider-builder
"Returns a builder for the default ExecutorProvider for this service.
returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`"
(^com.google.api.gax.core.InstantiatingExecutorProvider.Builder []
(CompletionStubSettings/defaultExecutorProviderBuilder )))
(defn *get-default-endpoint
"Returns the default service endpoint.
returns: `java.lang.String`"
(^java.lang.String []
(CompletionStubSettings/getDefaultEndpoint )))
(defn *get-default-service-scopes
"Returns the default service scopes.
returns: `java.util.List<java.lang.String>`"
(^java.util.List []
(CompletionStubSettings/getDefaultServiceScopes )))
(defn *default-credentials-provider-builder
"Returns a builder for the default credentials for this service.
returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`"
(^com.google.api.gax.core.GoogleCredentialsProvider.Builder []
(CompletionStubSettings/defaultCredentialsProviderBuilder )))
(defn *default-grpc-transport-provider-builder
"Returns a builder for the default ChannelProvider for this service.
returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`"
(^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder []
(CompletionStubSettings/defaultGrpcTransportProviderBuilder )))
(defn *default-transport-channel-provider
"returns: `com.google.api.gax.rpc.TransportChannelProvider`"
(^com.google.api.gax.rpc.TransportChannelProvider []
(CompletionStubSettings/defaultTransportChannelProvider )))
(defn *default-api-client-header-provider-builder
"returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`"
([]
(CompletionStubSettings/defaultApiClientHeaderProviderBuilder )))
(defn *new-builder
"Returns a new builder for this class.
client-context - `com.google.api.gax.rpc.ClientContext`
returns: `com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder`"
(^com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context]
(CompletionStubSettings/newBuilder client-context))
(^com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder []
(CompletionStubSettings/newBuilder )))
(defn complete-query-settings
"Returns the object with the settings used for calls to completeQuery.
returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.talent.v4beta1.CompleteQueryRequest,com.google.cloud.talent.v4beta1.CompleteQueryResponse>`"
(^com.google.api.gax.rpc.UnaryCallSettings [^CompletionStubSettings this]
(-> this (.completeQuerySettings))))
(defn create-stub
"returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.talent.v4beta1.stub.CompletionStub`
throws: java.io.IOException"
([^CompletionStubSettings this]
(-> this (.createStub))))
(defn to-builder
"Returns a builder containing all the values of this settings class.
returns: `com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder`"
(^com.google.cloud.talent.v4beta1.stub.CompletionStubSettings$Builder [^CompletionStubSettings this]
(-> this (.toBuilder))))
|
374c11a3b6f73f53a38bcf7684d6df53be79916fa0306c0eab0319ff44cf1c22 | yminer/libml | visitable.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[ LibML - Machine Learning Library ]
Copyright ( C ) 2002 - 2003 LAGACHERIE
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 .
SPECIAL NOTE ( the beerware clause ):
This software is free software . However , it also falls under the beerware
special category . That is , if you find this software useful , or use it
every day , or want to grant us for our modest contribution to the
free software community , feel free to send us a beer from one of
your local brewery . Our preference goes to Belgium abbey beers and
irish stout ( Guiness for strength ! ) , but we like to try new stuffs .
Authors :
E - mail : RICORDEAU
E - mail :
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[LibML - Machine Learning Library]
Copyright (C) 2002 - 2003 LAGACHERIE Matthieu RICORDEAU Olivier
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.
SPECIAL NOTE (the beerware clause):
This software is free software. However, it also falls under the beerware
special category. That is, if you find this software useful, or use it
every day, or want to grant us for our modest contribution to the
free software community, feel free to send us a beer from one of
your local brewery. Our preference goes to Belgium abbey beers and
irish stout (Guiness for strength!), but we like to try new stuffs.
Authors:
Matthieu LAGACHERIE
E-mail :
Olivier RICORDEAU
E-mail :
****************************************************************)
*
The visitable abstract class .
Instances of classes which inherit from this class must implement methods
which enable them to accept a visitor ( i.e. an instance of a class which
inherit from the defaultVisitor class ) .
@author
@author
@since 12/06/2003
Instances of classes which inherit from this class must implement methods
which enable them to accept a visitor ( i.e. an instance of a class which
inherit from the defaultVisitor class ) .
The visitable abstract class.
Instances of classes which inherit from this class must implement methods
which enable them to accept a visitor (i.e. an instance of a class which
inherit from the defaultVisitor class).
@author Matthieu Lagacherie
@author Olivier Ricordeau
@since 12/06/2003
Instances of classes which inherit from this class must implement methods
which enable them to accept a visitor (i.e. an instance of a class which
inherit from the defaultVisitor class).
*)
open DefaultVisitor
(**
The visitable class.
*)
class virtual visitable =
object(this : 'a)
(**
The generic accept method.
*)
method accept (visitor : ('a) defaultVisitor) =
visitor#visit this
end
| null | https://raw.githubusercontent.com/yminer/libml/1475dd87c2c16983366fab62124e8bbfbbf2161b/src/common/visitable.ml | ocaml | *
The visitable class.
*
The generic accept method.
| * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[ LibML - Machine Learning Library ]
Copyright ( C ) 2002 - 2003 LAGACHERIE
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 .
SPECIAL NOTE ( the beerware clause ):
This software is free software . However , it also falls under the beerware
special category . That is , if you find this software useful , or use it
every day , or want to grant us for our modest contribution to the
free software community , feel free to send us a beer from one of
your local brewery . Our preference goes to Belgium abbey beers and
irish stout ( Guiness for strength ! ) , but we like to try new stuffs .
Authors :
E - mail : RICORDEAU
E - mail :
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[LibML - Machine Learning Library]
Copyright (C) 2002 - 2003 LAGACHERIE Matthieu RICORDEAU Olivier
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.
SPECIAL NOTE (the beerware clause):
This software is free software. However, it also falls under the beerware
special category. That is, if you find this software useful, or use it
every day, or want to grant us for our modest contribution to the
free software community, feel free to send us a beer from one of
your local brewery. Our preference goes to Belgium abbey beers and
irish stout (Guiness for strength!), but we like to try new stuffs.
Authors:
Matthieu LAGACHERIE
E-mail :
Olivier RICORDEAU
E-mail :
****************************************************************)
*
The visitable abstract class .
Instances of classes which inherit from this class must implement methods
which enable them to accept a visitor ( i.e. an instance of a class which
inherit from the defaultVisitor class ) .
@author
@author
@since 12/06/2003
Instances of classes which inherit from this class must implement methods
which enable them to accept a visitor ( i.e. an instance of a class which
inherit from the defaultVisitor class ) .
The visitable abstract class.
Instances of classes which inherit from this class must implement methods
which enable them to accept a visitor (i.e. an instance of a class which
inherit from the defaultVisitor class).
@author Matthieu Lagacherie
@author Olivier Ricordeau
@since 12/06/2003
Instances of classes which inherit from this class must implement methods
which enable them to accept a visitor (i.e. an instance of a class which
inherit from the defaultVisitor class).
*)
open DefaultVisitor
class virtual visitable =
object(this : 'a)
method accept (visitor : ('a) defaultVisitor) =
visitor#visit this
end
|
a3ab0ec8ad36bc6d6349ab32909950315b4b4cadc33c94cddd3672e70dbe5385 | gregtatcam/imaplet-lwt | smtp_client.ml |
* Copyright ( c ) 2013 - 2014 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2013-2014 Gregory Tsipenyuk <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Lwt
open Imaplet
open Commands
exception InvalidCommand of string
let opt_val = function
| None -> raise (InvalidCommand "no value")
| Some v -> v
let rec args i archive addr port ehlo from rcptto =
if i >= Array.length Sys.argv then
archive,addr,port,ehlo,from,rcptto
else
match Sys.argv.(i) with
| "-archive" -> args (i+2) (Some Sys.argv.(i+1)) addr port ehlo from rcptto
| "-address" -> args (i+2) archive (Some Sys.argv.(i+1)) port ehlo from rcptto
| "-port" -> args (i+2) archive addr (Some (int_of_string Sys.argv.(i+1))) ehlo from rcptto
| "-ehlo" -> args (i+1) archive addr port true from rcptto
| "-from" -> args (i+2) archive addr port ehlo (Some Sys.argv.(i+1)) rcptto
| "-rcptto" -> args (i+2) archive addr port ehlo from (Some Sys.argv.(i+1))
| _ -> raise (InvalidCommand Sys.argv.(i))
let usage () =
Printf.fprintf stderr "usage: smtp_client -archive [path] -address [address] \
-port [port] [-ehlo] [-from user@domain] [-rcptto user@domain]\n%!"
let commands f =
try
let archive,addr,port,ehlo,from,rcptto = args 1 None None None false None None in
f (opt_val archive) (opt_val addr) (opt_val port) ehlo (opt_val from) (opt_val rcptto)
with | InvalidCommand msg -> Printf.printf "%s\n%!" msg; usage ()
let post archive from rcpt f =
Utils.fold_email_with_file archive (fun cnt message ->
Printf.printf "%d\r%!" cnt;
let ic = Lwt_io.of_bytes ~mode:Lwt_io.Input (Lwt_bytes.of_string message) in
let feeder () =
Lwt_io.read_line_opt ic >>= function
(* escape single dot *)
| Some str -> if str = "." then return (Some "..") else return (Some str)
| None -> return None
in
( ) > > = fun _ - > ignore the from postmark
f ~from ~rcpt feeder >>= function
| `Ok -> Lwt_io.close ic >> return (`Ok (cnt+1))
| `Error err ->
Printf.printf "error %s\n%!" err;
Lwt_io.close ic >>
return (`Done (cnt))
) 1 >>= fun _ ->
return `Ok
let () =
commands (fun archive addr port ehlo from rcptto ->
Lwt_main.run (
catch(fun() ->
let t = Smtplet_clnt.create
~log:(fun level msg -> if level = `Error then Printf.printf "%s%!" msg else ())
addr port ehlo (post archive from rcptto) in
Smtplet_clnt.send_server t >>= fun _ ->
Printf.printf "done\n%!";
return ()
)
(fun ex -> Printf.fprintf stderr "client: fatal exception: %s %s"
(Printexc.to_string ex) (Printexc.get_backtrace()); return()
)
)
)
| null | https://raw.githubusercontent.com/gregtatcam/imaplet-lwt/d7b51253e79cffa97e98ab899ed833cd7cb44bb6/utils/smtp_client.ml | ocaml | escape single dot |
* Copyright ( c ) 2013 - 2014 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2013-2014 Gregory Tsipenyuk <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Lwt
open Imaplet
open Commands
exception InvalidCommand of string
let opt_val = function
| None -> raise (InvalidCommand "no value")
| Some v -> v
let rec args i archive addr port ehlo from rcptto =
if i >= Array.length Sys.argv then
archive,addr,port,ehlo,from,rcptto
else
match Sys.argv.(i) with
| "-archive" -> args (i+2) (Some Sys.argv.(i+1)) addr port ehlo from rcptto
| "-address" -> args (i+2) archive (Some Sys.argv.(i+1)) port ehlo from rcptto
| "-port" -> args (i+2) archive addr (Some (int_of_string Sys.argv.(i+1))) ehlo from rcptto
| "-ehlo" -> args (i+1) archive addr port true from rcptto
| "-from" -> args (i+2) archive addr port ehlo (Some Sys.argv.(i+1)) rcptto
| "-rcptto" -> args (i+2) archive addr port ehlo from (Some Sys.argv.(i+1))
| _ -> raise (InvalidCommand Sys.argv.(i))
let usage () =
Printf.fprintf stderr "usage: smtp_client -archive [path] -address [address] \
-port [port] [-ehlo] [-from user@domain] [-rcptto user@domain]\n%!"
let commands f =
try
let archive,addr,port,ehlo,from,rcptto = args 1 None None None false None None in
f (opt_val archive) (opt_val addr) (opt_val port) ehlo (opt_val from) (opt_val rcptto)
with | InvalidCommand msg -> Printf.printf "%s\n%!" msg; usage ()
let post archive from rcpt f =
Utils.fold_email_with_file archive (fun cnt message ->
Printf.printf "%d\r%!" cnt;
let ic = Lwt_io.of_bytes ~mode:Lwt_io.Input (Lwt_bytes.of_string message) in
let feeder () =
Lwt_io.read_line_opt ic >>= function
| Some str -> if str = "." then return (Some "..") else return (Some str)
| None -> return None
in
( ) > > = fun _ - > ignore the from postmark
f ~from ~rcpt feeder >>= function
| `Ok -> Lwt_io.close ic >> return (`Ok (cnt+1))
| `Error err ->
Printf.printf "error %s\n%!" err;
Lwt_io.close ic >>
return (`Done (cnt))
) 1 >>= fun _ ->
return `Ok
let () =
commands (fun archive addr port ehlo from rcptto ->
Lwt_main.run (
catch(fun() ->
let t = Smtplet_clnt.create
~log:(fun level msg -> if level = `Error then Printf.printf "%s%!" msg else ())
addr port ehlo (post archive from rcptto) in
Smtplet_clnt.send_server t >>= fun _ ->
Printf.printf "done\n%!";
return ()
)
(fun ex -> Printf.fprintf stderr "client: fatal exception: %s %s"
(Printexc.to_string ex) (Printexc.get_backtrace()); return()
)
)
)
|
c601157f6d468e8fd3050a5314a58aa2bb17e25b2950d2ca081aa0275f555bba | erlcloud/erlcloud | erlcloud_ddb_util.erl | -*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*-
@author >
%% @doc
Helpers for using DynamoDB from Erlang .
%%
%% This is a higher layer API that augments the operations supported
%% by erlcloud_ddb2. The functions in this file do not map directly to
%% DynamoDB operations. Instead they will perform multiple operations
%% in order to implement functionality that isn't available directly
using the DynamoDB API .
%%
%% @end
-module(erlcloud_ddb_util).
-include("erlcloud.hrl").
-include("erlcloud_ddb2.hrl").
-include("erlcloud_aws.hrl").
%%% DynamoDB Higher Layer API
-export([delete_all/2, delete_all/3, delete_all/4,
delete_hash_key/3, delete_hash_key/4, delete_hash_key/5,
get_all/2, get_all/3, get_all/4, get_all/5,
put_all/2, put_all/3, put_all/4,
list_tables_all/0, list_tables_all/1,
q_all/2, q_all/3, q_all/4,
scan_all/1, scan_all/2, scan_all/3,
wait_for_table_active/1, wait_for_table_active/2, wait_for_table_active/3, wait_for_table_active/4,
write_all/2, write_all/3, write_all/4
]).
-ifdef(TEST).
-export([set_out_opt/1]).
-endif.
-define(BATCH_WRITE_LIMIT, 25).
-define(BATCH_GET_LIMIT, 100).
-type typed_out() :: {typed_out, boolean()}.
-type batch_read_ddb_opt() :: typed_out() | erlcloud_ddb2:out_opt().
-type batch_read_ddb_opts() :: [batch_read_ddb_opt()].
-type conditions() :: erlcloud_ddb2:conditions().
-type ddb_opts() :: erlcloud_ddb2:ddb_opts().
-type expression() :: erlcloud_ddb2:expression().
-type hash_key() :: erlcloud_ddb2:in_attr().
-type in_item() :: erlcloud_ddb2:in_item().
-type key() :: erlcloud_ddb2:key().
-type out_item() :: erlcloud_ddb2:out_item().
-type range_key_name() :: erlcloud_ddb2:range_key_name().
-type table_name() :: erlcloud_ddb2:table_name().
-type items_return() :: {ok, [out_item()]}
| {ok, non_neg_integer()}
| {error, term()}.
-export_type(
[batch_read_ddb_opt/0,
batch_read_ddb_opts/0,
typed_out/0]).
default_config() -> erlcloud_aws:default_config().
%%%------------------------------------------------------------------------------
%%% delete_all
%%%------------------------------------------------------------------------------
-spec delete_all(table_name(), [key()]) -> ok | {error, term()}.
delete_all(Table, Keys) ->
delete_all(Table, Keys, [], default_config()).
-spec delete_all(table_name(), [key()], ddb_opts()) -> ok | {error, term()}.
delete_all(Table, Keys, Opts) ->
delete_all(Table, Keys, Opts, default_config()).
%%------------------------------------------------------------------------------
%% @doc
%%
Perform one or more BatchWriteItem operations to delete all items .
Operations are performed in parallel . Writing to only one table is supported .
%%
%% ===Example===
%%
%% `
%% ok =
%% erlcloud_ddb_util:delete_all(
%% [{<<"Forum">>,
[ { < < " Name " > > , { s , < < " Amazon DynamoDB " > > } } ,
{ < < " Name " > > , { s , < < " Amazon RDS " > > } } ,
{ < < " Name " > > , { s , < < " Amazon Redshift " > > } } ,
{ < < " Name " > > , { s , < < " Amazon ElastiCache " > > } }
%% ]}]),
%% '
%%
%% @end
%%------------------------------------------------------------------------------
-spec delete_all(table_name(), [key()], ddb_opts(), aws_config()) -> ok | {error, term()}.
delete_all(Table, Keys, Opts, Config) ->
write_all(Table, [{delete, Key} || Key <- Keys], Opts, Config).
%%%------------------------------------------------------------------------------
%%% delete_hash_key
%%%------------------------------------------------------------------------------
-spec delete_hash_key(table_name(), hash_key(), range_key_name()) -> ok | {error, term()}.
delete_hash_key(Table, HashKey, RangeKeyName) ->
delete_hash_key(Table, HashKey, RangeKeyName, [], default_config()).
-spec delete_hash_key(table_name(), hash_key(), range_key_name(), ddb_opts()) -> ok | {error, term()}.
delete_hash_key(Table, HashKey, RangeKeyName, Opts) ->
delete_hash_key(Table, HashKey, RangeKeyName, Opts, default_config()).
%%------------------------------------------------------------------------------
%% @doc
%%
%% Delete all items with the specified table. Table must be a
hash - and - range primary key table . Opts is currently ignored and is
%% provided for future enhancements. This method is not transacted.
%%
%% ===Example===
%%
%% `
%% ok = erlcloud_ddb_util:delete_hash_key(<<"tn">>, {<<"hash-key-name">>, <<"hash-key-value">>}, <<"range-key-name">>, [])),
%% '
%%
%% @end
%%------------------------------------------------------------------------------
-spec delete_hash_key(table_name(), hash_key(), range_key_name(), ddb_opts(), aws_config()) -> ok | {error, term()}.
delete_hash_key(Table, HashKey, RangeKeyName, Opts, Config) ->
case erlcloud_ddb2:q(Table, HashKey,
[{consistent_read, true},
{limit, ?BATCH_WRITE_LIMIT},
{attributes_to_get, [RangeKeyName]},
{out, typed_record}],
Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_q{count = 0}} ->
ok;
{ok, QResult} ->
case erlcloud_ddb2:batch_write_item(
[{Table, [{delete, [HashKey, RangeKey]} || [RangeKey] <- QResult#ddb2_q.items]}],
[{out, record}], Config) of
{error, Reason} ->
{error, Reason};
{ok, BatchResult} ->
if QResult#ddb2_q.last_evaluated_key == undefined andalso
BatchResult#ddb2_batch_write_item.unprocessed_items == [] ->
%% No more work to do
ok;
true ->
%% Some stuff was unprocessed - keep going
delete_hash_key(Table, HashKey, RangeKeyName, Opts, Config)
end
end
end.
%%%------------------------------------------------------------------------------
%%% get_all
%%%------------------------------------------------------------------------------
-type get_all_opts() :: erlcloud_ddb2:batch_get_item_request_item_opts().
-spec get_all(table_name(), [key()]) -> items_return().
get_all(Table, Keys) ->
get_all(Table, Keys, [], default_config()).
-spec get_all(table_name(), [key()], get_all_opts()) -> items_return().
get_all(Table, Keys, Opts) ->
get_all(Table, Keys, Opts, default_config()).
-spec get_all(table_name(), [key()], get_all_opts(), aws_config() | batch_read_ddb_opts()) -> items_return().
get_all(Table, Keys, Opts, Config) when is_record(Config, aws_config) ->
get_all(Table, Keys, Opts, [], Config);
get_all(Table, Keys, Opts, DdbOpts) ->
get_all(Table, Keys, Opts, DdbOpts, default_config()).
%%------------------------------------------------------------------------------
%% @doc
%%
Perform one or more BatchGetItem operations to get all matching
%% items. Operations are performed in parallel. Order may not be preserved.
Getting from only one table is supported .
%%
%% ===Example===
%%
%% `
%% {ok, Items} =
%% erlcloud_ddb_util:get_all(
%% <<"Forum">>,
[ { < < " Name " > > , { s , < < " Amazon DynamoDB " > > } } ,
{ < < " Name " > > , { s , < < " Amazon RDS " > > } } ,
{ < < " Name " > > , { s , < < " Amazon Redshift " > > } } ] ,
%% [{projection_expression, <<"Name, Threads, Messages, Views">>}],
%% [{typed_out, false}]),
%% '
%%
%% @end
%%------------------------------------------------------------------------------
-spec get_all(table_name(), [key()], get_all_opts(), batch_read_ddb_opts(), aws_config()) -> items_return().
get_all(Table, Keys, Opts, DdbOpts, Config) when length(Keys) =< ?BATCH_GET_LIMIT ->
batch_get_retry([{Table, Keys, Opts}], DdbOpts, Config, []);
get_all(Table, Keys, Opts, DdbOpts, Config) ->
BatchList = chop(?BATCH_GET_LIMIT, Keys),
Results = pmap_unordered(
fun(Batch) ->
%% try/catch to prevent hang forever if there is an exception
try
batch_get_retry([{Table, Batch, Opts}], DdbOpts, Config, [])
catch
Type:Ex ->
{error, {Type, Ex}}
end
end,
BatchList),
lists:foldl(fun parfold/2, {ok, []}, Results).
-spec batch_get_retry([erlcloud_ddb2:batch_get_item_request_item()], ddb_opts(), aws_config(), [out_item()]) -> items_return().
batch_get_retry(RequestItems, DdbOpts, Config, Acc) ->
case erlcloud_ddb2:batch_get_item(RequestItems, set_out_opt(DdbOpts), Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_batch_get_item{unprocessed_keys = [],
responses = [#ddb2_batch_get_item_response{items = Items}]}} ->
{ok, Items ++ Acc};
{ok, #ddb2_batch_get_item{unprocessed_keys = Unprocessed,
responses = [#ddb2_batch_get_item_response{items = Items}]}} ->
batch_get_retry(Unprocessed, DdbOpts, Config, Items ++ Acc)
end.
%%%------------------------------------------------------------------------------
%%% list_tables_all
%%%------------------------------------------------------------------------------
list_tables_all() ->
list_tables_all(default_config()).
-spec list_tables_all(aws_config()) -> {ok, [table_name()]} | {error, any()}.
list_tables_all(Config) ->
do_list_tables_all(undefined, Config, []).
do_list_tables_all(LastTable, Config, Result) ->
Options = [{exclusive_start_table_name, LastTable}, {out, record}],
case erlcloud_ddb2:list_tables(Options, Config) of
{ok, #ddb2_list_tables{table_names = TableNames, last_evaluated_table_name = undefined}} ->
{ok, flatreverse([TableNames, Result])};
{ok, #ddb2_list_tables{table_names = TableNames, last_evaluated_table_name = LastTableName}} ->
do_list_tables_all(LastTableName, Config, flatreverse([TableNames, Result]));
{error, _} = Error ->
Error
end.
%%%------------------------------------------------------------------------------
%%% put_all
%%%------------------------------------------------------------------------------
-spec put_all(table_name(), [in_item()]) -> ok | {error, term()}.
put_all(Table, Items) ->
put_all(Table, Items, [], default_config()).
-spec put_all(table_name(), [in_item()], ddb_opts()) -> ok | {error, term()}.
put_all(Table, Items, Opts) ->
put_all(Table, Items, Opts, default_config()).
%%------------------------------------------------------------------------------
%% @doc
%%
Perform one or more BatchWriteItem operations to put all items .
Operations are performed in parallel . Writing to only one table is supported .
%%
%% ===Example===
%%
%% `
%% ok =
%% erlcloud_ddb_util:put_all(
%% [{<<"Forum">>,
[ [ { < < " Name " > > , { s , < < " Amazon DynamoDB " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] ,
[ { < < " Name " > > , { s , < < " Amazon RDS " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] ,
[ { < < " Name " > > , { s , < < " Amazon Redshift " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] ,
[ { < < " Name " > > , { s , < < " Amazon ElastiCache " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ]
%% ]}]),
%% '
%%
%% @end
%%------------------------------------------------------------------------------
-spec put_all(table_name(), [in_item()], ddb_opts(), aws_config()) -> ok | {error, term()}.
put_all(Table, Items, Opts, Config) ->
write_all(Table, [{put, Item} || Item <- Items], Opts, Config).
%%%------------------------------------------------------------------------------
q_all
%%%------------------------------------------------------------------------------
-type q_all_opts() :: [erlcloud_ddb2:q_opt() | batch_read_ddb_opt()].
-spec q_all(table_name(), conditions() | expression()) -> items_return().
q_all(Table, KeyConditionsOrExpression) ->
q_all(Table, KeyConditionsOrExpression, [], default_config()).
-spec q_all(table_name(), conditions() | expression(), q_all_opts()) -> items_return().
q_all(Table, KeyConditionsOrExpression, Opts) ->
q_all(Table, KeyConditionsOrExpression, Opts, default_config()).
%%------------------------------------------------------------------------------
%% @doc
%%
Perform one or more Query operations to get all matching items .
%%
%% ===Example===
%%
%% `
%% {ok, Items} =
erlcloud_ddb_util : (
%% <<"Thread">>,
< < " ForumName = : n AND LastPostDateTime BETWEEN : t1 AND : t2 " > > ,
%% [{expression_attribute_values,
[ { < < " : n " > > , < < " Amazon DynamoDB " > > } ,
{ < < " : t1 " > > , < < " 20130101 " > > } ,
{ < < " : t2 " > > , < < " 20130115 " > > } ] } ,
%% {index_name, <<"LastPostIndex">>},
%% {select, all_attributes},
%% {consistent_read, true},
%% {typed_out, true}]),
%% '
%%
%% @end
%%------------------------------------------------------------------------------
-spec q_all(table_name(),
conditions() | expression(),
q_all_opts(),
aws_config()) -> items_return().
q_all(Table, KeyConditionsOrExpression, Opts, Config) ->
q_all(Table, KeyConditionsOrExpression, Opts, Config, [], undefined).
-spec q_all(table_name(),
conditions() | expression(),
q_all_opts(),
aws_config(),
[[out_item()]],
key() | undefined) -> items_return().
q_all(Table, KeyCondOrExpr, Opts0, Config, Acc, StartKey) ->
Opts = [{exclusive_start_key, StartKey}|set_out_opt(Opts0)],
case erlcloud_ddb2:q(Table, KeyCondOrExpr, Opts, Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_q{last_evaluated_key = undefined,
items = undefined,
count = Count}} ->
{ok, lists:sum([Count|Acc])};
{ok, #ddb2_q{last_evaluated_key = undefined,
items = Items}} ->
{ok, flatreverse([Items|Acc])};
{ok, #ddb2_q{last_evaluated_key = LastKey,
items = undefined,
count = Count}} ->
q_all(Table, KeyCondOrExpr, Opts0, Config, [Count|Acc], LastKey);
{ok, #ddb2_q{last_evaluated_key = LastKey,
items = Items}} ->
q_all(Table, KeyCondOrExpr, Opts0, Config, [Items|Acc], LastKey)
end.
%%%------------------------------------------------------------------------------
%%% scan_all
%%%------------------------------------------------------------------------------
-type scan_all_opts() :: [erlcloud_ddb2:scan_opt() | batch_read_ddb_opt()].
-spec scan_all(table_name()) -> items_return().
scan_all(Table) ->
scan_all(Table, [], default_config()).
-spec scan_all(table_name(), scan_all_opts()) -> items_return().
scan_all(Table, Opts) ->
scan_all(Table, Opts, default_config()).
%%------------------------------------------------------------------------------
%% @doc
%%
%% Perform one or more Scan operations to get all matching items.
%%
%% ===Example===
%%
%% `
%% {ok, Items} =
%% erlcloud_ddb_util:scan_all(
%% <<"Thread">>,
%% [{segment, 0},
{ total_segments , 4 } ,
%% {typed_out, true}]),
%% '
%%
%% @end
%%------------------------------------------------------------------------------
-spec scan_all(table_name(), scan_all_opts(), aws_config()) -> items_return().
scan_all(Table, Opts, Config) ->
scan_all(Table, Opts, Config, [], undefined).
-spec scan_all(table_name(),
scan_all_opts(),
aws_config(),
[[out_item()]],
key() | undefined) -> items_return().
scan_all(Table, Opts0, Config, Acc, StartKey) ->
Opts = [{exclusive_start_key, StartKey}|set_out_opt(Opts0)],
case erlcloud_ddb2:scan(Table, Opts, Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_scan{last_evaluated_key = undefined,
items = undefined,
count = Count}} ->
{ok, lists:sum([Count|Acc])};
{ok, #ddb2_scan{last_evaluated_key = undefined,
items = Items}} ->
{ok, flatreverse([Items|Acc])};
{ok, #ddb2_scan{last_evaluated_key = LastKey,
items = undefined,
count = Count}} ->
scan_all(Table, Opts0, Config, [Count|Acc], LastKey);
{ok, #ddb2_scan{last_evaluated_key = LastKey,
items = Items}} ->
scan_all(Table, Opts0, Config, [Items|Acc], LastKey)
end.
%%%------------------------------------------------------------------------------
%%% write_all
%%%------------------------------------------------------------------------------
-type write_all_item() :: erlcloud_ddb2:batch_write_item_request().
-spec write_all(table_name(), [write_all_item()]) -> ok | {error, term()}.
write_all(Table, Items) ->
write_all(Table, Items, [], default_config()).
-spec write_all(table_name(), [write_all_item()], ddb_opts()) -> ok | {error, term()}.
write_all(Table, Items, Opts) ->
write_all(Table, Items, Opts, default_config()).
%%------------------------------------------------------------------------------
%% @doc
%%
Perform one or more BatchWriteItem operations to put or delete all items .
Operations are performed in parallel . Writing to only one table is supported .
%%
%% ===Example===
%%
%% `
%% ok =
%% erlcloud_ddb_util:write_all(
%% [{<<"Forum">>,
[ { put , [ { < < " Name " > > , { s , < < " Amazon DynamoDB " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] } ,
{ put , [ { < < " Name " > > , { s , < < " Amazon RDS " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] } ,
{ put , [ { < < " Name " > > , { s , < < " Amazon Redshift " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] } ,
{ put , [ { < < " Name " > > , { s , < < " Amazon ElastiCache " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] }
%% ]}]),
%% '
%%
%% @end
%%------------------------------------------------------------------------------
-spec write_all(table_name(), [write_all_item()], ddb_opts(), aws_config()) -> ok | {error, term()}.
write_all(Table, Items, _Opts, Config) when length(Items) =< ?BATCH_WRITE_LIMIT ->
batch_write_retry([{Table, Items}], Config);
write_all(Table, Items, _Opts, Config) ->
BatchList = chop(?BATCH_WRITE_LIMIT, Items),
Results = pmap_unordered(
fun(Batch) ->
%% try/catch to prevent hang forever if there is an exception
try
batch_write_retry([{Table, Batch}], Config)
catch
Type:Ex ->
{error, {Type, Ex}}
end
end,
BatchList),
write_all_result(Results).
-spec batch_write_retry([erlcloud_ddb2:batch_write_item_request_item()], aws_config()) -> ok | {error, term()}.
batch_write_retry(RequestItems, Config) ->
case erlcloud_ddb2:batch_write_item(RequestItems, [{out, record}], Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_batch_write_item{unprocessed_items = []}} ->
ok;
{ok, #ddb2_batch_write_item{unprocessed_items = Unprocessed}} ->
batch_write_retry(Unprocessed, Config)
end.
%%------------------------------------------------------------------------------
%% @doc
%% wait until table_status==active.
%%
%% ===Example===
%%
%% `
erlcloud_ddb2 : wait_for_table_active(<<"TableName " > > , 3000 , 40 , Config )
%% '
%% @end
%%------------------------------------------------------------------------------
-spec wait_for_table_active(table_name(), pos_integer() | infinity, non_neg_integer() | infinity, aws_config()) ->
ok | {error, deleting | retry_threshold_exceeded | any()}.
wait_for_table_active(Table, Interval, RetryTimes, Config) when is_binary(Table), Interval > 0, RetryTimes >= 0 ->
case erlcloud_ddb2:describe_table(Table, [{out, record}], Config) of
{ok, #ddb2_describe_table{table = #ddb2_table_description{table_status = active}}} ->
ok;
{ok, #ddb2_describe_table{table = #ddb2_table_description{table_status = deleting}}} ->
{error, deleting};
{ok, _} ->
case RetryTimes of
infinity ->
timer:sleep(Interval),
wait_for_table_active(Table, infinity, RetryTimes, Config);
1 ->
{error, retry_threshold_exceeded};
_ ->
timer:sleep(Interval),
wait_for_table_active(Table, Interval, RetryTimes - 1, Config)
end;
{error, Reason} ->
{error, Reason}
end.
wait_for_table_active(Table, Interval, RetryTimes) ->
wait_for_table_active(Table, Interval, RetryTimes, default_config()).
wait_for_table_active(Table, AWSCfg) ->
wait_for_table_active(Table, 3000, 100, AWSCfg).
wait_for_table_active(Table) ->
wait_for_table_active(Table, default_config()).
write_all_result([ok | T]) ->
write_all_result(T);
write_all_result([{error, Reason} | _]) ->
{error, Reason};
write_all_result([]) ->
ok.
%%%------------------------------------------------------------------------------
%%% Internal Functions
%%%------------------------------------------------------------------------------
%% Set `out' option to record/typed_record output formats based on `typed_out'
boolean setting for get_all , scan_all , q_all . Other output formats are not
%% supported for multi_call reads. Validation is bypassed for backwards
%% compatibility.
-spec set_out_opt(batch_read_ddb_opts()) -> ddb_opts().
set_out_opt(Opts) ->
{OutOpt, NewOpts} = case lists:keytake(typed_out, 1, Opts) of
{value, {typed_out, true}, Opts1} -> {{out, typed_record}, Opts1};
{value, {typed_out, _}, Opts2} -> {{out, record}, Opts2};
false -> {{out, record}, Opts}
end,
lists:keystore(out, 1, NewOpts, OutOpt).
Reverses a list of lists and flattens one level
flatreverse(List) ->
lists:foldl(fun(I, A) -> I ++ A end, [], List).
%% fold a set of results from parallel operations producing lists
parfold(_, {error, Reason}) ->
{error, Reason};
parfold({error, Reason}, _) ->
{error, Reason};
parfold({ok, I}, {ok, A}) ->
{ok, I ++ A}.
parallel map implementation . See 's Programming Erlang and
pmap_unordered(F, L) ->
Parent = self(),
Ref = make_ref(),
Pids = [spawn(fun() -> Parent ! {Ref, F(X)} end) || X <- L],
[receive {Ref, Result} -> Result end || _ <- Pids].
%% creates a list of list each of which has N or fewer elements
chop(N, List) ->
chop(N, List, []).
chop(_, [], Acc) ->
lists:reverse(Acc);
chop(N, List, Acc) ->
{H, T} = safe_split(N, List),
chop(N, T, [H | Acc]).
%% lists:split throws if N is larger than the list, safe_split doesn't
safe_split(N, List) ->
safe_split(N, List, []).
safe_split(0, List, Acc) ->
{lists:reverse(Acc), List};
safe_split(_, [], Acc) ->
{lists:reverse(Acc), []};
safe_split(N, [H|T], Acc) ->
safe_split(N - 1, T, [H | Acc]).
| null | https://raw.githubusercontent.com/erlcloud/erlcloud/874181d01a9c62a5afbcf621c7704fda0f3023dc/src/erlcloud_ddb_util.erl | erlang | @doc
This is a higher layer API that augments the operations supported
by erlcloud_ddb2. The functions in this file do not map directly to
DynamoDB operations. Instead they will perform multiple operations
in order to implement functionality that isn't available directly
@end
DynamoDB Higher Layer API
------------------------------------------------------------------------------
delete_all
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
===Example===
`
ok =
erlcloud_ddb_util:delete_all(
[{<<"Forum">>,
]}]),
'
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
delete_hash_key
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
Delete all items with the specified table. Table must be a
provided for future enhancements. This method is not transacted.
===Example===
`
ok = erlcloud_ddb_util:delete_hash_key(<<"tn">>, {<<"hash-key-name">>, <<"hash-key-value">>}, <<"range-key-name">>, [])),
'
@end
------------------------------------------------------------------------------
No more work to do
Some stuff was unprocessed - keep going
------------------------------------------------------------------------------
get_all
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
items. Operations are performed in parallel. Order may not be preserved.
===Example===
`
{ok, Items} =
erlcloud_ddb_util:get_all(
<<"Forum">>,
[{projection_expression, <<"Name, Threads, Messages, Views">>}],
[{typed_out, false}]),
'
@end
------------------------------------------------------------------------------
try/catch to prevent hang forever if there is an exception
------------------------------------------------------------------------------
list_tables_all
------------------------------------------------------------------------------
------------------------------------------------------------------------------
put_all
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
===Example===
`
ok =
erlcloud_ddb_util:put_all(
[{<<"Forum">>,
]}]),
'
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
===Example===
`
{ok, Items} =
<<"Thread">>,
[{expression_attribute_values,
{index_name, <<"LastPostIndex">>},
{select, all_attributes},
{consistent_read, true},
{typed_out, true}]),
'
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
scan_all
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
Perform one or more Scan operations to get all matching items.
===Example===
`
{ok, Items} =
erlcloud_ddb_util:scan_all(
<<"Thread">>,
[{segment, 0},
{typed_out, true}]),
'
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
write_all
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
===Example===
`
ok =
erlcloud_ddb_util:write_all(
[{<<"Forum">>,
]}]),
'
@end
------------------------------------------------------------------------------
try/catch to prevent hang forever if there is an exception
------------------------------------------------------------------------------
@doc
wait until table_status==active.
===Example===
`
'
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Internal Functions
------------------------------------------------------------------------------
Set `out' option to record/typed_record output formats based on `typed_out'
supported for multi_call reads. Validation is bypassed for backwards
compatibility.
fold a set of results from parallel operations producing lists
creates a list of list each of which has N or fewer elements
lists:split throws if N is larger than the list, safe_split doesn't | -*- mode : erlang;erlang - indent - level : 4;indent - tabs - mode : nil -*-
@author >
Helpers for using DynamoDB from Erlang .
using the DynamoDB API .
-module(erlcloud_ddb_util).
-include("erlcloud.hrl").
-include("erlcloud_ddb2.hrl").
-include("erlcloud_aws.hrl").
-export([delete_all/2, delete_all/3, delete_all/4,
delete_hash_key/3, delete_hash_key/4, delete_hash_key/5,
get_all/2, get_all/3, get_all/4, get_all/5,
put_all/2, put_all/3, put_all/4,
list_tables_all/0, list_tables_all/1,
q_all/2, q_all/3, q_all/4,
scan_all/1, scan_all/2, scan_all/3,
wait_for_table_active/1, wait_for_table_active/2, wait_for_table_active/3, wait_for_table_active/4,
write_all/2, write_all/3, write_all/4
]).
-ifdef(TEST).
-export([set_out_opt/1]).
-endif.
-define(BATCH_WRITE_LIMIT, 25).
-define(BATCH_GET_LIMIT, 100).
-type typed_out() :: {typed_out, boolean()}.
-type batch_read_ddb_opt() :: typed_out() | erlcloud_ddb2:out_opt().
-type batch_read_ddb_opts() :: [batch_read_ddb_opt()].
-type conditions() :: erlcloud_ddb2:conditions().
-type ddb_opts() :: erlcloud_ddb2:ddb_opts().
-type expression() :: erlcloud_ddb2:expression().
-type hash_key() :: erlcloud_ddb2:in_attr().
-type in_item() :: erlcloud_ddb2:in_item().
-type key() :: erlcloud_ddb2:key().
-type out_item() :: erlcloud_ddb2:out_item().
-type range_key_name() :: erlcloud_ddb2:range_key_name().
-type table_name() :: erlcloud_ddb2:table_name().
-type items_return() :: {ok, [out_item()]}
| {ok, non_neg_integer()}
| {error, term()}.
-export_type(
[batch_read_ddb_opt/0,
batch_read_ddb_opts/0,
typed_out/0]).
default_config() -> erlcloud_aws:default_config().
-spec delete_all(table_name(), [key()]) -> ok | {error, term()}.
delete_all(Table, Keys) ->
delete_all(Table, Keys, [], default_config()).
-spec delete_all(table_name(), [key()], ddb_opts()) -> ok | {error, term()}.
delete_all(Table, Keys, Opts) ->
delete_all(Table, Keys, Opts, default_config()).
Perform one or more BatchWriteItem operations to delete all items .
Operations are performed in parallel . Writing to only one table is supported .
[ { < < " Name " > > , { s , < < " Amazon DynamoDB " > > } } ,
{ < < " Name " > > , { s , < < " Amazon RDS " > > } } ,
{ < < " Name " > > , { s , < < " Amazon Redshift " > > } } ,
{ < < " Name " > > , { s , < < " Amazon ElastiCache " > > } }
-spec delete_all(table_name(), [key()], ddb_opts(), aws_config()) -> ok | {error, term()}.
delete_all(Table, Keys, Opts, Config) ->
write_all(Table, [{delete, Key} || Key <- Keys], Opts, Config).
-spec delete_hash_key(table_name(), hash_key(), range_key_name()) -> ok | {error, term()}.
delete_hash_key(Table, HashKey, RangeKeyName) ->
delete_hash_key(Table, HashKey, RangeKeyName, [], default_config()).
-spec delete_hash_key(table_name(), hash_key(), range_key_name(), ddb_opts()) -> ok | {error, term()}.
delete_hash_key(Table, HashKey, RangeKeyName, Opts) ->
delete_hash_key(Table, HashKey, RangeKeyName, Opts, default_config()).
hash - and - range primary key table . Opts is currently ignored and is
-spec delete_hash_key(table_name(), hash_key(), range_key_name(), ddb_opts(), aws_config()) -> ok | {error, term()}.
delete_hash_key(Table, HashKey, RangeKeyName, Opts, Config) ->
case erlcloud_ddb2:q(Table, HashKey,
[{consistent_read, true},
{limit, ?BATCH_WRITE_LIMIT},
{attributes_to_get, [RangeKeyName]},
{out, typed_record}],
Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_q{count = 0}} ->
ok;
{ok, QResult} ->
case erlcloud_ddb2:batch_write_item(
[{Table, [{delete, [HashKey, RangeKey]} || [RangeKey] <- QResult#ddb2_q.items]}],
[{out, record}], Config) of
{error, Reason} ->
{error, Reason};
{ok, BatchResult} ->
if QResult#ddb2_q.last_evaluated_key == undefined andalso
BatchResult#ddb2_batch_write_item.unprocessed_items == [] ->
ok;
true ->
delete_hash_key(Table, HashKey, RangeKeyName, Opts, Config)
end
end
end.
-type get_all_opts() :: erlcloud_ddb2:batch_get_item_request_item_opts().
-spec get_all(table_name(), [key()]) -> items_return().
get_all(Table, Keys) ->
get_all(Table, Keys, [], default_config()).
-spec get_all(table_name(), [key()], get_all_opts()) -> items_return().
get_all(Table, Keys, Opts) ->
get_all(Table, Keys, Opts, default_config()).
-spec get_all(table_name(), [key()], get_all_opts(), aws_config() | batch_read_ddb_opts()) -> items_return().
get_all(Table, Keys, Opts, Config) when is_record(Config, aws_config) ->
get_all(Table, Keys, Opts, [], Config);
get_all(Table, Keys, Opts, DdbOpts) ->
get_all(Table, Keys, Opts, DdbOpts, default_config()).
Perform one or more BatchGetItem operations to get all matching
Getting from only one table is supported .
[ { < < " Name " > > , { s , < < " Amazon DynamoDB " > > } } ,
{ < < " Name " > > , { s , < < " Amazon RDS " > > } } ,
{ < < " Name " > > , { s , < < " Amazon Redshift " > > } } ] ,
-spec get_all(table_name(), [key()], get_all_opts(), batch_read_ddb_opts(), aws_config()) -> items_return().
get_all(Table, Keys, Opts, DdbOpts, Config) when length(Keys) =< ?BATCH_GET_LIMIT ->
batch_get_retry([{Table, Keys, Opts}], DdbOpts, Config, []);
get_all(Table, Keys, Opts, DdbOpts, Config) ->
BatchList = chop(?BATCH_GET_LIMIT, Keys),
Results = pmap_unordered(
fun(Batch) ->
try
batch_get_retry([{Table, Batch, Opts}], DdbOpts, Config, [])
catch
Type:Ex ->
{error, {Type, Ex}}
end
end,
BatchList),
lists:foldl(fun parfold/2, {ok, []}, Results).
-spec batch_get_retry([erlcloud_ddb2:batch_get_item_request_item()], ddb_opts(), aws_config(), [out_item()]) -> items_return().
batch_get_retry(RequestItems, DdbOpts, Config, Acc) ->
case erlcloud_ddb2:batch_get_item(RequestItems, set_out_opt(DdbOpts), Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_batch_get_item{unprocessed_keys = [],
responses = [#ddb2_batch_get_item_response{items = Items}]}} ->
{ok, Items ++ Acc};
{ok, #ddb2_batch_get_item{unprocessed_keys = Unprocessed,
responses = [#ddb2_batch_get_item_response{items = Items}]}} ->
batch_get_retry(Unprocessed, DdbOpts, Config, Items ++ Acc)
end.
list_tables_all() ->
list_tables_all(default_config()).
-spec list_tables_all(aws_config()) -> {ok, [table_name()]} | {error, any()}.
list_tables_all(Config) ->
do_list_tables_all(undefined, Config, []).
do_list_tables_all(LastTable, Config, Result) ->
Options = [{exclusive_start_table_name, LastTable}, {out, record}],
case erlcloud_ddb2:list_tables(Options, Config) of
{ok, #ddb2_list_tables{table_names = TableNames, last_evaluated_table_name = undefined}} ->
{ok, flatreverse([TableNames, Result])};
{ok, #ddb2_list_tables{table_names = TableNames, last_evaluated_table_name = LastTableName}} ->
do_list_tables_all(LastTableName, Config, flatreverse([TableNames, Result]));
{error, _} = Error ->
Error
end.
-spec put_all(table_name(), [in_item()]) -> ok | {error, term()}.
put_all(Table, Items) ->
put_all(Table, Items, [], default_config()).
-spec put_all(table_name(), [in_item()], ddb_opts()) -> ok | {error, term()}.
put_all(Table, Items, Opts) ->
put_all(Table, Items, Opts, default_config()).
Perform one or more BatchWriteItem operations to put all items .
Operations are performed in parallel . Writing to only one table is supported .
[ [ { < < " Name " > > , { s , < < " Amazon DynamoDB " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] ,
[ { < < " Name " > > , { s , < < " Amazon RDS " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] ,
[ { < < " Name " > > , { s , < < " Amazon Redshift " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] ,
[ { < < " Name " > > , { s , < < " Amazon ElastiCache " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ]
-spec put_all(table_name(), [in_item()], ddb_opts(), aws_config()) -> ok | {error, term()}.
put_all(Table, Items, Opts, Config) ->
write_all(Table, [{put, Item} || Item <- Items], Opts, Config).
q_all
-type q_all_opts() :: [erlcloud_ddb2:q_opt() | batch_read_ddb_opt()].
-spec q_all(table_name(), conditions() | expression()) -> items_return().
q_all(Table, KeyConditionsOrExpression) ->
q_all(Table, KeyConditionsOrExpression, [], default_config()).
-spec q_all(table_name(), conditions() | expression(), q_all_opts()) -> items_return().
q_all(Table, KeyConditionsOrExpression, Opts) ->
q_all(Table, KeyConditionsOrExpression, Opts, default_config()).
Perform one or more Query operations to get all matching items .
erlcloud_ddb_util : (
< < " ForumName = : n AND LastPostDateTime BETWEEN : t1 AND : t2 " > > ,
[ { < < " : n " > > , < < " Amazon DynamoDB " > > } ,
{ < < " : t1 " > > , < < " 20130101 " > > } ,
{ < < " : t2 " > > , < < " 20130115 " > > } ] } ,
-spec q_all(table_name(),
conditions() | expression(),
q_all_opts(),
aws_config()) -> items_return().
q_all(Table, KeyConditionsOrExpression, Opts, Config) ->
q_all(Table, KeyConditionsOrExpression, Opts, Config, [], undefined).
-spec q_all(table_name(),
conditions() | expression(),
q_all_opts(),
aws_config(),
[[out_item()]],
key() | undefined) -> items_return().
q_all(Table, KeyCondOrExpr, Opts0, Config, Acc, StartKey) ->
Opts = [{exclusive_start_key, StartKey}|set_out_opt(Opts0)],
case erlcloud_ddb2:q(Table, KeyCondOrExpr, Opts, Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_q{last_evaluated_key = undefined,
items = undefined,
count = Count}} ->
{ok, lists:sum([Count|Acc])};
{ok, #ddb2_q{last_evaluated_key = undefined,
items = Items}} ->
{ok, flatreverse([Items|Acc])};
{ok, #ddb2_q{last_evaluated_key = LastKey,
items = undefined,
count = Count}} ->
q_all(Table, KeyCondOrExpr, Opts0, Config, [Count|Acc], LastKey);
{ok, #ddb2_q{last_evaluated_key = LastKey,
items = Items}} ->
q_all(Table, KeyCondOrExpr, Opts0, Config, [Items|Acc], LastKey)
end.
-type scan_all_opts() :: [erlcloud_ddb2:scan_opt() | batch_read_ddb_opt()].
-spec scan_all(table_name()) -> items_return().
scan_all(Table) ->
scan_all(Table, [], default_config()).
-spec scan_all(table_name(), scan_all_opts()) -> items_return().
scan_all(Table, Opts) ->
scan_all(Table, Opts, default_config()).
{ total_segments , 4 } ,
-spec scan_all(table_name(), scan_all_opts(), aws_config()) -> items_return().
scan_all(Table, Opts, Config) ->
scan_all(Table, Opts, Config, [], undefined).
-spec scan_all(table_name(),
scan_all_opts(),
aws_config(),
[[out_item()]],
key() | undefined) -> items_return().
scan_all(Table, Opts0, Config, Acc, StartKey) ->
Opts = [{exclusive_start_key, StartKey}|set_out_opt(Opts0)],
case erlcloud_ddb2:scan(Table, Opts, Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_scan{last_evaluated_key = undefined,
items = undefined,
count = Count}} ->
{ok, lists:sum([Count|Acc])};
{ok, #ddb2_scan{last_evaluated_key = undefined,
items = Items}} ->
{ok, flatreverse([Items|Acc])};
{ok, #ddb2_scan{last_evaluated_key = LastKey,
items = undefined,
count = Count}} ->
scan_all(Table, Opts0, Config, [Count|Acc], LastKey);
{ok, #ddb2_scan{last_evaluated_key = LastKey,
items = Items}} ->
scan_all(Table, Opts0, Config, [Items|Acc], LastKey)
end.
-type write_all_item() :: erlcloud_ddb2:batch_write_item_request().
-spec write_all(table_name(), [write_all_item()]) -> ok | {error, term()}.
write_all(Table, Items) ->
write_all(Table, Items, [], default_config()).
-spec write_all(table_name(), [write_all_item()], ddb_opts()) -> ok | {error, term()}.
write_all(Table, Items, Opts) ->
write_all(Table, Items, Opts, default_config()).
Perform one or more BatchWriteItem operations to put or delete all items .
Operations are performed in parallel . Writing to only one table is supported .
[ { put , [ { < < " Name " > > , { s , < < " Amazon DynamoDB " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] } ,
{ put , [ { < < " Name " > > , { s , < < " Amazon RDS " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] } ,
{ put , [ { < < " Name " > > , { s , < < " Amazon Redshift " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] } ,
{ put , [ { < < " Name " > > , { s , < < " Amazon ElastiCache " > > } } ,
{ < < " Category " > > , { s , < < " Amazon Web Services " > > } } ] }
-spec write_all(table_name(), [write_all_item()], ddb_opts(), aws_config()) -> ok | {error, term()}.
write_all(Table, Items, _Opts, Config) when length(Items) =< ?BATCH_WRITE_LIMIT ->
batch_write_retry([{Table, Items}], Config);
write_all(Table, Items, _Opts, Config) ->
BatchList = chop(?BATCH_WRITE_LIMIT, Items),
Results = pmap_unordered(
fun(Batch) ->
try
batch_write_retry([{Table, Batch}], Config)
catch
Type:Ex ->
{error, {Type, Ex}}
end
end,
BatchList),
write_all_result(Results).
-spec batch_write_retry([erlcloud_ddb2:batch_write_item_request_item()], aws_config()) -> ok | {error, term()}.
batch_write_retry(RequestItems, Config) ->
case erlcloud_ddb2:batch_write_item(RequestItems, [{out, record}], Config) of
{error, Reason} ->
{error, Reason};
{ok, #ddb2_batch_write_item{unprocessed_items = []}} ->
ok;
{ok, #ddb2_batch_write_item{unprocessed_items = Unprocessed}} ->
batch_write_retry(Unprocessed, Config)
end.
erlcloud_ddb2 : wait_for_table_active(<<"TableName " > > , 3000 , 40 , Config )
-spec wait_for_table_active(table_name(), pos_integer() | infinity, non_neg_integer() | infinity, aws_config()) ->
ok | {error, deleting | retry_threshold_exceeded | any()}.
wait_for_table_active(Table, Interval, RetryTimes, Config) when is_binary(Table), Interval > 0, RetryTimes >= 0 ->
case erlcloud_ddb2:describe_table(Table, [{out, record}], Config) of
{ok, #ddb2_describe_table{table = #ddb2_table_description{table_status = active}}} ->
ok;
{ok, #ddb2_describe_table{table = #ddb2_table_description{table_status = deleting}}} ->
{error, deleting};
{ok, _} ->
case RetryTimes of
infinity ->
timer:sleep(Interval),
wait_for_table_active(Table, infinity, RetryTimes, Config);
1 ->
{error, retry_threshold_exceeded};
_ ->
timer:sleep(Interval),
wait_for_table_active(Table, Interval, RetryTimes - 1, Config)
end;
{error, Reason} ->
{error, Reason}
end.
wait_for_table_active(Table, Interval, RetryTimes) ->
wait_for_table_active(Table, Interval, RetryTimes, default_config()).
wait_for_table_active(Table, AWSCfg) ->
wait_for_table_active(Table, 3000, 100, AWSCfg).
wait_for_table_active(Table) ->
wait_for_table_active(Table, default_config()).
write_all_result([ok | T]) ->
write_all_result(T);
write_all_result([{error, Reason} | _]) ->
{error, Reason};
write_all_result([]) ->
ok.
boolean setting for get_all , scan_all , q_all . Other output formats are not
-spec set_out_opt(batch_read_ddb_opts()) -> ddb_opts().
set_out_opt(Opts) ->
{OutOpt, NewOpts} = case lists:keytake(typed_out, 1, Opts) of
{value, {typed_out, true}, Opts1} -> {{out, typed_record}, Opts1};
{value, {typed_out, _}, Opts2} -> {{out, record}, Opts2};
false -> {{out, record}, Opts}
end,
lists:keystore(out, 1, NewOpts, OutOpt).
Reverses a list of lists and flattens one level
flatreverse(List) ->
lists:foldl(fun(I, A) -> I ++ A end, [], List).
parfold(_, {error, Reason}) ->
{error, Reason};
parfold({error, Reason}, _) ->
{error, Reason};
parfold({ok, I}, {ok, A}) ->
{ok, I ++ A}.
parallel map implementation . See 's Programming Erlang and
pmap_unordered(F, L) ->
Parent = self(),
Ref = make_ref(),
Pids = [spawn(fun() -> Parent ! {Ref, F(X)} end) || X <- L],
[receive {Ref, Result} -> Result end || _ <- Pids].
chop(N, List) ->
chop(N, List, []).
chop(_, [], Acc) ->
lists:reverse(Acc);
chop(N, List, Acc) ->
{H, T} = safe_split(N, List),
chop(N, T, [H | Acc]).
safe_split(N, List) ->
safe_split(N, List, []).
safe_split(0, List, Acc) ->
{lists:reverse(Acc), List};
safe_split(_, [], Acc) ->
{lists:reverse(Acc), []};
safe_split(N, [H|T], Acc) ->
safe_split(N - 1, T, [H | Acc]).
|
be02ab0de99ab150e1f88a3d1a621dccb5c7fc5299c3ce545f73c7b5d73715fb | omelkonian/AlgoRhythm | ChaosPitches.hs | # language GADTs #
-- | An example implementation of a `Generate.Chaos` that generates music with
-- chaotic octave and pitch selection.
module Generate.Applications.ChaosPitches (
genChaosMusic
, chaos1
, bSolo
, chaos1Selector) where
import Music
import Utils.Vec
import Generate.Generate
import Control.Monad.State hiding (state)
import Generate.Chaos
| Generates ` Music ` with chaos function f x = 1 - 1.9521 * x^2 in range [ -1,1 ]
with initial x = 1.2 .
genChaosMusic :: IO (Music Pitch)
genChaosMusic = do
let mapping = defaultMapping {pcSel=chaos1Selector, octSel=chaos1Selector }
runChaosGenerator chaos1 mapping bSolo
| ChaosState with chaos function f x = 1 - 1.9521 * x^2 in range [ -1,1 ]
with initial x = 1.2 .
chaos1 :: ChaosState D1
chaos1 = do
let startX = 1.2
buildChaos (startX :. Nil) (f :. Nil)
where f :: (Vec D1 Double -> Double)
f (x:.Nil) = max (-1) (min 1 (1 - 1.9521 * x**2))
| ` MusicGenerator ` that uses ` chaos1 ` to generate some blues music .
bSolo :: MusicGenerator (ChaosState D1) Melody
bSolo = do
addConstraint pitchClass (`elem` (E +| blues :: [PitchClass]))
run1 <- local $ do
octave >! (`elem` [4,5])
duration >! (`elem` [1%32, 1%16])
line <$> 12 .#. genNote
run2 <- local $ do
octave >! (`elem` [2,3,4])
duration >! (`elem` [1%8, 1%16])
pitchClass >! (`elem` [E, Fs, Gs, B, Cs])
line <$> 6 .#. genNote
return $ run1 :=: run2
| The selector that maps the chaos function from ` ` to an element in a.
chaos1Selector :: Selector (ChaosState n) a
chaos1Selector s as = do
([d], s') <- runStateT genNextIteration s
let dNormalised = (d+1) / 2
let maxI = fromIntegral (length as - 1)
let index = round (dNormalised * maxI)
let a = as !! index
return (snd a, s')
| null | https://raw.githubusercontent.com/omelkonian/AlgoRhythm/fdc1ccbae0b3d8a7635b24d37716123aba2d6c11/AlgoRhythm/src/Generate/Applications/ChaosPitches.hs | haskell | | An example implementation of a `Generate.Chaos` that generates music with
chaotic octave and pitch selection. | # language GADTs #
module Generate.Applications.ChaosPitches (
genChaosMusic
, chaos1
, bSolo
, chaos1Selector) where
import Music
import Utils.Vec
import Generate.Generate
import Control.Monad.State hiding (state)
import Generate.Chaos
| Generates ` Music ` with chaos function f x = 1 - 1.9521 * x^2 in range [ -1,1 ]
with initial x = 1.2 .
genChaosMusic :: IO (Music Pitch)
genChaosMusic = do
let mapping = defaultMapping {pcSel=chaos1Selector, octSel=chaos1Selector }
runChaosGenerator chaos1 mapping bSolo
| ChaosState with chaos function f x = 1 - 1.9521 * x^2 in range [ -1,1 ]
with initial x = 1.2 .
chaos1 :: ChaosState D1
chaos1 = do
let startX = 1.2
buildChaos (startX :. Nil) (f :. Nil)
where f :: (Vec D1 Double -> Double)
f (x:.Nil) = max (-1) (min 1 (1 - 1.9521 * x**2))
| ` MusicGenerator ` that uses ` chaos1 ` to generate some blues music .
bSolo :: MusicGenerator (ChaosState D1) Melody
bSolo = do
addConstraint pitchClass (`elem` (E +| blues :: [PitchClass]))
run1 <- local $ do
octave >! (`elem` [4,5])
duration >! (`elem` [1%32, 1%16])
line <$> 12 .#. genNote
run2 <- local $ do
octave >! (`elem` [2,3,4])
duration >! (`elem` [1%8, 1%16])
pitchClass >! (`elem` [E, Fs, Gs, B, Cs])
line <$> 6 .#. genNote
return $ run1 :=: run2
| The selector that maps the chaos function from ` ` to an element in a.
chaos1Selector :: Selector (ChaosState n) a
chaos1Selector s as = do
([d], s') <- runStateT genNextIteration s
let dNormalised = (d+1) / 2
let maxI = fromIntegral (length as - 1)
let index = round (dNormalised * maxI)
let a = as !! index
return (snd a, s')
|
c230d4ac76a8e5d01eefe82133cedb62bc463abee12e6ca8a450534931fdb4f0 | strojure/zizzmap | impl_test.clj | (ns strojure.zizzmap.impl-test
(:require [clojure.test :as test :refer [deftest testing]]
[strojure.zizzmap.impl :as impl])
(:import (clojure.lang IPersistentVector MapEntry)
(java.util Map)))
(set! *warn-on-reflection* true)
(declare thrown?)
#_(test/run-tests)
;;,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
(def ^:private -e (impl/boxed-map-entry :k (impl/boxed-delay :x)))
(deftest boxed-map-entry-t
(test/are [expr result] (= result expr)
(key -e) #_= :k
(val -e) #_= :x
(count -e) #_= 2
(.length ^IPersistentVector -e) #_= 2
(nth -e 0) #_= :k
(nth -e 1) #_= :x
(nth -e 2 :not-found) #_= :not-found
(.valAt ^IPersistentVector -e 0) #_= :k
(.valAt ^IPersistentVector -e 1) #_= :x
(.valAt ^IPersistentVector -e 2) #_= nil
(.valAt ^IPersistentVector -e 2 :not-found) #_= :not-found
-e #_= [:k :x]
(let [[k v] -e] [k v]) #_= [:k :x]
(conj -e :y) #_= [:k :x :y]
(pop -e) #_= [:k]
(peek -e) #_= :x
(assoc -e 0 :kk) #_= [:kk :x]
(assoc -e 1 :xx) #_= [:k :xx]
(assoc -e 1 (impl/boxed-delay :xx)) #_= [:k :xx]
(assoc -e 2 :y) #_= [:k :x :y]
(contains? -e 0) #_= true
(contains? -e 1) #_= true
(contains? -e 2) #_= false
(.entryAt ^IPersistentVector -e 0) #_= [0 :k]
(.entryAt ^IPersistentVector -e 1) #_= [1 :x]
(.entryAt ^IPersistentVector -e 2) #_= nil
(let [a (atom :pending)
e (impl/boxed-map-entry :k (impl/boxed-delay (reset! a :realized)
:x))
e (.entryAt ^IPersistentVector e 1)]
[e @a]) #_= [[1 :x] :pending]
(.assocN ^IPersistentVector -e 0 :kk) #_= [:kk :x]
(.assocN ^IPersistentVector -e 1 :xx) #_= [:k :xx]
(.assocN ^IPersistentVector -e 1 (impl/boxed-delay :xx)) #_= [:k :xx]
(.assocN ^IPersistentVector -e 2 :y) #_= [:k :x :y]
(empty -e) #_= (empty (MapEntry. :k :x))
(realized? (seq -e)) #_= false
(first (seq -e)) #_= :k
(second (seq -e)) #_= :x
(let [a (atom :pending)
e (impl/boxed-map-entry :k (impl/boxed-delay (reset! a :realized)
:x))]
[(first e) @a]) #_= [:k :pending]
(let [a (atom :pending)
e (impl/boxed-map-entry :k (impl/boxed-delay (reset! a :realized)
:x))]
[(second e) @a]) #_= [:x :realized]
(.equiv ^IPersistentVector -e -e) #_= true
(.equiv ^IPersistentVector -e [:k :x]) #_= true
(.equiv ^IPersistentVector -e (impl/boxed-map-entry :k (impl/boxed-delay :x))) #_= true
(.equiv ^IPersistentVector -e [:k :y]) #_= false
(sequential? -e) #_= true
(rseq -e) #_= '(:x :k)
)
(testing "Exceptional operations"
(test/are [expr] expr
(thrown? IndexOutOfBoundsException
(nth -e 2))
(thrown? IllegalArgumentException "Key must be integer"
(assoc -e :x nil))
)))
;;,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
(def ^:private -m
(impl/persistent-map {:a (impl/boxed-delay :x)
:b :y}))
(deftest persistent-map-t
(test/are [expr result] (= result expr)
(get -m :a) #_= :x
(get -m :b) #_= :y
(get -m :c) #_= nil
(get -m :a :not-found) #_= :x
(get -m :b :not-found) #_= :y
(get -m :c :not-found) #_= :not-found
(:a -m) #_= :x
(:b -m) #_= :y
(:c -m) #_= nil
(-m :a) #_= :x
(-m :b) #_= :y
(-m :c) #_= nil
(instance? Map -m) #_= true
(= -m -m) #_= true
(= -m {:a :x :b :y}) #_= true
(= {:a :x :b :y} -m) #_= true
(= (impl/persistent-map {:a (impl/boxed-delay :x)})
(impl/persistent-map {:a (impl/boxed-delay :x)})) #_= true
(assoc -m :a :xx) #_= {:a :xx :b :y}
(assoc -m :b :yy) #_= {:a :x :b :yy}
(assoc -m :c :zz) #_= {:a :x :b :y :c :zz}
(dissoc -m :a) #_= {:b :y}
(dissoc -m :b) #_= {:a :x}
(dissoc -m :c) #_= {:a :x :b :y}
(update -m :a name) #_= {:a "x" :b :y}
(update -m :b name) #_= {:a :x :b "y"}
(select-keys -m [:a :b]) #_= {:a :x :b :y}
(select-keys -m [:a]) #_= {:a :x}
(select-keys -m [:b]) #_= {:b :y}
(seq -m) #_= '([:a :x] [:b :y])
(into {} -m) #_= {:a :x :b :y}
(into -m {}) #_= {:a :x :b :y}
(into {:c :z} -m) #_= {:a :x :b :y :c :z}
(into -m {:c :z}) #_= {:a :x :b :y :c :z}
(impl/persistent? (into {:c :z} -m)) #_= false
(impl/persistent? (into -m {:c :z})) #_= true
(merge {} -m) #_= {:a :x :b :y}
(merge -m {}) #_= {:a :x :b :y}
(merge {:c :z} -m) #_= {:a :x :b :y :c :z}
(merge -m {:c :z}) #_= {:a :x :b :y :c :z}
(impl/persistent? (merge {:c :z} -m)) #_= false
(impl/persistent? (merge -m {:c :z})) #_= true
(counted? -m) #_= true
(count -m) #_= 2
(set (keys -m)) #_= #{:a :b}
(set (vals -m)) #_= #{:x :y}
(conj -m [:c :z]) #_= {:a :x, :b :y, :c :z}
(conj -m [:c (impl/boxed-delay :z)]) #_= {:a :x, :b :y, :c :z}
(empty -m) #_= {}
(impl/persistent? (empty -m)) #_= true
(find -m :a) #_= [:a :x]
(reduce-kv conj [] -m) #_= [:a :x :b :y]
(str -m) #_= "{:a :x, :b :y}"
)
(testing "Value laziness"
(test/are [expr result] (= result expr)
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)})
before @a
x (get m :a)
after @a]
[before x after]) #_= [:pending :x :realized]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)})
m (assoc m :a :xx)]
[@a m]) #_= [:pending {:a :xx}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)})
m (assoc m :b :yy)]
[@a m]) #_= [:pending {:a :x :b :yy}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (dissoc m :a)]
[@a m]) #_= [:pending {:b :y}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (dissoc m :b)]
[@a m]) #_= [:pending {:a :x}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (update m :b name)]
[@a m]) #_= [:pending {:a :x :b "y"}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (select-keys m [:a :b])]
[@a m]) #_= [:realized {:a :x :b :y}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (select-keys m [:b])]
[@a m]) #_= [:pending {:b :y}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
_ (doall (seq m))]
[@a]) #_= [:pending]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (into m {:c :z})]
[@a m]) #_= [:pending {:a :x, :b :y, :c :z}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (into {:c :z} m)]
[@a m]) #_= [:realized {:a :x, :b :y, :c :z}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (conj m [:c :z])]
[@a m]) #_= [:pending {:a :x, :b :y, :c :z}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
k (key (find m :a))]
[@a k]) #_= [:pending :a]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
v (val (find m :a))]
[@a v]) #_= [:realized :x]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (persistent! (transient m))]
[@a m]) #_= [:pending {:a :x, :b :y}]
))
)
| null | https://raw.githubusercontent.com/strojure/zizzmap/27940fd8dc80b2758bab6dc6eae18a84893fd26d/test/strojure/zizzmap/impl_test.clj | clojure | ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, | (ns strojure.zizzmap.impl-test
(:require [clojure.test :as test :refer [deftest testing]]
[strojure.zizzmap.impl :as impl])
(:import (clojure.lang IPersistentVector MapEntry)
(java.util Map)))
(set! *warn-on-reflection* true)
(declare thrown?)
#_(test/run-tests)
(def ^:private -e (impl/boxed-map-entry :k (impl/boxed-delay :x)))
(deftest boxed-map-entry-t
(test/are [expr result] (= result expr)
(key -e) #_= :k
(val -e) #_= :x
(count -e) #_= 2
(.length ^IPersistentVector -e) #_= 2
(nth -e 0) #_= :k
(nth -e 1) #_= :x
(nth -e 2 :not-found) #_= :not-found
(.valAt ^IPersistentVector -e 0) #_= :k
(.valAt ^IPersistentVector -e 1) #_= :x
(.valAt ^IPersistentVector -e 2) #_= nil
(.valAt ^IPersistentVector -e 2 :not-found) #_= :not-found
-e #_= [:k :x]
(let [[k v] -e] [k v]) #_= [:k :x]
(conj -e :y) #_= [:k :x :y]
(pop -e) #_= [:k]
(peek -e) #_= :x
(assoc -e 0 :kk) #_= [:kk :x]
(assoc -e 1 :xx) #_= [:k :xx]
(assoc -e 1 (impl/boxed-delay :xx)) #_= [:k :xx]
(assoc -e 2 :y) #_= [:k :x :y]
(contains? -e 0) #_= true
(contains? -e 1) #_= true
(contains? -e 2) #_= false
(.entryAt ^IPersistentVector -e 0) #_= [0 :k]
(.entryAt ^IPersistentVector -e 1) #_= [1 :x]
(.entryAt ^IPersistentVector -e 2) #_= nil
(let [a (atom :pending)
e (impl/boxed-map-entry :k (impl/boxed-delay (reset! a :realized)
:x))
e (.entryAt ^IPersistentVector e 1)]
[e @a]) #_= [[1 :x] :pending]
(.assocN ^IPersistentVector -e 0 :kk) #_= [:kk :x]
(.assocN ^IPersistentVector -e 1 :xx) #_= [:k :xx]
(.assocN ^IPersistentVector -e 1 (impl/boxed-delay :xx)) #_= [:k :xx]
(.assocN ^IPersistentVector -e 2 :y) #_= [:k :x :y]
(empty -e) #_= (empty (MapEntry. :k :x))
(realized? (seq -e)) #_= false
(first (seq -e)) #_= :k
(second (seq -e)) #_= :x
(let [a (atom :pending)
e (impl/boxed-map-entry :k (impl/boxed-delay (reset! a :realized)
:x))]
[(first e) @a]) #_= [:k :pending]
(let [a (atom :pending)
e (impl/boxed-map-entry :k (impl/boxed-delay (reset! a :realized)
:x))]
[(second e) @a]) #_= [:x :realized]
(.equiv ^IPersistentVector -e -e) #_= true
(.equiv ^IPersistentVector -e [:k :x]) #_= true
(.equiv ^IPersistentVector -e (impl/boxed-map-entry :k (impl/boxed-delay :x))) #_= true
(.equiv ^IPersistentVector -e [:k :y]) #_= false
(sequential? -e) #_= true
(rseq -e) #_= '(:x :k)
)
(testing "Exceptional operations"
(test/are [expr] expr
(thrown? IndexOutOfBoundsException
(nth -e 2))
(thrown? IllegalArgumentException "Key must be integer"
(assoc -e :x nil))
)))
(def ^:private -m
(impl/persistent-map {:a (impl/boxed-delay :x)
:b :y}))
(deftest persistent-map-t
(test/are [expr result] (= result expr)
(get -m :a) #_= :x
(get -m :b) #_= :y
(get -m :c) #_= nil
(get -m :a :not-found) #_= :x
(get -m :b :not-found) #_= :y
(get -m :c :not-found) #_= :not-found
(:a -m) #_= :x
(:b -m) #_= :y
(:c -m) #_= nil
(-m :a) #_= :x
(-m :b) #_= :y
(-m :c) #_= nil
(instance? Map -m) #_= true
(= -m -m) #_= true
(= -m {:a :x :b :y}) #_= true
(= {:a :x :b :y} -m) #_= true
(= (impl/persistent-map {:a (impl/boxed-delay :x)})
(impl/persistent-map {:a (impl/boxed-delay :x)})) #_= true
(assoc -m :a :xx) #_= {:a :xx :b :y}
(assoc -m :b :yy) #_= {:a :x :b :yy}
(assoc -m :c :zz) #_= {:a :x :b :y :c :zz}
(dissoc -m :a) #_= {:b :y}
(dissoc -m :b) #_= {:a :x}
(dissoc -m :c) #_= {:a :x :b :y}
(update -m :a name) #_= {:a "x" :b :y}
(update -m :b name) #_= {:a :x :b "y"}
(select-keys -m [:a :b]) #_= {:a :x :b :y}
(select-keys -m [:a]) #_= {:a :x}
(select-keys -m [:b]) #_= {:b :y}
(seq -m) #_= '([:a :x] [:b :y])
(into {} -m) #_= {:a :x :b :y}
(into -m {}) #_= {:a :x :b :y}
(into {:c :z} -m) #_= {:a :x :b :y :c :z}
(into -m {:c :z}) #_= {:a :x :b :y :c :z}
(impl/persistent? (into {:c :z} -m)) #_= false
(impl/persistent? (into -m {:c :z})) #_= true
(merge {} -m) #_= {:a :x :b :y}
(merge -m {}) #_= {:a :x :b :y}
(merge {:c :z} -m) #_= {:a :x :b :y :c :z}
(merge -m {:c :z}) #_= {:a :x :b :y :c :z}
(impl/persistent? (merge {:c :z} -m)) #_= false
(impl/persistent? (merge -m {:c :z})) #_= true
(counted? -m) #_= true
(count -m) #_= 2
(set (keys -m)) #_= #{:a :b}
(set (vals -m)) #_= #{:x :y}
(conj -m [:c :z]) #_= {:a :x, :b :y, :c :z}
(conj -m [:c (impl/boxed-delay :z)]) #_= {:a :x, :b :y, :c :z}
(empty -m) #_= {}
(impl/persistent? (empty -m)) #_= true
(find -m :a) #_= [:a :x]
(reduce-kv conj [] -m) #_= [:a :x :b :y]
(str -m) #_= "{:a :x, :b :y}"
)
(testing "Value laziness"
(test/are [expr result] (= result expr)
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)})
before @a
x (get m :a)
after @a]
[before x after]) #_= [:pending :x :realized]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)})
m (assoc m :a :xx)]
[@a m]) #_= [:pending {:a :xx}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)})
m (assoc m :b :yy)]
[@a m]) #_= [:pending {:a :x :b :yy}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (dissoc m :a)]
[@a m]) #_= [:pending {:b :y}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (dissoc m :b)]
[@a m]) #_= [:pending {:a :x}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (update m :b name)]
[@a m]) #_= [:pending {:a :x :b "y"}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (select-keys m [:a :b])]
[@a m]) #_= [:realized {:a :x :b :y}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (select-keys m [:b])]
[@a m]) #_= [:pending {:b :y}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
_ (doall (seq m))]
[@a]) #_= [:pending]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (into m {:c :z})]
[@a m]) #_= [:pending {:a :x, :b :y, :c :z}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (into {:c :z} m)]
[@a m]) #_= [:realized {:a :x, :b :y, :c :z}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (conj m [:c :z])]
[@a m]) #_= [:pending {:a :x, :b :y, :c :z}]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
k (key (find m :a))]
[@a k]) #_= [:pending :a]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
v (val (find m :a))]
[@a v]) #_= [:realized :x]
(let [a (atom :pending) m (impl/persistent-map {:a (impl/boxed-delay
(reset! a :realized)
:x)
:b :y})
m (persistent! (transient m))]
[@a m]) #_= [:pending {:a :x, :b :y}]
))
)
|
fbde12591e73b1cc9c1dbe294812004001b6c6fcfdd6317cf6b779b2b49693cc | rtoy/cmucl | boot-2008-05-cross-unicode-x86.lisp | Cross - compile script to add 16 - bit strings for Unicode support .
;;; Use as the cross-compile script for cross-build-world.sh.
(in-package :cl-user)
;;; Rename the X86 package and backend so that new-backend does the
;;; right thing.
(rename-package "X86" "OLD-X86" '("OLD-VM"))
(setf (c:backend-name c:*native-backend*) "OLD-X86")
(c::new-backend "X86"
;; Features to add here
'(:x86 :i486 :pentium
:stack-checking
:heap-overflow-check
:relative-package-names
:mp
:gencgc
:conservative-float-type
:hash-new :random-mt19937
:cmu :cmu19 :cmu19e
:double-double
:unicode
)
;; Features to remove from current *features* here
'())
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Things needed to cross-compile unicode changes.
(load "target:bootfiles/19e/boot-2008-05-cross-unicode-common.lisp")
;; Kill the any deftransforms
(in-package "C")
(dolist (f '(concatenate subseq replace copy-seq))
(setf (c::function-info-transforms (c::function-info-or-lose f)) nil))
;; End changes for unicode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :cl-user)
;;; Compile the new backend.
(pushnew :bootstrap *features*)
(pushnew :building-cross-compiler *features*)
(load "target:tools/comcom")
;;; Load the new backend.
(setf (search-list "c:")
'("target:compiler/"))
(setf (search-list "vm:")
'("c:x86/" "c:generic/"))
(setf (search-list "assem:")
'("target:assembly/" "target:assembly/x86/"))
;; Load the backend of the compiler.
(in-package "C")
(load "vm:vm-macs")
(load "vm:parms")
(load "vm:objdef")
(load "vm:interr")
(load "assem:support")
(load "target:compiler/srctran")
(load "vm:vm-typetran")
(load "target:compiler/float-tran")
(load "target:compiler/saptran")
(load "vm:macros")
(load "vm:utils")
(load "vm:vm")
(load "vm:insts")
(load "vm:primtype")
(load "vm:move")
(load "vm:sap")
(when (target-featurep :sse2)
(load "vm:sse2-sap"))
(load "vm:system")
(load "vm:char")
(if (target-featurep :sse2)
(load "vm:float-sse2")
(load "vm:float"))
(load "vm:memory")
(load "vm:static-fn")
(load "vm:arith")
(load "vm:cell")
(load "vm:subprim")
(load "vm:debug")
(load "vm:c-call")
(if (target-featurep :sse2)
(load "vm:sse2-c-call")
(load "vm:x87-c-call"))
(load "vm:print")
(load "vm:alloc")
(load "vm:call")
(load "vm:nlx")
(load "vm:values")
;; These need to be loaded before array because array wants to use
;; some vops as templates.
(load (if (target-featurep :sse2)
"vm:sse2-array"
"vm:x87-array"))
(load "vm:array")
(load "vm:pred")
(load "vm:type-vops")
(load "assem:assem-rtns")
(load "assem:array")
(load "assem:arith")
(load "assem:alloc")
(load "c:pseudo-vops")
(check-move-function-consistency)
(load "vm:new-genesis")
;;; OK, the cross compiler backend is loaded.
(setf *features* (remove :building-cross-compiler *features*))
;;; Info environment hacks.
(macrolet ((frob (&rest syms)
`(progn ,@(mapcar #'(lambda (sym)
`(defconstant ,sym
(symbol-value
(find-symbol ,(symbol-name sym)
:vm))))
syms))))
(frob OLD-X86:BYTE-BITS OLD-X86:WORD-BITS
#+long-float OLD-X86:SIMPLE-ARRAY-LONG-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-DOUBLE-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-SINGLE-FLOAT-TYPE
#+long-float OLD-X86:SIMPLE-ARRAY-COMPLEX-LONG-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-COMPLEX-DOUBLE-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-COMPLEX-SINGLE-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-2-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-4-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-8-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-16-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-32-TYPE
OLD-X86:SIMPLE-ARRAY-SIGNED-BYTE-8-TYPE
OLD-X86:SIMPLE-ARRAY-SIGNED-BYTE-16-TYPE
OLD-X86:SIMPLE-ARRAY-SIGNED-BYTE-30-TYPE
OLD-X86:SIMPLE-ARRAY-SIGNED-BYTE-32-TYPE
OLD-X86:SIMPLE-BIT-VECTOR-TYPE
OLD-X86:SIMPLE-STRING-TYPE OLD-X86:SIMPLE-VECTOR-TYPE
OLD-X86:SIMPLE-ARRAY-TYPE OLD-X86:VECTOR-DATA-OFFSET
OLD-X86:DOUBLE-FLOAT-EXPONENT-BYTE
OLD-X86:DOUBLE-FLOAT-NORMAL-EXPONENT-MAX
OLD-X86:DOUBLE-FLOAT-SIGNIFICAND-BYTE
OLD-X86:SINGLE-FLOAT-EXPONENT-BYTE
OLD-X86:SINGLE-FLOAT-NORMAL-EXPONENT-MAX
OLD-X86:SINGLE-FLOAT-SIGNIFICAND-BYTE
)
#+double-double
(frob OLD-X86:SIMPLE-ARRAY-COMPLEX-DOUBLE-DOUBLE-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-DOUBLE-DOUBLE-FLOAT-TYPE))
Modular arith hacks
(setf (fdefinition 'vm::ash-left-mod32) #'old-x86::ash-left-mod32)
(setf (fdefinition 'vm::lognot-mod32) #'old-x86::lognot-mod32)
;; End arith hacks
(let ((function (symbol-function 'kernel:error-number-or-lose)))
(let ((*info-environment* (c:backend-info-environment c:*target-backend*)))
(setf (symbol-function 'kernel:error-number-or-lose) function)
(setf (info function kind 'kernel:error-number-or-lose) :function)
(setf (info function where-from 'kernel:error-number-or-lose) :defined)))
(defun fix-class (name)
(let* ((new-value (find-class name))
(new-layout (kernel::%class-layout new-value))
(new-cell (kernel::find-class-cell name))
(*info-environment* (c:backend-info-environment c:*target-backend*)))
(remhash name kernel::*forward-referenced-layouts*)
(kernel::%note-type-defined name)
(setf (info type kind name) :instance)
(setf (info type class name) new-cell)
(setf (info type compiler-layout name) new-layout)
new-value))
(fix-class 'c::vop-parse)
(fix-class 'c::operand-parse)
#+random-mt19937
(declaim (notinline kernel:random-chunk))
(setf c:*backend* c:*target-backend*)
Extern - alien - name for the new backend .
(in-package :vm)
(defun extern-alien-name (name)
(declare (type simple-string name))
name)
(export 'extern-alien-name)
(export 'fixup-code-object)
(export 'sanctify-for-execution)
(in-package :cl-user)
;;; Don't load compiler parts from the target compilation
(defparameter *load-stuff* nil)
;; hack, hack, hack: Make old-x86::any-reg the same as
x86::any - reg as an SC . Do this by adding old - x86::any - reg
;; to the hash table with the same value as x86::any-reg.
(let ((ht (c::backend-sc-names c::*target-backend*)))
(setf (gethash 'old-x86::any-reg ht)
(gethash 'x86::any-reg ht)))
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/bootfiles/19e/boot-2008-05-cross-unicode-x86.lisp | lisp | Use as the cross-compile script for cross-build-world.sh.
Rename the X86 package and backend so that new-backend does the
right thing.
Features to add here
Features to remove from current *features* here
Things needed to cross-compile unicode changes.
Kill the any deftransforms
End changes for unicode
Compile the new backend.
Load the new backend.
Load the backend of the compiler.
These need to be loaded before array because array wants to use
some vops as templates.
OK, the cross compiler backend is loaded.
Info environment hacks.
End arith hacks
Don't load compiler parts from the target compilation
hack, hack, hack: Make old-x86::any-reg the same as
to the hash table with the same value as x86::any-reg. | Cross - compile script to add 16 - bit strings for Unicode support .
(in-package :cl-user)
(rename-package "X86" "OLD-X86" '("OLD-VM"))
(setf (c:backend-name c:*native-backend*) "OLD-X86")
(c::new-backend "X86"
'(:x86 :i486 :pentium
:stack-checking
:heap-overflow-check
:relative-package-names
:mp
:gencgc
:conservative-float-type
:hash-new :random-mt19937
:cmu :cmu19 :cmu19e
:double-double
:unicode
)
'())
(load "target:bootfiles/19e/boot-2008-05-cross-unicode-common.lisp")
(in-package "C")
(dolist (f '(concatenate subseq replace copy-seq))
(setf (c::function-info-transforms (c::function-info-or-lose f)) nil))
(in-package :cl-user)
(pushnew :bootstrap *features*)
(pushnew :building-cross-compiler *features*)
(load "target:tools/comcom")
(setf (search-list "c:")
'("target:compiler/"))
(setf (search-list "vm:")
'("c:x86/" "c:generic/"))
(setf (search-list "assem:")
'("target:assembly/" "target:assembly/x86/"))
(in-package "C")
(load "vm:vm-macs")
(load "vm:parms")
(load "vm:objdef")
(load "vm:interr")
(load "assem:support")
(load "target:compiler/srctran")
(load "vm:vm-typetran")
(load "target:compiler/float-tran")
(load "target:compiler/saptran")
(load "vm:macros")
(load "vm:utils")
(load "vm:vm")
(load "vm:insts")
(load "vm:primtype")
(load "vm:move")
(load "vm:sap")
(when (target-featurep :sse2)
(load "vm:sse2-sap"))
(load "vm:system")
(load "vm:char")
(if (target-featurep :sse2)
(load "vm:float-sse2")
(load "vm:float"))
(load "vm:memory")
(load "vm:static-fn")
(load "vm:arith")
(load "vm:cell")
(load "vm:subprim")
(load "vm:debug")
(load "vm:c-call")
(if (target-featurep :sse2)
(load "vm:sse2-c-call")
(load "vm:x87-c-call"))
(load "vm:print")
(load "vm:alloc")
(load "vm:call")
(load "vm:nlx")
(load "vm:values")
(load (if (target-featurep :sse2)
"vm:sse2-array"
"vm:x87-array"))
(load "vm:array")
(load "vm:pred")
(load "vm:type-vops")
(load "assem:assem-rtns")
(load "assem:array")
(load "assem:arith")
(load "assem:alloc")
(load "c:pseudo-vops")
(check-move-function-consistency)
(load "vm:new-genesis")
(setf *features* (remove :building-cross-compiler *features*))
(macrolet ((frob (&rest syms)
`(progn ,@(mapcar #'(lambda (sym)
`(defconstant ,sym
(symbol-value
(find-symbol ,(symbol-name sym)
:vm))))
syms))))
(frob OLD-X86:BYTE-BITS OLD-X86:WORD-BITS
#+long-float OLD-X86:SIMPLE-ARRAY-LONG-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-DOUBLE-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-SINGLE-FLOAT-TYPE
#+long-float OLD-X86:SIMPLE-ARRAY-COMPLEX-LONG-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-COMPLEX-DOUBLE-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-COMPLEX-SINGLE-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-2-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-4-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-8-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-16-TYPE
OLD-X86:SIMPLE-ARRAY-UNSIGNED-BYTE-32-TYPE
OLD-X86:SIMPLE-ARRAY-SIGNED-BYTE-8-TYPE
OLD-X86:SIMPLE-ARRAY-SIGNED-BYTE-16-TYPE
OLD-X86:SIMPLE-ARRAY-SIGNED-BYTE-30-TYPE
OLD-X86:SIMPLE-ARRAY-SIGNED-BYTE-32-TYPE
OLD-X86:SIMPLE-BIT-VECTOR-TYPE
OLD-X86:SIMPLE-STRING-TYPE OLD-X86:SIMPLE-VECTOR-TYPE
OLD-X86:SIMPLE-ARRAY-TYPE OLD-X86:VECTOR-DATA-OFFSET
OLD-X86:DOUBLE-FLOAT-EXPONENT-BYTE
OLD-X86:DOUBLE-FLOAT-NORMAL-EXPONENT-MAX
OLD-X86:DOUBLE-FLOAT-SIGNIFICAND-BYTE
OLD-X86:SINGLE-FLOAT-EXPONENT-BYTE
OLD-X86:SINGLE-FLOAT-NORMAL-EXPONENT-MAX
OLD-X86:SINGLE-FLOAT-SIGNIFICAND-BYTE
)
#+double-double
(frob OLD-X86:SIMPLE-ARRAY-COMPLEX-DOUBLE-DOUBLE-FLOAT-TYPE
OLD-X86:SIMPLE-ARRAY-DOUBLE-DOUBLE-FLOAT-TYPE))
Modular arith hacks
(setf (fdefinition 'vm::ash-left-mod32) #'old-x86::ash-left-mod32)
(setf (fdefinition 'vm::lognot-mod32) #'old-x86::lognot-mod32)
(let ((function (symbol-function 'kernel:error-number-or-lose)))
(let ((*info-environment* (c:backend-info-environment c:*target-backend*)))
(setf (symbol-function 'kernel:error-number-or-lose) function)
(setf (info function kind 'kernel:error-number-or-lose) :function)
(setf (info function where-from 'kernel:error-number-or-lose) :defined)))
(defun fix-class (name)
(let* ((new-value (find-class name))
(new-layout (kernel::%class-layout new-value))
(new-cell (kernel::find-class-cell name))
(*info-environment* (c:backend-info-environment c:*target-backend*)))
(remhash name kernel::*forward-referenced-layouts*)
(kernel::%note-type-defined name)
(setf (info type kind name) :instance)
(setf (info type class name) new-cell)
(setf (info type compiler-layout name) new-layout)
new-value))
(fix-class 'c::vop-parse)
(fix-class 'c::operand-parse)
#+random-mt19937
(declaim (notinline kernel:random-chunk))
(setf c:*backend* c:*target-backend*)
Extern - alien - name for the new backend .
(in-package :vm)
(defun extern-alien-name (name)
(declare (type simple-string name))
name)
(export 'extern-alien-name)
(export 'fixup-code-object)
(export 'sanctify-for-execution)
(in-package :cl-user)
(defparameter *load-stuff* nil)
x86::any - reg as an SC . Do this by adding old - x86::any - reg
(let ((ht (c::backend-sc-names c::*target-backend*)))
(setf (gethash 'old-x86::any-reg ht)
(gethash 'x86::any-reg ht)))
|
7a95663ae9d4bb50cf9ea4b3c65a55888c3aa0eb312fe9e35401866d100b0d3d | jwiegley/notes | FastNub.hs | module FastNub where
import Data.List (nub)
import Data.Set as Set
import Data.Time
fastNub :: Ord a => [a] -> [a]
fastNub = go Set.empty
where
go _ [] = []
go m (y:ys)
| Set.member y m = go m ys
| otherwise = y : go (Set.insert y m) ys
main :: IO ()
main = do
start <- getCurrentTime
print $ take 100 $ nub $ take 100000000 $ cycle [1,1,2,5,3,8,13,21,34]
end <- getCurrentTime
print $ diffUTCTime end start
start <- getCurrentTime
print $ take 100 $ fastNub $ take 100000000 $ cycle [1,1,2,5,3,8,13,21,34]
end <- getCurrentTime
print $ diffUTCTime end start
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/f719a3d41696d48f6005/gists/928ec32184aeb99492a3/FastNub.hs | haskell | module FastNub where
import Data.List (nub)
import Data.Set as Set
import Data.Time
fastNub :: Ord a => [a] -> [a]
fastNub = go Set.empty
where
go _ [] = []
go m (y:ys)
| Set.member y m = go m ys
| otherwise = y : go (Set.insert y m) ys
main :: IO ()
main = do
start <- getCurrentTime
print $ take 100 $ nub $ take 100000000 $ cycle [1,1,2,5,3,8,13,21,34]
end <- getCurrentTime
print $ diffUTCTime end start
start <- getCurrentTime
print $ take 100 $ fastNub $ take 100000000 $ cycle [1,1,2,5,3,8,13,21,34]
end <- getCurrentTime
print $ diffUTCTime end start
| |
d5925b3f4256db96bf134a4b48e3a9378bad5746b04f87d5d1ea8c18c20ae850 | wargrey/w3s | whitespace.rkt | #lang typed/racket/base
(provide (all-defined-out))
(require sgml/xml)
(require "../digitama/stdin.rkt")
(require "../digitama/digicore.rkt")
(require "../digitama/normalize.rkt")
(require "../digitama/tokenizer.rkt")
(require "../digitama/tokenizer/port.rkt")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define tamer-xml:space : (-> Symbol [#:xml:space-filter (Option XML:Space-Filter)] [#:xml:lang String] Char * XML-Syntax-Any)
(lambda [#:xml:space-filter [filter #false] #:xml:lang [xml:lang ""] xml:space . src]
(define ws (tamer-src->token (format "xml:space-~a" xml:space) filter xml:lang src))
(cond [(not (xml:whitespace? ws)) ws]
[(eq? xml:space 'preserve) (xml:space=preserve* '|| ws filter xml:lang)]
[else (tamer-xml:space-default ws filter '|| xml:lang)])))
(define tamer-svg:space : (-> Symbol [#:xml:lang String] Char * XML-Syntax-Any)
(lambda [#:xml:lang [xml:lang ""] xml:space . src]
(define ws (tamer-src->token (format "svg:space-~a" xml:space) svg:space-filter xml:lang src))
(cond [(not (xml:whitespace? ws)) ws]
[(eq? xml:space 'preserve) (xml:space=preserve* '|| ws svg:space-filter xml:lang)]
[else (tamer-xml:space-default ws svg:space-filter '|| xml:lang)])))
(define tamer-src->token : (-> (U Symbol String) (Option XML:Space-Filter) String (Listof Char) XML-Syntax-Any)
(lambda [portname filter xml:lang src]
(define-values (/dev/xmlin version encoding standalone?)
(xml-open-input-port
(open-input-string (string-append "<space>"
(list->string src)
"</space>"))
#true))
(let*-values ([(< status) (xml-consume-token* /dev/xmlin portname (cons xml-consume-token:* 1))]
[(space status) (xml-consume-token* /dev/xmlin portname status)]
[(> status) (xml-consume-token* /dev/xmlin portname status)]
[(ws status) (xml-consume-token* /dev/xmlin portname status)])
(and (xml-token? ws) ws))))
(define tamer-xml:space-default : (-> XML:WhiteSpace (Option XML:Space-Filter) Symbol String XML-Syntax-Any)
(lambda [ws filter tag xml:lang]
(assert (car (xml-child-cons* (list ws) (list ws) filter tag xml:lang))
xml:whitespace?)))
(module+ main
(require "normalize.txml")
(tamer-xml:space 'preserve
#\return #\newline
#\newline
#\return)
(tamer-svg:space 'default
#\return #\newline
#\newline
#\return)
(tamer-svg:space 'preserve
#\return #\newline
#\newline
#\return)
normalize.xml
NOTE : Plain APIs does not support , so do n't be surprised entity references are not expanded properly .
(xml-document-normalize #:xml:space 'default #:xml:space-filter svg:space-filter
(read-xml-document (assert (xml-doc-location normalize.xml) string?))))
| null | https://raw.githubusercontent.com/wargrey/w3s/9483c427b45615dd9d4d450a63f7f81aaf98c780/sgml/tamer/whitespace.rkt | racket | #lang typed/racket/base
(provide (all-defined-out))
(require sgml/xml)
(require "../digitama/stdin.rkt")
(require "../digitama/digicore.rkt")
(require "../digitama/normalize.rkt")
(require "../digitama/tokenizer.rkt")
(require "../digitama/tokenizer/port.rkt")
(define tamer-xml:space : (-> Symbol [#:xml:space-filter (Option XML:Space-Filter)] [#:xml:lang String] Char * XML-Syntax-Any)
(lambda [#:xml:space-filter [filter #false] #:xml:lang [xml:lang ""] xml:space . src]
(define ws (tamer-src->token (format "xml:space-~a" xml:space) filter xml:lang src))
(cond [(not (xml:whitespace? ws)) ws]
[(eq? xml:space 'preserve) (xml:space=preserve* '|| ws filter xml:lang)]
[else (tamer-xml:space-default ws filter '|| xml:lang)])))
(define tamer-svg:space : (-> Symbol [#:xml:lang String] Char * XML-Syntax-Any)
(lambda [#:xml:lang [xml:lang ""] xml:space . src]
(define ws (tamer-src->token (format "svg:space-~a" xml:space) svg:space-filter xml:lang src))
(cond [(not (xml:whitespace? ws)) ws]
[(eq? xml:space 'preserve) (xml:space=preserve* '|| ws svg:space-filter xml:lang)]
[else (tamer-xml:space-default ws svg:space-filter '|| xml:lang)])))
(define tamer-src->token : (-> (U Symbol String) (Option XML:Space-Filter) String (Listof Char) XML-Syntax-Any)
(lambda [portname filter xml:lang src]
(define-values (/dev/xmlin version encoding standalone?)
(xml-open-input-port
(open-input-string (string-append "<space>"
(list->string src)
"</space>"))
#true))
(let*-values ([(< status) (xml-consume-token* /dev/xmlin portname (cons xml-consume-token:* 1))]
[(space status) (xml-consume-token* /dev/xmlin portname status)]
[(> status) (xml-consume-token* /dev/xmlin portname status)]
[(ws status) (xml-consume-token* /dev/xmlin portname status)])
(and (xml-token? ws) ws))))
(define tamer-xml:space-default : (-> XML:WhiteSpace (Option XML:Space-Filter) Symbol String XML-Syntax-Any)
(lambda [ws filter tag xml:lang]
(assert (car (xml-child-cons* (list ws) (list ws) filter tag xml:lang))
xml:whitespace?)))
(module+ main
(require "normalize.txml")
(tamer-xml:space 'preserve
#\return #\newline
#\newline
#\return)
(tamer-svg:space 'default
#\return #\newline
#\newline
#\return)
(tamer-svg:space 'preserve
#\return #\newline
#\newline
#\return)
normalize.xml
NOTE : Plain APIs does not support , so do n't be surprised entity references are not expanded properly .
(xml-document-normalize #:xml:space 'default #:xml:space-filter svg:space-filter
(read-xml-document (assert (xml-doc-location normalize.xml) string?))))
| |
73bbd38ae8392fbc426eeb8fdc2ed2704f114e60812bfeba29cccf73a79c4d6e | krisajenkins/BellRinger | Render.hs | module Render (rootView) where
import GHC.Exts (sortWith)
import HTML
import Data.Maybe
import Messages
import MarketData
import Prelude hiding (div,id,span)
import Virtual
marketDataGraph :: [Market] -> HTML
marketDataGraph rows =
svg (Size "100%" "200px")
(zipWith (curry f)
[(0 :: Int) ..]
rows)
where count = length rows
closes = mapMaybe close rows
highest = maximum closes
f (n,r) =
rect (Size (show w ++ "%")
(show h ++ "%"))
(Position (show x ++ "%")
(show y ++ "%"))
where w, h, x, y :: Double
x = 100.0 * fromIntegral n / fromIntegral count
y = 100 - h
w = 100 / fromIntegral count
h =
100.0 *
fromMaybe 0 (close r) /
highest
marketDataView :: (Market -> Bool) -> Pending [Market] -> HTML
marketDataView _ NotRequested = span "No data loaded yet. (Press the AJAX button!)"
marketDataView _ NotFound = span "Data not found. Sadness."
marketDataView _ Loading = span "Loading marketData...please wait."
marketDataView _ (LoadFailed e) = span ("Loading marketData failed: " ++ e)
marketDataView filterFn (Loaded rows) =
vnode "div"
[marketDataGraph filteredRows,simpleTable marketTableDef filteredRows]
where filteredRows =
sortWith symbol $
filter filterFn rows
showMaybe :: Show a => String -> Maybe a -> String
showMaybe d Nothing = d
showMaybe _ (Just s) = show s
marketTableDef :: TableDef Market
marketTableDef =
[("Latest Trade",show . time . latest_trade)
,("Symbol",symbol)
,("Bid"
,showMaybe "-" .
bid)
,("Ask"
,showMaybe "-" .
ask)
,("High"
,showMaybe "-" .
high)
,("Low"
,showMaybe "-" .
low)
,("Close"
,showMaybe "-" .
close)
,("Volume"
,showMaybe "-" .
volume)
,("Currency Volume"
,\x ->
currency x ++
" " ++
showMaybe "-" (fmap floor (currency_volume x) :: Maybe Integer))]
msgButton :: (Message -> IO ()) -> Message -> String -> HTML
msgButton send msg =
vbutton "button.btn.btn-primary" (\_ -> send msg)
marketControls :: (Message -> IO ()) -> Pending [Market] -> HTML
marketControls send (Loaded _) =
vnode "div"
[msgButton send (FilterCurrency (Just "USD")) "USD"
,msgButton send (FilterCurrency (Just "GBP")) "GBP"
,msgButton send (FilterCurrency Nothing) "All"]
marketControls send _ =
vnode "div" [msgButton send FetchMarket "AJAX"]
controls :: (Message -> IO ()) -> Pending [Market] -> HTML
controls send marketData =
vnode "div"
([msgButton send (IncFst 5) "+(5, 0)"
,msgButton send (IncSnd 3) "+(0, 3)"
,msgButton send (IncBoth 1 2) "+(1, 2)"] ++
[marketControls send marketData])
rootView :: (Message -> IO ()) -> World -> HTML
rootView send (a,b,filterFn,marketData) =
vnode "div.container"
[navbar [vtext "div.navbar-brand" "Demo"]
,row [col3 [controls send marketData],col9 [well [span (show (a,b))]]]
,row [col12 [well [marketDataView filterFn marketData]]]]
| null | https://raw.githubusercontent.com/krisajenkins/BellRinger/2cf4e4641862e478874c4414ac4050c4fd03641f/src/Render.hs | haskell | module Render (rootView) where
import GHC.Exts (sortWith)
import HTML
import Data.Maybe
import Messages
import MarketData
import Prelude hiding (div,id,span)
import Virtual
marketDataGraph :: [Market] -> HTML
marketDataGraph rows =
svg (Size "100%" "200px")
(zipWith (curry f)
[(0 :: Int) ..]
rows)
where count = length rows
closes = mapMaybe close rows
highest = maximum closes
f (n,r) =
rect (Size (show w ++ "%")
(show h ++ "%"))
(Position (show x ++ "%")
(show y ++ "%"))
where w, h, x, y :: Double
x = 100.0 * fromIntegral n / fromIntegral count
y = 100 - h
w = 100 / fromIntegral count
h =
100.0 *
fromMaybe 0 (close r) /
highest
marketDataView :: (Market -> Bool) -> Pending [Market] -> HTML
marketDataView _ NotRequested = span "No data loaded yet. (Press the AJAX button!)"
marketDataView _ NotFound = span "Data not found. Sadness."
marketDataView _ Loading = span "Loading marketData...please wait."
marketDataView _ (LoadFailed e) = span ("Loading marketData failed: " ++ e)
marketDataView filterFn (Loaded rows) =
vnode "div"
[marketDataGraph filteredRows,simpleTable marketTableDef filteredRows]
where filteredRows =
sortWith symbol $
filter filterFn rows
showMaybe :: Show a => String -> Maybe a -> String
showMaybe d Nothing = d
showMaybe _ (Just s) = show s
marketTableDef :: TableDef Market
marketTableDef =
[("Latest Trade",show . time . latest_trade)
,("Symbol",symbol)
,("Bid"
,showMaybe "-" .
bid)
,("Ask"
,showMaybe "-" .
ask)
,("High"
,showMaybe "-" .
high)
,("Low"
,showMaybe "-" .
low)
,("Close"
,showMaybe "-" .
close)
,("Volume"
,showMaybe "-" .
volume)
,("Currency Volume"
,\x ->
currency x ++
" " ++
showMaybe "-" (fmap floor (currency_volume x) :: Maybe Integer))]
msgButton :: (Message -> IO ()) -> Message -> String -> HTML
msgButton send msg =
vbutton "button.btn.btn-primary" (\_ -> send msg)
marketControls :: (Message -> IO ()) -> Pending [Market] -> HTML
marketControls send (Loaded _) =
vnode "div"
[msgButton send (FilterCurrency (Just "USD")) "USD"
,msgButton send (FilterCurrency (Just "GBP")) "GBP"
,msgButton send (FilterCurrency Nothing) "All"]
marketControls send _ =
vnode "div" [msgButton send FetchMarket "AJAX"]
controls :: (Message -> IO ()) -> Pending [Market] -> HTML
controls send marketData =
vnode "div"
([msgButton send (IncFst 5) "+(5, 0)"
,msgButton send (IncSnd 3) "+(0, 3)"
,msgButton send (IncBoth 1 2) "+(1, 2)"] ++
[marketControls send marketData])
rootView :: (Message -> IO ()) -> World -> HTML
rootView send (a,b,filterFn,marketData) =
vnode "div.container"
[navbar [vtext "div.navbar-brand" "Demo"]
,row [col3 [controls send marketData],col9 [well [span (show (a,b))]]]
,row [col12 [well [marketDataView filterFn marketData]]]]
| |
4a3e18cefe0cd20dd95a8c59ce796df52fa4a30acee89d8e858c68efaea8a5c4 | Stand-In-Language/stand-in-language | LLVM.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
module MemoryBench.LLVM where
import LLVM.AST hiding (Module)
import qualified LLVM.AST as AST
import LLVM.AST.AddrSpace
import LLVM.AST.CallingConvention
import LLVM.AST.Constant
import LLVM.AST.DataLayout
import LLVM.AST.DLL
import LLVM.AST.Float
import LLVM.AST.FloatingPointPredicate hiding (True)
import LLVM.AST.InlineAssembly
import LLVM.AST.IntegerPredicate
import LLVM.AST.Linkage
import LLVM.AST.ParameterAttribute
import LLVM.AST.RMWOperation
import LLVM.AST.ThreadLocalStorage
import LLVM.AST.Type hiding (void)
import LLVM.AST.Visibility
import LLVM.Context
import LLVM.Module hiding (Module)
import LLVM.AST.COMDAT
import LLVM.AST.FunctionAttribute
import LLVM.AST.Operand hiding (Module)
import qualified LLVM.AST.Operand as AST
import qualified LLVM.Internal.FFI.OrcJIT.CompileLayer as OJ.I
import qualified LLVM.Internal.OrcJIT.IRCompileLayer as OJ.I
import qualified LLVM.Internal.OrcJIT.LinkingLayer as OJ.I
import qualified LLVM.Linking as Linking
import qualified LLVM.OrcJIT as OJ
import qualified LLVM.OrcJIT.CompileLayer as OJ
import qualified LLVM.CodeGenOpt as CodeGenOpt
import qualified LLVM.CodeModel as CodeModel
import LLVM.Internal.Attribute
import LLVM.Internal.Coding
import LLVM.Internal.Context
import LLVM.Internal.EncodeAST
import LLVM.Internal.Function
import LLVM.Internal.Global
import LLVM.Internal.Module
import LLVM.Internal.Type
import qualified LLVM.Internal.Target as Target
import qualified LLVM.Relocation as Reloc
import qualified LLVM.Target as Target
import qualified LLVM.AST as A
import qualified LLVM.AST.AddrSpace as A
import qualified LLVM.AST.DataLayout as A
import qualified LLVM.AST.Global as A.G
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.State.Class
import qualified Data.ByteString as B
import Data.Foldable
import qualified Data.Map as Map
import Debug.Trace
import Foreign.C.String
import Foreign.Ptr
import Naturals
import Telomare
import qualified Telomare.Llvm as LLVM
import Weigh
instance NFData DataLayout
instance NFData Endianness
instance NFData Mangling
instance NFData AddrSpace
instance NFData AlignmentInfo
instance NFData AlignType
instance NFData Definition
instance NFData Global
instance NFData Linkage
instance NFData Visibility
instance NFData StorageClass
instance NFData Model
instance NFData UnnamedAddr
instance NFData CallingConvention
instance NFData ParameterAttribute
instance NFData Parameter
instance NFData BasicBlock
instance NFData Constant
instance NFData SomeFloat
instance NFData IntegerPredicate
instance NFData FloatingPointPredicate
instance NFData Type
instance NFData FloatingPointType
instance NFData a => NFData (Named a)
instance NFData Instruction
instance NFData FastMathFlags
instance NFData SynchronizationScope
instance NFData Terminator
instance NFData MemoryOrdering
instance NFData RMWOperation
instance NFData InlineAssembly
instance NFData TailCallKind
instance NFData Dialect
instance NFData LandingPadClause
instance (NFData a) => NFData (MDRef a)
instance NFData MDNode
instance NFData DINode
instance NFData DIObjCProperty
instance NFData DIVariable
instance NFData DIMacroNode
instance NFData DIMacroInfo
instance NFData DILocation
instance NFData DILocalScope
instance NFData DILexicalBlockBase
instance NFData DIScope
instance NFData DINamespace
instance NFData DIModule
instance NFData DICompileUnit
instance NFData DIImportedEntity
instance NFData ImportedEntityTag
instance NFData DebugEmissionKind
instance NFData DIGlobalVariableExpression
instance NFData DIGlobalVariable
instance NFData ChecksumKind
instance NFData DIType
instance NFData DIDerivedType
instance NFData DerivedTypeTag
instance NFData DIBasicType
instance NFData BasicTypeTag
instance NFData DICompositeType
instance NFData DITemplateParameter
instance NFData DIEnumerator
instance NFData TemplateValueParameterTag
instance NFData DISubprogram
instance NFData DILocalVariable
instance NFData Virtuality
instance NFData DISubroutineType
instance NFData DIFlag
instance NFData DIAccessibility
instance NFData DIInheritance
instance NFData DISubrange
instance NFData Encoding
instance NFData DIFile
instance NFData DIExpression
instance NFData DWOp
instance NFData DWOpFragment
instance NFData Name
instance NFData MetadataNodeID
instance NFData Metadata
instance NFData Operand
instance NFData GroupID
instance NFData FunctionAttribute
instance NFData SelectionKind
instance NFData AST.Module
instance NFData Context where
rnf (Context ptr) = rnf ptr
instance NFData Module where
rnf (Module ioref) = rnf ioref
instance NFData Target.TargetMachine where
rnf (Target.TargetMachine ptr) = rnf ptr
instance NFData OJ.ObjectLinkingLayer where
rnf (OJ.I.ObjectLinkingLayer ptr ioref) = rnf ptr `seq` rnf ioref
instance NFData OJ.ModuleHandle where
rnf (OJ.I.ModuleHandle w) = rnf w
instance NFData (OJ.IRCompileLayer a) where
rnf (OJ.I.IRCompileLayer ptr1 ptr2 ioref) = rnf ptr1 `seq` rnf ptr2 `seq` rnf ioref
benchLLVMDetails :: IExpr -> Weigh ()
benchLLVMDetails iexpr = do
let wrap_iexpr = SetEnv (Pair (Defer iexpr) Zero)
lmod = LLVM.makeModule $ toNExpr wrap_iexpr
sequence_ [ func "---------------" id ()
, benchModule lmod
]
benchModule :: AST.Module -> Weigh ()
benchModule amod = do
let moduleFromAST = do
b <- Linking.loadLibraryPermanently Nothing
withContext $ \ctx ->
withModuleFromAST ctx amod $ \mod -> return ()
action "withModuleFromAST" moduleFromAST
| null | https://raw.githubusercontent.com/Stand-In-Language/stand-in-language/20c86eb506eeec07adb61dc7bfe23b0c21e6ab93/bench/MemoryBench/LLVM.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
module MemoryBench.LLVM where
import LLVM.AST hiding (Module)
import qualified LLVM.AST as AST
import LLVM.AST.AddrSpace
import LLVM.AST.CallingConvention
import LLVM.AST.Constant
import LLVM.AST.DataLayout
import LLVM.AST.DLL
import LLVM.AST.Float
import LLVM.AST.FloatingPointPredicate hiding (True)
import LLVM.AST.InlineAssembly
import LLVM.AST.IntegerPredicate
import LLVM.AST.Linkage
import LLVM.AST.ParameterAttribute
import LLVM.AST.RMWOperation
import LLVM.AST.ThreadLocalStorage
import LLVM.AST.Type hiding (void)
import LLVM.AST.Visibility
import LLVM.Context
import LLVM.Module hiding (Module)
import LLVM.AST.COMDAT
import LLVM.AST.FunctionAttribute
import LLVM.AST.Operand hiding (Module)
import qualified LLVM.AST.Operand as AST
import qualified LLVM.Internal.FFI.OrcJIT.CompileLayer as OJ.I
import qualified LLVM.Internal.OrcJIT.IRCompileLayer as OJ.I
import qualified LLVM.Internal.OrcJIT.LinkingLayer as OJ.I
import qualified LLVM.Linking as Linking
import qualified LLVM.OrcJIT as OJ
import qualified LLVM.OrcJIT.CompileLayer as OJ
import qualified LLVM.CodeGenOpt as CodeGenOpt
import qualified LLVM.CodeModel as CodeModel
import LLVM.Internal.Attribute
import LLVM.Internal.Coding
import LLVM.Internal.Context
import LLVM.Internal.EncodeAST
import LLVM.Internal.Function
import LLVM.Internal.Global
import LLVM.Internal.Module
import LLVM.Internal.Type
import qualified LLVM.Internal.Target as Target
import qualified LLVM.Relocation as Reloc
import qualified LLVM.Target as Target
import qualified LLVM.AST as A
import qualified LLVM.AST.AddrSpace as A
import qualified LLVM.AST.DataLayout as A
import qualified LLVM.AST.Global as A.G
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.State.Class
import qualified Data.ByteString as B
import Data.Foldable
import qualified Data.Map as Map
import Debug.Trace
import Foreign.C.String
import Foreign.Ptr
import Naturals
import Telomare
import qualified Telomare.Llvm as LLVM
import Weigh
instance NFData DataLayout
instance NFData Endianness
instance NFData Mangling
instance NFData AddrSpace
instance NFData AlignmentInfo
instance NFData AlignType
instance NFData Definition
instance NFData Global
instance NFData Linkage
instance NFData Visibility
instance NFData StorageClass
instance NFData Model
instance NFData UnnamedAddr
instance NFData CallingConvention
instance NFData ParameterAttribute
instance NFData Parameter
instance NFData BasicBlock
instance NFData Constant
instance NFData SomeFloat
instance NFData IntegerPredicate
instance NFData FloatingPointPredicate
instance NFData Type
instance NFData FloatingPointType
instance NFData a => NFData (Named a)
instance NFData Instruction
instance NFData FastMathFlags
instance NFData SynchronizationScope
instance NFData Terminator
instance NFData MemoryOrdering
instance NFData RMWOperation
instance NFData InlineAssembly
instance NFData TailCallKind
instance NFData Dialect
instance NFData LandingPadClause
instance (NFData a) => NFData (MDRef a)
instance NFData MDNode
instance NFData DINode
instance NFData DIObjCProperty
instance NFData DIVariable
instance NFData DIMacroNode
instance NFData DIMacroInfo
instance NFData DILocation
instance NFData DILocalScope
instance NFData DILexicalBlockBase
instance NFData DIScope
instance NFData DINamespace
instance NFData DIModule
instance NFData DICompileUnit
instance NFData DIImportedEntity
instance NFData ImportedEntityTag
instance NFData DebugEmissionKind
instance NFData DIGlobalVariableExpression
instance NFData DIGlobalVariable
instance NFData ChecksumKind
instance NFData DIType
instance NFData DIDerivedType
instance NFData DerivedTypeTag
instance NFData DIBasicType
instance NFData BasicTypeTag
instance NFData DICompositeType
instance NFData DITemplateParameter
instance NFData DIEnumerator
instance NFData TemplateValueParameterTag
instance NFData DISubprogram
instance NFData DILocalVariable
instance NFData Virtuality
instance NFData DISubroutineType
instance NFData DIFlag
instance NFData DIAccessibility
instance NFData DIInheritance
instance NFData DISubrange
instance NFData Encoding
instance NFData DIFile
instance NFData DIExpression
instance NFData DWOp
instance NFData DWOpFragment
instance NFData Name
instance NFData MetadataNodeID
instance NFData Metadata
instance NFData Operand
instance NFData GroupID
instance NFData FunctionAttribute
instance NFData SelectionKind
instance NFData AST.Module
instance NFData Context where
rnf (Context ptr) = rnf ptr
instance NFData Module where
rnf (Module ioref) = rnf ioref
instance NFData Target.TargetMachine where
rnf (Target.TargetMachine ptr) = rnf ptr
instance NFData OJ.ObjectLinkingLayer where
rnf (OJ.I.ObjectLinkingLayer ptr ioref) = rnf ptr `seq` rnf ioref
instance NFData OJ.ModuleHandle where
rnf (OJ.I.ModuleHandle w) = rnf w
instance NFData (OJ.IRCompileLayer a) where
rnf (OJ.I.IRCompileLayer ptr1 ptr2 ioref) = rnf ptr1 `seq` rnf ptr2 `seq` rnf ioref
benchLLVMDetails :: IExpr -> Weigh ()
benchLLVMDetails iexpr = do
let wrap_iexpr = SetEnv (Pair (Defer iexpr) Zero)
lmod = LLVM.makeModule $ toNExpr wrap_iexpr
sequence_ [ func "---------------" id ()
, benchModule lmod
]
benchModule :: AST.Module -> Weigh ()
benchModule amod = do
let moduleFromAST = do
b <- Linking.loadLibraryPermanently Nothing
withContext $ \ctx ->
withModuleFromAST ctx amod $ \mod -> return ()
action "withModuleFromAST" moduleFromAST
|
b0cdd0d50f2ee04d59057ebca8ed5dfdb0e2de8f67f1a4336d5e2e375367665f | 8treenet/xy_server | gateway_server.erl | %%%--------------------------------------
%%% @Module : gateway_server
@Author : ys
@Email :
@Created :
%%% @Description: 网关服务器
%%%--------------------------------------
-module(gateway_server).
-behaviour(gen_server).
-export([start_link/1,init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
%% ====================================================================
%% API functions
%% ====================================================================
-export([]).
%% ====================================================================
%% Behavioural functions
%% ====================================================================
-record(state, {}).
%% init/1
%% ====================================================================
@doc < a href=" / doc / man / gen_server.html#Module : : init/1</a >
-spec init(Args :: term()) -> Result when
Result :: {ok, State}
| {ok, State, Timeout}
| {ok, State, hibernate}
| {stop, Reason :: term()}
| ignore,
State :: term(),
Timeout :: non_neg_integer() | infinity.
%% ====================================================================
init([LogicNode,Port]) ->
process_flag(trap_exit, true),
gen_server:cast({gateway_mod,LogicNode},{register_gateway, node()}),
network_lib:start([LogicNode,Port,game_server]),
{ok, #state{}}.
%% handle_call/3
%% ====================================================================
%% @doc <a href="#Module:handle_call-3">gen_server:handle_call/3</a>
-spec handle_call(Request :: term(), From :: {pid(), Tag :: term()}, State :: term()) -> Result when
Result :: {reply, Reply, NewState}
| {reply, Reply, NewState, Timeout}
| {reply, Reply, NewState, hibernate}
| {noreply, NewState}
| {noreply, NewState, Timeout}
| {noreply, NewState, hibernate}
| {stop, Reason, Reply, NewState}
| {stop, Reason, NewState},
Reply :: term(),
NewState :: term(),
Timeout :: non_neg_integer() | infinity,
Reason :: term().
%% ====================================================================
handle_call(Request, From, State) ->
Reply = ok,
{reply, Reply, State}.
%% handle_cast/2
%% ====================================================================
%% @doc <a href="#Module:handle_cast-2">gen_server:handle_cast/2</a>
-spec handle_cast(Request :: term(), State :: term()) -> Result when
Result :: {noreply, NewState}
| {noreply, NewState, Timeout}
| {noreply, NewState, hibernate}
| {stop, Reason :: term(), NewState},
NewState :: term(),
Timeout :: non_neg_integer() | infinity.
%% ====================================================================
handle_cast({player_send,PID,Bin}, State) ->
network_lib:send(PID, Bin),
{noreply, State};
handle_cast(Msg, State) ->
{noreply, State}.
%% handle_info/2
%% ====================================================================
%% @doc <a href="#Module:handle_info-2">gen_server:handle_info/2</a>
-spec handle_info(Info :: timeout | term(), State :: term()) -> Result when
Result :: {noreply, NewState}
| {noreply, NewState, Timeout}
| {noreply, NewState, hibernate}
| {stop, Reason :: term(), NewState},
NewState :: term(),
Timeout :: non_neg_integer() | infinity.
%% ====================================================================
handle_info(Info, State) ->
{noreply, State}.
%% terminate/2
%% ====================================================================
%% @doc <a href="#Module:terminate-2">gen_server:terminate/2</a>
-spec terminate(Reason, State :: term()) -> Any :: term() when
Reason :: normal
| shutdown
| {shutdown, term()}
| term().
%% ====================================================================
terminate(Reason, State) ->
ok.
%% code_change/3
%% ====================================================================
%% @doc <a href="#Module:code_change-3">gen_server:code_change/3</a>
-spec code_change(OldVsn, State :: term(), Extra :: term()) -> Result when
Result :: {ok, NewState :: term()} | {error, Reason :: term()},
OldVsn :: Vsn | {down, Vsn},
Vsn :: term().
%% ====================================================================
code_change(OldVsn, State, Extra) ->
{ok, State}.
%% ====================================================================
Internal functions
%% ====================================================================
start_link(Permanent)->
gen_server:start_link({local,?MODULE},?MODULE, Permanent, []). | null | https://raw.githubusercontent.com/8treenet/xy_server/352679e01eb4a26433ccbec513fbd282307a33bd/src/gateway_server.erl | erlang | --------------------------------------
@Module : gateway_server
@Description: 网关服务器
--------------------------------------
====================================================================
API functions
====================================================================
====================================================================
Behavioural functions
====================================================================
init/1
====================================================================
====================================================================
handle_call/3
====================================================================
@doc <a href="#Module:handle_call-3">gen_server:handle_call/3</a>
====================================================================
handle_cast/2
====================================================================
@doc <a href="#Module:handle_cast-2">gen_server:handle_cast/2</a>
====================================================================
handle_info/2
====================================================================
@doc <a href="#Module:handle_info-2">gen_server:handle_info/2</a>
====================================================================
terminate/2
====================================================================
@doc <a href="#Module:terminate-2">gen_server:terminate/2</a>
====================================================================
code_change/3
====================================================================
@doc <a href="#Module:code_change-3">gen_server:code_change/3</a>
====================================================================
====================================================================
==================================================================== | @Author : ys
@Email :
@Created :
-module(gateway_server).
-behaviour(gen_server).
-export([start_link/1,init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([]).
-record(state, {}).
@doc < a href=" / doc / man / gen_server.html#Module : : init/1</a >
-spec init(Args :: term()) -> Result when
Result :: {ok, State}
| {ok, State, Timeout}
| {ok, State, hibernate}
| {stop, Reason :: term()}
| ignore,
State :: term(),
Timeout :: non_neg_integer() | infinity.
init([LogicNode,Port]) ->
process_flag(trap_exit, true),
gen_server:cast({gateway_mod,LogicNode},{register_gateway, node()}),
network_lib:start([LogicNode,Port,game_server]),
{ok, #state{}}.
-spec handle_call(Request :: term(), From :: {pid(), Tag :: term()}, State :: term()) -> Result when
Result :: {reply, Reply, NewState}
| {reply, Reply, NewState, Timeout}
| {reply, Reply, NewState, hibernate}
| {noreply, NewState}
| {noreply, NewState, Timeout}
| {noreply, NewState, hibernate}
| {stop, Reason, Reply, NewState}
| {stop, Reason, NewState},
Reply :: term(),
NewState :: term(),
Timeout :: non_neg_integer() | infinity,
Reason :: term().
handle_call(Request, From, State) ->
Reply = ok,
{reply, Reply, State}.
-spec handle_cast(Request :: term(), State :: term()) -> Result when
Result :: {noreply, NewState}
| {noreply, NewState, Timeout}
| {noreply, NewState, hibernate}
| {stop, Reason :: term(), NewState},
NewState :: term(),
Timeout :: non_neg_integer() | infinity.
handle_cast({player_send,PID,Bin}, State) ->
network_lib:send(PID, Bin),
{noreply, State};
handle_cast(Msg, State) ->
{noreply, State}.
-spec handle_info(Info :: timeout | term(), State :: term()) -> Result when
Result :: {noreply, NewState}
| {noreply, NewState, Timeout}
| {noreply, NewState, hibernate}
| {stop, Reason :: term(), NewState},
NewState :: term(),
Timeout :: non_neg_integer() | infinity.
handle_info(Info, State) ->
{noreply, State}.
-spec terminate(Reason, State :: term()) -> Any :: term() when
Reason :: normal
| shutdown
| {shutdown, term()}
| term().
terminate(Reason, State) ->
ok.
-spec code_change(OldVsn, State :: term(), Extra :: term()) -> Result when
Result :: {ok, NewState :: term()} | {error, Reason :: term()},
OldVsn :: Vsn | {down, Vsn},
Vsn :: term().
code_change(OldVsn, State, Extra) ->
{ok, State}.
Internal functions
start_link(Permanent)->
gen_server:start_link({local,?MODULE},?MODULE, Permanent, []). |
33e6a109db673e1c3ea9662ad1039b0004763774e3b64770bd19f89da0960286 | herd/herdtools7 | semExtra.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2010 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(** Centralized definition for types to be included by the XXXSem *)
(* Some configuration *)
module type Config = sig
val verbose : int
val optace : OptAce.t
val debug : Debug_herd.t
val precision : Precision.t
val variant : Variant.t -> bool
val endian : Endian.t option
module PC : PrettyConf.S
end
module type S = sig
module O : Config (* Options, for Sem consumer *)
module A : Arch_herd.S
module E : Event.S with module A = A and module Act.A = A
module M : Monad.S
with module A = A and module E = E and type evt_struct = E.event_structure
module Cons : Constraints.S with module A = A
(* Report some flags *)
val do_deps : bool
(* A good place to (re)define all these types *)
type cst = A.V.Cst.v
type v = A.V.v
type proc = A.proc
type instruction = A.instruction
type global_loc = A.global_loc
type location = A.location
type state = A.state
type final_state = A.final_state
type program = A.program
type prop = A.prop
type constr = A.constr
type nice_prog = A.nice_prog
type start_points = A.start_points
type code_segment = A.code_segment
type proc_info = Test_herd.proc_info
type test =
(program, nice_prog, start_points, code_segment,
state, A.size_env, A.type_env,
prop, location, A.RLocSet.t, A.FaultAtomSet.t) Test_herd.t
val size_env : test -> A.size_env
val type_env : test -> A.type_env
(* Get sets of locations observed in outcomes *)
type loc_set = A.LocSet.t
type rloc_set = A.RLocSet.t
val observed_rlocations : test -> rloc_set
(* Notice, array rlocations are expanded to the locations of
their elements *)
val observed_locations : test -> loc_set
val displayed_rlocations : test -> rloc_set
val is_non_mixed_symbol : test -> Constant.symbol -> bool
(* "Exported" labels, i.e. labels that can find their way to registers *)
(* In initial state *)
val get_exported_labels_init : test -> Label.Full.Set.t
(* In code *)
val get_exported_labels_code : test -> Label.Full.Set.t
(* Both of them *)
val get_exported_labels : test -> Label.Full.Set.t
type event = E.event
type event_structure = E.event_structure
type event_set = E.EventSet.t
type event_rel = E.EventRel.t
val tr : event_rel -> event_rel
val rt : event_rel -> event_rel
val restrict :
(event -> bool) -> (event -> bool) ->
event_rel -> event_rel
val doWW : event_rel -> event_rel
val doWR : event_rel -> event_rel
val doRR : event_rel -> event_rel
val doRW : event_rel -> event_rel
val seq : event_rel -> event_rel -> event_rel
val seqs : event_rel list -> event_rel
val union : event_rel -> event_rel -> event_rel
val union3 : event_rel -> event_rel -> event_rel -> event_rel
val unions : event_rel list -> event_rel
(* relations packed to be shown on graphs *)
type rel_pp = (string * event_rel) list
type set_pp = event_set StringMap.t
(* Dependencies : ie complement for ace *)
type procrels =
{ addr : event_rel;
data : event_rel;
depend : event_rel;
data_commit : event_rel;
ctrl : event_rel;
ctrlisync : event_rel;
success : event_rel;
rf : event_rel;
tst: event_rel; }
(*********)
(*********)
type write_to =
| Final of location
| Load of event
type read_from =
| Init
| Store of event
val write_to_compare : write_to -> write_to -> int
val read_from_compare : read_from -> read_from -> int
val read_from_equal : read_from -> read_from -> bool
val event_rf_equal : event -> read_from -> bool
module RFMap : Map.S with type key = write_to
type rfmap = read_from RFMap.t
For pretty print , string arg is like the one of String.concat
val pp_rfmap :
out_channel -> string ->
(out_channel -> write_to -> read_from -> unit) ->
rfmap -> unit
val for_all_in_rfmap : (write_to -> read_from -> bool) -> rfmap -> bool
val simplify_vars_in_rfmap : A.V.solution -> rfmap -> rfmap
(**************************************)
Complete , concrete event structure
(**************************************)
type concrete =
{
str : event_structure ; (* event structure proper *)
rfmap : rfmap ; (* rfmap *)
fs : state * A.FaultSet.t ; (* final state *)
program order ( in fact )
pos : event_rel ; (* Same location same processor accesses *)
(* Write serialization precursor ie uniproc induced constraints over writes *)
pco : event_rel ;
View before relation deduced from
store_load_vbf : event_rel ; (* stores preceed their loads *)
init_load_vbf : event_rel; (* load from init preceed all stores *)
last_store_vbf : event_rel; (* stores to final state come last *)
atomic_load_store : event_rel; (* eg load-and-link/store conditional *)
}
val conc_zero : concrete
(************)
(* Branches *)
(************)
module B : Branch.S
with type reg = A.reg and type v = v and type 'a monad = 'a M.t
type branch = B.t
val tgt2tgt : A.inst_instance_id -> BranchTarget.t -> B.tgt
val gone_toofar : concrete -> bool
(************)
Barriers
(************)
(* barrier + cumulativity *)
type barrier = A.barrier
type pp_barrier = { barrier:barrier ; pp:string; }
end
module Make(C:Config) (A:Arch_herd.S) (Act:Action.S with module A = A)
: (S with module A = A and module E.Act = Act) =
struct
module O = C
module A = A
module V = A.V
module E = Event.Make(C)(A)(Act)
module CEM = struct (* Configure event monads *)
let hexa = C.PC.hexa
let debug = C.debug
let variant = C.variant
end
module M = EventsMonad.Make(CEM)(A)(E)
module Cons = Constraints.Make (C.PC)(A)
let do_deps = C.variant Variant.Deps
(* A good place to (re)define all these types *)
type cst = A.V.Cst.v
type v = A.V.v
type proc = A.proc
type instruction = A.instruction
type global_loc = A.global_loc
type location = A.location
type state = A.state
type final_state = A.final_state
type prop = A.prop
type constr = A.constr
type program = A.program
type nice_prog = A.nice_prog
type start_points = A.start_points
type code_segment = A.code_segment
type proc_info = Test_herd.proc_info
type test =
(program, nice_prog, start_points, code_segment, state,
A.size_env, A.type_env,
prop, location, A.RLocSet.t, A.FaultAtomSet.t) Test_herd.t
let size_env t = t.Test_herd.size_env
and type_env t = t.Test_herd.type_env
(* Sets of relevant location *)
type loc_set = A.LocSet.t
type rloc_set = A.RLocSet.t
let loc_of_rloc test rloc k =
let locs = A.locs_of_rloc (type_env test) rloc in
A.LocSet.union (A.LocSet.of_list locs) k
let locs_of_rlocs test rlocs =
A.RLocSet.fold
(fun rloc k -> loc_of_rloc test rloc k)
rlocs A.LocSet.empty
let observed_rlocations t = t.Test_herd.observed
let observed_locations t = locs_of_rlocs t (observed_rlocations t)
let displayed_rlocations t = t.Test_herd.displayed
let is_non_mixed_offset test s o = match o with
| 0 -> true
| _ ->
o > 0 &&
begin
let sym0 = Constant.mk_sym_virtual s in
let loc0 = A.Location_global (A.V.Val sym0) in
let t = A.look_type (type_env test) loc0 in
let open TestType in
match t with
| TyArray (t,sz) ->
let sz_elt = MachSize.nbytes (A.size_of_t t) in
o mod sz_elt = 0 && o < sz*sz_elt
| _ -> false
end
let is_non_mixed_symbol_virtual test sym =
let open Constant in
match sym.offset with
| 0 -> true
| o -> is_non_mixed_offset test sym.name o
let is_non_mixed_symbol test sym =
let open Constant in
match sym with
| Virtual sd -> is_non_mixed_symbol_virtual test sd
| Physical (s,o) -> is_non_mixed_offset test s o
| System ((PTE|PTE2|TLB|TAG),_) -> true
Exported labels :
* 1 . Labels from init environments
* 2 . Labels from instructions that transfer labels into regs .
* 1. Labels from init environments
* 2. Labels from instructions that transfer labels into regs.
*)
let get_exported_labels_init test =
let { Test_herd.init_state=st; _ } = test in
A.state_fold
(fun _ v k ->
match v with
| V.Val cst ->
begin
match Constant.as_label cst with
| Some lbl -> Label.Full.Set.add lbl k
| None -> k
end
| V.Var _ -> k)
st Label.Full.Set.empty
let get_exported_labels_code test =
let { Test_herd.nice_prog=prog; _ } = test in
List.fold_left
(fun k (p,code) ->
A.fold_pseudo_code
(fun k i ->
match A.V.Cst.Instr.get_exported_label i with
| None -> k
| Some lbl ->
Label.Full.Set.add (MiscParser.proc_num p,lbl) k)
k code)
Label.Full.Set.empty prog
let get_exported_labels test =
Label.Full.Set.union
(get_exported_labels_init test)
(get_exported_labels_code test)
(**********)
(* Events *)
(**********)
type event = E.event
let event_compare = E.event_compare
type event_set = E.EventSet.t
type event_structure = E.event_structure
type event_rel = E.EventRel.t
let tr = E.EventRel.transitive_closure
let rt = E.EventRel.remove_transitive_edges
let restrict = E.EventRel.restrict_domains
let doRR = restrict E.is_mem_load E.is_mem_load
let doRW = restrict E.is_mem_load E.is_mem_store
let doWW = restrict E.is_mem_store E.is_mem_store
let doWR = restrict E.is_mem_store E.is_mem_load
let seq = E.EventRel.sequence
let seqs = E.EventRel.sequences
let union = E.EventRel.union
let union3 = E.EventRel.union3
let unions = E.EventRel.unions
(* relations packed to be shown on graphs *)
type rel_pp = (string * event_rel) list
type set_pp = event_set StringMap.t
(* Dependencies : ie complement for ace *)
type procrels =
{ addr : event_rel;
data : event_rel;
depend : event_rel;
data_commit : event_rel;
ctrl : event_rel;
ctrlisync : event_rel;
success : event_rel;
rf : event_rel;
tst : event_rel; }
(* Read-From maps exploitation *)
type write_to =
| Final of location
| Load of event
type read_from =
| Init
| Store of event
let write_to_compare wt1 wt2 = match wt1,wt2 with
| Final loc1, Final loc2 -> A.location_compare loc1 loc2
| Final _, Load _ -> -1
| Load _,Final _ -> 1
| Load e1, Load e2 -> event_compare e1 e2
let read_from_compare rf1 rf2 = match rf1,rf2 with
| Init, Init -> 0
| Init, Store _ -> -1
| Store _,Init -> 1
| Store e1, Store e2 -> event_compare e1 e2
let read_from_equal rf1 rf2 = read_from_compare rf1 rf2 = 0
let event_rf_equal e rf = match rf with
| Init -> false
| Store e' -> E.event_equal e e'
module RFMap =
Map.Make
(struct
type t = write_to
let compare = write_to_compare
end)
type rfmap = read_from RFMap.t
let pp_rfmap chan delim pp rfm =
let first = ref true in
RFMap.iter
(fun wt rf ->
if not !first then output_string chan delim
else first := false ;
pp chan wt rf)
rfm
let for_all_in_rfmap pred rfm =
RFMap.fold
(fun wt rf k -> pred wt rf && k)
rfm true
let simplify_rf solns = function
| Init -> Init
| Store e -> Store (E.simplify_vars_in_event solns e)
and simplify_wt solns = function
| Final loc -> Final (A.simplify_vars_in_loc solns loc)
| Load e -> Load (E.simplify_vars_in_event solns e)
let simplify_vars_in_rfmap solns rfm =
if V.Solution.is_empty solns then rfm
else
RFMap.fold
(fun wt rf k ->
RFMap.add
(simplify_wt solns wt)
(simplify_rf solns rf)
k)
rfm RFMap.empty
(**************************************)
Complete , concrete event structure
(**************************************)
type concrete =
{
str : event_structure ; (* event structure proper *)
rfmap : rfmap ; (* rfmap *)
fs : state * A.FaultSet.t ; (* final state *)
po : event_rel ;
pos : event_rel ; (* Same location same processor accesses *)
pco : event_rel ;
View before relation deduced from
store_load_vbf : event_rel ; (* stores preceed their loads *)
init_load_vbf : event_rel; (* load from init preceed all stores *)
last_store_vbf : event_rel; (* stores to final state come last *)
atomic_load_store : event_rel; (* eg load-and-link/store conditional *)
}
let conc_zero =
{
str = E.empty_event_structure ;
rfmap = RFMap.empty ;
fs = A.state_empty,A.FaultSet.empty;
po = E.EventRel.empty ;
pos = E.EventRel.empty ;
pco = E.EventRel.empty ;
store_load_vbf = E.EventRel.empty ;
init_load_vbf = E.EventRel.empty ;
last_store_vbf = E.EventRel.empty ;
atomic_load_store = E.EventRel.empty ;
}
(************)
(* Branches *)
(************)
module B = Branch.Make(M)
type branch = B.t
let tgt2tgt ii = function
| BranchTarget.Lbl lbl -> B.Lbl lbl
| BranchTarget.Offset o -> B.Addr (ii.A.addr + o)
let gone_toofar { str; _ } =
try E.EventSet.exists E.is_toofar str.E.events
with Exit -> false
(************)
Barriers
(************)
type barrier = A.barrier
type pp_barrier = { barrier:barrier ; pp:string; }
end
module ConfigToArchConfig(C:Config) : ArchExtra_herd.Config =
struct
let verbose = C.verbose
let texmacros = C.PC.texmacros
let hexa = C.PC.hexa
let brackets = C.PC.brackets
let variant = C.variant
let endian = C.endian
let default_to_symb = false
end
| null | https://raw.githubusercontent.com/herd/herdtools7/6d781eb91debffdf56998171862a18e40908c3c5/herd/semExtra.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
* Centralized definition for types to be included by the XXXSem
Some configuration
Options, for Sem consumer
Report some flags
A good place to (re)define all these types
Get sets of locations observed in outcomes
Notice, array rlocations are expanded to the locations of
their elements
"Exported" labels, i.e. labels that can find their way to registers
In initial state
In code
Both of them
relations packed to be shown on graphs
Dependencies : ie complement for ace
*******
*******
************************************
************************************
event structure proper
rfmap
final state
Same location same processor accesses
Write serialization precursor ie uniproc induced constraints over writes
stores preceed their loads
load from init preceed all stores
stores to final state come last
eg load-and-link/store conditional
**********
Branches
**********
**********
**********
barrier + cumulativity
Configure event monads
A good place to (re)define all these types
Sets of relevant location
********
Events
********
relations packed to be shown on graphs
Dependencies : ie complement for ace
Read-From maps exploitation
************************************
************************************
event structure proper
rfmap
final state
Same location same processor accesses
stores preceed their loads
load from init preceed all stores
stores to final state come last
eg load-and-link/store conditional
**********
Branches
**********
**********
********** | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2010 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
module type Config = sig
val verbose : int
val optace : OptAce.t
val debug : Debug_herd.t
val precision : Precision.t
val variant : Variant.t -> bool
val endian : Endian.t option
module PC : PrettyConf.S
end
module type S = sig
module A : Arch_herd.S
module E : Event.S with module A = A and module Act.A = A
module M : Monad.S
with module A = A and module E = E and type evt_struct = E.event_structure
module Cons : Constraints.S with module A = A
val do_deps : bool
type cst = A.V.Cst.v
type v = A.V.v
type proc = A.proc
type instruction = A.instruction
type global_loc = A.global_loc
type location = A.location
type state = A.state
type final_state = A.final_state
type program = A.program
type prop = A.prop
type constr = A.constr
type nice_prog = A.nice_prog
type start_points = A.start_points
type code_segment = A.code_segment
type proc_info = Test_herd.proc_info
type test =
(program, nice_prog, start_points, code_segment,
state, A.size_env, A.type_env,
prop, location, A.RLocSet.t, A.FaultAtomSet.t) Test_herd.t
val size_env : test -> A.size_env
val type_env : test -> A.type_env
type loc_set = A.LocSet.t
type rloc_set = A.RLocSet.t
val observed_rlocations : test -> rloc_set
val observed_locations : test -> loc_set
val displayed_rlocations : test -> rloc_set
val is_non_mixed_symbol : test -> Constant.symbol -> bool
val get_exported_labels_init : test -> Label.Full.Set.t
val get_exported_labels_code : test -> Label.Full.Set.t
val get_exported_labels : test -> Label.Full.Set.t
type event = E.event
type event_structure = E.event_structure
type event_set = E.EventSet.t
type event_rel = E.EventRel.t
val tr : event_rel -> event_rel
val rt : event_rel -> event_rel
val restrict :
(event -> bool) -> (event -> bool) ->
event_rel -> event_rel
val doWW : event_rel -> event_rel
val doWR : event_rel -> event_rel
val doRR : event_rel -> event_rel
val doRW : event_rel -> event_rel
val seq : event_rel -> event_rel -> event_rel
val seqs : event_rel list -> event_rel
val union : event_rel -> event_rel -> event_rel
val union3 : event_rel -> event_rel -> event_rel -> event_rel
val unions : event_rel list -> event_rel
type rel_pp = (string * event_rel) list
type set_pp = event_set StringMap.t
type procrels =
{ addr : event_rel;
data : event_rel;
depend : event_rel;
data_commit : event_rel;
ctrl : event_rel;
ctrlisync : event_rel;
success : event_rel;
rf : event_rel;
tst: event_rel; }
type write_to =
| Final of location
| Load of event
type read_from =
| Init
| Store of event
val write_to_compare : write_to -> write_to -> int
val read_from_compare : read_from -> read_from -> int
val read_from_equal : read_from -> read_from -> bool
val event_rf_equal : event -> read_from -> bool
module RFMap : Map.S with type key = write_to
type rfmap = read_from RFMap.t
For pretty print , string arg is like the one of String.concat
val pp_rfmap :
out_channel -> string ->
(out_channel -> write_to -> read_from -> unit) ->
rfmap -> unit
val for_all_in_rfmap : (write_to -> read_from -> bool) -> rfmap -> bool
val simplify_vars_in_rfmap : A.V.solution -> rfmap -> rfmap
Complete , concrete event structure
type concrete =
{
program order ( in fact )
pco : event_rel ;
View before relation deduced from
}
val conc_zero : concrete
module B : Branch.S
with type reg = A.reg and type v = v and type 'a monad = 'a M.t
type branch = B.t
val tgt2tgt : A.inst_instance_id -> BranchTarget.t -> B.tgt
val gone_toofar : concrete -> bool
Barriers
type barrier = A.barrier
type pp_barrier = { barrier:barrier ; pp:string; }
end
module Make(C:Config) (A:Arch_herd.S) (Act:Action.S with module A = A)
: (S with module A = A and module E.Act = Act) =
struct
module O = C
module A = A
module V = A.V
module E = Event.Make(C)(A)(Act)
let hexa = C.PC.hexa
let debug = C.debug
let variant = C.variant
end
module M = EventsMonad.Make(CEM)(A)(E)
module Cons = Constraints.Make (C.PC)(A)
let do_deps = C.variant Variant.Deps
type cst = A.V.Cst.v
type v = A.V.v
type proc = A.proc
type instruction = A.instruction
type global_loc = A.global_loc
type location = A.location
type state = A.state
type final_state = A.final_state
type prop = A.prop
type constr = A.constr
type program = A.program
type nice_prog = A.nice_prog
type start_points = A.start_points
type code_segment = A.code_segment
type proc_info = Test_herd.proc_info
type test =
(program, nice_prog, start_points, code_segment, state,
A.size_env, A.type_env,
prop, location, A.RLocSet.t, A.FaultAtomSet.t) Test_herd.t
let size_env t = t.Test_herd.size_env
and type_env t = t.Test_herd.type_env
type loc_set = A.LocSet.t
type rloc_set = A.RLocSet.t
let loc_of_rloc test rloc k =
let locs = A.locs_of_rloc (type_env test) rloc in
A.LocSet.union (A.LocSet.of_list locs) k
let locs_of_rlocs test rlocs =
A.RLocSet.fold
(fun rloc k -> loc_of_rloc test rloc k)
rlocs A.LocSet.empty
let observed_rlocations t = t.Test_herd.observed
let observed_locations t = locs_of_rlocs t (observed_rlocations t)
let displayed_rlocations t = t.Test_herd.displayed
let is_non_mixed_offset test s o = match o with
| 0 -> true
| _ ->
o > 0 &&
begin
let sym0 = Constant.mk_sym_virtual s in
let loc0 = A.Location_global (A.V.Val sym0) in
let t = A.look_type (type_env test) loc0 in
let open TestType in
match t with
| TyArray (t,sz) ->
let sz_elt = MachSize.nbytes (A.size_of_t t) in
o mod sz_elt = 0 && o < sz*sz_elt
| _ -> false
end
let is_non_mixed_symbol_virtual test sym =
let open Constant in
match sym.offset with
| 0 -> true
| o -> is_non_mixed_offset test sym.name o
let is_non_mixed_symbol test sym =
let open Constant in
match sym with
| Virtual sd -> is_non_mixed_symbol_virtual test sd
| Physical (s,o) -> is_non_mixed_offset test s o
| System ((PTE|PTE2|TLB|TAG),_) -> true
Exported labels :
* 1 . Labels from init environments
* 2 . Labels from instructions that transfer labels into regs .
* 1. Labels from init environments
* 2. Labels from instructions that transfer labels into regs.
*)
let get_exported_labels_init test =
let { Test_herd.init_state=st; _ } = test in
A.state_fold
(fun _ v k ->
match v with
| V.Val cst ->
begin
match Constant.as_label cst with
| Some lbl -> Label.Full.Set.add lbl k
| None -> k
end
| V.Var _ -> k)
st Label.Full.Set.empty
let get_exported_labels_code test =
let { Test_herd.nice_prog=prog; _ } = test in
List.fold_left
(fun k (p,code) ->
A.fold_pseudo_code
(fun k i ->
match A.V.Cst.Instr.get_exported_label i with
| None -> k
| Some lbl ->
Label.Full.Set.add (MiscParser.proc_num p,lbl) k)
k code)
Label.Full.Set.empty prog
let get_exported_labels test =
Label.Full.Set.union
(get_exported_labels_init test)
(get_exported_labels_code test)
type event = E.event
let event_compare = E.event_compare
type event_set = E.EventSet.t
type event_structure = E.event_structure
type event_rel = E.EventRel.t
let tr = E.EventRel.transitive_closure
let rt = E.EventRel.remove_transitive_edges
let restrict = E.EventRel.restrict_domains
let doRR = restrict E.is_mem_load E.is_mem_load
let doRW = restrict E.is_mem_load E.is_mem_store
let doWW = restrict E.is_mem_store E.is_mem_store
let doWR = restrict E.is_mem_store E.is_mem_load
let seq = E.EventRel.sequence
let seqs = E.EventRel.sequences
let union = E.EventRel.union
let union3 = E.EventRel.union3
let unions = E.EventRel.unions
type rel_pp = (string * event_rel) list
type set_pp = event_set StringMap.t
type procrels =
{ addr : event_rel;
data : event_rel;
depend : event_rel;
data_commit : event_rel;
ctrl : event_rel;
ctrlisync : event_rel;
success : event_rel;
rf : event_rel;
tst : event_rel; }
type write_to =
| Final of location
| Load of event
type read_from =
| Init
| Store of event
let write_to_compare wt1 wt2 = match wt1,wt2 with
| Final loc1, Final loc2 -> A.location_compare loc1 loc2
| Final _, Load _ -> -1
| Load _,Final _ -> 1
| Load e1, Load e2 -> event_compare e1 e2
let read_from_compare rf1 rf2 = match rf1,rf2 with
| Init, Init -> 0
| Init, Store _ -> -1
| Store _,Init -> 1
| Store e1, Store e2 -> event_compare e1 e2
let read_from_equal rf1 rf2 = read_from_compare rf1 rf2 = 0
let event_rf_equal e rf = match rf with
| Init -> false
| Store e' -> E.event_equal e e'
module RFMap =
Map.Make
(struct
type t = write_to
let compare = write_to_compare
end)
type rfmap = read_from RFMap.t
let pp_rfmap chan delim pp rfm =
let first = ref true in
RFMap.iter
(fun wt rf ->
if not !first then output_string chan delim
else first := false ;
pp chan wt rf)
rfm
let for_all_in_rfmap pred rfm =
RFMap.fold
(fun wt rf k -> pred wt rf && k)
rfm true
let simplify_rf solns = function
| Init -> Init
| Store e -> Store (E.simplify_vars_in_event solns e)
and simplify_wt solns = function
| Final loc -> Final (A.simplify_vars_in_loc solns loc)
| Load e -> Load (E.simplify_vars_in_event solns e)
let simplify_vars_in_rfmap solns rfm =
if V.Solution.is_empty solns then rfm
else
RFMap.fold
(fun wt rf k ->
RFMap.add
(simplify_wt solns wt)
(simplify_rf solns rf)
k)
rfm RFMap.empty
Complete , concrete event structure
type concrete =
{
po : event_rel ;
pco : event_rel ;
View before relation deduced from
}
let conc_zero =
{
str = E.empty_event_structure ;
rfmap = RFMap.empty ;
fs = A.state_empty,A.FaultSet.empty;
po = E.EventRel.empty ;
pos = E.EventRel.empty ;
pco = E.EventRel.empty ;
store_load_vbf = E.EventRel.empty ;
init_load_vbf = E.EventRel.empty ;
last_store_vbf = E.EventRel.empty ;
atomic_load_store = E.EventRel.empty ;
}
module B = Branch.Make(M)
type branch = B.t
let tgt2tgt ii = function
| BranchTarget.Lbl lbl -> B.Lbl lbl
| BranchTarget.Offset o -> B.Addr (ii.A.addr + o)
let gone_toofar { str; _ } =
try E.EventSet.exists E.is_toofar str.E.events
with Exit -> false
Barriers
type barrier = A.barrier
type pp_barrier = { barrier:barrier ; pp:string; }
end
module ConfigToArchConfig(C:Config) : ArchExtra_herd.Config =
struct
let verbose = C.verbose
let texmacros = C.PC.texmacros
let hexa = C.PC.hexa
let brackets = C.PC.brackets
let variant = C.variant
let endian = C.endian
let default_to_symb = false
end
|
99d1bfd43f438ea4a0e4f4491f25b1513bd4a428966bd3eaf32e977e33fc5ecb | ZHaskell/stdio | Main.hs | # LANGUAGE QuasiQuotes #
# LANGUAGE FlexibleContexts #
# LANGUAGE DataKinds #
# LANGUAGE TypeApplications #
module Main (main) where
import Control.DeepSeq
import Criterion.Main
import qualified Data.ByteString as B
import qualified Data.List as List
import qualified Data.Vector.Unboxed as VU
import Data.Word
import System.IO (readFile)
import qualified Data.Text as T
import qualified Std.Data.Text as S
import qualified Std.Data.Vector as V
import Builder
import Bytes
import Text
import BitTwiddle
main :: IO ()
main = do
str <- readFile "./utf8-sample.txt"
let t = T.pack str
st = S.pack str
defaultMain -- $ List.reverse -- uncomment this reverse bench, useful for dev
[ bgroup "Bytes" bytes
, bgroup "Builder" builder
, bgroup "BitTwiddle" bitTwiddle
, bgroup "Text" (text t st)
]
| null | https://raw.githubusercontent.com/ZHaskell/stdio/7887b9413dc9feb957ddcbea96184f904cf37c12/bench/data/Main.hs | haskell | $ List.reverse -- uncomment this reverse bench, useful for dev | # LANGUAGE QuasiQuotes #
# LANGUAGE FlexibleContexts #
# LANGUAGE DataKinds #
# LANGUAGE TypeApplications #
module Main (main) where
import Control.DeepSeq
import Criterion.Main
import qualified Data.ByteString as B
import qualified Data.List as List
import qualified Data.Vector.Unboxed as VU
import Data.Word
import System.IO (readFile)
import qualified Data.Text as T
import qualified Std.Data.Text as S
import qualified Std.Data.Vector as V
import Builder
import Bytes
import Text
import BitTwiddle
main :: IO ()
main = do
str <- readFile "./utf8-sample.txt"
let t = T.pack str
st = S.pack str
[ bgroup "Bytes" bytes
, bgroup "Builder" builder
, bgroup "BitTwiddle" bitTwiddle
, bgroup "Text" (text t st)
]
|
37e52b341dcd677e9b8cda945dc1ba4e0e1fabd3b0a29d4f05ead0a31312ab9e | Bodigrim/linear-builder | BenchText.hs | -- |
Copyright : ( c ) 2022
Licence : BSD3
Maintainer : < >
module BenchText (benchText) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Builder as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Text.Builder.Linear.Buffer
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText, fromText)
import Test.Tasty.Bench
#ifdef MIN_VERSION_text_builder
import qualified Text.Builder
#endif
#ifdef MIN_VERSION_bytestring_strict_builder
import qualified ByteString.StrictBuilder
#endif
txt ∷ T.Text
txt = T.pack "Haskell + Linear Types = ♡"
benchLazyBuilder ∷ Int → T.Text
benchLazyBuilder = toStrict . toLazyText . go mempty
where
txtB = fromText txt
go !acc 0 = acc
go !acc n = go (txtB <> (acc <> txtB)) (n - 1)
benchLazyBuilderBS ∷ Int → B.ByteString
benchLazyBuilderBS = B.toStrict . B.toLazyByteString . go mempty
where
txtB = B.byteString $ T.encodeUtf8 txt
go !acc 0 = acc
go !acc n = go (txtB <> (acc <> txtB)) (n - 1)
#ifdef MIN_VERSION_text_builder
benchStrictBuilder ∷ Int → T.Text
benchStrictBuilder = Text.Builder.run . go mempty
where
txtB = Text.Builder.text txt
go !acc 0 = acc
go !acc n = go (txtB <> (acc <> txtB)) (n - 1)
#endif
#ifdef MIN_VERSION_bytestring_strict_builder
benchStrictBuilderBS ∷ Int → B.ByteString
benchStrictBuilderBS = ByteString.StrictBuilder.builderBytes . go mempty
where
txtB = ByteString.StrictBuilder.bytes $ T.encodeUtf8 txt
go !acc 0 = acc
go !acc n = go (txtB <> (acc <> txtB)) (n - 1)
#endif
benchLinearBuilder ∷ Int → T.Text
benchLinearBuilder m = runBuffer (\b → go b m)
where
go ∷ Buffer ⊸ Int → Buffer
go !acc 0 = acc
go !acc n = go (txt <| (acc |> txt)) (n - 1)
benchText ∷ Benchmark
benchText = bgroup "Text" $ map mkGroup [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6]
mkGroup :: Int → Benchmark
mkGroup n = bgroup (show n)
[ bench "Data.Text.Lazy.Builder" $ nf benchLazyBuilder n
, bench "Data.ByteString.Builder" $ nf benchLazyBuilderBS n
#ifdef MIN_VERSION_text_builder
, bench "Text.Builder" $ nf benchStrictBuilder n
#endif
#ifdef MIN_VERSION_bytestring_strict_builder
, bench "ByteString.StrictBuilder" $ nf benchStrictBuilderBS n
#endif
, bench "Data.Text.Builder.Linear" $ nf benchLinearBuilder n
]
| null | https://raw.githubusercontent.com/Bodigrim/linear-builder/946ede793abc757180e4c53dc14b6988e6ffc3c4/bench/BenchText.hs | haskell | | | Copyright : ( c ) 2022
Licence : BSD3
Maintainer : < >
module BenchText (benchText) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Builder as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Text.Builder.Linear.Buffer
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder (toLazyText, fromText)
import Test.Tasty.Bench
#ifdef MIN_VERSION_text_builder
import qualified Text.Builder
#endif
#ifdef MIN_VERSION_bytestring_strict_builder
import qualified ByteString.StrictBuilder
#endif
txt ∷ T.Text
txt = T.pack "Haskell + Linear Types = ♡"
benchLazyBuilder ∷ Int → T.Text
benchLazyBuilder = toStrict . toLazyText . go mempty
where
txtB = fromText txt
go !acc 0 = acc
go !acc n = go (txtB <> (acc <> txtB)) (n - 1)
benchLazyBuilderBS ∷ Int → B.ByteString
benchLazyBuilderBS = B.toStrict . B.toLazyByteString . go mempty
where
txtB = B.byteString $ T.encodeUtf8 txt
go !acc 0 = acc
go !acc n = go (txtB <> (acc <> txtB)) (n - 1)
#ifdef MIN_VERSION_text_builder
benchStrictBuilder ∷ Int → T.Text
benchStrictBuilder = Text.Builder.run . go mempty
where
txtB = Text.Builder.text txt
go !acc 0 = acc
go !acc n = go (txtB <> (acc <> txtB)) (n - 1)
#endif
#ifdef MIN_VERSION_bytestring_strict_builder
benchStrictBuilderBS ∷ Int → B.ByteString
benchStrictBuilderBS = ByteString.StrictBuilder.builderBytes . go mempty
where
txtB = ByteString.StrictBuilder.bytes $ T.encodeUtf8 txt
go !acc 0 = acc
go !acc n = go (txtB <> (acc <> txtB)) (n - 1)
#endif
benchLinearBuilder ∷ Int → T.Text
benchLinearBuilder m = runBuffer (\b → go b m)
where
go ∷ Buffer ⊸ Int → Buffer
go !acc 0 = acc
go !acc n = go (txt <| (acc |> txt)) (n - 1)
benchText ∷ Benchmark
benchText = bgroup "Text" $ map mkGroup [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6]
mkGroup :: Int → Benchmark
mkGroup n = bgroup (show n)
[ bench "Data.Text.Lazy.Builder" $ nf benchLazyBuilder n
, bench "Data.ByteString.Builder" $ nf benchLazyBuilderBS n
#ifdef MIN_VERSION_text_builder
, bench "Text.Builder" $ nf benchStrictBuilder n
#endif
#ifdef MIN_VERSION_bytestring_strict_builder
, bench "ByteString.StrictBuilder" $ nf benchStrictBuilderBS n
#endif
, bench "Data.Text.Builder.Linear" $ nf benchLinearBuilder n
]
|
83a7d4397219d504e5c6fc6b3f24565a338aaf4a3614d97c139993bd6bb108e0 | jjtolton/libapl-clj | api.clj | (ns ^{:doc "This is a low level API one level above
the JNA bindings to provide a thin layer of indirection.
Contributors: Please use this rather than than the JNA bindings for
: manipulating APL memory space.
Application developers: Please be careful hooking into this directly.
: While more stable than the JNA bindings,
: the API is subject to change.
overview
--------
No type coercion. Simply an abstraction
from the underlying JNA bindings in case we want to switch
to a different runtime down the road, such as Dyalog, for instance,
or to potentially provide hooks.
The only conveniences provided are:
* the `loc` argument is omitted, as it is for debugging C code.
* the API is made more idiomatic than raw JNA interop
variable conventions
--------------------
avp -- APL value pointer. \"Opaque\" pointer reference to an APL array or scalar,
: expressed in Clojure as a JNA Pointer.
atp -- APL value pointer that specifically an APL Tensor (aka NDarray, Vector, or
: multi-dimensional array).
asp -- APL value pointer that specifically maps to an APL Scalar.
fp -- APL function pointer. \"Opaque\" pointer reference to an APL function.
: the \"a\" is dropped from \"afp\" to provide a visual distinction from \"avp\".
op -- APL \"operation\" pointer. We refer to APL \"operations\" as higher order functions
: in Clojure. An example is `reduce`, which takes a function as an argument.
: In APL, reduce (given the `/` symbol) takes a function as its left argument.
s -- a string
ax, axis -- an integer representing the index of a value in the shape of a Tensor
: i.e., if the shape is [2 3 5], axis 0 is 2, axis 1 is 3, axis 2 is 5
p -- a pointer
vref -- a string, the variable name associate with an APL value
idx -- index
function naming conventions
---------------------------
x+y -- brutalist naming convention. avp+idx->char indicates a function
: that takes an avp and an idx and returns a char.
: avp+fp+avp->avp represents a function that has parameters [avp fp avp] and returns
: an avp. etc.
"}
libapl-clj.impl.api
(:require [libapl-clj.impl.jna :as jna :reload true]
[tech.v3.datatype :as dtype])
(:import [com.sun.jna Pointer]))
(defn initialize! []
;; todo -- add initialization options, such as library location
(jna/init_libapl "main" 1))
(defn run-simple-string! ^Integer [^String s]
(jna/apl_exec s))
(defn run-command-string! ^Integer [^String cmd & args]
;; todo -- important to understand GNU APL command context better
;; to make this more useful
(jna/apl_command ^String (clojure.string/join (into [cmd] args))))
(defn ^:private result-callback
[result committed]
;; todo -- what does this do...?
(jna/result_callback result committed))
(defn pointer->string ^String [^Pointer avp]
(jna/print_value_to_string avp))
(defn rank ^Integer [^Pointer avp]
(jna/get_rank avp))
(defn axis ^Integer [^Pointer avp ^Integer ax]
(jna/get_axis avp ax))
(defn ref->avp ^Pointer [^String vref]
(jna/get_var_value vref ""))
(defn atp->ref!
"Warning: crash if you attempt to assign a scalar pointer"
[^String ref ^Pointer atp]
(jna/set_var_value ref atp ""))
(defn avp->string! ^String [^Pointer avp]
(jna/print_value_to_string avp))
(defn n-elems ^Integer [^Pointer avp]
(jna/get_element_count avp))
(comment
(n-elems (char-vector "hello"))
(n-elems (int-scalar 1))
(n-elems (double-scalar 10.12))
(n-elems (complex-scalar 1 2))
)
(defn type-at-idx
"Get type of value for pointer at idx.
CT_NONE = 0,
CT_BASE = 0x01,
CT_CHAR = 0x02,
CT_POINTER = 0x04,
CT_CELLREF = 0x08,
CT_INT = 0x10,
CT_FLOAT = 0x20,
CT_COMPLEX = 0x40,
CT_NUMERIC = CT_INT | CT_FLOAT | CT_COMPLEX,
CT_SIMPLE = CT_CHAR | CT_NUMERIC,
CT_MASK = CT_CHAR | CT_NUMERIC | CT_POINTER | CT_CELLREF"
^Integer [^Pointer avp ^Integer idx]
(jna/get_type avp idx))
(defn atp+idx->avp ^Pointer [^Pointer atp ^Integer idx]
(jna/get_value atp idx))
(def avp< atp+idx->avp)
(defn atp+idx->int ^Integer [^Pointer atp ^Integer idx]
(jna/get_int atp idx))
(def int< atp+idx->int)
(defn atp+idx->real ^Double [^Pointer atp ^Integer idx]
(jna/get_real atp idx))
(def real< atp+idx->real)
(defn atp+idx->imag ^Double [^Pointer atp ^Integer idx]
(jna/get_imag atp idx))
(def imag< atp+idx->imag)
(defn atp+idx->char ^Character [^Pointer atp ^Integer idx]
(jna/get_char atp idx))
(def char< atp+idx->char)
(defn set-char! [^Pointer atp ^Integer idx ^Character c]
(jna/set_char c atp idx))
(defn set-value! [^Pointer atp ^Integer idx ^Pointer avp]
(jna/set_value avp atp idx))
(defn set-int! [^Pointer atp ^Integer idx ^Integer n]
(jna/set_int n atp idx))
(defn set-double! [^Pointer atp ^Integer idx ^Double n]
(jna/set_double n atp idx))
(defn set-complex! [^Pointer atp ^Integer idx ^Double real ^Double imag]
(jna/set_complex real imag atp idx))
;; constructors
(defn apl-value
"Another exception to the 'no casting' rule. I can't see
any reasion to not do the casting to a container here."
^Pointer [shape]
(jna/apl_value (count shape)
(dtype/make-container :native-heap :int64 shape)
""))
(defn apl-scalar ^Pointer []
(jna/apl_scalar ""))
(defn apl-vector ^Pointer [^Integer length]
(jna/apl_vector length ""))
(defn apl-cube ^Pointer [^Integer blocks ^Integer rows ^Integer cols]
(jna/apl_cube blocks rows cols ""))
(defn char-vector ^Pointer [^String string]
(jna/char_vector string ""))
(defn int-scalar ^Pointer [^Long n]
(jna/int_scalar n ""))
(defn double-scalar ^Pointer [^Double n]
(jna/double_scalar n ""))
(defn complex-scalar ^Pointer [^Pointer real ^Float imag]
(jna/complex_scalar real imag ""))
(defn char-scalar ^Pointer [^Character c]
(jna/char_scalar c))
;; destructors
(defn release-value! [^Pointer avp]
(jna/release_value avp ""))
;; auxiliary
(defn owner-count [^Pointer avp]
(jna/get_owner_count avp))
(defn ->string-container
([] (dtype/make-container :native-heap :uint64 []))
([s]
(if (nil? s)
(->string-container)
(->> s
str
vec
first
vector
(dtype/make-container :native-heap :uint64)))))
(defn get-function-ucs
"Note: this function is an exception to the 'no-coercion' rule for this
namespace because this is an esoteric technique and I can't think of a valid
reason not to do it here."
([^String fstring]
(get-function-ucs fstring nil nil))
([^String s1 ^String s2]
(get-function-ucs s1 s2 nil))
([s1 s2 s3]
(jna/get_function_ucs (->string-container s1)
(->string-container s2)
(->string-container s3))))
(comment
(get-function-ucs "⍴"))
(defn niladic-fp ^Pointer [^Pointer fp]
(jna/eval__fun fp))
(defn arg+fp+arg
"Note that order of arguments is more idiomatic to APL than Clojure"
^Pointer
[arg1 ^Pointer fp arg2]
(jna/eval__A_fun_B arg1 fp arg2))
(defn arg+fp+axis+arg ^Pointer [arg1 ^Pointer fp ^Pointer axis arg2]
(jna/eval__A_fun_X_B arg1 fp axis arg2))
(defn arg+fn+op+axis+arg ^Pointer [arg1 ^Pointer fp ^Pointer op ^Pointer axis arg2]
(jna/eval__A_L_oper_X_B arg1 fp op axis arg2))
(defn arg+fp+op+fp+arg ^Pointer [arg1 ^Pointer fp1 ^Pointer op ^Pointer fp2 ^Pointer arg2]
(jna/eval__A_L_oper_R_B arg1 fp1 op fp2 arg2))
(defn arg+fn+op+fn+axis+arg ^Pointer
[arg1
^Pointer fp1
^Pointer op
^Pointer fp2
^Pointer axis
arg2]
(jna/eval__A_L_oper_R_X_B arg1 fp1 op fp2 axis arg2))
(defn fp+arg ^Pointer [^Pointer fp arg]
(jna/eval__fun_B fp arg))
(defn fp+op+arg ^Pointer [^Pointer fp ^Pointer op arg]
(jna/eval__L_oper_B fp op arg))
(defn fp+op+axis+arg ^Pointer [^Pointer fp ^Pointer op ^Pointer axis arg]
(jna/eval__L_oper_X_B fp op axis arg))
(defn fp+axis+arg ^Pointer [^Pointer fp ^Pointer axis arg]
(jna/eval__fun_X_B fp axis arg))
(defn fp+op+fp+arg ^Pointer [^Pointer fp1 ^Pointer op ^Pointer fp2 arg]
(jna/eval__L_oper_R_B fp1 op fp2 arg))
(defn fp+op+axis+arg ^Pointer [^Pointer fp ^Pointer op ^Pointer axis arg]
(jna/eval__L_oper_X_B fp op axis arg))
(defn fp+op+fp+axis+arg ^Pointer [^Pointer fp1 ^Pointer op ^Pointer fp2 ^Pointer axis arg]
(jna/eval__L_oper_R_X_B fp1 op fp2 axis arg))
| null | https://raw.githubusercontent.com/jjtolton/libapl-clj/01e2bf7e0d20abd9f8f36c2d9fc829dd4082d455/src/libapl_clj/impl/api.clj | clojure | todo -- add initialization options, such as library location
todo -- important to understand GNU APL command context better
to make this more useful
todo -- what does this do...?
constructors
destructors
auxiliary | (ns ^{:doc "This is a low level API one level above
the JNA bindings to provide a thin layer of indirection.
Contributors: Please use this rather than than the JNA bindings for
: manipulating APL memory space.
Application developers: Please be careful hooking into this directly.
: While more stable than the JNA bindings,
: the API is subject to change.
overview
--------
No type coercion. Simply an abstraction
from the underlying JNA bindings in case we want to switch
to a different runtime down the road, such as Dyalog, for instance,
or to potentially provide hooks.
The only conveniences provided are:
* the `loc` argument is omitted, as it is for debugging C code.
* the API is made more idiomatic than raw JNA interop
variable conventions
--------------------
avp -- APL value pointer. \"Opaque\" pointer reference to an APL array or scalar,
: expressed in Clojure as a JNA Pointer.
atp -- APL value pointer that specifically an APL Tensor (aka NDarray, Vector, or
: multi-dimensional array).
asp -- APL value pointer that specifically maps to an APL Scalar.
fp -- APL function pointer. \"Opaque\" pointer reference to an APL function.
: the \"a\" is dropped from \"afp\" to provide a visual distinction from \"avp\".
op -- APL \"operation\" pointer. We refer to APL \"operations\" as higher order functions
: in Clojure. An example is `reduce`, which takes a function as an argument.
: In APL, reduce (given the `/` symbol) takes a function as its left argument.
s -- a string
ax, axis -- an integer representing the index of a value in the shape of a Tensor
: i.e., if the shape is [2 3 5], axis 0 is 2, axis 1 is 3, axis 2 is 5
p -- a pointer
vref -- a string, the variable name associate with an APL value
idx -- index
function naming conventions
---------------------------
x+y -- brutalist naming convention. avp+idx->char indicates a function
: that takes an avp and an idx and returns a char.
: avp+fp+avp->avp represents a function that has parameters [avp fp avp] and returns
: an avp. etc.
"}
libapl-clj.impl.api
(:require [libapl-clj.impl.jna :as jna :reload true]
[tech.v3.datatype :as dtype])
(:import [com.sun.jna Pointer]))
(defn initialize! []
(jna/init_libapl "main" 1))
(defn run-simple-string! ^Integer [^String s]
(jna/apl_exec s))
(defn run-command-string! ^Integer [^String cmd & args]
(jna/apl_command ^String (clojure.string/join (into [cmd] args))))
(defn ^:private result-callback
[result committed]
(jna/result_callback result committed))
(defn pointer->string ^String [^Pointer avp]
(jna/print_value_to_string avp))
(defn rank ^Integer [^Pointer avp]
(jna/get_rank avp))
(defn axis ^Integer [^Pointer avp ^Integer ax]
(jna/get_axis avp ax))
(defn ref->avp ^Pointer [^String vref]
(jna/get_var_value vref ""))
(defn atp->ref!
"Warning: crash if you attempt to assign a scalar pointer"
[^String ref ^Pointer atp]
(jna/set_var_value ref atp ""))
(defn avp->string! ^String [^Pointer avp]
(jna/print_value_to_string avp))
(defn n-elems ^Integer [^Pointer avp]
(jna/get_element_count avp))
(comment
(n-elems (char-vector "hello"))
(n-elems (int-scalar 1))
(n-elems (double-scalar 10.12))
(n-elems (complex-scalar 1 2))
)
(defn type-at-idx
"Get type of value for pointer at idx.
CT_NONE = 0,
CT_BASE = 0x01,
CT_CHAR = 0x02,
CT_POINTER = 0x04,
CT_CELLREF = 0x08,
CT_INT = 0x10,
CT_FLOAT = 0x20,
CT_COMPLEX = 0x40,
CT_NUMERIC = CT_INT | CT_FLOAT | CT_COMPLEX,
CT_SIMPLE = CT_CHAR | CT_NUMERIC,
CT_MASK = CT_CHAR | CT_NUMERIC | CT_POINTER | CT_CELLREF"
^Integer [^Pointer avp ^Integer idx]
(jna/get_type avp idx))
(defn atp+idx->avp ^Pointer [^Pointer atp ^Integer idx]
(jna/get_value atp idx))
(def avp< atp+idx->avp)
(defn atp+idx->int ^Integer [^Pointer atp ^Integer idx]
(jna/get_int atp idx))
(def int< atp+idx->int)
(defn atp+idx->real ^Double [^Pointer atp ^Integer idx]
(jna/get_real atp idx))
(def real< atp+idx->real)
(defn atp+idx->imag ^Double [^Pointer atp ^Integer idx]
(jna/get_imag atp idx))
(def imag< atp+idx->imag)
(defn atp+idx->char ^Character [^Pointer atp ^Integer idx]
(jna/get_char atp idx))
(def char< atp+idx->char)
(defn set-char! [^Pointer atp ^Integer idx ^Character c]
(jna/set_char c atp idx))
(defn set-value! [^Pointer atp ^Integer idx ^Pointer avp]
(jna/set_value avp atp idx))
(defn set-int! [^Pointer atp ^Integer idx ^Integer n]
(jna/set_int n atp idx))
(defn set-double! [^Pointer atp ^Integer idx ^Double n]
(jna/set_double n atp idx))
(defn set-complex! [^Pointer atp ^Integer idx ^Double real ^Double imag]
(jna/set_complex real imag atp idx))
(defn apl-value
"Another exception to the 'no casting' rule. I can't see
any reasion to not do the casting to a container here."
^Pointer [shape]
(jna/apl_value (count shape)
(dtype/make-container :native-heap :int64 shape)
""))
(defn apl-scalar ^Pointer []
(jna/apl_scalar ""))
(defn apl-vector ^Pointer [^Integer length]
(jna/apl_vector length ""))
(defn apl-cube ^Pointer [^Integer blocks ^Integer rows ^Integer cols]
(jna/apl_cube blocks rows cols ""))
(defn char-vector ^Pointer [^String string]
(jna/char_vector string ""))
(defn int-scalar ^Pointer [^Long n]
(jna/int_scalar n ""))
(defn double-scalar ^Pointer [^Double n]
(jna/double_scalar n ""))
(defn complex-scalar ^Pointer [^Pointer real ^Float imag]
(jna/complex_scalar real imag ""))
(defn char-scalar ^Pointer [^Character c]
(jna/char_scalar c))
(defn release-value! [^Pointer avp]
(jna/release_value avp ""))
(defn owner-count [^Pointer avp]
(jna/get_owner_count avp))
(defn ->string-container
([] (dtype/make-container :native-heap :uint64 []))
([s]
(if (nil? s)
(->string-container)
(->> s
str
vec
first
vector
(dtype/make-container :native-heap :uint64)))))
(defn get-function-ucs
"Note: this function is an exception to the 'no-coercion' rule for this
namespace because this is an esoteric technique and I can't think of a valid
reason not to do it here."
([^String fstring]
(get-function-ucs fstring nil nil))
([^String s1 ^String s2]
(get-function-ucs s1 s2 nil))
([s1 s2 s3]
(jna/get_function_ucs (->string-container s1)
(->string-container s2)
(->string-container s3))))
(comment
(get-function-ucs "⍴"))
(defn niladic-fp ^Pointer [^Pointer fp]
(jna/eval__fun fp))
(defn arg+fp+arg
"Note that order of arguments is more idiomatic to APL than Clojure"
^Pointer
[arg1 ^Pointer fp arg2]
(jna/eval__A_fun_B arg1 fp arg2))
(defn arg+fp+axis+arg ^Pointer [arg1 ^Pointer fp ^Pointer axis arg2]
(jna/eval__A_fun_X_B arg1 fp axis arg2))
(defn arg+fn+op+axis+arg ^Pointer [arg1 ^Pointer fp ^Pointer op ^Pointer axis arg2]
(jna/eval__A_L_oper_X_B arg1 fp op axis arg2))
(defn arg+fp+op+fp+arg ^Pointer [arg1 ^Pointer fp1 ^Pointer op ^Pointer fp2 ^Pointer arg2]
(jna/eval__A_L_oper_R_B arg1 fp1 op fp2 arg2))
(defn arg+fn+op+fn+axis+arg ^Pointer
[arg1
^Pointer fp1
^Pointer op
^Pointer fp2
^Pointer axis
arg2]
(jna/eval__A_L_oper_R_X_B arg1 fp1 op fp2 axis arg2))
(defn fp+arg ^Pointer [^Pointer fp arg]
(jna/eval__fun_B fp arg))
(defn fp+op+arg ^Pointer [^Pointer fp ^Pointer op arg]
(jna/eval__L_oper_B fp op arg))
(defn fp+op+axis+arg ^Pointer [^Pointer fp ^Pointer op ^Pointer axis arg]
(jna/eval__L_oper_X_B fp op axis arg))
(defn fp+axis+arg ^Pointer [^Pointer fp ^Pointer axis arg]
(jna/eval__fun_X_B fp axis arg))
(defn fp+op+fp+arg ^Pointer [^Pointer fp1 ^Pointer op ^Pointer fp2 arg]
(jna/eval__L_oper_R_B fp1 op fp2 arg))
(defn fp+op+axis+arg ^Pointer [^Pointer fp ^Pointer op ^Pointer axis arg]
(jna/eval__L_oper_X_B fp op axis arg))
(defn fp+op+fp+axis+arg ^Pointer [^Pointer fp1 ^Pointer op ^Pointer fp2 ^Pointer axis arg]
(jna/eval__L_oper_R_X_B fp1 op fp2 axis arg))
|
49a9f70552909288af56d8ee26ba17f4b42fc0469e9a2e3bf15ab8674601bd25 | yuriy-chumak/ol | keyboard.scm | (define-library (lib keyboard)
(version 1.2)
(license MIT/LGPL3)
(description "keyboard support library")
(import
(otus lisp) (otus ffi))
(export
KEY_ENTER KEY_ESC KEY_TILDE
KEY_UP KEY_DOWN KEY_LEFT KEY_RIGHT
KEY_BACKSPACE KEY_TAB KEY_HOME KEY_END
KEY_1 KEY_2 KEY_3 KEY_4 KEY_5 KEY_6 KEY_7 KEY_8 KEY_9 KEY_0
KEY_Q KEY_W KEY_E KEY_R KEY_T KEY_Y KEY_U KEY_I KEY_O KEY_P
KEY_A KEY_S KEY_D KEY_F KEY_G KEY_H KEY_J KEY_K KEY_L
KEY_Z KEY_X KEY_C KEY_V KEY_B KEY_N KEY_M
KEY_F1 KEY_F2 KEY_F3 KEY_F4 KEY_F5 KEY_F6 KEY_F7 KEY_F8 KEY_F9
key-pressed?)
(cond-expand
(Windows
(begin
(setq user32 (load-dynamic-library "user32.dll"))
(setq GetAsyncKeyState (user32 fft-unsigned-short "GetAsyncKeyState" fft-int))
(define (key-pressed? key)
(let ((state (GetAsyncKeyState key)))
( < < 1 15 )
; -us/windows/win32/inputdev/virtual-key-codes
(define KEY_ENTER 13) (define KEY_ESC 27) (define KEY_TILDE 192)
(define KEY_LEFTCTRL 17) (define KEY_LEFTALT 00) (define KEY_LEFTSHIFT 16)
(define KEY_UP 38) (define KEY_DOWN 40) (define KEY_LEFT 37) (define KEY_RIGHT 39)
(define KEY_BACKSPACE 8) (define KEY_TAB 9) (define KEY_HOME 36) (define KEY_END 36)
(define KEY_1 49) (define KEY_2 50) (define KEY_3 51) (define KEY_4 52) (define KEY_5 53) (define KEY_6 54) (define KEY_7 55) (define KEY_8 56) (define KEY_9 57) (define KEY_0 48)
(define KEY_Q 81) (define KEY_W 87) (define KEY_E 69) (define KEY_R 82) (define KEY_T 84) (define KEY_Y 89) (define KEY_U 85) (define KEY_I 73) (define KEY_O 79) (define KEY_P 80)
(define KEY_A 65) (define KEY_S 83) (define KEY_D 68) (define KEY_F 70) (define KEY_G 71) (define KEY_H 72) (define KEY_J 74) (define KEY_K 75) (define KEY_L 76)
(define KEY_Z 90) (define KEY_X 88) (define KEY_C 3167) (define KEY_V 86) (define KEY_B 66) (define KEY_N 78) (define KEY_M 77)
(define KEY_F1 112) (define KEY_F2 113) (define KEY_F3 114) (define KEY_F4 115) (define KEY_F5 116) (define KEY_F6 117) (define KEY_F7 118) (define KEY_F8 119) (define KEY_F9 120)
))
(Android
(begin
(setq this (load-dynamic-library "libmain.so"))
(setq anlKeyPressed (this fft-bool "anlKeyPressed" fft-int))
(define key-pressed? anlKeyPressed)
; /+/refs/heads/master/include/android/keycodes.h
(define KEY_ENTER 66) (define KEY_ESC 4) (define KEY_TILDE 68)
(define KEY_UP 19) (define KEY_DOWN 20) (define KEY_LEFT 21) (define KEY_RIGHT 22)
(define KEY_BACKSPACE 67) (define KEY_TAB 61) (define KEY_HOME #xff50) (define KEY_END #xff57)
(define KEY_1 8) (define KEY_2 9) (define KEY_3 10) (define KEY_4 11) (define KEY_5 12) (define KEY_6 13) (define KEY_7 14) (define KEY_8 15) (define KEY_9 16) (define KEY_0 7)
(define KEY_Q 45) (define KEY_W 51) (define KEY_E 33) (define KEY_R 46) (define KEY_T 48) (define KEY_Y 53) (define KEY_U 49) (define KEY_I 37) (define KEY_O 43) (define KEY_P 44)
(define KEY_A 29) (define KEY_S 47) (define KEY_D 32) (define KEY_F 34) (define KEY_G 35) (define KEY_H 36) (define KEY_J 38) (define KEY_K 39) (define KEY_L 40)
(define KEY_Z 54) (define KEY_X 52) (define KEY_C 31) (define KEY_V 50) (define KEY_B 30) (define KEY_N 42) (define KEY_M 41)
(define KEY_F1 131) (define KEY_F2 132) (define KEY_F3 133) (define KEY_F4 134) (define KEY_F5 135) (define KEY_F6 136) (define KEY_F7 137) (define KEY_F8 138) (define KEY_F9 139)
))
(Linux
(begin
;
(setq x11 (or (load-dynamic-library "libX11.so")
(load-dynamic-library "libX11.so.6")))
(setq XOpenDisplay (x11 fft-void* "XOpenDisplay" type-string))
(setq XQueryKeymap (x11 fft-void "XQueryKeymap" type-vptr type-vptr)) ; todo: change to (fft* fft-char))
(setq XKeysymToKeycode (x11 fft-int "XKeysymToKeycode" type-vptr fft-int))
(setq display (XOpenDisplay #f))
(define keys (make-bytevector 32))
(define (key-pressed? key)
(XQueryKeymap display keys)
(let ((code (XKeysymToKeycode display key)))
(not (zero?
(band (<< 1 (band code #b111))
(ref keys (>> code 3)))))))
/usr / include / X11 / keysymdef.h
(define KEY_ENTER #xff0d) (define KEY_ESC #xff1b) (define KEY_TILDE #x0060)
(define KEY_UP #xff52) (define KEY_DOWN #xff54) (define KEY_LEFT #xff51) (define KEY_RIGHT #xff53)
(define KEY_BACKSPACE #xff08) (define KEY_TAB #xff09) (define KEY_HOME #xff50) (define KEY_END #xff57)
(define KEY_1 #x31) (define KEY_2 #x32) (define KEY_3 #x33) (define KEY_4 #x34) (define KEY_5 #x35) (define KEY_6 #x36) (define KEY_7 #x37) (define KEY_8 #x38) (define KEY_9 #x39) (define KEY_0 #x30)
(define KEY_Q #x71) (define KEY_W #x77) (define KEY_E #x65) (define KEY_R #x72) (define KEY_T #x74) (define KEY_Y #x79) (define KEY_U #x75) (define KEY_I #x69) (define KEY_O #x6f) (define KEY_P #x70)
(define KEY_A #x61) (define KEY_S #x73) (define KEY_D #x64) (define KEY_F #x66) (define KEY_G #x67) (define KEY_H #x68) (define KEY_J #x6a) (define KEY_K #x6b) (define KEY_L #x6c)
(define KEY_Z #x7a) (define KEY_X #x78) (define KEY_C #x63) (define KEY_V #x76) (define KEY_B #x62) (define KEY_N #x6e) (define KEY_M #x6d)
(define KEY_F1 #xffbe) (define KEY_F2 #xffbf) (define KEY_F3 #xffc0) (define KEY_F4 #xffc1) (define KEY_F5 #xffc2) (define KEY_F6 #xffc3) (define KEY_F7 #xffc4) (define KEY_F8 #xffc5) (define KEY_F9 #xffc6)
))
(Darwin
(begin
(define (key-pressed? key)
#false)
(define KEY_ENTER #f) (define KEY_ESC #f)
(define KEY_LEFTCTRL #f) (define KEY_LEFTALT #f) (define KEY_LEFTSHIFT #f)
(define KEY_UP #f) (define KEY_DOWN #f) (define KEY_LEFT #f) (define KEY_RIGHT #f)
(define KEY_1 #f) (define KEY_2 #f) (define KEY_3 #f) (define KEY_4 #f) (define KEY_5 #f) (define KEY_6 #f) (define KEY_7 #f) (define KEY_8 #f) (define KEY_9 #f) (define KEY_0 #f)
(define KEY_MINUS #f) (define KEY_EQUAL #f) (define KEY_BACKSPACE #f) (define KEY_TAB #f)
))
(else
(begin
(runtime-error "Unsupported platform" (syscall 63))))))
| null | https://raw.githubusercontent.com/yuriy-chumak/ol/c8cb6a11f16836b0e7b448f22250117b3c1470b6/libraries/lib/keyboard.scm | scheme | -us/windows/win32/inputdev/virtual-key-codes
/+/refs/heads/master/include/android/keycodes.h
todo: change to (fft* fft-char)) | (define-library (lib keyboard)
(version 1.2)
(license MIT/LGPL3)
(description "keyboard support library")
(import
(otus lisp) (otus ffi))
(export
KEY_ENTER KEY_ESC KEY_TILDE
KEY_UP KEY_DOWN KEY_LEFT KEY_RIGHT
KEY_BACKSPACE KEY_TAB KEY_HOME KEY_END
KEY_1 KEY_2 KEY_3 KEY_4 KEY_5 KEY_6 KEY_7 KEY_8 KEY_9 KEY_0
KEY_Q KEY_W KEY_E KEY_R KEY_T KEY_Y KEY_U KEY_I KEY_O KEY_P
KEY_A KEY_S KEY_D KEY_F KEY_G KEY_H KEY_J KEY_K KEY_L
KEY_Z KEY_X KEY_C KEY_V KEY_B KEY_N KEY_M
KEY_F1 KEY_F2 KEY_F3 KEY_F4 KEY_F5 KEY_F6 KEY_F7 KEY_F8 KEY_F9
key-pressed?)
(cond-expand
(Windows
(begin
(setq user32 (load-dynamic-library "user32.dll"))
(setq GetAsyncKeyState (user32 fft-unsigned-short "GetAsyncKeyState" fft-int))
(define (key-pressed? key)
(let ((state (GetAsyncKeyState key)))
( < < 1 15 )
(define KEY_ENTER 13) (define KEY_ESC 27) (define KEY_TILDE 192)
(define KEY_LEFTCTRL 17) (define KEY_LEFTALT 00) (define KEY_LEFTSHIFT 16)
(define KEY_UP 38) (define KEY_DOWN 40) (define KEY_LEFT 37) (define KEY_RIGHT 39)
(define KEY_BACKSPACE 8) (define KEY_TAB 9) (define KEY_HOME 36) (define KEY_END 36)
(define KEY_1 49) (define KEY_2 50) (define KEY_3 51) (define KEY_4 52) (define KEY_5 53) (define KEY_6 54) (define KEY_7 55) (define KEY_8 56) (define KEY_9 57) (define KEY_0 48)
(define KEY_Q 81) (define KEY_W 87) (define KEY_E 69) (define KEY_R 82) (define KEY_T 84) (define KEY_Y 89) (define KEY_U 85) (define KEY_I 73) (define KEY_O 79) (define KEY_P 80)
(define KEY_A 65) (define KEY_S 83) (define KEY_D 68) (define KEY_F 70) (define KEY_G 71) (define KEY_H 72) (define KEY_J 74) (define KEY_K 75) (define KEY_L 76)
(define KEY_Z 90) (define KEY_X 88) (define KEY_C 3167) (define KEY_V 86) (define KEY_B 66) (define KEY_N 78) (define KEY_M 77)
(define KEY_F1 112) (define KEY_F2 113) (define KEY_F3 114) (define KEY_F4 115) (define KEY_F5 116) (define KEY_F6 117) (define KEY_F7 118) (define KEY_F8 119) (define KEY_F9 120)
))
(Android
(begin
(setq this (load-dynamic-library "libmain.so"))
(setq anlKeyPressed (this fft-bool "anlKeyPressed" fft-int))
(define key-pressed? anlKeyPressed)
(define KEY_ENTER 66) (define KEY_ESC 4) (define KEY_TILDE 68)
(define KEY_UP 19) (define KEY_DOWN 20) (define KEY_LEFT 21) (define KEY_RIGHT 22)
(define KEY_BACKSPACE 67) (define KEY_TAB 61) (define KEY_HOME #xff50) (define KEY_END #xff57)
(define KEY_1 8) (define KEY_2 9) (define KEY_3 10) (define KEY_4 11) (define KEY_5 12) (define KEY_6 13) (define KEY_7 14) (define KEY_8 15) (define KEY_9 16) (define KEY_0 7)
(define KEY_Q 45) (define KEY_W 51) (define KEY_E 33) (define KEY_R 46) (define KEY_T 48) (define KEY_Y 53) (define KEY_U 49) (define KEY_I 37) (define KEY_O 43) (define KEY_P 44)
(define KEY_A 29) (define KEY_S 47) (define KEY_D 32) (define KEY_F 34) (define KEY_G 35) (define KEY_H 36) (define KEY_J 38) (define KEY_K 39) (define KEY_L 40)
(define KEY_Z 54) (define KEY_X 52) (define KEY_C 31) (define KEY_V 50) (define KEY_B 30) (define KEY_N 42) (define KEY_M 41)
(define KEY_F1 131) (define KEY_F2 132) (define KEY_F3 133) (define KEY_F4 134) (define KEY_F5 135) (define KEY_F6 136) (define KEY_F7 137) (define KEY_F8 138) (define KEY_F9 139)
))
(Linux
(begin
(setq x11 (or (load-dynamic-library "libX11.so")
(load-dynamic-library "libX11.so.6")))
(setq XOpenDisplay (x11 fft-void* "XOpenDisplay" type-string))
(setq XKeysymToKeycode (x11 fft-int "XKeysymToKeycode" type-vptr fft-int))
(setq display (XOpenDisplay #f))
(define keys (make-bytevector 32))
(define (key-pressed? key)
(XQueryKeymap display keys)
(let ((code (XKeysymToKeycode display key)))
(not (zero?
(band (<< 1 (band code #b111))
(ref keys (>> code 3)))))))
/usr / include / X11 / keysymdef.h
(define KEY_ENTER #xff0d) (define KEY_ESC #xff1b) (define KEY_TILDE #x0060)
(define KEY_UP #xff52) (define KEY_DOWN #xff54) (define KEY_LEFT #xff51) (define KEY_RIGHT #xff53)
(define KEY_BACKSPACE #xff08) (define KEY_TAB #xff09) (define KEY_HOME #xff50) (define KEY_END #xff57)
(define KEY_1 #x31) (define KEY_2 #x32) (define KEY_3 #x33) (define KEY_4 #x34) (define KEY_5 #x35) (define KEY_6 #x36) (define KEY_7 #x37) (define KEY_8 #x38) (define KEY_9 #x39) (define KEY_0 #x30)
(define KEY_Q #x71) (define KEY_W #x77) (define KEY_E #x65) (define KEY_R #x72) (define KEY_T #x74) (define KEY_Y #x79) (define KEY_U #x75) (define KEY_I #x69) (define KEY_O #x6f) (define KEY_P #x70)
(define KEY_A #x61) (define KEY_S #x73) (define KEY_D #x64) (define KEY_F #x66) (define KEY_G #x67) (define KEY_H #x68) (define KEY_J #x6a) (define KEY_K #x6b) (define KEY_L #x6c)
(define KEY_Z #x7a) (define KEY_X #x78) (define KEY_C #x63) (define KEY_V #x76) (define KEY_B #x62) (define KEY_N #x6e) (define KEY_M #x6d)
(define KEY_F1 #xffbe) (define KEY_F2 #xffbf) (define KEY_F3 #xffc0) (define KEY_F4 #xffc1) (define KEY_F5 #xffc2) (define KEY_F6 #xffc3) (define KEY_F7 #xffc4) (define KEY_F8 #xffc5) (define KEY_F9 #xffc6)
))
(Darwin
(begin
(define (key-pressed? key)
#false)
(define KEY_ENTER #f) (define KEY_ESC #f)
(define KEY_LEFTCTRL #f) (define KEY_LEFTALT #f) (define KEY_LEFTSHIFT #f)
(define KEY_UP #f) (define KEY_DOWN #f) (define KEY_LEFT #f) (define KEY_RIGHT #f)
(define KEY_1 #f) (define KEY_2 #f) (define KEY_3 #f) (define KEY_4 #f) (define KEY_5 #f) (define KEY_6 #f) (define KEY_7 #f) (define KEY_8 #f) (define KEY_9 #f) (define KEY_0 #f)
(define KEY_MINUS #f) (define KEY_EQUAL #f) (define KEY_BACKSPACE #f) (define KEY_TAB #f)
))
(else
(begin
(runtime-error "Unsupported platform" (syscall 63))))))
|
aa4610a54421e6362e0d0847c8ed8f0a3c18be916006ee860fb7703aba03f5e8 | ChrisPenner/eve | EveSpec.hs | module EveSpec where
import Test.Hspec
spec :: Spec
spec = do
describe "Eve" $ do
it "runs tests" $
True `shouldBe` True
| null | https://raw.githubusercontent.com/ChrisPenner/eve/6081b1ff13229b93e5e5a4505fd23aa0a25c96b1/test/EveSpec.hs | haskell | module EveSpec where
import Test.Hspec
spec :: Spec
spec = do
describe "Eve" $ do
it "runs tests" $
True `shouldBe` True
| |
773d091953703c2c4582e71338741d24ea6acb4f7153e3c4065c996d183aa17b | uw-unsat/serval | x86.rkt | #lang racket/base
(require ffi/unsafe)
(provide (all-defined-out))
(require "const/x86.rkt"
"engine.rkt")
(define-cstruct _uc_x86_mmr ([selector _uint16] [base _uint64] [limit _uint32] [flags _uint32]))
(define-cstruct _uc_x86_msr ([rid _uint32] [value _uint64]))
(struct x86-engine (ptr mode)
#:methods gen:engine
[(define (engine-ptr engine)
(x86-engine-ptr engine))
(define (engine-reg-enum engine)
_uc_x86_reg)
(define (engine-reg-type engine reg)
(case reg
[(idtr gdtr ldtr tr) _uc_x86_mmr]
[(msr) _uc_x86_msr]
FIXME : FP / SEE registers
be safe - default to 64 - bit
[else _uint64]))])
| null | https://raw.githubusercontent.com/uw-unsat/serval/be11ecccf03f81b8bd0557acf8385a6a5d4f51ed/serval/unicorn/x86.rkt | racket | #lang racket/base
(require ffi/unsafe)
(provide (all-defined-out))
(require "const/x86.rkt"
"engine.rkt")
(define-cstruct _uc_x86_mmr ([selector _uint16] [base _uint64] [limit _uint32] [flags _uint32]))
(define-cstruct _uc_x86_msr ([rid _uint32] [value _uint64]))
(struct x86-engine (ptr mode)
#:methods gen:engine
[(define (engine-ptr engine)
(x86-engine-ptr engine))
(define (engine-reg-enum engine)
_uc_x86_reg)
(define (engine-reg-type engine reg)
(case reg
[(idtr gdtr ldtr tr) _uc_x86_mmr]
[(msr) _uc_x86_msr]
FIXME : FP / SEE registers
be safe - default to 64 - bit
[else _uint64]))])
| |
f0a668bf222c056c5153e0db3383af6fb3c10d50f884bea7fa7433e66c46702d | binaryage/chromex | memory.clj | (ns chromex.app.system.memory
"The chrome.system.memory API.
* available since Chrome 36
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro get-info
"Get physical memory information.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [info] where:
|info| - #property-callback-info.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getInfo."
([] (gen-call :function ::get-info &form)))
; -- convenience ------------------------------------------------------------------------------------------------------------
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.system.memory namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
; ---------------------------------------------------------------------------------------------------------------------------
; -- API TABLE --------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------------
(def api-table
{:namespace "chrome.system.memory",
:since "36",
:functions
[{:id ::get-info,
:name "getInfo",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "info", :type "object"}]}}]}]})
; -- helpers ----------------------------------------------------------------------------------------------------------------
; code generation for native API wrapper
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
; code generation for API call-site
(def gen-call (partial gen-call-helper api-table)) | null | https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/apps/chromex/app/system/memory.clj | clojure | -- convenience ------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- API TABLE --------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
-- helpers ----------------------------------------------------------------------------------------------------------------
code generation for native API wrapper
code generation for API call-site | (ns chromex.app.system.memory
"The chrome.system.memory API.
* available since Chrome 36
* "
(:refer-clojure :only [defmacro defn apply declare meta let partial])
(:require [chromex.wrapgen :refer [gen-wrap-helper]]
[chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]]))
(declare api-table)
(declare gen-call)
-- functions --------------------------------------------------------------------------------------------------------------
(defmacro get-info
"Get physical memory information.
This function returns a core.async channel of type `promise-chan` which eventually receives a result value.
Signature of the result value put on the channel is [info] where:
|info| - #property-callback-info.
In case of an error the channel closes without receiving any value and relevant error object can be obtained via
chromex.error/get-last-error.
#method-getInfo."
([] (gen-call :function ::get-info &form)))
(defmacro tap-all-events
"Taps all valid non-deprecated events in chromex.app.system.memory namespace."
[chan]
(gen-tap-all-events-call api-table (meta &form) chan))
(def api-table
{:namespace "chrome.system.memory",
:since "36",
:functions
[{:id ::get-info,
:name "getInfo",
:callback? true,
:params [{:name "callback", :type :callback, :callback {:params [{:name "info", :type "object"}]}}]}]})
(defmacro gen-wrap [kind item-id config & args]
(apply gen-wrap-helper api-table kind item-id config args))
(def gen-call (partial gen-call-helper api-table)) |
4e5da117717fa70533c7cacd945258d500ea97d8cdbbcf865457e454035bc005 | nikivazou/proof-combinators | Reverse.hs | {-@ LIQUID "--exactdc" @-}
{-@ LIQUID "--higherorder" @-}
module Reverse where
import LiquidHaskell.ProofCombinators
import Prelude hiding (reverse, (++), length)
{-@ measure length @-}
{-@ length :: [a] -> Nat @-}
length :: [a] -> Int
length [] = 0
length (_:xs) = 1 + length xs
{-@ infix : @-}
{-@ reflect reverse @-}
{-@ reverse :: is:[a] -> {os:[a] | length is == length os} @-}
reverse :: [a] -> [a]
reverse [] = []
reverse (x:xs) = reverse xs ++ [x]
{-@ infix ++ @-}
{-@ reflect ++ @-}
{-@ (++) :: xs:[a] -> ys:[a] -> {os:[a] | length os == length xs + length ys} @-}
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x:(xs ++ ys)
singletonP :: a -> Proof
{-@ singletonP :: x:a -> { reverse [x] == [x] } @-}
singletonP x
= reverse [x]
==. reverse [] ++ [x]
==. [] ++ [x]
==. [x]
*** QED
| null | https://raw.githubusercontent.com/nikivazou/proof-combinators/0df3094cf361f29608fa0718be5050a4e8e8af9f/examples/Reverse.hs | haskell | @ LIQUID "--exactdc" @
@ LIQUID "--higherorder" @
@ measure length @
@ length :: [a] -> Nat @
@ infix : @
@ reflect reverse @
@ reverse :: is:[a] -> {os:[a] | length is == length os} @
@ infix ++ @
@ reflect ++ @
@ (++) :: xs:[a] -> ys:[a] -> {os:[a] | length os == length xs + length ys} @
@ singletonP :: x:a -> { reverse [x] == [x] } @ |
module Reverse where
import LiquidHaskell.ProofCombinators
import Prelude hiding (reverse, (++), length)
length :: [a] -> Int
length [] = 0
length (_:xs) = 1 + length xs
reverse :: [a] -> [a]
reverse [] = []
reverse (x:xs) = reverse xs ++ [x]
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x:(xs ++ ys)
singletonP :: a -> Proof
singletonP x
= reverse [x]
==. reverse [] ++ [x]
==. [] ++ [x]
==. [x]
*** QED
|
4048f2b701c71fe41e9f390cec589b5c37cc5a14775c0808c1ccef8abb9c6286 | comby-tools/comby | test_c_style_comments_alpha.ml | open Core
open Rewriter
open Test_helpers
include Test_alpha
let all ?(configuration = configuration) template source =
C.all ~configuration ~template ~source ()
let%expect_test "rewrite_comments_1" =
let template = "replace this :[1] end" in
let source = "/* don't replace this () end */ do replace this () end" in
let rewrite_template = "X" in
all template source
|> (fun matches ->
Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact "/* don't replace this () end */ do X"]
let%expect_test "rewrite_comments_2" =
let template =
{|
if (:[1]) { :[2] }
|}
in
let source =
{|
/* if (fake_condition_body_must_be_non_empty) { fake_body; } */
// if (fake_condition_body_must_be_non_empty) { fake_body; }
if (real_condition_body_must_be_empty) {
int i;
int j;
}
|}
in
let rewrite_template =
{|
if (:[1]) {}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
if (real_condition_body_must_be_empty) {}
|}]
let%expect_test "capture_comments" =
let template = {|if (:[1]) { :[2] }|} in
let source = {|if (true) { /* some comment */ console.log(z); }|} in
let matches = all template source in
print_matches matches;
[%expect_exact {|[
{
"range": {
"start": { "offset": 0, "line": 1, "column": 1 },
"end": { "offset": 48, "line": 1, "column": 49 }
},
"environment": [
{
"variable": "1",
"value": "true",
"range": {
"start": { "offset": 4, "line": 1, "column": 5 },
"end": { "offset": 8, "line": 1, "column": 9 }
}
},
{
"variable": "2",
"value": "console.log(z);",
"range": {
"start": { "offset": 31, "line": 1, "column": 32 },
"end": { "offset": 46, "line": 1, "column": 47 }
}
}
],
"matched": "if (true) { /* some comment */ console.log(z); }"
}
]|}]
let%expect_test "single_quote_in_comment" =
let template =
{| {:[1]} |}
in
let source =
{|
/*'*/
{test}
|}
in
let rewrite_template =
{|
{:[1]}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
{test}
|}]
let%expect_test "single_quote_in_comment" =
let template =
{| {:[1]} |}
in
let source =
{|
{
a = 1;
/* Events with mask == AE_NONE are not set. So let's initiaize the
* vector with it. */
for (i = 0; i < setsize; i++)
}
|}
in
let rewrite_template =
{|
{:[1]}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
{
a = 1;
/* Events with mask == AE_NONE are not set. So let's initiaize the
* vector with it. */
for (i = 0; i < setsize; i++)
}
|}]
let%expect_test "single_quote_in_comment" =
let template =
{| {:[1]} |}
in
let source =
{|
{
a = 1;
/* ' */
for (i = 0; i < setsize; i++)
}
|}
in
let rewrite_template =
{|
{:[1]}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
{
a = 1;
/* ' */
for (i = 0; i < setsize; i++)
}
|}]
let%expect_test "give_back_the_comment_characters_for_newline_comments_too" =
let template =
{| {:[1]} |}
in
let source =
{|
{
// a comment
}
|}
in
let rewrite_template =
{|
{:[1]}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
{
// a comment
}
|}]
let%expect_test "comments_in_templates_imply_whitespace" =
let template =
{|
/* f */
// q
a
|}
in
let source =
{|
// idgaf
/* fooo */
a
|}
in
let rewrite_template =
{|erased|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|erased|}]
| null | https://raw.githubusercontent.com/comby-tools/comby/7b401063024da9ddc94446ade27a24806398d838/test/common/test_c_style_comments_alpha.ml | ocaml | open Core
open Rewriter
open Test_helpers
include Test_alpha
let all ?(configuration = configuration) template source =
C.all ~configuration ~template ~source ()
let%expect_test "rewrite_comments_1" =
let template = "replace this :[1] end" in
let source = "/* don't replace this () end */ do replace this () end" in
let rewrite_template = "X" in
all template source
|> (fun matches ->
Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact "/* don't replace this () end */ do X"]
let%expect_test "rewrite_comments_2" =
let template =
{|
if (:[1]) { :[2] }
|}
in
let source =
{|
/* if (fake_condition_body_must_be_non_empty) { fake_body; } */
// if (fake_condition_body_must_be_non_empty) { fake_body; }
if (real_condition_body_must_be_empty) {
int i;
int j;
}
|}
in
let rewrite_template =
{|
if (:[1]) {}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
if (real_condition_body_must_be_empty) {}
|}]
let%expect_test "capture_comments" =
let template = {|if (:[1]) { :[2] }|} in
let source = {|if (true) { /* some comment */ console.log(z); }|} in
let matches = all template source in
print_matches matches;
[%expect_exact {|[
{
"range": {
"start": { "offset": 0, "line": 1, "column": 1 },
"end": { "offset": 48, "line": 1, "column": 49 }
},
"environment": [
{
"variable": "1",
"value": "true",
"range": {
"start": { "offset": 4, "line": 1, "column": 5 },
"end": { "offset": 8, "line": 1, "column": 9 }
}
},
{
"variable": "2",
"value": "console.log(z);",
"range": {
"start": { "offset": 31, "line": 1, "column": 32 },
"end": { "offset": 46, "line": 1, "column": 47 }
}
}
],
"matched": "if (true) { /* some comment */ console.log(z); }"
}
]|}]
let%expect_test "single_quote_in_comment" =
let template =
{| {:[1]} |}
in
let source =
{|
/*'*/
{test}
|}
in
let rewrite_template =
{|
{:[1]}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
{test}
|}]
let%expect_test "single_quote_in_comment" =
let template =
{| {:[1]} |}
in
let source =
{|
{
a = 1;
/* Events with mask == AE_NONE are not set. So let's initiaize the
* vector with it. */
for (i = 0; i < setsize; i++)
}
|}
in
let rewrite_template =
{|
{:[1]}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
{
a = 1;
/* Events with mask == AE_NONE are not set. So let's initiaize the
* vector with it. */
for (i = 0; i < setsize; i++)
}
|}]
let%expect_test "single_quote_in_comment" =
let template =
{| {:[1]} |}
in
let source =
{|
{
a = 1;
/* ' */
for (i = 0; i < setsize; i++)
}
|}
in
let rewrite_template =
{|
{:[1]}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
{
a = 1;
/* ' */
for (i = 0; i < setsize; i++)
}
|}]
let%expect_test "give_back_the_comment_characters_for_newline_comments_too" =
let template =
{| {:[1]} |}
in
let source =
{|
{
// a comment
}
|}
in
let rewrite_template =
{|
{:[1]}
|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|
{
// a comment
}
|}]
let%expect_test "comments_in_templates_imply_whitespace" =
let template =
{|
/* f */
// q
a
|}
in
let source =
{|
// idgaf
/* fooo */
a
|}
in
let rewrite_template =
{|erased|}
in
all template source
|> (fun matches -> Option.value_exn (Rewrite.all ~source ~rewrite_template matches))
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string;
[%expect_exact
{|erased|}]
| |
5524d9dd31b33e30cf3581f471857f0469b87437749ae19b6cfcaebb35f6f8b7 | fujita-y/digamma | library.scm | Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
;;; See LICENSE file for terms and conditions of use.
(define scheme-library-paths (make-parameter '()))
(define scheme-library-exports (make-parameter (make-core-hashtable)))
(define scheme-library-versions (make-parameter (make-core-hashtable)))
(define exact-nonnegative-integer? (lambda (obj) (and (integer? obj) (exact? obj) (>= obj 0))))
(define id-list->string
(lambda (ref infix)
(apply
string-append
(cdr
(let loop ((lst ref))
(cond ((null? lst) '())
((symbol? (car lst))
(cons infix (cons (symbol->string (car lst)) (loop (cdr lst)))))
((number? (car lst))
(cons infix (cons (number->string (car lst)) (loop (cdr lst)))))
(else (loop (cdr lst)))))))))
(define generate-library-id
(lambda (name)
(string->symbol (id-list->string name (format "~a" (current-library-infix))))))
(define library-name->id
(lambda (form name)
(define malformed-name
(lambda ()
(if form
(syntax-violation 'library "malformed library name" (abbreviated-take-form form 4 8) name)
(syntax-violation 'library "malformed library name" name))))
(if (and (list? name) (not (null? name)))
(cond ((every1 symbol? name) (string->symbol (id-list->string name (format "~a" (current-library-infix)))))
((and (>= (lexical-syntax-version) 7)
(every1 (lambda (e) (or (symbol? e) (exact-nonnegative-integer? e))) name))
(string->symbol (id-list->string name (format "~a" (current-library-infix)))))
(else
(let ((body (list-head name (- (length name) 1))))
(if (every1 symbol? body)
(string->symbol (id-list->string body (format "~a" (current-library-infix))))
(malformed-name)))))
(malformed-name))))
(define library-name->version
(lambda (form name)
(define malformed-version
(lambda ()
(if (pair? form)
(syntax-violation 'library "malformed library version" (abbreviated-take-form form 4 8) name)
(syntax-violation 'library "malformed library version" name))))
(if (and (list? name) (not (null? name)))
(cond ((every1 symbol? name) #f)
((and (>= (lexical-syntax-version) 7) (every1 (lambda (e) (or (symbol? e) (exact-nonnegative-integer? e))) name)) #f)
(else
(let ((tail (car (list-tail name (- (length name) 1)))))
(cond ((null? tail) #f)
((and (list? tail) (every1 exact-nonnegative-integer? tail)) tail)
(else (malformed-version))))))
(malformed-version))))
(define library-reference->name
(lambda (form lst)
(define malformed-name
(lambda ()
(if (pair? form)
(syntax-violation 'library "malformed library name" (abbreviated-take-form form 4 8) lst)
(syntax-violation 'library "malformed library name" lst))))
(cond ((every1 symbol? lst) lst)
((and (>= (lexical-syntax-version) 7) (every1 (lambda (e) (or (symbol? e) (exact-nonnegative-integer? e))) lst)) lst)
(else
(let ((body (list-head lst (- (length lst) 1))))
(cond ((every1 symbol? body) body) (else (malformed-name))))))))
(define flatten-library-reference
(lambda (form lst)
(or (and (list? lst) (not (null? lst)))
(syntax-violation 'library "malformed library name" (abbreviated-take-form form 4 8) lst))
(destructuring-match lst
(('library (ref ...)) (flatten-library-reference form ref))
(('library . _) (syntax-violation 'library "malformed library name" (abbreviated-take-form form 4 8) lst))
(_ lst))))
(define library-reference->version
(lambda (form lst)
(define malformed-version
(lambda ()
(if (pair? form)
(syntax-violation 'import "malformed library version" (abbreviated-take-form form 4 8) lst)
(syntax-violation 'import "malformed library version" lst))))
(if (and (list? lst) (not (null? lst)))
(cond ((every1 symbol? lst) #f)
((and (>= (lexical-syntax-version) 7) (every1 (lambda (e) (or (symbol? e) (exact-nonnegative-integer? e))) lst)) #f)
(else (let ((tail (car (list-tail lst (- (length lst) 1))))) (cond ((list? tail) tail) (else (malformed-version))))))
(malformed-version))))
(define test-library-versions
(lambda (form spec reference current)
(define exact-nonnegative-integer?
(lambda (obj) (and (integer? obj) (exact? obj) (>= obj 0))))
(or (let loop ((reference reference))
(destructuring-match reference
(('not ref) (not (loop ref)))
(('or ref ...) (any1 (lambda (e) (loop e)) ref))
(('and ref ...) (every1 (lambda (e) (loop e)) ref))
(sub-reference
(let loop ((current current) (sub-reference sub-reference))
(or (and (list? current) (list? sub-reference))
(syntax-violation 'import "malformed version reference" (abbreviated-take-form form 4 8) spec))
(or (null? sub-reference)
(and (>= (length current) (length sub-reference))
(let ((current (list-head current (length sub-reference))))
(every2
(lambda (c s)
(destructuring-match s
(('not ref) (not (loop c ref)))
(('>= (? exact-nonnegative-integer? n)) (>= c n))
(('<= (? exact-nonnegative-integer? n)) (<= c n))
(('and ref ...) (every1 (lambda (e) (loop (list c) (list e))) ref))
(('or ref ...) (any1 (lambda (e) (loop (list c) (list e))) ref))
((? exact-nonnegative-integer? n) (= c n))
(else
(syntax-violation
'import
"malformed version reference"
(abbreviated-take-form form 4 8)
spec))))
current
sub-reference))))))))
(syntax-violation
'import
(format "mismatch between version reference ~a and current version ~a" reference current)
(abbreviated-take-form form 4 8)
spec))))
(define make-shield-id-table
(lambda (lst)
(let ((visited (make-core-hashtable)) (ids (make-core-hashtable)) (deno (make-unbound)))
(let loop ((lst lst))
(cond ((symbol? lst) (core-hashtable-set! ids lst deno))
((pair? lst)
(or (core-hashtable-contains? visited lst)
(begin (core-hashtable-set! visited lst #t) (loop (car lst)) (loop (cdr lst)))))
((vector? lst)
(or (core-hashtable-contains? visited lst)
(begin (core-hashtable-set! visited lst #t) (loop (vector->list lst)))))))
ids)))
(define parse-exports
(lambda (form specs)
(let loop ((spec specs) (exports '()))
(destructuring-match spec
(() (reverse exports))
(((? symbol? id) . more) (loop more (acons id id exports)))
((('rename . alist) . more)
(begin
(or (every1 (lambda (e) (= (safe-length e) 2)) alist)
(syntax-violation 'export "malformed export spec" (abbreviated-take-form form 4 8) (car spec)))
(loop more (append (map (lambda (e) (cons (car e) (cadr e))) alist) exports))))
(_ (syntax-violation 'export "malformed export spec" (abbreviated-take-form form 4 8) (car spec)))))))
(define parse-imports
(lambda (form specs)
(define check-unbound-identifier
(lambda (bindings ids subform)
(for-each
(lambda (id)
(or (assq id bindings)
(syntax-violation
'import
(format "attempt to reference unexported identifier ~a" id)
(abbreviated-take-form form 4 8)
subform)))
ids)))
(define check-bound-identifier
(lambda (bindings ids subform)
(for-each
(lambda (id)
(and (assq id bindings)
(syntax-violation
'import
(format "duplicate import identifiers ~a" id)
(abbreviated-take-form form 4 8)
subform)))
ids)))
(let loop ((spec specs) (imports '()))
(destructuring-match spec
(() imports)
((('for set . phases) . more) (loop more (loop (list set) imports)))
((('only set . ids) . more)
(let ((bindings (loop (list set) '())))
(check-unbound-identifier bindings ids (car spec))
(loop more (append (filter (lambda (e) (memq (car e) ids)) bindings) imports))))
((('except set . ids) . more)
(let ((bindings (loop (list set) '())))
(check-unbound-identifier bindings ids (car spec))
(loop more (append (filter (lambda (e) (not (memq (car e) ids))) bindings) imports))))
((('rename set . alist) . more)
(let ((bindings (loop (list set) '())))
(or (every1 (lambda (e) (= (safe-length e) 2)) alist)
(syntax-violation 'import "malformed import set" (abbreviated-take-form form 4 8) (car spec)))
(or (and (unique-id-list? (map car alist)) (unique-id-list? (map cadr alist)))
(syntax-violation
'import
"duplicate identifers in rename specs"
(abbreviated-take-form form 4 8)
(car spec)))
(check-bound-identifier bindings (map cadr alist) (car spec))
(check-unbound-identifier bindings (map car alist) (car spec))
(loop
more
(append
(map (lambda (e)
(cond ((assq (car e) alist) => (lambda (rename) (cons (cadr rename) (cdr e)))) (else e)))
bindings)
imports))))
((('prefix set id) . more)
(loop
more
(append
(map (lambda (e) (cons (string->symbol (format "~a~a" id (car e))) (cdr e))) (loop (list set) '()))
imports)))
((ref . more)
(let ((ref (flatten-library-reference form ref)))
(let ((name (library-reference->name form ref)) (version (library-reference->version form ref)))
(|.require-scheme-library| name)
(let ((library-id (library-name->id form name)))
(cond
((and version (core-hashtable-ref (scheme-library-versions) library-id #f))
=> (lambda (current-version) (test-library-versions form ref version current-version))))
(loop
more
(cond ((core-hashtable-ref (scheme-library-exports) library-id #f)
=> (lambda (lst) (append lst imports)))
(else
(syntax-violation
'import
(format "attempt to import undefined library ~s" name)
(abbreviated-take-form form 4 8)))))))))
(_ (syntax-violation 'import "malformed import set" (abbreviated-take-form form 4 8) (car spec)))))))
(define parse-depends
(lambda (form specs)
(let loop ((spec specs) (depends '()))
(destructuring-match spec
(() depends)
((('for set . _) . more) (loop more (loop (list set) depends)))
((('only set . _) . more) (loop more (loop (list set) depends)))
((('except set . _) . more) (loop more (loop (list set) depends)))
((('rename set . _) . more) (loop more (loop (list set) depends)))
((('prefix set _) . more) (loop more (loop (list set) depends)))
((ref . more)
(let ((ref (flatten-library-reference form ref)))
(let ((name (library-reference->name form ref))) (loop more (cons name depends)))))
(_ (syntax-violation 'import "malformed import set" (abbreviated-take-form form 4 8) (car spec)))))))
(define check-duplicate-definition
(lambda (who defs macros renames)
(or (unique-id-list? (map car renames))
(let ((id (find-duplicates (map car renames))))
(cond ((assq id defs)
=>
(lambda (e1)
(let ((e2 (assq id (reverse defs))))
(cond ((eq? e1 e2)
(let ((e2 (assq id macros)))
(syntax-violation
who
"duplicate definitions"
(annotate `(define-syntax ,(car e2) ...) e2)
(annotate `(define ,@e1) e1))))
(else
(syntax-violation
who
"duplicate definitions"
(annotate `(define ,@e1) e1)
(annotate `(define ,@e2) e2)))))))
((assq id macros)
=>
(lambda (e1)
(let ((e2 (assq id (reverse macros))))
(cond ((eq? e1 e2)
(let ((e2 (assq id defs)))
(syntax-violation
who
"duplicate definitions"
(annotate `(define-syntax ,(car e1) ...) e1)
(annotate `(define ,@e2) e2))))
(else
(syntax-violation
who
"duplicate definitions"
(annotate `(define-syntax ,(car e1) ...) e1)
(annotate `(define-syntax ,(car e2) ...) e2)))))))
(else (syntax-violation who "duplicate definitions" id)))))))
(define expand-library
(lambda (form env)
(define permute-env
(lambda (ht)
(let loop ((lst (core-hashtable->alist ht)) (bounds '()) (unbounds '()))
(cond ((null? lst) (append bounds unbounds))
((unbound? (cdar lst)) (loop (cdr lst) bounds (cons (car lst) unbounds)))
(else (loop (cdr lst) (cons (car lst) bounds) unbounds))))))
(parameterize ((lexical-syntax-version 6))
(destructuring-match form
((_ library-name ('export export-spec ...) ('import import-spec ...) body ...)
(let ((library-id (library-name->id form library-name)) (library-version (library-name->version form library-name)))
(and library-version (core-hashtable-set! (scheme-library-versions) library-id library-version))
(parameterize ((current-include-files (make-core-hashtable)))
(let ((coreform
(let ((exports (parse-exports form export-spec))
(imports (parse-imports form import-spec))
(depends (parse-depends form import-spec))
(ht-immutables (make-core-hashtable))
(ht-imports (make-core-hashtable))
(ht-publics (make-core-hashtable)))
(for-each
(lambda (a)
(and (core-hashtable-ref ht-publics (cdr a) #f)
(syntax-violation 'library "duplicate export identifiers" (abbreviated-take-form form 4 8) (cdr a)))
(core-hashtable-set! ht-publics (cdr a) #t)
(core-hashtable-set! ht-immutables (car a) #t))
exports)
(for-each
(lambda (a)
(core-hashtable-set! ht-immutables (car a) #t)
(cond ((core-hashtable-ref ht-imports (car a) #f)
=>
(lambda (deno)
(or (eq? deno (cdr a))
(syntax-violation
'library
"duplicate import identifiers"
(abbreviated-take-form form 4 8)
(car a)))))
(else (core-hashtable-set! ht-imports (car a) (cdr a)))))
imports)
(let ((ht-env (make-shield-id-table body)) (ht-libenv (make-core-hashtable)))
(for-each
(lambda (a) (core-hashtable-set! ht-env (car a) (cdr a)) (core-hashtable-set! ht-libenv (car a) (cdr a)))
(core-hashtable->alist ht-imports))
(parameterize ((current-immutable-identifiers ht-immutables))
(expand-library-body
form
library-id
library-version
body
exports
imports
depends
(extend-env private-primitives-environment (permute-env ht-env))
(permute-env ht-libenv)))))))
(or (= (core-hashtable-size (current-include-files)) 0)
(core-hashtable-set! library-include-dependencies library-id (current-include-files)))
coreform))))
(_ (syntax-violation 'library "expected library name, export spec, and import spec" (abbreviated-take-form form 4 8)))))))
(define expand-library-body
(lambda (form library-id library-version body exports imports depends env libenv)
(define initial-libenv #f)
(define internal-definition?
(lambda (lst)
(and (pair? lst)
(pair? (car lst))
(symbol? (caar lst))
(let ((deno (env-lookup env (caar lst))))
(or (macro? deno)
(eq? denote-define deno)
(eq? denote-define-syntax deno)
(eq? denote-let-syntax deno)
(eq? denote-letrec-syntax deno))))))
(define macro-defs '())
(define extend-env!
(lambda (datum1 datum2)
(and (macro? datum2) (set! macro-defs (acons datum1 datum2 macro-defs)))
(set! env (extend-env (list (cons datum1 datum2)) env))
(for-each (lambda (a) (set-cdr! (cddr a) env)) macro-defs)))
(define extend-libenv!
(lambda (datum1 datum2)
(set! libenv (extend-env (list (cons datum1 datum2)) libenv))
(current-template-environment libenv)))
(define rewrite-body
(lambda (body defs macros renames)
(rewrite-library-body
form
library-id
library-version
body
defs
macros
renames
exports
imports
depends
env
libenv)))
(define ht-imported-immutables (make-core-hashtable))
(current-template-environment libenv)
(for-each (lambda (b) (core-hashtable-set! ht-imported-immutables (car b) #t)) imports)
(let loop ((body (flatten-begin body env)) (defs '()) (macros '()) (renames '()))
(cond ((and (pair? body) (pair? (car body)) (symbol? (caar body)))
(let ((deno (env-lookup env (caar body))))
(cond ((eq? denote-begin deno) (loop (flatten-begin body env) defs macros renames))
((eq? denote-define-syntax deno)
(destructuring-match body
(((_ (? symbol? org) clause) more ...)
(begin
(and (core-hashtable-contains? ht-imported-immutables org)
(syntax-violation 'define-syntax "attempt to modify immutable binding" (car body)))
(let-values (((code . expr)
(parameterize ((current-template-environment initial-libenv))
(compile-macro (car body) clause env))))
(let ((new (generate-global-id library-id org)))
(extend-libenv! org (make-import new))
(cond ((procedure? code)
(extend-env! org (make-macro code env))
(loop
more
defs
(cons (list org 'procedure (car expr)) macros)
(acons org new renames)))
((macro-variable? code)
(extend-env! org (make-macro-variable (cadr code) env))
(loop
more
defs
(cons (list org 'variable (car expr)) macros)
(acons org new renames)))
(else
(extend-env! org (make-macro code env))
(loop
more
defs
(cons (list org 'template code) macros)
(acons org new renames))))))))
(_ (syntax-violation 'define-syntax "expected symbol and single expression" (car body)))))
((eq? denote-define deno)
(let ((def (annotate (cdr (desugar-define (car body))) (car body))))
(and (core-hashtable-contains? ht-imported-immutables (car def))
(syntax-violation 'define "attempt to modify immutable binding" (car body)))
(let ((org (car def)) (new (generate-global-id library-id (car def))))
(extend-env! org new)
(extend-libenv! org (make-import new))
(loop (cdr body) (cons def defs) macros (acons org new renames)))))
((or (macro? deno) (eq? denote-let-syntax deno) (eq? denote-letrec-syntax deno))
(let-values (((expr new) (expand-initial-forms (car body) env)))
(set! env new)
(let ((maybe-def (flatten-begin (list expr) env)))
(cond ((null? maybe-def) (loop (cdr body) defs macros renames))
((internal-definition? maybe-def)
(loop (append maybe-def (cdr body)) defs macros renames))
(else (rewrite-body body (reverse defs) (reverse macros) renames))))))
(else (rewrite-body body (reverse defs) (reverse macros) renames)))))
(else (rewrite-body body (reverse defs) (reverse macros) renames))))))
(define rewrite-library-body
(lambda (form library-id library-version body defs macros renames exports imports depends env libenv)
(define extend-libenv!
(lambda (datum1 datum2)
(set! libenv (extend-env (list (cons datum1 datum2)) libenv))
(current-template-environment libenv)))
(define rewrite-env
(lambda (env)
(let loop ((lst (reverse env)) (acc '()))
(cond ((null? lst) acc)
((uninterned-symbol? (caar lst))
(if (assq (cdar lst) defs)
(loop (cdr lst) (cons (cons (caar lst) (cddr (assq (cdar lst) libenv))) acc))
(loop (cdr lst) (cons (car lst) acc))))
((assq (caar lst) (cdr lst)) (loop (cdr lst) acc))
(else (loop (cdr lst) (cons (car lst) acc)))))))
(define make-rule-macro
(lambda (type id spec shared-env) `(|.set-top-level-macro!| ',type ',id ',spec ,shared-env)))
(define make-var-macro
(lambda (type id spec shared-env)
`(|.set-top-level-macro!| ',type ',id (|.transformer-thunk| ,spec) ,shared-env)))
(define make-proc-macro
(lambda (type id spec shared-env)
(cond ((and (pair? spec) (eq? (car spec) 'lambda))
`(|.set-top-level-macro!| ',type ',id (|.transformer-thunk| ,spec) ,shared-env))
(else
(let ((x (generate-temporary-symbol)))
`(|.set-top-level-macro!|
',type
',id
(let ((proc #f))
(lambda (,x) (if proc (proc ,x) (begin (set! proc (|.transformer-thunk| ,spec)) (proc ,x)))))
,shared-env))))))
(check-duplicate-definition 'library defs macros renames)
(let ((env (rewrite-env env)))
(let ((rewrited-body (expand-each body env)))
(let* ((rewrited-depends (map (lambda (dep) `(|.require-scheme-library| ',dep)) depends))
(rewrited-defs
(map (lambda (def)
(parameterize ((current-top-level-exterior (car def)))
(let ((lhs (cdr (assq (car def) renames))) (rhs (expand-form (cadr def) env)))
(set-closure-comment! rhs lhs)
`(define ,lhs ,rhs))))
defs))
(rewrited-macros
(cond ((null? macros) '())
(else
(let ((ht-visibles (make-core-hashtable)))
(for-each (lambda (e) (core-hashtable-set! ht-visibles (car e) #t)) macros)
(let loop ((lst (map caddr macros)))
(cond ((pair? lst) (loop (car lst)) (loop (cdr lst)))
((symbol? lst) (core-hashtable-set! ht-visibles lst #t))
((vector? lst) (loop (vector->list lst)))))
(for-each
(lambda (b)
(or (assq (car b) libenv)
(let ((deno (env-lookup env (car b))))
(if (and (symbol? deno) (not (eq? deno (car b))))
(extend-libenv! (car b) (make-import deno))
(or (uninterned-symbol? (car b))
(core-primitive-name? (car b))
(extend-libenv! (car b) (make-unbound)))))))
(core-hashtable->alist ht-visibles))
(let ((shared-env (generate-temporary-symbol)))
`((let ((,shared-env
',(let ((ht (make-core-hashtable)))
(for-each
(lambda (a)
(and (core-hashtable-contains? ht-visibles (car a))
(core-hashtable-set! ht (car a) (cdr a))))
(reverse libenv))
(core-hashtable->alist ht))))
,@(map (lambda (e)
(let ((id (cdr (assq (car e) renames))) (type (cadr e)) (spec (caddr e)))
(case type
((template) (make-rule-macro 'syntax id spec shared-env))
((procedure) (make-proc-macro 'syntax id spec shared-env))
((variable) (make-var-macro 'variable id spec shared-env))
(else
(scheme-error
"internal error in rewrite body: bad macro spec ~s"
e)))))
macros))))))))
(rewrited-exports
`(|.intern-scheme-library|
',library-id
',library-version
',(begin
(map (lambda (e)
(cons (cdr e)
(cond ((assq (car e) renames) => (lambda (a) (make-import (cdr a))))
((assq (car e) imports) => cdr)
(else
(current-macro-expression #f)
(syntax-violation
'library
(format "attempt to export unbound identifier ~u" (car e))
(caddr form))))))
exports)))))
(let ((vars (map cadr rewrited-defs)) (assignments (map caddr rewrited-defs)))
(cond
((check-rec*-contract-violation vars assignments)
=>
(lambda (var)
(let ((id (any1 (lambda (a) (and (eq? (cdr a) (car var)) (car a))) renames)))
(current-macro-expression #f)
(syntax-violation
#f
(format "attempt to reference uninitialized variable ~u" id)
(any1
(lambda (e) (and (check-rec-contract-violation (list id) e) (annotate `(define ,@e) e)))
defs)))))))
(annotate
`(begin ,@rewrited-depends ,@rewrited-defs ,@rewrited-body ,@rewrited-macros ,rewrited-exports)
form))))))
(define import-top-level-bindings
(lambda (bindings)
(let ((ht1 (make-core-hashtable)) (ht2 (current-top-level-renames)))
(for-each
(lambda (binding)
(core-hashtable-delete! ht2 (car bindings))
(cond ((core-hashtable-ref ht1 (cddr binding) #f) => (lambda (id) (core-hashtable-set! ht2 (car binding) id)))
(else (core-hashtable-set! ht1 (cddr binding) (car binding)))))
bindings)
(current-top-level-renames ht2))
(for-each
(lambda (binding)
(let ((intern (car binding)) (extern (cddr binding)))
(or (eq? intern extern)
(cond ((core-hashtable-ref (current-macro-environment) extern #f)
=>
(lambda (deno)
(if (top-level-bound? intern) (set-top-level-value! intern |.&UNDEF|))
(core-hashtable-set! (current-macro-environment) intern deno)))
(else
(core-hashtable-delete! (current-macro-environment) intern)
(set-top-level-value! intern (top-level-value extern)))))))
bindings)))
(define expand-import
(lambda (form env)
(and (unexpect-top-level-form) (syntax-violation 'import "misplaced top-level directive" form))
(auto-compile-cache-update)
(let ((imports (parse-imports form (cdr form))) (ht-bindings (make-core-hashtable)))
(for-each
(lambda (a)
(cond ((core-hashtable-ref ht-bindings (car a) #f)
=>
(lambda (deno)
(or (eq? deno (cdr a))
(syntax-violation
'import
"duplicate import identifiers"
(abbreviated-take-form form 4 8)
(car a)))))
(else (core-hashtable-set! ht-bindings (car a) (cdr a)))))
imports)
(import-top-level-bindings (core-hashtable->alist ht-bindings)))))
(define count-pending-import
(lambda ()
(length
(filter
(lambda (e) (eq? e 'pending))
(map cdr (core-hashtable->alist (scheme-library-exports)))))))
(set-top-level-value! '|.require-scheme-library|
(lambda (ref)
(let ((library-id (generate-library-id ref)))
(let ((exports (core-hashtable-ref (scheme-library-exports) library-id #f)))
(define lock-fd #f)
(cond ((eq? exports 'pending)
(core-hashtable-set! (scheme-library-exports) library-id #f)
(syntax-violation 'library "encountered cyclic dependencies" ref))
((eq? exports #f)
(dynamic-wind
(lambda ()
(and (auto-compile-cache)
(= (count-pending-import) 0)
(set! lock-fd (acquire-lockfile (auto-compile-cache-lock-path))))
(core-hashtable-set! (scheme-library-exports) library-id 'pending))
(lambda () (load-scheme-library ref #f))
(lambda ()
(and (eq? (core-hashtable-ref (scheme-library-exports) library-id #f) 'pending)
(core-hashtable-set! (scheme-library-exports) library-id #f))
(and (auto-compile-cache)
(= (count-pending-import) 0)
(release-lockfile lock-fd))))))))
(unspecified)))
(define unify-import-bindings
(let ((ht-import-bindings (make-core-hashtable 'equal?)))
(lambda (lst)
(map (lambda (binding)
(cond ((core-hashtable-ref ht-import-bindings binding #f) => values)
(else (begin (core-hashtable-set! ht-import-bindings binding binding) binding))))
lst))))
(set-top-level-value!
'|.intern-scheme-library|
(lambda (library-id library-version exports)
(and library-version (core-hashtable-set! (scheme-library-versions) library-id library-version))
(core-hashtable-set! (scheme-library-exports) library-id (unify-import-bindings exports))))
(set-top-level-value!
'|.unintern-scheme-library|
(lambda (library-id) (core-hashtable-delete! (scheme-library-exports) library-id)))
| null | https://raw.githubusercontent.com/fujita-y/digamma/31f1512de2d406448ba3a9c8c352c56f30eb99e4/heap/boot/macro/library.scm | scheme | See LICENSE file for terms and conditions of use. | Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
(define scheme-library-paths (make-parameter '()))
(define scheme-library-exports (make-parameter (make-core-hashtable)))
(define scheme-library-versions (make-parameter (make-core-hashtable)))
(define exact-nonnegative-integer? (lambda (obj) (and (integer? obj) (exact? obj) (>= obj 0))))
(define id-list->string
(lambda (ref infix)
(apply
string-append
(cdr
(let loop ((lst ref))
(cond ((null? lst) '())
((symbol? (car lst))
(cons infix (cons (symbol->string (car lst)) (loop (cdr lst)))))
((number? (car lst))
(cons infix (cons (number->string (car lst)) (loop (cdr lst)))))
(else (loop (cdr lst)))))))))
(define generate-library-id
(lambda (name)
(string->symbol (id-list->string name (format "~a" (current-library-infix))))))
(define library-name->id
(lambda (form name)
(define malformed-name
(lambda ()
(if form
(syntax-violation 'library "malformed library name" (abbreviated-take-form form 4 8) name)
(syntax-violation 'library "malformed library name" name))))
(if (and (list? name) (not (null? name)))
(cond ((every1 symbol? name) (string->symbol (id-list->string name (format "~a" (current-library-infix)))))
((and (>= (lexical-syntax-version) 7)
(every1 (lambda (e) (or (symbol? e) (exact-nonnegative-integer? e))) name))
(string->symbol (id-list->string name (format "~a" (current-library-infix)))))
(else
(let ((body (list-head name (- (length name) 1))))
(if (every1 symbol? body)
(string->symbol (id-list->string body (format "~a" (current-library-infix))))
(malformed-name)))))
(malformed-name))))
(define library-name->version
(lambda (form name)
(define malformed-version
(lambda ()
(if (pair? form)
(syntax-violation 'library "malformed library version" (abbreviated-take-form form 4 8) name)
(syntax-violation 'library "malformed library version" name))))
(if (and (list? name) (not (null? name)))
(cond ((every1 symbol? name) #f)
((and (>= (lexical-syntax-version) 7) (every1 (lambda (e) (or (symbol? e) (exact-nonnegative-integer? e))) name)) #f)
(else
(let ((tail (car (list-tail name (- (length name) 1)))))
(cond ((null? tail) #f)
((and (list? tail) (every1 exact-nonnegative-integer? tail)) tail)
(else (malformed-version))))))
(malformed-version))))
(define library-reference->name
(lambda (form lst)
(define malformed-name
(lambda ()
(if (pair? form)
(syntax-violation 'library "malformed library name" (abbreviated-take-form form 4 8) lst)
(syntax-violation 'library "malformed library name" lst))))
(cond ((every1 symbol? lst) lst)
((and (>= (lexical-syntax-version) 7) (every1 (lambda (e) (or (symbol? e) (exact-nonnegative-integer? e))) lst)) lst)
(else
(let ((body (list-head lst (- (length lst) 1))))
(cond ((every1 symbol? body) body) (else (malformed-name))))))))
(define flatten-library-reference
(lambda (form lst)
(or (and (list? lst) (not (null? lst)))
(syntax-violation 'library "malformed library name" (abbreviated-take-form form 4 8) lst))
(destructuring-match lst
(('library (ref ...)) (flatten-library-reference form ref))
(('library . _) (syntax-violation 'library "malformed library name" (abbreviated-take-form form 4 8) lst))
(_ lst))))
(define library-reference->version
(lambda (form lst)
(define malformed-version
(lambda ()
(if (pair? form)
(syntax-violation 'import "malformed library version" (abbreviated-take-form form 4 8) lst)
(syntax-violation 'import "malformed library version" lst))))
(if (and (list? lst) (not (null? lst)))
(cond ((every1 symbol? lst) #f)
((and (>= (lexical-syntax-version) 7) (every1 (lambda (e) (or (symbol? e) (exact-nonnegative-integer? e))) lst)) #f)
(else (let ((tail (car (list-tail lst (- (length lst) 1))))) (cond ((list? tail) tail) (else (malformed-version))))))
(malformed-version))))
(define test-library-versions
(lambda (form spec reference current)
(define exact-nonnegative-integer?
(lambda (obj) (and (integer? obj) (exact? obj) (>= obj 0))))
(or (let loop ((reference reference))
(destructuring-match reference
(('not ref) (not (loop ref)))
(('or ref ...) (any1 (lambda (e) (loop e)) ref))
(('and ref ...) (every1 (lambda (e) (loop e)) ref))
(sub-reference
(let loop ((current current) (sub-reference sub-reference))
(or (and (list? current) (list? sub-reference))
(syntax-violation 'import "malformed version reference" (abbreviated-take-form form 4 8) spec))
(or (null? sub-reference)
(and (>= (length current) (length sub-reference))
(let ((current (list-head current (length sub-reference))))
(every2
(lambda (c s)
(destructuring-match s
(('not ref) (not (loop c ref)))
(('>= (? exact-nonnegative-integer? n)) (>= c n))
(('<= (? exact-nonnegative-integer? n)) (<= c n))
(('and ref ...) (every1 (lambda (e) (loop (list c) (list e))) ref))
(('or ref ...) (any1 (lambda (e) (loop (list c) (list e))) ref))
((? exact-nonnegative-integer? n) (= c n))
(else
(syntax-violation
'import
"malformed version reference"
(abbreviated-take-form form 4 8)
spec))))
current
sub-reference))))))))
(syntax-violation
'import
(format "mismatch between version reference ~a and current version ~a" reference current)
(abbreviated-take-form form 4 8)
spec))))
(define make-shield-id-table
(lambda (lst)
(let ((visited (make-core-hashtable)) (ids (make-core-hashtable)) (deno (make-unbound)))
(let loop ((lst lst))
(cond ((symbol? lst) (core-hashtable-set! ids lst deno))
((pair? lst)
(or (core-hashtable-contains? visited lst)
(begin (core-hashtable-set! visited lst #t) (loop (car lst)) (loop (cdr lst)))))
((vector? lst)
(or (core-hashtable-contains? visited lst)
(begin (core-hashtable-set! visited lst #t) (loop (vector->list lst)))))))
ids)))
(define parse-exports
(lambda (form specs)
(let loop ((spec specs) (exports '()))
(destructuring-match spec
(() (reverse exports))
(((? symbol? id) . more) (loop more (acons id id exports)))
((('rename . alist) . more)
(begin
(or (every1 (lambda (e) (= (safe-length e) 2)) alist)
(syntax-violation 'export "malformed export spec" (abbreviated-take-form form 4 8) (car spec)))
(loop more (append (map (lambda (e) (cons (car e) (cadr e))) alist) exports))))
(_ (syntax-violation 'export "malformed export spec" (abbreviated-take-form form 4 8) (car spec)))))))
(define parse-imports
(lambda (form specs)
(define check-unbound-identifier
(lambda (bindings ids subform)
(for-each
(lambda (id)
(or (assq id bindings)
(syntax-violation
'import
(format "attempt to reference unexported identifier ~a" id)
(abbreviated-take-form form 4 8)
subform)))
ids)))
(define check-bound-identifier
(lambda (bindings ids subform)
(for-each
(lambda (id)
(and (assq id bindings)
(syntax-violation
'import
(format "duplicate import identifiers ~a" id)
(abbreviated-take-form form 4 8)
subform)))
ids)))
(let loop ((spec specs) (imports '()))
(destructuring-match spec
(() imports)
((('for set . phases) . more) (loop more (loop (list set) imports)))
((('only set . ids) . more)
(let ((bindings (loop (list set) '())))
(check-unbound-identifier bindings ids (car spec))
(loop more (append (filter (lambda (e) (memq (car e) ids)) bindings) imports))))
((('except set . ids) . more)
(let ((bindings (loop (list set) '())))
(check-unbound-identifier bindings ids (car spec))
(loop more (append (filter (lambda (e) (not (memq (car e) ids))) bindings) imports))))
((('rename set . alist) . more)
(let ((bindings (loop (list set) '())))
(or (every1 (lambda (e) (= (safe-length e) 2)) alist)
(syntax-violation 'import "malformed import set" (abbreviated-take-form form 4 8) (car spec)))
(or (and (unique-id-list? (map car alist)) (unique-id-list? (map cadr alist)))
(syntax-violation
'import
"duplicate identifers in rename specs"
(abbreviated-take-form form 4 8)
(car spec)))
(check-bound-identifier bindings (map cadr alist) (car spec))
(check-unbound-identifier bindings (map car alist) (car spec))
(loop
more
(append
(map (lambda (e)
(cond ((assq (car e) alist) => (lambda (rename) (cons (cadr rename) (cdr e)))) (else e)))
bindings)
imports))))
((('prefix set id) . more)
(loop
more
(append
(map (lambda (e) (cons (string->symbol (format "~a~a" id (car e))) (cdr e))) (loop (list set) '()))
imports)))
((ref . more)
(let ((ref (flatten-library-reference form ref)))
(let ((name (library-reference->name form ref)) (version (library-reference->version form ref)))
(|.require-scheme-library| name)
(let ((library-id (library-name->id form name)))
(cond
((and version (core-hashtable-ref (scheme-library-versions) library-id #f))
=> (lambda (current-version) (test-library-versions form ref version current-version))))
(loop
more
(cond ((core-hashtable-ref (scheme-library-exports) library-id #f)
=> (lambda (lst) (append lst imports)))
(else
(syntax-violation
'import
(format "attempt to import undefined library ~s" name)
(abbreviated-take-form form 4 8)))))))))
(_ (syntax-violation 'import "malformed import set" (abbreviated-take-form form 4 8) (car spec)))))))
(define parse-depends
(lambda (form specs)
(let loop ((spec specs) (depends '()))
(destructuring-match spec
(() depends)
((('for set . _) . more) (loop more (loop (list set) depends)))
((('only set . _) . more) (loop more (loop (list set) depends)))
((('except set . _) . more) (loop more (loop (list set) depends)))
((('rename set . _) . more) (loop more (loop (list set) depends)))
((('prefix set _) . more) (loop more (loop (list set) depends)))
((ref . more)
(let ((ref (flatten-library-reference form ref)))
(let ((name (library-reference->name form ref))) (loop more (cons name depends)))))
(_ (syntax-violation 'import "malformed import set" (abbreviated-take-form form 4 8) (car spec)))))))
(define check-duplicate-definition
(lambda (who defs macros renames)
(or (unique-id-list? (map car renames))
(let ((id (find-duplicates (map car renames))))
(cond ((assq id defs)
=>
(lambda (e1)
(let ((e2 (assq id (reverse defs))))
(cond ((eq? e1 e2)
(let ((e2 (assq id macros)))
(syntax-violation
who
"duplicate definitions"
(annotate `(define-syntax ,(car e2) ...) e2)
(annotate `(define ,@e1) e1))))
(else
(syntax-violation
who
"duplicate definitions"
(annotate `(define ,@e1) e1)
(annotate `(define ,@e2) e2)))))))
((assq id macros)
=>
(lambda (e1)
(let ((e2 (assq id (reverse macros))))
(cond ((eq? e1 e2)
(let ((e2 (assq id defs)))
(syntax-violation
who
"duplicate definitions"
(annotate `(define-syntax ,(car e1) ...) e1)
(annotate `(define ,@e2) e2))))
(else
(syntax-violation
who
"duplicate definitions"
(annotate `(define-syntax ,(car e1) ...) e1)
(annotate `(define-syntax ,(car e2) ...) e2)))))))
(else (syntax-violation who "duplicate definitions" id)))))))
(define expand-library
(lambda (form env)
(define permute-env
(lambda (ht)
(let loop ((lst (core-hashtable->alist ht)) (bounds '()) (unbounds '()))
(cond ((null? lst) (append bounds unbounds))
((unbound? (cdar lst)) (loop (cdr lst) bounds (cons (car lst) unbounds)))
(else (loop (cdr lst) (cons (car lst) bounds) unbounds))))))
(parameterize ((lexical-syntax-version 6))
(destructuring-match form
((_ library-name ('export export-spec ...) ('import import-spec ...) body ...)
(let ((library-id (library-name->id form library-name)) (library-version (library-name->version form library-name)))
(and library-version (core-hashtable-set! (scheme-library-versions) library-id library-version))
(parameterize ((current-include-files (make-core-hashtable)))
(let ((coreform
(let ((exports (parse-exports form export-spec))
(imports (parse-imports form import-spec))
(depends (parse-depends form import-spec))
(ht-immutables (make-core-hashtable))
(ht-imports (make-core-hashtable))
(ht-publics (make-core-hashtable)))
(for-each
(lambda (a)
(and (core-hashtable-ref ht-publics (cdr a) #f)
(syntax-violation 'library "duplicate export identifiers" (abbreviated-take-form form 4 8) (cdr a)))
(core-hashtable-set! ht-publics (cdr a) #t)
(core-hashtable-set! ht-immutables (car a) #t))
exports)
(for-each
(lambda (a)
(core-hashtable-set! ht-immutables (car a) #t)
(cond ((core-hashtable-ref ht-imports (car a) #f)
=>
(lambda (deno)
(or (eq? deno (cdr a))
(syntax-violation
'library
"duplicate import identifiers"
(abbreviated-take-form form 4 8)
(car a)))))
(else (core-hashtable-set! ht-imports (car a) (cdr a)))))
imports)
(let ((ht-env (make-shield-id-table body)) (ht-libenv (make-core-hashtable)))
(for-each
(lambda (a) (core-hashtable-set! ht-env (car a) (cdr a)) (core-hashtable-set! ht-libenv (car a) (cdr a)))
(core-hashtable->alist ht-imports))
(parameterize ((current-immutable-identifiers ht-immutables))
(expand-library-body
form
library-id
library-version
body
exports
imports
depends
(extend-env private-primitives-environment (permute-env ht-env))
(permute-env ht-libenv)))))))
(or (= (core-hashtable-size (current-include-files)) 0)
(core-hashtable-set! library-include-dependencies library-id (current-include-files)))
coreform))))
(_ (syntax-violation 'library "expected library name, export spec, and import spec" (abbreviated-take-form form 4 8)))))))
(define expand-library-body
(lambda (form library-id library-version body exports imports depends env libenv)
(define initial-libenv #f)
(define internal-definition?
(lambda (lst)
(and (pair? lst)
(pair? (car lst))
(symbol? (caar lst))
(let ((deno (env-lookup env (caar lst))))
(or (macro? deno)
(eq? denote-define deno)
(eq? denote-define-syntax deno)
(eq? denote-let-syntax deno)
(eq? denote-letrec-syntax deno))))))
(define macro-defs '())
(define extend-env!
(lambda (datum1 datum2)
(and (macro? datum2) (set! macro-defs (acons datum1 datum2 macro-defs)))
(set! env (extend-env (list (cons datum1 datum2)) env))
(for-each (lambda (a) (set-cdr! (cddr a) env)) macro-defs)))
(define extend-libenv!
(lambda (datum1 datum2)
(set! libenv (extend-env (list (cons datum1 datum2)) libenv))
(current-template-environment libenv)))
(define rewrite-body
(lambda (body defs macros renames)
(rewrite-library-body
form
library-id
library-version
body
defs
macros
renames
exports
imports
depends
env
libenv)))
(define ht-imported-immutables (make-core-hashtable))
(current-template-environment libenv)
(for-each (lambda (b) (core-hashtable-set! ht-imported-immutables (car b) #t)) imports)
(let loop ((body (flatten-begin body env)) (defs '()) (macros '()) (renames '()))
(cond ((and (pair? body) (pair? (car body)) (symbol? (caar body)))
(let ((deno (env-lookup env (caar body))))
(cond ((eq? denote-begin deno) (loop (flatten-begin body env) defs macros renames))
((eq? denote-define-syntax deno)
(destructuring-match body
(((_ (? symbol? org) clause) more ...)
(begin
(and (core-hashtable-contains? ht-imported-immutables org)
(syntax-violation 'define-syntax "attempt to modify immutable binding" (car body)))
(let-values (((code . expr)
(parameterize ((current-template-environment initial-libenv))
(compile-macro (car body) clause env))))
(let ((new (generate-global-id library-id org)))
(extend-libenv! org (make-import new))
(cond ((procedure? code)
(extend-env! org (make-macro code env))
(loop
more
defs
(cons (list org 'procedure (car expr)) macros)
(acons org new renames)))
((macro-variable? code)
(extend-env! org (make-macro-variable (cadr code) env))
(loop
more
defs
(cons (list org 'variable (car expr)) macros)
(acons org new renames)))
(else
(extend-env! org (make-macro code env))
(loop
more
defs
(cons (list org 'template code) macros)
(acons org new renames))))))))
(_ (syntax-violation 'define-syntax "expected symbol and single expression" (car body)))))
((eq? denote-define deno)
(let ((def (annotate (cdr (desugar-define (car body))) (car body))))
(and (core-hashtable-contains? ht-imported-immutables (car def))
(syntax-violation 'define "attempt to modify immutable binding" (car body)))
(let ((org (car def)) (new (generate-global-id library-id (car def))))
(extend-env! org new)
(extend-libenv! org (make-import new))
(loop (cdr body) (cons def defs) macros (acons org new renames)))))
((or (macro? deno) (eq? denote-let-syntax deno) (eq? denote-letrec-syntax deno))
(let-values (((expr new) (expand-initial-forms (car body) env)))
(set! env new)
(let ((maybe-def (flatten-begin (list expr) env)))
(cond ((null? maybe-def) (loop (cdr body) defs macros renames))
((internal-definition? maybe-def)
(loop (append maybe-def (cdr body)) defs macros renames))
(else (rewrite-body body (reverse defs) (reverse macros) renames))))))
(else (rewrite-body body (reverse defs) (reverse macros) renames)))))
(else (rewrite-body body (reverse defs) (reverse macros) renames))))))
(define rewrite-library-body
(lambda (form library-id library-version body defs macros renames exports imports depends env libenv)
(define extend-libenv!
(lambda (datum1 datum2)
(set! libenv (extend-env (list (cons datum1 datum2)) libenv))
(current-template-environment libenv)))
(define rewrite-env
(lambda (env)
(let loop ((lst (reverse env)) (acc '()))
(cond ((null? lst) acc)
((uninterned-symbol? (caar lst))
(if (assq (cdar lst) defs)
(loop (cdr lst) (cons (cons (caar lst) (cddr (assq (cdar lst) libenv))) acc))
(loop (cdr lst) (cons (car lst) acc))))
((assq (caar lst) (cdr lst)) (loop (cdr lst) acc))
(else (loop (cdr lst) (cons (car lst) acc)))))))
(define make-rule-macro
(lambda (type id spec shared-env) `(|.set-top-level-macro!| ',type ',id ',spec ,shared-env)))
(define make-var-macro
(lambda (type id spec shared-env)
`(|.set-top-level-macro!| ',type ',id (|.transformer-thunk| ,spec) ,shared-env)))
(define make-proc-macro
(lambda (type id spec shared-env)
(cond ((and (pair? spec) (eq? (car spec) 'lambda))
`(|.set-top-level-macro!| ',type ',id (|.transformer-thunk| ,spec) ,shared-env))
(else
(let ((x (generate-temporary-symbol)))
`(|.set-top-level-macro!|
',type
',id
(let ((proc #f))
(lambda (,x) (if proc (proc ,x) (begin (set! proc (|.transformer-thunk| ,spec)) (proc ,x)))))
,shared-env))))))
(check-duplicate-definition 'library defs macros renames)
(let ((env (rewrite-env env)))
(let ((rewrited-body (expand-each body env)))
(let* ((rewrited-depends (map (lambda (dep) `(|.require-scheme-library| ',dep)) depends))
(rewrited-defs
(map (lambda (def)
(parameterize ((current-top-level-exterior (car def)))
(let ((lhs (cdr (assq (car def) renames))) (rhs (expand-form (cadr def) env)))
(set-closure-comment! rhs lhs)
`(define ,lhs ,rhs))))
defs))
(rewrited-macros
(cond ((null? macros) '())
(else
(let ((ht-visibles (make-core-hashtable)))
(for-each (lambda (e) (core-hashtable-set! ht-visibles (car e) #t)) macros)
(let loop ((lst (map caddr macros)))
(cond ((pair? lst) (loop (car lst)) (loop (cdr lst)))
((symbol? lst) (core-hashtable-set! ht-visibles lst #t))
((vector? lst) (loop (vector->list lst)))))
(for-each
(lambda (b)
(or (assq (car b) libenv)
(let ((deno (env-lookup env (car b))))
(if (and (symbol? deno) (not (eq? deno (car b))))
(extend-libenv! (car b) (make-import deno))
(or (uninterned-symbol? (car b))
(core-primitive-name? (car b))
(extend-libenv! (car b) (make-unbound)))))))
(core-hashtable->alist ht-visibles))
(let ((shared-env (generate-temporary-symbol)))
`((let ((,shared-env
',(let ((ht (make-core-hashtable)))
(for-each
(lambda (a)
(and (core-hashtable-contains? ht-visibles (car a))
(core-hashtable-set! ht (car a) (cdr a))))
(reverse libenv))
(core-hashtable->alist ht))))
,@(map (lambda (e)
(let ((id (cdr (assq (car e) renames))) (type (cadr e)) (spec (caddr e)))
(case type
((template) (make-rule-macro 'syntax id spec shared-env))
((procedure) (make-proc-macro 'syntax id spec shared-env))
((variable) (make-var-macro 'variable id spec shared-env))
(else
(scheme-error
"internal error in rewrite body: bad macro spec ~s"
e)))))
macros))))))))
(rewrited-exports
`(|.intern-scheme-library|
',library-id
',library-version
',(begin
(map (lambda (e)
(cons (cdr e)
(cond ((assq (car e) renames) => (lambda (a) (make-import (cdr a))))
((assq (car e) imports) => cdr)
(else
(current-macro-expression #f)
(syntax-violation
'library
(format "attempt to export unbound identifier ~u" (car e))
(caddr form))))))
exports)))))
(let ((vars (map cadr rewrited-defs)) (assignments (map caddr rewrited-defs)))
(cond
((check-rec*-contract-violation vars assignments)
=>
(lambda (var)
(let ((id (any1 (lambda (a) (and (eq? (cdr a) (car var)) (car a))) renames)))
(current-macro-expression #f)
(syntax-violation
#f
(format "attempt to reference uninitialized variable ~u" id)
(any1
(lambda (e) (and (check-rec-contract-violation (list id) e) (annotate `(define ,@e) e)))
defs)))))))
(annotate
`(begin ,@rewrited-depends ,@rewrited-defs ,@rewrited-body ,@rewrited-macros ,rewrited-exports)
form))))))
(define import-top-level-bindings
(lambda (bindings)
(let ((ht1 (make-core-hashtable)) (ht2 (current-top-level-renames)))
(for-each
(lambda (binding)
(core-hashtable-delete! ht2 (car bindings))
(cond ((core-hashtable-ref ht1 (cddr binding) #f) => (lambda (id) (core-hashtable-set! ht2 (car binding) id)))
(else (core-hashtable-set! ht1 (cddr binding) (car binding)))))
bindings)
(current-top-level-renames ht2))
(for-each
(lambda (binding)
(let ((intern (car binding)) (extern (cddr binding)))
(or (eq? intern extern)
(cond ((core-hashtable-ref (current-macro-environment) extern #f)
=>
(lambda (deno)
(if (top-level-bound? intern) (set-top-level-value! intern |.&UNDEF|))
(core-hashtable-set! (current-macro-environment) intern deno)))
(else
(core-hashtable-delete! (current-macro-environment) intern)
(set-top-level-value! intern (top-level-value extern)))))))
bindings)))
(define expand-import
(lambda (form env)
(and (unexpect-top-level-form) (syntax-violation 'import "misplaced top-level directive" form))
(auto-compile-cache-update)
(let ((imports (parse-imports form (cdr form))) (ht-bindings (make-core-hashtable)))
(for-each
(lambda (a)
(cond ((core-hashtable-ref ht-bindings (car a) #f)
=>
(lambda (deno)
(or (eq? deno (cdr a))
(syntax-violation
'import
"duplicate import identifiers"
(abbreviated-take-form form 4 8)
(car a)))))
(else (core-hashtable-set! ht-bindings (car a) (cdr a)))))
imports)
(import-top-level-bindings (core-hashtable->alist ht-bindings)))))
(define count-pending-import
(lambda ()
(length
(filter
(lambda (e) (eq? e 'pending))
(map cdr (core-hashtable->alist (scheme-library-exports)))))))
(set-top-level-value! '|.require-scheme-library|
(lambda (ref)
(let ((library-id (generate-library-id ref)))
(let ((exports (core-hashtable-ref (scheme-library-exports) library-id #f)))
(define lock-fd #f)
(cond ((eq? exports 'pending)
(core-hashtable-set! (scheme-library-exports) library-id #f)
(syntax-violation 'library "encountered cyclic dependencies" ref))
((eq? exports #f)
(dynamic-wind
(lambda ()
(and (auto-compile-cache)
(= (count-pending-import) 0)
(set! lock-fd (acquire-lockfile (auto-compile-cache-lock-path))))
(core-hashtable-set! (scheme-library-exports) library-id 'pending))
(lambda () (load-scheme-library ref #f))
(lambda ()
(and (eq? (core-hashtable-ref (scheme-library-exports) library-id #f) 'pending)
(core-hashtable-set! (scheme-library-exports) library-id #f))
(and (auto-compile-cache)
(= (count-pending-import) 0)
(release-lockfile lock-fd))))))))
(unspecified)))
(define unify-import-bindings
(let ((ht-import-bindings (make-core-hashtable 'equal?)))
(lambda (lst)
(map (lambda (binding)
(cond ((core-hashtable-ref ht-import-bindings binding #f) => values)
(else (begin (core-hashtable-set! ht-import-bindings binding binding) binding))))
lst))))
(set-top-level-value!
'|.intern-scheme-library|
(lambda (library-id library-version exports)
(and library-version (core-hashtable-set! (scheme-library-versions) library-id library-version))
(core-hashtable-set! (scheme-library-exports) library-id (unify-import-bindings exports))))
(set-top-level-value!
'|.unintern-scheme-library|
(lambda (library-id) (core-hashtable-delete! (scheme-library-exports) library-id)))
|
43ed51070aba2f82dd052c0b720e8e18ec325884f8a9653f77e079ad996ad595 | roman/Haskell-Reactive-Extensions | ConcatTest.hs | module Rx.Observable.ConcatTest where
import Test.Hspec
import Test.HUnit
import Control.Concurrent.Async (async, wait)
import Control.Exception (ErrorCall (..), SomeException (..),
fromException)
import Data.Maybe (fromJust)
import qualified Rx.Observable as Rx
import qualified Rx.Subject as Rx (newPublishSubject)
tests :: Spec
tests =
describe "Rx.Observable.Concat" $ do
describe "concatList" $ do
it "concatenates elements from different observables in order" $ do
let obs = Rx.concatList [ Rx.fromList Rx.newThread [1..10]
, Rx.fromList Rx.newThread [11..20]
, Rx.fromList Rx.newThread [21..30] ]
result <- Rx.toList (obs :: Rx.Observable Rx.Async Int)
case result of
Left err -> assertFailure (show err)
Right out -> assertEqual "elements are not in order" (reverse [1..30]) out
describe "concat" $ do
it "concatanates async observables in order of subscription" $ do
outerSource <- Rx.newPublishSubject
innerSource1 <- Rx.newPublishSubject
innerSource2 <- Rx.newPublishSubject
let sources = Rx.toAsyncObservable outerSource
obs1 = Rx.toAsyncObservable innerSource1
obs2 = Rx.toAsyncObservable innerSource2
resultObs = Rx.concat sources
resultA <- async (Rx.toList resultObs)
Rx.onNext outerSource (obs2 :: Rx.Observable Rx.Async Int)
Rx.onNext outerSource (obs1 :: Rx.Observable Rx.Async Int)
-- ignores this because it is not subscribed to obs1 yet
( obs2 needs to be completed first )
Rx.onNext innerSource1 (-1)
Rx.onNext innerSource1 (-2)
-- outer is completed, but won't be done until inner sources
-- are completed
Rx.onCompleted outerSource
-- first elements emitted
Rx.onNext innerSource2 1
Rx.onNext innerSource2 2
Rx.onNext innerSource2 3
Rx.onCompleted innerSource2
-- this elements are emitted because innerSource2 completed
Rx.onNext innerSource1 11
Rx.onNext innerSource1 12
-- after this, the whole thing is completed
Rx.onCompleted innerSource1
result <- wait resultA
case result of
Left err -> assertFailure (show err)
Right xs -> assertEqual "should be on the right order" (reverse [1,2,3,11,12]) xs
it "handles error when outer source fails " $ do
outerSource <- Rx.newPublishSubject
innerSource1 <- Rx.newPublishSubject
innerSource2 <- Rx.newPublishSubject
let sources = Rx.toAsyncObservable outerSource
obs1 = Rx.toAsyncObservable innerSource1
obs2 = Rx.toAsyncObservable innerSource2
resultObs = Rx.concat sources
resultA <- async (Rx.toList resultObs)
Rx.onNext outerSource (obs2 :: Rx.Observable Rx.Async Int)
Rx.onNext outerSource (obs1 :: Rx.Observable Rx.Async Int)
Rx.onNext innerSource2 123
Rx.onError outerSource (SomeException (ErrorCall "foobar"))
Rx.onNext innerSource2 456
result <- wait resultA
case result of
Right _ -> assertFailure "expected failure, got valid response"
Left (xs, err) -> do
assertEqual "received elements before error" [123] xs
assertEqual "received error" (ErrorCall "foobar") (fromJust $ fromException err)
it "handles error on inner source" $ do
outerSource <- Rx.newPublishSubject
innerSource1 <- Rx.newPublishSubject
innerSource2 <- Rx.newPublishSubject
let sources = Rx.toAsyncObservable outerSource
obs1 = Rx.toAsyncObservable innerSource1
obs2 = Rx.toAsyncObservable innerSource2
resultObs = Rx.concat sources
resultA <- async (Rx.toList resultObs)
Rx.onNext outerSource (obs2 :: Rx.Observable Rx.Async Int)
Rx.onNext outerSource (obs1 :: Rx.Observable Rx.Async Int)
Rx.onNext innerSource2 123
Rx.onError innerSource2 (SomeException (ErrorCall "foobar"))
Rx.onCompleted outerSource
result <- wait resultA
case result of
Right _ -> assertFailure "expected failure, got valid response"
Left (xs, err) -> do
assertEqual "received elements before error" [123] xs
assertEqual "received error" (ErrorCall "foobar") (fromJust $ fromException err)
| null | https://raw.githubusercontent.com/roman/Haskell-Reactive-Extensions/0faddbb671be7f169eeadbe6163e8d0b2be229fb/rx-core/test/Rx/Observable/ConcatTest.hs | haskell | ignores this because it is not subscribed to obs1 yet
outer is completed, but won't be done until inner sources
are completed
first elements emitted
this elements are emitted because innerSource2 completed
after this, the whole thing is completed | module Rx.Observable.ConcatTest where
import Test.Hspec
import Test.HUnit
import Control.Concurrent.Async (async, wait)
import Control.Exception (ErrorCall (..), SomeException (..),
fromException)
import Data.Maybe (fromJust)
import qualified Rx.Observable as Rx
import qualified Rx.Subject as Rx (newPublishSubject)
tests :: Spec
tests =
describe "Rx.Observable.Concat" $ do
describe "concatList" $ do
it "concatenates elements from different observables in order" $ do
let obs = Rx.concatList [ Rx.fromList Rx.newThread [1..10]
, Rx.fromList Rx.newThread [11..20]
, Rx.fromList Rx.newThread [21..30] ]
result <- Rx.toList (obs :: Rx.Observable Rx.Async Int)
case result of
Left err -> assertFailure (show err)
Right out -> assertEqual "elements are not in order" (reverse [1..30]) out
describe "concat" $ do
it "concatanates async observables in order of subscription" $ do
outerSource <- Rx.newPublishSubject
innerSource1 <- Rx.newPublishSubject
innerSource2 <- Rx.newPublishSubject
let sources = Rx.toAsyncObservable outerSource
obs1 = Rx.toAsyncObservable innerSource1
obs2 = Rx.toAsyncObservable innerSource2
resultObs = Rx.concat sources
resultA <- async (Rx.toList resultObs)
Rx.onNext outerSource (obs2 :: Rx.Observable Rx.Async Int)
Rx.onNext outerSource (obs1 :: Rx.Observable Rx.Async Int)
( obs2 needs to be completed first )
Rx.onNext innerSource1 (-1)
Rx.onNext innerSource1 (-2)
Rx.onCompleted outerSource
Rx.onNext innerSource2 1
Rx.onNext innerSource2 2
Rx.onNext innerSource2 3
Rx.onCompleted innerSource2
Rx.onNext innerSource1 11
Rx.onNext innerSource1 12
Rx.onCompleted innerSource1
result <- wait resultA
case result of
Left err -> assertFailure (show err)
Right xs -> assertEqual "should be on the right order" (reverse [1,2,3,11,12]) xs
it "handles error when outer source fails " $ do
outerSource <- Rx.newPublishSubject
innerSource1 <- Rx.newPublishSubject
innerSource2 <- Rx.newPublishSubject
let sources = Rx.toAsyncObservable outerSource
obs1 = Rx.toAsyncObservable innerSource1
obs2 = Rx.toAsyncObservable innerSource2
resultObs = Rx.concat sources
resultA <- async (Rx.toList resultObs)
Rx.onNext outerSource (obs2 :: Rx.Observable Rx.Async Int)
Rx.onNext outerSource (obs1 :: Rx.Observable Rx.Async Int)
Rx.onNext innerSource2 123
Rx.onError outerSource (SomeException (ErrorCall "foobar"))
Rx.onNext innerSource2 456
result <- wait resultA
case result of
Right _ -> assertFailure "expected failure, got valid response"
Left (xs, err) -> do
assertEqual "received elements before error" [123] xs
assertEqual "received error" (ErrorCall "foobar") (fromJust $ fromException err)
it "handles error on inner source" $ do
outerSource <- Rx.newPublishSubject
innerSource1 <- Rx.newPublishSubject
innerSource2 <- Rx.newPublishSubject
let sources = Rx.toAsyncObservable outerSource
obs1 = Rx.toAsyncObservable innerSource1
obs2 = Rx.toAsyncObservable innerSource2
resultObs = Rx.concat sources
resultA <- async (Rx.toList resultObs)
Rx.onNext outerSource (obs2 :: Rx.Observable Rx.Async Int)
Rx.onNext outerSource (obs1 :: Rx.Observable Rx.Async Int)
Rx.onNext innerSource2 123
Rx.onError innerSource2 (SomeException (ErrorCall "foobar"))
Rx.onCompleted outerSource
result <- wait resultA
case result of
Right _ -> assertFailure "expected failure, got valid response"
Left (xs, err) -> do
assertEqual "received elements before error" [123] xs
assertEqual "received error" (ErrorCall "foobar") (fromJust $ fromException err)
|
fc3cf0dd6dfe44a50f58399506dbcc08665e8b55e4f61dc288464b0194f352a6 | gafiatulin/codewars | Scrabble.hs | -- Scrabble Score
--
module Codewars.Exercise.Scrabble where
import Codewars.Exercise.Scrabble.Score (dict)
import Data.Char (toUpper)
import Data.Map.Lazy (findWithDefault, fromList)
scrabbleScore :: String -> Int
scrabbleScore str = sum $ map (\c -> findWithDefault 0 (toUpper c) (fromList dict)) str
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/7%20kyu/Scrabble.hs | haskell | Scrabble Score
|
module Codewars.Exercise.Scrabble where
import Codewars.Exercise.Scrabble.Score (dict)
import Data.Char (toUpper)
import Data.Map.Lazy (findWithDefault, fromList)
scrabbleScore :: String -> Int
scrabbleScore str = sum $ map (\c -> findWithDefault 0 (toUpper c) (fromList dict)) str
|
db5c6d729944797606c0f526fa978900485324f09e7cdd4499d4c87f24317734 | qitab/bazelisp | sbcl.lisp | Copyright 2015 - 2020 Google LLC
;;;
Use of this source code is governed by an MIT - style
;;; license that can be found in the LICENSE file or at
;;; .
Utilities for and their implementation in SBCL .
;;;
;; Default optimization settings.
# -dbg ( declaim ( optimize ( speed 3 ) ( safety 1 ) ) )
(eval-when (:compile-toplevel :load-toplevel :execute)
MD5 pulls in SB - ROTATE - BYTE which makes it impossible
;; to compile either of those from fresh upstream sources without some magic.
(require :sb-md5))
(defpackage #:bazel.sbcl
(:use #:common-lisp #:sb-thread #:sb-alien #:bazel.utils)
(:import-from #:sb-md5 #:md5sum-file)
(:export #:compile-files
#:exit
#:run
#:inline-function-p
#:function-has-transforms-p
#:getenv #:unsetenv #:chdir
#:command-line-arguments #:program-name
#:default-toplevel-loop
#:mute-output-streams
#:save-lisp-and-die
#:dump-alien-symbols
#:dump-extern-symbols
#:dump-dynamic-list-lds
#:combine-run-time-and-core
#:md5sum-file
#:set-interpret-mode
#:set-interactive-mode
#:setup-readtable
#:remove-extra-debug-info
#:name-closure
#:with-creating-find-package
#:with-default-package
;; threading
#:make-thread
#:join-thread
#:with-recursive-lock
#:make-mutex #:mutex
#:pmapcar
#:pprog1))
(in-package #:bazel.sbcl)
(defun exit (&optional (code 0))
"Exit the process with a return CODE."
(sb-ext:exit :code code))
(defun run (program &key args input output (error :output) dir)
"Run a PROGRAM suppling ARGS and return the exit code.
Arguments:
ARGS - a list of string arguments to the program,
INPUT - a spec for the standard input for the program,
OUTPUT - a spec for the standard output for the program,
ERROR - a spec for the error output for the program.
DIR - the directory used for the program to run.
The specification for INPUT, OUTPUT, and ERROR can be:
NIL - the stream is mapped to /dev/null,
T - the standard input, output, or error stream of this process is used,
pathname - the file functions as input or output,
stream - the stream functions as input or output,
:OUTPUT - indicates that the error stream equals the output stream."
(sb-ext:process-exit-code
(sb-ext:run-program program args :input input :output output :error error :directory dir)))
(declaim (ftype (function (function &rest list) (values list &optional)) pmapcar))
(defun pmapcar (function &rest lists)
"Takes a FUNCTION and LISTS of arguments and executes the function for each argument tuple.
The function is run is separate threads. The first tuple of arguments is run in the current one."
(flet ((run (args) (make-thread function :arguments args)))
(declare (dynamic-extent #'run) (inline run))
(let* ((args (apply #'mapcar #'list lists))
(threads (mapcar #'run (rest args))))
(when args
(list* (apply function (first args)) (mapcar #'join-thread threads))))))
(defmacro pprog1 (form1 &rest forms)
"Take each of the FORMS and run them in a separate thread. Join threads at the end.
Returns the result of the first form. FORM1 is executed in the current thread."
(let ((functions (gensym "F"))
(threads (gensym "T")))
`(let* ((,functions (list ,@(loop for form in forms collect `(lambda () ,form))))
(,threads (mapcar #'make-thread ,functions)))
(prog1 ,form1
(mapc #'join-thread ,threads)))))
(defun inline-function-p (function)
"Returns non-nil when the FUNCTION is declared inline."
(eq (sb-int:info :function :inlinep function) 'inline))
(defun function-has-transforms-p (function)
"Returns non-nil if the FUNCTION has transforms."
(or (sb-c::info :function :source-transform function)
(let ((info (sb-c::info :function :info function)))
(and info (sb-c::fun-info-transforms info)))))
(defun getenv (variable)
"Returns the value of the environment VARIABLE."
(sb-ext:posix-getenv variable))
(defun unsetenv (variable)
"Removes the VARIABLE from the environment."
(alien-funcall
(extern-alien "unsetenv" (function sb-alien:int sb-alien:c-string))
variable))
(defun command-line-arguments ()
"Returns the command-line arguments without the program name."
(rest sb-unix::*posix-argv*))
(defun program-name ()
"Returns the name of the program."
(first sb-unix::*posix-argv*))
(defun default-toplevel-loop ()
"Gives control to the default toplevel REPL."
(sb-ext:enable-debugger)
(sb-impl::toplevel-init))
(defun mute-output-streams ()
"Mute SBCL image write messages."
Set runtime --noinform option to 1 , which also hides the " [ writing ... ] " noise
(setf (extern-alien "lisp_startup_options" int) 1)
nil)
(defun terminate-other-threads ()
"Terminates all non-system threads but the current one."
(let ((threads (remove-if (lambda (x)
(or (thread-ephemeral-p x)
(eq x *current-thread*)))
(list-all-threads))))
(mapc #'terminate-thread threads)
(mapc (lambda (thread) (join-thread thread :default nil)) threads)))
(defun name-closure (closure name)
"Return CLOSURE with the NAME changed, so it prints nicely."
;; This is not necessary, except for debugging and aesthetics.
(setf (sb-kernel:%fun-name closure) name)
closure)
(defun remove-extra-debug-info ()
"Removes debug info like docstrings and xrefs."
(sb-vm::map-allocated-objects
(lambda (obj type size)
(declare (ignore size))
(when (= type sb-vm:code-header-widetag)
(dotimes (i (sb-kernel:code-n-entries obj))
(let ((f (sb-kernel:%code-entry-point obj i)))
(setf (sb-kernel:%simple-fun-info f) 'function)
;; Preserve source forms, assuming we want them if they exist.
(setf (sb-kernel:%simple-fun-source f)
(sb-kernel:%simple-fun-lexpr f))))))
:all))
;;;
;;; Precompile generic functions.
TODO(czak ): This needs to go into SBCL upstream .
;;;
;;; For more information see:
;;; -internals/Discriminating-Functions.html
;;;
;;;
;;; /
(defun eql-specializer-p (spec)
"True if SPEC is an eql specializer."
(typep spec 'sb-mop:eql-specializer))
(defun trivial-class-specializer-p (spec)
"True if SPEC is a trivial class specializer."
(or (eq spec #.(find-class t))
(eq spec #.(find-class 'standard-object))
(eq spec #.(find-class 'sb-pcl::slot-object))
(eq spec #.(find-class 'sb-pcl::structure-object))))
(defun non-trivial-class-specializer-p (spec)
"True if SPEC is non-trivial class specializer."
(not (or (eql-specializer-p spec)
(trivial-class-specializer-p spec))))
(defun simple-specializer-p (spec)
"True if SPEC is not a class specializer with subclasses."
(or (eql-specializer-p spec)
(trivial-class-specializer-p spec)
;; Precompute the discriminating function only for shallow class hierarchies.
(null (sb-mop:class-direct-subclasses spec))))
(defun gf-specializers-list (gf)
"Returns a list of method specializers for the generic function GF."
(let ((methods (sb-mop:generic-function-methods gf))
(specializers-list nil))
(dolist (method methods (nreverse specializers-list))
(pushnew (sb-mop:method-specializers method) specializers-list :test #'equalp))))
(defun precompile-generic-function (gf &key verbose)
"Precompiles the dispatch code for the generic function GF.
When VERBOSE is larger than 2, print some debug info.
Returns true when the GF has been precompiled."
(when (sb-pcl::special-case-for-compute-discriminating-function-p gf)
TODO(czak ): Those special cases are handled differently by SBCL .
(return-from precompile-generic-function))
(let ((methods (sb-mop:generic-function-methods gf))
(simple-p t)
(class-specializers-p nil)
(eql-specializers-p nil)
(specializers-list (gf-specializers-list gf)))
(dolist (method methods)
(let ((specializers (sb-mop:method-specializers method))
(count-not-simple 0))
(dolist (spec specializers)
(unless (simple-specializer-p spec)
(when (> (incf count-not-simple) 1)
If we have more than one class specializer with subclasses ,
;; we run the danger of an exponential combination of those subclasses.
Precompilation might then explode the caches and takes time .
(when (> verbose 2) (format t "!SIMPLE: ~S~%" gf))
(return-from precompile-generic-function)))
(cond ((non-trivial-class-specializer-p spec)
(setf class-specializers-p t)
;; Finalize the inheritance of those classes.
;; This is useful for accessor functions.
(unless (sb-mop:class-finalized-p spec)
(sb-mop:finalize-inheritance spec)))
((eql-specializer-p spec)
(setf eql-specializers-p t))))
(when (plusp count-not-simple)
(setf simple-p nil))))
(unless simple-p
;; Enumerate all the subclasses for not simple specializers.
(dolist (specializers specializers-list)
(let ((pos (position-if-not #'simple-specializer-p specializers)))
(when pos
(labels ((augment (spec)
(dolist (sub (sb-mop:class-direct-subclasses spec))
(let ((new (copy-list specializers)))
(setf (nth pos new) sub)
(pushnew new specializers-list :test #'equal))
(augment sub))))
(augment (nth pos specializers)))))))
Making a caching discriminating function for EQL specializers fails .
;; A dispatching discriminating function is expensive for class specializers.
(when (and class-specializers-p eql-specializers-p
(> (max (length methods) (length specializers-list)) 10))
(when (> verbose 2) (format t "!C+E: ~S: ~D specs~%" gf (length specializers-list)))
(return-from precompile-generic-function))
(setf (sb-pcl::gf-precompute-dfun-and-emf-p (sb-pcl::gf-arg-info gf)) t)
(multiple-value-bind (dfun cache info)
(cond ((and eql-specializers-p
(or (cdr methods) (cdr specializers-list) (cdar specializers-list)))
;; Make a dispatching discriminating function.
(when (> verbose 2) (format t "DISPATCH: ~S~%" gf))
(sb-pcl::make-final-dispatch-dfun gf))
(t
;; Make a caching discriminating function.
;; The MAKE-FINAL-DFUN-INTERNAL will also optimize for other cases.
(when (> verbose 2)
(format t "DEFAULT: ~S: ~D specs~:[~;, EQL~]~:[~;, CLS~]~%"
gf (length specializers-list) eql-specializers-p class-specializers-p))
(sb-pcl::make-final-dfun-internal gf specializers-list)))
(sb-pcl::update-dfun gf dfun cache info))
t))
;; This list contains packages holding symbols of generic functions which will not be precompiled.
(defvar *skip-precompile-packages* nil)
(defun precompile-generic-functions (&key (verbose 0))
"Enumerates all generic functions and pre-compiles their dispatch functions.
When VERBOSE is larger then 0, print some debug info.
Returns a count of successfully precompiled dispatch functions."
(let ((count 0)
(all 0))
(flet ((precompile (s)
(let ((f (and (fboundp s) (fdefinition s))))
(when (typep f 'standard-generic-function)
(incf all)
(when (precompile-generic-function f :verbose verbose)
(incf count))))))
(do-all-symbols (s)
(unless (find (symbol-package s) *skip-precompile-packages*)
(when (precompile s)
(precompile `(setf ,s)))))
(when (plusp verbose)
(bazel.log:info "Precompiled ~D (~D% out of ~D) generic functions.~%"
count (round (* 100 count) all) all))
(values count all))))
;;;
;;; Generate an image.
;;;
(defun save-lisp-and-die (name &key toplevel save-runtime-options verbose
precompile-generics executable)
"Saves the current Lisp image and dies.
Arguments:
NAME - the file name to save the image.
TOPLEVEL - the name of the toplevel function.
SAVE-RUNTIME-OPTIONS - indicates if the runtime options shall be saved to the C runtime.
This is usually permanent.
VERBOSE - if true, the output streams are not muted before dumping the image.
PRECOMPILE-GENERICS - will precompile the generic functions before saving.
EXECUTABLE - Whether to combine the launcher with the image to create an executable."
(sb-ext:disable-debugger)
(terminate-other-threads)
(when precompile-generics
(precompile-generic-functions :verbose bazel.log:*verbose*))
(unless verbose (mute-output-streams))
(sb-ext:fold-identical-code :aggressive t)
(setf (extern-alien "gc_coalesce_string_literals" char) 2)
(sb-ext:save-lisp-and-die
name
:executable executable
:toplevel toplevel
:save-runtime-options save-runtime-options)
NOLINT
(defun set-interpret-mode (compile-mode)
"Set the mode of eval to :interpret if COMPILE-MODE is :LOAD. Otherwise, set it to :COMPILE."
(declare (optimize (speed 1) (safety 3) (compilation-speed 1) (debug 1)))
(setf sb-ext:*evaluator-mode* (if (eq compile-mode :load) :interpret :compile))
(bazel.log:vvv "Set interpret mode to: ~A" sb-ext:*evaluator-mode*)
sb-ext:*evaluator-mode*)
(defun set-interactive-mode (&optional (interactive-p t))
"If INTERACTIVE-P is true, the debugger will be enabled."
(if interactive-p
(sb-ext:enable-debugger)
(sb-ext:disable-debugger)))
;;;
;;; Reading lisp files.
;;;
(defun setup-readtable (rt)
(setf (sb-ext:readtable-base-char-preference rt) :both)
rt)
(defvar *in-find-package* nil "Prevents cycles in make-package")
(defvar *with-creating-find-package-mutex* (make-mutex :name "with-creating-find-package-mutex"))
(defun call-with-augmented-find-package (body &key (use '("COMMON-LISP")) (default nil))
"Calls the BODY after making sure that the reader
will not error on unknown packages or not exported symbols.
USE is the set of packages to use by the new package.
This affects _all_ threads' calls to FIND-PACKAGE, and
is generally not appropriate to use in production code"
(declare (function body))
;; The instant that ENCAPSULATE stores the new definition of FIND-PACKAGE, we must
;; accept that any thread - whether already running, or newly created - can access
;; our local function as a consequence of needing FIND-PACKAGE for any random reason.
;; Were the closure allocated on this thread's stack, then this function's frame
;; would be forbidden from returning until no other thread was executing the code
;; that was made globally visible. Since there's no way to determine when the last
;; execution has ended, the FLET body has indefinite, not dynamic, extent.
(flet ((creating-find-package (f name)
(or (funcall f name)
default
(unless *in-find-package*
(let ((*in-find-package* t))
(make-package name :use use))))))
(with-recursive-lock (*with-creating-find-package-mutex*)
(sb-int:encapsulate 'find-package 'create #'creating-find-package)
(unwind-protect
(handler-bind ((package-error #'continue))
(funcall body))
(sb-int:unencapsulate 'find-package 'create)))))
(defmacro with-creating-find-package ((&key (use '("COMMON-LISP"))) &body body)
"Executes body in an environment where FIND-PACKAGE will not signal an unknown package error.
Instead it will create the package with the missing name with the provided USE packages."
`(call-with-augmented-find-package (lambda () ,@body) :use ',use))
(defmacro with-default-package ((default) &body body)
"Executes body in an environment where FIND-PACKAGE will not signal an unknown package error.
Instead it will return the DEFAULT package."
`(call-with-augmented-find-package (lambda () ,@body) :default ,default))
(defun compile-files (names &rest rest)
"Call COMPILE-FILE on NAMES, which must be singular despite being named NAMES,
passing through REST unaltered."
(if (typep names '(or atom (cons string null)))
(apply #'compile-file (if (atom names) names (car names)) rest)
(error "Multiple file support is incomplete")))
| null | https://raw.githubusercontent.com/qitab/bazelisp/8c601ed97b0eeab1c5f2f64c7a5978bbce9960ea/sbcl.lisp | lisp |
license that can be found in the LICENSE file or at
.
Default optimization settings.
to compile either of those from fresh upstream sources without some magic.
threading
This is not necessary, except for debugging and aesthetics.
Preserve source forms, assuming we want them if they exist.
Precompile generic functions.
For more information see:
-internals/Discriminating-Functions.html
/
Precompute the discriminating function only for shallow class hierarchies.
we run the danger of an exponential combination of those subclasses.
Finalize the inheritance of those classes.
This is useful for accessor functions.
Enumerate all the subclasses for not simple specializers.
A dispatching discriminating function is expensive for class specializers.
Make a dispatching discriminating function.
Make a caching discriminating function.
The MAKE-FINAL-DFUN-INTERNAL will also optimize for other cases.
This list contains packages holding symbols of generic functions which will not be precompiled.
Generate an image.
Reading lisp files.
The instant that ENCAPSULATE stores the new definition of FIND-PACKAGE, we must
accept that any thread - whether already running, or newly created - can access
our local function as a consequence of needing FIND-PACKAGE for any random reason.
Were the closure allocated on this thread's stack, then this function's frame
would be forbidden from returning until no other thread was executing the code
that was made globally visible. Since there's no way to determine when the last
execution has ended, the FLET body has indefinite, not dynamic, extent. | Copyright 2015 - 2020 Google LLC
Use of this source code is governed by an MIT - style
Utilities for and their implementation in SBCL .
# -dbg ( declaim ( optimize ( speed 3 ) ( safety 1 ) ) )
(eval-when (:compile-toplevel :load-toplevel :execute)
MD5 pulls in SB - ROTATE - BYTE which makes it impossible
(require :sb-md5))
(defpackage #:bazel.sbcl
(:use #:common-lisp #:sb-thread #:sb-alien #:bazel.utils)
(:import-from #:sb-md5 #:md5sum-file)
(:export #:compile-files
#:exit
#:run
#:inline-function-p
#:function-has-transforms-p
#:getenv #:unsetenv #:chdir
#:command-line-arguments #:program-name
#:default-toplevel-loop
#:mute-output-streams
#:save-lisp-and-die
#:dump-alien-symbols
#:dump-extern-symbols
#:dump-dynamic-list-lds
#:combine-run-time-and-core
#:md5sum-file
#:set-interpret-mode
#:set-interactive-mode
#:setup-readtable
#:remove-extra-debug-info
#:name-closure
#:with-creating-find-package
#:with-default-package
#:make-thread
#:join-thread
#:with-recursive-lock
#:make-mutex #:mutex
#:pmapcar
#:pprog1))
(in-package #:bazel.sbcl)
(defun exit (&optional (code 0))
"Exit the process with a return CODE."
(sb-ext:exit :code code))
(defun run (program &key args input output (error :output) dir)
"Run a PROGRAM suppling ARGS and return the exit code.
Arguments:
ARGS - a list of string arguments to the program,
INPUT - a spec for the standard input for the program,
OUTPUT - a spec for the standard output for the program,
ERROR - a spec for the error output for the program.
DIR - the directory used for the program to run.
The specification for INPUT, OUTPUT, and ERROR can be:
NIL - the stream is mapped to /dev/null,
T - the standard input, output, or error stream of this process is used,
pathname - the file functions as input or output,
stream - the stream functions as input or output,
:OUTPUT - indicates that the error stream equals the output stream."
(sb-ext:process-exit-code
(sb-ext:run-program program args :input input :output output :error error :directory dir)))
(declaim (ftype (function (function &rest list) (values list &optional)) pmapcar))
(defun pmapcar (function &rest lists)
"Takes a FUNCTION and LISTS of arguments and executes the function for each argument tuple.
The function is run is separate threads. The first tuple of arguments is run in the current one."
(flet ((run (args) (make-thread function :arguments args)))
(declare (dynamic-extent #'run) (inline run))
(let* ((args (apply #'mapcar #'list lists))
(threads (mapcar #'run (rest args))))
(when args
(list* (apply function (first args)) (mapcar #'join-thread threads))))))
(defmacro pprog1 (form1 &rest forms)
"Take each of the FORMS and run them in a separate thread. Join threads at the end.
Returns the result of the first form. FORM1 is executed in the current thread."
(let ((functions (gensym "F"))
(threads (gensym "T")))
`(let* ((,functions (list ,@(loop for form in forms collect `(lambda () ,form))))
(,threads (mapcar #'make-thread ,functions)))
(prog1 ,form1
(mapc #'join-thread ,threads)))))
(defun inline-function-p (function)
"Returns non-nil when the FUNCTION is declared inline."
(eq (sb-int:info :function :inlinep function) 'inline))
(defun function-has-transforms-p (function)
"Returns non-nil if the FUNCTION has transforms."
(or (sb-c::info :function :source-transform function)
(let ((info (sb-c::info :function :info function)))
(and info (sb-c::fun-info-transforms info)))))
(defun getenv (variable)
"Returns the value of the environment VARIABLE."
(sb-ext:posix-getenv variable))
(defun unsetenv (variable)
"Removes the VARIABLE from the environment."
(alien-funcall
(extern-alien "unsetenv" (function sb-alien:int sb-alien:c-string))
variable))
(defun command-line-arguments ()
"Returns the command-line arguments without the program name."
(rest sb-unix::*posix-argv*))
(defun program-name ()
"Returns the name of the program."
(first sb-unix::*posix-argv*))
(defun default-toplevel-loop ()
"Gives control to the default toplevel REPL."
(sb-ext:enable-debugger)
(sb-impl::toplevel-init))
(defun mute-output-streams ()
"Mute SBCL image write messages."
Set runtime --noinform option to 1 , which also hides the " [ writing ... ] " noise
(setf (extern-alien "lisp_startup_options" int) 1)
nil)
(defun terminate-other-threads ()
"Terminates all non-system threads but the current one."
(let ((threads (remove-if (lambda (x)
(or (thread-ephemeral-p x)
(eq x *current-thread*)))
(list-all-threads))))
(mapc #'terminate-thread threads)
(mapc (lambda (thread) (join-thread thread :default nil)) threads)))
(defun name-closure (closure name)
"Return CLOSURE with the NAME changed, so it prints nicely."
(setf (sb-kernel:%fun-name closure) name)
closure)
(defun remove-extra-debug-info ()
"Removes debug info like docstrings and xrefs."
(sb-vm::map-allocated-objects
(lambda (obj type size)
(declare (ignore size))
(when (= type sb-vm:code-header-widetag)
(dotimes (i (sb-kernel:code-n-entries obj))
(let ((f (sb-kernel:%code-entry-point obj i)))
(setf (sb-kernel:%simple-fun-info f) 'function)
(setf (sb-kernel:%simple-fun-source f)
(sb-kernel:%simple-fun-lexpr f))))))
:all))
TODO(czak ): This needs to go into SBCL upstream .
(defun eql-specializer-p (spec)
"True if SPEC is an eql specializer."
(typep spec 'sb-mop:eql-specializer))
(defun trivial-class-specializer-p (spec)
"True if SPEC is a trivial class specializer."
(or (eq spec #.(find-class t))
(eq spec #.(find-class 'standard-object))
(eq spec #.(find-class 'sb-pcl::slot-object))
(eq spec #.(find-class 'sb-pcl::structure-object))))
(defun non-trivial-class-specializer-p (spec)
"True if SPEC is non-trivial class specializer."
(not (or (eql-specializer-p spec)
(trivial-class-specializer-p spec))))
(defun simple-specializer-p (spec)
"True if SPEC is not a class specializer with subclasses."
(or (eql-specializer-p spec)
(trivial-class-specializer-p spec)
(null (sb-mop:class-direct-subclasses spec))))
(defun gf-specializers-list (gf)
"Returns a list of method specializers for the generic function GF."
(let ((methods (sb-mop:generic-function-methods gf))
(specializers-list nil))
(dolist (method methods (nreverse specializers-list))
(pushnew (sb-mop:method-specializers method) specializers-list :test #'equalp))))
(defun precompile-generic-function (gf &key verbose)
"Precompiles the dispatch code for the generic function GF.
When VERBOSE is larger than 2, print some debug info.
Returns true when the GF has been precompiled."
(when (sb-pcl::special-case-for-compute-discriminating-function-p gf)
TODO(czak ): Those special cases are handled differently by SBCL .
(return-from precompile-generic-function))
(let ((methods (sb-mop:generic-function-methods gf))
(simple-p t)
(class-specializers-p nil)
(eql-specializers-p nil)
(specializers-list (gf-specializers-list gf)))
(dolist (method methods)
(let ((specializers (sb-mop:method-specializers method))
(count-not-simple 0))
(dolist (spec specializers)
(unless (simple-specializer-p spec)
(when (> (incf count-not-simple) 1)
If we have more than one class specializer with subclasses ,
Precompilation might then explode the caches and takes time .
(when (> verbose 2) (format t "!SIMPLE: ~S~%" gf))
(return-from precompile-generic-function)))
(cond ((non-trivial-class-specializer-p spec)
(setf class-specializers-p t)
(unless (sb-mop:class-finalized-p spec)
(sb-mop:finalize-inheritance spec)))
((eql-specializer-p spec)
(setf eql-specializers-p t))))
(when (plusp count-not-simple)
(setf simple-p nil))))
(unless simple-p
(dolist (specializers specializers-list)
(let ((pos (position-if-not #'simple-specializer-p specializers)))
(when pos
(labels ((augment (spec)
(dolist (sub (sb-mop:class-direct-subclasses spec))
(let ((new (copy-list specializers)))
(setf (nth pos new) sub)
(pushnew new specializers-list :test #'equal))
(augment sub))))
(augment (nth pos specializers)))))))
Making a caching discriminating function for EQL specializers fails .
(when (and class-specializers-p eql-specializers-p
(> (max (length methods) (length specializers-list)) 10))
(when (> verbose 2) (format t "!C+E: ~S: ~D specs~%" gf (length specializers-list)))
(return-from precompile-generic-function))
(setf (sb-pcl::gf-precompute-dfun-and-emf-p (sb-pcl::gf-arg-info gf)) t)
(multiple-value-bind (dfun cache info)
(cond ((and eql-specializers-p
(or (cdr methods) (cdr specializers-list) (cdar specializers-list)))
(when (> verbose 2) (format t "DISPATCH: ~S~%" gf))
(sb-pcl::make-final-dispatch-dfun gf))
(t
(when (> verbose 2)
(format t "DEFAULT: ~S: ~D specs~:[~;, EQL~]~:[~;, CLS~]~%"
gf (length specializers-list) eql-specializers-p class-specializers-p))
(sb-pcl::make-final-dfun-internal gf specializers-list)))
(sb-pcl::update-dfun gf dfun cache info))
t))
(defvar *skip-precompile-packages* nil)
(defun precompile-generic-functions (&key (verbose 0))
"Enumerates all generic functions and pre-compiles their dispatch functions.
When VERBOSE is larger then 0, print some debug info.
Returns a count of successfully precompiled dispatch functions."
(let ((count 0)
(all 0))
(flet ((precompile (s)
(let ((f (and (fboundp s) (fdefinition s))))
(when (typep f 'standard-generic-function)
(incf all)
(when (precompile-generic-function f :verbose verbose)
(incf count))))))
(do-all-symbols (s)
(unless (find (symbol-package s) *skip-precompile-packages*)
(when (precompile s)
(precompile `(setf ,s)))))
(when (plusp verbose)
(bazel.log:info "Precompiled ~D (~D% out of ~D) generic functions.~%"
count (round (* 100 count) all) all))
(values count all))))
(defun save-lisp-and-die (name &key toplevel save-runtime-options verbose
precompile-generics executable)
"Saves the current Lisp image and dies.
Arguments:
NAME - the file name to save the image.
TOPLEVEL - the name of the toplevel function.
SAVE-RUNTIME-OPTIONS - indicates if the runtime options shall be saved to the C runtime.
This is usually permanent.
VERBOSE - if true, the output streams are not muted before dumping the image.
PRECOMPILE-GENERICS - will precompile the generic functions before saving.
EXECUTABLE - Whether to combine the launcher with the image to create an executable."
(sb-ext:disable-debugger)
(terminate-other-threads)
(when precompile-generics
(precompile-generic-functions :verbose bazel.log:*verbose*))
(unless verbose (mute-output-streams))
(sb-ext:fold-identical-code :aggressive t)
(setf (extern-alien "gc_coalesce_string_literals" char) 2)
(sb-ext:save-lisp-and-die
name
:executable executable
:toplevel toplevel
:save-runtime-options save-runtime-options)
NOLINT
(defun set-interpret-mode (compile-mode)
"Set the mode of eval to :interpret if COMPILE-MODE is :LOAD. Otherwise, set it to :COMPILE."
(declare (optimize (speed 1) (safety 3) (compilation-speed 1) (debug 1)))
(setf sb-ext:*evaluator-mode* (if (eq compile-mode :load) :interpret :compile))
(bazel.log:vvv "Set interpret mode to: ~A" sb-ext:*evaluator-mode*)
sb-ext:*evaluator-mode*)
(defun set-interactive-mode (&optional (interactive-p t))
"If INTERACTIVE-P is true, the debugger will be enabled."
(if interactive-p
(sb-ext:enable-debugger)
(sb-ext:disable-debugger)))
(defun setup-readtable (rt)
(setf (sb-ext:readtable-base-char-preference rt) :both)
rt)
(defvar *in-find-package* nil "Prevents cycles in make-package")
(defvar *with-creating-find-package-mutex* (make-mutex :name "with-creating-find-package-mutex"))
(defun call-with-augmented-find-package (body &key (use '("COMMON-LISP")) (default nil))
"Calls the BODY after making sure that the reader
will not error on unknown packages or not exported symbols.
USE is the set of packages to use by the new package.
This affects _all_ threads' calls to FIND-PACKAGE, and
is generally not appropriate to use in production code"
(declare (function body))
(flet ((creating-find-package (f name)
(or (funcall f name)
default
(unless *in-find-package*
(let ((*in-find-package* t))
(make-package name :use use))))))
(with-recursive-lock (*with-creating-find-package-mutex*)
(sb-int:encapsulate 'find-package 'create #'creating-find-package)
(unwind-protect
(handler-bind ((package-error #'continue))
(funcall body))
(sb-int:unencapsulate 'find-package 'create)))))
(defmacro with-creating-find-package ((&key (use '("COMMON-LISP"))) &body body)
"Executes body in an environment where FIND-PACKAGE will not signal an unknown package error.
Instead it will create the package with the missing name with the provided USE packages."
`(call-with-augmented-find-package (lambda () ,@body) :use ',use))
(defmacro with-default-package ((default) &body body)
"Executes body in an environment where FIND-PACKAGE will not signal an unknown package error.
Instead it will return the DEFAULT package."
`(call-with-augmented-find-package (lambda () ,@body) :default ,default))
(defun compile-files (names &rest rest)
"Call COMPILE-FILE on NAMES, which must be singular despite being named NAMES,
passing through REST unaltered."
(if (typep names '(or atom (cons string null)))
(apply #'compile-file (if (atom names) names (car names)) rest)
(error "Multiple file support is incomplete")))
|
a6ca859818646353fc6805ed12e0e75a62e526a9365e99964dcc9d6f9b31f891 | brendanhay/gogol | Delete.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . SourceRepo . Projects . Repos . Delete
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Deletes a repo.
--
-- /See:/ <-repositories/docs/apis Cloud Source Repositories API Reference> for @sourcerepo.projects.repos.delete@.
module Gogol.SourceRepo.Projects.Repos.Delete
( -- * Resource
SourceRepoProjectsReposDeleteResource,
-- ** Constructing a Request
SourceRepoProjectsReposDelete (..),
newSourceRepoProjectsReposDelete,
)
where
import qualified Gogol.Prelude as Core
import Gogol.SourceRepo.Types
| A resource alias for @sourcerepo.projects.repos.delete@ method which the
-- 'SourceRepoProjectsReposDelete' request conforms to.
type SourceRepoProjectsReposDeleteResource =
"v1"
Core.:> Core.Capture "name" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Delete '[Core.JSON] Empty
-- | Deletes a repo.
--
/See:/ ' ' smart constructor .
data SourceRepoProjectsReposDelete = SourceRepoProjectsReposDelete
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
-- | The name of the repo to delete. Values are of the form @projects\/\/repos\/@.
name :: Core.Text,
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'SourceRepoProjectsReposDelete' with the minimum fields required to make a request.
newSourceRepoProjectsReposDelete ::
-- | The name of the repo to delete. Values are of the form @projects\/\/repos\/@. See 'name'.
Core.Text ->
SourceRepoProjectsReposDelete
newSourceRepoProjectsReposDelete name =
SourceRepoProjectsReposDelete
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
name = name,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
SourceRepoProjectsReposDelete
where
type Rs SourceRepoProjectsReposDelete = Empty
type
Scopes SourceRepoProjectsReposDelete =
'[CloudPlatform'FullControl, Source'FullControl]
requestClient SourceRepoProjectsReposDelete {..} =
go
name
xgafv
accessToken
callback
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
sourceRepoService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy SourceRepoProjectsReposDeleteResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-sourcerepo/gen/Gogol/SourceRepo/Projects/Repos/Delete.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Deletes a repo.
/See:/ <-repositories/docs/apis Cloud Source Repositories API Reference> for @sourcerepo.projects.repos.delete@.
* Resource
** Constructing a Request
'SourceRepoProjectsReposDelete' request conforms to.
| Deletes a repo.
| V1 error format.
| OAuth access token.
| The name of the repo to delete. Values are of the form @projects\/\/repos\/@.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'SourceRepoProjectsReposDelete' with the minimum fields required to make a request.
| The name of the repo to delete. Values are of the form @projects\/\/repos\/@. See 'name'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . SourceRepo . Projects . Repos . Delete
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.SourceRepo.Projects.Repos.Delete
SourceRepoProjectsReposDeleteResource,
SourceRepoProjectsReposDelete (..),
newSourceRepoProjectsReposDelete,
)
where
import qualified Gogol.Prelude as Core
import Gogol.SourceRepo.Types
| A resource alias for @sourcerepo.projects.repos.delete@ method which the
type SourceRepoProjectsReposDeleteResource =
"v1"
Core.:> Core.Capture "name" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.Delete '[Core.JSON] Empty
/See:/ ' ' smart constructor .
data SourceRepoProjectsReposDelete = SourceRepoProjectsReposDelete
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
name :: Core.Text,
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSourceRepoProjectsReposDelete ::
Core.Text ->
SourceRepoProjectsReposDelete
newSourceRepoProjectsReposDelete name =
SourceRepoProjectsReposDelete
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
name = name,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
SourceRepoProjectsReposDelete
where
type Rs SourceRepoProjectsReposDelete = Empty
type
Scopes SourceRepoProjectsReposDelete =
'[CloudPlatform'FullControl, Source'FullControl]
requestClient SourceRepoProjectsReposDelete {..} =
go
name
xgafv
accessToken
callback
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
sourceRepoService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy SourceRepoProjectsReposDeleteResource
)
Core.mempty
|
e36327945f8d4301918e260f4f9c6cf53f01361d6bf15d8bfb02400a5f401608 | lukaszcz/coinduction | cUtils.ml | open Util
open Term
open Names
open Declarations
open Entries
(***************************************************************************************)
(* numbers from m up to but not including n *)
let range m n =
let rec go acc i j =
if i >= j then acc else go (i :: acc) (i + 1) j
in List.rev (go [] m n)
let rec repl n x =
if n = 0 then
[]
else
x :: repl (n - 1) x
let rec take n lst =
if n > 0 then
match lst with
| [] -> []
| h :: t -> h :: take (n - 1) t
else
[]
let rec drop n lst =
if n > 0 then
match lst with
| [] -> []
| h :: t -> drop (n - 1) t
else
lst
let string_ends_with s1 s2 =
let n1 = String.length s1
and n2 = String.length s2
in
if n1 < n2 then
false
else
String.sub s1 (n1 - n2) n2 = s2
let get_basename s =
try
let i = String.rindex s '.' in
String.sub s (i + 1) (String.length s - i - 1)
with Not_found ->
s
let id_app id app = Id.of_string (Id.to_string id ^ app)
let string_to_id s = Id.of_string (get_basename s)
(***************************************************************************************)
let intern_constr env evd cexpr =
let (t, uctx) = Constrintern.interp_constr env evd cexpr in
let sigma = Evd.from_ctx uctx in
Typing.solve_evars env sigma t
let to_constr r =
let open Names.GlobRef in
match r with
| VarRef(v) -> EConstr.mkVar v
| ConstRef(c) -> EConstr.mkConst c
| IndRef(i) -> EConstr.mkInd i
| ConstructRef(cr) -> EConstr.mkConstruct cr
let get_global s =
Nametab.locate (Libnames.qualid_of_string s)
let exists_global s =
try
ignore (get_global s);
true
with Not_found -> false
let get_constr s =
to_constr (get_global s)
let get_inductive s =
match get_global s with
| Names.GlobRef.IndRef(i) -> i
| _ -> failwith "get_inductive: not an inductive type"
let get_ind_name ind =
Libnames.string_of_path (Nametab.path_of_global
(Globnames.canonical_gr (Names.GlobRef.IndRef ind)))
let get_ind_nparams ind =
let mind = fst (Inductive.lookup_mind_specif (Global.env ()) ind) in
let open Declarations in
mind.mind_nparams
let rec close f ctx t =
match ctx with
| [] -> t
| (x,ty) :: l -> f (x, ty, close f l t)
(***************************************************************************************)
let rec drop_lambdas evd n t =
let open Constr in
let open EConstr in
if n = 0 then
t
else
match kind evd t with
| Lambda (na, ty, body) -> drop_lambdas evd (n - 1) body
| _ -> t
let rec take_lambdas evd n t =
let open Constr in
let open EConstr in
if n = 0 then
[]
else
match kind evd t with
| Lambda (na, ty, body) -> (na, ty) :: take_lambdas evd (n - 1) body
| _ -> []
let rec drop_prods evd n t =
let open Constr in
let open EConstr in
if n = 0 then
t
else
match kind evd t with
| Prod (na, ty, body) -> drop_prods evd (n - 1) body
| _ -> t
let rec take_prods evd n t =
let open Constr in
let open EConstr in
if n = 0 then
[]
else
match kind evd t with
| Prod (na, ty, body) -> (na, ty) :: take_prods evd (n - 1) body
| _ -> []
let rec drop_all_lambdas evd t =
let open Constr in
let open EConstr in
match kind evd t with
| Lambda (na, ty, body) -> drop_all_lambdas evd body
| _ -> t
let rec take_all_lambdas evd t =
let open Constr in
let open EConstr in
match kind evd t with
| Lambda (na, ty, body) -> (na, ty) :: take_all_lambdas evd body
| _ -> []
let rec drop_all_prods evd t =
let open Constr in
let open EConstr in
match kind evd t with
| Prod (na, ty, body) -> drop_all_prods evd body
| _ -> t
let rec take_all_prods evd t =
let open Constr in
let open EConstr in
match kind evd t with
| Prod (na, ty, body) -> (na, ty) :: take_all_prods evd body
| _ -> []
(***************************************************************************************)
let map_fold_constr f acc evd t =
let open Constr in
let open EConstr in
let rec hlp m acc t =
let fold_arr k ac ar =
let (ac1, lst) =
List.fold_left
(fun (ac,l) x -> let (ac',x') = hlp k ac x in (ac',x'::l))
(ac, [])
(Array.to_list ar)
in
(ac1, Array.of_list (List.rev lst))
in
match kind evd t with
| Rel _ | Meta _ | Var _ | Sort _ | Const _ |
Ind _ | Construct _ | Int _ ->
f m acc t
| Cast (ty1,ck,ty2) ->
let (acc1, ty1') = hlp m acc ty1 in
let (acc2, ty2') = hlp m acc1 ty2 in
f m acc2 (mkCast(ty1',ck,ty2'))
| Prod (na,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, c') = hlp (m+1) acc1 c in
f m acc2 (mkProd(na,ty',c'))
| Lambda (na,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, c') = hlp (m+1) acc1 c in
f m acc2 (mkLambda(na,ty',c'))
| LetIn (na,b,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, b') = hlp m acc1 b in
let (acc3, c') = hlp (m+1) acc2 c in
f m acc3 (mkLetIn(na,b',ty',c'))
| App (a,args) ->
let (acc1, a') = hlp m acc a in
let (acc2, args') = fold_arr m acc1 args in
f m acc2 (mkApp(a',args'))
| Proj (p,c) ->
let (acc1, c') = hlp m acc c in
f m acc1 (mkProj(p,c'))
| Evar (evk,cl) ->
let (acc1, cl') = fold_arr m acc cl in
f m acc1 (mkEvar(evk,cl'))
| Case (ci,p,c,bl) ->
let (acc1, p') = hlp m acc p in
let (acc2, c') = hlp m acc1 c in
let (acc3, bl') = fold_arr m acc2 bl in
f m acc3 (mkCase(ci,p',c',bl'))
| Fix (nvn,recdef) ->
let (fnames,typs,bodies) = recdef in
let (acc1, typs') = fold_arr m acc typs in
let (acc2, bodies') = fold_arr (m + Array.length typs) acc1 bodies in
f m acc2 (mkFix(nvn,(fnames,typs',bodies')))
| CoFix (n,recdef) ->
let (fnames,typs,bodies) = recdef in
let (acc1, typs') = fold_arr m acc typs in
let (acc2, bodies') = fold_arr (m + Array.length typs) acc1 bodies in
f m acc2 (mkCoFix(n,(fnames,typs',bodies')))
in
hlp 0 acc t
let map_constr f evd x = snd (map_fold_constr (fun m () t -> ((), f m t)) () evd x)
let fold_constr f acc evd x = fst (map_fold_constr (fun m acc t -> (f m acc t, t)) acc evd x)
let map_fold_constr_ker f acc t =
let open Constr in
let rec hlp m acc t =
let fold_arr k ac ar =
let (ac1, lst) =
List.fold_left
(fun (ac,l) x -> let (ac',x') = hlp k ac x in (ac',x'::l))
(ac, [])
(Array.to_list ar)
in
(ac1, Array.of_list (List.rev lst))
in
match kind t with
| Rel _ | Meta _ | Var _ | Sort _ | Const _ | Ind _ | Construct _ | Int _ ->
f m acc t
| Cast (ty1,ck,ty2) ->
let (acc1, ty1') = hlp m acc ty1 in
let (acc2, ty2') = hlp m acc1 ty2 in
f m acc2 (mkCast(ty1',ck,ty2'))
| Prod (na,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, c') = hlp (m+1) acc1 c in
f m acc2 (mkProd(na,ty',c'))
| Lambda (na,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, c') = hlp (m+1) acc1 c in
f m acc2 (mkLambda(na,ty',c'))
| LetIn (na,b,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, b') = hlp m acc1 b in
let (acc3, c') = hlp (m+1) acc2 c in
f m acc3 (mkLetIn(na,b',ty',c'))
| App (a,args) ->
let (acc1, a') = hlp m acc a in
let (acc2, args') = fold_arr m acc1 args in
f m acc2 (mkApp(a',args'))
| Proj (p,c) ->
let (acc1, c') = hlp m acc c in
f m acc1 (mkProj(p,c'))
| Evar (evk,cl) ->
let (acc1, cl') = fold_arr m acc cl in
f m acc1 (mkEvar(evk,cl'))
| Case (ci,p,c,bl) ->
let (acc1, p') = hlp m acc p in
let (acc2, c') = hlp m acc1 c in
let (acc3, bl') = fold_arr m acc2 bl in
f m acc3 (mkCase(ci,p',c',bl'))
| Fix (nvn,recdef) ->
let (fnames,typs,bodies) = recdef in
let (acc1, typs') = fold_arr m acc typs in
let (acc2, bodies') = fold_arr (m + Array.length typs) acc1 bodies in
f m acc2 (mkFix(nvn,(fnames,typs',bodies')))
| CoFix (n,recdef) ->
let (fnames,typs,bodies) = recdef in
let (acc1, typs') = fold_arr m acc typs in
let (acc2, bodies') = fold_arr (m + Array.length typs) acc1 bodies in
f m acc2 (mkCoFix(n,(fnames,typs',bodies')))
in
hlp 0 acc t
let map_constr_ker f x = snd (map_fold_constr_ker (fun m () t -> ((), f m t)) () x)
let fold_constr_ker f acc x = fst (map_fold_constr_ker (fun m acc t -> (f m acc t, t)) acc x)
let rel_occurs evd t lst =
let open Constr in
let open EConstr in
fold_constr
begin fun n b x ->
match kind evd x with
| Rel j -> if List.mem (j - n) lst then true else b
| _ -> b
end
false
evd
t
let do_shift evd k t =
let open Constr in
let open EConstr in
map_constr
begin fun n t ->
match kind evd t with
| Rel i when i > n -> mkRel (i + k)
| _ -> t
end
evd
t
let shift_binders_down evd k t =
assert (k >= 0);
if k = 0 then
t
else
do_shift evd (-k) t
let shift_binders_up evd k t =
assert (k >= 0);
if k = 0 then
t
else
do_shift evd k t
(***************************************************************************************)
let is_coinductive (ind : inductive) =
let mind = fst (Inductive.lookup_mind_specif (Global.env ()) ind) in
let open Declarations in
match mind.mind_finite with
| CoFinite -> true
| _ -> false
let is_like f (ind : inductive) =
let mind = fst (Inductive.lookup_mind_specif (Global.env ()) ind) in
let open Declarations in
if mind.mind_ntypes <> 1 then
false
else
let body = mind.mind_packets.(0) in
if Array.length body.mind_user_lc <> 1 then
false
else
f (mind.mind_nparams) (body.mind_user_lc.(0))
let is_and_like =
is_like begin fun p t ->
let open Constr in
let rec drop_params n t cont =
if n = 0 then
cont t
else
match kind t with
| Prod(na, ty, b) -> drop_params (n - 1) b cont
| _ -> false
in
let rec hlp n t =
match kind t with
| Prod(na, ty, b) ->
begin
match kind ty with
| Rel k when k = p -> hlp (n + 1) b
| _ -> false
end
| App (r, args) ->
begin
match kind r with
| Rel k when k = n + p + 1 ->
List.filter begin fun x ->
match kind x with
| Rel k when k <= n + p && k > n -> false
| _ -> true
end (Array.to_list args)
= []
| _ -> false
end
| _ -> false
in
drop_params p t (hlp 0)
end
let is_exists_like =
is_like begin fun p t ->
if p <> 2 then
false
else
let open Constr in
match kind t with
| Prod(_, _, t) ->
begin
match kind t with
| Prod(_, _, t) ->
begin
match kind t with
| Prod(_, r, t) ->
begin
match kind r with
| Rel 2 ->
begin
match kind t with
| Prod(_, app, t) ->
begin
match kind app with
| App(r, args) ->
begin
match args with
| [| a |] ->
begin
match (kind r, kind a) with
| (Rel 2, Rel 1) ->
begin
match kind t with
| App(r, _) ->
begin
match kind r with
| Rel 5 -> true
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
let get_inductive_typeargs evd (ind : inductive) =
let open Constr in
let open EConstr in
let rec hlp acc t =
match kind evd t with
| Prod(x, ty, b) -> hlp ((x,ty) :: acc) b
| _ -> List.rev acc
in
let env = Global.env () in
let minds = Inductive.lookup_mind_specif env ind in
let tp = Inductive.type_of_inductive env (Univ.in_punivs minds) in
hlp [] (EConstr.of_constr tp)
(***************************************************************************************)
The following contains code from .
Replace
Var(y1) .. Var(yq):C1 .. Bj
Var(y1) .. Var(yq):C1 .. Cq ; I1 .. Ip : B1 .. Bp |- ci : Ti
by
|- Ij : ( y1 .. yq : C1 .. Cq)Bj
I1 .. Ip:(B1 y1 .. yq) .. (Bp y1 .. yq ) : ( y1 .. yq : C1 .. Cq)Ti[Ij:=(Ij y1 .. yq ) ]
Var(y1)..Var(yq):C1..Cq |- Ij:Bj
Var(y1)..Var(yq):C1..Cq; I1..Ip:B1..Bp |- ci : Ti
by
|- Ij: (y1..yq:C1..Cq)Bj
I1..Ip:(B1 y1..yq)..(Bp y1..yq) |- ci : (y1..yq:C1..Cq)Ti[Ij:=(Ij y1..yq)]
*)
let abstract_inductive nparams inds =
(* To be sure to be the same as before, should probably be moved to process_inductive *)
let params' = let (_,arity,_,_,_) = List.hd inds in
let (params,_) = decompose_prod_n_assum nparams arity in
params
in
let ind'' =
List.map
(fun (a,arity,template,c,lc) ->
let _, short_arity = decompose_prod_n_assum nparams arity in
let shortlc =
List.map (fun c -> snd (decompose_prod_n_assum nparams c)) lc in
{ mind_entry_typename = a;
mind_entry_arity = short_arity;
mind_entry_template = template;
mind_entry_consnames = c;
mind_entry_lc = shortlc })
inds
in (params',ind'')
let refresh_polymorphic_type_of_inductive (_,mip) =
match mip.mind_arity with
| RegularArity s -> s.mind_user_arity, false
| TemplateArity ar ->
let ctx = List.rev mip.mind_arity_ctxt in
mkArity (List.rev ctx, Sorts.sort_of_univ ar.template_level), true
let process_inductive mib =
let nparams = Context.Rel.length mib.mind_params_ctxt in
let ind_univs = match mib.mind_universes with
| Monomorphic ctx -> Monomorphic_entry ctx
| Polymorphic auctx ->
let uctx = Univ.AUContext.repr auctx in
let names = Univ.AUContext.names auctx in
Polymorphic_entry (names, uctx)
in
let map mip =
let arity, template = refresh_polymorphic_type_of_inductive (mib,mip) in
(mip.mind_typename,
arity, template,
Array.to_list mip.mind_consnames,
Array.to_list mip.mind_user_lc)
in
let inds = Array.map_to_list map mib.mind_packets in
let (params', inds') = abstract_inductive nparams inds in
let record = match mib.mind_record with
| PrimRecord arr -> Some (Some (Array.map (fun (id, _, _, _) -> id) arr))
| FakeRecord -> Some None
| NotRecord -> None
in
{ mind_entry_record = record;
mind_entry_finite = mib.mind_finite;
mind_entry_params = params';
mind_entry_inds = inds';
mind_entry_private = mib.mind_private;
mind_entry_universes = ind_univs;
mind_entry_variance = None
}
The following contains code from
let edeclare ?hook ~ontop ident (_, poly, _ as k) ~opaque sigma udecl body tyopt imps =
let sigma = Evd.minimize_universes sigma in
let body = EConstr.to_constr sigma body in
let tyopt = Option.map (EConstr.to_constr sigma) tyopt in
let uvars_fold uvars c =
Univ.LSet.union uvars (Vars.universes_of_constr c) in
let uvars = List.fold_left uvars_fold Univ.LSet.empty
(Option.List.cons tyopt [body]) in
let sigma = Evd.restrict_universe_context sigma uvars in
let univs = Evd.check_univ_decl ~poly sigma udecl in
let uctx = Evd.evar_universe_context sigma in
let ubinders = Evd.universe_binders sigma in
let ce = Declare.definition_entry ?types:tyopt ~univs body in
let hook_data = Option.map (fun hook -> hook, uctx, []) hook in
DeclareDef.declare_definition ~ontop ident k ce ubinders imps ?hook_data
let declare_definition name ?(opaque=false) sigma body =
let k = (Decl_kinds.Global, true, Decl_kinds.Definition) in
let udecl = UState.default_univ_decl in
ignore (edeclare ~ontop:None name k ~opaque sigma udecl body None [])
| null | https://raw.githubusercontent.com/lukaszcz/coinduction/b7437fe155a45f93042a5788dc62512534172dcd/src/cUtils.ml | ocaml | *************************************************************************************
numbers from m up to but not including n
*************************************************************************************
*************************************************************************************
*************************************************************************************
*************************************************************************************
*************************************************************************************
To be sure to be the same as before, should probably be moved to process_inductive | open Util
open Term
open Names
open Declarations
open Entries
let range m n =
let rec go acc i j =
if i >= j then acc else go (i :: acc) (i + 1) j
in List.rev (go [] m n)
let rec repl n x =
if n = 0 then
[]
else
x :: repl (n - 1) x
let rec take n lst =
if n > 0 then
match lst with
| [] -> []
| h :: t -> h :: take (n - 1) t
else
[]
let rec drop n lst =
if n > 0 then
match lst with
| [] -> []
| h :: t -> drop (n - 1) t
else
lst
let string_ends_with s1 s2 =
let n1 = String.length s1
and n2 = String.length s2
in
if n1 < n2 then
false
else
String.sub s1 (n1 - n2) n2 = s2
let get_basename s =
try
let i = String.rindex s '.' in
String.sub s (i + 1) (String.length s - i - 1)
with Not_found ->
s
let id_app id app = Id.of_string (Id.to_string id ^ app)
let string_to_id s = Id.of_string (get_basename s)
let intern_constr env evd cexpr =
let (t, uctx) = Constrintern.interp_constr env evd cexpr in
let sigma = Evd.from_ctx uctx in
Typing.solve_evars env sigma t
let to_constr r =
let open Names.GlobRef in
match r with
| VarRef(v) -> EConstr.mkVar v
| ConstRef(c) -> EConstr.mkConst c
| IndRef(i) -> EConstr.mkInd i
| ConstructRef(cr) -> EConstr.mkConstruct cr
let get_global s =
Nametab.locate (Libnames.qualid_of_string s)
let exists_global s =
try
ignore (get_global s);
true
with Not_found -> false
let get_constr s =
to_constr (get_global s)
let get_inductive s =
match get_global s with
| Names.GlobRef.IndRef(i) -> i
| _ -> failwith "get_inductive: not an inductive type"
let get_ind_name ind =
Libnames.string_of_path (Nametab.path_of_global
(Globnames.canonical_gr (Names.GlobRef.IndRef ind)))
let get_ind_nparams ind =
let mind = fst (Inductive.lookup_mind_specif (Global.env ()) ind) in
let open Declarations in
mind.mind_nparams
let rec close f ctx t =
match ctx with
| [] -> t
| (x,ty) :: l -> f (x, ty, close f l t)
let rec drop_lambdas evd n t =
let open Constr in
let open EConstr in
if n = 0 then
t
else
match kind evd t with
| Lambda (na, ty, body) -> drop_lambdas evd (n - 1) body
| _ -> t
let rec take_lambdas evd n t =
let open Constr in
let open EConstr in
if n = 0 then
[]
else
match kind evd t with
| Lambda (na, ty, body) -> (na, ty) :: take_lambdas evd (n - 1) body
| _ -> []
let rec drop_prods evd n t =
let open Constr in
let open EConstr in
if n = 0 then
t
else
match kind evd t with
| Prod (na, ty, body) -> drop_prods evd (n - 1) body
| _ -> t
let rec take_prods evd n t =
let open Constr in
let open EConstr in
if n = 0 then
[]
else
match kind evd t with
| Prod (na, ty, body) -> (na, ty) :: take_prods evd (n - 1) body
| _ -> []
let rec drop_all_lambdas evd t =
let open Constr in
let open EConstr in
match kind evd t with
| Lambda (na, ty, body) -> drop_all_lambdas evd body
| _ -> t
let rec take_all_lambdas evd t =
let open Constr in
let open EConstr in
match kind evd t with
| Lambda (na, ty, body) -> (na, ty) :: take_all_lambdas evd body
| _ -> []
let rec drop_all_prods evd t =
let open Constr in
let open EConstr in
match kind evd t with
| Prod (na, ty, body) -> drop_all_prods evd body
| _ -> t
let rec take_all_prods evd t =
let open Constr in
let open EConstr in
match kind evd t with
| Prod (na, ty, body) -> (na, ty) :: take_all_prods evd body
| _ -> []
let map_fold_constr f acc evd t =
let open Constr in
let open EConstr in
let rec hlp m acc t =
let fold_arr k ac ar =
let (ac1, lst) =
List.fold_left
(fun (ac,l) x -> let (ac',x') = hlp k ac x in (ac',x'::l))
(ac, [])
(Array.to_list ar)
in
(ac1, Array.of_list (List.rev lst))
in
match kind evd t with
| Rel _ | Meta _ | Var _ | Sort _ | Const _ |
Ind _ | Construct _ | Int _ ->
f m acc t
| Cast (ty1,ck,ty2) ->
let (acc1, ty1') = hlp m acc ty1 in
let (acc2, ty2') = hlp m acc1 ty2 in
f m acc2 (mkCast(ty1',ck,ty2'))
| Prod (na,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, c') = hlp (m+1) acc1 c in
f m acc2 (mkProd(na,ty',c'))
| Lambda (na,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, c') = hlp (m+1) acc1 c in
f m acc2 (mkLambda(na,ty',c'))
| LetIn (na,b,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, b') = hlp m acc1 b in
let (acc3, c') = hlp (m+1) acc2 c in
f m acc3 (mkLetIn(na,b',ty',c'))
| App (a,args) ->
let (acc1, a') = hlp m acc a in
let (acc2, args') = fold_arr m acc1 args in
f m acc2 (mkApp(a',args'))
| Proj (p,c) ->
let (acc1, c') = hlp m acc c in
f m acc1 (mkProj(p,c'))
| Evar (evk,cl) ->
let (acc1, cl') = fold_arr m acc cl in
f m acc1 (mkEvar(evk,cl'))
| Case (ci,p,c,bl) ->
let (acc1, p') = hlp m acc p in
let (acc2, c') = hlp m acc1 c in
let (acc3, bl') = fold_arr m acc2 bl in
f m acc3 (mkCase(ci,p',c',bl'))
| Fix (nvn,recdef) ->
let (fnames,typs,bodies) = recdef in
let (acc1, typs') = fold_arr m acc typs in
let (acc2, bodies') = fold_arr (m + Array.length typs) acc1 bodies in
f m acc2 (mkFix(nvn,(fnames,typs',bodies')))
| CoFix (n,recdef) ->
let (fnames,typs,bodies) = recdef in
let (acc1, typs') = fold_arr m acc typs in
let (acc2, bodies') = fold_arr (m + Array.length typs) acc1 bodies in
f m acc2 (mkCoFix(n,(fnames,typs',bodies')))
in
hlp 0 acc t
let map_constr f evd x = snd (map_fold_constr (fun m () t -> ((), f m t)) () evd x)
let fold_constr f acc evd x = fst (map_fold_constr (fun m acc t -> (f m acc t, t)) acc evd x)
let map_fold_constr_ker f acc t =
let open Constr in
let rec hlp m acc t =
let fold_arr k ac ar =
let (ac1, lst) =
List.fold_left
(fun (ac,l) x -> let (ac',x') = hlp k ac x in (ac',x'::l))
(ac, [])
(Array.to_list ar)
in
(ac1, Array.of_list (List.rev lst))
in
match kind t with
| Rel _ | Meta _ | Var _ | Sort _ | Const _ | Ind _ | Construct _ | Int _ ->
f m acc t
| Cast (ty1,ck,ty2) ->
let (acc1, ty1') = hlp m acc ty1 in
let (acc2, ty2') = hlp m acc1 ty2 in
f m acc2 (mkCast(ty1',ck,ty2'))
| Prod (na,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, c') = hlp (m+1) acc1 c in
f m acc2 (mkProd(na,ty',c'))
| Lambda (na,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, c') = hlp (m+1) acc1 c in
f m acc2 (mkLambda(na,ty',c'))
| LetIn (na,b,ty,c) ->
let (acc1, ty') = hlp m acc ty in
let (acc2, b') = hlp m acc1 b in
let (acc3, c') = hlp (m+1) acc2 c in
f m acc3 (mkLetIn(na,b',ty',c'))
| App (a,args) ->
let (acc1, a') = hlp m acc a in
let (acc2, args') = fold_arr m acc1 args in
f m acc2 (mkApp(a',args'))
| Proj (p,c) ->
let (acc1, c') = hlp m acc c in
f m acc1 (mkProj(p,c'))
| Evar (evk,cl) ->
let (acc1, cl') = fold_arr m acc cl in
f m acc1 (mkEvar(evk,cl'))
| Case (ci,p,c,bl) ->
let (acc1, p') = hlp m acc p in
let (acc2, c') = hlp m acc1 c in
let (acc3, bl') = fold_arr m acc2 bl in
f m acc3 (mkCase(ci,p',c',bl'))
| Fix (nvn,recdef) ->
let (fnames,typs,bodies) = recdef in
let (acc1, typs') = fold_arr m acc typs in
let (acc2, bodies') = fold_arr (m + Array.length typs) acc1 bodies in
f m acc2 (mkFix(nvn,(fnames,typs',bodies')))
| CoFix (n,recdef) ->
let (fnames,typs,bodies) = recdef in
let (acc1, typs') = fold_arr m acc typs in
let (acc2, bodies') = fold_arr (m + Array.length typs) acc1 bodies in
f m acc2 (mkCoFix(n,(fnames,typs',bodies')))
in
hlp 0 acc t
let map_constr_ker f x = snd (map_fold_constr_ker (fun m () t -> ((), f m t)) () x)
let fold_constr_ker f acc x = fst (map_fold_constr_ker (fun m acc t -> (f m acc t, t)) acc x)
let rel_occurs evd t lst =
let open Constr in
let open EConstr in
fold_constr
begin fun n b x ->
match kind evd x with
| Rel j -> if List.mem (j - n) lst then true else b
| _ -> b
end
false
evd
t
let do_shift evd k t =
let open Constr in
let open EConstr in
map_constr
begin fun n t ->
match kind evd t with
| Rel i when i > n -> mkRel (i + k)
| _ -> t
end
evd
t
let shift_binders_down evd k t =
assert (k >= 0);
if k = 0 then
t
else
do_shift evd (-k) t
let shift_binders_up evd k t =
assert (k >= 0);
if k = 0 then
t
else
do_shift evd k t
let is_coinductive (ind : inductive) =
let mind = fst (Inductive.lookup_mind_specif (Global.env ()) ind) in
let open Declarations in
match mind.mind_finite with
| CoFinite -> true
| _ -> false
let is_like f (ind : inductive) =
let mind = fst (Inductive.lookup_mind_specif (Global.env ()) ind) in
let open Declarations in
if mind.mind_ntypes <> 1 then
false
else
let body = mind.mind_packets.(0) in
if Array.length body.mind_user_lc <> 1 then
false
else
f (mind.mind_nparams) (body.mind_user_lc.(0))
let is_and_like =
is_like begin fun p t ->
let open Constr in
let rec drop_params n t cont =
if n = 0 then
cont t
else
match kind t with
| Prod(na, ty, b) -> drop_params (n - 1) b cont
| _ -> false
in
let rec hlp n t =
match kind t with
| Prod(na, ty, b) ->
begin
match kind ty with
| Rel k when k = p -> hlp (n + 1) b
| _ -> false
end
| App (r, args) ->
begin
match kind r with
| Rel k when k = n + p + 1 ->
List.filter begin fun x ->
match kind x with
| Rel k when k <= n + p && k > n -> false
| _ -> true
end (Array.to_list args)
= []
| _ -> false
end
| _ -> false
in
drop_params p t (hlp 0)
end
let is_exists_like =
is_like begin fun p t ->
if p <> 2 then
false
else
let open Constr in
match kind t with
| Prod(_, _, t) ->
begin
match kind t with
| Prod(_, _, t) ->
begin
match kind t with
| Prod(_, r, t) ->
begin
match kind r with
| Rel 2 ->
begin
match kind t with
| Prod(_, app, t) ->
begin
match kind app with
| App(r, args) ->
begin
match args with
| [| a |] ->
begin
match (kind r, kind a) with
| (Rel 2, Rel 1) ->
begin
match kind t with
| App(r, _) ->
begin
match kind r with
| Rel 5 -> true
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
| _ -> false
end
let get_inductive_typeargs evd (ind : inductive) =
let open Constr in
let open EConstr in
let rec hlp acc t =
match kind evd t with
| Prod(x, ty, b) -> hlp ((x,ty) :: acc) b
| _ -> List.rev acc
in
let env = Global.env () in
let minds = Inductive.lookup_mind_specif env ind in
let tp = Inductive.type_of_inductive env (Univ.in_punivs minds) in
hlp [] (EConstr.of_constr tp)
The following contains code from .
Replace
Var(y1) .. Var(yq):C1 .. Bj
Var(y1) .. Var(yq):C1 .. Cq ; I1 .. Ip : B1 .. Bp |- ci : Ti
by
|- Ij : ( y1 .. yq : C1 .. Cq)Bj
I1 .. Ip:(B1 y1 .. yq) .. (Bp y1 .. yq ) : ( y1 .. yq : C1 .. Cq)Ti[Ij:=(Ij y1 .. yq ) ]
Var(y1)..Var(yq):C1..Cq |- Ij:Bj
Var(y1)..Var(yq):C1..Cq; I1..Ip:B1..Bp |- ci : Ti
by
|- Ij: (y1..yq:C1..Cq)Bj
I1..Ip:(B1 y1..yq)..(Bp y1..yq) |- ci : (y1..yq:C1..Cq)Ti[Ij:=(Ij y1..yq)]
*)
let abstract_inductive nparams inds =
let params' = let (_,arity,_,_,_) = List.hd inds in
let (params,_) = decompose_prod_n_assum nparams arity in
params
in
let ind'' =
List.map
(fun (a,arity,template,c,lc) ->
let _, short_arity = decompose_prod_n_assum nparams arity in
let shortlc =
List.map (fun c -> snd (decompose_prod_n_assum nparams c)) lc in
{ mind_entry_typename = a;
mind_entry_arity = short_arity;
mind_entry_template = template;
mind_entry_consnames = c;
mind_entry_lc = shortlc })
inds
in (params',ind'')
let refresh_polymorphic_type_of_inductive (_,mip) =
match mip.mind_arity with
| RegularArity s -> s.mind_user_arity, false
| TemplateArity ar ->
let ctx = List.rev mip.mind_arity_ctxt in
mkArity (List.rev ctx, Sorts.sort_of_univ ar.template_level), true
let process_inductive mib =
let nparams = Context.Rel.length mib.mind_params_ctxt in
let ind_univs = match mib.mind_universes with
| Monomorphic ctx -> Monomorphic_entry ctx
| Polymorphic auctx ->
let uctx = Univ.AUContext.repr auctx in
let names = Univ.AUContext.names auctx in
Polymorphic_entry (names, uctx)
in
let map mip =
let arity, template = refresh_polymorphic_type_of_inductive (mib,mip) in
(mip.mind_typename,
arity, template,
Array.to_list mip.mind_consnames,
Array.to_list mip.mind_user_lc)
in
let inds = Array.map_to_list map mib.mind_packets in
let (params', inds') = abstract_inductive nparams inds in
let record = match mib.mind_record with
| PrimRecord arr -> Some (Some (Array.map (fun (id, _, _, _) -> id) arr))
| FakeRecord -> Some None
| NotRecord -> None
in
{ mind_entry_record = record;
mind_entry_finite = mib.mind_finite;
mind_entry_params = params';
mind_entry_inds = inds';
mind_entry_private = mib.mind_private;
mind_entry_universes = ind_univs;
mind_entry_variance = None
}
The following contains code from
let edeclare ?hook ~ontop ident (_, poly, _ as k) ~opaque sigma udecl body tyopt imps =
let sigma = Evd.minimize_universes sigma in
let body = EConstr.to_constr sigma body in
let tyopt = Option.map (EConstr.to_constr sigma) tyopt in
let uvars_fold uvars c =
Univ.LSet.union uvars (Vars.universes_of_constr c) in
let uvars = List.fold_left uvars_fold Univ.LSet.empty
(Option.List.cons tyopt [body]) in
let sigma = Evd.restrict_universe_context sigma uvars in
let univs = Evd.check_univ_decl ~poly sigma udecl in
let uctx = Evd.evar_universe_context sigma in
let ubinders = Evd.universe_binders sigma in
let ce = Declare.definition_entry ?types:tyopt ~univs body in
let hook_data = Option.map (fun hook -> hook, uctx, []) hook in
DeclareDef.declare_definition ~ontop ident k ce ubinders imps ?hook_data
let declare_definition name ?(opaque=false) sigma body =
let k = (Decl_kinds.Global, true, Decl_kinds.Definition) in
let udecl = UState.default_univ_decl in
ignore (edeclare ~ontop:None name k ~opaque sigma udecl body None [])
|
2a331879e0388dadbbae4758e03d61cf4c6fba06b3e8ed3e77dfef489ac917d5 | sydow/ireal | Erf.hs | module Erf where
import Data.Number.IReal.IRealOperations
import Data.Number.IReal.IntegerInterval
import Data.Number.IReal.IReal
import Data.Number.IReal
To illustrate how to extend the library with e.g. special functions we provide here the example of
the error function erf and the complementary error function erfc .
We follow and Zimmermann 's Modern Computer Arithmetic , chapter 4 .
We use the MacLaurin series which follows directly from the fact
that the derivative of erf is \x - > 2 / sqrt pi * exp(-x^2 ) . This series
actually converges for all x , but convergence is slow for large |x| and
no range reduction is known . For large |x| an asymptotic expansion for erfc
is preferrable , but we have not implemented this , but accept only arguments with
|x| < 100 . Note also that for x > 100 , erfc x < 1e-4345 .
To illustrate how to extend the library with e.g. special functions we provide here the example of
the error function erf and the complementary error function erfc.
We follow Brent and Zimmermann's Modern Computer Arithmetic, chapter 4.
We use the MacLaurin series which follows directly from the fact
that the derivative of erf is \x -> 2/sqrt pi * exp(-x^2). This series
actually converges for all x, but convergence is slow for large |x| and
no range reduction is known. For large |x| an asymptotic expansion for erfc
is preferrable, but we have not implemented this, but accept only arguments with
|x| < 100. Note also that for x > 100, erfc x < 1e-4345.
-}
erf, erfc :: IReal -> IReal
erf x
| midI (abs (appr x 0)) <= 100 = 2/sqrt pi * x * g (sq x)
| otherwise = error "erf(x) only implemented for |x| < 100; for bigger argument it differs from +-1 with at most 1e-4345"
where g = powerSeries (\a n -> negate (a *(2*n-1) `div`(n * (2*n+1)))) 2 id
erfc x = 1 - erf x | null | https://raw.githubusercontent.com/sydow/ireal/c06438544c711169baac7960540202379f9294b1/applications/Erf.hs | haskell | module Erf where
import Data.Number.IReal.IRealOperations
import Data.Number.IReal.IntegerInterval
import Data.Number.IReal.IReal
import Data.Number.IReal
To illustrate how to extend the library with e.g. special functions we provide here the example of
the error function erf and the complementary error function erfc .
We follow and Zimmermann 's Modern Computer Arithmetic , chapter 4 .
We use the MacLaurin series which follows directly from the fact
that the derivative of erf is \x - > 2 / sqrt pi * exp(-x^2 ) . This series
actually converges for all x , but convergence is slow for large |x| and
no range reduction is known . For large |x| an asymptotic expansion for erfc
is preferrable , but we have not implemented this , but accept only arguments with
|x| < 100 . Note also that for x > 100 , erfc x < 1e-4345 .
To illustrate how to extend the library with e.g. special functions we provide here the example of
the error function erf and the complementary error function erfc.
We follow Brent and Zimmermann's Modern Computer Arithmetic, chapter 4.
We use the MacLaurin series which follows directly from the fact
that the derivative of erf is \x -> 2/sqrt pi * exp(-x^2). This series
actually converges for all x, but convergence is slow for large |x| and
no range reduction is known. For large |x| an asymptotic expansion for erfc
is preferrable, but we have not implemented this, but accept only arguments with
|x| < 100. Note also that for x > 100, erfc x < 1e-4345.
-}
erf, erfc :: IReal -> IReal
erf x
| midI (abs (appr x 0)) <= 100 = 2/sqrt pi * x * g (sq x)
| otherwise = error "erf(x) only implemented for |x| < 100; for bigger argument it differs from +-1 with at most 1e-4345"
where g = powerSeries (\a n -> negate (a *(2*n-1) `div`(n * (2*n+1)))) 2 id
erfc x = 1 - erf x | |
5923ca664f1b30f23cd094ace3e7032caae2c5d1e8d2966b36e0f87ef0ad32ad | cojna/iota | LastMinSpec.hs | # LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -Wno - orphans #
module Data.Monoid.LastMinSpec (main, spec) where
import Data.Coerce
import Data.Monoid.LastMin
import Data.Proxy
import Test.Prelude
import Test.Prop.Monoid
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "LastMin Int" $
monoidSpec (Proxy :: Proxy (LastMin Int))
instance Arbitrary a => Arbitrary (LastMin a) where
arbitrary = (coerce :: a -> LastMin a) <$> arbitrary
| null | https://raw.githubusercontent.com/cojna/iota/a64e8c5e4dd4f92e5ed3fcd0413be94ef1108f9e/test/Data/Monoid/LastMinSpec.hs | haskell | # LANGUAGE ScopedTypeVariables #
# OPTIONS_GHC -Wno - orphans #
module Data.Monoid.LastMinSpec (main, spec) where
import Data.Coerce
import Data.Monoid.LastMin
import Data.Proxy
import Test.Prelude
import Test.Prop.Monoid
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "LastMin Int" $
monoidSpec (Proxy :: Proxy (LastMin Int))
instance Arbitrary a => Arbitrary (LastMin a) where
arbitrary = (coerce :: a -> LastMin a) <$> arbitrary
| |
343c38a25910cf5e971c81fae702ff782f8cb72b7f99cfa8100f8aa9cb77a2c9 | disteph/cdsat | range.mli | type _ t [@@deriving show]
val init : 'a t
val pick : 'a t -> Q.t
val mem : Q.t -> 'a t -> bool
type 'a update =
| Range of 'a t
| FourierMotzkin of 'a*'a
| DisEqual of 'a*'a*'a
val upper_update : Q.t -> is_strict:bool -> 'a -> 'a t -> 'a update
val lower_update : Q.t -> is_strict:bool -> 'a -> 'a t -> 'a update
val diseq_update : Q.t -> 'a -> 'a t -> 'a update
| null | https://raw.githubusercontent.com/disteph/cdsat/1b569f3eae59802148f4274186746a9ed3e667ed/src/portfolio/pluginsTh.mld/LRA.mld/range.mli | ocaml | type _ t [@@deriving show]
val init : 'a t
val pick : 'a t -> Q.t
val mem : Q.t -> 'a t -> bool
type 'a update =
| Range of 'a t
| FourierMotzkin of 'a*'a
| DisEqual of 'a*'a*'a
val upper_update : Q.t -> is_strict:bool -> 'a -> 'a t -> 'a update
val lower_update : Q.t -> is_strict:bool -> 'a -> 'a t -> 'a update
val diseq_update : Q.t -> 'a -> 'a t -> 'a update
| |
f27040d7db5774570765ac2bd8488dc5112a4b5f7b680ae647239eafc0e848fa | arichiardi/sicp-clojure | 1_2_samples.clj | (ns sicp-clojure.1-2-samples
(:require [clojure.test :as t]
[clojure.math.numeric-tower :as m]
[sicp-clojure.utils :as u]))
;;; 1.2.2 Example: Counting change
(defn first-denomination [kinds-of-coins]
(cond (= kinds-of-coins 1) 1
(= kinds-of-coins 2) 5
(= kinds-of-coins 3) 10
(= kinds-of-coins 4) 25
(= kinds-of-coins 5) 50))
(defn- cc
"Recursive helper function to count the change."
[amount kinds-of-coins]
(cond (= amount 0) 1
(or (< amount 0) (= kinds-of-coins 0)) 0
:else (+ (cc amount (- kinds-of-coins 1))
(cc (- amount (first-denomination kinds-of-coins)) kinds-of-coins))))
(defn count-change [amount]
(cc amount 5))
( count - change 11 ) ; uncomment to evaluate
;;; 1.2.4 Exponentiation
;; Recursive
(defn expt [b n]
(if (= n 0)
1
(* b (expt b (- n 1)))))
;; Iterative
(defn- expt-iter [b counter product]
(if (= counter 0)
product
(expt-iter b (- counter 1) (* b product))))
(defn expt* [b n]
(expt-iter b n 1))
(defn fast-expt [b n]
(cond (= n 0) 1
(even? n) (u/square (fast-expt b (quot n 2)))
:else (*' b (fast-expt b (- n 1)))))
1.2.6 Example : Testing for Primality
;; If the smallest divisor is n itself, the number is prime.
Order of growth is Theta(n ) = O(sqrt 5 ) .
(defn divides? [a b]
(= (rem b a) 0))
(defn- find-divisor [n test-divisor]
(cond (> (u/square test-divisor) n) n
(divides? test-divisor n) test-divisor
:else (find-divisor n (+ test-divisor 1))))
(defn smallest-divisor [n]
(find-divisor n 2))
(defn prime? [n]
(= (smallest-divisor n) n))
Alternative implementation with Clojure 's recur . It is necessary for the exercises ,
;; as the other find-divisor easily causes stack overflows for big numbers.
(defn- find-divisor-recur [n test-divisor]
(cond (> (u/square test-divisor) n) n
(divides? test-divisor n) test-divisor
:else (recur n (+ test-divisor 1))))
(defn smallest-divisor-recur [n]
(find-divisor-recur n 2))
(defn prime-recur? [n]
(= (smallest-divisor-recur n) n))
Fermat 's test
(defn expmod [base exp m]
(cond (= exp 0) 1
(even? exp) (rem (u/square (expmod base (quot exp 2) m)) m)
:else (rem (*' base (expmod base (- exp 1) m)) m)))
(defn- fermat-test [n]
(defn try-it [a n]
(= (expmod a n n) a))
(try-it (+ 1 (m/round (m/floor (rand (- n 1))))) n))
(defn fast-prime? [n times]
(cond (= times 0) true
(fermat-test n) (fast-prime? n (- times 1))
:else false))
(t/deftest tests
(t/is (= 4 (count-change 11)))
(t/is (= 292 (count-change 100)))
(t/is (= 1 (expt 2 0)))
(t/is (= 64 (expt 2 6)))
(t/is (= 512 (expt 2 9)))
(t/is (= (+ (bit-shift-right Long/MAX_VALUE 1) 1) (expt 2 62)))
(t/is (= 81 (expt 3 4)))
(t/is (= 243 (expt 3 5)))
(t/is (= 1 (expt* 2 0)))
(t/is (= 64 (expt* 2 6)))
(t/is (= 512 (expt* 2 9)))
(t/is (= (+ (bit-shift-right Long/MAX_VALUE 1) 1) (expt* 2 62)))
(t/is (= 81 (expt* 3 4)))
(t/is (= 243 (expt* 3 5)))
(t/is (= 1 (fast-expt 2 0)))
(t/is (= 64 (fast-expt 2 6)))
(t/is (= 512 (fast-expt 2 9)))
(t/is (= (+ (bit-shift-right Long/MAX_VALUE 1) 1) (fast-expt 2 62)))
(t/is (= 81 (fast-expt 3 4)))
(t/is (= 243 (fast-expt 3 5)))
(t/is (= true (prime? 29)))
(t/is (= false (prime? 27)))
(t/is (= true (fast-prime? 29 5)))
(t/is (= false (fast-prime? 27 5))))
| null | https://raw.githubusercontent.com/arichiardi/sicp-clojure/2dc128726406b12de3eaf38fea58dc469e3a60a6/src/sicp_clojure/1_2_samples.clj | clojure | 1.2.2 Example: Counting change
uncomment to evaluate
1.2.4 Exponentiation
Recursive
Iterative
If the smallest divisor is n itself, the number is prime.
as the other find-divisor easily causes stack overflows for big numbers. | (ns sicp-clojure.1-2-samples
(:require [clojure.test :as t]
[clojure.math.numeric-tower :as m]
[sicp-clojure.utils :as u]))
(defn first-denomination [kinds-of-coins]
(cond (= kinds-of-coins 1) 1
(= kinds-of-coins 2) 5
(= kinds-of-coins 3) 10
(= kinds-of-coins 4) 25
(= kinds-of-coins 5) 50))
(defn- cc
"Recursive helper function to count the change."
[amount kinds-of-coins]
(cond (= amount 0) 1
(or (< amount 0) (= kinds-of-coins 0)) 0
:else (+ (cc amount (- kinds-of-coins 1))
(cc (- amount (first-denomination kinds-of-coins)) kinds-of-coins))))
(defn count-change [amount]
(cc amount 5))
(defn expt [b n]
(if (= n 0)
1
(* b (expt b (- n 1)))))
(defn- expt-iter [b counter product]
(if (= counter 0)
product
(expt-iter b (- counter 1) (* b product))))
(defn expt* [b n]
(expt-iter b n 1))
(defn fast-expt [b n]
(cond (= n 0) 1
(even? n) (u/square (fast-expt b (quot n 2)))
:else (*' b (fast-expt b (- n 1)))))
1.2.6 Example : Testing for Primality
Order of growth is Theta(n ) = O(sqrt 5 ) .
(defn divides? [a b]
(= (rem b a) 0))
(defn- find-divisor [n test-divisor]
(cond (> (u/square test-divisor) n) n
(divides? test-divisor n) test-divisor
:else (find-divisor n (+ test-divisor 1))))
(defn smallest-divisor [n]
(find-divisor n 2))
(defn prime? [n]
(= (smallest-divisor n) n))
Alternative implementation with Clojure 's recur . It is necessary for the exercises ,
(defn- find-divisor-recur [n test-divisor]
(cond (> (u/square test-divisor) n) n
(divides? test-divisor n) test-divisor
:else (recur n (+ test-divisor 1))))
(defn smallest-divisor-recur [n]
(find-divisor-recur n 2))
(defn prime-recur? [n]
(= (smallest-divisor-recur n) n))
Fermat 's test
(defn expmod [base exp m]
(cond (= exp 0) 1
(even? exp) (rem (u/square (expmod base (quot exp 2) m)) m)
:else (rem (*' base (expmod base (- exp 1) m)) m)))
(defn- fermat-test [n]
(defn try-it [a n]
(= (expmod a n n) a))
(try-it (+ 1 (m/round (m/floor (rand (- n 1))))) n))
(defn fast-prime? [n times]
(cond (= times 0) true
(fermat-test n) (fast-prime? n (- times 1))
:else false))
(t/deftest tests
(t/is (= 4 (count-change 11)))
(t/is (= 292 (count-change 100)))
(t/is (= 1 (expt 2 0)))
(t/is (= 64 (expt 2 6)))
(t/is (= 512 (expt 2 9)))
(t/is (= (+ (bit-shift-right Long/MAX_VALUE 1) 1) (expt 2 62)))
(t/is (= 81 (expt 3 4)))
(t/is (= 243 (expt 3 5)))
(t/is (= 1 (expt* 2 0)))
(t/is (= 64 (expt* 2 6)))
(t/is (= 512 (expt* 2 9)))
(t/is (= (+ (bit-shift-right Long/MAX_VALUE 1) 1) (expt* 2 62)))
(t/is (= 81 (expt* 3 4)))
(t/is (= 243 (expt* 3 5)))
(t/is (= 1 (fast-expt 2 0)))
(t/is (= 64 (fast-expt 2 6)))
(t/is (= 512 (fast-expt 2 9)))
(t/is (= (+ (bit-shift-right Long/MAX_VALUE 1) 1) (fast-expt 2 62)))
(t/is (= 81 (fast-expt 3 4)))
(t/is (= 243 (fast-expt 3 5)))
(t/is (= true (prime? 29)))
(t/is (= false (prime? 27)))
(t/is (= true (fast-prime? 29 5)))
(t/is (= false (fast-prime? 27 5))))
|
039bef78ed3208178da5ab7d4fcaa3ecf60bdc842f8dcd789c7465f13989b3ad | matterandvoid-space/subscriptions | fulcro.clj | (ns space.matterandvoid.subscriptions.fulcro
(:require
[com.fulcrologic.fulcro.algorithm :as-alias fulcro.algo]
[com.fulcrologic.fulcro.algorithms.indexing :as fulcro.index]
[com.fulcrologic.fulcro.application :as fulcro.app]
[com.fulcrologic.fulcro.components :as c]
[com.fulcrologic.fulcro.rendering.ident-optimized-render :as ident-optimized-render]
[space.matterandvoid.subscriptions :as-alias subs-keys]
[space.matterandvoid.subscriptions.impl.fulcro :as impl]
[space.matterandvoid.subscriptions.impl.reagent-ratom :as ratom]
[taoensso.timbre :as log]))
( defn get - fulcro - component - query - keys
; []
; (let [query-nodes (some-> class (rc/get-query) (eql/query->ast) :children)
; query-nodes-by-key (into {}
; (map (fn [n] [(:dispatch-key n) n]))
; query-nodes)
; {props :prop joins :join} (group-by :type query-nodes)
; join-keys (->> joins (map :dispatch-key) set)
; prop-keys (->> props (map :dispatch-key) set)]
; {:join join-keys :leaf prop-keys}))
;; copied query handling from fulcro.form-state.derive-form-info
( defn component->subscriptions
; "todo
; The idea here is to register subscriptions for the given component based on its query to reduce boilerplate.
; This can be a normal function because reg-sub operates at runtime"
; [com])
(def query-key ::subs-keys/query)
(defn set-memoize-fn! [f] (impl/set-memoize-fn! f))
(defn set-args-merge-fn! [f] (impl/set-args-merge-fn! f))
(defn reg-sub
"A call to `reg-sub` associates a `query-id` with two functions ->
a function returning input signals and a function (the signals function)
taking the input-signals current value(s) as input and returning a value (the computation function).
The two functions provide 'a mechanism' for creating a node
in the Signal Graph. When a node of type `query-id` is needed,
the two functions can be used to create it.
The three arguments are:
- `query-id` - typically a namespaced keyword (later used in subscribe)
- optionally, an `input signals` function which returns the input data
flows required by this kind of node.
- a `computation function` which computes the value (output) of the
node (from the input data flows)
It registers 'a mechanism' (the two functions) by which nodes
can be created later, when a node is bought into existence by the
use of `subscribe` in a `View Function`reg-sub.
The `computation function` is expected to take two arguments:
- `input-values` - the values which flow into this node (how is it wired into the graph?)
- `query-vector` - the vector given to `subscribe`
and it returns a computed value (which then becomes the output of the node)
When `computation function` is called, the 2nd `query-vector` argument will be that
vector supplied to the `subscribe`. So, if the call was `(subscribe [:sub-id 3 :blue])`,
then the `query-vector` supplied to the computaton function will be `[:sub-id 3 :blue]`.
The argument(s) supplied to `reg-sub` between `query-id` and the `computation-function`
can vary in 3 ways, but whatever is there defines the `input signals` part
of `the mechanism`, specifying what input values \"flow into\" the
`computation function` (as the 1st argument) when it is called."
[query-id & args]
(apply impl/reg-sub query-id args))
(defn subscribe
"Given a `query` vector, returns a Reagent `reaction` which will, over
time, reactively deliver a stream of values. Also known as a `Signal`.
To obtain the current value from the Signal, it must be dereferenced"
[?app query] (impl/subscribe ?app query))
(defn <sub
"Subscribe and deref a subscription, returning its value, not a reaction."
[?app query]
(impl/<sub ?app query))
(defn clear-sub
"Unregisters subscription handlers (presumably registered previously via the use of `reg-sub`).
When called with no args, it will unregister all currently registered subscription handlers.
When given one arg, assumed to be the `id` of a previously registered
subscription handler, it will unregister the associated handler. Will produce a warning to
console if it finds no matching registration.
NOTE: Depending on the usecase, it may be necessary to call `clear-subscription-cache!` afterwards"
{:api-docs/heading "Subscriptions"}
([registry] (impl/clear-handlers registry))
([registry query-id] (impl/clear-handlers registry query-id)))
(defn reg-sub-raw
"This is a low level, advanced function. You should probably be
using `reg-sub` instead.
Some explanation is available in the docs at
<a href=\"-frame/flow-mechanics/\" target=\"_blank\">-frame/flow-mechanics/</a>"
{:api-docs/heading "Subscriptions"}
[query-id handler-fn] (impl/reg-sub-raw query-id handler-fn))
(defn clear-subscription-cache!
"Removes all subscriptions from the cache.
This function can be used at development time or test time. Useful when hot reloading
namespaces containing subscription handlers. Also call it after a React/render exception,
because React components won't have been cleaned up properly. And this, in turn, means
the subscriptions within those components won't have been cleaned up correctly. So this
forces the issue."
[registry] (impl/clear-subscription-cache! registry))
(defn clear-handlers
([app] (impl/clear-handlers app))
([app id] (impl/clear-handlers app id)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reactive refresh of components
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn cleanup! "Intended to be called when a component unmounts to clear the registered Reaction."
[this] (impl/cleanup! this))
(defn setup-reaction!
"Installs a Reaction on the provided component which will re-render the component when any of the subscriptions'
values change.
Takes a component instance and a render function with signature: (fn render [this])"
[this client-render] (impl/setup-reaction! this client-render))
(defn with-reactive-subscriptions
"Takes a fulcro app and adds support for using subscriptions
The components which deref subscriptions in their render bodies will be refreshed when those subscriptions change,
separate from the fulcro rendering mechanism.
- Adds render middleware to run-in-reaction for class components
- Adds cleanup when a component is unmounted
- Changes the state atom to be a reagent.ratom/atom
- Changes the `optimized-render! algorithm to be the ident-optmized-render algorithm."
[app]
(-> app
(assoc ::fulcro.app/state-atom (ratom/atom @(::fulcro.app/state-atom app)))
(update ::fulcro.app/algorithms
assoc
::fulcro.algo/optimized-render! ident-optimized-render/render!
::fulcro.algo/render-middleware
(fn [this render-fn]
(let [final-render-fn
(if-let [middleware (::fulcro.algo/render-middleware app)]
(fn [] (middleware this render-fn))
render-fn)]
(if-let [reaction (impl/get-component-reaction this)]
(._run reaction false)
(setup-reaction! this final-render-fn))))
::fulcro.algo/drop-component!
(fn drop-component-middleware
([this]
(log/info "Drop component!" (c/component-name this))
(cleanup! this)
(fulcro.index/drop-component! this))
([this ident]
(log/info "Drop component!" (c/component-name this))
(cleanup! this)
(fulcro.index/drop-component! this ident))))))
(defn with-subscriptions
"Takes a fulcro app and adds support for using subscriptions
- Adds render middleware to run-in-reaction for class components
- Adds cleanup when a component is unmounted
- Changes the state atom to be a reagent.ratom/atom
- Changes the `optimized-render! algorithm to be the ident-optmized-render algorithm."
[app]
(-> app
(assoc ::fulcro.app/state-atom (ratom/atom @(::fulcro.app/state-atom app)))
(update ::fulcro.app/algorithms
assoc
::fulcro.algo/optimized-render! ident-optimized-render/render!
::fulcro.algo/before-render (fn [app root-class]
(log/info "in before-render")
(impl/subs-cache->fulcro-app-state app))
::fulcro.algo/render-middleware
(fn [this render-fn]
(log/info "in render middleware")
(let [final-render-fn
(if-let [middleware (::fulcro.algo/render-middleware app)]
(fn [] (middleware this render-fn))
render-fn)]
(log/info "in render middleware")
(if-let [reaction (impl/get-component-reaction this)]
(._run reaction false)
(setup-reaction! this final-render-fn))))
::fulcro.algo/drop-component!
(fn drop-component-middleware
([this]
(log/info "Drop component!" (c/component-name this))
(cleanup! this)
(fulcro.index/drop-component! this))
([this ident]
(log/info "Drop component!" (c/component-name this))
(cleanup! this)
(fulcro.index/drop-component! this ident))))))
(defn with-headless-fulcro
"Takes a fulcro app, disables all UI rendering and replaces the state atom with a Reagent RAtom."
[app]
(assoc app :render-root! identity
:optimized-render! identity
:hydrate-root! identity
::fulcro.app/state-atom (ratom/atom @(::fulcro.app/state-atom app))))
(defmacro defregsub
"Has the same function signature as `reg-sub`.
Registers a subscription and creates a function which is invokes subscribe and deref on the registered subscription
with the args map passed in."
[sub-name & args]
(let [sub-kw (keyword (str *ns*) (str sub-name))]
`(do
(reg-sub ~sub-kw ~@args)
(defn ~sub-name
([app#] (deref (subscribe app# [~sub-kw])))
([app# args#] (deref (subscribe app# [~sub-kw args#])))))))
(defn make-sub-fn [query-id sub-args]
(impl/make-sub-fn ::subscription query-id sub-args))
(defmacro defsub
"Has the same function signature as `reg-sub` without a keyword name argument.
Returns a subscription function and creates a function which invokes subscribe and deref on the registered subscription
with the args map passed in."
[fn-name & args]
`(def ~fn-name (make-sub-fn ~(keyword (str *ns*) (str fn-name)) ~(vec args))))
(defmacro defsubraw
"Creates a subscription function that takes the datasource ratom and optionally an args map and returns a Reaction."
[sub-name args & body]
`(impl/defsubraw ::subscription ~sub-name ~args ~body))
(defmacro deflayer2-sub
"Takes a symbol for a subscription name and a way to derive a path in your fulcro app db. Returns a function subscription
which itself returns a Reagent RCursor.
Supports a vector path, a single keyword, or a function which takes the RAtom datasource and the arguments map passed to subscribe and
must return a path vector to use as an RCursor path.
Examples:
(deflayer2-sub my-subscription :a-path-in-your-db)
(deflayer2-sub my-subscription [:a-path-in-your-db])
(deflayer2-sub my-subscription (fn [db-atom sub-args-map] [:a-key (:some-val sub-args-map])))
"
[sub-name ?path] `(impl/deflayer2-sub ::subscription ~sub-name ~?path))
(defn sub-fn
"Takes a function that returns either a Reaction or RCursor. Returns a function that when invoked delegates to `f` and
derefs its output. The returned function can be used in subscriptions."
[f]
(impl/sub-fn ::subscription f))
(defn with-name
[f sub-name]
(vary-meta f assoc ::sub-name sub-name))
| null | https://raw.githubusercontent.com/matterandvoid-space/subscriptions/686912827bae018a594088bc712d454b78fcdb2e/src/main/space/matterandvoid/subscriptions/fulcro.clj | clojure | []
(let [query-nodes (some-> class (rc/get-query) (eql/query->ast) :children)
query-nodes-by-key (into {}
(map (fn [n] [(:dispatch-key n) n]))
query-nodes)
{props :prop joins :join} (group-by :type query-nodes)
join-keys (->> joins (map :dispatch-key) set)
prop-keys (->> props (map :dispatch-key) set)]
{:join join-keys :leaf prop-keys}))
copied query handling from fulcro.form-state.derive-form-info
"todo
The idea here is to register subscriptions for the given component based on its query to reduce boilerplate.
This can be a normal function because reg-sub operates at runtime"
[com])
reactive refresh of components
| (ns space.matterandvoid.subscriptions.fulcro
(:require
[com.fulcrologic.fulcro.algorithm :as-alias fulcro.algo]
[com.fulcrologic.fulcro.algorithms.indexing :as fulcro.index]
[com.fulcrologic.fulcro.application :as fulcro.app]
[com.fulcrologic.fulcro.components :as c]
[com.fulcrologic.fulcro.rendering.ident-optimized-render :as ident-optimized-render]
[space.matterandvoid.subscriptions :as-alias subs-keys]
[space.matterandvoid.subscriptions.impl.fulcro :as impl]
[space.matterandvoid.subscriptions.impl.reagent-ratom :as ratom]
[taoensso.timbre :as log]))
( defn get - fulcro - component - query - keys
( defn component->subscriptions
(def query-key ::subs-keys/query)
(defn set-memoize-fn! [f] (impl/set-memoize-fn! f))
(defn set-args-merge-fn! [f] (impl/set-args-merge-fn! f))
(defn reg-sub
"A call to `reg-sub` associates a `query-id` with two functions ->
a function returning input signals and a function (the signals function)
taking the input-signals current value(s) as input and returning a value (the computation function).
The two functions provide 'a mechanism' for creating a node
in the Signal Graph. When a node of type `query-id` is needed,
the two functions can be used to create it.
The three arguments are:
- `query-id` - typically a namespaced keyword (later used in subscribe)
- optionally, an `input signals` function which returns the input data
flows required by this kind of node.
- a `computation function` which computes the value (output) of the
node (from the input data flows)
It registers 'a mechanism' (the two functions) by which nodes
can be created later, when a node is bought into existence by the
use of `subscribe` in a `View Function`reg-sub.
The `computation function` is expected to take two arguments:
- `input-values` - the values which flow into this node (how is it wired into the graph?)
- `query-vector` - the vector given to `subscribe`
and it returns a computed value (which then becomes the output of the node)
When `computation function` is called, the 2nd `query-vector` argument will be that
vector supplied to the `subscribe`. So, if the call was `(subscribe [:sub-id 3 :blue])`,
then the `query-vector` supplied to the computaton function will be `[:sub-id 3 :blue]`.
The argument(s) supplied to `reg-sub` between `query-id` and the `computation-function`
can vary in 3 ways, but whatever is there defines the `input signals` part
of `the mechanism`, specifying what input values \"flow into\" the
`computation function` (as the 1st argument) when it is called."
[query-id & args]
(apply impl/reg-sub query-id args))
(defn subscribe
"Given a `query` vector, returns a Reagent `reaction` which will, over
time, reactively deliver a stream of values. Also known as a `Signal`.
To obtain the current value from the Signal, it must be dereferenced"
[?app query] (impl/subscribe ?app query))
(defn <sub
"Subscribe and deref a subscription, returning its value, not a reaction."
[?app query]
(impl/<sub ?app query))
(defn clear-sub
"Unregisters subscription handlers (presumably registered previously via the use of `reg-sub`).
When called with no args, it will unregister all currently registered subscription handlers.
When given one arg, assumed to be the `id` of a previously registered
subscription handler, it will unregister the associated handler. Will produce a warning to
console if it finds no matching registration.
NOTE: Depending on the usecase, it may be necessary to call `clear-subscription-cache!` afterwards"
{:api-docs/heading "Subscriptions"}
([registry] (impl/clear-handlers registry))
([registry query-id] (impl/clear-handlers registry query-id)))
(defn reg-sub-raw
"This is a low level, advanced function. You should probably be
using `reg-sub` instead.
Some explanation is available in the docs at
<a href=\"-frame/flow-mechanics/\" target=\"_blank\">-frame/flow-mechanics/</a>"
{:api-docs/heading "Subscriptions"}
[query-id handler-fn] (impl/reg-sub-raw query-id handler-fn))
(defn clear-subscription-cache!
"Removes all subscriptions from the cache.
This function can be used at development time or test time. Useful when hot reloading
namespaces containing subscription handlers. Also call it after a React/render exception,
because React components won't have been cleaned up properly. And this, in turn, means
the subscriptions within those components won't have been cleaned up correctly. So this
forces the issue."
[registry] (impl/clear-subscription-cache! registry))
(defn clear-handlers
([app] (impl/clear-handlers app))
([app id] (impl/clear-handlers app id)))
(defn cleanup! "Intended to be called when a component unmounts to clear the registered Reaction."
[this] (impl/cleanup! this))
(defn setup-reaction!
"Installs a Reaction on the provided component which will re-render the component when any of the subscriptions'
values change.
Takes a component instance and a render function with signature: (fn render [this])"
[this client-render] (impl/setup-reaction! this client-render))
(defn with-reactive-subscriptions
"Takes a fulcro app and adds support for using subscriptions
The components which deref subscriptions in their render bodies will be refreshed when those subscriptions change,
separate from the fulcro rendering mechanism.
- Adds render middleware to run-in-reaction for class components
- Adds cleanup when a component is unmounted
- Changes the state atom to be a reagent.ratom/atom
- Changes the `optimized-render! algorithm to be the ident-optmized-render algorithm."
[app]
(-> app
(assoc ::fulcro.app/state-atom (ratom/atom @(::fulcro.app/state-atom app)))
(update ::fulcro.app/algorithms
assoc
::fulcro.algo/optimized-render! ident-optimized-render/render!
::fulcro.algo/render-middleware
(fn [this render-fn]
(let [final-render-fn
(if-let [middleware (::fulcro.algo/render-middleware app)]
(fn [] (middleware this render-fn))
render-fn)]
(if-let [reaction (impl/get-component-reaction this)]
(._run reaction false)
(setup-reaction! this final-render-fn))))
::fulcro.algo/drop-component!
(fn drop-component-middleware
([this]
(log/info "Drop component!" (c/component-name this))
(cleanup! this)
(fulcro.index/drop-component! this))
([this ident]
(log/info "Drop component!" (c/component-name this))
(cleanup! this)
(fulcro.index/drop-component! this ident))))))
(defn with-subscriptions
"Takes a fulcro app and adds support for using subscriptions
- Adds render middleware to run-in-reaction for class components
- Adds cleanup when a component is unmounted
- Changes the state atom to be a reagent.ratom/atom
- Changes the `optimized-render! algorithm to be the ident-optmized-render algorithm."
[app]
(-> app
(assoc ::fulcro.app/state-atom (ratom/atom @(::fulcro.app/state-atom app)))
(update ::fulcro.app/algorithms
assoc
::fulcro.algo/optimized-render! ident-optimized-render/render!
::fulcro.algo/before-render (fn [app root-class]
(log/info "in before-render")
(impl/subs-cache->fulcro-app-state app))
::fulcro.algo/render-middleware
(fn [this render-fn]
(log/info "in render middleware")
(let [final-render-fn
(if-let [middleware (::fulcro.algo/render-middleware app)]
(fn [] (middleware this render-fn))
render-fn)]
(log/info "in render middleware")
(if-let [reaction (impl/get-component-reaction this)]
(._run reaction false)
(setup-reaction! this final-render-fn))))
::fulcro.algo/drop-component!
(fn drop-component-middleware
([this]
(log/info "Drop component!" (c/component-name this))
(cleanup! this)
(fulcro.index/drop-component! this))
([this ident]
(log/info "Drop component!" (c/component-name this))
(cleanup! this)
(fulcro.index/drop-component! this ident))))))
(defn with-headless-fulcro
"Takes a fulcro app, disables all UI rendering and replaces the state atom with a Reagent RAtom."
[app]
(assoc app :render-root! identity
:optimized-render! identity
:hydrate-root! identity
::fulcro.app/state-atom (ratom/atom @(::fulcro.app/state-atom app))))
(defmacro defregsub
"Has the same function signature as `reg-sub`.
Registers a subscription and creates a function which is invokes subscribe and deref on the registered subscription
with the args map passed in."
[sub-name & args]
(let [sub-kw (keyword (str *ns*) (str sub-name))]
`(do
(reg-sub ~sub-kw ~@args)
(defn ~sub-name
([app#] (deref (subscribe app# [~sub-kw])))
([app# args#] (deref (subscribe app# [~sub-kw args#])))))))
(defn make-sub-fn [query-id sub-args]
(impl/make-sub-fn ::subscription query-id sub-args))
(defmacro defsub
"Has the same function signature as `reg-sub` without a keyword name argument.
Returns a subscription function and creates a function which invokes subscribe and deref on the registered subscription
with the args map passed in."
[fn-name & args]
`(def ~fn-name (make-sub-fn ~(keyword (str *ns*) (str fn-name)) ~(vec args))))
(defmacro defsubraw
"Creates a subscription function that takes the datasource ratom and optionally an args map and returns a Reaction."
[sub-name args & body]
`(impl/defsubraw ::subscription ~sub-name ~args ~body))
(defmacro deflayer2-sub
"Takes a symbol for a subscription name and a way to derive a path in your fulcro app db. Returns a function subscription
which itself returns a Reagent RCursor.
Supports a vector path, a single keyword, or a function which takes the RAtom datasource and the arguments map passed to subscribe and
must return a path vector to use as an RCursor path.
Examples:
(deflayer2-sub my-subscription :a-path-in-your-db)
(deflayer2-sub my-subscription [:a-path-in-your-db])
(deflayer2-sub my-subscription (fn [db-atom sub-args-map] [:a-key (:some-val sub-args-map])))
"
[sub-name ?path] `(impl/deflayer2-sub ::subscription ~sub-name ~?path))
(defn sub-fn
"Takes a function that returns either a Reaction or RCursor. Returns a function that when invoked delegates to `f` and
derefs its output. The returned function can be used in subscriptions."
[f]
(impl/sub-fn ::subscription f))
(defn with-name
[f sub-name]
(vary-meta f assoc ::sub-name sub-name))
|
b9eae91f1051ca85c0aae313c6d8f2930e26f6c7f220d26aa39b17377500b6a1 | sheaf/acts | Act.hs | # LANGUAGE
CPP
, DeriveGeneric
, DeriveDataTypeable
, DerivingVia
, FlexibleInstances
, , MultiParamTypeClasses
, ScopedTypeVariables
, StandaloneDeriving
, TypeFamilies
, UndecidableInstances
#
CPP
, DeriveGeneric
, DeriveDataTypeable
, DerivingVia
, FlexibleInstances
, GeneralizedNewtypeDeriving
, MultiParamTypeClasses
, ScopedTypeVariables
, StandaloneDeriving
, TypeFamilies
, UndecidableInstances
#-}
|
Module : Data . Act
An " Act " of a semigroup \ ( S \ ) on a type \ ( X \ ) gives a way to transform terms of type \ ( X \ ) by terms of type \ ( S \ ) ,
in a way that is compatible with the semigroup operation on \ ( S \ ) .
In the special case that there is a unique way of going from one term of type \ ( X \ ) to another
through a transformation by a term of type \ ( S \ ) , we say that \ ( X \ ) is a torsor under \ ( S \ ) .
For example , the plane has an action by translations . Given any two points , there is a unique translation
that takes the first point to the second . Note that an unmarked plane ( like a blank piece of paper )
has no designated origin or reference point , whereas the set of translations is a plane with a given origin
( the zero translation ) . This is the distinction between an affine space ( an unmarked plane ) and a vector space .
Enforcing this distinction in the types can help to avoid confusing absolute points with translation vectors .
Simple ' Act ' and ' ' instances can be derived through self - actions :
> > newtype Seconds = Seconds { getSeconds : : Double }
> > deriving ( Act TimeDelta , )
> > via TimeDelta
> > newtype TimeDelta = TimeDelta { timeDeltaInSeconds : : Seconds }
> > deriving ( Semigroup , Monoid , Group )
> > via Sum Double
Module: Data.Act
An "Act" of a semigroup \( S \) on a type \( X \) gives a way to transform terms of type \( X \) by terms of type \( S \),
in a way that is compatible with the semigroup operation on \( S \).
In the special case that there is a unique way of going from one term of type \( X \) to another
through a transformation by a term of type \( S \), we say that \( X \) is a torsor under \( S \).
For example, the plane has an action by translations. Given any two points, there is a unique translation
that takes the first point to the second. Note that an unmarked plane (like a blank piece of paper)
has no designated origin or reference point, whereas the set of translations is a plane with a given origin
(the zero translation). This is the distinction between an affine space (an unmarked plane) and a vector space.
Enforcing this distinction in the types can help to avoid confusing absolute points with translation vectors.
Simple 'Act' and 'Torsor' instances can be derived through self-actions:
> > newtype Seconds = Seconds { getSeconds :: Double }
> > deriving ( Act TimeDelta, Torsor TimeDelta )
> > via TimeDelta
> > newtype TimeDelta = TimeDelta { timeDeltaInSeconds :: Seconds }
> > deriving ( Semigroup, Monoid, Group )
> > via Sum Double
-}
module Data.Act
( Act(..)
, transportAction
, Trivial(..)
, Torsor(..)
, anti
, intertwiner
, Finitely(..)
)
where
-- base
import Data.Coerce
( coerce )
import Data.Data
( Data )
import Data.Functor.Const
( Const(..) )
import Data.Functor.Contravariant
( Op(..) )
import Data.Monoid
( Any(..), All(..)
, Sum(..), Product(..)
, Ap(..), Endo(..)
)
import Data.Semigroup
( Dual(..) )
import GHC.Generics
( Generic, Generic1 )
deepseq
import Control.DeepSeq
( NFData )
#ifdef FIN
-- finitary
import Data.Finitary
( Finitary(..) )
-- finite-typelits
import Data.Finite
( Finite )
#endif
-- groups
import Data.Group
( Group(..) )
-----------------------------------------------------------------
-- | A left __act__ (or left __semigroup action__) of a semigroup @s@ on @x@ consists of an operation
--
@(• ) : : s - > x - >
--
-- such that:
--
@a • ( b • x ) = ( a < > b ) •
--
-- In case @s@ is also a 'Monoid', we additionally require:
--
@mempty • x =
--
-- The synonym @ act = (•) @ is also provided.
class Semigroup s => Act s x where
{-# MINIMAL (•) | act #-}
-- | Left action of a semigroup.
(•), act :: s -> x -> x
(•) = act
act = (•)
infixr 5 •
infixr 5 `act`
-- | Transport an act:
--
-- <<img/transport.svg>>
transportAction :: ( a -> b ) -> ( b -> a ) -> ( g -> b -> b ) -> ( g -> a -> a )
transportAction to from actBy g = from . actBy g . to
-- | Natural left action of a semigroup on itself.
instance Semigroup s => Act s s where
(•) = (<>)
-- | Trivial act of a semigroup on any type (acting by the identity).
newtype Trivial a = Trivial { getTrivial :: a }
deriving stock ( Show, Read, Data, Generic, Generic1 )
deriving newtype ( Eq, Ord, Enum, Bounded, NFData )
instance Semigroup s => Act s ( Trivial a ) where
act _ = id
deriving via Any instance Act Any Bool
deriving via All instance Act All Bool
instance Num a => Act ( Sum a ) a where
act s = coerce ( act s :: Sum a -> Sum a )
instance Num a => Act ( Product a ) a where
act s = coerce ( act s :: Product a -> Product a )
instance {-# OVERLAPPING #-} Act () x where
act _ = id
instance ( Act s1 x1, Act s2 x2 )
=> Act ( s1, s2 ) ( x1,x2 ) where
act ( s1, s2 ) ( x1, x2 ) =
( act s1 x1, act s2 x2 )
instance ( Act s1 x1, Act s2 x2, Act s3 x3 )
=> Act ( s1, s2, s3 ) ( x1, x2, x3 ) where
act ( s1, s2, s3 ) ( x1, x2, x3 ) =
( act s1 x1, act s2 x2, act s3 x3 )
instance ( Act s1 x1, Act s2 x2, Act s3 x3, Act s4 x4 )
=> Act ( s1, s2, s3, s4 ) ( x1, x2, x3, x4 ) where
act ( s1, s2, s3, s4 ) ( x1, x2, x3, x4 ) =
( act s1 x1, act s2 x2, act s3 x3, act s4 x4 )
instance ( Act s1 x1, Act s2 x2, Act s3 x3, Act s4 x4, Act s5 x5 )
=> Act ( s1, s2, s3, s4, s5 ) ( x1, x2, x3, x4, x5 ) where
act ( s1, s2, s3, s4, s5 ) ( x1, x2, x3, x4, x5 ) =
( act s1 x1, act s2 x2, act s3 x3, act s4 x4, act s5 x5 )
deriving newtype instance Act s a => Act s ( Const a b )
| Acting through a functor using
instance ( Act s x, Functor f ) => Act s ( Ap f x ) where
act s = coerce ( fmap ( act s ) :: f x -> f x )
-- | Acting through the contravariant function arrow functor: right action.
--
-- If acting by a group, use `anti :: Group g => g -> Dual g` to act by the original group
-- instead of the opposite group.
instance ( Semigroup s, Act s a ) => Act ( Dual s ) ( Op b a ) where
act ( Dual s ) = coerce ( ( . act s ) :: ( a -> b ) -> ( a -> b ) )
-- | Acting through a function arrow: both covariant and contravariant actions.
--
-- If acting by a group, use `anti :: Group g => g -> Dual g` to act by the original group
-- instead of the opposite group.
instance ( Semigroup s, Act s a, Act t b ) => Act ( Dual s, t ) ( a -> b ) where
act ( Dual s, t ) p = act t . p . act s
-- | Action of a group on endomorphisms.
instance ( Group g, Act g a ) => Act g ( Endo a ) where
act g = coerce ( act ( anti g, g ) :: ( a -> a ) -> ( a -> a ) )
| Newtype for the action on a type through its ' Finitary ' instance .
--
> data ABCD = A | B | C | D
-- > deriving stock ( Eq, Generic )
> deriving anyclass Finitary
> deriving ( Act ( Sum ( Finite 4 ) ) , ( Sum ( Finite 4 ) ) )
-- > via Finitely ABCD
--
-- Sizes are checked statically. For instance if we had instead written:
--
> deriving ( Act ( Sum ( Finite 3 ) ) , ( Sum ( Finite 3 ) ) )
-- > via Finitely ABCD
--
-- we would have gotten the error messages:
--
> * No instance for ( Act ( Sum ( Finite 3 ) ) ( Finite 4 ) )
> * No instance for ( Torsor ( Sum ( Finite 3 ) ) ( Finite 4 ) )
--
newtype Finitely a = Finitely { getFinitely :: a }
deriving stock ( Show, Read, Data, Generic, Generic1 )
deriving newtype ( Eq, Ord, NFData )
#ifdef FIN
| Act on a type through its ' Finitary ' instance .
instance ( Semigroup s, Act s ( Finite n ), Finitary a, n ~ Cardinality a )
=> Act s ( Finitely a ) where
act s = Finitely . fromFinite . act s . toFinite . getFinitely
| Torsor for a type using its ' Finitary ' instance .
instance ( Group g, Torsor g ( Finite n ), Finitary a, n ~ Cardinality a )
=> Torsor g ( Finitely a ) where
> Finitely y = x -- > y
#endif
-----------------------------------------------------------------
| A left _ _ torsor _ _ consists of a /free/ and /transitive/ left action of a group on an inhabited type .
--
This precisely means that for any two terms @x@ , @y@ , there exists a /unique/ group element @g@ taking @x@ to @y@ ,
-- which is denoted @ y <-- x @ (or @ x --> y @, but the left-pointing arrow is more natural when working with left actions).
--
-- That is @ y <-- x @ is the /unique/ element satisfying:
--
-- @( y <-- x ) • x = y@
--
--
-- Note the order of composition of @<--@ and @-->@ with respect to @<>@:
--
-- > ( z <-- y ) <> ( y <-- x ) = z <-- x
--
-- > ( y --> z ) <> ( x --> y ) = x --> z
class ( Group g, Act g x ) => Torsor g x where
{-# MINIMAL (-->) | (<--) #-}
-- | Unique group element effecting the given transition
(<--), (-->) :: x -> x -> g
(-->) = flip (<--)
(<--) = flip (-->)
infix 7 -->
infix 7 <--
-- | A group's inversion anti-automorphism corresponds to an isomorphism to the opposite group.
--
-- The inversion allows us to obtain a left action from a right action (of the same group);
-- the equivalent operation is not possible for general semigroups.
anti :: Group g => g -> Dual g
anti g = Dual ( invert g )
-- | Any group is a torsor under its own natural left action.
instance Group g => Torsor g g where
h <-- g = h <> invert g
instance Num a => Torsor ( Sum a ) a where
(<--) = coerce ( (<--) :: Sum a -> Sum a -> Sum a )
-- | Given
--
-- * \( g \in G \) acting on \( A \),
-- * \( B \) a torsor under \( H \),
-- * a map \( p \colon A \to B \),
--
-- this function returns the unique element \( h \in H \) making the following diagram commute:
--
-- <<img/intertwiner.svg>>
intertwiner :: forall h g a b. ( Act g a, Torsor h b ) => g -> ( a -> b ) -> a -> h
intertwiner g p a = p a --> p ( g • a )
| null | https://raw.githubusercontent.com/sheaf/acts/ad365362867781973a962294a985ec95240198a2/src/Data/Act.hs | haskell | base
finitary
finite-typelits
groups
---------------------------------------------------------------
| A left __act__ (or left __semigroup action__) of a semigroup @s@ on @x@ consists of an operation
such that:
In case @s@ is also a 'Monoid', we additionally require:
The synonym @ act = (•) @ is also provided.
# MINIMAL (•) | act #
| Left action of a semigroup.
| Transport an act:
<<img/transport.svg>>
| Natural left action of a semigroup on itself.
| Trivial act of a semigroup on any type (acting by the identity).
# OVERLAPPING #
| Acting through the contravariant function arrow functor: right action.
If acting by a group, use `anti :: Group g => g -> Dual g` to act by the original group
instead of the opposite group.
| Acting through a function arrow: both covariant and contravariant actions.
If acting by a group, use `anti :: Group g => g -> Dual g` to act by the original group
instead of the opposite group.
| Action of a group on endomorphisms.
> deriving stock ( Eq, Generic )
> via Finitely ABCD
Sizes are checked statically. For instance if we had instead written:
> via Finitely ABCD
we would have gotten the error messages:
> y
---------------------------------------------------------------
which is denoted @ y <-- x @ (or @ x --> y @, but the left-pointing arrow is more natural when working with left actions).
That is @ y <-- x @ is the /unique/ element satisfying:
@( y <-- x ) • x = y@
Note the order of composition of @<--@ and @-->@ with respect to @<>@:
> ( z <-- y ) <> ( y <-- x ) = z <-- x
> ( y --> z ) <> ( x --> y ) = x --> z
# MINIMAL (-->) | (<--) #
| Unique group element effecting the given transition
), (-->) :: x -> x -> g
>) = flip (<--)
) = flip (-->)
>
| A group's inversion anti-automorphism corresponds to an isomorphism to the opposite group.
The inversion allows us to obtain a left action from a right action (of the same group);
the equivalent operation is not possible for general semigroups.
| Any group is a torsor under its own natural left action.
g = h <> invert g
) = coerce ( (<--) :: Sum a -> Sum a -> Sum a )
| Given
* \( g \in G \) acting on \( A \),
* \( B \) a torsor under \( H \),
* a map \( p \colon A \to B \),
this function returns the unique element \( h \in H \) making the following diagram commute:
<<img/intertwiner.svg>>
> p ( g • a ) | # LANGUAGE
CPP
, DeriveGeneric
, DeriveDataTypeable
, DerivingVia
, FlexibleInstances
, , MultiParamTypeClasses
, ScopedTypeVariables
, StandaloneDeriving
, TypeFamilies
, UndecidableInstances
#
CPP
, DeriveGeneric
, DeriveDataTypeable
, DerivingVia
, FlexibleInstances
, GeneralizedNewtypeDeriving
, MultiParamTypeClasses
, ScopedTypeVariables
, StandaloneDeriving
, TypeFamilies
, UndecidableInstances
#-}
|
Module : Data . Act
An " Act " of a semigroup \ ( S \ ) on a type \ ( X \ ) gives a way to transform terms of type \ ( X \ ) by terms of type \ ( S \ ) ,
in a way that is compatible with the semigroup operation on \ ( S \ ) .
In the special case that there is a unique way of going from one term of type \ ( X \ ) to another
through a transformation by a term of type \ ( S \ ) , we say that \ ( X \ ) is a torsor under \ ( S \ ) .
For example , the plane has an action by translations . Given any two points , there is a unique translation
that takes the first point to the second . Note that an unmarked plane ( like a blank piece of paper )
has no designated origin or reference point , whereas the set of translations is a plane with a given origin
( the zero translation ) . This is the distinction between an affine space ( an unmarked plane ) and a vector space .
Enforcing this distinction in the types can help to avoid confusing absolute points with translation vectors .
Simple ' Act ' and ' ' instances can be derived through self - actions :
> > newtype Seconds = Seconds { getSeconds : : Double }
> > deriving ( Act TimeDelta , )
> > via TimeDelta
> > newtype TimeDelta = TimeDelta { timeDeltaInSeconds : : Seconds }
> > deriving ( Semigroup , Monoid , Group )
> > via Sum Double
Module: Data.Act
An "Act" of a semigroup \( S \) on a type \( X \) gives a way to transform terms of type \( X \) by terms of type \( S \),
in a way that is compatible with the semigroup operation on \( S \).
In the special case that there is a unique way of going from one term of type \( X \) to another
through a transformation by a term of type \( S \), we say that \( X \) is a torsor under \( S \).
For example, the plane has an action by translations. Given any two points, there is a unique translation
that takes the first point to the second. Note that an unmarked plane (like a blank piece of paper)
has no designated origin or reference point, whereas the set of translations is a plane with a given origin
(the zero translation). This is the distinction between an affine space (an unmarked plane) and a vector space.
Enforcing this distinction in the types can help to avoid confusing absolute points with translation vectors.
Simple 'Act' and 'Torsor' instances can be derived through self-actions:
> > newtype Seconds = Seconds { getSeconds :: Double }
> > deriving ( Act TimeDelta, Torsor TimeDelta )
> > via TimeDelta
> > newtype TimeDelta = TimeDelta { timeDeltaInSeconds :: Seconds }
> > deriving ( Semigroup, Monoid, Group )
> > via Sum Double
-}
module Data.Act
( Act(..)
, transportAction
, Trivial(..)
, Torsor(..)
, anti
, intertwiner
, Finitely(..)
)
where
import Data.Coerce
( coerce )
import Data.Data
( Data )
import Data.Functor.Const
( Const(..) )
import Data.Functor.Contravariant
( Op(..) )
import Data.Monoid
( Any(..), All(..)
, Sum(..), Product(..)
, Ap(..), Endo(..)
)
import Data.Semigroup
( Dual(..) )
import GHC.Generics
( Generic, Generic1 )
deepseq
import Control.DeepSeq
( NFData )
#ifdef FIN
import Data.Finitary
( Finitary(..) )
import Data.Finite
( Finite )
#endif
import Data.Group
( Group(..) )
@(• ) : : s - > x - >
@a • ( b • x ) = ( a < > b ) •
@mempty • x =
class Semigroup s => Act s x where
(•), act :: s -> x -> x
(•) = act
act = (•)
infixr 5 •
infixr 5 `act`
transportAction :: ( a -> b ) -> ( b -> a ) -> ( g -> b -> b ) -> ( g -> a -> a )
transportAction to from actBy g = from . actBy g . to
instance Semigroup s => Act s s where
(•) = (<>)
newtype Trivial a = Trivial { getTrivial :: a }
deriving stock ( Show, Read, Data, Generic, Generic1 )
deriving newtype ( Eq, Ord, Enum, Bounded, NFData )
instance Semigroup s => Act s ( Trivial a ) where
act _ = id
deriving via Any instance Act Any Bool
deriving via All instance Act All Bool
instance Num a => Act ( Sum a ) a where
act s = coerce ( act s :: Sum a -> Sum a )
instance Num a => Act ( Product a ) a where
act s = coerce ( act s :: Product a -> Product a )
act _ = id
instance ( Act s1 x1, Act s2 x2 )
=> Act ( s1, s2 ) ( x1,x2 ) where
act ( s1, s2 ) ( x1, x2 ) =
( act s1 x1, act s2 x2 )
instance ( Act s1 x1, Act s2 x2, Act s3 x3 )
=> Act ( s1, s2, s3 ) ( x1, x2, x3 ) where
act ( s1, s2, s3 ) ( x1, x2, x3 ) =
( act s1 x1, act s2 x2, act s3 x3 )
instance ( Act s1 x1, Act s2 x2, Act s3 x3, Act s4 x4 )
=> Act ( s1, s2, s3, s4 ) ( x1, x2, x3, x4 ) where
act ( s1, s2, s3, s4 ) ( x1, x2, x3, x4 ) =
( act s1 x1, act s2 x2, act s3 x3, act s4 x4 )
instance ( Act s1 x1, Act s2 x2, Act s3 x3, Act s4 x4, Act s5 x5 )
=> Act ( s1, s2, s3, s4, s5 ) ( x1, x2, x3, x4, x5 ) where
act ( s1, s2, s3, s4, s5 ) ( x1, x2, x3, x4, x5 ) =
( act s1 x1, act s2 x2, act s3 x3, act s4 x4, act s5 x5 )
deriving newtype instance Act s a => Act s ( Const a b )
| Acting through a functor using
instance ( Act s x, Functor f ) => Act s ( Ap f x ) where
act s = coerce ( fmap ( act s ) :: f x -> f x )
instance ( Semigroup s, Act s a ) => Act ( Dual s ) ( Op b a ) where
act ( Dual s ) = coerce ( ( . act s ) :: ( a -> b ) -> ( a -> b ) )
instance ( Semigroup s, Act s a, Act t b ) => Act ( Dual s, t ) ( a -> b ) where
act ( Dual s, t ) p = act t . p . act s
instance ( Group g, Act g a ) => Act g ( Endo a ) where
act g = coerce ( act ( anti g, g ) :: ( a -> a ) -> ( a -> a ) )
| Newtype for the action on a type through its ' Finitary ' instance .
> data ABCD = A | B | C | D
> deriving anyclass Finitary
> deriving ( Act ( Sum ( Finite 4 ) ) , ( Sum ( Finite 4 ) ) )
> deriving ( Act ( Sum ( Finite 3 ) ) , ( Sum ( Finite 3 ) ) )
> * No instance for ( Act ( Sum ( Finite 3 ) ) ( Finite 4 ) )
> * No instance for ( Torsor ( Sum ( Finite 3 ) ) ( Finite 4 ) )
newtype Finitely a = Finitely { getFinitely :: a }
deriving stock ( Show, Read, Data, Generic, Generic1 )
deriving newtype ( Eq, Ord, NFData )
#ifdef FIN
| Act on a type through its ' Finitary ' instance .
instance ( Semigroup s, Act s ( Finite n ), Finitary a, n ~ Cardinality a )
=> Act s ( Finitely a ) where
act s = Finitely . fromFinite . act s . toFinite . getFinitely
| Torsor for a type using its ' Finitary ' instance .
instance ( Group g, Torsor g ( Finite n ), Finitary a, n ~ Cardinality a )
=> Torsor g ( Finitely a ) where
#endif
| A left _ _ torsor _ _ consists of a /free/ and /transitive/ left action of a group on an inhabited type .
This precisely means that for any two terms @x@ , @y@ , there exists a /unique/ group element @g@ taking @x@ to @y@ ,
class ( Group g, Act g x ) => Torsor g x where
anti :: Group g => g -> Dual g
anti g = Dual ( invert g )
instance Group g => Torsor g g where
instance Num a => Torsor ( Sum a ) a where
intertwiner :: forall h g a b. ( Act g a, Torsor h b ) => g -> ( a -> b ) -> a -> h
|
5f98312706a7e4206ca95bc35c9ac29649795e8b17044f356ba3e422c6a09da0 | apache/couchdb-rebar | xref_behavior.erl | -module(xref_behavior).
-behavior(gen_xref_behavior).
% behavior-defined callbacks don't require xref_ignore
-export([init/1, handle/1]).
init(_Args) -> ok.
handle(_Atom) -> next_event.
| null | https://raw.githubusercontent.com/apache/couchdb-rebar/8578221c20d0caa3deb724e5622a924045ffa8bf/inttest/xref_behavior/xref_behavior.erl | erlang | behavior-defined callbacks don't require xref_ignore | -module(xref_behavior).
-behavior(gen_xref_behavior).
-export([init/1, handle/1]).
init(_Args) -> ok.
handle(_Atom) -> next_event.
|
f3d486b3df6862f122dbf3e26cc1b1b8f5b44350cd711166a75427ad7fc33e3d | jadahl/mod_restful | mod_restful_mochijson2.erl | %%
%% This file contains parts of the json implementation from mochiweb. Copyright
%% information and license information follows.
%%
@author < >
2007 Mochi Media , Inc.
%%
%% 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.
%%
@doc Yet another JSON ( RFC 4627 ) library for Erlang . mochijson2 works
%% with binaries as strings, arrays as lists (without an {array, _})
wrapper and it only knows how to decode UTF-8 ( and ASCII ) .
%%
%% JSON terms are decoded as follows (javascript -> erlang):
%% <ul>
%% <li>{"key": "value"} ->
%% {struct, [{<<"key">>, <<"value">>}]}</li>
< li>["array " , 123 , 12.34 , true , false , null ] - >
[ & lt;<"array " > > , 123 , 12.34 , true , false , null ]
%% </li>
%% </ul>
%% <ul>
%% <li>Strings in JSON decode to UTF-8 binaries in Erlang</li>
%% <li>Objects decode to {struct, PropList}</li>
%% <li>Numbers decode to integer or float</li>
%% <li>true, false, null decode to their respective terms.</li>
%% </ul>
%% The encoder will accept the same format that the decoder will produce,
%% but will also allow additional cases for leniency:
%% <ul>
< li > atoms other than true , false , null will be considered UTF-8
%% strings (even as a proplist key)
%% </li>
< li>{json , } will insert IoList directly into the output
%% with no validation
%% </li>
%% <li>{array, Array} will be encoded as Array
%% (legacy mochijson style)
%% </li>
< li > A non - empty raw proplist will be encoded as an object as long
as the first pair does not have an atom key of json , struct ,
%% or array
%% </li>
%% </ul>
-module(mod_restful_mochijson2).
-author('').
-export([encoder/1, encode/1]).
-export([decoder/1, decode/1]).
% This is a macro to placate syntax highlighters..
-define(Q, $\").
-define(ADV_COL(S, N), S#decoder{offset=N+S#decoder.offset,
column=N+S#decoder.column}).
-define(INC_COL(S), S#decoder{offset=1+S#decoder.offset,
column=1+S#decoder.column}).
-define(INC_LINE(S), S#decoder{offset=1+S#decoder.offset,
column=1,
line=1+S#decoder.line}).
-define(INC_CHAR(S, C),
case C of
$\n ->
S#decoder{column=1,
line=1+S#decoder.line,
offset=1+S#decoder.offset};
_ ->
S#decoder{column=1+S#decoder.column,
offset=1+S#decoder.offset}
end).
-define(IS_WHITESPACE(C),
(C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)).
%% @type iolist() = [char() | binary() | iolist()]
@type iodata ( ) = iolist ( ) | binary ( )
%% @type json_string() = atom | binary()
%% @type json_number() = integer() | float()
%% @type json_array() = [json_term()]
%% @type json_object() = {struct, [{json_string(), json_term()}]}
@type json_iolist ( ) = , ( ) }
%% @type json_term() = json_string() | json_number() | json_array() |
%% json_object() | json_iolist()
-record(encoder, {handler=null,
utf8=false}).
-record(decoder, {object_hook=null,
offset=0,
line=1,
column=1,
state=null}).
%% @spec encoder([encoder_option()]) -> function()
%% @doc Create an encoder/1 with the given options.
%% @type encoder_option() = handler_option() | utf8_option()
@type utf8_option ( ) = boolean ( ) . Emit unicode as ( default - false )
encoder(Options) ->
State = parse_encoder_options(Options, #encoder{}),
fun (O) -> json_encode(O, State) end.
%% @spec encode(json_term()) -> iolist()
%% @doc Encode the given as JSON to an iolist.
encode(Any) ->
json_encode(Any, #encoder{}).
%% @spec decoder([decoder_option()]) -> function()
%% @doc Create a decoder/1 with the given options.
decoder(Options) ->
State = parse_decoder_options(Options, #decoder{}),
fun (O) -> json_decode(O, State) end.
%% @spec decode(iolist()) -> json_term()
@doc Decode the given iolist to Erlang terms .
decode(S) ->
json_decode(S, #decoder{}).
%% Internal API
parse_encoder_options([], State) ->
State;
parse_encoder_options([{handler, Handler} | Rest], State) ->
parse_encoder_options(Rest, State#encoder{handler=Handler});
parse_encoder_options([{utf8, Switch} | Rest], State) ->
parse_encoder_options(Rest, State#encoder{utf8=Switch}).
parse_decoder_options([], State) ->
State;
parse_decoder_options([{object_hook, Hook} | Rest], State) ->
parse_decoder_options(Rest, State#decoder{object_hook=Hook}).
json_encode(true, _State) ->
<<"true">>;
json_encode(false, _State) ->
<<"false">>;
json_encode(null, _State) ->
<<"null">>;
json_encode(I, _State) when is_integer(I) ->
integer_to_list(I);
json_encode(F, _State) when is_float(F) ->
mod_restful_mochinum:digits(F);
json_encode(S, State) when is_binary(S); is_atom(S) ->
json_encode_string(S, State);
json_encode([{K, _}|_] = Props, State) when (K =/= struct andalso
K =/= array andalso
K =/= json) ->
json_encode_proplist(Props, State);
json_encode({struct, Props}, State) when is_list(Props) ->
json_encode_proplist(Props, State);
json_encode(Array, State) when is_list(Array) ->
json_encode_array(Array, State);
json_encode({array, Array}, State) when is_list(Array) ->
json_encode_array(Array, State);
json_encode({json, IoList}, _State) ->
IoList;
json_encode(Bad, #encoder{handler=null}) ->
exit({json_encode, {bad_term, Bad}});
json_encode(Bad, State=#encoder{handler=Handler}) ->
json_encode(Handler(Bad), State).
json_encode_array([], _State) ->
<<"[]">>;
json_encode_array(L, State) ->
F = fun (O, Acc) ->
[$,, json_encode(O, State) | Acc]
end,
[$, | Acc1] = lists:foldl(F, "[", L),
lists:reverse([$\] | Acc1]).
json_encode_proplist([], _State) ->
<<"{}">>;
json_encode_proplist(Props, State) ->
F = fun ({K, V}, Acc) ->
KS = json_encode_string(K, State),
VS = json_encode(V, State),
[$,, VS, $:, KS | Acc]
end,
[$, | Acc1] = lists:foldl(F, "{", Props),
lists:reverse([$\} | Acc1]).
json_encode_string(A, State) when is_atom(A) ->
L = atom_to_list(A),
case json_string_is_safe(L) of
true ->
[?Q, L, ?Q];
false ->
json_encode_string_unicode(xmerl_ucs:from_utf8(L), State, [?Q])
end;
json_encode_string(B, State) when is_binary(B) ->
case json_bin_is_safe(B) of
true ->
[?Q, B, ?Q];
false ->
json_encode_string_unicode(xmerl_ucs:from_utf8(B), State, [?Q])
end;
json_encode_string(I, _State) when is_integer(I) ->
[?Q, integer_to_list(I), ?Q];
json_encode_string(L, State) when is_list(L) ->
case json_string_is_safe(L) of
true ->
[?Q, L, ?Q];
false ->
json_encode_string_unicode(L, State, [?Q])
end.
json_string_is_safe([]) ->
true;
json_string_is_safe([C | Rest]) ->
case C of
?Q ->
false;
$\\ ->
false;
$\b ->
false;
$\f ->
false;
$\n ->
false;
$\r ->
false;
$\t ->
false;
C when C >= 0, C < $\s; C >= 16#7f, C =< 16#10FFFF ->
false;
C when C < 16#7f ->
json_string_is_safe(Rest);
_ ->
false
end.
json_bin_is_safe(<<>>) ->
true;
json_bin_is_safe(<<C, Rest/binary>>) ->
case C of
?Q ->
false;
$\\ ->
false;
$\b ->
false;
$\f ->
false;
$\n ->
false;
$\r ->
false;
$\t ->
false;
C when C >= 0, C < $\s; C >= 16#7f ->
false;
C when C < 16#7f ->
json_bin_is_safe(Rest)
end.
json_encode_string_unicode([], _State, Acc) ->
lists:reverse([$\" | Acc]);
json_encode_string_unicode([C | Cs], State, Acc) ->
Acc1 = case C of
?Q ->
[?Q, $\\ | Acc];
%% Escaping solidus is only useful when trying to protect
against " < > " injection attacks which are only
%% possible when JSON is inserted into a HTML document
%% in-line. mochijson2 does not protect you from this, so
%% if you do insert directly into HTML then you need to
%% uncomment the following case or escape the output of encode.
%%
%% $/ ->
%% [$/, $\\ | Acc];
%%
$\\ ->
[$\\, $\\ | Acc];
$\b ->
[$b, $\\ | Acc];
$\f ->
[$f, $\\ | Acc];
$\n ->
[$n, $\\ | Acc];
$\r ->
[$r, $\\ | Acc];
$\t ->
[$t, $\\ | Acc];
C when C >= 0, C < $\s ->
[unihex(C) | Acc];
C when C >= 16#7f, C =< 16#10FFFF, State#encoder.utf8 ->
[xmerl_ucs:to_utf8(C) | Acc];
C when C >= 16#7f, C =< 16#10FFFF, not State#encoder.utf8 ->
[unihex(C) | Acc];
C when C < 16#7f ->
[C | Acc];
_ ->
exit({json_encode, {bad_char, C}})
end,
json_encode_string_unicode(Cs, State, Acc1).
hexdigit(C) when C >= 0, C =< 9 ->
C + $0;
hexdigit(C) when C =< 15 ->
C + $a - 10.
unihex(C) when C < 16#10000 ->
<<D3:4, D2:4, D1:4, D0:4>> = <<C:16>>,
Digits = [hexdigit(D) || D <- [D3, D2, D1, D0]],
[$\\, $u | Digits];
unihex(C) when C =< 16#10FFFF ->
N = C - 16#10000,
S1 = 16#d800 bor ((N bsr 10) band 16#3ff),
S2 = 16#dc00 bor (N band 16#3ff),
[unihex(S1), unihex(S2)].
json_decode(L, S) when is_list(L) ->
json_decode(iolist_to_binary(L), S);
json_decode(B, S) ->
{Res, S1} = decode1(B, S),
{eof, _} = tokenize(B, S1#decoder{state=trim}),
Res.
decode1(B, S=#decoder{state=null}) ->
case tokenize(B, S#decoder{state=any}) of
{{const, C}, S1} ->
{C, S1};
{start_array, S1} ->
decode_array(B, S1);
{start_object, S1} ->
decode_object(B, S1)
end.
make_object(V, #decoder{object_hook=null}) ->
V;
make_object(V, #decoder{object_hook=Hook}) ->
Hook(V).
decode_object(B, S) ->
decode_object(B, S#decoder{state=key}, []).
decode_object(B, S=#decoder{state=key}, Acc) ->
case tokenize(B, S) of
{end_object, S1} ->
V = make_object({struct, lists:reverse(Acc)}, S1),
{V, S1#decoder{state=null}};
{{const, K}, S1} ->
{colon, S2} = tokenize(B, S1),
{V, S3} = decode1(B, S2#decoder{state=null}),
decode_object(B, S3#decoder{state=comma}, [{K, V} | Acc])
end;
decode_object(B, S=#decoder{state=comma}, Acc) ->
case tokenize(B, S) of
{end_object, S1} ->
V = make_object({struct, lists:reverse(Acc)}, S1),
{V, S1#decoder{state=null}};
{comma, S1} ->
decode_object(B, S1#decoder{state=key}, Acc)
end.
decode_array(B, S) ->
decode_array(B, S#decoder{state=any}, []).
decode_array(B, S=#decoder{state=any}, Acc) ->
case tokenize(B, S) of
{end_array, S1} ->
{lists:reverse(Acc), S1#decoder{state=null}};
{start_array, S1} ->
{Array, S2} = decode_array(B, S1),
decode_array(B, S2#decoder{state=comma}, [Array | Acc]);
{start_object, S1} ->
{Array, S2} = decode_object(B, S1),
decode_array(B, S2#decoder{state=comma}, [Array | Acc]);
{{const, Const}, S1} ->
decode_array(B, S1#decoder{state=comma}, [Const | Acc])
end;
decode_array(B, S=#decoder{state=comma}, Acc) ->
case tokenize(B, S) of
{end_array, S1} ->
{lists:reverse(Acc), S1#decoder{state=null}};
{comma, S1} ->
decode_array(B, S1#decoder{state=any}, Acc)
end.
tokenize_string(B, S=#decoder{offset=O}) ->
case tokenize_string_fast(B, O) of
{escape, O1} ->
Length = O1 - O,
S1 = ?ADV_COL(S, Length),
<<_:O/binary, Head:Length/binary, _/binary>> = B,
tokenize_string(B, S1, lists:reverse(binary_to_list(Head)));
O1 ->
Length = O1 - O,
<<_:O/binary, String:Length/binary, ?Q, _/binary>> = B,
{{const, String}, ?ADV_COL(S, Length + 1)}
end.
tokenize_string_fast(B, O) ->
case B of
<<_:O/binary, ?Q, _/binary>> ->
O;
<<_:O/binary, $\\, _/binary>> ->
{escape, O};
<<_:O/binary, C1, _/binary>> when C1 < 128 ->
tokenize_string_fast(B, 1 + O);
<<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223,
C2 >= 128, C2 =< 191 ->
tokenize_string_fast(B, 2 + O);
<<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239,
C2 >= 128, C2 =< 191,
C3 >= 128, C3 =< 191 ->
tokenize_string_fast(B, 3 + O);
<<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244,
C2 >= 128, C2 =< 191,
C3 >= 128, C3 =< 191,
C4 >= 128, C4 =< 191 ->
tokenize_string_fast(B, 4 + O);
_ ->
throw(invalid_utf8)
end.
tokenize_string(B, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, ?Q, _/binary>> ->
{{const, iolist_to_binary(lists:reverse(Acc))}, ?INC_COL(S)};
<<_:O/binary, "\\\"", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\" | Acc]);
<<_:O/binary, "\\\\", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\\ | Acc]);
<<_:O/binary, "\\/", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$/ | Acc]);
<<_:O/binary, "\\b", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\b | Acc]);
<<_:O/binary, "\\f", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\f | Acc]);
<<_:O/binary, "\\n", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\n | Acc]);
<<_:O/binary, "\\r", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\r | Acc]);
<<_:O/binary, "\\t", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\t | Acc]);
<<_:O/binary, "\\u", C3, C2, C1, C0, Rest/binary>> ->
C = erlang:list_to_integer([C3, C2, C1, C0], 16),
if C > 16#D7FF, C < 16#DC00 ->
%% coalesce UTF-16 surrogate pair
<<"\\u", D3, D2, D1, D0, _/binary>> = Rest,
D = erlang:list_to_integer([D3,D2,D1,D0], 16),
[CodePoint] = xmerl_ucs:from_utf16be(<<C:16/big-unsigned-integer,
D:16/big-unsigned-integer>>),
Acc1 = lists:reverse(xmerl_ucs:to_utf8(CodePoint), Acc),
tokenize_string(B, ?ADV_COL(S, 12), Acc1);
true ->
Acc1 = lists:reverse(xmerl_ucs:to_utf8(C), Acc),
tokenize_string(B, ?ADV_COL(S, 6), Acc1)
end;
<<_:O/binary, C1, _/binary>> when C1 < 128 ->
tokenize_string(B, ?INC_CHAR(S, C1), [C1 | Acc]);
<<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223,
C2 >= 128, C2 =< 191 ->
tokenize_string(B, ?ADV_COL(S, 2), [C2, C1 | Acc]);
<<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239,
C2 >= 128, C2 =< 191,
C3 >= 128, C3 =< 191 ->
tokenize_string(B, ?ADV_COL(S, 3), [C3, C2, C1 | Acc]);
<<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244,
C2 >= 128, C2 =< 191,
C3 >= 128, C3 =< 191,
C4 >= 128, C4 =< 191 ->
tokenize_string(B, ?ADV_COL(S, 4), [C4, C3, C2, C1 | Acc]);
_ ->
throw(invalid_utf8)
end.
tokenize_number(B, S) ->
case tokenize_number(B, sign, S, []) of
{{int, Int}, S1} ->
{{const, list_to_integer(Int)}, S1};
{{float, Float}, S1} ->
{{const, list_to_float(Float)}, S1}
end.
tokenize_number(B, sign, S=#decoder{offset=O}, []) ->
case B of
<<_:O/binary, $-, _/binary>> ->
tokenize_number(B, int, ?INC_COL(S), [$-]);
_ ->
tokenize_number(B, int, S, [])
end;
tokenize_number(B, int, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, $0, _/binary>> ->
tokenize_number(B, frac, ?INC_COL(S), [$0 | Acc]);
<<_:O/binary, C, _/binary>> when C >= $1 andalso C =< $9 ->
tokenize_number(B, int1, ?INC_COL(S), [C | Acc])
end;
tokenize_number(B, int1, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
tokenize_number(B, int1, ?INC_COL(S), [C | Acc]);
_ ->
tokenize_number(B, frac, S, Acc)
end;
tokenize_number(B, frac, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, $., C, _/binary>> when C >= $0, C =< $9 ->
tokenize_number(B, frac1, ?ADV_COL(S, 2), [C, $. | Acc]);
<<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E ->
tokenize_number(B, esign, ?INC_COL(S), [$e, $0, $. | Acc]);
_ ->
{{int, lists:reverse(Acc)}, S}
end;
tokenize_number(B, frac1, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
tokenize_number(B, frac1, ?INC_COL(S), [C | Acc]);
<<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E ->
tokenize_number(B, esign, ?INC_COL(S), [$e | Acc]);
_ ->
{{float, lists:reverse(Acc)}, S}
end;
tokenize_number(B, esign, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C =:= $- orelse C=:= $+ ->
tokenize_number(B, eint, ?INC_COL(S), [C | Acc]);
_ ->
tokenize_number(B, eint, S, Acc)
end;
tokenize_number(B, eint, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
tokenize_number(B, eint1, ?INC_COL(S), [C | Acc])
end;
tokenize_number(B, eint1, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
tokenize_number(B, eint1, ?INC_COL(S), [C | Acc]);
_ ->
{{float, lists:reverse(Acc)}, S}
end.
tokenize(B, S=#decoder{offset=O}) ->
case B of
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
tokenize(B, ?INC_CHAR(S, C));
<<_:O/binary, "{", _/binary>> ->
{start_object, ?INC_COL(S)};
<<_:O/binary, "}", _/binary>> ->
{end_object, ?INC_COL(S)};
<<_:O/binary, "[", _/binary>> ->
{start_array, ?INC_COL(S)};
<<_:O/binary, "]", _/binary>> ->
{end_array, ?INC_COL(S)};
<<_:O/binary, ",", _/binary>> ->
{comma, ?INC_COL(S)};
<<_:O/binary, ":", _/binary>> ->
{colon, ?INC_COL(S)};
<<_:O/binary, "null", _/binary>> ->
{{const, null}, ?ADV_COL(S, 4)};
<<_:O/binary, "true", _/binary>> ->
{{const, true}, ?ADV_COL(S, 4)};
<<_:O/binary, "false", _/binary>> ->
{{const, false}, ?ADV_COL(S, 5)};
<<_:O/binary, "\"", _/binary>> ->
tokenize_string(B, ?INC_COL(S));
<<_:O/binary, C, _/binary>> when (C >= $0 andalso C =< $9)
orelse C =:= $- ->
tokenize_number(B, S);
<<_:O/binary>> ->
trim = S#decoder.state,
{eof, S}
end.
%%
%% Tests
%%
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
%% testing constructs borrowed from the Yaws JSON implementation.
Create an object from a list of Key / Value pairs .
obj_new() ->
{struct, []}.
is_obj({struct, Props}) ->
F = fun ({K, _}) when is_binary(K) -> true end,
lists:all(F, Props).
obj_from_list(Props) ->
Obj = {struct, Props},
?assert(is_obj(Obj)),
Obj.
Test for equivalence of Erlang terms .
%% Due to arbitrary order of construction, equivalent objects might
compare unequal as erlang terms , so we need to carefully recurse
%% through aggregates (tuples and objects).
equiv({struct, Props1}, {struct, Props2}) ->
equiv_object(Props1, Props2);
equiv(L1, L2) when is_list(L1), is_list(L2) ->
equiv_list(L1, L2);
equiv(N1, N2) when is_number(N1), is_number(N2) -> N1 == N2;
equiv(B1, B2) when is_binary(B1), is_binary(B2) -> B1 == B2;
equiv(A, A) when A =:= true orelse A =:= false orelse A =:= null -> true.
%% Object representation and traversal order is unknown.
%% Use the sledgehammer and sort property lists.
equiv_object(Props1, Props2) ->
L1 = lists:keysort(1, Props1),
L2 = lists:keysort(1, Props2),
Pairs = lists:zip(L1, L2),
true = lists:all(fun({{K1, V1}, {K2, V2}}) ->
equiv(K1, K2) and equiv(V1, V2)
end, Pairs).
%% Recursively compare tuple elements for equivalence.
equiv_list([], []) ->
true;
equiv_list([V1 | L1], [V2 | L2]) ->
equiv(V1, V2) andalso equiv_list(L1, L2).
decode_test() ->
[1199344435545.0, 1] = decode(<<"[1199344435545.0,1]">>),
<<16#F0,16#9D,16#9C,16#95>> = decode([34,"\\ud835","\\udf15",34]).
e2j_vec_test() ->
test_one(e2j_test_vec(utf8), 1).
test_one([], _N) ->
%% io:format("~p tests passed~n", [N-1]),
ok;
test_one([{E, J} | Rest], N) ->
%% io:format("[~p] ~p ~p~n", [N, E, J]),
true = equiv(E, decode(J)),
true = equiv(E, decode(encode(E))),
test_one(Rest, 1+N).
e2j_test_vec(utf8) ->
[
{1, "1"},
text representation may truncate , trail zeroes
{-1, "-1"},
{-3.1416, "-3.14160"},
{12.0e10, "1.20000e+11"},
{1.234E+10, "1.23400e+10"},
{-1.234E-10, "-1.23400e-10"},
{10.0, "1.0e+01"},
{123.456, "1.23456E+2"},
{10.0, "1e1"},
{<<"foo">>, "\"foo\""},
{<<"foo", 5, "bar">>, "\"foo\\u0005bar\""},
{<<"">>, "\"\""},
{<<"\n\n\n">>, "\"\\n\\n\\n\""},
{<<"\" \b\f\r\n\t\"">>, "\"\\\" \\b\\f\\r\\n\\t\\\"\""},
{obj_new(), "{}"},
{obj_from_list([{<<"foo">>, <<"bar">>}]), "{\"foo\":\"bar\"}"},
{obj_from_list([{<<"foo">>, <<"bar">>}, {<<"baz">>, 123}]),
"{\"foo\":\"bar\",\"baz\":123}"},
{[], "[]"},
{[[]], "[[]]"},
{[1, <<"foo">>], "[1,\"foo\"]"},
%% json array in a json object
{obj_from_list([{<<"foo">>, [123]}]),
"{\"foo\":[123]}"},
%% json object in a json object
{obj_from_list([{<<"foo">>, obj_from_list([{<<"bar">>, true}])}]),
"{\"foo\":{\"bar\":true}}"},
%% fold evaluation order
{obj_from_list([{<<"foo">>, []},
{<<"bar">>, obj_from_list([{<<"baz">>, true}])},
{<<"alice">>, <<"bob">>}]),
"{\"foo\":[],\"bar\":{\"baz\":true},\"alice\":\"bob\"}"},
%% json object in a json array
{[-123, <<"foo">>, obj_from_list([{<<"bar">>, []}]), null],
"[-123,\"foo\",{\"bar\":[]},null]"}
].
%% test utf8 encoding
encoder_utf8_test() ->
%% safe conversion case (default)
[34,"\\u0001","\\u0442","\\u0435","\\u0441","\\u0442",34] =
encode(<<1,"\321\202\320\265\321\201\321\202">>),
%% raw utf8 output (optional)
Enc = mochijson2:encoder([{utf8, true}]),
[34,"\\u0001",[209,130],[208,181],[209,129],[209,130],34] =
Enc(<<1,"\321\202\320\265\321\201\321\202">>).
input_validation_test() ->
Good = [
{16#00A3, <<?Q, 16#C2, 16#A3, ?Q>>}, %% pound
{16#20AC, <<?Q, 16#E2, 16#82, 16#AC, ?Q>>}, %% euro
{16#10196, <<?Q, 16#F0, 16#90, 16#86, 16#96, ?Q>>} %% denarius
],
lists:foreach(fun({CodePoint, UTF8}) ->
Expect = list_to_binary(xmerl_ucs:to_utf8(CodePoint)),
Expect = decode(UTF8)
end, Good),
Bad = [
2nd , 3rd , or 4th byte of a multi - byte sequence w/o leading byte
<<?Q, 16#80, ?Q>>,
missing continuations , last byte in each should be 80 - BF
<<?Q, 16#C2, 16#7F, ?Q>>,
<<?Q, 16#E0, 16#80,16#7F, ?Q>>,
<<?Q, 16#F0, 16#80, 16#80, 16#7F, ?Q>>,
%% we don't support code points > 10FFFF per RFC 3629
<<?Q, 16#F5, 16#80, 16#80, 16#80, ?Q>>,
%% escape characters trigger a different code path
<<?Q, $\\, $\n, 16#80, ?Q>>
],
lists:foreach(
fun(X) ->
ok = try decode(X) catch invalid_utf8 -> ok end,
could be { } } or
%% {json_encode,{bad_char,_}}
{'EXIT', _} = (catch encode(X))
end, Bad).
inline_json_test() ->
?assertEqual(<<"\"iodata iodata\"">>,
iolist_to_binary(
encode({json, [<<"\"iodata">>, " iodata\""]}))),
?assertEqual({struct, [{<<"key">>, <<"iodata iodata">>}]},
decode(
encode({struct,
[{key, {json, [<<"\"iodata">>, " iodata\""]}}]}))),
ok.
big_unicode_test() ->
UTF8Seq = list_to_binary(xmerl_ucs:to_utf8(16#0001d120)),
?assertEqual(
<<"\"\\ud834\\udd20\"">>,
iolist_to_binary(encode(UTF8Seq))),
?assertEqual(
UTF8Seq,
decode(iolist_to_binary(encode(UTF8Seq)))),
ok.
custom_decoder_test() ->
?assertEqual(
{struct, [{<<"key">>, <<"value">>}]},
(decoder([]))("{\"key\": \"value\"}")),
F = fun ({struct, [{<<"key">>, <<"value">>}]}) -> win end,
?assertEqual(
win,
(decoder([{object_hook, F}]))("{\"key\": \"value\"}")),
ok.
atom_test() ->
%% JSON native atoms
[begin
?assertEqual(A, decode(atom_to_list(A))),
?assertEqual(iolist_to_binary(atom_to_list(A)),
iolist_to_binary(encode(A)))
end || A <- [true, false, null]],
%% Atom to string
?assertEqual(
<<"\"foo\"">>,
iolist_to_binary(encode(foo))),
?assertEqual(
<<"\"\\ud834\\udd20\"">>,
iolist_to_binary(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))),
ok.
key_encode_test() ->
%% Some forms are accepted as keys that would not be strings in other
%% cases
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode({struct, [{foo, 1}]}))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode({struct, [{<<"foo">>, 1}]}))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode({struct, [{"foo", 1}]}))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode([{foo, 1}]))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode([{<<"foo">>, 1}]))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode([{"foo", 1}]))),
?assertEqual(
<<"{\"\\ud834\\udd20\":1}">>,
iolist_to_binary(
encode({struct, [{[16#0001d120], 1}]}))),
?assertEqual(
<<"{\"1\":1}">>,
iolist_to_binary(encode({struct, [{1, 1}]}))),
ok.
unsafe_chars_test() ->
Chars = "\"\\\b\f\n\r\t",
[begin
?assertEqual(false, json_string_is_safe([C])),
?assertEqual(false, json_bin_is_safe(<<C>>)),
?assertEqual(<<C>>, decode(encode(<<C>>)))
end || C <- Chars],
?assertEqual(
false,
json_string_is_safe([16#0001d120])),
?assertEqual(
false,
json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8(16#0001d120)))),
?assertEqual(
[16#0001d120],
xmerl_ucs:from_utf8(
binary_to_list(
decode(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))))),
?assertEqual(
false,
json_string_is_safe([16#110000])),
?assertEqual(
false,
json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8([16#110000])))),
%% solidus can be escaped but isn't unsafe by default
?assertEqual(
<<"/">>,
decode(<<"\"\\/\"">>)),
ok.
int_test() ->
?assertEqual(0, decode("0")),
?assertEqual(1, decode("1")),
?assertEqual(11, decode("11")),
ok.
large_int_test() ->
?assertEqual(<<"-2147483649214748364921474836492147483649">>,
iolist_to_binary(encode(-2147483649214748364921474836492147483649))),
?assertEqual(<<"2147483649214748364921474836492147483649">>,
iolist_to_binary(encode(2147483649214748364921474836492147483649))),
ok.
float_test() ->
?assertEqual(<<"-2147483649.0">>, iolist_to_binary(encode(-2147483649.0))),
?assertEqual(<<"2147483648.0">>, iolist_to_binary(encode(2147483648.0))),
ok.
handler_test() ->
?assertEqual(
{'EXIT',{json_encode,{bad_term,{}}}},
catch encode({})),
F = fun ({}) -> [] end,
?assertEqual(
<<"[]">>,
iolist_to_binary((encoder([{handler, F}]))({}))),
ok.
-endif.
| null | https://raw.githubusercontent.com/jadahl/mod_restful/3a4995e0facd29879a6c2949547177a1ac618474/src/mod_restful_mochijson2.erl | erlang |
This file contains parts of the json implementation from mochiweb. Copyright
information and license information follows.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
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
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
with binaries as strings, arrays as lists (without an {array, _})
JSON terms are decoded as follows (javascript -> erlang):
<ul>
<li>{"key": "value"} ->
{struct, [{<<"key">>, <<"value">>}]}</li>
</li>
</ul>
<ul>
<li>Strings in JSON decode to UTF-8 binaries in Erlang</li>
<li>Objects decode to {struct, PropList}</li>
<li>Numbers decode to integer or float</li>
<li>true, false, null decode to their respective terms.</li>
</ul>
The encoder will accept the same format that the decoder will produce,
but will also allow additional cases for leniency:
<ul>
strings (even as a proplist key)
</li>
with no validation
</li>
<li>{array, Array} will be encoded as Array
(legacy mochijson style)
</li>
or array
</li>
</ul>
This is a macro to placate syntax highlighters..
@type iolist() = [char() | binary() | iolist()]
@type json_string() = atom | binary()
@type json_number() = integer() | float()
@type json_array() = [json_term()]
@type json_object() = {struct, [{json_string(), json_term()}]}
@type json_term() = json_string() | json_number() | json_array() |
json_object() | json_iolist()
@spec encoder([encoder_option()]) -> function()
@doc Create an encoder/1 with the given options.
@type encoder_option() = handler_option() | utf8_option()
@spec encode(json_term()) -> iolist()
@doc Encode the given as JSON to an iolist.
@spec decoder([decoder_option()]) -> function()
@doc Create a decoder/1 with the given options.
@spec decode(iolist()) -> json_term()
Internal API
Escaping solidus is only useful when trying to protect
possible when JSON is inserted into a HTML document
in-line. mochijson2 does not protect you from this, so
if you do insert directly into HTML then you need to
uncomment the following case or escape the output of encode.
$/ ->
[$/, $\\ | Acc];
coalesce UTF-16 surrogate pair
Tests
testing constructs borrowed from the Yaws JSON implementation.
Due to arbitrary order of construction, equivalent objects might
through aggregates (tuples and objects).
Object representation and traversal order is unknown.
Use the sledgehammer and sort property lists.
Recursively compare tuple elements for equivalence.
io:format("~p tests passed~n", [N-1]),
io:format("[~p] ~p ~p~n", [N, E, J]),
json array in a json object
json object in a json object
fold evaluation order
json object in a json array
test utf8 encoding
safe conversion case (default)
raw utf8 output (optional)
pound
euro
denarius
we don't support code points > 10FFFF per RFC 3629
escape characters trigger a different code path
{json_encode,{bad_char,_}}
JSON native atoms
Atom to string
Some forms are accepted as keys that would not be strings in other
cases
solidus can be escaped but isn't unsafe by default | @author < >
2007 Mochi Media , Inc.
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
@doc Yet another JSON ( RFC 4627 ) library for Erlang . mochijson2 works
wrapper and it only knows how to decode UTF-8 ( and ASCII ) .
< li>["array " , 123 , 12.34 , true , false , null ] - >
[ & lt;<"array " > > , 123 , 12.34 , true , false , null ]
< li > atoms other than true , false , null will be considered UTF-8
< li>{json , } will insert IoList directly into the output
< li > A non - empty raw proplist will be encoded as an object as long
as the first pair does not have an atom key of json , struct ,
-module(mod_restful_mochijson2).
-author('').
-export([encoder/1, encode/1]).
-export([decoder/1, decode/1]).
-define(Q, $\").
-define(ADV_COL(S, N), S#decoder{offset=N+S#decoder.offset,
column=N+S#decoder.column}).
-define(INC_COL(S), S#decoder{offset=1+S#decoder.offset,
column=1+S#decoder.column}).
-define(INC_LINE(S), S#decoder{offset=1+S#decoder.offset,
column=1,
line=1+S#decoder.line}).
-define(INC_CHAR(S, C),
case C of
$\n ->
S#decoder{column=1,
line=1+S#decoder.line,
offset=1+S#decoder.offset};
_ ->
S#decoder{column=1+S#decoder.column,
offset=1+S#decoder.offset}
end).
-define(IS_WHITESPACE(C),
(C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)).
@type iodata ( ) = iolist ( ) | binary ( )
@type json_iolist ( ) = , ( ) }
-record(encoder, {handler=null,
utf8=false}).
-record(decoder, {object_hook=null,
offset=0,
line=1,
column=1,
state=null}).
@type utf8_option ( ) = boolean ( ) . Emit unicode as ( default - false )
encoder(Options) ->
State = parse_encoder_options(Options, #encoder{}),
fun (O) -> json_encode(O, State) end.
encode(Any) ->
json_encode(Any, #encoder{}).
decoder(Options) ->
State = parse_decoder_options(Options, #decoder{}),
fun (O) -> json_decode(O, State) end.
@doc Decode the given iolist to Erlang terms .
decode(S) ->
json_decode(S, #decoder{}).
parse_encoder_options([], State) ->
State;
parse_encoder_options([{handler, Handler} | Rest], State) ->
parse_encoder_options(Rest, State#encoder{handler=Handler});
parse_encoder_options([{utf8, Switch} | Rest], State) ->
parse_encoder_options(Rest, State#encoder{utf8=Switch}).
parse_decoder_options([], State) ->
State;
parse_decoder_options([{object_hook, Hook} | Rest], State) ->
parse_decoder_options(Rest, State#decoder{object_hook=Hook}).
json_encode(true, _State) ->
<<"true">>;
json_encode(false, _State) ->
<<"false">>;
json_encode(null, _State) ->
<<"null">>;
json_encode(I, _State) when is_integer(I) ->
integer_to_list(I);
json_encode(F, _State) when is_float(F) ->
mod_restful_mochinum:digits(F);
json_encode(S, State) when is_binary(S); is_atom(S) ->
json_encode_string(S, State);
json_encode([{K, _}|_] = Props, State) when (K =/= struct andalso
K =/= array andalso
K =/= json) ->
json_encode_proplist(Props, State);
json_encode({struct, Props}, State) when is_list(Props) ->
json_encode_proplist(Props, State);
json_encode(Array, State) when is_list(Array) ->
json_encode_array(Array, State);
json_encode({array, Array}, State) when is_list(Array) ->
json_encode_array(Array, State);
json_encode({json, IoList}, _State) ->
IoList;
json_encode(Bad, #encoder{handler=null}) ->
exit({json_encode, {bad_term, Bad}});
json_encode(Bad, State=#encoder{handler=Handler}) ->
json_encode(Handler(Bad), State).
json_encode_array([], _State) ->
<<"[]">>;
json_encode_array(L, State) ->
F = fun (O, Acc) ->
[$,, json_encode(O, State) | Acc]
end,
[$, | Acc1] = lists:foldl(F, "[", L),
lists:reverse([$\] | Acc1]).
json_encode_proplist([], _State) ->
<<"{}">>;
json_encode_proplist(Props, State) ->
F = fun ({K, V}, Acc) ->
KS = json_encode_string(K, State),
VS = json_encode(V, State),
[$,, VS, $:, KS | Acc]
end,
[$, | Acc1] = lists:foldl(F, "{", Props),
lists:reverse([$\} | Acc1]).
json_encode_string(A, State) when is_atom(A) ->
L = atom_to_list(A),
case json_string_is_safe(L) of
true ->
[?Q, L, ?Q];
false ->
json_encode_string_unicode(xmerl_ucs:from_utf8(L), State, [?Q])
end;
json_encode_string(B, State) when is_binary(B) ->
case json_bin_is_safe(B) of
true ->
[?Q, B, ?Q];
false ->
json_encode_string_unicode(xmerl_ucs:from_utf8(B), State, [?Q])
end;
json_encode_string(I, _State) when is_integer(I) ->
[?Q, integer_to_list(I), ?Q];
json_encode_string(L, State) when is_list(L) ->
case json_string_is_safe(L) of
true ->
[?Q, L, ?Q];
false ->
json_encode_string_unicode(L, State, [?Q])
end.
json_string_is_safe([]) ->
true;
json_string_is_safe([C | Rest]) ->
case C of
?Q ->
false;
$\\ ->
false;
$\b ->
false;
$\f ->
false;
$\n ->
false;
$\r ->
false;
$\t ->
false;
C when C >= 0, C < $\s; C >= 16#7f, C =< 16#10FFFF ->
false;
C when C < 16#7f ->
json_string_is_safe(Rest);
_ ->
false
end.
json_bin_is_safe(<<>>) ->
true;
json_bin_is_safe(<<C, Rest/binary>>) ->
case C of
?Q ->
false;
$\\ ->
false;
$\b ->
false;
$\f ->
false;
$\n ->
false;
$\r ->
false;
$\t ->
false;
C when C >= 0, C < $\s; C >= 16#7f ->
false;
C when C < 16#7f ->
json_bin_is_safe(Rest)
end.
json_encode_string_unicode([], _State, Acc) ->
lists:reverse([$\" | Acc]);
json_encode_string_unicode([C | Cs], State, Acc) ->
Acc1 = case C of
?Q ->
[?Q, $\\ | Acc];
against " < > " injection attacks which are only
$\\ ->
[$\\, $\\ | Acc];
$\b ->
[$b, $\\ | Acc];
$\f ->
[$f, $\\ | Acc];
$\n ->
[$n, $\\ | Acc];
$\r ->
[$r, $\\ | Acc];
$\t ->
[$t, $\\ | Acc];
C when C >= 0, C < $\s ->
[unihex(C) | Acc];
C when C >= 16#7f, C =< 16#10FFFF, State#encoder.utf8 ->
[xmerl_ucs:to_utf8(C) | Acc];
C when C >= 16#7f, C =< 16#10FFFF, not State#encoder.utf8 ->
[unihex(C) | Acc];
C when C < 16#7f ->
[C | Acc];
_ ->
exit({json_encode, {bad_char, C}})
end,
json_encode_string_unicode(Cs, State, Acc1).
hexdigit(C) when C >= 0, C =< 9 ->
C + $0;
hexdigit(C) when C =< 15 ->
C + $a - 10.
unihex(C) when C < 16#10000 ->
<<D3:4, D2:4, D1:4, D0:4>> = <<C:16>>,
Digits = [hexdigit(D) || D <- [D3, D2, D1, D0]],
[$\\, $u | Digits];
unihex(C) when C =< 16#10FFFF ->
N = C - 16#10000,
S1 = 16#d800 bor ((N bsr 10) band 16#3ff),
S2 = 16#dc00 bor (N band 16#3ff),
[unihex(S1), unihex(S2)].
json_decode(L, S) when is_list(L) ->
json_decode(iolist_to_binary(L), S);
json_decode(B, S) ->
{Res, S1} = decode1(B, S),
{eof, _} = tokenize(B, S1#decoder{state=trim}),
Res.
decode1(B, S=#decoder{state=null}) ->
case tokenize(B, S#decoder{state=any}) of
{{const, C}, S1} ->
{C, S1};
{start_array, S1} ->
decode_array(B, S1);
{start_object, S1} ->
decode_object(B, S1)
end.
make_object(V, #decoder{object_hook=null}) ->
V;
make_object(V, #decoder{object_hook=Hook}) ->
Hook(V).
decode_object(B, S) ->
decode_object(B, S#decoder{state=key}, []).
decode_object(B, S=#decoder{state=key}, Acc) ->
case tokenize(B, S) of
{end_object, S1} ->
V = make_object({struct, lists:reverse(Acc)}, S1),
{V, S1#decoder{state=null}};
{{const, K}, S1} ->
{colon, S2} = tokenize(B, S1),
{V, S3} = decode1(B, S2#decoder{state=null}),
decode_object(B, S3#decoder{state=comma}, [{K, V} | Acc])
end;
decode_object(B, S=#decoder{state=comma}, Acc) ->
case tokenize(B, S) of
{end_object, S1} ->
V = make_object({struct, lists:reverse(Acc)}, S1),
{V, S1#decoder{state=null}};
{comma, S1} ->
decode_object(B, S1#decoder{state=key}, Acc)
end.
decode_array(B, S) ->
decode_array(B, S#decoder{state=any}, []).
decode_array(B, S=#decoder{state=any}, Acc) ->
case tokenize(B, S) of
{end_array, S1} ->
{lists:reverse(Acc), S1#decoder{state=null}};
{start_array, S1} ->
{Array, S2} = decode_array(B, S1),
decode_array(B, S2#decoder{state=comma}, [Array | Acc]);
{start_object, S1} ->
{Array, S2} = decode_object(B, S1),
decode_array(B, S2#decoder{state=comma}, [Array | Acc]);
{{const, Const}, S1} ->
decode_array(B, S1#decoder{state=comma}, [Const | Acc])
end;
decode_array(B, S=#decoder{state=comma}, Acc) ->
case tokenize(B, S) of
{end_array, S1} ->
{lists:reverse(Acc), S1#decoder{state=null}};
{comma, S1} ->
decode_array(B, S1#decoder{state=any}, Acc)
end.
tokenize_string(B, S=#decoder{offset=O}) ->
case tokenize_string_fast(B, O) of
{escape, O1} ->
Length = O1 - O,
S1 = ?ADV_COL(S, Length),
<<_:O/binary, Head:Length/binary, _/binary>> = B,
tokenize_string(B, S1, lists:reverse(binary_to_list(Head)));
O1 ->
Length = O1 - O,
<<_:O/binary, String:Length/binary, ?Q, _/binary>> = B,
{{const, String}, ?ADV_COL(S, Length + 1)}
end.
tokenize_string_fast(B, O) ->
case B of
<<_:O/binary, ?Q, _/binary>> ->
O;
<<_:O/binary, $\\, _/binary>> ->
{escape, O};
<<_:O/binary, C1, _/binary>> when C1 < 128 ->
tokenize_string_fast(B, 1 + O);
<<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223,
C2 >= 128, C2 =< 191 ->
tokenize_string_fast(B, 2 + O);
<<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239,
C2 >= 128, C2 =< 191,
C3 >= 128, C3 =< 191 ->
tokenize_string_fast(B, 3 + O);
<<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244,
C2 >= 128, C2 =< 191,
C3 >= 128, C3 =< 191,
C4 >= 128, C4 =< 191 ->
tokenize_string_fast(B, 4 + O);
_ ->
throw(invalid_utf8)
end.
tokenize_string(B, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, ?Q, _/binary>> ->
{{const, iolist_to_binary(lists:reverse(Acc))}, ?INC_COL(S)};
<<_:O/binary, "\\\"", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\" | Acc]);
<<_:O/binary, "\\\\", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\\ | Acc]);
<<_:O/binary, "\\/", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$/ | Acc]);
<<_:O/binary, "\\b", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\b | Acc]);
<<_:O/binary, "\\f", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\f | Acc]);
<<_:O/binary, "\\n", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\n | Acc]);
<<_:O/binary, "\\r", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\r | Acc]);
<<_:O/binary, "\\t", _/binary>> ->
tokenize_string(B, ?ADV_COL(S, 2), [$\t | Acc]);
<<_:O/binary, "\\u", C3, C2, C1, C0, Rest/binary>> ->
C = erlang:list_to_integer([C3, C2, C1, C0], 16),
if C > 16#D7FF, C < 16#DC00 ->
<<"\\u", D3, D2, D1, D0, _/binary>> = Rest,
D = erlang:list_to_integer([D3,D2,D1,D0], 16),
[CodePoint] = xmerl_ucs:from_utf16be(<<C:16/big-unsigned-integer,
D:16/big-unsigned-integer>>),
Acc1 = lists:reverse(xmerl_ucs:to_utf8(CodePoint), Acc),
tokenize_string(B, ?ADV_COL(S, 12), Acc1);
true ->
Acc1 = lists:reverse(xmerl_ucs:to_utf8(C), Acc),
tokenize_string(B, ?ADV_COL(S, 6), Acc1)
end;
<<_:O/binary, C1, _/binary>> when C1 < 128 ->
tokenize_string(B, ?INC_CHAR(S, C1), [C1 | Acc]);
<<_:O/binary, C1, C2, _/binary>> when C1 >= 194, C1 =< 223,
C2 >= 128, C2 =< 191 ->
tokenize_string(B, ?ADV_COL(S, 2), [C2, C1 | Acc]);
<<_:O/binary, C1, C2, C3, _/binary>> when C1 >= 224, C1 =< 239,
C2 >= 128, C2 =< 191,
C3 >= 128, C3 =< 191 ->
tokenize_string(B, ?ADV_COL(S, 3), [C3, C2, C1 | Acc]);
<<_:O/binary, C1, C2, C3, C4, _/binary>> when C1 >= 240, C1 =< 244,
C2 >= 128, C2 =< 191,
C3 >= 128, C3 =< 191,
C4 >= 128, C4 =< 191 ->
tokenize_string(B, ?ADV_COL(S, 4), [C4, C3, C2, C1 | Acc]);
_ ->
throw(invalid_utf8)
end.
tokenize_number(B, S) ->
case tokenize_number(B, sign, S, []) of
{{int, Int}, S1} ->
{{const, list_to_integer(Int)}, S1};
{{float, Float}, S1} ->
{{const, list_to_float(Float)}, S1}
end.
tokenize_number(B, sign, S=#decoder{offset=O}, []) ->
case B of
<<_:O/binary, $-, _/binary>> ->
tokenize_number(B, int, ?INC_COL(S), [$-]);
_ ->
tokenize_number(B, int, S, [])
end;
tokenize_number(B, int, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, $0, _/binary>> ->
tokenize_number(B, frac, ?INC_COL(S), [$0 | Acc]);
<<_:O/binary, C, _/binary>> when C >= $1 andalso C =< $9 ->
tokenize_number(B, int1, ?INC_COL(S), [C | Acc])
end;
tokenize_number(B, int1, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
tokenize_number(B, int1, ?INC_COL(S), [C | Acc]);
_ ->
tokenize_number(B, frac, S, Acc)
end;
tokenize_number(B, frac, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, $., C, _/binary>> when C >= $0, C =< $9 ->
tokenize_number(B, frac1, ?ADV_COL(S, 2), [C, $. | Acc]);
<<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E ->
tokenize_number(B, esign, ?INC_COL(S), [$e, $0, $. | Acc]);
_ ->
{{int, lists:reverse(Acc)}, S}
end;
tokenize_number(B, frac1, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
tokenize_number(B, frac1, ?INC_COL(S), [C | Acc]);
<<_:O/binary, E, _/binary>> when E =:= $e orelse E =:= $E ->
tokenize_number(B, esign, ?INC_COL(S), [$e | Acc]);
_ ->
{{float, lists:reverse(Acc)}, S}
end;
tokenize_number(B, esign, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C =:= $- orelse C=:= $+ ->
tokenize_number(B, eint, ?INC_COL(S), [C | Acc]);
_ ->
tokenize_number(B, eint, S, Acc)
end;
tokenize_number(B, eint, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
tokenize_number(B, eint1, ?INC_COL(S), [C | Acc])
end;
tokenize_number(B, eint1, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary, C, _/binary>> when C >= $0 andalso C =< $9 ->
tokenize_number(B, eint1, ?INC_COL(S), [C | Acc]);
_ ->
{{float, lists:reverse(Acc)}, S}
end.
tokenize(B, S=#decoder{offset=O}) ->
case B of
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
tokenize(B, ?INC_CHAR(S, C));
<<_:O/binary, "{", _/binary>> ->
{start_object, ?INC_COL(S)};
<<_:O/binary, "}", _/binary>> ->
{end_object, ?INC_COL(S)};
<<_:O/binary, "[", _/binary>> ->
{start_array, ?INC_COL(S)};
<<_:O/binary, "]", _/binary>> ->
{end_array, ?INC_COL(S)};
<<_:O/binary, ",", _/binary>> ->
{comma, ?INC_COL(S)};
<<_:O/binary, ":", _/binary>> ->
{colon, ?INC_COL(S)};
<<_:O/binary, "null", _/binary>> ->
{{const, null}, ?ADV_COL(S, 4)};
<<_:O/binary, "true", _/binary>> ->
{{const, true}, ?ADV_COL(S, 4)};
<<_:O/binary, "false", _/binary>> ->
{{const, false}, ?ADV_COL(S, 5)};
<<_:O/binary, "\"", _/binary>> ->
tokenize_string(B, ?INC_COL(S));
<<_:O/binary, C, _/binary>> when (C >= $0 andalso C =< $9)
orelse C =:= $- ->
tokenize_number(B, S);
<<_:O/binary>> ->
trim = S#decoder.state,
{eof, S}
end.
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
Create an object from a list of Key / Value pairs .
obj_new() ->
{struct, []}.
is_obj({struct, Props}) ->
F = fun ({K, _}) when is_binary(K) -> true end,
lists:all(F, Props).
obj_from_list(Props) ->
Obj = {struct, Props},
?assert(is_obj(Obj)),
Obj.
Test for equivalence of Erlang terms .
compare unequal as erlang terms , so we need to carefully recurse
equiv({struct, Props1}, {struct, Props2}) ->
equiv_object(Props1, Props2);
equiv(L1, L2) when is_list(L1), is_list(L2) ->
equiv_list(L1, L2);
equiv(N1, N2) when is_number(N1), is_number(N2) -> N1 == N2;
equiv(B1, B2) when is_binary(B1), is_binary(B2) -> B1 == B2;
equiv(A, A) when A =:= true orelse A =:= false orelse A =:= null -> true.
equiv_object(Props1, Props2) ->
L1 = lists:keysort(1, Props1),
L2 = lists:keysort(1, Props2),
Pairs = lists:zip(L1, L2),
true = lists:all(fun({{K1, V1}, {K2, V2}}) ->
equiv(K1, K2) and equiv(V1, V2)
end, Pairs).
equiv_list([], []) ->
true;
equiv_list([V1 | L1], [V2 | L2]) ->
equiv(V1, V2) andalso equiv_list(L1, L2).
decode_test() ->
[1199344435545.0, 1] = decode(<<"[1199344435545.0,1]">>),
<<16#F0,16#9D,16#9C,16#95>> = decode([34,"\\ud835","\\udf15",34]).
e2j_vec_test() ->
test_one(e2j_test_vec(utf8), 1).
test_one([], _N) ->
ok;
test_one([{E, J} | Rest], N) ->
true = equiv(E, decode(J)),
true = equiv(E, decode(encode(E))),
test_one(Rest, 1+N).
e2j_test_vec(utf8) ->
[
{1, "1"},
text representation may truncate , trail zeroes
{-1, "-1"},
{-3.1416, "-3.14160"},
{12.0e10, "1.20000e+11"},
{1.234E+10, "1.23400e+10"},
{-1.234E-10, "-1.23400e-10"},
{10.0, "1.0e+01"},
{123.456, "1.23456E+2"},
{10.0, "1e1"},
{<<"foo">>, "\"foo\""},
{<<"foo", 5, "bar">>, "\"foo\\u0005bar\""},
{<<"">>, "\"\""},
{<<"\n\n\n">>, "\"\\n\\n\\n\""},
{<<"\" \b\f\r\n\t\"">>, "\"\\\" \\b\\f\\r\\n\\t\\\"\""},
{obj_new(), "{}"},
{obj_from_list([{<<"foo">>, <<"bar">>}]), "{\"foo\":\"bar\"}"},
{obj_from_list([{<<"foo">>, <<"bar">>}, {<<"baz">>, 123}]),
"{\"foo\":\"bar\",\"baz\":123}"},
{[], "[]"},
{[[]], "[[]]"},
{[1, <<"foo">>], "[1,\"foo\"]"},
{obj_from_list([{<<"foo">>, [123]}]),
"{\"foo\":[123]}"},
{obj_from_list([{<<"foo">>, obj_from_list([{<<"bar">>, true}])}]),
"{\"foo\":{\"bar\":true}}"},
{obj_from_list([{<<"foo">>, []},
{<<"bar">>, obj_from_list([{<<"baz">>, true}])},
{<<"alice">>, <<"bob">>}]),
"{\"foo\":[],\"bar\":{\"baz\":true},\"alice\":\"bob\"}"},
{[-123, <<"foo">>, obj_from_list([{<<"bar">>, []}]), null],
"[-123,\"foo\",{\"bar\":[]},null]"}
].
encoder_utf8_test() ->
[34,"\\u0001","\\u0442","\\u0435","\\u0441","\\u0442",34] =
encode(<<1,"\321\202\320\265\321\201\321\202">>),
Enc = mochijson2:encoder([{utf8, true}]),
[34,"\\u0001",[209,130],[208,181],[209,129],[209,130],34] =
Enc(<<1,"\321\202\320\265\321\201\321\202">>).
input_validation_test() ->
Good = [
],
lists:foreach(fun({CodePoint, UTF8}) ->
Expect = list_to_binary(xmerl_ucs:to_utf8(CodePoint)),
Expect = decode(UTF8)
end, Good),
Bad = [
2nd , 3rd , or 4th byte of a multi - byte sequence w/o leading byte
<<?Q, 16#80, ?Q>>,
missing continuations , last byte in each should be 80 - BF
<<?Q, 16#C2, 16#7F, ?Q>>,
<<?Q, 16#E0, 16#80,16#7F, ?Q>>,
<<?Q, 16#F0, 16#80, 16#80, 16#7F, ?Q>>,
<<?Q, 16#F5, 16#80, 16#80, 16#80, ?Q>>,
<<?Q, $\\, $\n, 16#80, ?Q>>
],
lists:foreach(
fun(X) ->
ok = try decode(X) catch invalid_utf8 -> ok end,
could be { } } or
{'EXIT', _} = (catch encode(X))
end, Bad).
inline_json_test() ->
?assertEqual(<<"\"iodata iodata\"">>,
iolist_to_binary(
encode({json, [<<"\"iodata">>, " iodata\""]}))),
?assertEqual({struct, [{<<"key">>, <<"iodata iodata">>}]},
decode(
encode({struct,
[{key, {json, [<<"\"iodata">>, " iodata\""]}}]}))),
ok.
big_unicode_test() ->
UTF8Seq = list_to_binary(xmerl_ucs:to_utf8(16#0001d120)),
?assertEqual(
<<"\"\\ud834\\udd20\"">>,
iolist_to_binary(encode(UTF8Seq))),
?assertEqual(
UTF8Seq,
decode(iolist_to_binary(encode(UTF8Seq)))),
ok.
custom_decoder_test() ->
?assertEqual(
{struct, [{<<"key">>, <<"value">>}]},
(decoder([]))("{\"key\": \"value\"}")),
F = fun ({struct, [{<<"key">>, <<"value">>}]}) -> win end,
?assertEqual(
win,
(decoder([{object_hook, F}]))("{\"key\": \"value\"}")),
ok.
atom_test() ->
[begin
?assertEqual(A, decode(atom_to_list(A))),
?assertEqual(iolist_to_binary(atom_to_list(A)),
iolist_to_binary(encode(A)))
end || A <- [true, false, null]],
?assertEqual(
<<"\"foo\"">>,
iolist_to_binary(encode(foo))),
?assertEqual(
<<"\"\\ud834\\udd20\"">>,
iolist_to_binary(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))),
ok.
key_encode_test() ->
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode({struct, [{foo, 1}]}))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode({struct, [{<<"foo">>, 1}]}))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode({struct, [{"foo", 1}]}))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode([{foo, 1}]))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode([{<<"foo">>, 1}]))),
?assertEqual(
<<"{\"foo\":1}">>,
iolist_to_binary(encode([{"foo", 1}]))),
?assertEqual(
<<"{\"\\ud834\\udd20\":1}">>,
iolist_to_binary(
encode({struct, [{[16#0001d120], 1}]}))),
?assertEqual(
<<"{\"1\":1}">>,
iolist_to_binary(encode({struct, [{1, 1}]}))),
ok.
unsafe_chars_test() ->
Chars = "\"\\\b\f\n\r\t",
[begin
?assertEqual(false, json_string_is_safe([C])),
?assertEqual(false, json_bin_is_safe(<<C>>)),
?assertEqual(<<C>>, decode(encode(<<C>>)))
end || C <- Chars],
?assertEqual(
false,
json_string_is_safe([16#0001d120])),
?assertEqual(
false,
json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8(16#0001d120)))),
?assertEqual(
[16#0001d120],
xmerl_ucs:from_utf8(
binary_to_list(
decode(encode(list_to_atom(xmerl_ucs:to_utf8(16#0001d120))))))),
?assertEqual(
false,
json_string_is_safe([16#110000])),
?assertEqual(
false,
json_bin_is_safe(list_to_binary(xmerl_ucs:to_utf8([16#110000])))),
?assertEqual(
<<"/">>,
decode(<<"\"\\/\"">>)),
ok.
int_test() ->
?assertEqual(0, decode("0")),
?assertEqual(1, decode("1")),
?assertEqual(11, decode("11")),
ok.
large_int_test() ->
?assertEqual(<<"-2147483649214748364921474836492147483649">>,
iolist_to_binary(encode(-2147483649214748364921474836492147483649))),
?assertEqual(<<"2147483649214748364921474836492147483649">>,
iolist_to_binary(encode(2147483649214748364921474836492147483649))),
ok.
float_test() ->
?assertEqual(<<"-2147483649.0">>, iolist_to_binary(encode(-2147483649.0))),
?assertEqual(<<"2147483648.0">>, iolist_to_binary(encode(2147483648.0))),
ok.
handler_test() ->
?assertEqual(
{'EXIT',{json_encode,{bad_term,{}}}},
catch encode({})),
F = fun ({}) -> [] end,
?assertEqual(
<<"[]">>,
iolist_to_binary((encoder([{handler, F}]))({}))),
ok.
-endif.
|
41d0e82b0d034781bca27e19ea57e4294751eb516e2137399b6ea4b72adcab4e | dvingo/my-clj-utils | crux_pull.clj | (ns dv.crux-pull
(:require
[dv.crux-util :as cu]
[crux.api :as crux]
;[dv.crux-node :refer [crux-node]]
[datascript.pull-parser :as dpp]
[taoensso.timbre :as log])
(:import [datascript.pull_parser PullSpec]))
(def --log false)
(defmacro log
[& args]
(when --log `(log/info ~@args)))
(defn- into!
[transient-coll items]
(reduce conj! transient-coll items))
(def ^:private ^:const +default-limit+ 1000)
(defn- initial-frame
[pattern eids multi?]
{:state :pattern
:pattern pattern
:wildcard? (:wildcard? pattern)
:specs (-> pattern :attrs seq)
:results (transient [])
:kvps (transient {})
:eids eids
:multi? multi?
:recursion {:depth {} :seen #{}}})
(defn- subpattern-frame
[pattern eids multi? attr]
(assoc (initial-frame pattern eids multi?) :attr attr))
(defn- reset-frame
[frame eids kvps]
(let [pattern (:pattern frame)]
(assoc frame
:eids eids
:specs (seq (:attrs pattern))
:wildcard? (:wildcard? pattern)
:kvps (transient {})
:results (cond-> (:results frame)
(seq kvps) (conj! kvps)))))
(defn- push-recursion
[rec attr eid]
(let [{:keys [depth seen]} rec]
(assoc rec
:depth (update depth attr (fnil inc 0))
:seen (conj seen eid))))
(defn- seen-eid?
[frame eid]
(-> frame
(get-in [:recursion :seen] #{})
(contains? eid)))
(defn- pull-seen-eid
[frame frames eid]
(when (seen-eid? frame eid)
(conj frames (update frame :results conj! {:db/id eid}))))
(defn- single-frame-result
[key frame]
(some-> (:kvps frame) persistent! (get key)))
(defn- recursion-result [frame]
(single-frame-result ::recursion frame))
(defn- recursion-frame
[parent eid]
(let [attr (:attr parent)
rec (push-recursion (:recursion parent) attr eid)]
(assoc (subpattern-frame (:pattern parent) [eid] false ::recursion)
:recursion rec)))
(defn- pull-recursion-frame
[_ [frame & frames]]
(log "pull-recursion-frame")
(if-let [eids (seq (:eids frame))]
(do (log "eids are: " eids)
(let [frame (reset-frame frame (rest eids) (recursion-result frame))
eid (first eids)]
(or (pull-seen-eid frame frames eid)
(conj frames frame (recursion-frame frame eid)))))
(let [kvps (recursion-result frame)
results (cond-> (:results frame)
(seq kvps) (conj! kvps))]
(conj frames (assoc frame :state :done :results results)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; uses db
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- recurse-attr
[db attr multi? eids eid parent frames]
(log "recurse-attr")
(let [{:keys [recursion pattern]} parent
depth (-> recursion (get :depth) (get attr 0))]
(if (-> pattern :attrs (get attr) :recursion (= depth))
(conj frames parent)
(pull-recursion-frame
db
(conj frames parent
{:state :recursion :pattern pattern
:attr attr :multi? multi? :eids eids
:recursion recursion
:results (transient [])})))))
(let [pattern (PullSpec. true {})]
(defn- expand-frame
[parent eid attr-key multi? eids]
(let [rec (push-recursion (:recursion parent) attr-key eid)]
(-> pattern
(subpattern-frame eids multi? attr-key)
(assoc :recursion rec)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; uses db
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pull-attr-datoms
[db attr-key attr eid forward? datoms opts [parent & frames]]
(log "pull-attr-datoms datoms: " datoms " opts: " opts)
(let [limit (get opts :limit +default-limit+)
attr-key (or (:as opts) attr-key)
found (not-empty
(cond->> (if (coll? datoms) datoms [datoms])
limit (into [] (take limit))
true (filterv some?)))]
(if found
(let [component? (:subpattern opts)
multi? (coll? datoms)
datom-val (if forward?
identity
identity
;(fn [d] (.-v ^Datom d))
;(fn [d] (.-e ^Datom d))
)]
(cond
(contains? opts :subpattern)
(->> (subpattern-frame (:subpattern opts)
(mapv #(cu/entity db %) found)
multi? attr-key)
(conj frames parent))
(contains? opts :recursion)
(recurse-attr db attr-key multi?
(mapv #(cu/entity db %) found)
eid parent frames)
(and component? forward?)
(->> found
(mapv datom-val)
(expand-frame parent eid attr-key multi?)
(conj frames parent))
:else
(let [single? (not multi?)]
(->> (cond-> (into [] (map datom-val) found)
single? first)
(update parent :kvps assoc! attr-key)
(conj frames)))))
;; missing attr value
(->> (cond-> parent
(contains? opts :default)
(update :kvps assoc! attr-key (:default opts)))
(conj frames)))))
(defn- pull-attr
[db spec eid frames]
(log "---------pull-attr " spec " eid: " eid)
(let [[attr-key opts] spec]
(if (= :db/id attr-key)
frames
(let [attr (:attr opts)
forward? (= attr-key attr)
results (if forward?
(attr-key eid)
;; todo reverse
(do
;(log "REVERSE: attr-key: " attr-key)
;(log "attr: " attr)
(let [p (cu/get-parent attr (:crux.db/id eid))]
#_(log "parent: " p)
p
)
))]
(pull-attr-datoms db attr-key attr eid forward? results opts frames)))))
(def ^:private filter-reverse-attrs
(filter (fn [[k v]] (not= k (:attr v)))))
(defn- expand-reverse-subpattern-frame
[parent eid rattrs]
(-> (:pattern parent)
(assoc :attrs rattrs :wildcard? false)
(subpattern-frame [eid] false ::expand-rev)))
;; kvps is a transient map
(defn- expand-result
[frames kvps]
(let [res
(->> kvps
(persistent!)
(update (first frames) :kvps into!)
(conj (rest frames)))
]
res))
(defn- pull-expand-reverse-frame
[db [frame & frames]]
(->> (or (single-frame-result ::expand-rev frame) {})
(into! (:expand-kvps frame))
(expand-result frames)))
(defn- pull-expand-frame
[db [frame & frames]]
(if-let [datoms-by-attr (seq (:datoms frame))]
(let [[attr datoms] (first datoms-by-attr)
opts (-> frame
(get-in [:pattern :attrs])
(get attr {}))]
(pull-attr-datoms db attr attr (:eid frame) true datoms opts
(conj frames (update frame :datoms rest))))
(if-let [rattrs (->> (get-in frame [:pattern :attrs])
(into {} filter-reverse-attrs)
not-empty)]
(let [frame (assoc frame
:state :expand-rev
:expand-kvps (:kvps frame)
:kvps (transient {}))]
(->> rattrs
(expand-reverse-subpattern-frame frame (:eid frame))
(conj frames frame)))
(expand-result frames (:kvps frame)))))
(defn- pull-wildcard-expand
[db frame frames eid pattern]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; uses db
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(let [datoms eid
{:keys [attr recursion]} frame
rec (cond-> recursion
(some? attr) (push-recursion attr eid))]
(->> {:state :expand
:kvps (transient {:db/id eid})
:eid eid
:pattern pattern
:datoms nil
:recursion rec}
(conj frames frame)
(pull-expand-frame db))))
(defn- pull-wildcard
[db frame frames]
(log "pull wildcard")
(let [{:keys [eid pattern]} frame]
(or (pull-seen-eid frame frames eid)
(pull-wildcard-expand db frame frames eid pattern))))
(defn- pull-pattern-frame
[db [frame & frames]]
(log "pull-pattern-frame " frame)
(if-let [eids (seq (:eids frame))]
(if (:wildcard? frame)
(pull-wildcard db
(assoc frame
:specs []
:eid (first eids)
:wildcard? false)
frames)
(if-let [specs (seq (:specs frame))]
(let [spec (first specs)
new-frames (conj frames (assoc frame :specs (rest specs)))]
(pull-attr db spec (first eids) new-frames))
(->> frame :kvps persistent! not-empty
(reset-frame frame (rest eids))
(conj frames)
(recur db))))
(conj frames (assoc frame :state :done))))
(defn- pull-pattern
[db frames]
(log "pull-pattern----------------------------------pulling frame with state: " (:state (first frames)))
(case (:state (first frames))
:expand (recur db (pull-expand-frame db frames))
:expand-rev (recur db (pull-expand-reverse-frame db frames))
:pattern (recur db (pull-pattern-frame db frames))
:recursion (recur db (pull-recursion-frame db frames))
:done (let [[f & remaining] frames
result (persistent! (:results f))
result (mapv #(if (contains? % :db/id)
(:db/id %) %) result)
result (cond-> result (not (:multi? f)) first)]
( log / info " \n\nDONE : result : " result )
(if (seq remaining)
(->> (cond-> (first remaining)
result (update :kvps assoc! (:attr f) result))
(conj (rest remaining))
(recur db))
result))))
(defn start-entity [db e]
(if (vector? e)
(cu/entity-with-prop db e)
(cu/entity db e)))
(defn pull-spec
[db pattern eids multi?]
(let [db (cond-> db (cu/crux-node? db) crux/db)
eids (into [] (map (partial start-entity db)) eids)]
(pull-pattern db (list (initial-frame pattern eids multi?)))))
(defn pull
"db: Crux node or db
selector: pull syntax selector
eid: starting entity id"
[db selector eid]
(pull-spec db (dpp/parse-pull selector) [eid] false))
(defn pull-many
"db: Crux node or db
selector: pull syntax selector
eids: starting entity ids"
[db selector eids]
(pull-spec db (dpp/parse-pull selector) eids true))
; (comment
( pull crux - node [: task / description ] : )
;
( dpp / parse - pull [: task / description ] )
( initial - frame ( dpp / parse - pull [: task / description ] ) [ { } ] false )
( subpattern - frame ( dpp / parse - pull [: task / description ] ) [ { } ] false : task / description )
( dpp / parse - pull [: task / description ] )
( dpp / parse - pull [ { : user / habits [: task / id : task / description ] } : user / id ] )
;
( pull crux - node [: name { : children 1 } ] : task-1 )
( pull crux - node [ [: name : as : other ] { [: children : limit 2 ] ' ... } ] : task-1 )
;
( crux / entity db : )
( pull crux - node [: user / id : user / password { : user / tasks [ ' * ] } ] : )
( pull crux - node [: user / id : user / password { : user / tasks [: task / description ] } ] : )
;
; (pull crux-node [[:user/id :as :hi]
{ [: user / habits : limit 1 ]
[ [: habit / schedule2 : default 10 ]
; {:habit/task [[:task/description :as :diff]]}]}]
; #uuid"8d5a0a66-e98f-43ff-8803-e411073d0880")
;
; (pull crux-node [[:user/id :as :hi]
{ : user / habits [ [: habit / schedule2 : default 10 ]
; {:habit/task [[:task/description :as :diff]]}]
} ] # uuid"8d5a0a66 - e98f-43ff-8803 - e411073d0880 " )
;
; (pull crux-node [:user/email :user/tasks] [:user/email ""])
( pull crux - node [: user / id [: user / id2 : default : hi ] ] # uuid"8d5a0a66 - e98f-43ff-8803 - e411073d0880 " )
; )
;(comment
; (cu/put-all
[ { : :1
; :task/id :1
: task / description " one "
: task / subtasks [ [: task / id : 2 ] [: task / id :3 ] ] }
{ : : 2
: task / id : 2
: task / description " two "
: task / subtasks [ [: task / id : 5 ] ] }
{ : crux.db/id :3 : task / id :3 : task / description " three "
: task / subtasks [ [: task / id : 4 ] ] }
{ : crux.db/id : 4
: task / id : 4 : task / description " four " }
{ : crux.db/id : 5 : task / id : 5 : task / description " five " } ] )
;
( pull crux - node [: task / id : task / description { : task/_subtasks ' ... } ] : 5 )
( pull crux - node [: task / id : task / description { : task/_subtasks 1 } ] : 5 )
; )
| null | https://raw.githubusercontent.com/dvingo/my-clj-utils/cccfe6419c088f9089836b6d9f2572dbf9d66a8a/src/main/dv/crux_pull.clj | clojure | [dv.crux-node :refer [crux-node]]
uses db
uses db
(fn [d] (.-v ^Datom d))
(fn [d] (.-e ^Datom d))
missing attr value
todo reverse
(log "REVERSE: attr-key: " attr-key)
(log "attr: " attr)
kvps is a transient map
uses db
(comment
(pull crux-node [[:user/id :as :hi]
{:habit/task [[:task/description :as :diff]]}]}]
#uuid"8d5a0a66-e98f-43ff-8803-e411073d0880")
(pull crux-node [[:user/id :as :hi]
{:habit/task [[:task/description :as :diff]]}]
(pull crux-node [:user/email :user/tasks] [:user/email ""])
)
(comment
(cu/put-all
:task/id :1
) | (ns dv.crux-pull
(:require
[dv.crux-util :as cu]
[crux.api :as crux]
[datascript.pull-parser :as dpp]
[taoensso.timbre :as log])
(:import [datascript.pull_parser PullSpec]))
(def --log false)
(defmacro log
[& args]
(when --log `(log/info ~@args)))
(defn- into!
[transient-coll items]
(reduce conj! transient-coll items))
(def ^:private ^:const +default-limit+ 1000)
(defn- initial-frame
[pattern eids multi?]
{:state :pattern
:pattern pattern
:wildcard? (:wildcard? pattern)
:specs (-> pattern :attrs seq)
:results (transient [])
:kvps (transient {})
:eids eids
:multi? multi?
:recursion {:depth {} :seen #{}}})
(defn- subpattern-frame
[pattern eids multi? attr]
(assoc (initial-frame pattern eids multi?) :attr attr))
(defn- reset-frame
[frame eids kvps]
(let [pattern (:pattern frame)]
(assoc frame
:eids eids
:specs (seq (:attrs pattern))
:wildcard? (:wildcard? pattern)
:kvps (transient {})
:results (cond-> (:results frame)
(seq kvps) (conj! kvps)))))
(defn- push-recursion
[rec attr eid]
(let [{:keys [depth seen]} rec]
(assoc rec
:depth (update depth attr (fnil inc 0))
:seen (conj seen eid))))
(defn- seen-eid?
[frame eid]
(-> frame
(get-in [:recursion :seen] #{})
(contains? eid)))
(defn- pull-seen-eid
[frame frames eid]
(when (seen-eid? frame eid)
(conj frames (update frame :results conj! {:db/id eid}))))
(defn- single-frame-result
[key frame]
(some-> (:kvps frame) persistent! (get key)))
(defn- recursion-result [frame]
(single-frame-result ::recursion frame))
(defn- recursion-frame
[parent eid]
(let [attr (:attr parent)
rec (push-recursion (:recursion parent) attr eid)]
(assoc (subpattern-frame (:pattern parent) [eid] false ::recursion)
:recursion rec)))
(defn- pull-recursion-frame
[_ [frame & frames]]
(log "pull-recursion-frame")
(if-let [eids (seq (:eids frame))]
(do (log "eids are: " eids)
(let [frame (reset-frame frame (rest eids) (recursion-result frame))
eid (first eids)]
(or (pull-seen-eid frame frames eid)
(conj frames frame (recursion-frame frame eid)))))
(let [kvps (recursion-result frame)
results (cond-> (:results frame)
(seq kvps) (conj! kvps))]
(conj frames (assoc frame :state :done :results results)))))
(defn- recurse-attr
[db attr multi? eids eid parent frames]
(log "recurse-attr")
(let [{:keys [recursion pattern]} parent
depth (-> recursion (get :depth) (get attr 0))]
(if (-> pattern :attrs (get attr) :recursion (= depth))
(conj frames parent)
(pull-recursion-frame
db
(conj frames parent
{:state :recursion :pattern pattern
:attr attr :multi? multi? :eids eids
:recursion recursion
:results (transient [])})))))
(let [pattern (PullSpec. true {})]
(defn- expand-frame
[parent eid attr-key multi? eids]
(let [rec (push-recursion (:recursion parent) attr-key eid)]
(-> pattern
(subpattern-frame eids multi? attr-key)
(assoc :recursion rec)))))
(defn- pull-attr-datoms
[db attr-key attr eid forward? datoms opts [parent & frames]]
(log "pull-attr-datoms datoms: " datoms " opts: " opts)
(let [limit (get opts :limit +default-limit+)
attr-key (or (:as opts) attr-key)
found (not-empty
(cond->> (if (coll? datoms) datoms [datoms])
limit (into [] (take limit))
true (filterv some?)))]
(if found
(let [component? (:subpattern opts)
multi? (coll? datoms)
datom-val (if forward?
identity
identity
)]
(cond
(contains? opts :subpattern)
(->> (subpattern-frame (:subpattern opts)
(mapv #(cu/entity db %) found)
multi? attr-key)
(conj frames parent))
(contains? opts :recursion)
(recurse-attr db attr-key multi?
(mapv #(cu/entity db %) found)
eid parent frames)
(and component? forward?)
(->> found
(mapv datom-val)
(expand-frame parent eid attr-key multi?)
(conj frames parent))
:else
(let [single? (not multi?)]
(->> (cond-> (into [] (map datom-val) found)
single? first)
(update parent :kvps assoc! attr-key)
(conj frames)))))
(->> (cond-> parent
(contains? opts :default)
(update :kvps assoc! attr-key (:default opts)))
(conj frames)))))
(defn- pull-attr
[db spec eid frames]
(log "---------pull-attr " spec " eid: " eid)
(let [[attr-key opts] spec]
(if (= :db/id attr-key)
frames
(let [attr (:attr opts)
forward? (= attr-key attr)
results (if forward?
(attr-key eid)
(do
(let [p (cu/get-parent attr (:crux.db/id eid))]
#_(log "parent: " p)
p
)
))]
(pull-attr-datoms db attr-key attr eid forward? results opts frames)))))
(def ^:private filter-reverse-attrs
(filter (fn [[k v]] (not= k (:attr v)))))
(defn- expand-reverse-subpattern-frame
[parent eid rattrs]
(-> (:pattern parent)
(assoc :attrs rattrs :wildcard? false)
(subpattern-frame [eid] false ::expand-rev)))
(defn- expand-result
[frames kvps]
(let [res
(->> kvps
(persistent!)
(update (first frames) :kvps into!)
(conj (rest frames)))
]
res))
(defn- pull-expand-reverse-frame
[db [frame & frames]]
(->> (or (single-frame-result ::expand-rev frame) {})
(into! (:expand-kvps frame))
(expand-result frames)))
(defn- pull-expand-frame
[db [frame & frames]]
(if-let [datoms-by-attr (seq (:datoms frame))]
(let [[attr datoms] (first datoms-by-attr)
opts (-> frame
(get-in [:pattern :attrs])
(get attr {}))]
(pull-attr-datoms db attr attr (:eid frame) true datoms opts
(conj frames (update frame :datoms rest))))
(if-let [rattrs (->> (get-in frame [:pattern :attrs])
(into {} filter-reverse-attrs)
not-empty)]
(let [frame (assoc frame
:state :expand-rev
:expand-kvps (:kvps frame)
:kvps (transient {}))]
(->> rattrs
(expand-reverse-subpattern-frame frame (:eid frame))
(conj frames frame)))
(expand-result frames (:kvps frame)))))
(defn- pull-wildcard-expand
[db frame frames eid pattern]
(let [datoms eid
{:keys [attr recursion]} frame
rec (cond-> recursion
(some? attr) (push-recursion attr eid))]
(->> {:state :expand
:kvps (transient {:db/id eid})
:eid eid
:pattern pattern
:datoms nil
:recursion rec}
(conj frames frame)
(pull-expand-frame db))))
(defn- pull-wildcard
[db frame frames]
(log "pull wildcard")
(let [{:keys [eid pattern]} frame]
(or (pull-seen-eid frame frames eid)
(pull-wildcard-expand db frame frames eid pattern))))
(defn- pull-pattern-frame
[db [frame & frames]]
(log "pull-pattern-frame " frame)
(if-let [eids (seq (:eids frame))]
(if (:wildcard? frame)
(pull-wildcard db
(assoc frame
:specs []
:eid (first eids)
:wildcard? false)
frames)
(if-let [specs (seq (:specs frame))]
(let [spec (first specs)
new-frames (conj frames (assoc frame :specs (rest specs)))]
(pull-attr db spec (first eids) new-frames))
(->> frame :kvps persistent! not-empty
(reset-frame frame (rest eids))
(conj frames)
(recur db))))
(conj frames (assoc frame :state :done))))
(defn- pull-pattern
[db frames]
(log "pull-pattern----------------------------------pulling frame with state: " (:state (first frames)))
(case (:state (first frames))
:expand (recur db (pull-expand-frame db frames))
:expand-rev (recur db (pull-expand-reverse-frame db frames))
:pattern (recur db (pull-pattern-frame db frames))
:recursion (recur db (pull-recursion-frame db frames))
:done (let [[f & remaining] frames
result (persistent! (:results f))
result (mapv #(if (contains? % :db/id)
(:db/id %) %) result)
result (cond-> result (not (:multi? f)) first)]
( log / info " \n\nDONE : result : " result )
(if (seq remaining)
(->> (cond-> (first remaining)
result (update :kvps assoc! (:attr f) result))
(conj (rest remaining))
(recur db))
result))))
(defn start-entity [db e]
(if (vector? e)
(cu/entity-with-prop db e)
(cu/entity db e)))
(defn pull-spec
[db pattern eids multi?]
(let [db (cond-> db (cu/crux-node? db) crux/db)
eids (into [] (map (partial start-entity db)) eids)]
(pull-pattern db (list (initial-frame pattern eids multi?)))))
(defn pull
"db: Crux node or db
selector: pull syntax selector
eid: starting entity id"
[db selector eid]
(pull-spec db (dpp/parse-pull selector) [eid] false))
(defn pull-many
"db: Crux node or db
selector: pull syntax selector
eids: starting entity ids"
[db selector eids]
(pull-spec db (dpp/parse-pull selector) eids true))
( pull crux - node [: task / description ] : )
( dpp / parse - pull [: task / description ] )
( initial - frame ( dpp / parse - pull [: task / description ] ) [ { } ] false )
( subpattern - frame ( dpp / parse - pull [: task / description ] ) [ { } ] false : task / description )
( dpp / parse - pull [: task / description ] )
( dpp / parse - pull [ { : user / habits [: task / id : task / description ] } : user / id ] )
( pull crux - node [: name { : children 1 } ] : task-1 )
( pull crux - node [ [: name : as : other ] { [: children : limit 2 ] ' ... } ] : task-1 )
( crux / entity db : )
( pull crux - node [: user / id : user / password { : user / tasks [ ' * ] } ] : )
( pull crux - node [: user / id : user / password { : user / tasks [: task / description ] } ] : )
{ [: user / habits : limit 1 ]
[ [: habit / schedule2 : default 10 ]
{ : user / habits [ [: habit / schedule2 : default 10 ]
} ] # uuid"8d5a0a66 - e98f-43ff-8803 - e411073d0880 " )
( pull crux - node [: user / id [: user / id2 : default : hi ] ] # uuid"8d5a0a66 - e98f-43ff-8803 - e411073d0880 " )
[ { : :1
: task / description " one "
: task / subtasks [ [: task / id : 2 ] [: task / id :3 ] ] }
{ : : 2
: task / id : 2
: task / description " two "
: task / subtasks [ [: task / id : 5 ] ] }
{ : crux.db/id :3 : task / id :3 : task / description " three "
: task / subtasks [ [: task / id : 4 ] ] }
{ : crux.db/id : 4
: task / id : 4 : task / description " four " }
{ : crux.db/id : 5 : task / id : 5 : task / description " five " } ] )
( pull crux - node [: task / id : task / description { : task/_subtasks ' ... } ] : 5 )
( pull crux - node [: task / id : task / description { : task/_subtasks 1 } ] : 5 )
|
d22954e6232e40435ffc976c5f54987c34343e1f4f713b3addd6ae492cba46f3 | andorp/bead | RequestParams.hs | module Bead.View.RequestParams where
import Control.Monad (join)
import Data.String (IsString(..))
import Bead.Domain.Entities (Username(..))
import Bead.Domain.Relationships
import Bead.View.Dictionary (Language, languageCata)
import Bead.View.Fay.HookIds
import Bead.View.TemplateAndComponentNames
-- Request Parameter Name Constants
assignmentKeyParamName :: IsString s => s
assignmentKeyParamName = fromString $ fieldName assignmentKeyField
assessmentKeyParamName :: IsString s => s
assessmentKeyParamName = fromString $ fieldName assessmentKeyField
submissionKeyParamName :: IsString s => s
submissionKeyParamName = fromString $ fieldName submissionKeyField
scoreKeyParamName :: IsString s => s
scoreKeyParamName = fromString $ fieldName scoreKeyField
evaluationKeyParamName :: IsString s => s
evaluationKeyParamName = fromString $ fieldName evaluationKeyField
languageParamName :: IsString s => s
languageParamName = fromString $ fieldName changeLanguageField
courseKeyParamName :: IsString s => s
courseKeyParamName = fromString $ fieldName courseKeyField
groupKeyParamName :: IsString s => s
groupKeyParamName = fromString $ fieldName groupKeyField
testScriptKeyParamName :: IsString s => s
testScriptKeyParamName = fromString $ fieldName testScriptKeyField
Request is a Pair of Strings , which
-- are key and value representing a parameter in
-- the GET or POST http request
newtype ReqParam = ReqParam (String,String)
-- Produces a string representing the key value pair
E.g : ReqParam ( " name " , " rika " ) = " name "
queryStringParam :: ReqParam -> String
queryStringParam (ReqParam (k,v)) = join [k, "=", v]
-- Values that can be converted into a request param,
-- only the value of the param is calculated
class ReqParamValue p where
paramValue :: (IsString s) => p -> s
-- Values that can be converted into request param,
-- the name and the value is also calculated
class (ReqParamValue r) => RequestParam r where
requestParam :: r -> ReqParam
instance ReqParamValue AssignmentKey where
paramValue (AssignmentKey a) = fromString a
instance RequestParam AssignmentKey where
requestParam a = ReqParam (assignmentKeyParamName, paramValue a)
instance ReqParamValue AssessmentKey where
paramValue (AssessmentKey a) = fromString a
instance RequestParam AssessmentKey where
requestParam a = ReqParam (assessmentKeyParamName, paramValue a)
instance ReqParamValue SubmissionKey where
paramValue (SubmissionKey s) = fromString s
instance RequestParam SubmissionKey where
requestParam s = ReqParam (submissionKeyParamName, paramValue s)
instance ReqParamValue ScoreKey where
paramValue (ScoreKey s) = fromString s
instance RequestParam ScoreKey where
requestParam s = ReqParam (scoreKeyParamName, paramValue s)
instance ReqParamValue GroupKey where
paramValue (GroupKey g) = fromString g
instance RequestParam GroupKey where
requestParam g = ReqParam (groupKeyParamName, paramValue g)
instance ReqParamValue TestScriptKey where
paramValue (TestScriptKey t) = fromString t
instance RequestParam TestScriptKey where
requestParam t = ReqParam (testScriptKeyParamName, paramValue t)
instance ReqParamValue CourseKey where
paramValue (CourseKey c) = fromString c
instance RequestParam CourseKey where
requestParam g = ReqParam (courseKeyParamName, paramValue g)
instance ReqParamValue EvaluationKey where
paramValue (EvaluationKey e) = fromString e
instance RequestParam EvaluationKey where
requestParam e = ReqParam (evaluationKeyParamName, paramValue e)
instance ReqParamValue Username where
paramValue (Username u) = fromString u
instance RequestParam Username where
requestParam u = ReqParam (fieldName usernameField, paramValue u)
instance ReqParamValue Language where
paramValue = languageCata fromString
instance RequestParam Language where
requestParam l = ReqParam (languageParamName, paramValue l)
| null | https://raw.githubusercontent.com/andorp/bead/280dc9c3d5cfe1b9aac0f2f802c705ae65f02ac2/src/Bead/View/RequestParams.hs | haskell | Request Parameter Name Constants
are key and value representing a parameter in
the GET or POST http request
Produces a string representing the key value pair
Values that can be converted into a request param,
only the value of the param is calculated
Values that can be converted into request param,
the name and the value is also calculated | module Bead.View.RequestParams where
import Control.Monad (join)
import Data.String (IsString(..))
import Bead.Domain.Entities (Username(..))
import Bead.Domain.Relationships
import Bead.View.Dictionary (Language, languageCata)
import Bead.View.Fay.HookIds
import Bead.View.TemplateAndComponentNames
assignmentKeyParamName :: IsString s => s
assignmentKeyParamName = fromString $ fieldName assignmentKeyField
assessmentKeyParamName :: IsString s => s
assessmentKeyParamName = fromString $ fieldName assessmentKeyField
submissionKeyParamName :: IsString s => s
submissionKeyParamName = fromString $ fieldName submissionKeyField
scoreKeyParamName :: IsString s => s
scoreKeyParamName = fromString $ fieldName scoreKeyField
evaluationKeyParamName :: IsString s => s
evaluationKeyParamName = fromString $ fieldName evaluationKeyField
languageParamName :: IsString s => s
languageParamName = fromString $ fieldName changeLanguageField
courseKeyParamName :: IsString s => s
courseKeyParamName = fromString $ fieldName courseKeyField
groupKeyParamName :: IsString s => s
groupKeyParamName = fromString $ fieldName groupKeyField
testScriptKeyParamName :: IsString s => s
testScriptKeyParamName = fromString $ fieldName testScriptKeyField
Request is a Pair of Strings , which
newtype ReqParam = ReqParam (String,String)
E.g : ReqParam ( " name " , " rika " ) = " name "
queryStringParam :: ReqParam -> String
queryStringParam (ReqParam (k,v)) = join [k, "=", v]
class ReqParamValue p where
paramValue :: (IsString s) => p -> s
class (ReqParamValue r) => RequestParam r where
requestParam :: r -> ReqParam
instance ReqParamValue AssignmentKey where
paramValue (AssignmentKey a) = fromString a
instance RequestParam AssignmentKey where
requestParam a = ReqParam (assignmentKeyParamName, paramValue a)
instance ReqParamValue AssessmentKey where
paramValue (AssessmentKey a) = fromString a
instance RequestParam AssessmentKey where
requestParam a = ReqParam (assessmentKeyParamName, paramValue a)
instance ReqParamValue SubmissionKey where
paramValue (SubmissionKey s) = fromString s
instance RequestParam SubmissionKey where
requestParam s = ReqParam (submissionKeyParamName, paramValue s)
instance ReqParamValue ScoreKey where
paramValue (ScoreKey s) = fromString s
instance RequestParam ScoreKey where
requestParam s = ReqParam (scoreKeyParamName, paramValue s)
instance ReqParamValue GroupKey where
paramValue (GroupKey g) = fromString g
instance RequestParam GroupKey where
requestParam g = ReqParam (groupKeyParamName, paramValue g)
instance ReqParamValue TestScriptKey where
paramValue (TestScriptKey t) = fromString t
instance RequestParam TestScriptKey where
requestParam t = ReqParam (testScriptKeyParamName, paramValue t)
instance ReqParamValue CourseKey where
paramValue (CourseKey c) = fromString c
instance RequestParam CourseKey where
requestParam g = ReqParam (courseKeyParamName, paramValue g)
instance ReqParamValue EvaluationKey where
paramValue (EvaluationKey e) = fromString e
instance RequestParam EvaluationKey where
requestParam e = ReqParam (evaluationKeyParamName, paramValue e)
instance ReqParamValue Username where
paramValue (Username u) = fromString u
instance RequestParam Username where
requestParam u = ReqParam (fieldName usernameField, paramValue u)
instance ReqParamValue Language where
paramValue = languageCata fromString
instance RequestParam Language where
requestParam l = ReqParam (languageParamName, paramValue l)
|
757558947d7a7d74a4bbaf167d4a57f0bc92087e2eeb3ee2ae53d6934124fddf | chaoxu/fancy-walks | A.hs | {-# OPTIONS_GHC -O2 #-}
# LANGUAGE TupleSections #
import Data.List
import Data.Maybe
import Data.Char
import Data.Array
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)
import qualified Data.Sequence as Seq
import Data.Tree
import Data.Graph
parseInput = do
cas <- readInt
replicateM cas $ do
n <- readInt
replicateM n $ (\x -> (readRational x, x)) . BS.unpack <$> readString
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readRational str = read (filter isDigit str) % 10^(length str - dotplace - 1)
where
dotplace = fromMaybe (length str - 1) $ elemIndex '.' str
main = do
input <- evalState parseInput <$> BS.getContents
forM_ (zip [1..] input) $ \(cas, a) -> do
putStrLn $ "Case #" ++ show cas ++ ":"
forM_ (solve a) putStrLn
getTimes :: Rational -> State (Map Rational Int) Int
getTimes a = do
map <- get
if Map.member a map
then return (map Map.! a)
else do
modify $ Map.insert a maxBound
r <- if c == 1 then return 0 else (\x -> if x == maxBound then x else x+1) <$> getTimes d
modify $ Map.insert a r
return r
where
(c, d) = properFraction (a * 3)
solve :: [(Rational,String)] -> [String]
solve a = map snd $ sort a'
where
monads = foldM (\xs (v,s) -> (:xs).(,s).(,v) <$> getTimes v) [] a
a' = evalState monads Map.empty
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/code.google.com/codejam/Code%20Jam%20Africa%20and%20Arabia%202011/Online%20Competition/A.hs | haskell | # OPTIONS_GHC -O2 # | # LANGUAGE TupleSections #
import Data.List
import Data.Maybe
import Data.Char
import Data.Array
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)
import qualified Data.Sequence as Seq
import Data.Tree
import Data.Graph
parseInput = do
cas <- readInt
replicateM cas $ do
n <- readInt
replicateM n $ (\x -> (readRational x, x)) . BS.unpack <$> readString
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readRational str = read (filter isDigit str) % 10^(length str - dotplace - 1)
where
dotplace = fromMaybe (length str - 1) $ elemIndex '.' str
main = do
input <- evalState parseInput <$> BS.getContents
forM_ (zip [1..] input) $ \(cas, a) -> do
putStrLn $ "Case #" ++ show cas ++ ":"
forM_ (solve a) putStrLn
getTimes :: Rational -> State (Map Rational Int) Int
getTimes a = do
map <- get
if Map.member a map
then return (map Map.! a)
else do
modify $ Map.insert a maxBound
r <- if c == 1 then return 0 else (\x -> if x == maxBound then x else x+1) <$> getTimes d
modify $ Map.insert a r
return r
where
(c, d) = properFraction (a * 3)
solve :: [(Rational,String)] -> [String]
solve a = map snd $ sort a'
where
monads = foldM (\xs (v,s) -> (:xs).(,s).(,v) <$> getTimes v) [] a
a' = evalState monads Map.empty
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.