_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
470edec2e95a273b2fec16d21933e532a45d469dc19cfeb6fedecc69617e2633
input-output-hk/cardano-shell
DaedalusIPCSpec.hs
module DaedalusIPCSpec ( spec ) where import Cardano.Prelude import Test.Hspec (Spec, describe, it, pending) spec :: Spec spec = describe "DaedalusIPC" $ do it "should reply with the port when asked" $ do pending --spec = describe "DaedalusIPC" $ do -- it "should reply with the port when asked" $ do let port = 42 : : Int -- let testScript = "test/js/mock-daedalus.js" -- (_, _, _, ph) <- createProcess (proc "node" [testScript, show port]) waitForProcess ph ` shouldReturn ` ExitSuccess
null
https://raw.githubusercontent.com/input-output-hk/cardano-shell/8e0d6f5548c1c13a9edfeb56e4ea27c0a6d10948/cardano-shell/test/DaedalusIPCSpec.hs
haskell
spec = describe "DaedalusIPC" $ do it "should reply with the port when asked" $ do let testScript = "test/js/mock-daedalus.js" (_, _, _, ph) <- createProcess (proc "node" [testScript, show port])
module DaedalusIPCSpec ( spec ) where import Cardano.Prelude import Test.Hspec (Spec, describe, it, pending) spec :: Spec spec = describe "DaedalusIPC" $ do it "should reply with the port when asked" $ do pending let port = 42 : : Int waitForProcess ph ` shouldReturn ` ExitSuccess
db8edec34faf1b79fb65a94cb204816b7af2d960c75d1b9534dbd71af5ed6f1d
racket/gui
info.rkt
#lang info (define test-responsibles '((all robby)))
null
https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-test/framework/info.rkt
racket
#lang info (define test-responsibles '((all robby)))
e45679560340665260c9da9c0048da44ef3b9fcb9b9e298573a9e9f7579e04e7
retro/keechma-next-realworld-app
comment_form.cljs
(ns app.controllers.user.comment-form (:require [keechma.next.controller :as ctrl] [keechma.next.controllers.pipelines :as pipelines] [keechma.pipelines.core :as pp :refer-macros [pipeline!]] [keechma.next.controllers.form :as form] [keechma.next.controllers.entitydb :as edb] [keechma.next.controllers.router :as router] [app.api :as api] [promesa.core :as p] [app.validators :as v] [promesa.core :as p])) (derive :user/comment-form ::pipelines/controller) (def pipelines {:keechma.form/submit-data (pipeline! [value {:keys [deps-state* meta-state*] :as ctrl}] (let [jwt (:jwt @deps-state*) slug (:keechma.controller/params ctrl)] (api/comment-create {:jwt jwt :article-slug slug :comment (select-keys value [:body])})) (ctrl/broadcast ctrl :comment/created value) (pp/swap! meta-state* form/mount-form {}))}) (defmethod ctrl/prep :user/comment-form [ctrl] (pipelines/register ctrl (form/wrap pipelines (v/to-validator {:body [:not-empty]}))))
null
https://raw.githubusercontent.com/retro/keechma-next-realworld-app/47a14f4f3f6d56be229cd82f7806d7397e559ebe/src/app/controllers/user/comment_form.cljs
clojure
(ns app.controllers.user.comment-form (:require [keechma.next.controller :as ctrl] [keechma.next.controllers.pipelines :as pipelines] [keechma.pipelines.core :as pp :refer-macros [pipeline!]] [keechma.next.controllers.form :as form] [keechma.next.controllers.entitydb :as edb] [keechma.next.controllers.router :as router] [app.api :as api] [promesa.core :as p] [app.validators :as v] [promesa.core :as p])) (derive :user/comment-form ::pipelines/controller) (def pipelines {:keechma.form/submit-data (pipeline! [value {:keys [deps-state* meta-state*] :as ctrl}] (let [jwt (:jwt @deps-state*) slug (:keechma.controller/params ctrl)] (api/comment-create {:jwt jwt :article-slug slug :comment (select-keys value [:body])})) (ctrl/broadcast ctrl :comment/created value) (pp/swap! meta-state* form/mount-form {}))}) (defmethod ctrl/prep :user/comment-form [ctrl] (pipelines/register ctrl (form/wrap pipelines (v/to-validator {:body [:not-empty]}))))
afadfc1f7943f97146af8cb5bee53e3802b86dc7a52adf7ac726d215afd9903b
intermine/bluegenes
auth.cljs
(ns bluegenes.subs.auth (:require [re-frame.core :refer [reg-sub]])) (reg-sub ::auth :<- [:current-mine] (fn [current-mine] (:auth current-mine))) (reg-sub ::identity :<- [::auth] (fn [auth] (:identity auth))) (reg-sub ::superuser? :<- [::identity] (fn [identity] (:superuser identity))) (reg-sub ::authenticated? :<- [::identity] (fn [identity] (some? (not-empty identity)))) (reg-sub ::email :<- [::identity] (fn [identity] ;; Set when using OAuth2, where username is just "GOOGLE:gibberish". (or (not-empty (get-in identity [:preferences :email])) (:username identity)))) (reg-sub ::oauth2? :<- [::identity] (fn [identity] (= (:login-method identity) :oauth2)))
null
https://raw.githubusercontent.com/intermine/bluegenes/417ea23b2d00fdca20ce4810bb2838326a09010e/src/cljs/bluegenes/subs/auth.cljs
clojure
Set when using OAuth2, where username is just "GOOGLE:gibberish".
(ns bluegenes.subs.auth (:require [re-frame.core :refer [reg-sub]])) (reg-sub ::auth :<- [:current-mine] (fn [current-mine] (:auth current-mine))) (reg-sub ::identity :<- [::auth] (fn [auth] (:identity auth))) (reg-sub ::superuser? :<- [::identity] (fn [identity] (:superuser identity))) (reg-sub ::authenticated? :<- [::identity] (fn [identity] (some? (not-empty identity)))) (reg-sub ::email :<- [::identity] (fn [identity] (or (not-empty (get-in identity [:preferences :email])) (:username identity)))) (reg-sub ::oauth2? :<- [::identity] (fn [identity] (= (:login-method identity) :oauth2)))
62c4b79ffeec95d6cefbe1f8f97e5c6ff2c14df3eb0a185b94cd9a67f80a03ad
sdiehl/picologic
Repl.hs
module Picologic.Repl ( repl, stdin, file, runRepl, ) where import Picologic.AST import Picologic.Parser import Picologic.Solver import Picologic.Pretty import Text.PrettyPrint import Control.Monad.State import Data.List (isPrefixOf) import System.Console.Haskeline ------------------------------------------------------------------------------- -- REPL ------------------------------------------------------------------------------- type Repl = StateT IState (InputT IO) data IState = IState { _module :: Maybe Expr , _curFile :: Maybe FilePath } initState :: IState initState = IState Nothing Nothing preamble :: Repl () preamble = liftIO $ do putStrLn "Picologic 0.1" putStrLn "Type :help for help" runRepl :: Repl a -> IO IState runRepl f = runInputT defaultSettings (execStateT (preamble >> f) initState) ------------------------------------------------------------------------------- -- Commands ------------------------------------------------------------------------------- load :: String -> Repl () load arg = do liftIO $ putStrLn $ "Loading " ++ arg file arg modify $ \s -> s { _curFile = Just arg } reload :: Repl () reload = do fname <- gets _curFile case fname of Just fname' -> handleCommand "load" [fname'] Nothing -> liftIO $ putStrLn "No such file" run :: Repl () run = do mod <- gets _module case mod of Nothing -> liftIO $ putStrLn "No expression." Just ex -> liftIO $ do sols <- solveProp ex putStrLn "Solutions:" putStrLn (ppSolutions sols) clauses :: Repl () clauses = do env <- gets _module case env of Just ex -> liftIO $ print (clausesExpr ex) Nothing -> liftIO $ putStrLn "No file loaded." help :: Repl () help = liftIO $ do putStrLn ":clauses Show the SAT solver clauses" putStrLn ":load <file> Load a program from file" ------------------------------------------------------------------------------- -- Test ------------------------------------------------------------------------------- -- evaluate a module modl :: FilePath -> Repl () modl fname = do mod <- liftIO $ parseFile fname case mod of Left err -> liftIO $ print err Right res -> let ex = (simp . cnf $ res) in modify $ \s -> s { _module = Just ex } -- evaluate an expression exec :: String -> Repl () exec source = do let mod = parseExpr source case mod of Left err -> liftIO $ print err Right res -> do let ex = (simp . cnf $ res) liftIO $ putStrLn (render $ ppExprU ex) liftIO $ do sols <- solveProp ex putStrLn "Solutions:" putStrLn (ppSolutions sols) modify $ \s -> s { _module = Just ex } file :: FilePath -> Repl () file fname = modl fname stdin :: IO () stdin = do contents <- getContents case parseExpr contents of Left err -> print err Right ex -> do sols <- solveProp ex putStrLn (ppSolutions sols) handleCommand :: String -> [String] -> Repl () handleCommand cmd args | "ru" `isPrefixOf` cmd = run | "r" `isPrefixOf` cmd = reload | "cl" `isPrefixOf` cmd = clauses | "h" `isPrefixOf` cmd = help | length args == 0 = liftIO $ putStrLn "Not enough arguments" | "l" `isPrefixOf` cmd = load arg | otherwise = liftIO $ putStrLn "Unknown command" where arg = head args repl :: Repl () repl = do minput <- lift $ getInputLine "Logic> " case minput of Nothing -> lift $ outputStrLn "Goodbye." Just (':' : cmds) -> do let (cmd:args) = words cmds handleCommand cmd args repl Just input -> do exec input repl
null
https://raw.githubusercontent.com/sdiehl/picologic/5ecd27fd80fea1ef5889f3ef46ea8a7fd917531a/src/Picologic/Repl.hs
haskell
----------------------------------------------------------------------------- REPL ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Commands ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Test ----------------------------------------------------------------------------- evaluate a module evaluate an expression
module Picologic.Repl ( repl, stdin, file, runRepl, ) where import Picologic.AST import Picologic.Parser import Picologic.Solver import Picologic.Pretty import Text.PrettyPrint import Control.Monad.State import Data.List (isPrefixOf) import System.Console.Haskeline type Repl = StateT IState (InputT IO) data IState = IState { _module :: Maybe Expr , _curFile :: Maybe FilePath } initState :: IState initState = IState Nothing Nothing preamble :: Repl () preamble = liftIO $ do putStrLn "Picologic 0.1" putStrLn "Type :help for help" runRepl :: Repl a -> IO IState runRepl f = runInputT defaultSettings (execStateT (preamble >> f) initState) load :: String -> Repl () load arg = do liftIO $ putStrLn $ "Loading " ++ arg file arg modify $ \s -> s { _curFile = Just arg } reload :: Repl () reload = do fname <- gets _curFile case fname of Just fname' -> handleCommand "load" [fname'] Nothing -> liftIO $ putStrLn "No such file" run :: Repl () run = do mod <- gets _module case mod of Nothing -> liftIO $ putStrLn "No expression." Just ex -> liftIO $ do sols <- solveProp ex putStrLn "Solutions:" putStrLn (ppSolutions sols) clauses :: Repl () clauses = do env <- gets _module case env of Just ex -> liftIO $ print (clausesExpr ex) Nothing -> liftIO $ putStrLn "No file loaded." help :: Repl () help = liftIO $ do putStrLn ":clauses Show the SAT solver clauses" putStrLn ":load <file> Load a program from file" modl :: FilePath -> Repl () modl fname = do mod <- liftIO $ parseFile fname case mod of Left err -> liftIO $ print err Right res -> let ex = (simp . cnf $ res) in modify $ \s -> s { _module = Just ex } exec :: String -> Repl () exec source = do let mod = parseExpr source case mod of Left err -> liftIO $ print err Right res -> do let ex = (simp . cnf $ res) liftIO $ putStrLn (render $ ppExprU ex) liftIO $ do sols <- solveProp ex putStrLn "Solutions:" putStrLn (ppSolutions sols) modify $ \s -> s { _module = Just ex } file :: FilePath -> Repl () file fname = modl fname stdin :: IO () stdin = do contents <- getContents case parseExpr contents of Left err -> print err Right ex -> do sols <- solveProp ex putStrLn (ppSolutions sols) handleCommand :: String -> [String] -> Repl () handleCommand cmd args | "ru" `isPrefixOf` cmd = run | "r" `isPrefixOf` cmd = reload | "cl" `isPrefixOf` cmd = clauses | "h" `isPrefixOf` cmd = help | length args == 0 = liftIO $ putStrLn "Not enough arguments" | "l" `isPrefixOf` cmd = load arg | otherwise = liftIO $ putStrLn "Unknown command" where arg = head args repl :: Repl () repl = do minput <- lift $ getInputLine "Logic> " case minput of Nothing -> lift $ outputStrLn "Goodbye." Just (':' : cmds) -> do let (cmd:args) = words cmds handleCommand cmd args repl Just input -> do exec input repl
f46f23c7a941c841aa2a5d6e8729883e34e8fda9ac62853cc4b696248aa66892
mirleft/ocaml-x509
public_key.ml
let ( let* ) = Result.bind type ecdsa = [ | `P224 of Mirage_crypto_ec.P224.Dsa.pub | `P256 of Mirage_crypto_ec.P256.Dsa.pub | `P384 of Mirage_crypto_ec.P384.Dsa.pub | `P521 of Mirage_crypto_ec.P521.Dsa.pub ] type t = [ | ecdsa | `RSA of Mirage_crypto_pk.Rsa.pub | `ED25519 of Mirage_crypto_ec.Ed25519.pub ] module Asn_oid = Asn.OID module Asn = struct open Asn_grammars open Asn.S open Mirage_crypto_pk let rsa_public_key = let f (n, e) = match Rsa.pub ~e ~n with | Ok p -> p | Error (`Msg m) -> parse_error "bad RSA public key %s" m and g ({ Rsa.n; e } : Rsa.pub) = (n, e) in map f g @@ sequence2 (required ~label:"modulus" integer) (required ~label:"publicExponent" integer) let (rsa_public_of_cstruct, rsa_public_to_cstruct) = projections_of Asn.der rsa_public_key let rsa_pub_of_cs, rsa_pub_to_cs = project_exn rsa_public_key let to_err = function | Ok r -> r | Error e -> parse_error "failed to decode public EC key %a" Mirage_crypto_ec.pp_error e let reparse_pk = let open Mirage_crypto_ec in let open Algorithm in function | (RSA , cs) -> `RSA (rsa_pub_of_cs cs) | (ED25519 , cs) -> `ED25519 (to_err (Ed25519.pub_of_cstruct cs)) | (EC_pub `SECP224R1, cs) -> `P224 (to_err (P224.Dsa.pub_of_cstruct cs)) | (EC_pub `SECP256R1, cs) -> `P256 (to_err (P256.Dsa.pub_of_cstruct cs)) | (EC_pub `SECP384R1, cs) -> `P384 (to_err (P384.Dsa.pub_of_cstruct cs)) | (EC_pub `SECP521R1, cs) -> `P521 (to_err (P521.Dsa.pub_of_cstruct cs)) | _ -> parse_error "unknown public key algorithm" let unparse_pk = let open Mirage_crypto_ec in let open Algorithm in function | `RSA pk -> (RSA, rsa_pub_to_cs pk) | `ED25519 pk -> (ED25519, Ed25519.pub_to_cstruct pk) | `P224 pk -> (EC_pub `SECP224R1, P224.Dsa.pub_to_cstruct pk) | `P256 pk -> (EC_pub `SECP256R1, P256.Dsa.pub_to_cstruct pk) | `P384 pk -> (EC_pub `SECP384R1, P384.Dsa.pub_to_cstruct pk) | `P521 pk -> (EC_pub `SECP521R1, P521.Dsa.pub_to_cstruct pk) let pk_info_der = map reparse_pk unparse_pk @@ sequence2 (required ~label:"algorithm" Algorithm.identifier) (required ~label:"subjectPK" bit_string_cs) let (pub_info_of_cstruct, pub_info_to_cstruct) = projections_of Asn.der pk_info_der end let id k = let data = match k with | `RSA p -> Asn.rsa_public_to_cstruct p | `ED25519 pk -> Mirage_crypto_ec.Ed25519.pub_to_cstruct pk | `P224 pk -> Mirage_crypto_ec.P224.Dsa.pub_to_cstruct pk | `P256 pk -> Mirage_crypto_ec.P256.Dsa.pub_to_cstruct pk | `P384 pk -> Mirage_crypto_ec.P384.Dsa.pub_to_cstruct pk | `P521 pk -> Mirage_crypto_ec.P521.Dsa.pub_to_cstruct pk in Mirage_crypto.Hash.digest `SHA1 data let fingerprint ?(hash = `SHA256) pub = Mirage_crypto.Hash.digest hash (Asn.pub_info_to_cstruct pub) let key_type = function | `RSA _ -> `RSA | `ED25519 _ -> `ED25519 | `P224 _ -> `P224 | `P256 _ -> `P256 | `P384 _ -> `P384 | `P521 _ -> `P521 let sig_alg = function | #ecdsa -> `ECDSA | `RSA _ -> `RSA | `ED25519 _ -> `ED25519 let pp ppf k = Fmt.string ppf (Key_type.to_string (key_type k)); Fmt.sp ppf (); Cstruct.hexdump_pp ppf (fingerprint k) let hashed hash data = match data with | `Message msg -> Ok (Mirage_crypto.Hash.digest hash msg) | `Digest d -> let n = Cstruct.length d and m = Mirage_crypto.Hash.digest_size hash in if n = m then Ok d else Error (`Msg "digested data of invalid size") let trunc len data = if Cstruct.length data > len then Cstruct.sub data 0 len else data let verify hash ?scheme ~signature key data = let open Mirage_crypto_ec in let ok_if_true p = if p then Ok () else Error (`Msg "bad signature") in let ecdsa_of_cs cs = Result.map_error (function `Parse s -> `Msg s) (Algorithm.ecdsa_sig_of_cstruct cs) in let scheme = Key_type.opt_signature_scheme ?scheme (key_type key) in match key, scheme with | `RSA key, `RSA_PSS -> let module H = (val (Mirage_crypto.Hash.module_of hash)) in let module PSS = Mirage_crypto_pk.Rsa.PSS(H) in let* d = hashed hash data in ok_if_true (PSS.verify ~key ~signature (`Digest d)) | `RSA key, `RSA_PKCS1 -> let hashp x = x = hash in let* d = hashed hash data in ok_if_true (Mirage_crypto_pk.Rsa.PKCS1.verify ~hashp ~key ~signature (`Digest d)) | `ED25519 key, `ED25519 -> begin match data with | `Message msg -> ok_if_true (Ed25519.verify ~key signature ~msg) | `Digest _ -> Error (`Msg "Ed25519 only suitable with raw message") end | #ecdsa as key, `ECDSA -> let* d = hashed hash data in let* s = ecdsa_of_cs signature in ok_if_true (match key with | `P224 key -> P224.Dsa.verify ~key s (trunc P224.Dsa.byte_length d) | `P256 key -> P256.Dsa.verify ~key s (trunc P256.Dsa.byte_length d) | `P384 key -> P384.Dsa.verify ~key s (trunc P384.Dsa.byte_length d) | `P521 key -> P521.Dsa.verify ~key s (trunc P521.Dsa.byte_length d)) | _ -> Error (`Msg "invalid key and signature scheme combination") let encode_der = Asn.pub_info_to_cstruct let decode_der cs = Asn_grammars.err_to_msg (Asn.pub_info_of_cstruct cs) let decode_pem cs = let* data = Pem.parse cs in let pks = List.filter (fun (t, _) -> String.equal "PUBLIC KEY" t) data in let* keys = Pem.foldM (fun (_, k) -> decode_der k) pks in Pem.exactly_one ~what:"public key" keys let encode_pem v = Pem.unparse ~tag:"PUBLIC KEY" (encode_der v)
null
https://raw.githubusercontent.com/mirleft/ocaml-x509/73f8d60c42f09c9712ad04a62582bda816895dd8/lib/public_key.ml
ocaml
let ( let* ) = Result.bind type ecdsa = [ | `P224 of Mirage_crypto_ec.P224.Dsa.pub | `P256 of Mirage_crypto_ec.P256.Dsa.pub | `P384 of Mirage_crypto_ec.P384.Dsa.pub | `P521 of Mirage_crypto_ec.P521.Dsa.pub ] type t = [ | ecdsa | `RSA of Mirage_crypto_pk.Rsa.pub | `ED25519 of Mirage_crypto_ec.Ed25519.pub ] module Asn_oid = Asn.OID module Asn = struct open Asn_grammars open Asn.S open Mirage_crypto_pk let rsa_public_key = let f (n, e) = match Rsa.pub ~e ~n with | Ok p -> p | Error (`Msg m) -> parse_error "bad RSA public key %s" m and g ({ Rsa.n; e } : Rsa.pub) = (n, e) in map f g @@ sequence2 (required ~label:"modulus" integer) (required ~label:"publicExponent" integer) let (rsa_public_of_cstruct, rsa_public_to_cstruct) = projections_of Asn.der rsa_public_key let rsa_pub_of_cs, rsa_pub_to_cs = project_exn rsa_public_key let to_err = function | Ok r -> r | Error e -> parse_error "failed to decode public EC key %a" Mirage_crypto_ec.pp_error e let reparse_pk = let open Mirage_crypto_ec in let open Algorithm in function | (RSA , cs) -> `RSA (rsa_pub_of_cs cs) | (ED25519 , cs) -> `ED25519 (to_err (Ed25519.pub_of_cstruct cs)) | (EC_pub `SECP224R1, cs) -> `P224 (to_err (P224.Dsa.pub_of_cstruct cs)) | (EC_pub `SECP256R1, cs) -> `P256 (to_err (P256.Dsa.pub_of_cstruct cs)) | (EC_pub `SECP384R1, cs) -> `P384 (to_err (P384.Dsa.pub_of_cstruct cs)) | (EC_pub `SECP521R1, cs) -> `P521 (to_err (P521.Dsa.pub_of_cstruct cs)) | _ -> parse_error "unknown public key algorithm" let unparse_pk = let open Mirage_crypto_ec in let open Algorithm in function | `RSA pk -> (RSA, rsa_pub_to_cs pk) | `ED25519 pk -> (ED25519, Ed25519.pub_to_cstruct pk) | `P224 pk -> (EC_pub `SECP224R1, P224.Dsa.pub_to_cstruct pk) | `P256 pk -> (EC_pub `SECP256R1, P256.Dsa.pub_to_cstruct pk) | `P384 pk -> (EC_pub `SECP384R1, P384.Dsa.pub_to_cstruct pk) | `P521 pk -> (EC_pub `SECP521R1, P521.Dsa.pub_to_cstruct pk) let pk_info_der = map reparse_pk unparse_pk @@ sequence2 (required ~label:"algorithm" Algorithm.identifier) (required ~label:"subjectPK" bit_string_cs) let (pub_info_of_cstruct, pub_info_to_cstruct) = projections_of Asn.der pk_info_der end let id k = let data = match k with | `RSA p -> Asn.rsa_public_to_cstruct p | `ED25519 pk -> Mirage_crypto_ec.Ed25519.pub_to_cstruct pk | `P224 pk -> Mirage_crypto_ec.P224.Dsa.pub_to_cstruct pk | `P256 pk -> Mirage_crypto_ec.P256.Dsa.pub_to_cstruct pk | `P384 pk -> Mirage_crypto_ec.P384.Dsa.pub_to_cstruct pk | `P521 pk -> Mirage_crypto_ec.P521.Dsa.pub_to_cstruct pk in Mirage_crypto.Hash.digest `SHA1 data let fingerprint ?(hash = `SHA256) pub = Mirage_crypto.Hash.digest hash (Asn.pub_info_to_cstruct pub) let key_type = function | `RSA _ -> `RSA | `ED25519 _ -> `ED25519 | `P224 _ -> `P224 | `P256 _ -> `P256 | `P384 _ -> `P384 | `P521 _ -> `P521 let sig_alg = function | #ecdsa -> `ECDSA | `RSA _ -> `RSA | `ED25519 _ -> `ED25519 let pp ppf k = Fmt.string ppf (Key_type.to_string (key_type k)); Fmt.sp ppf (); Cstruct.hexdump_pp ppf (fingerprint k) let hashed hash data = match data with | `Message msg -> Ok (Mirage_crypto.Hash.digest hash msg) | `Digest d -> let n = Cstruct.length d and m = Mirage_crypto.Hash.digest_size hash in if n = m then Ok d else Error (`Msg "digested data of invalid size") let trunc len data = if Cstruct.length data > len then Cstruct.sub data 0 len else data let verify hash ?scheme ~signature key data = let open Mirage_crypto_ec in let ok_if_true p = if p then Ok () else Error (`Msg "bad signature") in let ecdsa_of_cs cs = Result.map_error (function `Parse s -> `Msg s) (Algorithm.ecdsa_sig_of_cstruct cs) in let scheme = Key_type.opt_signature_scheme ?scheme (key_type key) in match key, scheme with | `RSA key, `RSA_PSS -> let module H = (val (Mirage_crypto.Hash.module_of hash)) in let module PSS = Mirage_crypto_pk.Rsa.PSS(H) in let* d = hashed hash data in ok_if_true (PSS.verify ~key ~signature (`Digest d)) | `RSA key, `RSA_PKCS1 -> let hashp x = x = hash in let* d = hashed hash data in ok_if_true (Mirage_crypto_pk.Rsa.PKCS1.verify ~hashp ~key ~signature (`Digest d)) | `ED25519 key, `ED25519 -> begin match data with | `Message msg -> ok_if_true (Ed25519.verify ~key signature ~msg) | `Digest _ -> Error (`Msg "Ed25519 only suitable with raw message") end | #ecdsa as key, `ECDSA -> let* d = hashed hash data in let* s = ecdsa_of_cs signature in ok_if_true (match key with | `P224 key -> P224.Dsa.verify ~key s (trunc P224.Dsa.byte_length d) | `P256 key -> P256.Dsa.verify ~key s (trunc P256.Dsa.byte_length d) | `P384 key -> P384.Dsa.verify ~key s (trunc P384.Dsa.byte_length d) | `P521 key -> P521.Dsa.verify ~key s (trunc P521.Dsa.byte_length d)) | _ -> Error (`Msg "invalid key and signature scheme combination") let encode_der = Asn.pub_info_to_cstruct let decode_der cs = Asn_grammars.err_to_msg (Asn.pub_info_of_cstruct cs) let decode_pem cs = let* data = Pem.parse cs in let pks = List.filter (fun (t, _) -> String.equal "PUBLIC KEY" t) data in let* keys = Pem.foldM (fun (_, k) -> decode_der k) pks in Pem.exactly_one ~what:"public key" keys let encode_pem v = Pem.unparse ~tag:"PUBLIC KEY" (encode_der v)
d20b8d02a66ca48150540a75a29a740366b4de72621b3c7915513c2cf189435e
mnieper/unsyntax
macro.scm
Copyright © ( 2020 ) . ;; This file is part of unsyntax. ;; 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 (including the ;; next paragraph) 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. (define (expand-meta stx) (receive (expr inv-reqs) (parameterize ((invoke-collector (make-library-collector)) (visit-collector (make-library-collector))) (let ((expr (in-meta (expand stx)))) (values expr (invoke-requirements)))) (for-each (lambda (lib) (invoke-library! lib) (require-visit! lib)) inv-reqs) expr)) ;;;;;;;;;;;;;;;; ;; Properties ;; ;;;;;;;;;;;;;;;; (define (expand-property id stx) (list (expand-meta stx) id)) (define (make-property-binding def) (make-binding 'property (cons (execute (car def)) (cdr def)))) (define (property-lookup id key) (assert (identifier? id)) (assert (identifier? key)) (let ((klbl (or (resolve key) (raise-syntax-error key "identifier ‘~a’ unbound" (identifier-name key))))) (let ((ilbl (or (resolve id) (raise-syntax-error id "identifier ‘~a’ unbound" (identifier-name id))))) (if (and (eq? klbl 'auxiliary-syntax-name) (auxiliary-syntax-label? ilbl)) (auxiliary-syntax-name ilbl) (and-let* ((plbl (resolve-prop id ilbl klbl)) (b (lookup plbl)) (type (binding-type b)) (val (binding-value b))) (case type ((property) (car val)) ((global-property) (and-let* ((lib (car val))) (visit-library! lib)) (caadr val)) (else (error "compiler error")))))))) (define (property-aware transformer) (lambda (stx) (let f ((res (transformer stx))) (if (procedure? res) (f (res property-lookup)) res)))) (define (er-property-aware transformer inject) (lambda (expr rename compare) (let f ((res (transformer expr rename compare))) (if (procedure? res) (f (res (lambda (id key) (property-lookup (inject id) (inject key))))) res)))) (define (ir-property-aware transformer rename) (lambda (expr inject compare) (let f ((res (transformer expr inject compare))) (if (procedure? res) (f (res (lambda (id key) (property-lookup (rename id) (rename key))))) res)))) (define (sc-property-aware transformer) (lambda (exp env) (let f ((res (transformer exp env))) (if (procedure? res) (f (res (lambda (id-env id key-env key) (property-lookup (close-syntax id id-env) (close-syntax key key-env))))) res)))) ;;;;;;;;;;;;;;;;;;;;;; ;; Meta Definitions ;; ;;;;;;;;;;;;;;;;;;;;;; (define (expand-meta-definition id stx n) (list (build (syntax-object-srcloc stx) (arguments->vector ',id ',n (lambda () ,(expand-meta stx)))) id)) (define (eval-meta stx) (execute (expand-meta stx))) (define (make-meta-variable-binding plbl i) (make-meta-binding 'meta-variable (list plbl i))) (define (meta-lookup id lbl) (define b (lookup lbl)) (unless b (raise-syntax-error id "circular reference of meta variabie ‘~a’" (identifier-name id))) (let ((val (binding-value b))) (case (binding-type b) ((property) (car val)) ((global-property) (and-let* ((lib (car val))) (visit-library! lib)) (caadr val))))) (define (meta-unbox id plbl i) (define vals (meta-lookup id plbl)) (vector-ref vals i)) (define (meta-set-box! id plbl i obj) (define vals (meta-lookup id plbl)) (vector-set! vals i obj)) ;;;;;;;;;;;;;;;;;; ;; Transformers ;; ;;;;;;;;;;;;;;;;;; (define (expand-transformer id stx) (list (expand-meta stx) id)) (define (make-transformer-binding type def) (let ((transformer (execute (car def)))) (make-binding (case type ((define-syntax) 'macro) ((define-syntax-parameter) 'macro-parameter)) (cons transformer (cdr def))))) (define transform/global-keyword (case-lambda ((val stx env) (transform/global-keyword val stx env #f)) ((val stx env id) (and-let* ((lib (car val))) (visit-library! lib)) (transform/macro (caddr val) stx env id)))) (define transform/macro (case-lambda ((def stx env) (transform/macro def stx env #f)) ((def stx env id) (let* ((maybe-variable-transformer (car def)) (transformer-stx (cadr def)) (transformer (cond ((variable-transformer? maybe-variable-transformer) (variable-transformer-procedure maybe-variable-transformer)) (id (raise-syntax-error id "not a variable transformer ‘~s’" (identifier-name id))) (else maybe-variable-transformer)))) (cond ((procedure? transformer) (apply-transformer (property-aware transformer) stx (add-mark (anti-mark) stx) env)) ((er-macro-transformer? transformer) (er-transform transformer stx (add-mark (anti-mark) stx) transformer-stx env)) ((ir-macro-transformer? transformer) (ir-transform transformer stx (add-mark (anti-mark) stx) transformer-stx env)) ((sc-macro-transformer? transformer) (sc-transform transformer stx transformer-stx)) (else (raise-syntax-error transformer-stx "‘~a’ is not a transformer" (identifier-name transformer-stx)))))))) (define (apply-transformer transform stx e env) (let* ((loc (syntax-object-srcloc stx)) (wrap (lambda (e) (datum->syntax #f e loc)))) (wrap (build-output stx (transform e) (make-mark) env)))) (define (apply-transformer/closure transform stx e k env) (let* ((loc (syntax-object-srcloc stx)) (wrap (lambda (e) (datum->syntax #f e loc)))) (wrap (build-output/closure stx k (transform e) (make-mark) env)))) (define (build-output stx e m env) (let f ((e e)) (cond ((pair? e) (cons (f (car e)) (f (cdr e)))) ((vector? e) (vector-map f e)) ((symbol? e) (raise-syntax-error stx "encountered raw symbol ‘~a’ in output of macro" e)) ((syntax-object? e) (receive (m* s*) (let ((m* (syntax-object-marks e)) (s* (syntax-object-substs e))) (if (and (pair? m*) (anti-mark? (car m*))) (values (cdr m*) (cdr s*)) (values (cons m m*) (if env (cons* env (shift) s*) (cons (shift) s*))))) (make-syntax-object (syntax-object-expr e) m* s* (syntax-object-srcloc e)))) (else ;; TODO: Check whether this is an allowed datum. e)))) (define (build-output/closure stx k e m env) (let ((table (make-hash-table eq-comparator))) (let f ((e e)) (cond ((hash-table-ref/default table e #f)) ((pair? e) (let ((v (cons #f #f))) (hash-table-set! table e v) (set-car! v (f (car e))) (set-cdr! v (f (cdr e))) v)) ((vector? e) (let ((v (make-vector (vector-length e)))) (hash-table-set! table e v) (do ((i 0 (+ i 1))) ((= i (vector-length v)) v) (vector-set! v i (f (vector-ref e i)))))) ((symbol? e) (f (datum->syntax k e))) ((syntax-object? e) (receive (m* s*) (let ((m* (syntax-object-marks e)) (s* (syntax-object-substs e))) (if (and (pair? m*) (anti-mark? (car m*))) (values (cdr m*) (cdr s*)) (values (cons m m*) (if env (cons* env (shift) s*) (cons (shift) s*))))) (make-syntax-object (syntax-object-expr e) m* s* (syntax-object-srcloc e)))) (else ;; TODO: Check whether this is an allowed datum. e))))) ;;;;;;;;;;;;;;;;;;;;;;;;;; ER macro transformer ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;; (define (er-transform transformer stx e k env) (let* ((i (if (identifier? e) e (syntax-car e))) (inject (lambda (id) (if (identifier? id) id (datum->syntax i id)))) (transform (er-property-aware (er-macro-transformer-procedure transformer) inject))) (apply-transformer/closure (lambda (stx) (transform (syntax->sexpr e) (lambda (exp) (datum->syntax k exp)) (lambda (id1 id2) (free-identifier=? (inject id1) (inject id2))))) stx e i env))) ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; IR macro transformer ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; (define (ir-transform transformer stx e k env) (let* ((rename (lambda (id) (if (identifier? id) id (datum->syntax k id)))) (transform (ir-property-aware (ir-macro-transformer-procedure transformer) rename))) (apply-transformer/closure (lambda (stx) (let ((i (if (identifier? e) e (syntax-car e)))) (transform (syntax->sexpr e) (lambda (exp) (datum->syntax i exp)) (lambda (id1 id2) (free-identifier=? (rename id1) (rename id2)))))) stx e k env))) ;;;;;;;;;;;;;;;;;;;;;;;;;; SC macro transformer ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;; (define (sc-transform transformer stx k) (let ((transform (sc-macro-transformer-procedure transformer)) (i (if (identifier? stx) stx (syntax-car stx)))) (sc-build-output stx (transform (syntax->sexpr stx i) i) (add-mark (make-mark) k)))) (define (sc-build-output stx e k) (let* ((loc (syntax-object-srcloc stx)) (wrap (lambda (e) (datum->syntax #f e loc))) (table (make-hash-table eq-comparator))) (wrap (let g ((e e) (k k) (contexts '())) (let f ((e e)) (cond ;; FIXME: The same pair or vector may appear in different ;; syntactic closures. For the moment, disable gracefully ;; handling of cyclic data structures. #; ((hash-table-ref/default table e #f)) ((pair? e) (let ((v (cons #f #f))) (hash-table-set! table e v) (set-car! v (f (car e))) (set-cdr! v (f (cdr e))) v)) ((vector? e) (let ((v (make-vector (vector-length e)))) (hash-table-set! table e v) (do ((i 0 (+ i 1))) ((= i (vector-length v)) v) (vector-set! v i (f (vector-ref e i)))))) ((symbol? e) (cond ((assoc (datum->syntax #f e) contexts bound-identifier=?) => (lambda (pair) (datum->syntax (cdr pair) (car pair)))) (else (datum->syntax k e)))) ((syntax-object? e) (cond ((and (identifier? e) (assoc e contexts bound-identifier=?)) => (lambda (pair) (datum->syntax (cdr pair) (car pair)))) (else (datum->syntax k e)))) ((syntactic-closure? e) (let ((i (syntactic-closure-environment e))) (g (syntactic-closure-form e) i (map (lambda (id) (let ((id (if (identifier? id) id (datum->syntax #f id)))) (cond ((assoc id contexts bound-identifier=?)) (else (cons id k))))) (syntactic-closure-free-names e))))) ((capture-syntactic-environment? e) (datum->syntax k (capture-syntactic-environment (lambda (env) (wrap (f ((capture-syntactic-environment-procedure e) env))))) loc)) (else e)))))))
null
https://raw.githubusercontent.com/mnieper/unsyntax/c3fcb22d9b7021d4dc308b054995e817fa9ccbbd/src/unsyntax/expander/macro.scm
scheme
This file is part of unsyntax. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files including without limitation the rights to use, copy, modify, merge, subject to the following conditions: The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial 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 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. Properties ;; Meta Definitions ;; Transformers ;; TODO: Check whether this is an allowed datum. TODO: Check whether this is an allowed datum. ; IR macro transformer ;; ; FIXME: The same pair or vector may appear in different syntactic closures. For the moment, disable gracefully handling of cyclic data structures.
Copyright © ( 2020 ) . ( the " Software " ) , to deal in the Software without restriction , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN (define (expand-meta stx) (receive (expr inv-reqs) (parameterize ((invoke-collector (make-library-collector)) (visit-collector (make-library-collector))) (let ((expr (in-meta (expand stx)))) (values expr (invoke-requirements)))) (for-each (lambda (lib) (invoke-library! lib) (require-visit! lib)) inv-reqs) expr)) (define (expand-property id stx) (list (expand-meta stx) id)) (define (make-property-binding def) (make-binding 'property (cons (execute (car def)) (cdr def)))) (define (property-lookup id key) (assert (identifier? id)) (assert (identifier? key)) (let ((klbl (or (resolve key) (raise-syntax-error key "identifier ‘~a’ unbound" (identifier-name key))))) (let ((ilbl (or (resolve id) (raise-syntax-error id "identifier ‘~a’ unbound" (identifier-name id))))) (if (and (eq? klbl 'auxiliary-syntax-name) (auxiliary-syntax-label? ilbl)) (auxiliary-syntax-name ilbl) (and-let* ((plbl (resolve-prop id ilbl klbl)) (b (lookup plbl)) (type (binding-type b)) (val (binding-value b))) (case type ((property) (car val)) ((global-property) (and-let* ((lib (car val))) (visit-library! lib)) (caadr val)) (else (error "compiler error")))))))) (define (property-aware transformer) (lambda (stx) (let f ((res (transformer stx))) (if (procedure? res) (f (res property-lookup)) res)))) (define (er-property-aware transformer inject) (lambda (expr rename compare) (let f ((res (transformer expr rename compare))) (if (procedure? res) (f (res (lambda (id key) (property-lookup (inject id) (inject key))))) res)))) (define (ir-property-aware transformer rename) (lambda (expr inject compare) (let f ((res (transformer expr inject compare))) (if (procedure? res) (f (res (lambda (id key) (property-lookup (rename id) (rename key))))) res)))) (define (sc-property-aware transformer) (lambda (exp env) (let f ((res (transformer exp env))) (if (procedure? res) (f (res (lambda (id-env id key-env key) (property-lookup (close-syntax id id-env) (close-syntax key key-env))))) res)))) (define (expand-meta-definition id stx n) (list (build (syntax-object-srcloc stx) (arguments->vector ',id ',n (lambda () ,(expand-meta stx)))) id)) (define (eval-meta stx) (execute (expand-meta stx))) (define (make-meta-variable-binding plbl i) (make-meta-binding 'meta-variable (list plbl i))) (define (meta-lookup id lbl) (define b (lookup lbl)) (unless b (raise-syntax-error id "circular reference of meta variabie ‘~a’" (identifier-name id))) (let ((val (binding-value b))) (case (binding-type b) ((property) (car val)) ((global-property) (and-let* ((lib (car val))) (visit-library! lib)) (caadr val))))) (define (meta-unbox id plbl i) (define vals (meta-lookup id plbl)) (vector-ref vals i)) (define (meta-set-box! id plbl i obj) (define vals (meta-lookup id plbl)) (vector-set! vals i obj)) (define (expand-transformer id stx) (list (expand-meta stx) id)) (define (make-transformer-binding type def) (let ((transformer (execute (car def)))) (make-binding (case type ((define-syntax) 'macro) ((define-syntax-parameter) 'macro-parameter)) (cons transformer (cdr def))))) (define transform/global-keyword (case-lambda ((val stx env) (transform/global-keyword val stx env #f)) ((val stx env id) (and-let* ((lib (car val))) (visit-library! lib)) (transform/macro (caddr val) stx env id)))) (define transform/macro (case-lambda ((def stx env) (transform/macro def stx env #f)) ((def stx env id) (let* ((maybe-variable-transformer (car def)) (transformer-stx (cadr def)) (transformer (cond ((variable-transformer? maybe-variable-transformer) (variable-transformer-procedure maybe-variable-transformer)) (id (raise-syntax-error id "not a variable transformer ‘~s’" (identifier-name id))) (else maybe-variable-transformer)))) (cond ((procedure? transformer) (apply-transformer (property-aware transformer) stx (add-mark (anti-mark) stx) env)) ((er-macro-transformer? transformer) (er-transform transformer stx (add-mark (anti-mark) stx) transformer-stx env)) ((ir-macro-transformer? transformer) (ir-transform transformer stx (add-mark (anti-mark) stx) transformer-stx env)) ((sc-macro-transformer? transformer) (sc-transform transformer stx transformer-stx)) (else (raise-syntax-error transformer-stx "‘~a’ is not a transformer" (identifier-name transformer-stx)))))))) (define (apply-transformer transform stx e env) (let* ((loc (syntax-object-srcloc stx)) (wrap (lambda (e) (datum->syntax #f e loc)))) (wrap (build-output stx (transform e) (make-mark) env)))) (define (apply-transformer/closure transform stx e k env) (let* ((loc (syntax-object-srcloc stx)) (wrap (lambda (e) (datum->syntax #f e loc)))) (wrap (build-output/closure stx k (transform e) (make-mark) env)))) (define (build-output stx e m env) (let f ((e e)) (cond ((pair? e) (cons (f (car e)) (f (cdr e)))) ((vector? e) (vector-map f e)) ((symbol? e) (raise-syntax-error stx "encountered raw symbol ‘~a’ in output of macro" e)) ((syntax-object? e) (receive (m* s*) (let ((m* (syntax-object-marks e)) (s* (syntax-object-substs e))) (if (and (pair? m*) (anti-mark? (car m*))) (values (cdr m*) (cdr s*)) (values (cons m m*) (if env (cons* env (shift) s*) (cons (shift) s*))))) (make-syntax-object (syntax-object-expr e) m* s* (syntax-object-srcloc e)))) (else e)))) (define (build-output/closure stx k e m env) (let ((table (make-hash-table eq-comparator))) (let f ((e e)) (cond ((hash-table-ref/default table e #f)) ((pair? e) (let ((v (cons #f #f))) (hash-table-set! table e v) (set-car! v (f (car e))) (set-cdr! v (f (cdr e))) v)) ((vector? e) (let ((v (make-vector (vector-length e)))) (hash-table-set! table e v) (do ((i 0 (+ i 1))) ((= i (vector-length v)) v) (vector-set! v i (f (vector-ref e i)))))) ((symbol? e) (f (datum->syntax k e))) ((syntax-object? e) (receive (m* s*) (let ((m* (syntax-object-marks e)) (s* (syntax-object-substs e))) (if (and (pair? m*) (anti-mark? (car m*))) (values (cdr m*) (cdr s*)) (values (cons m m*) (if env (cons* env (shift) s*) (cons (shift) s*))))) (make-syntax-object (syntax-object-expr e) m* s* (syntax-object-srcloc e)))) (else e))))) (define (er-transform transformer stx e k env) (let* ((i (if (identifier? e) e (syntax-car e))) (inject (lambda (id) (if (identifier? id) id (datum->syntax i id)))) (transform (er-property-aware (er-macro-transformer-procedure transformer) inject))) (apply-transformer/closure (lambda (stx) (transform (syntax->sexpr e) (lambda (exp) (datum->syntax k exp)) (lambda (id1 id2) (free-identifier=? (inject id1) (inject id2))))) stx e i env))) (define (ir-transform transformer stx e k env) (let* ((rename (lambda (id) (if (identifier? id) id (datum->syntax k id)))) (transform (ir-property-aware (ir-macro-transformer-procedure transformer) rename))) (apply-transformer/closure (lambda (stx) (let ((i (if (identifier? e) e (syntax-car e)))) (transform (syntax->sexpr e) (lambda (exp) (datum->syntax i exp)) (lambda (id1 id2) (free-identifier=? (rename id1) (rename id2)))))) stx e k env))) (define (sc-transform transformer stx k) (let ((transform (sc-macro-transformer-procedure transformer)) (i (if (identifier? stx) stx (syntax-car stx)))) (sc-build-output stx (transform (syntax->sexpr stx i) i) (add-mark (make-mark) k)))) (define (sc-build-output stx e k) (let* ((loc (syntax-object-srcloc stx)) (wrap (lambda (e) (datum->syntax #f e loc))) (table (make-hash-table eq-comparator))) (wrap (let g ((e e) (k k) (contexts '())) (let f ((e e)) (cond ((hash-table-ref/default table e #f)) ((pair? e) (let ((v (cons #f #f))) (hash-table-set! table e v) (set-car! v (f (car e))) (set-cdr! v (f (cdr e))) v)) ((vector? e) (let ((v (make-vector (vector-length e)))) (hash-table-set! table e v) (do ((i 0 (+ i 1))) ((= i (vector-length v)) v) (vector-set! v i (f (vector-ref e i)))))) ((symbol? e) (cond ((assoc (datum->syntax #f e) contexts bound-identifier=?) => (lambda (pair) (datum->syntax (cdr pair) (car pair)))) (else (datum->syntax k e)))) ((syntax-object? e) (cond ((and (identifier? e) (assoc e contexts bound-identifier=?)) => (lambda (pair) (datum->syntax (cdr pair) (car pair)))) (else (datum->syntax k e)))) ((syntactic-closure? e) (let ((i (syntactic-closure-environment e))) (g (syntactic-closure-form e) i (map (lambda (id) (let ((id (if (identifier? id) id (datum->syntax #f id)))) (cond ((assoc id contexts bound-identifier=?)) (else (cons id k))))) (syntactic-closure-free-names e))))) ((capture-syntactic-environment? e) (datum->syntax k (capture-syntactic-environment (lambda (env) (wrap (f ((capture-syntactic-environment-procedure e) env))))) loc)) (else e)))))))
ed0706b790de3ed592f46fb10d02ac397fb3631a0191955b5812b9d34badbf1c
elaforge/karya
Control.hs
Copyright 2013 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # -- | Control flow and monadic utilities. module Util.Control ( module Util.Control , module Data.Bifunctor, module Control.Monad.Extra, module Util.CallStack ) where import qualified Control.Monad as Monad import qualified Control.Monad.Except as Except import Control.Monad.Extra (allM, andM, anyM, findM, mapMaybeM, notM, orM, partitionM) import qualified Control.Monad.Fix as Fix import Data.Bifunctor (Bifunctor(bimap, first, second)) import Util.CallStack (errorIO, errorStack) These are the same as Control . Monad . Extra , but they are frequently used , and -- by defining them here I can explicitly INLINE them. Surely they're short enough that ghc will inline anyway , but -fprof - auto - exported is n't that -- clever. I got around by recompiling all of hackage with -- 'profiling-detail: none', but I might as well keep the definitions anyway -- since it gives me more control. {-# INLINE whenJust #-} whenJust :: Applicative m => Maybe a -> (a -> m ()) -> m () whenJust ma f = maybe (pure ()) f ma # INLINE whenJustM # whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () whenJustM mma f = mma >>= \case Nothing -> pure () Just a -> f a # INLINE whenM # whenM :: Monad m => m Bool -> m () -> m () whenM mb true = ifM mb true (pure ()) # INLINE unlessM # unlessM :: Monad m => m Bool -> m () -> m () unlessM mb false = ifM mb (pure ()) false # INLINE ifM # ifM :: Monad m => m Bool -> m a -> m a -> m a ifM mb true false = mb >>= \case True -> true False -> false uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e uncurry4 f (a, b, c, d) = f a b c d -- * local while :: Monad m => m Bool -> m a -> m [a] while cond op = do b <- cond case b of True -> do val <- op rest <- while cond op return (val:rest) False -> return [] while_ :: Monad m => m Bool -> m a -> m () while_ cond op = do b <- cond Monad.when b $ op >> while_ cond op -- | Loop with no arguments. This is the same as 'Fix.fix' but the name is -- clearer. loop0 :: (a -> a) -> a loop0 = Fix.fix -- | Loop with a single state argument. loop1 :: forall state a. state -> ((state -> a) -> state -> a) -> a loop1 state f = f again state where again :: state -> a again = f again | Loop with two state arguments . You could use loop1 with a pair , but -- sometimes the currying is convenient. loop2 :: forall s1 s2 a. s1 -> s2 -> ((s1 -> s2 -> a) -> s1 -> s2 -> a) -> a loop2 s1 s2 f = f again s1 s2 where again :: s1 -> s2 -> a again = f again -- | This is 'Foldable.foldMap' specialized to lists. mconcatMap :: Monoid b => (a -> b) -> [a] -> b mconcatMap f = mconcat . map f | This is actually a -- -- A further generalized version would be: -- > foldMapA : : ( Applicative f , t , Monoid m ) = > -- > (a -> f m) -> t a -> f m > foldMapA f = fmap Foldable.fold . traverse f concatMapM :: (Monad m, Monoid b) => (a -> m b) -> [a] -> m b concatMapM f = Monad.liftM mconcat . mapM f | Run the second action only if the first action returns Just . -- -- This is like MaybeT, but using MaybeT itself required lots of annoying -- explicit lifting. justm :: Monad m => m (Maybe a) -> (a -> m (Maybe b)) -> m (Maybe b) justm op1 op2 = maybe (return Nothing) op2 =<< op1 | The Either equivalent of ' justm ' . EitherT solves the same problem , but -- requires a runEitherT and lots of hoistEithers. rightm :: Monad m => m (Either err a) -> (a -> m (Either err b)) -> m (Either err b) rightm op1 op2 = op1 >>= \x -> case x of Left err -> return (Left err) Right val -> op2 val I could generalize justm and with : : : ( , , ) = > m1 ( m2 a ) - > ( a - > m1 ( m2 b ) ) - > m1 ( m2 b ) bind2 > = traverse mb > > = return . Monad.join But I ca n't think of any other Traversables I want . I could generalize justm and rightm with: bind2 :: (Monad m1, Traversable m2, Monad m2) => m1 (m2 a) -> (a -> m1 (m2 b)) -> m1 (m2 b) bind2 ma mb = ma >>= traverse mb >>= return . Monad.join But I can't think of any other Traversables I want. -} | Return the first action to return Just . firstJust :: Monad m => m (Maybe a) -> m (Maybe a) -> m (Maybe a) firstJust action alternative = maybe alternative (return . Just) =<< action -- | 'firstJust' applied to a list. firstJusts :: Monad m => [m (Maybe a)] -> m (Maybe a) firstJusts = foldr firstJust (return Nothing) -- * errors The names are chosen to be consistent with the @errors@ package . -- | Throw on Nothing. justErr :: err -> Maybe a -> Either err a justErr err = maybe (Left err) Right -- | I usually call this @require@. tryJust :: Except.MonadError e m => e -> Maybe a -> m a tryJust err = maybe (Except.throwError err) return -- | I usually call this @require_right@. tryRight :: Except.MonadError e m => Either e a -> m a tryRight = either Except.throwError return rethrow :: Except.MonadError e m => (e -> e) -> m a -> m a rethrow modify action = action `Except.catchError` \e -> Except.throwError (modify e)
null
https://raw.githubusercontent.com/elaforge/karya/a6638f16da9f018686023977c1292d6ce5095e28/Util/Control.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt | Control flow and monadic utilities. by defining them here I can explicitly INLINE them. Surely they're short clever. I got around by recompiling all of hackage with 'profiling-detail: none', but I might as well keep the definitions anyway since it gives me more control. # INLINE whenJust # * local | Loop with no arguments. This is the same as 'Fix.fix' but the name is clearer. | Loop with a single state argument. sometimes the currying is convenient. | This is 'Foldable.foldMap' specialized to lists. A further generalized version would be: > (a -> f m) -> t a -> f m This is like MaybeT, but using MaybeT itself required lots of annoying explicit lifting. requires a runEitherT and lots of hoistEithers. | 'firstJust' applied to a list. * errors | Throw on Nothing. | I usually call this @require@. | I usually call this @require_right@.
Copyright 2013 # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # module Util.Control ( module Util.Control , module Data.Bifunctor, module Control.Monad.Extra, module Util.CallStack ) where import qualified Control.Monad as Monad import qualified Control.Monad.Except as Except import Control.Monad.Extra (allM, andM, anyM, findM, mapMaybeM, notM, orM, partitionM) import qualified Control.Monad.Fix as Fix import Data.Bifunctor (Bifunctor(bimap, first, second)) import Util.CallStack (errorIO, errorStack) These are the same as Control . Monad . Extra , but they are frequently used , and enough that ghc will inline anyway , but -fprof - auto - exported is n't that whenJust :: Applicative m => Maybe a -> (a -> m ()) -> m () whenJust ma f = maybe (pure ()) f ma # INLINE whenJustM # whenJustM :: Monad m => m (Maybe a) -> (a -> m ()) -> m () whenJustM mma f = mma >>= \case Nothing -> pure () Just a -> f a # INLINE whenM # whenM :: Monad m => m Bool -> m () -> m () whenM mb true = ifM mb true (pure ()) # INLINE unlessM # unlessM :: Monad m => m Bool -> m () -> m () unlessM mb false = ifM mb (pure ()) false # INLINE ifM # ifM :: Monad m => m Bool -> m a -> m a -> m a ifM mb true false = mb >>= \case True -> true False -> false uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e uncurry4 f (a, b, c, d) = f a b c d while :: Monad m => m Bool -> m a -> m [a] while cond op = do b <- cond case b of True -> do val <- op rest <- while cond op return (val:rest) False -> return [] while_ :: Monad m => m Bool -> m a -> m () while_ cond op = do b <- cond Monad.when b $ op >> while_ cond op loop0 :: (a -> a) -> a loop0 = Fix.fix loop1 :: forall state a. state -> ((state -> a) -> state -> a) -> a loop1 state f = f again state where again :: state -> a again = f again | Loop with two state arguments . You could use loop1 with a pair , but loop2 :: forall s1 s2 a. s1 -> s2 -> ((s1 -> s2 -> a) -> s1 -> s2 -> a) -> a loop2 s1 s2 f = f again s1 s2 where again :: s1 -> s2 -> a again = f again mconcatMap :: Monoid b => (a -> b) -> [a] -> b mconcatMap f = mconcat . map f | This is actually a > foldMapA : : ( Applicative f , t , Monoid m ) = > > foldMapA f = fmap Foldable.fold . traverse f concatMapM :: (Monad m, Monoid b) => (a -> m b) -> [a] -> m b concatMapM f = Monad.liftM mconcat . mapM f | Run the second action only if the first action returns Just . justm :: Monad m => m (Maybe a) -> (a -> m (Maybe b)) -> m (Maybe b) justm op1 op2 = maybe (return Nothing) op2 =<< op1 | The Either equivalent of ' justm ' . EitherT solves the same problem , but rightm :: Monad m => m (Either err a) -> (a -> m (Either err b)) -> m (Either err b) rightm op1 op2 = op1 >>= \x -> case x of Left err -> return (Left err) Right val -> op2 val I could generalize justm and with : : : ( , , ) = > m1 ( m2 a ) - > ( a - > m1 ( m2 b ) ) - > m1 ( m2 b ) bind2 > = traverse mb > > = return . Monad.join But I ca n't think of any other Traversables I want . I could generalize justm and rightm with: bind2 :: (Monad m1, Traversable m2, Monad m2) => m1 (m2 a) -> (a -> m1 (m2 b)) -> m1 (m2 b) bind2 ma mb = ma >>= traverse mb >>= return . Monad.join But I can't think of any other Traversables I want. -} | Return the first action to return Just . firstJust :: Monad m => m (Maybe a) -> m (Maybe a) -> m (Maybe a) firstJust action alternative = maybe alternative (return . Just) =<< action firstJusts :: Monad m => [m (Maybe a)] -> m (Maybe a) firstJusts = foldr firstJust (return Nothing) The names are chosen to be consistent with the @errors@ package . justErr :: err -> Maybe a -> Either err a justErr err = maybe (Left err) Right tryJust :: Except.MonadError e m => e -> Maybe a -> m a tryJust err = maybe (Except.throwError err) return tryRight :: Except.MonadError e m => Either e a -> m a tryRight = either Except.throwError return rethrow :: Except.MonadError e m => (e -> e) -> m a -> m a rethrow modify action = action `Except.catchError` \e -> Except.throwError (modify e)
1874907c8de3198f17faffceffa387916dd2c04dff7333950a283e0f07ac8975
frankiesardo/sicp-in-clojure
chapter-2.clj
(ns sicp.ch2) Exercise 2.1 . ;; Define a better version of make-rat that handles both positive and negative arguments. ;; Make-rat should normalize the sign so that if the rational number is positive, both the numerator and denominator are positive, and if the rational number is negative, only the numerator is negative. (defn add-rat [x y] (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (defn sub-rat [x y] (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (defn mul-rat [x y] (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (defn div-rat [x y] (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (defn equal-rat? [x y] (= (* (numer x) (denom y)) (* (numer y) (denom x)))) (defn make-rat [n d] [n d]) (defn numer [r] (first r)) (defn denom [r] (second r)) (defn print-rat [r] (println-str (numer r) "/" (denom r))) (def one-half (make-rat 1 2)) (print-rat one-half) (def one-third (make-rat 1 3)) (print-rat (add-rat one-half one-third)) (print-rat (mul-rat one-half one-third)) (print-rat (add-rat one-third one-third)) (defn gcd [a b] (if (= b 0) a (gcd b (rem a b)))) (defn make-rat [n d] (let [g (gcd n d)] [(/ n g) (/ d g)])) (print-rat (add-rat one-third one-third)) (defn make-rat-better [n d] (if (< d 0) (make-rat (* -1 n) (* -1 d)) (make-rat n d))) (make-rat-better 6 -7) Exercise 2.2 (defn make-segment [a b] [a b]) (defn start-segment [s] (first s)) (defn end-segment [s] (second s)) (defn make-point [x y] [x y]) (defn x-point [p] (first p)) (defn y-point [p] (second p)) (defn print-point [p] (println-str "(" (x-point p) "," (y-point p) ")")) (defn midpoint-segment [s] (make-point (/ (+ (x-point (start-segment s)) (x-point (end-segment s))) 2) (/ (+ (y-point (start-segment s)) (y-point (end-segment s))) 2) )) (def segment (make-segment (make-point -3 4) (make-point 1 2))) (print-point (midpoint-segment segment)) Exercise 2.3 (defn make-rect [left-right-diagonal] left-right-diagonal) (defn rec-width [r] (Math/abs (- (x-point (start-segment r)) (x-point (end-segment r))))) (defn rec-height [r] (Math/abs (- (y-point (end-segment r)) (y-point (start-segment r))))) (defn rec-perimeter [r] (+ (* 2 (rec-height r)) (* 2 (rec-width r)))) (defn rec-area [r] (* (rec-height r) (rec-width r))) (rec-perimeter (make-rect segment)) (rec-area (make-rect segment)) (defn make-rect [width height top-left-point] [width height top-left-point]) (defn rec-width [r] (first r)) (defn rec-height [r] (second r)) (rec-perimeter (make-rect 4 2 :top-left-point)) (rec-area (make-rect 4 2 :top-left-point)) Exercise 2.4 (defn cons' [x y] (fn [m] (m x y))) (defn car' [z] (z (fn [p q] p))) (defn cdr' [z] (z (fn [p q] q))) (def pair (cons' :a :b)) (car' pair) (cdr' pair) Exercise 2.5 (defn cons' [a b] (* (Math/pow 2 a) (Math/pow 3 b))) (defn car' [x] (if (zero? (rem x 2)) (+ 1 (car' (/ x 2))) 0)) (defn cdr' [x] (if (zero? (rem x 3)) (+ 1 (cdr' (/ x 3))) 0)) (car' (cons' 3 4)) (cdr' (cons' 3 4)) ;; Exercise 2.6 (def zero (fn [f] (fn [x] x))) ((zero inc) 0) (defn add-1 [n] (fn [f] (fn [x] (f ((n f) x))))) (def one (fn [f] (fn [x] (f x)))) ((one inc) 0) (def two (fn [f] (fn [x] (f (f x))))) (defn plus [a b] (fn [f] (fn [x] ((a f)((b f) x))))) (def three (plus two one)) ((three inc) 0) (defn mult [a b] (fn [f] (fn [x] ((a (b f)) x)))) (def six (mult three two)) ((six inc) 0) (defn exp [a b] (fn [f] (fn [x] (((b a) f) x)))) (def sixty-four (exp two six)) ((sixty-four inc) 0) Exercise 2.7 (defn make-interval [a b] [a b]) (defn lower-bound [i] (first i)) (defn upper-bound [i] (second i)) (defn add-interval [x y] (make-interval (+ (lower-bound x) (lower-bound y)) (+ (upper-bound x) (upper-bound y)))) (defn mul-interval [x y] (let [p1 (* (lower-bound x) (lower-bound y)) p2 (* (lower-bound x) (upper-bound y)) p3 (* (upper-bound x) (lower-bound y)) p4 (* (upper-bound x) (upper-bound y))] (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4)))) (defn div-interval [x y] (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y))))) Exercise 2.8 (defn sub-interval [x y] (make-interval (- (lower-bound x) (upper-bound y)) (- (upper-bound x) (lower-bound y)))) Exercise 2.9 (defn width-interval [i] (- (upper-bound i) (lower-bound i))) (def interval1 (make-interval 9.5 12)) (def interval2 (make-interval 3.5 7.5)) (def interval3 (make-interval 0.5 4.5)) (= (width-interval (add-interval interval1 interval2)) (width-interval (add-interval interval1 interval3))) (= (width-interval (sub-interval interval1 interval2)) (width-interval (sub-interval interval1 interval3))) (not= (width-interval (mul-interval interval1 interval2)) (width-interval (mul-interval interval1 interval3))) (not= (width-interval (div-interval interval1 interval2)) (width-interval (div-interval interval1 interval3))) Exercise 2.10 (defn includes-zero? [interval] (and (<= (lower-bound interval) 0) (>= (upper-bound interval) 0))) (defn div-interval [x y] (if (includes-zero? y) (throw (ArithmeticException. "Divide by zero")) (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y)))))) Exercise 2.11 (defn mul-interval [x y] (let [xlo (lower-bound x) xup (upper-bound x) ylo (lower-bound y) yup (upper-bound y)] (cond (and (>= xlo 0) (>= xup 0) (>= ylo 0) (>= yup 0)) ; [+, +] * [+, +] (make-interval (* xlo ylo) (* xup yup)) (and (>= xlo 0) (>= xup 0) (<= ylo 0) (>= yup 0)) ; [+, +] * [-, +] (make-interval (* xup ylo) (* xup yup)) (and (>= xlo 0) (>= xup 0) (<= ylo 0) (<= yup 0)) ; [+, +] * [-, -] (make-interval (* xup ylo) (* xlo yup)) (and (<= xlo 0) (>= xup 0) (>= ylo 0) (>= yup 0)) ; [-, +] * [+, +] (make-interval (* xlo yup) (* xup yup)) (and (<= xlo 0) (>= xup 0) (<= ylo 0) (>= yup 0)) ; [-, +] * [-, +] (make-interval (min (* xup ylo) (* xlo yup)) (max (* xlo ylo) (* xup yup))) (and (<= xlo 0) (>= xup 0) (<= ylo 0) (<= yup 0)) ; [-, +] * [-, -] (make-interval (* xup ylo) (* xlo ylo)) (and (<= xlo 0) (<= xup 0) (>= ylo 0) (>= yup 0)) ; [-, -] * [+, +] (make-interval (* xlo yup) (* xup ylo)) (and (<= xlo 0) (<= xup 0) (<= ylo 0) (>= yup 0)) ; [-, -] * [-, +] (make-interval (* xlo yup) (* xlo ylo)) (and (<= xlo 0) (<= xup 0) (<= ylo 0) (<= yup 0)) ; [-, -] * [-, -] (make-interval (* xup yup) (* xlo ylo))))) (mul-interval interval1 interval2) Exercise 2.12 (defn make-center-width [c w] (make-interval (- c w) (+ c w))) (defn center [i] (/ (+ (lower-bound i) (upper-bound i)) 2)) (defn width [i] (/ (- (upper-bound i) (lower-bound i)) 2)) (defn make-center-percent [c p] (let [w (* c (/ p 100.0))] (make-center-width c w))) (defn percent [i] (* (/ (width i) (center i)) 100.0)) (make-center-width 100 15) (make-center-percent 100 15) Exercise 2.13 (def small-perc1 (make-center-percent 10 2)) (def small-perc2 (make-center-percent 30 7)) ~ 9 Exercise 2.14 (defn par1 [r1 r2] (div-interval (mul-interval r1 r2) (add-interval r1 r2))) (defn par2 [r1 r2] (let [one (make-interval 1 1)] (div-interval one (add-interval (div-interval one r1) (div-interval one r2))))) (par1 interval1 interval2) (par2 interval1 interval2) (def should-be-one (div-interval interval1 interval1)) (center should-be-one) (percent interval1) ;; Exercise 2.15 > Because diving an interval by itself does not yield one , so repeating the same iterval in the formula introduces errors when you simplify it . Exercise 2.16 ;> #Dependency_problem Exercise 2.17 (defn last-pair [l] (if (empty? (rest l)) (first l) (last-pair (rest l)))) (last-pair [1 2 3 4]) Exercise 2.18 (defn append [l1 l2] (if (empty? l1) [l2] (cons (first l1) (append (rest l1) l2)))) (append [1 2] [3 4]) (defn reverse' [l] (if (empty? l) l (append (reverse' (rest l)) (first l)))) (reverse' [1 2 3 4 5]) Exercise 2.19 (def us-coins (list 50 25 10 5 1)) (def uk-coins (list 100 50 20 10 5 2 1)) (defn no-more? [coin-values] (empty? coin-values)) (defn first-denomination [coin-values] (first coin-values)) (defn except-first-denomination [coin-values] (rest coin-values)) (defn cc [amount coin-values] (cond (= amount 0) 1 (or (< amount 0) (no-more? coin-values)) 0 :else (+ (cc amount (except-first-denomination coin-values)) (cc (- amount (first-denomination coin-values)) coin-values)))) (cc 100 us-coins) (cc 100 uk-coins) (cc 100 (reverse uk-coins)) (cc 100 (reverse us-coins)) ; Order does not matter because the execution is a decision tree Exercise 2.20 (defn same-parity [pivot & more] (cons pivot (same-parity' pivot more))) (defn same-parity' [pivot candidates] (if-let [candidate (first candidates)] (if (= (rem pivot 2) (rem candidate 2)) (cons candidate (same-parity' pivot (rest candidates))) (same-parity' pivot (rest candidates))))) (same-parity 1) (same-parity 1 2 3 4 5 6 7 8 9 ) Exercise 2.21 (defn square-list [items] (if (empty? items) [] (cons (* (first items) (first items)) (square-list (rest items))))) (square-list [1 23 4 5]) (defn square-list [items] (map #(* % %) items)) (square-list [1 23 4 5]) Exercise 2.22 (defn square-list [items] (defn iter [things answer] (if (empty? things) answer (iter (rest things) (cons (#(* % %) (first things)) answer)))) (iter items [])) (square-list [1 2 3 4]) cons insert element to first position (defn square-list [items] (defn iter [things answer] (if (empty? things) answer (iter (rest things) (cons answer (#(* % %) (first things)))))) (iter items nil)) ; This should fail (square-list [1 2 3 4]) ; cons takes an element and a list. In that example we should use append Exercise 2.23 (defn for-each [f items] (let [head (first items)] (when head (f head) (for-each f (rest items))))) (for-each println [1 2 3]) Exercise 2.24 (list 1 (list 2 (list 3 4))) Exercise 2.25 (first (rest (first (rest (rest '(1 3 (5 7) 9)))))) (first (first '((7)))) (first (rest (first (rest (first (rest (first (rest (first (rest (first (rest '(1 (2 (3 (4 (5 (6 7)))))))))))))))))) Exercise 2.26 (def x (list 1 2 3)) (def y (list 4 5 6)) > ( 1 2 3 4 5 6 ) > ( ( 1 2 3 ) 4 5 6 ) > ( ( 1 2 3 ) ( 4 5 6 ) ) Exercise 2.27 (defn deep-reverse [l] (when-let [head (first l)] (append (deep-reverse (rest l)) (if (coll? head) (deep-reverse head) head)))) (deep-reverse [1 2 3 [1 2 3 [4 5 6]]]) Exercise 2.28 (defn fringe [tree] (cond (nil? tree) [] (not (coll? tree)) [tree] :else (concat (fringe (first tree)) (fringe (next tree))))) (fringe [1 2 3 [1 2 3 [4 5 6]]]) Exercise 2.29 (defn make-mobile [left right] [left right]) (defn make-branch [length structure] [length structure]) (defn left-branch [mobile] (mobile 0)) (defn right-branch [mobile] (mobile 1)) (defn branch-length [branch] (branch 0)) (defn branch-structure [branch] (branch 1)) (defn branch-weight [branch] (let [structure (branch-structure branch)] (if (number? structure) structure (total-weight structure)))) (defn total-weight [mobile] (+ (branch-weight (left-branch mobile)) (branch-weight (right-branch mobile)))) (def unbalanced-mobile (make-mobile (make-branch 1 (make-mobile (make-branch 2 3) (make-branch 4 5) ) ) (make-branch 3 (make-mobile (make-branch 4 5) (make-branch 6 7) ) ) ) ) (total-weight unbalanced-mobile) (defn balanced-branch? [branch] (let [structure (branch-structure branch)] (if (number? structure) true (balanced? structure)))) (defn balanced? [mobile] (let [lb (left-branch mobile) rb (right-branch mobile)] (and (balanced-branch? lb) (balanced-branch? rb) (= (* (branch-length lb) (branch-weight lb)) (* (branch-length rb) (branch-weight rb)))))) (balanced? unbalanced-mobile) (def balanced-mobile (make-mobile (make-branch 2 (make-mobile (make-branch 6 7) (make-branch 14 3) ) ) (make-branch 5 4) ) ) (balanced? balanced-mobile) ;; Exercise 2.30 (defn square-tree [tree] (cond (not (coll? tree)) (* tree tree) (empty? tree) nil :else (cons (square-tree (first tree)) (square-tree (rest tree))))) (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) (defn square-tree [tree] (map (fn [sub-tree] (if (coll? sub-tree) (square-tree sub-tree) (* sub-tree sub-tree))) tree)) (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) Exercise 2.31 (defn tree-map [f tree] (map (fn [sub-tree] (if (coll? sub-tree) (tree-map f sub-tree) (f sub-tree))) tree)) (tree-map #(* % %) (list 1 (list 2 (list 3 4) 5) (list 6 7))) Exercise 2.32 (defn subsets [s] (if (nil? s) [[]] (let [rest (subsets (next s))] (concat rest (map #(cons (first s) %) rest))))) Exercise 2.33 (defn accumulate [op initial sequence] (if (empty? sequence) initial (op (first sequence) (accumulate op initial (rest sequence))))) (defn map' [p sequence] (accumulate (fn [x y] (cons (p x) y)) [] sequence)) (map' #(* % 2) [1 2 3]) (defn append [seq1 seq2] (accumulate cons seq2 seq1)) (append [1 2 3 4] [5 6 7]) (defn length [sequence] (accumulate (fn [x y] (+ y 1)) 0 sequence)) (length [:one :two :three :four]) Exercise 2.34 (defn horner-eval [x coefficient-sequence] (accumulate (fn [this-coeff higher-terms] (+ this-coeff (* x higher-terms))) 0 coefficient-sequence)) (horner-eval 2 (list 1 3 0 5 0 1)) Exercise 2.35 (defn count-leaves [t] (accumulate + 0 (map (fn [x] 1) (fringe t)))) (count-leaves [1 [2 [5 [6]]] 3 [ 1 2 [ 3 4]]]) Exercise 2.36 (defn accumulate-n [op init seqs] (if (empty? (first seqs)) nil (cons (accumulate op init (map first seqs)) (accumulate-n op init (map rest seqs))))) (accumulate-n + 0 [[1 2 3] [4 5 6] [7 8 9]]) Exercise 2.37 (defn dot-product [v w] (accumulate + 0 (map * v w))) (defn matrix-*-vector [m v] (map #(dot-product v %) m)) (defn transpose [mat] (accumulate-n cons [] mat)) (defn matrix-*-matrix [m n] (let [cols (transpose n)] (map #(matrix-*-vector cols %) m))) (def v (list 1 3 -5)) (def w (list 4 -2 -1)) > 3 (def m (list (list 1 2 3) (list 4 5 6))) (matrix-*-vector m v) ;> [-8 -11] (def n (list (list 14 9 3) (list 2 11 15))) (matrix-*-matrix m n) Exercise 2.38 (defn fold-right [op initial sequence] (if (nil? sequence) initial (op (first sequence) (fold-right op initial (next sequence))))) (defn fold-left [op initial sequence] (defn iter [result rest] (if (nil? rest) result (iter (op result (first rest)) (next rest)))) (iter initial sequence)) (fold-right / 1 (list 1 2 3)) (/ 1 (/ 2 (/ 3 1))) (fold-left / 1 (list 1 2 3)) (/ (/ (/ 1 1) 2) 3) (fold-right list nil (list 1 2 3)) (fold-left list nil (list 1 2 3)) (fold-right + 0 (list 1 2 3)) (fold-left + 0 (list 1 2 3)) Exercise 2.39 (defn reverse [sequence] (fold-right (fn [x y] (append y [x])) [] sequence)) (reverse [1 2 3]) (defn reverse [sequence] (fold-left (fn [x y] (cons y x)) [] sequence)) (reverse [1 2 3]) ;; Exercise 2.40 (defn unique-pairs [n] (mapcat (fn [i] (map (fn [j] [i j]) (range 1 i))) (range 1 (inc n)))) (unique-pairs 4) (defn prime? [n] (-> n (bigint) (.toBigInteger) (.isProbablePrime 100))) (defn prime-sum? [[x y]] (prime? (+ x y))) (defn make-pair-sum [[x y]] [x y (+ x y)]) (defn prime-sum-pairs [n] (map make-pair-sum (filter prime-sum? (unique-pairs n)))) (prime-sum-pairs 6) Exercise 2.41 (defn unique-triplets [n] (mapcat (fn [i] (mapcat (fn [j] (map (fn [k] [i j k]) (range 1 j))) (range 1 i))) (range 1 (inc n)))) (defn make-triplet-sum [[x y z]] [x y z (+ x y z)]) (defn sum-to [[x y z] n] (= n (+ x y z))) (defn sum-triplets [n] (map make-triplet-sum (filter #(sum-to % n) (unique-triplets n)))) (sum-triplets 15) Exercise 2.42 (def empty-board []) (defn adjoin-position [new-row col rest-of-queens] (cons new-row rest-of-queens)) (defn safe? [k positions] (def candidate (first positions)) (defn safe-iter [top bot remain] (cond (empty? remain) true (or (= (first remain) candidate) (= (first remain) top) (= (first remain) bot)) false :else (safe-iter (- top 1) (+ bot 1) (rest remain)))) (safe-iter (- candidate 1) (+ candidate 1) (rest positions))) (defn queens [board-size] (defn queen-cols [k] (if (= k 0) (list empty-board) (filter (fn [positions] (safe? k positions)) (mapcat (fn [rest-of-queens] (map (fn [new-row] (adjoin-position new-row k rest-of-queens)) (range 1 (inc board-size)))) (queen-cols (dec k)))))) (queen-cols board-size)) (queens 4) Exercise 2.42 (defn queens [board-size] (defn queen-cols [k] (if (= k 0) (list empty-board) (filter (fn [positions] (safe? k positions)) (mapcat (fn [new-row] (map (fn [rest-of-queens] (adjoin-position new-row k rest-of-queens)) (queen-cols (dec k)))) (range 1 (inc board-size)))))) (queen-cols board-size)) Exercise 2.43 ( queens 6 ) - > from linear recursive to tree recursive = T^board - size Exercise 2.44 (defn below [p1 p2] :new-painter) (defn beside [p1 p2] :new-painter) (defn up-split [painter n] (if (= n 0) painter (let [smaller (up-split painter (- n 1))] (below painter (beside smaller smaller))))) Exercise 2.45 (defn split [split1 split2] (fn [painter n] (if (= n 0) painter (let [smaller (split painter (dec n))] (split1 painter (split2 smaller smaller)))))) (def right-split (split beside below)) (def up-split (split below beside)) Exercise 2.46 (defn make-vect [x y]) (defn xcor-vect [v] (v 0)) (defn ycor-vect [v] (v 1)) (defn add-vect [v1 v2] (make-vect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2)))) (defn sub-vect [v1 v2] (make-vect (- (xcor-vect v1) (xcor-vect v2)) (- (ycor-vect v1) (ycor-vect v2)))) (defn scale-vect [v s] (make-vect (* s (xcor-vect v)) (* (ycor-vect v)))) Exercise 2.47 (defn make-frame [origin edge1 edge2] [origin edge1 edge2]) (defn origin-frame [f] (f 0)) (defn edge1-frame [f] (f 1)) (defn edge2-frame [f] (f 2)) (defn make-frame [origin edge1 edge2] (cons origin [edge1 edge2])) (defn origin-frame [f] (f 0)) (defn edge1-frame [f] ((f 0) 0)) (defn edge2-frame [f] ((f 0) 1)) Exercise 2.48 (defn make-segment [v1 v2] [v1 v2]) (defn start-segment [s] (s 0)) (defn end-segment [s] (s 1)) Exercise 2.49 ; The painter that draws the outline of the designated frame. (def outline-segments (list (make-segment (make-vect 0.0 0.0) (make-vect 0.0 0.99)) (make-segment (make-vect 0.0 0.0) (make-vect 0.99 0.0)) (make-segment (make-vect 0.99 0.0) (make-vect 0.99 0.99)) (make-segment (make-vect 0.0 0.99) (make-vect 0.99 0.99)))) ; The painter that draws an 'X' by connecting opposite corners of the frame. (def x-segments (list (make-segment (make-vect 0.0 0.0) (make-vect 0.99 0.99)) (make-segment (make-vect 0.0 0.99) (make-vect 0.99 0.0)))) ; The painter that draws a diamond shape by connecting the midpoints of the sides of the frame. (def diamond-segments (list (make-segment (make-vect 0.0 0.5) (make-vect 0.5 0.0)) (make-segment (make-vect 0.0 0.5) (make-vect 0.5 0.99)) (make-segment (make-vect 0.5 0.99) (make-vect 0.99 0.5)) (make-segment (make-vect 0.99 0.5) (make-vect 0.5 0.0)))) ; The wave painter. (def wave-segments (list (make-segment (make-vect 0.006 0.840) (make-vect 0.155 0.591)) (make-segment (make-vect 0.006 0.635) (make-vect 0.155 0.392)) (make-segment (make-vect 0.304 0.646) (make-vect 0.155 0.591)) (make-segment (make-vect 0.298 0.591) (make-vect 0.155 0.392)) (make-segment (make-vect 0.304 0.646) (make-vect 0.403 0.646)) (make-segment (make-vect 0.298 0.591) (make-vect 0.354 0.492)) (make-segment (make-vect 0.403 0.646) (make-vect 0.348 0.845)) (make-segment (make-vect 0.354 0.492) (make-vect 0.249 0.000)) (make-segment (make-vect 0.403 0.000) (make-vect 0.502 0.293)) (make-segment (make-vect 0.502 0.293) (make-vect 0.602 0.000)) (make-segment (make-vect 0.348 0.845) (make-vect 0.403 0.999)) (make-segment (make-vect 0.602 0.999) (make-vect 0.652 0.845)) (make-segment (make-vect 0.652 0.845) (make-vect 0.602 0.646)) (make-segment (make-vect 0.602 0.646) (make-vect 0.751 0.646)) (make-segment (make-vect 0.751 0.646) (make-vect 0.999 0.343)) (make-segment (make-vect 0.751 0.000) (make-vect 0.597 0.442)) (make-segment (make-vect 0.597 0.442) (make-vect 0.999 0.144)))) Exercise 2.50 (defn frame-coord-map [frame] (fn [v] (add-vect (origin-frame frame) (add-vect (scale-vect (xcor-vect v) (edge1-frame frame)) (scale-vect (ycor-vect v) (edge2-frame frame)))))) (defn transform-painter [painter origin corner1 corner2] (fn [frame] (let [m (frame-coord-map frame) new-origin (m origin)] (painter (make-frame new-origin (sub-vect (m corner1) new-origin) (sub-vect (m corner2) new-origin)))))) (defn flip-horiz [painter] ((transform-painter (make-vect 1.0 0.0) (make-vect 0.0 0.0) (make-vect 1.0 1.0)) painter)) (defn rotate180 [painter] ((transform-painter (make-vect 1.0 1.0) (make-vect 0.0 1.0) (make-vect 1.0 0.0)) painter)) (defn rotate270 [painter] ((transform-painter (make-vect 0.0 1.0) (make-vect 0.0 0.0) (make-vect 1.0 1.0)) painter)) Exercise 2.51 (defn beside [painter1 painter2] (let [split-point (make-vect 0.5 0.0) paint-left (transform-painter painter1 (make-vect 0.0 0.0) split-point (make-vect 0.0 1.0)) paint-right (transform-painter painter2 split-point (make-vect 1.0 0.0) (make-vect 0.5 1.0)) ] (fn [frame] (paint-left frame) (paint-right frame)))) (defn below [painter1 painter2] (let [split-point (make-vect 0.0 0.5) paint-bottom ((transform-painter (make-vect 0.0 0.0) (make-vect 1.0 0.0) split-point) painter1) paint-top ((transform-painter split-point (make-vect 1.0 0.5) (make-vect 0.0 1.0)) painter2) ] (fn [frame] (paint-bottom frame) (paint-top frame)))) (defn rotate90 [painter] ((transform-painter (make-vect 1.0 0.0) (make-vect 1.0 1.0) (make-vect 0.0 0.0)) painter)) (defn below [painter1 painter2] (rotate90 (beside (rotate270 painter1) (rotate270 painter2)))) Exercise 2.52 (def wave-segments (list (make-segment (make-vect 0.006 0.840) (make-vect 0.155 0.591)) (make-segment (make-vect 0.006 0.635) (make-vect 0.155 0.392)) (make-segment (make-vect 0.304 0.646) (make-vect 0.155 0.591)) (make-segment (make-vect 0.298 0.591) (make-vect 0.155 0.392)) (make-segment (make-vect 0.304 0.646) (make-vect 0.403 0.646)) (make-segment (make-vect 0.298 0.591) (make-vect 0.354 0.492)) (make-segment ; left face (make-vect 0.403 0.646) (make-vect 0.348 0.845)) (make-segment (make-vect 0.354 0.492) (make-vect 0.249 0.000)) (make-segment (make-vect 0.403 0.000) (make-vect 0.502 0.293)) (make-segment (make-vect 0.502 0.293) (make-vect 0.602 0.000)) (make-segment (make-vect 0.348 0.845) (make-vect 0.403 0.999)) (make-segment (make-vect 0.602 0.999) (make-vect 0.652 0.845)) (make-segment (make-vect 0.652 0.845) (make-vect 0.602 0.646)) (make-segment (make-vect 0.602 0.646) (make-vect 0.751 0.646)) (make-segment (make-vect 0.751 0.646) (make-vect 0.999 0.343)) (make-segment (make-vect 0.751 0.000) (make-vect 0.597 0.442)) (make-segment (make-vect 0.597 0.442) (make-vect 0.999 0.144)) (make-segment ; eye (make-vect 0.395 0.916) (make-vect 0.410 0.916)) (make-segment ; smile (make-vect 0.376 0.746) (make-vect 0.460 0.790)))) (defn corner-split [painter n] (if (= n 0) painter (let [up (up-split painter (- n 1)) right (right-split painter (- n 1)) corner (corner-split painter (- n 1))] (beside (below painter up) (below right corner))))) (defn flip-vert [painter] (transform-painter painter (make-vect 0.0 1.0) ; new origin (make-vect 1.0 1.0) ; new end of edge1 (make-vect 0.0 0.0))) ; new end of edge2 (defn square-limit [painter n] (let [quarter (rotate180 (corner-split painter n)) half (beside (flip-horiz quarter) quarter)] (below (flip-vert half) half))) Exercise 2.53 (defn memq [item x] (cond (empty? x) false (= item (first x)) x :else (memq item (rest x)))) (list 'a 'b 'c) (list (list 'george)) (rest '((x1 x2) (y1 y2))) (first '((x1 x2) (y1 y2))) (coll? (first '(a short list))) (memq 'red '((red shoes) (blue socks))) (memq 'red '(red shoes blue socks)) Exercise 2.54 (defn equal? [a b] (cond (and (symbol? a) (symbol? b) (= a b)) true (and (coll? a) (coll? b) (= (first a) (first b))) (equal? (rest a) (rest b)) :else false)) Exercise 2.55 (first ''abracadabra) ; -> ''abracadabra yields (quote abracadabra) Exercise 2.55 (defn variable? [x] (symbol? x)) (defn same-variable? [v1 v2] (and (variable? v1) (variable? v2) (= v1 v2))) (defn make-sum [a1 a2] (cond (= a1 0) a2 (= a2 0) a1 (and (number? a1) (number? a2)) (+ a1 a2) :else (list '+ a1 a2))) (defn make-product [m1 m2] (cond (or (= m1 0) (= m2 0)) 0 (= m1 1) m2 (= m2 1) m1 (and (number? m1) (number? m2)) (* m1 m2) :else (list '* m1 m2))) (defn sum? [x] (and (coll? x) (= (first x) '+))) (defn addend [s] (second s)) (defn augend [s] (second (rest s))) (defn product? [x] (and (coll? x) (= (first x) '*))) (defn multiplier [p] (second p)) (defn multiplicand [p] (second (rest p))) (defn deriv [exp var] (cond (number? exp) 0 (variable? exp) (if (same-variable? exp var) 1 0) (sum? exp) (make-sum (deriv (addend exp) var) (deriv (augend exp) var)) (product? exp) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp))) :else (throw (Exception. "unknown expression type -- DERIV" exp)))) Exercise 2.56 (defn exponentiation? [x] (and (coll? x) (= (first x) '**))) (defn base [p] (second p)) (defn exponent [p] (second (rest p))) (defn make-exponentiation [b e] (cond (= e 0) 1 (= e 1) b (or (= b 1) (= b 0)) b :else (list '** b e))) (defn deriv [exp var] (cond (number? exp) 0 (variable? exp) (if (same-variable? exp var) 1 0) (sum? exp) (make-sum (deriv (addend exp) var) (deriv (augend exp) var)) (product? exp) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp))) (exponentiation? exp) (make-product (make-product (exponent exp) (make-exponentiation (base exp) (dec (exponent exp)))) (deriv (base exp) var) ) :else (throw (Exception. "unknown expression type -- DERIV" exp)))) Exercise 2.57 (defn augend [s] (let [a (rest (drop 1 s))] (if (= 1 (count a)) a (cons '+ a)))) (defn multiplicand [s] (let [m (rest (drop 1 s))] (if (= 1 (count m)) m (cons '* m)))) Exercise 2.58 (defn make-sum [a1 a2] (cond (= a1 0) a2 (= a2 0) a1 (and (number? a1) (number? a2)) (+ a1 a2) :else (list a1 '+ a2))) (defn make-product [m1 m2] (cond (or (= m1 0) (= m2 0)) 0 (= m1 1) m2 (= m2 1) m1 (and (number? m1) (number? m2)) (* m1 m2) :else (list m1 '* m2))) (defn sum? [x] (and (coll? x) (= (second x) '+))) (defn addend [s] (first s)) (defn augend [s] (second (rest s))) (defn product? [x] (and (coll? x) (= (second x) '*))) (defn multiplier [p] (first p)) (defn multiplicand [p] (second (rest p))) (defn exponentiation? [x] (and (coll? x) (= (second x) '**))) (defn base [p] (first p)) (defn exponent [p] (second (rest p))) (defn make-exponentiation [b e] (cond (= e 0) 1 (= e 1) b (or (= b 1) (= b 0)) b :else (list b '** e))) ; b) (defn sum? [x] (check-symbol '+ x)) (defn addend [s] (left '+ s)) (defn augend [s] (right '+ s)) (defn product? [x] (check-symbol '* x)) (defn multiplier [p] (left '* p)) (defn multiplicand [p] (right '* p)) (defn exponentiation? [x] (check-symbol '** x)) (defn base [e] (left '** e)) (defn exponent [e] (right '** e)) (defn check-symbol [s x] (and (coll? x) (memq s x))) (defn left [s x] (let [exp (take-while #(not= % s) x)] (if (= 1 (count exp)) (first exp) exp))) (defn right [s x] (let [exp (rest (memq s x))] (if (= 1 (count exp)) (first exp) exp))) (defn make-sum [a1 a2] (cond (= a1 0) a2 (= a2 0) a1 (and (number? a1) (number? a2)) (+ a1 a2) (and (coll? a1) (coll? a2)) (concat a1 '(+) a2) (coll? a1) (concat a1 ['+ a2]) (coll? a2) (concat [a1 '+] a2) :else (list a1 '+ a2))) (defn make-product [m1 m2] (cond (or (= m1 0) (= m2 0)) 0 (= m1 1) m2 (= m2 1) m1 (and (number? m1) (number? m2)) (* m1 m2) (and (coll? m1) (coll? m2) (not (sum? m1)) (not (sum? m2))) (concat m1 '(*) m2) (and (coll? m1) (not (sum? m1))) (concat m1 ['* m2]) (and (coll? m2) (not (sum? m2))) (concat [m1 '*] m2) :else (list m1 '* m2))) (defn make-exponentiation [b e] (cond (= e 0) 1 (= e 1) b (or (= b 1) (= b 0)) b (and (number? b) (number? e)) (* b e) :else (list b '** e))) Exercise 2.59 (defn element-of-set? [x set] (cond (empty? set) false (= x (first set)) true :else (element-of-set? x (rest set)))) (defn adjoin-set [x set] (if (element-of-set? x set) set (cons x set))) (defn intersection-set [set1 set2] (cond (or (empty? set1) (empty? set2)) '() (element-of-set? (first set1) set2) (cons (first set1) (intersection-set (rest set1) set2)) :else (intersection-set (rest set1) set2))) (defn union-set [set1 set2] (cond (empty? set1) set2 (element-of-set? (first set1) set2) (union-set (rest set1) set2) :else (union-set (rest set1) (cons (first set1) set2)))) Exercise 2.60 (defn element-of-set? [x set] (cond (empty? set) false (= x (first set)) true :else (element-of-set? x (rest set)))) (defn adjoin-set [x set] (cons x set)) (defn intersection-set [set1 set2] (cond (or (empty? set1) (empty? set2)) '() (element-of-set? (first set1) set2) (cons (first set1) (intersection-set (rest set1) set2)) :else (intersection-set (rest set1) set2))) (defn union-set [set1 set2] (concat set1 set2)) Exercise 2.61 (defn element-of-set? [x set] (cond (empty? set) false (= x (first set)) true (< x (first set)) false :else (element-of-set? x (rest set)))) (defn intersection-set [set1 set2] (if (or (empty? set1) (empty? set2)) [] (let [x1 (first set1) x2 (first set2)] (cond (= x1 x2) (cons x1 (intersection-set (rest set1) (rest set2))) (< x1 x2) (intersection-set (rest set1) set2) (< x2 x1) (intersection-set set1 (rest set2)))))) (defn adjoin-set [x set] (cond (empty? set) (cons x set) (= x (first set)) set (< x (first set)) (cons x set) :else (cons (first set) (adjoin-set x (rest set))))) Exercise 2.62 (defn union-set [set1 set2] (cond (empty? set1) set2 (empty? set2) set1 :else (let [x1 (first set1) x2 (first set2)] (cond (= x1 x2) (cons x1 (union-set (rest set1) (rest set2))) (< x1 x2) (cons x1 (union-set (rest set1) set2)) (< x2 x1) (cons x2 (union-set set1 (rest set2))))))) Exercise 2.63 (defn entry [tree] (tree 0)) (defn left-branch [tree] (tree 1)) (defn right-branch [tree] (tree 2)) (defn make-tree [entry left right] [entry left right]) (defn element-of-set? [x set] (cond (empty? set) false (= x (entry set)) true (< x (entry set)) (element-of-set? x (left-branch set)) (> x (entry set)) (element-of-set? x (right-branch set)))) (defn adjoin-set [x set] (cond (empty? set) (make-tree x [] []) (= x (entry set)) set (< x (entry set)) (make-tree (entry set) (adjoin-set x (left-branch set)) (right-branch set)) (> x (entry set)) (make-tree (entry set) (left-branch set) (adjoin-set x (right-branch set))))) (defn tree->list-1 [tree] (if (empty? tree) [] (concat (tree->list-1 (left-branch tree)) (cons (entry tree) (tree->list-1 (right-branch tree)))))) (defn tree->list-2 [tree] (defn copy-to-list [tree result-list] (if (empty? tree) result-list (copy-to-list (left-branch tree) (cons (entry tree) (copy-to-list (right-branch tree) result-list))))) (copy-to-list tree [])) (def tree1 [7 [3 [1 [] []] [5 [] []]] [9 [] [11 [] []]]]) (tree->list-1 tree1) (tree->list-2 tree1) (def tree2 [3 [1 [] []] [7 [5 [] []] [9 [] [11 [] []]]]]) (tree->list-1 tree2) (tree->list-2 tree2) (def tree3 [5 [3 [1 [] []] []] [9 [7 [] []] [11 [] []]]]) (tree->list-1 tree3) (tree->list-2 tree3) ; In tree->list-1 concat is called on every recursive called ; Append is O(length) and the length is halves on each call so log n ; Total complexity tree->list-1 O(n logn) while tree->list-2 is just O(n) Exercise 2.64 (defn list->tree [elements] (first (partial-tree elements (count elements)))) (defn partial-tree [elts n] (if (= n 0) ([[] elts]) (let [left-size (quot (dec n) 2) left-result (partial-tree elts left-size) left-tree (first left-result) non-left-elts (second left-result) right-size (- n (inc left-size)) this-entry (first non-left-elts) right-result (partial-tree (rest non-left-elts) right-size) right-tree (first right-result) remaining-elts (second right-result) ] [(make-tree this-entry left-tree right-tree) remaining-elts]))) The important bit is to substract 1 in the calculation of left and right size so you can extract this - entry ; There is one recursive call for each element in the list with no expensive operands like concat so O(n) Exercise 2.65 Just use tree->list2 on the sets , feed them to the functions 2.61 2.62 and reconvert them back with list->tree Exercise 2.66 (defn lookup [given-key set-of-records] (cond (empty? set-of-records) false (= given-key (key (entry set-of-records))) (entry set-of-records) (< given-key (key (entry set-of-records))) (lookup given-key (left-branch set-of-records)) (> given-key (key (entry set-of-records))) (lookup given-key (right-branch set-of-records)))) Exercise 2.67 (defn make-leaf [symbol weight] ['leaf symbol weight]) (defn leaf? [object] (= (object 0) 'leaf)) (defn symbol-leaf [x] (x 1)) (defn weight-leaf [x] (x 2)) (defn make-code-tree [left right] [left right (concat (symbols left) (symbols right)) (+ (weight left) (weight right))]) (defn left-branch [tree] (tree 0)) (defn right-branch [tree] (tree 1)) (defn symbols [tree] (if (leaf? tree) [(symbol-leaf tree)] (tree 2))) (defn weight [tree] (if (leaf? tree) (weight-leaf tree) (tree 3))) (defn decode [bits tree] (defn decode-1 [bits current-branch] (if (empty? bits) [] (let [next-branch (choose-branch (first bits) current-branch)] (if (leaf? next-branch) (cons (symbol-leaf next-branch) (decode-1 (rest bits) tree)) (decode-1 (rest bits) next-branch))))) (decode-1 bits tree)) (defn choose-branch [bit branch] (cond (= bit 0) (left-branch branch) (= bit 1) (right-branch branch))) (defn adjoin-set [x set] (cond (empty? set) [x] (< (weight x) (weight (first set))) (cons x set) :else (cons (first set) (adjoin-set x (rest set))))) (defn make-leaf-set [pairs] (if (empty? pairs) [] (let [pair (first pairs)] (adjoin-set (make-leaf (first pair) ; symbol (second pair)) ; frequency (make-leaf-set (rest pairs)))))) (def sample-tree (make-code-tree (make-leaf 'A 4) (make-code-tree (make-leaf 'B 2) (make-code-tree (make-leaf 'D 1) (make-leaf 'C 1))))) (def sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0)) (decode sample-message sample-tree) Exercise 2.68 (defn encode [message tree] (if (empty? message) [] (concat (encode-symbol (first message) tree) (encode (rest message) tree)))) (defn encode-symbol [symbol tree] (defn in-branch? [branch] (if (leaf? branch) (= symbol (symbol-leaf branch)) (memq symbol (symbols branch)))) (let [lb (left-branch tree) rb (right-branch tree)] (cond (in-branch? lb) (if (leaf? lb) [0] (cons 0 (encode-symbol symbol lb))) (in-branch? rb) (if (leaf? rb) [1] (cons 1 (encode-symbol symbol rb))) :else (throw (RuntimeException. (str "Can't encode symbol " symbol)))))) (encode '(A D A B B C A) sample-tree) Exercise 2.69 (defn generate-huffman-tree [pairs] (successive-merge (make-leaf-set pairs))) (defn successive-merge [trees] (if (= 1 (count trees)) (first trees) (let [a (first trees) b (second trees) remainder (drop 2 trees) new-tree (make-code-tree a b) new-trees (adjoin-set new-tree remainder)] (successive-merge new-trees)))) (generate-huffman-tree #{'(A 8) '(B 3) '(C 1) '(D 1) '(E 1) '(F 1) '(G 1) '(H 1)}) Exercise 2.70 (def rock-tree (generate-huffman-tree #{'(a 2) '(boom 1) '(Get 2) '(job 2) '(na 16) '(Sha 3) '(yip 9) '(Wah 1)})) (def rock-lyric '(Get a job Sha na na na na na na na na Get a job Sha na na na na na na na na Wah yip yip yip yip yip yip yip yip yip Sha boom)) (def encoded-lyric (encode rock-lyric rock-tree)) (< (count encoded-lyric) (* 3 (count rock-lyric))) Exercise 2.71 Such tree always has a leaf on its left branch so the most frequent symbol is encoded with 1 bit and the least frequent with ( n - 1 ) bits Exercise 2.72 ; In a normal tree the complexity is O(n log n) ; In a skewed tree the complexity is O(n) for the most frequent and O(n^2) for the least frequent ; If a tree doesn't need to be modified we can store all the symbols in a map with their encodings for maximum performance ;; Exercise 2.73 ; a) Because they have no type tag on their data structure. We could in principle but we have to change their representation. ; b) (defn addend [s] (first s)) (defn augend [s] (second s)) (defn multiplier [p] (first p)) (defn multiplicand [p] (second p)) (defn operator [exp] (first exp)) (defn operands [exp] (rest exp)) (defn deriv [exp var] (cond (number? exp) 0 (variable? exp) (if (same-variable? exp var) 1 0) :else ((pt-get 'deriv (operator exp)) (operands exp) var))) (defn deriv-sum [exp var] (make-sum (deriv (addend exp) var) (deriv (augend exp) var))) (defn deriv-product [exp var] (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp)))) (def proc-table (atom {})) (defn pt-get [op type] (@proc-table [op type])) (defn pt-put [op type item] (swap! proc-table #(assoc % [op type] item))) (defn install-deriv [] (pt-put 'deriv '+ deriv-sum) (pt-put 'deriv '* deriv-product)) (install-deriv) (deriv '(* (+ x y) 3) 'x) ; c) (defn base [e] (first e)) (defn exponent [e] (second e)) (defn deriv-exponentiation [expr var] (let [base (base expr) exponent (exponent expr)] (make-product exponent (make-product (make-exponentiation base (make-sum exponent -1)) (deriv base var))))) (defn install-deriv [] (pt-put 'deriv '+ deriv-sum) (pt-put 'deriv '* deriv-product) (pt-put 'deriv '** deriv-exponentiation)) (install-deriv) (deriv '(** (+ x y) 3) 'x) ; d) We only need to change the way we save them Exercise 2.74 ; a) (defn make-hq-file [division file] (cons division file)) (defn file-division [hq-file] (first hq-file)) (defn original-file [hq-file] (second hq-file)) (defn get-record [employee hq-file] (let [get-record-fn (pt-get 'get-record (file-division hq-file))] (get-record-fn employee (original-file hq-file)))) (defn has-record? [employee division] (let [has-record?-fn (pt-get 'has-record? division)] (has-record?-fn employee))) ; b) (defn make-hq-record [division record] (cons division record)) (defn record-division [hq-record] (first hq-record)) (defn original-record [hq-record] (second hq-record)) (defn get-salary [hq-file] (let [get-salary-fn (pt-get 'get-salary (file-division hq-file))] (get-salary-fn (original-record hq-file)))) ; c) (defn find-employee-record [employee files] (cond (empty? files) (throw (RuntimeException. (str "FIND-EMPLOYEE-RECORD : No such employee." employee))) (has-record? employee (file-division (first files))) (get-record employee (first files)) :else (find-employee-record employee (rest files)))) ; d) (defn install-ultra-mega-corp [table] (assoc table 'get-record :ultra-mega-corp-get-record) (assoc table 'has-record? :ultra-mega-corp-has-record?) (assoc table 'get-salary :ultra-mega-corp-get-salary)) Exercise 2.75 (defn apply-generic [op arg] (arg op)) (defn make-from-mag-ang [m a] (defn dispatch [op] (cond (= op 'real-part) (* m (Math/cos a)) (= op 'imag-part) (* m (Math/sin a)) (= op 'magnitude) m (= op 'angle) a :else (throw (RuntimeException. (str "Unknown op -- MAKE-FROM-REAL-IMAG" op))))) dispatch) Exercise 2.76 Lots of new types - > message passing ( which is basically OO ) ; Lots of new operations -> data-directed style Exercise 2.77 (def proc-table (atom {})) (defn pt-get [op type] (@proc-table [op type])) (defn pt-put [op type item] (swap! proc-table #(assoc % [op type] item))) (defn type-tag [datum] (cond (number? datum) datum (coll? datum) (first datum) :else (throw (RuntimeException. (str "Wrong datum -- TYPE-TAG " datum))))) (defn contents [datum] (cond (number? datum) datum (coll? datum) (rest datum) :else (throw (RuntimeException. (str "Wrong datum -- CONTENGS " datum))))) (defn attach-tag [tag content] (if (coll? content) (cons tag content) content)) (defn gcd [a b] (if (= b 0) a (gcd b (rem a b)))) 2.77 (defn install-rectangular-package [] (let [real-part (fn [z] (first z)) imag-part (fn [z] (second z)) make-from-real-imag (fn [x y] [x y]) magnitude (fn [z] (Math/sqrt (+ (#(* % %) (real-part z)) (#(* % %) (imag-part z))))) angle (fn [z] (Math/atan2 (imag-part z) (real-part z))) make-from-mag-ang (fn [r a] [(* r (Math/cos a)) (* r (Math/sin a))]) tag (fn [x] (attach-tag 'rectangular x))] (pt-put 'real-part '(rectangular) real-part) (pt-put 'imag-part '(rectangular) imag-part) (pt-put 'magnitude '(rectangular) magnitude) (pt-put 'angle '(rectangular) angle) (pt-put 'make-from-real-imag 'rectangular (fn [x y] (tag (make-from-real-imag x y)))) (pt-put 'make-from-mag-ang 'rectangular (fn [r a] (tag (make-from-mag-ang r a)))))) (defn install-polar-package [] (let [magnitude (fn [z] (first z)) angle (fn [z] (second z)) make-from-mag-ang (fn [r a] [r a]) real-part (fn [z] (* (magnitude z) (Math/cos (angle z)))) imag-part (fn [z] (* (magnitude z) (Math/sin (angle z)))) make-from-real-imag (fn [x y] [(Math/sqrt (+ (#(* % %) x) (#(* % %) y))) (Math/atan2 y x)]) tag (fn [x] (attach-tag 'polar x))] (pt-put 'real-part '(polar) real-part) (pt-put 'imag-part '(polar) imag-part) (pt-put 'magnitude '(polar) magnitude) (pt-put 'angle '(polar) angle) (pt-put 'make-from-real-imag 'polar (fn [x y] (tag (make-from-real-imag x y)))) (pt-put 'make-from-mag-ang 'polar (fn [r a] (tag (make-from-mag-ang r a)))))) (defn apply-generic [op & args] (let [type-tags (map type-tag args) proc (pt-get op type-tags)] (if proc (apply proc (map contents args)) (throw (RuntimeException. (str "No method for -- " op type-tags)))))) (defn real-part [z] (apply-generic 'real-part z)) (defn imag-part [z] (apply-generic 'imag-part z)) (defn magnitude [z] (apply-generic 'magnitude z)) (defn angle [z] (apply-generic 'angle z)) (defn add [x y] (apply-generic 'add x y)) (defn sub [x y] (apply-generic 'sub x y)) (defn mul [x y] (apply-generic 'mul x y)) (defn div [x y] (apply-generic 'div x y)) (defn install-scheme-number-package [] (let [tag (fn [x] (attach-tag 'scheme-number x))] (pt-put 'add '(scheme-number scheme-number) (fn [x y] (tag (+ x y)))) (pt-put 'sub '(scheme-number scheme-number) (fn [x y] (tag (- x y)))) (pt-put 'mul '(scheme-number scheme-number) (fn [x y] (tag (* x y)))) (pt-put 'div '(scheme-number scheme-number) (fn [x y] (tag (/ x y)))) (pt-put 'make 'scheme-number (fn [x] (tag x))))) (defn make-scheme-number [n] ((pt-get 'make 'scheme-number) n)) (defn install-rational-package [] (let [numer (fn [x] (first x)) denom (fn [x] (second x)) make-rat (fn [n d] (let [g (gcd n d)] [(/ n g) (/ d g)])) add-rat (fn [x y] (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) sub-rat (fn [x y] (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) mul-rat (fn [x y] (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) div-rat (fn [x y] (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) tag (fn [x] (attach-tag 'rational x)) ] (pt-put 'add '(rational rational) (fn [x y] (tag (add-rat x y)))) (pt-put 'sub '(rational rational) (fn [x y] (tag (sub-rat x y)))) (pt-put 'mul '(rational rational) (fn [x y] (tag (mul-rat x y)))) (pt-put 'div '(rational rational) (fn [x y] (tag (div-rat x y)))) (pt-put 'make 'rational (fn [n d] (tag (make-rat n d)))))) (defn make-rational [n d] ((pt-get 'make 'rational) n d)) (defn install-complex-package [] (let [;; imported procedures from rectangular and polar packages make-from-real-imag (fn [x y] ((pt-get 'make-from-real-imag 'rectangular) x y)) make-from-mag-ang (fn [r a] ((pt-get 'make-from-mag-ang 'polar) r a)) add-complex (fn [z1 z2] (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) sub-complex (fn [z1 z2] (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) mul-complex (fn [z1 z2] (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) div-complex (fn [z1 z2] (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) tag (fn [z] (attach-tag 'complex z)) ] (pt-put 'add '(complex complex) (fn [z1 z2] (tag (add-complex z1 z2)))) (pt-put 'sub '(complex complex) (fn [z1 z2] (tag (sub-complex z1 z2)))) (pt-put 'mul '(complex complex) (fn [z1 z2] (tag (mul-complex z1 z2)))) (pt-put 'div '(complex complex) (fn [z1 z2] (tag (div-complex z1 z2)))) (pt-put 'make-from-real-imag 'complex (fn [x y] (tag (make-from-real-imag x y)))) (pt-put 'make-from-mag-ang 'complex (fn [r a] (tag (make-from-mag-ang r a)))))) (install-rectangular-package) (install-polar-package) (install-scheme-number-package) (install-rational-package) (install-complex-package) (defn make-complex-from-real-imag [x y] ((pt-get 'make-from-real-imag 'complex) x y)) (defn make-complex-from-mag-ang [r a] ((pt-get 'make-from-mag-ang 'complex) r a)) (def z (make-complex-from-mag-ang 8 6)) ; This fails (magnitude z) (pt-put 'real-part '(complex) real-part) (pt-put 'imag-part '(complex) imag-part) (pt-put 'magnitude '(complex) magnitude) (pt-put 'angle '(complex) angle) (magnitude z) apply - generic is invoked twice , first dispatch is magnitude of ' complex , second is magnitude of ' rectangular . Exercise 2.78 (defn type-tag [datum] (cond (number? datum) 'scheme-number (coll? datum) (first datum) :else (throw (RuntimeException. (str "Wrong datum -- TYPE-TAG" datum))))) (defn contents [datum] (cond (number? datum) datum (coll? datum) (rest datum) :else (throw (RuntimeException. (str "Wrong datum -- CONTENGS" datum))))) (defn attach-tag [tag content] (if (coll? content) (cons tag content) content)) Exercise 2.79 (defn install-scheme-number-package [] (let [equ? =]) ; ... put ) (defn install-rational-package [] (let [equ? (fn [x y] (= (* (numer x) (denom y)) (* (numer y) (denom x))))]) ;; ... put ) (defn install-complex-package [] ;; ... (let [equ? (fn [x y] (and (= (real-part x) (real-part y)) (= (imag-part x) (imag-part y))))]) ;; ... put ) (defn equ? [x y] (apply-generic 'equ? x y)) Exercise 2.80 (defn =zero? [x] (apply-generic '=zero? x)) (pt-put '=zero? 'scheme-number (fn [x] (= x 0))) (pt-put '=zero? 'rational-number (fn [x] (= (numer x) 0))) (pt-put '=zero? 'complex-number (fn [x] (= (real-part x) (imag-part x) 0))) Exercise 2.81 ;;a ; apply-generic will go into infinite recursion. ;;b ; apply-generic just works as it is. ;;c (defn put-coercion [source-type target-type proc] (pt-put 'coercion [source-type target-type] proc)) (defn get-coercion [source-type target-type] (pt-get 'coercion [source-type target-type])) (defn scheme-number->complex [n] (make-complex-from-real-imag (contents n) 0)) (put-coercion 'scheme-number 'complex scheme-number->complex) (defn apply-generic [op & args] (defn no-method [type-tags] (throw (RuntimeException. (str "No method for -- " op " -- " type-tags)))) (let [type-tags (map type-tag args) proc (pt-get op type-tags)] (if proc (apply proc (map contents args)) (if (= (count args) 2) (let [type1 (first type-tags) type2 (second type-tags) a1 (first args) a2 (second args)] (if (= type1 type2) (no-method type-tags) (let [t1->t2 (get-coercion type1 type2) t2->t1 (get-coercion type2 type1)] (cond t1->t2 (apply-generic op (t1->t2 a1) a2) t2->t1 (apply-generic op a1 (t2->t1 a2)) :else (no-method type-tags))))) (no-method type-tags))))) (add (make-rational 1 2) (make-rational 3 4)) (add (make-scheme-number 2) (make-complex-from-real-imag 3 4)) Exercise 2.82 (defn add [& args] (apply apply-generic 'add args)) (pt-put 'add '(scheme-number scheme-number scheme-number) str) (pt-put 'add '(complex complex complex) str) (defn apply-generic [op & args] ; coercing list to a type (defn coerce-list-to-type [lst type] (if (empty? lst) [] (let [t1->t2 (get-coercion (type-tag (first lst)) type)] (if t1->t2 (cons (t1->t2 (first lst)) (coerce-list-to-type (rest lst) type)) (cons (first lst) (coerce-list-to-type (rest lst) type)))))) ; applying to a list of multiple arguments (defn apply-coerced [lst] (if (empty? lst) (throw (RuntimeException. (str "No method for -- " op " - " args))) (let [coerced-list (coerce-list-to-type args (type-tag (first lst))) proc (pt-get op (map type-tag coerced-list))] (if proc (apply proc (map contents coerced-list)) (apply-coerced (rest lst)))))) ; logic to prevent always coercing if there is already direct input entry (let [type-tags (map type-tag args) proc (pt-get op type-tags)] (if proc (apply proc (map contents args)) (apply-coerced args)))) (add (make-scheme-number 2) (make-scheme-number 2) (make-scheme-number 2)) (add (make-complex-from-real-imag 3 4) (make-complex-from-real-imag 3 4) (make-complex-from-real-imag 3 4)) (add (make-scheme-number 2) (make-complex-from-real-imag 3 4) (make-scheme-number 2)) ; Problems ; a) It fails for operations defined for mixed types. ; b) It fails for operations defined on types that are not present in the argument list. Exercise 2.83 ; number -> rational -> complex (defn raise [x] (apply-generic 'raise x)) (defn install-scheme-number-package [] (let [tag (fn [x] (attach-tag 'scheme-number x))] (pt-put 'add '(scheme-number scheme-number) (fn [x y] (tag (+ x y)))) (pt-put 'sub '(scheme-number scheme-number) (fn [x y] (tag (- x y)))) (pt-put 'mul '(scheme-number scheme-number) (fn [x y] (tag (* x y)))) (pt-put 'div '(scheme-number scheme-number) (fn [x y] (tag (/ x y)))) (pt-put 'raise '(scheme-number) (fn [x] (make-rational x 1))) (pt-put 'make 'scheme-number tag))) (defn install-rational-package [] (let [numer (fn [x] (first x)) denom (fn [x] (second x)) make-rat (fn [n d] (let [g (gcd n d)] [(/ n g) (/ d g)])) add-rat (fn [x y] (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) sub-rat (fn [x y] (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) mul-rat (fn [x y] (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) div-rat (fn [x y] (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) tag (fn [x] (attach-tag 'rational x)) ] (pt-put 'add '(rational rational) (fn [x y] (tag (add-rat x y)))) (pt-put 'sub '(rational rational) (fn [x y] (tag (sub-rat x y)))) (pt-put 'mul '(rational rational) (fn [x y] (tag (mul-rat x y)))) (pt-put 'div '(rational rational) (fn [x y] (tag (div-rat x y)))) (pt-put 'raise '(rational) (fn [x] (make-complex-from-real-imag (/ (numer x) (denom x)) 0))) (pt-put 'make 'rational (fn [n d] (tag (make-rat n d)))))) (install-scheme-number-package) (install-rational-package) (raise (raise (make-scheme-number 3))) Exercise 2.84 (def type-levels {'scheme-number 0, 'rational 1, 'complex 2}) (defn get-coercion [orig-type dest-type] (let [orig-level (type-levels orig-type) dest-level (type-levels dest-type) level-diff (- dest-level orig-level)] (if (> level-diff 0) (apply comp (repeat level-diff raise)) nil))) (defn apply-generic [op & args] ; coercing list to a type (defn coerce-list-to-type [lst type] (if (empty? lst) [] (let [t1->t2 (get-coercion (type-tag (first lst)) type)] (if t1->t2 (cons (t1->t2 (first lst)) (coerce-list-to-type (rest lst) type)) (cons (first lst) (coerce-list-to-type (rest lst) type)))))) ; applying to a list of multiple arguments (defn apply-coerced [lst] (if (empty? lst) (throw (RuntimeException. (str "No method for -- " op " - " args))) (let [coerced-list (coerce-list-to-type args (type-tag (first lst))) proc (pt-get op (map type-tag coerced-list))] (if proc (apply proc (map contents coerced-list)) (apply-coerced (rest lst)))))) ; logic to prevent always coercing if there is already direct input entry (let [type-tags (map type-tag args) proc (pt-get op type-tags)] (if proc (apply proc (map contents args)) (apply-coerced args)))) (add (make-scheme-number 2) (make-scheme-number 2) (make-scheme-number 2)) (add (make-complex-from-real-imag 3 4) (make-complex-from-real-imag 3 4) (make-complex-from-real-imag 3 4)) (add (make-scheme-number 2) (make-complex-from-real-imag 3 4) (make-scheme-number 2))
null
https://raw.githubusercontent.com/frankiesardo/sicp-in-clojure/dc341617c2ab8eb34ac316175a56141a0c605421/src/sicp/chapter-2.clj
clojure
Define a better version of make-rat that handles both positive and negative arguments. Make-rat should normalize the sign so that if the rational number is positive, both the numerator and denominator are positive, and if the rational number is negative, only the numerator is negative. Exercise 2.6 [+, +] * [+, +] [+, +] * [-, +] [+, +] * [-, -] [-, +] * [+, +] [-, +] * [-, +] [-, +] * [-, -] [-, -] * [+, +] [-, -] * [-, +] [-, -] * [-, -] Exercise 2.15 > #Dependency_problem Order does not matter because the execution is a decision tree This should fail cons takes an element and a list. In that example we should use append Exercise 2.30 > [-8 -11] Exercise 2.40 The painter that draws the outline of the designated frame. The painter that draws an 'X' by connecting opposite corners of the frame. The painter that draws a diamond shape by connecting the midpoints of the sides of the frame. The wave painter. left face eye smile new origin new end of edge1 new end of edge2 -> ''abracadabra yields (quote abracadabra) b) In tree->list-1 concat is called on every recursive called Append is O(length) and the length is halves on each call so log n Total complexity tree->list-1 O(n logn) while tree->list-2 is just O(n) There is one recursive call for each element in the list with no expensive operands like concat so O(n) symbol frequency In a normal tree the complexity is O(n log n) In a skewed tree the complexity is O(n) for the most frequent and O(n^2) for the least frequent If a tree doesn't need to be modified we can store all the symbols in a map with their encodings for maximum performance Exercise 2.73 a) Because they have no type tag on their data structure. We could in principle but we have to change their representation. b) c) d) We only need to change the way we save them a) b) c) d) Lots of new operations -> data-directed style imported procedures from rectangular and polar packages This fails ... put ... put ... ... put a apply-generic will go into infinite recursion. b apply-generic just works as it is. c coercing list to a type applying to a list of multiple arguments logic to prevent always coercing if there is already direct input entry Problems a) It fails for operations defined for mixed types. b) It fails for operations defined on types that are not present in the argument list. number -> rational -> complex coercing list to a type applying to a list of multiple arguments logic to prevent always coercing if there is already direct input entry
(ns sicp.ch2) Exercise 2.1 . (defn add-rat [x y] (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (defn sub-rat [x y] (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (defn mul-rat [x y] (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (defn div-rat [x y] (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (defn equal-rat? [x y] (= (* (numer x) (denom y)) (* (numer y) (denom x)))) (defn make-rat [n d] [n d]) (defn numer [r] (first r)) (defn denom [r] (second r)) (defn print-rat [r] (println-str (numer r) "/" (denom r))) (def one-half (make-rat 1 2)) (print-rat one-half) (def one-third (make-rat 1 3)) (print-rat (add-rat one-half one-third)) (print-rat (mul-rat one-half one-third)) (print-rat (add-rat one-third one-third)) (defn gcd [a b] (if (= b 0) a (gcd b (rem a b)))) (defn make-rat [n d] (let [g (gcd n d)] [(/ n g) (/ d g)])) (print-rat (add-rat one-third one-third)) (defn make-rat-better [n d] (if (< d 0) (make-rat (* -1 n) (* -1 d)) (make-rat n d))) (make-rat-better 6 -7) Exercise 2.2 (defn make-segment [a b] [a b]) (defn start-segment [s] (first s)) (defn end-segment [s] (second s)) (defn make-point [x y] [x y]) (defn x-point [p] (first p)) (defn y-point [p] (second p)) (defn print-point [p] (println-str "(" (x-point p) "," (y-point p) ")")) (defn midpoint-segment [s] (make-point (/ (+ (x-point (start-segment s)) (x-point (end-segment s))) 2) (/ (+ (y-point (start-segment s)) (y-point (end-segment s))) 2) )) (def segment (make-segment (make-point -3 4) (make-point 1 2))) (print-point (midpoint-segment segment)) Exercise 2.3 (defn make-rect [left-right-diagonal] left-right-diagonal) (defn rec-width [r] (Math/abs (- (x-point (start-segment r)) (x-point (end-segment r))))) (defn rec-height [r] (Math/abs (- (y-point (end-segment r)) (y-point (start-segment r))))) (defn rec-perimeter [r] (+ (* 2 (rec-height r)) (* 2 (rec-width r)))) (defn rec-area [r] (* (rec-height r) (rec-width r))) (rec-perimeter (make-rect segment)) (rec-area (make-rect segment)) (defn make-rect [width height top-left-point] [width height top-left-point]) (defn rec-width [r] (first r)) (defn rec-height [r] (second r)) (rec-perimeter (make-rect 4 2 :top-left-point)) (rec-area (make-rect 4 2 :top-left-point)) Exercise 2.4 (defn cons' [x y] (fn [m] (m x y))) (defn car' [z] (z (fn [p q] p))) (defn cdr' [z] (z (fn [p q] q))) (def pair (cons' :a :b)) (car' pair) (cdr' pair) Exercise 2.5 (defn cons' [a b] (* (Math/pow 2 a) (Math/pow 3 b))) (defn car' [x] (if (zero? (rem x 2)) (+ 1 (car' (/ x 2))) 0)) (defn cdr' [x] (if (zero? (rem x 3)) (+ 1 (cdr' (/ x 3))) 0)) (car' (cons' 3 4)) (cdr' (cons' 3 4)) (def zero (fn [f] (fn [x] x))) ((zero inc) 0) (defn add-1 [n] (fn [f] (fn [x] (f ((n f) x))))) (def one (fn [f] (fn [x] (f x)))) ((one inc) 0) (def two (fn [f] (fn [x] (f (f x))))) (defn plus [a b] (fn [f] (fn [x] ((a f)((b f) x))))) (def three (plus two one)) ((three inc) 0) (defn mult [a b] (fn [f] (fn [x] ((a (b f)) x)))) (def six (mult three two)) ((six inc) 0) (defn exp [a b] (fn [f] (fn [x] (((b a) f) x)))) (def sixty-four (exp two six)) ((sixty-four inc) 0) Exercise 2.7 (defn make-interval [a b] [a b]) (defn lower-bound [i] (first i)) (defn upper-bound [i] (second i)) (defn add-interval [x y] (make-interval (+ (lower-bound x) (lower-bound y)) (+ (upper-bound x) (upper-bound y)))) (defn mul-interval [x y] (let [p1 (* (lower-bound x) (lower-bound y)) p2 (* (lower-bound x) (upper-bound y)) p3 (* (upper-bound x) (lower-bound y)) p4 (* (upper-bound x) (upper-bound y))] (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4)))) (defn div-interval [x y] (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y))))) Exercise 2.8 (defn sub-interval [x y] (make-interval (- (lower-bound x) (upper-bound y)) (- (upper-bound x) (lower-bound y)))) Exercise 2.9 (defn width-interval [i] (- (upper-bound i) (lower-bound i))) (def interval1 (make-interval 9.5 12)) (def interval2 (make-interval 3.5 7.5)) (def interval3 (make-interval 0.5 4.5)) (= (width-interval (add-interval interval1 interval2)) (width-interval (add-interval interval1 interval3))) (= (width-interval (sub-interval interval1 interval2)) (width-interval (sub-interval interval1 interval3))) (not= (width-interval (mul-interval interval1 interval2)) (width-interval (mul-interval interval1 interval3))) (not= (width-interval (div-interval interval1 interval2)) (width-interval (div-interval interval1 interval3))) Exercise 2.10 (defn includes-zero? [interval] (and (<= (lower-bound interval) 0) (>= (upper-bound interval) 0))) (defn div-interval [x y] (if (includes-zero? y) (throw (ArithmeticException. "Divide by zero")) (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y)))))) Exercise 2.11 (defn mul-interval [x y] (let [xlo (lower-bound x) xup (upper-bound x) ylo (lower-bound y) yup (upper-bound y)] (make-interval (* xlo ylo) (* xup yup)) (make-interval (* xup ylo) (* xup yup)) (make-interval (* xup ylo) (* xlo yup)) (make-interval (* xlo yup) (* xup yup)) (make-interval (min (* xup ylo) (* xlo yup)) (max (* xlo ylo) (* xup yup))) (make-interval (* xup ylo) (* xlo ylo)) (make-interval (* xlo yup) (* xup ylo)) (make-interval (* xlo yup) (* xlo ylo)) (make-interval (* xup yup) (* xlo ylo))))) (mul-interval interval1 interval2) Exercise 2.12 (defn make-center-width [c w] (make-interval (- c w) (+ c w))) (defn center [i] (/ (+ (lower-bound i) (upper-bound i)) 2)) (defn width [i] (/ (- (upper-bound i) (lower-bound i)) 2)) (defn make-center-percent [c p] (let [w (* c (/ p 100.0))] (make-center-width c w))) (defn percent [i] (* (/ (width i) (center i)) 100.0)) (make-center-width 100 15) (make-center-percent 100 15) Exercise 2.13 (def small-perc1 (make-center-percent 10 2)) (def small-perc2 (make-center-percent 30 7)) ~ 9 Exercise 2.14 (defn par1 [r1 r2] (div-interval (mul-interval r1 r2) (add-interval r1 r2))) (defn par2 [r1 r2] (let [one (make-interval 1 1)] (div-interval one (add-interval (div-interval one r1) (div-interval one r2))))) (par1 interval1 interval2) (par2 interval1 interval2) (def should-be-one (div-interval interval1 interval1)) (center should-be-one) (percent interval1) > Because diving an interval by itself does not yield one , so repeating the same iterval in the formula introduces errors when you simplify it . Exercise 2.16 Exercise 2.17 (defn last-pair [l] (if (empty? (rest l)) (first l) (last-pair (rest l)))) (last-pair [1 2 3 4]) Exercise 2.18 (defn append [l1 l2] (if (empty? l1) [l2] (cons (first l1) (append (rest l1) l2)))) (append [1 2] [3 4]) (defn reverse' [l] (if (empty? l) l (append (reverse' (rest l)) (first l)))) (reverse' [1 2 3 4 5]) Exercise 2.19 (def us-coins (list 50 25 10 5 1)) (def uk-coins (list 100 50 20 10 5 2 1)) (defn no-more? [coin-values] (empty? coin-values)) (defn first-denomination [coin-values] (first coin-values)) (defn except-first-denomination [coin-values] (rest coin-values)) (defn cc [amount coin-values] (cond (= amount 0) 1 (or (< amount 0) (no-more? coin-values)) 0 :else (+ (cc amount (except-first-denomination coin-values)) (cc (- amount (first-denomination coin-values)) coin-values)))) (cc 100 us-coins) (cc 100 uk-coins) (cc 100 (reverse uk-coins)) (cc 100 (reverse us-coins)) Exercise 2.20 (defn same-parity [pivot & more] (cons pivot (same-parity' pivot more))) (defn same-parity' [pivot candidates] (if-let [candidate (first candidates)] (if (= (rem pivot 2) (rem candidate 2)) (cons candidate (same-parity' pivot (rest candidates))) (same-parity' pivot (rest candidates))))) (same-parity 1) (same-parity 1 2 3 4 5 6 7 8 9 ) Exercise 2.21 (defn square-list [items] (if (empty? items) [] (cons (* (first items) (first items)) (square-list (rest items))))) (square-list [1 23 4 5]) (defn square-list [items] (map #(* % %) items)) (square-list [1 23 4 5]) Exercise 2.22 (defn square-list [items] (defn iter [things answer] (if (empty? things) answer (iter (rest things) (cons (#(* % %) (first things)) answer)))) (iter items [])) (square-list [1 2 3 4]) cons insert element to first position (defn square-list [items] (defn iter [things answer] (if (empty? things) answer (iter (rest things) (cons answer (#(* % %) (first things)))))) (iter items nil)) (square-list [1 2 3 4]) Exercise 2.23 (defn for-each [f items] (let [head (first items)] (when head (f head) (for-each f (rest items))))) (for-each println [1 2 3]) Exercise 2.24 (list 1 (list 2 (list 3 4))) Exercise 2.25 (first (rest (first (rest (rest '(1 3 (5 7) 9)))))) (first (first '((7)))) (first (rest (first (rest (first (rest (first (rest (first (rest (first (rest '(1 (2 (3 (4 (5 (6 7)))))))))))))))))) Exercise 2.26 (def x (list 1 2 3)) (def y (list 4 5 6)) > ( 1 2 3 4 5 6 ) > ( ( 1 2 3 ) 4 5 6 ) > ( ( 1 2 3 ) ( 4 5 6 ) ) Exercise 2.27 (defn deep-reverse [l] (when-let [head (first l)] (append (deep-reverse (rest l)) (if (coll? head) (deep-reverse head) head)))) (deep-reverse [1 2 3 [1 2 3 [4 5 6]]]) Exercise 2.28 (defn fringe [tree] (cond (nil? tree) [] (not (coll? tree)) [tree] :else (concat (fringe (first tree)) (fringe (next tree))))) (fringe [1 2 3 [1 2 3 [4 5 6]]]) Exercise 2.29 (defn make-mobile [left right] [left right]) (defn make-branch [length structure] [length structure]) (defn left-branch [mobile] (mobile 0)) (defn right-branch [mobile] (mobile 1)) (defn branch-length [branch] (branch 0)) (defn branch-structure [branch] (branch 1)) (defn branch-weight [branch] (let [structure (branch-structure branch)] (if (number? structure) structure (total-weight structure)))) (defn total-weight [mobile] (+ (branch-weight (left-branch mobile)) (branch-weight (right-branch mobile)))) (def unbalanced-mobile (make-mobile (make-branch 1 (make-mobile (make-branch 2 3) (make-branch 4 5) ) ) (make-branch 3 (make-mobile (make-branch 4 5) (make-branch 6 7) ) ) ) ) (total-weight unbalanced-mobile) (defn balanced-branch? [branch] (let [structure (branch-structure branch)] (if (number? structure) true (balanced? structure)))) (defn balanced? [mobile] (let [lb (left-branch mobile) rb (right-branch mobile)] (and (balanced-branch? lb) (balanced-branch? rb) (= (* (branch-length lb) (branch-weight lb)) (* (branch-length rb) (branch-weight rb)))))) (balanced? unbalanced-mobile) (def balanced-mobile (make-mobile (make-branch 2 (make-mobile (make-branch 6 7) (make-branch 14 3) ) ) (make-branch 5 4) ) ) (balanced? balanced-mobile) (defn square-tree [tree] (cond (not (coll? tree)) (* tree tree) (empty? tree) nil :else (cons (square-tree (first tree)) (square-tree (rest tree))))) (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) (defn square-tree [tree] (map (fn [sub-tree] (if (coll? sub-tree) (square-tree sub-tree) (* sub-tree sub-tree))) tree)) (square-tree (list 1 (list 2 (list 3 4) 5) (list 6 7))) Exercise 2.31 (defn tree-map [f tree] (map (fn [sub-tree] (if (coll? sub-tree) (tree-map f sub-tree) (f sub-tree))) tree)) (tree-map #(* % %) (list 1 (list 2 (list 3 4) 5) (list 6 7))) Exercise 2.32 (defn subsets [s] (if (nil? s) [[]] (let [rest (subsets (next s))] (concat rest (map #(cons (first s) %) rest))))) Exercise 2.33 (defn accumulate [op initial sequence] (if (empty? sequence) initial (op (first sequence) (accumulate op initial (rest sequence))))) (defn map' [p sequence] (accumulate (fn [x y] (cons (p x) y)) [] sequence)) (map' #(* % 2) [1 2 3]) (defn append [seq1 seq2] (accumulate cons seq2 seq1)) (append [1 2 3 4] [5 6 7]) (defn length [sequence] (accumulate (fn [x y] (+ y 1)) 0 sequence)) (length [:one :two :three :four]) Exercise 2.34 (defn horner-eval [x coefficient-sequence] (accumulate (fn [this-coeff higher-terms] (+ this-coeff (* x higher-terms))) 0 coefficient-sequence)) (horner-eval 2 (list 1 3 0 5 0 1)) Exercise 2.35 (defn count-leaves [t] (accumulate + 0 (map (fn [x] 1) (fringe t)))) (count-leaves [1 [2 [5 [6]]] 3 [ 1 2 [ 3 4]]]) Exercise 2.36 (defn accumulate-n [op init seqs] (if (empty? (first seqs)) nil (cons (accumulate op init (map first seqs)) (accumulate-n op init (map rest seqs))))) (accumulate-n + 0 [[1 2 3] [4 5 6] [7 8 9]]) Exercise 2.37 (defn dot-product [v w] (accumulate + 0 (map * v w))) (defn matrix-*-vector [m v] (map #(dot-product v %) m)) (defn transpose [mat] (accumulate-n cons [] mat)) (defn matrix-*-matrix [m n] (let [cols (transpose n)] (map #(matrix-*-vector cols %) m))) (def v (list 1 3 -5)) (def w (list 4 -2 -1)) > 3 (def m (list (list 1 2 3) (list 4 5 6))) (def n (list (list 14 9 3) (list 2 11 15))) (matrix-*-matrix m n) Exercise 2.38 (defn fold-right [op initial sequence] (if (nil? sequence) initial (op (first sequence) (fold-right op initial (next sequence))))) (defn fold-left [op initial sequence] (defn iter [result rest] (if (nil? rest) result (iter (op result (first rest)) (next rest)))) (iter initial sequence)) (fold-right / 1 (list 1 2 3)) (/ 1 (/ 2 (/ 3 1))) (fold-left / 1 (list 1 2 3)) (/ (/ (/ 1 1) 2) 3) (fold-right list nil (list 1 2 3)) (fold-left list nil (list 1 2 3)) (fold-right + 0 (list 1 2 3)) (fold-left + 0 (list 1 2 3)) Exercise 2.39 (defn reverse [sequence] (fold-right (fn [x y] (append y [x])) [] sequence)) (reverse [1 2 3]) (defn reverse [sequence] (fold-left (fn [x y] (cons y x)) [] sequence)) (reverse [1 2 3]) (defn unique-pairs [n] (mapcat (fn [i] (map (fn [j] [i j]) (range 1 i))) (range 1 (inc n)))) (unique-pairs 4) (defn prime? [n] (-> n (bigint) (.toBigInteger) (.isProbablePrime 100))) (defn prime-sum? [[x y]] (prime? (+ x y))) (defn make-pair-sum [[x y]] [x y (+ x y)]) (defn prime-sum-pairs [n] (map make-pair-sum (filter prime-sum? (unique-pairs n)))) (prime-sum-pairs 6) Exercise 2.41 (defn unique-triplets [n] (mapcat (fn [i] (mapcat (fn [j] (map (fn [k] [i j k]) (range 1 j))) (range 1 i))) (range 1 (inc n)))) (defn make-triplet-sum [[x y z]] [x y z (+ x y z)]) (defn sum-to [[x y z] n] (= n (+ x y z))) (defn sum-triplets [n] (map make-triplet-sum (filter #(sum-to % n) (unique-triplets n)))) (sum-triplets 15) Exercise 2.42 (def empty-board []) (defn adjoin-position [new-row col rest-of-queens] (cons new-row rest-of-queens)) (defn safe? [k positions] (def candidate (first positions)) (defn safe-iter [top bot remain] (cond (empty? remain) true (or (= (first remain) candidate) (= (first remain) top) (= (first remain) bot)) false :else (safe-iter (- top 1) (+ bot 1) (rest remain)))) (safe-iter (- candidate 1) (+ candidate 1) (rest positions))) (defn queens [board-size] (defn queen-cols [k] (if (= k 0) (list empty-board) (filter (fn [positions] (safe? k positions)) (mapcat (fn [rest-of-queens] (map (fn [new-row] (adjoin-position new-row k rest-of-queens)) (range 1 (inc board-size)))) (queen-cols (dec k)))))) (queen-cols board-size)) (queens 4) Exercise 2.42 (defn queens [board-size] (defn queen-cols [k] (if (= k 0) (list empty-board) (filter (fn [positions] (safe? k positions)) (mapcat (fn [new-row] (map (fn [rest-of-queens] (adjoin-position new-row k rest-of-queens)) (queen-cols (dec k)))) (range 1 (inc board-size)))))) (queen-cols board-size)) Exercise 2.43 ( queens 6 ) - > from linear recursive to tree recursive = T^board - size Exercise 2.44 (defn below [p1 p2] :new-painter) (defn beside [p1 p2] :new-painter) (defn up-split [painter n] (if (= n 0) painter (let [smaller (up-split painter (- n 1))] (below painter (beside smaller smaller))))) Exercise 2.45 (defn split [split1 split2] (fn [painter n] (if (= n 0) painter (let [smaller (split painter (dec n))] (split1 painter (split2 smaller smaller)))))) (def right-split (split beside below)) (def up-split (split below beside)) Exercise 2.46 (defn make-vect [x y]) (defn xcor-vect [v] (v 0)) (defn ycor-vect [v] (v 1)) (defn add-vect [v1 v2] (make-vect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2)))) (defn sub-vect [v1 v2] (make-vect (- (xcor-vect v1) (xcor-vect v2)) (- (ycor-vect v1) (ycor-vect v2)))) (defn scale-vect [v s] (make-vect (* s (xcor-vect v)) (* (ycor-vect v)))) Exercise 2.47 (defn make-frame [origin edge1 edge2] [origin edge1 edge2]) (defn origin-frame [f] (f 0)) (defn edge1-frame [f] (f 1)) (defn edge2-frame [f] (f 2)) (defn make-frame [origin edge1 edge2] (cons origin [edge1 edge2])) (defn origin-frame [f] (f 0)) (defn edge1-frame [f] ((f 0) 0)) (defn edge2-frame [f] ((f 0) 1)) Exercise 2.48 (defn make-segment [v1 v2] [v1 v2]) (defn start-segment [s] (s 0)) (defn end-segment [s] (s 1)) Exercise 2.49 (def outline-segments (list (make-segment (make-vect 0.0 0.0) (make-vect 0.0 0.99)) (make-segment (make-vect 0.0 0.0) (make-vect 0.99 0.0)) (make-segment (make-vect 0.99 0.0) (make-vect 0.99 0.99)) (make-segment (make-vect 0.0 0.99) (make-vect 0.99 0.99)))) (def x-segments (list (make-segment (make-vect 0.0 0.0) (make-vect 0.99 0.99)) (make-segment (make-vect 0.0 0.99) (make-vect 0.99 0.0)))) (def diamond-segments (list (make-segment (make-vect 0.0 0.5) (make-vect 0.5 0.0)) (make-segment (make-vect 0.0 0.5) (make-vect 0.5 0.99)) (make-segment (make-vect 0.5 0.99) (make-vect 0.99 0.5)) (make-segment (make-vect 0.99 0.5) (make-vect 0.5 0.0)))) (def wave-segments (list (make-segment (make-vect 0.006 0.840) (make-vect 0.155 0.591)) (make-segment (make-vect 0.006 0.635) (make-vect 0.155 0.392)) (make-segment (make-vect 0.304 0.646) (make-vect 0.155 0.591)) (make-segment (make-vect 0.298 0.591) (make-vect 0.155 0.392)) (make-segment (make-vect 0.304 0.646) (make-vect 0.403 0.646)) (make-segment (make-vect 0.298 0.591) (make-vect 0.354 0.492)) (make-segment (make-vect 0.403 0.646) (make-vect 0.348 0.845)) (make-segment (make-vect 0.354 0.492) (make-vect 0.249 0.000)) (make-segment (make-vect 0.403 0.000) (make-vect 0.502 0.293)) (make-segment (make-vect 0.502 0.293) (make-vect 0.602 0.000)) (make-segment (make-vect 0.348 0.845) (make-vect 0.403 0.999)) (make-segment (make-vect 0.602 0.999) (make-vect 0.652 0.845)) (make-segment (make-vect 0.652 0.845) (make-vect 0.602 0.646)) (make-segment (make-vect 0.602 0.646) (make-vect 0.751 0.646)) (make-segment (make-vect 0.751 0.646) (make-vect 0.999 0.343)) (make-segment (make-vect 0.751 0.000) (make-vect 0.597 0.442)) (make-segment (make-vect 0.597 0.442) (make-vect 0.999 0.144)))) Exercise 2.50 (defn frame-coord-map [frame] (fn [v] (add-vect (origin-frame frame) (add-vect (scale-vect (xcor-vect v) (edge1-frame frame)) (scale-vect (ycor-vect v) (edge2-frame frame)))))) (defn transform-painter [painter origin corner1 corner2] (fn [frame] (let [m (frame-coord-map frame) new-origin (m origin)] (painter (make-frame new-origin (sub-vect (m corner1) new-origin) (sub-vect (m corner2) new-origin)))))) (defn flip-horiz [painter] ((transform-painter (make-vect 1.0 0.0) (make-vect 0.0 0.0) (make-vect 1.0 1.0)) painter)) (defn rotate180 [painter] ((transform-painter (make-vect 1.0 1.0) (make-vect 0.0 1.0) (make-vect 1.0 0.0)) painter)) (defn rotate270 [painter] ((transform-painter (make-vect 0.0 1.0) (make-vect 0.0 0.0) (make-vect 1.0 1.0)) painter)) Exercise 2.51 (defn beside [painter1 painter2] (let [split-point (make-vect 0.5 0.0) paint-left (transform-painter painter1 (make-vect 0.0 0.0) split-point (make-vect 0.0 1.0)) paint-right (transform-painter painter2 split-point (make-vect 1.0 0.0) (make-vect 0.5 1.0)) ] (fn [frame] (paint-left frame) (paint-right frame)))) (defn below [painter1 painter2] (let [split-point (make-vect 0.0 0.5) paint-bottom ((transform-painter (make-vect 0.0 0.0) (make-vect 1.0 0.0) split-point) painter1) paint-top ((transform-painter split-point (make-vect 1.0 0.5) (make-vect 0.0 1.0)) painter2) ] (fn [frame] (paint-bottom frame) (paint-top frame)))) (defn rotate90 [painter] ((transform-painter (make-vect 1.0 0.0) (make-vect 1.0 1.0) (make-vect 0.0 0.0)) painter)) (defn below [painter1 painter2] (rotate90 (beside (rotate270 painter1) (rotate270 painter2)))) Exercise 2.52 (def wave-segments (list (make-segment (make-vect 0.006 0.840) (make-vect 0.155 0.591)) (make-segment (make-vect 0.006 0.635) (make-vect 0.155 0.392)) (make-segment (make-vect 0.304 0.646) (make-vect 0.155 0.591)) (make-segment (make-vect 0.298 0.591) (make-vect 0.155 0.392)) (make-segment (make-vect 0.304 0.646) (make-vect 0.403 0.646)) (make-segment (make-vect 0.298 0.591) (make-vect 0.354 0.492)) (make-vect 0.403 0.646) (make-vect 0.348 0.845)) (make-segment (make-vect 0.354 0.492) (make-vect 0.249 0.000)) (make-segment (make-vect 0.403 0.000) (make-vect 0.502 0.293)) (make-segment (make-vect 0.502 0.293) (make-vect 0.602 0.000)) (make-segment (make-vect 0.348 0.845) (make-vect 0.403 0.999)) (make-segment (make-vect 0.602 0.999) (make-vect 0.652 0.845)) (make-segment (make-vect 0.652 0.845) (make-vect 0.602 0.646)) (make-segment (make-vect 0.602 0.646) (make-vect 0.751 0.646)) (make-segment (make-vect 0.751 0.646) (make-vect 0.999 0.343)) (make-segment (make-vect 0.751 0.000) (make-vect 0.597 0.442)) (make-segment (make-vect 0.597 0.442) (make-vect 0.999 0.144)) (make-vect 0.395 0.916) (make-vect 0.410 0.916)) (make-vect 0.376 0.746) (make-vect 0.460 0.790)))) (defn corner-split [painter n] (if (= n 0) painter (let [up (up-split painter (- n 1)) right (right-split painter (- n 1)) corner (corner-split painter (- n 1))] (beside (below painter up) (below right corner))))) (defn flip-vert [painter] (transform-painter painter (defn square-limit [painter n] (let [quarter (rotate180 (corner-split painter n)) half (beside (flip-horiz quarter) quarter)] (below (flip-vert half) half))) Exercise 2.53 (defn memq [item x] (cond (empty? x) false (= item (first x)) x :else (memq item (rest x)))) (list 'a 'b 'c) (list (list 'george)) (rest '((x1 x2) (y1 y2))) (first '((x1 x2) (y1 y2))) (coll? (first '(a short list))) (memq 'red '((red shoes) (blue socks))) (memq 'red '(red shoes blue socks)) Exercise 2.54 (defn equal? [a b] (cond (and (symbol? a) (symbol? b) (= a b)) true (and (coll? a) (coll? b) (= (first a) (first b))) (equal? (rest a) (rest b)) :else false)) Exercise 2.55 (first ''abracadabra) Exercise 2.55 (defn variable? [x] (symbol? x)) (defn same-variable? [v1 v2] (and (variable? v1) (variable? v2) (= v1 v2))) (defn make-sum [a1 a2] (cond (= a1 0) a2 (= a2 0) a1 (and (number? a1) (number? a2)) (+ a1 a2) :else (list '+ a1 a2))) (defn make-product [m1 m2] (cond (or (= m1 0) (= m2 0)) 0 (= m1 1) m2 (= m2 1) m1 (and (number? m1) (number? m2)) (* m1 m2) :else (list '* m1 m2))) (defn sum? [x] (and (coll? x) (= (first x) '+))) (defn addend [s] (second s)) (defn augend [s] (second (rest s))) (defn product? [x] (and (coll? x) (= (first x) '*))) (defn multiplier [p] (second p)) (defn multiplicand [p] (second (rest p))) (defn deriv [exp var] (cond (number? exp) 0 (variable? exp) (if (same-variable? exp var) 1 0) (sum? exp) (make-sum (deriv (addend exp) var) (deriv (augend exp) var)) (product? exp) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp))) :else (throw (Exception. "unknown expression type -- DERIV" exp)))) Exercise 2.56 (defn exponentiation? [x] (and (coll? x) (= (first x) '**))) (defn base [p] (second p)) (defn exponent [p] (second (rest p))) (defn make-exponentiation [b e] (cond (= e 0) 1 (= e 1) b (or (= b 1) (= b 0)) b :else (list '** b e))) (defn deriv [exp var] (cond (number? exp) 0 (variable? exp) (if (same-variable? exp var) 1 0) (sum? exp) (make-sum (deriv (addend exp) var) (deriv (augend exp) var)) (product? exp) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp))) (exponentiation? exp) (make-product (make-product (exponent exp) (make-exponentiation (base exp) (dec (exponent exp)))) (deriv (base exp) var) ) :else (throw (Exception. "unknown expression type -- DERIV" exp)))) Exercise 2.57 (defn augend [s] (let [a (rest (drop 1 s))] (if (= 1 (count a)) a (cons '+ a)))) (defn multiplicand [s] (let [m (rest (drop 1 s))] (if (= 1 (count m)) m (cons '* m)))) Exercise 2.58 (defn make-sum [a1 a2] (cond (= a1 0) a2 (= a2 0) a1 (and (number? a1) (number? a2)) (+ a1 a2) :else (list a1 '+ a2))) (defn make-product [m1 m2] (cond (or (= m1 0) (= m2 0)) 0 (= m1 1) m2 (= m2 1) m1 (and (number? m1) (number? m2)) (* m1 m2) :else (list m1 '* m2))) (defn sum? [x] (and (coll? x) (= (second x) '+))) (defn addend [s] (first s)) (defn augend [s] (second (rest s))) (defn product? [x] (and (coll? x) (= (second x) '*))) (defn multiplier [p] (first p)) (defn multiplicand [p] (second (rest p))) (defn exponentiation? [x] (and (coll? x) (= (second x) '**))) (defn base [p] (first p)) (defn exponent [p] (second (rest p))) (defn make-exponentiation [b e] (cond (= e 0) 1 (= e 1) b (or (= b 1) (= b 0)) b :else (list b '** e))) (defn sum? [x] (check-symbol '+ x)) (defn addend [s] (left '+ s)) (defn augend [s] (right '+ s)) (defn product? [x] (check-symbol '* x)) (defn multiplier [p] (left '* p)) (defn multiplicand [p] (right '* p)) (defn exponentiation? [x] (check-symbol '** x)) (defn base [e] (left '** e)) (defn exponent [e] (right '** e)) (defn check-symbol [s x] (and (coll? x) (memq s x))) (defn left [s x] (let [exp (take-while #(not= % s) x)] (if (= 1 (count exp)) (first exp) exp))) (defn right [s x] (let [exp (rest (memq s x))] (if (= 1 (count exp)) (first exp) exp))) (defn make-sum [a1 a2] (cond (= a1 0) a2 (= a2 0) a1 (and (number? a1) (number? a2)) (+ a1 a2) (and (coll? a1) (coll? a2)) (concat a1 '(+) a2) (coll? a1) (concat a1 ['+ a2]) (coll? a2) (concat [a1 '+] a2) :else (list a1 '+ a2))) (defn make-product [m1 m2] (cond (or (= m1 0) (= m2 0)) 0 (= m1 1) m2 (= m2 1) m1 (and (number? m1) (number? m2)) (* m1 m2) (and (coll? m1) (coll? m2) (not (sum? m1)) (not (sum? m2))) (concat m1 '(*) m2) (and (coll? m1) (not (sum? m1))) (concat m1 ['* m2]) (and (coll? m2) (not (sum? m2))) (concat [m1 '*] m2) :else (list m1 '* m2))) (defn make-exponentiation [b e] (cond (= e 0) 1 (= e 1) b (or (= b 1) (= b 0)) b (and (number? b) (number? e)) (* b e) :else (list b '** e))) Exercise 2.59 (defn element-of-set? [x set] (cond (empty? set) false (= x (first set)) true :else (element-of-set? x (rest set)))) (defn adjoin-set [x set] (if (element-of-set? x set) set (cons x set))) (defn intersection-set [set1 set2] (cond (or (empty? set1) (empty? set2)) '() (element-of-set? (first set1) set2) (cons (first set1) (intersection-set (rest set1) set2)) :else (intersection-set (rest set1) set2))) (defn union-set [set1 set2] (cond (empty? set1) set2 (element-of-set? (first set1) set2) (union-set (rest set1) set2) :else (union-set (rest set1) (cons (first set1) set2)))) Exercise 2.60 (defn element-of-set? [x set] (cond (empty? set) false (= x (first set)) true :else (element-of-set? x (rest set)))) (defn adjoin-set [x set] (cons x set)) (defn intersection-set [set1 set2] (cond (or (empty? set1) (empty? set2)) '() (element-of-set? (first set1) set2) (cons (first set1) (intersection-set (rest set1) set2)) :else (intersection-set (rest set1) set2))) (defn union-set [set1 set2] (concat set1 set2)) Exercise 2.61 (defn element-of-set? [x set] (cond (empty? set) false (= x (first set)) true (< x (first set)) false :else (element-of-set? x (rest set)))) (defn intersection-set [set1 set2] (if (or (empty? set1) (empty? set2)) [] (let [x1 (first set1) x2 (first set2)] (cond (= x1 x2) (cons x1 (intersection-set (rest set1) (rest set2))) (< x1 x2) (intersection-set (rest set1) set2) (< x2 x1) (intersection-set set1 (rest set2)))))) (defn adjoin-set [x set] (cond (empty? set) (cons x set) (= x (first set)) set (< x (first set)) (cons x set) :else (cons (first set) (adjoin-set x (rest set))))) Exercise 2.62 (defn union-set [set1 set2] (cond (empty? set1) set2 (empty? set2) set1 :else (let [x1 (first set1) x2 (first set2)] (cond (= x1 x2) (cons x1 (union-set (rest set1) (rest set2))) (< x1 x2) (cons x1 (union-set (rest set1) set2)) (< x2 x1) (cons x2 (union-set set1 (rest set2))))))) Exercise 2.63 (defn entry [tree] (tree 0)) (defn left-branch [tree] (tree 1)) (defn right-branch [tree] (tree 2)) (defn make-tree [entry left right] [entry left right]) (defn element-of-set? [x set] (cond (empty? set) false (= x (entry set)) true (< x (entry set)) (element-of-set? x (left-branch set)) (> x (entry set)) (element-of-set? x (right-branch set)))) (defn adjoin-set [x set] (cond (empty? set) (make-tree x [] []) (= x (entry set)) set (< x (entry set)) (make-tree (entry set) (adjoin-set x (left-branch set)) (right-branch set)) (> x (entry set)) (make-tree (entry set) (left-branch set) (adjoin-set x (right-branch set))))) (defn tree->list-1 [tree] (if (empty? tree) [] (concat (tree->list-1 (left-branch tree)) (cons (entry tree) (tree->list-1 (right-branch tree)))))) (defn tree->list-2 [tree] (defn copy-to-list [tree result-list] (if (empty? tree) result-list (copy-to-list (left-branch tree) (cons (entry tree) (copy-to-list (right-branch tree) result-list))))) (copy-to-list tree [])) (def tree1 [7 [3 [1 [] []] [5 [] []]] [9 [] [11 [] []]]]) (tree->list-1 tree1) (tree->list-2 tree1) (def tree2 [3 [1 [] []] [7 [5 [] []] [9 [] [11 [] []]]]]) (tree->list-1 tree2) (tree->list-2 tree2) (def tree3 [5 [3 [1 [] []] []] [9 [7 [] []] [11 [] []]]]) (tree->list-1 tree3) (tree->list-2 tree3) Exercise 2.64 (defn list->tree [elements] (first (partial-tree elements (count elements)))) (defn partial-tree [elts n] (if (= n 0) ([[] elts]) (let [left-size (quot (dec n) 2) left-result (partial-tree elts left-size) left-tree (first left-result) non-left-elts (second left-result) right-size (- n (inc left-size)) this-entry (first non-left-elts) right-result (partial-tree (rest non-left-elts) right-size) right-tree (first right-result) remaining-elts (second right-result) ] [(make-tree this-entry left-tree right-tree) remaining-elts]))) The important bit is to substract 1 in the calculation of left and right size so you can extract this - entry Exercise 2.65 Just use tree->list2 on the sets , feed them to the functions 2.61 2.62 and reconvert them back with list->tree Exercise 2.66 (defn lookup [given-key set-of-records] (cond (empty? set-of-records) false (= given-key (key (entry set-of-records))) (entry set-of-records) (< given-key (key (entry set-of-records))) (lookup given-key (left-branch set-of-records)) (> given-key (key (entry set-of-records))) (lookup given-key (right-branch set-of-records)))) Exercise 2.67 (defn make-leaf [symbol weight] ['leaf symbol weight]) (defn leaf? [object] (= (object 0) 'leaf)) (defn symbol-leaf [x] (x 1)) (defn weight-leaf [x] (x 2)) (defn make-code-tree [left right] [left right (concat (symbols left) (symbols right)) (+ (weight left) (weight right))]) (defn left-branch [tree] (tree 0)) (defn right-branch [tree] (tree 1)) (defn symbols [tree] (if (leaf? tree) [(symbol-leaf tree)] (tree 2))) (defn weight [tree] (if (leaf? tree) (weight-leaf tree) (tree 3))) (defn decode [bits tree] (defn decode-1 [bits current-branch] (if (empty? bits) [] (let [next-branch (choose-branch (first bits) current-branch)] (if (leaf? next-branch) (cons (symbol-leaf next-branch) (decode-1 (rest bits) tree)) (decode-1 (rest bits) next-branch))))) (decode-1 bits tree)) (defn choose-branch [bit branch] (cond (= bit 0) (left-branch branch) (= bit 1) (right-branch branch))) (defn adjoin-set [x set] (cond (empty? set) [x] (< (weight x) (weight (first set))) (cons x set) :else (cons (first set) (adjoin-set x (rest set))))) (defn make-leaf-set [pairs] (if (empty? pairs) [] (let [pair (first pairs)] (make-leaf-set (rest pairs)))))) (def sample-tree (make-code-tree (make-leaf 'A 4) (make-code-tree (make-leaf 'B 2) (make-code-tree (make-leaf 'D 1) (make-leaf 'C 1))))) (def sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0)) (decode sample-message sample-tree) Exercise 2.68 (defn encode [message tree] (if (empty? message) [] (concat (encode-symbol (first message) tree) (encode (rest message) tree)))) (defn encode-symbol [symbol tree] (defn in-branch? [branch] (if (leaf? branch) (= symbol (symbol-leaf branch)) (memq symbol (symbols branch)))) (let [lb (left-branch tree) rb (right-branch tree)] (cond (in-branch? lb) (if (leaf? lb) [0] (cons 0 (encode-symbol symbol lb))) (in-branch? rb) (if (leaf? rb) [1] (cons 1 (encode-symbol symbol rb))) :else (throw (RuntimeException. (str "Can't encode symbol " symbol)))))) (encode '(A D A B B C A) sample-tree) Exercise 2.69 (defn generate-huffman-tree [pairs] (successive-merge (make-leaf-set pairs))) (defn successive-merge [trees] (if (= 1 (count trees)) (first trees) (let [a (first trees) b (second trees) remainder (drop 2 trees) new-tree (make-code-tree a b) new-trees (adjoin-set new-tree remainder)] (successive-merge new-trees)))) (generate-huffman-tree #{'(A 8) '(B 3) '(C 1) '(D 1) '(E 1) '(F 1) '(G 1) '(H 1)}) Exercise 2.70 (def rock-tree (generate-huffman-tree #{'(a 2) '(boom 1) '(Get 2) '(job 2) '(na 16) '(Sha 3) '(yip 9) '(Wah 1)})) (def rock-lyric '(Get a job Sha na na na na na na na na Get a job Sha na na na na na na na na Wah yip yip yip yip yip yip yip yip yip Sha boom)) (def encoded-lyric (encode rock-lyric rock-tree)) (< (count encoded-lyric) (* 3 (count rock-lyric))) Exercise 2.71 Such tree always has a leaf on its left branch so the most frequent symbol is encoded with 1 bit and the least frequent with ( n - 1 ) bits Exercise 2.72 (defn addend [s] (first s)) (defn augend [s] (second s)) (defn multiplier [p] (first p)) (defn multiplicand [p] (second p)) (defn operator [exp] (first exp)) (defn operands [exp] (rest exp)) (defn deriv [exp var] (cond (number? exp) 0 (variable? exp) (if (same-variable? exp var) 1 0) :else ((pt-get 'deriv (operator exp)) (operands exp) var))) (defn deriv-sum [exp var] (make-sum (deriv (addend exp) var) (deriv (augend exp) var))) (defn deriv-product [exp var] (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp)))) (def proc-table (atom {})) (defn pt-get [op type] (@proc-table [op type])) (defn pt-put [op type item] (swap! proc-table #(assoc % [op type] item))) (defn install-deriv [] (pt-put 'deriv '+ deriv-sum) (pt-put 'deriv '* deriv-product)) (install-deriv) (deriv '(* (+ x y) 3) 'x) (defn base [e] (first e)) (defn exponent [e] (second e)) (defn deriv-exponentiation [expr var] (let [base (base expr) exponent (exponent expr)] (make-product exponent (make-product (make-exponentiation base (make-sum exponent -1)) (deriv base var))))) (defn install-deriv [] (pt-put 'deriv '+ deriv-sum) (pt-put 'deriv '* deriv-product) (pt-put 'deriv '** deriv-exponentiation)) (install-deriv) (deriv '(** (+ x y) 3) 'x) Exercise 2.74 (defn make-hq-file [division file] (cons division file)) (defn file-division [hq-file] (first hq-file)) (defn original-file [hq-file] (second hq-file)) (defn get-record [employee hq-file] (let [get-record-fn (pt-get 'get-record (file-division hq-file))] (get-record-fn employee (original-file hq-file)))) (defn has-record? [employee division] (let [has-record?-fn (pt-get 'has-record? division)] (has-record?-fn employee))) (defn make-hq-record [division record] (cons division record)) (defn record-division [hq-record] (first hq-record)) (defn original-record [hq-record] (second hq-record)) (defn get-salary [hq-file] (let [get-salary-fn (pt-get 'get-salary (file-division hq-file))] (get-salary-fn (original-record hq-file)))) (defn find-employee-record [employee files] (cond (empty? files) (throw (RuntimeException. (str "FIND-EMPLOYEE-RECORD : No such employee." employee))) (has-record? employee (file-division (first files))) (get-record employee (first files)) :else (find-employee-record employee (rest files)))) (defn install-ultra-mega-corp [table] (assoc table 'get-record :ultra-mega-corp-get-record) (assoc table 'has-record? :ultra-mega-corp-has-record?) (assoc table 'get-salary :ultra-mega-corp-get-salary)) Exercise 2.75 (defn apply-generic [op arg] (arg op)) (defn make-from-mag-ang [m a] (defn dispatch [op] (cond (= op 'real-part) (* m (Math/cos a)) (= op 'imag-part) (* m (Math/sin a)) (= op 'magnitude) m (= op 'angle) a :else (throw (RuntimeException. (str "Unknown op -- MAKE-FROM-REAL-IMAG" op))))) dispatch) Exercise 2.76 Lots of new types - > message passing ( which is basically OO ) Exercise 2.77 (def proc-table (atom {})) (defn pt-get [op type] (@proc-table [op type])) (defn pt-put [op type item] (swap! proc-table #(assoc % [op type] item))) (defn type-tag [datum] (cond (number? datum) datum (coll? datum) (first datum) :else (throw (RuntimeException. (str "Wrong datum -- TYPE-TAG " datum))))) (defn contents [datum] (cond (number? datum) datum (coll? datum) (rest datum) :else (throw (RuntimeException. (str "Wrong datum -- CONTENGS " datum))))) (defn attach-tag [tag content] (if (coll? content) (cons tag content) content)) (defn gcd [a b] (if (= b 0) a (gcd b (rem a b)))) 2.77 (defn install-rectangular-package [] (let [real-part (fn [z] (first z)) imag-part (fn [z] (second z)) make-from-real-imag (fn [x y] [x y]) magnitude (fn [z] (Math/sqrt (+ (#(* % %) (real-part z)) (#(* % %) (imag-part z))))) angle (fn [z] (Math/atan2 (imag-part z) (real-part z))) make-from-mag-ang (fn [r a] [(* r (Math/cos a)) (* r (Math/sin a))]) tag (fn [x] (attach-tag 'rectangular x))] (pt-put 'real-part '(rectangular) real-part) (pt-put 'imag-part '(rectangular) imag-part) (pt-put 'magnitude '(rectangular) magnitude) (pt-put 'angle '(rectangular) angle) (pt-put 'make-from-real-imag 'rectangular (fn [x y] (tag (make-from-real-imag x y)))) (pt-put 'make-from-mag-ang 'rectangular (fn [r a] (tag (make-from-mag-ang r a)))))) (defn install-polar-package [] (let [magnitude (fn [z] (first z)) angle (fn [z] (second z)) make-from-mag-ang (fn [r a] [r a]) real-part (fn [z] (* (magnitude z) (Math/cos (angle z)))) imag-part (fn [z] (* (magnitude z) (Math/sin (angle z)))) make-from-real-imag (fn [x y] [(Math/sqrt (+ (#(* % %) x) (#(* % %) y))) (Math/atan2 y x)]) tag (fn [x] (attach-tag 'polar x))] (pt-put 'real-part '(polar) real-part) (pt-put 'imag-part '(polar) imag-part) (pt-put 'magnitude '(polar) magnitude) (pt-put 'angle '(polar) angle) (pt-put 'make-from-real-imag 'polar (fn [x y] (tag (make-from-real-imag x y)))) (pt-put 'make-from-mag-ang 'polar (fn [r a] (tag (make-from-mag-ang r a)))))) (defn apply-generic [op & args] (let [type-tags (map type-tag args) proc (pt-get op type-tags)] (if proc (apply proc (map contents args)) (throw (RuntimeException. (str "No method for -- " op type-tags)))))) (defn real-part [z] (apply-generic 'real-part z)) (defn imag-part [z] (apply-generic 'imag-part z)) (defn magnitude [z] (apply-generic 'magnitude z)) (defn angle [z] (apply-generic 'angle z)) (defn add [x y] (apply-generic 'add x y)) (defn sub [x y] (apply-generic 'sub x y)) (defn mul [x y] (apply-generic 'mul x y)) (defn div [x y] (apply-generic 'div x y)) (defn install-scheme-number-package [] (let [tag (fn [x] (attach-tag 'scheme-number x))] (pt-put 'add '(scheme-number scheme-number) (fn [x y] (tag (+ x y)))) (pt-put 'sub '(scheme-number scheme-number) (fn [x y] (tag (- x y)))) (pt-put 'mul '(scheme-number scheme-number) (fn [x y] (tag (* x y)))) (pt-put 'div '(scheme-number scheme-number) (fn [x y] (tag (/ x y)))) (pt-put 'make 'scheme-number (fn [x] (tag x))))) (defn make-scheme-number [n] ((pt-get 'make 'scheme-number) n)) (defn install-rational-package [] (let [numer (fn [x] (first x)) denom (fn [x] (second x)) make-rat (fn [n d] (let [g (gcd n d)] [(/ n g) (/ d g)])) add-rat (fn [x y] (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) sub-rat (fn [x y] (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) mul-rat (fn [x y] (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) div-rat (fn [x y] (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) tag (fn [x] (attach-tag 'rational x)) ] (pt-put 'add '(rational rational) (fn [x y] (tag (add-rat x y)))) (pt-put 'sub '(rational rational) (fn [x y] (tag (sub-rat x y)))) (pt-put 'mul '(rational rational) (fn [x y] (tag (mul-rat x y)))) (pt-put 'div '(rational rational) (fn [x y] (tag (div-rat x y)))) (pt-put 'make 'rational (fn [n d] (tag (make-rat n d)))))) (defn make-rational [n d] ((pt-get 'make 'rational) n d)) (defn install-complex-package [] make-from-real-imag (fn [x y] ((pt-get 'make-from-real-imag 'rectangular) x y)) make-from-mag-ang (fn [r a] ((pt-get 'make-from-mag-ang 'polar) r a)) add-complex (fn [z1 z2] (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) sub-complex (fn [z1 z2] (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) mul-complex (fn [z1 z2] (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) div-complex (fn [z1 z2] (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) tag (fn [z] (attach-tag 'complex z)) ] (pt-put 'add '(complex complex) (fn [z1 z2] (tag (add-complex z1 z2)))) (pt-put 'sub '(complex complex) (fn [z1 z2] (tag (sub-complex z1 z2)))) (pt-put 'mul '(complex complex) (fn [z1 z2] (tag (mul-complex z1 z2)))) (pt-put 'div '(complex complex) (fn [z1 z2] (tag (div-complex z1 z2)))) (pt-put 'make-from-real-imag 'complex (fn [x y] (tag (make-from-real-imag x y)))) (pt-put 'make-from-mag-ang 'complex (fn [r a] (tag (make-from-mag-ang r a)))))) (install-rectangular-package) (install-polar-package) (install-scheme-number-package) (install-rational-package) (install-complex-package) (defn make-complex-from-real-imag [x y] ((pt-get 'make-from-real-imag 'complex) x y)) (defn make-complex-from-mag-ang [r a] ((pt-get 'make-from-mag-ang 'complex) r a)) (def z (make-complex-from-mag-ang 8 6)) (magnitude z) (pt-put 'real-part '(complex) real-part) (pt-put 'imag-part '(complex) imag-part) (pt-put 'magnitude '(complex) magnitude) (pt-put 'angle '(complex) angle) (magnitude z) apply - generic is invoked twice , first dispatch is magnitude of ' complex , second is magnitude of ' rectangular . Exercise 2.78 (defn type-tag [datum] (cond (number? datum) 'scheme-number (coll? datum) (first datum) :else (throw (RuntimeException. (str "Wrong datum -- TYPE-TAG" datum))))) (defn contents [datum] (cond (number? datum) datum (coll? datum) (rest datum) :else (throw (RuntimeException. (str "Wrong datum -- CONTENGS" datum))))) (defn attach-tag [tag content] (if (coll? content) (cons tag content) content)) Exercise 2.79 (defn install-scheme-number-package [] (let [equ? =]) ) (defn install-rational-package [] (let [equ? (fn [x y] (= (* (numer x) (denom y)) (* (numer y) (denom x))))]) ) (defn install-complex-package [] (let [equ? (fn [x y] (and (= (real-part x) (real-part y)) (= (imag-part x) (imag-part y))))]) ) (defn equ? [x y] (apply-generic 'equ? x y)) Exercise 2.80 (defn =zero? [x] (apply-generic '=zero? x)) (pt-put '=zero? 'scheme-number (fn [x] (= x 0))) (pt-put '=zero? 'rational-number (fn [x] (= (numer x) 0))) (pt-put '=zero? 'complex-number (fn [x] (= (real-part x) (imag-part x) 0))) Exercise 2.81 (defn put-coercion [source-type target-type proc] (pt-put 'coercion [source-type target-type] proc)) (defn get-coercion [source-type target-type] (pt-get 'coercion [source-type target-type])) (defn scheme-number->complex [n] (make-complex-from-real-imag (contents n) 0)) (put-coercion 'scheme-number 'complex scheme-number->complex) (defn apply-generic [op & args] (defn no-method [type-tags] (throw (RuntimeException. (str "No method for -- " op " -- " type-tags)))) (let [type-tags (map type-tag args) proc (pt-get op type-tags)] (if proc (apply proc (map contents args)) (if (= (count args) 2) (let [type1 (first type-tags) type2 (second type-tags) a1 (first args) a2 (second args)] (if (= type1 type2) (no-method type-tags) (let [t1->t2 (get-coercion type1 type2) t2->t1 (get-coercion type2 type1)] (cond t1->t2 (apply-generic op (t1->t2 a1) a2) t2->t1 (apply-generic op a1 (t2->t1 a2)) :else (no-method type-tags))))) (no-method type-tags))))) (add (make-rational 1 2) (make-rational 3 4)) (add (make-scheme-number 2) (make-complex-from-real-imag 3 4)) Exercise 2.82 (defn add [& args] (apply apply-generic 'add args)) (pt-put 'add '(scheme-number scheme-number scheme-number) str) (pt-put 'add '(complex complex complex) str) (defn apply-generic [op & args] (defn coerce-list-to-type [lst type] (if (empty? lst) [] (let [t1->t2 (get-coercion (type-tag (first lst)) type)] (if t1->t2 (cons (t1->t2 (first lst)) (coerce-list-to-type (rest lst) type)) (cons (first lst) (coerce-list-to-type (rest lst) type)))))) (defn apply-coerced [lst] (if (empty? lst) (throw (RuntimeException. (str "No method for -- " op " - " args))) (let [coerced-list (coerce-list-to-type args (type-tag (first lst))) proc (pt-get op (map type-tag coerced-list))] (if proc (apply proc (map contents coerced-list)) (apply-coerced (rest lst)))))) (let [type-tags (map type-tag args) proc (pt-get op type-tags)] (if proc (apply proc (map contents args)) (apply-coerced args)))) (add (make-scheme-number 2) (make-scheme-number 2) (make-scheme-number 2)) (add (make-complex-from-real-imag 3 4) (make-complex-from-real-imag 3 4) (make-complex-from-real-imag 3 4)) (add (make-scheme-number 2) (make-complex-from-real-imag 3 4) (make-scheme-number 2)) Exercise 2.83 (defn raise [x] (apply-generic 'raise x)) (defn install-scheme-number-package [] (let [tag (fn [x] (attach-tag 'scheme-number x))] (pt-put 'add '(scheme-number scheme-number) (fn [x y] (tag (+ x y)))) (pt-put 'sub '(scheme-number scheme-number) (fn [x y] (tag (- x y)))) (pt-put 'mul '(scheme-number scheme-number) (fn [x y] (tag (* x y)))) (pt-put 'div '(scheme-number scheme-number) (fn [x y] (tag (/ x y)))) (pt-put 'raise '(scheme-number) (fn [x] (make-rational x 1))) (pt-put 'make 'scheme-number tag))) (defn install-rational-package [] (let [numer (fn [x] (first x)) denom (fn [x] (second x)) make-rat (fn [n d] (let [g (gcd n d)] [(/ n g) (/ d g)])) add-rat (fn [x y] (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) sub-rat (fn [x y] (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) mul-rat (fn [x y] (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) div-rat (fn [x y] (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) tag (fn [x] (attach-tag 'rational x)) ] (pt-put 'add '(rational rational) (fn [x y] (tag (add-rat x y)))) (pt-put 'sub '(rational rational) (fn [x y] (tag (sub-rat x y)))) (pt-put 'mul '(rational rational) (fn [x y] (tag (mul-rat x y)))) (pt-put 'div '(rational rational) (fn [x y] (tag (div-rat x y)))) (pt-put 'raise '(rational) (fn [x] (make-complex-from-real-imag (/ (numer x) (denom x)) 0))) (pt-put 'make 'rational (fn [n d] (tag (make-rat n d)))))) (install-scheme-number-package) (install-rational-package) (raise (raise (make-scheme-number 3))) Exercise 2.84 (def type-levels {'scheme-number 0, 'rational 1, 'complex 2}) (defn get-coercion [orig-type dest-type] (let [orig-level (type-levels orig-type) dest-level (type-levels dest-type) level-diff (- dest-level orig-level)] (if (> level-diff 0) (apply comp (repeat level-diff raise)) nil))) (defn apply-generic [op & args] (defn coerce-list-to-type [lst type] (if (empty? lst) [] (let [t1->t2 (get-coercion (type-tag (first lst)) type)] (if t1->t2 (cons (t1->t2 (first lst)) (coerce-list-to-type (rest lst) type)) (cons (first lst) (coerce-list-to-type (rest lst) type)))))) (defn apply-coerced [lst] (if (empty? lst) (throw (RuntimeException. (str "No method for -- " op " - " args))) (let [coerced-list (coerce-list-to-type args (type-tag (first lst))) proc (pt-get op (map type-tag coerced-list))] (if proc (apply proc (map contents coerced-list)) (apply-coerced (rest lst)))))) (let [type-tags (map type-tag args) proc (pt-get op type-tags)] (if proc (apply proc (map contents args)) (apply-coerced args)))) (add (make-scheme-number 2) (make-scheme-number 2) (make-scheme-number 2)) (add (make-complex-from-real-imag 3 4) (make-complex-from-real-imag 3 4) (make-complex-from-real-imag 3 4)) (add (make-scheme-number 2) (make-complex-from-real-imag 3 4) (make-scheme-number 2))
3834b12aaa9d083ceebf74c6ae7498dfafd5f42ef96007be0b5e80efe11944ea
joergen7/cre
cre_sup.erl
%% -*- erlang -*- %% CRE : common runtime environment for distributed programming languages %% Copyright 2015 - 2019 < > %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% ------------------------------------------------------------------- @author < > %% @version 0.1.9 2013 - 2020 %% %% %% %% %% %% @end %% ------------------------------------------------------------------- -module( cre_sup ). -behaviour( supervisor ). %%==================================================================== %% Exports %%==================================================================== -export( [start_link/0] ). -export( [init/1] ). %%==================================================================== %% API functions %%==================================================================== -spec start_link() -> {ok, pid()} | {error, _}. start_link() -> supervisor:start_link( {local, cre_sup}, ?MODULE, [] ). %%==================================================================== %% Application callback functions %%==================================================================== -spec init( _ ) -> {ok, {#{ strategy => one_for_one, intensity => non_neg_integer(), period => pos_integer() }, [#{ id := _, start := {atom(), atom(), [_]}, restart => temporary, shutdown => non_neg_integer(), type => worker, modules => [atom()] }]}}. init( _Args ) -> SupFlags = #{ strategy => one_for_one, intensity => 0, period => 5 }, ChildSpec = #{ id => cre_master, start => {cre_master, start_link, [{local, cre_master}]}, restart => temporary, shutdown => 5000, type => worker, modules => [cre_master] }, {ok, {SupFlags, [ChildSpec]}}.
null
https://raw.githubusercontent.com/joergen7/cre/06435b4b8be6a74c26b3204314696b05ce066813/src/cre_sup.erl
erlang
-*- erlang -*- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @version 0.1.9 @end ------------------------------------------------------------------- ==================================================================== Exports ==================================================================== ==================================================================== API functions ==================================================================== ==================================================================== Application callback functions ====================================================================
CRE : common runtime environment for distributed programming languages Copyright 2015 - 2019 < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > 2013 - 2020 -module( cre_sup ). -behaviour( supervisor ). -export( [start_link/0] ). -export( [init/1] ). -spec start_link() -> {ok, pid()} | {error, _}. start_link() -> supervisor:start_link( {local, cre_sup}, ?MODULE, [] ). -spec init( _ ) -> {ok, {#{ strategy => one_for_one, intensity => non_neg_integer(), period => pos_integer() }, [#{ id := _, start := {atom(), atom(), [_]}, restart => temporary, shutdown => non_neg_integer(), type => worker, modules => [atom()] }]}}. init( _Args ) -> SupFlags = #{ strategy => one_for_one, intensity => 0, period => 5 }, ChildSpec = #{ id => cre_master, start => {cre_master, start_link, [{local, cre_master}]}, restart => temporary, shutdown => 5000, type => worker, modules => [cre_master] }, {ok, {SupFlags, [ChildSpec]}}.
a09603469a684f9dd58d701c52fa2d5b99b3744e3070f12ea929e12fdc7340cf
msakai/toysolver
PriorityQueue.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -Wall # {-# OPTIONS_HADDOCK show-extensions #-} ----------------------------------------------------------------------------- -- | -- Module : ToySolver.Internal.Data.PriorityQueue Copyright : ( c ) 2012 -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : non-portable -- -- Priority queue implemented as array-based binary heap. -- ----------------------------------------------------------------------------- module ToySolver.Internal.Data.PriorityQueue ( -- * PriorityQueue type PriorityQueue , Index -- * Constructors , newPriorityQueue , newPriorityQueueBy , NewFifo (..) -- * Operators , getElems , clear , clone , Enqueue (..) , Dequeue (..) , QueueSize (..) , rebuild , getHeapArray , getHeapVec -- * Misc operations , resizeHeapCapacity ) where import Control.Loop import qualified Data.Array.IO as A import Data.Queue.Classes import qualified ToySolver.Internal.Data.Vec as Vec type Index = Int -- | Priority queue implemented as array-based binary heap. data PriorityQueue a = PriorityQueue { lt :: !(a -> a -> IO Bool) , heap :: !(Vec.Vec a) } | Build a priority queue with default ordering ( ' ( < ) ' of ' ' class ) newPriorityQueue :: Ord a => IO (PriorityQueue a) newPriorityQueue = newPriorityQueueBy (\a b -> return (a < b)) -- | Build a priority queue with a given /less than/ operator. newPriorityQueueBy :: (a -> a -> IO Bool) -> IO (PriorityQueue a) newPriorityQueueBy cmp = do vec <- Vec.new return $ PriorityQueue{ lt = cmp, heap = vec } -- | Return a list of all the elements of a priority queue. (not sorted) getElems :: PriorityQueue a -> IO [a] getElems q = Vec.getElems (heap q) -- | Remove all elements from a priority queue. clear :: PriorityQueue a -> IO () clear q = Vec.clear (heap q) -- | Create a copy of a priority queue. clone :: PriorityQueue a -> IO (PriorityQueue a) clone q = do h2 <- Vec.clone (heap q) return $ PriorityQueue{ lt = lt q, heap = h2 } instance Ord a => NewFifo (PriorityQueue a) IO where newFifo = newPriorityQueue instance Enqueue (PriorityQueue a) IO a where enqueue q val = do n <- Vec.getSize (heap q) Vec.push (heap q) val up q n instance Dequeue (PriorityQueue a) IO a where dequeue q = do n <- Vec.getSize (heap q) case n of 0 -> return Nothing _ -> do val <- Vec.unsafeRead (heap q) 0 if n == 1 then do Vec.resize (heap q) (n-1) else do val1 <- Vec.unsafePop (heap q) Vec.unsafeWrite (heap q) 0 val1 down q 0 return (Just val) dequeueBatch q = go [] where go :: [a] -> IO [a] go xs = do r <- dequeue q case r of Nothing -> return (reverse xs) Just x -> go (x:xs) instance QueueSize (PriorityQueue a) IO where queueSize q = Vec.getSize (heap q) up :: PriorityQueue a -> Index -> IO () up q !i = do val <- Vec.unsafeRead (heap q) i let loop 0 = return 0 loop j = do let p = parent j val_p <- Vec.unsafeRead (heap q) p b <- lt q val val_p if b then do Vec.unsafeWrite (heap q) j val_p loop p else return j j <- loop i Vec.unsafeWrite (heap q) j val down :: PriorityQueue a -> Index -> IO () down q !i = do n <- Vec.getSize (heap q) val <- Vec.unsafeRead (heap q) i let loop !j = do let !l = left j !r = right j if l >= n then return j else do child <- do if r >= n then return l else do val_l <- Vec.unsafeRead (heap q) l val_r <- Vec.unsafeRead (heap q) r b <- lt q val_r val_l if b then return r else return l val_child <- Vec.unsafeRead (heap q) child b <- lt q val_child val if not b then return j else do Vec.unsafeWrite (heap q) j val_child loop child j <- loop i Vec.unsafeWrite (heap q) j val rebuild :: PriorityQueue a -> IO () rebuild q = do n <- Vec.getSize (heap q) forLoop 0 (<n) (+1) $ \i -> do up q i -- | Get the internal representation of a given priority queue. getHeapArray :: PriorityQueue a -> IO (A.IOArray Index a) getHeapArray q = Vec.getArray (heap q) -- | Get the internal representation of a given priority queue. getHeapVec :: PriorityQueue a -> IO (Vec.Vec a) getHeapVec q = return (heap q) | Pre - allocate internal buffer for @n@ elements . resizeHeapCapacity :: PriorityQueue a -> Int -> IO () resizeHeapCapacity q capa = Vec.resizeCapacity (heap q) capa {-------------------------------------------------------------------- Index "traversal" functions --------------------------------------------------------------------} {-# INLINE left #-} left :: Index -> Index left i = i*2 + 1 # INLINE right # right :: Index -> Index right i = (i+1)*2; {-# INLINE parent #-} parent :: Index -> Index parent i = (i-1) `div` 2 {-------------------------------------------------------------------- test --------------------------------------------------------------------} checkHeapProperty : : String - > PriorityQueue a - > IO ( ) = do ( n , ) < - readIORef ( heap q ) let go i = do val < - A.readArray arr i forM _ [ left i , right i ] $ \j - > when ( j < n ) $ do val2 < - A.readArray arr j b < - lt q val2 val when b $ do error ( str + + " : invalid heap " + + show j ) go j when ( n > 0 ) $ go 0 checkHeapProperty :: String -> PriorityQueue a -> IO () checkHeapProperty str q = do (n,arr) <- readIORef (heap q) let go i = do val <- A.readArray arr i forM_ [left i, right i] $ \j -> when (j < n) $ do val2 <- A.readArray arr j b <- lt q val2 val when b $ do error (str ++ ": invalid heap " ++ show j) go j when (n > 0) $ go 0 -}
null
https://raw.githubusercontent.com/msakai/toysolver/6233d130d3dcea32fa34c26feebd151f546dea85/src/ToySolver/Internal/Data/PriorityQueue.hs
haskell
# LANGUAGE BangPatterns # # OPTIONS_HADDOCK show-extensions # --------------------------------------------------------------------------- | Module : ToySolver.Internal.Data.PriorityQueue License : BSD-style Maintainer : Stability : provisional Portability : non-portable Priority queue implemented as array-based binary heap. --------------------------------------------------------------------------- * PriorityQueue type * Constructors * Operators * Misc operations | Priority queue implemented as array-based binary heap. | Build a priority queue with a given /less than/ operator. | Return a list of all the elements of a priority queue. (not sorted) | Remove all elements from a priority queue. | Create a copy of a priority queue. | Get the internal representation of a given priority queue. | Get the internal representation of a given priority queue. ------------------------------------------------------------------- Index "traversal" functions ------------------------------------------------------------------- # INLINE left # # INLINE parent # ------------------------------------------------------------------- test -------------------------------------------------------------------
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -Wall # Copyright : ( c ) 2012 module ToySolver.Internal.Data.PriorityQueue ( PriorityQueue , Index , newPriorityQueue , newPriorityQueueBy , NewFifo (..) , getElems , clear , clone , Enqueue (..) , Dequeue (..) , QueueSize (..) , rebuild , getHeapArray , getHeapVec , resizeHeapCapacity ) where import Control.Loop import qualified Data.Array.IO as A import Data.Queue.Classes import qualified ToySolver.Internal.Data.Vec as Vec type Index = Int data PriorityQueue a = PriorityQueue { lt :: !(a -> a -> IO Bool) , heap :: !(Vec.Vec a) } | Build a priority queue with default ordering ( ' ( < ) ' of ' ' class ) newPriorityQueue :: Ord a => IO (PriorityQueue a) newPriorityQueue = newPriorityQueueBy (\a b -> return (a < b)) newPriorityQueueBy :: (a -> a -> IO Bool) -> IO (PriorityQueue a) newPriorityQueueBy cmp = do vec <- Vec.new return $ PriorityQueue{ lt = cmp, heap = vec } getElems :: PriorityQueue a -> IO [a] getElems q = Vec.getElems (heap q) clear :: PriorityQueue a -> IO () clear q = Vec.clear (heap q) clone :: PriorityQueue a -> IO (PriorityQueue a) clone q = do h2 <- Vec.clone (heap q) return $ PriorityQueue{ lt = lt q, heap = h2 } instance Ord a => NewFifo (PriorityQueue a) IO where newFifo = newPriorityQueue instance Enqueue (PriorityQueue a) IO a where enqueue q val = do n <- Vec.getSize (heap q) Vec.push (heap q) val up q n instance Dequeue (PriorityQueue a) IO a where dequeue q = do n <- Vec.getSize (heap q) case n of 0 -> return Nothing _ -> do val <- Vec.unsafeRead (heap q) 0 if n == 1 then do Vec.resize (heap q) (n-1) else do val1 <- Vec.unsafePop (heap q) Vec.unsafeWrite (heap q) 0 val1 down q 0 return (Just val) dequeueBatch q = go [] where go :: [a] -> IO [a] go xs = do r <- dequeue q case r of Nothing -> return (reverse xs) Just x -> go (x:xs) instance QueueSize (PriorityQueue a) IO where queueSize q = Vec.getSize (heap q) up :: PriorityQueue a -> Index -> IO () up q !i = do val <- Vec.unsafeRead (heap q) i let loop 0 = return 0 loop j = do let p = parent j val_p <- Vec.unsafeRead (heap q) p b <- lt q val val_p if b then do Vec.unsafeWrite (heap q) j val_p loop p else return j j <- loop i Vec.unsafeWrite (heap q) j val down :: PriorityQueue a -> Index -> IO () down q !i = do n <- Vec.getSize (heap q) val <- Vec.unsafeRead (heap q) i let loop !j = do let !l = left j !r = right j if l >= n then return j else do child <- do if r >= n then return l else do val_l <- Vec.unsafeRead (heap q) l val_r <- Vec.unsafeRead (heap q) r b <- lt q val_r val_l if b then return r else return l val_child <- Vec.unsafeRead (heap q) child b <- lt q val_child val if not b then return j else do Vec.unsafeWrite (heap q) j val_child loop child j <- loop i Vec.unsafeWrite (heap q) j val rebuild :: PriorityQueue a -> IO () rebuild q = do n <- Vec.getSize (heap q) forLoop 0 (<n) (+1) $ \i -> do up q i getHeapArray :: PriorityQueue a -> IO (A.IOArray Index a) getHeapArray q = Vec.getArray (heap q) getHeapVec :: PriorityQueue a -> IO (Vec.Vec a) getHeapVec q = return (heap q) | Pre - allocate internal buffer for @n@ elements . resizeHeapCapacity :: PriorityQueue a -> Int -> IO () resizeHeapCapacity q capa = Vec.resizeCapacity (heap q) capa left :: Index -> Index left i = i*2 + 1 # INLINE right # right :: Index -> Index right i = (i+1)*2; parent :: Index -> Index parent i = (i-1) `div` 2 checkHeapProperty : : String - > PriorityQueue a - > IO ( ) = do ( n , ) < - readIORef ( heap q ) let go i = do val < - A.readArray arr i forM _ [ left i , right i ] $ \j - > when ( j < n ) $ do val2 < - A.readArray arr j b < - lt q val2 val when b $ do error ( str + + " : invalid heap " + + show j ) go j when ( n > 0 ) $ go 0 checkHeapProperty :: String -> PriorityQueue a -> IO () checkHeapProperty str q = do (n,arr) <- readIORef (heap q) let go i = do val <- A.readArray arr i forM_ [left i, right i] $ \j -> when (j < n) $ do val2 <- A.readArray arr j b <- lt q val2 val when b $ do error (str ++ ": invalid heap " ++ show j) go j when (n > 0) $ go 0 -}
7f4768ef92b66d76043278a838ae063025a68ad40d62486ca83d0acf033ba75d
generateme/fastmath
complex_examples.clj
(ns fastmath.complex-examples (:refer-clojure :exclude [abs]) (:require [fastmath.complex :refer :all] [metadoc.examples :refer :all] [fastmath.core :as m])) (add-examples complex (example "New complex number." (complex 2 -1))) (add-examples abs (example "Abs" (abs (complex 1 -3)))) (add-examples add (example "Sum" (add I ONE))) (add-examples sub (example "Subtract" (sub ONE I-))) (add-examples arg (example "Argument" (m/degrees (arg I-)))) (add-examples conjugate (example "Conjugate" (conjugate I))) (add-examples div (example "Divide" (div (complex 1 2) (complex 3 4)))) (add-examples reciprocal (example "Reciprocal of real" (reciprocal TWO)) (example "Reciprocal of complex" (reciprocal (complex 0 2)))) (add-examples mult (example "Multiply" (mult (complex 1 2) (complex 3 4)))) (add-examples neg (example "Negate." (neg (complex 1 2)))) (add-examples sq (example "Square." (sq (complex 1 2))) (example "\\\\(i^2\\\\)" (sq I))) (add-examples sqrt (example "Square root of real." (sqrt (complex 2 0))) (example "Square root of complex." (sqrt (complex 2 2)))) (add-examples sqrt1z (example "Example 1" (sqrt1z (complex 2 3)))) (add-examples cos (example "cos(z)" (cos (complex 2 -1)))) (add-examples sin (example "sin(z)" (sin (complex 2 -1)))) (add-examples cosh (example "cosh(z)" (cosh (complex 2 -1)))) (add-examples sinh (example "sinh(z)" (sinh (complex 2 -1)))) (add-examples tan (example "tan(z)" (tan (complex 2 -1)))) (add-examples tanh (example "tanh(z)" (tanh (complex 2 -1)))) (add-examples sec (example "sec(z)" (sec (complex 2 -1)))) (add-examples csc (example "csc(z)" (csc (complex 2 -1)))) (add-examples acos (example "acos(z)" (acos (complex 2 -1)))) (add-examples asin (example "asin(z)" (asin (complex 2 -1)))) (add-examples atan (example "atan(z)" (atan (complex 2 -1)))) (add-examples exp (example "exp(z)" (exp (complex 2 -1))) (example "\\\\(e^{i\\pi}+1\\\\)" (add (exp (complex 0 m/PI)) ONE))) (add-examples log (example "log(z)" (log (complex 2 -1))) (example "log(e)" (log (complex m/E 0)))) (add-examples pow (example "\\\\(\\sqrt{2}\\\\)" (pow TWO (complex 0.5 0.0))) (example "Complex power" (pow (complex 1 2) (complex 3 4)))) (def fn-list `(atan asin acos log exp csc sec tanh tan sinh sin cosh cos sqrt sq sqrt1z reciprocal)) (defmacro ^:private add-image-examples [] `(do ~@(for [x fn-list] `(add-examples ~x (example-image ~(str "Plot of " (name x)) ~(str "images/c/" (name x) ".jpg")))))) (add-image-examples)
null
https://raw.githubusercontent.com/generateme/fastmath/19c2a6e9a734c815cc55594fc1b5bb58a5993910/metadoc/fastmath/complex_examples.clj
clojure
(ns fastmath.complex-examples (:refer-clojure :exclude [abs]) (:require [fastmath.complex :refer :all] [metadoc.examples :refer :all] [fastmath.core :as m])) (add-examples complex (example "New complex number." (complex 2 -1))) (add-examples abs (example "Abs" (abs (complex 1 -3)))) (add-examples add (example "Sum" (add I ONE))) (add-examples sub (example "Subtract" (sub ONE I-))) (add-examples arg (example "Argument" (m/degrees (arg I-)))) (add-examples conjugate (example "Conjugate" (conjugate I))) (add-examples div (example "Divide" (div (complex 1 2) (complex 3 4)))) (add-examples reciprocal (example "Reciprocal of real" (reciprocal TWO)) (example "Reciprocal of complex" (reciprocal (complex 0 2)))) (add-examples mult (example "Multiply" (mult (complex 1 2) (complex 3 4)))) (add-examples neg (example "Negate." (neg (complex 1 2)))) (add-examples sq (example "Square." (sq (complex 1 2))) (example "\\\\(i^2\\\\)" (sq I))) (add-examples sqrt (example "Square root of real." (sqrt (complex 2 0))) (example "Square root of complex." (sqrt (complex 2 2)))) (add-examples sqrt1z (example "Example 1" (sqrt1z (complex 2 3)))) (add-examples cos (example "cos(z)" (cos (complex 2 -1)))) (add-examples sin (example "sin(z)" (sin (complex 2 -1)))) (add-examples cosh (example "cosh(z)" (cosh (complex 2 -1)))) (add-examples sinh (example "sinh(z)" (sinh (complex 2 -1)))) (add-examples tan (example "tan(z)" (tan (complex 2 -1)))) (add-examples tanh (example "tanh(z)" (tanh (complex 2 -1)))) (add-examples sec (example "sec(z)" (sec (complex 2 -1)))) (add-examples csc (example "csc(z)" (csc (complex 2 -1)))) (add-examples acos (example "acos(z)" (acos (complex 2 -1)))) (add-examples asin (example "asin(z)" (asin (complex 2 -1)))) (add-examples atan (example "atan(z)" (atan (complex 2 -1)))) (add-examples exp (example "exp(z)" (exp (complex 2 -1))) (example "\\\\(e^{i\\pi}+1\\\\)" (add (exp (complex 0 m/PI)) ONE))) (add-examples log (example "log(z)" (log (complex 2 -1))) (example "log(e)" (log (complex m/E 0)))) (add-examples pow (example "\\\\(\\sqrt{2}\\\\)" (pow TWO (complex 0.5 0.0))) (example "Complex power" (pow (complex 1 2) (complex 3 4)))) (def fn-list `(atan asin acos log exp csc sec tanh tan sinh sin cosh cos sqrt sq sqrt1z reciprocal)) (defmacro ^:private add-image-examples [] `(do ~@(for [x fn-list] `(add-examples ~x (example-image ~(str "Plot of " (name x)) ~(str "images/c/" (name x) ".jpg")))))) (add-image-examples)
348c052397702d9352815e21f6e274ba2730b351b47e71a9c18a1324b8ed4596
emqx/emqx
emqx_authz_mnesia.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_authz_mnesia). -include_lib("emqx/include/emqx.hrl"). -include_lib("stdlib/include/ms_transform.hrl"). -include_lib("emqx/include/logger.hrl"). -include("emqx_authz.hrl"). -define(ACL_SHARDED, emqx_acl_sharded). To save some space , use an integer for label , 0 for ' all ' , { 1 , Username } and { 2 , ClientId } . -define(ACL_TABLE_ALL, 0). -define(ACL_TABLE_USERNAME, 1). -define(ACL_TABLE_CLIENTID, 2). -type username() :: {username, binary()}. -type clientid() :: {clientid, binary()}. -type who() :: username() | clientid() | all. -type rule() :: {emqx_authz_rule:permission(), emqx_authz_rule:action(), emqx_topic:topic()}. -type rules() :: [rule()]. -record(emqx_acl, { who :: ?ACL_TABLE_ALL | {?ACL_TABLE_USERNAME, binary()} | {?ACL_TABLE_CLIENTID, binary()}, rules :: rules() }). -behaviour(emqx_authz). AuthZ Callbacks -export([ description/0, create/1, update/1, destroy/1, authorize/4 ]). %% Management API -export([ mnesia/1, init_tables/0, store_rules/2, purge_rules/0, get_rules/1, delete_rules/1, list_clientid_rules/0, list_username_rules/0, record_count/0 ]). -ifdef(TEST). -compile(export_all). -compile(nowarn_export_all). -endif. -boot_mnesia({mnesia, [boot]}). -spec mnesia(boot | copy) -> ok. mnesia(boot) -> ok = mria:create_table(?ACL_TABLE, [ {type, ordered_set}, {rlog_shard, ?ACL_SHARDED}, {storage, disc_copies}, {attributes, record_info(fields, ?ACL_TABLE)}, {storage_properties, [{ets, [{read_concurrency, true}]}]} ]). %%-------------------------------------------------------------------- %% emqx_authz callbacks %%-------------------------------------------------------------------- description() -> "AuthZ with Mnesia". create(Source) -> Source. update(Source) -> Source. destroy(_Source) -> ok. authorize( #{ username := Username, clientid := Clientid } = Client, PubSub, Topic, #{type := built_in_database} ) -> Rules = case mnesia:dirty_read(?ACL_TABLE, {?ACL_TABLE_CLIENTID, Clientid}) of [] -> []; [#emqx_acl{rules = Rules0}] when is_list(Rules0) -> Rules0 end ++ case mnesia:dirty_read(?ACL_TABLE, {?ACL_TABLE_USERNAME, Username}) of [] -> []; [#emqx_acl{rules = Rules1}] when is_list(Rules1) -> Rules1 end ++ case mnesia:dirty_read(?ACL_TABLE, ?ACL_TABLE_ALL) of [] -> []; [#emqx_acl{rules = Rules2}] when is_list(Rules2) -> Rules2 end, do_authorize(Client, PubSub, Topic, Rules). %%-------------------------------------------------------------------- %% Management API %%-------------------------------------------------------------------- Init -spec init_tables() -> ok. init_tables() -> ok = mria_rlog:wait_for_shards([?ACL_SHARDED], infinity). %% @doc Update authz rules -spec store_rules(who(), rules()) -> ok. store_rules({username, Username}, Rules) -> Record = #emqx_acl{who = {?ACL_TABLE_USERNAME, Username}, rules = normalize_rules(Rules)}, mria:dirty_write(Record); store_rules({clientid, Clientid}, Rules) -> Record = #emqx_acl{who = {?ACL_TABLE_CLIENTID, Clientid}, rules = normalize_rules(Rules)}, mria:dirty_write(Record); store_rules(all, Rules) -> Record = #emqx_acl{who = ?ACL_TABLE_ALL, rules = normalize_rules(Rules)}, mria:dirty_write(Record). @doc Clean all authz rules for ( username & clientid & all ) -spec purge_rules() -> ok. purge_rules() -> ok = lists:foreach( fun(Key) -> ok = mria:dirty_delete(?ACL_TABLE, Key) end, mnesia:dirty_all_keys(?ACL_TABLE) ). @doc Get one record -spec get_rules(who()) -> {ok, rules()} | not_found. get_rules({username, Username}) -> do_get_rules({?ACL_TABLE_USERNAME, Username}); get_rules({clientid, Clientid}) -> do_get_rules({?ACL_TABLE_CLIENTID, Clientid}); get_rules(all) -> do_get_rules(?ACL_TABLE_ALL). @doc Delete one record -spec delete_rules(who()) -> ok. delete_rules({username, Username}) -> mria:dirty_delete(?ACL_TABLE, {?ACL_TABLE_USERNAME, Username}); delete_rules({clientid, Clientid}) -> mria:dirty_delete(?ACL_TABLE, {?ACL_TABLE_CLIENTID, Clientid}); delete_rules(all) -> mria:dirty_delete(?ACL_TABLE, ?ACL_TABLE_ALL). -spec list_username_rules() -> ets:match_spec(). list_username_rules() -> ets:fun2ms( fun(#emqx_acl{who = {?ACL_TABLE_USERNAME, Username}, rules = Rules}) -> [{username, Username}, {rules, Rules}] end ). -spec list_clientid_rules() -> ets:match_spec(). list_clientid_rules() -> ets:fun2ms( fun(#emqx_acl{who = {?ACL_TABLE_CLIENTID, Clientid}, rules = Rules}) -> [{clientid, Clientid}, {rules, Rules}] end ). -spec record_count() -> non_neg_integer(). record_count() -> mnesia:table_info(?ACL_TABLE, size). %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- normalize_rules(Rules) -> lists:map(fun normalize_rule/1, Rules). normalize_rule({Permission, Action, Topic}) -> {normalize_permission(Permission), normalize_action(Action), normalize_topic(Topic)}; normalize_rule(Rule) -> error({invalid_rule, Rule}). normalize_topic(Topic) when is_list(Topic) -> list_to_binary(Topic); normalize_topic(Topic) when is_binary(Topic) -> Topic; normalize_topic(Topic) -> error({invalid_rule_topic, Topic}). normalize_action(publish) -> publish; normalize_action(subscribe) -> subscribe; normalize_action(all) -> all; normalize_action(Action) -> error({invalid_rule_action, Action}). normalize_permission(allow) -> allow; normalize_permission(deny) -> deny; normalize_permission(Permission) -> error({invalid_rule_permission, Permission}). do_get_rules(Key) -> case mnesia:dirty_read(?ACL_TABLE, Key) of [#emqx_acl{rules = Rules}] -> {ok, Rules}; [] -> not_found end. do_authorize(_Client, _PubSub, _Topic, []) -> nomatch; do_authorize(Client, PubSub, Topic, [{Permission, Action, TopicFilter} | Tail]) -> Rule = emqx_authz_rule:compile({Permission, all, Action, [TopicFilter]}), case emqx_authz_rule:match(Client, PubSub, Topic, Rule) of {matched, Permission} -> {matched, Permission}; nomatch -> do_authorize(Client, PubSub, Topic, Tail) end.
null
https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_authz/src/emqx_authz_mnesia.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------- Management API -------------------------------------------------------------------- emqx_authz callbacks -------------------------------------------------------------------- -------------------------------------------------------------------- Management API -------------------------------------------------------------------- @doc Update authz rules -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_authz_mnesia). -include_lib("emqx/include/emqx.hrl"). -include_lib("stdlib/include/ms_transform.hrl"). -include_lib("emqx/include/logger.hrl"). -include("emqx_authz.hrl"). -define(ACL_SHARDED, emqx_acl_sharded). To save some space , use an integer for label , 0 for ' all ' , { 1 , Username } and { 2 , ClientId } . -define(ACL_TABLE_ALL, 0). -define(ACL_TABLE_USERNAME, 1). -define(ACL_TABLE_CLIENTID, 2). -type username() :: {username, binary()}. -type clientid() :: {clientid, binary()}. -type who() :: username() | clientid() | all. -type rule() :: {emqx_authz_rule:permission(), emqx_authz_rule:action(), emqx_topic:topic()}. -type rules() :: [rule()]. -record(emqx_acl, { who :: ?ACL_TABLE_ALL | {?ACL_TABLE_USERNAME, binary()} | {?ACL_TABLE_CLIENTID, binary()}, rules :: rules() }). -behaviour(emqx_authz). AuthZ Callbacks -export([ description/0, create/1, update/1, destroy/1, authorize/4 ]). -export([ mnesia/1, init_tables/0, store_rules/2, purge_rules/0, get_rules/1, delete_rules/1, list_clientid_rules/0, list_username_rules/0, record_count/0 ]). -ifdef(TEST). -compile(export_all). -compile(nowarn_export_all). -endif. -boot_mnesia({mnesia, [boot]}). -spec mnesia(boot | copy) -> ok. mnesia(boot) -> ok = mria:create_table(?ACL_TABLE, [ {type, ordered_set}, {rlog_shard, ?ACL_SHARDED}, {storage, disc_copies}, {attributes, record_info(fields, ?ACL_TABLE)}, {storage_properties, [{ets, [{read_concurrency, true}]}]} ]). description() -> "AuthZ with Mnesia". create(Source) -> Source. update(Source) -> Source. destroy(_Source) -> ok. authorize( #{ username := Username, clientid := Clientid } = Client, PubSub, Topic, #{type := built_in_database} ) -> Rules = case mnesia:dirty_read(?ACL_TABLE, {?ACL_TABLE_CLIENTID, Clientid}) of [] -> []; [#emqx_acl{rules = Rules0}] when is_list(Rules0) -> Rules0 end ++ case mnesia:dirty_read(?ACL_TABLE, {?ACL_TABLE_USERNAME, Username}) of [] -> []; [#emqx_acl{rules = Rules1}] when is_list(Rules1) -> Rules1 end ++ case mnesia:dirty_read(?ACL_TABLE, ?ACL_TABLE_ALL) of [] -> []; [#emqx_acl{rules = Rules2}] when is_list(Rules2) -> Rules2 end, do_authorize(Client, PubSub, Topic, Rules). Init -spec init_tables() -> ok. init_tables() -> ok = mria_rlog:wait_for_shards([?ACL_SHARDED], infinity). -spec store_rules(who(), rules()) -> ok. store_rules({username, Username}, Rules) -> Record = #emqx_acl{who = {?ACL_TABLE_USERNAME, Username}, rules = normalize_rules(Rules)}, mria:dirty_write(Record); store_rules({clientid, Clientid}, Rules) -> Record = #emqx_acl{who = {?ACL_TABLE_CLIENTID, Clientid}, rules = normalize_rules(Rules)}, mria:dirty_write(Record); store_rules(all, Rules) -> Record = #emqx_acl{who = ?ACL_TABLE_ALL, rules = normalize_rules(Rules)}, mria:dirty_write(Record). @doc Clean all authz rules for ( username & clientid & all ) -spec purge_rules() -> ok. purge_rules() -> ok = lists:foreach( fun(Key) -> ok = mria:dirty_delete(?ACL_TABLE, Key) end, mnesia:dirty_all_keys(?ACL_TABLE) ). @doc Get one record -spec get_rules(who()) -> {ok, rules()} | not_found. get_rules({username, Username}) -> do_get_rules({?ACL_TABLE_USERNAME, Username}); get_rules({clientid, Clientid}) -> do_get_rules({?ACL_TABLE_CLIENTID, Clientid}); get_rules(all) -> do_get_rules(?ACL_TABLE_ALL). @doc Delete one record -spec delete_rules(who()) -> ok. delete_rules({username, Username}) -> mria:dirty_delete(?ACL_TABLE, {?ACL_TABLE_USERNAME, Username}); delete_rules({clientid, Clientid}) -> mria:dirty_delete(?ACL_TABLE, {?ACL_TABLE_CLIENTID, Clientid}); delete_rules(all) -> mria:dirty_delete(?ACL_TABLE, ?ACL_TABLE_ALL). -spec list_username_rules() -> ets:match_spec(). list_username_rules() -> ets:fun2ms( fun(#emqx_acl{who = {?ACL_TABLE_USERNAME, Username}, rules = Rules}) -> [{username, Username}, {rules, Rules}] end ). -spec list_clientid_rules() -> ets:match_spec(). list_clientid_rules() -> ets:fun2ms( fun(#emqx_acl{who = {?ACL_TABLE_CLIENTID, Clientid}, rules = Rules}) -> [{clientid, Clientid}, {rules, Rules}] end ). -spec record_count() -> non_neg_integer(). record_count() -> mnesia:table_info(?ACL_TABLE, size). Internal functions normalize_rules(Rules) -> lists:map(fun normalize_rule/1, Rules). normalize_rule({Permission, Action, Topic}) -> {normalize_permission(Permission), normalize_action(Action), normalize_topic(Topic)}; normalize_rule(Rule) -> error({invalid_rule, Rule}). normalize_topic(Topic) when is_list(Topic) -> list_to_binary(Topic); normalize_topic(Topic) when is_binary(Topic) -> Topic; normalize_topic(Topic) -> error({invalid_rule_topic, Topic}). normalize_action(publish) -> publish; normalize_action(subscribe) -> subscribe; normalize_action(all) -> all; normalize_action(Action) -> error({invalid_rule_action, Action}). normalize_permission(allow) -> allow; normalize_permission(deny) -> deny; normalize_permission(Permission) -> error({invalid_rule_permission, Permission}). do_get_rules(Key) -> case mnesia:dirty_read(?ACL_TABLE, Key) of [#emqx_acl{rules = Rules}] -> {ok, Rules}; [] -> not_found end. do_authorize(_Client, _PubSub, _Topic, []) -> nomatch; do_authorize(Client, PubSub, Topic, [{Permission, Action, TopicFilter} | Tail]) -> Rule = emqx_authz_rule:compile({Permission, all, Action, [TopicFilter]}), case emqx_authz_rule:match(Client, PubSub, Topic, Rule) of {matched, Permission} -> {matched, Permission}; nomatch -> do_authorize(Client, PubSub, Topic, Tail) end.
f3b037cd36da74aa6c30e6ac04bf0c121a6bc70f6619784c5b382cd4b4c77b1e
exercism/racket
gigasecond-test.rkt
#lang racket (require "gigasecond.rkt") (module+ test (require rackunit rackunit/text-ui racket/date)) (module+ test (define (make-datetime year month day hour minute second) (seconds->date (find-seconds second minute hour day month year #f))) (define suite (test-suite "Tests for the gigasecond exercise" (test-equal? "test 2011 04 25" (add-gigasecond (make-datetime 2011 4 25 0 0 0)) (make-datetime 2043 1 1 1 46 40)) (test-equal? "test 1977 06 13" (add-gigasecond (make-datetime 1977 6 13 0 0 0)) (make-datetime 2009 2 19 1 46 40)) (test-equal? "test 1959 07 19" (add-gigasecond (make-datetime 1959 7 19 0 0 0)) (make-datetime 1991 3 27 1 46 40)) (test-equal? "test full time specified" (add-gigasecond (make-datetime 2015 1 24 22 0 0)) (make-datetime 2046 10 2 23 46 40)) (test-equal? "test full time with day roll over" (add-gigasecond (make-datetime 2015 1 24 23 59 59)) (make-datetime 2046 10 3 1 46 39)))) (run-tests suite))
null
https://raw.githubusercontent.com/exercism/racket/4110268ed331b1b4dac8888550f05d0dacb1865b/exercises/practice/gigasecond/gigasecond-test.rkt
racket
#lang racket (require "gigasecond.rkt") (module+ test (require rackunit rackunit/text-ui racket/date)) (module+ test (define (make-datetime year month day hour minute second) (seconds->date (find-seconds second minute hour day month year #f))) (define suite (test-suite "Tests for the gigasecond exercise" (test-equal? "test 2011 04 25" (add-gigasecond (make-datetime 2011 4 25 0 0 0)) (make-datetime 2043 1 1 1 46 40)) (test-equal? "test 1977 06 13" (add-gigasecond (make-datetime 1977 6 13 0 0 0)) (make-datetime 2009 2 19 1 46 40)) (test-equal? "test 1959 07 19" (add-gigasecond (make-datetime 1959 7 19 0 0 0)) (make-datetime 1991 3 27 1 46 40)) (test-equal? "test full time specified" (add-gigasecond (make-datetime 2015 1 24 22 0 0)) (make-datetime 2046 10 2 23 46 40)) (test-equal? "test full time with day roll over" (add-gigasecond (make-datetime 2015 1 24 23 59 59)) (make-datetime 2046 10 3 1 46 39)))) (run-tests suite))
2077f80f29b61b8d9e4fa344ec931cecbb55c12e836b4779ebccdcabeeed4442
metaocaml/ber-metaocaml
test_strongly_connected_components.ml
(* TEST include config include testing binary_modules = "config build_path_prefix_map misc identifiable numbers \ strongly_connected_components" * bytecode *) module Int = Numbers.Int module SCC = Strongly_connected_components.Make (Int) let graph_1 = [1, [2;3;4]; 2, [3;5]; 3, [5]; 4, [1]; 5, [5]] let empty = [] let print_scc scc = Printf.printf "begin\n"; Array.iter (function | SCC.No_loop e -> Printf.printf "%i\n" e | SCC.Has_loop l -> Printf.printf "[%s]\n" (String.concat "; " (List.map Stdlib.Int.to_string l))) scc; Printf.printf "end\n" let scc graph = SCC.connected_components_sorted_from_roots_to_leaf (Int.Map.map Int.Set.of_list (Int.Map.of_list graph)) let run () = print_scc (scc empty); print_scc (scc graph_1); Format.printf "done@."
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/utils/test_strongly_connected_components.ml
ocaml
TEST include config include testing binary_modules = "config build_path_prefix_map misc identifiable numbers \ strongly_connected_components" * bytecode
module Int = Numbers.Int module SCC = Strongly_connected_components.Make (Int) let graph_1 = [1, [2;3;4]; 2, [3;5]; 3, [5]; 4, [1]; 5, [5]] let empty = [] let print_scc scc = Printf.printf "begin\n"; Array.iter (function | SCC.No_loop e -> Printf.printf "%i\n" e | SCC.Has_loop l -> Printf.printf "[%s]\n" (String.concat "; " (List.map Stdlib.Int.to_string l))) scc; Printf.printf "end\n" let scc graph = SCC.connected_components_sorted_from_roots_to_leaf (Int.Map.map Int.Set.of_list (Int.Map.of_list graph)) let run () = print_scc (scc empty); print_scc (scc graph_1); Format.printf "done@."
a32c58fe96fbf7a98657c231606e07342867137d6f564c7a372fe5d4d5d1a8f4
haroldcarr/learn-haskell-coq-ml-etc
TreeMap.hs
-- Introducing Functors 244/284 data Tree a = Node (Tree a) (Tree a) | Leaf a deriving (Show) -- take tree of strings and turn into tree of string lengths treeLengths (Leaf s) = Leaf (length s) treeLengths (Node l r) = Node (treeLengths l) (treeLengths r) -- more abstract treeMap :: (a -> b) -> Tree a -> Tree b treeMap f (Leaf a) = Leaf (f a) treeMap f (Node l r) = Node (treeMap f l) (treeMap f r) ( fmap : : ( a - > b ) - > f a - > f b ) can further generalize a kind of " lifting " takes a function over ordinary values a- > b lifts it to a function over containers f a - > f b , where f is the container type typeclass Functor (fmap :: (a -> b) -> f a -> f b) can further generalize a kind of "lifting" takes a function over ordinary values a-> b lifts it to a function over containers f a -> f b, where f is the container type -} for above instance Functor Tree where fmap = treeMap Functor imposes restrictions . Can only make instances of Functor from types that have one type parameter . E.g. , ca n't write an fmap implementation for Either a b or ( a , b ) or for or Int ( no type parameters ) . Also , ca n't place any constraints on type definitions - page 246/286 But putting type constraints on type definitions is a misfeature in Haskell . Alternative : only place on functions that need them . Functor imposes restrictions. Can only make instances of Functor from types that have one type parameter. E.g., can't write an fmap implementation for Either a b or (a, b) or for Bool or Int (no type parameters). Also, can't place any constraints on type definitions - page 246/286 But putting type constraints on type definitions is a misfeature in Haskell. Alternative: only place on functions that need them. -}
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/book/2009-Real_World_Haskell/TreeMap.hs
haskell
Introducing Functors 244/284 take tree of strings and turn into tree of string lengths more abstract
data Tree a = Node (Tree a) (Tree a) | Leaf a deriving (Show) treeLengths (Leaf s) = Leaf (length s) treeLengths (Node l r) = Node (treeLengths l) (treeLengths r) treeMap :: (a -> b) -> Tree a -> Tree b treeMap f (Leaf a) = Leaf (f a) treeMap f (Node l r) = Node (treeMap f l) (treeMap f r) ( fmap : : ( a - > b ) - > f a - > f b ) can further generalize a kind of " lifting " takes a function over ordinary values a- > b lifts it to a function over containers f a - > f b , where f is the container type typeclass Functor (fmap :: (a -> b) -> f a -> f b) can further generalize a kind of "lifting" takes a function over ordinary values a-> b lifts it to a function over containers f a -> f b, where f is the container type -} for above instance Functor Tree where fmap = treeMap Functor imposes restrictions . Can only make instances of Functor from types that have one type parameter . E.g. , ca n't write an fmap implementation for Either a b or ( a , b ) or for or Int ( no type parameters ) . Also , ca n't place any constraints on type definitions - page 246/286 But putting type constraints on type definitions is a misfeature in Haskell . Alternative : only place on functions that need them . Functor imposes restrictions. Can only make instances of Functor from types that have one type parameter. E.g., can't write an fmap implementation for Either a b or (a, b) or for Bool or Int (no type parameters). Also, can't place any constraints on type definitions - page 246/286 But putting type constraints on type definitions is a misfeature in Haskell. Alternative: only place on functions that need them. -}
e1eab4a8f6038ed19717f59179545a49f4d08a4f2de7c1a5118f5653f79f551d
incoherentsoftware/defect-process
Data.hs
module Level.Room.Tutorial.SandbagAir.Data ( SandbagAirData(..) , mkSandbagAirData ) where import Control.Monad.IO.Class (MonadIO) import Configs import Configs.All.Enemy import Level.Room.Tutorial.SandbagAir.Behavior import Level.Room.Tutorial.SandbagAir.Sprites import FileCache import Util import Window.Graphics data SandbagAirData = SandbagAirData { _spawnPos :: Pos2 , _spawnDir :: Direction , _sprites :: SandbagAirSprites , _behavior :: SandbagAirBehavior , _prevBehavior :: SandbagAirBehavior , _config :: EnemyConfig } mkSandbagAirData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => Pos2 -> Direction -> m SandbagAirData mkSandbagAirData spawnPos spawnDir = do sprs <- mkSandbagAirSprites cfg <- _enemy <$> readConfigs return $ SandbagAirData { _spawnPos = spawnPos , _spawnDir = spawnDir , _sprites = sprs , _behavior = SpawnBehavior , _prevBehavior = SpawnBehavior , _config = cfg }
null
https://raw.githubusercontent.com/incoherentsoftware/defect-process/c39ce1f742d32a0ffcde82c03bf872adeb7d9162/src/Level/Room/Tutorial/SandbagAir/Data.hs
haskell
module Level.Room.Tutorial.SandbagAir.Data ( SandbagAirData(..) , mkSandbagAirData ) where import Control.Monad.IO.Class (MonadIO) import Configs import Configs.All.Enemy import Level.Room.Tutorial.SandbagAir.Behavior import Level.Room.Tutorial.SandbagAir.Sprites import FileCache import Util import Window.Graphics data SandbagAirData = SandbagAirData { _spawnPos :: Pos2 , _spawnDir :: Direction , _sprites :: SandbagAirSprites , _behavior :: SandbagAirBehavior , _prevBehavior :: SandbagAirBehavior , _config :: EnemyConfig } mkSandbagAirData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => Pos2 -> Direction -> m SandbagAirData mkSandbagAirData spawnPos spawnDir = do sprs <- mkSandbagAirSprites cfg <- _enemy <$> readConfigs return $ SandbagAirData { _spawnPos = spawnPos , _spawnDir = spawnDir , _sprites = sprs , _behavior = SpawnBehavior , _prevBehavior = SpawnBehavior , _config = cfg }
296e0e00277d8b4bca63a612dde53fe9a25ceb03f5918e1c403d8be5cebde46f
rothfield/doremi-script
views.cljs
(ns doremi-script.views (:require [doremi-script.dom-utils :refer [by-id]] ;; listen seconds]] [doremi-script.utils :refer [get-attributes keywordize-vector log is?] ] ;; [doremi-script.doremi_core :as doremi_core ;; :refer [doremi-text->collapsed-parse-tree]] [doremi-script.dom-fixes :refer [dom-fixes]] [goog.dom :as dom] [goog.Uri] [goog.events :as events] [clojure.string :as string :refer [join]] [dommy.core :as dommy :refer-macros [sel sel1]] [cljs.core.async :refer [<! chan close! timeout put!]] [reagent.core :as reagent] [re-frame.core :refer [register-handler path register-sub dispatch dispatch-sync subscribe]] [cljs.reader :refer [read-string]] [instaparse.core :as insta] )) (def debug false) (enable-console-print!) (def printing (atom false)) (defn stop-default-action[event] (.preventDefault event)) (declare draw-item) ;; need forward reference since it is recursive (defn css-class-name-for[x] (string/replace (name x) "-" "_") ) (def class-for-octave {nil "octave0" 0 "octave0" -1 "lower_octave_1" -2 "lower_octave_2" -3 "lower_octave_3" -4 "lower_octave_4" 1 "upper_octave_1 upper_octave_indicator" 2 "upper_octave_2 upper_octave_indicator" 3 "upper_octave_3 upper_octave_indicator" 4 "upper_octave_4 upper_octave_indicator" 5 "upper_octave_5 upper_octave_indicator" } ) (def class-for-ornament-octave {nil "octave0" 0 "octave0" -1 "lower_octave_1" -2 "lower_octave_2" -3 "lower_octave_3" -4 "lower_octave_4" 1 "upper_octave_1" 2 "upper_octave_2" 3 "upper_octave_3" 4 "upper_octave_4" 5 "upper_octave_5" } ) . The Unicode character ♭ ( U+266D ) is the flat sign . Its HTML entity is & # 9837 ; . In , the sharp symbol ( ♯ ) is at code point U+266F. Its HTML entity is & # 9839 ; . The symbol for double sharp ( double sharp ) is at U+1D12A ( so & # 119082 ;) . These characters may not display correctly in all fonts . (def bullet "&bull;") (def sharp-symbol "#") (def sharp-symbol-utf8 "&#9839;") (def flat-symbol "b") (def flat-symbol-utf8 "&#9837;") (def alteration->utf8 { "b" flat-symbol-utf8 "#" sharp-symbol-utf8 }) TODO : need to put fallback mechanism if the UTF symbols are not supported ;; old versions added data-fallback-if-no-utf8-chars="|" for example for barline ;; to the html. Then a small bit of javascript can adjust things (dom_fixer) in the case of a statically generated page. ;; For dynamic pages, set the value appropriately. Perhaps a lookup table ;; utf->simple { flat-symbol "b" bar-line "|" } etc. ;; app-state should have :supports-utf8-chars (def lookup-sargam { "Cb" ["S", flat-symbol] "C" ["S"] "C#" ["S", sharp-symbol] "Db" ["r"] "D" ["R"] "D#" ["R", sharp-symbol] "Eb" ["g"] "E" ["G"] "E#" ["G", sharp-symbol] "F" ["m"] "F#" ["M"] "Gb" ["P", flat-symbol] "G" ["P"] "G#" ["P", sharp-symbol] "Ab" ["d"] "A" ["D"] "A#" ["D", sharp-symbol] "Bb" ["n"] "B" ["N"] "B#" ["N", sharp-symbol] }) (def lookup-number { "Cb" ["1", flat-symbol] "C" ["1"] "C#" ["1", sharp-symbol] "Db" ["2", flat-symbol] "D" ["2"] "D#" ["2", sharp-symbol] "Eb" ["3", flat-symbol] "E" ["3"] "E#" ["3", sharp-symbol] "F" ["4"] "F#" ["4", sharp-symbol] "Gb" ["5", flat-symbol] "G" ["5"] "G#" ["5", sharp-symbol] "Ab" ["6", flat-symbol] "A" ["6"] "A#" ["6", sharp-symbol] "Bb" ["7", flat-symbol] "B" ["7"] "B#" ["7", sharp-symbol] }) (def lookup-hindi (let [s "&#2360;" ;; "र" r "&#2352;" ;; र g "&#2327;";; "ग़" m "&#2350;" ;; "म" p "&#2346;" ;; "प" d "&#2343" ;;"ध" " ऩ " tick "'"] { "Cb" [s flat-symbol] "C" [s] "C#"[s sharp-symbol] "Db" [r] "D" [r] "D#" [r sharp-symbol] "Eb" [g] "E" [g] "E#" [g sharp-symbol] "F" [m] "F#" [m tick] "Gb" [p flat-symbol] "G" [p] "G#" [p sharp-symbol] "Ab" [d] "A" [d] "A#" [d sharp-symbol] "Bb" [n] "B" [n] "B#" [n sharp-symbol] })) (def lookup-ABC { "Cb" ["C", flat-symbol] "C" ["C"] "C#" ["C", sharp-symbol] "Db" ["D", flat-symbol] "D" ["D"] "D#" ["D", sharp-symbol] "Eb" ["E", flat-symbol] "E" ["E"] "E#" ["E", sharp-symbol] "F" ["F"] "F#" ["F", sharp-symbol] "Gb" ["G", flat-symbol] "G" ["G"] "G#" ["G", sharp-symbol] "Ab" ["A", flat-symbol] "A" ["A"] "A#" ["A", sharp-symbol] "Bb" ["B", flat-symbol] "B" ["B"] "B#" ["B", sharp-symbol] }) (def lookup-DoReMi { "Cb" ["D", flat-symbol] "C" ["D"] "C#" ["D", sharp-symbol] "Db" ["R", flat-symbol] "D" ["R"] "D#" ["R", sharp-symbol] "Eb" ["M", flat-symbol] "E" ["M"] "E#" ["M", sharp-symbol] "F" ["F"] "F#" ["F", sharp-symbol] "Gb" ["S", flat-symbol] "G" ["S"] "G#" ["S", sharp-symbol] "Ab" ["L", flat-symbol] "A" ["L"] "A#" ["L", sharp-symbol] "Bb" ["T", flat-symbol] "B" ["T"] "B#" ["T", sharp-symbol] }) ;; not sure if using multi-methods is better than a case statement (defmulti deconstruct-pitch-string-by-kind (fn [pitch kind] kind)) (defmethod deconstruct-pitch-string-by-kind :sargam-composition [pitch kind] (get lookup-sargam pitch)) (defmethod deconstruct-pitch-string-by-kind :number-composition [pitch kind] (get lookup-number pitch)) (defmethod deconstruct-pitch-string-by-kind :abc-composition [pitch kind] (get lookup-ABC pitch)) (defmethod deconstruct-pitch-string-by-kind :doremi-composition [pitch kind] (get lookup-DoReMi pitch)) (defmethod deconstruct-pitch-string-by-kind :hindi-composition [pitch kind] (get lookup-hindi pitch)) (defmethod deconstruct-pitch-string-by-kind :default [pitch _] (get lookup-sargam pitch)) (defn deconstruct-pitch-string[pitch kind utf-supported] (let [ [p alteration] (deconstruct-pitch-string-by-kind pitch kind)] [p (if utf-supported (get alteration->utf8 alteration alteration) alteration) ] )) (def mordent-entity "&#x1D19D&#x1D19D") (def lookup-barline-utf8 { :single-barline "&#x1d100" :double-barline "&#x1d101" :left-repeat "&#x1d106" :mordent "&#x1D19D&#x1D19D" :right-repeat "&#x1d107" :final-barline "&#x1d102" :reverse-final-barline "&#x1d103" } ) (def lookup-barline { :single-barline "|" :double-barline "||" :left-repeat "|:" :mordent "~" :right-repeat ":|" :final-barline "||" :reverse-final-barline ":||" } ) (defn redraw-lilypond-button[] [:button.btn.btn-primary { :title "Display Lilypond Source", :name "redraw_lilypond_source" :on-click (fn [e] (stop-default-action e) (dispatch [:redraw-lilypond-source]) ;; include dom-id as param ?? ) } "Lilypond Source" ] ) (defn display-lilypond-source [] (let [ lilypond-source (subscribe [:lilypond-source]) ] [:div.form-group.hidden-print { ;; :class (if @error "has-error" "") } [redraw-lilypond-button] [:label.control-label {:for "lilypond_source" } "Lilypond Source:"] [:textarea#lilypond_source.form-control {:rows "3" :spellCheck false :readOnly true :value (print-str @lilypond-source) } ]])) (defn display-parse-to-user-box [] (let [error (subscribe [:error]) composition (subscribe [:composition]) ] [:div.form-group.hidden-print { :class (if @error "has-error" "") } [:label.control-label {:for "parse-results" } "Parse Results:"] [:textarea#parse-results.form-control {:rows "3" :spellCheck false :readOnly true :value (if @error (print-str @error) (print-str @composition)) } ]])) (def text-area-placeholder "Select notation system from \"Enter notation as\" select box. Enter letter music notation as follows: For number notation use: | 1234 567- | For abc notation use: | CDEF F#GABC | For sargam use: | SrRg GmMP dDnN ---- | For devanagri/bhatkande use: स र ग़ म म' प ध ऩ For doremi use: drmf slt- Use dots above/below notes for octave indicators." ) (defn get-selection[dom-node] ;; TODO: goog equivalent ??? {:start (.-selectionStart dom-node) :end (.-selectionEnd dom-node) }) (defn my-contains?[x y] (not= -1 (.indexOf x y)) ) (defn within-sargam-line?[txt idx] TODO : Create function ( defn get - current - line[txt idx ] ) (comment "within-sargam-line?, txt,idx,class(text)" txt idx ) (let [ left (.substring txt 0 idx) right (.substring txt idx) x (.indexOf right "\n") index-of-right-newline (if (not= -1 x) (+ idx x) (.-length txt) ) y (.lastIndexOf left "\n") index-of-left-newline (if (not= -1 y) (inc y) 0) _ (comment "index-of-left-newline=" index-of-left-newline) line (.substring txt index-of-left-newline index-of-right-newline) _ (comment "line is" line) ] (comment "left right index-of-right-newline" left right index-of-right-newline) (comment "line is" line) (my-contains? line "|"))) (defn on-key-press-new[event my-key-map composition-kind] ;; event is a dom event (when debug (println "entering on-key-press, my-key-map=" my-key-map)) (if (not= :sargam-composition composition-kind) true (let [ target (.-target event) key-code (.-keyCode event) ctrl-key? (or (.-ctrlKey event) (.-altKey event) (.-metaKey event)) from-char-code-fn (.-fromCharCode js/String) ch (from-char-code-fn key-code) new-char (if-not ctrl-key? (get my-key-map ch )) caret-pos (.-selectionStart target) text-area-text (.-value target) selection (get-selection target) my-within-sargam-line (within-sargam-line? text-area-text (:start selection)) ] nativeEvent looks like { which : 189 , keyCode : 189 , charCode : 0 , repeat : false , : false … } (if (and my-within-sargam-line new-char) (do (when debug "in do********") (set! (.-value target) (str (.substring text-area-text 0 caret-pos) new-char (.substring text-area-text caret-pos))) (set! (.-selectionStart target) (inc (:start selection))) (set! (.-selectionEnd target) (inc (:end selection))) (dispatch [:set-doremi-text (.-value target)]) false ) (do (dispatch [:set-doremi-text (.-value target)]) true) )) )) (defn parse-button[] [:button.btn.btn-primary { :title "Redraw Letter Notation", :name "redraw_letter_notation" :on-click (fn [e] (stop-default-action e) (dispatch [:redraw-letter-notation]) ;; include dom-id as param ?? ) } "Redraw" ] ) ;; "form-3" component see ;; -frame/wiki/Creating-Reagent-Components (defn entry-area-input[] ;; textarea input keypresses is not handled by reagent (let [ dom-id "area2" online (subscribe [:online]) composition-kind (subscribe [:composition-kind]) key-map (subscribe [:key-map]) ] (reagent.core/create-class {:component-did-mount (fn entry-area-input-did-mount[this] (dispatch [:start-parse-timer dom-id]) (dispatch [:set-current-entry-area dom-id]) (set! (.-onkeypress (by-id dom-id) ) (fn my-on-key-press[event] (when debug (println "my-on-key-press")) (on-key-press-new event @key-map @composition-kind )))) :display-name "entry-area-input" :reagent-render (fn [] ;; remember to repeat parameters [:div.form-group.hidden-print [:label {:for "entryArea"} "Enter Letter Notation Source:"] (if (not @online) [:span.offline "You are working offline. Features such as generating staff notation are disabled" ] ) [:textarea.entryArea.form-control { :autofocus true :placeholder text-area-placeholder :id "area2" :name "src", :spellCheck false ;; :onKeyPress - for handling key strokes see above :on-change (fn on-change-text-area[event] (dispatch [:set-doremi-text (-> event .-target .-value)])) } ]] )}))) (defn draw-children[items] (doall (map-indexed (fn notes-line-aux[idx item] (draw-item item idx)) items))) (defn staff-notation[] (let [staff-notation-url (subscribe [:staff-notation-url])] [:img#staff_notation.hidden-print {:class (if @printing "printing" "") :src @staff-notation-url }])) (defn html-rendered-composition[] (let [composition (subscribe [:composition])] (if (not @composition) [:div#doremiContent.composition.doremiContent ] ;; else [:div#doremiContent.composition.doremiContent {:class (if @printing "printing" "")} (draw-children (rest @composition))] ))) (defn attribute-section[{item :item}] nil ) (defn notes-line [{item :item}] (log "notes-line, item is") (log item) (assert (is? :notes-line item)) [:div.stave.sargam_line (draw-children (rest item))]) TODO ;;; componentDidMount: function () { window.dom_fixes($(this.getDOMNode())); }, ;; componentDidUpdate: function () { window.dom_fixes($(this.getDOMNode())); }, ;; var items = rest(item); ;; (defn user-entry[] (.-value (dom/getElement "area2")) ) (def composition-wrapper (with-meta html-rendered-composition {:component-did-mount (fn[this] (log "component-did-mount composition to call dom_fixes") (dom-fixes this) ) :component-did-update (fn[this] (log "component-did-update composition-about to call dom_fixes") (dom-fixes this) ) } )) (defn composition-box[] [:div [:ul.nav.nav-justified [:li [:label.hidden-print {:for "entryArea"} "Rendered Letter Notation: "] ] [:li [parse-button] ] ] [composition-wrapper] ] ) (defn ornament-pitch[{item :item render-as :render-as}] (let [utf-supported (subscribe [:supports-utf8-characters])] ;; item looks like: ;; ;; ["ornament",["ornament-pitch","B",["octave",1]] ;; [:span.ornament_item.upper_octave_1 "g"] (log "entering ornament-pitch") (log item) (let [ deconstructed-pitch ;; C#,sargam -> ["S" "#"] (deconstruct-pitch-string (second item) render-as @utf-supported ) octave (some #(when (and (vector %) (= :octave (first %))) (second %)) (rest item)) alteration-string (second deconstructed-pitch) pitch-src (join deconstructed-pitch) octave_class (get class-for-ornament-octave octave) ] [:span.ornament_item {:class octave_class :dangerouslySetInnerHTML { :__html pitch-src } } ] ))) (defn ornament[{item :item}] ;; should generate something like this: (comment [:span.upper_attribute.ornament.placement_after [:span.ornament_item.upper_octave_1 "g"]]) (let [render-as (subscribe [:render-as]) items (rest item) filtered (filter #(and (vector? %) (= :ornament-pitch (first %))) items) _ (log "filtered " filtered) placement (last item) placement-class (str "placement_" (name placement)) ] [:span.upper_attribute.ornament {:class placement-class} (doall (map-indexed (fn notes-line-aux[idx item] [ornament-pitch {:item item :render-as @render-as :key idx } ]) filtered)) ] )) (defn mordent[{item :item}] (let [utf-supported (subscribe [:supports-utf8-characters])] [:span.mordent {:dangerouslySetInnerHTML { :__html (if @utf-supported mordent-entity "~") } }]) ) (defn ending[{item :item}] [:span.ending (second item) ]) (defn line-number[{item :item}] [:span.note_wrapper [:span.note.line_number (str (second item) ")") ] ]) (defn line-item [{src :src kind :kind item :item}] (log "entering line-item, item") (log item) ;; className = item[0].replace(/-/g, '_'); ;;src = "S" ;;; this.props.src; [:span {:class "note_wrapper" } [:span.note {:class kind} ;; TODO: should use css-class-name-for ??? src]]) (defn barline[{src :src item :item}] (let [barline-name (first (second item)) utf-supported (subscribe [:supports-utf8-characters]) ] (log "barline-name is" barline-name) [:span.note_wrapper [:span.note.barline {:dangerouslySetInnerHTML { :__html (if @utf-supported (get lookup-barline-utf8 (keyword (first (second item)))) (get lookup-barline (keyword (first (second item)))) ) } } ]])) (defn beat[{item :item}] (log "entering beat") (assert (is? :beat item)) (log "beat, item is") (log item) (let [beat-count (reduce (fn count-beats[accum cur] (log "cur is" cur) (if (and (vector? cur) (get #{:pitch :dash} (first cur))) (inc accum) accum)) 0 (rest item)) _ (log "beat-count is" beat-count) looped (if (> beat-count 1) "looped" "") ] TODO [:span.beat {:class looped} (draw-children (rest item)) ])) (comment TODO : Add underline for hindi pitches that need it . Old code : ;;;; if ((this.props.kind === "hindi-composition") && ;;;; (needs_underline[second(pitch)]) ;;;; ) { ;;;; kommalIndicator = span({ key : 99 , ;;;; className: "kommalIndicator" ;;;; }, "_"); ;;;; } ) (defn pitch-name[{item :item}] ;; (assert (is? :pitch-name item)) (when false (println "pitch-name, item is") (println item) (println (second item))) [:span.note.pitch {:dangerouslySetInnerHTML { :__html (second item) } } ] ) (defn pitch-alteration[{item :item}] (log "pitch-alteration") (assert (is? :pitch-alteration item)) [:span.note.pitch.alteration {:dangerouslySetInnerHTML { :__html (second item) } } ] ) (defn begin-slur-id[{item :item}] [:span.slur {:id (second item)}] ) (defn needs-kommal-indicator?[normalized-pitch kind] (log "entering needs-kommal-indicator," normalized-pitch kind) (assert (string? normalized-pitch)) (assert (keyword? kind)) (and (= kind :hindi-composition) (#{"Db" "Eb" "Ab" "Bb"} normalized-pitch))) (defn pitch[{item :item render-as :render-as}] (let [utf-supported (subscribe [:supports-utf8-characters])] (log "entering pitch, item=" item) ;; gnarly code here. (log "pitch, (first (last item))=" (first (last item))) ;; In the following case ;; ["pitch","C",["begin-slur"],["octave",0],["begin-slur-id",0]] ;; if there is "begin-slur-id, add ;; <span class="slur" id="0"></span> ;; before the note span. ;; ;; for end slur, add data-begin-slur-id to the note-wrapper ;; confusing ;; ;; ;;; ["pitch","C#",["octave",1],["syl","syl"]] ;;; ["pitch","E",["end-slur"],["octave",0],["end-slur-id",0]] (log "entring pitch, item is" item) ;; (assert (is? :pitch item)) (log item) ;; need to sort attributes in order: ;; ornament octave syl note alteration ;; TODO: refactor. Hard to understand. (let [ ;; Looks like ["end-slur-id",0] begin-slur-id (some (fn[x] (if (and (vector? x) (= :begin-slur-id (first x))) x)) item) end-slur-id (some (fn[x] (if (and (vector? x) (= :end-slur-id (first x))) x)) item) h (if end-slur-id {:data-begin-slur-id (second end-slur-id) } {} :class (css-class-name-for (first item)) ) kommal-indicator (when (needs-kommal-indicator? (second item) @render-as) [:kommal-indicator]) deconstructed-pitch ;; C#,sargam -> ["S" "#"] (deconstruct-pitch-string (second item) @render-as @utf-supported ) sort-table {:ornament 1 :octave 2 :syl 3 :kommal-indicator 4 :begin-slur-id 5 :slur 6 :pitch-name 7 :pitch 8 :pitch-alteration 9} item1 (into[] (cons [:pitch-name (first deconstructed-pitch)] (rest (rest item)))) item2 (if begin-slur-id (into[] (cons [:slur (second begin-slur-id)] item1)) item1) alteration-string (second deconstructed-pitch) my-pitch-alteration (when alteration-string [:pitch-alteration alteration-string]) item4 (remove nil? (into[] (cons my-pitch-alteration item2))) item5 (remove (fn[x] (get #{:end-slur-id :slur} (first x))) item4) item5a (remove nil? (into [] (cons kommal-indicator item5))) item6 (sort-by #(get sort-table (first %)) item5a) ] (log "item6 is") ;;[["pitch-name","D#"],["octave",1],["syl","syl"]] (log item6) [:span.note_wrapper h ;; This indicates slur is ending and gives the id of where the slur starts. NOTE. (draw-children item6) ] ))) (defn lyrics-section [{item :item}] ;; ["lyrics-section",["lyrics-line","first","line","of","ly-","rics"],["lyrics-line","se-","cond","line","of","ly-","rics"]] ;; assert(isA("lyrics-section", lyricsSection)) return rest(x ) ( " " ) ; ;; (let [line-strings (map (fn[x] (join " " (rest x))) (rest item)) s (join "\n" line-strings) ] [:div.stave.lyrics_section.unhyphenated {:title "Lyrics Section"} s])) (defn stave[{item :item}] (log "entering stave") (log item) ;; (assert (is? :stave item)) [notes-line {:item (second item)}] ) (defn measure[{item :item}] (assert (is? :measure item)) [:span {:class "measure"} (draw-children (rest item))]) (defn tala[{item :item}] (assert (is? :tala item)) [:span.tala (second item)] ) (defn chord[{item :item}] (assert (is? :chord item)) [:span.chord (second item)] ) (def EMPTY-SYLLABLE "\" \"") ;; " " which quotes ;; EMPTY_SYLLABLE is for the benefit of lilypond. (defn syl[{item :item}] (assert (is? :syl item)) (log "in syl, item is" item) (log "syl- item is") (log item) (when (not= (second item) EMPTY-SYLLABLE) [:span.syl (second item)] )) (defn abs [n] (max n (- n))) (defn octave[{item :item}] ;; TODO: support upper-upper and lower-lower (log "octave- item is") (log item) (assert (is? :octave item)) (let [octave-num (second item)] (if (or (nil? octave-num) (zero? octave-num)) nil ;; else [:span {:class (class-for-octave (second item)) :dangerouslySetInnerHTML { :__html (clojure.string/join (repeat (abs octave-num) bullet)) } } ] ))) (defn kommal-indicator[{item :item}] (assert (is? :kommal-indicator item)) [:span.kommalIndicator "_"] ) ;; kommalIndicator = span({ key : 99 , ;; className: "kommalIndicator" ;; }, "_"); (defn draw-item[item idx] (let [my-key (first item) render-as (subscribe [:render-as]) ] (cond (= my-key :begin-slur) nil (= my-key :end-slur) nil (= my-key :ornament) [ornament {:key idx :item item}] (= my-key :mordent) [mordent {:key idx :item item}] (= my-key :ending) [ending {:key idx :item item}] (= my-key :barline) [barline {:key idx :item item}] (= my-key :lyrics-section) [lyrics-section {:key idx :item item}] (= my-key :tala) [tala {:key idx :item item}] (= my-key :chord) [chord {:key idx :item item}] (= my-key :kommal-indicator) [kommal-indicator {:key idx :item item}] (= my-key :syl) [syl {:key idx :item item}] (= my-key :beat) [beat {:key idx :item item}] (= my-key :stave) [stave {:key idx :item item}] (= my-key :measure) [measure {:key idx :item item}] (= my-key :end-slur-id) nil (= my-key :begin-slur-id) [begin-slur-id {:key idx :item item}] (= my-key :attribute-section) [attribute-section {:key idx :item item}] (= my-key :pitch-alteration) [pitch-alteration {:key idx :item item}] (= my-key :ornament-pitch) (do (println "error-don't use-my-key= :ornament-pitch") [ ornament - pitch { : key idx : item item : render - as @render - as } ] ) (= my-key :pitch) [pitch {:key idx :item item :render-as render-as }] (= my-key "syl") [syl {:key idx :item item}] (= my-key :octave) [octave {:key idx :item item}] (= my-key :pitch-name) [pitch-name {:key idx :item item}] (= my-key :notes-line) [notes-line {:key idx :item item}] (= my-key :line-number) [line-number {:key idx :item item}] (= my-key :dash) [line-item {:src "-" :key idx :item item}] true [:span {:key idx :item item} (str "todo-draw-item" (.stringify js/JSON (clj->js item))) ] ))) (defn select-notation-box[kind] (let [composition-kind (subscribe [:composition-kind])] selectNotationBox [:label {:for "selectNotation"} "Enter Notation as: "] [:select#selectNotation.selectNotation.form-control {:value @composition-kind :on-change (fn on-change-select-notation[x] (let [kind-str (-> x .-target .-value) my-kind (if (= "" kind-str) nil ;; else (keyword kind-str)) ] (dispatch [:set-composition-kind my-kind]) )) } [:option] [:option {:value :abc-composition} "ABC"] [:option {:value :doremi-composition} "doremi"] [:option {:value :hindi-composition} "hindi( स र ग़ म म' प ध ऩ )"] [:option {:value :number-composition} "number"] [:option {:value :sargam-composition} "sargam"]]] )) (defn render-as-box[] (let [render-as (subscribe [:render-as])] selectNotationBox ;;[:div.RenderAsBox [:label { :for "renderAs"} "Render as:"] [:select#renderAs.renderAs.form-control {:value @render-as :on-change (fn on-change-render-as[x] (let [value (-> x .-target .-value)] (when (not= value "") (dispatch [:set-render-as (keyword value)])))) } [:option {:value nil}] [:option {:value :abc-composition} "ABC"] [:option {:value :doremi-composition} "doremi"] [:option {:value :hindi-composition} "hindi( स र ग़ म म' प ध ऩ )"] [:option {:value :number-composition} "number"] [:option {:value :sargam-composition} "sargam"]]] )) (defn generate-staff-notation-button[] (let [ ajax-is-running (subscribe [:ajax-is-running]) parse-xhr-is-running (subscribe [:parse-xhr-is-running]) parser (subscribe [:parser]) online (subscribe [:online]) ] [:button.btn.btn-primary { :title "Redraws rendered letter notation and Generates staff notation and MIDI file using Lilypond", :name "generateStaffNotation" :disabled (or ;;;@parse-xhr-is-running (not @online) @ajax-is-running) :on-click (fn [e] (stop-default-action e) (dispatch [:generate-staff-notation])) } (cond ;; @parse-xhr-is-running " Generate Staff Notation and audio " @ajax-is-running "Redrawing..." true "Generate Staff Notation and audio" ) ] )) (defn audio-div[mp3-url] [:audio#audio { :controls "controls" :preload "auto" :src mp3-url } ] ) (defn key-map[] ;; for debugging. Not currently used (let [key-map (subscribe [:key-map]) environment (subscribe [:environment]) ] (when (= :development @environment) [:div (print-str @key-map) ] ))) (defn links[] (let [my-links (subscribe [:links]) environment (subscribe [:environment]) ] selectNotationBox ;;[:div.RenderAsBox [:select.form-control { :title "Opens a new window" :value "" :on-change (fn[x] (let [value (-> x .-target .-value)] (cond (= value "") nil (= value "print-grammar") (dispatch [:print-grammar]) true (dispatch [:open-link value])))) } [:option {:value ""} "Links"] (doall (map-indexed (fn[idx z] (let [k (first z) v (second z)] [:option {:key idx :value v} (string/replace (name k) #"-url$" "")] )) @my-links )) [:option {:value "print-grammar"} "Print grammar to console"] [:option {:value "-script/#readme"} "Help (github README)"] ]])) (defn utf-support-div[] (let [] (reagent.core/create-class {:component-did-mount (fn utf-support-div-did-mount[this] (dispatch [:check-utf-support (reagent/dom-node this) ]) ) :reagent-render (fn [] ;; remember to repeat parameters [:div.testing_utf_support [:span#utf_left_repeat.note.testing_utf_support {:style {:display "none"} } "𝄆"] [:span#utf_single_barline.note.testing_utf_support {:style {:display "none"} } "𝄀"] ] ) } ))) (defn controls[] (let [mp3-url (subscribe [:mp3-url]) composition-kind (subscribe [:composition-kind]) ] [:form.form-inline [select-notation-box @composition-kind] [render-as-box] [generate-staff-notation-button] [links] (if @mp3-url [audio-div @mp3-url]) ] )) (defn doremi-box[] [:div.doremiBox [controls] [entry-area-input] [composition-box] [staff-notation] [display-parse-to-user-box] [display-lilypond-source] [utf-support-div] ] )
null
https://raw.githubusercontent.com/rothfield/doremi-script/7141720e14bb0dbac344b55caab47c4f046635a5/src/doremi_script/views.cljs
clojure
listen seconds]] [doremi-script.doremi_core :as doremi_core :refer [doremi-text->collapsed-parse-tree]] need forward reference since it is recursive . . The symbol for double sharp ( double sharp ) is at U+1D12A ( so & # 119082 ;) . These characters may not display correctly in all fonts . old versions added data-fallback-if-no-utf8-chars="|" for example for barline to the html. Then a small bit of javascript can adjust things (dom_fixer) in the case of a statically generated page. For dynamic pages, set the value appropriately. Perhaps a lookup table utf->simple { flat-symbol "b" bar-line "|" } etc. app-state should have :supports-utf8-chars "र" र "ग़" "म" "प" "ध" not sure if using multi-methods is better than a case statement include dom-id as param ?? :class (if @error "has-error" "") TODO: goog equivalent ??? event is a dom event include dom-id as param ?? "form-3" component see -frame/wiki/Creating-Reagent-Components textarea input keypresses is not handled by reagent remember to repeat parameters :onKeyPress - for handling key strokes see above else componentDidMount: function () { window.dom_fixes($(this.getDOMNode())); }, componentDidUpdate: function () { window.dom_fixes($(this.getDOMNode())); }, var items = rest(item); item looks like: ;; ["ornament",["ornament-pitch","B",["octave",1]] [:span.ornament_item.upper_octave_1 "g"] C#,sargam -> ["S" "#"] should generate something like this: className = item[0].replace(/-/g, '_'); src = "S" ;;; this.props.src; TODO: should use css-class-name-for ??? if ((this.props.kind === "hindi-composition") && (needs_underline[second(pitch)]) ) { kommalIndicator = span({ className: "kommalIndicator" }, "_"); } (assert (is? :pitch-name item)) gnarly code here. In the following case ["pitch","C",["begin-slur"],["octave",0],["begin-slur-id",0]] if there is "begin-slur-id, add <span class="slur" id="0"></span> before the note span. for end slur, add data-begin-slur-id to the note-wrapper confusing ["pitch","C#",["octave",1],["syl","syl"]] ["pitch","E",["end-slur"],["octave",0],["end-slur-id",0]] (assert (is? :pitch item)) need to sort attributes in order: ornament octave syl note alteration TODO: refactor. Hard to understand. Looks like ["end-slur-id",0] C#,sargam -> ["S" "#"] [["pitch-name","D#"],["octave",1],["syl","syl"]] This indicates slur is ending and gives the id of where the slur starts. NOTE. ["lyrics-section",["lyrics-line","first","line","of","ly-","rics"],["lyrics-line","se-","cond","line","of","ly-","rics"]] assert(isA("lyrics-section", lyricsSection)) (assert (is? :stave item)) " " which quotes EMPTY_SYLLABLE is for the benefit of lilypond. TODO: support upper-upper and lower-lower else kommalIndicator = span({ className: "kommalIndicator" }, "_"); else [:div.RenderAsBox @parse-xhr-is-running @parse-xhr-is-running for debugging. Not currently used [:div.RenderAsBox remember to repeat parameters
(ns doremi-script.views (:require [doremi-script.utils :refer [get-attributes keywordize-vector log is?] ] [doremi-script.dom-fixes :refer [dom-fixes]] [goog.dom :as dom] [goog.Uri] [goog.events :as events] [clojure.string :as string :refer [join]] [dommy.core :as dommy :refer-macros [sel sel1]] [cljs.core.async :refer [<! chan close! timeout put!]] [reagent.core :as reagent] [re-frame.core :refer [register-handler path register-sub dispatch dispatch-sync subscribe]] [cljs.reader :refer [read-string]] [instaparse.core :as insta] )) (def debug false) (enable-console-print!) (def printing (atom false)) (defn stop-default-action[event] (.preventDefault event)) (defn css-class-name-for[x] (string/replace (name x) "-" "_") ) (def class-for-octave {nil "octave0" 0 "octave0" -1 "lower_octave_1" -2 "lower_octave_2" -3 "lower_octave_3" -4 "lower_octave_4" 1 "upper_octave_1 upper_octave_indicator" 2 "upper_octave_2 upper_octave_indicator" 3 "upper_octave_3 upper_octave_indicator" 4 "upper_octave_4 upper_octave_indicator" 5 "upper_octave_5 upper_octave_indicator" } ) (def class-for-ornament-octave {nil "octave0" 0 "octave0" -1 "lower_octave_1" -2 "lower_octave_2" -3 "lower_octave_3" -4 "lower_octave_4" 1 "upper_octave_1" 2 "upper_octave_2" 3 "upper_octave_3" 4 "upper_octave_4" 5 "upper_octave_5" } ) (def bullet "&bull;") (def sharp-symbol "#") (def sharp-symbol-utf8 "&#9839;") (def flat-symbol "b") (def flat-symbol-utf8 "&#9837;") (def alteration->utf8 { "b" flat-symbol-utf8 "#" sharp-symbol-utf8 }) TODO : need to put fallback mechanism if the UTF symbols are not supported (def lookup-sargam { "Cb" ["S", flat-symbol] "C" ["S"] "C#" ["S", sharp-symbol] "Db" ["r"] "D" ["R"] "D#" ["R", sharp-symbol] "Eb" ["g"] "E" ["G"] "E#" ["G", sharp-symbol] "F" ["m"] "F#" ["M"] "Gb" ["P", flat-symbol] "G" ["P"] "G#" ["P", sharp-symbol] "Ab" ["d"] "A" ["D"] "A#" ["D", sharp-symbol] "Bb" ["n"] "B" ["N"] "B#" ["N", sharp-symbol] }) (def lookup-number { "Cb" ["1", flat-symbol] "C" ["1"] "C#" ["1", sharp-symbol] "Db" ["2", flat-symbol] "D" ["2"] "D#" ["2", sharp-symbol] "Eb" ["3", flat-symbol] "E" ["3"] "E#" ["3", sharp-symbol] "F" ["4"] "F#" ["4", sharp-symbol] "Gb" ["5", flat-symbol] "G" ["5"] "G#" ["5", sharp-symbol] "Ab" ["6", flat-symbol] "A" ["6"] "A#" ["6", sharp-symbol] "Bb" ["7", flat-symbol] "B" ["7"] "B#" ["7", sharp-symbol] }) (def lookup-hindi " ऩ " tick "'"] { "Cb" [s flat-symbol] "C" [s] "C#"[s sharp-symbol] "Db" [r] "D" [r] "D#" [r sharp-symbol] "Eb" [g] "E" [g] "E#" [g sharp-symbol] "F" [m] "F#" [m tick] "Gb" [p flat-symbol] "G" [p] "G#" [p sharp-symbol] "Ab" [d] "A" [d] "A#" [d sharp-symbol] "Bb" [n] "B" [n] "B#" [n sharp-symbol] })) (def lookup-ABC { "Cb" ["C", flat-symbol] "C" ["C"] "C#" ["C", sharp-symbol] "Db" ["D", flat-symbol] "D" ["D"] "D#" ["D", sharp-symbol] "Eb" ["E", flat-symbol] "E" ["E"] "E#" ["E", sharp-symbol] "F" ["F"] "F#" ["F", sharp-symbol] "Gb" ["G", flat-symbol] "G" ["G"] "G#" ["G", sharp-symbol] "Ab" ["A", flat-symbol] "A" ["A"] "A#" ["A", sharp-symbol] "Bb" ["B", flat-symbol] "B" ["B"] "B#" ["B", sharp-symbol] }) (def lookup-DoReMi { "Cb" ["D", flat-symbol] "C" ["D"] "C#" ["D", sharp-symbol] "Db" ["R", flat-symbol] "D" ["R"] "D#" ["R", sharp-symbol] "Eb" ["M", flat-symbol] "E" ["M"] "E#" ["M", sharp-symbol] "F" ["F"] "F#" ["F", sharp-symbol] "Gb" ["S", flat-symbol] "G" ["S"] "G#" ["S", sharp-symbol] "Ab" ["L", flat-symbol] "A" ["L"] "A#" ["L", sharp-symbol] "Bb" ["T", flat-symbol] "B" ["T"] "B#" ["T", sharp-symbol] }) (defmulti deconstruct-pitch-string-by-kind (fn [pitch kind] kind)) (defmethod deconstruct-pitch-string-by-kind :sargam-composition [pitch kind] (get lookup-sargam pitch)) (defmethod deconstruct-pitch-string-by-kind :number-composition [pitch kind] (get lookup-number pitch)) (defmethod deconstruct-pitch-string-by-kind :abc-composition [pitch kind] (get lookup-ABC pitch)) (defmethod deconstruct-pitch-string-by-kind :doremi-composition [pitch kind] (get lookup-DoReMi pitch)) (defmethod deconstruct-pitch-string-by-kind :hindi-composition [pitch kind] (get lookup-hindi pitch)) (defmethod deconstruct-pitch-string-by-kind :default [pitch _] (get lookup-sargam pitch)) (defn deconstruct-pitch-string[pitch kind utf-supported] (let [ [p alteration] (deconstruct-pitch-string-by-kind pitch kind)] [p (if utf-supported (get alteration->utf8 alteration alteration) alteration) ] )) (def mordent-entity "&#x1D19D&#x1D19D") (def lookup-barline-utf8 { :single-barline "&#x1d100" :double-barline "&#x1d101" :left-repeat "&#x1d106" :mordent "&#x1D19D&#x1D19D" :right-repeat "&#x1d107" :final-barline "&#x1d102" :reverse-final-barline "&#x1d103" } ) (def lookup-barline { :single-barline "|" :double-barline "||" :left-repeat "|:" :mordent "~" :right-repeat ":|" :final-barline "||" :reverse-final-barline ":||" } ) (defn redraw-lilypond-button[] [:button.btn.btn-primary { :title "Display Lilypond Source", :name "redraw_lilypond_source" :on-click (fn [e] (stop-default-action e) ) } "Lilypond Source" ] ) (defn display-lilypond-source [] (let [ lilypond-source (subscribe [:lilypond-source]) ] [:div.form-group.hidden-print { } [redraw-lilypond-button] [:label.control-label {:for "lilypond_source" } "Lilypond Source:"] [:textarea#lilypond_source.form-control {:rows "3" :spellCheck false :readOnly true :value (print-str @lilypond-source) } ]])) (defn display-parse-to-user-box [] (let [error (subscribe [:error]) composition (subscribe [:composition]) ] [:div.form-group.hidden-print { :class (if @error "has-error" "") } [:label.control-label {:for "parse-results" } "Parse Results:"] [:textarea#parse-results.form-control {:rows "3" :spellCheck false :readOnly true :value (if @error (print-str @error) (print-str @composition)) } ]])) (def text-area-placeholder "Select notation system from \"Enter notation as\" select box. Enter letter music notation as follows: For number notation use: | 1234 567- | For abc notation use: | CDEF F#GABC | For sargam use: | SrRg GmMP dDnN ---- | For devanagri/bhatkande use: स र ग़ म म' प ध ऩ For doremi use: drmf slt- Use dots above/below notes for octave indicators." ) (defn get-selection[dom-node] {:start (.-selectionStart dom-node) :end (.-selectionEnd dom-node) }) (defn my-contains?[x y] (not= -1 (.indexOf x y)) ) (defn within-sargam-line?[txt idx] TODO : Create function ( defn get - current - line[txt idx ] ) (comment "within-sargam-line?, txt,idx,class(text)" txt idx ) (let [ left (.substring txt 0 idx) right (.substring txt idx) x (.indexOf right "\n") index-of-right-newline (if (not= -1 x) (+ idx x) (.-length txt) ) y (.lastIndexOf left "\n") index-of-left-newline (if (not= -1 y) (inc y) 0) _ (comment "index-of-left-newline=" index-of-left-newline) line (.substring txt index-of-left-newline index-of-right-newline) _ (comment "line is" line) ] (comment "left right index-of-right-newline" left right index-of-right-newline) (comment "line is" line) (my-contains? line "|"))) (defn on-key-press-new[event my-key-map composition-kind] (when debug (println "entering on-key-press, my-key-map=" my-key-map)) (if (not= :sargam-composition composition-kind) true (let [ target (.-target event) key-code (.-keyCode event) ctrl-key? (or (.-ctrlKey event) (.-altKey event) (.-metaKey event)) from-char-code-fn (.-fromCharCode js/String) ch (from-char-code-fn key-code) new-char (if-not ctrl-key? (get my-key-map ch )) caret-pos (.-selectionStart target) text-area-text (.-value target) selection (get-selection target) my-within-sargam-line (within-sargam-line? text-area-text (:start selection)) ] nativeEvent looks like { which : 189 , keyCode : 189 , charCode : 0 , repeat : false , : false … } (if (and my-within-sargam-line new-char) (do (when debug "in do********") (set! (.-value target) (str (.substring text-area-text 0 caret-pos) new-char (.substring text-area-text caret-pos))) (set! (.-selectionStart target) (inc (:start selection))) (set! (.-selectionEnd target) (inc (:end selection))) (dispatch [:set-doremi-text (.-value target)]) false ) (do (dispatch [:set-doremi-text (.-value target)]) true) )) )) (defn parse-button[] [:button.btn.btn-primary { :title "Redraw Letter Notation", :name "redraw_letter_notation" :on-click (fn [e] (stop-default-action e) ) } "Redraw" ] ) (defn entry-area-input[] (let [ dom-id "area2" online (subscribe [:online]) composition-kind (subscribe [:composition-kind]) key-map (subscribe [:key-map]) ] (reagent.core/create-class {:component-did-mount (fn entry-area-input-did-mount[this] (dispatch [:start-parse-timer dom-id]) (dispatch [:set-current-entry-area dom-id]) (set! (.-onkeypress (by-id dom-id) ) (fn my-on-key-press[event] (when debug (println "my-on-key-press")) (on-key-press-new event @key-map @composition-kind )))) :display-name "entry-area-input" :reagent-render [:div.form-group.hidden-print [:label {:for "entryArea"} "Enter Letter Notation Source:"] (if (not @online) [:span.offline "You are working offline. Features such as generating staff notation are disabled" ] ) [:textarea.entryArea.form-control { :autofocus true :placeholder text-area-placeholder :id "area2" :name "src", :spellCheck false :on-change (fn on-change-text-area[event] (dispatch [:set-doremi-text (-> event .-target .-value)])) } ]] )}))) (defn draw-children[items] (doall (map-indexed (fn notes-line-aux[idx item] (draw-item item idx)) items))) (defn staff-notation[] (let [staff-notation-url (subscribe [:staff-notation-url])] [:img#staff_notation.hidden-print {:class (if @printing "printing" "") :src @staff-notation-url }])) (defn html-rendered-composition[] (let [composition (subscribe [:composition])] (if (not @composition) [:div#doremiContent.composition.doremiContent ] [:div#doremiContent.composition.doremiContent {:class (if @printing "printing" "")} (draw-children (rest @composition))] ))) (defn attribute-section[{item :item}] nil ) (defn notes-line [{item :item}] (log "notes-line, item is") (log item) (assert (is? :notes-line item)) [:div.stave.sargam_line (draw-children (rest item))]) TODO (defn user-entry[] (.-value (dom/getElement "area2")) ) (def composition-wrapper (with-meta html-rendered-composition {:component-did-mount (fn[this] (log "component-did-mount composition to call dom_fixes") (dom-fixes this) ) :component-did-update (fn[this] (log "component-did-update composition-about to call dom_fixes") (dom-fixes this) ) } )) (defn composition-box[] [:div [:ul.nav.nav-justified [:li [:label.hidden-print {:for "entryArea"} "Rendered Letter Notation: "] ] [:li [parse-button] ] ] [composition-wrapper] ] ) (defn ornament-pitch[{item :item render-as :render-as}] (let [utf-supported (subscribe [:supports-utf8-characters])] (log "entering ornament-pitch") (log item) (let [ (deconstruct-pitch-string (second item) render-as @utf-supported ) octave (some #(when (and (vector %) (= :octave (first %))) (second %)) (rest item)) alteration-string (second deconstructed-pitch) pitch-src (join deconstructed-pitch) octave_class (get class-for-ornament-octave octave) ] [:span.ornament_item {:class octave_class :dangerouslySetInnerHTML { :__html pitch-src } } ] ))) (defn ornament[{item :item}] (comment [:span.upper_attribute.ornament.placement_after [:span.ornament_item.upper_octave_1 "g"]]) (let [render-as (subscribe [:render-as]) items (rest item) filtered (filter #(and (vector? %) (= :ornament-pitch (first %))) items) _ (log "filtered " filtered) placement (last item) placement-class (str "placement_" (name placement)) ] [:span.upper_attribute.ornament {:class placement-class} (doall (map-indexed (fn notes-line-aux[idx item] [ornament-pitch {:item item :render-as @render-as :key idx } ]) filtered)) ] )) (defn mordent[{item :item}] (let [utf-supported (subscribe [:supports-utf8-characters])] [:span.mordent {:dangerouslySetInnerHTML { :__html (if @utf-supported mordent-entity "~") } }]) ) (defn ending[{item :item}] [:span.ending (second item) ]) (defn line-number[{item :item}] [:span.note_wrapper [:span.note.line_number (str (second item) ")") ] ]) (defn line-item [{src :src kind :kind item :item}] (log "entering line-item, item") (log item) [:span {:class "note_wrapper" } src]]) (defn barline[{src :src item :item}] (let [barline-name (first (second item)) utf-supported (subscribe [:supports-utf8-characters]) ] (log "barline-name is" barline-name) [:span.note_wrapper [:span.note.barline {:dangerouslySetInnerHTML { :__html (if @utf-supported (get lookup-barline-utf8 (keyword (first (second item)))) (get lookup-barline (keyword (first (second item)))) ) } } ]])) (defn beat[{item :item}] (log "entering beat") (assert (is? :beat item)) (log "beat, item is") (log item) (let [beat-count (reduce (fn count-beats[accum cur] (log "cur is" cur) (if (and (vector? cur) (get #{:pitch :dash} (first cur))) (inc accum) accum)) 0 (rest item)) _ (log "beat-count is" beat-count) looped (if (> beat-count 1) "looped" "") ] TODO [:span.beat {:class looped} (draw-children (rest item)) ])) (comment TODO : Add underline for hindi pitches that need it . Old code : key : 99 , ) (defn pitch-name[{item :item}] (when false (println "pitch-name, item is") (println item) (println (second item))) [:span.note.pitch {:dangerouslySetInnerHTML { :__html (second item) } } ] ) (defn pitch-alteration[{item :item}] (log "pitch-alteration") (assert (is? :pitch-alteration item)) [:span.note.pitch.alteration {:dangerouslySetInnerHTML { :__html (second item) } } ] ) (defn begin-slur-id[{item :item}] [:span.slur {:id (second item)}] ) (defn needs-kommal-indicator?[normalized-pitch kind] (log "entering needs-kommal-indicator," normalized-pitch kind) (assert (string? normalized-pitch)) (assert (keyword? kind)) (and (= kind :hindi-composition) (#{"Db" "Eb" "Ab" "Bb"} normalized-pitch))) (defn pitch[{item :item render-as :render-as}] (let [utf-supported (subscribe [:supports-utf8-characters])] (log "entering pitch, item=" item) (log "pitch, (first (last item))=" (first (last item))) (log "entring pitch, item is" item) (log item) (let [ begin-slur-id (some (fn[x] (if (and (vector? x) (= :begin-slur-id (first x))) x)) item) end-slur-id (some (fn[x] (if (and (vector? x) (= :end-slur-id (first x))) x)) item) h (if end-slur-id {:data-begin-slur-id (second end-slur-id) } {} :class (css-class-name-for (first item)) ) kommal-indicator (when (needs-kommal-indicator? (second item) @render-as) [:kommal-indicator]) (deconstruct-pitch-string (second item) @render-as @utf-supported ) sort-table {:ornament 1 :octave 2 :syl 3 :kommal-indicator 4 :begin-slur-id 5 :slur 6 :pitch-name 7 :pitch 8 :pitch-alteration 9} item1 (into[] (cons [:pitch-name (first deconstructed-pitch)] (rest (rest item)))) item2 (if begin-slur-id (into[] (cons [:slur (second begin-slur-id)] item1)) item1) alteration-string (second deconstructed-pitch) my-pitch-alteration (when alteration-string [:pitch-alteration alteration-string]) item4 (remove nil? (into[] (cons my-pitch-alteration item2))) item5 (remove (fn[x] (get #{:end-slur-id :slur} (first x))) item4) item5a (remove nil? (into [] (cons kommal-indicator item5))) item6 (sort-by #(get sort-table (first %)) item5a) ] (log "item6 is") (log item6) (draw-children item6) ] ))) (defn lyrics-section [{item :item}] (let [line-strings (map (fn[x] (join " " (rest x))) (rest item)) s (join "\n" line-strings) ] [:div.stave.lyrics_section.unhyphenated {:title "Lyrics Section"} s])) (defn stave[{item :item}] (log "entering stave") (log item) [notes-line {:item (second item)}] ) (defn measure[{item :item}] (assert (is? :measure item)) [:span {:class "measure"} (draw-children (rest item))]) (defn tala[{item :item}] (assert (is? :tala item)) [:span.tala (second item)] ) (defn chord[{item :item}] (assert (is? :chord item)) [:span.chord (second item)] ) (defn syl[{item :item}] (assert (is? :syl item)) (log "in syl, item is" item) (log "syl- item is") (log item) (when (not= (second item) EMPTY-SYLLABLE) [:span.syl (second item)] )) (defn abs [n] (max n (- n))) (defn octave[{item :item}] (log "octave- item is") (log item) (assert (is? :octave item)) (let [octave-num (second item)] (if (or (nil? octave-num) (zero? octave-num)) nil [:span {:class (class-for-octave (second item)) :dangerouslySetInnerHTML { :__html (clojure.string/join (repeat (abs octave-num) bullet)) } } ] ))) (defn kommal-indicator[{item :item}] (assert (is? :kommal-indicator item)) [:span.kommalIndicator "_"] ) key : 99 , (defn draw-item[item idx] (let [my-key (first item) render-as (subscribe [:render-as]) ] (cond (= my-key :begin-slur) nil (= my-key :end-slur) nil (= my-key :ornament) [ornament {:key idx :item item}] (= my-key :mordent) [mordent {:key idx :item item}] (= my-key :ending) [ending {:key idx :item item}] (= my-key :barline) [barline {:key idx :item item}] (= my-key :lyrics-section) [lyrics-section {:key idx :item item}] (= my-key :tala) [tala {:key idx :item item}] (= my-key :chord) [chord {:key idx :item item}] (= my-key :kommal-indicator) [kommal-indicator {:key idx :item item}] (= my-key :syl) [syl {:key idx :item item}] (= my-key :beat) [beat {:key idx :item item}] (= my-key :stave) [stave {:key idx :item item}] (= my-key :measure) [measure {:key idx :item item}] (= my-key :end-slur-id) nil (= my-key :begin-slur-id) [begin-slur-id {:key idx :item item}] (= my-key :attribute-section) [attribute-section {:key idx :item item}] (= my-key :pitch-alteration) [pitch-alteration {:key idx :item item}] (= my-key :ornament-pitch) (do (println "error-don't use-my-key= :ornament-pitch") [ ornament - pitch { : key idx : item item : render - as @render - as } ] ) (= my-key :pitch) [pitch {:key idx :item item :render-as render-as }] (= my-key "syl") [syl {:key idx :item item}] (= my-key :octave) [octave {:key idx :item item}] (= my-key :pitch-name) [pitch-name {:key idx :item item}] (= my-key :notes-line) [notes-line {:key idx :item item}] (= my-key :line-number) [line-number {:key idx :item item}] (= my-key :dash) [line-item {:src "-" :key idx :item item}] true [:span {:key idx :item item} (str "todo-draw-item" (.stringify js/JSON (clj->js item))) ] ))) (defn select-notation-box[kind] (let [composition-kind (subscribe [:composition-kind])] selectNotationBox [:label {:for "selectNotation"} "Enter Notation as: "] [:select#selectNotation.selectNotation.form-control {:value @composition-kind :on-change (fn on-change-select-notation[x] (let [kind-str (-> x .-target .-value) my-kind (if (= "" kind-str) nil (keyword kind-str)) ] (dispatch [:set-composition-kind my-kind]) )) } [:option] [:option {:value :abc-composition} "ABC"] [:option {:value :doremi-composition} "doremi"] [:option {:value :hindi-composition} "hindi( स र ग़ म म' प ध ऩ )"] [:option {:value :number-composition} "number"] [:option {:value :sargam-composition} "sargam"]]] )) (defn render-as-box[] (let [render-as (subscribe [:render-as])] selectNotationBox [:label { :for "renderAs"} "Render as:"] [:select#renderAs.renderAs.form-control {:value @render-as :on-change (fn on-change-render-as[x] (let [value (-> x .-target .-value)] (when (not= value "") (dispatch [:set-render-as (keyword value)])))) } [:option {:value nil}] [:option {:value :abc-composition} "ABC"] [:option {:value :doremi-composition} "doremi"] [:option {:value :hindi-composition} "hindi( स र ग़ म म' प ध ऩ )"] [:option {:value :number-composition} "number"] [:option {:value :sargam-composition} "sargam"]]] )) (defn generate-staff-notation-button[] (let [ ajax-is-running (subscribe [:ajax-is-running]) parse-xhr-is-running (subscribe [:parse-xhr-is-running]) parser (subscribe [:parser]) online (subscribe [:online]) ] [:button.btn.btn-primary { :title "Redraws rendered letter notation and Generates staff notation and MIDI file using Lilypond", :name "generateStaffNotation" (not @online) @ajax-is-running) :on-click (fn [e] (stop-default-action e) (dispatch [:generate-staff-notation])) } (cond " Generate Staff Notation and audio " @ajax-is-running "Redrawing..." true "Generate Staff Notation and audio" ) ] )) (defn audio-div[mp3-url] [:audio#audio { :controls "controls" :preload "auto" :src mp3-url } ] ) (defn key-map[] (let [key-map (subscribe [:key-map]) environment (subscribe [:environment]) ] (when (= :development @environment) [:div (print-str @key-map) ] ))) (defn links[] (let [my-links (subscribe [:links]) environment (subscribe [:environment]) ] selectNotationBox [:select.form-control { :title "Opens a new window" :value "" :on-change (fn[x] (let [value (-> x .-target .-value)] (cond (= value "") nil (= value "print-grammar") (dispatch [:print-grammar]) true (dispatch [:open-link value])))) } [:option {:value ""} "Links"] (doall (map-indexed (fn[idx z] (let [k (first z) v (second z)] [:option {:key idx :value v} (string/replace (name k) #"-url$" "")] )) @my-links )) [:option {:value "print-grammar"} "Print grammar to console"] [:option {:value "-script/#readme"} "Help (github README)"] ]])) (defn utf-support-div[] (let [] (reagent.core/create-class {:component-did-mount (fn utf-support-div-did-mount[this] (dispatch [:check-utf-support (reagent/dom-node this) ]) ) :reagent-render [:div.testing_utf_support [:span#utf_left_repeat.note.testing_utf_support {:style {:display "none"} } "𝄆"] [:span#utf_single_barline.note.testing_utf_support {:style {:display "none"} } "𝄀"] ] ) } ))) (defn controls[] (let [mp3-url (subscribe [:mp3-url]) composition-kind (subscribe [:composition-kind]) ] [:form.form-inline [select-notation-box @composition-kind] [render-as-box] [generate-staff-notation-button] [links] (if @mp3-url [audio-div @mp3-url]) ] )) (defn doremi-box[] [:div.doremiBox [controls] [entry-area-input] [composition-box] [staff-notation] [display-parse-to-user-box] [display-lilypond-source] [utf-support-div] ] )
69b353dd6ff4c22697c4c0d4dadc7ca3f1bfb395804f51eed85e6a5f1301ded8
mstksg/advent-of-code-2022
Day08.hs
-- | Module : AOC.Challenge . -- License : BSD3 -- -- Stability : experimental -- Portability : non-portable -- Day 8 . See " AOC.Solver " for the types used in this module ! module AOC.Challenge.Day08 ( day08a , day08b ) where import AOC.Common (countTrue, digitToIntSafe) import AOC.Solver ((:~>) (..)) import Data.List (foldl', mapAccumL, transpose) import qualified Data.Map as M import Data.Profunctor (dimap) import Safe.Foldable (maximumMay) onSightLines :: ([Int] -> [a]) -> (a -> a -> a) -> [[Int]] -> [a] onSightLines f g rows = foldl' (zipWith g) leftLines [rightLines, upLines, downLines] where leftLines = concatMap f rows rightLines = concatMap (rev f) rows upLines = concat $ tra (map f) rows downLines = concat $ tra (map (rev f)) rows rev = dimap reverse reverse tra = dimap transpose transpose day08a :: [[Int]] :~> Int day08a = MkSol { sParse = (traverse . traverse) digitToIntSafe . lines , sShow = show , sSolve = Just . countTrue id . onSightLines (snd . mapAccumL propagateSight (-1)) (||) } where propagateSight i x = (max i x, x > i) day08b :: [[Int]] :~> Int day08b = MkSol { sParse = (traverse . traverse) digitToIntSafe . lines , sShow = show , sSolve = maximumMay . onSightLines (snd . mapAccumL findSight M.empty . zip [0 ..]) (*) } where findSight lastSeeable (i, x) = ( M.fromList ((,i) <$> [0 .. x]) `M.union` lastSeeable , i - M.findWithDefault 0 x lastSeeable )
null
https://raw.githubusercontent.com/mstksg/advent-of-code-2022/de9ceee002d3a62746468492c746b8d7ca3fc8a0/src/AOC/Challenge/Day08.hs
haskell
| License : BSD3 Stability : experimental Portability : non-portable
Module : AOC.Challenge . Day 8 . See " AOC.Solver " for the types used in this module ! module AOC.Challenge.Day08 ( day08a , day08b ) where import AOC.Common (countTrue, digitToIntSafe) import AOC.Solver ((:~>) (..)) import Data.List (foldl', mapAccumL, transpose) import qualified Data.Map as M import Data.Profunctor (dimap) import Safe.Foldable (maximumMay) onSightLines :: ([Int] -> [a]) -> (a -> a -> a) -> [[Int]] -> [a] onSightLines f g rows = foldl' (zipWith g) leftLines [rightLines, upLines, downLines] where leftLines = concatMap f rows rightLines = concatMap (rev f) rows upLines = concat $ tra (map f) rows downLines = concat $ tra (map (rev f)) rows rev = dimap reverse reverse tra = dimap transpose transpose day08a :: [[Int]] :~> Int day08a = MkSol { sParse = (traverse . traverse) digitToIntSafe . lines , sShow = show , sSolve = Just . countTrue id . onSightLines (snd . mapAccumL propagateSight (-1)) (||) } where propagateSight i x = (max i x, x > i) day08b :: [[Int]] :~> Int day08b = MkSol { sParse = (traverse . traverse) digitToIntSafe . lines , sShow = show , sSolve = maximumMay . onSightLines (snd . mapAccumL findSight M.empty . zip [0 ..]) (*) } where findSight lastSeeable (i, x) = ( M.fromList ((,i) <$> [0 .. x]) `M.union` lastSeeable , i - M.findWithDefault 0 x lastSeeable )
93a812faa82d832a9c57c9b77ca8910d43fd9df8a06d17c1485ef973217a678d
jarohen/yoyo
project.clj
(defproject yoyo-api/lein-template "0.0.7" :description "A template to generate a Yo-yo API project" :url "-henderson/yoyo" :license {:name "Eclipse Public License" :url "-v10.html"} :eval-in-leiningen true)
null
https://raw.githubusercontent.com/jarohen/yoyo/b579d21becd06b5330dee9f5963708db03ce1e25/templates/yoyo-api/project.clj
clojure
(defproject yoyo-api/lein-template "0.0.7" :description "A template to generate a Yo-yo API project" :url "-henderson/yoyo" :license {:name "Eclipse Public License" :url "-v10.html"} :eval-in-leiningen true)
a56967fe99650ef9022f57d37ba821e425893be53b7699bf5701b6042767c68a
juspay/atlas
Person.hs
# LANGUAGE TypeApplications # | Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : Storage . Queries . Person Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : Storage.Queries.Person Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Storage.Queries.Person where import Beckn.External.Encryption import Beckn.External.FCM.Types (FCMRecipientToken) import Beckn.Prelude import qualified Beckn.Product.MapSearch.GoogleMaps as GoogleMaps import Beckn.Storage.Esqueleto as Esq import Beckn.Types.Id import Beckn.Types.MapSearch (LatLong (..)) import qualified Data.Maybe as Mb import Domain.Types.Organization import Domain.Types.Person as Person import Domain.Types.Vehicle as Vehicle import Storage.Tabular.DriverInformation import Storage.Tabular.DriverLocation import Storage.Tabular.Person import Storage.Tabular.Vehicle as Vehicle import Types.App (Driver) import Utils.Common create :: Person -> SqlDB () create = create' findById :: Transactionable m => Id Person -> m (Maybe Person) findById = Esq.findById findByIdAndRoleAndOrgId :: Transactionable m => Id Person -> Person.Role -> Id Organization -> m (Maybe Person) findByIdAndRoleAndOrgId pid role_ orgId = Esq.findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonTId ==. val (toKey pid) &&. person ^. PersonRole ==. val role_ &&. person ^. PersonOrganizationId ==. val (Just $ toKey orgId) return person findAllByOrgId :: Transactionable m => [Person.Role] -> Id Organization -> m [Person] findAllByOrgId roles orgId = Esq.findAll $ do person <- from $ table @PersonT where_ $ (person ^. PersonRole `in_` valList roles ||. val (null roles)) &&. person ^. PersonOrganizationId ==. val (Just $ toKey orgId) return person findAdminsByOrgId :: Transactionable m => Id Organization -> m [Person] findAdminsByOrgId orgId = Esq.findAll $ do person <- from $ table @PersonT where_ $ person ^. PersonOrganizationId ==. val (Just (toKey orgId)) &&. person ^. PersonRole ==. val Person.ADMIN return person findByMobileNumber :: (Transactionable m, EncFlow m r) => Text -> Text -> m (Maybe Person) findByMobileNumber countryCode mobileNumber_ = do mobileNumberDbHash <- getDbHash mobileNumber_ findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonMobileCountryCode ==. val (Just countryCode) &&. person ^. PersonMobileNumberHash ==. val (Just mobileNumberDbHash) return person findByIdentifier :: Transactionable m => Text -> m (Maybe Person) findByIdentifier identifier_ = findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonIdentifier ==. val (Just identifier_) return person findByEmail :: Transactionable m => Text -> m (Maybe Person) findByEmail email_ = findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonEmail ==. val (Just email_) return person updateOrganizationIdAndMakeAdmin :: Id Person -> Id Organization -> SqlDB () updateOrganizationIdAndMakeAdmin personId orgId = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonOrganizationId =. val (Just $ toKey orgId), PersonRole =. val Person.ADMIN, PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) updatePersonRec :: Id Person -> Person -> SqlDB () updatePersonRec personId person = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonFirstName =. val (person.firstName), PersonMiddleName =. val (person.middleName), PersonLastName =. val (person.lastName), PersonRole =. val (person.role), PersonGender =. val (person.gender), PersonEmail =. val (person.email), PersonIdentifier =. val (person.identifier), PersonRating =. val (person.rating), PersonDeviceToken =. val (person.deviceToken), PersonUdf1 =. val (person.udf1), PersonUdf2 =. val (person.udf2), PersonOrganizationId =. val (toKey <$> person.organizationId), PersonDescription =. val (person.description), PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) updateDeviceToken :: Id Person -> Maybe FCMRecipientToken -> SqlDB () updateDeviceToken personId mbDeviceToken = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonDeviceToken =. val mbDeviceToken, PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) setIsNewFalse :: Id Person -> SqlDB () setIsNewFalse personId = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonIsNew =. val False, PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) deleteById :: Id Person -> SqlDB () deleteById = Esq.deleteByKey' @PersonT updateVehicle :: Id Person -> Maybe (Id Vehicle) -> SqlDB () updateVehicle personId mbVehicleId = do let (mEntityId, mEntityType) = case mbVehicleId of Just vehicleId -> (Just (getId vehicleId), Just "VEHICLE") Nothing -> (Nothing, Nothing) now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonUdf1 =. val mEntityId, PersonUdf2 =. val mEntityType, PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) findByVehicleId :: Transactionable m => Id Vehicle -> m (Maybe Person) findByVehicleId (Id vehicleId) = findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonUdf1 ==. val (Just vehicleId) return person updateAverageRating :: Id Person -> Double -> SqlDB () updateAverageRating personId newAverageRating = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonRating =. val (Just newAverageRating), PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) data DriverPoolResult = DriverPoolResult { driverId :: Id Driver, distanceToDriver :: Double, vehicle :: Vehicle, lat :: Double, lon :: Double } deriving (Generic) instance GoogleMaps.HasCoordinates DriverPoolResult where getCoordinates dpRes = LatLong dpRes.lat dpRes.lon getNearestDrivers :: (Transactionable m, HasFlowEnv m r '["driverPositionInfoExpiry" ::: Maybe Seconds]) => LatLong -> Integer -> Id Organization -> m [DriverPoolResult] getNearestDrivers LatLong {..} radiusMeters orgId = do mbDriverPositionInfoExpiry <- asks (.driverPositionInfoExpiry) now <- getCurrentTime res <- Esq.findAll $ do withTable <- with $ do (person :& location :& driverInfo :& vehicle) <- from $ table @PersonT `innerJoin` table @DriverLocationT `Esq.on` ( \(person :& location) -> person ^. PersonTId ==. location ^. DriverLocationDriverId ) `innerJoin` table @DriverInformationT `Esq.on` ( \(person :& _ :& driverInfo) -> person ^. PersonTId ==. driverInfo ^. DriverInformationDriverId ) `innerJoin` table @VehicleT `Esq.on` ( \(person :& _ :& _ :& vehicle) -> (person ^. PersonUdf1) ==. just (castString $ vehicle ^. VehicleId) ) where_ $ person ^. PersonRole ==. val Person.DRIVER &&. person ^. PersonOrganizationId ==. val (Just $ toKey orgId) &&. driverInfo ^. DriverInformationActive &&. not_ (driverInfo ^. DriverInformationOnRide) &&. ( val (Mb.isNothing mbDriverPositionInfoExpiry) ||. (location ^. DriverLocationUpdatedAt +. Esq.interval [Esq.SECOND $ maybe 0 getSeconds mbDriverPositionInfoExpiry] >=. val now) ) return ( person ^. PersonTId, location ^. DriverLocationPoint <->. Esq.getPoint (val lat, val lon), location ^. DriverLocationLat, location ^. DriverLocationLon, vehicle ) (personId, dist, dlat, dlon, vehicleVariant) <- from withTable where_ $ dist <. val (fromIntegral radiusMeters) orderBy [asc dist] return (personId, dist, vehicleVariant, dlat, dlon) return $ makeDriverPoolResult <$> res where makeDriverPoolResult (personId, dist, vehicleVariant, dlat, dlon) = DriverPoolResult (cast personId) dist vehicleVariant dlat dlon
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/driver-offer-bpp/src/Storage/Queries/Person.hs
haskell
# LANGUAGE TypeApplications # | Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Module : Storage . Queries . Person Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module : Storage.Queries.Person Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module Storage.Queries.Person where import Beckn.External.Encryption import Beckn.External.FCM.Types (FCMRecipientToken) import Beckn.Prelude import qualified Beckn.Product.MapSearch.GoogleMaps as GoogleMaps import Beckn.Storage.Esqueleto as Esq import Beckn.Types.Id import Beckn.Types.MapSearch (LatLong (..)) import qualified Data.Maybe as Mb import Domain.Types.Organization import Domain.Types.Person as Person import Domain.Types.Vehicle as Vehicle import Storage.Tabular.DriverInformation import Storage.Tabular.DriverLocation import Storage.Tabular.Person import Storage.Tabular.Vehicle as Vehicle import Types.App (Driver) import Utils.Common create :: Person -> SqlDB () create = create' findById :: Transactionable m => Id Person -> m (Maybe Person) findById = Esq.findById findByIdAndRoleAndOrgId :: Transactionable m => Id Person -> Person.Role -> Id Organization -> m (Maybe Person) findByIdAndRoleAndOrgId pid role_ orgId = Esq.findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonTId ==. val (toKey pid) &&. person ^. PersonRole ==. val role_ &&. person ^. PersonOrganizationId ==. val (Just $ toKey orgId) return person findAllByOrgId :: Transactionable m => [Person.Role] -> Id Organization -> m [Person] findAllByOrgId roles orgId = Esq.findAll $ do person <- from $ table @PersonT where_ $ (person ^. PersonRole `in_` valList roles ||. val (null roles)) &&. person ^. PersonOrganizationId ==. val (Just $ toKey orgId) return person findAdminsByOrgId :: Transactionable m => Id Organization -> m [Person] findAdminsByOrgId orgId = Esq.findAll $ do person <- from $ table @PersonT where_ $ person ^. PersonOrganizationId ==. val (Just (toKey orgId)) &&. person ^. PersonRole ==. val Person.ADMIN return person findByMobileNumber :: (Transactionable m, EncFlow m r) => Text -> Text -> m (Maybe Person) findByMobileNumber countryCode mobileNumber_ = do mobileNumberDbHash <- getDbHash mobileNumber_ findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonMobileCountryCode ==. val (Just countryCode) &&. person ^. PersonMobileNumberHash ==. val (Just mobileNumberDbHash) return person findByIdentifier :: Transactionable m => Text -> m (Maybe Person) findByIdentifier identifier_ = findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonIdentifier ==. val (Just identifier_) return person findByEmail :: Transactionable m => Text -> m (Maybe Person) findByEmail email_ = findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonEmail ==. val (Just email_) return person updateOrganizationIdAndMakeAdmin :: Id Person -> Id Organization -> SqlDB () updateOrganizationIdAndMakeAdmin personId orgId = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonOrganizationId =. val (Just $ toKey orgId), PersonRole =. val Person.ADMIN, PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) updatePersonRec :: Id Person -> Person -> SqlDB () updatePersonRec personId person = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonFirstName =. val (person.firstName), PersonMiddleName =. val (person.middleName), PersonLastName =. val (person.lastName), PersonRole =. val (person.role), PersonGender =. val (person.gender), PersonEmail =. val (person.email), PersonIdentifier =. val (person.identifier), PersonRating =. val (person.rating), PersonDeviceToken =. val (person.deviceToken), PersonUdf1 =. val (person.udf1), PersonUdf2 =. val (person.udf2), PersonOrganizationId =. val (toKey <$> person.organizationId), PersonDescription =. val (person.description), PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) updateDeviceToken :: Id Person -> Maybe FCMRecipientToken -> SqlDB () updateDeviceToken personId mbDeviceToken = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonDeviceToken =. val mbDeviceToken, PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) setIsNewFalse :: Id Person -> SqlDB () setIsNewFalse personId = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonIsNew =. val False, PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) deleteById :: Id Person -> SqlDB () deleteById = Esq.deleteByKey' @PersonT updateVehicle :: Id Person -> Maybe (Id Vehicle) -> SqlDB () updateVehicle personId mbVehicleId = do let (mEntityId, mEntityType) = case mbVehicleId of Just vehicleId -> (Just (getId vehicleId), Just "VEHICLE") Nothing -> (Nothing, Nothing) now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonUdf1 =. val mEntityId, PersonUdf2 =. val mEntityType, PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) findByVehicleId :: Transactionable m => Id Vehicle -> m (Maybe Person) findByVehicleId (Id vehicleId) = findOne $ do person <- from $ table @PersonT where_ $ person ^. PersonUdf1 ==. val (Just vehicleId) return person updateAverageRating :: Id Person -> Double -> SqlDB () updateAverageRating personId newAverageRating = do now <- getCurrentTime update' $ \tbl -> do set tbl [ PersonRating =. val (Just newAverageRating), PersonUpdatedAt =. val now ] where_ $ tbl ^. PersonTId ==. val (toKey personId) data DriverPoolResult = DriverPoolResult { driverId :: Id Driver, distanceToDriver :: Double, vehicle :: Vehicle, lat :: Double, lon :: Double } deriving (Generic) instance GoogleMaps.HasCoordinates DriverPoolResult where getCoordinates dpRes = LatLong dpRes.lat dpRes.lon getNearestDrivers :: (Transactionable m, HasFlowEnv m r '["driverPositionInfoExpiry" ::: Maybe Seconds]) => LatLong -> Integer -> Id Organization -> m [DriverPoolResult] getNearestDrivers LatLong {..} radiusMeters orgId = do mbDriverPositionInfoExpiry <- asks (.driverPositionInfoExpiry) now <- getCurrentTime res <- Esq.findAll $ do withTable <- with $ do (person :& location :& driverInfo :& vehicle) <- from $ table @PersonT `innerJoin` table @DriverLocationT `Esq.on` ( \(person :& location) -> person ^. PersonTId ==. location ^. DriverLocationDriverId ) `innerJoin` table @DriverInformationT `Esq.on` ( \(person :& _ :& driverInfo) -> person ^. PersonTId ==. driverInfo ^. DriverInformationDriverId ) `innerJoin` table @VehicleT `Esq.on` ( \(person :& _ :& _ :& vehicle) -> (person ^. PersonUdf1) ==. just (castString $ vehicle ^. VehicleId) ) where_ $ person ^. PersonRole ==. val Person.DRIVER &&. person ^. PersonOrganizationId ==. val (Just $ toKey orgId) &&. driverInfo ^. DriverInformationActive &&. not_ (driverInfo ^. DriverInformationOnRide) &&. ( val (Mb.isNothing mbDriverPositionInfoExpiry) ||. (location ^. DriverLocationUpdatedAt +. Esq.interval [Esq.SECOND $ maybe 0 getSeconds mbDriverPositionInfoExpiry] >=. val now) ) return ( person ^. PersonTId, location ^. DriverLocationPoint <->. Esq.getPoint (val lat, val lon), location ^. DriverLocationLat, location ^. DriverLocationLon, vehicle ) (personId, dist, dlat, dlon, vehicleVariant) <- from withTable where_ $ dist <. val (fromIntegral radiusMeters) orderBy [asc dist] return (personId, dist, vehicleVariant, dlat, dlon) return $ makeDriverPoolResult <$> res where makeDriverPoolResult (personId, dist, vehicleVariant, dlat, dlon) = DriverPoolResult (cast personId) dist vehicleVariant dlat dlon
550a96f5120fec2b1fa67a12d64844abdb96bade4744bba8728b8417f7401f9e
NorfairKing/smos
GetListBackups.hs
# LANGUAGE RecordWildCards # module Smos.Server.Handler.GetListBackups ( serveGetListBackups, ) where import Smos.Server.Handler.Import serveGetListBackups :: AuthNCookie -> ServerHandler [BackupInfo] serveGetListBackups ac = withUserId ac $ \uid -> runDB $ do backupEntities <- selectList [BackupUser ==. uid] [Desc BackupTime] pure $ flip map backupEntities $ \(Entity _ Backup {..}) -> BackupInfo { backupInfoUUID = backupUuid, backupInfoTime = backupTime, backupInfoSize = backupSize }
null
https://raw.githubusercontent.com/NorfairKing/smos/91efacaede3574e2f8f9d9601bf0383897eebfd8/smos-server/src/Smos/Server/Handler/GetListBackups.hs
haskell
# LANGUAGE RecordWildCards # module Smos.Server.Handler.GetListBackups ( serveGetListBackups, ) where import Smos.Server.Handler.Import serveGetListBackups :: AuthNCookie -> ServerHandler [BackupInfo] serveGetListBackups ac = withUserId ac $ \uid -> runDB $ do backupEntities <- selectList [BackupUser ==. uid] [Desc BackupTime] pure $ flip map backupEntities $ \(Entity _ Backup {..}) -> BackupInfo { backupInfoUUID = backupUuid, backupInfoTime = backupTime, backupInfoSize = backupSize }
ceb3226957d832328179930339873a24476cbf3ca1e314a6993082d2b92456be
ajhc/ajhc
TypeCheck.hs
module E.TypeCheck( canBeBox, eAp, inferType, infertype, typecheck, match, sortSortLike, sortKindLike, sortTermLike, sortTypeLike, typeInfer, typeInfer' ) where import Control.Monad.Reader import Control.Monad.Writer import qualified Data.Map as Map import Doc.DocLike import Doc.PPrint import Doc.Pretty import E.E import E.Eval(strong) import E.Subst import GenUtil import Name.Id import Name.Name import Name.Names import Support.CanType import Util.ContextMonad import Util.SetLike import qualified Util.Seq as Seq import {-# SOURCE #-} DataConstructors import {-# SOURCE #-} E.Show @Internals # Ajhc Core Type System Ajhc 's core is based on a pure type system . A pure type system ( also called a PTS ) is actually a parameterized set of type systems . 's version is described by the following . Sorts = ( * , ! , * * , # , ( # ) , # # , □ ) Axioms = ( * :* * , # : # # , ! :* * , * * : □ , # # : □ ) -- sort kind * is the kind of boxed values ! is the kind of boxed strict values # is the kind of unboxed values ( # ) is the kind of unboxed tuples -- sort superkind * * is the superkind of all boxed value # # is the superkind of all unboxed values -- sort box □ superkinds inhabit this in addition there exist user defined kinds , which are always of supersort # # The following Rules table shows what sort of abstractions are allowed , a rule of the form ( A , B , C ) means you can have functions of things of sort A to things of sort B and the result is something of sort C. _ Function _ in this context subsumes both term and type level abstractions . Notice that functions are always boxed , but may be strict if they take an unboxed tuple as an argument . When a function is strict it means that it is represented by a pointer to code directly , it can not be a suspended value that evaluates to a function . These type system rules apply to lambda abstractions . It is possible that data constructors might exist that can not be given a type on their own with these rules , even though when fully applied it has a well formed type . An example would be unboxed tuples . This presents no difficulty as one concludes correctly that it is a type error for these constructors to ever appear when not fully saturated with arguments . as a shortcut we will use * # to mean every combination involving * and # , and so forth . for instance , ( * # , * # , * ) means the set ( * , * , * ) ( # , * , * ) ( * , # , * ) ( # , # , * ) Rules = ( * # ! , * # ! , * ) -- functions from values to values are boxed and lazy ( * # ! , ( # ) , * ) -- functions from values to unboxed tuples are boxed and lazy ( ( # ) , * # ! , ! ) -- functions from unboxed tuples to values are boxed and strict ( ( # ) , ( # ) , ! ) -- functions from unboxed tuples to unboxed tuples are boxed and strict ( * * , * , * ) -- may have a function from an unboxed type to a value ( * * , # , * ) ( * * , ! , * ) ( * * , * * , * * ) -- we have functions from types to types ( * * , # # , # # ) -- MutArray _ : : * - > # ( # # , # # , # # ) -- Complex _ : : # - > # The defining feature of boxed values is _ | _ : : t iff t : :* This PTS is functional but not injective The PTS can be considered stratified into the following levels □ - sort box * * , # # , - sort superkind * , # , ( # ) , ! - sort kind Int , Bits32_,Char - sort type 3,True,"bob " - sort value # # On boxed kinds The boxed kinds ( * and ! ) represent types that have a uniform run time representation . Due to this , functions may be written that are polymorphic in types of these kinds . Hence the rules of the form ( * * , ? , ? ) , allowing taking types of boxed kinds as arguments . the unboxed kind # is inhabited with types that have their own specific run time representation . Hence you can not write functions that are polymorphic in unboxed types # # On sort box , the unboxed tuple , and friends Although sort box does not appear in the code , it is useful from a theoretical point of view to talk about certain types such as the types of unboxed tuples . tuples may have boxed and unboxed arguments , without sort box it would be impossible to express this since it must be superkind polymorphic . sort box allows one to express this as ( in the case of the unboxed 2 - tuple ) : □ : □ ∀k1 : s1 ∀k2 : s2 ∀t1 : : k2 . ( # t1 , t2 # ) However , although this is a valid typing of what it would mean if a unboxed tuple were not fully applied , since we do not have any rules of form ( # # , ? , ? ) or ( □ , ? , ? ) this type obviously does not typecheck . Which is what enforces the invarient that unboxed tuples are always fully applied , and is also why we do not need a code representation of sort box . # # # Do we need a superbox ? You will notice that if you look at the axioms involving the sorts , you end up with a disjoint graph □ - the box / \ * * # # - superkind /\ \ * ! # ( # ) - kind This is simply due to the fact that nothing is polymorphic in unboxed tuples of kind ( # ) so we never need to refer to any super - sorts of them . We can add sorts ( # # ) , ( □ ) and □ □ to fill in the gaps , but since these sorts will never appear in code or discourse , we will ignore them from now on . □ □ - sort superbox / \ □ ( □ ) - sort box / \ \ * * # # ( # # ) - sort superkind /\ \ | * ! # ( # ) - sort kind # Ajhc Core Type System Ajhc's core is based on a pure type system. A pure type system (also called a PTS) is actually a parameterized set of type systems. Ajhc's version is described by the following. Sorts = (*, !, **, #, (#), ##, □) Axioms = (*:**, #:##, !:**, **:□, ##:□) -- sort kind * is the kind of boxed values ! is the kind of boxed strict values # is the kind of unboxed values (#) is the kind of unboxed tuples -- sort superkind ** is the superkind of all boxed value ## is the superkind of all unboxed values -- sort box □ superkinds inhabit this in addition there exist user defined kinds, which are always of supersort ## The following Rules table shows what sort of abstractions are allowed, a rule of the form (A,B,C) means you can have functions of things of sort A to things of sort B and the result is something of sort C. _Function_ in this context subsumes both term and type level abstractions. Notice that functions are always boxed, but may be strict if they take an unboxed tuple as an argument. When a function is strict it means that it is represented by a pointer to code directly, it cannot be a suspended value that evaluates to a function. These type system rules apply to lambda abstractions. It is possible that data constructors might exist that cannot be given a type on their own with these rules, even though when fully applied it has a well formed type. An example would be unboxed tuples. This presents no difficulty as one concludes correctly that it is a type error for these constructors to ever appear when not fully saturated with arguments. as a shortcut we will use *# to mean every combination involving * and #, and so forth. for instance, (*#,*#,*) means the set (*,*,*) (#,*,*) (*,#,*) (#,#,*) Rules = (*#!,*#!,*) -- functions from values to values are boxed and lazy (*#!,(#),*) -- functions from values to unboxed tuples are boxed and lazy ((#),*#!,!) -- functions from unboxed tuples to values are boxed and strict ((#),(#),!) -- functions from unboxed tuples to unboxed tuples are boxed and strict (**,*,*) -- may have a function from an unboxed type to a value (**,#,*) (**,!,*) (**,**,**) -- we have functions from types to types (**,##,##) -- MutArray_ :: * -> # (##,##,##) -- Complex_ :: # -> # The defining feature of boxed values is _|_ :: t iff t::* This PTS is functional but not injective The PTS can be considered stratified into the following levels □ - sort box **,##, - sort superkind *,#,(#),! - sort kind Int,Bits32_,Char - sort type 3,True,"bob" - sort value ## On boxed kinds The boxed kinds (* and !) represent types that have a uniform run time representation. Due to this, functions may be written that are polymorphic in types of these kinds. Hence the rules of the form (**,?,?), allowing taking types of boxed kinds as arguments. the unboxed kind # is inhabited with types that have their own specific run time representation. Hence you cannot write functions that are polymorphic in unboxed types ## On sort box, the unboxed tuple, and friends Although sort box does not appear in the code, it is useful from a theoretical point of view to talk about certain types such as the types of unboxed tuples. Unboxed tuples may have boxed and unboxed arguments, without sort box it would be impossible to express this since it must be superkind polymorphic. sort box allows one to express this as (in the case of the unboxed 2-tuple) ∀s1:□ ∀s2:□ ∀k1:s1 ∀k2:s2 ∀t1:k1 ∀t2:k2 . (# t1, t2 #) However, although this is a valid typing of what it would mean if a unboxed tuple were not fully applied, since we do not have any rules of form (##,?,?) or (□,?,?) this type obviously does not typecheck. Which is what enforces the invarient that unboxed tuples are always fully applied, and is also why we do not need a code representation of sort box. ### Do we need a superbox? You will notice that if you look at the axioms involving the sorts, you end up with a disjoint graph □ - the box / \ ** ## - superkind /\ \ * ! # (#) - kind This is simply due to the fact that nothing is polymorphic in unboxed tuples of kind (#) so we never need to refer to any super-sorts of them. We can add sorts (##),(□) and □□ to fill in the gaps, but since these sorts will never appear in code or discourse, we will ignore them from now on. □□ - sort superbox / \ □ (□) - sort box / \ \ ** ## (##) - sort superkind /\ \ | * ! # (#) - sort kind -} ptsAxioms :: Map.Map ESort ESort ptsAxioms = Map.fromList [ (EStar,EStarStar), (EBang,EStarStar), (EHash,EHashHash), (ETuple,EHashHash) ] ptsRulesMap :: Map.Map (ESort,ESort) ESort ptsRulesMap = Map.fromList [ ((a,b),c) | (as,bs,c) <- ptsRules, a <- as, b <- bs ] where starHashBang = [EStar,EHash,EBang] ptsRules = [ (starHashBang,ETuple:starHashBang,EStar), ([ETuple],ETuple:starHashBang,EBang), ([EStarStar],starHashBang,EStar), ([EStarStar],[EStarStar],EStarStar), ([EStarStar],[EHashHash],EHashHash), ([EHashHash],[EHashHash],EHashHash) ] canBeBox x | getType (getType x) == ESort EStarStar = True canBeBox _ = False tBox = mktBox eStar monadicLookup key m = case Map.lookup key m of Just x -> return x Nothing -> fail "Key not found" -- Fast (and lazy, and perhaps unsafe) typeof instance CanType E where type TypeOf E = E getType (ESort s) = ESort $ getType s getType (ELit l) = getType l getType (EVar v) = getType v getType e@(EPi TVr { tvrType = a } b) | isUnknown typa || isUnknown typb = Unknown | otherwise = maybe (error $ "E.TypeCheck.getType: " ++ show (e,getType a,getType b)) ESort $ do ESort s1 <- return $ getType a ESort s2 <- return $ getType b monadicLookup (s1,s2) ptsRulesMap where typa = getType a; typb = getType b getType (EAp (ELit LitCons { litType = EPi tvr a }) b) = getType (subst tvr b a) getType (EAp (ELit lc@LitCons { litAliasFor = Just af }) b) = getType (foldl eAp af (litArgs lc ++ [b])) getType (EAp (EPi tvr a) b) = getType (subst tvr b a) getType e@(EAp a b) = ans where ans = if isUnknown typa then Unknown else if a == tBox || typa == tBox then tBox else (case a of (ELit LitCons {}) -> error $ "getType: application of type alias " ++ (render $ parens $ ePretty e) _ -> eAp typa b) typa = getType a getType (ELam (TVr { tvrIdent = x, tvrType = a}) b) = EPi (tVr x a) (getType b) getType (ELetRec _ e) = getType e getType ECase {eCaseType = ty} = ty getType (EError _ e) = e getType (EPrim _ _ t) = t getType Unknown = Unknown instance CanType ESort where type TypeOf ESort = ESort getType (ESortNamed _) = EHashHash getType s = case Map.lookup s ptsAxioms of Just s -> s Nothing -> error $ "getType: " ++ show s instance CanType TVr where type TypeOf TVr = E getType = tvrType instance CanType (Lit x t) where type TypeOf (Lit x t) = t getType l = litType l instance CanType e => CanType (Alt e) where type TypeOf (Alt e) = TypeOf e getType (Alt _ e) = getType e sortSortLike (ESort s) = isEHashHash s || isEStarStar s sortSortLike _ = False sortKindLike (ESort s) = not (isEHashHash s) && not (isEStarStar s) sortKindLike e = sortSortLike (getType e) sortTypeLike ESort {} = False sortTypeLike e = sortKindLike (getType e) sortTermLike ESort {} = False sortTermLike e = sortTypeLike (getType e) withContextDoc s a = withContext (render s) a -- | Perform a full typecheck, evaluating type terms as necessary. inferType :: (ContextMonad m, ContextOf m ~ String) => DataTable -> [(TVr,E)] -> E -> m E inferType dataTable ds e = rfc e where inferType' ds e = inferType dataTable ds e prettyE = ePretty rfc e = withContextDoc (text "fullCheck:" </> prettyE e) (fc e >>= strong') rfc' nds e = withContextDoc (text "fullCheck':" </> prettyE e) (inferType' nds e) strong' e = withContextDoc (parens $ text "Strong:" </> prettyE e) $ strong ds e fc s@(ESort _) = return $ getType s fc (ELit lc@LitCons {}) | let lc' = updateLit dataTable lc, litAliasFor lc /= litAliasFor lc' = fail $ "Alias not correct: " ++ show (lc, litAliasFor lc') fc (ELit LitCons { litName = n, litArgs = es, litType = t}) | nameType n == TypeConstructor, Just _ <- fromUnboxedNameTuple n = do withContext ("Checking Unboxed Tuple: " ++ show n) $ do -- we omit kind checking for unboxed tuples valid t es' <- mapM rfc es strong' t fc e@(ELit LitCons { litName = n, litArgs = es, litType = t}) = do withContext ("Checking Constructor: " ++ show e) $ do valid t es' <- mapM rfc es t' <- strong' t let sts = slotTypes dataTable n t les = length es lsts = length sts withContext ("Checking Args: " ++ show (sts,es')) $ do unless (les == lsts || (les < lsts && isEPi t')) $ do fail "constructor with wrong number of arguments" zipWithM_ eq sts es' return t' fc e@(ELit _) = let t = getType e in valid t >> return t fc (EVar (TVr { tvrIdent = eid })) | eid == emptyId = fail "variable with nothing!" fc (EVar (TVr { tvrType = t})) = valid t >> strong' t fc (EPi (TVr { tvrIdent = n, tvrType = at}) b) = do ESort a <- rfc at ESort b <- rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b liftM ESort $ monadicLookup (a,b) ptsRulesMap --valid at >> rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b fc ( ELam tvr@(TVr n at ) b ) = valid at > > rfc ' [ d | d@(v , _ ) < - ds , tvrIdent v /= n ] b > > = \b ' - > ( strong ' $ EPi tvr b ' ) fc (ELam tvr@(TVr { tvrIdent = n, tvrType = at}) b) = do withContext "Checking Lambda" $ do valid at b' <- withContext "Checking Lambda Body" $ rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b withContext "Checking lambda pi" $ strong' $ EPi tvr b' fc (EAp (EPi tvr e) b) = rfc (subst tvr b e) fc (EAp (ELit lc@LitCons { litAliasFor = Just af }) b) = rfc (EAp (foldl eAp af (litArgs lc)) b) fc (EAp a b) = do withContextDoc (text "EAp:" </> parens (prettyE a) </> parens (prettyE b)) $ do a' <- rfc a if a' == tBox then return tBox else strong' (eAp a' b) fc (ELetRec vs e) = do let ck (TVr { tvrIdent = eid },_) | eid == emptyId = fail "binding of empty var" ck (tv@(TVr { tvrType = t}),e) = withContextDoc (hsep [text "Checking Let: ", parens (pprint tv),text " = ", parens $ prettyE e ]) $ do when (getType t == eHash && not (isEPi t)) $ fail $ "Let binding unboxed value: " ++ show (tv,e) valid' nds t fceq nds e t nds = vs ++ ds mapM_ ck vs when (hasRepeatUnder (tvrIdent . fst) vs) $ fail "Repeat Variable in ELetRec" inferType' nds e --et <- inferType' nds e strong fc (EError _ e) = valid e >> (strong' e) fc (EPrim _ ts t) = mapM_ valid ts >> valid t >> ( strong' t) TODO - this is a hack to get around case of constants . withContext "Checking typelike pattern binding case" $ do et <- rfc e withContext "Checking typelike default binding" $ eq et (getType b) verifyPats (casePats ec) -- skip checking alternatives ps <- mapM (strong' . getType) $ casePats ec withContext "Checking typelike pattern equality" $ eqAll (et:ps) strong' dt fc ec@ECase {eCaseScrutinee = e, eCaseBind = b, eCaseAlts = as, eCaseType = dt } | sortTypeLike e = do -- TODO - we should substitute the tested for value into the default type. withContext "Checking typelike binding case" $ do et <- rfc e withContext "Checking typelike default binding" $ eq et (getType b) --dt <- rfc d bs < - mapM rfc ( caseBodies ec ) -- these should be specializations of dt withContext "Checking typelike alternatives" $ mapM_ (calt e) as --eqAll bs verifyPats (casePats ec) ps <- withContext "Getting pattern types" $ mapM (strong' . getType) $ casePats ec withContext "checking typelike pattern equality" $ eqAll (et:ps) withContext "Evaluating Case Type" $ strong' dt fc ec@ECase { eCaseScrutinee =e, eCaseBind = b } = do withContext "Checking plain case" $ do et <- rfc e withContext "Checking default binding" $ eq et (getType b) bs <- withContext "Checking case bodies" $ mapM rfc (caseBodies ec) ect <- strong' (eCaseType ec) withContext "Checking case bodies have equal types" $ eqAll (ect:bs) verifyPats (casePats ec) ps <- mapM (strong' . getType) $ casePats ec withContext "checking pattern equality" $ eqAll (et:ps) return ect fc Unknown = return Unknown --fc e = failDoc $ text "what's this? " </> (prettyE e) calt (EVar v) (Alt l e) = do let nv = followAliases undefined (patToLitEE l) rfc (subst' v nv e) calt _ (Alt _ e) = rfc e verifyPats xs = do mapM_ verifyPats' xs when (hasRepeatUnder litHead xs) $ fail "Duplicate case alternatives" verifyPats' LitCons { litArgs = xs } = when (hasRepeatUnder id (filter (/= emptyId) $ map tvrIdent xs)) $ fail "Case pattern is non-linear" verifyPats' _ = return () eqAll ts = withContextDoc (text "eqAll" </> list (map prettyE ts)) $ foldl1M_ eq ts valid s = valid' ds s valid' nds ESort {} = return () valid' nds s | Unknown <- s = return () | otherwise = withContextDoc (text "valid:" <+> prettyE s) (do t <- inferType' nds s; valid' nds t) eq box t2 | boxCompat box t2 = return t2 eq t1 box | boxCompat box t1 = return t1 box = = , canBeBox t2 = return t2 eq t1 box | box = = , canBeBox t1 = return t1 eq Unknown t2 = return t2 eq t1 Unknown = return t1 eq t1 t2 = eq' ds t1 t2 eq' nds t1 t2 = do e1 <- strong nds (t1) e2 <- strong nds (t2) case typesCompatable e1 e2 of Just () -> return (e1) Nothing -> failDoc $ text "eq:" <+> align $ vcat [ prettyE (e1), prettyE (e2) ] fceq nds e1 t2 = do withContextDoc (hsep [text "fceq:", align $ vcat [parens $ prettyE e1, parens $ prettyE t2]]) $ do t1 <- inferType' nds e1 eq' nds t1 t2 boxCompat (ELit (LitCons { litName = n })) t | Just e <- fromConjured modBox n = e == getType t boxCompat _ _ = False -- This should perform a full typecheck and may take any extra information needed as an extra parameter class CanTypeCheck a where typecheck :: Monad m => DataTable -> a -> m E infertype :: CanTypeCheck a => DataTable -> a -> E infertype env a = case typecheck env a of Left s -> error $ "infertype: " ++ s Right x -> x instance CanTypeCheck E where typecheck dataTable e = case runContextEither $ typeInfer'' dataTable [] e of Left ss -> fail $ "\n>>> internal error:\n" ++ unlines ss Right v -> return v instance CanTypeCheck TVr where typecheck dt tvr = do typecheck dt (getType tvr) return $ getType tvr instance CanTypeCheck (Lit a E) where typecheck dt LitCons { litType = t } = typecheck dt t >> return t typecheck dt LitInt { litType = t } = typecheck dt t >> return t TODO , types might be bound in scrutinization instance CanTypeCheck (Alt E) where typecheck dt (Alt l e) = typecheck dt l >> typecheck dt e -- | Determine type of term using full algorithm with substitutions. This -- should be used instead of 'typ' when let-bound type variables exist or you -- wish a more thorough checking of types. typeInfer :: DataTable -> E -> E typeInfer dataTable e = case runContextEither $ typeInfer'' dataTable [] e of Left ss -> error $ "\n>>> internal error:\n" ++ unlines (tail ss) Right v -> v typeInfer' :: DataTable -> [(TVr,E)] -> E -> E typeInfer' dataTable ds e = case runContextEither $ typeInfer'' dataTable ds e of Left ss -> error $ "\n>>> internal error:\n" ++ unlines (tail ss) Right v -> v data TcEnv = TcEnv { --tcDefns :: [(TVr,E)], tcContext :: [String] --tcDataTable :: DataTable } tcContext_u f r@TcEnv{tcContext = x} = r{tcContext = f x} newtype Tc a = Tc (Reader TcEnv a) deriving(Monad,Functor,MonadReader TcEnv) instance ContextMonad Tc where type ContextOf Tc = String withContext s = local (tcContext_u (s:)) tcE : : E - > Tc E tcE e = rfc e where rfc e = withContextDoc ( text " tcE : " < / > ePretty e ) ( fc e > > = strong ' ) strong ' e = do ds < - asks tcDefns withContextDoc ( text " tcE.strong : " < / > ePretty e ) $ strong ds e fc s@ESort { } = return $ getType s fc ( ELit LitCons { litType = t } ) = strong ' t fc e@ELit { } = strong ' ( ) fc ( EVar TVr { tvrIdent = eid } ) | eid = = emptyId = fail " variable with nothing ! " fc ( EVar TVr { tvrType = t } ) = strong ' t fc ( EPi TVr { tvrIdent = n , tvrType = at } b ) = do ESort a < - rfc at ESort b < - local ( ( \ds - > [ d | d@(v , _ ) < - ds , tvrIdent v /= n ] ) ) $ rfc b liftM ESort $ monadicLookup ( a , b ) ptsRulesMap fc ( ELam tvr@TVr { tvrIdent = n , tvrType = at } b ) = do at ' < - strong ' at b ' < - local ( ( \ds - > [ d | d@(v , _ ) < - ds , tvrIdent v /= n ] ) ) $ rfc b return ( EPi ( tVr n at ' ) b ' ) fc ( EAp ( EPi tvr e ) b ) = do b < - strong ' b rfc ( subst tvr b e ) fc ( EAp ( ELit lc@LitCons { litAliasFor = Just af } ) b ) = fc ( EAp ( foldl eAp af ( ) ) b ) fc ( EAp a b ) = do a ' < - rfc a if a ' = = then return else strong ' ( eAp a ' b ) fc ( ELetRec vs e ) = local ( ( vs + + ) ) $ rfc e fc ( EError _ e ) = strong ' e fc ( EPrim _ ts t ) = strong ' t fc ECase { eCaseType = ty } = do strong ' ty fc Unknown = return Unknown fc e = failDoc $ text " what 's this ? " < / > ( ePretty e ) tcE :: E -> Tc E tcE e = rfc e where rfc e = withContextDoc (text "tcE:" </> ePretty e) (fc e >>= strong') strong' e = do ds <- asks tcDefns withContextDoc (text "tcE.strong:" </> ePretty e) $ strong ds e fc s@ESort {} = return $ getType s fc (ELit LitCons { litType = t }) = strong' t fc e@ELit {} = strong' (getType e) fc (EVar TVr { tvrIdent = eid }) | eid == emptyId = fail "variable with nothing!" fc (EVar TVr { tvrType = t}) = strong' t fc (EPi TVr { tvrIdent = n, tvrType = at} b) = do ESort a <- rfc at ESort b <- local (tcDefns_u (\ds -> [ d | d@(v,_) <- ds, tvrIdent v /= n ])) $ rfc b liftM ESort $ monadicLookup (a,b) ptsRulesMap fc (ELam tvr@TVr { tvrIdent = n, tvrType = at} b) = do at' <- strong' at b' <- local (tcDefns_u (\ds -> [ d | d@(v,_) <- ds, tvrIdent v /= n ])) $ rfc b return (EPi (tVr n at') b') fc (EAp (EPi tvr e) b) = do b <- strong' b rfc (subst tvr b e) fc (EAp (ELit lc@LitCons { litAliasFor = Just af }) b) = fc (EAp (foldl eAp af (litArgs lc)) b) fc (EAp a b) = do a' <- rfc a if a' == tBox then return tBox else strong' (eAp a' b) fc (ELetRec vs e) = local (tcDefns_u (vs ++)) $ rfc e fc (EError _ e) = strong' e fc (EPrim _ ts t) = strong' t fc ECase { eCaseType = ty } = do strong' ty fc Unknown = return Unknown fc e = failDoc $ text "what's this? " </> (ePretty e) -} typeInfer'' :: (ContextMonad m, ContextOf m ~ String) => DataTable -> [(TVr,E)] -> E -> m E typeInfer'' dataTable ds e = rfc e where inferType' ds e = typeInfer'' dataTable ds e rfc e = withContextDoc (text "fullCheck':" </> ePretty e) (fc e >>= strong') rfc' nds e = withContextDoc (text "fullCheck':" </> ePretty e) (inferType' nds e) strong' e = withContextDoc (text "Strong':" </> ePretty e) $ strong ds e fc s@ESort {} = return $ getType s fc (ELit LitCons { litType = t }) = strong' t fc e@ELit {} = strong' (getType e) fc (EVar TVr { tvrIdent = eid }) | eid == emptyId = fail "variable with nothing!" fc (EVar TVr { tvrType = t}) = strong' t fc (EPi TVr { tvrIdent = n, tvrType = at} b) = do ESort a <- rfc at ESort b <- rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b liftM ESort $ monadicLookup (a,b) ptsRulesMap fc (ELam tvr@TVr { tvrIdent = n, tvrType = at} b) = do at' <- strong' at b' <- rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b return (EPi (tVr n at') b') fc (EAp (EPi tvr e) b) = do b <- strong' b rfc (subst tvr b e) fc (EAp (ELit lc@LitCons { litAliasFor = Just af }) b) = fc (EAp (foldl eAp af (litArgs lc)) b) fc (EAp a b) = do a' <- rfc a if a' == tBox then return tBox else strong' (eAp a' b) fc (ELetRec vs e) = do let nds = vs ++ ds --et <- inferType' nds e strong inferType' nds e fc (EError _ e) = strong' e fc (EPrim _ ts t) = strong' t fc ECase { eCaseType = ty } = do strong' ty fc Unknown = return Unknown --fc e = failDoc $ text "what's this? " </> (ePretty e) -- | find substitution that will transform the left term into the right one, -- only substituting for the vars in the list match :: Monad m => (Id -> Maybe E) -- ^ function to look up values in the environment -> [TVr] -- ^ vars which may be substituted -> E -- ^ pattern to match -> E -- ^ input expression -> m [(TVr,E)] match lup vs = \e1 e2 -> liftM Seq.toList $ execWriterT (un e1 e2 etherealIds) where bvs :: IdSet bvs = fromList (map tvrIdent vs) un (EAp a b) (EAp a' b') c = do un a a' c un b b' c un (ELam va ea) (ELam vb eb) c = lam va ea vb eb c un (EPi va ea) (EPi vb eb) c = lam va ea vb eb c un (EPi va ea) (ELit LitCons { litName = ar, litArgs = [x,y], litType = lt}) c | ar == tc_Arrow = do un (tvrType va) x c un ea y c un (EPrim s xs t) (EPrim s' ys t') c | length xs == length ys = do sequence_ [ un x y c | x <- xs | y <- ys] un t t' c un (ESort x) (ESort y) c | x == y = return () un (ELit (LitInt x t1)) (ELit (LitInt y t2)) c | x == y = un t1 t2 c un (ELit LitCons { litName = n, litArgs = xs, litType = t }) (ELit LitCons { litName = n', litArgs = ys, litType = t'}) c | n == n' && length xs == length ys = do sequence_ [ un x y c | x <- xs | y <- ys] un t t' c un (EVar TVr { tvrIdent = i, tvrType = t}) (EVar TVr {tvrIdent = j, tvrType = u}) c | i == j = un t u c un (EVar TVr { tvrIdent = i, tvrType = t}) (EVar TVr {tvrIdent = j, tvrType = u}) c | isEtherealId i || isEtherealId j = fail "Expressions don't match" un (EAp a b) (ELit lc@LitCons { litArgs = bas@(_:_), litType = t }) c = do let (al:as) = reverse bas un a (ELit lc { litArgs = reverse as, litType = ePi tvr { tvrType = getType al } t }) c un b al c un (EAp a b) (EPi TVr { tvrType = a1 } a2) c = do un a (ELit litCons { litArgs = [a1], litName = tc_Arrow, litType = EPi tvr { tvrType = getType a2 } (getType a1) }) c un b a2 c un (EVar tvr@TVr { tvrIdent = i, tvrType = t}) b c | i `member` bvs = tell (Seq.single (tvr,b)) | otherwise = fail $ "Expressions do not unify: " ++ show tvr ++ show b un a (EVar tvr) c | Just b <- lup (tvrIdent tvr), not $ isEVar b = un a b c un a b c | Just a ' < - followAlias undefined a = un a ' b c un a b c | Just b' <- followAlias undefined b = un a b' c un a b _ = fail $ "Expressions do not unify: " ++ show a ++ show b lam va ea vb eb (c:cs) = do un (tvrType va) (tvrType vb) (c:cs) un (subst va (EVar va { tvrIdent = c }) ea) (subst vb (EVar vb { tvrIdent = c }) eb) cs lam _ _ _ _ _ = error "TypeCheck.match: bad."
null
https://raw.githubusercontent.com/ajhc/ajhc/8ef784a6a3b5998cfcd95d0142d627da9576f264/src/E/TypeCheck.hs
haskell
# SOURCE # # SOURCE # sort kind sort superkind sort box functions from values to values are boxed and lazy functions from values to unboxed tuples are boxed and lazy functions from unboxed tuples to values are boxed and strict functions from unboxed tuples to unboxed tuples are boxed and strict may have a function from an unboxed type to a value we have functions from types to types MutArray _ : : * - > # Complex _ : : # - > # sort kind sort superkind sort box functions from values to values are boxed and lazy functions from values to unboxed tuples are boxed and lazy functions from unboxed tuples to values are boxed and strict functions from unboxed tuples to unboxed tuples are boxed and strict may have a function from an unboxed type to a value we have functions from types to types MutArray_ :: * -> # Complex_ :: # -> # Fast (and lazy, and perhaps unsafe) typeof | Perform a full typecheck, evaluating type terms as necessary. we omit kind checking for unboxed tuples valid at >> rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b et <- inferType' nds e skip checking alternatives TODO - we should substitute the tested for value into the default type. dt <- rfc d these should be specializations of dt eqAll bs fc e = failDoc $ text "what's this? " </> (prettyE e) This should perform a full typecheck and may take any extra information needed as an extra parameter | Determine type of term using full algorithm with substitutions. This should be used instead of 'typ' when let-bound type variables exist or you wish a more thorough checking of types. tcDefns :: [(TVr,E)], tcDataTable :: DataTable et <- inferType' nds e fc e = failDoc $ text "what's this? " </> (ePretty e) | find substitution that will transform the left term into the right one, only substituting for the vars in the list ^ function to look up values in the environment ^ vars which may be substituted ^ pattern to match ^ input expression
module E.TypeCheck( canBeBox, eAp, inferType, infertype, typecheck, match, sortSortLike, sortKindLike, sortTermLike, sortTypeLike, typeInfer, typeInfer' ) where import Control.Monad.Reader import Control.Monad.Writer import qualified Data.Map as Map import Doc.DocLike import Doc.PPrint import Doc.Pretty import E.E import E.Eval(strong) import E.Subst import GenUtil import Name.Id import Name.Name import Name.Names import Support.CanType import Util.ContextMonad import Util.SetLike import qualified Util.Seq as Seq @Internals # Ajhc Core Type System Ajhc 's core is based on a pure type system . A pure type system ( also called a PTS ) is actually a parameterized set of type systems . 's version is described by the following . Sorts = ( * , ! , * * , # , ( # ) , # # , □ ) Axioms = ( * :* * , # : # # , ! :* * , * * : □ , # # : □ ) * is the kind of boxed values ! is the kind of boxed strict values # is the kind of unboxed values ( # ) is the kind of unboxed tuples * * is the superkind of all boxed value # # is the superkind of all unboxed values □ superkinds inhabit this in addition there exist user defined kinds , which are always of supersort # # The following Rules table shows what sort of abstractions are allowed , a rule of the form ( A , B , C ) means you can have functions of things of sort A to things of sort B and the result is something of sort C. _ Function _ in this context subsumes both term and type level abstractions . Notice that functions are always boxed , but may be strict if they take an unboxed tuple as an argument . When a function is strict it means that it is represented by a pointer to code directly , it can not be a suspended value that evaluates to a function . These type system rules apply to lambda abstractions . It is possible that data constructors might exist that can not be given a type on their own with these rules , even though when fully applied it has a well formed type . An example would be unboxed tuples . This presents no difficulty as one concludes correctly that it is a type error for these constructors to ever appear when not fully saturated with arguments . as a shortcut we will use * # to mean every combination involving * and # , and so forth . for instance , ( * # , * # , * ) means the set ( * , * , * ) ( # , * , * ) ( * , # , * ) ( # , # , * ) Rules = ( * * , # , * ) ( * * , ! , * ) The defining feature of boxed values is _ | _ : : t iff t : :* This PTS is functional but not injective The PTS can be considered stratified into the following levels □ - sort box * * , # # , - sort superkind * , # , ( # ) , ! - sort kind Int , Bits32_,Char - sort type 3,True,"bob " - sort value # # On boxed kinds The boxed kinds ( * and ! ) represent types that have a uniform run time representation . Due to this , functions may be written that are polymorphic in types of these kinds . Hence the rules of the form ( * * , ? , ? ) , allowing taking types of boxed kinds as arguments . the unboxed kind # is inhabited with types that have their own specific run time representation . Hence you can not write functions that are polymorphic in unboxed types # # On sort box , the unboxed tuple , and friends Although sort box does not appear in the code , it is useful from a theoretical point of view to talk about certain types such as the types of unboxed tuples . tuples may have boxed and unboxed arguments , without sort box it would be impossible to express this since it must be superkind polymorphic . sort box allows one to express this as ( in the case of the unboxed 2 - tuple ) : □ : □ ∀k1 : s1 ∀k2 : s2 ∀t1 : : k2 . ( # t1 , t2 # ) However , although this is a valid typing of what it would mean if a unboxed tuple were not fully applied , since we do not have any rules of form ( # # , ? , ? ) or ( □ , ? , ? ) this type obviously does not typecheck . Which is what enforces the invarient that unboxed tuples are always fully applied , and is also why we do not need a code representation of sort box . # # # Do we need a superbox ? You will notice that if you look at the axioms involving the sorts , you end up with a disjoint graph □ - the box / \ * * # # - superkind /\ \ * ! # ( # ) - kind This is simply due to the fact that nothing is polymorphic in unboxed tuples of kind ( # ) so we never need to refer to any super - sorts of them . We can add sorts ( # # ) , ( □ ) and □ □ to fill in the gaps , but since these sorts will never appear in code or discourse , we will ignore them from now on . □ □ - sort superbox / \ □ ( □ ) - sort box / \ \ * * # # ( # # ) - sort superkind /\ \ | * ! # ( # ) - sort kind # Ajhc Core Type System Ajhc's core is based on a pure type system. A pure type system (also called a PTS) is actually a parameterized set of type systems. Ajhc's version is described by the following. Sorts = (*, !, **, #, (#), ##, □) Axioms = (*:**, #:##, !:**, **:□, ##:□) * is the kind of boxed values ! is the kind of boxed strict values # is the kind of unboxed values (#) is the kind of unboxed tuples ** is the superkind of all boxed value ## is the superkind of all unboxed values □ superkinds inhabit this in addition there exist user defined kinds, which are always of supersort ## The following Rules table shows what sort of abstractions are allowed, a rule of the form (A,B,C) means you can have functions of things of sort A to things of sort B and the result is something of sort C. _Function_ in this context subsumes both term and type level abstractions. Notice that functions are always boxed, but may be strict if they take an unboxed tuple as an argument. When a function is strict it means that it is represented by a pointer to code directly, it cannot be a suspended value that evaluates to a function. These type system rules apply to lambda abstractions. It is possible that data constructors might exist that cannot be given a type on their own with these rules, even though when fully applied it has a well formed type. An example would be unboxed tuples. This presents no difficulty as one concludes correctly that it is a type error for these constructors to ever appear when not fully saturated with arguments. as a shortcut we will use *# to mean every combination involving * and #, and so forth. for instance, (*#,*#,*) means the set (*,*,*) (#,*,*) (*,#,*) (#,#,*) Rules = (**,#,*) (**,!,*) The defining feature of boxed values is _|_ :: t iff t::* This PTS is functional but not injective The PTS can be considered stratified into the following levels □ - sort box **,##, - sort superkind *,#,(#),! - sort kind Int,Bits32_,Char - sort type 3,True,"bob" - sort value ## On boxed kinds The boxed kinds (* and !) represent types that have a uniform run time representation. Due to this, functions may be written that are polymorphic in types of these kinds. Hence the rules of the form (**,?,?), allowing taking types of boxed kinds as arguments. the unboxed kind # is inhabited with types that have their own specific run time representation. Hence you cannot write functions that are polymorphic in unboxed types ## On sort box, the unboxed tuple, and friends Although sort box does not appear in the code, it is useful from a theoretical point of view to talk about certain types such as the types of unboxed tuples. Unboxed tuples may have boxed and unboxed arguments, without sort box it would be impossible to express this since it must be superkind polymorphic. sort box allows one to express this as (in the case of the unboxed 2-tuple) ∀s1:□ ∀s2:□ ∀k1:s1 ∀k2:s2 ∀t1:k1 ∀t2:k2 . (# t1, t2 #) However, although this is a valid typing of what it would mean if a unboxed tuple were not fully applied, since we do not have any rules of form (##,?,?) or (□,?,?) this type obviously does not typecheck. Which is what enforces the invarient that unboxed tuples are always fully applied, and is also why we do not need a code representation of sort box. ### Do we need a superbox? You will notice that if you look at the axioms involving the sorts, you end up with a disjoint graph □ - the box / \ ** ## - superkind /\ \ * ! # (#) - kind This is simply due to the fact that nothing is polymorphic in unboxed tuples of kind (#) so we never need to refer to any super-sorts of them. We can add sorts (##),(□) and □□ to fill in the gaps, but since these sorts will never appear in code or discourse, we will ignore them from now on. □□ - sort superbox / \ □ (□) - sort box / \ \ ** ## (##) - sort superkind /\ \ | * ! # (#) - sort kind -} ptsAxioms :: Map.Map ESort ESort ptsAxioms = Map.fromList [ (EStar,EStarStar), (EBang,EStarStar), (EHash,EHashHash), (ETuple,EHashHash) ] ptsRulesMap :: Map.Map (ESort,ESort) ESort ptsRulesMap = Map.fromList [ ((a,b),c) | (as,bs,c) <- ptsRules, a <- as, b <- bs ] where starHashBang = [EStar,EHash,EBang] ptsRules = [ (starHashBang,ETuple:starHashBang,EStar), ([ETuple],ETuple:starHashBang,EBang), ([EStarStar],starHashBang,EStar), ([EStarStar],[EStarStar],EStarStar), ([EStarStar],[EHashHash],EHashHash), ([EHashHash],[EHashHash],EHashHash) ] canBeBox x | getType (getType x) == ESort EStarStar = True canBeBox _ = False tBox = mktBox eStar monadicLookup key m = case Map.lookup key m of Just x -> return x Nothing -> fail "Key not found" instance CanType E where type TypeOf E = E getType (ESort s) = ESort $ getType s getType (ELit l) = getType l getType (EVar v) = getType v getType e@(EPi TVr { tvrType = a } b) | isUnknown typa || isUnknown typb = Unknown | otherwise = maybe (error $ "E.TypeCheck.getType: " ++ show (e,getType a,getType b)) ESort $ do ESort s1 <- return $ getType a ESort s2 <- return $ getType b monadicLookup (s1,s2) ptsRulesMap where typa = getType a; typb = getType b getType (EAp (ELit LitCons { litType = EPi tvr a }) b) = getType (subst tvr b a) getType (EAp (ELit lc@LitCons { litAliasFor = Just af }) b) = getType (foldl eAp af (litArgs lc ++ [b])) getType (EAp (EPi tvr a) b) = getType (subst tvr b a) getType e@(EAp a b) = ans where ans = if isUnknown typa then Unknown else if a == tBox || typa == tBox then tBox else (case a of (ELit LitCons {}) -> error $ "getType: application of type alias " ++ (render $ parens $ ePretty e) _ -> eAp typa b) typa = getType a getType (ELam (TVr { tvrIdent = x, tvrType = a}) b) = EPi (tVr x a) (getType b) getType (ELetRec _ e) = getType e getType ECase {eCaseType = ty} = ty getType (EError _ e) = e getType (EPrim _ _ t) = t getType Unknown = Unknown instance CanType ESort where type TypeOf ESort = ESort getType (ESortNamed _) = EHashHash getType s = case Map.lookup s ptsAxioms of Just s -> s Nothing -> error $ "getType: " ++ show s instance CanType TVr where type TypeOf TVr = E getType = tvrType instance CanType (Lit x t) where type TypeOf (Lit x t) = t getType l = litType l instance CanType e => CanType (Alt e) where type TypeOf (Alt e) = TypeOf e getType (Alt _ e) = getType e sortSortLike (ESort s) = isEHashHash s || isEStarStar s sortSortLike _ = False sortKindLike (ESort s) = not (isEHashHash s) && not (isEStarStar s) sortKindLike e = sortSortLike (getType e) sortTypeLike ESort {} = False sortTypeLike e = sortKindLike (getType e) sortTermLike ESort {} = False sortTermLike e = sortTypeLike (getType e) withContextDoc s a = withContext (render s) a inferType :: (ContextMonad m, ContextOf m ~ String) => DataTable -> [(TVr,E)] -> E -> m E inferType dataTable ds e = rfc e where inferType' ds e = inferType dataTable ds e prettyE = ePretty rfc e = withContextDoc (text "fullCheck:" </> prettyE e) (fc e >>= strong') rfc' nds e = withContextDoc (text "fullCheck':" </> prettyE e) (inferType' nds e) strong' e = withContextDoc (parens $ text "Strong:" </> prettyE e) $ strong ds e fc s@(ESort _) = return $ getType s fc (ELit lc@LitCons {}) | let lc' = updateLit dataTable lc, litAliasFor lc /= litAliasFor lc' = fail $ "Alias not correct: " ++ show (lc, litAliasFor lc') fc (ELit LitCons { litName = n, litArgs = es, litType = t}) | nameType n == TypeConstructor, Just _ <- fromUnboxedNameTuple n = do withContext ("Checking Unboxed Tuple: " ++ show n) $ do valid t es' <- mapM rfc es strong' t fc e@(ELit LitCons { litName = n, litArgs = es, litType = t}) = do withContext ("Checking Constructor: " ++ show e) $ do valid t es' <- mapM rfc es t' <- strong' t let sts = slotTypes dataTable n t les = length es lsts = length sts withContext ("Checking Args: " ++ show (sts,es')) $ do unless (les == lsts || (les < lsts && isEPi t')) $ do fail "constructor with wrong number of arguments" zipWithM_ eq sts es' return t' fc e@(ELit _) = let t = getType e in valid t >> return t fc (EVar (TVr { tvrIdent = eid })) | eid == emptyId = fail "variable with nothing!" fc (EVar (TVr { tvrType = t})) = valid t >> strong' t fc (EPi (TVr { tvrIdent = n, tvrType = at}) b) = do ESort a <- rfc at ESort b <- rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b liftM ESort $ monadicLookup (a,b) ptsRulesMap fc ( ELam tvr@(TVr n at ) b ) = valid at > > rfc ' [ d | d@(v , _ ) < - ds , tvrIdent v /= n ] b > > = \b ' - > ( strong ' $ EPi tvr b ' ) fc (ELam tvr@(TVr { tvrIdent = n, tvrType = at}) b) = do withContext "Checking Lambda" $ do valid at b' <- withContext "Checking Lambda Body" $ rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b withContext "Checking lambda pi" $ strong' $ EPi tvr b' fc (EAp (EPi tvr e) b) = rfc (subst tvr b e) fc (EAp (ELit lc@LitCons { litAliasFor = Just af }) b) = rfc (EAp (foldl eAp af (litArgs lc)) b) fc (EAp a b) = do withContextDoc (text "EAp:" </> parens (prettyE a) </> parens (prettyE b)) $ do a' <- rfc a if a' == tBox then return tBox else strong' (eAp a' b) fc (ELetRec vs e) = do let ck (TVr { tvrIdent = eid },_) | eid == emptyId = fail "binding of empty var" ck (tv@(TVr { tvrType = t}),e) = withContextDoc (hsep [text "Checking Let: ", parens (pprint tv),text " = ", parens $ prettyE e ]) $ do when (getType t == eHash && not (isEPi t)) $ fail $ "Let binding unboxed value: " ++ show (tv,e) valid' nds t fceq nds e t nds = vs ++ ds mapM_ ck vs when (hasRepeatUnder (tvrIdent . fst) vs) $ fail "Repeat Variable in ELetRec" inferType' nds e strong fc (EError _ e) = valid e >> (strong' e) fc (EPrim _ ts t) = mapM_ valid ts >> valid t >> ( strong' t) TODO - this is a hack to get around case of constants . withContext "Checking typelike pattern binding case" $ do et <- rfc e withContext "Checking typelike default binding" $ eq et (getType b) verifyPats (casePats ec) ps <- mapM (strong' . getType) $ casePats ec withContext "Checking typelike pattern equality" $ eqAll (et:ps) strong' dt withContext "Checking typelike binding case" $ do et <- rfc e withContext "Checking typelike default binding" $ eq et (getType b) withContext "Checking typelike alternatives" $ mapM_ (calt e) as verifyPats (casePats ec) ps <- withContext "Getting pattern types" $ mapM (strong' . getType) $ casePats ec withContext "checking typelike pattern equality" $ eqAll (et:ps) withContext "Evaluating Case Type" $ strong' dt fc ec@ECase { eCaseScrutinee =e, eCaseBind = b } = do withContext "Checking plain case" $ do et <- rfc e withContext "Checking default binding" $ eq et (getType b) bs <- withContext "Checking case bodies" $ mapM rfc (caseBodies ec) ect <- strong' (eCaseType ec) withContext "Checking case bodies have equal types" $ eqAll (ect:bs) verifyPats (casePats ec) ps <- mapM (strong' . getType) $ casePats ec withContext "checking pattern equality" $ eqAll (et:ps) return ect fc Unknown = return Unknown calt (EVar v) (Alt l e) = do let nv = followAliases undefined (patToLitEE l) rfc (subst' v nv e) calt _ (Alt _ e) = rfc e verifyPats xs = do mapM_ verifyPats' xs when (hasRepeatUnder litHead xs) $ fail "Duplicate case alternatives" verifyPats' LitCons { litArgs = xs } = when (hasRepeatUnder id (filter (/= emptyId) $ map tvrIdent xs)) $ fail "Case pattern is non-linear" verifyPats' _ = return () eqAll ts = withContextDoc (text "eqAll" </> list (map prettyE ts)) $ foldl1M_ eq ts valid s = valid' ds s valid' nds ESort {} = return () valid' nds s | Unknown <- s = return () | otherwise = withContextDoc (text "valid:" <+> prettyE s) (do t <- inferType' nds s; valid' nds t) eq box t2 | boxCompat box t2 = return t2 eq t1 box | boxCompat box t1 = return t1 box = = , canBeBox t2 = return t2 eq t1 box | box = = , canBeBox t1 = return t1 eq Unknown t2 = return t2 eq t1 Unknown = return t1 eq t1 t2 = eq' ds t1 t2 eq' nds t1 t2 = do e1 <- strong nds (t1) e2 <- strong nds (t2) case typesCompatable e1 e2 of Just () -> return (e1) Nothing -> failDoc $ text "eq:" <+> align $ vcat [ prettyE (e1), prettyE (e2) ] fceq nds e1 t2 = do withContextDoc (hsep [text "fceq:", align $ vcat [parens $ prettyE e1, parens $ prettyE t2]]) $ do t1 <- inferType' nds e1 eq' nds t1 t2 boxCompat (ELit (LitCons { litName = n })) t | Just e <- fromConjured modBox n = e == getType t boxCompat _ _ = False class CanTypeCheck a where typecheck :: Monad m => DataTable -> a -> m E infertype :: CanTypeCheck a => DataTable -> a -> E infertype env a = case typecheck env a of Left s -> error $ "infertype: " ++ s Right x -> x instance CanTypeCheck E where typecheck dataTable e = case runContextEither $ typeInfer'' dataTable [] e of Left ss -> fail $ "\n>>> internal error:\n" ++ unlines ss Right v -> return v instance CanTypeCheck TVr where typecheck dt tvr = do typecheck dt (getType tvr) return $ getType tvr instance CanTypeCheck (Lit a E) where typecheck dt LitCons { litType = t } = typecheck dt t >> return t typecheck dt LitInt { litType = t } = typecheck dt t >> return t TODO , types might be bound in scrutinization instance CanTypeCheck (Alt E) where typecheck dt (Alt l e) = typecheck dt l >> typecheck dt e typeInfer :: DataTable -> E -> E typeInfer dataTable e = case runContextEither $ typeInfer'' dataTable [] e of Left ss -> error $ "\n>>> internal error:\n" ++ unlines (tail ss) Right v -> v typeInfer' :: DataTable -> [(TVr,E)] -> E -> E typeInfer' dataTable ds e = case runContextEither $ typeInfer'' dataTable ds e of Left ss -> error $ "\n>>> internal error:\n" ++ unlines (tail ss) Right v -> v data TcEnv = TcEnv { tcContext :: [String] } tcContext_u f r@TcEnv{tcContext = x} = r{tcContext = f x} newtype Tc a = Tc (Reader TcEnv a) deriving(Monad,Functor,MonadReader TcEnv) instance ContextMonad Tc where type ContextOf Tc = String withContext s = local (tcContext_u (s:)) tcE : : E - > Tc E tcE e = rfc e where rfc e = withContextDoc ( text " tcE : " < / > ePretty e ) ( fc e > > = strong ' ) strong ' e = do ds < - asks tcDefns withContextDoc ( text " tcE.strong : " < / > ePretty e ) $ strong ds e fc s@ESort { } = return $ getType s fc ( ELit LitCons { litType = t } ) = strong ' t fc e@ELit { } = strong ' ( ) fc ( EVar TVr { tvrIdent = eid } ) | eid = = emptyId = fail " variable with nothing ! " fc ( EVar TVr { tvrType = t } ) = strong ' t fc ( EPi TVr { tvrIdent = n , tvrType = at } b ) = do ESort a < - rfc at ESort b < - local ( ( \ds - > [ d | d@(v , _ ) < - ds , tvrIdent v /= n ] ) ) $ rfc b liftM ESort $ monadicLookup ( a , b ) ptsRulesMap fc ( ELam tvr@TVr { tvrIdent = n , tvrType = at } b ) = do at ' < - strong ' at b ' < - local ( ( \ds - > [ d | d@(v , _ ) < - ds , tvrIdent v /= n ] ) ) $ rfc b return ( EPi ( tVr n at ' ) b ' ) fc ( EAp ( EPi tvr e ) b ) = do b < - strong ' b rfc ( subst tvr b e ) fc ( EAp ( ELit lc@LitCons { litAliasFor = Just af } ) b ) = fc ( EAp ( foldl eAp af ( ) ) b ) fc ( EAp a b ) = do a ' < - rfc a if a ' = = then return else strong ' ( eAp a ' b ) fc ( ELetRec vs e ) = local ( ( vs + + ) ) $ rfc e fc ( EError _ e ) = strong ' e fc ( EPrim _ ts t ) = strong ' t fc ECase { eCaseType = ty } = do strong ' ty fc Unknown = return Unknown fc e = failDoc $ text " what 's this ? " < / > ( ePretty e ) tcE :: E -> Tc E tcE e = rfc e where rfc e = withContextDoc (text "tcE:" </> ePretty e) (fc e >>= strong') strong' e = do ds <- asks tcDefns withContextDoc (text "tcE.strong:" </> ePretty e) $ strong ds e fc s@ESort {} = return $ getType s fc (ELit LitCons { litType = t }) = strong' t fc e@ELit {} = strong' (getType e) fc (EVar TVr { tvrIdent = eid }) | eid == emptyId = fail "variable with nothing!" fc (EVar TVr { tvrType = t}) = strong' t fc (EPi TVr { tvrIdent = n, tvrType = at} b) = do ESort a <- rfc at ESort b <- local (tcDefns_u (\ds -> [ d | d@(v,_) <- ds, tvrIdent v /= n ])) $ rfc b liftM ESort $ monadicLookup (a,b) ptsRulesMap fc (ELam tvr@TVr { tvrIdent = n, tvrType = at} b) = do at' <- strong' at b' <- local (tcDefns_u (\ds -> [ d | d@(v,_) <- ds, tvrIdent v /= n ])) $ rfc b return (EPi (tVr n at') b') fc (EAp (EPi tvr e) b) = do b <- strong' b rfc (subst tvr b e) fc (EAp (ELit lc@LitCons { litAliasFor = Just af }) b) = fc (EAp (foldl eAp af (litArgs lc)) b) fc (EAp a b) = do a' <- rfc a if a' == tBox then return tBox else strong' (eAp a' b) fc (ELetRec vs e) = local (tcDefns_u (vs ++)) $ rfc e fc (EError _ e) = strong' e fc (EPrim _ ts t) = strong' t fc ECase { eCaseType = ty } = do strong' ty fc Unknown = return Unknown fc e = failDoc $ text "what's this? " </> (ePretty e) -} typeInfer'' :: (ContextMonad m, ContextOf m ~ String) => DataTable -> [(TVr,E)] -> E -> m E typeInfer'' dataTable ds e = rfc e where inferType' ds e = typeInfer'' dataTable ds e rfc e = withContextDoc (text "fullCheck':" </> ePretty e) (fc e >>= strong') rfc' nds e = withContextDoc (text "fullCheck':" </> ePretty e) (inferType' nds e) strong' e = withContextDoc (text "Strong':" </> ePretty e) $ strong ds e fc s@ESort {} = return $ getType s fc (ELit LitCons { litType = t }) = strong' t fc e@ELit {} = strong' (getType e) fc (EVar TVr { tvrIdent = eid }) | eid == emptyId = fail "variable with nothing!" fc (EVar TVr { tvrType = t}) = strong' t fc (EPi TVr { tvrIdent = n, tvrType = at} b) = do ESort a <- rfc at ESort b <- rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b liftM ESort $ monadicLookup (a,b) ptsRulesMap fc (ELam tvr@TVr { tvrIdent = n, tvrType = at} b) = do at' <- strong' at b' <- rfc' [ d | d@(v,_) <- ds, tvrIdent v /= n ] b return (EPi (tVr n at') b') fc (EAp (EPi tvr e) b) = do b <- strong' b rfc (subst tvr b e) fc (EAp (ELit lc@LitCons { litAliasFor = Just af }) b) = fc (EAp (foldl eAp af (litArgs lc)) b) fc (EAp a b) = do a' <- rfc a if a' == tBox then return tBox else strong' (eAp a' b) fc (ELetRec vs e) = do let nds = vs ++ ds strong inferType' nds e fc (EError _ e) = strong' e fc (EPrim _ ts t) = strong' t fc ECase { eCaseType = ty } = do strong' ty fc Unknown = return Unknown match :: Monad m => -> m [(TVr,E)] match lup vs = \e1 e2 -> liftM Seq.toList $ execWriterT (un e1 e2 etherealIds) where bvs :: IdSet bvs = fromList (map tvrIdent vs) un (EAp a b) (EAp a' b') c = do un a a' c un b b' c un (ELam va ea) (ELam vb eb) c = lam va ea vb eb c un (EPi va ea) (EPi vb eb) c = lam va ea vb eb c un (EPi va ea) (ELit LitCons { litName = ar, litArgs = [x,y], litType = lt}) c | ar == tc_Arrow = do un (tvrType va) x c un ea y c un (EPrim s xs t) (EPrim s' ys t') c | length xs == length ys = do sequence_ [ un x y c | x <- xs | y <- ys] un t t' c un (ESort x) (ESort y) c | x == y = return () un (ELit (LitInt x t1)) (ELit (LitInt y t2)) c | x == y = un t1 t2 c un (ELit LitCons { litName = n, litArgs = xs, litType = t }) (ELit LitCons { litName = n', litArgs = ys, litType = t'}) c | n == n' && length xs == length ys = do sequence_ [ un x y c | x <- xs | y <- ys] un t t' c un (EVar TVr { tvrIdent = i, tvrType = t}) (EVar TVr {tvrIdent = j, tvrType = u}) c | i == j = un t u c un (EVar TVr { tvrIdent = i, tvrType = t}) (EVar TVr {tvrIdent = j, tvrType = u}) c | isEtherealId i || isEtherealId j = fail "Expressions don't match" un (EAp a b) (ELit lc@LitCons { litArgs = bas@(_:_), litType = t }) c = do let (al:as) = reverse bas un a (ELit lc { litArgs = reverse as, litType = ePi tvr { tvrType = getType al } t }) c un b al c un (EAp a b) (EPi TVr { tvrType = a1 } a2) c = do un a (ELit litCons { litArgs = [a1], litName = tc_Arrow, litType = EPi tvr { tvrType = getType a2 } (getType a1) }) c un b a2 c un (EVar tvr@TVr { tvrIdent = i, tvrType = t}) b c | i `member` bvs = tell (Seq.single (tvr,b)) | otherwise = fail $ "Expressions do not unify: " ++ show tvr ++ show b un a (EVar tvr) c | Just b <- lup (tvrIdent tvr), not $ isEVar b = un a b c un a b c | Just a ' < - followAlias undefined a = un a ' b c un a b c | Just b' <- followAlias undefined b = un a b' c un a b _ = fail $ "Expressions do not unify: " ++ show a ++ show b lam va ea vb eb (c:cs) = do un (tvrType va) (tvrType vb) (c:cs) un (subst va (EVar va { tvrIdent = c }) ea) (subst vb (EVar vb { tvrIdent = c }) eb) cs lam _ _ _ _ _ = error "TypeCheck.match: bad."
6e2f6e82bb629e1432e431041cb14fb8d9360f57aafbe810ed57d3e46bbe7d0f
janestreet/ecaml
mode_line.mli
open! Core open! Import module Format : sig type t [@@deriving sexp_of] (** [(describe-variable 'mode-line-format)] *) val in_buffer : t Buffer_local.t end * [ ( describe - function ' format - mode - line ) ] Sadly , in test , which runs Emacs batch mode , [ text ] always returns the empty string . Sadly, in test, which runs Emacs batch mode, [text] always returns the empty string. *) val text : Format.t -> Text.t
null
https://raw.githubusercontent.com/janestreet/ecaml/7c16e5720ee1da04e0757cf185a074debf9088df/src/mode_line.mli
ocaml
* [(describe-variable 'mode-line-format)]
open! Core open! Import module Format : sig type t [@@deriving sexp_of] val in_buffer : t Buffer_local.t end * [ ( describe - function ' format - mode - line ) ] Sadly , in test , which runs Emacs batch mode , [ text ] always returns the empty string . Sadly, in test, which runs Emacs batch mode, [text] always returns the empty string. *) val text : Format.t -> Text.t
4d38716311c236372dd4f5f24361dfff7970149bc6f2f160020cfe03ac662dd2
savonet/ocaml-mm
audio.ml
* Copyright 2011 The Savonet Team * * This file is part of ocaml - mm . * * is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * * As a special exception to the GNU Library General Public License , you may * link , statically or dynamically , a " work that uses the Library " with a publicly * distributed version of the Library to produce an executable file containing * portions of the Library , and distribute that executable file under terms of * your choice , without any of the additional requirements listed in clause 6 * of the GNU Library General Public License . * By " a publicly distributed version of the Library " , we mean either the unmodified * Library as distributed by The Savonet Team , or a modified version of the Library that is * distributed under the conditions defined in clause 3 of the GNU Library General * Public License . This exception does not however invalidate any other reasons why * the executable file might be covered by the GNU Library General Public License . * * Copyright 2011 The Savonet Team * * This file is part of ocaml-mm. * * ocaml-mm is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * ocaml-mm 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 Lesser General Public License * along with ocaml-mm; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * As a special exception to the GNU Library General Public License, you may * link, statically or dynamically, a "work that uses the Library" with a publicly * distributed version of the Library to produce an executable file containing * portions of the Library, and distribute that executable file under terms of * your choice, without any of the additional requirements listed in clause 6 * of the GNU Library General Public License. * By "a publicly distributed version of the Library", we mean either the unmodified * Library as distributed by The Savonet Team, or a modified version of the Library that is * distributed under the conditions defined in clause 3 of the GNU Library General * Public License. This exception does not however invalidate any other reasons why * the executable file might be covered by the GNU Library General Public License. * *) (* TODO: - lots of functions require offset and length whereas in most cases we want to apply the operations on the whole buffers -> labeled optional arguments? - do we want to pass samplerate as an argument or to store it in buffers? *) open Mm_base let list_filter_ctxt f l = let rec aux b = function | [] -> [] | h :: t -> if f b h t then h :: aux (b @ [h]) t else aux (b @ [h]) t in aux [] l let pi = 3.14159265358979323846 let lin_of_dB x = 10. ** (x /. 20.) let dB_of_lin x = 20. *. log x /. log 10. (** Fractional part of a float. *) let fracf x = if x < 1. then x else if x < 2. then x -. 1. else fst (modf x) let samples_of_seconds sr t = int_of_float (float sr *. t) let seconds_of_samples sr n = float n /. float sr module Note = struct A4 = 69 type t = int let a4 = 69 let c5 = 72 let c0 = 12 let create name oct = name + (12 * (oct + 1)) let freq n = 440. *. (2. ** ((float n -. 69.) /. 12.)) let of_freq f = int_of_float (0.5 +. ((12. *. log (f /. 440.) /. log 2.) +. 69.)) let name n = n mod 12 let octave n = (n / 12) - 1 let modulo n = (name n, octave n) let to_string n = let n, o = modulo n in (match n with | 0 -> "A" | 1 -> "A#" | 2 -> "B" | 3 -> "C" | 4 -> "C#" | 5 -> "D" | 6 -> "D#" | 7 -> "E" | 8 -> "F" | 9 -> "F#" | 10 -> "G" | 11 -> "G#" | _ -> assert false) ^ " " ^ string_of_int o (* TODO: sharps and flats *) let of_string s = assert (String.length s >= 2); let note = String.sub s 0 (String.length s - 1) in let oct = int_of_char s.[String.length s - 1] - int_of_char '0' in let off = match note with | "a" | "A" -> 0 | "b" | "B" -> 2 | "c" | "C" -> 3 | "d" | "D" -> 5 | "e" | "E" -> 7 | "f" | "F" -> 8 | "g" | "G" -> 10 | _ -> raise Not_found in 64 + (12 * (oct - 4)) + off end module Sample = struct type t = float let clip x = let x = max (-1.) x in let x = min 1. x in x let iir a b = let na = Array.length a in let nb = Array.length b in assert (a.(0) = 1.); let x = Array.make nb 0. in let y = Array.make na 0. in let ka = ref 0 in let kb = ref 0 in fun x0 -> let y0 = ref 0. in x.(!kb) <- x0; for i = 0 to nb - 1 do y0 := !y0 +. (b.(i) *. x.((!kb + i) mod nb)) done; for i = 1 to na - 1 do y0 := !y0 -. (a.(i) *. y.((!ka + i) mod na)) done; if na > 0 then y.(!ka) <- !y0; let decr n k = decr k; if !k < 0 then k := !k + n in decr na ka; decr nb kb; !y0 let fir b = iir [||] b end module Mono = struct type t = float array type buffer = t let create = Array.create_float let length = Array.length let buffer_length = length let clear data ofs len = Array.fill data ofs len 0. let make n (x : float) = Array.make n x let sub = Array.sub let blit = Array.blit let copy src ofs len = let dst = create len in blit src ofs dst 0 len; dst external copy_from_ba : (float, Bigarray.float32_elt, Bigarray.c_layout) Bigarray.Array1.t -> float array -> int -> int -> unit = "caml_mm_audio_copy_from_ba" external copy_to_ba : float array -> int -> int -> (float, Bigarray.float32_elt, Bigarray.c_layout) Bigarray.Array1.t -> unit = "caml_mm_audio_copy_to_ba" let of_ba buf = let len = Bigarray.Array1.dim buf in let dst = Array.create_float len in copy_from_ba buf dst 0 len; dst let to_ba buf ofs len = let ba = Bigarray.Array1.create Bigarray.float32 Bigarray.c_layout len in copy_to_ba buf ofs len ba; ba let append b1 ofs1 len1 b2 ofs2 len2 = assert (length b1 - ofs1 >= len1); assert (length b2 - ofs2 >= len2); let data = Array.create_float (len1 + len2) in Array.blit b1 ofs1 data 0 len1; Array.blit b2 ofs2 data len1 len2; data let add b1 ofs1 b2 ofs2 len = assert (length b1 - ofs1 >= len); assert (length b2 - ofs2 >= len); for i = 0 to len - 1 do Array.unsafe_set b1 (ofs1 + i) (Array.unsafe_get b1 (ofs1 + i) +. Array.unsafe_get b2 (ofs2 + i)) done let add_coeff b1 ofs1 k b2 ofs2 len = assert (length b1 - ofs1 >= len); assert (length b2 - ofs2 >= len); for i = 0 to len - 1 do Array.unsafe_set b1 (ofs1 + i) (Array.unsafe_get b1 (ofs1 + i) +. (k *. Array.unsafe_get b2 (ofs2 + i))) done let add_coeff b1 ofs1 k b2 ofs2 len = if k = 0. then () else if k = 1. then add b1 ofs1 b2 ofs2 len else add_coeff b1 ofs1 k b2 ofs2 len let mult b1 ofs1 b2 ofs2 len = assert (length b1 - ofs1 >= len); assert (length b2 - ofs2 >= len); for i = 0 to len - 1 do Array.unsafe_set b1 (ofs1 + i) (Array.unsafe_get b1 (ofs1 + i) *. Array.unsafe_get b2 (ofs2 + i)) done let amplify c b ofs len = assert (length b - ofs >= len); for i = 0 to len - 1 do Array.unsafe_set b (ofs + i) (Array.unsafe_get b (ofs + i) *. c) done let clip b ofs len = assert (length b - ofs >= len); for i = 0 to len - 1 do let s = Array.unsafe_get b (ofs + i) in Array.unsafe_set b (ofs + i) (if Float.is_nan s then 0. else if s < -1. then -1. else if 1. < s then 1. else s) done let squares b ofs len = assert (length b - ofs >= len); let ret = ref 0. in for i = 0 to len - 1 do let s = Array.unsafe_get b (ofs + i) in ret := !ret +. (s *. s) done; !ret let noise b ofs len = assert (length b - ofs >= len); for i = 0 to len - 1 do Array.unsafe_set b (ofs + i) (Random.float 2. -. 1.) done let resample ?(mode = `Linear) ratio inbuf ofs len = assert (length inbuf - ofs >= len); if ratio = 1. then copy inbuf ofs len else if mode = `Nearest then ( let outlen = int_of_float ((float len *. ratio) +. 0.5) in let outbuf = create outlen in for i = 0 to outlen - 1 do let pos = min (int_of_float ((float i /. ratio) +. 0.5)) (len - 1) in Array.unsafe_set outbuf i (Array.unsafe_get inbuf (ofs + pos)) done; outbuf) else ( let outlen = int_of_float (float len *. ratio) in let outbuf = create outlen in for i = 0 to outlen - 1 do let ir = float i /. ratio in let pos = min (int_of_float ir) (len - 1) in if pos = len - 1 then Array.unsafe_set outbuf i (Array.unsafe_get inbuf (ofs + pos)) else ( let a = ir -. float pos in Array.unsafe_set outbuf i ((Array.unsafe_get inbuf (ofs + pos) *. (1. -. a)) +. (Array.unsafe_get inbuf (ofs + pos + 1) *. a))) done; outbuf) module B = struct type t = buffer let create = create let blit = blit end module Ringbuffer_ext = Ringbuffer.Make_ext (B) module Ringbuffer = Ringbuffer.Make (B) (* TODO: refined allocation/deallocation policies *) module Buffer_ext = struct type t = { mutable buffer : buffer } let prepare buf len = if length buf.buffer >= len then sub buf.buffer 0 len else ( (* TODO: optionally blit the old buffer onto the new one. *) (* let oldbuf = buf.buffer in *) let newbuf = create len in buf.buffer <- newbuf; newbuf) let create len = { buffer = create len } let length buf = length buf.buffer end module Analyze = struct let rms buf ofs len = let r = ref 0. in for i = 0 to len - 1 do let x = buf.(i + ofs) in r := !r +. (x *. x) done; sqrt (!r /. float len) module FFT = struct type t = { b : int; (* number of bits *) n : int; (* number of samples *) circle : Complex.t array; temp : Complex.t array; } let init b = let n = 1 lsl b in let h = n / 2 in let fh = float h in let circle = Array.make h Complex.zero in for i = 0 to h - 1 do let theta = pi *. float_of_int i /. fh in circle.(i) <- { Complex.re = cos theta; Complex.im = sin theta } done; { b; n; circle; temp = Array.make n Complex.zero } let length f = f.n let complex_create buf ofs len = Array.init len (fun i -> { Complex.re = buf.(ofs + i); Complex.im = 0. }) let ccoef k c = { Complex.re = k *. c.Complex.re; Complex.im = k *. c.Complex.im } let fft f d = (* TODO: greater should be ok too? *) assert (Array.length d = f.n); let ( +~ ) = Complex.add in let ( -~ ) = Complex.sub in let ( *~ ) = Complex.mul in let rec fft t (* temporary buffer *) d (* data *) s (* stride in the data array *) n (* number of samples *) = if n > 1 then ( let h = n / 2 in for i = 0 to h - 1 do t.(s + i) <- d.(s + (2 * i)); (* even *) t.(s + h + i) <- d.(s + (2 * i) + 1) (* odd *) done; fft d t s h; fft d t (s + h) h; let a = f.n / n in for i = 0 to h - 1 do let wkt = f.circle.(i * a) *~ t.(s + h + i) in d.(s + i) <- t.(s + i) +~ wkt; d.(s + h + i) <- t.(s + i) -~ wkt done) in fft f.temp d 0 f.n (* See *) module Window = struct let iter f d = let len = Array.length d in let n = float len in for i = 0 to len - 1 do let k = f (float i) n in d.(i) <- ccoef k d.(i) done let hann d = iter (fun i n -> 0.5 *. (1. -. cos (2. *. pi *. i /. n))) d let hamming d = iter (fun i n -> 0.54 *. (0.46 *. cos (2. *. pi *. i /. n))) d let cosine d = iter (fun i n -> sin (pi *. i /. n)) d let lanczos d = let sinc x = let px = pi *. x in sin px /. px in iter (fun i n -> sinc (2. *. i /. n)) d let triangular d = iter (fun i n -> if i <= n /. 2. then 2. *. i /. n else ((n /. 2.) -. i) *. 2. /. n) d let bartlett_hann d = let a0 = 0.62 in let a1 = 0.48 in let a2 = 0.38 in iter (fun i n -> a0 -. (a1 *. abs_float ((i /. n) -. 0.5)) -. (a2 *. cos (2. *. pi *. i /. n))) d let blackman ?(alpha = 0.16) d = let a = alpha in let a0 = (1. -. a) /. 2. in let a1 = 1. /. 2. in let a2 = a /. 2. in iter (fun i n -> a0 -. (a1 *. cos (2. *. pi *. i /. n)) +. (a2 *. cos (4. *. pi *. i /. n))) d (* TODO: use circle to compute cosines *) let low_res a0 a1 a2 a3 d = iter (fun i n -> a0 -. (a1 *. cos (2. *. pi *. i /. n)) +. (a2 *. cos (4. *. pi *. i /. n)) -. (a3 *. cos (6. *. pi *. i /. n))) d let nuttall d = low_res 0.355768 0.487396 0.144232 0.012604 d let blackman_harris d = low_res 0.35875 0.48829 0.14128 0.01168 d let blackman_nuttall d = low_res 0.3635819 0.4891775 0.1365995 0.0106411 d end let band_freq sr f k = float k *. float sr /. float f.n let notes sr f ?(note_min = Note.c0) ?(note_max = 128) ?(volume_min = 0.01) ?(filter_harmonics = true) buf = let len = buffer_length buf in assert (len = length f); let bdur = float len /. float sr in let fdf = float (length f) in let c = complex_create buf 0 len in fft f c; let ans = ref [] in let kstart = max 0 (int_of_float (Note.freq note_min *. bdur)) in let kend = min (len / 2) (int_of_float (Note.freq note_max *. bdur)) in for k = kstart + 1 to kend - 2 do (* Quadratic interpolation. *) let v' = Complex.norm c.(k - 1) in let v = Complex.norm c.(k) in let v'' = Complex.norm c.(k - 1) in (* Do we have a maximum here? *) if v' +. v'' < 2. *. v then ( let p = (v'' -. v') /. ((2. *. v') -. (2. *. v) +. v'') in let v = v -. ((v' -. v'') *. p /. 4.) in let v = v /. fdf in let p = p +. float k in if v >= volume_min then ans := (p, v) :: !ans) done; let ans = List.map (fun (k, v) -> (Note.of_freq (k /. bdur), v)) !ans in (* TODO: improve this filtering... *) let ans = if filter_harmonics then list_filter_ctxt (fun b (n, _) t -> let o = Note.octave n in let n = Note.name n in List.for_all (fun (n', _) -> Note.name n' <> n || Note.octave n' >= o) (b @ t)) ans else ans in ans let loudest_note l = match l with | [] -> None | h :: t -> Some (List.fold_left (fun (nmax, vmax) (n, v) -> if v > vmax then (n, v) else (nmax, vmax)) h t) end end module Effect = struct let compand_mu_law mu buf ofs len = for i = 0 to len - 1 do let bufi = buf.(i + ofs) in let sign = if bufi < 0. then -1. else 1. in buf.(i + ofs) <- sign *. log (1. +. (mu *. abs_float bufi)) /. log (1. +. mu) done class type t = object method process : buffer -> int -> int -> unit end class amplify k : t = object method process = amplify k end class clip c : t = object method process buf ofs len = for i = 0 to len - 1 do Array.unsafe_set buf (i + ofs) (max (-.c) (min c (Array.unsafe_get buf (i + ofs)))) done end Digital filter based on " Cookbook formulae for audio EQ biquad filter coefficients " by < > . URL : -EQ-Cookbook.txt coefficients" by Robert Bristow-Johnson <>. URL: -EQ-Cookbook.txt *) class biquad_filter samplerate (kind : [ `Low_pass | `High_pass | `Band_pass | `Notch | `All_pass | `Peaking | `Low_shelf | `High_shelf ]) ?(gain = 0.) freq q = let samplerate = float samplerate in object (self) val mutable p0 = 0. val mutable p1 = 0. val mutable p2 = 0. val mutable q1 = 0. val mutable q2 = 0. method private init = let w0 = 2. *. pi *. freq /. samplerate in let cos_w0 = cos w0 in let sin_w0 = sin w0 in let alpha = sin w0 /. (2. *. q) in let a = if gain = 0. then 1. else 10. ** (gain /. 40.) in let b0, b1, b2, a0, a1, a2 = match kind with | `Low_pass -> let b1 = 1. -. cos_w0 in let b0 = b1 /. 2. in (b0, b1, b0, 1. +. alpha, -2. *. cos_w0, 1. -. alpha) | `High_pass -> let b1 = 1. +. cos_w0 in let b0 = b1 /. 2. in let b1 = -.b1 in (b0, b1, b0, 1. +. alpha, -2. *. cos_w0, 1. -. alpha) | `Band_pass -> let b0 = sin_w0 /. 2. in (b0, 0., -.b0, 1. +. alpha, -2. *. cos_w0, 1. -. alpha) | `Notch -> let b1 = -2. *. cos_w0 in (1., b1, 1., 1. +. alpha, b1, 1. -. alpha) | `All_pass -> let b0 = 1. -. alpha in let b1 = -2. *. cos_w0 in let b2 = 1. +. alpha in (b0, b1, b2, b2, b1, b0) | `Peaking -> let ama = alpha *. a in let ada = alpha /. a in let b1 = -2. *. cos_w0 in (1. +. ama, b1, 1. -. ama, 1. +. ada, b1, 1. -. ada) | `Low_shelf -> let s = 2. *. sqrt a *. alpha in ( a *. (a +. 1. -. ((a -. 1.) *. cos_w0) +. s), 2. *. a *. (a -. 1. -. ((a +. 1.) *. cos_w0)), a *. (a +. 1. -. ((a -. 1.) *. cos_w0) -. s), a +. 1. +. ((a -. 1.) *. cos_w0) +. s, (-2. *. (a -. 1.)) +. ((a +. 1.) *. cos_w0), a +. 1. +. ((a -. 1.) *. cos_w0) -. s ) | `High_shelf -> let s = 2. *. sqrt a *. alpha in ( a *. (a +. 1. +. ((a -. 1.) *. cos_w0) +. s), -2. *. a *. (a -. 1. +. ((a +. 1.) *. cos_w0)), a *. (a +. 1. +. ((a -. 1.) *. cos_w0) -. s), a +. 1. -. ((a -. 1.) *. cos_w0) +. s, (2. *. (a -. 1.)) -. ((a +. 1.) *. cos_w0), a +. 1. -. ((a -. 1.) *. cos_w0) -. s ) in p0 <- b0 /. a0; p1 <- b1 /. a0; p2 <- b2 /. a0; q1 <- a1 /. a0; q2 <- a2 /. a0 initializer self#init val mutable x1 = 0. val mutable x2 = 0. val mutable y0 = 0. val mutable y1 = 0. val mutable y2 = 0. method process (buf : buffer) ofs len = for i = 0 to len - 1 do let x0 = buf.(i + ofs) in let y0 = (p0 *. x0) +. (p1 *. x1) +. (p2 *. x2) -. (q1 *. y1) -. (q2 *. y2) in buf.(i + ofs) <- y0; x2 <- x1; x1 <- x0; y2 <- y1; y1 <- y0 done end module ADSR = struct type t = int * int * float * int * Convert adsr in seconds to samples . let make sr (a, d, s, r) = ( samples_of_seconds sr a, samples_of_seconds sr d, s, samples_of_seconds sr r ) (** State in the ADSR enveloppe (A/D/S/R/dead + position in the state). *) type state = int * int let init () = (0, 0) let release (_, p) = (3, p) let dead (s, _) = s = 4 let rec process adsr st (buf : buffer) ofs len = let a, (d : int), s, (r : int) = adsr in let state, state_pos = st in match state with | 0 -> let fa = float a in for i = 0 to min len (a - state_pos) - 1 do buf.(i + ofs) <- float (state_pos + i) /. fa *. buf.(i + ofs) done; if len < a - state_pos then (0, state_pos + len) else process adsr (1, 0) buf (ofs + a - state_pos) (len - (a - state_pos)) | 1 -> let fd = float d in for i = 0 to min len (d - state_pos) - 1 do buf.(i + ofs) <- (1. -. (float (state_pos + i) /. fd *. (1. -. s))) *. buf.(i + ofs) done; if len < d - state_pos then (1, state_pos + len) else if (* Negative sustain means release immediately. *) s >= 0. then process adsr (2, 0) buf (ofs + d - state_pos) (len - (d - state_pos)) else process adsr (3, 0) buf (ofs + d - state_pos) (len - (d - state_pos)) | 2 -> amplify s buf ofs len; st | 3 -> let fr = float r in for i = 0 to min len (r - state_pos) - 1 do buf.(i + ofs) <- s *. (1. -. (float (state_pos + i) /. fr)) *. buf.(i + ofs) done; if len < r - state_pos then (3, state_pos + len) else process adsr (4, 0) buf (ofs + r - state_pos) (len - (r - state_pos)) | 4 -> clear buf ofs len; st | _ -> assert false end end module Generator = struct let white_noise buf = noise buf class type t = object method set_volume : float -> unit method set_frequency : float -> unit method fill : buffer -> int -> int -> unit method fill_add : buffer -> int -> int -> unit method release : unit method dead : bool end class virtual base sample_rate ?(volume = 1.) freq = object (self) val mutable vol = volume val mutable freq : float = freq val mutable dead = false method dead = dead method release = vol <- 0.; dead <- true method private sample_rate : int = sample_rate method private volume : float = vol method set_volume v = vol <- v method set_frequency f = freq <- f method virtual fill : buffer -> int -> int -> unit (* TODO: might be optimized by various synths *) method fill_add (buf : buffer) ofs len = let tmp = create len in self#fill tmp 0 len; add buf ofs tmp 0 len end class white_noise ?volume sr = object (self) inherit base sr ?volume 0. method fill buf ofs len = let volume = self#volume in for i = 0 to len - 1 do buf.(i + ofs) <- volume *. (Random.float 2. -. 1.) done end class sine sr ?volume ?(phase = 0.) freq = object (self) inherit base sr ?volume freq val mutable phase = phase method fill buf ofs len = let sr = float self#sample_rate in let omega = 2. *. pi *. freq /. sr in let volume = self#volume in for i = 0 to len - 1 do buf.(i + ofs) <- volume *. sin ((float i *. omega) +. phase) done; phase <- mod_float (phase +. (float len *. omega)) (2. *. pi) end class square sr ?volume ?(phase = 0.) freq = object (self) inherit base sr ?volume freq val mutable phase = phase method fill buf ofs len = let sr = float self#sample_rate in let volume = self#volume in let omega = freq /. sr in for i = 0 to len - 1 do let t = fracf ((float i *. omega) +. phase) in buf.(i + ofs) <- (if t < 0.5 then volume else -.volume) done; phase <- mod_float (phase +. (float len *. omega)) 1. end class saw sr ?volume ?(phase = 0.) freq = object (self) inherit base sr ?volume freq val mutable phase = phase method fill buf ofs len = let volume = self#volume in let sr = float self#sample_rate in let omega = freq /. sr in for i = 0 to len - 1 do let t = fracf ((float i *. omega) +. phase) in buf.(i + ofs) <- volume *. ((2. *. t) -. 1.) done; phase <- mod_float (phase +. (float len *. omega)) 1. end class triangle sr ?volume ?(phase = 0.) freq = object (self) inherit base sr ?volume freq val mutable phase = phase method fill buf ofs len = let sr = float self#sample_rate in let volume = self#volume in let omega = freq /. sr in for i = 0 to len - 1 do let t = fracf ((float i *. omega) +. phase +. 0.25) in buf.(i + ofs) <- (volume *. if t < 0.5 then (4. *. t) -. 1. else (4. *. (1. -. t)) -. 1.) done; phase <- mod_float (phase +. (float len *. omega)) 1. end class chain (g : t) (e : Effect.t) : t = object method fill buf ofs len = g#fill buf ofs len; e#process buf ofs len val tmpbuf = Buffer_ext.create 0 method fill_add (buf : buffer) ofs len = let tmpbuf = Buffer_ext.prepare tmpbuf len in g#fill tmpbuf 0 len; add buf ofs tmpbuf 0 len method set_volume = g#set_volume method set_frequency = g#set_frequency method release = g#release method dead = g#dead end class combine f (g1 : t) (g2 : t) : t = object val tmpbuf = Buffer_ext.create 0 val tmpbuf2 = Buffer_ext.create 0 method fill buf ofs len = g1#fill buf ofs len; let tmpbuf = Buffer_ext.prepare tmpbuf len in g2#fill tmpbuf 0 len; f buf ofs tmpbuf 0 len method fill_add buf ofs len = let tmpbuf = Buffer_ext.prepare tmpbuf len in g1#fill tmpbuf 0 len; let tmpbuf2 = Buffer_ext.prepare tmpbuf2 len in g2#fill tmpbuf2 0 len; f tmpbuf 0 tmpbuf2 0 len; add buf ofs tmpbuf 0 len method set_volume v = g1#set_volume v; g2#set_volume v method set_frequency v = g1#set_frequency v; g2#set_frequency v method release = g1#release; g2#release method dead = g1#dead && g2#dead end class add g1 g2 = object inherit combine add g1 g2 end class mult g1 g2 = object inherit combine mult g1 g2 end class adsr (adsr : Effect.ADSR.t) (g : t) = object (self) val mutable adsr_st = Effect.ADSR.init () val tmpbuf = Buffer_ext.create 0 method set_volume = g#set_volume method set_frequency = g#set_frequency method fill buf ofs len = g#fill buf ofs len; adsr_st <- Effect.ADSR.process adsr adsr_st buf ofs len method fill_add buf ofs len = let tmpbuf = Buffer_ext.prepare tmpbuf len in self#fill tmpbuf 0 len; blit tmpbuf 0 buf ofs len method release = adsr_st <- Effect.ADSR.release adsr_st; g#release method dead = Effect.ADSR.dead adsr_st || g#dead end end end (** An audio buffer. *) type t = Mono.buffer array type buffer = t (** Iterate a function on each channel of the buffer. *) let iter f data offset length = Array.iter (fun b -> f b offset length) data let create chans n = Array.init chans (fun _ -> Mono.create n) let make chans n x = Array.init chans (fun _ -> Mono.make n x) let channels data = Array.length data let length = function [||] -> 0 | a -> Array.length a.(0) let create_same buf = create (channels buf) (length buf) (* TODO: in C *) let interleave data length offset = let chans = Array.length data in let ibuf = Mono.create (chans * length) in for c = 0 to chans - 1 do let bufc = data.(c) in for i = 0 to length - 1 do ibuf.((chans * i) + c) <- bufc.(offset + i) done done; ibuf (* TODO: in C *) let deinterleave chans ibuf ofs len = let len = len / chans in let buf = create chans len in for c = 0 to chans - 1 do let bufc = buf.(c) in for i = 0 to len - 1 do bufc.(i) <- ibuf.((chans * i) + c + ofs) done done; buf let append b1 ofs1 len1 b2 ofs2 len2 = Array.mapi (fun i b -> Mono.append b ofs1 len2 b2.(i) ofs2 len1) b1 let clear = iter Mono.clear let clip = iter Mono.clip let noise = iter Mono.noise let copy b ofs len = Array.init (Array.length b) (fun i -> Mono.copy b.(i) ofs len) let blit b1 ofs1 b2 ofs2 len = Array.iteri (fun i b -> Mono.blit b ofs1 b2.(i) ofs2 len) b1 let sub b ofs len = Array.map (fun b -> Array.sub b ofs len) b let squares data offset length = Array.fold_left (fun squares buf -> squares +. Mono.squares buf offset length) 0. data let to_mono b ofs len = let channels = channels b in if channels = 1 then Array.sub b.(0) ofs len else ( let chans = float channels in let ans = Mono.create len in Mono.clear ans 0 len; for i = 0 to len - 1 do for c = 0 to channels - 1 do ans.(i) <- ans.(i) +. b.(c).(i + ofs) done; ans.(i) <- ans.(i) /. chans done; ans) let of_mono b = [| b |] let resample ?mode ratio data offset length = Array.map (fun buf -> Mono.resample ?mode ratio buf offset length) data let copy_from_ba ba buf ofs len = Array.iteri (fun i b -> Mono.copy_from_ba ba.(i) b ofs len) buf let copy_to_ba buf ofs len ba = Array.iteri (fun i b -> Mono.copy_to_ba buf.(i) ofs len b) ba let of_ba = Array.map Mono.of_ba let to_ba buf ofs len = Array.map (fun b -> Mono.to_ba b ofs len) buf module U8 = struct let size channels samples = channels * samples external of_audio : buffer -> int -> Bytes.t -> int -> int -> unit = "caml_mm_audio_to_u8" external to_audio : string -> int -> buffer -> int -> int -> unit = "caml_mm_audio_of_u8" end external to_s16 : bool -> buffer -> int -> Bytes.t -> int -> int -> unit = "caml_mm_audio_to_s16_byte" "caml_mm_audio_to_s16" external convert_s16 : bool -> string -> int -> buffer -> int -> int -> unit = "caml_mm_audio_convert_s16_byte" "caml_mm_audio_convert_s16" module S16LE = struct let size channels samples = channels * samples * 2 let length channels len = len / (2 * channels) let of_audio = to_s16 true let make buf ofs len = let slen = size (channels buf) len in let sbuf = Bytes.create slen in of_audio buf ofs sbuf 0 len; Bytes.unsafe_to_string sbuf let to_audio = convert_s16 true end module S16BE = struct let size channels samples = channels * samples * 2 let length channels len = len / (2 * channels) let of_audio = to_s16 false let make buf ofs len = let slen = size (channels buf) len in let sbuf = Bytes.create slen in of_audio buf ofs sbuf 0 len; Bytes.unsafe_to_string sbuf let to_audio = convert_s16 false end module S24LE = struct let size channels samples = channels * samples * 3 external of_audio : buffer -> int -> Bytes.t -> int -> int -> unit = "caml_mm_audio_to_s24le" external to_audio : string -> int -> buffer -> int -> int -> unit = "caml_mm_audio_convert_s24le" end module S32LE = struct let size channels samples = channels * samples * 4 external of_audio : buffer -> int -> Bytes.t -> int -> int -> unit = "caml_mm_audio_to_s32le" external to_audio : string -> int -> buffer -> int -> int -> unit = "caml_mm_audio_convert_s32le" end let add b1 ofs1 b2 ofs2 len = Array.iteri (fun i b -> Mono.add b ofs1 b2.(i) ofs2 len) b1 let add_coeff b1 ofs1 k b2 ofs2 len = Array.iteri (fun i b -> Mono.add_coeff b ofs1 k b2.(i) ofs2 len) b1 let amplify k data offset length = if k <> 1. then Array.iter (fun data -> Mono.amplify k data offset length) data x between -1 and 1 let pan x buf offset length = if x > 0. then ( let x = 1. -. x in Mono.amplify x buf.(0) offset length) else if x < 0. then ( let x = 1. +. x in Mono.amplify x buf.(1) offset length) (* TODO: we cannot share this with mono, right? *) module Buffer_ext = struct type t = { mutable buffer : buffer } let chans = channels let prepare buf ?channels len = match channels with | Some channels when chans buf.buffer <> channels -> let newbuf = create channels len in buf.buffer <- newbuf; newbuf | _ -> if length buf.buffer >= len then sub buf.buffer 0 len else ( (* TODO: optionally blit the old buffer onto the new one. *) let oldbuf = buf.buffer in let newbuf = create (chans oldbuf) len in buf.buffer <- newbuf; newbuf) let create chans len = { buffer = create chans len } end (* TODO: share code with ringbuffer module! *) module Ringbuffer = struct type t = { size : int; buffer : buffer; mutable rpos : int; (** current read position *) mutable wpos : int; (** current write position *) } let create chans size = { size + 1 so we can store full buffers , while keeping rpos and wpos different for implementation matters rpos and wpos different for implementation matters *) size = size + 1; buffer = create chans (size + 1); rpos = 0; wpos = 0; } let channels t = channels t.buffer let read_space t = if t.wpos >= t.rpos then t.wpos - t.rpos else t.size - (t.rpos - t.wpos) let write_space t = if t.wpos >= t.rpos then t.size - (t.wpos - t.rpos) - 1 else t.rpos - t.wpos - 1 let read_advance t n = assert (n <= read_space t); if t.rpos + n < t.size then t.rpos <- t.rpos + n else t.rpos <- t.rpos + n - t.size let write_advance t n = assert (n <= write_space t); if t.wpos + n < t.size then t.wpos <- t.wpos + n else t.wpos <- t.wpos + n - t.size let peek t buf = let len = length buf in assert (len <= read_space t); let pre = t.size - t.rpos in let extra = len - pre in if extra > 0 then ( blit t.buffer t.rpos buf 0 pre; blit t.buffer 0 buf pre extra) else blit t.buffer t.rpos buf 0 len let read t buf = peek t buf; read_advance t (length buf) let write t buf = let len = length buf in assert (len <= write_space t); let pre = t.size - t.wpos in let extra = len - pre in if extra > 0 then ( blit buf 0 t.buffer t.wpos pre; blit buf pre t.buffer 0 extra) else blit buf 0 t.buffer t.wpos len; write_advance t len let transmit t f = if t.wpos = t.rpos then 0 else ( let len0 = if t.wpos >= t.rpos then t.wpos - t.rpos else t.size - t.rpos in let len = f (sub t.buffer t.rpos len0) in assert (len <= len0); read_advance t len; len) end module Ringbuffer_ext = struct type t = { mutable ringbuffer : Ringbuffer.t } let prepare buf len = if Ringbuffer.write_space buf.ringbuffer >= len then buf.ringbuffer else ( let rb = Ringbuffer.create (Ringbuffer.channels buf.ringbuffer) (Ringbuffer.read_space buf.ringbuffer + len) in while Ringbuffer.read_space buf.ringbuffer <> 0 do ignore (Ringbuffer.transmit buf.ringbuffer (fun buf -> Ringbuffer.write rb buf; length buf)) done; buf.ringbuffer <- rb; rb) let channels rb = Ringbuffer.channels rb.ringbuffer let peek rb = Ringbuffer.peek rb.ringbuffer let read rb = Ringbuffer.read rb.ringbuffer let write rb buf = let rb = prepare rb (length buf) in Ringbuffer.write rb buf let transmit rb = Ringbuffer.transmit rb.ringbuffer let read_space rb = Ringbuffer.read_space rb.ringbuffer let write_space rb = Ringbuffer.write_space rb.ringbuffer let read_advance rb = Ringbuffer.read_advance rb.ringbuffer let write_advance rb = Ringbuffer.write_advance rb.ringbuffer let create chans len = { ringbuffer = Ringbuffer.create chans len } end module Analyze = struct let rms buf ofs len = Array.init (channels buf) (fun i -> Mono.Analyze.rms buf.(i) ofs len) (* See *) (* See *) (** Replaygain computations. *) module ReplayGain = struct type t = { channels : int; mutable frame_pos : int; frame_length : int; prefilter : float array -> float array; mutable peak : float; mutable rms : float; histogram : int array; } exception Not_supported let histogram_slots = 12000 (** Create internal state. *) let create = let coeffs = [ ( 48000, ( [| 1.00000000000000; -3.84664617118067; 7.81501653005538; -11.34170355132042; 13.05504219327545; -12.28759895145294; 9.48293806319790; -5.87257861775999; 2.75465861874613; -0.86984376593551; 0.13919314567432; |], [| 0.03857599435200; -0.02160367184185; -0.00123395316851; -0.00009291677959; -0.01655260341619; 0.02161526843274; -0.02074045215285; 0.00594298065125; 0.00306428023191; 0.00012025322027; 0.00288463683916; |], [| 1.00000000000000; -1.97223372919527; 0.97261396931306 |], [| 0.98621192462708; -1.97242384925416; 0.98621192462708 |] ) ); ( 44100, ( [| 1.00000000000000; -3.47845948550071; 6.36317777566148; -8.54751527471874; 9.47693607801280; -8.81498681370155; 6.85401540936998; -4.39470996079559; 2.19611684890774; -0.75104302451432; 0.13149317958808; |], [| 0.05418656406430; -0.02911007808948; -0.00848709379851; -0.00851165645469; -0.00834990904936; 0.02245293253339; -0.02596338512915; 0.01624864962975; -0.00240879051584; 0.00674613682247; -0.00187763777362; |], [| 1.00000000000000; -1.96977855582618; 0.97022847566350 |], [| 0.98500175787242; -1.97000351574484; 0.98500175787242 |] ) ); ( 22050, ( [| 1.00000000000000; -1.49858979367799; 0.87350271418188; 0.12205022308084; -0.80774944671438; 0.47854794562326; -0.12453458140019; -0.04067510197014; 0.08333755284107; -0.04237348025746; 0.02977207319925; |], [| 0.33642304856132; -0.25572241425570; -0.11828570177555; 0.11921148675203; -0.07834489609479; -0.00469977914380; -0.00589500224440; 0.05724228140351; 0.00832043980773; -0.01635381384540; -0.01760176568150; |], [| 1.00000000000000; -1.94561023566527; 0.94705070426118 |], [| 0.97316523498161; -1.94633046996323; 0.97316523498161 |] ) ); ] in fun ~channels ~samplerate -> Frame length in samples ( a frame is 50 ms ) . let frame_length = samplerate * 50 / 1000 in Coefficients of the Yulewalk and Butterworth filters . let yule_a, yule_b, butter_a, butter_b = match List.assoc_opt samplerate coeffs with | Some c -> c | None -> raise Not_supported in let yulewalk = Array.init channels (fun _ -> Sample.iir yule_a yule_b) in let butterworth = Array.init channels (fun _ -> Sample.iir butter_a butter_b) in let prefilter x = Array.mapi (fun i x -> x |> yulewalk.(i) |> butterworth.(i)) x in { channels; frame_pos = 0; frame_length; prefilter; peak = 0.; rms = 0.; histogram = Array.make histogram_slots 0; } (** Process a sample. *) let process_sample rg x = Array.iter (fun x -> let x = abs_float x in if x > rg.peak then rg.peak <- x) x; let x = rg.prefilter x in Array.iter (fun x -> rg.rms <- rg.rms +. (x *. x)) x; rg.frame_pos <- rg.frame_pos + 1; if rg.frame_pos >= rg.frame_length then ( Minimum value is about -100 dB for digital silence . The 90 dB offset is to compensate for the normalized float range and 3 dB is for stereo samples . offset is to compensate for the normalized float range and 3 dB is for stereo samples. *) let rms = (10. *. log10 (rg.rms /. float (rg.frame_length * rg.channels))) +. 90. in let level = int_of_float (100. *. rms) |> max 0 |> min (histogram_slots - 1) in rg.histogram.(level) <- rg.histogram.(level) + 1; rg.rms <- 0.; rg.frame_pos <- 0) (** Process a buffer. *) let process rg buf off len = assert (channels buf = rg.channels); for i = off to off + len - 1 do let x = Array.init rg.channels (fun c -> buf.(c).(i)) in process_sample rg x done (** Computed peak. *) let peak rg = rg.peak (** Compute gain. *) let gain rg = let windows = Array.fold_left ( + ) 0 rg.histogram in let i = ref (histogram_slots - 1) in let loud_count = ref 0 in Find i below the top 5 % while !i > 0 && !loud_count * 20 < windows do loud_count := !loud_count + rg.histogram.(!i); decr i done; 64.54 -. (float !i /. 100.) |> max (-24.) |> min 64. end end module Effect = struct class type t = object method process : buffer -> int -> int -> unit end class chain (e1 : t) (e2 : t) = object method process buf ofs len = e1#process buf ofs len; e2#process buf ofs len end class of_mono chans (g : unit -> Mono.Effect.t) = object val g = Array.init chans (fun _ -> g ()) method process buf ofs len = for c = 0 to chans - 1 do g.(c)#process buf.(c) ofs len done end class biquad_filter chans samplerate kind ?gain freq q = of_mono chans (fun () -> (new Mono.Effect.biquad_filter samplerate kind ?gain freq q :> Mono.Effect.t)) class type delay_t = object inherit t method set_delay : float -> unit method set_feedback : float -> unit end class delay_only chans sample_rate delay = let delay = int_of_float (float sample_rate *. delay) in object val mutable delay = delay method set_delay d = delay <- int_of_float (float sample_rate *. d) val rb = Ringbuffer_ext.create chans 0 initializer Ringbuffer_ext.write rb (create chans delay) method process buf ofs len = Ringbuffer_ext.write rb (sub buf ofs len); Ringbuffer_ext.read rb (sub buf ofs len) end class delay chans sample_rate delay once feedback = let delay = int_of_float (float sample_rate *. delay) in object val mutable delay = delay method set_delay d = delay <- int_of_float (float sample_rate *. d) val mutable feedback = feedback method set_feedback f = feedback <- f val rb = Ringbuffer_ext.create chans 0 val tmpbuf = Buffer_ext.create chans 0 method process buf ofs len = if once then Ringbuffer_ext.write rb buf; (* Make sure that we have a past of exactly d samples. *) if Ringbuffer_ext.read_space rb < delay then Ringbuffer_ext.write rb (create chans delay); if Ringbuffer_ext.read_space rb > delay then Ringbuffer_ext.read_advance rb (Ringbuffer_ext.read_space rb - delay); if len > delay then add_coeff buf delay feedback buf ofs (len - delay); let rlen = min delay len in let tmpbuf = Buffer_ext.prepare tmpbuf rlen in Ringbuffer_ext.read rb (sub tmpbuf 0 rlen); add_coeff buf 0 feedback tmpbuf 0 rlen; if not once then Ringbuffer_ext.write rb buf end class delay_ping_pong chans sample_rate delay once feedback = let r1 = new delay_only 1 sample_rate delay in let d1 = new delay 1 sample_rate (2. *. delay) once feedback in let d1' = new chain (r1 :> t) (d1 :> t) in let d2 = new delay 1 sample_rate (2. *. delay) once feedback in object initializer assert (chans = 2) method set_delay d = r1#set_delay d; d1#set_delay (2. *. d); d2#set_delay (2. *. d) method set_feedback f = d1#set_feedback f; d2#set_feedback f method process buf ofs len = assert (channels buf = 2); (* Add original on channel 0. *) d1'#process [| buf.(0) |] ofs len; d2#process [| buf.(1) |] ofs len end let delay chans sample_rate d ?(once = false) ?(ping_pong = false) feedback = if ping_pong then new delay_ping_pong chans sample_rate d once feedback else new delay chans sample_rate d once feedback (* See #169 *) times in sec , ratios in dB , gain linear class compress ?(attack = 0.1) ?(release = 0.1) ?(threshold = -10.) ?(ratio = 3.) ?(knee = 1.) ?(rms_window = 0.1) ?(gain = 1.) chans samplerate = (* Number of samples for computing rms. *) let rmsn = samples_of_seconds samplerate rms_window in let samplerate = float samplerate in object val mutable attack = attack method set_attack a = attack <- a val mutable release = release method set_release r = release <- r val mutable threshold = threshold method set_threshold t = threshold <- t val mutable ratio = ratio method set_ratio r = ratio <- r val mutable knee = knee method set_knee k = knee <- k val mutable gain = gain method set_gain g = gain <- g (* [rmsn] last squares. *) val rmsv = Array.make rmsn 0. (* Current position in [rmsv]. *) val mutable rmsp = 0 Current squares of RMS . val mutable rms = 0. (* Processing variables. *) val mutable amp = 0. (* Envelope. *) val mutable env = 0. (* Current gain. *) val mutable g = 1. method process (buf : buffer) ofs len = let ratio = (ratio -. 1.) /. ratio in (* Attack and release "per sample decay". *) let g_attack = if attack = 0. then 0. else exp (-1. /. (samplerate *. attack)) in let ef_a = g_attack *. 0.25 in let g_release = if release = 0. then 0. else exp (-1. /. (samplerate *. release)) in let ef_ai = 1. -. ef_a in (* Knees. *) let knee_min = lin_of_dB (threshold -. knee) in let knee_max = lin_of_dB (threshold +. knee) in for i = 0 to len - 1 do (* Input level. *) let lev_in = let ans = ref 0. in for c = 0 to chans - 1 do let x = buf.(c).(i + ofs) *. gain in ans := !ans +. (x *. x) done; !ans /. float chans in (* RMS *) rms <- rms -. rmsv.(rmsp) +. lev_in; rms <- abs_float rms; (* Sometimes the rms was -0., avoid that. *) rmsv.(rmsp) <- lev_in; rmsp <- (rmsp + 1) mod rmsn; amp <- sqrt (rms /. float rmsn); Dynamic selection : attack or release ? (* Smoothing with capacitor, envelope extraction... Here be aware of * pIV denormal numbers glitch. *) if amp > env then env <- (env *. g_attack) +. (amp *. (1. -. g_attack)) else env <- (env *. g_release) +. (amp *. (1. -. g_release)); (* Compute the gain. *) let gain_t = if env < knee_min then (* Do not compress. *) 1. else if env < knee_max then ( (* Knee: compress smoothly. *) let x = (knee +. dB_of_lin env -. threshold) /. (2. *. knee) in lin_of_dB (0. -. (knee *. ratio *. x *. x))) else Maximal ( n:1 ) compression . lin_of_dB ((threshold -. dB_of_lin env) *. ratio) in g <- (g *. ef_a) +. (gain_t *. ef_ai); (* Apply the gain. *) let g = g *. gain in for c = 0 to chans - 1 do buf.(c).(i + ofs) <- buf.(c).(i + ofs) *. g done (* (* Debug messages. *) count <- count + 1; if count mod 10000 = 0 then self#log#f 4 "RMS:%7.02f Env:%7.02f Gain: %4.02f\r%!" (Audio.dB_of_lin amp) (Audio.dB_of_lin env) gain *) done method reset = rms <- 0.; rmsp <- 0; for i = 0 to rmsn - 1 do rmsv.(i) <- 0. done; g <- 1.; env <- 0.; amp <- 0. end target RMS duration of the RMS collection in seconds speed when volume is going up in coeff per sec (* speed when volume is going down *) rms_threshold (* RMS threshold under which the volume should not be changed *) vol_init (* initial volume *) vol_min (* minimal gain *) vol_max (* maximal gain *) = let rms_len = samples_of_seconds samplerate rms_len in let rms_lenf = float rms_len in (* TODO: is this the right conversion? *) let kup = kup ** seconds_of_samples samplerate rms_len in let kdown = kdown ** seconds_of_samples samplerate rms_len in object (** Square of the currently computed rms. *) val mutable rms = Array.make channels 0. (** Number of samples collected so far. *) val mutable rms_collected = 0 (** Current volume. *) val mutable vol = vol_init (** Previous value of volume. *) val mutable vol_old = vol_init (** Is it enabled? (disabled if below the threshold) *) val mutable enabled = true method process (buf : buffer) ofs len = for c = 0 to channels - 1 do let bufc = buf.(c) in for i = 0 to len - 1 do let bufci = bufc.(ofs + i) in if rms_collected >= rms_len then ( let rms_cur = let ans = ref 0. in for c = 0 to channels - 1 do ans := !ans +. rms.(c) done; sqrt (!ans /. float channels) in rms <- Array.make channels 0.; rms_collected <- 0; enabled <- rms_cur >= rms_threshold; if enabled then ( let vol_opt = rmst /. rms_cur in vol_old <- vol; if rms_cur < rmst then vol <- vol +. (kup *. (vol_opt -. vol)) else vol <- vol +. (kdown *. (vol_opt -. vol)); vol <- max vol_min vol; vol <- min vol_max vol)); rms.(c) <- rms.(c) +. (bufci *. bufci); rms_collected <- rms_collected + 1; Affine transition between vol_old and vol . bufc.(i) <- (vol_old +. (float rms_collected /. rms_lenf *. (vol -. vol_old))) *. bufci done done end (* TODO: check default parameters. *) let auto_gain_control channels samplerate ?(rms_target = 1.) ?(rms_window = 0.2) ?(kup = 0.6) ?(kdown = 0.8) ?(rms_threshold = 0.01) ?(volume_init = 1.) ?(volume_min = 0.1) ?(volume_max = 10.) () = new auto_gain_control channels samplerate rms_target rms_window kup kdown rms_threshold volume_init volume_min volume_max (* module ADSR = struct type t = Mono.Effect.ADSR.t type state = Mono.Effect.ADSR.state end *) end module Generator = struct let white_noise buf ofs len = for c = 0 to channels buf - 1 do Mono.Generator.white_noise buf.(c) ofs len done class type t = object method set_volume : float -> unit method set_frequency : float -> unit method release : unit method dead : bool method fill : buffer -> int -> int -> unit method fill_add : buffer -> int -> int -> unit end class of_mono (g : Mono.Generator.t) = object val tmpbuf = Mono.Buffer_ext.create 0 method set_volume = g#set_volume method set_frequency = g#set_frequency method fill buf ofs len = g#fill buf.(0) ofs len; for c = 1 to channels buf - 1 do Mono.blit buf.(0) ofs buf.(c) ofs len done method fill_add (buf : buffer) ofs len = let tmpbuf = Mono.Buffer_ext.prepare tmpbuf len in g#fill tmpbuf 0 len; for c = 0 to channels buf - 1 do Mono.add buf.(c) ofs tmpbuf 0 len done method release = g#release method dead = g#dead end class chain (g : t) (e : Effect.t) : t = object method fill buf ofs len = g#fill buf ofs len; e#process buf ofs len val tmpbuf = Buffer_ext.create 0 0 method fill_add buf ofs len = let tmpbuf = Buffer_ext.prepare tmpbuf ~channels:(channels buf) len in g#fill tmpbuf 0 len; add buf ofs tmpbuf 0 len method set_volume = g#set_volume method set_frequency = g#set_frequency method release = g#release method dead = g#dead end end module IO = struct exception Invalid_file exception Invalid_operation exception End_of_stream module Reader = struct class type t = object method channels : int method sample_rate : int method length : int method duration : float method seek : int -> unit method close : unit method read : buffer -> int -> int -> int end class virtual base = object (self) method virtual channels : int method virtual sample_rate : int method virtual length : int method duration = float self#length /. float self#sample_rate (* method virtual seek : int -> unit method virtual close : unit method virtual read : buffer -> int -> int -> int *) end (* TODO: handle more formats... *) class virtual wav = object (self) inherit IO.helper method virtual private stream_close : unit method virtual private stream_seek : int -> unit method virtual private stream_cur_pos : int val mutable sample_rate = 0 val mutable channels = 0 (* Size of a sample in bits. *) val mutable sample_size = 0 val mutable bytes_per_sample = 0 (* Length in samples. *) val mutable length = 0 val mutable data_offset = 0 method sample_rate = sample_rate method channels = channels method length = length initializer if self#input 4 <> "RIFF" then failwith " Bad header : \"RIFF\ " not found " ; raise Invalid_file; (* Ignore the file size *) ignore (self#input 4); if self#input 8 <> "WAVEfmt " then failwith " Bad header : \"WAVEfmt \ " not found " ; raise Invalid_file; Now we always have the following uninteresting bytes : * 0x10 0x00 0x00 0x00 0x01 0x00 * 0x10 0x00 0x00 0x00 0x01 0x00 *) ignore (self#really_input 6); channels <- self#input_short; sample_rate <- self#input_int; byt_per_sec (* byt_per_samp *) ignore self#input_short; sample_size <- self#input_short; let section = self#really_input 4 in if section <> "data" then ( if section = "INFO" then failwith " Valid wav file but unread " ; raise Invalid_file; failwith " Bad header : string \"data\ " not found " raise Invalid_file); let len_dat = self#input_int in data_offset <- self#stream_cur_pos; bytes_per_sample <- sample_size / 8 * channels; length <- len_dat / bytes_per_sample method read (buf : buffer) ofs len = let sbuflen = len * channels * 2 in let sbuf = self#input sbuflen in let sbuflen = String.length sbuf in let len = sbuflen / (channels * 2) in begin match sample_size with | 16 -> S16LE.to_audio sbuf 0 buf ofs len | 8 -> U8.to_audio sbuf 0 buf ofs len | _ -> assert false end; len method seek n = let n = data_offset + (n * bytes_per_sample) in self#stream_seek n method close = self#stream_close end class of_wav_file fname = object inherit IO.Unix.rw ~read:true fname inherit base inherit wav end end module Writer = struct class type t = object method write : buffer -> int -> int -> unit method close : unit end class virtual base chans sr = object method private channels : int = chans method private sample_rate : int = sr end class virtual wav = object (self) inherit IO.helper method virtual private stream_write : string -> int -> int -> int method virtual private stream_seek : int -> unit method virtual private stream_close : unit method virtual private channels : int method virtual private sample_rate : int initializer let bits_per_sample = 16 in (* RIFF *) self#output "RIFF"; self#output_int 0; self#output "WAVE"; (* Format *) self#output "fmt "; self#output_int 16; self#output_short 1; self#output_short self#channels; self#output_int self#sample_rate; self#output_int (self#sample_rate * self#channels * bits_per_sample / 8); self#output_short (self#channels * bits_per_sample / 8); self#output_short bits_per_sample; (* Data *) self#output "data"; (* size of the data, to be updated afterwards *) self#output_short 0xffff; self#output_short 0xffff val mutable datalen = 0 method write buf ofs len = let s = S16LE.make buf ofs len in self#output s; datalen <- datalen + String.length s method close = self#stream_seek 4; self#output_int (36 + datalen); self#stream_seek 40; self#output_int datalen; self#stream_close end class to_wav_file chans sr fname = object inherit base chans sr inherit IO.Unix.rw ~write:true fname inherit wav end end module RW = struct class type t = object method read : buffer -> int -> int -> unit method write : buffer -> int -> int -> unit method close : unit end class virtual bufferized channels ~min_duration ~fill_duration ~max_duration ~drop_duration = object method virtual io_read : buffer -> unit method virtual io_write : buffer -> unit initializer assert (fill_duration <= max_duration); assert (drop_duration <= max_duration) val rb = Ringbuffer.create channels max_duration method read buf = let len = length buf in let rs = Ringbuffer.read_space rb in if rs < min_duration + len then ( let ps = min_duration + len - rs in Ringbuffer.write rb (create channels ps)); Ringbuffer.read rb buf method write buf = let len = length buf in let ws = Ringbuffer.write_space rb in if ws + len > max_duration then Ringbuffer.read_advance rb (ws - drop_duration); Ringbuffer.write rb buf end end end
null
https://raw.githubusercontent.com/savonet/ocaml-mm/f931d881512cf3a74399c261aa5877fb69bfe524/src/audio.ml
ocaml
TODO: - lots of functions require offset and length whereas in most cases we want to apply the operations on the whole buffers -> labeled optional arguments? - do we want to pass samplerate as an argument or to store it in buffers? * Fractional part of a float. TODO: sharps and flats TODO: refined allocation/deallocation policies TODO: optionally blit the old buffer onto the new one. let oldbuf = buf.buffer in number of bits number of samples TODO: greater should be ok too? temporary buffer data stride in the data array number of samples even odd See TODO: use circle to compute cosines Quadratic interpolation. Do we have a maximum here? TODO: improve this filtering... * State in the ADSR enveloppe (A/D/S/R/dead + position in the state). Negative sustain means release immediately. TODO: might be optimized by various synths * An audio buffer. * Iterate a function on each channel of the buffer. TODO: in C TODO: in C TODO: we cannot share this with mono, right? TODO: optionally blit the old buffer onto the new one. TODO: share code with ringbuffer module! * current read position * current write position See See * Replaygain computations. * Create internal state. * Process a sample. * Process a buffer. * Computed peak. * Compute gain. Make sure that we have a past of exactly d samples. Add original on channel 0. See #169 Number of samples for computing rms. [rmsn] last squares. Current position in [rmsv]. Processing variables. Envelope. Current gain. Attack and release "per sample decay". Knees. Input level. RMS Sometimes the rms was -0., avoid that. Smoothing with capacitor, envelope extraction... Here be aware of * pIV denormal numbers glitch. Compute the gain. Do not compress. Knee: compress smoothly. Apply the gain. (* Debug messages. speed when volume is going down RMS threshold under which the volume should not be changed initial volume minimal gain maximal gain TODO: is this the right conversion? * Square of the currently computed rms. * Number of samples collected so far. * Current volume. * Previous value of volume. * Is it enabled? (disabled if below the threshold) TODO: check default parameters. module ADSR = struct type t = Mono.Effect.ADSR.t type state = Mono.Effect.ADSR.state end method virtual seek : int -> unit method virtual close : unit method virtual read : buffer -> int -> int -> int TODO: handle more formats... Size of a sample in bits. Length in samples. Ignore the file size byt_per_samp RIFF Format Data size of the data, to be updated afterwards
* Copyright 2011 The Savonet Team * * This file is part of ocaml - mm . * * is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * * As a special exception to the GNU Library General Public License , you may * link , statically or dynamically , a " work that uses the Library " with a publicly * distributed version of the Library to produce an executable file containing * portions of the Library , and distribute that executable file under terms of * your choice , without any of the additional requirements listed in clause 6 * of the GNU Library General Public License . * By " a publicly distributed version of the Library " , we mean either the unmodified * Library as distributed by The Savonet Team , or a modified version of the Library that is * distributed under the conditions defined in clause 3 of the GNU Library General * Public License . This exception does not however invalidate any other reasons why * the executable file might be covered by the GNU Library General Public License . * * Copyright 2011 The Savonet Team * * This file is part of ocaml-mm. * * ocaml-mm is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * ocaml-mm 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 Lesser General Public License * along with ocaml-mm; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * As a special exception to the GNU Library General Public License, you may * link, statically or dynamically, a "work that uses the Library" with a publicly * distributed version of the Library to produce an executable file containing * portions of the Library, and distribute that executable file under terms of * your choice, without any of the additional requirements listed in clause 6 * of the GNU Library General Public License. * By "a publicly distributed version of the Library", we mean either the unmodified * Library as distributed by The Savonet Team, or a modified version of the Library that is * distributed under the conditions defined in clause 3 of the GNU Library General * Public License. This exception does not however invalidate any other reasons why * the executable file might be covered by the GNU Library General Public License. * *) open Mm_base let list_filter_ctxt f l = let rec aux b = function | [] -> [] | h :: t -> if f b h t then h :: aux (b @ [h]) t else aux (b @ [h]) t in aux [] l let pi = 3.14159265358979323846 let lin_of_dB x = 10. ** (x /. 20.) let dB_of_lin x = 20. *. log x /. log 10. let fracf x = if x < 1. then x else if x < 2. then x -. 1. else fst (modf x) let samples_of_seconds sr t = int_of_float (float sr *. t) let seconds_of_samples sr n = float n /. float sr module Note = struct A4 = 69 type t = int let a4 = 69 let c5 = 72 let c0 = 12 let create name oct = name + (12 * (oct + 1)) let freq n = 440. *. (2. ** ((float n -. 69.) /. 12.)) let of_freq f = int_of_float (0.5 +. ((12. *. log (f /. 440.) /. log 2.) +. 69.)) let name n = n mod 12 let octave n = (n / 12) - 1 let modulo n = (name n, octave n) let to_string n = let n, o = modulo n in (match n with | 0 -> "A" | 1 -> "A#" | 2 -> "B" | 3 -> "C" | 4 -> "C#" | 5 -> "D" | 6 -> "D#" | 7 -> "E" | 8 -> "F" | 9 -> "F#" | 10 -> "G" | 11 -> "G#" | _ -> assert false) ^ " " ^ string_of_int o let of_string s = assert (String.length s >= 2); let note = String.sub s 0 (String.length s - 1) in let oct = int_of_char s.[String.length s - 1] - int_of_char '0' in let off = match note with | "a" | "A" -> 0 | "b" | "B" -> 2 | "c" | "C" -> 3 | "d" | "D" -> 5 | "e" | "E" -> 7 | "f" | "F" -> 8 | "g" | "G" -> 10 | _ -> raise Not_found in 64 + (12 * (oct - 4)) + off end module Sample = struct type t = float let clip x = let x = max (-1.) x in let x = min 1. x in x let iir a b = let na = Array.length a in let nb = Array.length b in assert (a.(0) = 1.); let x = Array.make nb 0. in let y = Array.make na 0. in let ka = ref 0 in let kb = ref 0 in fun x0 -> let y0 = ref 0. in x.(!kb) <- x0; for i = 0 to nb - 1 do y0 := !y0 +. (b.(i) *. x.((!kb + i) mod nb)) done; for i = 1 to na - 1 do y0 := !y0 -. (a.(i) *. y.((!ka + i) mod na)) done; if na > 0 then y.(!ka) <- !y0; let decr n k = decr k; if !k < 0 then k := !k + n in decr na ka; decr nb kb; !y0 let fir b = iir [||] b end module Mono = struct type t = float array type buffer = t let create = Array.create_float let length = Array.length let buffer_length = length let clear data ofs len = Array.fill data ofs len 0. let make n (x : float) = Array.make n x let sub = Array.sub let blit = Array.blit let copy src ofs len = let dst = create len in blit src ofs dst 0 len; dst external copy_from_ba : (float, Bigarray.float32_elt, Bigarray.c_layout) Bigarray.Array1.t -> float array -> int -> int -> unit = "caml_mm_audio_copy_from_ba" external copy_to_ba : float array -> int -> int -> (float, Bigarray.float32_elt, Bigarray.c_layout) Bigarray.Array1.t -> unit = "caml_mm_audio_copy_to_ba" let of_ba buf = let len = Bigarray.Array1.dim buf in let dst = Array.create_float len in copy_from_ba buf dst 0 len; dst let to_ba buf ofs len = let ba = Bigarray.Array1.create Bigarray.float32 Bigarray.c_layout len in copy_to_ba buf ofs len ba; ba let append b1 ofs1 len1 b2 ofs2 len2 = assert (length b1 - ofs1 >= len1); assert (length b2 - ofs2 >= len2); let data = Array.create_float (len1 + len2) in Array.blit b1 ofs1 data 0 len1; Array.blit b2 ofs2 data len1 len2; data let add b1 ofs1 b2 ofs2 len = assert (length b1 - ofs1 >= len); assert (length b2 - ofs2 >= len); for i = 0 to len - 1 do Array.unsafe_set b1 (ofs1 + i) (Array.unsafe_get b1 (ofs1 + i) +. Array.unsafe_get b2 (ofs2 + i)) done let add_coeff b1 ofs1 k b2 ofs2 len = assert (length b1 - ofs1 >= len); assert (length b2 - ofs2 >= len); for i = 0 to len - 1 do Array.unsafe_set b1 (ofs1 + i) (Array.unsafe_get b1 (ofs1 + i) +. (k *. Array.unsafe_get b2 (ofs2 + i))) done let add_coeff b1 ofs1 k b2 ofs2 len = if k = 0. then () else if k = 1. then add b1 ofs1 b2 ofs2 len else add_coeff b1 ofs1 k b2 ofs2 len let mult b1 ofs1 b2 ofs2 len = assert (length b1 - ofs1 >= len); assert (length b2 - ofs2 >= len); for i = 0 to len - 1 do Array.unsafe_set b1 (ofs1 + i) (Array.unsafe_get b1 (ofs1 + i) *. Array.unsafe_get b2 (ofs2 + i)) done let amplify c b ofs len = assert (length b - ofs >= len); for i = 0 to len - 1 do Array.unsafe_set b (ofs + i) (Array.unsafe_get b (ofs + i) *. c) done let clip b ofs len = assert (length b - ofs >= len); for i = 0 to len - 1 do let s = Array.unsafe_get b (ofs + i) in Array.unsafe_set b (ofs + i) (if Float.is_nan s then 0. else if s < -1. then -1. else if 1. < s then 1. else s) done let squares b ofs len = assert (length b - ofs >= len); let ret = ref 0. in for i = 0 to len - 1 do let s = Array.unsafe_get b (ofs + i) in ret := !ret +. (s *. s) done; !ret let noise b ofs len = assert (length b - ofs >= len); for i = 0 to len - 1 do Array.unsafe_set b (ofs + i) (Random.float 2. -. 1.) done let resample ?(mode = `Linear) ratio inbuf ofs len = assert (length inbuf - ofs >= len); if ratio = 1. then copy inbuf ofs len else if mode = `Nearest then ( let outlen = int_of_float ((float len *. ratio) +. 0.5) in let outbuf = create outlen in for i = 0 to outlen - 1 do let pos = min (int_of_float ((float i /. ratio) +. 0.5)) (len - 1) in Array.unsafe_set outbuf i (Array.unsafe_get inbuf (ofs + pos)) done; outbuf) else ( let outlen = int_of_float (float len *. ratio) in let outbuf = create outlen in for i = 0 to outlen - 1 do let ir = float i /. ratio in let pos = min (int_of_float ir) (len - 1) in if pos = len - 1 then Array.unsafe_set outbuf i (Array.unsafe_get inbuf (ofs + pos)) else ( let a = ir -. float pos in Array.unsafe_set outbuf i ((Array.unsafe_get inbuf (ofs + pos) *. (1. -. a)) +. (Array.unsafe_get inbuf (ofs + pos + 1) *. a))) done; outbuf) module B = struct type t = buffer let create = create let blit = blit end module Ringbuffer_ext = Ringbuffer.Make_ext (B) module Ringbuffer = Ringbuffer.Make (B) module Buffer_ext = struct type t = { mutable buffer : buffer } let prepare buf len = if length buf.buffer >= len then sub buf.buffer 0 len else ( let newbuf = create len in buf.buffer <- newbuf; newbuf) let create len = { buffer = create len } let length buf = length buf.buffer end module Analyze = struct let rms buf ofs len = let r = ref 0. in for i = 0 to len - 1 do let x = buf.(i + ofs) in r := !r +. (x *. x) done; sqrt (!r /. float len) module FFT = struct type t = { b : int; n : int; circle : Complex.t array; temp : Complex.t array; } let init b = let n = 1 lsl b in let h = n / 2 in let fh = float h in let circle = Array.make h Complex.zero in for i = 0 to h - 1 do let theta = pi *. float_of_int i /. fh in circle.(i) <- { Complex.re = cos theta; Complex.im = sin theta } done; { b; n; circle; temp = Array.make n Complex.zero } let length f = f.n let complex_create buf ofs len = Array.init len (fun i -> { Complex.re = buf.(ofs + i); Complex.im = 0. }) let ccoef k c = { Complex.re = k *. c.Complex.re; Complex.im = k *. c.Complex.im } let fft f d = assert (Array.length d = f.n); let ( +~ ) = Complex.add in let ( -~ ) = Complex.sub in let ( *~ ) = Complex.mul in if n > 1 then ( let h = n / 2 in for i = 0 to h - 1 do t.(s + i) <- d.(s + (2 * i)); done; fft d t s h; fft d t (s + h) h; let a = f.n / n in for i = 0 to h - 1 do let wkt = f.circle.(i * a) *~ t.(s + h + i) in d.(s + i) <- t.(s + i) +~ wkt; d.(s + h + i) <- t.(s + i) -~ wkt done) in fft f.temp d 0 f.n module Window = struct let iter f d = let len = Array.length d in let n = float len in for i = 0 to len - 1 do let k = f (float i) n in d.(i) <- ccoef k d.(i) done let hann d = iter (fun i n -> 0.5 *. (1. -. cos (2. *. pi *. i /. n))) d let hamming d = iter (fun i n -> 0.54 *. (0.46 *. cos (2. *. pi *. i /. n))) d let cosine d = iter (fun i n -> sin (pi *. i /. n)) d let lanczos d = let sinc x = let px = pi *. x in sin px /. px in iter (fun i n -> sinc (2. *. i /. n)) d let triangular d = iter (fun i n -> if i <= n /. 2. then 2. *. i /. n else ((n /. 2.) -. i) *. 2. /. n) d let bartlett_hann d = let a0 = 0.62 in let a1 = 0.48 in let a2 = 0.38 in iter (fun i n -> a0 -. (a1 *. abs_float ((i /. n) -. 0.5)) -. (a2 *. cos (2. *. pi *. i /. n))) d let blackman ?(alpha = 0.16) d = let a = alpha in let a0 = (1. -. a) /. 2. in let a1 = 1. /. 2. in let a2 = a /. 2. in iter (fun i n -> a0 -. (a1 *. cos (2. *. pi *. i /. n)) +. (a2 *. cos (4. *. pi *. i /. n))) d let low_res a0 a1 a2 a3 d = iter (fun i n -> a0 -. (a1 *. cos (2. *. pi *. i /. n)) +. (a2 *. cos (4. *. pi *. i /. n)) -. (a3 *. cos (6. *. pi *. i /. n))) d let nuttall d = low_res 0.355768 0.487396 0.144232 0.012604 d let blackman_harris d = low_res 0.35875 0.48829 0.14128 0.01168 d let blackman_nuttall d = low_res 0.3635819 0.4891775 0.1365995 0.0106411 d end let band_freq sr f k = float k *. float sr /. float f.n let notes sr f ?(note_min = Note.c0) ?(note_max = 128) ?(volume_min = 0.01) ?(filter_harmonics = true) buf = let len = buffer_length buf in assert (len = length f); let bdur = float len /. float sr in let fdf = float (length f) in let c = complex_create buf 0 len in fft f c; let ans = ref [] in let kstart = max 0 (int_of_float (Note.freq note_min *. bdur)) in let kend = min (len / 2) (int_of_float (Note.freq note_max *. bdur)) in for k = kstart + 1 to kend - 2 do let v' = Complex.norm c.(k - 1) in let v = Complex.norm c.(k) in let v'' = Complex.norm c.(k - 1) in if v' +. v'' < 2. *. v then ( let p = (v'' -. v') /. ((2. *. v') -. (2. *. v) +. v'') in let v = v -. ((v' -. v'') *. p /. 4.) in let v = v /. fdf in let p = p +. float k in if v >= volume_min then ans := (p, v) :: !ans) done; let ans = List.map (fun (k, v) -> (Note.of_freq (k /. bdur), v)) !ans in let ans = if filter_harmonics then list_filter_ctxt (fun b (n, _) t -> let o = Note.octave n in let n = Note.name n in List.for_all (fun (n', _) -> Note.name n' <> n || Note.octave n' >= o) (b @ t)) ans else ans in ans let loudest_note l = match l with | [] -> None | h :: t -> Some (List.fold_left (fun (nmax, vmax) (n, v) -> if v > vmax then (n, v) else (nmax, vmax)) h t) end end module Effect = struct let compand_mu_law mu buf ofs len = for i = 0 to len - 1 do let bufi = buf.(i + ofs) in let sign = if bufi < 0. then -1. else 1. in buf.(i + ofs) <- sign *. log (1. +. (mu *. abs_float bufi)) /. log (1. +. mu) done class type t = object method process : buffer -> int -> int -> unit end class amplify k : t = object method process = amplify k end class clip c : t = object method process buf ofs len = for i = 0 to len - 1 do Array.unsafe_set buf (i + ofs) (max (-.c) (min c (Array.unsafe_get buf (i + ofs)))) done end Digital filter based on " Cookbook formulae for audio EQ biquad filter coefficients " by < > . URL : -EQ-Cookbook.txt coefficients" by Robert Bristow-Johnson <>. URL: -EQ-Cookbook.txt *) class biquad_filter samplerate (kind : [ `Low_pass | `High_pass | `Band_pass | `Notch | `All_pass | `Peaking | `Low_shelf | `High_shelf ]) ?(gain = 0.) freq q = let samplerate = float samplerate in object (self) val mutable p0 = 0. val mutable p1 = 0. val mutable p2 = 0. val mutable q1 = 0. val mutable q2 = 0. method private init = let w0 = 2. *. pi *. freq /. samplerate in let cos_w0 = cos w0 in let sin_w0 = sin w0 in let alpha = sin w0 /. (2. *. q) in let a = if gain = 0. then 1. else 10. ** (gain /. 40.) in let b0, b1, b2, a0, a1, a2 = match kind with | `Low_pass -> let b1 = 1. -. cos_w0 in let b0 = b1 /. 2. in (b0, b1, b0, 1. +. alpha, -2. *. cos_w0, 1. -. alpha) | `High_pass -> let b1 = 1. +. cos_w0 in let b0 = b1 /. 2. in let b1 = -.b1 in (b0, b1, b0, 1. +. alpha, -2. *. cos_w0, 1. -. alpha) | `Band_pass -> let b0 = sin_w0 /. 2. in (b0, 0., -.b0, 1. +. alpha, -2. *. cos_w0, 1. -. alpha) | `Notch -> let b1 = -2. *. cos_w0 in (1., b1, 1., 1. +. alpha, b1, 1. -. alpha) | `All_pass -> let b0 = 1. -. alpha in let b1 = -2. *. cos_w0 in let b2 = 1. +. alpha in (b0, b1, b2, b2, b1, b0) | `Peaking -> let ama = alpha *. a in let ada = alpha /. a in let b1 = -2. *. cos_w0 in (1. +. ama, b1, 1. -. ama, 1. +. ada, b1, 1. -. ada) | `Low_shelf -> let s = 2. *. sqrt a *. alpha in ( a *. (a +. 1. -. ((a -. 1.) *. cos_w0) +. s), 2. *. a *. (a -. 1. -. ((a +. 1.) *. cos_w0)), a *. (a +. 1. -. ((a -. 1.) *. cos_w0) -. s), a +. 1. +. ((a -. 1.) *. cos_w0) +. s, (-2. *. (a -. 1.)) +. ((a +. 1.) *. cos_w0), a +. 1. +. ((a -. 1.) *. cos_w0) -. s ) | `High_shelf -> let s = 2. *. sqrt a *. alpha in ( a *. (a +. 1. +. ((a -. 1.) *. cos_w0) +. s), -2. *. a *. (a -. 1. +. ((a +. 1.) *. cos_w0)), a *. (a +. 1. +. ((a -. 1.) *. cos_w0) -. s), a +. 1. -. ((a -. 1.) *. cos_w0) +. s, (2. *. (a -. 1.)) -. ((a +. 1.) *. cos_w0), a +. 1. -. ((a -. 1.) *. cos_w0) -. s ) in p0 <- b0 /. a0; p1 <- b1 /. a0; p2 <- b2 /. a0; q1 <- a1 /. a0; q2 <- a2 /. a0 initializer self#init val mutable x1 = 0. val mutable x2 = 0. val mutable y0 = 0. val mutable y1 = 0. val mutable y2 = 0. method process (buf : buffer) ofs len = for i = 0 to len - 1 do let x0 = buf.(i + ofs) in let y0 = (p0 *. x0) +. (p1 *. x1) +. (p2 *. x2) -. (q1 *. y1) -. (q2 *. y2) in buf.(i + ofs) <- y0; x2 <- x1; x1 <- x0; y2 <- y1; y1 <- y0 done end module ADSR = struct type t = int * int * float * int * Convert adsr in seconds to samples . let make sr (a, d, s, r) = ( samples_of_seconds sr a, samples_of_seconds sr d, s, samples_of_seconds sr r ) type state = int * int let init () = (0, 0) let release (_, p) = (3, p) let dead (s, _) = s = 4 let rec process adsr st (buf : buffer) ofs len = let a, (d : int), s, (r : int) = adsr in let state, state_pos = st in match state with | 0 -> let fa = float a in for i = 0 to min len (a - state_pos) - 1 do buf.(i + ofs) <- float (state_pos + i) /. fa *. buf.(i + ofs) done; if len < a - state_pos then (0, state_pos + len) else process adsr (1, 0) buf (ofs + a - state_pos) (len - (a - state_pos)) | 1 -> let fd = float d in for i = 0 to min len (d - state_pos) - 1 do buf.(i + ofs) <- (1. -. (float (state_pos + i) /. fd *. (1. -. s))) *. buf.(i + ofs) done; if len < d - state_pos then (1, state_pos + len) s >= 0. then process adsr (2, 0) buf (ofs + d - state_pos) (len - (d - state_pos)) else process adsr (3, 0) buf (ofs + d - state_pos) (len - (d - state_pos)) | 2 -> amplify s buf ofs len; st | 3 -> let fr = float r in for i = 0 to min len (r - state_pos) - 1 do buf.(i + ofs) <- s *. (1. -. (float (state_pos + i) /. fr)) *. buf.(i + ofs) done; if len < r - state_pos then (3, state_pos + len) else process adsr (4, 0) buf (ofs + r - state_pos) (len - (r - state_pos)) | 4 -> clear buf ofs len; st | _ -> assert false end end module Generator = struct let white_noise buf = noise buf class type t = object method set_volume : float -> unit method set_frequency : float -> unit method fill : buffer -> int -> int -> unit method fill_add : buffer -> int -> int -> unit method release : unit method dead : bool end class virtual base sample_rate ?(volume = 1.) freq = object (self) val mutable vol = volume val mutable freq : float = freq val mutable dead = false method dead = dead method release = vol <- 0.; dead <- true method private sample_rate : int = sample_rate method private volume : float = vol method set_volume v = vol <- v method set_frequency f = freq <- f method virtual fill : buffer -> int -> int -> unit method fill_add (buf : buffer) ofs len = let tmp = create len in self#fill tmp 0 len; add buf ofs tmp 0 len end class white_noise ?volume sr = object (self) inherit base sr ?volume 0. method fill buf ofs len = let volume = self#volume in for i = 0 to len - 1 do buf.(i + ofs) <- volume *. (Random.float 2. -. 1.) done end class sine sr ?volume ?(phase = 0.) freq = object (self) inherit base sr ?volume freq val mutable phase = phase method fill buf ofs len = let sr = float self#sample_rate in let omega = 2. *. pi *. freq /. sr in let volume = self#volume in for i = 0 to len - 1 do buf.(i + ofs) <- volume *. sin ((float i *. omega) +. phase) done; phase <- mod_float (phase +. (float len *. omega)) (2. *. pi) end class square sr ?volume ?(phase = 0.) freq = object (self) inherit base sr ?volume freq val mutable phase = phase method fill buf ofs len = let sr = float self#sample_rate in let volume = self#volume in let omega = freq /. sr in for i = 0 to len - 1 do let t = fracf ((float i *. omega) +. phase) in buf.(i + ofs) <- (if t < 0.5 then volume else -.volume) done; phase <- mod_float (phase +. (float len *. omega)) 1. end class saw sr ?volume ?(phase = 0.) freq = object (self) inherit base sr ?volume freq val mutable phase = phase method fill buf ofs len = let volume = self#volume in let sr = float self#sample_rate in let omega = freq /. sr in for i = 0 to len - 1 do let t = fracf ((float i *. omega) +. phase) in buf.(i + ofs) <- volume *. ((2. *. t) -. 1.) done; phase <- mod_float (phase +. (float len *. omega)) 1. end class triangle sr ?volume ?(phase = 0.) freq = object (self) inherit base sr ?volume freq val mutable phase = phase method fill buf ofs len = let sr = float self#sample_rate in let volume = self#volume in let omega = freq /. sr in for i = 0 to len - 1 do let t = fracf ((float i *. omega) +. phase +. 0.25) in buf.(i + ofs) <- (volume *. if t < 0.5 then (4. *. t) -. 1. else (4. *. (1. -. t)) -. 1.) done; phase <- mod_float (phase +. (float len *. omega)) 1. end class chain (g : t) (e : Effect.t) : t = object method fill buf ofs len = g#fill buf ofs len; e#process buf ofs len val tmpbuf = Buffer_ext.create 0 method fill_add (buf : buffer) ofs len = let tmpbuf = Buffer_ext.prepare tmpbuf len in g#fill tmpbuf 0 len; add buf ofs tmpbuf 0 len method set_volume = g#set_volume method set_frequency = g#set_frequency method release = g#release method dead = g#dead end class combine f (g1 : t) (g2 : t) : t = object val tmpbuf = Buffer_ext.create 0 val tmpbuf2 = Buffer_ext.create 0 method fill buf ofs len = g1#fill buf ofs len; let tmpbuf = Buffer_ext.prepare tmpbuf len in g2#fill tmpbuf 0 len; f buf ofs tmpbuf 0 len method fill_add buf ofs len = let tmpbuf = Buffer_ext.prepare tmpbuf len in g1#fill tmpbuf 0 len; let tmpbuf2 = Buffer_ext.prepare tmpbuf2 len in g2#fill tmpbuf2 0 len; f tmpbuf 0 tmpbuf2 0 len; add buf ofs tmpbuf 0 len method set_volume v = g1#set_volume v; g2#set_volume v method set_frequency v = g1#set_frequency v; g2#set_frequency v method release = g1#release; g2#release method dead = g1#dead && g2#dead end class add g1 g2 = object inherit combine add g1 g2 end class mult g1 g2 = object inherit combine mult g1 g2 end class adsr (adsr : Effect.ADSR.t) (g : t) = object (self) val mutable adsr_st = Effect.ADSR.init () val tmpbuf = Buffer_ext.create 0 method set_volume = g#set_volume method set_frequency = g#set_frequency method fill buf ofs len = g#fill buf ofs len; adsr_st <- Effect.ADSR.process adsr adsr_st buf ofs len method fill_add buf ofs len = let tmpbuf = Buffer_ext.prepare tmpbuf len in self#fill tmpbuf 0 len; blit tmpbuf 0 buf ofs len method release = adsr_st <- Effect.ADSR.release adsr_st; g#release method dead = Effect.ADSR.dead adsr_st || g#dead end end end type t = Mono.buffer array type buffer = t let iter f data offset length = Array.iter (fun b -> f b offset length) data let create chans n = Array.init chans (fun _ -> Mono.create n) let make chans n x = Array.init chans (fun _ -> Mono.make n x) let channels data = Array.length data let length = function [||] -> 0 | a -> Array.length a.(0) let create_same buf = create (channels buf) (length buf) let interleave data length offset = let chans = Array.length data in let ibuf = Mono.create (chans * length) in for c = 0 to chans - 1 do let bufc = data.(c) in for i = 0 to length - 1 do ibuf.((chans * i) + c) <- bufc.(offset + i) done done; ibuf let deinterleave chans ibuf ofs len = let len = len / chans in let buf = create chans len in for c = 0 to chans - 1 do let bufc = buf.(c) in for i = 0 to len - 1 do bufc.(i) <- ibuf.((chans * i) + c + ofs) done done; buf let append b1 ofs1 len1 b2 ofs2 len2 = Array.mapi (fun i b -> Mono.append b ofs1 len2 b2.(i) ofs2 len1) b1 let clear = iter Mono.clear let clip = iter Mono.clip let noise = iter Mono.noise let copy b ofs len = Array.init (Array.length b) (fun i -> Mono.copy b.(i) ofs len) let blit b1 ofs1 b2 ofs2 len = Array.iteri (fun i b -> Mono.blit b ofs1 b2.(i) ofs2 len) b1 let sub b ofs len = Array.map (fun b -> Array.sub b ofs len) b let squares data offset length = Array.fold_left (fun squares buf -> squares +. Mono.squares buf offset length) 0. data let to_mono b ofs len = let channels = channels b in if channels = 1 then Array.sub b.(0) ofs len else ( let chans = float channels in let ans = Mono.create len in Mono.clear ans 0 len; for i = 0 to len - 1 do for c = 0 to channels - 1 do ans.(i) <- ans.(i) +. b.(c).(i + ofs) done; ans.(i) <- ans.(i) /. chans done; ans) let of_mono b = [| b |] let resample ?mode ratio data offset length = Array.map (fun buf -> Mono.resample ?mode ratio buf offset length) data let copy_from_ba ba buf ofs len = Array.iteri (fun i b -> Mono.copy_from_ba ba.(i) b ofs len) buf let copy_to_ba buf ofs len ba = Array.iteri (fun i b -> Mono.copy_to_ba buf.(i) ofs len b) ba let of_ba = Array.map Mono.of_ba let to_ba buf ofs len = Array.map (fun b -> Mono.to_ba b ofs len) buf module U8 = struct let size channels samples = channels * samples external of_audio : buffer -> int -> Bytes.t -> int -> int -> unit = "caml_mm_audio_to_u8" external to_audio : string -> int -> buffer -> int -> int -> unit = "caml_mm_audio_of_u8" end external to_s16 : bool -> buffer -> int -> Bytes.t -> int -> int -> unit = "caml_mm_audio_to_s16_byte" "caml_mm_audio_to_s16" external convert_s16 : bool -> string -> int -> buffer -> int -> int -> unit = "caml_mm_audio_convert_s16_byte" "caml_mm_audio_convert_s16" module S16LE = struct let size channels samples = channels * samples * 2 let length channels len = len / (2 * channels) let of_audio = to_s16 true let make buf ofs len = let slen = size (channels buf) len in let sbuf = Bytes.create slen in of_audio buf ofs sbuf 0 len; Bytes.unsafe_to_string sbuf let to_audio = convert_s16 true end module S16BE = struct let size channels samples = channels * samples * 2 let length channels len = len / (2 * channels) let of_audio = to_s16 false let make buf ofs len = let slen = size (channels buf) len in let sbuf = Bytes.create slen in of_audio buf ofs sbuf 0 len; Bytes.unsafe_to_string sbuf let to_audio = convert_s16 false end module S24LE = struct let size channels samples = channels * samples * 3 external of_audio : buffer -> int -> Bytes.t -> int -> int -> unit = "caml_mm_audio_to_s24le" external to_audio : string -> int -> buffer -> int -> int -> unit = "caml_mm_audio_convert_s24le" end module S32LE = struct let size channels samples = channels * samples * 4 external of_audio : buffer -> int -> Bytes.t -> int -> int -> unit = "caml_mm_audio_to_s32le" external to_audio : string -> int -> buffer -> int -> int -> unit = "caml_mm_audio_convert_s32le" end let add b1 ofs1 b2 ofs2 len = Array.iteri (fun i b -> Mono.add b ofs1 b2.(i) ofs2 len) b1 let add_coeff b1 ofs1 k b2 ofs2 len = Array.iteri (fun i b -> Mono.add_coeff b ofs1 k b2.(i) ofs2 len) b1 let amplify k data offset length = if k <> 1. then Array.iter (fun data -> Mono.amplify k data offset length) data x between -1 and 1 let pan x buf offset length = if x > 0. then ( let x = 1. -. x in Mono.amplify x buf.(0) offset length) else if x < 0. then ( let x = 1. +. x in Mono.amplify x buf.(1) offset length) module Buffer_ext = struct type t = { mutable buffer : buffer } let chans = channels let prepare buf ?channels len = match channels with | Some channels when chans buf.buffer <> channels -> let newbuf = create channels len in buf.buffer <- newbuf; newbuf | _ -> if length buf.buffer >= len then sub buf.buffer 0 len else ( let oldbuf = buf.buffer in let newbuf = create (chans oldbuf) len in buf.buffer <- newbuf; newbuf) let create chans len = { buffer = create chans len } end module Ringbuffer = struct type t = { size : int; buffer : buffer; } let create chans size = { size + 1 so we can store full buffers , while keeping rpos and wpos different for implementation matters rpos and wpos different for implementation matters *) size = size + 1; buffer = create chans (size + 1); rpos = 0; wpos = 0; } let channels t = channels t.buffer let read_space t = if t.wpos >= t.rpos then t.wpos - t.rpos else t.size - (t.rpos - t.wpos) let write_space t = if t.wpos >= t.rpos then t.size - (t.wpos - t.rpos) - 1 else t.rpos - t.wpos - 1 let read_advance t n = assert (n <= read_space t); if t.rpos + n < t.size then t.rpos <- t.rpos + n else t.rpos <- t.rpos + n - t.size let write_advance t n = assert (n <= write_space t); if t.wpos + n < t.size then t.wpos <- t.wpos + n else t.wpos <- t.wpos + n - t.size let peek t buf = let len = length buf in assert (len <= read_space t); let pre = t.size - t.rpos in let extra = len - pre in if extra > 0 then ( blit t.buffer t.rpos buf 0 pre; blit t.buffer 0 buf pre extra) else blit t.buffer t.rpos buf 0 len let read t buf = peek t buf; read_advance t (length buf) let write t buf = let len = length buf in assert (len <= write_space t); let pre = t.size - t.wpos in let extra = len - pre in if extra > 0 then ( blit buf 0 t.buffer t.wpos pre; blit buf pre t.buffer 0 extra) else blit buf 0 t.buffer t.wpos len; write_advance t len let transmit t f = if t.wpos = t.rpos then 0 else ( let len0 = if t.wpos >= t.rpos then t.wpos - t.rpos else t.size - t.rpos in let len = f (sub t.buffer t.rpos len0) in assert (len <= len0); read_advance t len; len) end module Ringbuffer_ext = struct type t = { mutable ringbuffer : Ringbuffer.t } let prepare buf len = if Ringbuffer.write_space buf.ringbuffer >= len then buf.ringbuffer else ( let rb = Ringbuffer.create (Ringbuffer.channels buf.ringbuffer) (Ringbuffer.read_space buf.ringbuffer + len) in while Ringbuffer.read_space buf.ringbuffer <> 0 do ignore (Ringbuffer.transmit buf.ringbuffer (fun buf -> Ringbuffer.write rb buf; length buf)) done; buf.ringbuffer <- rb; rb) let channels rb = Ringbuffer.channels rb.ringbuffer let peek rb = Ringbuffer.peek rb.ringbuffer let read rb = Ringbuffer.read rb.ringbuffer let write rb buf = let rb = prepare rb (length buf) in Ringbuffer.write rb buf let transmit rb = Ringbuffer.transmit rb.ringbuffer let read_space rb = Ringbuffer.read_space rb.ringbuffer let write_space rb = Ringbuffer.write_space rb.ringbuffer let read_advance rb = Ringbuffer.read_advance rb.ringbuffer let write_advance rb = Ringbuffer.write_advance rb.ringbuffer let create chans len = { ringbuffer = Ringbuffer.create chans len } end module Analyze = struct let rms buf ofs len = Array.init (channels buf) (fun i -> Mono.Analyze.rms buf.(i) ofs len) module ReplayGain = struct type t = { channels : int; mutable frame_pos : int; frame_length : int; prefilter : float array -> float array; mutable peak : float; mutable rms : float; histogram : int array; } exception Not_supported let histogram_slots = 12000 let create = let coeffs = [ ( 48000, ( [| 1.00000000000000; -3.84664617118067; 7.81501653005538; -11.34170355132042; 13.05504219327545; -12.28759895145294; 9.48293806319790; -5.87257861775999; 2.75465861874613; -0.86984376593551; 0.13919314567432; |], [| 0.03857599435200; -0.02160367184185; -0.00123395316851; -0.00009291677959; -0.01655260341619; 0.02161526843274; -0.02074045215285; 0.00594298065125; 0.00306428023191; 0.00012025322027; 0.00288463683916; |], [| 1.00000000000000; -1.97223372919527; 0.97261396931306 |], [| 0.98621192462708; -1.97242384925416; 0.98621192462708 |] ) ); ( 44100, ( [| 1.00000000000000; -3.47845948550071; 6.36317777566148; -8.54751527471874; 9.47693607801280; -8.81498681370155; 6.85401540936998; -4.39470996079559; 2.19611684890774; -0.75104302451432; 0.13149317958808; |], [| 0.05418656406430; -0.02911007808948; -0.00848709379851; -0.00851165645469; -0.00834990904936; 0.02245293253339; -0.02596338512915; 0.01624864962975; -0.00240879051584; 0.00674613682247; -0.00187763777362; |], [| 1.00000000000000; -1.96977855582618; 0.97022847566350 |], [| 0.98500175787242; -1.97000351574484; 0.98500175787242 |] ) ); ( 22050, ( [| 1.00000000000000; -1.49858979367799; 0.87350271418188; 0.12205022308084; -0.80774944671438; 0.47854794562326; -0.12453458140019; -0.04067510197014; 0.08333755284107; -0.04237348025746; 0.02977207319925; |], [| 0.33642304856132; -0.25572241425570; -0.11828570177555; 0.11921148675203; -0.07834489609479; -0.00469977914380; -0.00589500224440; 0.05724228140351; 0.00832043980773; -0.01635381384540; -0.01760176568150; |], [| 1.00000000000000; -1.94561023566527; 0.94705070426118 |], [| 0.97316523498161; -1.94633046996323; 0.97316523498161 |] ) ); ] in fun ~channels ~samplerate -> Frame length in samples ( a frame is 50 ms ) . let frame_length = samplerate * 50 / 1000 in Coefficients of the Yulewalk and Butterworth filters . let yule_a, yule_b, butter_a, butter_b = match List.assoc_opt samplerate coeffs with | Some c -> c | None -> raise Not_supported in let yulewalk = Array.init channels (fun _ -> Sample.iir yule_a yule_b) in let butterworth = Array.init channels (fun _ -> Sample.iir butter_a butter_b) in let prefilter x = Array.mapi (fun i x -> x |> yulewalk.(i) |> butterworth.(i)) x in { channels; frame_pos = 0; frame_length; prefilter; peak = 0.; rms = 0.; histogram = Array.make histogram_slots 0; } let process_sample rg x = Array.iter (fun x -> let x = abs_float x in if x > rg.peak then rg.peak <- x) x; let x = rg.prefilter x in Array.iter (fun x -> rg.rms <- rg.rms +. (x *. x)) x; rg.frame_pos <- rg.frame_pos + 1; if rg.frame_pos >= rg.frame_length then ( Minimum value is about -100 dB for digital silence . The 90 dB offset is to compensate for the normalized float range and 3 dB is for stereo samples . offset is to compensate for the normalized float range and 3 dB is for stereo samples. *) let rms = (10. *. log10 (rg.rms /. float (rg.frame_length * rg.channels))) +. 90. in let level = int_of_float (100. *. rms) |> max 0 |> min (histogram_slots - 1) in rg.histogram.(level) <- rg.histogram.(level) + 1; rg.rms <- 0.; rg.frame_pos <- 0) let process rg buf off len = assert (channels buf = rg.channels); for i = off to off + len - 1 do let x = Array.init rg.channels (fun c -> buf.(c).(i)) in process_sample rg x done let peak rg = rg.peak let gain rg = let windows = Array.fold_left ( + ) 0 rg.histogram in let i = ref (histogram_slots - 1) in let loud_count = ref 0 in Find i below the top 5 % while !i > 0 && !loud_count * 20 < windows do loud_count := !loud_count + rg.histogram.(!i); decr i done; 64.54 -. (float !i /. 100.) |> max (-24.) |> min 64. end end module Effect = struct class type t = object method process : buffer -> int -> int -> unit end class chain (e1 : t) (e2 : t) = object method process buf ofs len = e1#process buf ofs len; e2#process buf ofs len end class of_mono chans (g : unit -> Mono.Effect.t) = object val g = Array.init chans (fun _ -> g ()) method process buf ofs len = for c = 0 to chans - 1 do g.(c)#process buf.(c) ofs len done end class biquad_filter chans samplerate kind ?gain freq q = of_mono chans (fun () -> (new Mono.Effect.biquad_filter samplerate kind ?gain freq q :> Mono.Effect.t)) class type delay_t = object inherit t method set_delay : float -> unit method set_feedback : float -> unit end class delay_only chans sample_rate delay = let delay = int_of_float (float sample_rate *. delay) in object val mutable delay = delay method set_delay d = delay <- int_of_float (float sample_rate *. d) val rb = Ringbuffer_ext.create chans 0 initializer Ringbuffer_ext.write rb (create chans delay) method process buf ofs len = Ringbuffer_ext.write rb (sub buf ofs len); Ringbuffer_ext.read rb (sub buf ofs len) end class delay chans sample_rate delay once feedback = let delay = int_of_float (float sample_rate *. delay) in object val mutable delay = delay method set_delay d = delay <- int_of_float (float sample_rate *. d) val mutable feedback = feedback method set_feedback f = feedback <- f val rb = Ringbuffer_ext.create chans 0 val tmpbuf = Buffer_ext.create chans 0 method process buf ofs len = if once then Ringbuffer_ext.write rb buf; if Ringbuffer_ext.read_space rb < delay then Ringbuffer_ext.write rb (create chans delay); if Ringbuffer_ext.read_space rb > delay then Ringbuffer_ext.read_advance rb (Ringbuffer_ext.read_space rb - delay); if len > delay then add_coeff buf delay feedback buf ofs (len - delay); let rlen = min delay len in let tmpbuf = Buffer_ext.prepare tmpbuf rlen in Ringbuffer_ext.read rb (sub tmpbuf 0 rlen); add_coeff buf 0 feedback tmpbuf 0 rlen; if not once then Ringbuffer_ext.write rb buf end class delay_ping_pong chans sample_rate delay once feedback = let r1 = new delay_only 1 sample_rate delay in let d1 = new delay 1 sample_rate (2. *. delay) once feedback in let d1' = new chain (r1 :> t) (d1 :> t) in let d2 = new delay 1 sample_rate (2. *. delay) once feedback in object initializer assert (chans = 2) method set_delay d = r1#set_delay d; d1#set_delay (2. *. d); d2#set_delay (2. *. d) method set_feedback f = d1#set_feedback f; d2#set_feedback f method process buf ofs len = assert (channels buf = 2); d1'#process [| buf.(0) |] ofs len; d2#process [| buf.(1) |] ofs len end let delay chans sample_rate d ?(once = false) ?(ping_pong = false) feedback = if ping_pong then new delay_ping_pong chans sample_rate d once feedback else new delay chans sample_rate d once feedback times in sec , ratios in dB , gain linear class compress ?(attack = 0.1) ?(release = 0.1) ?(threshold = -10.) ?(ratio = 3.) ?(knee = 1.) ?(rms_window = 0.1) ?(gain = 1.) chans samplerate = let rmsn = samples_of_seconds samplerate rms_window in let samplerate = float samplerate in object val mutable attack = attack method set_attack a = attack <- a val mutable release = release method set_release r = release <- r val mutable threshold = threshold method set_threshold t = threshold <- t val mutable ratio = ratio method set_ratio r = ratio <- r val mutable knee = knee method set_knee k = knee <- k val mutable gain = gain method set_gain g = gain <- g val rmsv = Array.make rmsn 0. val mutable rmsp = 0 Current squares of RMS . val mutable rms = 0. val mutable amp = 0. val mutable env = 0. val mutable g = 1. method process (buf : buffer) ofs len = let ratio = (ratio -. 1.) /. ratio in let g_attack = if attack = 0. then 0. else exp (-1. /. (samplerate *. attack)) in let ef_a = g_attack *. 0.25 in let g_release = if release = 0. then 0. else exp (-1. /. (samplerate *. release)) in let ef_ai = 1. -. ef_a in let knee_min = lin_of_dB (threshold -. knee) in let knee_max = lin_of_dB (threshold +. knee) in for i = 0 to len - 1 do let lev_in = let ans = ref 0. in for c = 0 to chans - 1 do let x = buf.(c).(i + ofs) *. gain in ans := !ans +. (x *. x) done; !ans /. float chans in rms <- rms -. rmsv.(rmsp) +. lev_in; rms <- abs_float rms; rmsv.(rmsp) <- lev_in; rmsp <- (rmsp + 1) mod rmsn; amp <- sqrt (rms /. float rmsn); Dynamic selection : attack or release ? if amp > env then env <- (env *. g_attack) +. (amp *. (1. -. g_attack)) else env <- (env *. g_release) +. (amp *. (1. -. g_release)); let gain_t = 1. else if env < knee_max then ( let x = (knee +. dB_of_lin env -. threshold) /. (2. *. knee) in lin_of_dB (0. -. (knee *. ratio *. x *. x))) else Maximal ( n:1 ) compression . lin_of_dB ((threshold -. dB_of_lin env) *. ratio) in g <- (g *. ef_a) +. (gain_t *. ef_ai); let g = g *. gain in for c = 0 to chans - 1 do buf.(c).(i + ofs) <- buf.(c).(i + ofs) *. g done count <- count + 1; if count mod 10000 = 0 then self#log#f 4 "RMS:%7.02f Env:%7.02f Gain: %4.02f\r%!" (Audio.dB_of_lin amp) (Audio.dB_of_lin env) gain *) done method reset = rms <- 0.; rmsp <- 0; for i = 0 to rmsn - 1 do rmsv.(i) <- 0. done; g <- 1.; env <- 0.; amp <- 0. end target RMS duration of the RMS collection in seconds speed when volume is going up in coeff per sec let rms_len = samples_of_seconds samplerate rms_len in let rms_lenf = float rms_len in let kup = kup ** seconds_of_samples samplerate rms_len in let kdown = kdown ** seconds_of_samples samplerate rms_len in object val mutable rms = Array.make channels 0. val mutable rms_collected = 0 val mutable vol = vol_init val mutable vol_old = vol_init val mutable enabled = true method process (buf : buffer) ofs len = for c = 0 to channels - 1 do let bufc = buf.(c) in for i = 0 to len - 1 do let bufci = bufc.(ofs + i) in if rms_collected >= rms_len then ( let rms_cur = let ans = ref 0. in for c = 0 to channels - 1 do ans := !ans +. rms.(c) done; sqrt (!ans /. float channels) in rms <- Array.make channels 0.; rms_collected <- 0; enabled <- rms_cur >= rms_threshold; if enabled then ( let vol_opt = rmst /. rms_cur in vol_old <- vol; if rms_cur < rmst then vol <- vol +. (kup *. (vol_opt -. vol)) else vol <- vol +. (kdown *. (vol_opt -. vol)); vol <- max vol_min vol; vol <- min vol_max vol)); rms.(c) <- rms.(c) +. (bufci *. bufci); rms_collected <- rms_collected + 1; Affine transition between vol_old and vol . bufc.(i) <- (vol_old +. (float rms_collected /. rms_lenf *. (vol -. vol_old))) *. bufci done done end let auto_gain_control channels samplerate ?(rms_target = 1.) ?(rms_window = 0.2) ?(kup = 0.6) ?(kdown = 0.8) ?(rms_threshold = 0.01) ?(volume_init = 1.) ?(volume_min = 0.1) ?(volume_max = 10.) () = new auto_gain_control channels samplerate rms_target rms_window kup kdown rms_threshold volume_init volume_min volume_max end module Generator = struct let white_noise buf ofs len = for c = 0 to channels buf - 1 do Mono.Generator.white_noise buf.(c) ofs len done class type t = object method set_volume : float -> unit method set_frequency : float -> unit method release : unit method dead : bool method fill : buffer -> int -> int -> unit method fill_add : buffer -> int -> int -> unit end class of_mono (g : Mono.Generator.t) = object val tmpbuf = Mono.Buffer_ext.create 0 method set_volume = g#set_volume method set_frequency = g#set_frequency method fill buf ofs len = g#fill buf.(0) ofs len; for c = 1 to channels buf - 1 do Mono.blit buf.(0) ofs buf.(c) ofs len done method fill_add (buf : buffer) ofs len = let tmpbuf = Mono.Buffer_ext.prepare tmpbuf len in g#fill tmpbuf 0 len; for c = 0 to channels buf - 1 do Mono.add buf.(c) ofs tmpbuf 0 len done method release = g#release method dead = g#dead end class chain (g : t) (e : Effect.t) : t = object method fill buf ofs len = g#fill buf ofs len; e#process buf ofs len val tmpbuf = Buffer_ext.create 0 0 method fill_add buf ofs len = let tmpbuf = Buffer_ext.prepare tmpbuf ~channels:(channels buf) len in g#fill tmpbuf 0 len; add buf ofs tmpbuf 0 len method set_volume = g#set_volume method set_frequency = g#set_frequency method release = g#release method dead = g#dead end end module IO = struct exception Invalid_file exception Invalid_operation exception End_of_stream module Reader = struct class type t = object method channels : int method sample_rate : int method length : int method duration : float method seek : int -> unit method close : unit method read : buffer -> int -> int -> int end class virtual base = object (self) method virtual channels : int method virtual sample_rate : int method virtual length : int method duration = float self#length /. float self#sample_rate end class virtual wav = object (self) inherit IO.helper method virtual private stream_close : unit method virtual private stream_seek : int -> unit method virtual private stream_cur_pos : int val mutable sample_rate = 0 val mutable channels = 0 val mutable sample_size = 0 val mutable bytes_per_sample = 0 val mutable length = 0 val mutable data_offset = 0 method sample_rate = sample_rate method channels = channels method length = length initializer if self#input 4 <> "RIFF" then failwith " Bad header : \"RIFF\ " not found " ; raise Invalid_file; ignore (self#input 4); if self#input 8 <> "WAVEfmt " then failwith " Bad header : \"WAVEfmt \ " not found " ; raise Invalid_file; Now we always have the following uninteresting bytes : * 0x10 0x00 0x00 0x00 0x01 0x00 * 0x10 0x00 0x00 0x00 0x01 0x00 *) ignore (self#really_input 6); channels <- self#input_short; sample_rate <- self#input_int; byt_per_sec sample_size <- self#input_short; let section = self#really_input 4 in if section <> "data" then ( if section = "INFO" then failwith " Valid wav file but unread " ; raise Invalid_file; failwith " Bad header : string \"data\ " not found " raise Invalid_file); let len_dat = self#input_int in data_offset <- self#stream_cur_pos; bytes_per_sample <- sample_size / 8 * channels; length <- len_dat / bytes_per_sample method read (buf : buffer) ofs len = let sbuflen = len * channels * 2 in let sbuf = self#input sbuflen in let sbuflen = String.length sbuf in let len = sbuflen / (channels * 2) in begin match sample_size with | 16 -> S16LE.to_audio sbuf 0 buf ofs len | 8 -> U8.to_audio sbuf 0 buf ofs len | _ -> assert false end; len method seek n = let n = data_offset + (n * bytes_per_sample) in self#stream_seek n method close = self#stream_close end class of_wav_file fname = object inherit IO.Unix.rw ~read:true fname inherit base inherit wav end end module Writer = struct class type t = object method write : buffer -> int -> int -> unit method close : unit end class virtual base chans sr = object method private channels : int = chans method private sample_rate : int = sr end class virtual wav = object (self) inherit IO.helper method virtual private stream_write : string -> int -> int -> int method virtual private stream_seek : int -> unit method virtual private stream_close : unit method virtual private channels : int method virtual private sample_rate : int initializer let bits_per_sample = 16 in self#output "RIFF"; self#output_int 0; self#output "WAVE"; self#output "fmt "; self#output_int 16; self#output_short 1; self#output_short self#channels; self#output_int self#sample_rate; self#output_int (self#sample_rate * self#channels * bits_per_sample / 8); self#output_short (self#channels * bits_per_sample / 8); self#output_short bits_per_sample; self#output "data"; self#output_short 0xffff; self#output_short 0xffff val mutable datalen = 0 method write buf ofs len = let s = S16LE.make buf ofs len in self#output s; datalen <- datalen + String.length s method close = self#stream_seek 4; self#output_int (36 + datalen); self#stream_seek 40; self#output_int datalen; self#stream_close end class to_wav_file chans sr fname = object inherit base chans sr inherit IO.Unix.rw ~write:true fname inherit wav end end module RW = struct class type t = object method read : buffer -> int -> int -> unit method write : buffer -> int -> int -> unit method close : unit end class virtual bufferized channels ~min_duration ~fill_duration ~max_duration ~drop_duration = object method virtual io_read : buffer -> unit method virtual io_write : buffer -> unit initializer assert (fill_duration <= max_duration); assert (drop_duration <= max_duration) val rb = Ringbuffer.create channels max_duration method read buf = let len = length buf in let rs = Ringbuffer.read_space rb in if rs < min_duration + len then ( let ps = min_duration + len - rs in Ringbuffer.write rb (create channels ps)); Ringbuffer.read rb buf method write buf = let len = length buf in let ws = Ringbuffer.write_space rb in if ws + len > max_duration then Ringbuffer.read_advance rb (ws - drop_duration); Ringbuffer.write rb buf end end end
e065c4d15beeee75abc12c77f87e4442bc01636c0e8c426eec6b8bf4189967c1
QuentinDuval/triboard
store.cljs
(ns triboard.store (:require [cljs.spec :as s] [reagent.core :as reagent] [triboard.logic.game :as game] [triboard.logic.player :as player] [triboard.logic.turn :as turn]) (:require-macros [reagent.ratom :refer [reaction]])) ;; ----------------------------------------- ;; Private ;; ----------------------------------------- (defonce app-state (reagent/atom {:game (game/new-game) :help false})) ;; ----------------------------------------- ;; Public API (reactive consumption) ;; ----------------------------------------- (def game (reaction (:game @app-state))) (def current-turn (reaction (game/current-turn @game))) (def ai-player? (reaction (player/is-ai? (:player @current-turn)))) (def suggestions (reaction (if (and (:help @app-state) (not @ai-player?)) #(contains? (turn/transitions @current-turn) %) (constantly false)))) ;; ----------------------------------------- ;; Public API (updates) ;; ----------------------------------------- (defn swap-game! [update-fn & args] (apply swap! app-state update :game update-fn args)) (defn toggle-help! [] (swap! app-state update :help not))
null
https://raw.githubusercontent.com/QuentinDuval/triboard/2641d4c033fa0c64a02ef4564005b616d81b1a13/src/cljs/triboard/store.cljs
clojure
----------------------------------------- Private ----------------------------------------- ----------------------------------------- Public API (reactive consumption) ----------------------------------------- ----------------------------------------- Public API (updates) -----------------------------------------
(ns triboard.store (:require [cljs.spec :as s] [reagent.core :as reagent] [triboard.logic.game :as game] [triboard.logic.player :as player] [triboard.logic.turn :as turn]) (:require-macros [reagent.ratom :refer [reaction]])) (defonce app-state (reagent/atom {:game (game/new-game) :help false})) (def game (reaction (:game @app-state))) (def current-turn (reaction (game/current-turn @game))) (def ai-player? (reaction (player/is-ai? (:player @current-turn)))) (def suggestions (reaction (if (and (:help @app-state) (not @ai-player?)) #(contains? (turn/transitions @current-turn) %) (constantly false)))) (defn swap-game! [update-fn & args] (apply swap! app-state update :game update-fn args)) (defn toggle-help! [] (swap! app-state update :help not))
074828a33593ff8ab52b7ca3b369d603d394c8ef66274ea4dbb34ec25663330e
thheller/shadow-cljs
debug.clj
(ns shadow.debug) (defn merge-opts [m opts] (cond (map? opts) (merge m opts) (keyword? opts) (assoc m :label opts) :else (assoc m :view-opts opts))) (defn dbg-info [env form opts] (let [{:keys [line column]} (meta form)] (-> {:ns (str *ns*)} (cond-> line (assoc :line line) column (assoc :column column)) (merge-opts opts)))) ;; abusing tap> because it is in core and doesn't require additional requires which is fine for CLJ but problematic for CLJS ;; FIXME: make this all noop unless enabled (defmacro ?> ([obj] `(tap> [:shadow.remote/wrap ~obj ~(dbg-info &env &form {})])) ([obj opts] `(tap> [:shadow.remote/wrap ~obj ~(dbg-info &env &form opts)]))) (defn tap-> [obj opts] (tap> [:shadow.remote/wrap obj opts]) obj) (defmacro ?-> ([obj] `(tap-> ~obj ~(dbg-info &env &form {}))) ([obj opts] `(tap-> ~obj ~(dbg-info &env &form opts)))) (defmacro ?->> ([obj] `(tap-> ~obj ~(dbg-info &env &form {}))) ([opts obj] `(tap-> ~obj ~(dbg-info &env &form opts)))) (defmacro locals [] (let [locals (reduce-kv (fn [m local info] (assoc m (keyword (name local)) local)) {} (if (:ns &env) (:locals &env) &env))] `(tap> [:shadow.remote/wrap ~locals ~(dbg-info &env &form {})]))) (defn java-obj [o] (let [class (.getClass o) fields (.getDeclaredFields class)] (reduce (fn [m field] (.setAccessible field true) (assoc m (.getName field) (.get field o))) {} fields))) (comment (?> (:clj-runtime (shadow.cljs.devtools.server.runtime/get-instance)) :view-opts ) (let [x 1 y 2] (locals)) (?> :yo) (-> :thing (?-> :view-opts)) (?> :hello ::send-help) (?> :hello) (-> :x (?-> ::view-opts)) (-> :thing (?-> {:label "you fool"})) (->> :thing (?->> ::omg)))
null
https://raw.githubusercontent.com/thheller/shadow-cljs/93f6eea3b02d81440ec2fb97b89f7a99b8459004/src/main/shadow/debug.clj
clojure
abusing tap> because it is in core and doesn't require additional requires FIXME: make this all noop unless enabled
(ns shadow.debug) (defn merge-opts [m opts] (cond (map? opts) (merge m opts) (keyword? opts) (assoc m :label opts) :else (assoc m :view-opts opts))) (defn dbg-info [env form opts] (let [{:keys [line column]} (meta form)] (-> {:ns (str *ns*)} (cond-> line (assoc :line line) column (assoc :column column)) (merge-opts opts)))) which is fine for CLJ but problematic for CLJS (defmacro ?> ([obj] `(tap> [:shadow.remote/wrap ~obj ~(dbg-info &env &form {})])) ([obj opts] `(tap> [:shadow.remote/wrap ~obj ~(dbg-info &env &form opts)]))) (defn tap-> [obj opts] (tap> [:shadow.remote/wrap obj opts]) obj) (defmacro ?-> ([obj] `(tap-> ~obj ~(dbg-info &env &form {}))) ([obj opts] `(tap-> ~obj ~(dbg-info &env &form opts)))) (defmacro ?->> ([obj] `(tap-> ~obj ~(dbg-info &env &form {}))) ([opts obj] `(tap-> ~obj ~(dbg-info &env &form opts)))) (defmacro locals [] (let [locals (reduce-kv (fn [m local info] (assoc m (keyword (name local)) local)) {} (if (:ns &env) (:locals &env) &env))] `(tap> [:shadow.remote/wrap ~locals ~(dbg-info &env &form {})]))) (defn java-obj [o] (let [class (.getClass o) fields (.getDeclaredFields class)] (reduce (fn [m field] (.setAccessible field true) (assoc m (.getName field) (.get field o))) {} fields))) (comment (?> (:clj-runtime (shadow.cljs.devtools.server.runtime/get-instance)) :view-opts ) (let [x 1 y 2] (locals)) (?> :yo) (-> :thing (?-> :view-opts)) (?> :hello ::send-help) (?> :hello) (-> :x (?-> ::view-opts)) (-> :thing (?-> {:label "you fool"})) (->> :thing (?->> ::omg)))
18dd33e90e8ac40f7e094e6dc72eb111fcb00b03a11694b4682552c8715c5789
chiroptical/polysemy-playground
Main.hs
# LANGUAGE TypeApplications # module Main where import Api import DatabaseEff ( databaseEffToIO, makeTablesIfNotExists, ) import Database (DbErr (..)) import Polysemy (runM) import Polysemy.Error (runError) import Polysemy.Reader (runReader) import Colog.Polysemy (runLogAction) import Message (logMessageStdout) import Network.Wai.Handler.Warp as Warp main :: IO () main = do let dbName :: String dbName = "database.db" _ <- runM . runError @DbErr . runLogAction @IO logMessageStdout . runReader dbName . databaseEffToIO $ makeTablesIfNotExists app' <- app dbName Warp.run 8081 app'
null
https://raw.githubusercontent.com/chiroptical/polysemy-playground/00e84ddc0f32996e09f48ea45cd9e9333fdcc147/app/Main.hs
haskell
# LANGUAGE TypeApplications # module Main where import Api import DatabaseEff ( databaseEffToIO, makeTablesIfNotExists, ) import Database (DbErr (..)) import Polysemy (runM) import Polysemy.Error (runError) import Polysemy.Reader (runReader) import Colog.Polysemy (runLogAction) import Message (logMessageStdout) import Network.Wai.Handler.Warp as Warp main :: IO () main = do let dbName :: String dbName = "database.db" _ <- runM . runError @DbErr . runLogAction @IO logMessageStdout . runReader dbName . databaseEffToIO $ makeTablesIfNotExists app' <- app dbName Warp.run 8081 app'
3a054750ce0a0eea6149ba8f5fdbe558d2ec63f372ba0347422d13dfb2c50ea2
mbj/stratosphere
S3OutputProperty.hs
module Stratosphere.SageMaker.ModelBiasJobDefinition.S3OutputProperty ( S3OutputProperty(..), mkS3OutputProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data S3OutputProperty = S3OutputProperty {localPath :: (Value Prelude.Text), s3UploadMode :: (Prelude.Maybe (Value Prelude.Text)), s3Uri :: (Value Prelude.Text)} mkS3OutputProperty :: Value Prelude.Text -> Value Prelude.Text -> S3OutputProperty mkS3OutputProperty localPath s3Uri = S3OutputProperty {localPath = localPath, s3Uri = s3Uri, s3UploadMode = Prelude.Nothing} instance ToResourceProperties S3OutputProperty where toResourceProperties S3OutputProperty {..} = ResourceProperties {awsType = "AWS::SageMaker::ModelBiasJobDefinition.S3Output", supportsTags = Prelude.False, properties = Prelude.fromList ((Prelude.<>) ["LocalPath" JSON..= localPath, "S3Uri" JSON..= s3Uri] (Prelude.catMaybes [(JSON..=) "S3UploadMode" Prelude.<$> s3UploadMode]))} instance JSON.ToJSON S3OutputProperty where toJSON S3OutputProperty {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["LocalPath" JSON..= localPath, "S3Uri" JSON..= s3Uri] (Prelude.catMaybes [(JSON..=) "S3UploadMode" Prelude.<$> s3UploadMode]))) instance Property "LocalPath" S3OutputProperty where type PropertyType "LocalPath" S3OutputProperty = Value Prelude.Text set newValue S3OutputProperty {..} = S3OutputProperty {localPath = newValue, ..} instance Property "S3UploadMode" S3OutputProperty where type PropertyType "S3UploadMode" S3OutputProperty = Value Prelude.Text set newValue S3OutputProperty {..} = S3OutputProperty {s3UploadMode = Prelude.pure newValue, ..} instance Property "S3Uri" S3OutputProperty where type PropertyType "S3Uri" S3OutputProperty = Value Prelude.Text set newValue S3OutputProperty {..} = S3OutputProperty {s3Uri = newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/ModelBiasJobDefinition/S3OutputProperty.hs
haskell
module Stratosphere.SageMaker.ModelBiasJobDefinition.S3OutputProperty ( S3OutputProperty(..), mkS3OutputProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data S3OutputProperty = S3OutputProperty {localPath :: (Value Prelude.Text), s3UploadMode :: (Prelude.Maybe (Value Prelude.Text)), s3Uri :: (Value Prelude.Text)} mkS3OutputProperty :: Value Prelude.Text -> Value Prelude.Text -> S3OutputProperty mkS3OutputProperty localPath s3Uri = S3OutputProperty {localPath = localPath, s3Uri = s3Uri, s3UploadMode = Prelude.Nothing} instance ToResourceProperties S3OutputProperty where toResourceProperties S3OutputProperty {..} = ResourceProperties {awsType = "AWS::SageMaker::ModelBiasJobDefinition.S3Output", supportsTags = Prelude.False, properties = Prelude.fromList ((Prelude.<>) ["LocalPath" JSON..= localPath, "S3Uri" JSON..= s3Uri] (Prelude.catMaybes [(JSON..=) "S3UploadMode" Prelude.<$> s3UploadMode]))} instance JSON.ToJSON S3OutputProperty where toJSON S3OutputProperty {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["LocalPath" JSON..= localPath, "S3Uri" JSON..= s3Uri] (Prelude.catMaybes [(JSON..=) "S3UploadMode" Prelude.<$> s3UploadMode]))) instance Property "LocalPath" S3OutputProperty where type PropertyType "LocalPath" S3OutputProperty = Value Prelude.Text set newValue S3OutputProperty {..} = S3OutputProperty {localPath = newValue, ..} instance Property "S3UploadMode" S3OutputProperty where type PropertyType "S3UploadMode" S3OutputProperty = Value Prelude.Text set newValue S3OutputProperty {..} = S3OutputProperty {s3UploadMode = Prelude.pure newValue, ..} instance Property "S3Uri" S3OutputProperty where type PropertyType "S3Uri" S3OutputProperty = Value Prelude.Text set newValue S3OutputProperty {..} = S3OutputProperty {s3Uri = newValue, ..}
a5c35d2905f53ef0ddf96399378311c17300e81788af206f987442f5c86ee369
Stratus3D/programming_erlang_exercises
spawn_registered_fun.erl
-module(spawn_registered_fun). -export([start/2]). % Example usage: % 1 > spawn_registered_fun : start(foo , fun ( ) - > receive _ - > ok end end ) . % {ok,<0.40.0>} 2 > spawn_registered_fun : start(foo , fun ( ) - > receive _ - > ok end end ) . % {error,already_running} % Use guards to ensure the arguments passed in are what this function requires start(AnAtom, Fun) when is_atom(AnAtom), is_function(Fun, 0) -> Sender = self(), % Since we can only execute Fun after we are sure the the register/2 call has succeeded we need to invoke register/2 and then if it succeeds execute % Fun. This is most easily done inside the newly spawned process. If the % register/2 call fails we can simply send an error back to the spawning % process and let the spawned process exit normally. Runner = fun() -> try register(AnAtom, self()) of true -> Sender ! {ok, self()}, Fun() catch error:_ -> Sender ! {error, {already_running, self()}} end end, Spawn the function as a linked process so we are alware of errors Pid = spawn_link(Runner), Receive the messages back from the Runner process so we know the status % of the register/2 call so we can return the appropriate value to the % caller of this function. receive {ok, Pid} -> {ok, Pid}; {error, {already_running, Pid}} -> {error, already_running} end.
null
https://raw.githubusercontent.com/Stratus3D/programming_erlang_exercises/e4fd01024812059d338facc20f551e7dff4dac7e/chapter_12/exercise_1/spawn_registered_fun.erl
erlang
Example usage: {ok,<0.40.0>} {error,already_running} Use guards to ensure the arguments passed in are what this function requires Since we can only execute Fun after we are sure the the register/2 call Fun. This is most easily done inside the newly spawned process. If the register/2 call fails we can simply send an error back to the spawning process and let the spawned process exit normally. of the register/2 call so we can return the appropriate value to the caller of this function.
-module(spawn_registered_fun). -export([start/2]). 1 > spawn_registered_fun : start(foo , fun ( ) - > receive _ - > ok end end ) . 2 > spawn_registered_fun : start(foo , fun ( ) - > receive _ - > ok end end ) . start(AnAtom, Fun) when is_atom(AnAtom), is_function(Fun, 0) -> Sender = self(), has succeeded we need to invoke register/2 and then if it succeeds execute Runner = fun() -> try register(AnAtom, self()) of true -> Sender ! {ok, self()}, Fun() catch error:_ -> Sender ! {error, {already_running, self()}} end end, Spawn the function as a linked process so we are alware of errors Pid = spawn_link(Runner), Receive the messages back from the Runner process so we know the status receive {ok, Pid} -> {ok, Pid}; {error, {already_running, Pid}} -> {error, already_running} end.
861833e5f2810ad84cbba35e79374d505f325d4d29e4ff58f3e0d1cc608f85b1
herd/herdtools7
ARMBase.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 . (****************************************************************************) (** Define registers, barriers, and instructions for ARM *) open Printf (* Who am i ? *) let arch = Archs.arm let endian = Endian.Little let base_type = CType.Base "int" (*************) (* Registers *) (*************) type reg = | R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | R11 | R12 | SP | LR | PC | Z (* condition flags *) | Symbolic_reg of string | Internal of int | RESADDR let base = Internal 0 and max_idx = Internal 1 and idx = Internal 2 and ephemeral = Internal 3 let loop_idx = Internal 4 let pc = PC let regs = [ R0, "R0" ; R1, "R1" ; R2, "R2" ; R3, "R3" ; R4, "R4" ; R5, "R5" ; R6, "R6" ; R7, "R7" ; R8, "R8" ; R9, "R9" ; R10, "R10" ; R11, "R11" ; R12, "R12" ; SP, "SP" ; LR, "LR" ; PC, "PC" ; Z, "Z" ; RESADDR, "RESADDR" ; ] let to_parse = List.filter (fun (r,_) -> match r with | Z|RESADDR -> false | _ -> true) regs let parse_list = List.map (fun (r,s) -> s,r) (List.filter (fun (r,_) -> match r with | Z|RESADDR -> false | _ -> true) regs) let parse_reg s = try Some (List.assoc s parse_list) with Not_found -> None let pp_reg r = match r with | Symbolic_reg r -> "%"^r | Internal i -> Printf.sprintf "i%i" i | _ -> try List.assoc r regs with Not_found -> assert false let reg_compare = compare let symb_reg_name = function | Symbolic_reg r -> Some r | _ -> None let symb_reg r = Symbolic_reg r let type_reg _ = base_type (************) Barriers (************) type barrier_option = | SY | ST | ISH | ISHST | NSH | NSHST | OSH | OSHST let fold_barrier_option f k = let k = f SY k in let k = f ST k in let k = f ISH k in let k = f ISHST k in let k = f NSH k in let k = f NSHST k in let k = f OSH k in let k = f OSHST k in k type barrier = | DMB of barrier_option | DSB of barrier_option | ISB let all_kinds_of_barriers = [DMB SY; ] let pp_option = function | SY -> "SY" | ST -> "ST" | ISH -> "ISH" | ISHST -> "ISHST" | NSH -> "NSH" | NSHST -> "NSHST" | OSH -> "OSH" | OSHST -> "OSHST" let pp_barrier_option memo o = match o with | SY -> memo | _ -> sprintf "%s.%s" memo (pp_option o) let pp_barrier_ins memo o = match o with | SY -> memo | _ -> sprintf "%s %s" memo (pp_option o) let pp_barrier b = match b with | DMB o -> pp_barrier_option "DMB" o | DSB o -> pp_barrier_option "DSB" o | ISB -> "ISB" let barrier_compare = compare (****************) (* Instructions *) (****************) type lbl = Label.t type setflags = SetFlags | DontSetFlags type condition = NE | EQ | AL (* ALWAYS *) type 'k kinstruction = | I_NOP | I_ADD of setflags * reg * reg * 'k | I_ADD3 of setflags * reg * reg * reg | I_SUB of setflags * reg * reg * 'k | I_SUB3 of setflags * reg * reg * reg | I_AND of setflags * reg * reg * 'k | I_B of lbl | I_BEQ of lbl | I_BNE of lbl (* Was maybeVal ??? *) | I_CB of bool * reg * lbl | I_CMPI of reg * 'k | I_CMP of reg * reg | I_LDR of reg * reg * condition | I_LDREX of reg * reg | I_LDR3 of reg * reg * reg * condition | I_STR of reg * reg * condition | I_STR3 of reg * reg * reg * condition | I_STREX of reg * reg * reg * condition | I_MOVI of reg * 'k * condition | I_MOV of reg * reg * condition | I_XOR of setflags * reg * reg * reg | I_DMB of barrier_option | I_DSB of barrier_option | I_ISB (* SIMD *) | I_SADD16 of reg * reg * reg | I_SEL of reg * reg * reg type instruction = int kinstruction type parsedInstruction = MetaConst.k kinstruction let pp_lbl = fun i -> i open PPMode let pp_hash m = match m with | Ascii | Dot -> "#" | Latex -> "\\#" | DotFig -> "\\\\#" let pp_k m v = pp_hash m ^ string_of_int v type 'k basic_pp = { pp_k : 'k -> string; } let pp_memo memo = function | SetFlags -> memo ^ "S" | DontSetFlags -> memo let pp_condition = function | NE -> "NE" | EQ -> "EQ" | AL -> "" let pp_memoc memo c = sprintf "%s%s" memo (pp_condition c) let do_pp_instruction m = let ppi_rrr opcode s rt rn rm = pp_memo opcode s^" "^ pp_reg rt ^ "," ^ pp_reg rn ^ "," ^ pp_reg rm in let ppi_rrr_noflags opcode = ppi_rrr opcode DontSetFlags in let ppi_rri opcode s rt rn v = pp_memo opcode s^" "^pp_reg rt ^ ","^ pp_reg rn ^ "," ^ m.pp_k v in let ppi_rrmc opcode rt rn c= pp_memoc opcode c^" "^pp_reg rt ^ ","^ "[" ^ pp_reg rn ^ "]" in let ppi_rrm opcode rt rn = ppi_rrmc opcode rt rn AL in let ppi_rrrmc opcode rt ri rn c = pp_memoc opcode c^" "^pp_reg rt ^ ","^ "[" ^ pp_reg ri ^ "," ^ pp_reg rn ^ "]" in let ppi_strex opcode rt rn rm c = pp_memoc opcode c^" "^pp_reg rt ^ ","^ pp_reg rn ^ ",[" ^ pp_reg rm ^ "]" in let ppi_rr opcode rt rn = opcode^" "^pp_reg rt ^ ","^ pp_reg rn in let ppi_rrc opcode rt rn c= pp_memoc opcode c^" "^pp_reg rt ^ ","^ pp_reg rn in let ppi_ri opcode r i = opcode^" "^pp_reg r ^ "," ^ m.pp_k i in let ppi_ric opcode r i c= pp_memoc opcode c^" "^pp_reg r ^ "," ^ m.pp_k i in fun i -> match i with | I_NOP -> "NOP" | I_ADD(s,rt,rn,v) -> ppi_rri "ADD" s rt rn v | I_ADD3 (s,r1,r2,r3) -> ppi_rrr "ADD" s r1 r2 r3 | I_SUB(s,rt,rn,v) -> ppi_rri "SUB" s rt rn v | I_SUB3 (s,r1,r2,r3) -> ppi_rrr "SUB" s r1 r2 r3 | I_AND(s,rt,rn,v) -> ppi_rri "AND" s rt rn v | I_B v -> "B " ^ pp_lbl v | I_BEQ(v) -> "BEQ "^ pp_lbl v | I_BNE(v) -> "BNE "^ pp_lbl v | I_CB (n,r,lbl) -> sprintf "CB%sZ" (if n then "N" else "") ^ " " ^ pp_reg r ^ "," ^ pp_lbl lbl | I_CMPI (r,v) -> ppi_ri "CMP" r v | I_CMP (r1,r2) -> ppi_rr "CMP" r1 r2 | I_LDREX(rt,rn) -> ppi_rrm "LDREX" rt rn | I_LDR(rt,rn,c) -> ppi_rrmc "LDR" rt rn c | I_LDR3(rt,rn,rm,c) -> ppi_rrrmc "LDR" rt rn rm c | I_STR(rt,rn,c) -> ppi_rrmc "STR" rt rn c | I_STR3(rt,rn,rm,c) -> ppi_rrrmc "STR" rt rn rm c | I_STREX(rt,rn,rm,c) -> ppi_strex "STREX" rt rn rm c | I_MOVI(r,i,c) -> ppi_ric "MOV" r i c | I_MOV(r1,r2,c) -> ppi_rrc "MOV" r1 r2 c | I_XOR(s,r1,r2,r3) -> ppi_rrr "EOR" s r1 r2 r3 | I_DMB o -> pp_barrier_ins "DMB" o | I_DSB o -> pp_barrier_ins "DSB" o | I_ISB -> "ISB" | I_SADD16 (r1,r2,r3) -> ppi_rrr_noflags "SADD16" r1 r2 r3 | I_SEL (r1,r2,r3) -> ppi_rrr_noflags "SEL" r1 r2 r3 let pp_instruction m = do_pp_instruction {pp_k = pp_k m} let dump_instruction = do_pp_instruction {pp_k = (fun v -> "#" ^ string_of_int v)} and dump_parsedInstruction = do_pp_instruction {pp_k = MetaConst.pp_prefix "#"; } let dump_instruction_hash = dump_instruction (****************************) (* Symbolic registers stuff *) (****************************) let allowed_for_symb = [ R0 ; R1 ; R2 ; R3 ; R4 ; R5 ; R6 ; R7 ; R8 ; R9 ; R10; R11; R12 ] let fold_regs (f_reg,f_sreg) = let fold_reg reg (y_reg,y_sreg) = match reg with | R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | R11 | R12 | SP | LR | PC | Z | RESADDR -> f_reg reg y_reg,y_sreg | Symbolic_reg reg -> y_reg,f_sreg reg y_sreg | Internal _ -> y_reg,y_sreg in fun c ins -> match ins with | I_ADD (_,r1, r2, _) | I_SUB (_,r1, r2, _) | I_AND (_,r1, r2, _) | I_LDR (r1, r2, _) | I_LDREX (r1, r2) | I_STR (r1, r2, _) | I_MOV (r1, r2, _) | I_CMP (r1,r2) -> fold_reg r2 (fold_reg r1 c) | I_LDR3 (r1, r2, r3, _) | I_ADD3 (_, r1, r2, r3) | I_SUB3 (_, r1, r2, r3) | I_STR3 (r1, r2, r3, _) | I_STREX (r1, r2, r3, _) | I_XOR (_,r1, r2, r3) | I_SADD16 (r1, r2, r3) | I_SEL (r1, r2, r3) -> fold_reg r3 (fold_reg r2 (fold_reg r1 c)) | I_CMPI (r, _) | I_MOVI (r, _, _) | I_CB (_,r,_) -> fold_reg r c | I_NOP | I_B _ | I_BEQ _ | I_BNE _ | I_DMB _ | I_DSB _ | I_ISB -> c let map_regs f_reg f_symb = let map_reg reg = match reg with | R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | R11 | R12 | SP | LR | PC | Z | RESADDR -> f_reg reg | Symbolic_reg reg -> f_symb reg | Internal _ -> reg in fun ins -> match ins with | I_ADD (s,r1, r2, k) -> I_ADD (s,map_reg r1, map_reg r2, k) | I_ADD3 (s,r1, r2, r3) -> I_ADD3 (s,map_reg r1, map_reg r2, map_reg r3) | I_SUB (s,r1, r2, k) -> I_SUB (s,map_reg r1, map_reg r2, k) | I_SUB3 (s,r1, r2, r3) -> I_SUB3 (s,map_reg r1, map_reg r2, map_reg r3) | I_AND (s,r1, r2, k) -> I_AND (s,map_reg r1, map_reg r2, k) | I_NOP | I_B _ | I_BEQ _ | I_BNE _ -> ins | I_CB (n,r,lbl) -> I_CB (n,map_reg r,lbl) | I_CMPI (r, k) -> I_CMPI (map_reg r, k) | I_CMP (r1, r2) -> I_CMP (map_reg r1, map_reg r2) | I_LDREX (r1, r2) -> I_LDREX (map_reg r1, map_reg r2) | I_LDR (r1, r2, c) -> I_LDR (map_reg r1, map_reg r2, c) | I_LDR3 (r1, r2, r3, c) -> I_LDR3 (map_reg r1, map_reg r2, map_reg r3, c) | I_STR (r1, r2, c) -> I_STR (map_reg r1, map_reg r2, c) | I_STR3 (r1, r2, r3, c) -> I_STR3 (map_reg r1, map_reg r2, map_reg r3, c) | I_STREX (r1, r2, r3, c) -> I_STREX (map_reg r1, map_reg r2, map_reg r3, c) | I_MOVI (r, k, c) -> I_MOVI (map_reg r, k, c) | I_MOV (r1, r2, c) -> I_MOV (map_reg r1, map_reg r2, c) | I_XOR (s,r1, r2, r3) -> I_XOR (s,map_reg r1, map_reg r2, map_reg r3) | I_DMB _ | I_DSB _ | I_ISB -> ins | I_SADD16 (r1, r2, r3) -> I_SADD16 (map_reg r1, map_reg r2, map_reg r3) | I_SEL (r1, r2, r3) -> I_SEL (map_reg r1, map_reg r2, map_reg r3) (* No addresses burried in ARM code *) let fold_addrs _f c _ins = c let map_addrs _f ins = ins let norm_ins ins = ins PLDI submission , complete later let is_data _ _ = assert false (* Instruction continuation *) let get_next = function | I_NOP | I_ADD _ | I_ADD3 _ | I_SUB _ | I_SUB3 _ | I_AND _ | I_CMPI _ | I_CMP _ | I_LDR _ | I_LDREX _ | I_LDR3 _ | I_STR _ | I_STR3 _ | I_STREX _ | I_MOVI _ | I_MOV _ | I_XOR _ | I_DMB _ | I_DSB _ | I_ISB | I_SADD16 _ | I_SEL _ -> [Label.Next] | I_B lbl -> [Label.To lbl] | I_BEQ lbl|I_BNE lbl|I_CB (_,_,lbl) -> [Label.Next; Label.To lbl] include Pseudo.Make (struct type ins = instruction type pins = parsedInstruction type reg_arg = reg let parsed_tr = function | I_ADD (c,r1,r2,k) -> I_ADD (c,r1,r2,MetaConst.as_int k) | I_SUB (c,r1,r2,k) -> I_SUB (c,r1,r2,MetaConst.as_int k) | I_AND (c,r1,r2,k) -> I_AND (c,r1,r2,MetaConst.as_int k) | I_CMPI (r,k) -> I_CMPI (r,MetaConst.as_int k) | I_MOVI (r,k,c) -> I_MOVI (r,MetaConst.as_int k,c) | I_NOP | I_ADD3 _ | I_SUB3 _ | I_B _ | I_BEQ _ | I_BNE _ | I_CB _ | I_CMP _ | I_LDR _ | I_LDREX _ | I_LDR3 _ | I_STR _ | I_STR3 _ | I_STREX _ | I_MOV _ | I_XOR _ | I_DMB _ | I_DSB _ | I_ISB | I_SADD16 _ | I_SEL _ as keep -> keep let get_naccesses = function | I_NOP | I_ADD _ | I_ADD3 _ | I_SUB _ | I_SUB3 _ | I_AND _ | I_B _ | I_BEQ _ | I_BNE _ | I_CB _ | I_CMPI _ | I_CMP _ | I_MOVI _ | I_MOV _ | I_XOR _ | I_DMB _ | I_DSB _ | I_ISB | I_SADD16 _ | I_SEL _ -> 0 | I_LDR _ | I_LDREX _ | I_LDR3 _ | I_STR _ | I_STR3 _ | I_STREX _ -> 1 let fold_labels k f = function | I_B lbl | I_BEQ lbl | I_BNE lbl | I_CB (_,_,lbl) -> f k lbl | _ -> k let map_labels f = function | I_B lbl -> I_B (f lbl) | I_BEQ lbl -> I_BEQ (f lbl) | I_BNE lbl -> I_BNE (f lbl) | I_CB (n,r,lbl) -> I_CB (n,r,f lbl) | ins -> ins end) let get_macro _name = raise Not_found let get_id_and_list _i = Warn.fatal "get_id_and_list is only for Bell" let hash_pteval _ = assert false module Instr = Instr.No(struct type instr = instruction end)
null
https://raw.githubusercontent.com/herd/herdtools7/b22ec02af1300a45e2b646cce4253ecd4fa7f250/lib/ARMBase.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, ************************************************************************** * Define registers, barriers, and instructions for ARM Who am i ? *********** Registers *********** condition flags ********** ********** ************** Instructions ************** ALWAYS Was maybeVal ??? SIMD ************************** Symbolic registers stuff ************************** No addresses burried in ARM code Instruction continuation
, 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 . open Printf let arch = Archs.arm let endian = Endian.Little let base_type = CType.Base "int" type reg = | R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | R11 | R12 | SP | LR | PC | Symbolic_reg of string | Internal of int | RESADDR let base = Internal 0 and max_idx = Internal 1 and idx = Internal 2 and ephemeral = Internal 3 let loop_idx = Internal 4 let pc = PC let regs = [ R0, "R0" ; R1, "R1" ; R2, "R2" ; R3, "R3" ; R4, "R4" ; R5, "R5" ; R6, "R6" ; R7, "R7" ; R8, "R8" ; R9, "R9" ; R10, "R10" ; R11, "R11" ; R12, "R12" ; SP, "SP" ; LR, "LR" ; PC, "PC" ; Z, "Z" ; RESADDR, "RESADDR" ; ] let to_parse = List.filter (fun (r,_) -> match r with | Z|RESADDR -> false | _ -> true) regs let parse_list = List.map (fun (r,s) -> s,r) (List.filter (fun (r,_) -> match r with | Z|RESADDR -> false | _ -> true) regs) let parse_reg s = try Some (List.assoc s parse_list) with Not_found -> None let pp_reg r = match r with | Symbolic_reg r -> "%"^r | Internal i -> Printf.sprintf "i%i" i | _ -> try List.assoc r regs with Not_found -> assert false let reg_compare = compare let symb_reg_name = function | Symbolic_reg r -> Some r | _ -> None let symb_reg r = Symbolic_reg r let type_reg _ = base_type Barriers type barrier_option = | SY | ST | ISH | ISHST | NSH | NSHST | OSH | OSHST let fold_barrier_option f k = let k = f SY k in let k = f ST k in let k = f ISH k in let k = f ISHST k in let k = f NSH k in let k = f NSHST k in let k = f OSH k in let k = f OSHST k in k type barrier = | DMB of barrier_option | DSB of barrier_option | ISB let all_kinds_of_barriers = [DMB SY; ] let pp_option = function | SY -> "SY" | ST -> "ST" | ISH -> "ISH" | ISHST -> "ISHST" | NSH -> "NSH" | NSHST -> "NSHST" | OSH -> "OSH" | OSHST -> "OSHST" let pp_barrier_option memo o = match o with | SY -> memo | _ -> sprintf "%s.%s" memo (pp_option o) let pp_barrier_ins memo o = match o with | SY -> memo | _ -> sprintf "%s %s" memo (pp_option o) let pp_barrier b = match b with | DMB o -> pp_barrier_option "DMB" o | DSB o -> pp_barrier_option "DSB" o | ISB -> "ISB" let barrier_compare = compare type lbl = Label.t type setflags = SetFlags | DontSetFlags type 'k kinstruction = | I_NOP | I_ADD of setflags * reg * reg * 'k | I_ADD3 of setflags * reg * reg * reg | I_SUB of setflags * reg * reg * 'k | I_SUB3 of setflags * reg * reg * reg | I_AND of setflags * reg * reg * 'k | I_B of lbl | I_BEQ of lbl | I_CB of bool * reg * lbl | I_CMPI of reg * 'k | I_CMP of reg * reg | I_LDR of reg * reg * condition | I_LDREX of reg * reg | I_LDR3 of reg * reg * reg * condition | I_STR of reg * reg * condition | I_STR3 of reg * reg * reg * condition | I_STREX of reg * reg * reg * condition | I_MOVI of reg * 'k * condition | I_MOV of reg * reg * condition | I_XOR of setflags * reg * reg * reg | I_DMB of barrier_option | I_DSB of barrier_option | I_ISB | I_SADD16 of reg * reg * reg | I_SEL of reg * reg * reg type instruction = int kinstruction type parsedInstruction = MetaConst.k kinstruction let pp_lbl = fun i -> i open PPMode let pp_hash m = match m with | Ascii | Dot -> "#" | Latex -> "\\#" | DotFig -> "\\\\#" let pp_k m v = pp_hash m ^ string_of_int v type 'k basic_pp = { pp_k : 'k -> string; } let pp_memo memo = function | SetFlags -> memo ^ "S" | DontSetFlags -> memo let pp_condition = function | NE -> "NE" | EQ -> "EQ" | AL -> "" let pp_memoc memo c = sprintf "%s%s" memo (pp_condition c) let do_pp_instruction m = let ppi_rrr opcode s rt rn rm = pp_memo opcode s^" "^ pp_reg rt ^ "," ^ pp_reg rn ^ "," ^ pp_reg rm in let ppi_rrr_noflags opcode = ppi_rrr opcode DontSetFlags in let ppi_rri opcode s rt rn v = pp_memo opcode s^" "^pp_reg rt ^ ","^ pp_reg rn ^ "," ^ m.pp_k v in let ppi_rrmc opcode rt rn c= pp_memoc opcode c^" "^pp_reg rt ^ ","^ "[" ^ pp_reg rn ^ "]" in let ppi_rrm opcode rt rn = ppi_rrmc opcode rt rn AL in let ppi_rrrmc opcode rt ri rn c = pp_memoc opcode c^" "^pp_reg rt ^ ","^ "[" ^ pp_reg ri ^ "," ^ pp_reg rn ^ "]" in let ppi_strex opcode rt rn rm c = pp_memoc opcode c^" "^pp_reg rt ^ ","^ pp_reg rn ^ ",[" ^ pp_reg rm ^ "]" in let ppi_rr opcode rt rn = opcode^" "^pp_reg rt ^ ","^ pp_reg rn in let ppi_rrc opcode rt rn c= pp_memoc opcode c^" "^pp_reg rt ^ ","^ pp_reg rn in let ppi_ri opcode r i = opcode^" "^pp_reg r ^ "," ^ m.pp_k i in let ppi_ric opcode r i c= pp_memoc opcode c^" "^pp_reg r ^ "," ^ m.pp_k i in fun i -> match i with | I_NOP -> "NOP" | I_ADD(s,rt,rn,v) -> ppi_rri "ADD" s rt rn v | I_ADD3 (s,r1,r2,r3) -> ppi_rrr "ADD" s r1 r2 r3 | I_SUB(s,rt,rn,v) -> ppi_rri "SUB" s rt rn v | I_SUB3 (s,r1,r2,r3) -> ppi_rrr "SUB" s r1 r2 r3 | I_AND(s,rt,rn,v) -> ppi_rri "AND" s rt rn v | I_B v -> "B " ^ pp_lbl v | I_BEQ(v) -> "BEQ "^ pp_lbl v | I_BNE(v) -> "BNE "^ pp_lbl v | I_CB (n,r,lbl) -> sprintf "CB%sZ" (if n then "N" else "") ^ " " ^ pp_reg r ^ "," ^ pp_lbl lbl | I_CMPI (r,v) -> ppi_ri "CMP" r v | I_CMP (r1,r2) -> ppi_rr "CMP" r1 r2 | I_LDREX(rt,rn) -> ppi_rrm "LDREX" rt rn | I_LDR(rt,rn,c) -> ppi_rrmc "LDR" rt rn c | I_LDR3(rt,rn,rm,c) -> ppi_rrrmc "LDR" rt rn rm c | I_STR(rt,rn,c) -> ppi_rrmc "STR" rt rn c | I_STR3(rt,rn,rm,c) -> ppi_rrrmc "STR" rt rn rm c | I_STREX(rt,rn,rm,c) -> ppi_strex "STREX" rt rn rm c | I_MOVI(r,i,c) -> ppi_ric "MOV" r i c | I_MOV(r1,r2,c) -> ppi_rrc "MOV" r1 r2 c | I_XOR(s,r1,r2,r3) -> ppi_rrr "EOR" s r1 r2 r3 | I_DMB o -> pp_barrier_ins "DMB" o | I_DSB o -> pp_barrier_ins "DSB" o | I_ISB -> "ISB" | I_SADD16 (r1,r2,r3) -> ppi_rrr_noflags "SADD16" r1 r2 r3 | I_SEL (r1,r2,r3) -> ppi_rrr_noflags "SEL" r1 r2 r3 let pp_instruction m = do_pp_instruction {pp_k = pp_k m} let dump_instruction = do_pp_instruction {pp_k = (fun v -> "#" ^ string_of_int v)} and dump_parsedInstruction = do_pp_instruction {pp_k = MetaConst.pp_prefix "#"; } let dump_instruction_hash = dump_instruction let allowed_for_symb = [ R0 ; R1 ; R2 ; R3 ; R4 ; R5 ; R6 ; R7 ; R8 ; R9 ; R10; R11; R12 ] let fold_regs (f_reg,f_sreg) = let fold_reg reg (y_reg,y_sreg) = match reg with | R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | R11 | R12 | SP | LR | PC | Z | RESADDR -> f_reg reg y_reg,y_sreg | Symbolic_reg reg -> y_reg,f_sreg reg y_sreg | Internal _ -> y_reg,y_sreg in fun c ins -> match ins with | I_ADD (_,r1, r2, _) | I_SUB (_,r1, r2, _) | I_AND (_,r1, r2, _) | I_LDR (r1, r2, _) | I_LDREX (r1, r2) | I_STR (r1, r2, _) | I_MOV (r1, r2, _) | I_CMP (r1,r2) -> fold_reg r2 (fold_reg r1 c) | I_LDR3 (r1, r2, r3, _) | I_ADD3 (_, r1, r2, r3) | I_SUB3 (_, r1, r2, r3) | I_STR3 (r1, r2, r3, _) | I_STREX (r1, r2, r3, _) | I_XOR (_,r1, r2, r3) | I_SADD16 (r1, r2, r3) | I_SEL (r1, r2, r3) -> fold_reg r3 (fold_reg r2 (fold_reg r1 c)) | I_CMPI (r, _) | I_MOVI (r, _, _) | I_CB (_,r,_) -> fold_reg r c | I_NOP | I_B _ | I_BEQ _ | I_BNE _ | I_DMB _ | I_DSB _ | I_ISB -> c let map_regs f_reg f_symb = let map_reg reg = match reg with | R0 | R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 | R11 | R12 | SP | LR | PC | Z | RESADDR -> f_reg reg | Symbolic_reg reg -> f_symb reg | Internal _ -> reg in fun ins -> match ins with | I_ADD (s,r1, r2, k) -> I_ADD (s,map_reg r1, map_reg r2, k) | I_ADD3 (s,r1, r2, r3) -> I_ADD3 (s,map_reg r1, map_reg r2, map_reg r3) | I_SUB (s,r1, r2, k) -> I_SUB (s,map_reg r1, map_reg r2, k) | I_SUB3 (s,r1, r2, r3) -> I_SUB3 (s,map_reg r1, map_reg r2, map_reg r3) | I_AND (s,r1, r2, k) -> I_AND (s,map_reg r1, map_reg r2, k) | I_NOP | I_B _ | I_BEQ _ | I_BNE _ -> ins | I_CB (n,r,lbl) -> I_CB (n,map_reg r,lbl) | I_CMPI (r, k) -> I_CMPI (map_reg r, k) | I_CMP (r1, r2) -> I_CMP (map_reg r1, map_reg r2) | I_LDREX (r1, r2) -> I_LDREX (map_reg r1, map_reg r2) | I_LDR (r1, r2, c) -> I_LDR (map_reg r1, map_reg r2, c) | I_LDR3 (r1, r2, r3, c) -> I_LDR3 (map_reg r1, map_reg r2, map_reg r3, c) | I_STR (r1, r2, c) -> I_STR (map_reg r1, map_reg r2, c) | I_STR3 (r1, r2, r3, c) -> I_STR3 (map_reg r1, map_reg r2, map_reg r3, c) | I_STREX (r1, r2, r3, c) -> I_STREX (map_reg r1, map_reg r2, map_reg r3, c) | I_MOVI (r, k, c) -> I_MOVI (map_reg r, k, c) | I_MOV (r1, r2, c) -> I_MOV (map_reg r1, map_reg r2, c) | I_XOR (s,r1, r2, r3) -> I_XOR (s,map_reg r1, map_reg r2, map_reg r3) | I_DMB _ | I_DSB _ | I_ISB -> ins | I_SADD16 (r1, r2, r3) -> I_SADD16 (map_reg r1, map_reg r2, map_reg r3) | I_SEL (r1, r2, r3) -> I_SEL (map_reg r1, map_reg r2, map_reg r3) let fold_addrs _f c _ins = c let map_addrs _f ins = ins let norm_ins ins = ins PLDI submission , complete later let is_data _ _ = assert false let get_next = function | I_NOP | I_ADD _ | I_ADD3 _ | I_SUB _ | I_SUB3 _ | I_AND _ | I_CMPI _ | I_CMP _ | I_LDR _ | I_LDREX _ | I_LDR3 _ | I_STR _ | I_STR3 _ | I_STREX _ | I_MOVI _ | I_MOV _ | I_XOR _ | I_DMB _ | I_DSB _ | I_ISB | I_SADD16 _ | I_SEL _ -> [Label.Next] | I_B lbl -> [Label.To lbl] | I_BEQ lbl|I_BNE lbl|I_CB (_,_,lbl) -> [Label.Next; Label.To lbl] include Pseudo.Make (struct type ins = instruction type pins = parsedInstruction type reg_arg = reg let parsed_tr = function | I_ADD (c,r1,r2,k) -> I_ADD (c,r1,r2,MetaConst.as_int k) | I_SUB (c,r1,r2,k) -> I_SUB (c,r1,r2,MetaConst.as_int k) | I_AND (c,r1,r2,k) -> I_AND (c,r1,r2,MetaConst.as_int k) | I_CMPI (r,k) -> I_CMPI (r,MetaConst.as_int k) | I_MOVI (r,k,c) -> I_MOVI (r,MetaConst.as_int k,c) | I_NOP | I_ADD3 _ | I_SUB3 _ | I_B _ | I_BEQ _ | I_BNE _ | I_CB _ | I_CMP _ | I_LDR _ | I_LDREX _ | I_LDR3 _ | I_STR _ | I_STR3 _ | I_STREX _ | I_MOV _ | I_XOR _ | I_DMB _ | I_DSB _ | I_ISB | I_SADD16 _ | I_SEL _ as keep -> keep let get_naccesses = function | I_NOP | I_ADD _ | I_ADD3 _ | I_SUB _ | I_SUB3 _ | I_AND _ | I_B _ | I_BEQ _ | I_BNE _ | I_CB _ | I_CMPI _ | I_CMP _ | I_MOVI _ | I_MOV _ | I_XOR _ | I_DMB _ | I_DSB _ | I_ISB | I_SADD16 _ | I_SEL _ -> 0 | I_LDR _ | I_LDREX _ | I_LDR3 _ | I_STR _ | I_STR3 _ | I_STREX _ -> 1 let fold_labels k f = function | I_B lbl | I_BEQ lbl | I_BNE lbl | I_CB (_,_,lbl) -> f k lbl | _ -> k let map_labels f = function | I_B lbl -> I_B (f lbl) | I_BEQ lbl -> I_BEQ (f lbl) | I_BNE lbl -> I_BNE (f lbl) | I_CB (n,r,lbl) -> I_CB (n,r,f lbl) | ins -> ins end) let get_macro _name = raise Not_found let get_id_and_list _i = Warn.fatal "get_id_and_list is only for Bell" let hash_pteval _ = assert false module Instr = Instr.No(struct type instr = instruction end)
b02ac930720ef4a3c663f7be1ae90e3cfeefabbb0807066d57e06b9b959b32b1
typelead/eta
T3743.hs
{ - # OPTIONS_GHC -fno - warn - redundant - constraints # - } {-# LANGUAGE ImplicitParams, GADTs #-} module T3743 where class Foo a data M where M :: Foo a => a -> M x :: (?x :: ()) => () x = undefined -- foo :: (?x :: ()) => M -> () foo y = case y of M _ -> x
null
https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/T3743.hs
haskell
# LANGUAGE ImplicitParams, GADTs # foo :: (?x :: ()) => M -> ()
{ - # OPTIONS_GHC -fno - warn - redundant - constraints # - } module T3743 where class Foo a data M where M :: Foo a => a -> M x :: (?x :: ()) => () x = undefined foo y = case y of M _ -> x
c0fd215c18fbfa088459a33fb8b16e28584356f9a31b1eb8db6cae8faa37a0ce
SchornacklabSLCU/amfinder
amfbrowser.ml
AMFinder - amfbrowser.ml * * MIT License * Copyright ( c ) 2021 * * 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 . * * MIT License * Copyright (c) 2021 Edouard Evangelisti * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. *) let imgr = ref None (* Callbacks apply to the active image. It is given as * a reference so changes won't affect callback behavior. *) let connect_callbacks () = let open AmfCallback in AmfLog.info_debug "Setting up GTK callbacks"; GtkWindow events . Window.save imgr; Window.cursor imgr; Window.annotate imgr; (* Magnifier events. *) Magnifier.capture_screenshot imgr; (* Prediction events. *) Predictions.convert imgr; Predictions.update_list imgr; Predictions.update_cam imgr; Predictions.select_list_item imgr; Predictions.move_to_ambiguous_tile imgr; (* GtkToggleButtons. *) ToggleBar.annotate imgr; (* GtkDrawingArea events. *) DrawingArea.cursor imgr; DrawingArea.annotate imgr; DrawingArea.repaint imgr; DrawingArea.repaint_and_count imgr; (* Toolbox events. *) Toolbox.snap imgr; Toolbox.export imgr let load_image () = (* Retrieve input image. *) let path = match !AmfPar.path with | None -> AmfUI.FileChooser.run () | Some path -> path in AmfLog.info_debug "Input image: %s" path; (* Displays the main window and sets UI drawing parameters. *) AmfUI.window#show (); (* Loads the image based on UI drawing parameters. *) let image = AmfImage.create path in imgr := Some image; image#show () let _ = print_endline "amfbrowser version 2.0"; AmfLog.info_debug "Running in verbose mode (debugging)"; Printexc.record_backtrace true; AmfPar.initialize (); connect_callbacks (); load_image (); GMain.main ()
null
https://raw.githubusercontent.com/SchornacklabSLCU/amfinder/1053045b431b9e9e85a7bcebea2e38cda92a8dcd/amfbrowser/sources/amfbrowser.ml
ocaml
Callbacks apply to the active image. It is given as * a reference so changes won't affect callback behavior. Magnifier events. Prediction events. GtkToggleButtons. GtkDrawingArea events. Toolbox events. Retrieve input image. Displays the main window and sets UI drawing parameters. Loads the image based on UI drawing parameters.
AMFinder - amfbrowser.ml * * MIT License * Copyright ( c ) 2021 * * 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 . * * MIT License * Copyright (c) 2021 Edouard Evangelisti * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. *) let imgr = ref None let connect_callbacks () = let open AmfCallback in AmfLog.info_debug "Setting up GTK callbacks"; GtkWindow events . Window.save imgr; Window.cursor imgr; Window.annotate imgr; Magnifier.capture_screenshot imgr; Predictions.convert imgr; Predictions.update_list imgr; Predictions.update_cam imgr; Predictions.select_list_item imgr; Predictions.move_to_ambiguous_tile imgr; ToggleBar.annotate imgr; DrawingArea.cursor imgr; DrawingArea.annotate imgr; DrawingArea.repaint imgr; DrawingArea.repaint_and_count imgr; Toolbox.snap imgr; Toolbox.export imgr let load_image () = let path = match !AmfPar.path with | None -> AmfUI.FileChooser.run () | Some path -> path in AmfLog.info_debug "Input image: %s" path; AmfUI.window#show (); let image = AmfImage.create path in imgr := Some image; image#show () let _ = print_endline "amfbrowser version 2.0"; AmfLog.info_debug "Running in verbose mode (debugging)"; Printexc.record_backtrace true; AmfPar.initialize (); connect_callbacks (); load_image (); GMain.main ()
31cef171613025bce8146cde93563d2588389dd0ae2972290e492ea308dc39f6
damhiya/MetaLambda
PrettyPrinter.hs
module MetaLambda.ConcreteSyntax.PrettyPrinter where import Prettyprinter import MetaLambda.Syntax prettyId :: Id -> Doc ann prettyId (Id x i) = pretty $ mconcat [x,"_",show i] prettyGId :: GId -> Doc ann prettyGId (GId u i) = pretty $ mconcat [u,"_",show i] arrow :: Doc ann arrow = "->" vdash :: Doc ann vdash = "|-" typing :: Id -> Type -> Doc ann typing x t = hsep [prettyId x, colon, prettyType 1 t] prettyTerm :: Int -> Term -> Doc ann prettyTerm _ (Var x) = prettyId x prettyTerm p (Lam x t e) | p > 1 = parens doc | otherwise = doc where doc = hsep [ "fn" , parens $ typing x t , arrow , prettyTerm 1 e ] prettyTerm p (App t1 t2) | p > 2 = parens doc | otherwise = doc where doc = prettyTerm 2 t1 <+> prettyTerm 3 t2 prettyTerm _ (Box ctx t) = "box" <> brackets (prettyLCtx ctx <+> dot <+> prettyTerm 1 t) prettyTerm p (LetBox ectx u e1 e2) | p > 1 = parens doc | otherwise = doc where doc = hsep [ "let" , "box" <> brackets (prettyLECtx ectx <+> dot <+> prettyGId u) , "=" , prettyTerm 1 e1 , "in" , prettyTerm 1 e2 ] prettyTerm p (Clo u es) | p > 1 = parens doc | otherwise = doc where doc = hsep [prettyGId u, "with", tupled (map (prettyTerm 1) es)] prettyType :: Int -> Type -> Doc ann prettyType _ Base = "base" prettyType p (Arr t1 t2) | p > 1 = parens doc | otherwise = doc where doc = hsep [ prettyType 2 t1 , arrow , prettyType 1 t2 ] prettyType _ (BoxT ctx t) = brackets $ hsep [ prettyLCtx ctx , vdash , prettyType 1 t ] prettyLCtx :: LCtx -> Doc ann prettyLCtx ctx = hsep $ punctuate comma $ map (uncurry typing) ctx prettyLECtx :: LECtx -> Doc ann prettyLECtx ectx = hsep $ punctuate comma $ map prettyId ectx
null
https://raw.githubusercontent.com/damhiya/MetaLambda/d9fe28f3df1c8020e7d0960ca333b759e1ac5f95/src/MetaLambda/ConcreteSyntax/PrettyPrinter.hs
haskell
module MetaLambda.ConcreteSyntax.PrettyPrinter where import Prettyprinter import MetaLambda.Syntax prettyId :: Id -> Doc ann prettyId (Id x i) = pretty $ mconcat [x,"_",show i] prettyGId :: GId -> Doc ann prettyGId (GId u i) = pretty $ mconcat [u,"_",show i] arrow :: Doc ann arrow = "->" vdash :: Doc ann vdash = "|-" typing :: Id -> Type -> Doc ann typing x t = hsep [prettyId x, colon, prettyType 1 t] prettyTerm :: Int -> Term -> Doc ann prettyTerm _ (Var x) = prettyId x prettyTerm p (Lam x t e) | p > 1 = parens doc | otherwise = doc where doc = hsep [ "fn" , parens $ typing x t , arrow , prettyTerm 1 e ] prettyTerm p (App t1 t2) | p > 2 = parens doc | otherwise = doc where doc = prettyTerm 2 t1 <+> prettyTerm 3 t2 prettyTerm _ (Box ctx t) = "box" <> brackets (prettyLCtx ctx <+> dot <+> prettyTerm 1 t) prettyTerm p (LetBox ectx u e1 e2) | p > 1 = parens doc | otherwise = doc where doc = hsep [ "let" , "box" <> brackets (prettyLECtx ectx <+> dot <+> prettyGId u) , "=" , prettyTerm 1 e1 , "in" , prettyTerm 1 e2 ] prettyTerm p (Clo u es) | p > 1 = parens doc | otherwise = doc where doc = hsep [prettyGId u, "with", tupled (map (prettyTerm 1) es)] prettyType :: Int -> Type -> Doc ann prettyType _ Base = "base" prettyType p (Arr t1 t2) | p > 1 = parens doc | otherwise = doc where doc = hsep [ prettyType 2 t1 , arrow , prettyType 1 t2 ] prettyType _ (BoxT ctx t) = brackets $ hsep [ prettyLCtx ctx , vdash , prettyType 1 t ] prettyLCtx :: LCtx -> Doc ann prettyLCtx ctx = hsep $ punctuate comma $ map (uncurry typing) ctx prettyLECtx :: LECtx -> Doc ann prettyLECtx ectx = hsep $ punctuate comma $ map prettyId ectx
4960082828c0b22f02bfa8c51633a8aa278a4e4dc0d36e0d605ca5ec8f3036c6
akvo/akvo-flow-api
form_instance.clj
(ns org.akvo.flow-api.endpoint.form-instance (:require [clojure.set :refer [rename-keys]] [clojure.spec.alpha :as s] [compojure.core :refer [GET]] [org.akvo.flow-api.boundary.form-instance :as form-instance] [org.akvo.flow-api.boundary.survey :as survey] [org.akvo.flow-api.boundary.user :as user] [org.akvo.flow-api.endpoint.spec :as spec] [org.akvo.flow-api.endpoint.utils :as utils] [org.akvo.flow-api.datastore :as ds] [org.akvo.flow-api.middleware.resolve-alias :refer [wrap-resolve-alias]] [org.akvo.flow-api.middleware.jdo-persistent-manager :as jdo-pm] [ring.util.response :refer [response]]) (:import java.time.Instant)) (defn find-form [forms form-id] (some #(if (= (:id %) form-id) % nil) forms)) (defn next-page-url [api-root instance-id survey-id form-id page-size cursor] (utils/url-builder api-root instance-id "form_instances" {"survey_id" survey-id "form_id" form-id "page_size" page-size "cursor" cursor})) (defn add-next-page-url [form-instances api-root instance-id survey-id form-id page-size] (if (empty? (:form-instances form-instances)) (dissoc form-instances :cursor) (-> form-instances (assoc :next-page-url (next-page-url api-root instance-id survey-id form-id page-size (:cursor form-instances))) (dissoc :cursor)))) (defn parse-date [^String s] (if (.contains s "T") (try (Instant/parse s) (catch Exception _)) (try (Instant/ofEpochSecond (Long/parseLong s)) (catch Exception _)))) (defn parse-filter [^String s] (let [[_ op ts] (first (re-seq #"^(>=|>|<=|<)(\S+)$" s))] {:operator op :timestamp (parse-date ts)})) (defn valid-filter? [^String s] (let [parsed (parse-filter s)] (boolean (and (:operator parsed) (:timestamp parsed))))) (s/def ::submission-date (s/nilable valid-filter?)) (def params-spec (s/keys :req-un [::spec/survey-id ::spec/form-id] :opt-un [::spec/cursor ::spec/page-size ::submission-date])) (defn endpoint* [{:keys [remote-api]}] (GET "/form_instances" {:keys [email instance-id alias params] :as req} (ds/with-remote-api remote-api instance-id (let [{:keys [survey-id form-id page-size cursor submission-date]} (spec/validate-params params-spec (rename-keys params {:survey_id :survey-id :form_id :form-id :page_size :page-size :submission_date :submission-date})) page-size (when page-size (Long/parseLong page-size)) user-id (user/id-by-email-or-throw-error remote-api instance-id email) survey (survey/by-id remote-api instance-id user-id survey-id) form (find-form (:forms survey) form-id) parsed-date (when submission-date (parse-filter submission-date))] (if (some? form) (-> remote-api (form-instance/list instance-id user-id form {:page-size page-size :cursor cursor :submission-date (:timestamp parsed-date) :operator (:operator parsed-date)}) (add-next-page-url (utils/get-api-root req) alias survey-id form-id page-size) (response)) {:status 404 :body {"formId" form-id "message" "Form not found"}}))))) (defn endpoint [{:keys [akvo-flow-server-config] :as deps}] (-> (endpoint* deps) (wrap-resolve-alias akvo-flow-server-config) (jdo-pm/wrap-close-persistent-manager)))
null
https://raw.githubusercontent.com/akvo/akvo-flow-api/a4ac1158fe25d64639add86a075c47f8b01b9b68/api/src/clojure/org/akvo/flow_api/endpoint/form_instance.clj
clojure
(ns org.akvo.flow-api.endpoint.form-instance (:require [clojure.set :refer [rename-keys]] [clojure.spec.alpha :as s] [compojure.core :refer [GET]] [org.akvo.flow-api.boundary.form-instance :as form-instance] [org.akvo.flow-api.boundary.survey :as survey] [org.akvo.flow-api.boundary.user :as user] [org.akvo.flow-api.endpoint.spec :as spec] [org.akvo.flow-api.endpoint.utils :as utils] [org.akvo.flow-api.datastore :as ds] [org.akvo.flow-api.middleware.resolve-alias :refer [wrap-resolve-alias]] [org.akvo.flow-api.middleware.jdo-persistent-manager :as jdo-pm] [ring.util.response :refer [response]]) (:import java.time.Instant)) (defn find-form [forms form-id] (some #(if (= (:id %) form-id) % nil) forms)) (defn next-page-url [api-root instance-id survey-id form-id page-size cursor] (utils/url-builder api-root instance-id "form_instances" {"survey_id" survey-id "form_id" form-id "page_size" page-size "cursor" cursor})) (defn add-next-page-url [form-instances api-root instance-id survey-id form-id page-size] (if (empty? (:form-instances form-instances)) (dissoc form-instances :cursor) (-> form-instances (assoc :next-page-url (next-page-url api-root instance-id survey-id form-id page-size (:cursor form-instances))) (dissoc :cursor)))) (defn parse-date [^String s] (if (.contains s "T") (try (Instant/parse s) (catch Exception _)) (try (Instant/ofEpochSecond (Long/parseLong s)) (catch Exception _)))) (defn parse-filter [^String s] (let [[_ op ts] (first (re-seq #"^(>=|>|<=|<)(\S+)$" s))] {:operator op :timestamp (parse-date ts)})) (defn valid-filter? [^String s] (let [parsed (parse-filter s)] (boolean (and (:operator parsed) (:timestamp parsed))))) (s/def ::submission-date (s/nilable valid-filter?)) (def params-spec (s/keys :req-un [::spec/survey-id ::spec/form-id] :opt-un [::spec/cursor ::spec/page-size ::submission-date])) (defn endpoint* [{:keys [remote-api]}] (GET "/form_instances" {:keys [email instance-id alias params] :as req} (ds/with-remote-api remote-api instance-id (let [{:keys [survey-id form-id page-size cursor submission-date]} (spec/validate-params params-spec (rename-keys params {:survey_id :survey-id :form_id :form-id :page_size :page-size :submission_date :submission-date})) page-size (when page-size (Long/parseLong page-size)) user-id (user/id-by-email-or-throw-error remote-api instance-id email) survey (survey/by-id remote-api instance-id user-id survey-id) form (find-form (:forms survey) form-id) parsed-date (when submission-date (parse-filter submission-date))] (if (some? form) (-> remote-api (form-instance/list instance-id user-id form {:page-size page-size :cursor cursor :submission-date (:timestamp parsed-date) :operator (:operator parsed-date)}) (add-next-page-url (utils/get-api-root req) alias survey-id form-id page-size) (response)) {:status 404 :body {"formId" form-id "message" "Form not found"}}))))) (defn endpoint [{:keys [akvo-flow-server-config] :as deps}] (-> (endpoint* deps) (wrap-resolve-alias akvo-flow-server-config) (jdo-pm/wrap-close-persistent-manager)))
c9f619fe408c9a442fccc305526c559cdde29d97b915fa61ab2a1e0117108e21
alexandersgreen/qio-haskell
Heap.hs
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} | This module contains the definition of a Type Class that represents a Heap . In the context of QIO , a Heap is the type used to represent a classical basis state . An instance of a Heap is also defined , that makes use of a Map . module QIO.Heap where import qualified Data.Map as Map import Data.Maybe as Maybe import QIO.QioSyn -- | The Heap Type Class class Eq h => Heap h where -- | define an 'initial' (i.e. empty) Heap initial :: h | ' update ' the value of a Qubit within the Heap to the given Boolen value update :: h -> Qbit -> Bool -> h | Lookup the value of the given Qubit in the ( if it exists ) (?) :: h -> Qbit -> Maybe Bool | remove the given Qubit from the Heap forget :: h -> Qbit -> h | Swap the values associated with two Qubits within the Heap hswap :: h -> Qbit -> Qbit -> h hswap h x y = update (update h y (fromJust (h ? x))) x (fromJust (h ? y)) | HeapMap is simply a type synonym for a Map from Qubits to Boolean values type HeapMap = Map.Map Qbit Bool | A HeapMap is an instance of the Heap type class , where the Heap functions -- can make use of the underlying Map functions. instance Heap HeapMap where initial = Map.empty update h q b = Map.insert q b h h ? q = Map.lookup q h forget h q = Map.delete q h
null
https://raw.githubusercontent.com/alexandersgreen/qio-haskell/2525f5bad5f2f5f278da6cdc4771b08650109d04/QIO/Heap.hs
haskell
# LANGUAGE TypeSynonymInstances, FlexibleInstances # | The Heap Type Class | define an 'initial' (i.e. empty) Heap can make use of the underlying Map functions.
| This module contains the definition of a Type Class that represents a Heap . In the context of QIO , a Heap is the type used to represent a classical basis state . An instance of a Heap is also defined , that makes use of a Map . module QIO.Heap where import qualified Data.Map as Map import Data.Maybe as Maybe import QIO.QioSyn class Eq h => Heap h where initial :: h | ' update ' the value of a Qubit within the Heap to the given Boolen value update :: h -> Qbit -> Bool -> h | Lookup the value of the given Qubit in the ( if it exists ) (?) :: h -> Qbit -> Maybe Bool | remove the given Qubit from the Heap forget :: h -> Qbit -> h | Swap the values associated with two Qubits within the Heap hswap :: h -> Qbit -> Qbit -> h hswap h x y = update (update h y (fromJust (h ? x))) x (fromJust (h ? y)) | HeapMap is simply a type synonym for a Map from Qubits to Boolean values type HeapMap = Map.Map Qbit Bool | A HeapMap is an instance of the Heap type class , where the Heap functions instance Heap HeapMap where initial = Map.empty update h q b = Map.insert q b h h ? q = Map.lookup q h forget h q = Map.delete q h
82d5984b8ddda2e5c29b51537b53ce5aeda8b8295ac0a7040845f7697aa59fc6
meooow25/haccepted
LabelledGraph.hs
{-# LANGUAGE DeriveTraversable #-} | Edge - labeled / weighted graphs There are useful definitions and algorithms in Data . Tree and Data . Graph but sadly these only deal with unlabeled graphs . Most definitions here mirror those in Data . Graph . buildLG Builds a LGraph from a list of LEdges . O(n + m ) for bounds size n and m edges . dfsLTree For a LGraph that is known to be a tree , returns its LTree representation . O(n ) . lTreeToTree Drops labels from an LTree . O(n ) . Edge-labeled/weighted graphs There are useful definitions and algorithms in Data.Tree and Data.Graph but sadly these only deal with unlabeled graphs. Most definitions here mirror those in Data.Graph. buildLG Builds a LGraph from a list of LEdges. O(n + m) for bounds size n and m edges. dfsLTree For a LGraph that is known to be a tree, returns its LTree representation. O(n). lTreeToTree Drops labels from an LTree. O(n). -} module LabelledGraph ( LEdge , LGraph , LTree(..) , buildLG , dfsLTree , lTreeToTree ) where import Data.Array import Data.Graph import Control.DeepSeq type LEdge b = (Vertex, (b, Vertex)) type LGraph b = Array Vertex [(b, Vertex)] data LTree b a = LNode { rootLabelL :: a , subForestL :: [(b, LTree b a)] } deriving (Eq, Show, Functor, Foldable, Traversable) buildLG :: Bounds -> [LEdge b] -> LGraph b buildLG = accumArray (flip (:)) [] dfsLTree :: LGraph b -> Vertex -> LTree b Vertex dfsLTree g u = go u u where go p u = LNode u [(l, go u v) | (l, v) <- g!u, v /= p] lTreeToTree :: LTree b a -> Tree a lTreeToTree (LNode a ts) = Node a $ map (lTreeToTree . snd) ts -------------------------------------------------------------------------------- -- For tests instance (NFData a, NFData b) => NFData (LTree b a) where rnf (LNode u ts) = rnf u `seq` rnf ts
null
https://raw.githubusercontent.com/meooow25/haccepted/d7313e905988a5d1ef0f4666aa2b91169d48f26f/src/LabelledGraph.hs
haskell
# LANGUAGE DeriveTraversable # ------------------------------------------------------------------------------ For tests
| Edge - labeled / weighted graphs There are useful definitions and algorithms in Data . Tree and Data . Graph but sadly these only deal with unlabeled graphs . Most definitions here mirror those in Data . Graph . buildLG Builds a LGraph from a list of LEdges . O(n + m ) for bounds size n and m edges . dfsLTree For a LGraph that is known to be a tree , returns its LTree representation . O(n ) . lTreeToTree Drops labels from an LTree . O(n ) . Edge-labeled/weighted graphs There are useful definitions and algorithms in Data.Tree and Data.Graph but sadly these only deal with unlabeled graphs. Most definitions here mirror those in Data.Graph. buildLG Builds a LGraph from a list of LEdges. O(n + m) for bounds size n and m edges. dfsLTree For a LGraph that is known to be a tree, returns its LTree representation. O(n). lTreeToTree Drops labels from an LTree. O(n). -} module LabelledGraph ( LEdge , LGraph , LTree(..) , buildLG , dfsLTree , lTreeToTree ) where import Data.Array import Data.Graph import Control.DeepSeq type LEdge b = (Vertex, (b, Vertex)) type LGraph b = Array Vertex [(b, Vertex)] data LTree b a = LNode { rootLabelL :: a , subForestL :: [(b, LTree b a)] } deriving (Eq, Show, Functor, Foldable, Traversable) buildLG :: Bounds -> [LEdge b] -> LGraph b buildLG = accumArray (flip (:)) [] dfsLTree :: LGraph b -> Vertex -> LTree b Vertex dfsLTree g u = go u u where go p u = LNode u [(l, go u v) | (l, v) <- g!u, v /= p] lTreeToTree :: LTree b a -> Tree a lTreeToTree (LNode a ts) = Node a $ map (lTreeToTree . snd) ts instance (NFData a, NFData b) => NFData (LTree b a) where rnf (LNode u ts) = rnf u `seq` rnf ts
d0c9c4f126548fdbc2307a6f09ef86d60eda0c1892bc98b6f778d54e80d44ec2
ocamllabs/ocaml-effects
ocamldep.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1999 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) open Compenv open Parsetree let ppf = Format.err_formatter (* Print the dependencies *) type file_kind = ML | MLI;; let load_path = ref ([] : (string * string array) list) let ml_synonyms = ref [".ml"] let mli_synonyms = ref [".mli"] let native_only = ref false let error_occurred = ref false let raw_dependencies = ref false let sort_files = ref false let all_dependencies = ref false let one_line = ref false let files = ref [] let allow_approximation = ref false Fix path to use ' / ' as directory separator instead of ' \ ' . Only under Windows . Only under Windows. *) let fix_slash s = if Sys.os_type = "Unix" then s else begin String.map (function '\\' -> '/' | c -> c) s end Since we reinitialize load_path after reading OCAMLCOMP , we must use a cache instead of calling Sys.readdir too often . we must use a cache instead of calling Sys.readdir too often. *) module StringMap = Map.Make(String) let dirs = ref StringMap.empty let readdir dir = try StringMap.find dir !dirs with Not_found -> let contents = try Sys.readdir dir with Sys_error msg -> Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg; error_occurred := true; [||] in dirs := StringMap.add dir contents !dirs; contents let add_to_list li s = li := s :: !li let add_to_load_path dir = try let dir = Misc.expand_directory Config.standard_library dir in let contents = readdir dir in add_to_list load_path (dir, contents) with Sys_error msg -> Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg; error_occurred := true let add_to_synonym_list synonyms suffix = if (String.length suffix) > 1 && suffix.[0] = '.' then add_to_list synonyms suffix else begin Format.fprintf Format.err_formatter "@[Bad suffix: '%s'@]@." suffix; error_occurred := true end (* Find file 'name' (capitalized) in search path *) let find_file name = let uname = String.uncapitalize_ascii name in let rec find_in_array a pos = if pos >= Array.length a then None else begin let s = a.(pos) in if s = name || s = uname then Some s else find_in_array a (pos + 1) end in let rec find_in_path = function [] -> raise Not_found | (dir, contents) :: rem -> match find_in_array contents 0 with Some truename -> if dir = "." then truename else Filename.concat dir truename | None -> find_in_path rem in find_in_path !load_path let rec find_file_in_list = function [] -> raise Not_found | x :: rem -> try find_file x with Not_found -> find_file_in_list rem let find_dependency target_kind modname (byt_deps, opt_deps) = try let candidates = List.map ((^) modname) !mli_synonyms in let filename = find_file_in_list candidates in let basename = Filename.chop_extension filename in let cmi_file = basename ^ ".cmi" in let ml_exists = List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !ml_synonyms in let new_opt_dep = if !all_dependencies then match target_kind with | MLI -> [ cmi_file ] | ML -> cmi_file :: (if ml_exists then [ basename ^ ".cmx"] else []) else this is a make - specific hack that makes .cmx to be a ' proxy ' target that would force the dependency on via transitivity target that would force the dependency on .cmi via transitivity *) if ml_exists then [ basename ^ ".cmx" ] else [ cmi_file ] in ( cmi_file :: byt_deps, new_opt_dep @ opt_deps) with Not_found -> try " just .ml " case let candidates = List.map ((^) modname) !ml_synonyms in let filename = find_file_in_list candidates in let basename = Filename.chop_extension filename in let bytenames = if !all_dependencies then match target_kind with | MLI -> [basename ^ ".cmi"] | ML -> [basename ^ ".cmi";] else (* again, make-specific hack *) [basename ^ (if !native_only then ".cmx" else ".cmo")] in let optnames = if !all_dependencies then match target_kind with | MLI -> [basename ^ ".cmi"] | ML -> [basename ^ ".cmi"; basename ^ ".cmx"] else [ basename ^ ".cmx" ] in (bytenames @ byt_deps, optnames @ opt_deps) with Not_found -> (byt_deps, opt_deps) let (depends_on, escaped_eol) = (":", " \\\n ") let print_filename s = let s = if !Clflags.force_slash then fix_slash s else s in if not (String.contains s ' ') then begin print_string s; end else begin let rec count n i = if i >= String.length s then n else if s.[i] = ' ' then count (n+1) (i+1) else count n (i+1) in let spaces = count 0 0 in let result = Bytes.create (String.length s + spaces) in let rec loop i j = if i >= String.length s then () else if s.[i] = ' ' then begin Bytes.set result j '\\'; Bytes.set result (j+1) ' '; loop (i+1) (j+2); end else begin Bytes.set result j s.[i]; loop (i+1) (j+1); end in loop 0 0; print_bytes result; end ;; let print_dependencies target_files deps = let rec print_items pos = function [] -> print_string "\n" | dep :: rem -> if !one_line || (pos + 1 + String.length dep <= 77) then begin if pos <> 0 then print_string " "; print_filename dep; print_items (pos + String.length dep + 1) rem end else begin print_string escaped_eol; print_filename dep; print_items (String.length dep + 4) rem end in print_items 0 (target_files @ [depends_on] @ deps) let print_raw_dependencies source_file deps = print_filename source_file; print_string depends_on; Depend.StringSet.iter (fun dep -> (* filter out "*predef*" *) if (String.length dep > 0) && (match dep.[0] with | 'A'..'Z' | '\128'..'\255' -> true | _ -> false) then begin print_char ' '; print_string dep end) deps; print_char '\n' (* Process one file *) let report_err exn = error_occurred := true; match exn with | Sys_error msg -> Format.fprintf Format.err_formatter "@[I/O error:@ %s@]@." msg | x -> match Location.error_of_exn x with | Some err -> Format.fprintf Format.err_formatter "@[%a@]@." Location.report_error err | None -> raise x let tool_name = "ocamldep" let rec lexical_approximation lexbuf = (* Approximation when a file can't be parsed. Heuristic: - first component of any path starting with an uppercase character is a dependency. - always skip the token after a dot, unless dot is preceded by a lower-case identifier - always skip the token after a backquote *) try let rec process after_lident lexbuf = match Lexer.token lexbuf with | Parser.UIDENT name -> Depend.free_structure_names := Depend.StringSet.add name !Depend.free_structure_names; process false lexbuf | Parser.LIDENT _ -> process true lexbuf | Parser.DOT when after_lident -> process false lexbuf | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf | Parser.EOF -> () | _ -> process false lexbuf and skip_one lexbuf = match Lexer.token lexbuf with | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf | Parser.EOF -> () | _ -> process false lexbuf in process false lexbuf with Lexer.Error _ -> lexical_approximation lexbuf let read_and_approximate inputfile = error_occurred := false; let ic = open_in_bin inputfile in try seek_in ic 0; Location.input_name := inputfile; let lexbuf = Lexing.from_channel ic in Location.init lexbuf inputfile; lexical_approximation lexbuf; close_in ic; !Depend.free_structure_names with exn -> close_in ic; report_err exn; !Depend.free_structure_names let read_parse_and_extract parse_function extract_function magic source_file = Depend.free_structure_names := Depend.StringSet.empty; try let input_file = Pparse.preprocess source_file in begin try let ast = Pparse.file ~tool_name Format.err_formatter input_file parse_function magic in let bound_vars = Depend.StringSet.empty in List.iter (fun modname -> Depend.open_module bound_vars (Longident.Lident modname) ) !Clflags.open_modules; extract_function bound_vars ast; Pparse.remove_preprocessed input_file; !Depend.free_structure_names with x -> Pparse.remove_preprocessed input_file; raise x end with x -> begin report_err x; if not !allow_approximation then Depend.StringSet.empty else read_and_approximate source_file end let ml_file_dependencies source_file = let parse_use_file_as_impl lexbuf = let f x = match x with | Ptop_def s -> s | Ptop_dir _ -> [] in List.flatten (List.map f (Parse.use_file lexbuf)) in let extracted_deps = read_parse_and_extract parse_use_file_as_impl Depend.add_implementation Config.ast_impl_magic_number source_file in if !sort_files then files := (source_file, ML, !Depend.free_structure_names) :: !files else if !raw_dependencies then begin print_raw_dependencies source_file extracted_deps end else begin let basename = Filename.chop_extension source_file in let byte_targets = [ basename ^ ".cmo" ] in let native_targets = if !all_dependencies then [ basename ^ ".cmx"; basename ^ ".o" ] else [ basename ^ ".cmx" ] in let init_deps = if !all_dependencies then [source_file] else [] in let cmi_name = basename ^ ".cmi" in let init_deps, extra_targets = if List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !mli_synonyms then (cmi_name :: init_deps, cmi_name :: init_deps), [] else (init_deps, init_deps), (if !all_dependencies then [cmi_name] else []) in let (byt_deps, native_deps) = Depend.StringSet.fold (find_dependency ML) extracted_deps init_deps in print_dependencies (byte_targets @ extra_targets) byt_deps; print_dependencies (native_targets @ extra_targets) native_deps; end let mli_file_dependencies source_file = let extracted_deps = read_parse_and_extract Parse.interface Depend.add_signature Config.ast_intf_magic_number source_file in if !sort_files then files := (source_file, MLI, extracted_deps) :: !files else if !raw_dependencies then begin print_raw_dependencies source_file extracted_deps end else begin let basename = Filename.chop_extension source_file in let (byt_deps, _opt_deps) = Depend.StringSet.fold (find_dependency MLI) extracted_deps ([], []) in print_dependencies [basename ^ ".cmi"] byt_deps end let file_dependencies_as kind source_file = Compenv.readenv ppf Before_compile; load_path := []; List.iter add_to_load_path ( (!Compenv.last_include_dirs @ !Clflags.include_dirs @ !Compenv.first_include_dirs )); Location.input_name := source_file; try if Sys.file_exists source_file then begin match kind with | ML -> ml_file_dependencies source_file | MLI -> mli_file_dependencies source_file end with x -> report_err x let file_dependencies source_file = if List.exists (Filename.check_suffix source_file) !ml_synonyms then file_dependencies_as ML source_file else if List.exists (Filename.check_suffix source_file) !mli_synonyms then file_dependencies_as MLI source_file else () let sort_files_by_dependencies files = let h = Hashtbl.create 31 in let worklist = ref [] in (* Init Hashtbl with all defined modules *) let files = List.map (fun (file, file_kind, deps) -> let modname = String.capitalize_ascii (Filename.chop_extension (Filename.basename file)) in let key = (modname, file_kind) in let new_deps = ref [] in Hashtbl.add h key (file, new_deps); worklist := key :: !worklist; (modname, file_kind, deps, new_deps) ) files in (* Keep only dependencies to defined modules *) List.iter (fun (modname, file_kind, deps, new_deps) -> let add_dep modname kind = new_deps := (modname, kind) :: !new_deps; in Depend.StringSet.iter (fun modname -> match file_kind with ML depends both on ML and MLI if Hashtbl.mem h (modname, MLI) then add_dep modname MLI; if Hashtbl.mem h (modname, ML) then add_dep modname ML MLI depends on MLI if exists , or ML otherwise if Hashtbl.mem h (modname, MLI) then add_dep modname MLI else if Hashtbl.mem h (modname, ML) then add_dep modname ML ) deps; add dep from .ml to .mli if Hashtbl.mem h (modname, MLI) then add_dep modname MLI ) files; (* Print and remove all files with no remaining dependency. Iterate until all files have been removed (worklist is empty) or no file was removed during a turn (cycle). *) let printed = ref true in while !printed && !worklist <> [] do let files = !worklist in worklist := []; printed := false; List.iter (fun key -> let (file, deps) = Hashtbl.find h key in let set = !deps in deps := []; List.iter (fun key -> if Hashtbl.mem h key then deps := key :: !deps ) set; if !deps = [] then begin printed := true; Printf.printf "%s " file; Hashtbl.remove h key; end else worklist := key :: !worklist ) files done; if !worklist <> [] then begin Format.fprintf Format.err_formatter "@[Warning: cycle in dependencies. End of list is not sorted.@]@."; Hashtbl.iter (fun _ (file, deps) -> Format.fprintf Format.err_formatter "\t@[%s: " file; List.iter (fun (modname, kind) -> Format.fprintf Format.err_formatter "%s.%s " modname (if kind=ML then "ml" else "mli"); ) !deps; Format.fprintf Format.err_formatter "@]@."; Printf.printf "%s " file) h; end; Printf.printf "\n%!"; () (* Entry point *) let usage = "Usage: ocamldep [options] <source files>\nOptions are:" let print_version () = Format.printf "ocamldep, version %s@." Sys.ocaml_version; exit 0; ;; let print_version_num () = Format.printf "%s@." Sys.ocaml_version; exit 0; ;; let _ = Clflags.classic := false; add_to_list first_include_dirs Filename.current_dir_name; Compenv.readenv ppf Before_args; Arg.parse [ "-absname", Arg.Set Location.absname, " Show absolute filenames in error messages"; "-all", Arg.Set all_dependencies, " Generate dependencies on all files"; "-I", Arg.String (add_to_list Clflags.include_dirs), "<dir> Add <dir> to the list of include directories"; "-impl", Arg.String (file_dependencies_as ML), "<f> Process <f> as a .ml file"; "-intf", Arg.String (file_dependencies_as MLI), "<f> Process <f> as a .mli file"; "-allow-approx", Arg.Set allow_approximation, " Fallback to a lexer-based approximation on unparseable files."; "-ml-synonym", Arg.String(add_to_synonym_list ml_synonyms), "<e> Consider <e> as a synonym of the .ml extension"; "-mli-synonym", Arg.String(add_to_synonym_list mli_synonyms), "<e> Consider <e> as a synonym of the .mli extension"; "-modules", Arg.Set raw_dependencies, " Print module dependencies in raw form (not suitable for make)"; "-native", Arg.Set native_only, " Generate dependencies for native-code only (no .cmo files)"; "-one-line", Arg.Set one_line, " Output one line per file, regardless of the length"; "-open", Arg.String (add_to_list Clflags.open_modules), "<module> Opens the module <module> before typing"; "-pp", Arg.String(fun s -> Clflags.preprocessor := Some s), "<cmd> Pipe sources through preprocessor <cmd>"; "-ppx", Arg.String (add_to_list first_ppx), "<cmd> Pipe abstract syntax trees through preprocessor <cmd>"; "-slash", Arg.Set Clflags.force_slash, " (Windows) Use forward slash / instead of backslash \\ in file paths"; "-sort", Arg.Set sort_files, " Sort files according to their dependencies"; "-version", Arg.Unit print_version, " Print version and exit"; "-vnum", Arg.Unit print_version_num, " Print version number and exit"; ] file_dependencies usage; Compenv.readenv ppf Before_link; if !sort_files then sort_files_by_dependencies !files; exit (if !error_occurred then 2 else 0)
null
https://raw.githubusercontent.com/ocamllabs/ocaml-effects/36008b741adc201bf9b547545344507da603ae31/tools/ocamldep.ml
ocaml
********************************************************************* OCaml ********************************************************************* Print the dependencies Find file 'name' (capitalized) in search path again, make-specific hack filter out "*predef*" Process one file Approximation when a file can't be parsed. Heuristic: - first component of any path starting with an uppercase character is a dependency. - always skip the token after a dot, unless dot is preceded by a lower-case identifier - always skip the token after a backquote Init Hashtbl with all defined modules Keep only dependencies to defined modules Print and remove all files with no remaining dependency. Iterate until all files have been removed (worklist is empty) or no file was removed during a turn (cycle). Entry point
, projet Cristal , INRIA Rocquencourt Copyright 1999 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . open Compenv open Parsetree let ppf = Format.err_formatter type file_kind = ML | MLI;; let load_path = ref ([] : (string * string array) list) let ml_synonyms = ref [".ml"] let mli_synonyms = ref [".mli"] let native_only = ref false let error_occurred = ref false let raw_dependencies = ref false let sort_files = ref false let all_dependencies = ref false let one_line = ref false let files = ref [] let allow_approximation = ref false Fix path to use ' / ' as directory separator instead of ' \ ' . Only under Windows . Only under Windows. *) let fix_slash s = if Sys.os_type = "Unix" then s else begin String.map (function '\\' -> '/' | c -> c) s end Since we reinitialize load_path after reading OCAMLCOMP , we must use a cache instead of calling Sys.readdir too often . we must use a cache instead of calling Sys.readdir too often. *) module StringMap = Map.Make(String) let dirs = ref StringMap.empty let readdir dir = try StringMap.find dir !dirs with Not_found -> let contents = try Sys.readdir dir with Sys_error msg -> Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg; error_occurred := true; [||] in dirs := StringMap.add dir contents !dirs; contents let add_to_list li s = li := s :: !li let add_to_load_path dir = try let dir = Misc.expand_directory Config.standard_library dir in let contents = readdir dir in add_to_list load_path (dir, contents) with Sys_error msg -> Format.fprintf Format.err_formatter "@[Bad -I option: %s@]@." msg; error_occurred := true let add_to_synonym_list synonyms suffix = if (String.length suffix) > 1 && suffix.[0] = '.' then add_to_list synonyms suffix else begin Format.fprintf Format.err_formatter "@[Bad suffix: '%s'@]@." suffix; error_occurred := true end let find_file name = let uname = String.uncapitalize_ascii name in let rec find_in_array a pos = if pos >= Array.length a then None else begin let s = a.(pos) in if s = name || s = uname then Some s else find_in_array a (pos + 1) end in let rec find_in_path = function [] -> raise Not_found | (dir, contents) :: rem -> match find_in_array contents 0 with Some truename -> if dir = "." then truename else Filename.concat dir truename | None -> find_in_path rem in find_in_path !load_path let rec find_file_in_list = function [] -> raise Not_found | x :: rem -> try find_file x with Not_found -> find_file_in_list rem let find_dependency target_kind modname (byt_deps, opt_deps) = try let candidates = List.map ((^) modname) !mli_synonyms in let filename = find_file_in_list candidates in let basename = Filename.chop_extension filename in let cmi_file = basename ^ ".cmi" in let ml_exists = List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !ml_synonyms in let new_opt_dep = if !all_dependencies then match target_kind with | MLI -> [ cmi_file ] | ML -> cmi_file :: (if ml_exists then [ basename ^ ".cmx"] else []) else this is a make - specific hack that makes .cmx to be a ' proxy ' target that would force the dependency on via transitivity target that would force the dependency on .cmi via transitivity *) if ml_exists then [ basename ^ ".cmx" ] else [ cmi_file ] in ( cmi_file :: byt_deps, new_opt_dep @ opt_deps) with Not_found -> try " just .ml " case let candidates = List.map ((^) modname) !ml_synonyms in let filename = find_file_in_list candidates in let basename = Filename.chop_extension filename in let bytenames = if !all_dependencies then match target_kind with | MLI -> [basename ^ ".cmi"] | ML -> [basename ^ ".cmi";] else [basename ^ (if !native_only then ".cmx" else ".cmo")] in let optnames = if !all_dependencies then match target_kind with | MLI -> [basename ^ ".cmi"] | ML -> [basename ^ ".cmi"; basename ^ ".cmx"] else [ basename ^ ".cmx" ] in (bytenames @ byt_deps, optnames @ opt_deps) with Not_found -> (byt_deps, opt_deps) let (depends_on, escaped_eol) = (":", " \\\n ") let print_filename s = let s = if !Clflags.force_slash then fix_slash s else s in if not (String.contains s ' ') then begin print_string s; end else begin let rec count n i = if i >= String.length s then n else if s.[i] = ' ' then count (n+1) (i+1) else count n (i+1) in let spaces = count 0 0 in let result = Bytes.create (String.length s + spaces) in let rec loop i j = if i >= String.length s then () else if s.[i] = ' ' then begin Bytes.set result j '\\'; Bytes.set result (j+1) ' '; loop (i+1) (j+2); end else begin Bytes.set result j s.[i]; loop (i+1) (j+1); end in loop 0 0; print_bytes result; end ;; let print_dependencies target_files deps = let rec print_items pos = function [] -> print_string "\n" | dep :: rem -> if !one_line || (pos + 1 + String.length dep <= 77) then begin if pos <> 0 then print_string " "; print_filename dep; print_items (pos + String.length dep + 1) rem end else begin print_string escaped_eol; print_filename dep; print_items (String.length dep + 4) rem end in print_items 0 (target_files @ [depends_on] @ deps) let print_raw_dependencies source_file deps = print_filename source_file; print_string depends_on; Depend.StringSet.iter (fun dep -> if (String.length dep > 0) && (match dep.[0] with | 'A'..'Z' | '\128'..'\255' -> true | _ -> false) then begin print_char ' '; print_string dep end) deps; print_char '\n' let report_err exn = error_occurred := true; match exn with | Sys_error msg -> Format.fprintf Format.err_formatter "@[I/O error:@ %s@]@." msg | x -> match Location.error_of_exn x with | Some err -> Format.fprintf Format.err_formatter "@[%a@]@." Location.report_error err | None -> raise x let tool_name = "ocamldep" let rec lexical_approximation lexbuf = try let rec process after_lident lexbuf = match Lexer.token lexbuf with | Parser.UIDENT name -> Depend.free_structure_names := Depend.StringSet.add name !Depend.free_structure_names; process false lexbuf | Parser.LIDENT _ -> process true lexbuf | Parser.DOT when after_lident -> process false lexbuf | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf | Parser.EOF -> () | _ -> process false lexbuf and skip_one lexbuf = match Lexer.token lexbuf with | Parser.DOT | Parser.BACKQUOTE -> skip_one lexbuf | Parser.EOF -> () | _ -> process false lexbuf in process false lexbuf with Lexer.Error _ -> lexical_approximation lexbuf let read_and_approximate inputfile = error_occurred := false; let ic = open_in_bin inputfile in try seek_in ic 0; Location.input_name := inputfile; let lexbuf = Lexing.from_channel ic in Location.init lexbuf inputfile; lexical_approximation lexbuf; close_in ic; !Depend.free_structure_names with exn -> close_in ic; report_err exn; !Depend.free_structure_names let read_parse_and_extract parse_function extract_function magic source_file = Depend.free_structure_names := Depend.StringSet.empty; try let input_file = Pparse.preprocess source_file in begin try let ast = Pparse.file ~tool_name Format.err_formatter input_file parse_function magic in let bound_vars = Depend.StringSet.empty in List.iter (fun modname -> Depend.open_module bound_vars (Longident.Lident modname) ) !Clflags.open_modules; extract_function bound_vars ast; Pparse.remove_preprocessed input_file; !Depend.free_structure_names with x -> Pparse.remove_preprocessed input_file; raise x end with x -> begin report_err x; if not !allow_approximation then Depend.StringSet.empty else read_and_approximate source_file end let ml_file_dependencies source_file = let parse_use_file_as_impl lexbuf = let f x = match x with | Ptop_def s -> s | Ptop_dir _ -> [] in List.flatten (List.map f (Parse.use_file lexbuf)) in let extracted_deps = read_parse_and_extract parse_use_file_as_impl Depend.add_implementation Config.ast_impl_magic_number source_file in if !sort_files then files := (source_file, ML, !Depend.free_structure_names) :: !files else if !raw_dependencies then begin print_raw_dependencies source_file extracted_deps end else begin let basename = Filename.chop_extension source_file in let byte_targets = [ basename ^ ".cmo" ] in let native_targets = if !all_dependencies then [ basename ^ ".cmx"; basename ^ ".o" ] else [ basename ^ ".cmx" ] in let init_deps = if !all_dependencies then [source_file] else [] in let cmi_name = basename ^ ".cmi" in let init_deps, extra_targets = if List.exists (fun ext -> Sys.file_exists (basename ^ ext)) !mli_synonyms then (cmi_name :: init_deps, cmi_name :: init_deps), [] else (init_deps, init_deps), (if !all_dependencies then [cmi_name] else []) in let (byt_deps, native_deps) = Depend.StringSet.fold (find_dependency ML) extracted_deps init_deps in print_dependencies (byte_targets @ extra_targets) byt_deps; print_dependencies (native_targets @ extra_targets) native_deps; end let mli_file_dependencies source_file = let extracted_deps = read_parse_and_extract Parse.interface Depend.add_signature Config.ast_intf_magic_number source_file in if !sort_files then files := (source_file, MLI, extracted_deps) :: !files else if !raw_dependencies then begin print_raw_dependencies source_file extracted_deps end else begin let basename = Filename.chop_extension source_file in let (byt_deps, _opt_deps) = Depend.StringSet.fold (find_dependency MLI) extracted_deps ([], []) in print_dependencies [basename ^ ".cmi"] byt_deps end let file_dependencies_as kind source_file = Compenv.readenv ppf Before_compile; load_path := []; List.iter add_to_load_path ( (!Compenv.last_include_dirs @ !Clflags.include_dirs @ !Compenv.first_include_dirs )); Location.input_name := source_file; try if Sys.file_exists source_file then begin match kind with | ML -> ml_file_dependencies source_file | MLI -> mli_file_dependencies source_file end with x -> report_err x let file_dependencies source_file = if List.exists (Filename.check_suffix source_file) !ml_synonyms then file_dependencies_as ML source_file else if List.exists (Filename.check_suffix source_file) !mli_synonyms then file_dependencies_as MLI source_file else () let sort_files_by_dependencies files = let h = Hashtbl.create 31 in let worklist = ref [] in let files = List.map (fun (file, file_kind, deps) -> let modname = String.capitalize_ascii (Filename.chop_extension (Filename.basename file)) in let key = (modname, file_kind) in let new_deps = ref [] in Hashtbl.add h key (file, new_deps); worklist := key :: !worklist; (modname, file_kind, deps, new_deps) ) files in List.iter (fun (modname, file_kind, deps, new_deps) -> let add_dep modname kind = new_deps := (modname, kind) :: !new_deps; in Depend.StringSet.iter (fun modname -> match file_kind with ML depends both on ML and MLI if Hashtbl.mem h (modname, MLI) then add_dep modname MLI; if Hashtbl.mem h (modname, ML) then add_dep modname ML MLI depends on MLI if exists , or ML otherwise if Hashtbl.mem h (modname, MLI) then add_dep modname MLI else if Hashtbl.mem h (modname, ML) then add_dep modname ML ) deps; add dep from .ml to .mli if Hashtbl.mem h (modname, MLI) then add_dep modname MLI ) files; let printed = ref true in while !printed && !worklist <> [] do let files = !worklist in worklist := []; printed := false; List.iter (fun key -> let (file, deps) = Hashtbl.find h key in let set = !deps in deps := []; List.iter (fun key -> if Hashtbl.mem h key then deps := key :: !deps ) set; if !deps = [] then begin printed := true; Printf.printf "%s " file; Hashtbl.remove h key; end else worklist := key :: !worklist ) files done; if !worklist <> [] then begin Format.fprintf Format.err_formatter "@[Warning: cycle in dependencies. End of list is not sorted.@]@."; Hashtbl.iter (fun _ (file, deps) -> Format.fprintf Format.err_formatter "\t@[%s: " file; List.iter (fun (modname, kind) -> Format.fprintf Format.err_formatter "%s.%s " modname (if kind=ML then "ml" else "mli"); ) !deps; Format.fprintf Format.err_formatter "@]@."; Printf.printf "%s " file) h; end; Printf.printf "\n%!"; () let usage = "Usage: ocamldep [options] <source files>\nOptions are:" let print_version () = Format.printf "ocamldep, version %s@." Sys.ocaml_version; exit 0; ;; let print_version_num () = Format.printf "%s@." Sys.ocaml_version; exit 0; ;; let _ = Clflags.classic := false; add_to_list first_include_dirs Filename.current_dir_name; Compenv.readenv ppf Before_args; Arg.parse [ "-absname", Arg.Set Location.absname, " Show absolute filenames in error messages"; "-all", Arg.Set all_dependencies, " Generate dependencies on all files"; "-I", Arg.String (add_to_list Clflags.include_dirs), "<dir> Add <dir> to the list of include directories"; "-impl", Arg.String (file_dependencies_as ML), "<f> Process <f> as a .ml file"; "-intf", Arg.String (file_dependencies_as MLI), "<f> Process <f> as a .mli file"; "-allow-approx", Arg.Set allow_approximation, " Fallback to a lexer-based approximation on unparseable files."; "-ml-synonym", Arg.String(add_to_synonym_list ml_synonyms), "<e> Consider <e> as a synonym of the .ml extension"; "-mli-synonym", Arg.String(add_to_synonym_list mli_synonyms), "<e> Consider <e> as a synonym of the .mli extension"; "-modules", Arg.Set raw_dependencies, " Print module dependencies in raw form (not suitable for make)"; "-native", Arg.Set native_only, " Generate dependencies for native-code only (no .cmo files)"; "-one-line", Arg.Set one_line, " Output one line per file, regardless of the length"; "-open", Arg.String (add_to_list Clflags.open_modules), "<module> Opens the module <module> before typing"; "-pp", Arg.String(fun s -> Clflags.preprocessor := Some s), "<cmd> Pipe sources through preprocessor <cmd>"; "-ppx", Arg.String (add_to_list first_ppx), "<cmd> Pipe abstract syntax trees through preprocessor <cmd>"; "-slash", Arg.Set Clflags.force_slash, " (Windows) Use forward slash / instead of backslash \\ in file paths"; "-sort", Arg.Set sort_files, " Sort files according to their dependencies"; "-version", Arg.Unit print_version, " Print version and exit"; "-vnum", Arg.Unit print_version_num, " Print version number and exit"; ] file_dependencies usage; Compenv.readenv ppf Before_link; if !sort_files then sort_files_by_dependencies !files; exit (if !error_occurred then 2 else 0)
7722540f7c70aba01a96989bd96eb79253d0d573e8003f51d2dbe692753d49d7
zehaochen19/vanilla-lang
Context.hs
# LANGUAGE GeneralizedNewtypeDeriving # module Vanilla.Static.Context where import qualified Data.Sequence as S import Vanilla.Syntax.Cons (ConsVar) import Vanilla.Syntax.Expr (EVar) import Vanilla.Syntax.Type ( TEVar, TVar, Type (..), ) data CtxMember = CVar TVar | CAssump EVar Type | CCons ConsVar Type | CEVar TEVar | CSolve TEVar Type | CMarker TEVar deriving (Eq, Show) newtype Context = Context (S.Seq CtxMember) deriving (Eq, Show, Semigroup, Monoid) (|>) :: Context -> CtxMember -> Context (Context gamma) |> c = Context $ gamma S.|> c ctxElem :: CtxMember -> Context -> Bool ctxElem c (Context gamma) = c `elem` gamma ctxHole :: CtxMember -> Context -> Maybe (Context, Context) ctxHole c (Context gamma) = if c `elem` gamma then Just (dropR $ Context l, Context r) else Nothing where (r, l) = (== c) `S.breakr` gamma ctxHole2 :: CtxMember -> CtxMember -> Context -> Maybe (Context, Context, Context) ctxHole2 c1 c2 ctx = do (ctx', c) <- ctxHole c2 ctx (a, b) <- ctxHole c1 ctx' return (a, b, c) dropR :: Context -> Context dropR (Context gamma) = case S.viewr gamma of S.EmptyR -> Context S.empty gamma' S.:> _ -> Context gamma' ctxUntil :: CtxMember -> Context -> Context ctxUntil c (Context gamma) = dropR . Context $ S.dropWhileR (/= c) gamma -- | Find the solution of alpha hat in the context ctxSolve :: Context -> TEVar -> Maybe Type ctxSolve (Context gamma) alpha = loop gamma where loop S.Empty = Nothing loop (_ S.:|> CSolve alpha' ty) | alpha == alpha' = Just ty loop (ctx' S.:|> _) = loop ctx' ctxAssump :: Context -> EVar -> Maybe Type ctxAssump (Context gamma) x = loop gamma where loop S.Empty = Nothing loop (_ S.:|> CAssump x' ty) | x == x' = Just ty loop (ctx' S.:|> _) = loop ctx' ctxCons :: Context -> ConsVar -> Maybe Type ctxCons (Context gamma) c = loop gamma where loop S.Empty = Nothing loop (_ S.:|> CCons c' ty) | c == c' = Just ty loop (ctx' S.:|> _) = loop ctx' -- | Applying a context, as a substitution, to a type ctxApply :: Context -> Type -> Type ctxApply gamma ty = case ty of TVar _ -> ty TEVar alpha -> maybe ty (ctxApply gamma) $ ctxSolve gamma alpha TArr a b -> TArr (ctxApply gamma a) (ctxApply gamma b) TAll alpha a -> TAll alpha $ ctxApply gamma a TData d pat -> TData d (ctxApply gamma <$> pat)
null
https://raw.githubusercontent.com/zehaochen19/vanilla-lang/d1e2bbd3125151ce2c0ddc20f735d3a55aeb6bc8/src/Vanilla/Static/Context.hs
haskell
| Find the solution of alpha hat in the context | Applying a context, as a substitution, to a type
# LANGUAGE GeneralizedNewtypeDeriving # module Vanilla.Static.Context where import qualified Data.Sequence as S import Vanilla.Syntax.Cons (ConsVar) import Vanilla.Syntax.Expr (EVar) import Vanilla.Syntax.Type ( TEVar, TVar, Type (..), ) data CtxMember = CVar TVar | CAssump EVar Type | CCons ConsVar Type | CEVar TEVar | CSolve TEVar Type | CMarker TEVar deriving (Eq, Show) newtype Context = Context (S.Seq CtxMember) deriving (Eq, Show, Semigroup, Monoid) (|>) :: Context -> CtxMember -> Context (Context gamma) |> c = Context $ gamma S.|> c ctxElem :: CtxMember -> Context -> Bool ctxElem c (Context gamma) = c `elem` gamma ctxHole :: CtxMember -> Context -> Maybe (Context, Context) ctxHole c (Context gamma) = if c `elem` gamma then Just (dropR $ Context l, Context r) else Nothing where (r, l) = (== c) `S.breakr` gamma ctxHole2 :: CtxMember -> CtxMember -> Context -> Maybe (Context, Context, Context) ctxHole2 c1 c2 ctx = do (ctx', c) <- ctxHole c2 ctx (a, b) <- ctxHole c1 ctx' return (a, b, c) dropR :: Context -> Context dropR (Context gamma) = case S.viewr gamma of S.EmptyR -> Context S.empty gamma' S.:> _ -> Context gamma' ctxUntil :: CtxMember -> Context -> Context ctxUntil c (Context gamma) = dropR . Context $ S.dropWhileR (/= c) gamma ctxSolve :: Context -> TEVar -> Maybe Type ctxSolve (Context gamma) alpha = loop gamma where loop S.Empty = Nothing loop (_ S.:|> CSolve alpha' ty) | alpha == alpha' = Just ty loop (ctx' S.:|> _) = loop ctx' ctxAssump :: Context -> EVar -> Maybe Type ctxAssump (Context gamma) x = loop gamma where loop S.Empty = Nothing loop (_ S.:|> CAssump x' ty) | x == x' = Just ty loop (ctx' S.:|> _) = loop ctx' ctxCons :: Context -> ConsVar -> Maybe Type ctxCons (Context gamma) c = loop gamma where loop S.Empty = Nothing loop (_ S.:|> CCons c' ty) | c == c' = Just ty loop (ctx' S.:|> _) = loop ctx' ctxApply :: Context -> Type -> Type ctxApply gamma ty = case ty of TVar _ -> ty TEVar alpha -> maybe ty (ctxApply gamma) $ ctxSolve gamma alpha TArr a b -> TArr (ctxApply gamma a) (ctxApply gamma b) TAll alpha a -> TAll alpha $ ctxApply gamma a TData d pat -> TData d (ctxApply gamma <$> pat)
1f689564e6b755f04eb4c9a396f3f210a0336a7a945f52a792ea651a3838b18a
shortishly/tansu
tansu_mnesia.erl
Copyright ( c ) 2016 < > %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(tansu_mnesia). -export([activity/1]). -export([create_table/2]). -spec create_table(Table :: atom(), Options :: list()) -> ok | {error, Reason :: atom()} | {timeout, Tables :: list(atom())}. create_table(Table, Options) -> Definition = case tansu_config:db_schema() of ram -> Options; _ -> [{disc_copies, [node()]} | Options] end, case mnesia:create_table(Table, Definition) of {atomic, ok} -> ok; {aborted, {already_exists, _}} -> case mnesia:wait_for_tables([Table], tansu_config:timeout(mnesia_wait_for_tables)) of {timeout, Tables} -> {timeout, Tables}; {error, _} = Error -> Error; ok -> ok end; {aborted, Reason} -> {error, Reason} end. activity(F) -> mnesia:activity(transaction, F).
null
https://raw.githubusercontent.com/shortishly/tansu/154811fff81855419de9af380c81c7ae14e435d0/src/tansu_mnesia.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright ( c ) 2016 < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(tansu_mnesia). -export([activity/1]). -export([create_table/2]). -spec create_table(Table :: atom(), Options :: list()) -> ok | {error, Reason :: atom()} | {timeout, Tables :: list(atom())}. create_table(Table, Options) -> Definition = case tansu_config:db_schema() of ram -> Options; _ -> [{disc_copies, [node()]} | Options] end, case mnesia:create_table(Table, Definition) of {atomic, ok} -> ok; {aborted, {already_exists, _}} -> case mnesia:wait_for_tables([Table], tansu_config:timeout(mnesia_wait_for_tables)) of {timeout, Tables} -> {timeout, Tables}; {error, _} = Error -> Error; ok -> ok end; {aborted, Reason} -> {error, Reason} end. activity(F) -> mnesia:activity(transaction, F).
b95e4aaa709fe2a485294083b2cf2b0a4b13a8ac5677a39ee4adef58a490ae91
tek/polysemy-log
Log.hs
-- |Description: Internal module Polysemy.Log.Log where import Polysemy.Conc (Race) import Polysemy.Internal.Tactics (liftT) import Polysemy.Time (GhcTime, interpretTimeGhc) import Polysemy.Log.Conc (interceptDataLogConc) import Polysemy.Log.Effect.DataLog (DataLog (DataLog, Local), dataLog) import Polysemy.Log.Effect.Log (Log (Log)) import Polysemy.Log.Data.LogEntry (LogEntry, annotate) import Polysemy.Log.Data.LogMessage (LogMessage) import Polysemy.Log.Effect.LogMetadata (LogMetadata (Annotated), annotated) -- |Interpret 'Log' into the intermediate internal effect 'LogMetadata'. interpretLogLogMetadata :: Members [LogMetadata LogMessage, GhcTime] r => InterpreterFor Log r interpretLogLogMetadata = interpret \case Log msg -> annotated msg # inline interpretLogLogMetadata # -- |Interpret the intermediate internal effect 'LogMetadata' into 'DataLog'. -- Since this adds a timestamp , it has a dependency on ' GhcTime ' . Use ' interpretLogMetadataDataLog '' for a variant that interprets ' ' in - place . interpretLogMetadataDataLog :: ∀ a r . Members [DataLog (LogEntry a), GhcTime] r => InterpreterFor (LogMetadata a) r interpretLogMetadataDataLog = interpret \case Annotated msg -> dataLog =<< annotate msg {-# inline interpretLogMetadataDataLog #-} -- |Interpret the intermediate internal effect 'LogMetadata' into 'DataLog'. interpretLogMetadataDataLog' :: Members [DataLog (LogEntry a), Embed IO] r => InterpretersFor [LogMetadata a, GhcTime] r interpretLogMetadataDataLog' = interpretTimeGhc . interpretLogMetadataDataLog {-# inline interpretLogMetadataDataLog' #-} -- |Interpret 'Log' into 'DataLog', adding metadata information and wrapping with 'LogEntry'. -- Since this adds a timestamp , it has a dependency on ' GhcTime ' . Use ' interpretLogDataLog '' for a variant that interprets ' ' in - place . interpretLogDataLog :: Members [DataLog (LogEntry LogMessage), GhcTime] r => InterpreterFor Log r interpretLogDataLog = interpretLogMetadataDataLog @LogMessage . interpretLogLogMetadata . raiseUnder # inline interpretLogDataLog # -- |Interpret 'Log' into 'DataLog', adding metadata information and wrapping with 'LogEntry'. interpretLogDataLog' :: Members [DataLog (LogEntry LogMessage), Embed IO] r => InterpretersFor [Log, LogMetadata LogMessage, GhcTime] r interpretLogDataLog' = interpretLogMetadataDataLog' . interpretLogLogMetadata {-# inline interpretLogDataLog' #-} -- |Interpret 'Log' into 'DataLog' concurrently, adding metadata information and wrapping with 'LogEntry'. interpretLogDataLogConc :: Members [DataLog (LogEntry LogMessage), Resource, Async, Race, Embed IO] r => Int -> InterpreterFor Log r interpretLogDataLogConc maxQueued = interceptDataLogConc @(LogEntry LogMessage) maxQueued . interpretTimeGhc . interpretLogMetadataDataLog @LogMessage . interpretLogLogMetadata . raiseUnder2 # inline interpretLogDataLogConc # -- |Helper for maintaining a context function as state that is applied to each logged message, allowing the context of a -- block to be modified. interpretDataLogLocal :: ∀ a r . (a -> a) -> (a -> Sem r ()) -> InterpreterFor (DataLog a) r interpretDataLogLocal context log = interpretH \case DataLog msg -> liftT (log (context msg)) Local f ma -> raise . interpretDataLogLocal (f . context) log =<< runT ma # inline interpretDataLogLocal # -- |Combinator for building 'DataLog' interpreters that handles 'Local'. interpretDataLog :: ∀ a r . (a -> Sem r ()) -> InterpreterFor (DataLog a) r interpretDataLog = interpretDataLogLocal id
null
https://raw.githubusercontent.com/tek/polysemy-log/385efb9043de0fef84943982723cbf32ed6caee4/packages/polysemy-log/lib/Polysemy/Log/Log.hs
haskell
|Description: Internal |Interpret 'Log' into the intermediate internal effect 'LogMetadata'. |Interpret the intermediate internal effect 'LogMetadata' into 'DataLog'. # inline interpretLogMetadataDataLog # |Interpret the intermediate internal effect 'LogMetadata' into 'DataLog'. # inline interpretLogMetadataDataLog' # |Interpret 'Log' into 'DataLog', adding metadata information and wrapping with 'LogEntry'. |Interpret 'Log' into 'DataLog', adding metadata information and wrapping with 'LogEntry'. # inline interpretLogDataLog' # |Interpret 'Log' into 'DataLog' concurrently, adding metadata information and wrapping with 'LogEntry'. |Helper for maintaining a context function as state that is applied to each logged message, allowing the context of a block to be modified. |Combinator for building 'DataLog' interpreters that handles 'Local'.
module Polysemy.Log.Log where import Polysemy.Conc (Race) import Polysemy.Internal.Tactics (liftT) import Polysemy.Time (GhcTime, interpretTimeGhc) import Polysemy.Log.Conc (interceptDataLogConc) import Polysemy.Log.Effect.DataLog (DataLog (DataLog, Local), dataLog) import Polysemy.Log.Effect.Log (Log (Log)) import Polysemy.Log.Data.LogEntry (LogEntry, annotate) import Polysemy.Log.Data.LogMessage (LogMessage) import Polysemy.Log.Effect.LogMetadata (LogMetadata (Annotated), annotated) interpretLogLogMetadata :: Members [LogMetadata LogMessage, GhcTime] r => InterpreterFor Log r interpretLogLogMetadata = interpret \case Log msg -> annotated msg # inline interpretLogLogMetadata # Since this adds a timestamp , it has a dependency on ' GhcTime ' . Use ' interpretLogMetadataDataLog '' for a variant that interprets ' ' in - place . interpretLogMetadataDataLog :: ∀ a r . Members [DataLog (LogEntry a), GhcTime] r => InterpreterFor (LogMetadata a) r interpretLogMetadataDataLog = interpret \case Annotated msg -> dataLog =<< annotate msg interpretLogMetadataDataLog' :: Members [DataLog (LogEntry a), Embed IO] r => InterpretersFor [LogMetadata a, GhcTime] r interpretLogMetadataDataLog' = interpretTimeGhc . interpretLogMetadataDataLog Since this adds a timestamp , it has a dependency on ' GhcTime ' . Use ' interpretLogDataLog '' for a variant that interprets ' ' in - place . interpretLogDataLog :: Members [DataLog (LogEntry LogMessage), GhcTime] r => InterpreterFor Log r interpretLogDataLog = interpretLogMetadataDataLog @LogMessage . interpretLogLogMetadata . raiseUnder # inline interpretLogDataLog # interpretLogDataLog' :: Members [DataLog (LogEntry LogMessage), Embed IO] r => InterpretersFor [Log, LogMetadata LogMessage, GhcTime] r interpretLogDataLog' = interpretLogMetadataDataLog' . interpretLogLogMetadata interpretLogDataLogConc :: Members [DataLog (LogEntry LogMessage), Resource, Async, Race, Embed IO] r => Int -> InterpreterFor Log r interpretLogDataLogConc maxQueued = interceptDataLogConc @(LogEntry LogMessage) maxQueued . interpretTimeGhc . interpretLogMetadataDataLog @LogMessage . interpretLogLogMetadata . raiseUnder2 # inline interpretLogDataLogConc # interpretDataLogLocal :: ∀ a r . (a -> a) -> (a -> Sem r ()) -> InterpreterFor (DataLog a) r interpretDataLogLocal context log = interpretH \case DataLog msg -> liftT (log (context msg)) Local f ma -> raise . interpretDataLogLocal (f . context) log =<< runT ma # inline interpretDataLogLocal # interpretDataLog :: ∀ a r . (a -> Sem r ()) -> InterpreterFor (DataLog a) r interpretDataLog = interpretDataLogLocal id
8f19984eb46cef6399ca9be0c5fe6deb8b45da670b7a1bfea00dfe083c162815
input-output-hk/cardano-wallet
Addresses.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE NumericUnderscores # # LANGUAGE OverloadedLabels # # LANGUAGE QuasiQuotes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Test.Integration.Scenario.API.Shelley.Addresses ( spec ) where import Prelude import Cardano.Wallet.Api.Types ( AnyAddress , ApiAccountKey , ApiAddress , ApiT (..) , ApiTransaction , ApiVerificationKeyShelley , ApiWallet , DecodeAddress , DecodeStakeAddress , EncodeAddress , WalletStyle (..) ) import Cardano.Wallet.Primitive.AddressDerivation ( DerivationIndex (..), Role (..) ) import Cardano.Wallet.Primitive.AddressDiscovery.Sequential ( defaultAddressPoolGap, getAddressPoolGap, purposeCIP1852 ) import Cardano.Wallet.Primitive.Types.Address ( AddressState (..) ) import Cardano.Wallet.Primitive.Types.Tx ( TxStatus (..) ) import Control.Monad ( forM, forM_ ) import Control.Monad.IO.Class ( liftIO ) import Control.Monad.Trans.Resource ( runResourceT ) import Data.Aeson ( ToJSON (..), object, (.=) ) import Data.Generics.Internal.VL.Lens ( view, (^.) ) import Data.Quantity ( Quantity (..) ) import Data.Text ( Text ) import Test.Hspec ( SpecWith, describe ) import Test.Hspec.Expectations.Lifted ( shouldBe, shouldNotBe, shouldNotSatisfy, shouldSatisfy ) import Test.Hspec.Extra ( it ) import Test.Integration.Framework.DSL ( Context (..) , Headers (..) , Payload (..) , emptyRandomWallet , emptyWallet , emptyWalletWith , eventually , expectErrorMessage , expectField , expectListField , expectListSize , expectResponseCode , fixturePassphrase , fixtureWallet , getFromResponse , isValidDerivationPath , json , listAddresses , minUTxOValue , request , unsafeRequest , verify , walletId ) import Test.Integration.Framework.TestData ( errMsg400ScriptDuplicateKeys , errMsg400ScriptIllFormed , errMsg400ScriptNotUniformRoles , errMsg400ScriptTimelocksContradictory , errMsg400ScriptWrongCoeffcient , errMsg403WrongIndex , errMsg404NoWallet ) import qualified Cardano.Wallet.Api.Link as Link import qualified Data.Aeson as Aeson import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Aeson.Lens as Aeson import qualified Data.Text as T import qualified Network.HTTP.Types.Status as HTTP spec :: forall n. ( DecodeAddress n , DecodeStakeAddress n , EncodeAddress n ) => SpecWith Context spec = describe "SHELLEY_ADDRESSES" $ do it "BYRON_ADDRESS_LIST - Byron wallet on Shelley ep" $ \ctx -> runResourceT $ do w <- emptyRandomWallet ctx let wid = w ^. walletId let ep = ("GET", "v2/wallets/" <> wid <> "/addresses") r <- request @[ApiAddress n] ctx ep Default Empty expectResponseCode HTTP.status404 r expectErrorMessage (errMsg404NoWallet wid) r it "ADDRESS_LIST_01 - Can list known addresses on a default wallet" $ \ctx -> runResourceT $ do let g = fromIntegral $ getAddressPoolGap defaultAddressPoolGap w <- emptyWallet ctx r <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley w) Default Empty expectResponseCode HTTP.status200 r expectListSize g r forM_ [0..(g-1)] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) r expectListField addrNum #derivationPath (`shouldSatisfy` (isValidDerivationPath purposeCIP1852)) r it "ADDRESS_LIST_01 - Can list addresses with non-default pool gap" $ \ctx -> runResourceT $ do let g = 15 w <- emptyWalletWith ctx ("Wallet", fixturePassphrase, g) r <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley w) Default Empty expectResponseCode HTTP.status200 r expectListSize g r forM_ [0..(g-1)] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) r expectListField addrNum #derivationPath (`shouldSatisfy` (isValidDerivationPath purposeCIP1852)) r it "ADDRESS_LIST_02 - Can filter used and unused addresses" $ \ctx -> runResourceT $ do let g = fromIntegral $ getAddressPoolGap defaultAddressPoolGap w <- fixtureWallet ctx rUsed <- request @[ApiAddress n] ctx (Link.listAddresses' @'Shelley w (Just Used)) Default Empty expectResponseCode HTTP.status200 rUsed expectListSize 10 rUsed forM_ [0..9] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Used) rUsed rUnused <- request @[ApiAddress n] ctx (Link.listAddresses' @'Shelley w (Just Unused)) Default Empty expectResponseCode HTTP.status200 rUnused expectListSize g rUnused forM_ [10..(g-1)] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) rUnused it "ADDRESS_LIST_02 - Shows nothing when there are no used addresses" $ \ctx -> runResourceT $ do w <- emptyWallet ctx rUsed <- request @[ApiAddress n] ctx (Link.listAddresses' @'Shelley w (Just Used)) Default Empty rUnused <- request @[ApiAddress n] ctx (Link.listAddresses' @'Shelley w (Just Unused)) Default Empty expectResponseCode HTTP.status200 rUsed expectListSize 0 rUsed expectResponseCode HTTP.status200 rUnused expectListSize 20 rUnused forM_ [0..19] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) rUnused TODO MOVE TO test / unit / Cardano / Wallet / ApiSpec.hs describe "ADDRESS_LIST_02 - Invalid filters are bad requests" $ do let filters = [ "usedd" , "uused" , "unusedd" , "uunused" , "USED" , "UNUSED" , "-1000" , "44444444" , "*" ] let withQuery f (method, link) = (method, link <> "?state=" <> T.pack f) forM_ filters $ \fil -> it fil $ \ctx -> runResourceT $ do w <- emptyWallet ctx let link = withQuery fil $ Link.listAddresses @'Shelley w r <- request @[ApiAddress n] ctx link Default Empty verify r [ expectResponseCode HTTP.status400 , expectErrorMessage "Error parsing query parameter state failed: Unable to\ \ decode the given text value. Please specify\ \ one of the following values: used, unused." ] it "ADDRESS_LIST_03 - Generates new address pool gap" $ \ctx -> runResourceT $ do let initPoolGap = 10 wSrc <- fixtureWallet ctx wDest <- emptyWalletWith ctx ("Wallet", fixturePassphrase, initPoolGap) make sure all addresses in address_pool_gap are ' Unused ' r <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley wDest) Default Empty verify r [ expectResponseCode HTTP.status200 , expectListSize initPoolGap ] forM_ [0..9] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) r addrs <- listAddresses @n ctx wDest let amt = minUTxOValue (_mainEra ctx) run 10 transactions to make all addresses ` Used ` forM_ [0..9] $ \addrNum -> do let destination = (addrs !! addrNum) ^. #id let payload = Json [json|{ "payments": [{ "address": #{destination}, "amount": { "quantity": #{amt}, "unit": "lovelace" } }], "passphrase": #{fixturePassphrase} }|] rTrans <- request @(ApiTransaction n) ctx (Link.createTransactionOld @'Shelley wSrc) Default payload expectResponseCode HTTP.status202 rTrans -- make sure all transactions are in ledger eventually "Wallet balance = initPoolGap * minUTxOValue" $ do rb <- request @ApiWallet ctx (Link.getWallet @'Shelley wDest) Default Empty expectField (#balance . #available) (`shouldBe` Quantity (10 * amt)) rb verify new address_pool_gap has been created rAddr <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley wDest) Default Empty verify rAddr [ expectResponseCode HTTP.status200 , expectListSize 20 ] forM_ [0..9] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Used) rAddr forM_ [10..19] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) rAddr it "ADDRESS_LIST_04 - Deleted wallet" $ \ctx -> runResourceT $ do w <- emptyWallet ctx _ <- request @ApiWallet ctx (Link.deleteWallet @'Shelley w) Default Empty r <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley w) Default Empty expectResponseCode HTTP.status404 r expectErrorMessage (errMsg404NoWallet $ w ^. walletId) r it "ADDRESS_LIST_05 - bech32 HRP is correct - mainnet" $ \ctx -> runResourceT $ do w <- emptyWallet ctx r <- request @[Aeson.Value] ctx (Link.listAddresses @'Shelley w) Default Empty verify r [ expectResponseCode HTTP.status200 -- integration tests are configured for mainnet , expectListField 0 (Aeson.key "id" . Aeson._String) (`shouldSatisfy` T.isPrefixOf "addr") , expectListField 0 (Aeson.key "id" . Aeson._String) (`shouldNotSatisfy` T.isPrefixOf "addr_test") ] it "ADDRESS_LIST_06 - Used change addresses are listed after a transaction is no longer pending" $ \ctx -> runResourceT @IO $ do let verifyAddrs nTotal nUsed addrs = do liftIO (length addrs `shouldBe` nTotal) let onlyUsed = filter ((== Used) . (^. (#state . #getApiT))) addrs liftIO (length onlyUsed `shouldBe` nUsed) 1 . Create wallets let initialTotalA = 30 let initialUsedA = 10 wA <- fixtureWallet ctx listAddresses @n ctx wA >>= verifyAddrs initialTotalA initialUsedA let initialTotalB = 20 let initialUsedB = 0 wB <- emptyWallet ctx listAddresses @n ctx wB >>= verifyAddrs initialTotalB initialUsedB 2 . Send a transaction from A - > B destination <- view #id . head <$> listAddresses @n ctx wB let amount = 10 * minUTxOValue (_mainEra ctx) let payload = Json [json|{ "payments": [{ "address": #{destination}, "amount": { "quantity": #{amount}, "unit": "lovelace" } }], "passphrase": #{fixturePassphrase} }|] (_, rtx) <- unsafeRequest @(ApiTransaction n) ctx (Link.createTransactionOld @'Shelley wA) payload 3 . Check that there 's one more used addresses on A. -- -- Ideally, we would also like to check that there's no used address on -- B yet, but this would make the test quite flaky. Indeed, the integration -- tests produces block very fast and by the time we make this call the -- transaction may have already been inserted in the ledger and -- discovered by B. -- -- Similarly, we can't assert the length of used addresses on A. It -- _should_ be 'initialUsedA` but the transaction could have already -- been inserted and discovered by the time the 'listAddresses' call -- resolves. listAddresses @n ctx wA >>= \addrs -> liftIO $ length addrs `shouldBe` (initialTotalA + 1) 4 . Wait for transaction from A - > B to no longer be pending eventually "Transaction from A -> B is discovered on B" $ do request @(ApiTransaction n) ctx (Link.getTransaction @'Shelley wA rtx) Default Empty >>= expectField #status (`shouldBe` ApiT InLedger) request @(ApiTransaction n) ctx (Link.getTransaction @'Shelley wB rtx) Default Empty >>= expectField #status (`shouldBe` ApiT InLedger) 5 . Check that there 's one more used and total addresses on the wallets -- A and B. -- -- On A: The address comes from the internal pool gap and was hidden up -- until the transaction is created and remains after it is -- inserted. -- -- On B: There's a new total address because the address used was the first unused address from the consecutive sequence of the address -- pool. Thus the address window was shifted be exactly one. listAddresses @n ctx wA >>= verifyAddrs (initialTotalA + 1) (initialUsedA + 1) listAddresses @n ctx wB >>= verifyAddrs (initialTotalB + 1) (initialUsedB + 1) it "ADDRESS_INSPECT_01 - Address inspect OK Icarus" $ \ctx -> do let str = "Ae2tdPwUPEYz6ExfbWubiXPB6daUuhJxikMEb4eXRp5oKZBKZwrbJ2k7EZe" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty verify r [ expectResponseCode HTTP.status200 , expectField (Aeson.key "address_style" . Aeson._String) (`shouldBe` "Icarus") , expectField (Aeson.key "address_type" . Aeson._Number) (`shouldBe` 8) ] it "ADDRESS_INSPECT_02 - Address inspect OK Byron" $ \ctx -> do let str = "37btjrVyb4KE2ByiPiJUQfAUBGaMyKScg4mnYjzVAsN2PUxj1WxTg98ien3oAo8vKBhP2KTuC9wi76vZ9kDNFkjbmzywdLTJgaz8n3RD3Rueim3Pd3" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty verify r [ expectResponseCode HTTP.status200 , expectField (Aeson.key "address_style" . Aeson._String) (`shouldBe` "Byron") , expectField (Aeson.key "address_type" . Aeson._Number) (`shouldBe` 8) ] it "ADDRESS_INSPECT_03 - Address inspect OK reward" $ \ctx -> do let str = "stake1u8pn5jr7cfa0x8ndtdufyg5lty3avg3zd2tq35c06hpsh8gptdza4" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty verify r [ expectResponseCode HTTP.status200 , expectField (Aeson.key "address_style" . Aeson._String) (`shouldBe` "Shelley") , expectField (Aeson.key "address_type" . Aeson._Number) (`shouldBe` 14) ] it "ADDRESS_INSPECT_04 - Address inspect KO" $ \ctx -> runResourceT $ do let str = "patate" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty expectResponseCode HTTP.status400 r it "ADDRESS_INSPECT_05 - Address inspect OK bech32" $ \ctx -> do let str = "addr_test1qzamu40sglnsrylzv9jylekjmzgaqsg5v5z9u6yk3jpnnxjwck77fqu8deuumsvnazjnjhwasc2eetfqpa2pvygts78ssd5388" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty verify r [ expectResponseCode HTTP.status200 , expectField (Aeson.key "address_style" . Aeson._String) (`shouldBe` "Shelley") , expectField (Aeson.key "spending_key_hash_bech32" . Aeson._String) (`shouldBe` "addr_vkh1hwl9tuz8uuqe8cnpv387d5kcj8gyz9r9q30x395vsvue5e44fh7") , expectField (Aeson.key "stake_key_hash_bech32" . Aeson._String) (`shouldBe` "stake_vkh1fmzmmeyrsah8nnwpj0522w2amkrpt89dyq84g9s3pwrc7dqjnfu") , expectField (Aeson.key "address_type" . Aeson._Number) (`shouldBe` 0) ] -- Generating golden test data for enterprise addresses - script credential: --- (a) from script hash --- $ cardano-address script hash "$(cat script.txt)" \ --- | cardano-address address payment --network-tag mainnet --- (b) from script --- $ cardano-address address payment --network-tag mainnet "$(cat script.txt)" it "ANY_ADDRESS_POST_01 - Golden tests for enterprise script address - signature" $ \ctx -> do --- $ cat script.txt --- addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq --- $ cardano-address script hash "$(cat script.txt)" --- script1ccqe6wa40878s2pxrfwj0qxz9t7dxw8rhfreqwzjuy67gk2ausz let payload1 = Json [json|{ "payment": "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq" }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": "script1ccqe6wa40878s2pxrfwj0qxz9t7dxw8rhfreqwzjuy67gk2ausz" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "addr1w8rqr8fmk4ulc7pgycd96fuqcg40e5ecuway0ypc2tsnteqm5wul2" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr it "ANY_ADDRESS_POST_02 - Golden tests for enterprise script address - any" $ \ctx -> do --- $ cat script.txt - any [ addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq , addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp ] --- $ cardano-address script hash "$(cat script.txt)" --- script1ujl6y7gx0e3h79kyzqan0smw3xq6x289za64fn6tap6xc7rsm0z let payload1 = Json [json|{ "payment": { "any": [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp" ] } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": "script1ujl6y7gx0e3h79kyzqan0smw3xq6x289za64fn6tap6xc7rsm0z" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "addr1w8jtlgneqelxxlckcsgrkd7rd6ycrgegu5th24x0f058gmqhsnv92" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr it "ANY_ADDRESS_POST_03 - Golden tests for enterprise script address - all" $ \ctx -> do --- $ cat script.txt - all [ addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq , addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp ] --- $ cardano-address script hash "$(cat script.txt)" --- script1gr69m385thgvkrtspk73zmkwk537wxyxuevs2u9cukglvtlkz4k let payload1 = Json [json|{ "payment": { "all": [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp" ] } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": "script1gr69m385thgvkrtspk73zmkwk537wxyxuevs2u9cukglvtlkz4k" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "addr1w9q0ghwy73wapjcdwqxm6ytwe66j8eccsmn9jptshrjerasvf2cg0" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr it "ANY_ADDRESS_POST_04 - Golden tests for enterprise script address - some" $ \ctx -> do --- $ cat script.txt - at_least 2 [ addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq , addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp , addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9 ] --- $ cardano-address script hash "$(cat script.txt)" ---- script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778 let payload1 = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": "script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "addr1wyqmnmwuh85e0fxaggl6ac2hfeqncg76gsr0ld8qdjd84ag6sm0n8" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr -- Generating golden test data for reward account addresses - script credential: --- (a) script hash --- $ cardano-address script hash "$(cat script.txt)" \ --- | cardano-address address stake --network-tag mainnet --- (b) script --- $ cardano-address address stake --network-tag mainnet "$(cat script.txt)" it "ANY_ADDRESS_POST_05 - Golden tests for reward account script address - any" $ \ctx -> do --- $ cat script.txt --- any [stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5, stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s] --- $ cardano-address script hash "$(cat script.txt)" --- script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz let payload1 = Json [json|{ "stake": { "any": [ "stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5", "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s" ] } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "stake": "script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "stake17yshpfjkgh98wumvnn9y3yfhevllp4y04u6y84q3flxcv9sduxphm" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr -- Generating golden test data for reward account addresses - both script credentials: --- (a) script hashes --- $ cardano-address script hash "$(cat script1.txt)" \ --- | cardano-address address payment --network-tag mainnet \ --- | cardano-address address delegation $(cardano-address script hash "$(cat script2.txt)") --- (b) scripts --- $ cardano-address address payment --network-tag mainnet "$(cat script1.txt)" \ --- | cardano-address address delegation "$(cat script2.txt)" --- $ cat script1.txt - at_least 2 [ addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq , addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp , addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9 ] --- $ cardano-address script hash "$(cat script1.txt)" --- script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778 --- $ cat script2.txt --- any [stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5, stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s] --- $ cardano-address script hash "$(cat script2.txt)" --- script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz it "ANY_ADDRESS_POST_06 - Golden tests for delegating script address - any" $ \ctx -> do let payload1 = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "stake": { "any": [ "stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5", "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s" ] } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "stake": "script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let payload3 = Json [json|{ "payment": "script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778", "stake": { "any": [ "stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5", "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s" ] } }|] r3 <- request @AnyAddress ctx Link.postAnyAddress Default payload3 expectResponseCode HTTP.status202 r3 let payload4 = Json [json|{ "payment": "script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778", "stake": "script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz" }|] r4 <- request @AnyAddress ctx Link.postAnyAddress Default payload4 expectResponseCode HTTP.status202 r4 let goldenAddr = "addr1xyqmnmwuh85e0fxaggl6ac2hfeqncg76gsr0ld8qdjd84afpwzn9v3w2waeke8x2fzgn0jel7r2glte5g02pzn7dsctqu6mtx3" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr validateAddr r3 goldenAddr validateAddr r4 goldenAddr -- Generating golden test. We use the following mnemonic in all examples below: --- $ cat recovery-phrase.txt --- east student silly already breeze enact seat trade few way online skin grass humble electric - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --without-chain-code --- addr_vk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwpschzd2j -- Golden address can be obtained via - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --without-chain-code \ --- > | cardano-address address payment --network-tag mainnet it "ANY_ADDRESS_POST_07a - Golden tests for enterprise address - from non-extended public key" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwpschzd2j" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1v9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wfgknj82e" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code --- addr_xvk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwp3k2zz8796vdstcu7q0qp232wyvzjes0qkpmt7gzwa0x2q75h3qcgl5y4q0 -- Golden address can be obtained via - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address address payment --network-tag mainnet it "ANY_ADDRESS_POST_07b - Golden tests for enterprise address - from extended public key" $ \ctx -> do let payload = Json [json|{ "payment": "addr_xvk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwp3k2zz8796vdstcu7q0qp232wyvzjes0qkpmt7gzwa0x2q75h3qcgl5y4q0" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1v9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wfgknj82e" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address key hash --- addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs --- One can also use --without-chain-code to get the same key hash -- Golden address can be obtained via - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address key hash --- > | cardano-address address payment --network-tag mainnet it "ANY_ADDRESS_POST_07c - Golden tests for enterprise address - from key hash" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1v9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wfgknj82e" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --without-chain-code --- stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d -- Golden address can be obtained via - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --without-chain-code \ --- > | cardano-address address stake --network-tag mainnet it "ANY_ADDRESS_POST_08a - Golden tests for reward account address - from non-extended public key" $ \ctx -> do let payload = Json [json|{ "stake": "stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "stake1uy6pmlvyl3wn4ca6807e26gy2gek9hqu0gastzh5tk0xx0g2rxsr5" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --with-chain-code --- stake_xvk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7yak6lmcyst8yclpm3yalrspc7q2wy9f6683x6f9z4e3gclhs5snslcst62 -- Golden address can be obtained via - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address address stake --network-tag mainnet it "ANY_ADDRESS_POST_08b - Golden tests for reward account address - from extended public key" $ \ctx -> do let payload = Json [json|{ "stake": "stake_xvk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7yak6lmcyst8yclpm3yalrspc7q2wy9f6683x6f9z4e3gclhs5snslcst62" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "stake1uy6pmlvyl3wn4ca6807e26gy2gek9hqu0gastzh5tk0xx0g2rxsr5" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address key hash --- stake_vkh1xswlmp8ut5aw8w3mlk2kjpzjxd3dc8r68vzc4azane3n6r07ddx -- Golden address can be obtained via - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address key hash \ --- > | cardano-address address stake --network-tag mainnet it "ANY_ADDRESS_POST_08c - Golden tests for reward account address - from key hash" $ \ctx -> do let payload = Json [json|{ "stake": "stake_vkh1xswlmp8ut5aw8w3mlk2kjpzjxd3dc8r68vzc4azane3n6r07ddx" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "stake1uy6pmlvyl3wn4ca6807e26gy2gek9hqu0gastzh5tk0xx0g2rxsr5" :: Text validateAddr r goldenAddr -- Golden address can be obtained via - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --with-chain-code > stake.xvk - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --without-chain-code > stake.vk - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address key hash > stake.vkh - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address address payment --network-tag mainnet \ --- > | cardano-address address delegation $(cat stake.xvk) it "ANY_ADDRESS_POST_09a - Golden tests for delegating address with both non-extended pub key credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwpschzd2j", "stake": "stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address address payment --network-tag mainnet \ --- > | cardano-address address delegation $(cat stake.xvk) it "ANY_ADDRESS_POST_09b - Golden tests for delegating address with both extended pub key credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_xvk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwp3k2zz8796vdstcu7q0qp232wyvzjes0qkpmt7gzwa0x2q75h3qcgl5y4q0", "stake": "stake_xvk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7yak6lmcyst8yclpm3yalrspc7q2wy9f6683x6f9z4e3gclhs5snslcst62" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address key hash \ --- > | cardano-address address payment --network-tag mainnet \ --- > | cardano-address address delegation $(cat stake.vkh) it "ANY_ADDRESS_POST_09c - Golden tests for delegating address with both key hash credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs", "stake": "stake_vkh1xswlmp8ut5aw8w3mlk2kjpzjxd3dc8r68vzc4azane3n6r07ddx" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address key hash \ --- > | cardano-address address payment --network-tag mainnet \ --- > | cardano-address address delegation $(cat stake.xvk) it "ANY_ADDRESS_POST_09d - Golden tests for delegating address with mixed credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs", "stake": "stake_xvk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7yak6lmcyst8yclpm3yalrspc7q2wy9f6683x6f9z4e3gclhs5snslcst62" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address key hash \ --- > | cardano-address address payment --network-tag mainnet \ --- > | cardano-address address delegation $(cat stake.xvk) it "ANY_ADDRESS_POST_09e - Golden tests for delegating address with mixed credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs", "stake": "stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address address payment --network-tag mainnet \ --- > | cardano-address address delegation $(cat stake.vkh) it "ANY_ADDRESS_POST_09f - Golden tests for delegating address with mixed credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_xvk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwp3k2zz8796vdstcu7q0qp232wyvzjes0qkpmt7gzwa0x2q75h3qcgl5y4q0", "stake": "stake_vkh1xswlmp8ut5aw8w3mlk2kjpzjxd3dc8r68vzc4azane3n6r07ddx" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr -- Generating golden test data for delegating address - payment from script, stake from pub key: - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ - > | cardano - address key public --with - chain - code > stake.xpub --- $ cardano-address script hash "$(cat script.txt)" \ --- | cardano-address address payment --from-script --network-tag mainnet \ --- | cardano-address address delegation --from-key $(cat stake.xpub) it "ANY_ADDRESS_POST_10 - Golden tests for delegating address - payment from script, stake from key" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "stake": "stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1zyqmnmwuh85e0fxaggl6ac2hfeqncg76gsr0ld8qdjd84af5rh7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7srr0dle" :: Text validateAddr r goldenAddr -- Generating golden test data for delegating address - payment from pub key, stake from script: - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ --- > | cardano-address key public --with-chain-code \ --- > | cardano-address address payment --from-key --network-tag mainnet \ --- > | cardano-address address delegation --from-script $(cardano-address script hash "$(cat script3.txt)") it "ANY_ADDRESS_POST_11 - Golden tests for delegating address - payment from key, stake from script" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwpschzd2j", "stake": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1y9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wfgph8kaew0fj7jd6s3l4ms4wnjp8s3a53qxl76wqmy60t6ssqcamq" :: Text validateAddr r goldenAddr it "ANY_ADDRESS_POST_12 - Delegating addresses API roundtrip" $ \ctx -> runResourceT $ do w <- emptyWallet ctx Generate first 20 addresses using payment and stake keys derived from -- wallet API let indices = [0..19] generatedAddresses <- forM indices $ \index -> do let paymentPath = Link.getWalletKey @'Shelley w UtxoExternal (DerivationIndex index) Nothing (_, paymentKey) <- unsafeRequest @ApiVerificationKeyShelley ctx paymentPath Empty let stakePath = Link.getWalletKey @'Shelley w MutableAccount (DerivationIndex 0) Nothing (_, stakeKey) <- unsafeRequest @ApiVerificationKeyShelley ctx stakePath Empty let payload = Json [json|{ "payment": #{paymentKey}, "stake": #{stakeKey} }|] (_, addr) <- unsafeRequest @AnyAddress ctx Link.postAnyAddress payload pure (addr ^. #payload) -- Make sure the same addresses are already available in the wallet addrs <- listAddresses @n ctx w forM_ (zip (fmap fromIntegral indices) generatedAddresses) $ \(idx, genAddr) -> do let walAddr = fst (addrs !! idx ^. #id) ^. (#getApiT . #unAddress) walAddr `shouldBe` genAddr it "ANY_ADDRESS_POST_13 - Golden tests for script with timelocks" $ \ctx -> do let payload = Json [json|{ "payment": { "all" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", { "active_from": 120 } ] }, "stake": { "all" : [ "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s", { "active_from": 120 } ] } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1xy756z909yycvf5ah8j5pc4cvuedkhvhyylmgfz400t8jdwmwa0hp024gu7dm6h8n252lkgnzemp93mm9kyd48p64mjshqtu3c" :: Text validateAddr r goldenAddr it "ANY_ADDRESS_POST_14a - at_least 0 is valid when non-validated" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 0 } } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_14b - at_least 0 is valid when validation is required" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 0 } }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_14c - at_least 0 is not valid when validation is recommended" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 0 } }, "validation": "recommended" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptWrongCoeffcient r it "ANY_ADDRESS_POST_15a - at_least 4 is valid when non-validated" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 4 } } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_15b - at_least 4 is valid when validation is required" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 4 } }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptIllFormed r it "ANY_ADDRESS_POST_15c - at_least 4 is not valid when validation is recommended" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 4 } }, "validation": "recommended" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptIllFormed r it "ANY_ADDRESS_POST_16a - script with duplicated verification keys is valid when non-validated" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_16b - script with duplicated verification keys is valid when required validation used" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_16c - script with duplicated verification keys is invalid when recommended validation used" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "validation": "recommended" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptDuplicateKeys r it "ANY_ADDRESS_POST_17a - Script with contradictory timelocks is valid when validation not used" $ \ctx -> do let payload = Json [json|{ "payment": { "all" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", { "active_from": 120 }, { "active_until": 100 } ] }, "stake": { "all" : [ "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s", { "active_from": 120 } ] } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_17b - Script with contradictory timelocks is invalid when required validation is used" $ \ctx -> do let payload = Json [json|{ "payment": { "all" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", { "active_from": 120 }, { "active_until": 100 } ] }, "stake": { "all" : [ "script_vkh1yf07000d4ml3ywd3d439kmwp07xzgv6p35cwx8h605jfx0dtd4a", { "active_from": 120 } ] }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_17c - Script with contradictory timelocks is invalid when recommended validation is used" $ \ctx -> do let payload = Json [json|{ "payment": { "all" : [ "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s", { "active_from": 120 }, { "active_until": 100 } ] }, "stake": { "all" : [ "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s", { "active_from": 120 } ] }, "validation": "recommended" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptTimelocksContradictory r it "ANY_ADDRESS_POST_17d - script with mixed payment/delegation verification keys is invalid" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s" ], "at_least": 1 } }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptNotUniformRoles r it "POST_ACCOUNT_01 - Can retrieve account public keys" $ \ctx -> runResourceT $ do let initPoolGap = 10 w <- emptyWalletWith ctx ("Wallet", fixturePassphrase, initPoolGap) let endpoint = Link.postAccountKey @'Shelley w (DerivationIndex 0) let payload = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended" }|] resp <- request @ApiAccountKey ctx endpoint Default payload expectErrorMessage errMsg403WrongIndex resp Request first 10 extended account public keys let indices = [0..9] accountPublicKeys <- forM indices $ \index -> do let accountPath = Link.postAccountKey @'Shelley w (DerivationIndex $ 2_147_483_648 + index) let payload1 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended" }|] let payload2 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "non_extended" }|] (_, accXPub) <- unsafeRequest @ApiAccountKey ctx accountPath payload1 (_, accPub) <- unsafeRequest @ApiAccountKey ctx accountPath payload2 let (Aeson.String accXPubTxt) = toJSON accXPub let (Aeson.String accPubTxt) = toJSON accPub T.isPrefixOf "acct_xvk" accXPubTxt `shouldBe` True T.isPrefixOf "acct_vk" accPubTxt `shouldBe` True pure [accXPub, accPub] length (concat accountPublicKeys) `shouldBe` 20 it "POST_ACCOUNT_02 - Can get account public key using purpose" $ \ctx -> runResourceT $ do let initPoolGap = 10 w <- emptyWalletWith ctx ("Wallet", fixturePassphrase, initPoolGap) let accountPath = Link.postAccountKey @'Shelley w (DerivationIndex $ 2_147_483_648 + 1) let payload1 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended" }|] (_, accXPub1) <- unsafeRequest @ApiAccountKey ctx accountPath payload1 let (Aeson.String accXPub1Txt) = toJSON accXPub1 T.isPrefixOf "acct_xvk" accXPub1Txt `shouldBe` True let payload2 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended", "purpose": "1852H" }|] (_, accXPub2) <- unsafeRequest @ApiAccountKey ctx accountPath payload2 accXPub1 `shouldBe` accXPub2 let payload3 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended", "purpose": "1854H" }|] (_, accXPub3) <- unsafeRequest @ApiAccountKey ctx accountPath payload3 accXPub1 `shouldNotBe` accXPub3 let (Aeson.String accXPub3Txt) = toJSON accXPub3 T.isPrefixOf "acct_shared_xvk" accXPub3Txt `shouldBe` True let payload4 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended", "purpose": "1854" }|] resp <- request @ApiAccountKey ctx accountPath Default payload4 expectErrorMessage errMsg403WrongIndex resp it "ANY_ADDRESS_POST_15 - Staking address using stake credential non-hashed" $ \ctx -> runResourceT $ do w <- emptyWallet ctx let stakePath = Link.getWalletKey @'Shelley w MutableAccount (DerivationIndex 0) Nothing (_, stakeKey) <- unsafeRequest @ApiVerificationKeyShelley ctx stakePath Empty let (Aeson.String stakeKeyTxt) = toJSON stakeKey stakeKeyTxt `shouldSatisfy` T.isPrefixOf "stake_vk1" let payload = Json [json|{ "stake": #{stakeKey} }|] (_, stakeAddr) <- unsafeRequest @AnyAddress ctx Link.postAnyAddress payload let (Aeson.Object stakeAddrJson) = toJSON stakeAddr let (Just (Aeson.String stakeAddrTxt)) = KeyMap.lookup "address" stakeAddrJson stakeAddrTxt `shouldSatisfy` T.isPrefixOf "stake1" it "ANY_ADDRESS_POST_16 - Staking address using stake credential hashed" $ \ctx -> runResourceT $ do w <- emptyWallet ctx let stakePath = Link.getWalletKey @'Shelley w MutableAccount (DerivationIndex 0) (Just True) (_, stakeKeyHash) <- unsafeRequest @ApiVerificationKeyShelley ctx stakePath Empty let (Aeson.String stakeKeyHashTxt) = toJSON stakeKeyHash stakeKeyHashTxt `shouldSatisfy` T.isPrefixOf "stake_vkh1" let payload = Json [json|{ "stake": #{stakeKeyHash} }|] (_, stakeAddr) <- unsafeRequest @AnyAddress ctx Link.postAnyAddress payload let (Aeson.Object stakeAddrJson) = toJSON stakeAddr let (Just (Aeson.String stakeAddrTxt)) = KeyMap.lookup "address" stakeAddrJson stakeAddrTxt `shouldSatisfy` T.isPrefixOf "stake1" where validateAddr resp expected = do let addr = getFromResponse id resp toJSON addr `shouldBe` object ["address" .= expected ]
null
https://raw.githubusercontent.com/input-output-hk/cardano-wallet/7b541e0b11fdd69b30d94104dbd5fa633ff1d5c3/lib/wallet/integration/src/Test/Integration/Scenario/API/Shelley/Addresses.hs
haskell
make sure all transactions are in ledger integration tests are configured for mainnet Ideally, we would also like to check that there's no used address on B yet, but this would make the test quite flaky. Indeed, the integration tests produces block very fast and by the time we make this call the transaction may have already been inserted in the ledger and discovered by B. Similarly, we can't assert the length of used addresses on A. It _should_ be 'initialUsedA` but the transaction could have already been inserted and discovered by the time the 'listAddresses' call resolves. A and B. On A: The address comes from the internal pool gap and was hidden up until the transaction is created and remains after it is inserted. On B: There's a new total address because the address used was the pool. Thus the address window was shifted be exactly one. Generating golden test data for enterprise addresses - script credential: - (a) from script hash - $ cardano-address script hash "$(cat script.txt)" \ - | cardano-address address payment --network-tag mainnet - (b) from script - $ cardano-address address payment --network-tag mainnet "$(cat script.txt)" - $ cat script.txt - addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq - $ cardano-address script hash "$(cat script.txt)" - script1ccqe6wa40878s2pxrfwj0qxz9t7dxw8rhfreqwzjuy67gk2ausz - $ cat script.txt - $ cardano-address script hash "$(cat script.txt)" - script1ujl6y7gx0e3h79kyzqan0smw3xq6x289za64fn6tap6xc7rsm0z - $ cat script.txt - $ cardano-address script hash "$(cat script.txt)" - script1gr69m385thgvkrtspk73zmkwk537wxyxuevs2u9cukglvtlkz4k - $ cat script.txt - $ cardano-address script hash "$(cat script.txt)" -- script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778 Generating golden test data for reward account addresses - script credential: - (a) script hash - $ cardano-address script hash "$(cat script.txt)" \ - | cardano-address address stake --network-tag mainnet - (b) script - $ cardano-address address stake --network-tag mainnet "$(cat script.txt)" - $ cat script.txt - any [stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5, stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s] - $ cardano-address script hash "$(cat script.txt)" - script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz Generating golden test data for reward account addresses - both script credentials: - (a) script hashes - $ cardano-address script hash "$(cat script1.txt)" \ - | cardano-address address payment --network-tag mainnet \ - | cardano-address address delegation $(cardano-address script hash "$(cat script2.txt)") - (b) scripts - $ cardano-address address payment --network-tag mainnet "$(cat script1.txt)" \ - | cardano-address address delegation "$(cat script2.txt)" - $ cat script1.txt - $ cardano-address script hash "$(cat script1.txt)" - script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778 - $ cat script2.txt - any [stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5, stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s] - $ cardano-address script hash "$(cat script2.txt)" - script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz Generating golden test. We use the following mnemonic in all examples below: - $ cat recovery-phrase.txt - east student silly already breeze enact seat trade few way online skin grass humble electric - > | cardano-address key public --without-chain-code - addr_vk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwpschzd2j Golden address can be obtained via - > | cardano-address key public --without-chain-code \ - > | cardano-address address payment --network-tag mainnet - > | cardano-address key public --with-chain-code - addr_xvk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwp3k2zz8796vdstcu7q0qp232wyvzjes0qkpmt7gzwa0x2q75h3qcgl5y4q0 Golden address can be obtained via - > | cardano-address key public --with-chain-code \ - > | cardano-address address payment --network-tag mainnet - > | cardano-address key public --with-chain-code \ - > | cardano-address key hash - addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs - One can also use --without-chain-code to get the same key hash Golden address can be obtained via - > | cardano-address key public --with-chain-code \ - > | cardano-address key hash - > | cardano-address address payment --network-tag mainnet - > | cardano-address key public --without-chain-code - stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d Golden address can be obtained via - > | cardano-address key public --without-chain-code \ - > | cardano-address address stake --network-tag mainnet - > | cardano-address key public --with-chain-code - stake_xvk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7yak6lmcyst8yclpm3yalrspc7q2wy9f6683x6f9z4e3gclhs5snslcst62 Golden address can be obtained via - > | cardano-address key public --with-chain-code \ - > | cardano-address address stake --network-tag mainnet - > | cardano-address key public --with-chain-code \ - > | cardano-address key hash - stake_vkh1xswlmp8ut5aw8w3mlk2kjpzjxd3dc8r68vzc4azane3n6r07ddx Golden address can be obtained via - > | cardano-address key public --with-chain-code \ - > | cardano-address key hash \ - > | cardano-address address stake --network-tag mainnet Golden address can be obtained via - > | cardano-address key public --with-chain-code > stake.xvk - > | cardano-address key public --without-chain-code > stake.vk - > | cardano-address key public --with-chain-code \ - > | cardano-address key hash > stake.vkh - > | cardano-address key public --with-chain-code \ - > | cardano-address address payment --network-tag mainnet \ - > | cardano-address address delegation $(cat stake.xvk) - > | cardano-address key public --with-chain-code \ - > | cardano-address address payment --network-tag mainnet \ - > | cardano-address address delegation $(cat stake.xvk) - > | cardano-address key public --with-chain-code \ - > | cardano-address key hash \ - > | cardano-address address payment --network-tag mainnet \ - > | cardano-address address delegation $(cat stake.vkh) - > | cardano-address key public --with-chain-code \ - > | cardano-address key hash \ - > | cardano-address address payment --network-tag mainnet \ - > | cardano-address address delegation $(cat stake.xvk) - > | cardano-address key public --with-chain-code \ - > | cardano-address key hash \ - > | cardano-address address payment --network-tag mainnet \ - > | cardano-address address delegation $(cat stake.xvk) - > | cardano-address key public --with-chain-code \ - > | cardano-address address payment --network-tag mainnet \ - > | cardano-address address delegation $(cat stake.vkh) Generating golden test data for delegating address - payment from script, stake from pub key: with - chain - code > stake.xpub - $ cardano-address script hash "$(cat script.txt)" \ - | cardano-address address payment --from-script --network-tag mainnet \ - | cardano-address address delegation --from-key $(cat stake.xpub) Generating golden test data for delegating address - payment from pub key, stake from script: - > | cardano-address key public --with-chain-code \ - > | cardano-address address payment --from-key --network-tag mainnet \ - > | cardano-address address delegation --from-script $(cardano-address script hash "$(cat script3.txt)") wallet API Make sure the same addresses are already available in the wallet
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE NumericUnderscores # # LANGUAGE OverloadedLabels # # LANGUAGE QuasiQuotes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Test.Integration.Scenario.API.Shelley.Addresses ( spec ) where import Prelude import Cardano.Wallet.Api.Types ( AnyAddress , ApiAccountKey , ApiAddress , ApiT (..) , ApiTransaction , ApiVerificationKeyShelley , ApiWallet , DecodeAddress , DecodeStakeAddress , EncodeAddress , WalletStyle (..) ) import Cardano.Wallet.Primitive.AddressDerivation ( DerivationIndex (..), Role (..) ) import Cardano.Wallet.Primitive.AddressDiscovery.Sequential ( defaultAddressPoolGap, getAddressPoolGap, purposeCIP1852 ) import Cardano.Wallet.Primitive.Types.Address ( AddressState (..) ) import Cardano.Wallet.Primitive.Types.Tx ( TxStatus (..) ) import Control.Monad ( forM, forM_ ) import Control.Monad.IO.Class ( liftIO ) import Control.Monad.Trans.Resource ( runResourceT ) import Data.Aeson ( ToJSON (..), object, (.=) ) import Data.Generics.Internal.VL.Lens ( view, (^.) ) import Data.Quantity ( Quantity (..) ) import Data.Text ( Text ) import Test.Hspec ( SpecWith, describe ) import Test.Hspec.Expectations.Lifted ( shouldBe, shouldNotBe, shouldNotSatisfy, shouldSatisfy ) import Test.Hspec.Extra ( it ) import Test.Integration.Framework.DSL ( Context (..) , Headers (..) , Payload (..) , emptyRandomWallet , emptyWallet , emptyWalletWith , eventually , expectErrorMessage , expectField , expectListField , expectListSize , expectResponseCode , fixturePassphrase , fixtureWallet , getFromResponse , isValidDerivationPath , json , listAddresses , minUTxOValue , request , unsafeRequest , verify , walletId ) import Test.Integration.Framework.TestData ( errMsg400ScriptDuplicateKeys , errMsg400ScriptIllFormed , errMsg400ScriptNotUniformRoles , errMsg400ScriptTimelocksContradictory , errMsg400ScriptWrongCoeffcient , errMsg403WrongIndex , errMsg404NoWallet ) import qualified Cardano.Wallet.Api.Link as Link import qualified Data.Aeson as Aeson import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Aeson.Lens as Aeson import qualified Data.Text as T import qualified Network.HTTP.Types.Status as HTTP spec :: forall n. ( DecodeAddress n , DecodeStakeAddress n , EncodeAddress n ) => SpecWith Context spec = describe "SHELLEY_ADDRESSES" $ do it "BYRON_ADDRESS_LIST - Byron wallet on Shelley ep" $ \ctx -> runResourceT $ do w <- emptyRandomWallet ctx let wid = w ^. walletId let ep = ("GET", "v2/wallets/" <> wid <> "/addresses") r <- request @[ApiAddress n] ctx ep Default Empty expectResponseCode HTTP.status404 r expectErrorMessage (errMsg404NoWallet wid) r it "ADDRESS_LIST_01 - Can list known addresses on a default wallet" $ \ctx -> runResourceT $ do let g = fromIntegral $ getAddressPoolGap defaultAddressPoolGap w <- emptyWallet ctx r <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley w) Default Empty expectResponseCode HTTP.status200 r expectListSize g r forM_ [0..(g-1)] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) r expectListField addrNum #derivationPath (`shouldSatisfy` (isValidDerivationPath purposeCIP1852)) r it "ADDRESS_LIST_01 - Can list addresses with non-default pool gap" $ \ctx -> runResourceT $ do let g = 15 w <- emptyWalletWith ctx ("Wallet", fixturePassphrase, g) r <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley w) Default Empty expectResponseCode HTTP.status200 r expectListSize g r forM_ [0..(g-1)] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) r expectListField addrNum #derivationPath (`shouldSatisfy` (isValidDerivationPath purposeCIP1852)) r it "ADDRESS_LIST_02 - Can filter used and unused addresses" $ \ctx -> runResourceT $ do let g = fromIntegral $ getAddressPoolGap defaultAddressPoolGap w <- fixtureWallet ctx rUsed <- request @[ApiAddress n] ctx (Link.listAddresses' @'Shelley w (Just Used)) Default Empty expectResponseCode HTTP.status200 rUsed expectListSize 10 rUsed forM_ [0..9] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Used) rUsed rUnused <- request @[ApiAddress n] ctx (Link.listAddresses' @'Shelley w (Just Unused)) Default Empty expectResponseCode HTTP.status200 rUnused expectListSize g rUnused forM_ [10..(g-1)] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) rUnused it "ADDRESS_LIST_02 - Shows nothing when there are no used addresses" $ \ctx -> runResourceT $ do w <- emptyWallet ctx rUsed <- request @[ApiAddress n] ctx (Link.listAddresses' @'Shelley w (Just Used)) Default Empty rUnused <- request @[ApiAddress n] ctx (Link.listAddresses' @'Shelley w (Just Unused)) Default Empty expectResponseCode HTTP.status200 rUsed expectListSize 0 rUsed expectResponseCode HTTP.status200 rUnused expectListSize 20 rUnused forM_ [0..19] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) rUnused TODO MOVE TO test / unit / Cardano / Wallet / ApiSpec.hs describe "ADDRESS_LIST_02 - Invalid filters are bad requests" $ do let filters = [ "usedd" , "uused" , "unusedd" , "uunused" , "USED" , "UNUSED" , "-1000" , "44444444" , "*" ] let withQuery f (method, link) = (method, link <> "?state=" <> T.pack f) forM_ filters $ \fil -> it fil $ \ctx -> runResourceT $ do w <- emptyWallet ctx let link = withQuery fil $ Link.listAddresses @'Shelley w r <- request @[ApiAddress n] ctx link Default Empty verify r [ expectResponseCode HTTP.status400 , expectErrorMessage "Error parsing query parameter state failed: Unable to\ \ decode the given text value. Please specify\ \ one of the following values: used, unused." ] it "ADDRESS_LIST_03 - Generates new address pool gap" $ \ctx -> runResourceT $ do let initPoolGap = 10 wSrc <- fixtureWallet ctx wDest <- emptyWalletWith ctx ("Wallet", fixturePassphrase, initPoolGap) make sure all addresses in address_pool_gap are ' Unused ' r <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley wDest) Default Empty verify r [ expectResponseCode HTTP.status200 , expectListSize initPoolGap ] forM_ [0..9] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) r addrs <- listAddresses @n ctx wDest let amt = minUTxOValue (_mainEra ctx) run 10 transactions to make all addresses ` Used ` forM_ [0..9] $ \addrNum -> do let destination = (addrs !! addrNum) ^. #id let payload = Json [json|{ "payments": [{ "address": #{destination}, "amount": { "quantity": #{amt}, "unit": "lovelace" } }], "passphrase": #{fixturePassphrase} }|] rTrans <- request @(ApiTransaction n) ctx (Link.createTransactionOld @'Shelley wSrc) Default payload expectResponseCode HTTP.status202 rTrans eventually "Wallet balance = initPoolGap * minUTxOValue" $ do rb <- request @ApiWallet ctx (Link.getWallet @'Shelley wDest) Default Empty expectField (#balance . #available) (`shouldBe` Quantity (10 * amt)) rb verify new address_pool_gap has been created rAddr <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley wDest) Default Empty verify rAddr [ expectResponseCode HTTP.status200 , expectListSize 20 ] forM_ [0..9] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Used) rAddr forM_ [10..19] $ \addrNum -> do expectListField addrNum (#state . #getApiT) (`shouldBe` Unused) rAddr it "ADDRESS_LIST_04 - Deleted wallet" $ \ctx -> runResourceT $ do w <- emptyWallet ctx _ <- request @ApiWallet ctx (Link.deleteWallet @'Shelley w) Default Empty r <- request @[ApiAddress n] ctx (Link.listAddresses @'Shelley w) Default Empty expectResponseCode HTTP.status404 r expectErrorMessage (errMsg404NoWallet $ w ^. walletId) r it "ADDRESS_LIST_05 - bech32 HRP is correct - mainnet" $ \ctx -> runResourceT $ do w <- emptyWallet ctx r <- request @[Aeson.Value] ctx (Link.listAddresses @'Shelley w) Default Empty verify r [ expectResponseCode HTTP.status200 , expectListField 0 (Aeson.key "id" . Aeson._String) (`shouldSatisfy` T.isPrefixOf "addr") , expectListField 0 (Aeson.key "id" . Aeson._String) (`shouldNotSatisfy` T.isPrefixOf "addr_test") ] it "ADDRESS_LIST_06 - Used change addresses are listed after a transaction is no longer pending" $ \ctx -> runResourceT @IO $ do let verifyAddrs nTotal nUsed addrs = do liftIO (length addrs `shouldBe` nTotal) let onlyUsed = filter ((== Used) . (^. (#state . #getApiT))) addrs liftIO (length onlyUsed `shouldBe` nUsed) 1 . Create wallets let initialTotalA = 30 let initialUsedA = 10 wA <- fixtureWallet ctx listAddresses @n ctx wA >>= verifyAddrs initialTotalA initialUsedA let initialTotalB = 20 let initialUsedB = 0 wB <- emptyWallet ctx listAddresses @n ctx wB >>= verifyAddrs initialTotalB initialUsedB 2 . Send a transaction from A - > B destination <- view #id . head <$> listAddresses @n ctx wB let amount = 10 * minUTxOValue (_mainEra ctx) let payload = Json [json|{ "payments": [{ "address": #{destination}, "amount": { "quantity": #{amount}, "unit": "lovelace" } }], "passphrase": #{fixturePassphrase} }|] (_, rtx) <- unsafeRequest @(ApiTransaction n) ctx (Link.createTransactionOld @'Shelley wA) payload 3 . Check that there 's one more used addresses on A. listAddresses @n ctx wA >>= \addrs -> liftIO $ length addrs `shouldBe` (initialTotalA + 1) 4 . Wait for transaction from A - > B to no longer be pending eventually "Transaction from A -> B is discovered on B" $ do request @(ApiTransaction n) ctx (Link.getTransaction @'Shelley wA rtx) Default Empty >>= expectField #status (`shouldBe` ApiT InLedger) request @(ApiTransaction n) ctx (Link.getTransaction @'Shelley wB rtx) Default Empty >>= expectField #status (`shouldBe` ApiT InLedger) 5 . Check that there 's one more used and total addresses on the wallets first unused address from the consecutive sequence of the address listAddresses @n ctx wA >>= verifyAddrs (initialTotalA + 1) (initialUsedA + 1) listAddresses @n ctx wB >>= verifyAddrs (initialTotalB + 1) (initialUsedB + 1) it "ADDRESS_INSPECT_01 - Address inspect OK Icarus" $ \ctx -> do let str = "Ae2tdPwUPEYz6ExfbWubiXPB6daUuhJxikMEb4eXRp5oKZBKZwrbJ2k7EZe" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty verify r [ expectResponseCode HTTP.status200 , expectField (Aeson.key "address_style" . Aeson._String) (`shouldBe` "Icarus") , expectField (Aeson.key "address_type" . Aeson._Number) (`shouldBe` 8) ] it "ADDRESS_INSPECT_02 - Address inspect OK Byron" $ \ctx -> do let str = "37btjrVyb4KE2ByiPiJUQfAUBGaMyKScg4mnYjzVAsN2PUxj1WxTg98ien3oAo8vKBhP2KTuC9wi76vZ9kDNFkjbmzywdLTJgaz8n3RD3Rueim3Pd3" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty verify r [ expectResponseCode HTTP.status200 , expectField (Aeson.key "address_style" . Aeson._String) (`shouldBe` "Byron") , expectField (Aeson.key "address_type" . Aeson._Number) (`shouldBe` 8) ] it "ADDRESS_INSPECT_03 - Address inspect OK reward" $ \ctx -> do let str = "stake1u8pn5jr7cfa0x8ndtdufyg5lty3avg3zd2tq35c06hpsh8gptdza4" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty verify r [ expectResponseCode HTTP.status200 , expectField (Aeson.key "address_style" . Aeson._String) (`shouldBe` "Shelley") , expectField (Aeson.key "address_type" . Aeson._Number) (`shouldBe` 14) ] it "ADDRESS_INSPECT_04 - Address inspect KO" $ \ctx -> runResourceT $ do let str = "patate" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty expectResponseCode HTTP.status400 r it "ADDRESS_INSPECT_05 - Address inspect OK bech32" $ \ctx -> do let str = "addr_test1qzamu40sglnsrylzv9jylekjmzgaqsg5v5z9u6yk3jpnnxjwck77fqu8deuumsvnazjnjhwasc2eetfqpa2pvygts78ssd5388" r <- request @Aeson.Value ctx (Link.inspectAddress str) Default Empty verify r [ expectResponseCode HTTP.status200 , expectField (Aeson.key "address_style" . Aeson._String) (`shouldBe` "Shelley") , expectField (Aeson.key "spending_key_hash_bech32" . Aeson._String) (`shouldBe` "addr_vkh1hwl9tuz8uuqe8cnpv387d5kcj8gyz9r9q30x395vsvue5e44fh7") , expectField (Aeson.key "stake_key_hash_bech32" . Aeson._String) (`shouldBe` "stake_vkh1fmzmmeyrsah8nnwpj0522w2amkrpt89dyq84g9s3pwrc7dqjnfu") , expectField (Aeson.key "address_type" . Aeson._Number) (`shouldBe` 0) ] it "ANY_ADDRESS_POST_01 - Golden tests for enterprise script address - signature" $ \ctx -> do let payload1 = Json [json|{ "payment": "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq" }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": "script1ccqe6wa40878s2pxrfwj0qxz9t7dxw8rhfreqwzjuy67gk2ausz" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "addr1w8rqr8fmk4ulc7pgycd96fuqcg40e5ecuway0ypc2tsnteqm5wul2" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr it "ANY_ADDRESS_POST_02 - Golden tests for enterprise script address - any" $ \ctx -> do - any [ addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq , addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp ] let payload1 = Json [json|{ "payment": { "any": [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp" ] } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": "script1ujl6y7gx0e3h79kyzqan0smw3xq6x289za64fn6tap6xc7rsm0z" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "addr1w8jtlgneqelxxlckcsgrkd7rd6ycrgegu5th24x0f058gmqhsnv92" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr it "ANY_ADDRESS_POST_03 - Golden tests for enterprise script address - all" $ \ctx -> do - all [ addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq , addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp ] let payload1 = Json [json|{ "payment": { "all": [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp" ] } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": "script1gr69m385thgvkrtspk73zmkwk537wxyxuevs2u9cukglvtlkz4k" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "addr1w9q0ghwy73wapjcdwqxm6ytwe66j8eccsmn9jptshrjerasvf2cg0" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr it "ANY_ADDRESS_POST_04 - Golden tests for enterprise script address - some" $ \ctx -> do - at_least 2 [ addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq , addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp , addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9 ] let payload1 = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": "script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "addr1wyqmnmwuh85e0fxaggl6ac2hfeqncg76gsr0ld8qdjd84ag6sm0n8" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr it "ANY_ADDRESS_POST_05 - Golden tests for reward account script address - any" $ \ctx -> do let payload1 = Json [json|{ "stake": { "any": [ "stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5", "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s" ] } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "stake": "script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let goldenAddr = "stake17yshpfjkgh98wumvnn9y3yfhevllp4y04u6y84q3flxcv9sduxphm" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr - at_least 2 [ addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq , addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp , addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9 ] it "ANY_ADDRESS_POST_06 - Golden tests for delegating script address - any" $ \ctx -> do let payload1 = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "stake": { "any": [ "stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5", "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s" ] } }|] r1 <- request @AnyAddress ctx Link.postAnyAddress Default payload1 expectResponseCode HTTP.status202 r1 let payload2 = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "stake": "script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz" }|] r2 <- request @AnyAddress ctx Link.postAnyAddress Default payload2 expectResponseCode HTTP.status202 r2 let payload3 = Json [json|{ "payment": "script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778", "stake": { "any": [ "stake_shared_vkh1nqc00hvlc6cq0sfhretk0rmzw8dywmusp8retuqnnxzajtzhjg5", "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s" ] } }|] r3 <- request @AnyAddress ctx Link.postAnyAddress Default payload3 expectResponseCode HTTP.status202 r3 let payload4 = Json [json|{ "payment": "script1qxu7mh9eaxt6fh2z87hwz46wgy7z8kjyqmlmfcrvnfa02aj9778", "stake": "script1y9c2v4j9efmhxmyuefyfzd7t8lcdfra0x3pagy20ekrpvfxxxyz" }|] r4 <- request @AnyAddress ctx Link.postAnyAddress Default payload4 expectResponseCode HTTP.status202 r4 let goldenAddr = "addr1xyqmnmwuh85e0fxaggl6ac2hfeqncg76gsr0ld8qdjd84afpwzn9v3w2waeke8x2fzgn0jel7r2glte5g02pzn7dsctqu6mtx3" :: Text validateAddr r1 goldenAddr validateAddr r2 goldenAddr validateAddr r3 goldenAddr validateAddr r4 goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_07a - Golden tests for enterprise address - from non-extended public key" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwpschzd2j" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1v9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wfgknj82e" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_07b - Golden tests for enterprise address - from extended public key" $ \ctx -> do let payload = Json [json|{ "payment": "addr_xvk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwp3k2zz8796vdstcu7q0qp232wyvzjes0qkpmt7gzwa0x2q75h3qcgl5y4q0" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1v9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wfgknj82e" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_07c - Golden tests for enterprise address - from key hash" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1v9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wfgknj82e" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ it "ANY_ADDRESS_POST_08a - Golden tests for reward account address - from non-extended public key" $ \ctx -> do let payload = Json [json|{ "stake": "stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "stake1uy6pmlvyl3wn4ca6807e26gy2gek9hqu0gastzh5tk0xx0g2rxsr5" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ it "ANY_ADDRESS_POST_08b - Golden tests for reward account address - from extended public key" $ \ctx -> do let payload = Json [json|{ "stake": "stake_xvk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7yak6lmcyst8yclpm3yalrspc7q2wy9f6683x6f9z4e3gclhs5snslcst62" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "stake1uy6pmlvyl3wn4ca6807e26gy2gek9hqu0gastzh5tk0xx0g2rxsr5" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ it "ANY_ADDRESS_POST_08c - Golden tests for reward account address - from key hash" $ \ctx -> do let payload = Json [json|{ "stake": "stake_vkh1xswlmp8ut5aw8w3mlk2kjpzjxd3dc8r68vzc4azane3n6r07ddx" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "stake1uy6pmlvyl3wn4ca6807e26gy2gek9hqu0gastzh5tk0xx0g2rxsr5" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_09a - Golden tests for delegating address with both non-extended pub key credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwpschzd2j", "stake": "stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_09b - Golden tests for delegating address with both extended pub key credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_xvk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwp3k2zz8796vdstcu7q0qp232wyvzjes0qkpmt7gzwa0x2q75h3qcgl5y4q0", "stake": "stake_xvk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7yak6lmcyst8yclpm3yalrspc7q2wy9f6683x6f9z4e3gclhs5snslcst62" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_09c - Golden tests for delegating address with both key hash credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs", "stake": "stake_vkh1xswlmp8ut5aw8w3mlk2kjpzjxd3dc8r68vzc4azane3n6r07ddx" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_09d - Golden tests for delegating address with mixed credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs", "stake": "stake_xvk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7yak6lmcyst8yclpm3yalrspc7q2wy9f6683x6f9z4e3gclhs5snslcst62" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_09e - Golden tests for delegating address with mixed credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vkh1gza7wc699kqnjv55ldmj74x0acledxfd7z8zvlvjcwnj2h09mcs", "stake": "stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_09f - Golden tests for delegating address with mixed credentials" $ \ctx -> do let payload = Json [json|{ "payment": "addr_xvk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwp3k2zz8796vdstcu7q0qp232wyvzjes0qkpmt7gzwa0x2q75h3qcgl5y4q0", "stake": "stake_vkh1xswlmp8ut5aw8w3mlk2kjpzjxd3dc8r68vzc4azane3n6r07ddx" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1q9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wff5r\ \h7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7s64ryn2" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child \ it "ANY_ADDRESS_POST_10 - Golden tests for delegating address - payment from script, stake from key" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "stake": "stake_vk16apaenn9ut6s40lcw3l8v68xawlrlq20z2966uzcx8jmv2q9uy7qau558d" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1zyqmnmwuh85e0fxaggl6ac2hfeqncg76gsr0ld8qdjd84af5rh7cflza8t3m5wlaj45sg53nvtwpc73mqk90ghv7vv7srr0dle" :: Text validateAddr r goldenAddr - $ cat recovery-phrase.txt | cardano - address key from - recovery - phrase \ - > | cardano - address key child 1852H/1815H/0H/0/0 \ it "ANY_ADDRESS_POST_11 - Golden tests for delegating address - payment from key, stake from script" $ \ctx -> do let payload = Json [json|{ "payment": "addr_vk1lqglg77z6kajsdz4739q22c0zm0yhuy567z6xk2vc0z5ucjtkwpschzd2j", "stake": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1y9qthemrg5kczwfjjnahwt65elhrl95e9hcgufnajtp6wfgph8kaew0fj7jd6s3l4ms4wnjp8s3a53qxl76wqmy60t6ssqcamq" :: Text validateAddr r goldenAddr it "ANY_ADDRESS_POST_12 - Delegating addresses API roundtrip" $ \ctx -> runResourceT $ do w <- emptyWallet ctx Generate first 20 addresses using payment and stake keys derived from let indices = [0..19] generatedAddresses <- forM indices $ \index -> do let paymentPath = Link.getWalletKey @'Shelley w UtxoExternal (DerivationIndex index) Nothing (_, paymentKey) <- unsafeRequest @ApiVerificationKeyShelley ctx paymentPath Empty let stakePath = Link.getWalletKey @'Shelley w MutableAccount (DerivationIndex 0) Nothing (_, stakeKey) <- unsafeRequest @ApiVerificationKeyShelley ctx stakePath Empty let payload = Json [json|{ "payment": #{paymentKey}, "stake": #{stakeKey} }|] (_, addr) <- unsafeRequest @AnyAddress ctx Link.postAnyAddress payload pure (addr ^. #payload) addrs <- listAddresses @n ctx w forM_ (zip (fmap fromIntegral indices) generatedAddresses) $ \(idx, genAddr) -> do let walAddr = fst (addrs !! idx ^. #id) ^. (#getApiT . #unAddress) walAddr `shouldBe` genAddr it "ANY_ADDRESS_POST_13 - Golden tests for script with timelocks" $ \ctx -> do let payload = Json [json|{ "payment": { "all" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", { "active_from": 120 } ] }, "stake": { "all" : [ "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s", { "active_from": 120 } ] } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r let goldenAddr = "addr1xy756z909yycvf5ah8j5pc4cvuedkhvhyylmgfz400t8jdwmwa0hp024gu7dm6h8n252lkgnzemp93mm9kyd48p64mjshqtu3c" :: Text validateAddr r goldenAddr it "ANY_ADDRESS_POST_14a - at_least 0 is valid when non-validated" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 0 } } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_14b - at_least 0 is valid when validation is required" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 0 } }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_14c - at_least 0 is not valid when validation is recommended" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 0 } }, "validation": "recommended" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptWrongCoeffcient r it "ANY_ADDRESS_POST_15a - at_least 4 is valid when non-validated" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 4 } } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_15b - at_least 4 is valid when validation is required" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 4 } }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptIllFormed r it "ANY_ADDRESS_POST_15c - at_least 4 is not valid when validation is recommended" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 4 } }, "validation": "recommended" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptIllFormed r it "ANY_ADDRESS_POST_16a - script with duplicated verification keys is valid when non-validated" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_16b - script with duplicated verification keys is valid when required validation used" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1y3zl4nqgm96ankt96dsdhc86vd5geny0wr7hu8cpzdfcqskq2cp", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_16c - script with duplicated verification keys is invalid when recommended validation used" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "addr_shared_vkh175wsm9ckhm3snwcsn72543yguxeuqm7v9r6kl6gx57h8gdydcd9" ], "at_least": 2 } }, "validation": "recommended" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptDuplicateKeys r it "ANY_ADDRESS_POST_17a - Script with contradictory timelocks is valid when validation not used" $ \ctx -> do let payload = Json [json|{ "payment": { "all" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", { "active_from": 120 }, { "active_until": 100 } ] }, "stake": { "all" : [ "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s", { "active_from": 120 } ] } }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_17b - Script with contradictory timelocks is invalid when required validation is used" $ \ctx -> do let payload = Json [json|{ "payment": { "all" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", { "active_from": 120 }, { "active_until": 100 } ] }, "stake": { "all" : [ "script_vkh1yf07000d4ml3ywd3d439kmwp07xzgv6p35cwx8h605jfx0dtd4a", { "active_from": 120 } ] }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status202 r it "ANY_ADDRESS_POST_17c - Script with contradictory timelocks is invalid when recommended validation is used" $ \ctx -> do let payload = Json [json|{ "payment": { "all" : [ "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s", { "active_from": 120 }, { "active_until": 100 } ] }, "stake": { "all" : [ "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s", { "active_from": 120 } ] }, "validation": "recommended" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptTimelocksContradictory r it "ANY_ADDRESS_POST_17d - script with mixed payment/delegation verification keys is invalid" $ \ctx -> do let payload = Json [json|{ "payment": { "some": { "from" : [ "addr_shared_vkh1zxt0uvrza94h3hv4jpv0ttddgnwkvdgeyq8jf9w30mcs6y8w3nq", "stake_shared_vkh1nac0awgfa4zjsh4elnjmsscz0huhss8q2g0x3n7m539mwaa5m7s" ], "at_least": 1 } }, "validation": "required" }|] r <- request @AnyAddress ctx Link.postAnyAddress Default payload expectResponseCode HTTP.status400 r expectErrorMessage errMsg400ScriptNotUniformRoles r it "POST_ACCOUNT_01 - Can retrieve account public keys" $ \ctx -> runResourceT $ do let initPoolGap = 10 w <- emptyWalletWith ctx ("Wallet", fixturePassphrase, initPoolGap) let endpoint = Link.postAccountKey @'Shelley w (DerivationIndex 0) let payload = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended" }|] resp <- request @ApiAccountKey ctx endpoint Default payload expectErrorMessage errMsg403WrongIndex resp Request first 10 extended account public keys let indices = [0..9] accountPublicKeys <- forM indices $ \index -> do let accountPath = Link.postAccountKey @'Shelley w (DerivationIndex $ 2_147_483_648 + index) let payload1 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended" }|] let payload2 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "non_extended" }|] (_, accXPub) <- unsafeRequest @ApiAccountKey ctx accountPath payload1 (_, accPub) <- unsafeRequest @ApiAccountKey ctx accountPath payload2 let (Aeson.String accXPubTxt) = toJSON accXPub let (Aeson.String accPubTxt) = toJSON accPub T.isPrefixOf "acct_xvk" accXPubTxt `shouldBe` True T.isPrefixOf "acct_vk" accPubTxt `shouldBe` True pure [accXPub, accPub] length (concat accountPublicKeys) `shouldBe` 20 it "POST_ACCOUNT_02 - Can get account public key using purpose" $ \ctx -> runResourceT $ do let initPoolGap = 10 w <- emptyWalletWith ctx ("Wallet", fixturePassphrase, initPoolGap) let accountPath = Link.postAccountKey @'Shelley w (DerivationIndex $ 2_147_483_648 + 1) let payload1 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended" }|] (_, accXPub1) <- unsafeRequest @ApiAccountKey ctx accountPath payload1 let (Aeson.String accXPub1Txt) = toJSON accXPub1 T.isPrefixOf "acct_xvk" accXPub1Txt `shouldBe` True let payload2 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended", "purpose": "1852H" }|] (_, accXPub2) <- unsafeRequest @ApiAccountKey ctx accountPath payload2 accXPub1 `shouldBe` accXPub2 let payload3 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended", "purpose": "1854H" }|] (_, accXPub3) <- unsafeRequest @ApiAccountKey ctx accountPath payload3 accXPub1 `shouldNotBe` accXPub3 let (Aeson.String accXPub3Txt) = toJSON accXPub3 T.isPrefixOf "acct_shared_xvk" accXPub3Txt `shouldBe` True let payload4 = Json [json|{ "passphrase": #{fixturePassphrase}, "format": "extended", "purpose": "1854" }|] resp <- request @ApiAccountKey ctx accountPath Default payload4 expectErrorMessage errMsg403WrongIndex resp it "ANY_ADDRESS_POST_15 - Staking address using stake credential non-hashed" $ \ctx -> runResourceT $ do w <- emptyWallet ctx let stakePath = Link.getWalletKey @'Shelley w MutableAccount (DerivationIndex 0) Nothing (_, stakeKey) <- unsafeRequest @ApiVerificationKeyShelley ctx stakePath Empty let (Aeson.String stakeKeyTxt) = toJSON stakeKey stakeKeyTxt `shouldSatisfy` T.isPrefixOf "stake_vk1" let payload = Json [json|{ "stake": #{stakeKey} }|] (_, stakeAddr) <- unsafeRequest @AnyAddress ctx Link.postAnyAddress payload let (Aeson.Object stakeAddrJson) = toJSON stakeAddr let (Just (Aeson.String stakeAddrTxt)) = KeyMap.lookup "address" stakeAddrJson stakeAddrTxt `shouldSatisfy` T.isPrefixOf "stake1" it "ANY_ADDRESS_POST_16 - Staking address using stake credential hashed" $ \ctx -> runResourceT $ do w <- emptyWallet ctx let stakePath = Link.getWalletKey @'Shelley w MutableAccount (DerivationIndex 0) (Just True) (_, stakeKeyHash) <- unsafeRequest @ApiVerificationKeyShelley ctx stakePath Empty let (Aeson.String stakeKeyHashTxt) = toJSON stakeKeyHash stakeKeyHashTxt `shouldSatisfy` T.isPrefixOf "stake_vkh1" let payload = Json [json|{ "stake": #{stakeKeyHash} }|] (_, stakeAddr) <- unsafeRequest @AnyAddress ctx Link.postAnyAddress payload let (Aeson.Object stakeAddrJson) = toJSON stakeAddr let (Just (Aeson.String stakeAddrTxt)) = KeyMap.lookup "address" stakeAddrJson stakeAddrTxt `shouldSatisfy` T.isPrefixOf "stake1" where validateAddr resp expected = do let addr = getFromResponse id resp toJSON addr `shouldBe` object ["address" .= expected ]
e63d3e958ed17ef69ef31faecabc1441b6287ec6c8783c2287a984b94a5e9647
sangkilc/ofuzz
fastlib.mli
(* ofuzz - partition-based mutational fuzzing *) * fast library @author < sangkil.cha\@gmail.com > @since 2014 - 03 - 19 @author Sang Kil Cha <sangkil.cha\@gmail.com> @since 2014-03-19 *) Copyright ( c ) 2014 , All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . * Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . * Neither the name of the < organization > nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL SANG KIL CHA 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 Copyright (c) 2014, Sang Kil Cha All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANG KIL CHA 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 *) (** File handler type *) type file_t (** [copy a b] copies file [a] to file [b] *) val copy : string -> string -> unit (** [exec cmds timeout oflag] executes a command line [cmds] up to [timeout] seconds, and returns a tuple (code, pid). If [oflag] is true, then the output of execution is shown. The return code is 0 if there is no error, otherwise it contains signal number that causes the program to crash. *) val exec : string array -> int -> bool -> int * int (** mmap a file for a given name and a size *) val map_file : string -> int -> file_t * val unmap_file : file_t -> unit * [ mod_file f pos v ] modifies the file [ f ] by applying to the character at [ pos ] with [ v ] . [pos] with [v]. *) val mod_file : file_t -> int -> char -> unit (** Get a page-aligned size *) val get_mapping_size : int -> int (** [get_size_tuple f] returns a pair of a page-aligned file size and the actual file size from a given file path [f] *) val get_size_tuple: string -> int * int
null
https://raw.githubusercontent.com/sangkilc/ofuzz/ba53cc90cc06512eb90459a7159772d75ebe954f/src/fastlib.mli
ocaml
ofuzz - partition-based mutational fuzzing * File handler type * [copy a b] copies file [a] to file [b] * [exec cmds timeout oflag] executes a command line [cmds] up to [timeout] seconds, and returns a tuple (code, pid). If [oflag] is true, then the output of execution is shown. The return code is 0 if there is no error, otherwise it contains signal number that causes the program to crash. * mmap a file for a given name and a size * Get a page-aligned size * [get_size_tuple f] returns a pair of a page-aligned file size and the actual file size from a given file path [f]
* fast library @author < sangkil.cha\@gmail.com > @since 2014 - 03 - 19 @author Sang Kil Cha <sangkil.cha\@gmail.com> @since 2014-03-19 *) Copyright ( c ) 2014 , All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : * Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . * Redistributions in binary form must reproduce the above copyright notice , this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution . * Neither the name of the < organization > nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL SANG KIL CHA 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 Copyright (c) 2014, Sang Kil Cha All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANG KIL CHA 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 *) type file_t val copy : string -> string -> unit val exec : string array -> int -> bool -> int * int val map_file : string -> int -> file_t * val unmap_file : file_t -> unit * [ mod_file f pos v ] modifies the file [ f ] by applying to the character at [ pos ] with [ v ] . [pos] with [v]. *) val mod_file : file_t -> int -> char -> unit val get_mapping_size : int -> int val get_size_tuple: string -> int * int
533d7eb8a75330ab93e531ad4e56823a3dd1aa612cab4f9cd0e09f2b798a46a8
phadej/cabal-extras
Warning.hs
module CabalEnv.Warning where import Peura data W = WMissingCabalEnvData deriving (Eq, Ord, Enum, Bounded) instance Universe W where universe = [minBound .. maxBound] instance Finite W instance Warning W where warningToFlag WMissingCabalEnvData = "missing-cabal-envdata"
null
https://raw.githubusercontent.com/phadej/cabal-extras/378cac5495b829794d67f243b27a9317eeed0858/cabal-env/src/CabalEnv/Warning.hs
haskell
module CabalEnv.Warning where import Peura data W = WMissingCabalEnvData deriving (Eq, Ord, Enum, Bounded) instance Universe W where universe = [minBound .. maxBound] instance Finite W instance Warning W where warningToFlag WMissingCabalEnvData = "missing-cabal-envdata"
ca465715b371498c7575a6744d11cd6dc9286e9d5d3850a600de7a99661a328c
input-output-hk/cardano-sl
Parallelize.hs
module Test.Pos.Util.Parallel.Parallelize ( parallelizeAllCores ) where import Universum import GHC.Conc (getNumProcessors, setNumCapabilities) -- | `parallelizeAllCores` gets the number of processors on a machine and -- sets the number of threads equal to the number of processors on the machine. parallelizeAllCores :: IO () parallelizeAllCores = getNumProcessors >>= setNumCapabilities
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/util/test/Test/Pos/Util/Parallel/Parallelize.hs
haskell
| `parallelizeAllCores` gets the number of processors on a machine and sets the number of threads equal to the number of processors on the machine.
module Test.Pos.Util.Parallel.Parallelize ( parallelizeAllCores ) where import Universum import GHC.Conc (getNumProcessors, setNumCapabilities) parallelizeAllCores :: IO () parallelizeAllCores = getNumProcessors >>= setNumCapabilities
a3ab42508d654589146e2624d375fda702704e5b366a9247842e196297ddabd8
2600hz/kazoo
kzd_vm_message_metadata.erl
%%%----------------------------------------------------------------------------- ( C ) 2010 - 2020 , 2600Hz %%% @doc This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. %%% %%% @end %%%----------------------------------------------------------------------------- -module(kzd_vm_message_metadata). -export([new/0]). -export([call_id/1, call_id/2, set_call_id/2]). -export([caller_id_name/1, caller_id_name/2, set_caller_id_name/2]). -export([caller_id_number/1, caller_id_number/2, set_caller_id_number/2]). -export([folder/1, folder/2, set_folder/2]). -export([from/1, from/2, set_from/2]). -export([length/1, length/2, set_length/2]). -export([timestamp/1, timestamp/2, set_timestamp/2]). -export([to/1, to/2, set_to/2]). -include("kz_documents.hrl"). -type doc() :: kz_json:object(). -export_type([doc/0]). -define(SCHEMA, <<"vm_message_metadata">>). -spec new() -> doc(). new() -> kz_json_schema:default_object(?SCHEMA). -spec call_id(doc()) -> kz_term:api_binary(). call_id(Doc) -> call_id(Doc, 'undefined'). -spec call_id(doc(), Default) -> binary() | Default. call_id(Doc, Default) -> kz_json:get_binary_value([<<"call_id">>], Doc, Default). -spec set_call_id(doc(), binary()) -> doc(). set_call_id(Doc, CallId) -> kz_json:set_value([<<"call_id">>], CallId, Doc). -spec caller_id_name(doc()) -> kz_term:api_binary(). caller_id_name(Doc) -> caller_id_name(Doc, 'undefined'). -spec caller_id_name(doc(), Default) -> binary() | Default. caller_id_name(Doc, Default) -> kz_json:get_binary_value([<<"caller_id_name">>], Doc, Default). -spec set_caller_id_name(doc(), binary()) -> doc(). set_caller_id_name(Doc, CallerIdName) -> kz_json:set_value([<<"caller_id_name">>], CallerIdName, Doc). -spec caller_id_number(doc()) -> kz_term:api_binary(). caller_id_number(Doc) -> caller_id_number(Doc, 'undefined'). -spec caller_id_number(doc(), Default) -> binary() | Default. caller_id_number(Doc, Default) -> kz_json:get_binary_value([<<"caller_id_number">>], Doc, Default). -spec set_caller_id_number(doc(), binary()) -> doc(). set_caller_id_number(Doc, CallerIdNumber) -> kz_json:set_value([<<"caller_id_number">>], CallerIdNumber, Doc). -spec folder(doc()) -> kz_term:api_binary(). folder(Doc) -> folder(Doc, 'undefined'). -spec folder(doc(), Default) -> binary() | Default. folder(Doc, Default) -> kz_json:get_binary_value([<<"folder">>], Doc, Default). -spec set_folder(doc(), binary()) -> doc(). set_folder(Doc, Folder) -> kz_json:set_value([<<"folder">>], Folder, Doc). -spec from(doc()) -> kz_term:api_binary(). from(Doc) -> from(Doc, 'undefined'). -spec from(doc(), Default) -> binary() | Default. from(Doc, Default) -> kz_json:get_binary_value([<<"from">>], Doc, Default). -spec set_from(doc(), binary()) -> doc(). set_from(Doc, From) -> kz_json:set_value([<<"from">>], From, Doc). -spec length(doc()) -> kz_term:api_integer(). length(Doc) -> length(Doc, 'undefined'). -spec length(doc(), Default) -> integer() | Default. length(Doc, Default) -> kz_json:get_integer_value([<<"length">>], Doc, Default). -spec set_length(doc(), integer()) -> doc(). set_length(Doc, Length) -> kz_json:set_value([<<"length">>], Length, Doc). -spec timestamp(doc()) -> kz_term:api_integer(). timestamp(Doc) -> timestamp(Doc, 'undefined'). -spec timestamp(doc(), Default) -> integer() | Default. timestamp(Doc, Default) -> kz_json:get_integer_value([<<"timestamp">>], Doc, Default). -spec set_timestamp(doc(), integer()) -> doc(). set_timestamp(Doc, Timestamp) -> kz_json:set_value([<<"timestamp">>], Timestamp, Doc). -spec to(doc()) -> kz_term:api_binary(). to(Doc) -> to(Doc, 'undefined'). -spec to(doc(), Default) -> binary() | Default. to(Doc, Default) -> kz_json:get_binary_value([<<"to">>], Doc, Default). -spec set_to(doc(), binary()) -> doc(). set_to(Doc, To) -> kz_json:set_value([<<"to">>], To, Doc).
null
https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_documents/src/kzd_vm_message_metadata.erl
erlang
----------------------------------------------------------------------------- @doc @end -----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. -module(kzd_vm_message_metadata). -export([new/0]). -export([call_id/1, call_id/2, set_call_id/2]). -export([caller_id_name/1, caller_id_name/2, set_caller_id_name/2]). -export([caller_id_number/1, caller_id_number/2, set_caller_id_number/2]). -export([folder/1, folder/2, set_folder/2]). -export([from/1, from/2, set_from/2]). -export([length/1, length/2, set_length/2]). -export([timestamp/1, timestamp/2, set_timestamp/2]). -export([to/1, to/2, set_to/2]). -include("kz_documents.hrl"). -type doc() :: kz_json:object(). -export_type([doc/0]). -define(SCHEMA, <<"vm_message_metadata">>). -spec new() -> doc(). new() -> kz_json_schema:default_object(?SCHEMA). -spec call_id(doc()) -> kz_term:api_binary(). call_id(Doc) -> call_id(Doc, 'undefined'). -spec call_id(doc(), Default) -> binary() | Default. call_id(Doc, Default) -> kz_json:get_binary_value([<<"call_id">>], Doc, Default). -spec set_call_id(doc(), binary()) -> doc(). set_call_id(Doc, CallId) -> kz_json:set_value([<<"call_id">>], CallId, Doc). -spec caller_id_name(doc()) -> kz_term:api_binary(). caller_id_name(Doc) -> caller_id_name(Doc, 'undefined'). -spec caller_id_name(doc(), Default) -> binary() | Default. caller_id_name(Doc, Default) -> kz_json:get_binary_value([<<"caller_id_name">>], Doc, Default). -spec set_caller_id_name(doc(), binary()) -> doc(). set_caller_id_name(Doc, CallerIdName) -> kz_json:set_value([<<"caller_id_name">>], CallerIdName, Doc). -spec caller_id_number(doc()) -> kz_term:api_binary(). caller_id_number(Doc) -> caller_id_number(Doc, 'undefined'). -spec caller_id_number(doc(), Default) -> binary() | Default. caller_id_number(Doc, Default) -> kz_json:get_binary_value([<<"caller_id_number">>], Doc, Default). -spec set_caller_id_number(doc(), binary()) -> doc(). set_caller_id_number(Doc, CallerIdNumber) -> kz_json:set_value([<<"caller_id_number">>], CallerIdNumber, Doc). -spec folder(doc()) -> kz_term:api_binary(). folder(Doc) -> folder(Doc, 'undefined'). -spec folder(doc(), Default) -> binary() | Default. folder(Doc, Default) -> kz_json:get_binary_value([<<"folder">>], Doc, Default). -spec set_folder(doc(), binary()) -> doc(). set_folder(Doc, Folder) -> kz_json:set_value([<<"folder">>], Folder, Doc). -spec from(doc()) -> kz_term:api_binary(). from(Doc) -> from(Doc, 'undefined'). -spec from(doc(), Default) -> binary() | Default. from(Doc, Default) -> kz_json:get_binary_value([<<"from">>], Doc, Default). -spec set_from(doc(), binary()) -> doc(). set_from(Doc, From) -> kz_json:set_value([<<"from">>], From, Doc). -spec length(doc()) -> kz_term:api_integer(). length(Doc) -> length(Doc, 'undefined'). -spec length(doc(), Default) -> integer() | Default. length(Doc, Default) -> kz_json:get_integer_value([<<"length">>], Doc, Default). -spec set_length(doc(), integer()) -> doc(). set_length(Doc, Length) -> kz_json:set_value([<<"length">>], Length, Doc). -spec timestamp(doc()) -> kz_term:api_integer(). timestamp(Doc) -> timestamp(Doc, 'undefined'). -spec timestamp(doc(), Default) -> integer() | Default. timestamp(Doc, Default) -> kz_json:get_integer_value([<<"timestamp">>], Doc, Default). -spec set_timestamp(doc(), integer()) -> doc(). set_timestamp(Doc, Timestamp) -> kz_json:set_value([<<"timestamp">>], Timestamp, Doc). -spec to(doc()) -> kz_term:api_binary(). to(Doc) -> to(Doc, 'undefined'). -spec to(doc(), Default) -> binary() | Default. to(Doc, Default) -> kz_json:get_binary_value([<<"to">>], Doc, Default). -spec set_to(doc(), binary()) -> doc(). set_to(Doc, To) -> kz_json:set_value([<<"to">>], To, Doc).
7d207fc22441850fe83a91b7096c63b733663c2fcfb5302d74f7e36685032456
tnelson/Forge
basic-example-core.rkt
#lang forge/new-mode/core (sig A) (sig B) (relation r (A B)) (run my-run) (display my-run)
null
https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/new-mode/examples/basic-example-core.rkt
racket
#lang forge/new-mode/core (sig A) (sig B) (relation r (A B)) (run my-run) (display my-run)
427615f47a56be6ba4223f969428abbcb263522f9fbe57c6dff5415987d549a8
input-output-hk/hydra
MockChain.hs
# LANGUAGE RecordWildCards # module Hydra.Model.MockChain where import Hydra.Cardano.Api import Hydra.Prelude hiding (Any, label) import Cardano.Binary (serialize', unsafeDeserialize') import Cardano.Ledger.Alonzo.TxSeq (TxSeq (TxSeq)) import qualified Cardano.Ledger.Babbage.Tx as Ledger import qualified Cardano.Ledger.Shelley.API as Ledger import Control.Monad.Class.MonadAsync (Async, async) import Control.Monad.Class.MonadFork (labelThisThread) import Control.Monad.Class.MonadSTM ( MonadLabelledSTM, labelTQueueIO, modifyTVar, newTQueueIO, readTVarIO, tryReadTQueue, writeTQueue, ) import qualified Data.Sequence.Strict as StrictSeq import Hydra.BehaviorSpec ( ConnectToChain (..), ) import Hydra.Chain (Chain (..)) import Hydra.Chain.Direct.Fixture (testNetworkId) import Hydra.Chain.Direct.Handlers (ChainSyncHandler, DirectChainLog, SubmitTx, chainSyncHandler, mkChain, onRollForward) import Hydra.Chain.Direct.ScriptRegistry (ScriptRegistry (..)) import Hydra.Chain.Direct.State (ChainContext (..), ChainStateAt (..)) import qualified Hydra.Chain.Direct.State as S import Hydra.Chain.Direct.TimeHandle (TimeHandle) import qualified Hydra.Chain.Direct.Util as Util import Hydra.Chain.Direct.Wallet (TinyWallet (..)) import Hydra.ContestationPeriod (ContestationPeriod) import Hydra.Crypto (HydraKey) import Hydra.HeadLogic ( Environment (Environment, otherParties, party), Event (NetworkEvent), HeadState (..), IdleState (..), defaultTTL, ) import Hydra.Ledger.Cardano (genTxIn) import Hydra.Logging (Tracer) import Hydra.Model.Payment (CardanoSigningKey (..)) import Hydra.Network (Network (..)) import Hydra.Network.Message (Message) import Hydra.Node ( HydraNode (..), chainCallback, createNodeState, putEvent, ) import Hydra.Party (Party (..), deriveParty) import Ouroboros.Consensus.Cardano.Block (HardForkBlock (..)) import qualified Ouroboros.Consensus.Protocol.Praos.Header as Praos import Ouroboros.Consensus.Shelley.Ledger (mkShelleyBlock) import Test.Consensus.Cardano.Generators () | Provide the logic to connect a list of ` MockHydraNode ` through a dummy chain . mockChainAndNetwork :: forall m. ( MonadSTM m , MonadTimer m , MonadThrow m , MonadAsync m , MonadThrow (STM m) , MonadLabelledSTM m ) => Tracer m DirectChainLog -> [(SigningKey HydraKey, CardanoSigningKey)] -> TVar m [MockHydraNode m] -> ContestationPeriod -> m (ConnectToChain Tx m, Async m ()) mockChainAndNetwork tr seedKeys nodes cp = do queue <- newTQueueIO labelTQueueIO queue "chain-queue" tickThread <- async (labelThisThread "chain" >> simulateTicks queue) let chainComponent = \node -> do let Environment{party = ownParty, otherParties} = env node let (vkey, vkeys) = findOwnCardanoKey ownParty seedKeys let ctx = S.ChainContext { networkId = testNetworkId , peerVerificationKeys = vkeys , ownVerificationKey = vkey , ownParty , otherParties , scriptRegistry = TODO : we probably want different _ scripts _ as initial and commit one let txIn = mkMockTxIn vkey 0 txOut = TxOut (mkVkAddress testNetworkId vkey) (lovelaceToValue 10_000_000) TxOutDatumNone ReferenceScriptNone in ScriptRegistry { initialReference = (txIn, txOut) , commitReference = (txIn, txOut) , headReference = (txIn, txOut) } , contestationPeriod = cp } chainState = S.ChainStateAt { chainState = S.Idle , recordedAt = Nothing } let getTimeHandle = pure $ arbitrary `generateWith` 42 let seedInput = genTxIn `generateWith` 42 nodeState <- createNodeState $ Idle IdleState{chainState} let HydraNode{eq} = node let callback = chainCallback nodeState eq let chainHandler = chainSyncHandler tr callback getTimeHandle ctx let node' = node { hn = createMockNetwork node nodes , oc = createMockChain tr ctx (atomically . writeTQueue queue) getTimeHandle seedInput , nodeState } let mockNode = MockHydraNode{node = node', chainHandler} atomically $ modifyTVar nodes (mockNode :) pure node' -- NOTE: this is not used (yet) but could be used to trigger arbitrary rollbacks -- in the run model rollbackAndForward = error "Not implemented, should never be called" return (ConnectToChain{..}, tickThread) where blockTime = 20 -- seconds simulateTicks queue = forever $ do threadDelay blockTime hasTx <- atomically $ tryReadTQueue queue case hasTx of Just tx -> do let block = mkBlock tx allHandlers <- fmap chainHandler <$> readTVarIO nodes forM_ allHandlers (`onRollForward` block) Nothing -> pure () | Find Cardano vkey corresponding to our using signing keys lookup . This is a bit cumbersome and a tribute to the fact the ` HydraNode ` itself has no -- direct knowlege of the cardano keys which are stored only at the `ChainComponent` level. findOwnCardanoKey :: Party -> [(SigningKey HydraKey, CardanoSigningKey)] -> (VerificationKey PaymentKey, [VerificationKey PaymentKey]) findOwnCardanoKey me seedKeys = fromMaybe (error $ "cannot find cardano key for " <> show me <> " in " <> show seedKeys) $ do csk <- getVerificationKey . signingKey . snd <$> find ((== me) . deriveParty . fst) seedKeys pure (csk, filter (/= csk) $ map (getVerificationKey . signingKey . snd) seedKeys) mkBlock :: Ledger.ValidatedTx LedgerEra -> Util.Block mkBlock ledgerTx = let header = (arbitrary :: Gen (Praos.Header StandardCrypto)) `generateWith` 42 body = TxSeq . StrictSeq.fromList $ [ledgerTx] in BlockBabbage $ mkShelleyBlock $ Ledger.Block header body TODO : unify with BehaviorSpec 's ? createMockNetwork :: MonadSTM m => HydraNode Tx m -> TVar m [MockHydraNode m] -> Network m (Message Tx) createMockNetwork myNode nodes = Network{broadcast} where broadcast msg = do allNodes <- fmap node <$> readTVarIO nodes let otherNodes = filter (\n -> getNodeId n /= getNodeId myNode) allNodes mapM_ (`handleMessage` msg) otherNodes handleMessage HydraNode{eq} = putEvent eq . NetworkEvent defaultTTL getNodeId = party . env data MockHydraNode m = MockHydraNode { node :: HydraNode Tx m , chainHandler :: ChainSyncHandler m } createMockChain :: (MonadTimer m, MonadThrow (STM m)) => Tracer m DirectChainLog -> ChainContext -> SubmitTx m -> m TimeHandle -> TxIn -> Chain Tx m createMockChain tracer ctx submitTx timeHandle seedInput = -- NOTE: The wallet basically does nothing let wallet = TinyWallet { getUTxO = pure mempty , getSeedInput = pure (Just seedInput) , sign = id , coverFee = \_ tx -> pure (Right tx) , reset = pure () , update = const $ pure () } in mkChain tracer timeHandle wallet ctx submitTx mkMockTxIn :: VerificationKey PaymentKey -> Word -> TxIn mkMockTxIn vk ix = TxIn (TxId tid) (TxIx ix) where NOTE : Ugly , works because both binary representations are 32 - byte long . tid = unsafeDeserialize' (serialize' vk)
null
https://raw.githubusercontent.com/input-output-hk/hydra/87eb24e2e29e8cd4c0060569d3d6ce45ded3be1f/hydra-node/test/Hydra/Model/MockChain.hs
haskell
NOTE: this is not used (yet) but could be used to trigger arbitrary rollbacks in the run model seconds direct knowlege of the cardano keys which are stored only at the `ChainComponent` level. NOTE: The wallet basically does nothing
# LANGUAGE RecordWildCards # module Hydra.Model.MockChain where import Hydra.Cardano.Api import Hydra.Prelude hiding (Any, label) import Cardano.Binary (serialize', unsafeDeserialize') import Cardano.Ledger.Alonzo.TxSeq (TxSeq (TxSeq)) import qualified Cardano.Ledger.Babbage.Tx as Ledger import qualified Cardano.Ledger.Shelley.API as Ledger import Control.Monad.Class.MonadAsync (Async, async) import Control.Monad.Class.MonadFork (labelThisThread) import Control.Monad.Class.MonadSTM ( MonadLabelledSTM, labelTQueueIO, modifyTVar, newTQueueIO, readTVarIO, tryReadTQueue, writeTQueue, ) import qualified Data.Sequence.Strict as StrictSeq import Hydra.BehaviorSpec ( ConnectToChain (..), ) import Hydra.Chain (Chain (..)) import Hydra.Chain.Direct.Fixture (testNetworkId) import Hydra.Chain.Direct.Handlers (ChainSyncHandler, DirectChainLog, SubmitTx, chainSyncHandler, mkChain, onRollForward) import Hydra.Chain.Direct.ScriptRegistry (ScriptRegistry (..)) import Hydra.Chain.Direct.State (ChainContext (..), ChainStateAt (..)) import qualified Hydra.Chain.Direct.State as S import Hydra.Chain.Direct.TimeHandle (TimeHandle) import qualified Hydra.Chain.Direct.Util as Util import Hydra.Chain.Direct.Wallet (TinyWallet (..)) import Hydra.ContestationPeriod (ContestationPeriod) import Hydra.Crypto (HydraKey) import Hydra.HeadLogic ( Environment (Environment, otherParties, party), Event (NetworkEvent), HeadState (..), IdleState (..), defaultTTL, ) import Hydra.Ledger.Cardano (genTxIn) import Hydra.Logging (Tracer) import Hydra.Model.Payment (CardanoSigningKey (..)) import Hydra.Network (Network (..)) import Hydra.Network.Message (Message) import Hydra.Node ( HydraNode (..), chainCallback, createNodeState, putEvent, ) import Hydra.Party (Party (..), deriveParty) import Ouroboros.Consensus.Cardano.Block (HardForkBlock (..)) import qualified Ouroboros.Consensus.Protocol.Praos.Header as Praos import Ouroboros.Consensus.Shelley.Ledger (mkShelleyBlock) import Test.Consensus.Cardano.Generators () | Provide the logic to connect a list of ` MockHydraNode ` through a dummy chain . mockChainAndNetwork :: forall m. ( MonadSTM m , MonadTimer m , MonadThrow m , MonadAsync m , MonadThrow (STM m) , MonadLabelledSTM m ) => Tracer m DirectChainLog -> [(SigningKey HydraKey, CardanoSigningKey)] -> TVar m [MockHydraNode m] -> ContestationPeriod -> m (ConnectToChain Tx m, Async m ()) mockChainAndNetwork tr seedKeys nodes cp = do queue <- newTQueueIO labelTQueueIO queue "chain-queue" tickThread <- async (labelThisThread "chain" >> simulateTicks queue) let chainComponent = \node -> do let Environment{party = ownParty, otherParties} = env node let (vkey, vkeys) = findOwnCardanoKey ownParty seedKeys let ctx = S.ChainContext { networkId = testNetworkId , peerVerificationKeys = vkeys , ownVerificationKey = vkey , ownParty , otherParties , scriptRegistry = TODO : we probably want different _ scripts _ as initial and commit one let txIn = mkMockTxIn vkey 0 txOut = TxOut (mkVkAddress testNetworkId vkey) (lovelaceToValue 10_000_000) TxOutDatumNone ReferenceScriptNone in ScriptRegistry { initialReference = (txIn, txOut) , commitReference = (txIn, txOut) , headReference = (txIn, txOut) } , contestationPeriod = cp } chainState = S.ChainStateAt { chainState = S.Idle , recordedAt = Nothing } let getTimeHandle = pure $ arbitrary `generateWith` 42 let seedInput = genTxIn `generateWith` 42 nodeState <- createNodeState $ Idle IdleState{chainState} let HydraNode{eq} = node let callback = chainCallback nodeState eq let chainHandler = chainSyncHandler tr callback getTimeHandle ctx let node' = node { hn = createMockNetwork node nodes , oc = createMockChain tr ctx (atomically . writeTQueue queue) getTimeHandle seedInput , nodeState } let mockNode = MockHydraNode{node = node', chainHandler} atomically $ modifyTVar nodes (mockNode :) pure node' rollbackAndForward = error "Not implemented, should never be called" return (ConnectToChain{..}, tickThread) where simulateTicks queue = forever $ do threadDelay blockTime hasTx <- atomically $ tryReadTQueue queue case hasTx of Just tx -> do let block = mkBlock tx allHandlers <- fmap chainHandler <$> readTVarIO nodes forM_ allHandlers (`onRollForward` block) Nothing -> pure () | Find Cardano vkey corresponding to our using signing keys lookup . This is a bit cumbersome and a tribute to the fact the ` HydraNode ` itself has no findOwnCardanoKey :: Party -> [(SigningKey HydraKey, CardanoSigningKey)] -> (VerificationKey PaymentKey, [VerificationKey PaymentKey]) findOwnCardanoKey me seedKeys = fromMaybe (error $ "cannot find cardano key for " <> show me <> " in " <> show seedKeys) $ do csk <- getVerificationKey . signingKey . snd <$> find ((== me) . deriveParty . fst) seedKeys pure (csk, filter (/= csk) $ map (getVerificationKey . signingKey . snd) seedKeys) mkBlock :: Ledger.ValidatedTx LedgerEra -> Util.Block mkBlock ledgerTx = let header = (arbitrary :: Gen (Praos.Header StandardCrypto)) `generateWith` 42 body = TxSeq . StrictSeq.fromList $ [ledgerTx] in BlockBabbage $ mkShelleyBlock $ Ledger.Block header body TODO : unify with BehaviorSpec 's ? createMockNetwork :: MonadSTM m => HydraNode Tx m -> TVar m [MockHydraNode m] -> Network m (Message Tx) createMockNetwork myNode nodes = Network{broadcast} where broadcast msg = do allNodes <- fmap node <$> readTVarIO nodes let otherNodes = filter (\n -> getNodeId n /= getNodeId myNode) allNodes mapM_ (`handleMessage` msg) otherNodes handleMessage HydraNode{eq} = putEvent eq . NetworkEvent defaultTTL getNodeId = party . env data MockHydraNode m = MockHydraNode { node :: HydraNode Tx m , chainHandler :: ChainSyncHandler m } createMockChain :: (MonadTimer m, MonadThrow (STM m)) => Tracer m DirectChainLog -> ChainContext -> SubmitTx m -> m TimeHandle -> TxIn -> Chain Tx m createMockChain tracer ctx submitTx timeHandle seedInput = let wallet = TinyWallet { getUTxO = pure mempty , getSeedInput = pure (Just seedInput) , sign = id , coverFee = \_ tx -> pure (Right tx) , reset = pure () , update = const $ pure () } in mkChain tracer timeHandle wallet ctx submitTx mkMockTxIn :: VerificationKey PaymentKey -> Word -> TxIn mkMockTxIn vk ix = TxIn (TxId tid) (TxIx ix) where NOTE : Ugly , works because both binary representations are 32 - byte long . tid = unsafeDeserialize' (serialize' vk)
6e5eb6ad4f1f349896455df3923bdffab0e54d17c02a5c3fa75e19ee55b4a42a
haskell-opengl/OpenGLRaw
VertexArrayObject.hs
# LANGUAGE PatternSynonyms # -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.VertexArrayObject Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : < > -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.VertexArrayObject ( -- * Extension Support glGetARBVertexArrayObject, gl_ARB_vertex_array_object, -- * Enums pattern GL_VERTEX_ARRAY_BINDING, -- * Functions glBindVertexArray, glDeleteVertexArrays, glGenVertexArrays, glIsVertexArray ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
null
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/ARB/VertexArrayObject.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.GL.ARB.VertexArrayObject License : BSD3 Stability : stable Portability : portable ------------------------------------------------------------------------------ * Extension Support * Enums * Functions
# LANGUAGE PatternSynonyms # Copyright : ( c ) 2019 Maintainer : < > module Graphics.GL.ARB.VertexArrayObject ( glGetARBVertexArrayObject, gl_ARB_vertex_array_object, pattern GL_VERTEX_ARRAY_BINDING, glBindVertexArray, glDeleteVertexArrays, glGenVertexArrays, glIsVertexArray ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
587016de2a166426209440b77e0848ef10995822df9fda1b3cc5753f3d902091
hammerlab/prohlatype
mpjson2tsv.ml
open Prohlatype open Cmdline_options let app_name = "mpjson2tsv" let f_of_yojson = ParPHMM_drivers.(Output.of_yojson Multiple_loci.final_read_info_of_yojson) let of_json_file f = Yojson.Safe.stream_from_file f only one element per file . |> f_of_yojson |> unwrap let convert output_opt json_file = let open ParPHMM_drivers in let f = of_json_file json_file in let output_filename = Option.value output_opt ~default:((Filename.remove_extension json_file) ^ ".tsv") in let oc = open_out output_filename in let out_to_string rrp = sprintf "\n%s" (Multiple_loci.final_read_info_to_string rrp) in Output.f oc f Output.default_depth (Output.TabSeparated out_to_string); close_out oc let () = let open Cmdliner in let output_fname_arg = let docv = "FILE" in let doc = "Output file name, defaults to \"(input file).tsv\"." in Arg.(value & opt (some string) None & info ~doc ~docv ["o"; "output"] ) in let input_fname_arg = let docv = "FILE" in let doc = "Input json filename." in Arg.(required & pos 0 (some file) None & info ~doc ~docv [] ) in let convert = let doc = "Transform multi_par's or par_type's json output to a Tab Separated File.\ \ JSON provides a compact and machine useful format for communicating HLA \ typing results. Unfortunately, it is not as useful for human \ interpretation. This utility converts output as generated with the \ \"-json\" flag into Tab Separated format." in let bugs = sprintf "Browse and report new issues at <>" repo in let man = [ `S "AUTHORS" ; `P "Leonid Rozenberg <>" ; `Noblank ; `S "BUGS" ; `P bugs ] in Term.(const convert $ output_fname_arg $ input_fname_arg , info app_name ~version ~doc ~man) in match Term.eval convert with | `Ok () -> exit 0 | `Error _ -> failwith "Is this JSON input?" | `Version | `Help -> exit 0
null
https://raw.githubusercontent.com/hammerlab/prohlatype/3acaf7154f93675fc729971d4c76c2b133e90ce6/src/app/mpjson2tsv.ml
ocaml
open Prohlatype open Cmdline_options let app_name = "mpjson2tsv" let f_of_yojson = ParPHMM_drivers.(Output.of_yojson Multiple_loci.final_read_info_of_yojson) let of_json_file f = Yojson.Safe.stream_from_file f only one element per file . |> f_of_yojson |> unwrap let convert output_opt json_file = let open ParPHMM_drivers in let f = of_json_file json_file in let output_filename = Option.value output_opt ~default:((Filename.remove_extension json_file) ^ ".tsv") in let oc = open_out output_filename in let out_to_string rrp = sprintf "\n%s" (Multiple_loci.final_read_info_to_string rrp) in Output.f oc f Output.default_depth (Output.TabSeparated out_to_string); close_out oc let () = let open Cmdliner in let output_fname_arg = let docv = "FILE" in let doc = "Output file name, defaults to \"(input file).tsv\"." in Arg.(value & opt (some string) None & info ~doc ~docv ["o"; "output"] ) in let input_fname_arg = let docv = "FILE" in let doc = "Input json filename." in Arg.(required & pos 0 (some file) None & info ~doc ~docv [] ) in let convert = let doc = "Transform multi_par's or par_type's json output to a Tab Separated File.\ \ JSON provides a compact and machine useful format for communicating HLA \ typing results. Unfortunately, it is not as useful for human \ interpretation. This utility converts output as generated with the \ \"-json\" flag into Tab Separated format." in let bugs = sprintf "Browse and report new issues at <>" repo in let man = [ `S "AUTHORS" ; `P "Leonid Rozenberg <>" ; `Noblank ; `S "BUGS" ; `P bugs ] in Term.(const convert $ output_fname_arg $ input_fname_arg , info app_name ~version ~doc ~man) in match Term.eval convert with | `Ok () -> exit 0 | `Error _ -> failwith "Is this JSON input?" | `Version | `Help -> exit 0
96a7353547c5268a2b72e4643162cf5233d287e9fdf21ed9d60beb63ed96fd63
patzy/glaw
texture.lisp
(in-package #:glaw-examples) (defstruct texture view image (start-red 0) texture sprites) (defmethod init-example ((it texture)) (setf (texture-image it) (glaw::create-image 256 256 4) (texture-texture it) (glaw:create-texture-from-image (texture-image it)) (texture-view it) (glaw:create-2d-view 0 0 glaw:*display-width* glaw:*display-height*)) (loop for i from 0 to 10 do (push (glaw:create-sprite (float (random glaw:*display-width*)) (float (random glaw:*display-height*)) (+ 100.0 (random 100.0)) (+ 100.0 (random 100.0)) (texture-texture it)) (texture-sprites it)))) (defmethod shutdown-example ((it texture)) (declare (ignore it))) (defmethod render-example ((it texture)) (glaw:set-view-2d (texture-view it)) (dolist (sp (texture-sprites it)) (glaw:render-sprite sp))) (defmethod update-example ((it texture) dt) (let ((r (texture-start-red it)) (g 255) (b 255)) (loop for x below 256 do (loop for y below 256 do (glaw::image-set-pixel (texture-image it) x y r r r 255)) (setf r (mod (incf r) 255)))) (glaw::update-texture (texture-texture it) (glaw::image-data (texture-image it))) (setf (texture-start-red it) (mod (incf (texture-start-red it)) 255))) (defmethod reshape-example ((it texture) w h) (glaw:update-2d-view (texture-view it) 0 0 w h))
null
https://raw.githubusercontent.com/patzy/glaw/e678fc0c107ce4b1e3ff9921a6de7e32fd39bc37/examples/texture.lisp
lisp
(in-package #:glaw-examples) (defstruct texture view image (start-red 0) texture sprites) (defmethod init-example ((it texture)) (setf (texture-image it) (glaw::create-image 256 256 4) (texture-texture it) (glaw:create-texture-from-image (texture-image it)) (texture-view it) (glaw:create-2d-view 0 0 glaw:*display-width* glaw:*display-height*)) (loop for i from 0 to 10 do (push (glaw:create-sprite (float (random glaw:*display-width*)) (float (random glaw:*display-height*)) (+ 100.0 (random 100.0)) (+ 100.0 (random 100.0)) (texture-texture it)) (texture-sprites it)))) (defmethod shutdown-example ((it texture)) (declare (ignore it))) (defmethod render-example ((it texture)) (glaw:set-view-2d (texture-view it)) (dolist (sp (texture-sprites it)) (glaw:render-sprite sp))) (defmethod update-example ((it texture) dt) (let ((r (texture-start-red it)) (g 255) (b 255)) (loop for x below 256 do (loop for y below 256 do (glaw::image-set-pixel (texture-image it) x y r r r 255)) (setf r (mod (incf r) 255)))) (glaw::update-texture (texture-texture it) (glaw::image-data (texture-image it))) (setf (texture-start-red it) (mod (incf (texture-start-red it)) 255))) (defmethod reshape-example ((it texture) w h) (glaw:update-2d-view (texture-view it) 0 0 w h))
61ca9d6665b03563673fc3d4bd8282c7f336eaee19c8409a1bfd0cbc89584140
futurice/haskell-mega-repo
AWS.hs
{-# LANGUAGE OverloadedStrings #-} module Futurice.App.Sisosota.AWS where import Futurice.Prelude import Prelude () import Data.Conduit.Binary (sinkLbs) import qualified Codec.Compression.Lzma as LZMA import qualified Control.Monad.Trans.AWS as AWS import qualified Data.HashMap.Strict as HM import qualified Network.AWS.S3.GetObject as AWS import qualified Network.AWS.S3.PutObject as AWS import qualified Network.AWS.S3.Types as AWS import Futurice.App.Sisosota.Types awsUpload :: AWS.Env -> AWS.BucketName ^ optional filepath -> Maybe Text -- ^ optional mime type -> ContentData -- ^ content data -> IO ContentHash awsUpload env bucketName mfp mct (ContentData lbs) = AWS.runResourceT $ AWS.runAWST env $ do _ <- AWS.send $ AWS.putObject bucketName objectKey (AWS.toBody (LZMA.compress lbs)) & AWS.poContentType .~ mct & AWS.poMetadata .~ metadata -- & AWS.poContentEncoding ?~ "lzma" return ch where ch = contentHashLBS lbs objectKey = AWS.ObjectKey $ contentHashToText ch metadata = HM.fromList [ ("original-filename" :: Text, fp ^. packed) | Just fp <- [ mfp ] ] awsDownload :: AWS.Env -> AWS.BucketName -> ContentHash -> IO (Either String ContentData) awsDownload env bucketName ch = AWS.runResourceT $ AWS.runAWST env $ do r <- AWS.trying AWS._ServiceError $ AWS.send $ AWS.getObject bucketName objectKey case r of Left err -> return $ Left $ "getObject: " ++ show err Right r' -> do lbs <- AWS.sinkBody (r' ^. AWS.gorsBody) sinkLbs return (Right (ContentData (LZMA.decompress lbs))) where objectKey = AWS.ObjectKey $ contentHashToText ch
null
https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/sisosota-client/src/Futurice/App/Sisosota/AWS.hs
haskell
# LANGUAGE OverloadedStrings # ^ optional mime type ^ content data & AWS.poContentEncoding ?~ "lzma"
module Futurice.App.Sisosota.AWS where import Futurice.Prelude import Prelude () import Data.Conduit.Binary (sinkLbs) import qualified Codec.Compression.Lzma as LZMA import qualified Control.Monad.Trans.AWS as AWS import qualified Data.HashMap.Strict as HM import qualified Network.AWS.S3.GetObject as AWS import qualified Network.AWS.S3.PutObject as AWS import qualified Network.AWS.S3.Types as AWS import Futurice.App.Sisosota.Types awsUpload :: AWS.Env -> AWS.BucketName ^ optional filepath -> IO ContentHash awsUpload env bucketName mfp mct (ContentData lbs) = AWS.runResourceT $ AWS.runAWST env $ do _ <- AWS.send $ AWS.putObject bucketName objectKey (AWS.toBody (LZMA.compress lbs)) & AWS.poContentType .~ mct & AWS.poMetadata .~ metadata return ch where ch = contentHashLBS lbs objectKey = AWS.ObjectKey $ contentHashToText ch metadata = HM.fromList [ ("original-filename" :: Text, fp ^. packed) | Just fp <- [ mfp ] ] awsDownload :: AWS.Env -> AWS.BucketName -> ContentHash -> IO (Either String ContentData) awsDownload env bucketName ch = AWS.runResourceT $ AWS.runAWST env $ do r <- AWS.trying AWS._ServiceError $ AWS.send $ AWS.getObject bucketName objectKey case r of Left err -> return $ Left $ "getObject: " ++ show err Right r' -> do lbs <- AWS.sinkBody (r' ^. AWS.gorsBody) sinkLbs return (Right (ContentData (LZMA.decompress lbs))) where objectKey = AWS.ObjectKey $ contentHashToText ch
f8e96f7d21ed75be99445b0c6e15a3eafa68bd6eb5a2dd16147a3056165d8702
xclerc/ocamljava
bytecodegen_prim.ml
* This file is part of compiler . * Copyright ( C ) 2007 - 2015 . * * compiler is free software ; you can redistribute it and/or modify * it under the terms of the Q Public License as published by * ( with a change to choice of law ) . * * compiler 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 * Q Public License for more details . * * You should have received a copy of the Q Public License * along with this program . If not , see * < -1.0 > . * This file is part of OCaml-Java compiler. * Copyright (C) 2007-2015 Xavier Clerc. * * OCaml-Java compiler is free software; you can redistribute it and/or modify * it under the terms of the Q Public License as published by * Trolltech (with a change to choice of law). * * OCaml-Java compiler 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 * Q Public License for more details. * * You should have received a copy of the Q Public License * along with this program. If not, see * <-1.0>. *) open Asttypes open Lambda open Macroinstr open Bytecodeutils open Bytecodegen_misc open BaristaLibrary let node x = Instrtree.node x let leaf x = Instrtree.leaf x let size x = Instrtree.size x let with_size x = x, size x let inline_simple_arithmetic () = !Clflags.inline_threshold >= 100 let get_global id = if ((State.current_function ()) = "entry") && ((State.current_module ()) = (Ident.name id)) then begin make_class (Jcompilenv.current_global_class_name ()), leaf [ Instruction.ALOAD_0 ] end else begin try let classname = Jcompilenv.class_for_global id in let glob_classname = make_class (classname ^ "$Global") in let classname = make_class classname in glob_classname, node [ leaf [ Instruction.GETSTATIC (classname, make_field "GLOBALS", `Class class_ThreadLocal) ] ; meth_get_threadlocal ; leaf [ Instruction.CHECKCAST (`Class_or_interface glob_classname) ] ] with _ -> make_class "dummy_class", node [ leaf [ Instruction.LDC_W (`String (UTF8.of_string (Ident.name id))) ]; meth_getGlobal ] end let optimized_get_global id idx = (match Jcompilenv.global_approx_no_dep id with | Jlambda.Value_tuple app when idx < Array.length app -> true | Jlambda.Value_tuple _ -> false | _ ->false) && (try ignore (Jcompilenv.class_for_global id); true with _ -> false) let descriptor_of_approx = function | Jlambda.Value_closure _ -> `Class class_Value | Jlambda.Value_tuple _ -> `Class class_Value | Jlambda.Value_unknown None -> `Class class_Value | Jlambda.Value_unknown (Some repr) -> begin match repr with | LR_value | LR_string | LR_exn | LR_array _ | LR_list _ | LR_option _ | LR_lazy _ | LR_unit -> `Class class_Value | LR_int | LR_char | LR_bool -> `Long | LR_float -> `Double | LR_nativeint -> `Long | LR_int32 -> `Int | LR_int64 -> `Long | LR_java_instance cn | LR_java_extends cn -> `Class (make_class cn) | (LR_java_boolean_array | LR_java_byte_array | LR_java_char_array | LR_java_double_array | LR_java_float_array | LR_java_int_array | LR_java_long_array | LR_java_reference_array _ | LR_java_short_array) as arr -> let arr = array_type_of_repr arr in (Jlambda.unconvert_array_type arr :> Descriptor.for_field) | LR_none -> assert false end | Jlambda.Value_integer _ -> `Long | Jlambda.Value_integer32 _ -> `Int | Jlambda.Value_integer64 _ -> `Long | Jlambda.Value_integernat _ -> `Long | Jlambda.Value_constptr _ -> `Long | Jlambda.Value_float _ -> `Double | Jlambda.Value_java_null None -> `Class class_Object | Jlambda.Value_java_null (Some jt) -> begin match jt with | `Class cn -> `Class (make_class cn) | (`Array _) as arr -> (Jlambda.unconvert_array_type arr :> Descriptor.for_field) | `Long | `Float | `Byte | `Char | `Boolean | `Int | `Short | `Double -> assert false end | Jlambda.Value_java_string _ -> `Class class_String let rec compile_primitive ofs prim prim_args compile_expression_list compile_expression = let if_size = 3 in let goto_size = 3 in let lconst_size = 1 in let meth_size = 3 in let after_args_instrs l = node [ compile_expression_list ofs prim_args ; leaf l ] in let after_args_tree t = node [ compile_expression_list ofs prim_args ; t ] in let string_meth load meth = let params = if load then [`Class class_Value; `Class class_Value] else [`Class class_Value; `Class class_Value; `Class class_Value] in after_args_instrs [ Instruction.INVOKESTATIC (make_class "org.ocamljava.runtime.primitives.stdlib.Str", make_method meth, (params, `Class class_Value)) ] in let bigstring_meth load meth = let params = if load then [`Class class_Value; `Class class_Value] else [`Class class_Value; `Class class_Value; `Class class_Value] in after_args_instrs [ Instruction.INVOKESTATIC (make_class "org.ocamljava.runtime.primitives.otherlibs.bigarray.BigArray", make_method meth, (params, `Class class_Value)) ] in let fatal_error s = Misc.fatal_error ("Bytecodegen_prim.compile_primitive: " ^ s) in match prim, prim_args with | Pidentity, _ -> fatal_error "Pidentity" | Pignore, [arg] -> compile_expression false ofs arg | Pignore, _ -> assert false | Prevapply _, _ -> fatal_error "Prevapply" | Pdirapply _, _ -> fatal_error "Pdirapply" | Pgetglobal id, _ -> let field_name = match Ident.name id with | "caml_exn_Out_of_memory" -> Some "exnOutOfMemory" | "caml_exn_Sys_error" -> Some "exnSysError" | "caml_exn_Failure" -> Some "exnFailure" | "caml_exn_Invalid_argument" -> Some "exnInvalidArgument" | "caml_exn_End_of_file" -> Some "exnEndOfFile" | "caml_exn_Division_by_zero" -> Some "exnDivisionByZero" | "caml_exn_Not_found" -> Some "exnNotFound" | "caml_exn_Match_failure" -> Some "exnMatchFailure" | "caml_exn_Stack_overflow" -> Some "exnStackOverflow" | "caml_exn_Sys_blocked_io" -> Some "exnSysBlockedIO" | "caml_exn_Assert_failure" -> Some "exnAssertFailure" | "caml_exn_Undefined_recursive_module" -> Some "exnUndefinedRecursiveModule" | "caml_exn_Java_exception" -> Some "exnJavaException" | "caml_exn_Java_error" -> Some "exnJavaError" | _ -> None in begin match field_name with | None -> snd (get_global id) | Some fn -> node [ meth_getPredefinedExceptions ; leaf [ Instruction.GETFIELD (class_PredefinedExceptions, make_field fn, `Class class_Value) ] ] end | Psetglobal id, _ -> begin try let cls = Jcompilenv.class_for_global id in after_args_tree (node [ leaf [ Instruction.GETSTATIC (make_class cls, make_field "GLOBALS", `Class class_ThreadLocal) ; Instruction.SWAP ] ; meth_set_threadlocal ]) with _ -> after_args_tree (node [ leaf [ Instruction.LDC_W (`String (UTF8.of_string (Ident.name id))); ]; meth_setGlobal ]) end | Pmakeblock (tag, mut), args -> compile_block (Int32.of_int tag) mut ofs args compile_expression_list compile_expression | Pfield idx, [Mprim (Pgetglobal id, _, _)] when (optimized_get_global id idx) -> begin match Jcompilenv.global_approx_no_dep id with | Jlambda.Value_tuple approx -> let glob_classname, get_global_instrs = get_global id in let fieldname = make_field (Printf.sprintf "field_%d" idx) in let desc = descriptor_of_approx approx.(idx) in node [ get_global_instrs ; leaf [ Instruction.GETFIELD (glob_classname, fieldname, desc) ] ] | _ -> assert false end | Pfield n, [arg] -> node [ compile_expression false ofs arg ; (match n with | 0 -> meth_get0 | 1 -> meth_get1 | 2 -> meth_get2 | 3 -> meth_get3 | 4 -> meth_get4 | 5 -> meth_get5 | 6 -> meth_get6 | 7 -> meth_get7 | _ -> if is_int32 n then node [ push_int32 (Int32.of_int n); meth_get'int ] else node [ push_int n; meth_get ]) ] | Pfield _, _ -> assert false | Psetfield (idx, _), [Mprim (Pgetglobal id, _, _); arg] when (optimized_get_global id idx) -> begin match Jcompilenv.global_approx_no_dep id with | Jlambda.Value_tuple approx -> let glob_classname, get_global_instrs = get_global id in let fieldname = make_field (Printf.sprintf "field_%d" idx) in let desc = descriptor_of_approx approx.(idx) in let arg_instrs = compile_expression false (ofs + 3 + meth_size) arg in node [ get_global_instrs ; arg_instrs ; leaf [ Instruction.PUTFIELD (glob_classname, fieldname, desc) ] ; field_Value_UNIT ] | _ -> assert false end | Psetfield (n, _), [arg1; arg2] -> let arg1_instrs, arg1_sz = with_size (compile_expression false ofs arg1) in let idx_instrs, idx_sz = with_size (if n < 8 then leaf [] else if is_int32 n then push_int32 (Int32.of_int n) else push_int n) in let arg2_instrs = compile_expression false (ofs + arg1_sz + idx_sz) arg2 in node [ arg1_instrs ; idx_instrs ; arg2_instrs ; (match n with | 0 -> meth_set0 | 1 -> meth_set1 | 2 -> meth_set2 | 3 -> meth_set3 | 4 -> meth_set4 | 5 -> meth_set5 | 6 -> meth_set6 | 7 -> meth_set7 | _ -> if is_int32 n then meth_set'int else meth_set) ; field_Value_UNIT ] | Psetfield _, _ -> assert false | Pfloatfield n, [arg] -> node [ compile_expression false ofs arg ; (match n with | 0 -> meth_getGenericDouble0 | 1 -> meth_getGenericDouble1 | 2 -> meth_getGenericDouble2 | 3 -> meth_getGenericDouble3 | 4 -> meth_getGenericDouble4 | 5 -> meth_getGenericDouble5 | 6 -> meth_getGenericDouble6 | 7 -> meth_getGenericDouble7 | _ -> if is_int32 n then node [ push_int32 (Int32.of_int n); meth_getGenericDouble'int ] else node [ push_int n; meth_getGenericDouble ]) ] | Pfloatfield _, _ -> assert false | Psetfloatfield n, [arg1; arg2] -> let arg1_instrs, arg1_sz = with_size (compile_expression false ofs arg1) in let idx_instrs, idx_sz = with_size (if n < 8 then leaf [] else if is_int32 n then push_int32 (Int32.of_int n) else push_int n) in let arg2_instrs = compile_expression false (ofs + arg1_sz + idx_sz) arg2 in node [ arg1_instrs ; idx_instrs ; arg2_instrs ; (match n with | 0 -> meth_setGenericDouble0 | 1 -> meth_setGenericDouble1 | 2 -> meth_setGenericDouble2 | 3 -> meth_setGenericDouble3 | 4 -> meth_setGenericDouble4 | 5 -> meth_setGenericDouble5 | 6 -> meth_setGenericDouble6 | 7 -> meth_setGenericDouble7 | _ -> if is_int32 n then meth_setGenericDouble'int else meth_setGenericDouble) ; field_Value_UNIT ] | Psetfloatfield _, _ -> assert false | Pduprecord _, _ -> fatal_error "Pduprecord" | Plazyforce, _ -> fatal_error "Plazyforce" | Pccall prim, _ -> let name = prim.Primitive.prim_name in if Macrogen_primitives.is_unary_math_primitive name then after_args_instrs [ Instruction.INVOKESTATIC (make_class "java.lang.Math", make_method (Macrogen_primitives.unary_method name), ([`Double], `Double)) ] else if Macrogen_primitives.is_binary_math_primitive name then after_args_instrs [ Instruction.INVOKESTATIC (make_class "java.lang.Math", make_method (Macrogen_primitives.binary_method name), ([`Double; `Double], `Double)) ] else begin let desc = Runtimeprimitives.get_description name in after_args_tree (node [ (if desc.Runtimeprimitives.primdesc_parameters = [] then leaf [ Instruction.POP ] else leaf []) ; leaf [ Instruction.INVOKESTATIC (make_class desc.Runtimeprimitives.primdesc_class, make_method desc.Runtimeprimitives.primdesc_method, desc.Runtimeprimitives.primdesc_javadesc) ] ; (if desc.Runtimeprimitives.primdesc_return = LR_none then field_Value_UNIT else leaf []) ]) end | Praise, [arg] -> node [ compile_expression false ofs arg ; meth_raise; field_Value_UNIT ] | Praise, _ -> assert false | Psequand, _ -> assert false | Psequor, _ -> assert false | Pnot, [arg] -> node [ compile_expression false ofs arg ; leaf [ Instruction.L2I ; Instruction.IFEQ (Utils.s2 (if_size + lconst_size + goto_size)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] ] | Pnot, _ -> assert false | Pnegint, _ -> after_args_tree meth_negint | Paddint, [arg; Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int 1))))] | Paddint, [Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int 1)))); arg] | Paddint, [arg; Mconst (Jlambda.Lambda_const (Const_base (Const_int 1)))] | Paddint, [Mconst (Jlambda.Lambda_const (Const_base (Const_int 1))); arg] -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LDC2_W (`Long 2L); Instruction.LADD ] ] else node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LCONST_1 ; Instruction.LADD ] ] else node [ compile_expression_list ofs [arg] ; meth_incrint ] | Paddint, [arg; Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1)))))] | Paddint, [Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1))))); arg] | Paddint, [arg; Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1))))] | Paddint, [Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1)))); arg] -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LDC2_W (`Long 2L); Instruction.LSUB ] ] else node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LCONST_1 ; Instruction.LSUB ] ] else node [ compile_expression_list ofs [arg] ; meth_decrint ] | Paddint, _ -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then after_args_tree (leaf [ Instruction.LADD; Instruction.LCONST_1; Instruction.LSUB ]) else after_args_tree (leaf [ Instruction.LADD ]) else after_args_tree meth_addint | Psubint, [arg; Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int 1))))] | Psubint, [arg; Mconst (Jlambda.Lambda_const (Const_base (Const_int 1)))] -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LDC2_W (`Long 2L); Instruction.LSUB ] ] else node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LCONST_1 ; Instruction.LSUB ] ] else node [ compile_expression_list ofs [arg] ; meth_decrint ] | Psubint, [arg; Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1)))))] | Psubint, [arg; Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1))))] -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LDC2_W (`Long 2L); Instruction.LADD ] ] else node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LCONST_1 ; Instruction.LADD ] ] else node [ compile_expression_list ofs [arg] ; meth_incrint ] | Psubint, _ -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then after_args_tree (leaf [ Instruction.LSUB; Instruction.LCONST_1; Instruction.LADD ]) else after_args_tree (leaf [ Instruction.LSUB ]) else after_args_tree meth_subint | Pmulint, _ -> after_args_tree meth_mulint | Pdivint, _ -> after_args_tree meth_divint | Pmodint, _ -> after_args_tree meth_modint | Pandint, _ -> after_args_instrs [ Instruction.LAND ] | Porint, _ -> after_args_instrs [ Instruction.LOR ] | Pxorint, _ -> if Jconfig.ints_are_63_bit_long then after_args_instrs [ Instruction.LXOR; Instruction.LCONST_1; Instruction.LOR ] else after_args_instrs [ Instruction.LXOR ] | Plslint, _ -> after_args_tree meth_lslint | Plsrint, _ -> after_args_tree meth_lsrint | Pasrint, _ -> after_args_tree meth_asrint | Pintcomp cmp, [arg0; arg1; arg2] -> begin match arg0 with | Mconst (Jlambda.Lambda_const (Const_base (Const_int 1))) (* tagged values *) | Mconst (Jlambda.Lambda_const (Const_base (Const_int 2))) (* normalized values *) | Mconst (Jlambda.Lambda_const (Const_base (Const_int 3))) -> (* unboxed values *) let jump_ofs = if_size + lconst_size + goto_size in node [ compile_expression_list ofs [arg1; arg2] ; leaf [ Instruction.LCMP ; (match cmp with | Ceq -> Instruction.IFEQ (Utils.s2 jump_ofs) | Cneq -> Instruction.IFNE (Utils.s2 jump_ofs) | Clt -> Instruction.IFLT (Utils.s2 jump_ofs) | Cgt -> Instruction.IFGT (Utils.s2 jump_ofs) | Cle -> Instruction.IFLE (Utils.s2 jump_ofs) | Cge -> Instruction.IFGE (Utils.s2 jump_ofs)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] ] | _ -> (* boxed values *) node [ compile_expression_list ofs [arg1; arg2] ; (match cmp with | Ceq -> meth_equalValues | Cneq -> meth_notEqualValues | Clt -> meth_lowerThanValue | Cgt -> meth_greaterThanValue | Cle -> meth_lowerEqualValue | Cge -> meth_greaterEqualValue) ; leaf [ Instruction.I2L ] ] end | Pintcomp _, _ -> assert false | Poffsetint 1, _ -> after_args_tree (node [ meth_incrint ]) | Poffsetint (-1), _ -> after_args_tree (node [ meth_decrint ]) | Poffsetint n, _ -> if Jconfig.ints_are_63_bit_long then after_args_tree (node [ push_int ((n lsl 1) lor 1); meth_offsetint ]) else after_args_tree (node [ push_int n; meth_offsetint ]) | Poffsetref n, _ -> after_args_tree (node [ push_int (n * 2); meth_offsetref; field_Value_UNIT ]) | Pintoffloat, _ -> after_args_instrs [ Instruction.D2L ] | Pfloatofint, _ -> after_args_instrs [ Instruction.L2D ] | Pnegfloat, _ -> after_args_instrs [ Instruction.DNEG ] | Pabsfloat, _ -> after_args_tree meth_abs | Paddfloat, _ -> after_args_instrs [ Instruction.DADD ] | Psubfloat, _ -> after_args_instrs [ Instruction.DSUB ] | Pmulfloat, _ -> after_args_instrs [ Instruction.DMUL ] | Pdivfloat, _ -> after_args_instrs [ Instruction.DDIV ] | Pfloatcomp cmp, _ -> let jump_ofs = if_size + lconst_size + goto_size in after_args_instrs [ Instruction.DCMPG ; (match cmp with | Ceq -> Instruction.IFEQ (Utils.s2 jump_ofs) | Cneq -> Instruction.IFNE (Utils.s2 jump_ofs) | Clt -> Instruction.IFLT (Utils.s2 jump_ofs) | Cgt -> Instruction.IFGT (Utils.s2 jump_ofs) | Cle -> Instruction.IFLE (Utils.s2 jump_ofs) | Cge -> Instruction.IFGE (Utils.s2 jump_ofs)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] | Pstringlength, _ -> after_args_tree meth_sizeBytes; | Pstringrefu, _ -> after_args_tree (node [ meth_getUnsignedByte; leaf [ Instruction.I2L ] ]); | Pstringsetu, _ -> after_args_tree (node [ leaf [ Instruction.L2I ] ; meth_setUnsignedByte ; field_Value_UNIT ]) | Pstringrefs, _ -> after_args_tree meth_caml_string_get | Pstringsets, _ -> after_args_tree meth_caml_string_set | Pmakearray _, [] -> Bytecodegen_constants.push_structured_constant (Const_block (0, [])) | Pmakearray kind, args -> (match kind with | Paddrarray -> compile_block 0l Mutable ofs args compile_expression_list compile_expression | Pintarray -> let longs n = let rec lng acc = function | 0 -> (`Int :: acc, (`Class class_Value)) | n -> lng (`Long :: acc) (pred n) in lng [] n in let args_size = List.length args in if args_size <= 8 then node [ leaf [ Instruction.ICONST_0 ] ; compile_long_expression_list (succ ofs) args compile_expression ; leaf [ Instruction.INVOKESTATIC (class_Value, make_method "createLongBlock", longs args_size) ] ] else let dup_size = 1 in let alloc_instr, alloc_sz = with_size (node [ leaf [ Instruction.ICONST_0 ] ; push_int args_size ; meth_createLongBlockFromSize ]) in let _, _, set_instrs = List.fold_left (fun (idx, ofs, acc) elem -> let idx_instr, idx_sz = with_size (push_int idx) in let instrs = node [ leaf [ Instruction.DUP ] ; idx_instr ; compile_expression false (ofs + dup_size + idx_sz) elem ; meth_setRawLong ] in (succ idx, ofs + (size instrs), instrs :: acc)) (0, ofs + alloc_sz, []) args in node [ alloc_instr ; node (List.rev set_instrs) ] | Pfloatarray -> let doubles n = let rec dbl acc = function | 0 -> (acc, (`Class class_Value)) | n -> dbl (`Double :: acc) (pred n) in dbl [] n in let args_size = List.length args in if args_size <= 8 then node [ compile_double_expression_list ofs args compile_expression ; leaf [ Instruction.INVOKESTATIC (class_Value, make_method "createDoubleArray", doubles args_size) ] ] else let dup_size = 1 in let alloc_instr, alloc_sz = with_size (node [ push_int args_size ; meth_createDoubleArray ]) in let _, _, set_instrs = List.fold_left (fun (idx, ofs, acc) elem -> let idx_instr, idx_sz = with_size (push_int idx) in let instrs = node [ leaf [ Instruction.DUP ] ; idx_instr ; compile_expression false (ofs + dup_size + idx_sz) elem ; meth_setDouble ] in (succ idx, ofs + (size instrs), instrs :: acc)) (0, ofs + alloc_sz, []) args in node [ alloc_instr ; node (List.rev set_instrs) ] | Pgenarray -> node [ compile_block 0l Mutable ofs args compile_expression_list compile_expression ; meth_caml_make_array ]) | Parraylength _, _ -> after_args_tree meth_arrayLength | Parrayrefu Paddrarray, [Mconst (Jlambda.Lambda_const (Const_base (Const_int idx)))] when (is_int32 idx) -> node [ push_int32 (Int32.of_int idx) ; meth_get'int ] | Parrayrefu kind, _ -> after_args_tree (match kind with | Pgenarray -> meth_caml_array_unsafe_get | Pfloatarray -> meth_getDouble | Pintarray -> meth_getRawLong | Paddrarray -> meth_get) | Parraysetu kind, _ -> after_args_tree (match kind with | Pgenarray -> meth_caml_array_unsafe_set | Pfloatarray -> node [ meth_setDouble ; field_Value_UNIT ] | Pintarray -> node [ meth_setRawLong ; field_Value_UNIT ] | Paddrarray -> node [ meth_set ; field_Value_UNIT ]) | Parrayrefs kind, _ -> after_args_tree (match kind with | Pgenarray -> meth_caml_array_get | Pfloatarray -> meth_caml_array_get_float | Pintarray -> meth_caml_array_get_int | Paddrarray -> meth_caml_array_get_addr) | Parraysets kind, _ -> after_args_tree (match kind with | Pgenarray -> meth_caml_array_set | Pfloatarray -> meth_caml_array_set_float | Pintarray -> meth_caml_array_set_int | Paddrarray -> meth_caml_array_set_addr) | Pisint, _ -> after_args_tree (node [ meth_isLong ; leaf [ Instruction.I2L ] ]) | Pisout, [arg0; arg1] -> let can_be_represented_int x = (x lsr 62) = 0 in let can_be_represented_target_int x = (Targetint.compare (Targetint.shift_right_logical x (Targetint.of_int 62)) Targetint.zero) = 0 in let meth = match arg0, arg1 with | Mconst (Jlambda.Lambda_const (Const_base (Const_int x))), _ | Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int x)))), _ when can_be_represented_int x -> meth_isOutFirstPositive | Mconst (Jlambda.Const_targetint x), _ | Mconvert (_, _, Mconst (Jlambda.Const_targetint x)), _ when can_be_represented_target_int x -> meth_isOutFirstPositive | _, Mconst (Jlambda.Lambda_const (Const_base (Const_int x))) | _, Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int x)))) when can_be_represented_int x -> meth_isOutSecondPositive | _, Mconst (Jlambda.Const_targetint x) | _, Mconvert (_, _, Mconst (Jlambda.Const_targetint x)) when can_be_represented_target_int x -> meth_isOutSecondPositive | _ -> meth_isOut in after_args_tree (node [ meth ; leaf [ Instruction.I2L ] ]) | Pisout, _ -> assert false | Pbittest, _ -> after_args_tree (node [ meth_bitvect_test; leaf [ Instruction.I2L ] ]) | Pbintofint bi, _ -> after_args_tree (compile_conversion int_kind (kind_of_boxed_integer bi)) | Pintofbint bi, _ -> after_args_tree (compile_conversion (kind_of_boxed_integer bi) int_kind) | Pcvtbint (src, dst), _ -> let src_kind = kind_of_boxed_integer src in let dst_kind = kind_of_boxed_integer dst in after_args_tree (compile_conversion src_kind dst_kind) | Pnegbint Pnativeint, _ -> after_args_instrs [ Instruction.LNEG ] | Pnegbint Pint32, _ -> after_args_instrs [ Instruction.INEG ] | Pnegbint Pint64, _ -> after_args_instrs [ Instruction.LNEG ] | Paddbint Pnativeint, _ -> after_args_instrs [ Instruction.LADD ] | Paddbint Pint32, _ -> after_args_instrs [ Instruction.IADD ] | Paddbint Pint64, _ -> after_args_instrs [ Instruction.LADD ] | Psubbint Pnativeint, _ -> after_args_instrs [ Instruction.LSUB ] | Psubbint Pint32, _ -> after_args_instrs [ Instruction.ISUB ] | Psubbint Pint64, _ -> after_args_instrs [ Instruction.LSUB ] | Pmulbint Pnativeint, _ -> after_args_instrs [ Instruction.LMUL ] | Pmulbint Pint32, _ -> after_args_instrs [ Instruction.IMUL ] | Pmulbint Pint64, _ -> after_args_instrs [ Instruction.LMUL ] | Pdivbint Pnativeint, _ -> after_args_tree meth_divint64 | Pdivbint Pint32, _ -> after_args_tree meth_divint32 | Pdivbint Pint64, _ -> after_args_tree meth_divint64 | Pmodbint Pnativeint, _ -> after_args_tree meth_modint64 | Pmodbint Pint32, _ -> after_args_tree meth_modint32 | Pmodbint Pint64, _ -> after_args_tree meth_modint64 | Pandbint Pnativeint, _ -> after_args_instrs [ Instruction.LAND ] | Pandbint Pint32, _ -> after_args_instrs [ Instruction.IAND ] | Pandbint Pint64, _ -> after_args_instrs [ Instruction.LAND ] | Porbint Pnativeint, _ -> after_args_instrs [ Instruction.LOR ] | Porbint Pint32, _ -> after_args_instrs [ Instruction.IOR ] | Porbint Pint64, _ -> after_args_instrs [ Instruction.LOR ] | Pxorbint Pnativeint, _ -> after_args_instrs [ Instruction.LXOR ] | Pxorbint Pint32, _ -> after_args_instrs [ Instruction.IXOR ] | Pxorbint Pint64, _ -> after_args_instrs [ Instruction.LXOR ] | Plslbint Pnativeint, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LSHL ] | Plslbint Pint32, _ -> after_args_instrs [ Instruction.L2I ; Instruction.ISHL ] | Plslbint Pint64, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LSHL ] | Plsrbint Pnativeint, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LUSHR ] | Plsrbint Pint32, _ -> after_args_instrs [ Instruction.L2I ; Instruction.IUSHR ] | Plsrbint Pint64, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LUSHR ] | Pasrbint Pnativeint, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LSHR ] | Pasrbint Pint32, _ -> after_args_instrs [ Instruction.L2I ; Instruction.ISHR ] | Pasrbint Pint64, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LSHR ] | Pbintcomp (Pint32, cmp), _ -> let jump_ofs = if_size + lconst_size + goto_size in after_args_instrs [ (match cmp with | Ceq -> Instruction.IF_ICMPEQ (Utils.s2 jump_ofs) | Cneq -> Instruction.IF_ICMPNE (Utils.s2 jump_ofs) | Clt -> Instruction.IF_ICMPLT (Utils.s2 jump_ofs) | Cgt -> Instruction.IF_ICMPGT (Utils.s2 jump_ofs) | Cle -> Instruction.IF_ICMPLE (Utils.s2 jump_ofs) | Cge -> Instruction.IF_ICMPGE (Utils.s2 jump_ofs)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] | Pbintcomp (Pnativeint, cmp), _ | Pbintcomp (Pint64, cmp), _ -> let jump_ofs = if_size + lconst_size + goto_size in after_args_instrs [ Instruction.LCMP ; (match cmp with | Ceq -> Instruction.IFEQ (Utils.s2 jump_ofs) | Cneq -> Instruction.IFNE (Utils.s2 jump_ofs) | Clt -> Instruction.IFLT (Utils.s2 jump_ofs) | Cgt -> Instruction.IFGT (Utils.s2 jump_ofs) | Cle -> Instruction.IFLE (Utils.s2 jump_ofs) | Cge -> Instruction.IFGE (Utils.s2 jump_ofs)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] | Pbigarrayref _, _ -> fatal_error "Pbigarrayref" | Pbigarrayset _, _ -> fatal_error "Pbigarrayset" | Pbigarraydim ((1 | 2 | 3) as dim), _ -> after_args_instrs [ Instruction.INVOKESTATIC (make_class "org.ocamljava.runtime.primitives.otherlibs.bigarray.BigArray", make_method ("caml_ba_dim_" ^ (string_of_int dim)), ([`Class class_Value], `Class class_Value)) ] | Pbigarraydim _, _ -> assert false | Pstring_load_16 _, _ -> string_meth true "caml_string_get16" | Pstring_load_32 _, _ -> string_meth true "caml_string_get32" | Pstring_load_64 _, _ -> string_meth true "caml_string_get64" | Pstring_set_16 _, _ -> string_meth false "caml_string_set16" | Pstring_set_32 _, _ -> string_meth false "caml_string_set32" | Pstring_set_64 _, _ -> string_meth false "caml_string_set64" | Pbigstring_load_16 _, _ -> bigstring_meth true "caml_ba_uint8_get16" | Pbigstring_load_32 _, _ -> bigstring_meth true "caml_ba_uint8_get32" | Pbigstring_load_64 _, _ -> bigstring_meth true "caml_ba_uint8_get64" | Pbigstring_set_16 _, _ -> bigstring_meth false "caml_ba_uint8_set16" | Pbigstring_set_32 _, _ -> bigstring_meth false "caml_ba_uint8_set32" | Pbigstring_set_64 _, _ -> bigstring_meth false "caml_ba_uint8_set64" | Pctconst Big_endian, _ -> fatal_error "Pctconst Big_endian" | Pctconst Word_size, _ -> fatal_error "Pctconst Word_size" | Pctconst Ostype_unix, _ -> fatal_error "Pctconst Ostype_unix" | Pctconst Ostype_win32, _ -> fatal_error "Pctconst Ostype_win32" | Pctconst Ostype_cygwin, _ -> fatal_error "Pctconst Ostype_cygwin" | Pbswap16, _ -> after_args_instrs [ Instruction.I2S ; Instruction.INVOKESTATIC (make_class "java.lang.Short", make_method "reverseBytes", ([`Short], `Short)) ] | Pbbswap Pint32, _ -> after_args_instrs [ Instruction.INVOKESTATIC (make_class "java.lang.Integer", make_method "reverseBytes", ([`Int], `Int)) ] | Pbbswap Pint64, _ | Pbbswap Pnativeint, _ -> after_args_instrs [ Instruction.INVOKESTATIC (make_class "java.lang.Long", make_method "reverseBytes", ([`Long], `Long)) ] and compile_block tag mut ofs args compile_expression_list compile_expression = let args_size = List.length args in if args_size = 0 && mut = Asttypes.Immutable then node [ push_int32 tag ; meth_getAtom ] else if args_size <= 8 then let int_instr, int_sz = with_size (push_int32 tag) in node [ int_instr ; compile_expression_list (ofs + int_sz) args ; leaf [ Instruction.INVOKESTATIC (class_Value, make_method "createBlock", (`Int :: (repeat_parameters args_size), `Class class_Value)) ] ] else let dup_size = 1 in let alloc_instr, alloc_sz = with_size (node [ push_int32 tag ; push_int args_size ; meth_createBlock ]) in let _, _, set_instrs = List.fold_left (fun (idx, ofs, acc) elem -> let idx_instr, idx_sz = with_size (push_int idx) in let instrs = node [ leaf [ Instruction.DUP ] ; idx_instr ; compile_expression false (ofs + dup_size + idx_sz) elem ; meth_set ] in (succ idx, ofs + (size instrs), instrs :: acc)) (0, ofs + alloc_sz, []) args in node [ alloc_instr ; node (List.rev set_instrs) ] and compile_long_expression_list ofs l compile_expression = List.fold_left (fun (ofs, acc) elem -> let res, sz = with_size (compile_expression false ofs elem) in ofs + sz, res :: acc) (ofs, []) l |> snd |> List.rev |> node and compile_double_expression_list ofs l compile_expression = List.fold_left (fun (ofs, acc) elem -> let res, sz = with_size (compile_expression false ofs elem) in ofs + sz, res :: acc) (ofs, []) l |> snd |> List.rev |> node
null
https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/compiler/javacomp/bytecodegen_prim.ml
ocaml
tagged values normalized values unboxed values boxed values
* This file is part of compiler . * Copyright ( C ) 2007 - 2015 . * * compiler is free software ; you can redistribute it and/or modify * it under the terms of the Q Public License as published by * ( with a change to choice of law ) . * * compiler 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 * Q Public License for more details . * * You should have received a copy of the Q Public License * along with this program . If not , see * < -1.0 > . * This file is part of OCaml-Java compiler. * Copyright (C) 2007-2015 Xavier Clerc. * * OCaml-Java compiler is free software; you can redistribute it and/or modify * it under the terms of the Q Public License as published by * Trolltech (with a change to choice of law). * * OCaml-Java compiler 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 * Q Public License for more details. * * You should have received a copy of the Q Public License * along with this program. If not, see * <-1.0>. *) open Asttypes open Lambda open Macroinstr open Bytecodeutils open Bytecodegen_misc open BaristaLibrary let node x = Instrtree.node x let leaf x = Instrtree.leaf x let size x = Instrtree.size x let with_size x = x, size x let inline_simple_arithmetic () = !Clflags.inline_threshold >= 100 let get_global id = if ((State.current_function ()) = "entry") && ((State.current_module ()) = (Ident.name id)) then begin make_class (Jcompilenv.current_global_class_name ()), leaf [ Instruction.ALOAD_0 ] end else begin try let classname = Jcompilenv.class_for_global id in let glob_classname = make_class (classname ^ "$Global") in let classname = make_class classname in glob_classname, node [ leaf [ Instruction.GETSTATIC (classname, make_field "GLOBALS", `Class class_ThreadLocal) ] ; meth_get_threadlocal ; leaf [ Instruction.CHECKCAST (`Class_or_interface glob_classname) ] ] with _ -> make_class "dummy_class", node [ leaf [ Instruction.LDC_W (`String (UTF8.of_string (Ident.name id))) ]; meth_getGlobal ] end let optimized_get_global id idx = (match Jcompilenv.global_approx_no_dep id with | Jlambda.Value_tuple app when idx < Array.length app -> true | Jlambda.Value_tuple _ -> false | _ ->false) && (try ignore (Jcompilenv.class_for_global id); true with _ -> false) let descriptor_of_approx = function | Jlambda.Value_closure _ -> `Class class_Value | Jlambda.Value_tuple _ -> `Class class_Value | Jlambda.Value_unknown None -> `Class class_Value | Jlambda.Value_unknown (Some repr) -> begin match repr with | LR_value | LR_string | LR_exn | LR_array _ | LR_list _ | LR_option _ | LR_lazy _ | LR_unit -> `Class class_Value | LR_int | LR_char | LR_bool -> `Long | LR_float -> `Double | LR_nativeint -> `Long | LR_int32 -> `Int | LR_int64 -> `Long | LR_java_instance cn | LR_java_extends cn -> `Class (make_class cn) | (LR_java_boolean_array | LR_java_byte_array | LR_java_char_array | LR_java_double_array | LR_java_float_array | LR_java_int_array | LR_java_long_array | LR_java_reference_array _ | LR_java_short_array) as arr -> let arr = array_type_of_repr arr in (Jlambda.unconvert_array_type arr :> Descriptor.for_field) | LR_none -> assert false end | Jlambda.Value_integer _ -> `Long | Jlambda.Value_integer32 _ -> `Int | Jlambda.Value_integer64 _ -> `Long | Jlambda.Value_integernat _ -> `Long | Jlambda.Value_constptr _ -> `Long | Jlambda.Value_float _ -> `Double | Jlambda.Value_java_null None -> `Class class_Object | Jlambda.Value_java_null (Some jt) -> begin match jt with | `Class cn -> `Class (make_class cn) | (`Array _) as arr -> (Jlambda.unconvert_array_type arr :> Descriptor.for_field) | `Long | `Float | `Byte | `Char | `Boolean | `Int | `Short | `Double -> assert false end | Jlambda.Value_java_string _ -> `Class class_String let rec compile_primitive ofs prim prim_args compile_expression_list compile_expression = let if_size = 3 in let goto_size = 3 in let lconst_size = 1 in let meth_size = 3 in let after_args_instrs l = node [ compile_expression_list ofs prim_args ; leaf l ] in let after_args_tree t = node [ compile_expression_list ofs prim_args ; t ] in let string_meth load meth = let params = if load then [`Class class_Value; `Class class_Value] else [`Class class_Value; `Class class_Value; `Class class_Value] in after_args_instrs [ Instruction.INVOKESTATIC (make_class "org.ocamljava.runtime.primitives.stdlib.Str", make_method meth, (params, `Class class_Value)) ] in let bigstring_meth load meth = let params = if load then [`Class class_Value; `Class class_Value] else [`Class class_Value; `Class class_Value; `Class class_Value] in after_args_instrs [ Instruction.INVOKESTATIC (make_class "org.ocamljava.runtime.primitives.otherlibs.bigarray.BigArray", make_method meth, (params, `Class class_Value)) ] in let fatal_error s = Misc.fatal_error ("Bytecodegen_prim.compile_primitive: " ^ s) in match prim, prim_args with | Pidentity, _ -> fatal_error "Pidentity" | Pignore, [arg] -> compile_expression false ofs arg | Pignore, _ -> assert false | Prevapply _, _ -> fatal_error "Prevapply" | Pdirapply _, _ -> fatal_error "Pdirapply" | Pgetglobal id, _ -> let field_name = match Ident.name id with | "caml_exn_Out_of_memory" -> Some "exnOutOfMemory" | "caml_exn_Sys_error" -> Some "exnSysError" | "caml_exn_Failure" -> Some "exnFailure" | "caml_exn_Invalid_argument" -> Some "exnInvalidArgument" | "caml_exn_End_of_file" -> Some "exnEndOfFile" | "caml_exn_Division_by_zero" -> Some "exnDivisionByZero" | "caml_exn_Not_found" -> Some "exnNotFound" | "caml_exn_Match_failure" -> Some "exnMatchFailure" | "caml_exn_Stack_overflow" -> Some "exnStackOverflow" | "caml_exn_Sys_blocked_io" -> Some "exnSysBlockedIO" | "caml_exn_Assert_failure" -> Some "exnAssertFailure" | "caml_exn_Undefined_recursive_module" -> Some "exnUndefinedRecursiveModule" | "caml_exn_Java_exception" -> Some "exnJavaException" | "caml_exn_Java_error" -> Some "exnJavaError" | _ -> None in begin match field_name with | None -> snd (get_global id) | Some fn -> node [ meth_getPredefinedExceptions ; leaf [ Instruction.GETFIELD (class_PredefinedExceptions, make_field fn, `Class class_Value) ] ] end | Psetglobal id, _ -> begin try let cls = Jcompilenv.class_for_global id in after_args_tree (node [ leaf [ Instruction.GETSTATIC (make_class cls, make_field "GLOBALS", `Class class_ThreadLocal) ; Instruction.SWAP ] ; meth_set_threadlocal ]) with _ -> after_args_tree (node [ leaf [ Instruction.LDC_W (`String (UTF8.of_string (Ident.name id))); ]; meth_setGlobal ]) end | Pmakeblock (tag, mut), args -> compile_block (Int32.of_int tag) mut ofs args compile_expression_list compile_expression | Pfield idx, [Mprim (Pgetglobal id, _, _)] when (optimized_get_global id idx) -> begin match Jcompilenv.global_approx_no_dep id with | Jlambda.Value_tuple approx -> let glob_classname, get_global_instrs = get_global id in let fieldname = make_field (Printf.sprintf "field_%d" idx) in let desc = descriptor_of_approx approx.(idx) in node [ get_global_instrs ; leaf [ Instruction.GETFIELD (glob_classname, fieldname, desc) ] ] | _ -> assert false end | Pfield n, [arg] -> node [ compile_expression false ofs arg ; (match n with | 0 -> meth_get0 | 1 -> meth_get1 | 2 -> meth_get2 | 3 -> meth_get3 | 4 -> meth_get4 | 5 -> meth_get5 | 6 -> meth_get6 | 7 -> meth_get7 | _ -> if is_int32 n then node [ push_int32 (Int32.of_int n); meth_get'int ] else node [ push_int n; meth_get ]) ] | Pfield _, _ -> assert false | Psetfield (idx, _), [Mprim (Pgetglobal id, _, _); arg] when (optimized_get_global id idx) -> begin match Jcompilenv.global_approx_no_dep id with | Jlambda.Value_tuple approx -> let glob_classname, get_global_instrs = get_global id in let fieldname = make_field (Printf.sprintf "field_%d" idx) in let desc = descriptor_of_approx approx.(idx) in let arg_instrs = compile_expression false (ofs + 3 + meth_size) arg in node [ get_global_instrs ; arg_instrs ; leaf [ Instruction.PUTFIELD (glob_classname, fieldname, desc) ] ; field_Value_UNIT ] | _ -> assert false end | Psetfield (n, _), [arg1; arg2] -> let arg1_instrs, arg1_sz = with_size (compile_expression false ofs arg1) in let idx_instrs, idx_sz = with_size (if n < 8 then leaf [] else if is_int32 n then push_int32 (Int32.of_int n) else push_int n) in let arg2_instrs = compile_expression false (ofs + arg1_sz + idx_sz) arg2 in node [ arg1_instrs ; idx_instrs ; arg2_instrs ; (match n with | 0 -> meth_set0 | 1 -> meth_set1 | 2 -> meth_set2 | 3 -> meth_set3 | 4 -> meth_set4 | 5 -> meth_set5 | 6 -> meth_set6 | 7 -> meth_set7 | _ -> if is_int32 n then meth_set'int else meth_set) ; field_Value_UNIT ] | Psetfield _, _ -> assert false | Pfloatfield n, [arg] -> node [ compile_expression false ofs arg ; (match n with | 0 -> meth_getGenericDouble0 | 1 -> meth_getGenericDouble1 | 2 -> meth_getGenericDouble2 | 3 -> meth_getGenericDouble3 | 4 -> meth_getGenericDouble4 | 5 -> meth_getGenericDouble5 | 6 -> meth_getGenericDouble6 | 7 -> meth_getGenericDouble7 | _ -> if is_int32 n then node [ push_int32 (Int32.of_int n); meth_getGenericDouble'int ] else node [ push_int n; meth_getGenericDouble ]) ] | Pfloatfield _, _ -> assert false | Psetfloatfield n, [arg1; arg2] -> let arg1_instrs, arg1_sz = with_size (compile_expression false ofs arg1) in let idx_instrs, idx_sz = with_size (if n < 8 then leaf [] else if is_int32 n then push_int32 (Int32.of_int n) else push_int n) in let arg2_instrs = compile_expression false (ofs + arg1_sz + idx_sz) arg2 in node [ arg1_instrs ; idx_instrs ; arg2_instrs ; (match n with | 0 -> meth_setGenericDouble0 | 1 -> meth_setGenericDouble1 | 2 -> meth_setGenericDouble2 | 3 -> meth_setGenericDouble3 | 4 -> meth_setGenericDouble4 | 5 -> meth_setGenericDouble5 | 6 -> meth_setGenericDouble6 | 7 -> meth_setGenericDouble7 | _ -> if is_int32 n then meth_setGenericDouble'int else meth_setGenericDouble) ; field_Value_UNIT ] | Psetfloatfield _, _ -> assert false | Pduprecord _, _ -> fatal_error "Pduprecord" | Plazyforce, _ -> fatal_error "Plazyforce" | Pccall prim, _ -> let name = prim.Primitive.prim_name in if Macrogen_primitives.is_unary_math_primitive name then after_args_instrs [ Instruction.INVOKESTATIC (make_class "java.lang.Math", make_method (Macrogen_primitives.unary_method name), ([`Double], `Double)) ] else if Macrogen_primitives.is_binary_math_primitive name then after_args_instrs [ Instruction.INVOKESTATIC (make_class "java.lang.Math", make_method (Macrogen_primitives.binary_method name), ([`Double; `Double], `Double)) ] else begin let desc = Runtimeprimitives.get_description name in after_args_tree (node [ (if desc.Runtimeprimitives.primdesc_parameters = [] then leaf [ Instruction.POP ] else leaf []) ; leaf [ Instruction.INVOKESTATIC (make_class desc.Runtimeprimitives.primdesc_class, make_method desc.Runtimeprimitives.primdesc_method, desc.Runtimeprimitives.primdesc_javadesc) ] ; (if desc.Runtimeprimitives.primdesc_return = LR_none then field_Value_UNIT else leaf []) ]) end | Praise, [arg] -> node [ compile_expression false ofs arg ; meth_raise; field_Value_UNIT ] | Praise, _ -> assert false | Psequand, _ -> assert false | Psequor, _ -> assert false | Pnot, [arg] -> node [ compile_expression false ofs arg ; leaf [ Instruction.L2I ; Instruction.IFEQ (Utils.s2 (if_size + lconst_size + goto_size)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] ] | Pnot, _ -> assert false | Pnegint, _ -> after_args_tree meth_negint | Paddint, [arg; Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int 1))))] | Paddint, [Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int 1)))); arg] | Paddint, [arg; Mconst (Jlambda.Lambda_const (Const_base (Const_int 1)))] | Paddint, [Mconst (Jlambda.Lambda_const (Const_base (Const_int 1))); arg] -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LDC2_W (`Long 2L); Instruction.LADD ] ] else node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LCONST_1 ; Instruction.LADD ] ] else node [ compile_expression_list ofs [arg] ; meth_incrint ] | Paddint, [arg; Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1)))))] | Paddint, [Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1))))); arg] | Paddint, [arg; Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1))))] | Paddint, [Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1)))); arg] -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LDC2_W (`Long 2L); Instruction.LSUB ] ] else node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LCONST_1 ; Instruction.LSUB ] ] else node [ compile_expression_list ofs [arg] ; meth_decrint ] | Paddint, _ -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then after_args_tree (leaf [ Instruction.LADD; Instruction.LCONST_1; Instruction.LSUB ]) else after_args_tree (leaf [ Instruction.LADD ]) else after_args_tree meth_addint | Psubint, [arg; Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int 1))))] | Psubint, [arg; Mconst (Jlambda.Lambda_const (Const_base (Const_int 1)))] -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LDC2_W (`Long 2L); Instruction.LSUB ] ] else node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LCONST_1 ; Instruction.LSUB ] ] else node [ compile_expression_list ofs [arg] ; meth_decrint ] | Psubint, [arg; Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1)))))] | Psubint, [arg; Mconst (Jlambda.Lambda_const (Const_base (Const_int (-1))))] -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LDC2_W (`Long 2L); Instruction.LADD ] ] else node [ compile_expression_list ofs [arg] ; leaf [ Instruction.LCONST_1 ; Instruction.LADD ] ] else node [ compile_expression_list ofs [arg] ; meth_incrint ] | Psubint, _ -> if inline_simple_arithmetic () then if Jconfig.ints_are_63_bit_long then after_args_tree (leaf [ Instruction.LSUB; Instruction.LCONST_1; Instruction.LADD ]) else after_args_tree (leaf [ Instruction.LSUB ]) else after_args_tree meth_subint | Pmulint, _ -> after_args_tree meth_mulint | Pdivint, _ -> after_args_tree meth_divint | Pmodint, _ -> after_args_tree meth_modint | Pandint, _ -> after_args_instrs [ Instruction.LAND ] | Porint, _ -> after_args_instrs [ Instruction.LOR ] | Pxorint, _ -> if Jconfig.ints_are_63_bit_long then after_args_instrs [ Instruction.LXOR; Instruction.LCONST_1; Instruction.LOR ] else after_args_instrs [ Instruction.LXOR ] | Plslint, _ -> after_args_tree meth_lslint | Plsrint, _ -> after_args_tree meth_lsrint | Pasrint, _ -> after_args_tree meth_asrint | Pintcomp cmp, [arg0; arg1; arg2] -> begin match arg0 with let jump_ofs = if_size + lconst_size + goto_size in node [ compile_expression_list ofs [arg1; arg2] ; leaf [ Instruction.LCMP ; (match cmp with | Ceq -> Instruction.IFEQ (Utils.s2 jump_ofs) | Cneq -> Instruction.IFNE (Utils.s2 jump_ofs) | Clt -> Instruction.IFLT (Utils.s2 jump_ofs) | Cgt -> Instruction.IFGT (Utils.s2 jump_ofs) | Cle -> Instruction.IFLE (Utils.s2 jump_ofs) | Cge -> Instruction.IFGE (Utils.s2 jump_ofs)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] ] node [ compile_expression_list ofs [arg1; arg2] ; (match cmp with | Ceq -> meth_equalValues | Cneq -> meth_notEqualValues | Clt -> meth_lowerThanValue | Cgt -> meth_greaterThanValue | Cle -> meth_lowerEqualValue | Cge -> meth_greaterEqualValue) ; leaf [ Instruction.I2L ] ] end | Pintcomp _, _ -> assert false | Poffsetint 1, _ -> after_args_tree (node [ meth_incrint ]) | Poffsetint (-1), _ -> after_args_tree (node [ meth_decrint ]) | Poffsetint n, _ -> if Jconfig.ints_are_63_bit_long then after_args_tree (node [ push_int ((n lsl 1) lor 1); meth_offsetint ]) else after_args_tree (node [ push_int n; meth_offsetint ]) | Poffsetref n, _ -> after_args_tree (node [ push_int (n * 2); meth_offsetref; field_Value_UNIT ]) | Pintoffloat, _ -> after_args_instrs [ Instruction.D2L ] | Pfloatofint, _ -> after_args_instrs [ Instruction.L2D ] | Pnegfloat, _ -> after_args_instrs [ Instruction.DNEG ] | Pabsfloat, _ -> after_args_tree meth_abs | Paddfloat, _ -> after_args_instrs [ Instruction.DADD ] | Psubfloat, _ -> after_args_instrs [ Instruction.DSUB ] | Pmulfloat, _ -> after_args_instrs [ Instruction.DMUL ] | Pdivfloat, _ -> after_args_instrs [ Instruction.DDIV ] | Pfloatcomp cmp, _ -> let jump_ofs = if_size + lconst_size + goto_size in after_args_instrs [ Instruction.DCMPG ; (match cmp with | Ceq -> Instruction.IFEQ (Utils.s2 jump_ofs) | Cneq -> Instruction.IFNE (Utils.s2 jump_ofs) | Clt -> Instruction.IFLT (Utils.s2 jump_ofs) | Cgt -> Instruction.IFGT (Utils.s2 jump_ofs) | Cle -> Instruction.IFLE (Utils.s2 jump_ofs) | Cge -> Instruction.IFGE (Utils.s2 jump_ofs)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] | Pstringlength, _ -> after_args_tree meth_sizeBytes; | Pstringrefu, _ -> after_args_tree (node [ meth_getUnsignedByte; leaf [ Instruction.I2L ] ]); | Pstringsetu, _ -> after_args_tree (node [ leaf [ Instruction.L2I ] ; meth_setUnsignedByte ; field_Value_UNIT ]) | Pstringrefs, _ -> after_args_tree meth_caml_string_get | Pstringsets, _ -> after_args_tree meth_caml_string_set | Pmakearray _, [] -> Bytecodegen_constants.push_structured_constant (Const_block (0, [])) | Pmakearray kind, args -> (match kind with | Paddrarray -> compile_block 0l Mutable ofs args compile_expression_list compile_expression | Pintarray -> let longs n = let rec lng acc = function | 0 -> (`Int :: acc, (`Class class_Value)) | n -> lng (`Long :: acc) (pred n) in lng [] n in let args_size = List.length args in if args_size <= 8 then node [ leaf [ Instruction.ICONST_0 ] ; compile_long_expression_list (succ ofs) args compile_expression ; leaf [ Instruction.INVOKESTATIC (class_Value, make_method "createLongBlock", longs args_size) ] ] else let dup_size = 1 in let alloc_instr, alloc_sz = with_size (node [ leaf [ Instruction.ICONST_0 ] ; push_int args_size ; meth_createLongBlockFromSize ]) in let _, _, set_instrs = List.fold_left (fun (idx, ofs, acc) elem -> let idx_instr, idx_sz = with_size (push_int idx) in let instrs = node [ leaf [ Instruction.DUP ] ; idx_instr ; compile_expression false (ofs + dup_size + idx_sz) elem ; meth_setRawLong ] in (succ idx, ofs + (size instrs), instrs :: acc)) (0, ofs + alloc_sz, []) args in node [ alloc_instr ; node (List.rev set_instrs) ] | Pfloatarray -> let doubles n = let rec dbl acc = function | 0 -> (acc, (`Class class_Value)) | n -> dbl (`Double :: acc) (pred n) in dbl [] n in let args_size = List.length args in if args_size <= 8 then node [ compile_double_expression_list ofs args compile_expression ; leaf [ Instruction.INVOKESTATIC (class_Value, make_method "createDoubleArray", doubles args_size) ] ] else let dup_size = 1 in let alloc_instr, alloc_sz = with_size (node [ push_int args_size ; meth_createDoubleArray ]) in let _, _, set_instrs = List.fold_left (fun (idx, ofs, acc) elem -> let idx_instr, idx_sz = with_size (push_int idx) in let instrs = node [ leaf [ Instruction.DUP ] ; idx_instr ; compile_expression false (ofs + dup_size + idx_sz) elem ; meth_setDouble ] in (succ idx, ofs + (size instrs), instrs :: acc)) (0, ofs + alloc_sz, []) args in node [ alloc_instr ; node (List.rev set_instrs) ] | Pgenarray -> node [ compile_block 0l Mutable ofs args compile_expression_list compile_expression ; meth_caml_make_array ]) | Parraylength _, _ -> after_args_tree meth_arrayLength | Parrayrefu Paddrarray, [Mconst (Jlambda.Lambda_const (Const_base (Const_int idx)))] when (is_int32 idx) -> node [ push_int32 (Int32.of_int idx) ; meth_get'int ] | Parrayrefu kind, _ -> after_args_tree (match kind with | Pgenarray -> meth_caml_array_unsafe_get | Pfloatarray -> meth_getDouble | Pintarray -> meth_getRawLong | Paddrarray -> meth_get) | Parraysetu kind, _ -> after_args_tree (match kind with | Pgenarray -> meth_caml_array_unsafe_set | Pfloatarray -> node [ meth_setDouble ; field_Value_UNIT ] | Pintarray -> node [ meth_setRawLong ; field_Value_UNIT ] | Paddrarray -> node [ meth_set ; field_Value_UNIT ]) | Parrayrefs kind, _ -> after_args_tree (match kind with | Pgenarray -> meth_caml_array_get | Pfloatarray -> meth_caml_array_get_float | Pintarray -> meth_caml_array_get_int | Paddrarray -> meth_caml_array_get_addr) | Parraysets kind, _ -> after_args_tree (match kind with | Pgenarray -> meth_caml_array_set | Pfloatarray -> meth_caml_array_set_float | Pintarray -> meth_caml_array_set_int | Paddrarray -> meth_caml_array_set_addr) | Pisint, _ -> after_args_tree (node [ meth_isLong ; leaf [ Instruction.I2L ] ]) | Pisout, [arg0; arg1] -> let can_be_represented_int x = (x lsr 62) = 0 in let can_be_represented_target_int x = (Targetint.compare (Targetint.shift_right_logical x (Targetint.of_int 62)) Targetint.zero) = 0 in let meth = match arg0, arg1 with | Mconst (Jlambda.Lambda_const (Const_base (Const_int x))), _ | Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int x)))), _ when can_be_represented_int x -> meth_isOutFirstPositive | Mconst (Jlambda.Const_targetint x), _ | Mconvert (_, _, Mconst (Jlambda.Const_targetint x)), _ when can_be_represented_target_int x -> meth_isOutFirstPositive | _, Mconst (Jlambda.Lambda_const (Const_base (Const_int x))) | _, Mconvert (_, _, Mconst (Jlambda.Lambda_const (Const_base (Const_int x)))) when can_be_represented_int x -> meth_isOutSecondPositive | _, Mconst (Jlambda.Const_targetint x) | _, Mconvert (_, _, Mconst (Jlambda.Const_targetint x)) when can_be_represented_target_int x -> meth_isOutSecondPositive | _ -> meth_isOut in after_args_tree (node [ meth ; leaf [ Instruction.I2L ] ]) | Pisout, _ -> assert false | Pbittest, _ -> after_args_tree (node [ meth_bitvect_test; leaf [ Instruction.I2L ] ]) | Pbintofint bi, _ -> after_args_tree (compile_conversion int_kind (kind_of_boxed_integer bi)) | Pintofbint bi, _ -> after_args_tree (compile_conversion (kind_of_boxed_integer bi) int_kind) | Pcvtbint (src, dst), _ -> let src_kind = kind_of_boxed_integer src in let dst_kind = kind_of_boxed_integer dst in after_args_tree (compile_conversion src_kind dst_kind) | Pnegbint Pnativeint, _ -> after_args_instrs [ Instruction.LNEG ] | Pnegbint Pint32, _ -> after_args_instrs [ Instruction.INEG ] | Pnegbint Pint64, _ -> after_args_instrs [ Instruction.LNEG ] | Paddbint Pnativeint, _ -> after_args_instrs [ Instruction.LADD ] | Paddbint Pint32, _ -> after_args_instrs [ Instruction.IADD ] | Paddbint Pint64, _ -> after_args_instrs [ Instruction.LADD ] | Psubbint Pnativeint, _ -> after_args_instrs [ Instruction.LSUB ] | Psubbint Pint32, _ -> after_args_instrs [ Instruction.ISUB ] | Psubbint Pint64, _ -> after_args_instrs [ Instruction.LSUB ] | Pmulbint Pnativeint, _ -> after_args_instrs [ Instruction.LMUL ] | Pmulbint Pint32, _ -> after_args_instrs [ Instruction.IMUL ] | Pmulbint Pint64, _ -> after_args_instrs [ Instruction.LMUL ] | Pdivbint Pnativeint, _ -> after_args_tree meth_divint64 | Pdivbint Pint32, _ -> after_args_tree meth_divint32 | Pdivbint Pint64, _ -> after_args_tree meth_divint64 | Pmodbint Pnativeint, _ -> after_args_tree meth_modint64 | Pmodbint Pint32, _ -> after_args_tree meth_modint32 | Pmodbint Pint64, _ -> after_args_tree meth_modint64 | Pandbint Pnativeint, _ -> after_args_instrs [ Instruction.LAND ] | Pandbint Pint32, _ -> after_args_instrs [ Instruction.IAND ] | Pandbint Pint64, _ -> after_args_instrs [ Instruction.LAND ] | Porbint Pnativeint, _ -> after_args_instrs [ Instruction.LOR ] | Porbint Pint32, _ -> after_args_instrs [ Instruction.IOR ] | Porbint Pint64, _ -> after_args_instrs [ Instruction.LOR ] | Pxorbint Pnativeint, _ -> after_args_instrs [ Instruction.LXOR ] | Pxorbint Pint32, _ -> after_args_instrs [ Instruction.IXOR ] | Pxorbint Pint64, _ -> after_args_instrs [ Instruction.LXOR ] | Plslbint Pnativeint, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LSHL ] | Plslbint Pint32, _ -> after_args_instrs [ Instruction.L2I ; Instruction.ISHL ] | Plslbint Pint64, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LSHL ] | Plsrbint Pnativeint, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LUSHR ] | Plsrbint Pint32, _ -> after_args_instrs [ Instruction.L2I ; Instruction.IUSHR ] | Plsrbint Pint64, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LUSHR ] | Pasrbint Pnativeint, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LSHR ] | Pasrbint Pint32, _ -> after_args_instrs [ Instruction.L2I ; Instruction.ISHR ] | Pasrbint Pint64, _ -> after_args_instrs [ Instruction.L2I ; Instruction.LSHR ] | Pbintcomp (Pint32, cmp), _ -> let jump_ofs = if_size + lconst_size + goto_size in after_args_instrs [ (match cmp with | Ceq -> Instruction.IF_ICMPEQ (Utils.s2 jump_ofs) | Cneq -> Instruction.IF_ICMPNE (Utils.s2 jump_ofs) | Clt -> Instruction.IF_ICMPLT (Utils.s2 jump_ofs) | Cgt -> Instruction.IF_ICMPGT (Utils.s2 jump_ofs) | Cle -> Instruction.IF_ICMPLE (Utils.s2 jump_ofs) | Cge -> Instruction.IF_ICMPGE (Utils.s2 jump_ofs)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] | Pbintcomp (Pnativeint, cmp), _ | Pbintcomp (Pint64, cmp), _ -> let jump_ofs = if_size + lconst_size + goto_size in after_args_instrs [ Instruction.LCMP ; (match cmp with | Ceq -> Instruction.IFEQ (Utils.s2 jump_ofs) | Cneq -> Instruction.IFNE (Utils.s2 jump_ofs) | Clt -> Instruction.IFLT (Utils.s2 jump_ofs) | Cgt -> Instruction.IFGT (Utils.s2 jump_ofs) | Cle -> Instruction.IFLE (Utils.s2 jump_ofs) | Cge -> Instruction.IFGE (Utils.s2 jump_ofs)) ; Instruction.LCONST_0 ; Instruction.GOTO (Utils.s2 (goto_size + lconst_size)) ; Instruction.LCONST_1 ] | Pbigarrayref _, _ -> fatal_error "Pbigarrayref" | Pbigarrayset _, _ -> fatal_error "Pbigarrayset" | Pbigarraydim ((1 | 2 | 3) as dim), _ -> after_args_instrs [ Instruction.INVOKESTATIC (make_class "org.ocamljava.runtime.primitives.otherlibs.bigarray.BigArray", make_method ("caml_ba_dim_" ^ (string_of_int dim)), ([`Class class_Value], `Class class_Value)) ] | Pbigarraydim _, _ -> assert false | Pstring_load_16 _, _ -> string_meth true "caml_string_get16" | Pstring_load_32 _, _ -> string_meth true "caml_string_get32" | Pstring_load_64 _, _ -> string_meth true "caml_string_get64" | Pstring_set_16 _, _ -> string_meth false "caml_string_set16" | Pstring_set_32 _, _ -> string_meth false "caml_string_set32" | Pstring_set_64 _, _ -> string_meth false "caml_string_set64" | Pbigstring_load_16 _, _ -> bigstring_meth true "caml_ba_uint8_get16" | Pbigstring_load_32 _, _ -> bigstring_meth true "caml_ba_uint8_get32" | Pbigstring_load_64 _, _ -> bigstring_meth true "caml_ba_uint8_get64" | Pbigstring_set_16 _, _ -> bigstring_meth false "caml_ba_uint8_set16" | Pbigstring_set_32 _, _ -> bigstring_meth false "caml_ba_uint8_set32" | Pbigstring_set_64 _, _ -> bigstring_meth false "caml_ba_uint8_set64" | Pctconst Big_endian, _ -> fatal_error "Pctconst Big_endian" | Pctconst Word_size, _ -> fatal_error "Pctconst Word_size" | Pctconst Ostype_unix, _ -> fatal_error "Pctconst Ostype_unix" | Pctconst Ostype_win32, _ -> fatal_error "Pctconst Ostype_win32" | Pctconst Ostype_cygwin, _ -> fatal_error "Pctconst Ostype_cygwin" | Pbswap16, _ -> after_args_instrs [ Instruction.I2S ; Instruction.INVOKESTATIC (make_class "java.lang.Short", make_method "reverseBytes", ([`Short], `Short)) ] | Pbbswap Pint32, _ -> after_args_instrs [ Instruction.INVOKESTATIC (make_class "java.lang.Integer", make_method "reverseBytes", ([`Int], `Int)) ] | Pbbswap Pint64, _ | Pbbswap Pnativeint, _ -> after_args_instrs [ Instruction.INVOKESTATIC (make_class "java.lang.Long", make_method "reverseBytes", ([`Long], `Long)) ] and compile_block tag mut ofs args compile_expression_list compile_expression = let args_size = List.length args in if args_size = 0 && mut = Asttypes.Immutable then node [ push_int32 tag ; meth_getAtom ] else if args_size <= 8 then let int_instr, int_sz = with_size (push_int32 tag) in node [ int_instr ; compile_expression_list (ofs + int_sz) args ; leaf [ Instruction.INVOKESTATIC (class_Value, make_method "createBlock", (`Int :: (repeat_parameters args_size), `Class class_Value)) ] ] else let dup_size = 1 in let alloc_instr, alloc_sz = with_size (node [ push_int32 tag ; push_int args_size ; meth_createBlock ]) in let _, _, set_instrs = List.fold_left (fun (idx, ofs, acc) elem -> let idx_instr, idx_sz = with_size (push_int idx) in let instrs = node [ leaf [ Instruction.DUP ] ; idx_instr ; compile_expression false (ofs + dup_size + idx_sz) elem ; meth_set ] in (succ idx, ofs + (size instrs), instrs :: acc)) (0, ofs + alloc_sz, []) args in node [ alloc_instr ; node (List.rev set_instrs) ] and compile_long_expression_list ofs l compile_expression = List.fold_left (fun (ofs, acc) elem -> let res, sz = with_size (compile_expression false ofs elem) in ofs + sz, res :: acc) (ofs, []) l |> snd |> List.rev |> node and compile_double_expression_list ofs l compile_expression = List.fold_left (fun (ofs, acc) elem -> let res, sz = with_size (compile_expression false ofs elem) in ofs + sz, res :: acc) (ofs, []) l |> snd |> List.rev |> node
82ff1f2cd52352c9c31e0f95e25db5d3ac815d0f19bdb3ba4f979f27a2956a55
andrenth/srsly
proxymap.ml
open Lwt open Printf open Release_lwt open Log_lwt open Util module O = Release.Util.Option module B = Release.Buffer module C = Srslyd_config let replace_formats = List.fold_left (fun s (fmt, rep) -> Str.global_replace (Str.regexp fmt) rep s) let build_request fmt table flags key = replace_formats fmt [ ("{t}", table) ; ("{f}", string_of_int flags) ; ("{k}", key) ] let alloc_read fd = let rec read buf = let siz = B.size buf in let len = B.length buf in Release.IO.read_once fd buf len (siz - len) >>= fun n -> if len + n = siz then begin let buf' = B.create (siz * 2) in B.add_buffer buf' buf; read buf' end else return buf in read (B.create 8192) let make_request socket req = let fd = Lwt_unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in Lwt.catch (fun () -> Lwt_unix.connect fd (Unix.ADDR_UNIX socket) >>= fun () -> Release.IO.write fd (B.of_string req) >>= fun () -> alloc_read fd >>= fun buf -> Lwt_unix.close fd >>= fun () -> let n = B.length buf in return (B.to_string (B.sub buf 0 n))) (function | Unix.Unix_error (e, _, _) -> Lwt_unix.close fd >>= fun () -> let err = Unix.error_message e in fail_lwt (sprintf "Proxymap.make_request: connect: %s" err) | e -> Lwt_unix.close fd >>= fun () -> let bt = Printexc.to_string e in fail_lwt (sprintf "Proxymap.make_request: %s" bt)) type status = Ok of string list | Key_not_found | Try_again | Invalid_parameter | Table_not_approved | Unknown of int let status_of_code c values = match c with | 0 -> Ok values | 1 -> Key_not_found | 2 -> Try_again | 3 -> Invalid_parameter | 4 -> Table_not_approved | x -> Unknown c let string_of_status = function | Ok _ -> "operation succeeded" | Key_not_found -> "requested key not found" | Try_again -> "try lookup again later" | Invalid_parameter -> "invalid request parameter" | Table_not_approved -> "table not approved for proxying" | Unknown c -> sprintf "unknown proxymap return status: %d" c (* This parser doesn't take advantage of the null-byte separator of the * postfix query format because there's no guarantee it's not going to * change in the future. *) let parse_result res fmt sep = let results = Hashtbl.create 2 in let set_result k v = if Hashtbl.mem results k then failwith (sprintf "Proxymap.parse_result: key {%s} already set" k) else Hashtbl.replace results k v in let rec scan i j = if i < String.length res && j < String.length fmt then match res.[i], fmt.[j] with | _, '{' -> get_key i (j+1) | a, b when a = b -> scan (i+1) (j+1) | a, b -> failwith (sprintf "Proxymap.parse_result: got %c, want %c" b a) else () (* done *) and get_key i j = let close = String.index_from fmt j '}' in let key = String.sub fmt j (close-j) in 1 - char lookahead and get_value i j key = if j < String.length fmt then let val_end = String.index_from res i fmt.[j] in let value = String.sub res i (val_end-i) in set_result key value; scan val_end j else let value = String.sub res i (String.length res - i) in set_result key value in scan 0 0; try let code = int_of_string (Hashtbl.find results "s") in let value = Hashtbl.find results "v" in status_of_code code (Str.split sep value) with Not_found -> failwith (sprintf "parse_result: missing keys") let query key table = let query_fmt = C.proxymap_query_format () in let flags = C.proxymap_query_flags () in let socket = C.proxymap_query_socket () in let res_fmt = C.proxymap_result_format () in let sep = C.proxymap_result_value_separator () in let req = build_request query_fmt table flags key in make_request socket req >>= fun raw_res -> return (parse_result raw_res res_fmt sep) * Query the given table looking for a recipient key . Results are recursively * queried depth - first and recursion stops when a key is not found , or when * either the recursion depth limit or the maximum results limit is reached . * If the recursion depth limit is reached in a recursion branch , other * branches are still queried . The maximum results limit is global and stops * recursion completely . * * The function given in the first parameter is called for each leaf result , * that is , those for which a query returns " not found " . This function takes * the original query key , the leaf result , the current limit for the * maximum number of results , and an accumulator value . It is expected to * return an updated limit and a new accumulator . * Query the given table looking for a recipient key. Results are recursively * queried depth-first and recursion stops when a key is not found, or when * either the recursion depth limit or the maximum results limit is reached. * If the recursion depth limit is reached in a recursion branch, other * branches are still queried. The maximum results limit is global and stops * recursion completely. * * The function given in the first parameter is called for each leaf result, * that is, those for which a query returns "not found". This function takes * the original query key, the leaf result, the current limit for the * maximum number of results, and an accumulator value. It is expected to * return an updated limit and a new accumulator. *) let query_with f key table max_depth max_results acc = let rec resolve keys max_depth max_res acc = match keys with | [] -> debug "no more keys, returning" >>= fun () -> return (max_res, acc) | k::rest -> if max_res = 0 then error "too many results querying for %s in %s" key table >>= fun () -> return (0, acc) else if max_depth < 0 then error "maximum depth reached in %s for %s" table key >>= fun () -> resolve rest max_depth max_res acc else debug "querying key %s" k >>= fun () -> query k table >>= function | Ok values -> resolve values (max_depth - 1) max_res acc >>= fun (max, acc) -> resolve rest max_depth max acc | Key_not_found -> debug "no redirects found for %s" k >>= fun () -> f key k max_res acc >>= fun (max, acc) -> resolve rest max_depth max acc | other -> let e = string_of_status other in error "error querying %s for %s: %s" table key e >>= fun () -> resolve rest max_depth max_res acc in resolve [key] max_depth max_results acc let (=~) s re = try ignore (Str.search_forward re s 0); true with Not_found -> false let proxymap_key fmt addr = try let at = String.rindex addr '@' in let user = String.sub addr 0 at in let domain = String.sub addr (at+1) (String.length addr - at - 1) in replace_formats fmt [ ("{u}", user) ; ("{d}", domain) ; ("{a}", addr) ] with Not_found -> replace_formats fmt [("{a}", addr)] (* * Queries for `sender` in the appropriate lookup table and checks if the * result is a remote address. *) let is_remote_sender sender = let table = C.proxymap_sender_lookup_table () in let local_re = C.proxymap_local_sender_regexp () in let fmt = C.proxymap_sender_lookup_key_format () in let key = proxymap_key fmt sender in let max_depth = C.proxymap_sender_query_max_depth () in let max_res = C.proxymap_sender_query_max_results () in debug "is_remote_sender: querying for %s" key >>= fun () -> let is_remote _ sender max res = if not (sender =~ local_re) then return (max-1, true) else return (max-1, res) in query_with is_remote key table max_depth max_res false >>= fun (_, res) -> return res module RcptSet = Set.Make(struct type t = string let compare = Pervasives.compare end) module RcptMap = Map.Make(struct type t = string let compare = Pervasives.compare end) (* Chooses a random key from a map, weighting the choice by its value. *) let weighted_sample m = let module M = struct exception Sample of string end in let tot = float_of_int (RcptMap.fold (fun _ c s -> s + c) m 0) in let r = tot *. (1.0 -. Random.float 1.0) in try ignore (RcptMap.fold (fun k c r -> let s = r -. float_of_int c in if s < 0.0 then raise (M.Sample k) else s) m r); assert false (* not reached *) with M.Sample k -> k let map_incr k m = try let v = RcptMap.find k m in RcptMap.add k (v+1) m with Not_found -> RcptMap.add k 1 m (* * This function is given as a parameter to `query_with` when called from * the `choose_forward_domain` function, below. It adds a final destination * address to the recipients set and increments the count of remote * destinations for the given original recipient if the corresponding final * destination is a remote address. The maximum number of results is * decremented if appropriate. *) let visit_rcpt local_re orig_rcpt final_rcpt max_res (rcpts, counts) = if max_res > 0 then begin let max, rcpts = if not (RcptSet.mem final_rcpt rcpts) then max_res - 1, RcptSet.add final_rcpt rcpts else max_res, rcpts in begin if not (final_rcpt =~ local_re) then debug "%s is remote" final_rcpt >>= fun () -> return (map_incr orig_rcpt counts) else debug "%s is local" final_rcpt >>= fun () -> return counts end >>= fun counts -> return (max, (rcpts, counts)) end else return (max_res, (rcpts, counts)) * We choose a random domain to be used as the SRS forward domain . * This is done because there 's no way to associate each of the original * recipients to the final addresses after virtual alias translation * is done . * We choose a random domain to be used as the SRS forward domain. * This is done because there's no way to associate each of the original * recipients to the final addresses after virtual alias translation * is done. *) let choose_forward_domain orig_rcpts = let table = C.proxymap_recipient_lookup_table () in let re = C.proxymap_local_recipient_regexp () in let fmt = C.proxymap_recipient_lookup_key_format () in let max_depth = C.proxymap_recipient_query_max_depth () in let num_rcpts = List.length orig_rcpts in let max_res = num_rcpts * C.proxymap_recipient_query_max_results () in Lwt_list.fold_left_s (fun (max_res, rcpts, counts) rcpt -> let key = proxymap_key fmt rcpt in debug "choose_forward_domain: querying for %s" key >>= fun () -> query_with (visit_rcpt re) key table max_depth max_res (rcpts, counts) >>= fun (max_res', (rcpts', counts')) -> return (max_res', rcpts', counts')) (max_res, RcptSet.empty, RcptMap.empty) orig_rcpts >>= fun (_, _, counts) -> if counts <> RcptMap.empty then return (Some (weighted_sample counts)) else return None
null
https://raw.githubusercontent.com/andrenth/srsly/fce92645781a6a6037512be4d35116ec53737b17/src/proxymap.ml
ocaml
This parser doesn't take advantage of the null-byte separator of the * postfix query format because there's no guarantee it's not going to * change in the future. done * Queries for `sender` in the appropriate lookup table and checks if the * result is a remote address. Chooses a random key from a map, weighting the choice by its value. not reached * This function is given as a parameter to `query_with` when called from * the `choose_forward_domain` function, below. It adds a final destination * address to the recipients set and increments the count of remote * destinations for the given original recipient if the corresponding final * destination is a remote address. The maximum number of results is * decremented if appropriate.
open Lwt open Printf open Release_lwt open Log_lwt open Util module O = Release.Util.Option module B = Release.Buffer module C = Srslyd_config let replace_formats = List.fold_left (fun s (fmt, rep) -> Str.global_replace (Str.regexp fmt) rep s) let build_request fmt table flags key = replace_formats fmt [ ("{t}", table) ; ("{f}", string_of_int flags) ; ("{k}", key) ] let alloc_read fd = let rec read buf = let siz = B.size buf in let len = B.length buf in Release.IO.read_once fd buf len (siz - len) >>= fun n -> if len + n = siz then begin let buf' = B.create (siz * 2) in B.add_buffer buf' buf; read buf' end else return buf in read (B.create 8192) let make_request socket req = let fd = Lwt_unix.socket Unix.PF_UNIX Unix.SOCK_STREAM 0 in Lwt.catch (fun () -> Lwt_unix.connect fd (Unix.ADDR_UNIX socket) >>= fun () -> Release.IO.write fd (B.of_string req) >>= fun () -> alloc_read fd >>= fun buf -> Lwt_unix.close fd >>= fun () -> let n = B.length buf in return (B.to_string (B.sub buf 0 n))) (function | Unix.Unix_error (e, _, _) -> Lwt_unix.close fd >>= fun () -> let err = Unix.error_message e in fail_lwt (sprintf "Proxymap.make_request: connect: %s" err) | e -> Lwt_unix.close fd >>= fun () -> let bt = Printexc.to_string e in fail_lwt (sprintf "Proxymap.make_request: %s" bt)) type status = Ok of string list | Key_not_found | Try_again | Invalid_parameter | Table_not_approved | Unknown of int let status_of_code c values = match c with | 0 -> Ok values | 1 -> Key_not_found | 2 -> Try_again | 3 -> Invalid_parameter | 4 -> Table_not_approved | x -> Unknown c let string_of_status = function | Ok _ -> "operation succeeded" | Key_not_found -> "requested key not found" | Try_again -> "try lookup again later" | Invalid_parameter -> "invalid request parameter" | Table_not_approved -> "table not approved for proxying" | Unknown c -> sprintf "unknown proxymap return status: %d" c let parse_result res fmt sep = let results = Hashtbl.create 2 in let set_result k v = if Hashtbl.mem results k then failwith (sprintf "Proxymap.parse_result: key {%s} already set" k) else Hashtbl.replace results k v in let rec scan i j = if i < String.length res && j < String.length fmt then match res.[i], fmt.[j] with | _, '{' -> get_key i (j+1) | a, b when a = b -> scan (i+1) (j+1) | a, b -> failwith (sprintf "Proxymap.parse_result: got %c, want %c" b a) else and get_key i j = let close = String.index_from fmt j '}' in let key = String.sub fmt j (close-j) in 1 - char lookahead and get_value i j key = if j < String.length fmt then let val_end = String.index_from res i fmt.[j] in let value = String.sub res i (val_end-i) in set_result key value; scan val_end j else let value = String.sub res i (String.length res - i) in set_result key value in scan 0 0; try let code = int_of_string (Hashtbl.find results "s") in let value = Hashtbl.find results "v" in status_of_code code (Str.split sep value) with Not_found -> failwith (sprintf "parse_result: missing keys") let query key table = let query_fmt = C.proxymap_query_format () in let flags = C.proxymap_query_flags () in let socket = C.proxymap_query_socket () in let res_fmt = C.proxymap_result_format () in let sep = C.proxymap_result_value_separator () in let req = build_request query_fmt table flags key in make_request socket req >>= fun raw_res -> return (parse_result raw_res res_fmt sep) * Query the given table looking for a recipient key . Results are recursively * queried depth - first and recursion stops when a key is not found , or when * either the recursion depth limit or the maximum results limit is reached . * If the recursion depth limit is reached in a recursion branch , other * branches are still queried . The maximum results limit is global and stops * recursion completely . * * The function given in the first parameter is called for each leaf result , * that is , those for which a query returns " not found " . This function takes * the original query key , the leaf result , the current limit for the * maximum number of results , and an accumulator value . It is expected to * return an updated limit and a new accumulator . * Query the given table looking for a recipient key. Results are recursively * queried depth-first and recursion stops when a key is not found, or when * either the recursion depth limit or the maximum results limit is reached. * If the recursion depth limit is reached in a recursion branch, other * branches are still queried. The maximum results limit is global and stops * recursion completely. * * The function given in the first parameter is called for each leaf result, * that is, those for which a query returns "not found". This function takes * the original query key, the leaf result, the current limit for the * maximum number of results, and an accumulator value. It is expected to * return an updated limit and a new accumulator. *) let query_with f key table max_depth max_results acc = let rec resolve keys max_depth max_res acc = match keys with | [] -> debug "no more keys, returning" >>= fun () -> return (max_res, acc) | k::rest -> if max_res = 0 then error "too many results querying for %s in %s" key table >>= fun () -> return (0, acc) else if max_depth < 0 then error "maximum depth reached in %s for %s" table key >>= fun () -> resolve rest max_depth max_res acc else debug "querying key %s" k >>= fun () -> query k table >>= function | Ok values -> resolve values (max_depth - 1) max_res acc >>= fun (max, acc) -> resolve rest max_depth max acc | Key_not_found -> debug "no redirects found for %s" k >>= fun () -> f key k max_res acc >>= fun (max, acc) -> resolve rest max_depth max acc | other -> let e = string_of_status other in error "error querying %s for %s: %s" table key e >>= fun () -> resolve rest max_depth max_res acc in resolve [key] max_depth max_results acc let (=~) s re = try ignore (Str.search_forward re s 0); true with Not_found -> false let proxymap_key fmt addr = try let at = String.rindex addr '@' in let user = String.sub addr 0 at in let domain = String.sub addr (at+1) (String.length addr - at - 1) in replace_formats fmt [ ("{u}", user) ; ("{d}", domain) ; ("{a}", addr) ] with Not_found -> replace_formats fmt [("{a}", addr)] let is_remote_sender sender = let table = C.proxymap_sender_lookup_table () in let local_re = C.proxymap_local_sender_regexp () in let fmt = C.proxymap_sender_lookup_key_format () in let key = proxymap_key fmt sender in let max_depth = C.proxymap_sender_query_max_depth () in let max_res = C.proxymap_sender_query_max_results () in debug "is_remote_sender: querying for %s" key >>= fun () -> let is_remote _ sender max res = if not (sender =~ local_re) then return (max-1, true) else return (max-1, res) in query_with is_remote key table max_depth max_res false >>= fun (_, res) -> return res module RcptSet = Set.Make(struct type t = string let compare = Pervasives.compare end) module RcptMap = Map.Make(struct type t = string let compare = Pervasives.compare end) let weighted_sample m = let module M = struct exception Sample of string end in let tot = float_of_int (RcptMap.fold (fun _ c s -> s + c) m 0) in let r = tot *. (1.0 -. Random.float 1.0) in try ignore (RcptMap.fold (fun k c r -> let s = r -. float_of_int c in if s < 0.0 then raise (M.Sample k) else s) m r); with M.Sample k -> k let map_incr k m = try let v = RcptMap.find k m in RcptMap.add k (v+1) m with Not_found -> RcptMap.add k 1 m let visit_rcpt local_re orig_rcpt final_rcpt max_res (rcpts, counts) = if max_res > 0 then begin let max, rcpts = if not (RcptSet.mem final_rcpt rcpts) then max_res - 1, RcptSet.add final_rcpt rcpts else max_res, rcpts in begin if not (final_rcpt =~ local_re) then debug "%s is remote" final_rcpt >>= fun () -> return (map_incr orig_rcpt counts) else debug "%s is local" final_rcpt >>= fun () -> return counts end >>= fun counts -> return (max, (rcpts, counts)) end else return (max_res, (rcpts, counts)) * We choose a random domain to be used as the SRS forward domain . * This is done because there 's no way to associate each of the original * recipients to the final addresses after virtual alias translation * is done . * We choose a random domain to be used as the SRS forward domain. * This is done because there's no way to associate each of the original * recipients to the final addresses after virtual alias translation * is done. *) let choose_forward_domain orig_rcpts = let table = C.proxymap_recipient_lookup_table () in let re = C.proxymap_local_recipient_regexp () in let fmt = C.proxymap_recipient_lookup_key_format () in let max_depth = C.proxymap_recipient_query_max_depth () in let num_rcpts = List.length orig_rcpts in let max_res = num_rcpts * C.proxymap_recipient_query_max_results () in Lwt_list.fold_left_s (fun (max_res, rcpts, counts) rcpt -> let key = proxymap_key fmt rcpt in debug "choose_forward_domain: querying for %s" key >>= fun () -> query_with (visit_rcpt re) key table max_depth max_res (rcpts, counts) >>= fun (max_res', (rcpts', counts')) -> return (max_res', rcpts', counts')) (max_res, RcptSet.empty, RcptMap.empty) orig_rcpts >>= fun (_, _, counts) -> if counts <> RcptMap.empty then return (Some (weighted_sample counts)) else return None
e9ec2320afbc1b5f181fdd285e29b38cfe6c51a32402fd5ba02789cb5c42d824
spwhitton/consfigurator
libcap.lisp
(in-package :consfigurator.util.posix1e) (include "sys/capability.h") (ctype cap_t "cap_t") (ctype cap_value_t "cap_value_t") (cenum cap_flag_t ((:cap-effective "CAP_EFFECTIVE")) ((:cap-permitted "CAP_PERMITTED")) ((:cap-inheritable "CAP_INHERITABLE"))) (cenum cap_flag_value_t ((:cap-set "CAP_SET")) ((:cap-clear "CAP_CLEAR"))) (constant (CAP_CHOWN "CAP_CHOWN")) (constant (CAP_DAC_OVERRIDE "CAP_DAC_OVERRIDE")) (constant (CAP_DAC_READ_SEARCH "CAP_DAC_READ_SEARCH")) (constant (CAP_FOWNER "CAP_FOWNER")) (constant (CAP_FSETID "CAP_FSETID")) (constant (CAP_KILL "CAP_KILL")) (constant (CAP_SETGID "CAP_SETGID")) (constant (CAP_SETUID "CAP_SETUID")) #+linux (progn (constant (CAP_SETPCAP "CAP_SETPCAP")) (constant (CAP_LINUX_IMMUTABLE "CAP_LINUX_IMMUTABLE")) (constant (CAP_NET_BIND_SERVICE "CAP_NET_BIND_SERVICE")) (constant (CAP_NET_BROADCAST "CAP_NET_BROADCAST")) (constant (CAP_NET_ADMIN "CAP_NET_ADMIN")) (constant (CAP_NET_RAW "CAP_NET_RAW")) (constant (CAP_IPC_LOCK "CAP_IPC_LOCK")) (constant (CAP_IPC_OWNER "CAP_IPC_OWNER")) (constant (CAP_SYS_MODULE "CAP_SYS_MODULE")) (constant (CAP_SYS_RAWIO "CAP_SYS_RAWIO")) (constant (CAP_SYS_CHROOT "CAP_SYS_CHROOT")) (constant (CAP_SYS_PTRACE "CAP_SYS_PTRACE")) (constant (CAP_SYS_PACCT "CAP_SYS_PACCT")) (constant (CAP_SYS_ADMIN "CAP_SYS_ADMIN")) (constant (CAP_SYS_BOOT "CAP_SYS_BOOT")) (constant (CAP_SYS_NICE "CAP_SYS_NICE")) (constant (CAP_SYS_RESOURCE "CAP_SYS_RESOURCE")) (constant (CAP_SYS_TIME "CAP_SYS_TIME")) (constant (CAP_SYS_TTY_CONFIG "CAP_SYS_TTY_CONFIG")) (constant (CAP_MKNOD "CAP_MKNOD")) (constant (CAP_LEASE "CAP_LEASE")) (constant (CAP_AUDIT_WRITE "CAP_AUDIT_WRITE")) (constant (CAP_AUDIT_CONTROL "CAP_AUDIT_CONTROL")) (constant (CAP_SETFCAP "CAP_SETFCAP")) (constant (CAP_MAC_OVERRIDE "CAP_MAC_OVERRIDE")) (constant (CAP_MAC_ADMIN "CAP_MAC_ADMIN")) (constant (CAP_SYSLOG "CAP_SYSLOG")) (constant (CAP_WAKE_ALARM "CAP_WAKE_ALARM")) (constant (CAP_BLOCK_SUSPEND "CAP_BLOCK_SUSPEND")) (constant (CAP_AUDIT_READ "CAP_AUDIT_READ")) (constant (CAP_PERFMON "CAP_PERFMON")) (constant (CAP_BPF "CAP_BPF")) (constant (CAP_CHECKPOINT_RESTORE "CAP_CHECKPOINT_RESTORE")))
null
https://raw.githubusercontent.com/spwhitton/consfigurator/3019bfea87ab6df33845f3bf7f7df03a33a5970d/src/libcap.lisp
lisp
(in-package :consfigurator.util.posix1e) (include "sys/capability.h") (ctype cap_t "cap_t") (ctype cap_value_t "cap_value_t") (cenum cap_flag_t ((:cap-effective "CAP_EFFECTIVE")) ((:cap-permitted "CAP_PERMITTED")) ((:cap-inheritable "CAP_INHERITABLE"))) (cenum cap_flag_value_t ((:cap-set "CAP_SET")) ((:cap-clear "CAP_CLEAR"))) (constant (CAP_CHOWN "CAP_CHOWN")) (constant (CAP_DAC_OVERRIDE "CAP_DAC_OVERRIDE")) (constant (CAP_DAC_READ_SEARCH "CAP_DAC_READ_SEARCH")) (constant (CAP_FOWNER "CAP_FOWNER")) (constant (CAP_FSETID "CAP_FSETID")) (constant (CAP_KILL "CAP_KILL")) (constant (CAP_SETGID "CAP_SETGID")) (constant (CAP_SETUID "CAP_SETUID")) #+linux (progn (constant (CAP_SETPCAP "CAP_SETPCAP")) (constant (CAP_LINUX_IMMUTABLE "CAP_LINUX_IMMUTABLE")) (constant (CAP_NET_BIND_SERVICE "CAP_NET_BIND_SERVICE")) (constant (CAP_NET_BROADCAST "CAP_NET_BROADCAST")) (constant (CAP_NET_ADMIN "CAP_NET_ADMIN")) (constant (CAP_NET_RAW "CAP_NET_RAW")) (constant (CAP_IPC_LOCK "CAP_IPC_LOCK")) (constant (CAP_IPC_OWNER "CAP_IPC_OWNER")) (constant (CAP_SYS_MODULE "CAP_SYS_MODULE")) (constant (CAP_SYS_RAWIO "CAP_SYS_RAWIO")) (constant (CAP_SYS_CHROOT "CAP_SYS_CHROOT")) (constant (CAP_SYS_PTRACE "CAP_SYS_PTRACE")) (constant (CAP_SYS_PACCT "CAP_SYS_PACCT")) (constant (CAP_SYS_ADMIN "CAP_SYS_ADMIN")) (constant (CAP_SYS_BOOT "CAP_SYS_BOOT")) (constant (CAP_SYS_NICE "CAP_SYS_NICE")) (constant (CAP_SYS_RESOURCE "CAP_SYS_RESOURCE")) (constant (CAP_SYS_TIME "CAP_SYS_TIME")) (constant (CAP_SYS_TTY_CONFIG "CAP_SYS_TTY_CONFIG")) (constant (CAP_MKNOD "CAP_MKNOD")) (constant (CAP_LEASE "CAP_LEASE")) (constant (CAP_AUDIT_WRITE "CAP_AUDIT_WRITE")) (constant (CAP_AUDIT_CONTROL "CAP_AUDIT_CONTROL")) (constant (CAP_SETFCAP "CAP_SETFCAP")) (constant (CAP_MAC_OVERRIDE "CAP_MAC_OVERRIDE")) (constant (CAP_MAC_ADMIN "CAP_MAC_ADMIN")) (constant (CAP_SYSLOG "CAP_SYSLOG")) (constant (CAP_WAKE_ALARM "CAP_WAKE_ALARM")) (constant (CAP_BLOCK_SUSPEND "CAP_BLOCK_SUSPEND")) (constant (CAP_AUDIT_READ "CAP_AUDIT_READ")) (constant (CAP_PERFMON "CAP_PERFMON")) (constant (CAP_BPF "CAP_BPF")) (constant (CAP_CHECKPOINT_RESTORE "CAP_CHECKPOINT_RESTORE")))
1f7753dd1a7fa170e305917a12ff54e4ea292bd60d6e2c52db5f0a5fc6e2d2ca
ekmett/linear
V.hs
# LANGUAGE CPP # # LANGUAGE TypeOperators # # LANGUAGE KindSignatures # # LANGUAGE ScopedTypeVariables # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE DefaultSignatures # {-# LANGUAGE Rank2Types #-} # LANGUAGE TypeFamilies # {-# LANGUAGE EmptyDataDecls #-} # LANGUAGE MultiParamTypeClasses , FlexibleContexts , FlexibleInstances , UndecidableInstances # {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DataKinds # # LANGUAGE PolyKinds # # LANGUAGE RoleAnnotations # # LANGUAGE Trustworthy # # LANGUAGE DeriveGeneric # #ifndef MIN_VERSION_hashable #define MIN_VERSION_hashable(x,y,z) 1 #endif #ifndef MIN_VERSION_reflection #define MIN_VERSION_reflection(x,y,z) 1 #endif #ifndef MIN_VERSION_transformers #define MIN_VERSION_transformers(x,y,z) 1 #endif #ifndef MIN_VERSION_base #define MIN_VERSION_base(x,y,z) 1 #endif ----------------------------------------------------------------------------- -- | Copyright : ( C ) 2012 - 2015 -- License : BSD-style (see the file LICENSE) -- Maintainer : < > -- Stability : experimental -- Portability : non-portable -- -- n-D Vectors ---------------------------------------------------------------------------- module Linear.V ( V(V,toVector) #ifdef MIN_VERSION_template_haskell , int #endif , dim , Dim(..) , reifyDim , reifyVector , reifyDimNat , reifyVectorNat , fromVector , Finite(..) , _V, _V' ) where import Control.Applicative import Control.DeepSeq (NFData) import Control.Monad import Control.Monad.Fix import Control.Monad.Trans.State import Control.Monad.Zip import Control.Lens as Lens import Data.Binary as Binary import Data.Bytes.Serial import Data.Complex import Data.Data import Data.Distributive import Data.Foldable as Foldable import qualified Data.Foldable.WithIndex as WithIndex import Data.Functor.Bind import Data.Functor.Classes import Data.Functor.Rep as Rep import qualified Data.Functor.WithIndex as WithIndex import Data.Hashable import Data.Hashable.Lifted import Data.Kind import Data.Reflection as R import Data.Serialize as Cereal import qualified Data.Traversable.WithIndex as WithIndex import qualified Data.Vector as V import Data.Vector (Vector) import Data.Vector.Fusion.Util (Box(..)) import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Generic.Mutable as M import Foreign.Ptr import Foreign.Storable import GHC.TypeLits import GHC.Generics (Generic, Generic1) #if !(MIN_VERSION_reflection(1,3,0)) && defined(MIN_VERSION_template_haskell) import Language.Haskell.TH #endif import Linear.Epsilon import Linear.Metric import Linear.Vector import Prelude as P #if !(MIN_VERSION_base(4,11,0)) import Data.Semigroup #endif import System.Random (Random(..)) class Dim n where reflectDim :: p n -> Int type role V nominal representational class Finite v where this should allow kind k , for Reifies k Int toV :: v a -> V (Size v) a default toV :: Foldable v => v a -> V (Size v) a toV = V . V.fromList . Foldable.toList fromV :: V (Size v) a -> v a instance Finite Complex where type Size Complex = 2 toV (a :+ b) = V (V.fromListN 2 [a, b]) fromV (V v) = (v V.! 0) :+ (v V.! 1) _V :: (Finite u, Finite v) => Iso (V (Size u) a) (V (Size v) b) (u a) (v b) _V = iso fromV toV _V' :: Finite v => Iso (V (Size v) a) (V (Size v) b) (v a) (v b) _V' = iso fromV toV instance Finite (V (n :: Nat)) where type Size (V n) = n toV = id fromV = id newtype V n a = V { toVector :: V.Vector a } deriving (Eq,Ord,Show,Read,NFData ,Generic,Generic1 ) dim :: forall n a. Dim n => V n a -> Int dim _ = reflectDim (Proxy :: Proxy n) # INLINE dim # instance KnownNat n => Dim (n :: Nat) where reflectDim = fromInteger . natVal # INLINE reflectDim # instance (Dim n, Random a) => Random (V n a) where random = runState (V <$> V.replicateM (reflectDim (Proxy :: Proxy n)) (state random)) randomR (V ls,V hs) = runState (V <$> V.zipWithM (\l h -> state $ randomR (l,h)) ls hs) data ReifiedDim (s :: Type) retagDim :: (Proxy s -> a) -> proxy (ReifiedDim s) -> a retagDim f _ = f Proxy # INLINE retagDim # instance Reifies s Int => Dim (ReifiedDim s) where reflectDim = retagDim reflect # INLINE reflectDim # reifyDimNat :: Int -> (forall (n :: Nat). KnownNat n => Proxy n -> r) -> r reifyDimNat i f = R.reifyNat (fromIntegral i) f # INLINE reifyDimNat # reifyVectorNat :: forall a r. Vector a -> (forall (n :: Nat). KnownNat n => V n a -> r) -> r reifyVectorNat v f = reifyNat (fromIntegral $ V.length v) $ \(Proxy :: Proxy n) -> f (V v :: V n a) # INLINE reifyVectorNat # reifyDim :: Int -> (forall (n :: Type). Dim n => Proxy n -> r) -> r reifyDim i f = R.reify i (go f) where go :: (Proxy (ReifiedDim n) -> a) -> proxy n -> a go g _ = g Proxy # INLINE reifyDim # reifyVector :: forall a r. Vector a -> (forall (n :: Type). Dim n => V n a -> r) -> r reifyVector v f = reifyDim (V.length v) $ \(Proxy :: Proxy n) -> f (V v :: V n a) # INLINE reifyVector # instance Dim n => Dim (V n a) where reflectDim _ = reflectDim (Proxy :: Proxy n) # INLINE reflectDim # instance (Dim n, Semigroup a) => Semigroup (V n a) where (<>) = liftA2 (<>) instance (Dim n, Monoid a) => Monoid (V n a) where mempty = pure mempty #if !(MIN_VERSION_base(4,11,0)) mappend = liftA2 mappend #endif instance Functor (V n) where fmap f (V as) = V (fmap f as) # INLINE fmap # instance WithIndex.FunctorWithIndex Int (V n) where imap f (V as) = V (Lens.imap f as) # INLINE imap # instance Foldable (V n) where fold (V as) = fold as # INLINE fold # foldMap f (V as) = Foldable.foldMap f as {-# INLINE foldMap #-} foldr f z (V as) = V.foldr f z as # INLINE foldr # foldl f z (V as) = V.foldl f z as {-# INLINE foldl #-} foldr' f z (V as) = V.foldr' f z as # INLINE foldr ' # foldl' f z (V as) = V.foldl' f z as {-# INLINE foldl' #-} foldr1 f (V as) = V.foldr1 f as # INLINE foldr1 # foldl1 f (V as) = V.foldl1 f as # INLINE foldl1 # length (V as) = V.length as # INLINE length # null (V as) = V.null as # INLINE null # toList (V as) = V.toList as # INLINE toList # elem a (V as) = V.elem a as # INLINE elem # maximum (V as) = V.maximum as # INLINE maximum # minimum (V as) = V.minimum as # INLINE minimum # sum (V as) = V.sum as # INLINE sum # product (V as) = V.product as # INLINE product # instance WithIndex.FoldableWithIndex Int (V n) where ifoldMap f (V as) = ifoldMap f as # INLINE ifoldMap # instance Traversable (V n) where traverse f (V as) = V <$> traverse f as {-# INLINE traverse #-} instance WithIndex.TraversableWithIndex Int (V n) where itraverse f (V as) = V <$> itraverse f as # INLINE itraverse # #if !MIN_VERSION_lens(5,0,0) instance Lens.FunctorWithIndex Int (V n) where imap = WithIndex.imap instance Lens.FoldableWithIndex Int (V n) where ifoldMap = WithIndex.ifoldMap instance Lens.TraversableWithIndex Int (V n) where itraverse = WithIndex.itraverse #endif instance Apply (V n) where V as <.> V bs = V (V.zipWith id as bs) {-# INLINE (<.>) #-} instance Dim n => Applicative (V n) where pure = V . V.replicate (reflectDim (Proxy :: Proxy n)) # INLINE pure # V as <*> V bs = V (V.zipWith id as bs) {-# INLINE (<*>) #-} instance Bind (V n) where V as >>- f = V $ V.generate (V.length as) $ \i -> toVector (f (as `V.unsafeIndex` i)) `V.unsafeIndex` i {-# INLINE (>>-) #-} instance Dim n => Monad (V n) where #if !(MIN_VERSION_base(4,11,0)) return = V . V.replicate (reflectDim (Proxy :: Proxy n)) # INLINE return # #endif V as >>= f = V $ V.generate (reflectDim (Proxy :: Proxy n)) $ \i -> toVector (f (as `V.unsafeIndex` i)) `V.unsafeIndex` i {-# INLINE (>>=) #-} instance Dim n => Additive (V n) where zero = pure 0 # INLINE zero # liftU2 f (V as) (V bs) = V (V.zipWith f as bs) # INLINE liftU2 # liftI2 f (V as) (V bs) = V (V.zipWith f as bs) # INLINE liftI2 # instance (Dim n, Num a) => Num (V n a) where V as + V bs = V $ V.zipWith (+) as bs {-# INLINE (+) #-} V as - V bs = V $ V.zipWith (-) as bs {-# INLINE (-) #-} V as * V bs = V $ V.zipWith (*) as bs {-# INLINE (*) #-} negate = fmap negate # INLINE negate # abs = fmap abs # INLINE abs # signum = fmap signum # INLINE signum # fromInteger = pure . fromInteger # INLINE fromInteger # instance (Dim n, Fractional a) => Fractional (V n a) where recip = fmap recip # INLINE recip # V as / V bs = V $ V.zipWith (/) as bs {-# INLINE (/) #-} fromRational = pure . fromRational # INLINE fromRational # instance (Dim n, Floating a) => Floating (V n a) where pi = pure pi # INLINE pi # exp = fmap exp # INLINE exp # sqrt = fmap sqrt # INLINE sqrt # log = fmap log # INLINE log # V as ** V bs = V $ V.zipWith (**) as bs {-# INLINE (**) #-} logBase (V as) (V bs) = V $ V.zipWith logBase as bs # INLINE logBase # sin = fmap sin # INLINE sin # tan = fmap tan # INLINE tan # cos = fmap cos # INLINE cos # asin = fmap asin {-# INLINE asin #-} atan = fmap atan # INLINE atan # acos = fmap acos # INLINE acos # sinh = fmap sinh # INLINE sinh # tanh = fmap tanh # INLINE tanh # cosh = fmap cosh # INLINE cosh # asinh = fmap asinh # INLINE asinh # atanh = fmap atanh # INLINE atanh # acosh = fmap acosh # INLINE acosh # instance Dim n => Distributive (V n) where distribute f = V $ V.generate (reflectDim (Proxy :: Proxy n)) $ \i -> fmap (\(V v) -> V.unsafeIndex v i) f {-# INLINE distribute #-} instance Hashable a => Hashable (V n a) where hashWithSalt s0 (V v) = V.foldl' (\s a -> s `hashWithSalt` a) s0 v `hashWithSalt` V.length v instance Dim n => Hashable1 (V n) where liftHashWithSalt h s0 (V v) = V.foldl' (\s a -> h s a) s0 v `hashWithSalt` V.length v # INLINE liftHashWithSalt # instance (Dim n, Storable a) => Storable (V n a) where sizeOf _ = reflectDim (Proxy :: Proxy n) * sizeOf (undefined:: a) # INLINE sizeOf # alignment _ = alignment (undefined :: a) # INLINE alignment # poke ptr (V xs) = Foldable.forM_ [0..reflectDim (Proxy :: Proxy n)-1] $ \i -> pokeElemOff ptr' i (V.unsafeIndex xs i) where ptr' = castPtr ptr # INLINE poke # peek ptr = V <$> V.generateM (reflectDim (Proxy :: Proxy n)) (peekElemOff ptr') where ptr' = castPtr ptr # INLINE peek # instance (Dim n, Epsilon a) => Epsilon (V n a) where nearZero = nearZero . quadrance # INLINE nearZero # instance Dim n => Metric (V n) where dot (V a) (V b) = V.sum $ V.zipWith (*) a b # INLINE dot # -- TODO: instance (Dim n, Ix a) => Ix (V n a) fromVector :: forall n a. Dim n => Vector a -> Maybe (V n a) fromVector v | V.length v == reflectDim (Proxy :: Proxy n) = Just (V v) | otherwise = Nothing #if !(MIN_VERSION_reflection(1,3,0)) && defined(MIN_VERSION_template_haskell) 0 2n 2n+1 2n-1 instance Reifies Z Int where reflect _ = 0 # INLINE reflect # retagD :: (Proxy n -> a) -> proxy (D n) -> a retagD f _ = f Proxy # INLINE retagD # retagSD :: (Proxy n -> a) -> proxy (SD n) -> a retagSD f _ = f Proxy # INLINE retagSD # retagPD :: (Proxy n -> a) -> proxy (PD n) -> a retagPD f _ = f Proxy # INLINE retagPD # instance Reifies n Int => Reifies (D n) Int where reflect = (\n -> n+n) <$> retagD reflect # INLINE reflect # instance Reifies n Int => Reifies (SD n) Int where reflect = (\n -> n+n+1) <$> retagSD reflect # INLINE reflect # instance Reifies n Int => Reifies (PD n) Int where reflect = (\n -> n+n-1) <$> retagPD reflect # INLINE reflect # -- | This can be used to generate a template haskell splice for a type level version of a given 'int'. -- This does not use GHC TypeLits , instead it generates a numeric type by hand similar to the ones used in the \"Functional Pearl : Implicit Dimurations\ " paper by and . int :: Int -> TypeQ int n = case quotRem n 2 of (0, 0) -> conT ''Z (q,-1) -> conT ''PD `appT` int q (q, 0) -> conT ''D `appT` int q (q, 1) -> conT ''SD `appT` int q _ -> error "ghc is bad at math" #endif instance Dim n => Representable (V n) where type Rep (V n) = Int tabulate = V . V.generate (reflectDim (Proxy :: Proxy n)) # INLINE tabulate # index (V xs) i = xs V.! i # INLINE index # type instance Index (V n a) = Int type instance IxValue (V n a) = a instance Ixed (V n a) where ix i f v@(V as) | i < 0 || i >= V.length as = pure v | otherwise = vLens i f v # INLINE ix # instance Dim n => MonadZip (V n) where mzip (V as) (V bs) = V $ V.zip as bs mzipWith f (V as) (V bs) = V $ V.zipWith f as bs instance Dim n => MonadFix (V n) where mfix f = tabulate $ \r -> let a = Rep.index (f a) r in a instance Each (V n a) (V n b) a b where each = traverse # INLINE each # instance (Bounded a, Dim n) => Bounded (V n a) where minBound = pure minBound # INLINE minBound # maxBound = pure maxBound # INLINE maxBound # vConstr :: Constr vConstr = mkConstr vDataType "variadic" [] Prefix # NOINLINE vConstr # vDataType :: DataType vDataType = mkDataType "Linear.V.V" [vConstr] # NOINLINE vDataType # instance (Typeable (V n), Typeable (V n a), Dim n, Data a) => Data (V n a) where gfoldl f z (V as) = z (V . V.fromList) `f` V.toList as toConstr _ = vConstr gunfold k z c = case constrIndex c of 1 -> k (z (V . V.fromList)) _ -> error "gunfold" dataTypeOf _ = vDataType dataCast1 f = gcast1 f instance Dim n => Serial1 (V n) where serializeWith = traverse_ deserializeWith f = sequenceA $ pure f instance (Dim n, Serial a) => Serial (V n a) where serialize = traverse_ serialize deserialize = sequenceA $ pure deserialize instance (Dim n, Binary a) => Binary (V n a) where put = serializeWith Binary.put get = deserializeWith Binary.get instance (Dim n, Serialize a) => Serialize (V n a) where put = serializeWith Cereal.put get = deserializeWith Cereal.get instance Eq1 (V n) where liftEq f0 (V as0) (V bs0) = go f0 (V.toList as0) (V.toList bs0) where go _ [] [] = True go f (a:as) (b:bs) = f a b && go f as bs go _ _ _ = False instance Ord1 (V n) where liftCompare f0 (V as0) (V bs0) = go f0 (V.toList as0) (V.toList bs0) where go f (a:as) (b:bs) = f a b `mappend` go f as bs go _ [] [] = EQ go _ _ [] = GT go _ [] _ = LT instance Show1 (V n) where liftShowsPrec _ g d (V as) = showParen (d > 10) $ showString "V " . g (V.toList as) instance Dim n => Read1 (V n) where liftReadsPrec _ g d = readParen (d > 10) $ \r -> [ (V (V.fromList as), r2) | ("V",r1) <- lex r , (as, r2) <- g r1 , P.length as == reflectDim (Proxy :: Proxy n) ] data instance U.Vector (V n a) = V_VN {-# UNPACK #-} !Int !(U.Vector a) data instance U.MVector s (V n a) = MV_VN {-# UNPACK #-} !Int !(U.MVector s a) instance (Dim n, U.Unbox a) => U.Unbox (V n a) instance (Dim n, U.Unbox a) => M.MVector U.MVector (V n a) where # INLINE basicLength # # INLINE basicUnsafeSlice # # INLINE basicOverlaps # # INLINE basicUnsafeNew # # INLINE basicUnsafeRead # # INLINE basicUnsafeWrite # basicLength (MV_VN n _) = n basicUnsafeSlice m n (MV_VN _ v) = MV_VN n (M.basicUnsafeSlice (d*m) (d*n) v) where d = reflectDim (Proxy :: Proxy n) basicOverlaps (MV_VN _ v) (MV_VN _ u) = M.basicOverlaps v u basicUnsafeNew n = liftM (MV_VN n) (M.basicUnsafeNew (d*n)) where d = reflectDim (Proxy :: Proxy n) basicUnsafeRead (MV_VN _ v) i = liftM V $ V.generateM d (\j -> M.basicUnsafeRead v (d*i+j)) where d = reflectDim (Proxy :: Proxy n) basicUnsafeWrite (MV_VN _ v0) i (V vn0) = let d0 = V.length vn0 in go v0 vn0 d0 (d0*i) 0 where go v vn d o j | j >= d = return () | otherwise = do a <- liftBox $ G.basicUnsafeIndexM vn j M.basicUnsafeWrite v o a go v vn d (o+1) (j+1) basicInitialize (MV_VN _ v) = M.basicInitialize v # INLINE basicInitialize # liftBox :: Monad m => Box a -> m a liftBox (Box a) = return a # INLINE liftBox # instance (Dim n, U.Unbox a) => G.Vector U.Vector (V n a) where # INLINE basicUnsafeFreeze # {-# INLINE basicUnsafeThaw #-} # INLINE basicLength # # INLINE basicUnsafeSlice # # INLINE basicUnsafeIndexM # basicUnsafeFreeze (MV_VN n v) = liftM ( V_VN n) (G.basicUnsafeFreeze v) basicUnsafeThaw ( V_VN n v) = liftM (MV_VN n) (G.basicUnsafeThaw v) basicLength ( V_VN n _) = n basicUnsafeSlice m n (V_VN _ v) = V_VN n (G.basicUnsafeSlice (d*m) (d*n) v) where d = reflectDim (Proxy :: Proxy n) basicUnsafeIndexM (V_VN _ v) i = liftM V $ V.generateM d (\j -> G.basicUnsafeIndexM v (d*i+j)) where d = reflectDim (Proxy :: Proxy n) vLens :: Int -> Lens' (V n a) a vLens i = \f (V v) -> f (v V.! i) <&> \a -> V (v V.// [(i, a)]) # INLINE vLens # instance ( 1 <= n) => Field1 (V n a) (V n a) a a where _1 = vLens 0 instance ( 2 <= n) => Field2 (V n a) (V n a) a a where _2 = vLens 1 instance ( 3 <= n) => Field3 (V n a) (V n a) a a where _3 = vLens 2 instance ( 4 <= n) => Field4 (V n a) (V n a) a a where _4 = vLens 3 instance ( 5 <= n) => Field5 (V n a) (V n a) a a where _5 = vLens 4 instance ( 6 <= n) => Field6 (V n a) (V n a) a a where _6 = vLens 5 instance ( 7 <= n) => Field7 (V n a) (V n a) a a where _7 = vLens 6 instance ( 8 <= n) => Field8 (V n a) (V n a) a a where _8 = vLens 7 instance ( 9 <= n) => Field9 (V n a) (V n a) a a where _9 = vLens 8 instance (10 <= n) => Field10 (V n a) (V n a) a a where _10 = vLens 9 instance (11 <= n) => Field11 (V n a) (V n a) a a where _11 = vLens 10 instance (12 <= n) => Field12 (V n a) (V n a) a a where _12 = vLens 11 instance (13 <= n) => Field13 (V n a) (V n a) a a where _13 = vLens 12 instance (14 <= n) => Field14 (V n a) (V n a) a a where _14 = vLens 13 instance (15 <= n) => Field15 (V n a) (V n a) a a where _15 = vLens 14 instance (16 <= n) => Field16 (V n a) (V n a) a a where _16 = vLens 15 instance (17 <= n) => Field17 (V n a) (V n a) a a where _17 = vLens 16 instance (18 <= n) => Field18 (V n a) (V n a) a a where _18 = vLens 17 instance (19 <= n) => Field19 (V n a) (V n a) a a where _19 = vLens 18
null
https://raw.githubusercontent.com/ekmett/linear/7dbe6a55d68311320ca2994ca700392abe938114/src/Linear/V.hs
haskell
# LANGUAGE Rank2Types # # LANGUAGE EmptyDataDecls # # LANGUAGE DeriveDataTypeable # --------------------------------------------------------------------------- | License : BSD-style (see the file LICENSE) Stability : experimental Portability : non-portable n-D Vectors -------------------------------------------------------------------------- # INLINE foldMap # # INLINE foldl # # INLINE foldl' # # INLINE traverse # # INLINE (<.>) # # INLINE (<*>) # # INLINE (>>-) # # INLINE (>>=) # # INLINE (+) # # INLINE (-) # # INLINE (*) # # INLINE (/) # # INLINE (**) # # INLINE asin # # INLINE distribute # TODO: instance (Dim n, Ix a) => Ix (V n a) | This can be used to generate a template haskell splice for a type level version of a given 'int'. # UNPACK # # UNPACK # # INLINE basicUnsafeThaw #
# LANGUAGE CPP # # LANGUAGE TypeOperators # # LANGUAGE KindSignatures # # LANGUAGE ScopedTypeVariables # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE DefaultSignatures # # LANGUAGE TypeFamilies # # LANGUAGE MultiParamTypeClasses , FlexibleContexts , FlexibleInstances , UndecidableInstances # # LANGUAGE DataKinds # # LANGUAGE PolyKinds # # LANGUAGE RoleAnnotations # # LANGUAGE Trustworthy # # LANGUAGE DeriveGeneric # #ifndef MIN_VERSION_hashable #define MIN_VERSION_hashable(x,y,z) 1 #endif #ifndef MIN_VERSION_reflection #define MIN_VERSION_reflection(x,y,z) 1 #endif #ifndef MIN_VERSION_transformers #define MIN_VERSION_transformers(x,y,z) 1 #endif #ifndef MIN_VERSION_base #define MIN_VERSION_base(x,y,z) 1 #endif Copyright : ( C ) 2012 - 2015 Maintainer : < > module Linear.V ( V(V,toVector) #ifdef MIN_VERSION_template_haskell , int #endif , dim , Dim(..) , reifyDim , reifyVector , reifyDimNat , reifyVectorNat , fromVector , Finite(..) , _V, _V' ) where import Control.Applicative import Control.DeepSeq (NFData) import Control.Monad import Control.Monad.Fix import Control.Monad.Trans.State import Control.Monad.Zip import Control.Lens as Lens import Data.Binary as Binary import Data.Bytes.Serial import Data.Complex import Data.Data import Data.Distributive import Data.Foldable as Foldable import qualified Data.Foldable.WithIndex as WithIndex import Data.Functor.Bind import Data.Functor.Classes import Data.Functor.Rep as Rep import qualified Data.Functor.WithIndex as WithIndex import Data.Hashable import Data.Hashable.Lifted import Data.Kind import Data.Reflection as R import Data.Serialize as Cereal import qualified Data.Traversable.WithIndex as WithIndex import qualified Data.Vector as V import Data.Vector (Vector) import Data.Vector.Fusion.Util (Box(..)) import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Generic.Mutable as M import Foreign.Ptr import Foreign.Storable import GHC.TypeLits import GHC.Generics (Generic, Generic1) #if !(MIN_VERSION_reflection(1,3,0)) && defined(MIN_VERSION_template_haskell) import Language.Haskell.TH #endif import Linear.Epsilon import Linear.Metric import Linear.Vector import Prelude as P #if !(MIN_VERSION_base(4,11,0)) import Data.Semigroup #endif import System.Random (Random(..)) class Dim n where reflectDim :: p n -> Int type role V nominal representational class Finite v where this should allow kind k , for Reifies k Int toV :: v a -> V (Size v) a default toV :: Foldable v => v a -> V (Size v) a toV = V . V.fromList . Foldable.toList fromV :: V (Size v) a -> v a instance Finite Complex where type Size Complex = 2 toV (a :+ b) = V (V.fromListN 2 [a, b]) fromV (V v) = (v V.! 0) :+ (v V.! 1) _V :: (Finite u, Finite v) => Iso (V (Size u) a) (V (Size v) b) (u a) (v b) _V = iso fromV toV _V' :: Finite v => Iso (V (Size v) a) (V (Size v) b) (v a) (v b) _V' = iso fromV toV instance Finite (V (n :: Nat)) where type Size (V n) = n toV = id fromV = id newtype V n a = V { toVector :: V.Vector a } deriving (Eq,Ord,Show,Read,NFData ,Generic,Generic1 ) dim :: forall n a. Dim n => V n a -> Int dim _ = reflectDim (Proxy :: Proxy n) # INLINE dim # instance KnownNat n => Dim (n :: Nat) where reflectDim = fromInteger . natVal # INLINE reflectDim # instance (Dim n, Random a) => Random (V n a) where random = runState (V <$> V.replicateM (reflectDim (Proxy :: Proxy n)) (state random)) randomR (V ls,V hs) = runState (V <$> V.zipWithM (\l h -> state $ randomR (l,h)) ls hs) data ReifiedDim (s :: Type) retagDim :: (Proxy s -> a) -> proxy (ReifiedDim s) -> a retagDim f _ = f Proxy # INLINE retagDim # instance Reifies s Int => Dim (ReifiedDim s) where reflectDim = retagDim reflect # INLINE reflectDim # reifyDimNat :: Int -> (forall (n :: Nat). KnownNat n => Proxy n -> r) -> r reifyDimNat i f = R.reifyNat (fromIntegral i) f # INLINE reifyDimNat # reifyVectorNat :: forall a r. Vector a -> (forall (n :: Nat). KnownNat n => V n a -> r) -> r reifyVectorNat v f = reifyNat (fromIntegral $ V.length v) $ \(Proxy :: Proxy n) -> f (V v :: V n a) # INLINE reifyVectorNat # reifyDim :: Int -> (forall (n :: Type). Dim n => Proxy n -> r) -> r reifyDim i f = R.reify i (go f) where go :: (Proxy (ReifiedDim n) -> a) -> proxy n -> a go g _ = g Proxy # INLINE reifyDim # reifyVector :: forall a r. Vector a -> (forall (n :: Type). Dim n => V n a -> r) -> r reifyVector v f = reifyDim (V.length v) $ \(Proxy :: Proxy n) -> f (V v :: V n a) # INLINE reifyVector # instance Dim n => Dim (V n a) where reflectDim _ = reflectDim (Proxy :: Proxy n) # INLINE reflectDim # instance (Dim n, Semigroup a) => Semigroup (V n a) where (<>) = liftA2 (<>) instance (Dim n, Monoid a) => Monoid (V n a) where mempty = pure mempty #if !(MIN_VERSION_base(4,11,0)) mappend = liftA2 mappend #endif instance Functor (V n) where fmap f (V as) = V (fmap f as) # INLINE fmap # instance WithIndex.FunctorWithIndex Int (V n) where imap f (V as) = V (Lens.imap f as) # INLINE imap # instance Foldable (V n) where fold (V as) = fold as # INLINE fold # foldMap f (V as) = Foldable.foldMap f as foldr f z (V as) = V.foldr f z as # INLINE foldr # foldl f z (V as) = V.foldl f z as foldr' f z (V as) = V.foldr' f z as # INLINE foldr ' # foldl' f z (V as) = V.foldl' f z as foldr1 f (V as) = V.foldr1 f as # INLINE foldr1 # foldl1 f (V as) = V.foldl1 f as # INLINE foldl1 # length (V as) = V.length as # INLINE length # null (V as) = V.null as # INLINE null # toList (V as) = V.toList as # INLINE toList # elem a (V as) = V.elem a as # INLINE elem # maximum (V as) = V.maximum as # INLINE maximum # minimum (V as) = V.minimum as # INLINE minimum # sum (V as) = V.sum as # INLINE sum # product (V as) = V.product as # INLINE product # instance WithIndex.FoldableWithIndex Int (V n) where ifoldMap f (V as) = ifoldMap f as # INLINE ifoldMap # instance Traversable (V n) where traverse f (V as) = V <$> traverse f as instance WithIndex.TraversableWithIndex Int (V n) where itraverse f (V as) = V <$> itraverse f as # INLINE itraverse # #if !MIN_VERSION_lens(5,0,0) instance Lens.FunctorWithIndex Int (V n) where imap = WithIndex.imap instance Lens.FoldableWithIndex Int (V n) where ifoldMap = WithIndex.ifoldMap instance Lens.TraversableWithIndex Int (V n) where itraverse = WithIndex.itraverse #endif instance Apply (V n) where V as <.> V bs = V (V.zipWith id as bs) instance Dim n => Applicative (V n) where pure = V . V.replicate (reflectDim (Proxy :: Proxy n)) # INLINE pure # V as <*> V bs = V (V.zipWith id as bs) instance Bind (V n) where V as >>- f = V $ V.generate (V.length as) $ \i -> toVector (f (as `V.unsafeIndex` i)) `V.unsafeIndex` i instance Dim n => Monad (V n) where #if !(MIN_VERSION_base(4,11,0)) return = V . V.replicate (reflectDim (Proxy :: Proxy n)) # INLINE return # #endif V as >>= f = V $ V.generate (reflectDim (Proxy :: Proxy n)) $ \i -> toVector (f (as `V.unsafeIndex` i)) `V.unsafeIndex` i instance Dim n => Additive (V n) where zero = pure 0 # INLINE zero # liftU2 f (V as) (V bs) = V (V.zipWith f as bs) # INLINE liftU2 # liftI2 f (V as) (V bs) = V (V.zipWith f as bs) # INLINE liftI2 # instance (Dim n, Num a) => Num (V n a) where V as + V bs = V $ V.zipWith (+) as bs V as - V bs = V $ V.zipWith (-) as bs V as * V bs = V $ V.zipWith (*) as bs negate = fmap negate # INLINE negate # abs = fmap abs # INLINE abs # signum = fmap signum # INLINE signum # fromInteger = pure . fromInteger # INLINE fromInteger # instance (Dim n, Fractional a) => Fractional (V n a) where recip = fmap recip # INLINE recip # V as / V bs = V $ V.zipWith (/) as bs fromRational = pure . fromRational # INLINE fromRational # instance (Dim n, Floating a) => Floating (V n a) where pi = pure pi # INLINE pi # exp = fmap exp # INLINE exp # sqrt = fmap sqrt # INLINE sqrt # log = fmap log # INLINE log # V as ** V bs = V $ V.zipWith (**) as bs logBase (V as) (V bs) = V $ V.zipWith logBase as bs # INLINE logBase # sin = fmap sin # INLINE sin # tan = fmap tan # INLINE tan # cos = fmap cos # INLINE cos # asin = fmap asin atan = fmap atan # INLINE atan # acos = fmap acos # INLINE acos # sinh = fmap sinh # INLINE sinh # tanh = fmap tanh # INLINE tanh # cosh = fmap cosh # INLINE cosh # asinh = fmap asinh # INLINE asinh # atanh = fmap atanh # INLINE atanh # acosh = fmap acosh # INLINE acosh # instance Dim n => Distributive (V n) where distribute f = V $ V.generate (reflectDim (Proxy :: Proxy n)) $ \i -> fmap (\(V v) -> V.unsafeIndex v i) f instance Hashable a => Hashable (V n a) where hashWithSalt s0 (V v) = V.foldl' (\s a -> s `hashWithSalt` a) s0 v `hashWithSalt` V.length v instance Dim n => Hashable1 (V n) where liftHashWithSalt h s0 (V v) = V.foldl' (\s a -> h s a) s0 v `hashWithSalt` V.length v # INLINE liftHashWithSalt # instance (Dim n, Storable a) => Storable (V n a) where sizeOf _ = reflectDim (Proxy :: Proxy n) * sizeOf (undefined:: a) # INLINE sizeOf # alignment _ = alignment (undefined :: a) # INLINE alignment # poke ptr (V xs) = Foldable.forM_ [0..reflectDim (Proxy :: Proxy n)-1] $ \i -> pokeElemOff ptr' i (V.unsafeIndex xs i) where ptr' = castPtr ptr # INLINE poke # peek ptr = V <$> V.generateM (reflectDim (Proxy :: Proxy n)) (peekElemOff ptr') where ptr' = castPtr ptr # INLINE peek # instance (Dim n, Epsilon a) => Epsilon (V n a) where nearZero = nearZero . quadrance # INLINE nearZero # instance Dim n => Metric (V n) where dot (V a) (V b) = V.sum $ V.zipWith (*) a b # INLINE dot # fromVector :: forall n a. Dim n => Vector a -> Maybe (V n a) fromVector v | V.length v == reflectDim (Proxy :: Proxy n) = Just (V v) | otherwise = Nothing #if !(MIN_VERSION_reflection(1,3,0)) && defined(MIN_VERSION_template_haskell) 0 2n 2n+1 2n-1 instance Reifies Z Int where reflect _ = 0 # INLINE reflect # retagD :: (Proxy n -> a) -> proxy (D n) -> a retagD f _ = f Proxy # INLINE retagD # retagSD :: (Proxy n -> a) -> proxy (SD n) -> a retagSD f _ = f Proxy # INLINE retagSD # retagPD :: (Proxy n -> a) -> proxy (PD n) -> a retagPD f _ = f Proxy # INLINE retagPD # instance Reifies n Int => Reifies (D n) Int where reflect = (\n -> n+n) <$> retagD reflect # INLINE reflect # instance Reifies n Int => Reifies (SD n) Int where reflect = (\n -> n+n+1) <$> retagSD reflect # INLINE reflect # instance Reifies n Int => Reifies (PD n) Int where reflect = (\n -> n+n-1) <$> retagPD reflect # INLINE reflect # This does not use GHC TypeLits , instead it generates a numeric type by hand similar to the ones used in the \"Functional Pearl : Implicit Dimurations\ " paper by and . int :: Int -> TypeQ int n = case quotRem n 2 of (0, 0) -> conT ''Z (q,-1) -> conT ''PD `appT` int q (q, 0) -> conT ''D `appT` int q (q, 1) -> conT ''SD `appT` int q _ -> error "ghc is bad at math" #endif instance Dim n => Representable (V n) where type Rep (V n) = Int tabulate = V . V.generate (reflectDim (Proxy :: Proxy n)) # INLINE tabulate # index (V xs) i = xs V.! i # INLINE index # type instance Index (V n a) = Int type instance IxValue (V n a) = a instance Ixed (V n a) where ix i f v@(V as) | i < 0 || i >= V.length as = pure v | otherwise = vLens i f v # INLINE ix # instance Dim n => MonadZip (V n) where mzip (V as) (V bs) = V $ V.zip as bs mzipWith f (V as) (V bs) = V $ V.zipWith f as bs instance Dim n => MonadFix (V n) where mfix f = tabulate $ \r -> let a = Rep.index (f a) r in a instance Each (V n a) (V n b) a b where each = traverse # INLINE each # instance (Bounded a, Dim n) => Bounded (V n a) where minBound = pure minBound # INLINE minBound # maxBound = pure maxBound # INLINE maxBound # vConstr :: Constr vConstr = mkConstr vDataType "variadic" [] Prefix # NOINLINE vConstr # vDataType :: DataType vDataType = mkDataType "Linear.V.V" [vConstr] # NOINLINE vDataType # instance (Typeable (V n), Typeable (V n a), Dim n, Data a) => Data (V n a) where gfoldl f z (V as) = z (V . V.fromList) `f` V.toList as toConstr _ = vConstr gunfold k z c = case constrIndex c of 1 -> k (z (V . V.fromList)) _ -> error "gunfold" dataTypeOf _ = vDataType dataCast1 f = gcast1 f instance Dim n => Serial1 (V n) where serializeWith = traverse_ deserializeWith f = sequenceA $ pure f instance (Dim n, Serial a) => Serial (V n a) where serialize = traverse_ serialize deserialize = sequenceA $ pure deserialize instance (Dim n, Binary a) => Binary (V n a) where put = serializeWith Binary.put get = deserializeWith Binary.get instance (Dim n, Serialize a) => Serialize (V n a) where put = serializeWith Cereal.put get = deserializeWith Cereal.get instance Eq1 (V n) where liftEq f0 (V as0) (V bs0) = go f0 (V.toList as0) (V.toList bs0) where go _ [] [] = True go f (a:as) (b:bs) = f a b && go f as bs go _ _ _ = False instance Ord1 (V n) where liftCompare f0 (V as0) (V bs0) = go f0 (V.toList as0) (V.toList bs0) where go f (a:as) (b:bs) = f a b `mappend` go f as bs go _ [] [] = EQ go _ _ [] = GT go _ [] _ = LT instance Show1 (V n) where liftShowsPrec _ g d (V as) = showParen (d > 10) $ showString "V " . g (V.toList as) instance Dim n => Read1 (V n) where liftReadsPrec _ g d = readParen (d > 10) $ \r -> [ (V (V.fromList as), r2) | ("V",r1) <- lex r , (as, r2) <- g r1 , P.length as == reflectDim (Proxy :: Proxy n) ] instance (Dim n, U.Unbox a) => U.Unbox (V n a) instance (Dim n, U.Unbox a) => M.MVector U.MVector (V n a) where # INLINE basicLength # # INLINE basicUnsafeSlice # # INLINE basicOverlaps # # INLINE basicUnsafeNew # # INLINE basicUnsafeRead # # INLINE basicUnsafeWrite # basicLength (MV_VN n _) = n basicUnsafeSlice m n (MV_VN _ v) = MV_VN n (M.basicUnsafeSlice (d*m) (d*n) v) where d = reflectDim (Proxy :: Proxy n) basicOverlaps (MV_VN _ v) (MV_VN _ u) = M.basicOverlaps v u basicUnsafeNew n = liftM (MV_VN n) (M.basicUnsafeNew (d*n)) where d = reflectDim (Proxy :: Proxy n) basicUnsafeRead (MV_VN _ v) i = liftM V $ V.generateM d (\j -> M.basicUnsafeRead v (d*i+j)) where d = reflectDim (Proxy :: Proxy n) basicUnsafeWrite (MV_VN _ v0) i (V vn0) = let d0 = V.length vn0 in go v0 vn0 d0 (d0*i) 0 where go v vn d o j | j >= d = return () | otherwise = do a <- liftBox $ G.basicUnsafeIndexM vn j M.basicUnsafeWrite v o a go v vn d (o+1) (j+1) basicInitialize (MV_VN _ v) = M.basicInitialize v # INLINE basicInitialize # liftBox :: Monad m => Box a -> m a liftBox (Box a) = return a # INLINE liftBox # instance (Dim n, U.Unbox a) => G.Vector U.Vector (V n a) where # INLINE basicUnsafeFreeze # # INLINE basicLength # # INLINE basicUnsafeSlice # # INLINE basicUnsafeIndexM # basicUnsafeFreeze (MV_VN n v) = liftM ( V_VN n) (G.basicUnsafeFreeze v) basicUnsafeThaw ( V_VN n v) = liftM (MV_VN n) (G.basicUnsafeThaw v) basicLength ( V_VN n _) = n basicUnsafeSlice m n (V_VN _ v) = V_VN n (G.basicUnsafeSlice (d*m) (d*n) v) where d = reflectDim (Proxy :: Proxy n) basicUnsafeIndexM (V_VN _ v) i = liftM V $ V.generateM d (\j -> G.basicUnsafeIndexM v (d*i+j)) where d = reflectDim (Proxy :: Proxy n) vLens :: Int -> Lens' (V n a) a vLens i = \f (V v) -> f (v V.! i) <&> \a -> V (v V.// [(i, a)]) # INLINE vLens # instance ( 1 <= n) => Field1 (V n a) (V n a) a a where _1 = vLens 0 instance ( 2 <= n) => Field2 (V n a) (V n a) a a where _2 = vLens 1 instance ( 3 <= n) => Field3 (V n a) (V n a) a a where _3 = vLens 2 instance ( 4 <= n) => Field4 (V n a) (V n a) a a where _4 = vLens 3 instance ( 5 <= n) => Field5 (V n a) (V n a) a a where _5 = vLens 4 instance ( 6 <= n) => Field6 (V n a) (V n a) a a where _6 = vLens 5 instance ( 7 <= n) => Field7 (V n a) (V n a) a a where _7 = vLens 6 instance ( 8 <= n) => Field8 (V n a) (V n a) a a where _8 = vLens 7 instance ( 9 <= n) => Field9 (V n a) (V n a) a a where _9 = vLens 8 instance (10 <= n) => Field10 (V n a) (V n a) a a where _10 = vLens 9 instance (11 <= n) => Field11 (V n a) (V n a) a a where _11 = vLens 10 instance (12 <= n) => Field12 (V n a) (V n a) a a where _12 = vLens 11 instance (13 <= n) => Field13 (V n a) (V n a) a a where _13 = vLens 12 instance (14 <= n) => Field14 (V n a) (V n a) a a where _14 = vLens 13 instance (15 <= n) => Field15 (V n a) (V n a) a a where _15 = vLens 14 instance (16 <= n) => Field16 (V n a) (V n a) a a where _16 = vLens 15 instance (17 <= n) => Field17 (V n a) (V n a) a a where _17 = vLens 16 instance (18 <= n) => Field18 (V n a) (V n a) a a where _18 = vLens 17 instance (19 <= n) => Field19 (V n a) (V n a) a a where _19 = vLens 18
af2d8b1b6a9ca27a7c32d10a8286e4eab94ac6bbcc35d25507f21d5b4d748e3e
dnadales/sandbox
BinTree.hs
-- | A binary tree. module Data.BinTree where import Control.Monad.State import Data.Functor.Fixedpoint data BinTree a = Nil | Fork a (BinTree a) (BinTree a) deriving (Show, Eq) -- | Computes the leaves of a binary tree by straightforward recursion, -- using lists. leaves :: BinTree a -> [a] leaves Nil = [] leaves (Fork x Nil Nil) = [x] leaves (Fork _ lt rt) = leaves lt ++ leaves rt leavesT :: BinTree a -> [a] leavesT = leavesT' [] where leavesT' xs Nil = xs leavesT' xs (Fork x Nil Nil) = x : xs leavesT' xs (Fork _ lt rt) = leavesT' (leavesT' xs lt) rt -- | Recursion using difference lists. leavesC :: BinTree a -> [a] -> [a] leavesC Nil = id leavesC (Fork x Nil Nil) = \xs -> x : xs leavesC (Fork _ lt rt) = leavesC lt . leavesC rt -- | Computes the leaves of a binary tree by straightforward recursion, -- using difference lists. leaves' :: BinTree a -> [a] leaves' t = leavesC t [] -- | Compute the leaves in a state monad. leavesS :: BinTree a -> [a] leavesS t = execState (leavesS' t) [] where leavesS' :: BinTree a -> State [a] () leavesS' Nil = return () leavesS' (Fork x Nil Nil) = modify (\xs -> x:xs) leavesS' (Fork _ lt rt) = leavesS' lt >> leavesS' rt -- | Generate a tree from a list. mkTree :: [a] -> BinTree a mkTree [] = Nil mkTree (x:xs) = Fork x (mkTree lxs) (mkTree rxs) where (lxs, rxs) = splitAt ((length xs + 1) `div` 2) xs -- | Functor whose fixed point is a binary tree. data BinTreeF a b = NilF | ForkF a b b instance Functor (BinTreeF a) where fmap f NilF = NilF fmap f (ForkF x lt rt) = ForkF x (f lt) (f rt) -- | Same as BinTree, but defined as a fixed point of a functor. type BinTreeE a = Fix (BinTreeF a) toBinTreeE :: BinTree a -> BinTreeE a toBinTreeE Nil = Fix NilF toBinTreeE (Fork val lt rt) = Fix (ForkF val (toBinTreeE lt) (toBinTreeE rt)) mkTreeE :: [a] -> BinTreeE a mkTreeE = toBinTreeE . mkTree -- | Leaf enumeration routine implemented as a catamorphism. leavesCata :: BinTreeE a -> [a] leavesCata = cata gatherLeaves where gatherLeaves :: BinTreeF a [a] -> [a] gatherLeaves NilF = [] gatherLeaves (ForkF x [] []) = [x] gatherLeaves (ForkF _ xs ys) = xs ++ ys
null
https://raw.githubusercontent.com/dnadales/sandbox/401c4f0fac5f8044fb6e2e443bacddce6f135b4b/leaves-of-a-tree/src/Data/BinTree.hs
haskell
| A binary tree. | Computes the leaves of a binary tree by straightforward recursion, using lists. | Recursion using difference lists. | Computes the leaves of a binary tree by straightforward recursion, using difference lists. | Compute the leaves in a state monad. | Generate a tree from a list. | Functor whose fixed point is a binary tree. | Same as BinTree, but defined as a fixed point of a functor. | Leaf enumeration routine implemented as a catamorphism.
module Data.BinTree where import Control.Monad.State import Data.Functor.Fixedpoint data BinTree a = Nil | Fork a (BinTree a) (BinTree a) deriving (Show, Eq) leaves :: BinTree a -> [a] leaves Nil = [] leaves (Fork x Nil Nil) = [x] leaves (Fork _ lt rt) = leaves lt ++ leaves rt leavesT :: BinTree a -> [a] leavesT = leavesT' [] where leavesT' xs Nil = xs leavesT' xs (Fork x Nil Nil) = x : xs leavesT' xs (Fork _ lt rt) = leavesT' (leavesT' xs lt) rt leavesC :: BinTree a -> [a] -> [a] leavesC Nil = id leavesC (Fork x Nil Nil) = \xs -> x : xs leavesC (Fork _ lt rt) = leavesC lt . leavesC rt leaves' :: BinTree a -> [a] leaves' t = leavesC t [] leavesS :: BinTree a -> [a] leavesS t = execState (leavesS' t) [] where leavesS' :: BinTree a -> State [a] () leavesS' Nil = return () leavesS' (Fork x Nil Nil) = modify (\xs -> x:xs) leavesS' (Fork _ lt rt) = leavesS' lt >> leavesS' rt mkTree :: [a] -> BinTree a mkTree [] = Nil mkTree (x:xs) = Fork x (mkTree lxs) (mkTree rxs) where (lxs, rxs) = splitAt ((length xs + 1) `div` 2) xs data BinTreeF a b = NilF | ForkF a b b instance Functor (BinTreeF a) where fmap f NilF = NilF fmap f (ForkF x lt rt) = ForkF x (f lt) (f rt) type BinTreeE a = Fix (BinTreeF a) toBinTreeE :: BinTree a -> BinTreeE a toBinTreeE Nil = Fix NilF toBinTreeE (Fork val lt rt) = Fix (ForkF val (toBinTreeE lt) (toBinTreeE rt)) mkTreeE :: [a] -> BinTreeE a mkTreeE = toBinTreeE . mkTree leavesCata :: BinTreeE a -> [a] leavesCata = cata gatherLeaves where gatherLeaves :: BinTreeF a [a] -> [a] gatherLeaves NilF = [] gatherLeaves (ForkF x [] []) = [x] gatherLeaves (ForkF _ xs ys) = xs ++ ys
9c1da99e67759914b0a49c243150bc5b816e9b8342df995a24216fd6cb30ad4c
RichiH/git-annex
MagicWormhole.hs
Magic Wormhole integration - - Copyright 2016 < > - - License : BSD-2 - clause - - Copyright 2016 Joey Hess <> - - License: BSD-2-clause -} module Utility.MagicWormhole ( Code, mkCode, toCode, fromCode, validCode, CodeObserver, CodeProducer, mkCodeObserver, mkCodeProducer, waitCode, sendCode, WormHoleParams, appId, sendFile, receiveFile, isInstalled, ) where import Utility.Process import Utility.SafeCommand import Utility.Monad import Utility.Misc import Utility.Env import Utility.Path import System.IO import System.Exit import Control.Concurrent import Control.Exception import Data.Char import Data.List import Control.Applicative import Prelude -- | A Magic Wormhole code. newtype Code = Code String deriving (Eq, Show) -- | Smart constructor for Code mkCode :: String -> Maybe Code mkCode s | validCode s = Just (Code s) | otherwise = Nothing | Tries to fix up some common mistakes in a homan - entered code . toCode :: String -> Maybe Code toCode s = mkCode $ intercalate "-" $ words s fromCode :: Code -> String fromCode (Code s) = s | Codes have the form number - word - word and may contain 2 or more words . validCode :: String -> Bool validCode s = let (n, r) = separate (== '-') s (w1, w2) = separate (== '-') r in and [ not (null n) , all isDigit n , not (null w1) , not (null w2) , not $ any isSpace s ] newtype CodeObserver = CodeObserver (MVar Code) newtype CodeProducer = CodeProducer (MVar Code) mkCodeObserver :: IO CodeObserver mkCodeObserver = CodeObserver <$> newEmptyMVar mkCodeProducer :: IO CodeProducer mkCodeProducer = CodeProducer <$> newEmptyMVar waitCode :: CodeObserver -> IO Code waitCode (CodeObserver o) = readMVar o sendCode :: CodeProducer -> Code -> IO () sendCode (CodeProducer p) = putMVar p type WormHoleParams = [CommandParam] -- | An appid should be provided when using wormhole in an app, to avoid -- using the same channel space as ad-hoc wormhole users. appId :: String -> WormHoleParams appId s = [Param "--appid", Param s] | Sends a file . Once the send is underway , and the Code has been generated , it will be sent to the CodeObserver . ( This may not happen , -- eg if there's a network problem). -- -- Currently this has to parse the output of wormhole to find the code. -- To make this as robust as possible, avoids looking for any particular -- output strings, and only looks for the form of a wormhole code -- (number-word-word). -- Note that , if the filename looks like " foo 1 - wormhole - code bar " , when -- that is output by wormhole, it will look like it's output a wormhole code. -- -- A request to make the code available in machine-parsable form is here: -- -wormhole/issues/104 sendFile :: FilePath -> CodeObserver -> WormHoleParams -> IO Bool sendFile f (CodeObserver observer) ps = do -- Work around stupid stdout buffering behavior of python. See -wormhole/issues/108 environ <- addEntry "PYTHONUNBUFFERED" "1" <$> getEnvironment runWormHoleProcess p { env = Just environ} $ \_hin hout -> findcode =<< words <$> hGetContents hout where p = wormHoleProcess (Param "send" : ps ++ [File f]) findcode [] = return False findcode (w:ws) = case mkCode w of Just code -> do putMVar observer code return True Nothing -> findcode ws | Receives a file . Once the receive is under way , the Code will be read from the , and fed to wormhole on stdin . receiveFile :: FilePath -> CodeProducer -> WormHoleParams -> IO Bool receiveFile f (CodeProducer producer) ps = runWormHoleProcess p $ \hin _hout -> do Code c <- readMVar producer hPutStrLn hin c hFlush hin return True where p = wormHoleProcess $ [ Param "receive" , Param "--accept-file" , Param "--output-file" , File f ] ++ ps wormHoleProcess :: WormHoleParams -> CreateProcess wormHoleProcess = proc "wormhole" . toCommand runWormHoleProcess :: CreateProcess -> (Handle -> Handle -> IO Bool) -> IO Bool runWormHoleProcess p consumer = bracketOnError setup (\v -> cleanup v <&&> return False) go where setup = do (Just hin, Just hout, Nothing, pid) <- createProcess p { std_in = CreatePipe , std_out = CreatePipe } return (hin, hout, pid) cleanup (hin, hout, pid) = do r <- waitForProcess pid hClose hin hClose hout return $ case r of ExitSuccess -> True ExitFailure _ -> False go h@(hin, hout, _) = consumer hin hout <&&> cleanup h isInstalled :: IO Bool isInstalled = inPath "wormhole"
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Utility/MagicWormhole.hs
haskell
| A Magic Wormhole code. | Smart constructor for Code | An appid should be provided when using wormhole in an app, to avoid using the same channel space as ad-hoc wormhole users. eg if there's a network problem). Currently this has to parse the output of wormhole to find the code. To make this as robust as possible, avoids looking for any particular output strings, and only looks for the form of a wormhole code (number-word-word). that is output by wormhole, it will look like it's output a wormhole code. A request to make the code available in machine-parsable form is here: -wormhole/issues/104 Work around stupid stdout buffering behavior of python.
Magic Wormhole integration - - Copyright 2016 < > - - License : BSD-2 - clause - - Copyright 2016 Joey Hess <> - - License: BSD-2-clause -} module Utility.MagicWormhole ( Code, mkCode, toCode, fromCode, validCode, CodeObserver, CodeProducer, mkCodeObserver, mkCodeProducer, waitCode, sendCode, WormHoleParams, appId, sendFile, receiveFile, isInstalled, ) where import Utility.Process import Utility.SafeCommand import Utility.Monad import Utility.Misc import Utility.Env import Utility.Path import System.IO import System.Exit import Control.Concurrent import Control.Exception import Data.Char import Data.List import Control.Applicative import Prelude newtype Code = Code String deriving (Eq, Show) mkCode :: String -> Maybe Code mkCode s | validCode s = Just (Code s) | otherwise = Nothing | Tries to fix up some common mistakes in a homan - entered code . toCode :: String -> Maybe Code toCode s = mkCode $ intercalate "-" $ words s fromCode :: Code -> String fromCode (Code s) = s | Codes have the form number - word - word and may contain 2 or more words . validCode :: String -> Bool validCode s = let (n, r) = separate (== '-') s (w1, w2) = separate (== '-') r in and [ not (null n) , all isDigit n , not (null w1) , not (null w2) , not $ any isSpace s ] newtype CodeObserver = CodeObserver (MVar Code) newtype CodeProducer = CodeProducer (MVar Code) mkCodeObserver :: IO CodeObserver mkCodeObserver = CodeObserver <$> newEmptyMVar mkCodeProducer :: IO CodeProducer mkCodeProducer = CodeProducer <$> newEmptyMVar waitCode :: CodeObserver -> IO Code waitCode (CodeObserver o) = readMVar o sendCode :: CodeProducer -> Code -> IO () sendCode (CodeProducer p) = putMVar p type WormHoleParams = [CommandParam] appId :: String -> WormHoleParams appId s = [Param "--appid", Param s] | Sends a file . Once the send is underway , and the Code has been generated , it will be sent to the CodeObserver . ( This may not happen , Note that , if the filename looks like " foo 1 - wormhole - code bar " , when sendFile :: FilePath -> CodeObserver -> WormHoleParams -> IO Bool sendFile f (CodeObserver observer) ps = do See -wormhole/issues/108 environ <- addEntry "PYTHONUNBUFFERED" "1" <$> getEnvironment runWormHoleProcess p { env = Just environ} $ \_hin hout -> findcode =<< words <$> hGetContents hout where p = wormHoleProcess (Param "send" : ps ++ [File f]) findcode [] = return False findcode (w:ws) = case mkCode w of Just code -> do putMVar observer code return True Nothing -> findcode ws | Receives a file . Once the receive is under way , the Code will be read from the , and fed to wormhole on stdin . receiveFile :: FilePath -> CodeProducer -> WormHoleParams -> IO Bool receiveFile f (CodeProducer producer) ps = runWormHoleProcess p $ \hin _hout -> do Code c <- readMVar producer hPutStrLn hin c hFlush hin return True where p = wormHoleProcess $ [ Param "receive" , Param "--accept-file" , Param "--output-file" , File f ] ++ ps wormHoleProcess :: WormHoleParams -> CreateProcess wormHoleProcess = proc "wormhole" . toCommand runWormHoleProcess :: CreateProcess -> (Handle -> Handle -> IO Bool) -> IO Bool runWormHoleProcess p consumer = bracketOnError setup (\v -> cleanup v <&&> return False) go where setup = do (Just hin, Just hout, Nothing, pid) <- createProcess p { std_in = CreatePipe , std_out = CreatePipe } return (hin, hout, pid) cleanup (hin, hout, pid) = do r <- waitForProcess pid hClose hin hClose hout return $ case r of ExitSuccess -> True ExitFailure _ -> False go h@(hin, hout, _) = consumer hin hout <&&> cleanup h isInstalled :: IO Bool isInstalled = inPath "wormhole"
baaa8f30db7d899503cc9f598cb8912a0d014ae8eab41d7b1d70d22d717c6e22
Helium4Haskell/helium
ExprDoLastNotExpr.hs
module ExprDoLastNotExpr where main = do { x <- main }
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/staticerrors/ExprDoLastNotExpr.hs
haskell
module ExprDoLastNotExpr where main = do { x <- main }
2e0e84d8e4e233516d3b11eaf3e69350a83ade6c9ba7ea72d9f879e3a1a19244
ageneau/blossom
utils.cljc
(ns blossom.utils) (defn wget "Get index i from v, wrapping negative indices if necessary." [v i] (assert (counted? v) "inefficient count operation") (nth v (mod i (count v)))) (defn filter-and-find-min-for-key "Remove nil elements from sequence and find an element for which (get element key) is minimum" [key s] (let [filtered (filter some? s)] (when (seq filtered) (reduce (partial min-key key) (reverse filtered)))))
null
https://raw.githubusercontent.com/ageneau/blossom/67a6a2bcc30776867fe16b4e79122e7f43e4928a/src/blossom/utils.cljc
clojure
(ns blossom.utils) (defn wget "Get index i from v, wrapping negative indices if necessary." [v i] (assert (counted? v) "inefficient count operation") (nth v (mod i (count v)))) (defn filter-and-find-min-for-key "Remove nil elements from sequence and find an element for which (get element key) is minimum" [key s] (let [filtered (filter some? s)] (when (seq filtered) (reduce (partial min-key key) (reverse filtered)))))
13c2ff39afc5cfbac376fccd5d1c0761305bd1d5f633e167adf13efc6f8fac02
onlyshk/g711
g711.erl
Copyright ( c ) < 2011 > , < > %% All rights reserved. %% %% Redistribution and use in source and binary forms, with or without %% modification, are permitted provided that the following conditions are met: %% * Redistributions of source code must retain the above copyright %% notice, this list of conditions and the following disclaimer. %% * Redistributions in binary form must reproduce the above copyright %% notice, this list of conditions and the following disclaimer in the %% documentation and/or other materials provided with the distribution. %% * Neither the name of the <organization> nor the %% names of its contributors may be used to endorse or promote products %% derived from this software without specific prior written permission. %% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND %% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED %% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL < 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. %% Description : is an ITU - T standard for audio companding . %% -module(g711). %% %% Exported Functions %% -export([pcm_to_alow/1]). -export([alow_to_pcm/1]). -export([alow_to_ulaw/1]). -export([ulaw_to_alow/1]). -define(SIGNBIT, <<50:8>>). -define(QUANTMASK, <<16:8>>). -define(NSEGS, <<8:8>>). -define(SEG_SHIFT,<<4>>). -define(SEG_MASK,<<46:8>>). -define(USEGEND, [<<31:8>>,<<63:8>>,<<127:8>>,<<255:8>>, <<511>>,<<1023>>,<<2047>>,<<4095>>]). -define(ASEGEND, [<<63>>,<<127>>,<<255>>,<<511>>, <<1023>>,<<4095>>,<<8191>>]). -define(U2A, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7,7, 8, 8, 9,10, 11, 12,13,14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 29, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 87, 88, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,101,102,103,104, 105,106,107,108,109,110,111,112, 113,114,115,116,117,118,119,120, 121,122,123,124,125,126,127,128]). -define(A2U, [1, 3, 5, 7, 9, 11, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 48, 49, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 79, 73, 74, 75, 76, 77, 78, 79, 80, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127]). %% @ASEGEND @8 %% search(Value, Table, Size) -> TryFind = lists:filter(fun(X) -> Value =< X end, Table), case TryFind of [] -> Size; _ -> lists:nth(1, TryFind) end. %% Convert a 16 - bit linear PCM value to 8 - bit A - law %% Linear Input Code Compressed Code %% 0000000wxyza 000wxyz 0000001wxyza %% 000001wxyzab 010wxyz %% 00001wxyzabc 011wxyz 0001wxyzabcd 100wxyz 001wxyzabcde 101wxyz %% 01wxyzabcdef 110wxyz %% 1wxyzabcdefg 111wxyz %% pcm_to_alow(<<Val:16>>) -> NewPcmVal = Val bsr 3, [Mask, TmpPcmVal] = if (NewPcmVal >= 0) -> [213, NewPcmVal]; true -> [85, NewPcmVal - NewPcmVal - NewPcmVal - 1] end, Seg = search(TmpPcmVal, ?ASEGEND, 8), if Seg >= 8 -> 127 bxor Mask; true -> Aval = Seg bsl ?SEG_SHIFT, if Seg < 2 -> TmpAval = Aval bor Aval bor (TmpPcmVal bsl 1) band ?QUANTMASK, TmpAval bxor Mask; true -> TmpAval = Aval bor Aval bor (TmpPcmVal bsl Seg) band ?QUANTMASK, TmpAval bxor Mask end end. %% %% Convert A-law value to PCM %% alow_to_pcm(Val) when not is_binary(Val) -> Binary = term_to_binary(Val), alow_to_pcm(Binary); alow_to_pcm(<<Val:8>>) -> AVal = Val bxor 85, T = (AVal band ?QUANTMASK) bsl 4, Seg = (AVal band ?SEG_MASK) bsr ?SEG_SHIFT, case Seg of 0 -> T + 8; 1 -> T + 264; _ -> (T + 264) bsl Seg - 1 end. %% %% U-law to A-law conversation %% alow_to_ulaw(Val) when not is_binary(Val) -> Binary = term_to_binary(Val), alow_to_ulaw(Binary); alow_to_ulaw(<<Val:8>>) -> Aval = Val band 255, if Aval band 127 > 0 -> 225 bxor lists:nth(Aval bxor 213,?A2U); true -> 127 bxor lists:nth(Aval bxor 85, ?A2U) end. %% %% A-law to U-law conversation %% ulaw_to_alow(Val) when not is_binary(Val) -> Binary = term_to_binary(Val), ulaw_to_alow(Binary); ulaw_to_alow(<<Val:8>>) -> Uval = Val band 255, if Uval band 127 > 0 -> 213 bxor (lists:nth(255 bxor Uval,?U2A) - 1); true -> 85 bxor (lists:nth(213 bxor Uval, ?U2A)- 1) end.
null
https://raw.githubusercontent.com/onlyshk/g711/4eed180db195917bef452f9b8baaa727f7915983/src/g711.erl
erlang
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the <organization> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Exported Functions Linear Input Code Compressed Code 000001wxyzab 010wxyz 00001wxyzabc 011wxyz 01wxyzabcdef 110wxyz 1wxyzabcdefg 111wxyz Convert A-law value to PCM U-law to A-law conversation A-law to U-law conversation
Copyright ( c ) < 2011 > , < > THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND 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 ; ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT Description : is an ITU - T standard for audio companding . -module(g711). -export([pcm_to_alow/1]). -export([alow_to_pcm/1]). -export([alow_to_ulaw/1]). -export([ulaw_to_alow/1]). -define(SIGNBIT, <<50:8>>). -define(QUANTMASK, <<16:8>>). -define(NSEGS, <<8:8>>). -define(SEG_SHIFT,<<4>>). -define(SEG_MASK,<<46:8>>). -define(USEGEND, [<<31:8>>,<<63:8>>,<<127:8>>,<<255:8>>, <<511>>,<<1023>>,<<2047>>,<<4095>>]). -define(ASEGEND, [<<63>>,<<127>>,<<255>>,<<511>>, <<1023>>,<<4095>>,<<8191>>]). -define(U2A, [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7,7, 8, 8, 9,10, 11, 12,13,14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 29, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 87, 88, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,101,102,103,104, 105,106,107,108,109,110,111,112, 113,114,115,116,117,118,119,120, 121,122,123,124,125,126,127,128]). -define(A2U, [1, 3, 5, 7, 9, 11, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 48, 49, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 79, 73, 74, 75, 76, 77, 78, 79, 80, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127]). @ASEGEND @8 search(Value, Table, Size) -> TryFind = lists:filter(fun(X) -> Value =< X end, Table), case TryFind of [] -> Size; _ -> lists:nth(1, TryFind) end. Convert a 16 - bit linear PCM value to 8 - bit A - law 0000000wxyza 000wxyz 0000001wxyza 0001wxyzabcd 100wxyz 001wxyzabcde 101wxyz pcm_to_alow(<<Val:16>>) -> NewPcmVal = Val bsr 3, [Mask, TmpPcmVal] = if (NewPcmVal >= 0) -> [213, NewPcmVal]; true -> [85, NewPcmVal - NewPcmVal - NewPcmVal - 1] end, Seg = search(TmpPcmVal, ?ASEGEND, 8), if Seg >= 8 -> 127 bxor Mask; true -> Aval = Seg bsl ?SEG_SHIFT, if Seg < 2 -> TmpAval = Aval bor Aval bor (TmpPcmVal bsl 1) band ?QUANTMASK, TmpAval bxor Mask; true -> TmpAval = Aval bor Aval bor (TmpPcmVal bsl Seg) band ?QUANTMASK, TmpAval bxor Mask end end. alow_to_pcm(Val) when not is_binary(Val) -> Binary = term_to_binary(Val), alow_to_pcm(Binary); alow_to_pcm(<<Val:8>>) -> AVal = Val bxor 85, T = (AVal band ?QUANTMASK) bsl 4, Seg = (AVal band ?SEG_MASK) bsr ?SEG_SHIFT, case Seg of 0 -> T + 8; 1 -> T + 264; _ -> (T + 264) bsl Seg - 1 end. alow_to_ulaw(Val) when not is_binary(Val) -> Binary = term_to_binary(Val), alow_to_ulaw(Binary); alow_to_ulaw(<<Val:8>>) -> Aval = Val band 255, if Aval band 127 > 0 -> 225 bxor lists:nth(Aval bxor 213,?A2U); true -> 127 bxor lists:nth(Aval bxor 85, ?A2U) end. ulaw_to_alow(Val) when not is_binary(Val) -> Binary = term_to_binary(Val), ulaw_to_alow(Binary); ulaw_to_alow(<<Val:8>>) -> Uval = Val band 255, if Uval band 127 > 0 -> 213 bxor (lists:nth(255 bxor Uval,?U2A) - 1); true -> 85 bxor (lists:nth(213 bxor Uval, ?U2A)- 1) end.
58a125ce9ea0f1af554958d545c612c36c37f2f8420c725c662a36c0f5eeaa04
dwincort/AdaptiveFuzz
prim.ml
file name : prim.ml created by : Last modified : 12/20/2015 Description : This file contains code for interpreting primitives . created by: Daniel Winograd-Cort Last modified: 12/20/2015 Description: This file contains code for interpreting SFuzz primitives. *) open Types open Syntax open Interpreter.InterpMonad open Support.FileInfo open Print open Conversion open Conversion.Mkers We create a few helper functions for simplifying the creation of primitive functions . The main components are the functions fun_of_1arg , fun_of_2args , etc . which make creating k - argument primitives easy . There are also versions of these appended with _ i or _ type ( or both ) that allow the result to be in the interpreter monad or that allow the output type to be given as an argument respectively . These functions require function arguments for extracting values from terms as well as constructing terms from values . Thus , we also provide a few common extractors and makers in the forms of ex * * * * and mk * * * * respectively . That is , for example , exBool is a function for extracting a boolean value from a term and mkInt is for turning an integer value into a term . For polymorphic functions that can work on terms directly ( e.g. equality , etc . ) , we provide exAny and , which are basically identity functions . There are also some special purpose functions for dealing with the more interesting primitives ( the real fuzzy stuff ) . Finally , the main ( only ) export of this module is the list of primitives itself . primitive functions. The main components are the functions fun_of_1arg, fun_of_2args, etc. which make creating k-argument primitives easy. There are also versions of these appended with _i or _type (or both) that allow the result to be in the interpreter monad or that allow the output type to be given as an argument respectively. These functions require function arguments for extracting values from terms as well as constructing terms from values. Thus, we also provide a few common extractors and makers in the forms of ex**** and mk**** respectively. That is, for example, exBool is a function for extracting a boolean value from a term and mkInt is for turning an integer value into a term. For polymorphic functions that can work on terms directly (e.g. equality, etc.), we provide exAny and mkAny, which are basically identity functions. There are also some special purpose functions for dealing with the more interesting primitives (the real fuzzy stuff). Finally, the main (only) export of this module is the list of primitives itself. *) let rzFileName = ref "dataZoneTemp" let pinterpLimit = ref 50 let useCompiler = ref true let di = dummyinfo module Creation = struct (* The expectation functions take a term and return an ocaml value *) let exBool name tb = match tb with | TmPrim (_i, PrimTBool b) -> return b | _ -> fail_pp "** Primitive ** %s expected a bool but found %a" name pp_term tb let exToken name tt = match tt with | TmPrim (_i, PrimTToken(n,ty)) -> return (n,ty) | _ -> fail_pp "** Primitive ** %s expected a token but found %a" name pp_term tt let exNum name tn = match tn with | TmPrim (_i, PrimTNum n) -> return n | TmPrim (_i, PrimTInt n) -> return (float_of_int n) | TmPrim (_i, PrimTClipped n) -> return n | _ -> fail_pp "** Primitive ** %s expected a num but found %a" name pp_term tn let exInt name tn = match tn with | TmPrim (_i, PrimTInt n) -> return n | _ -> fail_pp "** Primitive ** %s expected an int but found %a" name pp_term tn let exString name ts = match ts with | TmPrim (_i, PrimTString s) -> return s | _ -> fail_pp "** Primitive ** %s expected a string but found %a" name pp_term ts let exBag name tb = match tb with | TmBag(_i, _ty, tlst) -> return tlst | _ -> fail_pp "** Primitive ** %s expected a bag but found %a" name pp_term tb let exVector name tb = match tb with | TmVector(_i, _ty, tlst) -> return tlst | _ -> fail_pp "** Primitive ** %s expected a vector but found %a" name pp_term tb let exPair ex1 ex2 name tp = match tp with | TmPair(_i, t1, t2) -> ex1 name t1 >>= fun v1 -> ex2 name t2 >>= fun v2 -> return (v1, v2) | _ -> fail_pp "** Primitive ** %s expected a pair but found %a" name pp_term tp let exAmp ex1 ex2 name tp = match tp with | TmAmpersand(i, t1, t2) -> ex1 name t1 >>= fun v1 -> ex2 name t2 >>= fun v2 -> return (v1, v2) | _ -> fail_pp "** Primitive ** %s expected a &-pair but found %a" name pp_term tp let rec exList exA name tl = match tl with | TmFold(_i, _, TmLeft(_,tm,_)) -> return [] | TmFold(_i, _, TmRight(_,TmPair(_, tx, txs),_)) -> exA name tx >>= fun vx -> exList exA name txs >>= fun vxs -> return (vx :: vxs) | _ -> fail_pp "** Primitive ** %s expected a list but found %a" name pp_term tl let exFun _name t = return t (* Theoretically, we could check that it's actually a function, but we don't need to *) let exAny _name t = return t (* thunkify is a special function whose purpose is to wrap around a primitive function and prevent it from being evaluated too soon. Essentially, it helps enforce that probabilistic values, which should only be evaluated when absolutely necessary, are properly lazy. In practice, it works by immediately returning a PVal, which is a lazy thunk, and sending all of the argument data to a new primitive function given by the argument. *) let thunkify (name : string) (newprimName : string) (newprimFun : primfun) : primfun = PrimFun (fun t -> match t with | TmPrimFun(i, _, _, ty, ttslst) -> return (mkPVal mkAny di (TmPrimFun(i, newprimName, newprimFun, ty, ttslst))) | _ -> fail_pp "** Primitive Internal ** %s expected a TmPrimFun but was given: %a" name pp_term t) (* The extractArgs function extracts the term list and output type from the given TmPrimFun argument. This is used repeatedly in the fun_of_*args functions below. *) let extractArgs (name : string) (t : term) : (ty * term list) interpreter = match t with | TmPrimFun(i, s, _, ty, ttslst) -> return (ty, List.map (fun (tm,_,_) -> tm) ttslst) | _ -> fail_pp "** Primitive Internal ** %s expected a TmPrimFun but was given: %a" name pp_term t (* The fun_of_*_arg* functions are short hands for making the primitives easily. *) (* -- "_with_type" indicates it accepts information about the output type. *) (* -- "_i" indicates that the operator's output is in the interpreter monad. *) let fun_of_no_args_with_type_i (name : string) (* The name of the function - for debug purposes *) (mk : info -> 'a -> term) (* A maker for the result *) (op : ty -> 'a interpreter) (* The operation to perform *) : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | [] -> op ty >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected no arguments but found %a" name (pp_list pp_term) tlst) let fun_of_1arg_with_type_i (name : string) (* The name of the function - for debug purposes *) (earg : string -> term -> 'a interpreter) (* An extractor for the argument *) (mk : info -> 'b -> term) (* A maker for the result *) (op : ty -> 'a -> 'b interpreter) (* The operation to perform *) : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: [] -> earg name ta >>= fun a -> op ty a >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 1 argument but found %a" name (pp_list pp_term) tlst) let fun_of_1arg_i (name : string) (* The name of the function - for debug purposes *) (earg : string -> term -> 'a interpreter) (* An extractor for the argument *) (mk : info -> 'b -> term) (* A maker for the result *) (op : 'a -> 'b interpreter) (* The operation to perform *) : primfun = fun_of_1arg_with_type_i name earg mk (fun _ty x -> op x) let fun_of_1arg (name : string) (* The name of the function - for debug purposes *) (earg : string -> term -> 'a interpreter) (* An extractor for the argument *) (mk : info -> 'b -> term) (* A maker for the result *) (op : 'a -> 'b) (* The operation to perform *) : primfun = fun_of_1arg_with_type_i name earg mk (fun _ty x -> return (op x)) let fun_of_2args_with_type_i_self (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument (mk : info -> 'c -> term) (* A maker for the result *) (op : term -> ty -> 'a -> 'b -> 'c interpreter) (* The operation to perform *) : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> op t ty a b >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 2 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_2args_with_type_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument (mk : info -> 'c -> term) (* A maker for the result *) (op : ty -> 'a -> 'b -> 'c interpreter) (* The operation to perform *) : primfun = fun_of_2args_with_type_i_self name efst esnd mk (fun _tm ty x y -> op ty x y) let fun_of_2args_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument (mk : info -> 'c -> term) (* A maker for the result *) (op : 'a -> 'b -> 'c interpreter) (* The operation to perform *) : primfun = fun_of_2args_with_type_i name efst esnd mk (fun _ty x y -> op x y) let fun_of_2args (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument (mk : info -> 'c -> term) (* A maker for the result *) (op : 'a -> 'b -> 'c) (* The operation to perform *) : primfun = fun_of_2args_with_type_i name efst esnd mk (fun _ty x y -> return (op x y)) let fun_of_3args_with_type_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument (mk : info -> 'd -> term) (* A maker for the result *) (op : ty -> 'a -> 'b -> 'c -> 'd interpreter) (* The operation to perform *) : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: tc :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> ethd name tc >>= fun c -> op ty a b c >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 3 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_3args_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument (mk : info -> 'd -> term) (* A maker for the result *) (op : 'a -> 'b -> 'c -> 'd interpreter) (* The operation to perform *) : primfun = fun_of_3args_with_type_i name efst esnd ethd mk (fun _ty x y z -> op x y z) let fun_of_3args (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument (mk : info -> 'd -> term) (* A maker for the result *) (op : 'a -> 'b -> 'c -> 'd) (* The operation to perform *) : primfun = fun_of_3args_with_type_i name efst esnd ethd mk (fun _ty x y z -> return (op x y z)) let fun_of_4args_with_type_i_self (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument (mk : info -> 'e -> term) (* A maker for the result *) (op : term -> ty -> 'a -> 'b -> 'c -> 'd -> 'e interpreter) (* The operation to perform *) : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: tc :: td :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> ethd name tc >>= fun c -> efth name td >>= fun d -> op t ty a b c d >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 4 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_4args_with_type_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument (mk : info -> 'e -> term) (* A maker for the result *) (op : ty -> 'a -> 'b -> 'c -> 'd -> 'e interpreter) (* The operation to perform *) : primfun = fun_of_4args_with_type_i_self name efst esnd ethd efth mk (fun _tm ty a b c d -> op ty a b c d) let fun_of_4args_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument (mk : info -> 'e -> term) (* A maker for the result *) (op : 'a -> 'b -> 'c -> 'd -> 'e interpreter) (* The operation to perform *) : primfun = fun_of_4args_with_type_i name efst esnd ethd efth mk (fun _ty a b c d -> op a b c d) let fun_of_5args_with_type_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument An extractor for the fifth argument (mk : info -> 'f -> term) (* A maker for the result *) (op : ty -> 'a -> 'b -> 'c -> 'd -> 'e -> 'f interpreter) (* The operation to perform *) : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: tc :: td :: te :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> ethd name tc >>= fun c -> efth name td >>= fun d -> efft name te >>= fun e -> op ty a b c d e >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 5 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_5args_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the second argument An extractor for the fifth argument (mk : info -> 'f -> term) (* A maker for the result *) (op : 'a -> 'b -> 'c -> 'd -> 'e -> 'f interpreter) (* The operation to perform *) : primfun = fun_of_5args_with_type_i name efst esnd ethd efth efft mk (fun _ty -> op) let fun_of_7args_with_type_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument An extractor for the fifth argument An extractor for the sixth argument An extractor for the seventh argument (mk : info -> 'h -> term) (* A maker for the result *) (op : ty -> 'a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g -> 'h interpreter) (* The operation to perform *) : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: tc :: td :: te :: tf :: tg :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> ethd name tc >>= fun c -> efth name td >>= fun d -> efft name te >>= fun e -> esxh name tf >>= fun f -> esvh name tg >>= fun g -> op ty a b c d e f g >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 7 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_7args_i (name : string) (* The name of the function - for debug purposes *) An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the second argument An extractor for the fifth argument An extractor for the sixth argument An extractor for the seventh argument (mk : info -> 'h -> term) (* A maker for the result *) (op : 'a -> 'b -> 'c -> 'd -> 'e -> 'f -> 'g -> 'h interpreter) (* The operation to perform *) : primfun = fun_of_7args_with_type_i name efst esnd ethd efth efft esxh esvh mk (fun _ty -> op) end open Creation let message n = Support.Error.message n Support.Options.Interpreter di let assertionMsg i = Support.Error.message (-1) Support.Options.Assertion i let printMsg i = Support.Error.message (-1) Support.Options.General i (*****************************************************************************) (* Here we have modifying functions *) (* Makes sure that the given function only evaluates when we are in full evaluation mode (as opposed to partial. *) let onlyInFullEval (name : string) : unit interpreter = isInPartial >>= fun b -> if b then fail (name^" not to be evaluated during partial evaluation") else (return ()) (*****************************************************************************) (* Here is the primitive for case on integers. *) let rec intToPeanoFun (ty : ty) (n : int) : term interpreter = if (n <= 0) then return @@ TmFold(di, ty, TmLeft(di, mkUnit di (), ty)) else intToPeanoFun ty (n - 1) >>= fun n' -> return @@ TmFold(di, ty, TmRight(di, n', TyPrim PrimUnit)) (*****************************************************************************) (* Here are some helpers for file and string parsing. *) let fileLines (maxLines : int) (filename : string) = let lines = ref [] in let chan = open_in filename in try for i=1 to maxLines; do lines := input_line chan :: !lines done; close_in chan; List.rev !lines with End_of_file -> close_in chan; List.rev !lines (*****************************************************************************) (*****************************************************************************) (* Here we have specific helper functions for specific primitives. *) (*****************************************************************************) (*****************************************************************************) (*****************************************************************************) (* We begin with assertions. *) let assertFun (s : string) (b : bool) : unit = ignore (assertionMsg di "%s: %s" s (if b then "PASS" else "FAIL")) let assertEqFun (s : string) (t1 : term) (t2 : term) : unit = let res = if Syntax.tmEq t1 t2 then "PASS" else pp_to_string "FAIL (%a != %a)" pp_term t1 pp_term t2 in ignore (assertionMsg di "%s: %s" s res) (*****************************************************************************) (* The following functions are for catching errors during reading. *) let readNumFun s = try float_of_string s with Failure s -> (message 1 "Failure to read %s as a float. Returning 0." s; 0.) let readIntFun s = try int_of_string s with Failure s -> (message 1 "Failure to read %s as an int. Returning 0." s; 0) (*****************************************************************************) The following functions invoke the sensitivity type checker . let tyCheckFuzzFun (sens : float) (f : term) : term interpreter = onlyInFullEval "tyCheckFuzz" >> let genFailResult s = return (TmLeft(di, TmPrim(di, PrimTString s), TyPrim PrimUnit)) in match Tycheck.type_of f (Ctx.empty_context, 0, true, Some (!pinterpLimit, Interpreter.genPinterp)) with | Ok (TyLollipop(_, SiConst n, _), _) when n <= sens -> return (TmRight(di, mkUnit di (), TyPrim PrimString)) | Ok (TyLollipop(_, SiConst n, _), _) -> genFailResult @@ pp_to_string "tyCheckFuzz expected a %F-sensitive function but found a %F-sensitive function" sens n | Ok (TyLollipop(_, SiInfty, _), _) -> genFailResult @@ pp_to_string "tyCheckFuzz expected a %F-sensitive function but found an infinitely sensitive function" sens | Ok (TyLollipop(_, si, _), _) -> fail_pp "**Primitive** tyCheckFuzz found an unexpected sensitivity: %a" pp_si si | Ok (tyf, _) -> fail_pp "**Primitive** tyCheckFuzz's function argument has non-lollipop type: %a" pp_type tyf | Error (d,e) -> genFailResult @@ pp_to_string "TYPE FAIL: %a %a" pp_fileinfo e.i (pp_tyerr d) e.v (* FIXME: Use mkSum to make this function prettier. *) let runFuzz (ty : ty) (sens : float) (f : term) : (ty * ty * (string, term) either) interpreter = onlyInFullEval "runFuzz" >> (match ty with | TyUnion(_, aty) -> return aty | _ -> fail_pp "**Primitive** runFuzz found an unexpected return type: %a" pp_type ty ) >>= fun outty -> (match Tycheck.type_of f (Ctx.empty_context, 0, true, Some (!pinterpLimit, Interpreter.genPinterp)) with | Ok (TyLollipop(_, SiConst n, _), _) when n <= sens -> begin attemptDataZone n >>= fun succ -> match succ, !useCompiler with | false, _ -> return @@ Left "Database is all used up" | true, true -> begin getDB >>= fun db -> let query = TmApp(di, TmApp(di, f, TmApp(di, db, mkUnit di ())), mkUnit di ()) in match Codegen.runCompiled (!rzFileName) di query outty with | Error s -> return @@ Left s | Ok r -> return @@ Right r end | true, false -> getDB >>= fun db -> Interpreter.interp (TmUnPVal (di, (TmApp(di, f, TmApp(di, db, TmPrim(di, PrimTUnit)))))) >>= fun r -> return @@ Right r end | Ok (TyLollipop(_, SiConst n, _), _) -> return @@ Left (pp_to_string "runFuzz expected a %F-sensitive function but found a %F-sensitive function" sens n) | Ok (TyLollipop(_, SiInfty, _), _) -> return @@ Left (pp_to_string "runFuzz expected a %F-sensitive function but found an infinitely sensitive function" sens) | Ok (TyLollipop(_, si, _), _) -> fail_pp "**Primitive** runFuzz found an unexpected sensitivity: %a" pp_si si | Ok (tyf, _) -> fail_pp "**Primitive** runFuzz's function argument has non-lollipop type: %a" pp_type tyf | Error (d,e) -> return @@ Left (pp_to_string "TYPE FAIL: %a %a" pp_fileinfo e.i (pp_tyerr d) e.v) ) >>= fun res -> return (TyPrim PrimString, outty, res) (*****************************************************************************) (* Here are ones specifically for bag stuff. *) let showBagFun (f : term) (b : term list) : string interpreter = mapM (fun t -> Interpreter.interp (TmApp(di, f, t)) >>= exString "showBag") b >>= fun strList -> return @@ String.concat "," strList let rec bagfoldlFun (f : term) (a : term) (bbag : term list) : term interpreter = match bbag with | [] -> return a | b::bs -> Interpreter.interp (TmApp(di, TmApp(di, f, a), b)) >>= fun x -> bagfoldlFun f x bs let bagmapFun (ty : ty) (f : term) (b : term list) : (ty * term list) interpreter = mapM (fun t -> Interpreter.interp (TmApp(di, f, t))) b >>= fun tmlst -> return (ty, tmlst) return ( ty , ( fun tm - > TmApp(di , f , tm ) ) b ) let bagsplitFun (oty : ty) (f : term) (b : term list) : ((ty * term list) * (ty * term list)) interpreter = (match oty with | TyTensor(ty,_) -> return ty | _ -> fail_pp "** Primitive ** bagsplit expected a tensor output but found %a" pp_type oty ) >>= fun bty -> mapM (fun tm -> Interpreter.interp (TmApp(di, f, tm)) >>= exBool "bagsplit" >>= fun res -> return (tm, res)) b >>= fun lst -> let (lst1, lst2) = List.partition snd lst in return ((bty, List.map fst lst1), (bty, List.map fst lst2)) let bagsumLFun (n : int) (b : term list) : (ty * float list) interpreter = let rec sumUp k xs ys = match k,xs,ys with | 0,_,_ -> [] | _,x::xs,y::ys -> (x +. y)::sumUp (k - 1) xs ys | _,xs,[] -> Util.listTake k xs | _,[],ys -> Util.listTake k ys in mapM (fun t -> Interpreter.interp t >>= exList exNum "bagsumL") b >>= fun numlstlst -> return @@ (TyPrim PrimNum, List.fold_left (sumUp n) [] numlstlst) let bagsumVFun (oty : ty) (n : int) (b : term list) : (ty * term list) interpreter = let rec sumUp k xs ys = match k,xs,ys with | 0,_,_ -> [] | _,x::xs,y::ys -> (x +. y)::sumUp (k - 1) xs ys | _,xs,[] -> Util.listTake k xs | _,[],ys -> Util.listTake k ys in mapM (fun t -> Interpreter.interp t >>= exVector "bagsumV" >>= mapM (fun t' -> Interpreter.interp t' >>= exNum "bagsumV")) b >>= fun numlstlst -> return (oty, List.map (mkNum di) (List.fold_left (sumUp n) [] numlstlst)) (*****************************************************************************) (* Here are ones specifically for differentially private noise. *) let addNoiseFun (eps : float) (n : float) : float interpreter = onlyInFullEval "addNoise" >> return (n +. Math.lap (1.0 /. eps)) : num[s ] - > num[k ] - > ( R - > DB -o[k ] num ) - > R bag - > DB -o[s ] fuzzy R let reportNoisyMaxFun (eps : float) (k : float) (quality : term) (rbag : term list) (db : term) : term interpreter = onlyInFullEval "reportNoisyMax" >> mapM (fun r -> Interpreter.interp (TmApp(di, TmApp(di, quality, r), db)) >>= exNum "reportNoisyMax" >>= fun q -> return (r, q +. Math.lap (k /. eps))) rbag >>= fun problist -> Support.Error.message 0 Support . Options . Interpreter Support.FileInfo.dummyinfo " --- reportNoisyMax : Probabilities are : % s " ( String.concat " , " ( List.map ( fun x - > string_of_float ( snd x ) ) problist ) ) ; "--- reportNoisyMax: Probabilities are: %s" (String.concat "," (List.map (fun x -> string_of_float (snd x)) problist));*) let (res, _i) = List.fold_left (fun best r -> if abs_float (snd r) > abs_float (snd best) then r else best) (mkUnit di (), 0.0) problist in return res (* expMech : num[s] -> num[k] -> (R -> DB -o[k] num) -> R bag -> DB -o[s] fuzzy R *) let expMechFun (eps : float) (k : float) (quality : term) (rbag : term list) (db : term) : term interpreter = onlyInFullEval "expMech" >> mapM (fun r -> Interpreter.interp (TmApp(di, TmApp(di, quality, r), db)) >>= exNum "expMech" >>= fun q -> return (r, exp (eps *. q /. (2.0 *. k)))) rbag >>= fun reslist -> let total = List.fold_left (+.) 0.0 (List.map snd reslist) in let rec sampleLst (p : float) (lst : ('a * float) list) : 'a interpreter = match lst with | [] -> fail_pp "**Primitive** expMechFun was given an empty list." | (a,x)::xs -> if p < x then return a else sampleLst (p -. x) xs in sampleLst (Math.randFloat total) (List.sort (fun a b -> truncate (snd b -. snd a)) reslist) (* aboveThreshold : num[s] -> num[k] -> num -> DB -o[k*s] fuzzy token *) let aboveThresholdFun (thisTerm : term) (ty : ty) (eps : float) (k : float) (t : float) (db : term) : term interpreter = onlyInFullEval "aboveThreshold" >> (match ty with | TyPrim1 (Prim1Fuzzy, TyPrim1 (Prim1Token, TyLollipop(argtype, _, outtype))) -> return (TyLollipop(argtype, SiConst k, outtype)) | _ -> fail_pp "**Primitive** aboveThreshold found an unexpected return type: %a" pp_type ty ) >>= fun ftype -> match !useCompiler with | true -> begin match Codegen.runCompiled (!rzFileName) di thisTerm (TyPrim1 (Prim1Token, ftype)) with | Error s -> fail @@ "**Primitive** aboveThreshold failed with message: "^s | Ok r -> return r end | false -> let index = List.length (!curatormem) in curatormem := List.append !curatormem [Some (t +. Math.lap (2.0 /. (eps *. k)), eps, db)]; return (mkToken di (index, ftype)) let rec updateNth (lst : 'a list) (index : int) (f : 'a -> 'a) : 'a list = match lst, index with | [],_ -> [] | x::xs, 0 -> f x :: xs | x::xs, n -> x :: updateNth xs (n-1) f let queryATFun (thisTerm : term) (oty : ty) (tok : (int * ty)) (q : term) : term interpreter = onlyInFullEval "aboveThreshold query" >> match tok with | (index, TyLollipop(_, SiConst k, TyPrim PrimNum)) -> begin match Tycheck.type_of q (Ctx.empty_context, 0, true, Some (!pinterpLimit, Interpreter.genPinterp)) with | Ok (TyLollipop(_, SiConst n, _), _) when n <= k -> begin match !useCompiler with | true -> begin match Codegen.runCompiled (!rzFileName) di thisTerm oty with | Error s -> fail @@ "**Primitive** aboveThresholdQuery failed with message: "^s | Ok res -> return res end | false -> begin match List.nth (!curatormem) index with | None -> return (Left ()) | Some (t,eps,db) -> Interpreter.interp (TmApp(di, q, db)) >>= exNum "aboveThreshold" >>= fun res -> if res +. Math.lap (4.0 /. eps) >= t then (curatormem := updateNth !curatormem index (fun _ -> None); return (Right true)) else return (Right false) end >>= (fun res -> return ((mkSum mkUnit mkBool) di (TyPrim PrimUnit, TyPrim PrimBool, res))) end | Ok (TyLollipop(_, SiConst n, _), _) -> fail_pp "**Primitive** aboveThreshold expected a %F-sensitive function but found a %F-sensitive function" k n | Ok (TyLollipop(_, SiInfty, _), _) -> fail_pp "**Primitive** aboveThreshold expected a %F-sensitive function but found an infinitely sensitive function" k | Ok (TyLollipop(_, si, _), _) -> fail_pp "**Primitive** aboveThreshold found an unexpected sensitivity: %a" pp_si si | Ok (tyf, _) -> fail_pp "**Primitive** aboveThreshold's function argument has non-lollipop type: %a" pp_type tyf | Error (d,e) -> fail_pp "TYPE FAIL: %a %a" pp_fileinfo e.i (pp_tyerr d) e.v end | _ -> fail_pp "**Primitive** aboveThreshold received an inappropriate or malformed token." let selectFun (ty : ty) (beta : float) (bag : term list) : (ty * term list) interpreter = onlyInFullEval "select" >> return (ty, Math.sampleList beta bag) (*****************************************************************************) (* Here are the *fromFile primitives. *) let bagFromFileFun (oty : ty) (maxsize : int) (fn : string) : (ty * term list) interpreter = let lines = fileLines maxsize fn in match oty with | TyPrim1 (Prim1Bag, subty) -> begin match Option.opt_bind_list (List.map (stringToFuzz di subty) lines) with | Some lst -> return (oty, lst) | None -> fail_pp "**Primitive** bagFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** bagFromFile found a weird type %a." pp_type oty let rec listFromFileFun (oty : ty) (maxsize : int) (fn : string) : (ty * ty * term list) interpreter = let lines = fileLines maxsize fn in match oty with | TyMu (_, TyUnion (TyPrim PrimUnit, TyTensor (subty, TyVar _))) -> begin match Option.opt_bind_list (List.map (stringToFuzz di subty) lines) with | Some lst -> return (subty, oty, lst) | None -> fail_pp "**Primitive** listFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** listFromFile found a weird type %a." pp_type oty let listbagFromFileFun (oty : ty) (maxsize : int) (fn : string) (rexp : string) : (ty * (ty * ty * term list) list) interpreter = let lines = fileLines maxsize fn in match oty with | TyPrim1 (Prim1Bag, (TyMu (_, TyUnion (TyPrim PrimUnit, TyTensor (subty, TyVar _))) as listty)) -> begin let lineFun line = Option.map (fun lst -> (subty, listty, lst)) (Option.opt_bind_list (List.map (stringToFuzz di subty) (Str.split (Str.regexp rexp) line))) (*"[ \t]+"*) in match Option.opt_bind_list (List.map lineFun lines) with | Some lst -> return (oty, lst) | None -> fail_pp "**Primitive** listbagFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** listbagFromFile found a weird type %a." pp_type oty let vectorbagFromFileFun (oty : ty) (maxsize : int) (fn : string) (rexp : string) : (ty * (ty * term list) list) interpreter = let lines = fileLines maxsize fn in match oty with | TyPrim1 (Prim1Bag, (TyPrim1 (Prim1Vector, subty) as vecty)) -> begin let lineFun line = Option.map (fun lst -> (vecty, lst)) (Option.opt_bind_list (List.map (stringToFuzz di subty) (Str.split (Str.regexp rexp) line))) in match Option.opt_bind_list (List.map lineFun lines) with | Some lst -> return (oty, lst) | None -> fail_pp "**Primitive** vectorbagFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** vectorbagFromFile found a weird type %a." pp_type oty let labeledVectorbagFromFileFun (oty : ty) (maxsize : int) (fn : string) (rexp : string) : (ty * (term * (ty * term list)) list) interpreter = let lines = fileLines maxsize fn in match oty with | TyPrim1 (Prim1Bag, TyTensor (_, (TyPrim1 (Prim1Vector, subty) as vecty))) -> begin let lineFun line = Option.map (fun lst -> (List.hd lst, (vecty, List.tl lst))) (Option.opt_bind_list (List.map (stringToFuzz di subty) (Str.split (Str.regexp rexp) line))) in match Option.opt_bind_list (List.map lineFun lines) with | Some lst -> return (oty, lst) | None -> fail_pp "**Primitive** labeledVectorbagFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** labeledVectorbagFromFile found a weird type %a." pp_type oty (*****************************************************************************) (* Here are the vector primitives. *) let showVecFun (f : term) (v : term list) : string interpreter = mapM (fun t -> Interpreter.interp (TmApp(di, f, t)) >>= exString "showVec") v >>= fun strList -> return @@ String.concat "," strList let vconsFun (oty : ty) (x : term) (xs : term list) : (ty * term list) interpreter = return (oty, x::xs) let vunconsFun (oty : ty) (v : term list) : (ty * ty * (unit, term * (ty * term list)) either) interpreter = (match oty with | TyUnion (tyl, TyTensor (tyx, tyxvec)) -> return (tyl, TyTensor (tyx, tyxvec), tyxvec) | _ -> fail_pp "**Primitive** vuncons found a weird type %a." pp_type oty ) >>= fun (tyl, tyr, tyxvec) -> match v with | [] -> return (tyl, tyr, Left ()) | x::xs -> return (tyl, tyr, Right (x, (tyxvec, xs))) let listToVectorFun (oty : ty) (lst : term list) : (ty * term list) interpreter = return (oty, lst) let vectorToListFun (oty : ty) (lst : term list) : (ty * term list) interpreter = (match oty with | TyMu (_, TyUnion (TyPrim PrimUnit, TyTensor (subty, TyVar _))) -> return subty | _ -> fail_pp "**Primitive** vectorToList found a weird type %a." pp_type oty ) >>= fun subty -> return (subty, lst) let vindexFun (def : term) (i : int) (v : term list) : term = let rec nth i lst = match lst with | [] -> def | x::xs -> if i <= 0 then x else nth (i-1) xs in nth i v let vperformAtFun (oty : ty) (i : int) (f : term) (v : term list) : (ty * term list) interpreter = if i >= List.length v || i < 0 then fail_pp "**Primitive** vperformAt had an out-of-bounds list index %a." pp_type oty else let rec inner i l = match i,l with | _,[] -> return [] | 0,x::xs -> Interpreter.interp (TmApp(di, f, x)) >>= fun x' -> return (x'::xs) | _,x::xs -> inner (i-1) xs >>= fun xs' -> return (x::xs') in inner i v >>= fun res -> return (oty, res) let vzipwithFun (oty : ty) (f : term) (lst1 : term list) (lst2 : term list) : (ty * term list) interpreter = let rec zip l1 l2 = match l1, l2 with | x::xs, y::ys -> (x, y)::(zip xs ys) | _,_ -> [] in mapM (fun (t1, t2) -> Interpreter.interp (TmApp(di, TmApp(di, f, t1), t2)) >>= exAny "vzipwith") (zip lst1 lst2) >>= fun lst' -> return (oty, lst') let rec vfilterFun (ty : ty) (test : term) (lst : term list) : (ty * term list) interpreter = match lst with | x::xs -> Interpreter.interp (TmApp(di, test, x)) >>= exBool "vfilter" >>= fun b -> vfilterFun ty test xs >>= fun (ty,ts) -> return (ty, if b then x::ts else ts) | _ -> return (ty,[]) let vfuzzFun (ty : ty) (lst : term list) : (ty * term list) interpreter = match ty with | TyPrim1 (Prim1Fuzzy, vty) -> return (vty, List.map (fun x -> TmUnPVal (di, x)) lst) | _ -> fail_pp "**Primitive** vfuzz found a weird type %a." pp_type ty let rec vfoldlFun (f : term) (a : term) (blst : term list) : term interpreter = match blst with | [] -> return a | b::bs -> Interpreter.interp (TmApp(di, TmApp(di, f, a), b)) >>= fun x -> vfoldlFun f x bs (*****************************************************************************) (*****************************************************************************) Core primitive definitions for the runtime (*****************************************************************************) (*****************************************************************************) let prim_list : (string * primfun) list = [ (* &-pair destruction *) ("_fst", fun_of_1arg "_fst" (exAmp exAny exAny) mkAny fst); ("_snd", fun_of_1arg "_snd" (exAmp exAny exAny) mkAny snd); (* Logical Operators *) ("_lor", fun_of_2args "_lor" exBool exBool mkBool ( || )); ("_land", fun_of_2args "_land" exBool exBool mkBool ( && )); ("_eq", fun_of_2args "_eq" exAny exAny mkBool Syntax.tmEq); Numerical Comparison Operators ("_lt", fun_of_2args "_lt" exNum exNum mkBool ( < )); ("_gt", fun_of_2args "_gt" exNum exNum mkBool ( > )); ("_lte", fun_of_2args "_lte" exNum exNum mkBool ( <= )); ("_gte", fun_of_2args "_gte" exNum exNum mkBool ( >= )); Numerical Computation Operators ("_add", fun_of_2args "_add" exNum exNum mkNum ( +. )); ("_sub", fun_of_2args "_sub" exNum exNum mkNum ( -. )); ("_mul", fun_of_2args "_mul" exNum exNum mkNum ( *. )); ("_div", fun_of_2args "_div" exNum exNum mkNum ( /. )); ("_exp", fun_of_1arg "_exp" exNum mkNum ( exp )); ("_log", fun_of_1arg "_log" exNum mkNum ( log )); ("_abs", fun_of_1arg "_abs" exNum mkNum ( abs_float )); ("cswp", fun_of_1arg "cswp" (exPair exNum exNum) (mkPair mkNum mkNum) (fun (x,y) -> if x < y then (x,y) else (y,x))); Integer primitives ("_iadd", fun_of_2args "_iadd" exInt exInt mkInt ( + )); ("_isub", fun_of_2args "_isub" exInt exInt mkInt ( - )); ("_imul", fun_of_2args "_imul" exInt exInt mkInt ( * )); ("_idiv", fun_of_2args "_idiv" exInt exInt mkInt ( / )); ("intToPeano", fun_of_1arg_with_type_i "intToPeano" exInt mkAny intToPeanoFun); (* clip creation *) ("clip", fun_of_1arg "clip" exNum mkClipped (fun x -> x)); ("fromClip", fun_of_1arg "fromClip" exNum mkNum (fun x -> x)); (* String operations *) ("string_cc", fun_of_2args "string_cc" exString exString mkString ( ^ )); (* Show functions *) ("showNum", fun_of_1arg "showNum" exNum mkString ( fun n -> if n = floor n then string_of_int (truncate n) else string_of_float n )); ("showInt", fun_of_1arg "showInt" exInt mkString ( string_of_int )); ("showBag", fun_of_2args_i "showBag" exFun exBag mkString showBagFun); ("showVec", fun_of_2args_i "showVec" exFun exVector mkString showVecFun); (* Read functions *) ("readNum", fun_of_1arg "readNum" exString mkNum readNumFun); ("readInt", fun_of_1arg "readInt" exString mkInt readIntFun); (* Testing Utilities *) ("_assert", fun_of_2args "_assert" exString exBool mkUnit assertFun); ("assertEq", fun_of_3args "assertEq" exString exAny exAny mkUnit assertEqFun); ("print", fun_of_1arg "print" exString mkUnit (fun s -> ignore (printMsg di "%s" s))); (* Probability monad operations *) ("_return", fun_of_1arg_i "_return" exAny (mkPVal mkAny) (fun x -> onlyInFullEval "return" >> return x)); ("loadDB", fun_of_2args_i "loadDB" exFun (exPair exNum exNum) mkUnit storeDB); (* Data zone activation primitives *) ("tyCheckFuzz", fun_of_2args_i "tyCheckFuzz" exNum exAny mkAny tyCheckFuzzFun); ("runFuzz", fun_of_2args_with_type_i "runFuzz" exNum exFun (mkSum mkString mkAny) runFuzz); ("getDelta", fun_of_1arg_i "getDelta" exAny mkNum (fun _ -> onlyInFullEval "getDelta" >> getDelta)); ("getEpsilon", fun_of_1arg_i "getEpsilon" exAny mkNum (fun _ -> onlyInFullEval "getEpsilon" >> getEpsilon)); (* Bag primitives *) ("emptybag", fun_of_no_args_with_type_i "emptybag" mkBag (fun ty -> return (ty,[]))); ("addtobag", fun_of_2args_with_type_i "addtobag" exAny exBag mkBag (fun ty x xs -> return (ty, x::xs))); ("bagjoin", fun_of_2args_with_type_i "bagjoin" exBag exBag mkBag (fun ty b1 b2 -> return (ty, List.append b1 b2))); ("bagsize", fun_of_1arg "bagsize" exBag mkInt ( List.length )); ("bagsum", fun_of_1arg_i "bagsum" exBag mkNum (fun l -> mapM (fun t -> Interpreter.interp t >>= exNum "bagsum") l >>= fun l' -> return (List.fold_left (+.) 0.0 l'))); ("bagfoldl", fun_of_3args_i "bagfoldl" exAny exAny exBag mkAny bagfoldlFun); ("bagmap", fun_of_2args_with_type_i "bagmap" exFun exBag mkBag bagmapFun); ("bagsplit", fun_of_2args_with_type_i "bagsplit" exFun exBag (mkPair mkBag mkBag) bagsplitFun); ("bagsumL", fun_of_2args_i "bagsumL" exInt exBag (mkList mkNum) bagsumLFun); ("bagsumV", fun_of_2args_with_type_i "bagsumV" exInt exBag mkVector bagsumVFun); (* Differential Privacy mechanisms *) ("addNoise", thunkify "addNoise" "addNoiseP" (fun_of_2args_i "addNoiseP" exNum exNum mkNum addNoiseFun)); ("reportNoisyMax", thunkify "reportNoisyMax" "reportNoisyMaxP" (fun_of_5args_i "reportNoisyMaxP" exNum exNum exFun exBag exAny mkAny reportNoisyMaxFun)); ("expMech", thunkify "expMech" "expMechP" (fun_of_5args_i "expMechP" exNum exNum exFun exBag exAny mkAny expMechFun)); ("select", fun_of_2args_with_type_i "select" exNum exBag mkBag selectFun); ("aboveThreshold", thunkify "aboveThreshold" "aboveThresholdP" (fun_of_4args_with_type_i_self "aboveThresholdP" exNum exNum exNum exAny mkAny aboveThresholdFun)); ("queryAT", fun_of_2args_with_type_i_self "queryAT" exToken exFun mkAny queryATFun); (* Load data from external file *) ("bagFromFile", fun_of_2args_with_type_i "bagFromFile" exInt exString mkBag bagFromFileFun); ("listFromFile", fun_of_2args_with_type_i "listFromFile" exInt exString (mkListWithType mkAny) listFromFileFun); ("listbagFromFile", fun_of_3args_with_type_i "listbagFromFile" exInt exString exString (mkBag' (mkListWithType mkAny)) listbagFromFileFun); ("vectorbagFromFile", fun_of_3args_with_type_i "vectorbagFromFile" exInt exString exString (mkBag' mkVector) vectorbagFromFileFun); ("labeledVectorbagFromFile", fun_of_3args_with_type_i "labeledVectorbagFromFile" exInt exString exString (mkBag' (mkPair mkAny mkVector)) labeledVectorbagFromFileFun); (* Vector operations *) ("vcons", fun_of_2args_with_type_i "vcons" exAny exVector mkVector vconsFun); ("vuncons", fun_of_1arg_with_type_i "vuncons" exVector (mkSum mkUnit (mkPair mkAny mkVector)) vunconsFun); ("listToVector", fun_of_1arg_with_type_i "listToVector" (exList exAny) mkVector listToVectorFun); ("vectorToList", fun_of_1arg_with_type_i "vectorToList" exVector (mkList mkAny) vectorToListFun); ("vindex", fun_of_3args "vindex" exAny exInt exVector mkAny vindexFun); ("vperformAt", fun_of_3args_with_type_i "vperformAt" exInt exFun exVector mkVector vperformAtFun); ("vfoldl", fun_of_3args_i "vfoldl" exAny exAny exVector mkAny vfoldlFun); ("vmap", fun_of_2args_with_type_i "vmap" exFun exVector mkVector bagmapFun); ("vsmap", fun_of_3args_with_type_i "vsmap" exNum exFun exVector mkVector (fun ty _ -> bagmapFun ty)); ("vfilter", fun_of_2args_with_type_i "vfilter" exFun exVector mkVector vfilterFun); ("vzipwith", fun_of_3args_with_type_i "vzipwith" exFun exVector exVector mkVector vzipwithFun); ("vszipwith", fun_of_5args_with_type_i "vszipwith" exNum exNum exFun exVector exVector mkVector (fun ty _ _ -> vzipwithFun ty)); ("vfuzz", fun_of_1arg_with_type_i "vfuzz" exVector (mkPVal mkVector) vfuzzFun); ("vsize", fun_of_1arg "vsize" exVector mkInt ( List.length )); ( " vsum " , fun_of_1arg_i " vsum " exVector mkNum ( fun l - > mapM ( fun t - > Interpreter.interp t > > = exNum " vsum " ) l > > = fun l ' - > return ( List.fold_left ( + . ) 0.0 l ' ) ) ) ; (fun l -> mapM (fun t -> Interpreter.interp t >>= exNum "vsum") l >>= fun l' -> return (List.fold_left (+.) 0.0 l')));*) ] (* Look for a primfun in the primitive list *) let lookup_prim (id : string) : primfun option = let rec lookup l = match l with | [] -> None | (s, t) :: l' -> if s = id then Some t else lookup l' in lookup prim_list
null
https://raw.githubusercontent.com/dwincort/AdaptiveFuzz/ec937e1ea028e17216928dbdd029a5b9b04a0533/src/prim.ml
ocaml
The expectation functions take a term and return an ocaml value Theoretically, we could check that it's actually a function, but we don't need to thunkify is a special function whose purpose is to wrap around a primitive function and prevent it from being evaluated too soon. Essentially, it helps enforce that probabilistic values, which should only be evaluated when absolutely necessary, are properly lazy. In practice, it works by immediately returning a PVal, which is a lazy thunk, and sending all of the argument data to a new primitive function given by the argument. The extractArgs function extracts the term list and output type from the given TmPrimFun argument. This is used repeatedly in the fun_of_*args functions below. The fun_of_*_arg* functions are short hands for making the primitives easily. -- "_with_type" indicates it accepts information about the output type. -- "_i" indicates that the operator's output is in the interpreter monad. The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes An extractor for the argument A maker for the result The operation to perform The name of the function - for debug purposes An extractor for the argument A maker for the result The operation to perform The name of the function - for debug purposes An extractor for the argument A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform The name of the function - for debug purposes A maker for the result The operation to perform *************************************************************************** Here we have modifying functions Makes sure that the given function only evaluates when we are in full evaluation mode (as opposed to partial. *************************************************************************** Here is the primitive for case on integers. *************************************************************************** Here are some helpers for file and string parsing. *************************************************************************** *************************************************************************** Here we have specific helper functions for specific primitives. *************************************************************************** *************************************************************************** *************************************************************************** We begin with assertions. *************************************************************************** The following functions are for catching errors during reading. *************************************************************************** FIXME: Use mkSum to make this function prettier. *************************************************************************** Here are ones specifically for bag stuff. *************************************************************************** Here are ones specifically for differentially private noise. expMech : num[s] -> num[k] -> (R -> DB -o[k] num) -> R bag -> DB -o[s] fuzzy R aboveThreshold : num[s] -> num[k] -> num -> DB -o[k*s] fuzzy token *************************************************************************** Here are the *fromFile primitives. "[ \t]+" *************************************************************************** Here are the vector primitives. *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** &-pair destruction Logical Operators clip creation String operations Show functions Read functions Testing Utilities Probability monad operations Data zone activation primitives Bag primitives Differential Privacy mechanisms Load data from external file Vector operations Look for a primfun in the primitive list
file name : prim.ml created by : Last modified : 12/20/2015 Description : This file contains code for interpreting primitives . created by: Daniel Winograd-Cort Last modified: 12/20/2015 Description: This file contains code for interpreting SFuzz primitives. *) open Types open Syntax open Interpreter.InterpMonad open Support.FileInfo open Print open Conversion open Conversion.Mkers We create a few helper functions for simplifying the creation of primitive functions . The main components are the functions fun_of_1arg , fun_of_2args , etc . which make creating k - argument primitives easy . There are also versions of these appended with _ i or _ type ( or both ) that allow the result to be in the interpreter monad or that allow the output type to be given as an argument respectively . These functions require function arguments for extracting values from terms as well as constructing terms from values . Thus , we also provide a few common extractors and makers in the forms of ex * * * * and mk * * * * respectively . That is , for example , exBool is a function for extracting a boolean value from a term and mkInt is for turning an integer value into a term . For polymorphic functions that can work on terms directly ( e.g. equality , etc . ) , we provide exAny and , which are basically identity functions . There are also some special purpose functions for dealing with the more interesting primitives ( the real fuzzy stuff ) . Finally , the main ( only ) export of this module is the list of primitives itself . primitive functions. The main components are the functions fun_of_1arg, fun_of_2args, etc. which make creating k-argument primitives easy. There are also versions of these appended with _i or _type (or both) that allow the result to be in the interpreter monad or that allow the output type to be given as an argument respectively. These functions require function arguments for extracting values from terms as well as constructing terms from values. Thus, we also provide a few common extractors and makers in the forms of ex**** and mk**** respectively. That is, for example, exBool is a function for extracting a boolean value from a term and mkInt is for turning an integer value into a term. For polymorphic functions that can work on terms directly (e.g. equality, etc.), we provide exAny and mkAny, which are basically identity functions. There are also some special purpose functions for dealing with the more interesting primitives (the real fuzzy stuff). Finally, the main (only) export of this module is the list of primitives itself. *) let rzFileName = ref "dataZoneTemp" let pinterpLimit = ref 50 let useCompiler = ref true let di = dummyinfo module Creation = struct let exBool name tb = match tb with | TmPrim (_i, PrimTBool b) -> return b | _ -> fail_pp "** Primitive ** %s expected a bool but found %a" name pp_term tb let exToken name tt = match tt with | TmPrim (_i, PrimTToken(n,ty)) -> return (n,ty) | _ -> fail_pp "** Primitive ** %s expected a token but found %a" name pp_term tt let exNum name tn = match tn with | TmPrim (_i, PrimTNum n) -> return n | TmPrim (_i, PrimTInt n) -> return (float_of_int n) | TmPrim (_i, PrimTClipped n) -> return n | _ -> fail_pp "** Primitive ** %s expected a num but found %a" name pp_term tn let exInt name tn = match tn with | TmPrim (_i, PrimTInt n) -> return n | _ -> fail_pp "** Primitive ** %s expected an int but found %a" name pp_term tn let exString name ts = match ts with | TmPrim (_i, PrimTString s) -> return s | _ -> fail_pp "** Primitive ** %s expected a string but found %a" name pp_term ts let exBag name tb = match tb with | TmBag(_i, _ty, tlst) -> return tlst | _ -> fail_pp "** Primitive ** %s expected a bag but found %a" name pp_term tb let exVector name tb = match tb with | TmVector(_i, _ty, tlst) -> return tlst | _ -> fail_pp "** Primitive ** %s expected a vector but found %a" name pp_term tb let exPair ex1 ex2 name tp = match tp with | TmPair(_i, t1, t2) -> ex1 name t1 >>= fun v1 -> ex2 name t2 >>= fun v2 -> return (v1, v2) | _ -> fail_pp "** Primitive ** %s expected a pair but found %a" name pp_term tp let exAmp ex1 ex2 name tp = match tp with | TmAmpersand(i, t1, t2) -> ex1 name t1 >>= fun v1 -> ex2 name t2 >>= fun v2 -> return (v1, v2) | _ -> fail_pp "** Primitive ** %s expected a &-pair but found %a" name pp_term tp let rec exList exA name tl = match tl with | TmFold(_i, _, TmLeft(_,tm,_)) -> return [] | TmFold(_i, _, TmRight(_,TmPair(_, tx, txs),_)) -> exA name tx >>= fun vx -> exList exA name txs >>= fun vxs -> return (vx :: vxs) | _ -> fail_pp "** Primitive ** %s expected a list but found %a" name pp_term tl let exAny _name t = return t let thunkify (name : string) (newprimName : string) (newprimFun : primfun) : primfun = PrimFun (fun t -> match t with | TmPrimFun(i, _, _, ty, ttslst) -> return (mkPVal mkAny di (TmPrimFun(i, newprimName, newprimFun, ty, ttslst))) | _ -> fail_pp "** Primitive Internal ** %s expected a TmPrimFun but was given: %a" name pp_term t) let extractArgs (name : string) (t : term) : (ty * term list) interpreter = match t with | TmPrimFun(i, s, _, ty, ttslst) -> return (ty, List.map (fun (tm,_,_) -> tm) ttslst) | _ -> fail_pp "** Primitive Internal ** %s expected a TmPrimFun but was given: %a" name pp_term t let fun_of_no_args_with_type_i : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | [] -> op ty >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected no arguments but found %a" name (pp_list pp_term) tlst) let fun_of_1arg_with_type_i : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: [] -> earg name ta >>= fun a -> op ty a >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 1 argument but found %a" name (pp_list pp_term) tlst) let fun_of_1arg_i : primfun = fun_of_1arg_with_type_i name earg mk (fun _ty x -> op x) let fun_of_1arg : primfun = fun_of_1arg_with_type_i name earg mk (fun _ty x -> return (op x)) let fun_of_2args_with_type_i_self An extractor for the first argument An extractor for the second argument : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> op t ty a b >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 2 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_2args_with_type_i An extractor for the first argument An extractor for the second argument : primfun = fun_of_2args_with_type_i_self name efst esnd mk (fun _tm ty x y -> op ty x y) let fun_of_2args_i An extractor for the first argument An extractor for the second argument : primfun = fun_of_2args_with_type_i name efst esnd mk (fun _ty x y -> op x y) let fun_of_2args An extractor for the first argument An extractor for the second argument : primfun = fun_of_2args_with_type_i name efst esnd mk (fun _ty x y -> return (op x y)) let fun_of_3args_with_type_i An extractor for the first argument An extractor for the second argument An extractor for the third argument : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: tc :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> ethd name tc >>= fun c -> op ty a b c >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 3 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_3args_i An extractor for the first argument An extractor for the second argument An extractor for the third argument : primfun = fun_of_3args_with_type_i name efst esnd ethd mk (fun _ty x y z -> op x y z) let fun_of_3args An extractor for the first argument An extractor for the second argument An extractor for the third argument : primfun = fun_of_3args_with_type_i name efst esnd ethd mk (fun _ty x y z -> return (op x y z)) let fun_of_4args_with_type_i_self An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: tc :: td :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> ethd name tc >>= fun c -> efth name td >>= fun d -> op t ty a b c d >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 4 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_4args_with_type_i An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument : primfun = fun_of_4args_with_type_i_self name efst esnd ethd efth mk (fun _tm ty a b c d -> op ty a b c d) let fun_of_4args_i An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument : primfun = fun_of_4args_with_type_i name efst esnd ethd efth mk (fun _ty a b c d -> op a b c d) let fun_of_5args_with_type_i An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument An extractor for the fifth argument : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: tc :: td :: te :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> ethd name tc >>= fun c -> efth name td >>= fun d -> efft name te >>= fun e -> op ty a b c d e >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 5 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_5args_i An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the second argument An extractor for the fifth argument : primfun = fun_of_5args_with_type_i name efst esnd ethd efth efft mk (fun _ty -> op) let fun_of_7args_with_type_i An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the fourth argument An extractor for the fifth argument An extractor for the sixth argument An extractor for the seventh argument : primfun = PrimFun (fun t -> extractArgs name t >>= fun (ty, tlst) -> match tlst with | ta :: tb :: tc :: td :: te :: tf :: tg :: [] -> efst name ta >>= fun a -> esnd name tb >>= fun b -> ethd name tc >>= fun c -> efth name td >>= fun d -> efft name te >>= fun e -> esxh name tf >>= fun f -> esvh name tg >>= fun g -> op ty a b c d e f g >>= fun res -> return (mk di res) | _ -> fail_pp "** Primitive ** %s expected 7 arguments but found %a" name (pp_list pp_term) tlst) let fun_of_7args_i An extractor for the first argument An extractor for the second argument An extractor for the third argument An extractor for the second argument An extractor for the fifth argument An extractor for the sixth argument An extractor for the seventh argument : primfun = fun_of_7args_with_type_i name efst esnd ethd efth efft esxh esvh mk (fun _ty -> op) end open Creation let message n = Support.Error.message n Support.Options.Interpreter di let assertionMsg i = Support.Error.message (-1) Support.Options.Assertion i let printMsg i = Support.Error.message (-1) Support.Options.General i let onlyInFullEval (name : string) : unit interpreter = isInPartial >>= fun b -> if b then fail (name^" not to be evaluated during partial evaluation") else (return ()) let rec intToPeanoFun (ty : ty) (n : int) : term interpreter = if (n <= 0) then return @@ TmFold(di, ty, TmLeft(di, mkUnit di (), ty)) else intToPeanoFun ty (n - 1) >>= fun n' -> return @@ TmFold(di, ty, TmRight(di, n', TyPrim PrimUnit)) let fileLines (maxLines : int) (filename : string) = let lines = ref [] in let chan = open_in filename in try for i=1 to maxLines; do lines := input_line chan :: !lines done; close_in chan; List.rev !lines with End_of_file -> close_in chan; List.rev !lines let assertFun (s : string) (b : bool) : unit = ignore (assertionMsg di "%s: %s" s (if b then "PASS" else "FAIL")) let assertEqFun (s : string) (t1 : term) (t2 : term) : unit = let res = if Syntax.tmEq t1 t2 then "PASS" else pp_to_string "FAIL (%a != %a)" pp_term t1 pp_term t2 in ignore (assertionMsg di "%s: %s" s res) let readNumFun s = try float_of_string s with Failure s -> (message 1 "Failure to read %s as a float. Returning 0." s; 0.) let readIntFun s = try int_of_string s with Failure s -> (message 1 "Failure to read %s as an int. Returning 0." s; 0) The following functions invoke the sensitivity type checker . let tyCheckFuzzFun (sens : float) (f : term) : term interpreter = onlyInFullEval "tyCheckFuzz" >> let genFailResult s = return (TmLeft(di, TmPrim(di, PrimTString s), TyPrim PrimUnit)) in match Tycheck.type_of f (Ctx.empty_context, 0, true, Some (!pinterpLimit, Interpreter.genPinterp)) with | Ok (TyLollipop(_, SiConst n, _), _) when n <= sens -> return (TmRight(di, mkUnit di (), TyPrim PrimString)) | Ok (TyLollipop(_, SiConst n, _), _) -> genFailResult @@ pp_to_string "tyCheckFuzz expected a %F-sensitive function but found a %F-sensitive function" sens n | Ok (TyLollipop(_, SiInfty, _), _) -> genFailResult @@ pp_to_string "tyCheckFuzz expected a %F-sensitive function but found an infinitely sensitive function" sens | Ok (TyLollipop(_, si, _), _) -> fail_pp "**Primitive** tyCheckFuzz found an unexpected sensitivity: %a" pp_si si | Ok (tyf, _) -> fail_pp "**Primitive** tyCheckFuzz's function argument has non-lollipop type: %a" pp_type tyf | Error (d,e) -> genFailResult @@ pp_to_string "TYPE FAIL: %a %a" pp_fileinfo e.i (pp_tyerr d) e.v let runFuzz (ty : ty) (sens : float) (f : term) : (ty * ty * (string, term) either) interpreter = onlyInFullEval "runFuzz" >> (match ty with | TyUnion(_, aty) -> return aty | _ -> fail_pp "**Primitive** runFuzz found an unexpected return type: %a" pp_type ty ) >>= fun outty -> (match Tycheck.type_of f (Ctx.empty_context, 0, true, Some (!pinterpLimit, Interpreter.genPinterp)) with | Ok (TyLollipop(_, SiConst n, _), _) when n <= sens -> begin attemptDataZone n >>= fun succ -> match succ, !useCompiler with | false, _ -> return @@ Left "Database is all used up" | true, true -> begin getDB >>= fun db -> let query = TmApp(di, TmApp(di, f, TmApp(di, db, mkUnit di ())), mkUnit di ()) in match Codegen.runCompiled (!rzFileName) di query outty with | Error s -> return @@ Left s | Ok r -> return @@ Right r end | true, false -> getDB >>= fun db -> Interpreter.interp (TmUnPVal (di, (TmApp(di, f, TmApp(di, db, TmPrim(di, PrimTUnit)))))) >>= fun r -> return @@ Right r end | Ok (TyLollipop(_, SiConst n, _), _) -> return @@ Left (pp_to_string "runFuzz expected a %F-sensitive function but found a %F-sensitive function" sens n) | Ok (TyLollipop(_, SiInfty, _), _) -> return @@ Left (pp_to_string "runFuzz expected a %F-sensitive function but found an infinitely sensitive function" sens) | Ok (TyLollipop(_, si, _), _) -> fail_pp "**Primitive** runFuzz found an unexpected sensitivity: %a" pp_si si | Ok (tyf, _) -> fail_pp "**Primitive** runFuzz's function argument has non-lollipop type: %a" pp_type tyf | Error (d,e) -> return @@ Left (pp_to_string "TYPE FAIL: %a %a" pp_fileinfo e.i (pp_tyerr d) e.v) ) >>= fun res -> return (TyPrim PrimString, outty, res) let showBagFun (f : term) (b : term list) : string interpreter = mapM (fun t -> Interpreter.interp (TmApp(di, f, t)) >>= exString "showBag") b >>= fun strList -> return @@ String.concat "," strList let rec bagfoldlFun (f : term) (a : term) (bbag : term list) : term interpreter = match bbag with | [] -> return a | b::bs -> Interpreter.interp (TmApp(di, TmApp(di, f, a), b)) >>= fun x -> bagfoldlFun f x bs let bagmapFun (ty : ty) (f : term) (b : term list) : (ty * term list) interpreter = mapM (fun t -> Interpreter.interp (TmApp(di, f, t))) b >>= fun tmlst -> return (ty, tmlst) return ( ty , ( fun tm - > TmApp(di , f , tm ) ) b ) let bagsplitFun (oty : ty) (f : term) (b : term list) : ((ty * term list) * (ty * term list)) interpreter = (match oty with | TyTensor(ty,_) -> return ty | _ -> fail_pp "** Primitive ** bagsplit expected a tensor output but found %a" pp_type oty ) >>= fun bty -> mapM (fun tm -> Interpreter.interp (TmApp(di, f, tm)) >>= exBool "bagsplit" >>= fun res -> return (tm, res)) b >>= fun lst -> let (lst1, lst2) = List.partition snd lst in return ((bty, List.map fst lst1), (bty, List.map fst lst2)) let bagsumLFun (n : int) (b : term list) : (ty * float list) interpreter = let rec sumUp k xs ys = match k,xs,ys with | 0,_,_ -> [] | _,x::xs,y::ys -> (x +. y)::sumUp (k - 1) xs ys | _,xs,[] -> Util.listTake k xs | _,[],ys -> Util.listTake k ys in mapM (fun t -> Interpreter.interp t >>= exList exNum "bagsumL") b >>= fun numlstlst -> return @@ (TyPrim PrimNum, List.fold_left (sumUp n) [] numlstlst) let bagsumVFun (oty : ty) (n : int) (b : term list) : (ty * term list) interpreter = let rec sumUp k xs ys = match k,xs,ys with | 0,_,_ -> [] | _,x::xs,y::ys -> (x +. y)::sumUp (k - 1) xs ys | _,xs,[] -> Util.listTake k xs | _,[],ys -> Util.listTake k ys in mapM (fun t -> Interpreter.interp t >>= exVector "bagsumV" >>= mapM (fun t' -> Interpreter.interp t' >>= exNum "bagsumV")) b >>= fun numlstlst -> return (oty, List.map (mkNum di) (List.fold_left (sumUp n) [] numlstlst)) let addNoiseFun (eps : float) (n : float) : float interpreter = onlyInFullEval "addNoise" >> return (n +. Math.lap (1.0 /. eps)) : num[s ] - > num[k ] - > ( R - > DB -o[k ] num ) - > R bag - > DB -o[s ] fuzzy R let reportNoisyMaxFun (eps : float) (k : float) (quality : term) (rbag : term list) (db : term) : term interpreter = onlyInFullEval "reportNoisyMax" >> mapM (fun r -> Interpreter.interp (TmApp(di, TmApp(di, quality, r), db)) >>= exNum "reportNoisyMax" >>= fun q -> return (r, q +. Math.lap (k /. eps))) rbag >>= fun problist -> Support.Error.message 0 Support . Options . Interpreter Support.FileInfo.dummyinfo " --- reportNoisyMax : Probabilities are : % s " ( String.concat " , " ( List.map ( fun x - > string_of_float ( snd x ) ) problist ) ) ; "--- reportNoisyMax: Probabilities are: %s" (String.concat "," (List.map (fun x -> string_of_float (snd x)) problist));*) let (res, _i) = List.fold_left (fun best r -> if abs_float (snd r) > abs_float (snd best) then r else best) (mkUnit di (), 0.0) problist in return res let expMechFun (eps : float) (k : float) (quality : term) (rbag : term list) (db : term) : term interpreter = onlyInFullEval "expMech" >> mapM (fun r -> Interpreter.interp (TmApp(di, TmApp(di, quality, r), db)) >>= exNum "expMech" >>= fun q -> return (r, exp (eps *. q /. (2.0 *. k)))) rbag >>= fun reslist -> let total = List.fold_left (+.) 0.0 (List.map snd reslist) in let rec sampleLst (p : float) (lst : ('a * float) list) : 'a interpreter = match lst with | [] -> fail_pp "**Primitive** expMechFun was given an empty list." | (a,x)::xs -> if p < x then return a else sampleLst (p -. x) xs in sampleLst (Math.randFloat total) (List.sort (fun a b -> truncate (snd b -. snd a)) reslist) let aboveThresholdFun (thisTerm : term) (ty : ty) (eps : float) (k : float) (t : float) (db : term) : term interpreter = onlyInFullEval "aboveThreshold" >> (match ty with | TyPrim1 (Prim1Fuzzy, TyPrim1 (Prim1Token, TyLollipop(argtype, _, outtype))) -> return (TyLollipop(argtype, SiConst k, outtype)) | _ -> fail_pp "**Primitive** aboveThreshold found an unexpected return type: %a" pp_type ty ) >>= fun ftype -> match !useCompiler with | true -> begin match Codegen.runCompiled (!rzFileName) di thisTerm (TyPrim1 (Prim1Token, ftype)) with | Error s -> fail @@ "**Primitive** aboveThreshold failed with message: "^s | Ok r -> return r end | false -> let index = List.length (!curatormem) in curatormem := List.append !curatormem [Some (t +. Math.lap (2.0 /. (eps *. k)), eps, db)]; return (mkToken di (index, ftype)) let rec updateNth (lst : 'a list) (index : int) (f : 'a -> 'a) : 'a list = match lst, index with | [],_ -> [] | x::xs, 0 -> f x :: xs | x::xs, n -> x :: updateNth xs (n-1) f let queryATFun (thisTerm : term) (oty : ty) (tok : (int * ty)) (q : term) : term interpreter = onlyInFullEval "aboveThreshold query" >> match tok with | (index, TyLollipop(_, SiConst k, TyPrim PrimNum)) -> begin match Tycheck.type_of q (Ctx.empty_context, 0, true, Some (!pinterpLimit, Interpreter.genPinterp)) with | Ok (TyLollipop(_, SiConst n, _), _) when n <= k -> begin match !useCompiler with | true -> begin match Codegen.runCompiled (!rzFileName) di thisTerm oty with | Error s -> fail @@ "**Primitive** aboveThresholdQuery failed with message: "^s | Ok res -> return res end | false -> begin match List.nth (!curatormem) index with | None -> return (Left ()) | Some (t,eps,db) -> Interpreter.interp (TmApp(di, q, db)) >>= exNum "aboveThreshold" >>= fun res -> if res +. Math.lap (4.0 /. eps) >= t then (curatormem := updateNth !curatormem index (fun _ -> None); return (Right true)) else return (Right false) end >>= (fun res -> return ((mkSum mkUnit mkBool) di (TyPrim PrimUnit, TyPrim PrimBool, res))) end | Ok (TyLollipop(_, SiConst n, _), _) -> fail_pp "**Primitive** aboveThreshold expected a %F-sensitive function but found a %F-sensitive function" k n | Ok (TyLollipop(_, SiInfty, _), _) -> fail_pp "**Primitive** aboveThreshold expected a %F-sensitive function but found an infinitely sensitive function" k | Ok (TyLollipop(_, si, _), _) -> fail_pp "**Primitive** aboveThreshold found an unexpected sensitivity: %a" pp_si si | Ok (tyf, _) -> fail_pp "**Primitive** aboveThreshold's function argument has non-lollipop type: %a" pp_type tyf | Error (d,e) -> fail_pp "TYPE FAIL: %a %a" pp_fileinfo e.i (pp_tyerr d) e.v end | _ -> fail_pp "**Primitive** aboveThreshold received an inappropriate or malformed token." let selectFun (ty : ty) (beta : float) (bag : term list) : (ty * term list) interpreter = onlyInFullEval "select" >> return (ty, Math.sampleList beta bag) let bagFromFileFun (oty : ty) (maxsize : int) (fn : string) : (ty * term list) interpreter = let lines = fileLines maxsize fn in match oty with | TyPrim1 (Prim1Bag, subty) -> begin match Option.opt_bind_list (List.map (stringToFuzz di subty) lines) with | Some lst -> return (oty, lst) | None -> fail_pp "**Primitive** bagFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** bagFromFile found a weird type %a." pp_type oty let rec listFromFileFun (oty : ty) (maxsize : int) (fn : string) : (ty * ty * term list) interpreter = let lines = fileLines maxsize fn in match oty with | TyMu (_, TyUnion (TyPrim PrimUnit, TyTensor (subty, TyVar _))) -> begin match Option.opt_bind_list (List.map (stringToFuzz di subty) lines) with | Some lst -> return (subty, oty, lst) | None -> fail_pp "**Primitive** listFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** listFromFile found a weird type %a." pp_type oty let listbagFromFileFun (oty : ty) (maxsize : int) (fn : string) (rexp : string) : (ty * (ty * ty * term list) list) interpreter = let lines = fileLines maxsize fn in match oty with | TyPrim1 (Prim1Bag, (TyMu (_, TyUnion (TyPrim PrimUnit, TyTensor (subty, TyVar _))) as listty)) -> begin let lineFun line = Option.map (fun lst -> (subty, listty, lst)) in match Option.opt_bind_list (List.map lineFun lines) with | Some lst -> return (oty, lst) | None -> fail_pp "**Primitive** listbagFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** listbagFromFile found a weird type %a." pp_type oty let vectorbagFromFileFun (oty : ty) (maxsize : int) (fn : string) (rexp : string) : (ty * (ty * term list) list) interpreter = let lines = fileLines maxsize fn in match oty with | TyPrim1 (Prim1Bag, (TyPrim1 (Prim1Vector, subty) as vecty)) -> begin let lineFun line = Option.map (fun lst -> (vecty, lst)) (Option.opt_bind_list (List.map (stringToFuzz di subty) (Str.split (Str.regexp rexp) line))) in match Option.opt_bind_list (List.map lineFun lines) with | Some lst -> return (oty, lst) | None -> fail_pp "**Primitive** vectorbagFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** vectorbagFromFile found a weird type %a." pp_type oty let labeledVectorbagFromFileFun (oty : ty) (maxsize : int) (fn : string) (rexp : string) : (ty * (term * (ty * term list)) list) interpreter = let lines = fileLines maxsize fn in match oty with | TyPrim1 (Prim1Bag, TyTensor (_, (TyPrim1 (Prim1Vector, subty) as vecty))) -> begin let lineFun line = Option.map (fun lst -> (List.hd lst, (vecty, List.tl lst))) (Option.opt_bind_list (List.map (stringToFuzz di subty) (Str.split (Str.regexp rexp) line))) in match Option.opt_bind_list (List.map lineFun lines) with | Some lst -> return (oty, lst) | None -> fail_pp "**Primitive** labeledVectorbagFromFile failed. Perhaps it used an unsupported output type %a." pp_type oty end | _ -> fail_pp "**Primitive** labeledVectorbagFromFile found a weird type %a." pp_type oty let showVecFun (f : term) (v : term list) : string interpreter = mapM (fun t -> Interpreter.interp (TmApp(di, f, t)) >>= exString "showVec") v >>= fun strList -> return @@ String.concat "," strList let vconsFun (oty : ty) (x : term) (xs : term list) : (ty * term list) interpreter = return (oty, x::xs) let vunconsFun (oty : ty) (v : term list) : (ty * ty * (unit, term * (ty * term list)) either) interpreter = (match oty with | TyUnion (tyl, TyTensor (tyx, tyxvec)) -> return (tyl, TyTensor (tyx, tyxvec), tyxvec) | _ -> fail_pp "**Primitive** vuncons found a weird type %a." pp_type oty ) >>= fun (tyl, tyr, tyxvec) -> match v with | [] -> return (tyl, tyr, Left ()) | x::xs -> return (tyl, tyr, Right (x, (tyxvec, xs))) let listToVectorFun (oty : ty) (lst : term list) : (ty * term list) interpreter = return (oty, lst) let vectorToListFun (oty : ty) (lst : term list) : (ty * term list) interpreter = (match oty with | TyMu (_, TyUnion (TyPrim PrimUnit, TyTensor (subty, TyVar _))) -> return subty | _ -> fail_pp "**Primitive** vectorToList found a weird type %a." pp_type oty ) >>= fun subty -> return (subty, lst) let vindexFun (def : term) (i : int) (v : term list) : term = let rec nth i lst = match lst with | [] -> def | x::xs -> if i <= 0 then x else nth (i-1) xs in nth i v let vperformAtFun (oty : ty) (i : int) (f : term) (v : term list) : (ty * term list) interpreter = if i >= List.length v || i < 0 then fail_pp "**Primitive** vperformAt had an out-of-bounds list index %a." pp_type oty else let rec inner i l = match i,l with | _,[] -> return [] | 0,x::xs -> Interpreter.interp (TmApp(di, f, x)) >>= fun x' -> return (x'::xs) | _,x::xs -> inner (i-1) xs >>= fun xs' -> return (x::xs') in inner i v >>= fun res -> return (oty, res) let vzipwithFun (oty : ty) (f : term) (lst1 : term list) (lst2 : term list) : (ty * term list) interpreter = let rec zip l1 l2 = match l1, l2 with | x::xs, y::ys -> (x, y)::(zip xs ys) | _,_ -> [] in mapM (fun (t1, t2) -> Interpreter.interp (TmApp(di, TmApp(di, f, t1), t2)) >>= exAny "vzipwith") (zip lst1 lst2) >>= fun lst' -> return (oty, lst') let rec vfilterFun (ty : ty) (test : term) (lst : term list) : (ty * term list) interpreter = match lst with | x::xs -> Interpreter.interp (TmApp(di, test, x)) >>= exBool "vfilter" >>= fun b -> vfilterFun ty test xs >>= fun (ty,ts) -> return (ty, if b then x::ts else ts) | _ -> return (ty,[]) let vfuzzFun (ty : ty) (lst : term list) : (ty * term list) interpreter = match ty with | TyPrim1 (Prim1Fuzzy, vty) -> return (vty, List.map (fun x -> TmUnPVal (di, x)) lst) | _ -> fail_pp "**Primitive** vfuzz found a weird type %a." pp_type ty let rec vfoldlFun (f : term) (a : term) (blst : term list) : term interpreter = match blst with | [] -> return a | b::bs -> Interpreter.interp (TmApp(di, TmApp(di, f, a), b)) >>= fun x -> vfoldlFun f x bs Core primitive definitions for the runtime let prim_list : (string * primfun) list = [ ("_fst", fun_of_1arg "_fst" (exAmp exAny exAny) mkAny fst); ("_snd", fun_of_1arg "_snd" (exAmp exAny exAny) mkAny snd); ("_lor", fun_of_2args "_lor" exBool exBool mkBool ( || )); ("_land", fun_of_2args "_land" exBool exBool mkBool ( && )); ("_eq", fun_of_2args "_eq" exAny exAny mkBool Syntax.tmEq); Numerical Comparison Operators ("_lt", fun_of_2args "_lt" exNum exNum mkBool ( < )); ("_gt", fun_of_2args "_gt" exNum exNum mkBool ( > )); ("_lte", fun_of_2args "_lte" exNum exNum mkBool ( <= )); ("_gte", fun_of_2args "_gte" exNum exNum mkBool ( >= )); Numerical Computation Operators ("_add", fun_of_2args "_add" exNum exNum mkNum ( +. )); ("_sub", fun_of_2args "_sub" exNum exNum mkNum ( -. )); ("_mul", fun_of_2args "_mul" exNum exNum mkNum ( *. )); ("_div", fun_of_2args "_div" exNum exNum mkNum ( /. )); ("_exp", fun_of_1arg "_exp" exNum mkNum ( exp )); ("_log", fun_of_1arg "_log" exNum mkNum ( log )); ("_abs", fun_of_1arg "_abs" exNum mkNum ( abs_float )); ("cswp", fun_of_1arg "cswp" (exPair exNum exNum) (mkPair mkNum mkNum) (fun (x,y) -> if x < y then (x,y) else (y,x))); Integer primitives ("_iadd", fun_of_2args "_iadd" exInt exInt mkInt ( + )); ("_isub", fun_of_2args "_isub" exInt exInt mkInt ( - )); ("_imul", fun_of_2args "_imul" exInt exInt mkInt ( * )); ("_idiv", fun_of_2args "_idiv" exInt exInt mkInt ( / )); ("intToPeano", fun_of_1arg_with_type_i "intToPeano" exInt mkAny intToPeanoFun); ("clip", fun_of_1arg "clip" exNum mkClipped (fun x -> x)); ("fromClip", fun_of_1arg "fromClip" exNum mkNum (fun x -> x)); ("string_cc", fun_of_2args "string_cc" exString exString mkString ( ^ )); ("showNum", fun_of_1arg "showNum" exNum mkString ( fun n -> if n = floor n then string_of_int (truncate n) else string_of_float n )); ("showInt", fun_of_1arg "showInt" exInt mkString ( string_of_int )); ("showBag", fun_of_2args_i "showBag" exFun exBag mkString showBagFun); ("showVec", fun_of_2args_i "showVec" exFun exVector mkString showVecFun); ("readNum", fun_of_1arg "readNum" exString mkNum readNumFun); ("readInt", fun_of_1arg "readInt" exString mkInt readIntFun); ("_assert", fun_of_2args "_assert" exString exBool mkUnit assertFun); ("assertEq", fun_of_3args "assertEq" exString exAny exAny mkUnit assertEqFun); ("print", fun_of_1arg "print" exString mkUnit (fun s -> ignore (printMsg di "%s" s))); ("_return", fun_of_1arg_i "_return" exAny (mkPVal mkAny) (fun x -> onlyInFullEval "return" >> return x)); ("loadDB", fun_of_2args_i "loadDB" exFun (exPair exNum exNum) mkUnit storeDB); ("tyCheckFuzz", fun_of_2args_i "tyCheckFuzz" exNum exAny mkAny tyCheckFuzzFun); ("runFuzz", fun_of_2args_with_type_i "runFuzz" exNum exFun (mkSum mkString mkAny) runFuzz); ("getDelta", fun_of_1arg_i "getDelta" exAny mkNum (fun _ -> onlyInFullEval "getDelta" >> getDelta)); ("getEpsilon", fun_of_1arg_i "getEpsilon" exAny mkNum (fun _ -> onlyInFullEval "getEpsilon" >> getEpsilon)); ("emptybag", fun_of_no_args_with_type_i "emptybag" mkBag (fun ty -> return (ty,[]))); ("addtobag", fun_of_2args_with_type_i "addtobag" exAny exBag mkBag (fun ty x xs -> return (ty, x::xs))); ("bagjoin", fun_of_2args_with_type_i "bagjoin" exBag exBag mkBag (fun ty b1 b2 -> return (ty, List.append b1 b2))); ("bagsize", fun_of_1arg "bagsize" exBag mkInt ( List.length )); ("bagsum", fun_of_1arg_i "bagsum" exBag mkNum (fun l -> mapM (fun t -> Interpreter.interp t >>= exNum "bagsum") l >>= fun l' -> return (List.fold_left (+.) 0.0 l'))); ("bagfoldl", fun_of_3args_i "bagfoldl" exAny exAny exBag mkAny bagfoldlFun); ("bagmap", fun_of_2args_with_type_i "bagmap" exFun exBag mkBag bagmapFun); ("bagsplit", fun_of_2args_with_type_i "bagsplit" exFun exBag (mkPair mkBag mkBag) bagsplitFun); ("bagsumL", fun_of_2args_i "bagsumL" exInt exBag (mkList mkNum) bagsumLFun); ("bagsumV", fun_of_2args_with_type_i "bagsumV" exInt exBag mkVector bagsumVFun); ("addNoise", thunkify "addNoise" "addNoiseP" (fun_of_2args_i "addNoiseP" exNum exNum mkNum addNoiseFun)); ("reportNoisyMax", thunkify "reportNoisyMax" "reportNoisyMaxP" (fun_of_5args_i "reportNoisyMaxP" exNum exNum exFun exBag exAny mkAny reportNoisyMaxFun)); ("expMech", thunkify "expMech" "expMechP" (fun_of_5args_i "expMechP" exNum exNum exFun exBag exAny mkAny expMechFun)); ("select", fun_of_2args_with_type_i "select" exNum exBag mkBag selectFun); ("aboveThreshold", thunkify "aboveThreshold" "aboveThresholdP" (fun_of_4args_with_type_i_self "aboveThresholdP" exNum exNum exNum exAny mkAny aboveThresholdFun)); ("queryAT", fun_of_2args_with_type_i_self "queryAT" exToken exFun mkAny queryATFun); ("bagFromFile", fun_of_2args_with_type_i "bagFromFile" exInt exString mkBag bagFromFileFun); ("listFromFile", fun_of_2args_with_type_i "listFromFile" exInt exString (mkListWithType mkAny) listFromFileFun); ("listbagFromFile", fun_of_3args_with_type_i "listbagFromFile" exInt exString exString (mkBag' (mkListWithType mkAny)) listbagFromFileFun); ("vectorbagFromFile", fun_of_3args_with_type_i "vectorbagFromFile" exInt exString exString (mkBag' mkVector) vectorbagFromFileFun); ("labeledVectorbagFromFile", fun_of_3args_with_type_i "labeledVectorbagFromFile" exInt exString exString (mkBag' (mkPair mkAny mkVector)) labeledVectorbagFromFileFun); ("vcons", fun_of_2args_with_type_i "vcons" exAny exVector mkVector vconsFun); ("vuncons", fun_of_1arg_with_type_i "vuncons" exVector (mkSum mkUnit (mkPair mkAny mkVector)) vunconsFun); ("listToVector", fun_of_1arg_with_type_i "listToVector" (exList exAny) mkVector listToVectorFun); ("vectorToList", fun_of_1arg_with_type_i "vectorToList" exVector (mkList mkAny) vectorToListFun); ("vindex", fun_of_3args "vindex" exAny exInt exVector mkAny vindexFun); ("vperformAt", fun_of_3args_with_type_i "vperformAt" exInt exFun exVector mkVector vperformAtFun); ("vfoldl", fun_of_3args_i "vfoldl" exAny exAny exVector mkAny vfoldlFun); ("vmap", fun_of_2args_with_type_i "vmap" exFun exVector mkVector bagmapFun); ("vsmap", fun_of_3args_with_type_i "vsmap" exNum exFun exVector mkVector (fun ty _ -> bagmapFun ty)); ("vfilter", fun_of_2args_with_type_i "vfilter" exFun exVector mkVector vfilterFun); ("vzipwith", fun_of_3args_with_type_i "vzipwith" exFun exVector exVector mkVector vzipwithFun); ("vszipwith", fun_of_5args_with_type_i "vszipwith" exNum exNum exFun exVector exVector mkVector (fun ty _ _ -> vzipwithFun ty)); ("vfuzz", fun_of_1arg_with_type_i "vfuzz" exVector (mkPVal mkVector) vfuzzFun); ("vsize", fun_of_1arg "vsize" exVector mkInt ( List.length )); ( " vsum " , fun_of_1arg_i " vsum " exVector mkNum ( fun l - > mapM ( fun t - > Interpreter.interp t > > = exNum " vsum " ) l > > = fun l ' - > return ( List.fold_left ( + . ) 0.0 l ' ) ) ) ; (fun l -> mapM (fun t -> Interpreter.interp t >>= exNum "vsum") l >>= fun l' -> return (List.fold_left (+.) 0.0 l')));*) ] let lookup_prim (id : string) : primfun option = let rec lookup l = match l with | [] -> None | (s, t) :: l' -> if s = id then Some t else lookup l' in lookup prim_list
59873f45941e5cecc648a9b6b6bc9f81bf22eb25d677387287578a5d51b8213f
tolysz/prepare-ghcjs
Micro.hs
module Main (main) where import Prelude () import Prelude.Compat import Criterion.Main import qualified Data.Aeson.Encoding.Builder as AB import qualified Data.ByteString.Builder as B import qualified Data.Text as T main :: IO () main = do let txt = "append (append b (primBounded w1 x1)) (primBounded w2 x2)" defaultMain [ bgroup "string" [ bench "text" $ nf (B.toLazyByteString . AB.text) (T.pack txt) , bench "string direct" $ nf (B.toLazyByteString . AB.string) txt , bench "string via text" $ nf (B.toLazyByteString . AB.text . T.pack) txt ] ]
null
https://raw.githubusercontent.com/tolysz/prepare-ghcjs/8499e14e27854a366e98f89fab0af355056cf055/spec-lts8/aeson/benchmarks/Micro.hs
haskell
module Main (main) where import Prelude () import Prelude.Compat import Criterion.Main import qualified Data.Aeson.Encoding.Builder as AB import qualified Data.ByteString.Builder as B import qualified Data.Text as T main :: IO () main = do let txt = "append (append b (primBounded w1 x1)) (primBounded w2 x2)" defaultMain [ bgroup "string" [ bench "text" $ nf (B.toLazyByteString . AB.text) (T.pack txt) , bench "string direct" $ nf (B.toLazyByteString . AB.string) txt , bench "string via text" $ nf (B.toLazyByteString . AB.text . T.pack) txt ] ]
069e4f47db5ff3fabb0307c2b3a038da96047357f88eabcadef2d1e887714a64
gethop-dev/hop-cli
user.cljs
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this ;; file, You can obtain one at / {{=<< >>=}} (ns <<project.name>>.client.user (:require [<<project.name>>.client.util :as util] [ajax.core :as ajax] [dev.gethop.session.re-frame.cognito.token :as session.token] [re-frame.core :as rf])) (rf/reg-sub ::user-data (fn [db _] (get db :user))) (rf/reg-event-db ::set-user-data (fn [db [_ user]] (assoc db :user user))) (defn- fetch-user-data-event-fx "This event handler gets jwt-token from session cofx instead of appdb. It is so because at times the token may not be present in appdb yet when ::ensure-data is called." [{:keys [session] :as _cofx} _] {:http-xhrio {:headers {"Authorization" (str "Bearer " (:id-token session))} :method :get :uri "/api/user" :format (ajax/transit-request-format) :response-format (ajax/transit-response-format) :on-success [::set-user-data] :on-failure [::util/generic-error]}}) (rf/reg-event-fx ::fetch-user-data [(rf/inject-cofx ::session.token/session)] fetch-user-data-event-fx)
null
https://raw.githubusercontent.com/gethop-dev/hop-cli/c7b848915ff268aa41ff9a61a62c614f58ecbeb9/resources/bootstrap/profiles/authentication/cognito/app/src/%7B%7Bproject.files-name%7D%7D/client/user.cljs
clojure
file, You can obtain one at /
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this {{=<< >>=}} (ns <<project.name>>.client.user (:require [<<project.name>>.client.util :as util] [ajax.core :as ajax] [dev.gethop.session.re-frame.cognito.token :as session.token] [re-frame.core :as rf])) (rf/reg-sub ::user-data (fn [db _] (get db :user))) (rf/reg-event-db ::set-user-data (fn [db [_ user]] (assoc db :user user))) (defn- fetch-user-data-event-fx "This event handler gets jwt-token from session cofx instead of appdb. It is so because at times the token may not be present in appdb yet when ::ensure-data is called." [{:keys [session] :as _cofx} _] {:http-xhrio {:headers {"Authorization" (str "Bearer " (:id-token session))} :method :get :uri "/api/user" :format (ajax/transit-request-format) :response-format (ajax/transit-response-format) :on-success [::set-user-data] :on-failure [::util/generic-error]}}) (rf/reg-event-fx ::fetch-user-data [(rf/inject-cofx ::session.token/session)] fetch-user-data-event-fx)
6d0fcf59879fc480ea41d272d2c392f4dcda6fc343be7b7875efc1a6217cb61b
codinuum/cca
cpp_unparsing.ml
Copyright 2012 - 2020 Codinuum Software Lab < > Copyright 2020 Chiba Institute of Technology Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2012-2020 Codinuum Software Lab <> Copyright 2020 Chiba Institute of Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) Author : < > (* * An unparser for C/C++ * * cpp_unparsing.ml * *) module L = Cpp_label module Tree = Sourcecode.Tree (L) open Unparsing_base (*******) let _pr_semicolon() = pr_string ";" let pr_semicolon() = _pr_semicolon(); pr_space() let pr_colon_colon() = pr_string "::" let pr_lt() = pr_string "<" let pr_gt() = pr_string ">" let pr_if_newline = Format.print_if_newline class ppbox_ = object (self) inherit ppbox as super val mutable block_style = BSshort method pr_block_head() = match block_style with | BStall -> pr_cut(); pr_lbrace(); self#open_vbox self#indent; pr_cut() | BSshort -> pr_lbrace(); pr_space(); self#open_vbox self#indent; pr_if_newline(); pad self#indent method pr_block_end() = self#close_box(); pr_space(); pr_rbrace() method pr_else() = match block_style with | BStall -> pr_space(); pr_string "else"; pr_space() | BSshort -> pr_string " else " end (*******) let pb = new ppbox_ let error_symbol = "###" let getlab nd = match nd#data#orig_lab_opt with | Some o -> (Obj.obj o : L.t) | None -> (Obj.obj nd#data#_label : L.t) let has_orig_lab nd = match nd#data#orig_lab_opt with | Some o -> (Obj.obj o : L.t) <> (Obj.obj nd#data#_label : L.t) | None -> false let get_nth_children = Tree._get_logical_nth_child let rec pr_node ?(fail_on_error=true) ?(va=false) ?(prec=0) node = let pr_node_ = pr_node ~fail_on_error in let children = node#initial_children in let nchildren = Array.length children in let pr_nth_child = if fail_on_error then fun ?(va=false) ?(prec=0) nth -> pr_node ~fail_on_error:true ~va ~prec children.(nth) else fun ?(va=false) ?(prec=0) nth -> try pr_node ~fail_on_error:false ~va ~prec children.(nth) with _ -> pr_string error_symbol in let nth_children = get_nth_children node in let pr_nth_children ?(head=pr_none) ?(tail=pr_none) = if fail_on_error then begin fun ?(va=false) ?(prec=0) nth -> let ca = nth_children nth in let non_empty = ca <> [||] in if non_empty then head(); pb#pr_a pad1 (pr_node ~fail_on_error:true ~va ~prec) ca; if non_empty then tail() end else fun ?(va=false) ?(prec=0) nth -> try let ca = get_nth_children node nth in let non_empty = ca <> [||] in if non_empty then head(); pb#pr_a pad1 (pr_node ~fail_on_error:false ~va ~prec) ca; if non_empty then tail() with _ -> pr_string error_symbol in let pr_macro_invocation i = pr_string i; pr_lparen(); pb#pr_a pr_comma pr_node_ children; pr_rparen() in let pr_seq ?(head=pr_none) ?(sep=pad1) ?(tail=pr_none) () = pb#pr_a ~head ~tail sep pr_node_ children in let prefix = node#data#get_prefix in if prefix <> "" then pr_string prefix; begin match getlab node with | DUMMY -> () | EMPTY -> () | AMBIGUOUS_CONSTRUCT -> pr_seq() | PARTIAL_CONSTRUCT -> pr_seq() | DECLS -> pr_seq ~sep:pr_cut () | MEM_DECLS -> pr_seq ~sep:pr_cut () | STMTS -> pb#open_vbox 0; pr_seq ~sep:pr_cut (); pb#close_box() | INITS -> pr_seq ~sep:pr_comma () | LABELS -> pr_seq() | SPECS -> pr_seq() | ETORS -> pr_seq ~sep:pr_comma () | TEMPL_PARAMS -> pr_seq ~sep:pr_comma () | TEMPL_ARGS -> pr_seq ~sep:pr_comma () | DELIM_MACRO i -> begin for i = 0 to nchildren - 2 do if i > 0 then pr_comma(); pr_node ~fail_on_error children.(i) done; pr_id i; pr_node ~fail_on_error children.(nchildren-1) end | Q_PROPERTY -> begin pr_id "Q_PROPERTY"; pr_lparen(); pb#pr_a pad1 pr_node_ children; pr_rparen() end | TranslationUnit -> pb#open_vbox 0; pb#pr_a pr_cut pr_node_ children; pb#close_box() PpDirective | PpInclude s -> pr_string "#include "; pr_string s | PpDefine i -> begin pb#enable_backslash_newline(); pr_string "#define "; pr_id i; if nchildren > 0 then pr_nth_child 0; pb#disable_backslash_newline() end | PpUndef i -> pr_string "#undef " ; pr_id i | PpLine (j, s) -> pr_string "#line "; pr_int j; pad1(); pr_string s | PpError s -> pr_string "#error "; pr_string s | PpPragma s -> pr_string "#pragma "; pr_string s | PpNull -> pr_string "#" | PpMarker(j, s, jl) -> begin pr_string "# "; pr_int j; pad1(); pr_string s; pr_string (String.concat " " (List.map string_of_int jl)) end | PpIf _ -> pr_string "#if "; pb#pr_a pad1 pr_node_ children | PpIfdef i -> pr_string "#ifdef "; pr_id i | PpIfndef i -> pr_string "#ifndef "; pr_id i | PpElif _ -> pr_string "#elif "; pb#pr_a pad1 pr_node_ children | PpElse _ -> pr_string "#else" | PpEndif _ -> pr_string "#endif" | PpUnknown s -> pr_string "#"; pr_string s | PpImport s -> pr_string "#import "; pr_string s | OmpDirective s -> pr_string "#pragma omp ";pr_string s | AccDirective s -> pr_string "#pragma acc ";pr_string s | PpIfSection _ | PpIfSectionFuncDef _ | PpIfSectionAltFuncDef | PpIfSectionBroken | PpIfSectionBrokenIf | PpIfSectionBrokenFuncDef | PpIfSectionBrokenDtorFunc | PpIfSectionCondExpr | PpIfSectionLogicalAnd | PpIfSectionLogicalOr | PpIfSectionTemplDecl | PpIfSectionHandler | PpIfSectionTryBlock -> begin force_newline(); pb#open_vbox 0; pb#pr_a pr_cut pr_node_ children; pb#close_box(); force_newline() end | PpIfGroup _ -> pb#pr_a pr_cut pr_node_ children | PpElifGroup _ -> pb#pr_a pr_cut pr_node_ children | PpElseGroup _ -> pb#pr_a pr_cut pr_node_ children | PpStringized s -> pr_string s | PpMacroParam s -> pr_string s (* Declaration *) | SimpleDeclaration -> pb#open_hbox(); pr_seq(); pb#close_box() | AsmDefinition s -> pr_nth_children 0; pr_string "asm"; pr_nth_children 1 | NamespaceAliasDefinition i -> begin pr_string "namespace "; pr_id i; pr_eq(); pr_nth_child 0 end | UsingDeclaration -> pr_string "using "; pr_seq ~sep:pr_comma () | UsingDirective i -> begin pr_nth_children 0; pr_string "using namespace "; pr_nth_children 1 end | Static_assertDeclaration -> begin pr_string "static_assert"; pr_lparen(); pr_nth_children 0; pr_nth_children ~head:pr_comma 1; pr_rparen() end | AliasDeclaration i -> begin pr_string "using "; pr_id i; pr_nth_children 0; pr_eq(); pr_nth_children 1 end | OpaqueEnumDeclaration -> pr_string "enum "; pr_seq() | OpaqueEnumDeclarationClass -> pr_string "enum class "; pr_seq() | OpaqueEnumDeclarationStruct -> pr_string "enum struct "; pr_seq() | OpaqueEnumDeclarationMacro i -> pr_id i; pad1(); pr_seq() | NodeclspecFunctionDeclaration -> pr_seq() | FunctionDefinition _ -> pr_seq() | NestedFunctionDefinition _ -> pr_seq() | TemplateDeclaration -> pr_nth_child 0; pr_space(); pr_nth_child 1 | DeductionGuide n -> begin pr_id n; pr_lparen(); pr_nth_children 1; pr_rparen(); pr_string " -> "; pr_nth_children 2; _pr_semicolon() end | ExplicitInstantiation -> pr_nth_children 0; pr_string "template "; pr_nth_children 1 | ExplicitSpecialization -> pr_string "template<>"; pr_nth_child 0; | LinkageSpecification s -> begin pr_string "extern "; pr_string s; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ children; pb#pr_block_end() end | NamedNamespaceDefinition i -> begin let has_ns = try not (L.is_namespace_head (getlab (nth_children 0).(0))) with _ -> true in pr_nth_children 0; if has_ns then pr_string "namespace "; pr_nth_children 1; pr_id i; pr_nth_children 2; if nth_children 3 <> [||] then begin pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 3); pb#pr_block_end() end end | UnnamedNamespaceDefinition -> begin pr_nth_children 0; pr_string "namespace "; pr_nth_children 1; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 2); pb#pr_block_end() end | NestedNamespaceDefinition i -> begin pr_string "namespace "; pr_nth_child 0; pr_colon_colon(); pr_nth_children 1; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 2); pb#pr_block_end() end | NamespaceDefinitionMacro i -> pr_id i | EmptyDeclaration -> _pr_semicolon() | AttributeDeclaration -> pr_seq() | DeclarationMacro i -> pr_id i | DeclarationMacroInvocation i -> pr_macro_invocation i | DeclarationMacroInvocationInvocation -> begin pr_nth_child 0; pr_lparen(); pb#pr_a pr_comma pr_node_ (nth_children 1); pr_rparen() end | DeclarationMacroInvocationArrow -> pr_nth_child 0; pr_string "->"; pr_nth_children 1; pr_nth_children 2 | DeclarationMacroInvocationDot -> pr_nth_child 0; pr_string "."; pr_nth_children 1; pr_nth_children 2 | ImportDeclaration s -> pr_string "import "; pr_string s (* Statement *) | Statement -> pr_string "<statement>" | ExpressionStatement -> pr_nth_children ~tail:pad1 0; pr_nth_children 1 | DeclarationStatement -> pb#open_hbox(); pr_seq(); pb#close_box() | TryBlock -> pr_string "try "; pr_nth_child 0 | LabeledStatement -> pr_seq() | SelectionStatement -> pr_string "<selection-statement>" | IfStatement -> begin let has_paren = try let lab = getlab (nth_children 2).(0) in not (L.is_expr_macro_ivk lab) && not (L.is_stmt_macro_ivk lab) with _ -> true in pr_string "if "; pr_nth_children 0; if has_paren then pr_lparen(); pr_nth_children 1; pr_nth_children 2; if has_paren then pr_rparen(); pad1(); pr_nth_children 3; pr_nth_children ~head:pb#pr_else 4 end | ElseStatement -> pr_string "else"; pr_seq ~head:pad1 () | SwitchStatement -> pr_string "switch "; pr_seq() (*| EmptyStatement -> _pr_semicolon()*) | CompoundStatement -> begin if nchildren = 0 then pr_string "{}" else begin pb#pr_block_head(); pr_seq ~sep:pr_cut (); pb#pr_block_end() end end | IterationStatement -> pr_string "<iteration-statement>" | WhileStatement -> pr_string "while "; pr_lparen(); pr_nth_children 0; pr_rparen(); pr_nth_children 1 | DoStatement -> begin pr_string "do "; pr_nth_children 0; if nth_children 1 <> [||] then begin pr_string "while "; pr_lparen(); pr_nth_children 1; pr_rparen(); _pr_semicolon() end end | ForStatement -> begin pb#open_hbox(); pr_string "for "; pr_lparen(); pr_nth_child 0; pad1(); pr_nth_children 1; pr_semicolon(); pr_nth_children 2; pr_rparen(); pad1(); pb#close_box(); pr_nth_children 3 end | ForInStatement -> begin pr_string "for "; pr_lparen(); pr_nth_children 0; pr_string " in "; pr_nth_children 1; pr_rparen(); pr_nth_children 2 end | RangeBasedForStatement -> begin pr_string "for "; pr_lparen(); pr_nth_children 0; pr_nth_children 1; pr_colon(); pr_nth_children 2; pr_rparen(); pr_nth_children 3 end | JumpStatement -> pr_string "<jump-statement>" | BreakStatement -> pr_string "break" | ContinueStatement -> pr_string "continue" | ReturnStatement -> begin pr_string "return"; if nchildren > 0 then begin pad1(); pr_nth_child 0; end end | GotoStatement i -> pr_string "goto "; pr_string i | ComputedGotoStatement -> pr_string "goto" | CoroutineReturnStatement -> pr_string "co_return"; pr_nth_children ~head:pad1 0 | StatementMacroInvocation i -> pr_macro_invocation i | StatementMacro i -> pr_id i | IterationMacroInvocation i -> pr_macro_invocation i | IterationMacro i -> pr_id i Expression | This -> pr_string "this" | ParenthesizedExpression -> pr_lparen(); pr_nth_child 0; pr_rparen() | RequiresExpression -> pr_string "requires "; pr_seq() | FoldExpression -> begin pr_lparen(); pr_nth_children 0; pr_nth_children 1; pr_ellipsis(); pr_nth_children 2; pr_nth_children 3; pr_rparen() end | LambdaExpression -> begin pr_nth_child 0; pr_nth_children ~head:pr_lt ~tail:pr_gt 1; pr_nth_children 2; pr_nth_children 3; pr_nth_children 4; pr_nth_children 5 end | LogicalOrExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | LogicalAndExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | InclusiveOrExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | ExclusiveOrExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | AndExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | EqualityExpression -> pr_string "<equality-expression>" | EqualityExpressionEq -> pr_nth_child 0; pr_string " == "; pr_nth_child 1 | EqualityExpressionStrictEq -> pr_nth_child 0; pr_string " === "; pr_nth_child 1 | EqualityExpressionNeq i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | RelationalExpression -> pr_string "<relational-expression>" | RelationalExpressionLt -> pr_nth_child 0; pr_string " < "; pr_nth_child 1 | RelationalExpressionGt -> pr_nth_child 0; pr_string " > "; pr_nth_child 1 | RelationalExpressionLe -> pr_nth_child 0; pr_string " <= "; pr_nth_child 1 | RelationalExpressionGe -> pr_nth_child 0; pr_string " >= "; pr_nth_child 1 | CompareExpression -> pr_string "<=>" | ShiftExpression -> pr_string "<shift-expression>" | ShiftExpressionLeft -> pr_nth_child 0; pr_string " << "; pr_nth_child 1 | ShiftExpressionRight -> pr_nth_child 0; pr_string " >> "; pr_nth_child 1 | ShiftExpressionRightU -> pr_nth_child 0; pr_string " >>> "; pr_nth_child 1 | AdditiveExpression -> pr_string "<additive-expression>" | AdditiveExpressionAdd -> pr_nth_child 0; pr_string " + "; pr_nth_child 1 | AdditiveExpressionSubt -> pr_nth_child 0; pr_string " - "; pr_nth_child 1 | MultiplicativeExpression -> pr_string "<multiplicative-expression>" | MultiplicativeExpressionMult -> pr_nth_child 0; pr_string " * "; pr_nth_child 1 | MultiplicativeExpressionDiv -> pr_nth_child 0; pr_string " / "; pr_nth_child 1 | MultiplicativeExpressionMod -> pr_nth_child 0; pr_string " % "; pr_nth_child 1 | PmExpression -> pr_string "<pm-expression>" | PmExpressionClass -> pr_nth_child 0; pr_string ".*"; pr_nth_child 1 | PmExpressionPtr -> pr_nth_child 0; pr_string "->*"; pr_nth_child 1 | CastExpression -> begin let has_head = try L.is_type_macro_ivk (getlab children.(0)) with _ -> false in if has_head then pr_seq() else begin pr_lparen(); pr_nth_children 0; pr_nth_children 1; pr_rparen(); pr_nth_children 2; end end | CompoundLiteralExpression -> pr_lparen(); pr_nth_child 0; pr_rparen(); pr_nth_child 1 | UnaryExpression -> pr_string "<unary-expression>" | UnaryExpressionIncr -> pr_string "++"; pr_nth_child 0 | UnaryExpressionDecr -> pr_string "--"; pr_nth_child 0 | UnaryExpressionInd -> pr_string "*"; pr_nth_child 0 | UnaryExpressionAddr -> pr_string "&"; pr_nth_child 0 | UnaryExpressionLabelAddr -> pr_string "&&"; pr_nth_child 0 | UnaryExpressionPlus -> pr_string "+"; pr_nth_child 0 | UnaryExpressionMinus -> pr_string "-"; pr_nth_child 0 | UnaryExpressionNeg i -> pr_string i; pr_nth_child 0 | UnaryExpressionCompl i -> pr_string i; pr_nth_child 0 | UnaryExpressionSizeof -> pr_string "sizeof "; pr_nth_child 0 | UnaryExpressionSizeofPack i -> pr_string (sprintf "sizeof ... (%s)" i) | UnaryExpressionAlignof -> pr_string "alignof"; pr_lparen(); pr_nth_child 0; pr_rparen() | NoexceptExpression -> pr_string "noexcept"; pr_lparen(); pr_nth_child 0; pr_rparen() | PostfixExpression -> pr_string "<postfix-expression>" | PostfixExpressionSubscr -> pr_nth_child 0; pr_lbracket(); pr_nth_child 1; pr_rbracket() | PostfixExpressionFunCall -> begin pb#open_hbox(); pr_nth_child 0; pr_nth_children 1; pb#close_box() end | PostfixExpressionFunCallGuarded i -> pr_nth_child 0; pr_id i; pr_lparen(); pr_nth_children 1; pr_rparen() | PostfixExpressionFunCallMacro i -> pr_id i | PostfixExpressionExplicitTypeConv -> pr_string "<explicit-type-conversion>" | PostfixExpressionExplicitTypeConvExpr -> pr_nth_children 0; pr_lparen(); pr_nth_children 1; pr_rparen() | PostfixExpressionExplicitTypeConvBraced -> pr_seq() | PostfixExpressionDot -> begin pr_nth_child 0; pr_string "."; pr_nth_children ~tail:pad1 1; pr_nth_children 2 end | PostfixExpressionArrow -> begin pr_nth_child 0; pr_string "->"; pr_nth_children ~tail:pad1 1; pr_nth_children 2 end | PostfixExpressionIncr -> pr_nth_child 0; pr_string "++" | PostfixExpressionDecr -> pr_nth_child 0; pr_string "--" | PostfixExpressionTypeid -> pr_string "typeid" | PostfixExpressionTypeidExpr -> pr_string "typeid"; pr_lparen(); pr_nth_child 0; pr_rparen() | PostfixExpressionTypeidTy -> pr_string "typeid"; pr_lparen(); pr_nth_child 0; pr_rparen() | PostfixExpressionDynamic_cast -> begin pr_string "dynamic_cast<"; pr_nth_child 0; pr_string ">"; if L.is_ident (getlab children.(1)) then pr_nth_child 1 else begin pr_lparen(); pr_nth_child 1; pr_rparen() end end | PostfixExpressionStatic_cast -> begin pr_string "static_cast"; pr_lt(); pr_nth_child 0; pr_gt(); pr_nth_child 1 end | PostfixExpressionReinterpret_cast -> begin pr_string "reinterpret_cast"; pr_lt(); pr_nth_child 0; pr_gt(); pr_nth_child 1 end | PostfixExpressionConst_cast -> begin pr_string "const_cast"; pr_lt(); pr_nth_child 0; pr_gt(); pr_nth_child 1 end | SwiftArg i -> begin pr_id i; pr_colon(); if nchildren > 0 then begin pad1(); pr_nth_child 0 end end | SwiftFunCall -> begin pb#open_hbox(); pr_nth_child 0; pr_nth_children 1; pb#close_box() end | AssignmentExpression -> pr_string "<assignment-expression>" | AssignmentExpressionOverloaded i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_children 1 | AssignmentExpressionEq -> pr_nth_child 0; pr_eq(); pr_nth_children 1 | AssignmentExpressionPlus -> pr_nth_child 0; pr_string " += "; pr_nth_children 1 | AssignmentExpressionMinus -> pr_nth_child 0; pr_string " -= "; pr_nth_children 1 | AssignmentExpressionMult -> pr_nth_child 0; pr_string " *= "; pr_nth_children 1 | AssignmentExpressionDiv -> pr_nth_child 0; pr_string " /= "; pr_nth_children 1 | AssignmentExpressionMod -> pr_nth_child 0; pr_string " %= "; pr_nth_children 1 | AssignmentExpressionShiftLeft -> pr_nth_child 0; pr_string " <<= "; pr_nth_children 1 | AssignmentExpressionShiftRight -> pr_nth_child 0; pr_string " >>= "; pr_nth_children 1 | AssignmentExpressionAnd i | AssignmentExpressionXor i | AssignmentExpressionOr i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_children 1 | ThrowExpression -> pr_string "throw"; pr_nth_children ~head:pad1 0 | ExpressionPair -> pr_seq ~sep:pr_comma () | ConditionalExpression -> pr_seq() | NewExpression -> begin let is_type_id = try L.is_type_id (getlab (nth_children 2).(0)) with _ -> false in pr_nth_children 0; pr_string "new "; pr_nth_children 1; if is_type_id then pr_lparen(); pr_nth_children 2; if is_type_id then pr_rparen(); pr_nth_children 3 end | RefNewExpression -> begin pr_string "ref "; pr_nth_children 0; pr_string "new "; pr_nth_children 1; pr_nth_children 2; pr_nth_children 3 end | DeleteExpression -> pr_nth_children 0; pr_string "delete "; pr_nth_children 1 | DeleteExpressionBracket -> pr_nth_children 0; pr_string "delete[] "; pr_nth_children 1 | YieldExpression -> pr_string "co_yield "; pr_nth_child 0 | AwaitExpression -> pr_string "co_await "; pr_nth_child 0 | BlockLiteralExpression -> pr_string "^"; pr_seq() | ExpressionMacroInvocation i -> pr_macro_invocation i | LogicalOrMacroInvocation i -> pr_macro_invocation i | DefinedMacroExpression i -> pr_string (sprintf "defined(%s)" i) | HasIncludeExpression s -> pr_string (sprintf "__has_include(%s)" s) | HasAttributeExpression -> pr_string "__has_cpp_attribute"; pr_seq ~sep:pr_none () (* Literal *) | Literal -> pr_string "<literal>" | IntegerLiteral v -> pr_string v | CharacterLiteral v -> pr_string v | FloatingLiteral v -> pr_string v | StringLiteral v -> pr_string v | StringMacro i -> pr_id i | BooleanLiteral v -> pr_string v | Nullptr -> pr_string "nullptr" | ConcatenatedString -> pr_seq() | UserDefinedCharacterLiteral v -> pr_string v | UserDefinedStringLiteral v -> pr_string v | UserDefinedFloatingLiteral v -> pr_string v | UserDefinedIntegerLiteral v -> pr_string v | LiteralMacro i -> pr_id i | LiteralMacroInvocation i -> pr_macro_invocation i (* UnqualifiedId *) | UnqualifiedId -> pr_string "<unqualified-id>" | OperatorFunctionId -> pr_string "operator"; pr_nth_child 0 | ConversionFunctionId -> pr_string "operator "; pr_nth_child 0 | LiteralOperatorId i -> pr_string "operator "; pr_nth_children 0; pr_id i | Destructor -> pr_string "~"; pr_nth_child 0 | TemplateId -> pr_string "<template-id>" | TemplateIdOp -> pr_nth_child 0; pr_nth_children ~head:pr_lt ~tail:pr_gt 1 | TemplateIdLit -> pr_nth_child 0; pr_nth_children ~head:pr_lt ~tail:pr_gt 1 (* Operator *) | Operator -> pr_string "<operator>" | New -> pr_string "new" | Delete -> pr_string "delete" | NewBracket -> pr_string "new[]" | DeleteBracket -> pr_string "delete[]" | Parentheses -> pr_string "()" | Brackets -> pr_string "[]" | MinusGt -> pr_string "->" | MinusGtStar -> pr_string "->*" | Tilde i -> pr_string i | Exclam i -> pr_string i | Plus -> pr_string "+" | Minus -> pr_string "-" | Star -> pr_string "*" | Slash -> pr_string "/" | Perc -> pr_string "%" | Hat i -> pr_string i | Amp i -> pr_string i | Bar i -> pr_string i | Eq -> pr_string "=" | PlusEq -> pr_string "+=" | MinusEq -> pr_string "-=" | StarEq -> pr_string "*=" | SlashEq -> pr_string "/=" | PercEq -> pr_string "%=" | HatEq i -> pr_string i | AmpEq i -> pr_string i | BarEq i -> pr_string i | EqEq -> pr_string "==" | ExclamEq i -> pr_string i | Lt -> pr_string "<" | Gt -> pr_string ">" | LtEq -> pr_string "<=" | GtEq -> pr_string ">=" | LtEqGt -> pr_string "<=>" | AmpAmp i -> pr_string i | BarBar i -> pr_string i | LtLt -> pr_string "<<" | GtGt -> pr_string ">>" | LtLtEq -> pr_string "<<=" | GtGtEq -> pr_string ">>=" | PlusPlus -> pr_string "++" | MinusMinus -> pr_string "--" | Comma -> pr_string "," | Semicolon -> pr_string ";" | Co_await -> pr_string "co_await" | DotStar -> pr_string ".*" | Dot -> pr_string "." (* DefiningTypeSpecifier *) | DefiningTypeSpecifier -> pr_seq() | SimpleTypeSpecifier i -> begin let ca2 = nth_children 2 in if ca2 = [||] then begin pr_nth_children 0; pr_string (Ast.decode_ident i) end else pr_seq ~sep:pr_none () end | ElaboratedTypeSpecifier -> pr_string "<elaborated-type-specifier>" | ElaboratedTypeSpecifierClass i -> begin pr_string "class "; pr_nth_children ~tail:pad1 0; pr_nth_children 1; if nth_children 2 = [||] then pr_id (Ast.decode_ident i) else pr_nth_children 2 end | ElaboratedTypeSpecifierStruct i -> pr_string "struct "; pr_id (Ast.decode_ident i) | ElaboratedTypeSpecifierUnion i -> pr_string "union "; pr_id (Ast.decode_ident i) | ElaboratedTypeSpecifierEnum i -> pr_string "enum "; pr_id (Ast.decode_ident i) | TypenameSpecifier i -> pr_string "typename "; pr_seq ~sep:pr_none () | CvQualifier -> pr_string "<cv-qualifier>" | TypeMacro i -> pr_id i | Const -> pr_string "const" | Volatile -> pr_string "volatile" | Restrict i -> pr_string i | MsAsmBlock(a, s) -> pr_string (sprintf "%s {%s}" a s) | MsCdecl i -> pr_string i | MsStdcall i -> pr_string i | MsPragma i -> pr_string i | MsWarningSpecifier i -> pr_string i | CallingConvention i -> pr_string i | GnuAsmBlock(a, s) -> pr_string (sprintf "%s %s" a s) | GnuAttribute i -> pr_string i; pr_seq() | GnuStatementExpression -> pr_lparen(); pr_nth_child 0; pr_rparen() | ClassSpecifier -> begin let mema = nth_children 1 in if mema = [||] then begin pr_nth_child 0; pad1(); pr_string "{}" end else begin pb#open_vbox 0; pr_nth_child 0; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ mema; pb#pr_block_end(); pb#close_box() end end | EnumSpecifier -> begin let mema = nth_children 1 in if mema = [||] then begin pr_nth_child 0; pad1(); pr_string "{}" end else begin pb#open_vbox 0; pr_nth_child 0; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 1); pb#pr_block_end(); pb#close_box() end end BasicType | BasicType -> pr_string "<basic-type>" | Char -> pr_string "char" | Char8_t -> pr_string "char8_t" | Char16_t -> pr_string "char16_t" | Char32_t -> pr_string "char32_t" | Wchar_t -> pr_string "wchar_t" | Bool -> pr_string "bool" | Short -> pr_string "short" | Int -> pr_string "int" | Long -> pr_string "long" | Signed -> pr_string "signed" | Unsigned -> pr_string "unsigned" | Float -> pr_string "float" | Double -> pr_string "double" | Void -> pr_string "void" | UnsignedInt -> pr_string "unsigned int" | UnsignedLong -> pr_string "unsigned long" (* AccessSpecifier *) | AccessSpecifier -> pr_string "<access-specifier>" | Private -> pr_string "private"; pr_nth_children ~head:pad1 0 | Protected -> pr_string "protected"; pr_nth_children ~head:pad1 0 | Public -> pr_string "public"; pr_nth_children ~head:pad1 0 | AccessSpecMacro i -> pr_id i; pr_nth_children ~head:pad1 0 AttributeSpecifier | AttributeSpecifier -> pr_string "<attribute-specifier>" | StandardAttributeSpecifier -> pr_string "[["; pr_seq(); pr_string "]]" | ContractAttributeSpecifier -> pr_string "<contract-attribute-specifier>" | ContractAttributeSpecifierExpects -> begin pr_string "[[expects "; pr_nth_children 0; pr_colon(); pr_nth_children 1; pr_string "]]" end | ContractAttributeSpecifierEnsures i -> begin pr_string "[[ensures "; pr_nth_children 0; if i <> "" then begin pad1(); pr_id i; end; pr_colon(); pr_nth_children 1; pr_string "]]" end | ContractAttributeSpecifierAssert -> begin pr_string "[[assert "; pr_nth_children 0; pr_colon(); pr_nth_children 1; pr_string "]]" end | AlignmentAttributeSpecifier b -> begin pr_string "alignas"; pr_lparen(); pr_nth_child 0; if b then pr_ellipsis(); pr_rparen() end | AttributeMacro i -> pr_id i | MsAttributeSpecifier -> pr_string "["; pr_seq(); pr_string "]" RefQualifier | RefQualifier -> pr_string "<ref-qualifier>" | RefQualifierAmp -> pr_string "&" | RefQualifierAmpAmp -> pr_string "&&" (* PlaceholderTypeSpecifier *) | PlaceholderTypeSpecifier -> pr_string "<placeholder-type-specifier>" | PlaceholderTypeSpecifierAuto -> pr_string "auto" | PlaceholderTypeSpecifierDecltype -> pr_string "decltype(auto)" PtrOperator | PtrOperator -> pr_string "<ptr-operator>" | PtrOperatorStar -> pr_nth_children 0; pr_string "*"; pr_nth_children ~head:pad1 1; pr_nth_children ~head:pad1 2 | PtrOperatorAmp -> pr_string "&"; pr_seq() | PtrOperatorAmpAmp -> pr_string "&&"; pr_seq() | PtrOperatorHat -> pr_string "^" | PtrOperatorMacro i -> pr_id i Declarator | Declarator -> pr_string "<declarator>" | DeclaratorFunc -> pr_seq() | PtrDeclarator -> pr_string "<ptr-declarator>" | PtrDeclaratorPtr -> pr_seq() | NoptrDeclarator -> pr_seq() | NoptrDeclaratorId -> pr_seq() | NoptrDeclaratorParen -> pr_lparen(); pr_nth_child 0; pr_rparen() | NoptrDeclaratorFunc -> pr_nth_children 0; pr_nth_children 1 | NoptrDeclaratorOldFunc -> begin pr_nth_child 0; pr_lparen(); pr_nth_children 1; pr_rparen(); pr_nth_children ~head:pr_space 2 end | NoptrDeclaratorArray -> begin pr_nth_child 0; pr_lbracket(); pr_nth_children 1; pr_nth_children 2; pr_rbracket(); pr_nth_children ~head:pad1 3; end | DtorMacro i -> pr_id i NoexceptSpecifier | NoexceptSpecifier -> pr_string "noexcept"; pr_nth_children ~head:pr_lparen ~tail:pr_rparen 0 | NoexceptSpecifierThrow -> pr_string "throw"; pr_lparen(); pr_seq ~sep:pr_comma (); pr_rparen() | NoexceptSpecifierThrowAny -> pr_string "throw(...)" | NoexceptSpecifierMacro i -> pr_id i VirtSpecifier | VirtSpecifier -> pr_string "<virt-specifier>" | VirtSpecifierFinal -> pr_string "final" | VirtSpecifierOverride -> pr_string "override" | VirtSpecifierMacro i -> pr_id i | VirtSpecifierMacroInvocation i -> pr_macro_invocation i (* StorageClassSpecifier *) | StorageClassSpecifier -> pr_string "<storage-class-specifier>" | StorageClassSpecifierStatic -> pr_string "static" | StorageClassSpecifierThread_local -> pr_string "thread_local" | StorageClassSpecifierExtern -> pr_string "extern" | StorageClassSpecifierMutable -> pr_string "mutable" | StorageClassSpecifierRegister -> pr_string "register" | StorageClassSpecifierVaxGlobaldef -> pr_string "globaldef" (* FunctionSpecifier *) | FunctionSpecifier -> pr_string "<function-specifier>" | FunctionSpecifierVirtual -> pr_string "virtual" | ExplicitSpecifier -> pr_string "explicit" ClassHead | ClassHead -> pr_string "<class-head>" | ClassHeadClass -> pr_string "class "; pr_seq() | ClassHeadStruct -> pr_string "struct "; pr_seq() | ClassHeadUnion -> pr_string "union "; pr_seq() | ClassHeadMsRefClass -> pr_string "ref class"; pr_seq() | ClassHeadMacro i -> pr_id i | ClassHeadMacroInvocation i -> pr_macro_invocation i EnumHead | EnumHead -> pr_string "<enum-head>" | EnumHeadEnum -> pr_string "enum "; pr_seq() | EnumHeadEnumClass -> pr_string "enum class "; pr_seq() | EnumHeadEnumStruct -> pr_string "enum struct "; pr_seq() | EnumHeadEnumMacro i -> pr_id i TypeParameterKey | TypeParameterKey -> pr_string "<type-parameter-key>" | TypeParameterKeyClass -> pr_string "class" | TypeParameterKeyTypename -> pr_string "typename" FunctionBody | FunctionBody _ -> pb#pr_a pad1 pr_node_ children | FunctionBodyDefault -> pr_string "= default;" | FunctionBodyDelete -> pr_string "= delete;" | FunctionTryBlock _ -> pr_string "try "; pr_nth_children ~tail:pad1 0; pr_nth_children 1; pr_nth_children 2 | FunctionBodyMacro i -> pr_id i | FunctionBodyMacroInvocation i -> pr_macro_invocation i DeclSpecifier | DeclSpecifier -> pr_string "<decl-specifier>" | DeclSpecifierInline -> pr_string "inline" | DeclSpecifierConstexpr -> pr_string "constexpr" | DeclSpecifierConsteval -> pr_string "consteval" | DeclSpecifierConstinit -> pr_string "constinit" | DeclSpecifierTypedef -> pr_string "typedef" | DeclSpecifierFriend -> pr_string "friend" | DeclSpecifierMacro i -> pr_id i | DeclSpecifierMacroInvocation i -> pr_macro_invocation i (* Requirement *) | Requirement -> pr_string "<requirement>" | SimpleRequirement -> pr_nth_child 0; _pr_semicolon() | TypeRequirement -> pr_string "typename "; pr_seq(); _pr_semicolon() | CompoundRequirement -> pr_lbrace(); pr_nth_child 0; pr_rbrace(); pr_nth_children 1; pr_nth_children ~head:pad1 2 | ReturnTypeRequirement -> pr_string "->"; pr_nth_child 0 | NestedRequirement -> pr_string "requires "; pr_nth_child 0; _pr_semicolon() AbstractDeclarator | AbstractDeclarator -> pr_string "<abstract-declarator>" | AbstractDeclaratorFunc -> pr_seq() | PtrAbstractDeclarator -> pr_string "<ptr-abstract-declarator>" | PtrAbstractDeclaratorPtr -> pr_seq() | NoptrAbstractDeclarator -> pr_string "<noptr-abstract-declarator>" | NoptrAbstractDeclaratorFunc -> pr_seq() | NoptrAbstractDeclaratorArray -> pr_nth_children 0; pr_lbracket(); pr_nth_children 1; pr_rbracket(); pr_nth_children 2 | NoptrAbstractDeclaratorParen -> pr_lparen(); pr_nth_child 0; pr_rparen() (* NoptrAbstractPackDeclarator *) | NoptrAbstractPackDeclaratorFunc -> pr_seq() | NoptrAbstractPackDeclaratorArray -> pr_nth_child 0; pr_lbracket(); pr_nth_children 1; pr_rbracket(); pr_nth_children 2 SimpleCapture | SimpleCapture i -> pr_string i | SimpleCaptureAmp i -> pr_string ("&"^i) | SimpleCaptureThis -> pr_string "this" | SimpleCaptureStarThis -> pr_string "*this" InitCapture | InitCapture i -> pr_string i; pr_nth_child 0 | InitCaptureAmp i -> pr_amp(); pr_id i; pr_nth_child 0 | LambdaCapture -> begin if nth_children 0 <> [||] && nth_children 1 <> [||] then begin pr_nth_children 0; pr_comma(); pr_nth_children 1 end else pr_seq() end | LambdaCaptureDefaultEq -> pr_string "=" | LambdaCaptureDefaultAmp -> pr_string "&" | LambdaCaptureMacroInvocation i -> pr_macro_invocation i MemberDeclarator | MemberDeclarator -> pr_string "<member-declarator>" | MemberDeclaratorDecl -> pb#pr_a pad1 pr_node_ children | MemberDeclaratorBitField i -> begin pr_string i; pr_nth_children 0; pr_colon(); pr_nth_children 1; pr_nth_children 2 end (* Label *) | Label i -> pr_seq(); pr_id i; pr_colon() | CaseLabel -> pr_nth_children 0; pr_string "case "; pr_nth_children 1; pr_colon() | RangedCaseLabel -> begin pr_nth_children 0; pr_string "case "; pr_nth_children 1; pr_ellipsis(); pr_nth_children 2; pr_colon() end | DefaultLabel -> pr_seq(); pr_string "default:" | LabelMacroInvocation i -> pr_macro_invocation i; pr_colon() ContractLevel | ContractLevel -> pr_string "<contract-level>" | ContractLevelDefault -> pr_string "default" | ContractLevelAudit -> pr_string "audit" | ContractLevelAxiom -> pr_string "axiom" (* Member *) | MemberSpecification -> pr_seq ~sep:pr_cut () | MemberDeclarationDecl -> pb#open_hbox(); pr_seq(); pb#close_box() | MsProperty i -> pr_string "property "; pr_nth_child 0; pad1(); pr_id i; if nchildren > 1 then begin pb#pr_block_head(); pr_nth_child 1; pb#pr_block_end() end (* *) | Explicit -> pr_string "explicit" | Virtual -> pr_string "virtual" | Template -> pr_string "template" | Noexcept -> pr_string "noexcept" | Extern -> pr_string "extern" | Inline -> pr_string "inline" | Default -> pr_string "default" | Constexpr -> pr_string "constexpr" | Typename -> pr_string "typename" | ColonColon -> pr_colon_colon() | Ellipsis -> pr_ellipsis() | PureSpecifier -> pr_string "= 0" | BaseSpecifier -> pr_seq() | BaseClause -> pr_seq() | BaseMacro i -> pr_id i | BaseSpecMacro i -> pr_id i | BaseSpecMacroInvocation i -> pr_macro_invocation i | SuffixMacro i -> pr_id i | SuffixMacroInvocation i -> pr_macro_invocation i | DslMacroArgument -> pr_lparen(); pr_seq(); pr_rparen() | ClassVirtSpecifierFinal -> pr_string "final" | ClassVirtSpecifierMsSealed -> pr_string "sealed" | ClassName i when nchildren = 0 -> pr_id (Ast.decode_ident i) | ClassName i -> pr_nth_child 0 | ClassHeadName n -> pr_seq ~sep:pr_none () | LambdaIntroducerMacro i -> pr_id i | MacroArgument -> pr_seq() | NoptrNewDeclarator -> begin pr_nth_children 0; pr_lbracket(); pr_nth_children 1; pr_rbracket(); pr_nth_children 2 end | NewInitializer -> begin let has_rparen = try not (L.is_pp_if_section (getlab (nth_children 1).(0))) with _ -> true in pr_lparen(); pr_nth_children 0; if has_rparen then pr_rparen() end | NewInitializerMacro i -> pr_id i | ArgumentsMacro i -> pr_id i | ArgumentsMacroInvocation i -> pr_macro_invocation i | NewDeclaratorPtr -> pr_seq() | NewDeclarator -> pr_string "<new-declarator>" | NewTypeId -> pr_seq() | NewPlacement -> pr_lparen(); pr_seq(); pr_rparen() | LambdaDeclarator -> begin pr_lparen(); pr_nth_child 0; pr_rparen(); pr_nth_children 1; pr_nth_children 2; pr_nth_children 3; pr_nth_children 4; pr_nth_children 5 end | ParenthesizedInitList -> pr_lparen(); pr_seq(); pr_rparen() | LambdaIntroducer -> pr_lbracket(); pr_seq(); pr_rbracket() | AbstractPackDeclarator -> pr_seq() | AbstractPack -> pr_ellipsis() | RequirementBody -> pr_lbrace(); pr_seq(); pr_rbrace() | RequirementParameterList -> pr_lparen(); pr_nth_child 0; pr_rparen() | MemInitializer -> begin pr_nth_child 0; pr_nth_children 1 end | MemInitMacroInvocation i -> pr_macro_invocation i | QualifiedTypeName -> pr_seq ~sep:pr_none () | InitDeclarator -> pb#pr_a pad1 pr_node_ children | ConceptDefinition n -> pr_string "concept "; pr_id n; pr_eq(); pr_nth_child 0; _pr_semicolon() | CtorInitializer -> pb#open_hvbox 0; pr_seq ~sep:pr_space (); pb#close_box() | ConstraintLogicalOrExpression _ -> pr_nth_child 0; pr_string " || "; pr_nth_child 1 | ConstraintLogicalAndExpression _ -> pr_nth_child 0; pr_string " && "; pr_nth_child 1 | RequiresClause -> pr_string "requires "; pr_nth_child 0 | TypeParameter i -> begin pr_nth_children ~tail:pad1 0; pr_nth_children ~tail:pad1 1; pr_nth_children ~tail:pad1 2; pr_id i; pr_nth_children ~head:pr_eq 3; end | TemplateHead -> begin pb#open_hvbox 0; pr_string "template"; pr_lt(); pb#pr_a pr_space pr_node_ (nth_children 0); pr_gt(); pr_nth_children ~head:pad1 1; pb#close_box(); end | EnclosingNamespaceSpecifier i -> pr_nth_children ~tail:pr_colon_colon 0; pr_nth_children 1; pr_id i | Enumerator i -> pr_string i; pr_seq() | EnumeratorDefinition -> pr_nth_child 0; pr_eq(); pr_nth_children ~tail:pad1 1; pr_nth_children 2 | EnumeratorDefinitionMacro i -> pr_id i | TypeMacroInvocation i -> pr_macro_invocation i | Condition -> pr_seq() | ParameterDeclaration -> pr_seq() | ParameterDeclarationClause b -> begin pb#open_hbox(); pr_seq ~sep:pr_space (); pb#close_box() end | ParametersAndQualifiers -> begin pb#open_hbox(); pr_lparen(); pr_nth_children 0; pr_rparen(); pr_nth_children ~head:pad1 1; pr_nth_children ~head:pad1 2; pr_nth_children ~head:pad1 3; pr_nth_children ~head:pad1 4; pb#close_box() end | ParametersAndQualifiersList -> pr_lparen(); pr_seq ~sep:pr_comma (); pr_rparen() | ParamDeclMacro i -> pr_id i | ParamDeclMacroInvocation i -> pr_macro_invocation i | ParametersMacro i -> pr_id i | ParametersMacroInvocation i -> pr_macro_invocation i | Handler -> pr_string "catch "; pr_lparen(); pr_nth_child 0; pr_rparen(); pr_nth_children 1 | ExceptionDeclaration -> pr_seq() | ExpressionList -> pr_lparen(); pr_seq(); pr_rparen(); pr_nth_children 1 | EqualInitializer -> pr_string "= "; pr_nth_child 0 | DesignatedInitializerClause -> begin if L.is_desig_old (getlab children.(0)) then begin pr_nth_child 0; pr_colon(); pr_nth_child 1 end else begin pr_seq() end end | DesignatorField i -> pr_string ("."^i) | DesignatorIndex -> pr_lbracket(); pr_seq(); pr_rbracket() | DesignatorRange -> pr_lbracket(); pr_seq ~sep:pr_ellipsis (); pr_rbracket() | TrailingReturnType -> pr_string " -> "; pr_nth_child 0 | BracedInitList -> pr_lbrace(); pr_seq(); pr_rbrace() | ForRangeDeclaration -> begin pr_nth_children 0; pr_nth_children 1; pr_nth_children 2; pr_nth_children 3; pr_nth_children ~head:pr_lbracket ~tail:pr_rbracket 4 end | DefiningTypeId -> pr_seq() | EnumHeadName i -> pr_nth_children 0; pr_id (Ast.decode_ident i) | EnumBase -> pr_colon(); pr_seq() | QualifiedId -> pr_seq ~sep:pr_none () | QualifiedNamespaceSpecifier i -> if nchildren > 0 then pr_nth_child 0; pr_id i | TypeName i -> pr_id i | ConversionDeclarator -> pr_seq() | ConversionTypeId -> pr_seq() | UsingDeclarator -> pr_seq() | TypeConstraint i -> begin pr_nth_children 0; pr_id (Ast.decode_ident i); pr_nth_children ~head:pr_lt ~tail:pr_gt 1 end | TypeId -> pr_seq() | DecltypeSpecifier -> pr_string "decltype"; pr_lparen(); pr_nth_child 0; pr_rparen() | SimpleTemplateId n -> begin pb#open_hvbox 0; pr_string n; pr_lt(); pr_seq ~sep:pr_space (); pr_gt(); pb#close_box() end | SimpleTemplateIdM -> begin pb#open_hvbox 0; pr_nth_child 0; pr_lt(); pr_nth_children 1; pr_gt(); pb#close_box() end | TemplateArguments -> pr_lt(); pr_seq(); pr_gt(); | Identifier i -> pr_id i | IdentifierMacroInvocation i -> pr_macro_invocation i | PpConcatenatedIdentifier -> pr_nth_child 0; pr_string "##"; pr_nth_child 1 | NestedNameSpecifier -> pr_string "<nested-name-specifier>" | NestedNameSpecifierHead -> pr_colon_colon() | NestedNameSpecifierIdent i -> pr_nth_children 0; pr_nth_children 1; pr_colon_colon() | NestedNameSpecifierTempl i -> pr_nth_children 0; pr_nth_children 1; pr_colon_colon() | NestedNameSpecifierDeclty -> pr_nth_child 0; pr_colon_colon() | PackExpansion -> pr_nth_child 0 | AttributeUsingPrefix -> pr_string "using "; pr_nth_child 0; pr_colon() | Attribute -> pr_seq() | AttributeToken i -> pr_id i | AttributeScopedToken i -> pr_nth_child 0; pr_colon_colon(); pr_string i | AttributeNamespace i -> pr_id i | AttributeArgumentClause -> pr_lparen(); pr_seq(); pr_rparen() | AttributeArgumentClauseMacro i -> pr_id i | BalancedToken -> pr_string "<balanced-token>" | BalancedTokenParen -> pr_lparen(); pr_seq(); pr_rparen() | BalancedTokenBracket -> pr_lbracket(); pr_seq(); pr_rbracket() | BalancedTokenBrace -> pr_lbrace(); pr_seq(); pr_rbrace() | BalancedTokenSingle s -> pr_string s | TokenSeq s -> pr_string s | ObjectLikeMacro -> pad1(); pr_seq() | FunctionLikeMacro mk -> begin pr_lparen(); pr_string (L.macro_kind_to_rep mk); pr_rparen(); pad1(); pr_seq(); end | OperatorMacro i -> pr_id i | OperatorMacroInvocation i -> pr_macro_invocation i | DefiningTypeSpecifierSeq -> pr_string "<defining-type-specifier-seq>" | DeclSpecifierSeq -> pr_string "<decl-specifier-seq>" | TypeSpecifierSeq -> pr_seq() | FunctionHead _ -> begin let has_rparen = try L.is_pp_if_section_broken (getlab (nth_children 2).(0)) with _ -> false in pr_seq(); if has_rparen then pr_rparen() end | FunctionHeadMacro i -> pr_id i | AccessSpecAnnot i -> pr_id i | EnumeratorMacroInvocation i -> pr_macro_invocation i | CvMacro i -> pr_id i | CvMacroInvocation i -> pr_macro_invocation i | OpeningBrace -> pr_lbrace() | ClosingBrace -> pr_rbrace() | OpeningBracket -> pr_lbracket() | ClosingBracket -> pr_rbracket() | DummyBody -> () | DummyDecl -> () | DummyStmt -> () | DummyExpr -> () | DummyDtor -> () | GnuAsmBlockFragmented a -> pr_string a; pad1(); pr_seq() | GnuAsmFragment s -> pr_string s | DesignatorFieldOld i -> pr_string (i^":") | DoxygenLine s -> pr_string s | AttributeMacroInvocation i -> pr_macro_invocation i | CudaExecutionConfiguration -> pr_string "<<<"; pr_seq(); pr_string ">>>"; | CudaKernelCall -> begin pr_nth_child 0; pad1(); pr_nth_children 1; pr_lparen(); pr_nth_children 2; pr_rparen() end | NamespaceHead i -> pr_id i | NamedNamespaceDefinitionHead i -> begin pr_nth_children 0; if try not (L.is_namespace_head (getlab (nth_children 0).(0))) with _ -> true then pr_string "namespace "; pr_nth_children 1; if nth_children 2 <> [||] then pr_nth_children 2 else pr_id i end | BlockHeadMacro i -> pr_id i | BlockEndMacro i -> pr_id i | PtrMacro i -> pr_id i | InitializerClause -> pr_seq() | TemplParamMacroInvocation i -> pr_macro_invocation i | Try -> pr_string "try" | DeclStmtBlock -> pr_seq() | AsmShader s -> pr_string s | AsmName i -> pr_string (sprintf "%%[%s]" i) | AsmDirective i -> pr_string ("."^i) | VaArgs s -> pr_string s | ClassBody -> pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 1); pb#pr_block_end() | At -> pr_string "@" | Lparen -> pr_lparen() | Rparen -> pr_rparen() | Asm -> pr_string "asm"; pr_lparen(); pr_seq(); pr_rparen() | HugeArray(_, c) -> pr_string c (* Objective C *) | ObjcThrow -> pr_string "@throw" | ObjcSynchronized -> pr_string "@synchronized" | ObjcClassDeclarationList -> pr_string "@class" | ObjcProtocolDeclarationList -> pr_string "@protocol" | ObjcProtocolDeclaration i -> pr_string ("@protocol "^i) | ObjcClassInterface i -> pr_string ("@interface "^i) | ObjcCategoryInterface(i, c) -> pr_string (sprintf "@interface %s (%s)" i c) | ObjcSuperclass i -> pr_string (": "^i) | ObjcProtocolReferenceList -> pr_string "<objc-protocol-reference-list>" | ObjcInstanceVariables -> pr_string "<objc-instance-variables>" | ObjcInstanceVariableDeclaration -> pr_string "<objc-instance-variable-declaration>" | ObjcInterfaceDeclaration -> pr_string "<objc-interface-declaration>" | ObjcPrivate -> pr_string "@private" | ObjcPublic -> pr_string "@public" | ObjcPackage -> pr_string "@package" | ObjcProtected -> pr_string "@protected" | ObjcStructDeclaration -> pr_string "<objc-struct-declaration>" | ObjcStructDeclarator -> pr_string "<objc-struct-declarator>" | ObjcPropertyDeclaration -> pr_string "<objc-property-declaration>" | ObjcPropertyAttributesDeclaration -> pr_string "<objc-property-attributes-declaration>" | ObjcClassMethodDeclaration -> pr_string "<objc-class-method-declaration>" | ObjcInstanceMethodDeclaration -> pr_string "<objc-instance-method-declaration>" | ObjcMethodMacroInvocation i -> pr_macro_invocation i | ObjcMethodType -> pr_string "<objc-MethodType" | ObjcMethodSelector -> pr_string "<objc-method-selector>" | ObjcMethodSelectorPack -> pr_string "<objc-method-selector-pack>" | ObjcSelector i -> pr_string i | ObjcKeywordSelector -> pr_string "<objc-keyword-selector>" | ObjcKeywordDeclarator i -> pr_string i | ObjcSpecifierQualifier i -> pr_string i | ObjcProtocolName i -> pr_string i | ObjcClassName i -> pr_string i | ObjcPropertyAttribute i -> pr_string i | ObjcMessageExpression -> pr_string "<objc-message-expression>" | ObjcMessageSelector -> pr_string "<objc-message-selector>" | ObjcKeywordArgument i -> pr_string i | ObjcProtocolInterfaceDeclarationOptional -> pr_string "@optional" | ObjcProtocolInterfaceDeclarationRequired -> pr_string "@required" | ObjcAutoreleasepool -> pr_string "@autoreleasepool" | ObjcAvailable -> pr_string "@available" | ObjcSelectorExpression i -> pr_string ("@selector "^i) | ObjcEncodeExpression -> pr_string "@encode" | ObjcTryBlock -> pr_string "<try-block>" | ObjcTry -> pr_string "@try" | ObjcCatchClause -> pr_string "@catch" | ObjcFinally -> pr_string "@finally" | ObjcKeywordName "" -> pr_colon() | ObjcKeywordName i -> pr_string i; pr_colon() end; let suffix = node#data#get_suffix in if suffix <> "" then pr_string suffix let unparse ?(no_boxing=false) ?(no_header=false) ?(fail_on_error=true) t = let prev_boxing_flag = pb#boxing_flag in if no_boxing && prev_boxing_flag then begin Format.open_hbox(); pb#disable_boxing() end; pb#open_vbox 0; if not no_header then begin pr_string "// generated by Diff/AST C/C++ Unparser"; pr_cut(); end; if not fail_on_error && no_header then begin pr_string (Printf.sprintf "// error_symbol=\"%s\"" error_symbol); pr_cut(); end; pr_node ~fail_on_error t; pb#close_box(); pr_cut(); pr_flush(); if no_boxing && prev_boxing_flag then begin pb#enable_boxing(); Format.close_box() end
null
https://raw.githubusercontent.com/codinuum/cca/85fd4426d998036a105509056690e963a174b581/src/ast/analyzing/langs/cpp/cpp_unparsing.ml
ocaml
* An unparser for C/C++ * * cpp_unparsing.ml * ***** ***** Declaration Statement | EmptyStatement -> _pr_semicolon() Literal UnqualifiedId Operator DefiningTypeSpecifier AccessSpecifier PlaceholderTypeSpecifier StorageClassSpecifier FunctionSpecifier Requirement NoptrAbstractPackDeclarator Label Member Objective C
Copyright 2012 - 2020 Codinuum Software Lab < > Copyright 2020 Chiba Institute of Technology Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2012-2020 Codinuum Software Lab <> Copyright 2020 Chiba Institute of Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) Author : < > module L = Cpp_label module Tree = Sourcecode.Tree (L) open Unparsing_base let _pr_semicolon() = pr_string ";" let pr_semicolon() = _pr_semicolon(); pr_space() let pr_colon_colon() = pr_string "::" let pr_lt() = pr_string "<" let pr_gt() = pr_string ">" let pr_if_newline = Format.print_if_newline class ppbox_ = object (self) inherit ppbox as super val mutable block_style = BSshort method pr_block_head() = match block_style with | BStall -> pr_cut(); pr_lbrace(); self#open_vbox self#indent; pr_cut() | BSshort -> pr_lbrace(); pr_space(); self#open_vbox self#indent; pr_if_newline(); pad self#indent method pr_block_end() = self#close_box(); pr_space(); pr_rbrace() method pr_else() = match block_style with | BStall -> pr_space(); pr_string "else"; pr_space() | BSshort -> pr_string " else " end let pb = new ppbox_ let error_symbol = "###" let getlab nd = match nd#data#orig_lab_opt with | Some o -> (Obj.obj o : L.t) | None -> (Obj.obj nd#data#_label : L.t) let has_orig_lab nd = match nd#data#orig_lab_opt with | Some o -> (Obj.obj o : L.t) <> (Obj.obj nd#data#_label : L.t) | None -> false let get_nth_children = Tree._get_logical_nth_child let rec pr_node ?(fail_on_error=true) ?(va=false) ?(prec=0) node = let pr_node_ = pr_node ~fail_on_error in let children = node#initial_children in let nchildren = Array.length children in let pr_nth_child = if fail_on_error then fun ?(va=false) ?(prec=0) nth -> pr_node ~fail_on_error:true ~va ~prec children.(nth) else fun ?(va=false) ?(prec=0) nth -> try pr_node ~fail_on_error:false ~va ~prec children.(nth) with _ -> pr_string error_symbol in let nth_children = get_nth_children node in let pr_nth_children ?(head=pr_none) ?(tail=pr_none) = if fail_on_error then begin fun ?(va=false) ?(prec=0) nth -> let ca = nth_children nth in let non_empty = ca <> [||] in if non_empty then head(); pb#pr_a pad1 (pr_node ~fail_on_error:true ~va ~prec) ca; if non_empty then tail() end else fun ?(va=false) ?(prec=0) nth -> try let ca = get_nth_children node nth in let non_empty = ca <> [||] in if non_empty then head(); pb#pr_a pad1 (pr_node ~fail_on_error:false ~va ~prec) ca; if non_empty then tail() with _ -> pr_string error_symbol in let pr_macro_invocation i = pr_string i; pr_lparen(); pb#pr_a pr_comma pr_node_ children; pr_rparen() in let pr_seq ?(head=pr_none) ?(sep=pad1) ?(tail=pr_none) () = pb#pr_a ~head ~tail sep pr_node_ children in let prefix = node#data#get_prefix in if prefix <> "" then pr_string prefix; begin match getlab node with | DUMMY -> () | EMPTY -> () | AMBIGUOUS_CONSTRUCT -> pr_seq() | PARTIAL_CONSTRUCT -> pr_seq() | DECLS -> pr_seq ~sep:pr_cut () | MEM_DECLS -> pr_seq ~sep:pr_cut () | STMTS -> pb#open_vbox 0; pr_seq ~sep:pr_cut (); pb#close_box() | INITS -> pr_seq ~sep:pr_comma () | LABELS -> pr_seq() | SPECS -> pr_seq() | ETORS -> pr_seq ~sep:pr_comma () | TEMPL_PARAMS -> pr_seq ~sep:pr_comma () | TEMPL_ARGS -> pr_seq ~sep:pr_comma () | DELIM_MACRO i -> begin for i = 0 to nchildren - 2 do if i > 0 then pr_comma(); pr_node ~fail_on_error children.(i) done; pr_id i; pr_node ~fail_on_error children.(nchildren-1) end | Q_PROPERTY -> begin pr_id "Q_PROPERTY"; pr_lparen(); pb#pr_a pad1 pr_node_ children; pr_rparen() end | TranslationUnit -> pb#open_vbox 0; pb#pr_a pr_cut pr_node_ children; pb#close_box() PpDirective | PpInclude s -> pr_string "#include "; pr_string s | PpDefine i -> begin pb#enable_backslash_newline(); pr_string "#define "; pr_id i; if nchildren > 0 then pr_nth_child 0; pb#disable_backslash_newline() end | PpUndef i -> pr_string "#undef " ; pr_id i | PpLine (j, s) -> pr_string "#line "; pr_int j; pad1(); pr_string s | PpError s -> pr_string "#error "; pr_string s | PpPragma s -> pr_string "#pragma "; pr_string s | PpNull -> pr_string "#" | PpMarker(j, s, jl) -> begin pr_string "# "; pr_int j; pad1(); pr_string s; pr_string (String.concat " " (List.map string_of_int jl)) end | PpIf _ -> pr_string "#if "; pb#pr_a pad1 pr_node_ children | PpIfdef i -> pr_string "#ifdef "; pr_id i | PpIfndef i -> pr_string "#ifndef "; pr_id i | PpElif _ -> pr_string "#elif "; pb#pr_a pad1 pr_node_ children | PpElse _ -> pr_string "#else" | PpEndif _ -> pr_string "#endif" | PpUnknown s -> pr_string "#"; pr_string s | PpImport s -> pr_string "#import "; pr_string s | OmpDirective s -> pr_string "#pragma omp ";pr_string s | AccDirective s -> pr_string "#pragma acc ";pr_string s | PpIfSection _ | PpIfSectionFuncDef _ | PpIfSectionAltFuncDef | PpIfSectionBroken | PpIfSectionBrokenIf | PpIfSectionBrokenFuncDef | PpIfSectionBrokenDtorFunc | PpIfSectionCondExpr | PpIfSectionLogicalAnd | PpIfSectionLogicalOr | PpIfSectionTemplDecl | PpIfSectionHandler | PpIfSectionTryBlock -> begin force_newline(); pb#open_vbox 0; pb#pr_a pr_cut pr_node_ children; pb#close_box(); force_newline() end | PpIfGroup _ -> pb#pr_a pr_cut pr_node_ children | PpElifGroup _ -> pb#pr_a pr_cut pr_node_ children | PpElseGroup _ -> pb#pr_a pr_cut pr_node_ children | PpStringized s -> pr_string s | PpMacroParam s -> pr_string s | SimpleDeclaration -> pb#open_hbox(); pr_seq(); pb#close_box() | AsmDefinition s -> pr_nth_children 0; pr_string "asm"; pr_nth_children 1 | NamespaceAliasDefinition i -> begin pr_string "namespace "; pr_id i; pr_eq(); pr_nth_child 0 end | UsingDeclaration -> pr_string "using "; pr_seq ~sep:pr_comma () | UsingDirective i -> begin pr_nth_children 0; pr_string "using namespace "; pr_nth_children 1 end | Static_assertDeclaration -> begin pr_string "static_assert"; pr_lparen(); pr_nth_children 0; pr_nth_children ~head:pr_comma 1; pr_rparen() end | AliasDeclaration i -> begin pr_string "using "; pr_id i; pr_nth_children 0; pr_eq(); pr_nth_children 1 end | OpaqueEnumDeclaration -> pr_string "enum "; pr_seq() | OpaqueEnumDeclarationClass -> pr_string "enum class "; pr_seq() | OpaqueEnumDeclarationStruct -> pr_string "enum struct "; pr_seq() | OpaqueEnumDeclarationMacro i -> pr_id i; pad1(); pr_seq() | NodeclspecFunctionDeclaration -> pr_seq() | FunctionDefinition _ -> pr_seq() | NestedFunctionDefinition _ -> pr_seq() | TemplateDeclaration -> pr_nth_child 0; pr_space(); pr_nth_child 1 | DeductionGuide n -> begin pr_id n; pr_lparen(); pr_nth_children 1; pr_rparen(); pr_string " -> "; pr_nth_children 2; _pr_semicolon() end | ExplicitInstantiation -> pr_nth_children 0; pr_string "template "; pr_nth_children 1 | ExplicitSpecialization -> pr_string "template<>"; pr_nth_child 0; | LinkageSpecification s -> begin pr_string "extern "; pr_string s; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ children; pb#pr_block_end() end | NamedNamespaceDefinition i -> begin let has_ns = try not (L.is_namespace_head (getlab (nth_children 0).(0))) with _ -> true in pr_nth_children 0; if has_ns then pr_string "namespace "; pr_nth_children 1; pr_id i; pr_nth_children 2; if nth_children 3 <> [||] then begin pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 3); pb#pr_block_end() end end | UnnamedNamespaceDefinition -> begin pr_nth_children 0; pr_string "namespace "; pr_nth_children 1; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 2); pb#pr_block_end() end | NestedNamespaceDefinition i -> begin pr_string "namespace "; pr_nth_child 0; pr_colon_colon(); pr_nth_children 1; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 2); pb#pr_block_end() end | NamespaceDefinitionMacro i -> pr_id i | EmptyDeclaration -> _pr_semicolon() | AttributeDeclaration -> pr_seq() | DeclarationMacro i -> pr_id i | DeclarationMacroInvocation i -> pr_macro_invocation i | DeclarationMacroInvocationInvocation -> begin pr_nth_child 0; pr_lparen(); pb#pr_a pr_comma pr_node_ (nth_children 1); pr_rparen() end | DeclarationMacroInvocationArrow -> pr_nth_child 0; pr_string "->"; pr_nth_children 1; pr_nth_children 2 | DeclarationMacroInvocationDot -> pr_nth_child 0; pr_string "."; pr_nth_children 1; pr_nth_children 2 | ImportDeclaration s -> pr_string "import "; pr_string s | Statement -> pr_string "<statement>" | ExpressionStatement -> pr_nth_children ~tail:pad1 0; pr_nth_children 1 | DeclarationStatement -> pb#open_hbox(); pr_seq(); pb#close_box() | TryBlock -> pr_string "try "; pr_nth_child 0 | LabeledStatement -> pr_seq() | SelectionStatement -> pr_string "<selection-statement>" | IfStatement -> begin let has_paren = try let lab = getlab (nth_children 2).(0) in not (L.is_expr_macro_ivk lab) && not (L.is_stmt_macro_ivk lab) with _ -> true in pr_string "if "; pr_nth_children 0; if has_paren then pr_lparen(); pr_nth_children 1; pr_nth_children 2; if has_paren then pr_rparen(); pad1(); pr_nth_children 3; pr_nth_children ~head:pb#pr_else 4 end | ElseStatement -> pr_string "else"; pr_seq ~head:pad1 () | SwitchStatement -> pr_string "switch "; pr_seq() | CompoundStatement -> begin if nchildren = 0 then pr_string "{}" else begin pb#pr_block_head(); pr_seq ~sep:pr_cut (); pb#pr_block_end() end end | IterationStatement -> pr_string "<iteration-statement>" | WhileStatement -> pr_string "while "; pr_lparen(); pr_nth_children 0; pr_rparen(); pr_nth_children 1 | DoStatement -> begin pr_string "do "; pr_nth_children 0; if nth_children 1 <> [||] then begin pr_string "while "; pr_lparen(); pr_nth_children 1; pr_rparen(); _pr_semicolon() end end | ForStatement -> begin pb#open_hbox(); pr_string "for "; pr_lparen(); pr_nth_child 0; pad1(); pr_nth_children 1; pr_semicolon(); pr_nth_children 2; pr_rparen(); pad1(); pb#close_box(); pr_nth_children 3 end | ForInStatement -> begin pr_string "for "; pr_lparen(); pr_nth_children 0; pr_string " in "; pr_nth_children 1; pr_rparen(); pr_nth_children 2 end | RangeBasedForStatement -> begin pr_string "for "; pr_lparen(); pr_nth_children 0; pr_nth_children 1; pr_colon(); pr_nth_children 2; pr_rparen(); pr_nth_children 3 end | JumpStatement -> pr_string "<jump-statement>" | BreakStatement -> pr_string "break" | ContinueStatement -> pr_string "continue" | ReturnStatement -> begin pr_string "return"; if nchildren > 0 then begin pad1(); pr_nth_child 0; end end | GotoStatement i -> pr_string "goto "; pr_string i | ComputedGotoStatement -> pr_string "goto" | CoroutineReturnStatement -> pr_string "co_return"; pr_nth_children ~head:pad1 0 | StatementMacroInvocation i -> pr_macro_invocation i | StatementMacro i -> pr_id i | IterationMacroInvocation i -> pr_macro_invocation i | IterationMacro i -> pr_id i Expression | This -> pr_string "this" | ParenthesizedExpression -> pr_lparen(); pr_nth_child 0; pr_rparen() | RequiresExpression -> pr_string "requires "; pr_seq() | FoldExpression -> begin pr_lparen(); pr_nth_children 0; pr_nth_children 1; pr_ellipsis(); pr_nth_children 2; pr_nth_children 3; pr_rparen() end | LambdaExpression -> begin pr_nth_child 0; pr_nth_children ~head:pr_lt ~tail:pr_gt 1; pr_nth_children 2; pr_nth_children 3; pr_nth_children 4; pr_nth_children 5 end | LogicalOrExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | LogicalAndExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | InclusiveOrExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | ExclusiveOrExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | AndExpression i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | EqualityExpression -> pr_string "<equality-expression>" | EqualityExpressionEq -> pr_nth_child 0; pr_string " == "; pr_nth_child 1 | EqualityExpressionStrictEq -> pr_nth_child 0; pr_string " === "; pr_nth_child 1 | EqualityExpressionNeq i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_child 1 | RelationalExpression -> pr_string "<relational-expression>" | RelationalExpressionLt -> pr_nth_child 0; pr_string " < "; pr_nth_child 1 | RelationalExpressionGt -> pr_nth_child 0; pr_string " > "; pr_nth_child 1 | RelationalExpressionLe -> pr_nth_child 0; pr_string " <= "; pr_nth_child 1 | RelationalExpressionGe -> pr_nth_child 0; pr_string " >= "; pr_nth_child 1 | CompareExpression -> pr_string "<=>" | ShiftExpression -> pr_string "<shift-expression>" | ShiftExpressionLeft -> pr_nth_child 0; pr_string " << "; pr_nth_child 1 | ShiftExpressionRight -> pr_nth_child 0; pr_string " >> "; pr_nth_child 1 | ShiftExpressionRightU -> pr_nth_child 0; pr_string " >>> "; pr_nth_child 1 | AdditiveExpression -> pr_string "<additive-expression>" | AdditiveExpressionAdd -> pr_nth_child 0; pr_string " + "; pr_nth_child 1 | AdditiveExpressionSubt -> pr_nth_child 0; pr_string " - "; pr_nth_child 1 | MultiplicativeExpression -> pr_string "<multiplicative-expression>" | MultiplicativeExpressionMult -> pr_nth_child 0; pr_string " * "; pr_nth_child 1 | MultiplicativeExpressionDiv -> pr_nth_child 0; pr_string " / "; pr_nth_child 1 | MultiplicativeExpressionMod -> pr_nth_child 0; pr_string " % "; pr_nth_child 1 | PmExpression -> pr_string "<pm-expression>" | PmExpressionClass -> pr_nth_child 0; pr_string ".*"; pr_nth_child 1 | PmExpressionPtr -> pr_nth_child 0; pr_string "->*"; pr_nth_child 1 | CastExpression -> begin let has_head = try L.is_type_macro_ivk (getlab children.(0)) with _ -> false in if has_head then pr_seq() else begin pr_lparen(); pr_nth_children 0; pr_nth_children 1; pr_rparen(); pr_nth_children 2; end end | CompoundLiteralExpression -> pr_lparen(); pr_nth_child 0; pr_rparen(); pr_nth_child 1 | UnaryExpression -> pr_string "<unary-expression>" | UnaryExpressionIncr -> pr_string "++"; pr_nth_child 0 | UnaryExpressionDecr -> pr_string "--"; pr_nth_child 0 | UnaryExpressionInd -> pr_string "*"; pr_nth_child 0 | UnaryExpressionAddr -> pr_string "&"; pr_nth_child 0 | UnaryExpressionLabelAddr -> pr_string "&&"; pr_nth_child 0 | UnaryExpressionPlus -> pr_string "+"; pr_nth_child 0 | UnaryExpressionMinus -> pr_string "-"; pr_nth_child 0 | UnaryExpressionNeg i -> pr_string i; pr_nth_child 0 | UnaryExpressionCompl i -> pr_string i; pr_nth_child 0 | UnaryExpressionSizeof -> pr_string "sizeof "; pr_nth_child 0 | UnaryExpressionSizeofPack i -> pr_string (sprintf "sizeof ... (%s)" i) | UnaryExpressionAlignof -> pr_string "alignof"; pr_lparen(); pr_nth_child 0; pr_rparen() | NoexceptExpression -> pr_string "noexcept"; pr_lparen(); pr_nth_child 0; pr_rparen() | PostfixExpression -> pr_string "<postfix-expression>" | PostfixExpressionSubscr -> pr_nth_child 0; pr_lbracket(); pr_nth_child 1; pr_rbracket() | PostfixExpressionFunCall -> begin pb#open_hbox(); pr_nth_child 0; pr_nth_children 1; pb#close_box() end | PostfixExpressionFunCallGuarded i -> pr_nth_child 0; pr_id i; pr_lparen(); pr_nth_children 1; pr_rparen() | PostfixExpressionFunCallMacro i -> pr_id i | PostfixExpressionExplicitTypeConv -> pr_string "<explicit-type-conversion>" | PostfixExpressionExplicitTypeConvExpr -> pr_nth_children 0; pr_lparen(); pr_nth_children 1; pr_rparen() | PostfixExpressionExplicitTypeConvBraced -> pr_seq() | PostfixExpressionDot -> begin pr_nth_child 0; pr_string "."; pr_nth_children ~tail:pad1 1; pr_nth_children 2 end | PostfixExpressionArrow -> begin pr_nth_child 0; pr_string "->"; pr_nth_children ~tail:pad1 1; pr_nth_children 2 end | PostfixExpressionIncr -> pr_nth_child 0; pr_string "++" | PostfixExpressionDecr -> pr_nth_child 0; pr_string "--" | PostfixExpressionTypeid -> pr_string "typeid" | PostfixExpressionTypeidExpr -> pr_string "typeid"; pr_lparen(); pr_nth_child 0; pr_rparen() | PostfixExpressionTypeidTy -> pr_string "typeid"; pr_lparen(); pr_nth_child 0; pr_rparen() | PostfixExpressionDynamic_cast -> begin pr_string "dynamic_cast<"; pr_nth_child 0; pr_string ">"; if L.is_ident (getlab children.(1)) then pr_nth_child 1 else begin pr_lparen(); pr_nth_child 1; pr_rparen() end end | PostfixExpressionStatic_cast -> begin pr_string "static_cast"; pr_lt(); pr_nth_child 0; pr_gt(); pr_nth_child 1 end | PostfixExpressionReinterpret_cast -> begin pr_string "reinterpret_cast"; pr_lt(); pr_nth_child 0; pr_gt(); pr_nth_child 1 end | PostfixExpressionConst_cast -> begin pr_string "const_cast"; pr_lt(); pr_nth_child 0; pr_gt(); pr_nth_child 1 end | SwiftArg i -> begin pr_id i; pr_colon(); if nchildren > 0 then begin pad1(); pr_nth_child 0 end end | SwiftFunCall -> begin pb#open_hbox(); pr_nth_child 0; pr_nth_children 1; pb#close_box() end | AssignmentExpression -> pr_string "<assignment-expression>" | AssignmentExpressionOverloaded i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_children 1 | AssignmentExpressionEq -> pr_nth_child 0; pr_eq(); pr_nth_children 1 | AssignmentExpressionPlus -> pr_nth_child 0; pr_string " += "; pr_nth_children 1 | AssignmentExpressionMinus -> pr_nth_child 0; pr_string " -= "; pr_nth_children 1 | AssignmentExpressionMult -> pr_nth_child 0; pr_string " *= "; pr_nth_children 1 | AssignmentExpressionDiv -> pr_nth_child 0; pr_string " /= "; pr_nth_children 1 | AssignmentExpressionMod -> pr_nth_child 0; pr_string " %= "; pr_nth_children 1 | AssignmentExpressionShiftLeft -> pr_nth_child 0; pr_string " <<= "; pr_nth_children 1 | AssignmentExpressionShiftRight -> pr_nth_child 0; pr_string " >>= "; pr_nth_children 1 | AssignmentExpressionAnd i | AssignmentExpressionXor i | AssignmentExpressionOr i -> pr_nth_child 0; pad1(); pr_string i; pad1(); pr_nth_children 1 | ThrowExpression -> pr_string "throw"; pr_nth_children ~head:pad1 0 | ExpressionPair -> pr_seq ~sep:pr_comma () | ConditionalExpression -> pr_seq() | NewExpression -> begin let is_type_id = try L.is_type_id (getlab (nth_children 2).(0)) with _ -> false in pr_nth_children 0; pr_string "new "; pr_nth_children 1; if is_type_id then pr_lparen(); pr_nth_children 2; if is_type_id then pr_rparen(); pr_nth_children 3 end | RefNewExpression -> begin pr_string "ref "; pr_nth_children 0; pr_string "new "; pr_nth_children 1; pr_nth_children 2; pr_nth_children 3 end | DeleteExpression -> pr_nth_children 0; pr_string "delete "; pr_nth_children 1 | DeleteExpressionBracket -> pr_nth_children 0; pr_string "delete[] "; pr_nth_children 1 | YieldExpression -> pr_string "co_yield "; pr_nth_child 0 | AwaitExpression -> pr_string "co_await "; pr_nth_child 0 | BlockLiteralExpression -> pr_string "^"; pr_seq() | ExpressionMacroInvocation i -> pr_macro_invocation i | LogicalOrMacroInvocation i -> pr_macro_invocation i | DefinedMacroExpression i -> pr_string (sprintf "defined(%s)" i) | HasIncludeExpression s -> pr_string (sprintf "__has_include(%s)" s) | HasAttributeExpression -> pr_string "__has_cpp_attribute"; pr_seq ~sep:pr_none () | Literal -> pr_string "<literal>" | IntegerLiteral v -> pr_string v | CharacterLiteral v -> pr_string v | FloatingLiteral v -> pr_string v | StringLiteral v -> pr_string v | StringMacro i -> pr_id i | BooleanLiteral v -> pr_string v | Nullptr -> pr_string "nullptr" | ConcatenatedString -> pr_seq() | UserDefinedCharacterLiteral v -> pr_string v | UserDefinedStringLiteral v -> pr_string v | UserDefinedFloatingLiteral v -> pr_string v | UserDefinedIntegerLiteral v -> pr_string v | LiteralMacro i -> pr_id i | LiteralMacroInvocation i -> pr_macro_invocation i | UnqualifiedId -> pr_string "<unqualified-id>" | OperatorFunctionId -> pr_string "operator"; pr_nth_child 0 | ConversionFunctionId -> pr_string "operator "; pr_nth_child 0 | LiteralOperatorId i -> pr_string "operator "; pr_nth_children 0; pr_id i | Destructor -> pr_string "~"; pr_nth_child 0 | TemplateId -> pr_string "<template-id>" | TemplateIdOp -> pr_nth_child 0; pr_nth_children ~head:pr_lt ~tail:pr_gt 1 | TemplateIdLit -> pr_nth_child 0; pr_nth_children ~head:pr_lt ~tail:pr_gt 1 | Operator -> pr_string "<operator>" | New -> pr_string "new" | Delete -> pr_string "delete" | NewBracket -> pr_string "new[]" | DeleteBracket -> pr_string "delete[]" | Parentheses -> pr_string "()" | Brackets -> pr_string "[]" | MinusGt -> pr_string "->" | MinusGtStar -> pr_string "->*" | Tilde i -> pr_string i | Exclam i -> pr_string i | Plus -> pr_string "+" | Minus -> pr_string "-" | Star -> pr_string "*" | Slash -> pr_string "/" | Perc -> pr_string "%" | Hat i -> pr_string i | Amp i -> pr_string i | Bar i -> pr_string i | Eq -> pr_string "=" | PlusEq -> pr_string "+=" | MinusEq -> pr_string "-=" | StarEq -> pr_string "*=" | SlashEq -> pr_string "/=" | PercEq -> pr_string "%=" | HatEq i -> pr_string i | AmpEq i -> pr_string i | BarEq i -> pr_string i | EqEq -> pr_string "==" | ExclamEq i -> pr_string i | Lt -> pr_string "<" | Gt -> pr_string ">" | LtEq -> pr_string "<=" | GtEq -> pr_string ">=" | LtEqGt -> pr_string "<=>" | AmpAmp i -> pr_string i | BarBar i -> pr_string i | LtLt -> pr_string "<<" | GtGt -> pr_string ">>" | LtLtEq -> pr_string "<<=" | GtGtEq -> pr_string ">>=" | PlusPlus -> pr_string "++" | MinusMinus -> pr_string "--" | Comma -> pr_string "," | Semicolon -> pr_string ";" | Co_await -> pr_string "co_await" | DotStar -> pr_string ".*" | Dot -> pr_string "." | DefiningTypeSpecifier -> pr_seq() | SimpleTypeSpecifier i -> begin let ca2 = nth_children 2 in if ca2 = [||] then begin pr_nth_children 0; pr_string (Ast.decode_ident i) end else pr_seq ~sep:pr_none () end | ElaboratedTypeSpecifier -> pr_string "<elaborated-type-specifier>" | ElaboratedTypeSpecifierClass i -> begin pr_string "class "; pr_nth_children ~tail:pad1 0; pr_nth_children 1; if nth_children 2 = [||] then pr_id (Ast.decode_ident i) else pr_nth_children 2 end | ElaboratedTypeSpecifierStruct i -> pr_string "struct "; pr_id (Ast.decode_ident i) | ElaboratedTypeSpecifierUnion i -> pr_string "union "; pr_id (Ast.decode_ident i) | ElaboratedTypeSpecifierEnum i -> pr_string "enum "; pr_id (Ast.decode_ident i) | TypenameSpecifier i -> pr_string "typename "; pr_seq ~sep:pr_none () | CvQualifier -> pr_string "<cv-qualifier>" | TypeMacro i -> pr_id i | Const -> pr_string "const" | Volatile -> pr_string "volatile" | Restrict i -> pr_string i | MsAsmBlock(a, s) -> pr_string (sprintf "%s {%s}" a s) | MsCdecl i -> pr_string i | MsStdcall i -> pr_string i | MsPragma i -> pr_string i | MsWarningSpecifier i -> pr_string i | CallingConvention i -> pr_string i | GnuAsmBlock(a, s) -> pr_string (sprintf "%s %s" a s) | GnuAttribute i -> pr_string i; pr_seq() | GnuStatementExpression -> pr_lparen(); pr_nth_child 0; pr_rparen() | ClassSpecifier -> begin let mema = nth_children 1 in if mema = [||] then begin pr_nth_child 0; pad1(); pr_string "{}" end else begin pb#open_vbox 0; pr_nth_child 0; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ mema; pb#pr_block_end(); pb#close_box() end end | EnumSpecifier -> begin let mema = nth_children 1 in if mema = [||] then begin pr_nth_child 0; pad1(); pr_string "{}" end else begin pb#open_vbox 0; pr_nth_child 0; pad1(); pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 1); pb#pr_block_end(); pb#close_box() end end BasicType | BasicType -> pr_string "<basic-type>" | Char -> pr_string "char" | Char8_t -> pr_string "char8_t" | Char16_t -> pr_string "char16_t" | Char32_t -> pr_string "char32_t" | Wchar_t -> pr_string "wchar_t" | Bool -> pr_string "bool" | Short -> pr_string "short" | Int -> pr_string "int" | Long -> pr_string "long" | Signed -> pr_string "signed" | Unsigned -> pr_string "unsigned" | Float -> pr_string "float" | Double -> pr_string "double" | Void -> pr_string "void" | UnsignedInt -> pr_string "unsigned int" | UnsignedLong -> pr_string "unsigned long" | AccessSpecifier -> pr_string "<access-specifier>" | Private -> pr_string "private"; pr_nth_children ~head:pad1 0 | Protected -> pr_string "protected"; pr_nth_children ~head:pad1 0 | Public -> pr_string "public"; pr_nth_children ~head:pad1 0 | AccessSpecMacro i -> pr_id i; pr_nth_children ~head:pad1 0 AttributeSpecifier | AttributeSpecifier -> pr_string "<attribute-specifier>" | StandardAttributeSpecifier -> pr_string "[["; pr_seq(); pr_string "]]" | ContractAttributeSpecifier -> pr_string "<contract-attribute-specifier>" | ContractAttributeSpecifierExpects -> begin pr_string "[[expects "; pr_nth_children 0; pr_colon(); pr_nth_children 1; pr_string "]]" end | ContractAttributeSpecifierEnsures i -> begin pr_string "[[ensures "; pr_nth_children 0; if i <> "" then begin pad1(); pr_id i; end; pr_colon(); pr_nth_children 1; pr_string "]]" end | ContractAttributeSpecifierAssert -> begin pr_string "[[assert "; pr_nth_children 0; pr_colon(); pr_nth_children 1; pr_string "]]" end | AlignmentAttributeSpecifier b -> begin pr_string "alignas"; pr_lparen(); pr_nth_child 0; if b then pr_ellipsis(); pr_rparen() end | AttributeMacro i -> pr_id i | MsAttributeSpecifier -> pr_string "["; pr_seq(); pr_string "]" RefQualifier | RefQualifier -> pr_string "<ref-qualifier>" | RefQualifierAmp -> pr_string "&" | RefQualifierAmpAmp -> pr_string "&&" | PlaceholderTypeSpecifier -> pr_string "<placeholder-type-specifier>" | PlaceholderTypeSpecifierAuto -> pr_string "auto" | PlaceholderTypeSpecifierDecltype -> pr_string "decltype(auto)" PtrOperator | PtrOperator -> pr_string "<ptr-operator>" | PtrOperatorStar -> pr_nth_children 0; pr_string "*"; pr_nth_children ~head:pad1 1; pr_nth_children ~head:pad1 2 | PtrOperatorAmp -> pr_string "&"; pr_seq() | PtrOperatorAmpAmp -> pr_string "&&"; pr_seq() | PtrOperatorHat -> pr_string "^" | PtrOperatorMacro i -> pr_id i Declarator | Declarator -> pr_string "<declarator>" | DeclaratorFunc -> pr_seq() | PtrDeclarator -> pr_string "<ptr-declarator>" | PtrDeclaratorPtr -> pr_seq() | NoptrDeclarator -> pr_seq() | NoptrDeclaratorId -> pr_seq() | NoptrDeclaratorParen -> pr_lparen(); pr_nth_child 0; pr_rparen() | NoptrDeclaratorFunc -> pr_nth_children 0; pr_nth_children 1 | NoptrDeclaratorOldFunc -> begin pr_nth_child 0; pr_lparen(); pr_nth_children 1; pr_rparen(); pr_nth_children ~head:pr_space 2 end | NoptrDeclaratorArray -> begin pr_nth_child 0; pr_lbracket(); pr_nth_children 1; pr_nth_children 2; pr_rbracket(); pr_nth_children ~head:pad1 3; end | DtorMacro i -> pr_id i NoexceptSpecifier | NoexceptSpecifier -> pr_string "noexcept"; pr_nth_children ~head:pr_lparen ~tail:pr_rparen 0 | NoexceptSpecifierThrow -> pr_string "throw"; pr_lparen(); pr_seq ~sep:pr_comma (); pr_rparen() | NoexceptSpecifierThrowAny -> pr_string "throw(...)" | NoexceptSpecifierMacro i -> pr_id i VirtSpecifier | VirtSpecifier -> pr_string "<virt-specifier>" | VirtSpecifierFinal -> pr_string "final" | VirtSpecifierOverride -> pr_string "override" | VirtSpecifierMacro i -> pr_id i | VirtSpecifierMacroInvocation i -> pr_macro_invocation i | StorageClassSpecifier -> pr_string "<storage-class-specifier>" | StorageClassSpecifierStatic -> pr_string "static" | StorageClassSpecifierThread_local -> pr_string "thread_local" | StorageClassSpecifierExtern -> pr_string "extern" | StorageClassSpecifierMutable -> pr_string "mutable" | StorageClassSpecifierRegister -> pr_string "register" | StorageClassSpecifierVaxGlobaldef -> pr_string "globaldef" | FunctionSpecifier -> pr_string "<function-specifier>" | FunctionSpecifierVirtual -> pr_string "virtual" | ExplicitSpecifier -> pr_string "explicit" ClassHead | ClassHead -> pr_string "<class-head>" | ClassHeadClass -> pr_string "class "; pr_seq() | ClassHeadStruct -> pr_string "struct "; pr_seq() | ClassHeadUnion -> pr_string "union "; pr_seq() | ClassHeadMsRefClass -> pr_string "ref class"; pr_seq() | ClassHeadMacro i -> pr_id i | ClassHeadMacroInvocation i -> pr_macro_invocation i EnumHead | EnumHead -> pr_string "<enum-head>" | EnumHeadEnum -> pr_string "enum "; pr_seq() | EnumHeadEnumClass -> pr_string "enum class "; pr_seq() | EnumHeadEnumStruct -> pr_string "enum struct "; pr_seq() | EnumHeadEnumMacro i -> pr_id i TypeParameterKey | TypeParameterKey -> pr_string "<type-parameter-key>" | TypeParameterKeyClass -> pr_string "class" | TypeParameterKeyTypename -> pr_string "typename" FunctionBody | FunctionBody _ -> pb#pr_a pad1 pr_node_ children | FunctionBodyDefault -> pr_string "= default;" | FunctionBodyDelete -> pr_string "= delete;" | FunctionTryBlock _ -> pr_string "try "; pr_nth_children ~tail:pad1 0; pr_nth_children 1; pr_nth_children 2 | FunctionBodyMacro i -> pr_id i | FunctionBodyMacroInvocation i -> pr_macro_invocation i DeclSpecifier | DeclSpecifier -> pr_string "<decl-specifier>" | DeclSpecifierInline -> pr_string "inline" | DeclSpecifierConstexpr -> pr_string "constexpr" | DeclSpecifierConsteval -> pr_string "consteval" | DeclSpecifierConstinit -> pr_string "constinit" | DeclSpecifierTypedef -> pr_string "typedef" | DeclSpecifierFriend -> pr_string "friend" | DeclSpecifierMacro i -> pr_id i | DeclSpecifierMacroInvocation i -> pr_macro_invocation i | Requirement -> pr_string "<requirement>" | SimpleRequirement -> pr_nth_child 0; _pr_semicolon() | TypeRequirement -> pr_string "typename "; pr_seq(); _pr_semicolon() | CompoundRequirement -> pr_lbrace(); pr_nth_child 0; pr_rbrace(); pr_nth_children 1; pr_nth_children ~head:pad1 2 | ReturnTypeRequirement -> pr_string "->"; pr_nth_child 0 | NestedRequirement -> pr_string "requires "; pr_nth_child 0; _pr_semicolon() AbstractDeclarator | AbstractDeclarator -> pr_string "<abstract-declarator>" | AbstractDeclaratorFunc -> pr_seq() | PtrAbstractDeclarator -> pr_string "<ptr-abstract-declarator>" | PtrAbstractDeclaratorPtr -> pr_seq() | NoptrAbstractDeclarator -> pr_string "<noptr-abstract-declarator>" | NoptrAbstractDeclaratorFunc -> pr_seq() | NoptrAbstractDeclaratorArray -> pr_nth_children 0; pr_lbracket(); pr_nth_children 1; pr_rbracket(); pr_nth_children 2 | NoptrAbstractDeclaratorParen -> pr_lparen(); pr_nth_child 0; pr_rparen() | NoptrAbstractPackDeclaratorFunc -> pr_seq() | NoptrAbstractPackDeclaratorArray -> pr_nth_child 0; pr_lbracket(); pr_nth_children 1; pr_rbracket(); pr_nth_children 2 SimpleCapture | SimpleCapture i -> pr_string i | SimpleCaptureAmp i -> pr_string ("&"^i) | SimpleCaptureThis -> pr_string "this" | SimpleCaptureStarThis -> pr_string "*this" InitCapture | InitCapture i -> pr_string i; pr_nth_child 0 | InitCaptureAmp i -> pr_amp(); pr_id i; pr_nth_child 0 | LambdaCapture -> begin if nth_children 0 <> [||] && nth_children 1 <> [||] then begin pr_nth_children 0; pr_comma(); pr_nth_children 1 end else pr_seq() end | LambdaCaptureDefaultEq -> pr_string "=" | LambdaCaptureDefaultAmp -> pr_string "&" | LambdaCaptureMacroInvocation i -> pr_macro_invocation i MemberDeclarator | MemberDeclarator -> pr_string "<member-declarator>" | MemberDeclaratorDecl -> pb#pr_a pad1 pr_node_ children | MemberDeclaratorBitField i -> begin pr_string i; pr_nth_children 0; pr_colon(); pr_nth_children 1; pr_nth_children 2 end | Label i -> pr_seq(); pr_id i; pr_colon() | CaseLabel -> pr_nth_children 0; pr_string "case "; pr_nth_children 1; pr_colon() | RangedCaseLabel -> begin pr_nth_children 0; pr_string "case "; pr_nth_children 1; pr_ellipsis(); pr_nth_children 2; pr_colon() end | DefaultLabel -> pr_seq(); pr_string "default:" | LabelMacroInvocation i -> pr_macro_invocation i; pr_colon() ContractLevel | ContractLevel -> pr_string "<contract-level>" | ContractLevelDefault -> pr_string "default" | ContractLevelAudit -> pr_string "audit" | ContractLevelAxiom -> pr_string "axiom" | MemberSpecification -> pr_seq ~sep:pr_cut () | MemberDeclarationDecl -> pb#open_hbox(); pr_seq(); pb#close_box() | MsProperty i -> pr_string "property "; pr_nth_child 0; pad1(); pr_id i; if nchildren > 1 then begin pb#pr_block_head(); pr_nth_child 1; pb#pr_block_end() end | Explicit -> pr_string "explicit" | Virtual -> pr_string "virtual" | Template -> pr_string "template" | Noexcept -> pr_string "noexcept" | Extern -> pr_string "extern" | Inline -> pr_string "inline" | Default -> pr_string "default" | Constexpr -> pr_string "constexpr" | Typename -> pr_string "typename" | ColonColon -> pr_colon_colon() | Ellipsis -> pr_ellipsis() | PureSpecifier -> pr_string "= 0" | BaseSpecifier -> pr_seq() | BaseClause -> pr_seq() | BaseMacro i -> pr_id i | BaseSpecMacro i -> pr_id i | BaseSpecMacroInvocation i -> pr_macro_invocation i | SuffixMacro i -> pr_id i | SuffixMacroInvocation i -> pr_macro_invocation i | DslMacroArgument -> pr_lparen(); pr_seq(); pr_rparen() | ClassVirtSpecifierFinal -> pr_string "final" | ClassVirtSpecifierMsSealed -> pr_string "sealed" | ClassName i when nchildren = 0 -> pr_id (Ast.decode_ident i) | ClassName i -> pr_nth_child 0 | ClassHeadName n -> pr_seq ~sep:pr_none () | LambdaIntroducerMacro i -> pr_id i | MacroArgument -> pr_seq() | NoptrNewDeclarator -> begin pr_nth_children 0; pr_lbracket(); pr_nth_children 1; pr_rbracket(); pr_nth_children 2 end | NewInitializer -> begin let has_rparen = try not (L.is_pp_if_section (getlab (nth_children 1).(0))) with _ -> true in pr_lparen(); pr_nth_children 0; if has_rparen then pr_rparen() end | NewInitializerMacro i -> pr_id i | ArgumentsMacro i -> pr_id i | ArgumentsMacroInvocation i -> pr_macro_invocation i | NewDeclaratorPtr -> pr_seq() | NewDeclarator -> pr_string "<new-declarator>" | NewTypeId -> pr_seq() | NewPlacement -> pr_lparen(); pr_seq(); pr_rparen() | LambdaDeclarator -> begin pr_lparen(); pr_nth_child 0; pr_rparen(); pr_nth_children 1; pr_nth_children 2; pr_nth_children 3; pr_nth_children 4; pr_nth_children 5 end | ParenthesizedInitList -> pr_lparen(); pr_seq(); pr_rparen() | LambdaIntroducer -> pr_lbracket(); pr_seq(); pr_rbracket() | AbstractPackDeclarator -> pr_seq() | AbstractPack -> pr_ellipsis() | RequirementBody -> pr_lbrace(); pr_seq(); pr_rbrace() | RequirementParameterList -> pr_lparen(); pr_nth_child 0; pr_rparen() | MemInitializer -> begin pr_nth_child 0; pr_nth_children 1 end | MemInitMacroInvocation i -> pr_macro_invocation i | QualifiedTypeName -> pr_seq ~sep:pr_none () | InitDeclarator -> pb#pr_a pad1 pr_node_ children | ConceptDefinition n -> pr_string "concept "; pr_id n; pr_eq(); pr_nth_child 0; _pr_semicolon() | CtorInitializer -> pb#open_hvbox 0; pr_seq ~sep:pr_space (); pb#close_box() | ConstraintLogicalOrExpression _ -> pr_nth_child 0; pr_string " || "; pr_nth_child 1 | ConstraintLogicalAndExpression _ -> pr_nth_child 0; pr_string " && "; pr_nth_child 1 | RequiresClause -> pr_string "requires "; pr_nth_child 0 | TypeParameter i -> begin pr_nth_children ~tail:pad1 0; pr_nth_children ~tail:pad1 1; pr_nth_children ~tail:pad1 2; pr_id i; pr_nth_children ~head:pr_eq 3; end | TemplateHead -> begin pb#open_hvbox 0; pr_string "template"; pr_lt(); pb#pr_a pr_space pr_node_ (nth_children 0); pr_gt(); pr_nth_children ~head:pad1 1; pb#close_box(); end | EnclosingNamespaceSpecifier i -> pr_nth_children ~tail:pr_colon_colon 0; pr_nth_children 1; pr_id i | Enumerator i -> pr_string i; pr_seq() | EnumeratorDefinition -> pr_nth_child 0; pr_eq(); pr_nth_children ~tail:pad1 1; pr_nth_children 2 | EnumeratorDefinitionMacro i -> pr_id i | TypeMacroInvocation i -> pr_macro_invocation i | Condition -> pr_seq() | ParameterDeclaration -> pr_seq() | ParameterDeclarationClause b -> begin pb#open_hbox(); pr_seq ~sep:pr_space (); pb#close_box() end | ParametersAndQualifiers -> begin pb#open_hbox(); pr_lparen(); pr_nth_children 0; pr_rparen(); pr_nth_children ~head:pad1 1; pr_nth_children ~head:pad1 2; pr_nth_children ~head:pad1 3; pr_nth_children ~head:pad1 4; pb#close_box() end | ParametersAndQualifiersList -> pr_lparen(); pr_seq ~sep:pr_comma (); pr_rparen() | ParamDeclMacro i -> pr_id i | ParamDeclMacroInvocation i -> pr_macro_invocation i | ParametersMacro i -> pr_id i | ParametersMacroInvocation i -> pr_macro_invocation i | Handler -> pr_string "catch "; pr_lparen(); pr_nth_child 0; pr_rparen(); pr_nth_children 1 | ExceptionDeclaration -> pr_seq() | ExpressionList -> pr_lparen(); pr_seq(); pr_rparen(); pr_nth_children 1 | EqualInitializer -> pr_string "= "; pr_nth_child 0 | DesignatedInitializerClause -> begin if L.is_desig_old (getlab children.(0)) then begin pr_nth_child 0; pr_colon(); pr_nth_child 1 end else begin pr_seq() end end | DesignatorField i -> pr_string ("."^i) | DesignatorIndex -> pr_lbracket(); pr_seq(); pr_rbracket() | DesignatorRange -> pr_lbracket(); pr_seq ~sep:pr_ellipsis (); pr_rbracket() | TrailingReturnType -> pr_string " -> "; pr_nth_child 0 | BracedInitList -> pr_lbrace(); pr_seq(); pr_rbrace() | ForRangeDeclaration -> begin pr_nth_children 0; pr_nth_children 1; pr_nth_children 2; pr_nth_children 3; pr_nth_children ~head:pr_lbracket ~tail:pr_rbracket 4 end | DefiningTypeId -> pr_seq() | EnumHeadName i -> pr_nth_children 0; pr_id (Ast.decode_ident i) | EnumBase -> pr_colon(); pr_seq() | QualifiedId -> pr_seq ~sep:pr_none () | QualifiedNamespaceSpecifier i -> if nchildren > 0 then pr_nth_child 0; pr_id i | TypeName i -> pr_id i | ConversionDeclarator -> pr_seq() | ConversionTypeId -> pr_seq() | UsingDeclarator -> pr_seq() | TypeConstraint i -> begin pr_nth_children 0; pr_id (Ast.decode_ident i); pr_nth_children ~head:pr_lt ~tail:pr_gt 1 end | TypeId -> pr_seq() | DecltypeSpecifier -> pr_string "decltype"; pr_lparen(); pr_nth_child 0; pr_rparen() | SimpleTemplateId n -> begin pb#open_hvbox 0; pr_string n; pr_lt(); pr_seq ~sep:pr_space (); pr_gt(); pb#close_box() end | SimpleTemplateIdM -> begin pb#open_hvbox 0; pr_nth_child 0; pr_lt(); pr_nth_children 1; pr_gt(); pb#close_box() end | TemplateArguments -> pr_lt(); pr_seq(); pr_gt(); | Identifier i -> pr_id i | IdentifierMacroInvocation i -> pr_macro_invocation i | PpConcatenatedIdentifier -> pr_nth_child 0; pr_string "##"; pr_nth_child 1 | NestedNameSpecifier -> pr_string "<nested-name-specifier>" | NestedNameSpecifierHead -> pr_colon_colon() | NestedNameSpecifierIdent i -> pr_nth_children 0; pr_nth_children 1; pr_colon_colon() | NestedNameSpecifierTempl i -> pr_nth_children 0; pr_nth_children 1; pr_colon_colon() | NestedNameSpecifierDeclty -> pr_nth_child 0; pr_colon_colon() | PackExpansion -> pr_nth_child 0 | AttributeUsingPrefix -> pr_string "using "; pr_nth_child 0; pr_colon() | Attribute -> pr_seq() | AttributeToken i -> pr_id i | AttributeScopedToken i -> pr_nth_child 0; pr_colon_colon(); pr_string i | AttributeNamespace i -> pr_id i | AttributeArgumentClause -> pr_lparen(); pr_seq(); pr_rparen() | AttributeArgumentClauseMacro i -> pr_id i | BalancedToken -> pr_string "<balanced-token>" | BalancedTokenParen -> pr_lparen(); pr_seq(); pr_rparen() | BalancedTokenBracket -> pr_lbracket(); pr_seq(); pr_rbracket() | BalancedTokenBrace -> pr_lbrace(); pr_seq(); pr_rbrace() | BalancedTokenSingle s -> pr_string s | TokenSeq s -> pr_string s | ObjectLikeMacro -> pad1(); pr_seq() | FunctionLikeMacro mk -> begin pr_lparen(); pr_string (L.macro_kind_to_rep mk); pr_rparen(); pad1(); pr_seq(); end | OperatorMacro i -> pr_id i | OperatorMacroInvocation i -> pr_macro_invocation i | DefiningTypeSpecifierSeq -> pr_string "<defining-type-specifier-seq>" | DeclSpecifierSeq -> pr_string "<decl-specifier-seq>" | TypeSpecifierSeq -> pr_seq() | FunctionHead _ -> begin let has_rparen = try L.is_pp_if_section_broken (getlab (nth_children 2).(0)) with _ -> false in pr_seq(); if has_rparen then pr_rparen() end | FunctionHeadMacro i -> pr_id i | AccessSpecAnnot i -> pr_id i | EnumeratorMacroInvocation i -> pr_macro_invocation i | CvMacro i -> pr_id i | CvMacroInvocation i -> pr_macro_invocation i | OpeningBrace -> pr_lbrace() | ClosingBrace -> pr_rbrace() | OpeningBracket -> pr_lbracket() | ClosingBracket -> pr_rbracket() | DummyBody -> () | DummyDecl -> () | DummyStmt -> () | DummyExpr -> () | DummyDtor -> () | GnuAsmBlockFragmented a -> pr_string a; pad1(); pr_seq() | GnuAsmFragment s -> pr_string s | DesignatorFieldOld i -> pr_string (i^":") | DoxygenLine s -> pr_string s | AttributeMacroInvocation i -> pr_macro_invocation i | CudaExecutionConfiguration -> pr_string "<<<"; pr_seq(); pr_string ">>>"; | CudaKernelCall -> begin pr_nth_child 0; pad1(); pr_nth_children 1; pr_lparen(); pr_nth_children 2; pr_rparen() end | NamespaceHead i -> pr_id i | NamedNamespaceDefinitionHead i -> begin pr_nth_children 0; if try not (L.is_namespace_head (getlab (nth_children 0).(0))) with _ -> true then pr_string "namespace "; pr_nth_children 1; if nth_children 2 <> [||] then pr_nth_children 2 else pr_id i end | BlockHeadMacro i -> pr_id i | BlockEndMacro i -> pr_id i | PtrMacro i -> pr_id i | InitializerClause -> pr_seq() | TemplParamMacroInvocation i -> pr_macro_invocation i | Try -> pr_string "try" | DeclStmtBlock -> pr_seq() | AsmShader s -> pr_string s | AsmName i -> pr_string (sprintf "%%[%s]" i) | AsmDirective i -> pr_string ("."^i) | VaArgs s -> pr_string s | ClassBody -> pb#pr_block_head(); pb#pr_a pr_cut pr_node_ (nth_children 1); pb#pr_block_end() | At -> pr_string "@" | Lparen -> pr_lparen() | Rparen -> pr_rparen() | Asm -> pr_string "asm"; pr_lparen(); pr_seq(); pr_rparen() | HugeArray(_, c) -> pr_string c | ObjcThrow -> pr_string "@throw" | ObjcSynchronized -> pr_string "@synchronized" | ObjcClassDeclarationList -> pr_string "@class" | ObjcProtocolDeclarationList -> pr_string "@protocol" | ObjcProtocolDeclaration i -> pr_string ("@protocol "^i) | ObjcClassInterface i -> pr_string ("@interface "^i) | ObjcCategoryInterface(i, c) -> pr_string (sprintf "@interface %s (%s)" i c) | ObjcSuperclass i -> pr_string (": "^i) | ObjcProtocolReferenceList -> pr_string "<objc-protocol-reference-list>" | ObjcInstanceVariables -> pr_string "<objc-instance-variables>" | ObjcInstanceVariableDeclaration -> pr_string "<objc-instance-variable-declaration>" | ObjcInterfaceDeclaration -> pr_string "<objc-interface-declaration>" | ObjcPrivate -> pr_string "@private" | ObjcPublic -> pr_string "@public" | ObjcPackage -> pr_string "@package" | ObjcProtected -> pr_string "@protected" | ObjcStructDeclaration -> pr_string "<objc-struct-declaration>" | ObjcStructDeclarator -> pr_string "<objc-struct-declarator>" | ObjcPropertyDeclaration -> pr_string "<objc-property-declaration>" | ObjcPropertyAttributesDeclaration -> pr_string "<objc-property-attributes-declaration>" | ObjcClassMethodDeclaration -> pr_string "<objc-class-method-declaration>" | ObjcInstanceMethodDeclaration -> pr_string "<objc-instance-method-declaration>" | ObjcMethodMacroInvocation i -> pr_macro_invocation i | ObjcMethodType -> pr_string "<objc-MethodType" | ObjcMethodSelector -> pr_string "<objc-method-selector>" | ObjcMethodSelectorPack -> pr_string "<objc-method-selector-pack>" | ObjcSelector i -> pr_string i | ObjcKeywordSelector -> pr_string "<objc-keyword-selector>" | ObjcKeywordDeclarator i -> pr_string i | ObjcSpecifierQualifier i -> pr_string i | ObjcProtocolName i -> pr_string i | ObjcClassName i -> pr_string i | ObjcPropertyAttribute i -> pr_string i | ObjcMessageExpression -> pr_string "<objc-message-expression>" | ObjcMessageSelector -> pr_string "<objc-message-selector>" | ObjcKeywordArgument i -> pr_string i | ObjcProtocolInterfaceDeclarationOptional -> pr_string "@optional" | ObjcProtocolInterfaceDeclarationRequired -> pr_string "@required" | ObjcAutoreleasepool -> pr_string "@autoreleasepool" | ObjcAvailable -> pr_string "@available" | ObjcSelectorExpression i -> pr_string ("@selector "^i) | ObjcEncodeExpression -> pr_string "@encode" | ObjcTryBlock -> pr_string "<try-block>" | ObjcTry -> pr_string "@try" | ObjcCatchClause -> pr_string "@catch" | ObjcFinally -> pr_string "@finally" | ObjcKeywordName "" -> pr_colon() | ObjcKeywordName i -> pr_string i; pr_colon() end; let suffix = node#data#get_suffix in if suffix <> "" then pr_string suffix let unparse ?(no_boxing=false) ?(no_header=false) ?(fail_on_error=true) t = let prev_boxing_flag = pb#boxing_flag in if no_boxing && prev_boxing_flag then begin Format.open_hbox(); pb#disable_boxing() end; pb#open_vbox 0; if not no_header then begin pr_string "// generated by Diff/AST C/C++ Unparser"; pr_cut(); end; if not fail_on_error && no_header then begin pr_string (Printf.sprintf "// error_symbol=\"%s\"" error_symbol); pr_cut(); end; pr_node ~fail_on_error t; pb#close_box(); pr_cut(); pr_flush(); if no_boxing && prev_boxing_flag then begin pb#enable_boxing(); Format.close_box() end
57f24c8fc5479acffaaaa69e87356308579e96211f03306a955c38b06e75bc28
ocaml/oasis2debian
GenPkg.ml
(******************************************************************************) oasis2debian : Create and maintain Debian package for an OASIS package (* *) Copyright ( C ) 2013 , (* *) (* This library is free software; you can redistribute it and/or modify it *) (* under the terms of the GNU Lesser General Public License as published by *) the Free Software Foundation ; either version 2.1 of the License , or ( at (* your option) any later version, with the OCaml static compilation *) (* exception. *) (* *) (* This library is distributed in the hope that it will be useful, but *) (* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *) (* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *) (* details. *) (* *) You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA (******************************************************************************) (** Compute package to generate *) open OASISTypes open Common let library_name = Conf.create ~cli:"--library-name" "pkg_name Short name of the library (XXX in libXXX-ocaml-dev)." (Conf.Fun (fun () -> failwith "Not set")) let executable_name = Conf.create ~cli:"--executable-name" "pkg_name Full name of the package that contains executables." (Conf.Fun (fun () -> failwith "Not set")) let set ~ctxt t = let obj, lib, doc, bin = List.fold_left (fun ((obj, lib, doc, bin) as acc) -> function | Object (cs, bs, obj') -> ((cs, bs, obj') :: obj), lib, doc, bin | Library (cs, bs, lib') -> obj, ((cs, bs, lib') :: lib), doc, bin | Executable (cs, bs, exec) -> obj, lib, doc, ((cs, bs, exec) :: bin) | Doc (cs, doc') -> obj, lib, ((cs, doc') :: doc), bin | Flag _ | Test _ | SrcRepo _ -> acc) ([], [], [], []) t.pkg_generic.sections in TODO : we may be ' all ' iff only an exec with no deps or a native arch iff Native in bs . native arch iff Native in bs. *) let arch lst = "any" in let mk_deb nm lst = {name = nm; arch = arch lst} in let base_name = if Conf.is_set library_name then begin Conf.get ~ctxt library_name end else begin let groups, _, _ = OASISFindlib.findlib_mapping t.pkg_generic in match groups with | [hd] -> First method : if there is a single findlib library use its name *) OASISFindlib.findlib_of_group hd | _ -> (* Default method: try to guess the target name using source name *) List.fold_left (fun name pat -> Pcre.replace ~pat ~templ:"" name) (* Start with the package name *) t.pkg_generic.OASISTypes.name ["^ocaml-?"; "-?ocaml$"] end in let spf fmt = Printf.sprintf fmt in let add_doc nm t = Add doc package , only if more than one documentation * shipped . * shipped. *) if List.length doc > 1 then {t with deb_doc = Some (mk_deb nm [])} else t in let t = (* Determine if we have bin+dev+runtime *) match lib, obj, bin with | [], [], bin -> begin (* Only a binary package, name = source name *) let exec_name = if Conf.is_set executable_name then Conf.get ~ctxt executable_name else t.deb_name in add_doc (base_name^"-doc") {t with deb_exec = Some (mk_deb exec_name bin)} end | lib, obj, bin -> begin (* Library only *) let t = {t with deb_dev = Some (mk_deb (spf "lib%s-ocaml-dev" base_name) lib, mk_deb (spf "lib%s-ocaml" base_name) lib)} in (* Also executables ? *) let t = if bin <> [] then let exec_name = if Conf.is_set executable_name then Conf.get ~ctxt executable_name else spf "lib%s-ocaml-bin" base_name in {t with deb_exec = Some (mk_deb exec_name bin)} else t in add_doc (spf "lib%s-ocaml-doc" base_name) t end in t
null
https://raw.githubusercontent.com/ocaml/oasis2debian/41d268cada4afdac8c906ac99277d7c685bc15ae/src/GenPkg.ml
ocaml
**************************************************************************** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by your option) any later version, with the OCaml static compilation exception. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more details. **************************************************************************** * Compute package to generate Default method: try to guess the target name using source name Start with the package name Determine if we have bin+dev+runtime Only a binary package, name = source name Library only Also executables ?
oasis2debian : Create and maintain Debian package for an OASIS package Copyright ( C ) 2013 , the Free Software Foundation ; either version 2.1 of the License , or ( at You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA open OASISTypes open Common let library_name = Conf.create ~cli:"--library-name" "pkg_name Short name of the library (XXX in libXXX-ocaml-dev)." (Conf.Fun (fun () -> failwith "Not set")) let executable_name = Conf.create ~cli:"--executable-name" "pkg_name Full name of the package that contains executables." (Conf.Fun (fun () -> failwith "Not set")) let set ~ctxt t = let obj, lib, doc, bin = List.fold_left (fun ((obj, lib, doc, bin) as acc) -> function | Object (cs, bs, obj') -> ((cs, bs, obj') :: obj), lib, doc, bin | Library (cs, bs, lib') -> obj, ((cs, bs, lib') :: lib), doc, bin | Executable (cs, bs, exec) -> obj, lib, doc, ((cs, bs, exec) :: bin) | Doc (cs, doc') -> obj, lib, ((cs, doc') :: doc), bin | Flag _ | Test _ | SrcRepo _ -> acc) ([], [], [], []) t.pkg_generic.sections in TODO : we may be ' all ' iff only an exec with no deps or a native arch iff Native in bs . native arch iff Native in bs. *) let arch lst = "any" in let mk_deb nm lst = {name = nm; arch = arch lst} in let base_name = if Conf.is_set library_name then begin Conf.get ~ctxt library_name end else begin let groups, _, _ = OASISFindlib.findlib_mapping t.pkg_generic in match groups with | [hd] -> First method : if there is a single findlib library use its name *) OASISFindlib.findlib_of_group hd | _ -> List.fold_left (fun name pat -> Pcre.replace ~pat ~templ:"" name) t.pkg_generic.OASISTypes.name ["^ocaml-?"; "-?ocaml$"] end in let spf fmt = Printf.sprintf fmt in let add_doc nm t = Add doc package , only if more than one documentation * shipped . * shipped. *) if List.length doc > 1 then {t with deb_doc = Some (mk_deb nm [])} else t in let t = match lib, obj, bin with | [], [], bin -> begin let exec_name = if Conf.is_set executable_name then Conf.get ~ctxt executable_name else t.deb_name in add_doc (base_name^"-doc") {t with deb_exec = Some (mk_deb exec_name bin)} end | lib, obj, bin -> begin let t = {t with deb_dev = Some (mk_deb (spf "lib%s-ocaml-dev" base_name) lib, mk_deb (spf "lib%s-ocaml" base_name) lib)} in let t = if bin <> [] then let exec_name = if Conf.is_set executable_name then Conf.get ~ctxt executable_name else spf "lib%s-ocaml-bin" base_name in {t with deb_exec = Some (mk_deb exec_name bin)} else t in add_doc (spf "lib%s-ocaml-doc" base_name) t end in t
747c07f1d7b08baf5376bb88cb8655ecd12862f80184751571800712500a07e9
bobzhang/ocaml-book
util.ml
open Camlp4.PreCast.Syntax; open Camlp4.PreCast; open Camlp4.PreCast.Ast; open Camlp4.Sig; (** [neg_string "ab" ] = ["-ab"] [neg_string ""] = ["-"] *) value neg_string n = let len = String.length n in if len > 0 && n.[0] = '-' then String.sub n 1 (len - 1) else "-" ^ n ; (** | "unary minus" NONA [ "-"; e = SELF -> mkumin _loc "-" e | "-."; e = SELF -> mkumin _loc "-." e ] since ocaml respect (~-) as a prefix (-) and (~-.) as a prefix (-.) *) value mkumin _loc f arg = match arg with [ <:expr< $int:n$ >> -> <:expr< $int:neg_string n$ >> | <:expr< $int32:n$ >> -> <:expr< $int32:neg_string n$ >> | <:expr< $int64:n$ >> -> <:expr< $int64:neg_string n$ >> | <:expr< $nativeint:n$ >> -> <:expr< $nativeint:neg_string n$ >> | <:expr< $flo:n$ >> -> <:expr< $flo:neg_string n$ >> | _ -> <:expr< $lid:"~" ^ f$ $arg$ >> ] ; * given a list expr , translate it into a expr Here [ Loc.merge ( Ast.loc_of_expr e1 ) _ loc ] will give more precise location [ : loc - > option expr - > list expr - > expr ] [ mklistexp _ loc None [ < : expr<3 > > ; < : expr<4 > > ] | > opr#expr std_formatter ; = > [ 3 ; 4 ] given a list expr, translate it into a expr Here [Loc.merge (Ast.loc_of_expr e1) _loc ] will give more precise location [mklistexp : loc -> option expr -> list expr -> expr ] [mklistexp _loc None [ <:expr<3 >> ; <:expr<4 >> ] |> opr#expr std_formatter; => [ 3; 4 ] *) value mklistexp _loc last = loop True where rec loop top = fun [ [] -> match last with [ Some e -> e | None -> <:expr< [] >> ] | [e1 :: el] -> let _loc = if top then _loc else Loc.merge (Ast.loc_of_expr e1) _loc in <:expr< [$e1$ :: $loop False el$] >> ] ; * Camlp4 treats [ assert False ] as a special construct [ ExAsf ] # < : expr < assert False > > ; < : expr < assert False > > ; - : = ExAsf # < : expr < assert $ < : expr < False > > $ > > ; < : expr < assert $ < : expr < False > > $ > > ; - : Camlp4.PreCast.Ast.expr = ExAsr ( ExId ( IdUid " False " ) ) Camlp4 treats [assert False] as a special construct [ExAsf] # <:expr< assert False>>; <:expr< assert False>>; - : Camlp4.PreCast.Ast.expr = ExAsf # <:expr< assert $ <:expr< False >> $>>; <:expr< assert $ <:expr< False >> $>>; - : Camlp4.PreCast.Ast.expr = ExAsr (ExId (IdUid "False")) *) value mkassert _loc = fun [ <:expr< False >> -> <:expr< assert False >> (* this case takes care about the special assert false node *) | e -> <:expr< assert $e$ >> ] ; value append_eLem el e = el @ [e]; * ~c:"binding " " list " " code " ; - : string = " \\$listbinding : code " mk_anti ~c:"binding" "list" "code" ; - : string = "\\$listbinding:code" *) value mk_anti ?(c = "") n s = "\\$"^n^c^":"^s; * This is translated as value mksequence _ loc = fun [ ( Ast . ExSem _ _ _ | Ast . ExAnt _ _ as e ) - > Ast . e ] ; Notice [ < : expr < $ _ $ > > ] would be translated to underscore directly in most case ExAnt is embedded as a hole in a bigger ast . 708 : | " ( " ; e = SELF ; " ; " ; " ) " - > mksequence _ loc e 713 : | " begin " ; seq = sequence ; " end " - > mksequence _ loc seq 757 : < : expr < let $ rec : rf$ $ bi$ in $ mksequence _ loc el$ > > 761 : < : expr < let module $ m$ = $ mb$ in $ mksequence _ loc el$ > > This is translated as value mksequence _loc = fun [ (Ast.ExSem _ _ _ | Ast.ExAnt _ _ as e) -> Ast.ExSeq _loc e | e -> e ]; Notice [ <:expr< $_$ >> ] would be translated to underscore directly in most case ExAnt is embedded as a hole in a bigger ast. 708: | "("; e = SELF; ";"; ")" -> mksequence _loc e 713: | "begin"; seq = sequence; "end" -> mksequence _loc seq 757: <:expr< let $rec:rf$ $bi$ in $mksequence _loc el$ >> 761: <:expr< let module $m$ = $mb$ in $mksequence _loc el$ >> *) value mksequence _loc = fun [ <:expr< $_$; $_$ >> | <:expr< $anti:_$ >> as e -> <:expr< do { $e$ } >> | e -> e ] ; * 600 : < : expr < match $ mksequence ' _ loc e$ with [ $ a$ ] > > 602 : < : expr < try $ mksequence ' _ loc e$ with [ $ a$ ] > > 608 : < : expr < for $ i$ = $ mksequence ' _ loc e1 $ $ to : df$ $ mksequence ' _ loc e2 $ do { $ seq$ } > > 610 : < : expr < while $ mksequence ' _ loc e$ do { $ seq$ } > > 600: <:expr< match $mksequence' _loc e$ with [ $a$ ] >> 602: <:expr< try $mksequence' _loc e$ with [ $a$ ] >> 608: <:expr< for $i$ = $mksequence' _loc e1$ $to:df$ $mksequence' _loc e2$ do { $seq$ } >> 610: <:expr< while $mksequence' _loc e$ do { $seq$ } >> *) value mksequence' _loc = fun [ <:expr< $_$; $_$ >> as e -> <:expr< do { $e$ } >> | e -> e ] ; (** lid_of_ident <:ident< A.B.c >>; - : string = "c" *) value rec lid_of_ident = fun [ <:ident< $_$ . $i$ >> -> lid_of_ident i | <:ident< $lid:lid$ >> -> lid | _ -> assert False ]; * module_type_app < : module_type < A > > < : module_type < B > > ; - : Camlp4.PreCast . Ast.module_type = MtId ( IdApp ( IdUid " A " ) ( IdUid " B " ) ) < : module_type < A > > ; - : Camlp4.PreCast . Ast.module_type = MtId ( IdUid " A " ) Here we need define module_type_app , since | IdApp of loc * ident * ident | ExApp of loc * expr * expr but for module_expr | MeId of loc * ident | MeApp of loc * module_expr * module_expr since we require that for module_type_app operation , only MeId can be used as app operation . module_type_app <:module_type< A >> <:module_type< B >>; - : Camlp4.PreCast.Ast.module_type = MtId (IdApp (IdUid "A") (IdUid "B")) <:module_type< A >>; - : Camlp4.PreCast.Ast.module_type = MtId (IdUid "A") Here we need define module_type_app, since | IdApp of loc * ident* ident | ExApp of loc * expr * expr but for module_expr | MeId of loc * ident | MeApp of loc * module_expr * module_expr since we require that for module_type_app operation, only MeId can be used as app operation. *) value module_type_app mt1 mt2 = match (mt1, mt2) with [ (<:module_type@_loc< $id:i1$ >>, <:module_type< $id:i2$ >>) -> <:module_type< $id:<:ident< $i1$ $i2$ >>$ >> | _ -> raise Stream.Failure ]; * module_type_acc < : module_type < A > > < : module_type < B > > ; - : Camlp4.PreCast . Ast.module_type = MtId ( IdAcc ( IdUid " A " ) ( IdUid " B " ) ) module_type_acc <:module_type< A >> <:module_type< B >>; - : Camlp4.PreCast.Ast.module_type = MtId (IdAcc (IdUid "A") (IdUid "B")) *) value module_type_acc mt1 mt2 = match (mt1, mt2) with [ (<:module_type@_loc< $id:i1$ >>, <:module_type< $id:i2$ >>) -> <:module_type< $id:<:ident< $i1$.$i2$ >>$ >> | _ -> raise Stream.Failure ]; * | e1 = SELF ; " . " ; " { " ; e2 = comma_expr ; " } " - > bigarray_get _ loc e1 e2 support bigarray syntax extension < : expr < a. { ( b , c ) } > > ; - : = ExApp ( ExApp ( ExApp ( ExId ( IdAcc ( IdUid " Bigarray " ) ( IdAcc ( IdUid " Array2 " ) ( IdLid " get " ) ) ) ) ( ExId ( IdLid " a " ) ) ) ( ExId ( IdLid " b " ) ) ) ( ExId ( IdLid " c " ) ) remember [ Ast.list_of_expr ] only handles case ( ExCom , ExSem ) exSem_of_list and exCom_of_list are on the other hand | e1 = SELF; "."; "{"; e2 = comma_expr; "}" -> bigarray_get _loc e1 e2 support bigarray syntax extension <:expr<a.{ (b,c)}>>; - : Camlp4.PreCast.Ast.expr = ExApp (ExApp (ExApp (ExId (IdAcc (IdUid "Bigarray") (IdAcc (IdUid "Array2") (IdLid "get")))) (ExId (IdLid "a"))) (ExId (IdLid "b"))) (ExId (IdLid "c")) remember [Ast.list_of_expr] only handles case (ExCom, ExSem) exSem_of_list and exCom_of_list are on the other hand *) value bigarray_get _loc arr arg = let coords = match arg with [ <:expr< ($e1$, $e2$) >> | <:expr< $e1$, $e2$ >> -> Ast.list_of_expr e1 (Ast.list_of_expr e2 []) | _ -> [arg] ] in match coords with [ [c1] -> <:expr< Bigarray.Array1.get $arr$ $c1$ >> | [c1; c2] -> <:expr< Bigarray.Array2.get $arr$ $c1$ $c2$ >> | [c1; c2; c3] -> <:expr< Bigarray.Array3.get $arr$ $c1$ $c2$ $c3$ >> (* | coords -> <:expr< Bigarray.Genarray.get $arr$ [| $list:coords$ |] >> ] *) | coords -> <:expr< Bigarray.Genarray.get $arr$ [| $Ast.exSem_of_list coords$ |] >> ]; * | " : = " NONA [ e1 = SELF ; " : = " ; e2 = SELF ; dummy - > match bigarray_set _ loc e1 e2 with [ Some e - > e | None - > < : expr < $ e1 $ : = $ e2 $ > > ] ] | ":=" NONA [ e1 = SELF; ":="; e2 = SELF; dummy -> match bigarray_set _loc e1 e2 with [ Some e -> e | None -> <:expr< $e1$ := $e2$ >> ] ] *) value bigarray_set _loc var newval = match var with [ <:expr< Bigarray.Array1.get $arr$ $c1$ >> -> Some <:expr< Bigarray.Array1.set $arr$ $c1$ $newval$ >> | <:expr< Bigarray.Array2.get $arr$ $c1$ $c2$ >> -> Some <:expr< Bigarray.Array2.set $arr$ $c1$ $c2$ $newval$ >> | <:expr< Bigarray.Array3.get $arr$ $c1$ $c2$ $c3$ >> -> Some <:expr< Bigarray.Array3.set $arr$ $c1$ $c2$ $c3$ $newval$ >> | <:expr< Bigarray.Genarray.get $arr$ [| $coords$ |] >> -> Some <:expr< Bigarray.Genarray.set $arr$ [| $coords$ |] $newval$ >> | _ -> None ]; * [ [ " # " ; n = a_LIDENT ; dp = opt_expr ; semi - > ( [ < : < # $ n$ $ dp$ > > ] , stopped_at _ loc ) [ [ "#"; n = a_LIDENT; dp = opt_expr; semi -> ([ <:sig_item< # $n$ $dp$ >> ], stopped_at _loc) *) value stopped_at _loc = Some (Loc.move_line 1 _loc) (* FIXME be more precise *); * symbolchar " a!$ " 0 ; - : bool = False # symbolchar " a!$ " 1 ; symbolchar " a!$ " 1 ; - : bool = True symbolchar "a!$" 0; - : bool = False # symbolchar "a!$" 1; symbolchar "a!$" 1; - : bool = True *) value symbolchar = let list = ['$'; '!'; '%'; '&'; '*'; '+'; '-'; '.'; '/'; ':'; '<'; '='; '>'; '?'; '@'; '^'; '|'; '~'; '\\'] in let rec loop s i = if i == String.length s then True else if List.mem s.[i] list then loop s (i + 1) else False in loop ; * notice that it patterns match KEYWORD , and SYMBOl notice that it patterns match KEYWORD, and SYMBOl *) value setup_op_parser entry p = Gram.Entry.setup_parser entry (parser [: `(KEYWORD x | SYMBOL x, ti) when p x :] -> let _loc = Gram.token_location ti in <:expr< $lid:x$ >>); * setup prefixop Gram.parse_string Syntax.prefixop _ " ! - " ; - : = ExId ( IdLid " ! - " ) setup prefixop Gram.parse_string Syntax.prefixop _loc "!-"; - : Camlp4.PreCast.Syntax.Ast.expr = ExId (IdLid "!-") *) let list = ['!'; '?'; '~'] in let excl = ["!="; "??"] in setup_op_parser prefixop (fun x -> not (List.mem x excl) && String.length x >= 2 && List.mem x.[0] list && symbolchar x 1); * setup parser setup infixop0 parser *) let list_ok = ["<"; ">"; "<="; ">="; "="; "<>"; "=="; "!="; "$"] in let list_first_char_ok = ['='; '<'; '>'; '|'; '&'; '$'; '!'] in let excl = ["<-"; "||"; "&&"] in setup_op_parser infixop0 (fun x -> (List.mem x list_ok) || (not (List.mem x excl) && String.length x >= 2 && List.mem x.[0] list_first_char_ok && symbolchar x 1)); (** setup infixop1 parser *) let list = ['@'; '^'] in setup_op_parser infixop1 (fun x -> String.length x >= 1 && List.mem x.[0] list && symbolchar x 1); * setup infixop2 parser let list = ['+'; '-'] in setup_op_parser infixop2 (fun x -> x <> "->" && String.length x >= 1 && List.mem x.[0] list && symbolchar x 1); (** setup infixop3 parser *) let list = ['*'; '/'; '%'; '\\'] in setup_op_parser infixop3 (fun x -> String.length x >= 1 && List.mem x.[0] list && (x.[0] <> '*' || String.length x < 2 || x.[1] <> '*') && symbolchar x 1); * setup parser setup_op_parser infixop4 (fun x -> String.length x >= 2 && x.[0] == '*' && x.[1] == '*' && symbolchar x 2); * filter the token stream merge ` KEYWORD ( , ` KEYWORD , ` KEYWORD ) into a ( ) module . . Make Token ; value s= " ( mod ) " ; Here we use our brand new Lexer , so we get " mod " instead of [ KEYWORD " mod " ] Stream.next s ; ( * * SYMBOL " ( " , , " mod " , SYMBOL " ) " filter the token stream merge `KEYWORD (, `KEYWORD lxor, `KEYWORD ) into a (LIDENT lxor) module Lexer = Camlp4.Struct.Lexer.Make Token; value s= Lexer.from_string _loc "(mod)"; Here we use our brand new Lexer, so we get LIDENT "mod" instead of [ KEYWORD "mod"] Stream.next s ; (** SYMBOL "(", , LIDENT "mod", SYMBOL ")" *) *) value rec infix_kwds_filter = parser [ [: `((KEYWORD "(", _) as tok); xs :] -> match xs with parser [ [: `(KEYWORD ("mod"|"land"|"lor"|"lxor"|"lsl"|"lsr"|"asr" as i), _loc); `(KEYWORD ")", _); xs :] -> [: `(LIDENT i, _loc); infix_kwds_filter xs :] | [: xs :] -> [: `tok; infix_kwds_filter xs :] ] | [: `x; xs :] -> [: `x; infix_kwds_filter xs :] ] ; (** introduce filter [define_filter]: allows to register a new filter to the token filter *chain*. value define_filter : t -> (token_filter -> token_filter) -> unit; *) Token.Filter.define_filter (Gram.get_filter ()) (fun f strm -> infix_kwds_filter (f strm)); * it 's built on top of expr given expr , we get symb parser , then use parser symb to generate sem_expr . If we do n't use [ parse_tokens_after_filter ] , what will happen ? ? ? We need to support antiquotations here Gram.parse_string Syntax.sem_expr _ loc " a;b $ list : bbb$ " ; - : = ExSem ( ExSem ( ExId ( IdLid " a " ) ) ( ExId ( IdLid " b " ) ) ) ( ExAnt " \\$listexpr;:bbb " ) ( * * notice here we get \\$listexpr;:bbb as expected it's built on top of expr given expr, we get symb parser, then use parser symb to generate sem_expr. If we don't use [parse_tokens_after_filter], what will happen??? We need to support antiquotations here Gram.parse_string Syntax.sem_expr _loc "a;b $list:bbb$"; - : Camlp4.PreCast.Syntax.Ast.expr = ExSem (ExSem (ExId (IdLid "a")) (ExId (IdLid "b"))) (ExAnt "\\$listexpr;:bbb") (** notice here we get \\$listexpr;:bbb as expected *) Gram.parse_string Syntax.sem_expr _loc "a;b $bb$"; - : Camlp4.PreCast.Syntax.Ast.expr = ExSem (ExId (IdLid "a")) (ExApp (ExId (IdLid "b")) (ExAnt "\\$expr:bb")) setup_parser translate (stream token -> expr) to (entry expr) *) Gram.Entry.setup_parser sem_expr begin let symb1 = Gram.parse_tokens_after_filter expr in let symb = parser [ [: `(ANTIQUOT ("list" as n) s, ti) :] -> let _loc = Gram.token_location ti in <:expr< $anti:mk_anti ~c:"expr;" n s$ >> | [: a = symb1 :] -> a ] in let rec kont al = parser [ [: `(KEYWORD ";", _); a = symb; s :] -> let _loc = Loc.merge (Ast.loc_of_expr al) (Ast.loc_of_expr a) in kont <:expr< $al$; $a$ >> s | [: :] -> al ] in parser [: a = symb; s :] -> kont a s end;
null
https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/code/camlp4/parsers/util.ml
ocaml
* [neg_string "ab" ] = ["-ab"] [neg_string ""] = ["-"] * | "unary minus" NONA [ "-"; e = SELF -> mkumin _loc "-" e | "-."; e = SELF -> mkumin _loc "-." e ] since ocaml respect (~-) as a prefix (-) and (~-.) as a prefix (-.) this case takes care about the special assert false node * lid_of_ident <:ident< A.B.c >>; - : string = "c" | coords -> <:expr< Bigarray.Genarray.get $arr$ [| $list:coords$ |] >> ] FIXME be more precise * setup infixop1 parser * setup infixop3 parser * SYMBOL "(", , LIDENT "mod", SYMBOL ")" * introduce filter [define_filter]: allows to register a new filter to the token filter *chain*. value define_filter : t -> (token_filter -> token_filter) -> unit; * notice here we get \\$listexpr;:bbb as expected
open Camlp4.PreCast.Syntax; open Camlp4.PreCast; open Camlp4.PreCast.Ast; open Camlp4.Sig; value neg_string n = let len = String.length n in if len > 0 && n.[0] = '-' then String.sub n 1 (len - 1) else "-" ^ n ; value mkumin _loc f arg = match arg with [ <:expr< $int:n$ >> -> <:expr< $int:neg_string n$ >> | <:expr< $int32:n$ >> -> <:expr< $int32:neg_string n$ >> | <:expr< $int64:n$ >> -> <:expr< $int64:neg_string n$ >> | <:expr< $nativeint:n$ >> -> <:expr< $nativeint:neg_string n$ >> | <:expr< $flo:n$ >> -> <:expr< $flo:neg_string n$ >> | _ -> <:expr< $lid:"~" ^ f$ $arg$ >> ] ; * given a list expr , translate it into a expr Here [ Loc.merge ( Ast.loc_of_expr e1 ) _ loc ] will give more precise location [ : loc - > option expr - > list expr - > expr ] [ mklistexp _ loc None [ < : expr<3 > > ; < : expr<4 > > ] | > opr#expr std_formatter ; = > [ 3 ; 4 ] given a list expr, translate it into a expr Here [Loc.merge (Ast.loc_of_expr e1) _loc ] will give more precise location [mklistexp : loc -> option expr -> list expr -> expr ] [mklistexp _loc None [ <:expr<3 >> ; <:expr<4 >> ] |> opr#expr std_formatter; => [ 3; 4 ] *) value mklistexp _loc last = loop True where rec loop top = fun [ [] -> match last with [ Some e -> e | None -> <:expr< [] >> ] | [e1 :: el] -> let _loc = if top then _loc else Loc.merge (Ast.loc_of_expr e1) _loc in <:expr< [$e1$ :: $loop False el$] >> ] ; * Camlp4 treats [ assert False ] as a special construct [ ExAsf ] # < : expr < assert False > > ; < : expr < assert False > > ; - : = ExAsf # < : expr < assert $ < : expr < False > > $ > > ; < : expr < assert $ < : expr < False > > $ > > ; - : Camlp4.PreCast.Ast.expr = ExAsr ( ExId ( IdUid " False " ) ) Camlp4 treats [assert False] as a special construct [ExAsf] # <:expr< assert False>>; <:expr< assert False>>; - : Camlp4.PreCast.Ast.expr = ExAsf # <:expr< assert $ <:expr< False >> $>>; <:expr< assert $ <:expr< False >> $>>; - : Camlp4.PreCast.Ast.expr = ExAsr (ExId (IdUid "False")) *) value mkassert _loc = fun [ <:expr< False >> -> | e -> <:expr< assert $e$ >> ] ; value append_eLem el e = el @ [e]; * ~c:"binding " " list " " code " ; - : string = " \\$listbinding : code " mk_anti ~c:"binding" "list" "code" ; - : string = "\\$listbinding:code" *) value mk_anti ?(c = "") n s = "\\$"^n^c^":"^s; * This is translated as value mksequence _ loc = fun [ ( Ast . ExSem _ _ _ | Ast . ExAnt _ _ as e ) - > Ast . e ] ; Notice [ < : expr < $ _ $ > > ] would be translated to underscore directly in most case ExAnt is embedded as a hole in a bigger ast . 708 : | " ( " ; e = SELF ; " ; " ; " ) " - > mksequence _ loc e 713 : | " begin " ; seq = sequence ; " end " - > mksequence _ loc seq 757 : < : expr < let $ rec : rf$ $ bi$ in $ mksequence _ loc el$ > > 761 : < : expr < let module $ m$ = $ mb$ in $ mksequence _ loc el$ > > This is translated as value mksequence _loc = fun [ (Ast.ExSem _ _ _ | Ast.ExAnt _ _ as e) -> Ast.ExSeq _loc e | e -> e ]; Notice [ <:expr< $_$ >> ] would be translated to underscore directly in most case ExAnt is embedded as a hole in a bigger ast. 708: | "("; e = SELF; ";"; ")" -> mksequence _loc e 713: | "begin"; seq = sequence; "end" -> mksequence _loc seq 757: <:expr< let $rec:rf$ $bi$ in $mksequence _loc el$ >> 761: <:expr< let module $m$ = $mb$ in $mksequence _loc el$ >> *) value mksequence _loc = fun [ <:expr< $_$; $_$ >> | <:expr< $anti:_$ >> as e -> <:expr< do { $e$ } >> | e -> e ] ; * 600 : < : expr < match $ mksequence ' _ loc e$ with [ $ a$ ] > > 602 : < : expr < try $ mksequence ' _ loc e$ with [ $ a$ ] > > 608 : < : expr < for $ i$ = $ mksequence ' _ loc e1 $ $ to : df$ $ mksequence ' _ loc e2 $ do { $ seq$ } > > 610 : < : expr < while $ mksequence ' _ loc e$ do { $ seq$ } > > 600: <:expr< match $mksequence' _loc e$ with [ $a$ ] >> 602: <:expr< try $mksequence' _loc e$ with [ $a$ ] >> 608: <:expr< for $i$ = $mksequence' _loc e1$ $to:df$ $mksequence' _loc e2$ do { $seq$ } >> 610: <:expr< while $mksequence' _loc e$ do { $seq$ } >> *) value mksequence' _loc = fun [ <:expr< $_$; $_$ >> as e -> <:expr< do { $e$ } >> | e -> e ] ; value rec lid_of_ident = fun [ <:ident< $_$ . $i$ >> -> lid_of_ident i | <:ident< $lid:lid$ >> -> lid | _ -> assert False ]; * module_type_app < : module_type < A > > < : module_type < B > > ; - : Camlp4.PreCast . Ast.module_type = MtId ( IdApp ( IdUid " A " ) ( IdUid " B " ) ) < : module_type < A > > ; - : Camlp4.PreCast . Ast.module_type = MtId ( IdUid " A " ) Here we need define module_type_app , since | IdApp of loc * ident * ident | ExApp of loc * expr * expr but for module_expr | MeId of loc * ident | MeApp of loc * module_expr * module_expr since we require that for module_type_app operation , only MeId can be used as app operation . module_type_app <:module_type< A >> <:module_type< B >>; - : Camlp4.PreCast.Ast.module_type = MtId (IdApp (IdUid "A") (IdUid "B")) <:module_type< A >>; - : Camlp4.PreCast.Ast.module_type = MtId (IdUid "A") Here we need define module_type_app, since | IdApp of loc * ident* ident | ExApp of loc * expr * expr but for module_expr | MeId of loc * ident | MeApp of loc * module_expr * module_expr since we require that for module_type_app operation, only MeId can be used as app operation. *) value module_type_app mt1 mt2 = match (mt1, mt2) with [ (<:module_type@_loc< $id:i1$ >>, <:module_type< $id:i2$ >>) -> <:module_type< $id:<:ident< $i1$ $i2$ >>$ >> | _ -> raise Stream.Failure ]; * module_type_acc < : module_type < A > > < : module_type < B > > ; - : Camlp4.PreCast . Ast.module_type = MtId ( IdAcc ( IdUid " A " ) ( IdUid " B " ) ) module_type_acc <:module_type< A >> <:module_type< B >>; - : Camlp4.PreCast.Ast.module_type = MtId (IdAcc (IdUid "A") (IdUid "B")) *) value module_type_acc mt1 mt2 = match (mt1, mt2) with [ (<:module_type@_loc< $id:i1$ >>, <:module_type< $id:i2$ >>) -> <:module_type< $id:<:ident< $i1$.$i2$ >>$ >> | _ -> raise Stream.Failure ]; * | e1 = SELF ; " . " ; " { " ; e2 = comma_expr ; " } " - > bigarray_get _ loc e1 e2 support bigarray syntax extension < : expr < a. { ( b , c ) } > > ; - : = ExApp ( ExApp ( ExApp ( ExId ( IdAcc ( IdUid " Bigarray " ) ( IdAcc ( IdUid " Array2 " ) ( IdLid " get " ) ) ) ) ( ExId ( IdLid " a " ) ) ) ( ExId ( IdLid " b " ) ) ) ( ExId ( IdLid " c " ) ) remember [ Ast.list_of_expr ] only handles case ( ExCom , ExSem ) exSem_of_list and exCom_of_list are on the other hand | e1 = SELF; "."; "{"; e2 = comma_expr; "}" -> bigarray_get _loc e1 e2 support bigarray syntax extension <:expr<a.{ (b,c)}>>; - : Camlp4.PreCast.Ast.expr = ExApp (ExApp (ExApp (ExId (IdAcc (IdUid "Bigarray") (IdAcc (IdUid "Array2") (IdLid "get")))) (ExId (IdLid "a"))) (ExId (IdLid "b"))) (ExId (IdLid "c")) remember [Ast.list_of_expr] only handles case (ExCom, ExSem) exSem_of_list and exCom_of_list are on the other hand *) value bigarray_get _loc arr arg = let coords = match arg with [ <:expr< ($e1$, $e2$) >> | <:expr< $e1$, $e2$ >> -> Ast.list_of_expr e1 (Ast.list_of_expr e2 []) | _ -> [arg] ] in match coords with [ [c1] -> <:expr< Bigarray.Array1.get $arr$ $c1$ >> | [c1; c2] -> <:expr< Bigarray.Array2.get $arr$ $c1$ $c2$ >> | [c1; c2; c3] -> <:expr< Bigarray.Array3.get $arr$ $c1$ $c2$ $c3$ >> | coords -> <:expr< Bigarray.Genarray.get $arr$ [| $Ast.exSem_of_list coords$ |] >> ]; * | " : = " NONA [ e1 = SELF ; " : = " ; e2 = SELF ; dummy - > match bigarray_set _ loc e1 e2 with [ Some e - > e | None - > < : expr < $ e1 $ : = $ e2 $ > > ] ] | ":=" NONA [ e1 = SELF; ":="; e2 = SELF; dummy -> match bigarray_set _loc e1 e2 with [ Some e -> e | None -> <:expr< $e1$ := $e2$ >> ] ] *) value bigarray_set _loc var newval = match var with [ <:expr< Bigarray.Array1.get $arr$ $c1$ >> -> Some <:expr< Bigarray.Array1.set $arr$ $c1$ $newval$ >> | <:expr< Bigarray.Array2.get $arr$ $c1$ $c2$ >> -> Some <:expr< Bigarray.Array2.set $arr$ $c1$ $c2$ $newval$ >> | <:expr< Bigarray.Array3.get $arr$ $c1$ $c2$ $c3$ >> -> Some <:expr< Bigarray.Array3.set $arr$ $c1$ $c2$ $c3$ $newval$ >> | <:expr< Bigarray.Genarray.get $arr$ [| $coords$ |] >> -> Some <:expr< Bigarray.Genarray.set $arr$ [| $coords$ |] $newval$ >> | _ -> None ]; * [ [ " # " ; n = a_LIDENT ; dp = opt_expr ; semi - > ( [ < : < # $ n$ $ dp$ > > ] , stopped_at _ loc ) [ [ "#"; n = a_LIDENT; dp = opt_expr; semi -> ([ <:sig_item< # $n$ $dp$ >> ], stopped_at _loc) *) value stopped_at _loc = * symbolchar " a!$ " 0 ; - : bool = False # symbolchar " a!$ " 1 ; symbolchar " a!$ " 1 ; - : bool = True symbolchar "a!$" 0; - : bool = False # symbolchar "a!$" 1; symbolchar "a!$" 1; - : bool = True *) value symbolchar = let list = ['$'; '!'; '%'; '&'; '*'; '+'; '-'; '.'; '/'; ':'; '<'; '='; '>'; '?'; '@'; '^'; '|'; '~'; '\\'] in let rec loop s i = if i == String.length s then True else if List.mem s.[i] list then loop s (i + 1) else False in loop ; * notice that it patterns match KEYWORD , and SYMBOl notice that it patterns match KEYWORD, and SYMBOl *) value setup_op_parser entry p = Gram.Entry.setup_parser entry (parser [: `(KEYWORD x | SYMBOL x, ti) when p x :] -> let _loc = Gram.token_location ti in <:expr< $lid:x$ >>); * setup prefixop Gram.parse_string Syntax.prefixop _ " ! - " ; - : = ExId ( IdLid " ! - " ) setup prefixop Gram.parse_string Syntax.prefixop _loc "!-"; - : Camlp4.PreCast.Syntax.Ast.expr = ExId (IdLid "!-") *) let list = ['!'; '?'; '~'] in let excl = ["!="; "??"] in setup_op_parser prefixop (fun x -> not (List.mem x excl) && String.length x >= 2 && List.mem x.[0] list && symbolchar x 1); * setup parser setup infixop0 parser *) let list_ok = ["<"; ">"; "<="; ">="; "="; "<>"; "=="; "!="; "$"] in let list_first_char_ok = ['='; '<'; '>'; '|'; '&'; '$'; '!'] in let excl = ["<-"; "||"; "&&"] in setup_op_parser infixop0 (fun x -> (List.mem x list_ok) || (not (List.mem x excl) && String.length x >= 2 && List.mem x.[0] list_first_char_ok && symbolchar x 1)); let list = ['@'; '^'] in setup_op_parser infixop1 (fun x -> String.length x >= 1 && List.mem x.[0] list && symbolchar x 1); * setup infixop2 parser let list = ['+'; '-'] in setup_op_parser infixop2 (fun x -> x <> "->" && String.length x >= 1 && List.mem x.[0] list && symbolchar x 1); let list = ['*'; '/'; '%'; '\\'] in setup_op_parser infixop3 (fun x -> String.length x >= 1 && List.mem x.[0] list && (x.[0] <> '*' || String.length x < 2 || x.[1] <> '*') && symbolchar x 1); * setup parser setup_op_parser infixop4 (fun x -> String.length x >= 2 && x.[0] == '*' && x.[1] == '*' && symbolchar x 2); * filter the token stream merge ` KEYWORD ( , ` KEYWORD , ` KEYWORD ) into a ( ) module . . Make Token ; value s= " ( mod ) " ; Here we use our brand new Lexer , so we get " mod " instead of [ KEYWORD " mod " ] Stream.next s ; ( * * SYMBOL " ( " , , " mod " , SYMBOL " ) " filter the token stream merge `KEYWORD (, `KEYWORD lxor, `KEYWORD ) into a (LIDENT lxor) module Lexer = Camlp4.Struct.Lexer.Make Token; value s= Lexer.from_string _loc "(mod)"; Here we use our brand new Lexer, so we get LIDENT "mod" instead of [ KEYWORD "mod"] Stream.next s ; *) value rec infix_kwds_filter = parser [ [: `((KEYWORD "(", _) as tok); xs :] -> match xs with parser [ [: `(KEYWORD ("mod"|"land"|"lor"|"lxor"|"lsl"|"lsr"|"asr" as i), _loc); `(KEYWORD ")", _); xs :] -> [: `(LIDENT i, _loc); infix_kwds_filter xs :] | [: xs :] -> [: `tok; infix_kwds_filter xs :] ] | [: `x; xs :] -> [: `x; infix_kwds_filter xs :] ] ; Token.Filter.define_filter (Gram.get_filter ()) (fun f strm -> infix_kwds_filter (f strm)); * it 's built on top of expr given expr , we get symb parser , then use parser symb to generate sem_expr . If we do n't use [ parse_tokens_after_filter ] , what will happen ? ? ? We need to support antiquotations here Gram.parse_string Syntax.sem_expr _ loc " a;b $ list : bbb$ " ; - : = ExSem ( ExSem ( ExId ( IdLid " a " ) ) ( ExId ( IdLid " b " ) ) ) ( ExAnt " \\$listexpr;:bbb " ) ( * * notice here we get \\$listexpr;:bbb as expected it's built on top of expr given expr, we get symb parser, then use parser symb to generate sem_expr. If we don't use [parse_tokens_after_filter], what will happen??? We need to support antiquotations here Gram.parse_string Syntax.sem_expr _loc "a;b $list:bbb$"; - : Camlp4.PreCast.Syntax.Ast.expr = ExSem (ExSem (ExId (IdLid "a")) (ExId (IdLid "b"))) (ExAnt "\\$listexpr;:bbb") Gram.parse_string Syntax.sem_expr _loc "a;b $bb$"; - : Camlp4.PreCast.Syntax.Ast.expr = ExSem (ExId (IdLid "a")) (ExApp (ExId (IdLid "b")) (ExAnt "\\$expr:bb")) setup_parser translate (stream token -> expr) to (entry expr) *) Gram.Entry.setup_parser sem_expr begin let symb1 = Gram.parse_tokens_after_filter expr in let symb = parser [ [: `(ANTIQUOT ("list" as n) s, ti) :] -> let _loc = Gram.token_location ti in <:expr< $anti:mk_anti ~c:"expr;" n s$ >> | [: a = symb1 :] -> a ] in let rec kont al = parser [ [: `(KEYWORD ";", _); a = symb; s :] -> let _loc = Loc.merge (Ast.loc_of_expr al) (Ast.loc_of_expr a) in kont <:expr< $al$; $a$ >> s | [: :] -> al ] in parser [: a = symb; s :] -> kont a s end;
213878663e3f8bf98184cb12bed808f549f457aa67136e03d3f08ab8b48bea71
jtdaugherty/tart
AskToSave.hs
module UI.AskToSave ( drawAskToSaveUI ) where import Brick import Brick.Widgets.Border import Brick.Widgets.Center import Types import Theme drawAskToSaveUI :: AppState -> [Widget Name] drawAskToSaveUI _ = [drawPromptWindow] drawPromptWindow :: Widget Name drawPromptWindow = centerLayer $ borderWithLabel (str "Save") $ hLimit 60 $ padLeftRight 2 $ padTopBottom 1 body where help = hBox [ str "(" , withDefAttr keybindingAttr $ str "Esc" , str " to quit without saving)" ] body = (hCenter $ str "You have unsaved changes. Save them? (y/n)") <=> (hCenter help)
null
https://raw.githubusercontent.com/jtdaugherty/tart/03d2bb8c3a01f3249c6a442b42aa319dc3a4f5de/programs/UI/AskToSave.hs
haskell
module UI.AskToSave ( drawAskToSaveUI ) where import Brick import Brick.Widgets.Border import Brick.Widgets.Center import Types import Theme drawAskToSaveUI :: AppState -> [Widget Name] drawAskToSaveUI _ = [drawPromptWindow] drawPromptWindow :: Widget Name drawPromptWindow = centerLayer $ borderWithLabel (str "Save") $ hLimit 60 $ padLeftRight 2 $ padTopBottom 1 body where help = hBox [ str "(" , withDefAttr keybindingAttr $ str "Esc" , str " to quit without saving)" ] body = (hCenter $ str "You have unsaved changes. Save them? (y/n)") <=> (hCenter help)
443ddf65ceebd114dc22fdc07b5a791ca5c2691ea0c5b347ea10fc658e2faeae
esl/MongooseIM
mongoose_graphql_enum.erl
-module(mongoose_graphql_enum). -export([input/2, output/2]). -ignore_xref([input/2, output/2]). input(<<"PresenceShow">>, Show) -> {ok, list_to_binary(string:to_lower(binary_to_list(Show)))}; input(<<"PresenceType">>, Type) -> {ok, list_to_binary(string:to_lower(binary_to_list(Type)))}; input(<<"Affiliation">>, <<"OWNER">>) -> {ok, owner}; input(<<"Affiliation">>, <<"MEMBER">>) -> {ok, member}; input(<<"Affiliation">>, <<"NONE">>) -> {ok, none}; input(<<"AddressTags">>, Name) -> {ok, Name}; input(<<"BlockingAction">>, <<"ALLOW">>) -> {ok, allow}; input(<<"BlockingAction">>, <<"DENY">>) -> {ok, deny}; input(<<"BlockedEntityType">>, <<"USER">>) -> {ok, user}; input(<<"BlockedEntityType">>, <<"ROOM">>) -> {ok, room}; input(<<"EmailTags">>, Name) -> {ok, Name}; input(<<"SubAction">>, <<"INVITE">>) -> {ok, invite}; input(<<"SubAction">>, <<"ACCEPT">>) -> {ok, accept}; input(<<"SubAction">>, <<"DECLINE">>) -> {ok, decline}; input(<<"SubAction">>, <<"CANCEL">>) -> {ok, cancel}; input(<<"MutualSubAction">>, <<"CONNECT">>) -> {ok, connect}; input(<<"MutualSubAction">>, <<"DISCONNECT">>) -> {ok, disconnect}; input(<<"MUCRole">>, <<"VISITOR">>) -> {ok, visitor}; input(<<"MUCRole">>, <<"PARTICIPANT">>) -> {ok, participant}; input(<<"MUCRole">>, <<"MODERATOR">>) -> {ok, moderator}; input(<<"MUCAffiliation">>, <<"NONE">>) -> {ok, none}; input(<<"MUCAffiliation">>, <<"MEMBER">>) -> {ok, member}; input(<<"MUCAffiliation">>, <<"OUTCAST">>) -> {ok, outcast}; input(<<"MUCAffiliation">>, <<"ADMIN">>) -> {ok, admin}; input(<<"MUCAffiliation">>, <<"OWNER">>) -> {ok, owner}; input(<<"PrivacyClassificationTags">>, Name) -> {ok, Name}; input(<<"TelephoneTags">>, Name) -> {ok, Name}; input(<<"LogLevel">>, Name) -> {ok, list_to_atom(string:to_lower(binary_to_list(Name)))}; input(<<"MetricType">>, Name) -> {ok, Name}. output(<<"DomainStatus">>, Type) -> {ok, list_to_binary(string:to_upper(atom_to_list(Type)))}; output(<<"PresenceShow">>, Show) -> {ok, list_to_binary(string:to_upper(binary_to_list(Show)))}; output(<<"PresenceType">>, Type) -> {ok, list_to_binary(string:to_upper(binary_to_list(Type)))}; output(<<"AuthStatus">>, Status) -> {ok, atom_to_binary(Status, utf8)}; output(<<"AuthType">>, Type) -> {ok, list_to_binary(string:to_upper(atom_to_list(Type)))}; output(<<"Affiliation">>, Aff) -> {ok, list_to_binary(string:to_upper(atom_to_list(Aff)))}; output(<<"BlockingAction">>, Action) -> {ok, list_to_binary(string:to_upper(atom_to_list(Action)))}; output(<<"BlockedEntityType">>, What) -> {ok, list_to_binary(string:to_upper(atom_to_list(What)))}; output(<<"ContactSub">>, Type) when Type =:= both; Type =:= from; Type =:= to; Type =:= none -> {ok, list_to_binary(string:to_upper(atom_to_list(Type)))}; output(<<"ContactAsk">>, Type) when Type =:= subscrube; Type =:= unsubscribe; Type =:= in; Type =:= out; Type =:= both; Type =:= none -> {ok, list_to_binary(string:to_upper(atom_to_list(Type)))}; output(<<"MUCRole">>, Role) -> {ok, list_to_binary(string:to_upper(atom_to_list(Role)))}; output(<<"MUCAffiliation">>, Aff) -> {ok, list_to_binary(string:to_upper(atom_to_list(Aff)))}; output(<<"AddressTags">>, Name) -> {ok, Name}; output(<<"EmailTags">>, Name) -> {ok, Name}; output(<<"PrivacyClassificationTags">>, Name) -> {ok, Name}; output(<<"LogLevel">>, Name) -> {ok, list_to_binary(string:to_upper(atom_to_list(Name)))}; output(<<"TelephoneTags">>, Name) -> {ok, Name}; output(<<"MetricType">>, Type) -> {ok, Type}; output(<<"StatusCode">>, Code) -> {ok, Code}.
null
https://raw.githubusercontent.com/esl/MongooseIM/c863ca0a6109c782577a63e00510f634ca31d831/src/graphql/mongoose_graphql_enum.erl
erlang
-module(mongoose_graphql_enum). -export([input/2, output/2]). -ignore_xref([input/2, output/2]). input(<<"PresenceShow">>, Show) -> {ok, list_to_binary(string:to_lower(binary_to_list(Show)))}; input(<<"PresenceType">>, Type) -> {ok, list_to_binary(string:to_lower(binary_to_list(Type)))}; input(<<"Affiliation">>, <<"OWNER">>) -> {ok, owner}; input(<<"Affiliation">>, <<"MEMBER">>) -> {ok, member}; input(<<"Affiliation">>, <<"NONE">>) -> {ok, none}; input(<<"AddressTags">>, Name) -> {ok, Name}; input(<<"BlockingAction">>, <<"ALLOW">>) -> {ok, allow}; input(<<"BlockingAction">>, <<"DENY">>) -> {ok, deny}; input(<<"BlockedEntityType">>, <<"USER">>) -> {ok, user}; input(<<"BlockedEntityType">>, <<"ROOM">>) -> {ok, room}; input(<<"EmailTags">>, Name) -> {ok, Name}; input(<<"SubAction">>, <<"INVITE">>) -> {ok, invite}; input(<<"SubAction">>, <<"ACCEPT">>) -> {ok, accept}; input(<<"SubAction">>, <<"DECLINE">>) -> {ok, decline}; input(<<"SubAction">>, <<"CANCEL">>) -> {ok, cancel}; input(<<"MutualSubAction">>, <<"CONNECT">>) -> {ok, connect}; input(<<"MutualSubAction">>, <<"DISCONNECT">>) -> {ok, disconnect}; input(<<"MUCRole">>, <<"VISITOR">>) -> {ok, visitor}; input(<<"MUCRole">>, <<"PARTICIPANT">>) -> {ok, participant}; input(<<"MUCRole">>, <<"MODERATOR">>) -> {ok, moderator}; input(<<"MUCAffiliation">>, <<"NONE">>) -> {ok, none}; input(<<"MUCAffiliation">>, <<"MEMBER">>) -> {ok, member}; input(<<"MUCAffiliation">>, <<"OUTCAST">>) -> {ok, outcast}; input(<<"MUCAffiliation">>, <<"ADMIN">>) -> {ok, admin}; input(<<"MUCAffiliation">>, <<"OWNER">>) -> {ok, owner}; input(<<"PrivacyClassificationTags">>, Name) -> {ok, Name}; input(<<"TelephoneTags">>, Name) -> {ok, Name}; input(<<"LogLevel">>, Name) -> {ok, list_to_atom(string:to_lower(binary_to_list(Name)))}; input(<<"MetricType">>, Name) -> {ok, Name}. output(<<"DomainStatus">>, Type) -> {ok, list_to_binary(string:to_upper(atom_to_list(Type)))}; output(<<"PresenceShow">>, Show) -> {ok, list_to_binary(string:to_upper(binary_to_list(Show)))}; output(<<"PresenceType">>, Type) -> {ok, list_to_binary(string:to_upper(binary_to_list(Type)))}; output(<<"AuthStatus">>, Status) -> {ok, atom_to_binary(Status, utf8)}; output(<<"AuthType">>, Type) -> {ok, list_to_binary(string:to_upper(atom_to_list(Type)))}; output(<<"Affiliation">>, Aff) -> {ok, list_to_binary(string:to_upper(atom_to_list(Aff)))}; output(<<"BlockingAction">>, Action) -> {ok, list_to_binary(string:to_upper(atom_to_list(Action)))}; output(<<"BlockedEntityType">>, What) -> {ok, list_to_binary(string:to_upper(atom_to_list(What)))}; output(<<"ContactSub">>, Type) when Type =:= both; Type =:= from; Type =:= to; Type =:= none -> {ok, list_to_binary(string:to_upper(atom_to_list(Type)))}; output(<<"ContactAsk">>, Type) when Type =:= subscrube; Type =:= unsubscribe; Type =:= in; Type =:= out; Type =:= both; Type =:= none -> {ok, list_to_binary(string:to_upper(atom_to_list(Type)))}; output(<<"MUCRole">>, Role) -> {ok, list_to_binary(string:to_upper(atom_to_list(Role)))}; output(<<"MUCAffiliation">>, Aff) -> {ok, list_to_binary(string:to_upper(atom_to_list(Aff)))}; output(<<"AddressTags">>, Name) -> {ok, Name}; output(<<"EmailTags">>, Name) -> {ok, Name}; output(<<"PrivacyClassificationTags">>, Name) -> {ok, Name}; output(<<"LogLevel">>, Name) -> {ok, list_to_binary(string:to_upper(atom_to_list(Name)))}; output(<<"TelephoneTags">>, Name) -> {ok, Name}; output(<<"MetricType">>, Type) -> {ok, Type}; output(<<"StatusCode">>, Code) -> {ok, Code}.
5adb3fcebc99dce2bb6b9c1a5f2a6608344ce309b354f5bcbfb2f8de1fc21b3e
qiao/sicp-solutions
1.19.scm
(define (fib n) (fit-iter 1 0 0 1 n)) (define (fib-iter a b p q count) (conf ((= count 0) b) ((even? count) (fib-iter a b (+ (square p) (square q)) (+ (* 2 p q) (square q)) (/ count 2))) (else (fib-iter (+ (* b q) (* a q) (*a p)) (+ (* b p) (* a q)) p q (- count 1)))))
null
https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter1/1.19.scm
scheme
(define (fib n) (fit-iter 1 0 0 1 n)) (define (fib-iter a b p q count) (conf ((= count 0) b) ((even? count) (fib-iter a b (+ (square p) (square q)) (+ (* 2 p q) (square q)) (/ count 2))) (else (fib-iter (+ (* b q) (* a q) (*a p)) (+ (* b p) (* a q)) p q (- count 1)))))
1b2b178d70a34edd7ac6034ee7df666ec8d93cecc6d23f0d4edb53cf67f4fef1
aisamanra/config-ini
basic.hs
fromList [ ( "s1", fromList [ ("foo", "bar"), ("baz", "quux") ] ), ( "s2", fromList [("argl", "bargl")] ) ]
null
https://raw.githubusercontent.com/aisamanra/config-ini/35dd9a28d32fde6c78b778653359579d65386d79/test/prewritten/cases/basic.hs
haskell
fromList [ ( "s1", fromList [ ("foo", "bar"), ("baz", "quux") ] ), ( "s2", fromList [("argl", "bargl")] ) ]
9ac77d492cbf5a7487612ff86ef712c3412d7736f682ff4ed8c242d0cc9e0dc7
maxcountryman/quanta
test_database.clj
(ns quanta.test_database (:require [clj-leveldb :as level] [clojure.set :refer [union]] [clojure.test :refer [deftest is use-fixtures]] [quanta.database :as database])) (def ^{:private true} db (atom nil)) (defn db-fixture [test-fn] (let [paths [".test-primary.db" ".test-trigram.db"]] ;; Setup the test db instance. (with-open [store (apply database/leveldb-store paths)] (swap! db (constantly store)) (test-fn)) ;; Destroy the test db instance. (doseq [path paths] (level/destroy-db path)))) (use-fixtures :each db-fixture) (deftest test-n-grams (is (= (database/n-grams 1 "foobar") '((\f) (\o) (\o) (\b) (\a) (\r)))) (is (= (database/n-grams 3 "foobar") '((\f \o \o) (\o \o \b) (\o \b \a) (\b \a \r))))) (deftest test-trigram-keys (is (= (database/trigram-keys "foobar") '("foo" "oob" "oba" "bar")))) (deftest test-k->re-s ;; Note that we apply str to the regex pattern in order to check equality. This is because Java 's regex pattern objects do not implement equals . ;; ;; See: -1182 (is (= (update-in (database/k->re-s "foo.") [0] str) [(str #"foo[.]") "foo."])) (is (= (update-in (database/k->re-s "foo%") [0] str) [(str #"foo.*") "foo"])) (is (= (update-in (database/k->re-s "foo*") [0] str) [(str #"foo.*") "foo"]))) (deftest test-match (database/put! @db "fooqux" "a") (database/put! @db "foobar" "b") (database/put! @db "foobaz" "c") (database/put! @db "nada" "d") (is (= (database/match @db "missing%") ())) (is (= (database/match @db "foob%") '("foobar" "foobaz"))) (is (= (database/match @db "fo%") '("foobar" "fooqux" "foobaz"))) (is (= (database/match @db "nada%") '("nada")))) (deftest test-put-with-merge! (database/put! @db "foo" #{1 2 3}) (database/put-with-merge! @db "foo" #{1 5 3} union) (= (database/get @db "foo") #{1 2 3 5})) (deftest test-max-vector (database/put! @db "vector" {0 1 13 42}) (is (= (database/max-vector @db "missing" {}) nil)) (is (= (database/max-vector @db "vector" {}) {0 1 13 42})) (is (= (database/max-vector @db "vector" {0 0 13 42}) {0 1})) (is (= (database/max-vector @db "vector" {0 1 13 42}) {}))) (deftest test-update-vector! ;; Ensure inserting a fresh vector populates the db. (is (= (database/update-vector! @db "vector" {0 1 13 42}) {0 1 13 42})) (is (= (database/get @db "vector") {0 1 13 42})) ;; Ensure only updates are returned. (is (database/update-vector! @db "vector" {0 0 13 42}) {0 1}) (is (= (database/get @db "vector") {0 1 13 42})) ;; Ensure partial updates work correctly. (is (= (database/update-vector! @db "vector" {0 2}) {0 2})) (is (= (database/get @db "vector") {0 2 13 42})) ;; Ensure an empty vector does not change stored vector. (is (= (database/update-vector! @db "vector" {}) {})) (is (= (database/get @db "vector") {0 2 13 42})) ;; Ensure adding new indices updates the store vector. (is (= (database/update-vector! @db "vector" {3 7}) {3 7})) (is (= (database/get @db "vector") {0 2 3 7 13 42})))
null
https://raw.githubusercontent.com/maxcountryman/quanta/9a1cd9b5b0d2b1706db9c5184fd653f26162cb23/test/quanta/test_database.clj
clojure
Setup the test db instance. Destroy the test db instance. Note that we apply str to the regex pattern in order to check equality. See: -1182 Ensure inserting a fresh vector populates the db. Ensure only updates are returned. Ensure partial updates work correctly. Ensure an empty vector does not change stored vector. Ensure adding new indices updates the store vector.
(ns quanta.test_database (:require [clj-leveldb :as level] [clojure.set :refer [union]] [clojure.test :refer [deftest is use-fixtures]] [quanta.database :as database])) (def ^{:private true} db (atom nil)) (defn db-fixture [test-fn] (let [paths [".test-primary.db" ".test-trigram.db"]] (with-open [store (apply database/leveldb-store paths)] (swap! db (constantly store)) (test-fn)) (doseq [path paths] (level/destroy-db path)))) (use-fixtures :each db-fixture) (deftest test-n-grams (is (= (database/n-grams 1 "foobar") '((\f) (\o) (\o) (\b) (\a) (\r)))) (is (= (database/n-grams 3 "foobar") '((\f \o \o) (\o \o \b) (\o \b \a) (\b \a \r))))) (deftest test-trigram-keys (is (= (database/trigram-keys "foobar") '("foo" "oob" "oba" "bar")))) (deftest test-k->re-s This is because Java 's regex pattern objects do not implement equals . (is (= (update-in (database/k->re-s "foo.") [0] str) [(str #"foo[.]") "foo."])) (is (= (update-in (database/k->re-s "foo%") [0] str) [(str #"foo.*") "foo"])) (is (= (update-in (database/k->re-s "foo*") [0] str) [(str #"foo.*") "foo"]))) (deftest test-match (database/put! @db "fooqux" "a") (database/put! @db "foobar" "b") (database/put! @db "foobaz" "c") (database/put! @db "nada" "d") (is (= (database/match @db "missing%") ())) (is (= (database/match @db "foob%") '("foobar" "foobaz"))) (is (= (database/match @db "fo%") '("foobar" "fooqux" "foobaz"))) (is (= (database/match @db "nada%") '("nada")))) (deftest test-put-with-merge! (database/put! @db "foo" #{1 2 3}) (database/put-with-merge! @db "foo" #{1 5 3} union) (= (database/get @db "foo") #{1 2 3 5})) (deftest test-max-vector (database/put! @db "vector" {0 1 13 42}) (is (= (database/max-vector @db "missing" {}) nil)) (is (= (database/max-vector @db "vector" {}) {0 1 13 42})) (is (= (database/max-vector @db "vector" {0 0 13 42}) {0 1})) (is (= (database/max-vector @db "vector" {0 1 13 42}) {}))) (deftest test-update-vector! (is (= (database/update-vector! @db "vector" {0 1 13 42}) {0 1 13 42})) (is (= (database/get @db "vector") {0 1 13 42})) (is (database/update-vector! @db "vector" {0 0 13 42}) {0 1}) (is (= (database/get @db "vector") {0 1 13 42})) (is (= (database/update-vector! @db "vector" {0 2}) {0 2})) (is (= (database/get @db "vector") {0 2 13 42})) (is (= (database/update-vector! @db "vector" {}) {})) (is (= (database/get @db "vector") {0 2 13 42})) (is (= (database/update-vector! @db "vector" {3 7}) {3 7})) (is (= (database/get @db "vector") {0 2 3 7 13 42})))
0f9698506a819ef5b3e5e566261e30cf6e6929956e6c0a9b010f845f674872c9
haskell/cabal
Upload.hs
module Distribution.Client.Upload (upload, uploadDoc, report) where import Distribution.Client.Compat.Prelude import qualified Prelude as Unsafe (tail, head, read) import Distribution.Client.Types.Credentials ( Username(..), Password(..) ) import Distribution.Client.Types.Repo (Repo, RemoteRepo(..), maybeRepoRemote) import Distribution.Client.Types.RepoName (unRepoName) import Distribution.Client.HttpUtils ( HttpTransport(..), remoteRepoTryUpgradeToHttps ) import Distribution.Client.Setup ( IsCandidate(..), RepoContext(..) ) import Distribution.Simple.Utils (notice, warn, info, die', toUTF8BS) import Distribution.Utils.String (trim) import Distribution.Client.Config import qualified Distribution.Client.BuildReports.Anonymous as BuildReport import Distribution.Client.BuildReports.Anonymous (parseBuildReport) import qualified Distribution.Client.BuildReports.Upload as BuildReport import Network.URI (URI(uriPath, uriAuthority), URIAuth(uriRegName)) import Network.HTTP (Header(..), HeaderName(..)) import System.IO (hFlush, stdout) import System.IO.Echo (withoutInputEcho) import System.FilePath ((</>), takeExtension, takeFileName, dropExtension) import qualified System.FilePath.Posix as FilePath.Posix ((</>)) import System.Directory type Auth = Maybe (String, String) -- > stripExtensions ["tar", "gz"] "foo.tar.gz" -- Just "foo" -- > stripExtensions ["tar", "gz"] "foo.gz.tar" -- Nothing stripExtensions :: [String] -> FilePath -> Maybe String stripExtensions exts path = foldM f path (reverse exts) where f p e | takeExtension p == '.':e = Just (dropExtension p) | otherwise = Nothing upload :: Verbosity -> RepoContext -> Maybe Username -> Maybe Password -> IsCandidate -> [FilePath] -> IO () upload verbosity repoCtxt mUsername mPassword isCandidate paths = do let repos :: [Repo] repos = repoContextRepos repoCtxt transport <- repoContextGetTransport repoCtxt targetRepo <- case [ remoteRepo | Just remoteRepo <- map maybeRepoRemote repos ] of [] -> die' verbosity "Cannot upload. No remote repositories are configured." (r:rs) -> remoteRepoTryUpgradeToHttps verbosity transport (last (r:|rs)) let targetRepoURI :: URI targetRepoURI = remoteRepoURI targetRepo domain :: String domain = maybe "Hackage" uriRegName $ uriAuthority targetRepoURI rootIfEmpty x = if null x then "/" else x uploadURI :: URI uploadURI = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> case isCandidate of IsCandidate -> "packages/candidates" IsPublished -> "upload" } packageURI pkgid = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> concat [ "package/", pkgid , case isCandidate of IsCandidate -> "/candidate" IsPublished -> "" ] } Username username <- maybe (promptUsername domain) return mUsername Password password <- maybe (promptPassword domain) return mPassword let auth = Just (username,password) for_ paths $ \path -> do notice verbosity $ "Uploading " ++ path ++ "... " case fmap takeFileName (stripExtensions ["tar", "gz"] path) of Just pkgid -> handlePackage transport verbosity uploadURI (packageURI pkgid) auth isCandidate path This case should n't really happen , since we check in Main that we -- only pass tar.gz files to upload. Nothing -> die' verbosity $ "Not a tar.gz file: " ++ path uploadDoc :: Verbosity -> RepoContext -> Maybe Username -> Maybe Password -> IsCandidate -> FilePath -> IO () uploadDoc verbosity repoCtxt mUsername mPassword isCandidate path = do let repos = repoContextRepos repoCtxt transport <- repoContextGetTransport repoCtxt targetRepo <- case [ remoteRepo | Just remoteRepo <- map maybeRepoRemote repos ] of [] -> die' verbosity $ "Cannot upload. No remote repositories are configured." (r:rs) -> remoteRepoTryUpgradeToHttps verbosity transport (last (r:|rs)) let targetRepoURI = remoteRepoURI targetRepo domain = maybe "Hackage" uriRegName $ uriAuthority targetRepoURI rootIfEmpty x = if null x then "/" else x uploadURI = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> concat [ "package/", pkgid , case isCandidate of IsCandidate -> "/candidate" IsPublished -> "" , "/docs" ] } packageUri = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> concat [ "package/", pkgid , case isCandidate of IsCandidate -> "/candidate" IsPublished -> "" ] } (reverseSuffix, reversePkgid) = break (== '-') (reverse (takeFileName path)) pkgid = reverse $ Unsafe.tail reversePkgid when (reverse reverseSuffix /= "docs.tar.gz" || null reversePkgid || Unsafe.head reversePkgid /= '-') $ die' verbosity "Expected a file name matching the pattern <pkgid>-docs.tar.gz" Username username <- maybe (promptUsername domain) return mUsername Password password <- maybe (promptPassword domain) return mPassword let auth = Just (username,password) headers = [ Header HdrContentType "application/x-tar" , Header HdrContentEncoding "gzip" ] notice verbosity $ "Uploading documentation " ++ path ++ "... " resp <- putHttpFile transport verbosity uploadURI path auth headers case resp of Hackage responds with 204 No Content when docs are uploaded -- successfully. (code,_) | code `elem` [200,204] -> do notice verbosity $ okMessage packageUri (code,err) -> do notice verbosity $ "Error uploading documentation " ++ path ++ ": " ++ "http code " ++ show code ++ "\n" ++ err exitFailure where okMessage packageUri = case isCandidate of IsCandidate -> "Documentation successfully uploaded for package candidate. " ++ "You can now preview the result at '" ++ show packageUri ++ "'. To upload non-candidate documentation, use 'cabal upload --publish'." IsPublished -> "Package documentation successfully published. You can now view it at '" ++ show packageUri ++ "'." promptUsername :: String -> IO Username promptUsername domain = do putStr $ domain ++ " username: " hFlush stdout fmap Username getLine promptPassword :: String -> IO Password promptPassword domain = do putStr $ domain ++ " password: " hFlush stdout -- save/restore the terminal echoing status (no echoing for entering the password) passwd <- withoutInputEcho $ fmap Password getLine putStrLn "" return passwd report :: Verbosity -> RepoContext -> Maybe Username -> Maybe Password -> IO () report verbosity repoCtxt mUsername mPassword = do let repos :: [Repo] repos = repoContextRepos repoCtxt remoteRepos :: [RemoteRepo] remoteRepos = mapMaybe maybeRepoRemote repos for_ remoteRepos $ \remoteRepo -> do let domain = maybe "Hackage" uriRegName $ uriAuthority (remoteRepoURI remoteRepo) Username username <- maybe (promptUsername domain) return mUsername Password password <- maybe (promptPassword domain) return mPassword let auth :: (String, String) auth = (username, password) reportsDir <- defaultReportsDir let srcDir :: FilePath srcDir = reportsDir </> unRepoName (remoteRepoName remoteRepo) -- We don't want to bomb out just because we haven't built any packages -- from this repo yet. srcExists <- doesDirectoryExist srcDir when srcExists $ do contents <- getDirectoryContents srcDir for_ (filter (\c -> takeExtension c ==".log") contents) $ \logFile -> do inp <- readFile (srcDir </> logFile) let (reportStr, buildLog) = Unsafe.read inp :: (String,String) -- TODO: eradicateNoParse case parseBuildReport (toUTF8BS reportStr) of FIXME Right report' -> do info verbosity $ "Uploading report for " ++ prettyShow (BuildReport.package report') BuildReport.uploadReports verbosity repoCtxt auth (remoteRepoURI remoteRepo) [(report', Just buildLog)] return () handlePackage :: HttpTransport -> Verbosity -> URI -> URI -> Auth -> IsCandidate -> FilePath -> IO () handlePackage transport verbosity uri packageUri auth isCandidate path = do resp <- postHttpFile transport verbosity uri path auth case resp of (code,warnings) | code `elem` [200, 204] -> notice verbosity $ okMessage isCandidate ++ if null warnings then "" else "\n" ++ formatWarnings (trim warnings) (code,err) -> do notice verbosity $ "Error uploading " ++ path ++ ": " ++ "http code " ++ show code ++ "\n" ++ err exitFailure where okMessage :: IsCandidate -> String okMessage IsCandidate = "Package successfully uploaded as candidate. " ++ "You can now preview the result at '" ++ show packageUri ++ "'. To publish the candidate, use 'cabal upload --publish'." okMessage IsPublished = "Package successfully published. You can now view it at '" ++ show packageUri ++ "'." formatWarnings :: String -> String formatWarnings x = "Warnings:\n" ++ (unlines . map ("- " ++) . lines) x
null
https://raw.githubusercontent.com/haskell/cabal/9f7dc559d682331515692dd7b42f9abd3a087898/cabal-install/src/Distribution/Client/Upload.hs
haskell
> stripExtensions ["tar", "gz"] "foo.tar.gz" Just "foo" > stripExtensions ["tar", "gz"] "foo.gz.tar" Nothing only pass tar.gz files to upload. successfully. save/restore the terminal echoing status (no echoing for entering the password) We don't want to bomb out just because we haven't built any packages from this repo yet. TODO: eradicateNoParse
module Distribution.Client.Upload (upload, uploadDoc, report) where import Distribution.Client.Compat.Prelude import qualified Prelude as Unsafe (tail, head, read) import Distribution.Client.Types.Credentials ( Username(..), Password(..) ) import Distribution.Client.Types.Repo (Repo, RemoteRepo(..), maybeRepoRemote) import Distribution.Client.Types.RepoName (unRepoName) import Distribution.Client.HttpUtils ( HttpTransport(..), remoteRepoTryUpgradeToHttps ) import Distribution.Client.Setup ( IsCandidate(..), RepoContext(..) ) import Distribution.Simple.Utils (notice, warn, info, die', toUTF8BS) import Distribution.Utils.String (trim) import Distribution.Client.Config import qualified Distribution.Client.BuildReports.Anonymous as BuildReport import Distribution.Client.BuildReports.Anonymous (parseBuildReport) import qualified Distribution.Client.BuildReports.Upload as BuildReport import Network.URI (URI(uriPath, uriAuthority), URIAuth(uriRegName)) import Network.HTTP (Header(..), HeaderName(..)) import System.IO (hFlush, stdout) import System.IO.Echo (withoutInputEcho) import System.FilePath ((</>), takeExtension, takeFileName, dropExtension) import qualified System.FilePath.Posix as FilePath.Posix ((</>)) import System.Directory type Auth = Maybe (String, String) stripExtensions :: [String] -> FilePath -> Maybe String stripExtensions exts path = foldM f path (reverse exts) where f p e | takeExtension p == '.':e = Just (dropExtension p) | otherwise = Nothing upload :: Verbosity -> RepoContext -> Maybe Username -> Maybe Password -> IsCandidate -> [FilePath] -> IO () upload verbosity repoCtxt mUsername mPassword isCandidate paths = do let repos :: [Repo] repos = repoContextRepos repoCtxt transport <- repoContextGetTransport repoCtxt targetRepo <- case [ remoteRepo | Just remoteRepo <- map maybeRepoRemote repos ] of [] -> die' verbosity "Cannot upload. No remote repositories are configured." (r:rs) -> remoteRepoTryUpgradeToHttps verbosity transport (last (r:|rs)) let targetRepoURI :: URI targetRepoURI = remoteRepoURI targetRepo domain :: String domain = maybe "Hackage" uriRegName $ uriAuthority targetRepoURI rootIfEmpty x = if null x then "/" else x uploadURI :: URI uploadURI = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> case isCandidate of IsCandidate -> "packages/candidates" IsPublished -> "upload" } packageURI pkgid = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> concat [ "package/", pkgid , case isCandidate of IsCandidate -> "/candidate" IsPublished -> "" ] } Username username <- maybe (promptUsername domain) return mUsername Password password <- maybe (promptPassword domain) return mPassword let auth = Just (username,password) for_ paths $ \path -> do notice verbosity $ "Uploading " ++ path ++ "... " case fmap takeFileName (stripExtensions ["tar", "gz"] path) of Just pkgid -> handlePackage transport verbosity uploadURI (packageURI pkgid) auth isCandidate path This case should n't really happen , since we check in Main that we Nothing -> die' verbosity $ "Not a tar.gz file: " ++ path uploadDoc :: Verbosity -> RepoContext -> Maybe Username -> Maybe Password -> IsCandidate -> FilePath -> IO () uploadDoc verbosity repoCtxt mUsername mPassword isCandidate path = do let repos = repoContextRepos repoCtxt transport <- repoContextGetTransport repoCtxt targetRepo <- case [ remoteRepo | Just remoteRepo <- map maybeRepoRemote repos ] of [] -> die' verbosity $ "Cannot upload. No remote repositories are configured." (r:rs) -> remoteRepoTryUpgradeToHttps verbosity transport (last (r:|rs)) let targetRepoURI = remoteRepoURI targetRepo domain = maybe "Hackage" uriRegName $ uriAuthority targetRepoURI rootIfEmpty x = if null x then "/" else x uploadURI = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> concat [ "package/", pkgid , case isCandidate of IsCandidate -> "/candidate" IsPublished -> "" , "/docs" ] } packageUri = targetRepoURI { uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> concat [ "package/", pkgid , case isCandidate of IsCandidate -> "/candidate" IsPublished -> "" ] } (reverseSuffix, reversePkgid) = break (== '-') (reverse (takeFileName path)) pkgid = reverse $ Unsafe.tail reversePkgid when (reverse reverseSuffix /= "docs.tar.gz" || null reversePkgid || Unsafe.head reversePkgid /= '-') $ die' verbosity "Expected a file name matching the pattern <pkgid>-docs.tar.gz" Username username <- maybe (promptUsername domain) return mUsername Password password <- maybe (promptPassword domain) return mPassword let auth = Just (username,password) headers = [ Header HdrContentType "application/x-tar" , Header HdrContentEncoding "gzip" ] notice verbosity $ "Uploading documentation " ++ path ++ "... " resp <- putHttpFile transport verbosity uploadURI path auth headers case resp of Hackage responds with 204 No Content when docs are uploaded (code,_) | code `elem` [200,204] -> do notice verbosity $ okMessage packageUri (code,err) -> do notice verbosity $ "Error uploading documentation " ++ path ++ ": " ++ "http code " ++ show code ++ "\n" ++ err exitFailure where okMessage packageUri = case isCandidate of IsCandidate -> "Documentation successfully uploaded for package candidate. " ++ "You can now preview the result at '" ++ show packageUri ++ "'. To upload non-candidate documentation, use 'cabal upload --publish'." IsPublished -> "Package documentation successfully published. You can now view it at '" ++ show packageUri ++ "'." promptUsername :: String -> IO Username promptUsername domain = do putStr $ domain ++ " username: " hFlush stdout fmap Username getLine promptPassword :: String -> IO Password promptPassword domain = do putStr $ domain ++ " password: " hFlush stdout passwd <- withoutInputEcho $ fmap Password getLine putStrLn "" return passwd report :: Verbosity -> RepoContext -> Maybe Username -> Maybe Password -> IO () report verbosity repoCtxt mUsername mPassword = do let repos :: [Repo] repos = repoContextRepos repoCtxt remoteRepos :: [RemoteRepo] remoteRepos = mapMaybe maybeRepoRemote repos for_ remoteRepos $ \remoteRepo -> do let domain = maybe "Hackage" uriRegName $ uriAuthority (remoteRepoURI remoteRepo) Username username <- maybe (promptUsername domain) return mUsername Password password <- maybe (promptPassword domain) return mPassword let auth :: (String, String) auth = (username, password) reportsDir <- defaultReportsDir let srcDir :: FilePath srcDir = reportsDir </> unRepoName (remoteRepoName remoteRepo) srcExists <- doesDirectoryExist srcDir when srcExists $ do contents <- getDirectoryContents srcDir for_ (filter (\c -> takeExtension c ==".log") contents) $ \logFile -> do inp <- readFile (srcDir </> logFile) case parseBuildReport (toUTF8BS reportStr) of FIXME Right report' -> do info verbosity $ "Uploading report for " ++ prettyShow (BuildReport.package report') BuildReport.uploadReports verbosity repoCtxt auth (remoteRepoURI remoteRepo) [(report', Just buildLog)] return () handlePackage :: HttpTransport -> Verbosity -> URI -> URI -> Auth -> IsCandidate -> FilePath -> IO () handlePackage transport verbosity uri packageUri auth isCandidate path = do resp <- postHttpFile transport verbosity uri path auth case resp of (code,warnings) | code `elem` [200, 204] -> notice verbosity $ okMessage isCandidate ++ if null warnings then "" else "\n" ++ formatWarnings (trim warnings) (code,err) -> do notice verbosity $ "Error uploading " ++ path ++ ": " ++ "http code " ++ show code ++ "\n" ++ err exitFailure where okMessage :: IsCandidate -> String okMessage IsCandidate = "Package successfully uploaded as candidate. " ++ "You can now preview the result at '" ++ show packageUri ++ "'. To publish the candidate, use 'cabal upload --publish'." okMessage IsPublished = "Package successfully published. You can now view it at '" ++ show packageUri ++ "'." formatWarnings :: String -> String formatWarnings x = "Warnings:\n" ++ (unlines . map ("- " ++) . lines) x
eeb2ee465846b3120a7d9d9c425aa61a9cabfdcdab03a2e38591329e4a654b5c
zachsully/dl
Syntax.hs
module DL.LLVM.Syntax where data LLVM :: * where
null
https://raw.githubusercontent.com/zachsully/dl/c99cdfa8a3b59b1977a34876f397c467518091b6/haskell/DL/LLVM/Syntax.hs
haskell
module DL.LLVM.Syntax where data LLVM :: * where
d89606bc15fb205d759549c5ad30738d0e9811b0c256fc36f7bc8f4f32dd20d8
naxels/youtube-channel-data
core.clj
(ns youtube-channel-data.core (:gen-class) (:require [clojure.string :as str] [clojure.tools.cli :refer [parse-opts]] [youtube-channel-data.output :as output] [youtube-channel-data.utils :as u] [youtube-channel-data.youtube.request :as yt-request])) (set! *warn-on-reflection* true) (def ^:dynamic *slurp* slurp) (defn video-id->channel-id "Takes youtube video id string and returns the channelId from youtube" [video-id] (->> (yt-request/video video-id *slurp*) (first) (:snippet) (:channelId))) (defn channel-id->playlist-id+title "Takes channel id string and returns vec with [playlist-id, title]" [channel-id] (let [channel-item (->> (yt-request/channel channel-id *slurp*) (first))] [(get-in channel-item [:contentDetails :relatedPlaylists :uploads]) (get-in channel-item [:brandingSettings :channel :title])])) (defn transform-playlist-items "Transform playlist-items & videos to output map" [playlist-items videos] (map output/output-map playlist-items videos)) (defn add-video-title-filter [{{filter-option :filter} :options :as data}] (assoc data :video-title-filter (and filter-option (str/lower-case filter-option)))) (defn add-video-id [{:keys [id-or-url] :as data}] (assoc data :video-id (u/parse-input id-or-url))) (defn add-channel-id [{:keys [video-id] :as data}] (assoc data :channel-id (video-id->channel-id video-id))) (defn add-playlist-id+channel-title [{:keys [channel-id] :as data}] (let [[playlist-id channel-title] (channel-id->playlist-id+title channel-id)] (assoc data :playlist-id playlist-id :channel-title channel-title))) (defn add-output-data [{:keys [video-title-filter channel-title] :as data}] (let [output-map {:location (output/location) :filename (output/filename video-title-filter channel-title) :separator \. :extension (output/extension (get-in data [:options :output]))} output (assoc output-map :file (apply str (vals output-map)))] (assoc data :output output))) (defn add-playlist-items [{:keys [video-title-filter playlist-id] :as data}] (assoc data :playlist-items (cond->> (yt-request/playlist-items playlist-id *slurp*) ;enable mocking with dynamically bound *slurp* video-title-filter (filter (partial u/title-match? video-title-filter))))) (defn add-videos-data [{:keys [playlist-items] :as data}] (assoc data :videos (yt-request/playlist-items->videos playlist-items *slurp*))) (defn add-transformed-playlist-items [{:keys [playlist-items videos] :as data}] (assoc data :playlist-items-transformed (transform-playlist-items playlist-items videos))) (defn output-to-file [{:keys [output playlist-items-transformed] :as data}] (let [{:keys [file extension]} output] (output/writer file extension playlist-items-transformed)) data) (defn notify "2 arity: print and return data 3 arity: print after applying f to data" ([data msg] (println msg) data) ([data msg f] (notify data (str msg " " (f data))))) (defn notify-if [data msg f conditionalf] (if (conditionalf data) (notify data msg f) data)) (defn pull-yt-channel-data [data] (-> data (add-video-title-filter) (add-video-id) (notify "Video id found:" :video-id) (notify-if "Filtering titles on:" :video-title-filter :video-title-filter) (add-channel-id) (notify "Channel Id:" :channel-id) (add-playlist-id+channel-title) (notify "Playlist Id:" :playlist-id) (notify "Channel title:" :channel-title) (add-output-data) (notify "Getting all playlist items.....") (add-playlist-items) (notify "Playlist items found:" #(count (:playlist-items %))) (notify "Getting all videos for duration data.....") (add-videos-data) (add-transformed-playlist-items) (notify-if "Playlist items left after filtering:" #(count (:playlist-items-transformed %)) :video-title-filter) (output-to-file) (notify "Data saved to:" #(get-in % [:output :file])))) ; CLI (defn usage [options-summary] (->> ["Youtube channel data" "" "Usage: youtube-channel-data [options] video-id/url" "" "Options:" options-summary "" "Video id/url:" "Can be just the video id, full Youtube url or short Youtu.be url"] (str/join \newline))) (def cli-options [["-f" "--filter SEARCHQUERY" "Search query to filter the channel video's on"] ["-o" "--output FORMAT" (format "Output formats supported: %s" (str/join ", " output/supported-formats)) :default "csv"]]) (defn -main "Start the app. Key examples: options: {:output csv}, {:output csv, :filter \"twosday\"} arguments: [\"1DQ0j_9Pq-g\"] summary: \"The system cannot find the path specified...\"" [& args] (let [{:keys [options arguments _errors summary]} (parse-opts args cli-options)] (if (empty? arguments) (println (usage summary)) (do (pull-yt-channel-data {:id-or-url (first arguments) :options options}) close futures thread pool used by pmap (println "All done, exiting")))))
null
https://raw.githubusercontent.com/naxels/youtube-channel-data/05447d2ecdaef714c51548d33cbe9dcc1a2728ef/src/youtube_channel_data/core.clj
clojure
enable mocking with dynamically bound *slurp* CLI
(ns youtube-channel-data.core (:gen-class) (:require [clojure.string :as str] [clojure.tools.cli :refer [parse-opts]] [youtube-channel-data.output :as output] [youtube-channel-data.utils :as u] [youtube-channel-data.youtube.request :as yt-request])) (set! *warn-on-reflection* true) (def ^:dynamic *slurp* slurp) (defn video-id->channel-id "Takes youtube video id string and returns the channelId from youtube" [video-id] (->> (yt-request/video video-id *slurp*) (first) (:snippet) (:channelId))) (defn channel-id->playlist-id+title "Takes channel id string and returns vec with [playlist-id, title]" [channel-id] (let [channel-item (->> (yt-request/channel channel-id *slurp*) (first))] [(get-in channel-item [:contentDetails :relatedPlaylists :uploads]) (get-in channel-item [:brandingSettings :channel :title])])) (defn transform-playlist-items "Transform playlist-items & videos to output map" [playlist-items videos] (map output/output-map playlist-items videos)) (defn add-video-title-filter [{{filter-option :filter} :options :as data}] (assoc data :video-title-filter (and filter-option (str/lower-case filter-option)))) (defn add-video-id [{:keys [id-or-url] :as data}] (assoc data :video-id (u/parse-input id-or-url))) (defn add-channel-id [{:keys [video-id] :as data}] (assoc data :channel-id (video-id->channel-id video-id))) (defn add-playlist-id+channel-title [{:keys [channel-id] :as data}] (let [[playlist-id channel-title] (channel-id->playlist-id+title channel-id)] (assoc data :playlist-id playlist-id :channel-title channel-title))) (defn add-output-data [{:keys [video-title-filter channel-title] :as data}] (let [output-map {:location (output/location) :filename (output/filename video-title-filter channel-title) :separator \. :extension (output/extension (get-in data [:options :output]))} output (assoc output-map :file (apply str (vals output-map)))] (assoc data :output output))) (defn add-playlist-items [{:keys [video-title-filter playlist-id] :as data}] video-title-filter (filter (partial u/title-match? video-title-filter))))) (defn add-videos-data [{:keys [playlist-items] :as data}] (assoc data :videos (yt-request/playlist-items->videos playlist-items *slurp*))) (defn add-transformed-playlist-items [{:keys [playlist-items videos] :as data}] (assoc data :playlist-items-transformed (transform-playlist-items playlist-items videos))) (defn output-to-file [{:keys [output playlist-items-transformed] :as data}] (let [{:keys [file extension]} output] (output/writer file extension playlist-items-transformed)) data) (defn notify "2 arity: print and return data 3 arity: print after applying f to data" ([data msg] (println msg) data) ([data msg f] (notify data (str msg " " (f data))))) (defn notify-if [data msg f conditionalf] (if (conditionalf data) (notify data msg f) data)) (defn pull-yt-channel-data [data] (-> data (add-video-title-filter) (add-video-id) (notify "Video id found:" :video-id) (notify-if "Filtering titles on:" :video-title-filter :video-title-filter) (add-channel-id) (notify "Channel Id:" :channel-id) (add-playlist-id+channel-title) (notify "Playlist Id:" :playlist-id) (notify "Channel title:" :channel-title) (add-output-data) (notify "Getting all playlist items.....") (add-playlist-items) (notify "Playlist items found:" #(count (:playlist-items %))) (notify "Getting all videos for duration data.....") (add-videos-data) (add-transformed-playlist-items) (notify-if "Playlist items left after filtering:" #(count (:playlist-items-transformed %)) :video-title-filter) (output-to-file) (notify "Data saved to:" #(get-in % [:output :file])))) (defn usage [options-summary] (->> ["Youtube channel data" "" "Usage: youtube-channel-data [options] video-id/url" "" "Options:" options-summary "" "Video id/url:" "Can be just the video id, full Youtube url or short Youtu.be url"] (str/join \newline))) (def cli-options [["-f" "--filter SEARCHQUERY" "Search query to filter the channel video's on"] ["-o" "--output FORMAT" (format "Output formats supported: %s" (str/join ", " output/supported-formats)) :default "csv"]]) (defn -main "Start the app. Key examples: options: {:output csv}, {:output csv, :filter \"twosday\"} arguments: [\"1DQ0j_9Pq-g\"] summary: \"The system cannot find the path specified...\"" [& args] (let [{:keys [options arguments _errors summary]} (parse-opts args cli-options)] (if (empty? arguments) (println (usage summary)) (do (pull-yt-channel-data {:id-or-url (first arguments) :options options}) close futures thread pool used by pmap (println "All done, exiting")))))
8ffc7dd9113b39ab0c4421753b467d801dbd775181d7a13c403926e79bb97784
well-typed/large-records
R080.hs
#if PROFILE_CORESIZE {-# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #-} #endif #if PROFILE_TIMING {-# OPTIONS_GHC -ddump-to-file -ddump-timings #-} #endif # OPTIONS_GHC -fplugin = TypeLet # module Experiment.HListLetAsCPS.Sized.R080 where import TypeLet import Bench.HList import Bench.Types import Common.HListOfSize.HL080 hlist :: HList Fields hlist = constructLet $ \_ -> 79 .. 70 letAs' (MkT 79 :* Nil) $ \xs79 -> letAs' (MkT 78 :* xs79) $ \xs78 -> letAs' (MkT 77 :* xs78) $ \xs77 -> letAs' (MkT 76 :* xs77) $ \xs76 -> letAs' (MkT 75 :* xs76) $ \xs75 -> letAs' (MkT 74 :* xs75) $ \xs74 -> letAs' (MkT 73 :* xs74) $ \xs73 -> letAs' (MkT 72 :* xs73) $ \xs72 -> letAs' (MkT 71 :* xs72) $ \xs71 -> letAs' (MkT 70 :* xs71) $ \xs70 -> 69 .. 60 letAs' (MkT 69 :* xs70) $ \xs69 -> letAs' (MkT 68 :* xs69) $ \xs68 -> letAs' (MkT 67 :* xs68) $ \xs67 -> letAs' (MkT 66 :* xs67) $ \xs66 -> letAs' (MkT 65 :* xs66) $ \xs65 -> letAs' (MkT 64 :* xs65) $ \xs64 -> letAs' (MkT 63 :* xs64) $ \xs63 -> letAs' (MkT 62 :* xs63) $ \xs62 -> letAs' (MkT 61 :* xs62) $ \xs61 -> letAs' (MkT 60 :* xs61) $ \xs60 -> 59 .. 50 letAs' (MkT 59 :* xs60) $ \xs59 -> letAs' (MkT 58 :* xs59) $ \xs58 -> letAs' (MkT 57 :* xs58) $ \xs57 -> letAs' (MkT 56 :* xs57) $ \xs56 -> letAs' (MkT 55 :* xs56) $ \xs55 -> letAs' (MkT 54 :* xs55) $ \xs54 -> letAs' (MkT 53 :* xs54) $ \xs53 -> letAs' (MkT 52 :* xs53) $ \xs52 -> letAs' (MkT 51 :* xs52) $ \xs51 -> letAs' (MkT 50 :* xs51) $ \xs50 -> 49 .. 40 letAs' (MkT 49 :* xs50) $ \xs49 -> letAs' (MkT 48 :* xs49) $ \xs48 -> letAs' (MkT 47 :* xs48) $ \xs47 -> letAs' (MkT 46 :* xs47) $ \xs46 -> letAs' (MkT 45 :* xs46) $ \xs45 -> letAs' (MkT 44 :* xs45) $ \xs44 -> letAs' (MkT 43 :* xs44) $ \xs43 -> letAs' (MkT 42 :* xs43) $ \xs42 -> letAs' (MkT 41 :* xs42) $ \xs41 -> letAs' (MkT 40 :* xs41) $ \xs40 -> 39 .. 30 letAs' (MkT 39 :* xs40) $ \xs39 -> letAs' (MkT 38 :* xs39) $ \xs38 -> letAs' (MkT 37 :* xs38) $ \xs37 -> letAs' (MkT 36 :* xs37) $ \xs36 -> letAs' (MkT 35 :* xs36) $ \xs35 -> letAs' (MkT 34 :* xs35) $ \xs34 -> letAs' (MkT 33 :* xs34) $ \xs33 -> letAs' (MkT 32 :* xs33) $ \xs32 -> letAs' (MkT 31 :* xs32) $ \xs31 -> letAs' (MkT 30 :* xs31) $ \xs30 -> 29 .. 20 letAs' (MkT 29 :* xs30) $ \xs29 -> letAs' (MkT 28 :* xs29) $ \xs28 -> letAs' (MkT 27 :* xs28) $ \xs27 -> letAs' (MkT 26 :* xs27) $ \xs26 -> letAs' (MkT 25 :* xs26) $ \xs25 -> letAs' (MkT 24 :* xs25) $ \xs24 -> letAs' (MkT 23 :* xs24) $ \xs23 -> letAs' (MkT 22 :* xs23) $ \xs22 -> letAs' (MkT 21 :* xs22) $ \xs21 -> letAs' (MkT 20 :* xs21) $ \xs20 -> 19 .. 10 letAs' (MkT 19 :* xs20) $ \xs19 -> letAs' (MkT 18 :* xs19) $ \xs18 -> letAs' (MkT 17 :* xs18) $ \xs17 -> letAs' (MkT 16 :* xs17) $ \xs16 -> letAs' (MkT 15 :* xs16) $ \xs15 -> letAs' (MkT 14 :* xs15) $ \xs14 -> letAs' (MkT 13 :* xs14) $ \xs13 -> letAs' (MkT 12 :* xs13) $ \xs12 -> letAs' (MkT 11 :* xs12) $ \xs11 -> letAs' (MkT 10 :* xs11) $ \xs10 -> 09 .. 00 letAs' (MkT 09 :* xs10) $ \xs09 -> letAs' (MkT 08 :* xs09) $ \xs08 -> letAs' (MkT 07 :* xs08) $ \xs07 -> letAs' (MkT 06 :* xs07) $ \xs06 -> letAs' (MkT 05 :* xs06) $ \xs05 -> letAs' (MkT 04 :* xs05) $ \xs04 -> letAs' (MkT 03 :* xs04) $ \xs03 -> letAs' (MkT 02 :* xs03) $ \xs02 -> letAs' (MkT 01 :* xs02) $ \xs01 -> letAs' (MkT 00 :* xs01) $ \xs00 -> castEqual xs00
null
https://raw.githubusercontent.com/well-typed/large-records/f75ba52570d07e1171e2c87ad7e4c1f466d9367f/large-records-benchmarks/bench/typelet/Experiment/HListLetAsCPS/Sized/R080.hs
haskell
# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl # # OPTIONS_GHC -ddump-to-file -ddump-timings #
#if PROFILE_CORESIZE #endif #if PROFILE_TIMING #endif # OPTIONS_GHC -fplugin = TypeLet # module Experiment.HListLetAsCPS.Sized.R080 where import TypeLet import Bench.HList import Bench.Types import Common.HListOfSize.HL080 hlist :: HList Fields hlist = constructLet $ \_ -> 79 .. 70 letAs' (MkT 79 :* Nil) $ \xs79 -> letAs' (MkT 78 :* xs79) $ \xs78 -> letAs' (MkT 77 :* xs78) $ \xs77 -> letAs' (MkT 76 :* xs77) $ \xs76 -> letAs' (MkT 75 :* xs76) $ \xs75 -> letAs' (MkT 74 :* xs75) $ \xs74 -> letAs' (MkT 73 :* xs74) $ \xs73 -> letAs' (MkT 72 :* xs73) $ \xs72 -> letAs' (MkT 71 :* xs72) $ \xs71 -> letAs' (MkT 70 :* xs71) $ \xs70 -> 69 .. 60 letAs' (MkT 69 :* xs70) $ \xs69 -> letAs' (MkT 68 :* xs69) $ \xs68 -> letAs' (MkT 67 :* xs68) $ \xs67 -> letAs' (MkT 66 :* xs67) $ \xs66 -> letAs' (MkT 65 :* xs66) $ \xs65 -> letAs' (MkT 64 :* xs65) $ \xs64 -> letAs' (MkT 63 :* xs64) $ \xs63 -> letAs' (MkT 62 :* xs63) $ \xs62 -> letAs' (MkT 61 :* xs62) $ \xs61 -> letAs' (MkT 60 :* xs61) $ \xs60 -> 59 .. 50 letAs' (MkT 59 :* xs60) $ \xs59 -> letAs' (MkT 58 :* xs59) $ \xs58 -> letAs' (MkT 57 :* xs58) $ \xs57 -> letAs' (MkT 56 :* xs57) $ \xs56 -> letAs' (MkT 55 :* xs56) $ \xs55 -> letAs' (MkT 54 :* xs55) $ \xs54 -> letAs' (MkT 53 :* xs54) $ \xs53 -> letAs' (MkT 52 :* xs53) $ \xs52 -> letAs' (MkT 51 :* xs52) $ \xs51 -> letAs' (MkT 50 :* xs51) $ \xs50 -> 49 .. 40 letAs' (MkT 49 :* xs50) $ \xs49 -> letAs' (MkT 48 :* xs49) $ \xs48 -> letAs' (MkT 47 :* xs48) $ \xs47 -> letAs' (MkT 46 :* xs47) $ \xs46 -> letAs' (MkT 45 :* xs46) $ \xs45 -> letAs' (MkT 44 :* xs45) $ \xs44 -> letAs' (MkT 43 :* xs44) $ \xs43 -> letAs' (MkT 42 :* xs43) $ \xs42 -> letAs' (MkT 41 :* xs42) $ \xs41 -> letAs' (MkT 40 :* xs41) $ \xs40 -> 39 .. 30 letAs' (MkT 39 :* xs40) $ \xs39 -> letAs' (MkT 38 :* xs39) $ \xs38 -> letAs' (MkT 37 :* xs38) $ \xs37 -> letAs' (MkT 36 :* xs37) $ \xs36 -> letAs' (MkT 35 :* xs36) $ \xs35 -> letAs' (MkT 34 :* xs35) $ \xs34 -> letAs' (MkT 33 :* xs34) $ \xs33 -> letAs' (MkT 32 :* xs33) $ \xs32 -> letAs' (MkT 31 :* xs32) $ \xs31 -> letAs' (MkT 30 :* xs31) $ \xs30 -> 29 .. 20 letAs' (MkT 29 :* xs30) $ \xs29 -> letAs' (MkT 28 :* xs29) $ \xs28 -> letAs' (MkT 27 :* xs28) $ \xs27 -> letAs' (MkT 26 :* xs27) $ \xs26 -> letAs' (MkT 25 :* xs26) $ \xs25 -> letAs' (MkT 24 :* xs25) $ \xs24 -> letAs' (MkT 23 :* xs24) $ \xs23 -> letAs' (MkT 22 :* xs23) $ \xs22 -> letAs' (MkT 21 :* xs22) $ \xs21 -> letAs' (MkT 20 :* xs21) $ \xs20 -> 19 .. 10 letAs' (MkT 19 :* xs20) $ \xs19 -> letAs' (MkT 18 :* xs19) $ \xs18 -> letAs' (MkT 17 :* xs18) $ \xs17 -> letAs' (MkT 16 :* xs17) $ \xs16 -> letAs' (MkT 15 :* xs16) $ \xs15 -> letAs' (MkT 14 :* xs15) $ \xs14 -> letAs' (MkT 13 :* xs14) $ \xs13 -> letAs' (MkT 12 :* xs13) $ \xs12 -> letAs' (MkT 11 :* xs12) $ \xs11 -> letAs' (MkT 10 :* xs11) $ \xs10 -> 09 .. 00 letAs' (MkT 09 :* xs10) $ \xs09 -> letAs' (MkT 08 :* xs09) $ \xs08 -> letAs' (MkT 07 :* xs08) $ \xs07 -> letAs' (MkT 06 :* xs07) $ \xs06 -> letAs' (MkT 05 :* xs06) $ \xs05 -> letAs' (MkT 04 :* xs05) $ \xs04 -> letAs' (MkT 03 :* xs04) $ \xs03 -> letAs' (MkT 02 :* xs03) $ \xs02 -> letAs' (MkT 01 :* xs02) $ \xs01 -> letAs' (MkT 00 :* xs01) $ \xs00 -> castEqual xs00
6089ae70910aa2365b10207657d71ba9a7fbf1b5ab4da16b4a60533d78862b67
AndrasKovacs/ELTE-func-lang
Practice09.hs
# LANGUAGE InstanceSigs # module Practice09 where import Control.Applicative newtype Parser a = P { runParser :: String -> Maybe (a, String) } instance Functor Parser where fmap :: (a -> b) -> Parser a -> Parser b fmap f (P g) = P $ \str -> case g str of Just (x, str') -> Just (f x, str') Nothing -> Nothing instance Applicative Parser where pure :: a -> Parser a pure x = P $ \str -> Just (x, str) (<*>) :: Parser (a -> b) -> Parser a -> Parser b (<*>) (P pF) (P g) = P $ \str -> do (f, str') <- pF str (x, str'') <- g str' pure (f x, str'') eof :: Parser () eof = P $ \str -> case str of "" -> Just ((), str) _ -> Nothing char :: Char -> Parser Char char c = P $ \str -> case str of (x:xs) | x == c -> Just (c, xs) _ -> Nothing instance Alternative Parser where empty :: Parser a empty = P (\_ -> Nothing) (<|>) :: Parser a -> Parser a -> Parser a (<|>) p q = P $ \str -> case runParser p str of Just res -> Just res Nothing -> runParser q str charXY :: Parser Char charXY = char 'x' <|> char 'y' anyChar :: Parser Char anyChar = foldr (<|>) empty $ map char ['a'..'z'] -- char 'a' <|> char 'b' <|> char 'c' <|> ... <|> char 'z' -- parses a given string string :: String -> Parser [Char] string = traverse char some' :: Alternative f => f a -> f [a] some' f = (:) <$> f <*> many' f many' :: Alternative f => f a -> f [a] many' f = some' f <|> pure [] data Bit = F | T deriving (Eq, Ord, Show) data ShortByte = SB Bit Bit Bit Bit deriving (Eq, Ord, Show) bitF :: Parser Bit bitF = char '0' *> pure F bitT :: Parser Bit bitT = char '1' *> pure T bit :: Parser Bit bit = bitF <|> bitT shortByte :: Parser ShortByte shortByte = SB <$> bit <*> bit <*> bit <*> bit instance Monad Parser where return :: a -> Parser a return = pure (>>=) :: Parser a -> (a -> Parser b) -> Parser b (>>=) p k = P $ \str -> case runParser p str of Nothing -> Nothing Just (x, str') -> runParser (k x) str' times :: Int -> Parser a -> Parser [a] -- times 0 p = pure [] -- times n p = (:) <$> p <*> times (n-1) p times n p = traverse (\_ -> p) [1..n] digit :: Parser Int digit = fmap (\n -> n - 48) . fmap fromEnum . foldr (<|>) empty $ map char ['0'..'9'] natural :: Parser Int natural = foldl (\acc cur -> acc*10 + cur) 0 <$> some digit foo :: Parser a -> Parser [a] foo p = do n <- natural times n p
null
https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/88d41930999d6056bdd7bfaa85761a527cce4113/2019-20-1/szerda_gyak/Practice09.hs
haskell
char 'a' <|> char 'b' <|> char 'c' <|> ... <|> char 'z' parses a given string times 0 p = pure [] times n p = (:) <$> p <*> times (n-1) p
# LANGUAGE InstanceSigs # module Practice09 where import Control.Applicative newtype Parser a = P { runParser :: String -> Maybe (a, String) } instance Functor Parser where fmap :: (a -> b) -> Parser a -> Parser b fmap f (P g) = P $ \str -> case g str of Just (x, str') -> Just (f x, str') Nothing -> Nothing instance Applicative Parser where pure :: a -> Parser a pure x = P $ \str -> Just (x, str) (<*>) :: Parser (a -> b) -> Parser a -> Parser b (<*>) (P pF) (P g) = P $ \str -> do (f, str') <- pF str (x, str'') <- g str' pure (f x, str'') eof :: Parser () eof = P $ \str -> case str of "" -> Just ((), str) _ -> Nothing char :: Char -> Parser Char char c = P $ \str -> case str of (x:xs) | x == c -> Just (c, xs) _ -> Nothing instance Alternative Parser where empty :: Parser a empty = P (\_ -> Nothing) (<|>) :: Parser a -> Parser a -> Parser a (<|>) p q = P $ \str -> case runParser p str of Just res -> Just res Nothing -> runParser q str charXY :: Parser Char charXY = char 'x' <|> char 'y' anyChar :: Parser Char anyChar = foldr (<|>) empty $ map char ['a'..'z'] string :: String -> Parser [Char] string = traverse char some' :: Alternative f => f a -> f [a] some' f = (:) <$> f <*> many' f many' :: Alternative f => f a -> f [a] many' f = some' f <|> pure [] data Bit = F | T deriving (Eq, Ord, Show) data ShortByte = SB Bit Bit Bit Bit deriving (Eq, Ord, Show) bitF :: Parser Bit bitF = char '0' *> pure F bitT :: Parser Bit bitT = char '1' *> pure T bit :: Parser Bit bit = bitF <|> bitT shortByte :: Parser ShortByte shortByte = SB <$> bit <*> bit <*> bit <*> bit instance Monad Parser where return :: a -> Parser a return = pure (>>=) :: Parser a -> (a -> Parser b) -> Parser b (>>=) p k = P $ \str -> case runParser p str of Nothing -> Nothing Just (x, str') -> runParser (k x) str' times :: Int -> Parser a -> Parser [a] times n p = traverse (\_ -> p) [1..n] digit :: Parser Int digit = fmap (\n -> n - 48) . fmap fromEnum . foldr (<|>) empty $ map char ['0'..'9'] natural :: Parser Int natural = foldl (\acc cur -> acc*10 + cur) 0 <$> some digit foo :: Parser a -> Parser [a] foo p = do n <- natural times n p
5c0097d5780c4969f1f1007599869a51eef1ca7f042c8f7b78e8c89d9dd46b28
nvim-treesitter/nvim-treesitter
locals.scm
[ (object) (array) ] @scope
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/ddc0f1b606472b6a1ab85ee9becfd4877507627d/queries/json/locals.scm
scheme
[ (object) (array) ] @scope
c144b76f22c5aee821d05c172e5d1661f81018227d7ad04320888e7ca407b49a
emqx/emqx
emqx_authn_enable_flag_SUITE.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_authn_enable_flag_SUITE). -compile(export_all). -compile(nowarn_export_all). -include("emqx_authn.hrl"). -define(PATH, [?CONF_NS_ATOM]). -include_lib("eunit/include/eunit.hrl"). all() -> emqx_common_test_helpers:all(?MODULE). init_per_suite(Config) -> emqx_common_test_helpers:start_apps([emqx_conf, emqx_authn]), Config. end_per_suite(_) -> emqx_common_test_helpers:stop_apps([emqx_authn, emqx_conf]), ok. init_per_testcase(_Case, Config) -> AuthnConfig = #{ <<"mechanism">> => <<"password_based">>, <<"backend">> => <<"built_in_database">>, <<"user_id_type">> => <<"clientid">> }, emqx:update_config( ?PATH, {create_authenticator, ?GLOBAL, AuthnConfig} ), emqx_conf:update( [listeners, tcp, listener_authn_enabled], {create, listener_mqtt_tcp_conf(18830, true)}, #{} ), emqx_conf:update( [listeners, tcp, listener_authn_disabled], {create, listener_mqtt_tcp_conf(18831, false)}, #{} ), Config. end_per_testcase(_Case, Config) -> emqx_authn_test_lib:delete_authenticators( ?PATH, ?GLOBAL ), emqx_conf:remove( [listeners, tcp, listener_authn_enabled], #{} ), emqx_conf:remove( [listeners, tcp, listener_authn_disabled], #{} ), Config. listener_mqtt_tcp_conf(Port, EnableAuthn) -> PortS = integer_to_binary(Port), #{ <<"acceptors">> => 16, <<"zone">> => <<"default">>, <<"access_rules">> => ["allow all"], <<"bind">> => <<"0.0.0.0:", PortS/binary>>, <<"max_connections">> => 1024000, <<"mountpoint">> => <<>>, <<"proxy_protocol">> => false, <<"proxy_protocol_timeout">> => 3000, <<"enable_authn">> => EnableAuthn }. t_enable_authn(_Config) -> %% enable_authn set to false, we connect successfully {ok, ConnPid0} = emqtt:start_link([{port, 18831}, {clientid, <<"clientid">>}]), ?assertMatch( {ok, _}, emqtt:connect(ConnPid0) ), ok = emqtt:disconnect(ConnPid0), process_flag(trap_exit, true), %% enable_authn set to true, we go to the set up authn and fail {ok, ConnPid1} = emqtt:start_link([{port, 18830}, {clientid, <<"clientid">>}]), ?assertMatch( {error, {unauthorized_client, _}}, emqtt:connect(ConnPid1) ), ok.
null
https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_authn/test/emqx_authn_enable_flag_SUITE.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------- enable_authn set to false, we connect successfully enable_authn set to true, we go to the set up authn and fail
Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_authn_enable_flag_SUITE). -compile(export_all). -compile(nowarn_export_all). -include("emqx_authn.hrl"). -define(PATH, [?CONF_NS_ATOM]). -include_lib("eunit/include/eunit.hrl"). all() -> emqx_common_test_helpers:all(?MODULE). init_per_suite(Config) -> emqx_common_test_helpers:start_apps([emqx_conf, emqx_authn]), Config. end_per_suite(_) -> emqx_common_test_helpers:stop_apps([emqx_authn, emqx_conf]), ok. init_per_testcase(_Case, Config) -> AuthnConfig = #{ <<"mechanism">> => <<"password_based">>, <<"backend">> => <<"built_in_database">>, <<"user_id_type">> => <<"clientid">> }, emqx:update_config( ?PATH, {create_authenticator, ?GLOBAL, AuthnConfig} ), emqx_conf:update( [listeners, tcp, listener_authn_enabled], {create, listener_mqtt_tcp_conf(18830, true)}, #{} ), emqx_conf:update( [listeners, tcp, listener_authn_disabled], {create, listener_mqtt_tcp_conf(18831, false)}, #{} ), Config. end_per_testcase(_Case, Config) -> emqx_authn_test_lib:delete_authenticators( ?PATH, ?GLOBAL ), emqx_conf:remove( [listeners, tcp, listener_authn_enabled], #{} ), emqx_conf:remove( [listeners, tcp, listener_authn_disabled], #{} ), Config. listener_mqtt_tcp_conf(Port, EnableAuthn) -> PortS = integer_to_binary(Port), #{ <<"acceptors">> => 16, <<"zone">> => <<"default">>, <<"access_rules">> => ["allow all"], <<"bind">> => <<"0.0.0.0:", PortS/binary>>, <<"max_connections">> => 1024000, <<"mountpoint">> => <<>>, <<"proxy_protocol">> => false, <<"proxy_protocol_timeout">> => 3000, <<"enable_authn">> => EnableAuthn }. t_enable_authn(_Config) -> {ok, ConnPid0} = emqtt:start_link([{port, 18831}, {clientid, <<"clientid">>}]), ?assertMatch( {ok, _}, emqtt:connect(ConnPid0) ), ok = emqtt:disconnect(ConnPid0), process_flag(trap_exit, true), {ok, ConnPid1} = emqtt:start_link([{port, 18830}, {clientid, <<"clientid">>}]), ?assertMatch( {error, {unauthorized_client, _}}, emqtt:connect(ConnPid1) ), ok.
afc01f2b768f82937874dd47f904f259c0c9c8e6a97229dd8af0bde355a3488a
rowangithub/DOrder
030_rlock.ml
let lock st = assert (st=0); 10 let unlock st = assert (st=10); 0 let f n st : int= if n > 0 then lock (st) else st let g n st : int = if n > 0 then unlock (st) else st let main n = assert ((g n (f n 0)) = 0)
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/mochi2/benchs/030_rlock.ml
ocaml
let lock st = assert (st=0); 10 let unlock st = assert (st=10); 0 let f n st : int= if n > 0 then lock (st) else st let g n st : int = if n > 0 then unlock (st) else st let main n = assert ((g n (f n 0)) = 0)
4ffd81b725397104c7ac49b4f549ff35a5178258461ec8aa473301e324ef1cae
facebook/flow
ty_simplifier_test.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open OUnit2 open Ty open Ty_utils module UnionSimplification = struct let tests = [ (* * {f: number} | {f: number} * ~> * {f: number} *) ( "simplify_union_obj" >:: fun ctxt -> let t_in = Ty.Union ( false, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true ~sort:false t_in in let t_exp = Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; } in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); (* * {+f: number} | {-f: number} * ~> * {+f: number} | {-f: number} *) ( "simplify_union_obj" >:: fun ctxt -> let t_in = Ty.Union ( false, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Positive; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Negative; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true ~sort:false t_in in let t_exp = t_in in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ] end module BotAndTopSimplification = struct let tests = [ (* When merge_kinds is true, all kinds of `empty` are equivalent, even when * nested under a type constructor. * * {f: empty} | {f: empty'} * ~> (merge_kinds:true) * {f: empty'} *) ( "simplify_union_obj_empty_insensitive" >:: fun ctxt -> let t_in = Ty.Union ( false, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Bot Ty.EmptyType; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Bot Ty.EmptyMatchingPropT; polarity = Ty.Neutral; optional = false; }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true ~sort:false t_in in let t_exp = Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Bot Ty.EmptyType; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; } in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); (* This tests the conversion `mixed & T -> T` and that `empty' | T` remains * as is when: * - `empty'` is not the empty type due to * + an annotation, or * + a tvar with no lower and no upper bounds * - merge_kinds is false * * mixed & (empty' | (mixed & (empty'' | number))) * ~> (merge_kinds:false) * empty' | empty'' | number *) ( "merge_bot_and_any_kinds_sensitive" >:: fun ctxt -> let t_in = Ty.Inter ( Ty.Top, Ty.Union ( false, Ty.Bot (Ty.EmptyTypeDestructorTriggerT ALoc.none), Ty.Inter ( Ty.Top, Ty.Union ( false, Ty.Bot (Ty.NoLowerWithUpper (Ty.SomeUnknownUpper "blah")), Ty.Num None, [] ), [] ), [] ), [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:false ~sort:false t_in in let t_exp = Ty.Union ( false, Ty.Bot (Ty.EmptyTypeDestructorTriggerT ALoc.none), Ty.Bot (Ty.NoLowerWithUpper (Ty.SomeUnknownUpper "blah")), [Ty.Num None] ) in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); (* This tests the conversion `mixed & T -> T` and `empty' | T -> T` when * merge_kinds is true. * * mixed & (empty' | (mixed & (empty'' | number))) * ~> * number *) ( "merge_bot_and_any_kinds_insensitive" >:: fun ctxt -> let t_in = Ty.Inter ( Ty.Top, Ty.Union ( false, Ty.Bot (Ty.EmptyTypeDestructorTriggerT ALoc.none), Ty.Inter ( Ty.Top, Ty.Union ( false, Ty.Bot (Ty.NoLowerWithUpper (Ty.SomeUnknownUpper "blah")), Ty.Num None, [] ), [] ), [] ), [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true ~sort:false t_in in let t_exp = Ty.Num None in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ] end module AnySimplification = struct open Ty (* When merge_kinds is false, we preserve the different kinds of any. * * any | (any' & (any & any')) * ~> * any | (any' & (any & any')) *) let tests = [ ( "merge_any_kinds_sensitive" >:: fun ctxt -> let t_in = Union ( false, Any (Unsound BoundFunctionThis), Inter ( Any (Annotated ALoc.none), Union (false, Any (Unsound BoundFunctionThis), Ty.Any (Annotated ALoc.none), []), [] ), [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:false t_in in let t_exp = t_in in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); (* When merge_kinds is true, all kinds of any are considered equal and so * are merged when appearing in unions or intersections. * * any | (any' & (any & any')) * ~> * any * * The output could also be any'. The kind of the resulting any type when * merge_kinds is true, is not specified. *) ( "merge_any_kinds_insensitive" >:: fun ctxt -> let t_in = Union ( false, Any (Unsound BoundFunctionThis), Inter ( Any (Annotated ALoc.none), Union (false, Any (Unsound BoundFunctionThis), Ty.Any (Annotated ALoc.none), []), [] ), [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true t_in in let t_exp = Any (Unsound BoundFunctionThis) in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ] end module Sorting = struct let simplify_base = simplify_type ~merge_kinds:false ~sort:false let simplify_sort = simplify_type ~merge_kinds:false ~sort:true let t0 = Union (false, Any (Annotated ALoc.none), Num None, [NumLit "42"]) let t1 = Union (false, NumLit "1", NumLit "2", [NumLit "42"]) let t2 = Union (false, NumLit "2", t0, [t1]) let t3 = Union (false, t0, t1, [t2]) let t4 = Union (false, t3, t2, [t1; t0]) let t5 = Union (false, t0, t1, [t2; t3; t4]) let t6 = Union (false, t3, t2, [t4; t0; t1; t5]) let t6_sorted = Union (false, Any (Annotated ALoc.none), NumLit "1", [NumLit "2"; NumLit "42"; Num None]) let tests = [ ( "idempotence" >:: fun ctxt -> assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) (simplify_base t0) (simplify_base (simplify_base t0)); assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) (simplify_base t6) (simplify_base (simplify_base (simplify_base t6))); assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) (simplify_sort t4) (simplify_sort (simplify_sort t4)); assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) (simplify_sort t6) (simplify_sort (simplify_sort (simplify_sort t6))) ); ( "sorting" >:: fun ctxt -> assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) t6_sorted (simplify_sort t6) ); ( "union/intersection" >:: fun ctxt -> let t_in = Inter ( Union ( false, Void, Inter (Void, Any (Annotated ALoc.none), [NumLit "1"]), [Inter (NumLit "1", Any (Annotated ALoc.none), [Void])] ), Union (false, Inter (Any (Annotated ALoc.none), Void, [NumLit "1"]), Void, []), [] ) in let t_out = simplify_sort t_in in let t_exp = Union (false, Void, Inter (Any (Annotated ALoc.none), Void, [NumLit "1"]), []) in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ] end let tests = "ty_simplifier" >::: UnionSimplification.tests @ BotAndTopSimplification.tests @ AnySimplification.tests @ Sorting.tests
null
https://raw.githubusercontent.com/facebook/flow/d3c792ce86a18b200eb4cf9ff66734c2002951f1/src/common/ty/__tests__/ty_simplifier_test.ml
ocaml
* {f: number} | {f: number} * ~> * {f: number} * {+f: number} | {-f: number} * ~> * {+f: number} | {-f: number} When merge_kinds is true, all kinds of `empty` are equivalent, even when * nested under a type constructor. * * {f: empty} | {f: empty'} * ~> (merge_kinds:true) * {f: empty'} This tests the conversion `mixed & T -> T` and that `empty' | T` remains * as is when: * - `empty'` is not the empty type due to * + an annotation, or * + a tvar with no lower and no upper bounds * - merge_kinds is false * * mixed & (empty' | (mixed & (empty'' | number))) * ~> (merge_kinds:false) * empty' | empty'' | number This tests the conversion `mixed & T -> T` and `empty' | T -> T` when * merge_kinds is true. * * mixed & (empty' | (mixed & (empty'' | number))) * ~> * number When merge_kinds is false, we preserve the different kinds of any. * * any | (any' & (any & any')) * ~> * any | (any' & (any & any')) When merge_kinds is true, all kinds of any are considered equal and so * are merged when appearing in unions or intersections. * * any | (any' & (any & any')) * ~> * any * * The output could also be any'. The kind of the resulting any type when * merge_kinds is true, is not specified.
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open OUnit2 open Ty open Ty_utils module UnionSimplification = struct let tests = [ ( "simplify_union_obj" >:: fun ctxt -> let t_in = Ty.Union ( false, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true ~sort:false t_in in let t_exp = Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; } in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ( "simplify_union_obj" >:: fun ctxt -> let t_in = Ty.Union ( false, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Positive; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Num None; polarity = Ty.Negative; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true ~sort:false t_in in let t_exp = t_in in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ] end module BotAndTopSimplification = struct let tests = [ ( "simplify_union_obj_empty_insensitive" >:: fun ctxt -> let t_in = Ty.Union ( false, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Bot Ty.EmptyType; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Bot Ty.EmptyMatchingPropT; polarity = Ty.Neutral; optional = false; }; inherited = false; source = Ty.Other; def_loc = None; }; ]; }, [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true ~sort:false t_in in let t_exp = Ty.Obj { Ty.obj_kind = Ty.InexactObj; obj_def_loc = None; obj_frozen = false; obj_literal = None; obj_props = [ Ty.NamedProp { name = Reason.OrdinaryName "f"; prop = Ty.Field { t = Ty.Bot Ty.EmptyType; polarity = Ty.Neutral; optional = false }; inherited = false; source = Ty.Other; def_loc = None; }; ]; } in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ( "merge_bot_and_any_kinds_sensitive" >:: fun ctxt -> let t_in = Ty.Inter ( Ty.Top, Ty.Union ( false, Ty.Bot (Ty.EmptyTypeDestructorTriggerT ALoc.none), Ty.Inter ( Ty.Top, Ty.Union ( false, Ty.Bot (Ty.NoLowerWithUpper (Ty.SomeUnknownUpper "blah")), Ty.Num None, [] ), [] ), [] ), [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:false ~sort:false t_in in let t_exp = Ty.Union ( false, Ty.Bot (Ty.EmptyTypeDestructorTriggerT ALoc.none), Ty.Bot (Ty.NoLowerWithUpper (Ty.SomeUnknownUpper "blah")), [Ty.Num None] ) in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ( "merge_bot_and_any_kinds_insensitive" >:: fun ctxt -> let t_in = Ty.Inter ( Ty.Top, Ty.Union ( false, Ty.Bot (Ty.EmptyTypeDestructorTriggerT ALoc.none), Ty.Inter ( Ty.Top, Ty.Union ( false, Ty.Bot (Ty.NoLowerWithUpper (Ty.SomeUnknownUpper "blah")), Ty.Num None, [] ), [] ), [] ), [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true ~sort:false t_in in let t_exp = Ty.Num None in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ] end module AnySimplification = struct open Ty let tests = [ ( "merge_any_kinds_sensitive" >:: fun ctxt -> let t_in = Union ( false, Any (Unsound BoundFunctionThis), Inter ( Any (Annotated ALoc.none), Union (false, Any (Unsound BoundFunctionThis), Ty.Any (Annotated ALoc.none), []), [] ), [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:false t_in in let t_exp = t_in in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ( "merge_any_kinds_insensitive" >:: fun ctxt -> let t_in = Union ( false, Any (Unsound BoundFunctionThis), Inter ( Any (Annotated ALoc.none), Union (false, Any (Unsound BoundFunctionThis), Ty.Any (Annotated ALoc.none), []), [] ), [] ) in let t_out = Ty_utils.simplify_type ~merge_kinds:true t_in in let t_exp = Any (Unsound BoundFunctionThis) in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ] end module Sorting = struct let simplify_base = simplify_type ~merge_kinds:false ~sort:false let simplify_sort = simplify_type ~merge_kinds:false ~sort:true let t0 = Union (false, Any (Annotated ALoc.none), Num None, [NumLit "42"]) let t1 = Union (false, NumLit "1", NumLit "2", [NumLit "42"]) let t2 = Union (false, NumLit "2", t0, [t1]) let t3 = Union (false, t0, t1, [t2]) let t4 = Union (false, t3, t2, [t1; t0]) let t5 = Union (false, t0, t1, [t2; t3; t4]) let t6 = Union (false, t3, t2, [t4; t0; t1; t5]) let t6_sorted = Union (false, Any (Annotated ALoc.none), NumLit "1", [NumLit "2"; NumLit "42"; Num None]) let tests = [ ( "idempotence" >:: fun ctxt -> assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) (simplify_base t0) (simplify_base (simplify_base t0)); assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) (simplify_base t6) (simplify_base (simplify_base (simplify_base t6))); assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) (simplify_sort t4) (simplify_sort (simplify_sort t4)); assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) (simplify_sort t6) (simplify_sort (simplify_sort (simplify_sort t6))) ); ( "sorting" >:: fun ctxt -> assert_equal ~ctxt ~printer:(Ty_printer.string_of_t ~exact_by_default:true) t6_sorted (simplify_sort t6) ); ( "union/intersection" >:: fun ctxt -> let t_in = Inter ( Union ( false, Void, Inter (Void, Any (Annotated ALoc.none), [NumLit "1"]), [Inter (NumLit "1", Any (Annotated ALoc.none), [Void])] ), Union (false, Inter (Any (Annotated ALoc.none), Void, [NumLit "1"]), Void, []), [] ) in let t_out = simplify_sort t_in in let t_exp = Union (false, Void, Inter (Any (Annotated ALoc.none), Void, [NumLit "1"]), []) in assert_equal ~ctxt ~printer:Ty.show t_exp t_out ); ] end let tests = "ty_simplifier" >::: UnionSimplification.tests @ BotAndTopSimplification.tests @ AnySimplification.tests @ Sorting.tests
d71c6a7f5f322295de318878020522ec3fd334d46c39f55ebc62199468e883da
GillianPlatform/Gillian
pc.ml
open Gil_syntax module PureContext = Engine.PFS module TypEnv = Engine.TypEnv module FOSolver = Engine.FOSolver type t = { pfs : PureContext.t; gamma : TypEnv.t; learned : Formula.Set.t; learned_types : (string * Type.t) list; unification : bool; } let copy { pfs; gamma; learned; learned_types; unification } = { pfs = PureContext.copy pfs; gamma = TypEnv.copy gamma; learned; learned_types; unification; } let make ~pfs ~gamma ?(unification = false) ?(learned = []) ?(learned_types = []) () = { pfs; gamma; learned = Formula.Set.of_list learned; learned_types; unification; } let init ?(unification = false) () = make ~pfs:(PureContext.init ()) ~gamma:(TypEnv.init ()) ~unification () let empty = init () let pfs_to_pfs_and_gamma pfs = let expr_type_binding_to_gamma etb = match etb with | Expr.PVar s, t | Expr.LVar s, t -> Some (s, t) | _ -> None in let rec aux = function | [] -> ([], []) | Formula.Eq (UnOp (TypeOf, e), Lit (Type t)) :: r | Eq (Lit (Type t), UnOp (TypeOf, e)) :: r -> ( let other_pfs, other_gamma = aux r in match expr_type_binding_to_gamma (e, t) with | None -> ( Formula.Eq (Lit (Type t), UnOp (TypeOf, e)) :: other_pfs, other_gamma ) | Some gamma -> (other_pfs, gamma :: other_gamma)) | f :: r -> let other_pfs, other_gamma = aux r in (f :: other_pfs, other_gamma) in aux pfs let extend pc fs = let fs = List.concat_map Formula.split_conjunct_formulae fs in let pfs, gamma = (pc.pfs, pc.gamma) in let fs = List.filter_map (fun f -> match Engine.Reduction.reduce_formula ~unification:pc.unification ~pfs ~gamma f with | Formula.True -> None | f -> Some f) fs in let new_pfs, new_gamma = pfs_to_pfs_and_gamma fs in { pc with learned = Formula.Set.add_seq (List.to_seq new_pfs) pc.learned; learned_types = new_gamma @ pc.learned_types; } let extend_types pc types = { pc with learned_types = types @ pc.learned_types } let equal pca pcb = pca.pfs = pcb.pfs && pca.gamma = pcb.gamma && Formula.Set.equal pca.learned pcb.learned && List.for_all2 (fun (n1, t1) (n2, t2) -> String.equal n1 n2 && String.equal (Type.str t1) (Type.str t2)) pca.learned_types pcb.learned_types let pp = Fmt.braces (Fmt.record ~sep:Fmt.semi [ Fmt.field "pfs" (fun x -> x.pfs) (fun fmt pfs -> (Fmt.Dump.list Formula.pp) fmt (PureContext.to_list pfs)); Fmt.field "gamma" (fun x -> x.gamma) TypEnv.pp; Fmt.field "learned" (fun x -> Formula.Set.to_seq x.learned) (Fmt.Dump.seq Formula.pp); Fmt.field "learned_types" (fun x -> x.learned_types) (Fmt.Dump.list (Fmt.Dump.pair Fmt.string (Fmt.of_to_string Type.str))); ]) let diff pca pcb = ( Formula.Set.diff pca.learned pcb.learned, Formula.Set.diff pcb.learned pca.learned )
null
https://raw.githubusercontent.com/GillianPlatform/Gillian/1c8d65120c04ef87cda689a9d41268e25b5ffa7e/GillianCore/monadic/pc.ml
ocaml
open Gil_syntax module PureContext = Engine.PFS module TypEnv = Engine.TypEnv module FOSolver = Engine.FOSolver type t = { pfs : PureContext.t; gamma : TypEnv.t; learned : Formula.Set.t; learned_types : (string * Type.t) list; unification : bool; } let copy { pfs; gamma; learned; learned_types; unification } = { pfs = PureContext.copy pfs; gamma = TypEnv.copy gamma; learned; learned_types; unification; } let make ~pfs ~gamma ?(unification = false) ?(learned = []) ?(learned_types = []) () = { pfs; gamma; learned = Formula.Set.of_list learned; learned_types; unification; } let init ?(unification = false) () = make ~pfs:(PureContext.init ()) ~gamma:(TypEnv.init ()) ~unification () let empty = init () let pfs_to_pfs_and_gamma pfs = let expr_type_binding_to_gamma etb = match etb with | Expr.PVar s, t | Expr.LVar s, t -> Some (s, t) | _ -> None in let rec aux = function | [] -> ([], []) | Formula.Eq (UnOp (TypeOf, e), Lit (Type t)) :: r | Eq (Lit (Type t), UnOp (TypeOf, e)) :: r -> ( let other_pfs, other_gamma = aux r in match expr_type_binding_to_gamma (e, t) with | None -> ( Formula.Eq (Lit (Type t), UnOp (TypeOf, e)) :: other_pfs, other_gamma ) | Some gamma -> (other_pfs, gamma :: other_gamma)) | f :: r -> let other_pfs, other_gamma = aux r in (f :: other_pfs, other_gamma) in aux pfs let extend pc fs = let fs = List.concat_map Formula.split_conjunct_formulae fs in let pfs, gamma = (pc.pfs, pc.gamma) in let fs = List.filter_map (fun f -> match Engine.Reduction.reduce_formula ~unification:pc.unification ~pfs ~gamma f with | Formula.True -> None | f -> Some f) fs in let new_pfs, new_gamma = pfs_to_pfs_and_gamma fs in { pc with learned = Formula.Set.add_seq (List.to_seq new_pfs) pc.learned; learned_types = new_gamma @ pc.learned_types; } let extend_types pc types = { pc with learned_types = types @ pc.learned_types } let equal pca pcb = pca.pfs = pcb.pfs && pca.gamma = pcb.gamma && Formula.Set.equal pca.learned pcb.learned && List.for_all2 (fun (n1, t1) (n2, t2) -> String.equal n1 n2 && String.equal (Type.str t1) (Type.str t2)) pca.learned_types pcb.learned_types let pp = Fmt.braces (Fmt.record ~sep:Fmt.semi [ Fmt.field "pfs" (fun x -> x.pfs) (fun fmt pfs -> (Fmt.Dump.list Formula.pp) fmt (PureContext.to_list pfs)); Fmt.field "gamma" (fun x -> x.gamma) TypEnv.pp; Fmt.field "learned" (fun x -> Formula.Set.to_seq x.learned) (Fmt.Dump.seq Formula.pp); Fmt.field "learned_types" (fun x -> x.learned_types) (Fmt.Dump.list (Fmt.Dump.pair Fmt.string (Fmt.of_to_string Type.str))); ]) let diff pca pcb = ( Formula.Set.diff pca.learned pcb.learned, Formula.Set.diff pcb.learned pca.learned )
d11b3fa4d477b14680e0253a28d7985c7bc1664231f9788a3e7a941a2ffc2a2f
gossiperl/gossiperl
gossiperl_member_fsm.erl
Copyright ( c ) 2014 < > %% %% 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(gossiperl_member_fsm). -behaviour(gen_fsm). -include("gossiperl.hrl"). -export([start_link/6, init/1, handle_info/3, terminate/3, code_change/4, handle_sync_event/4, handle_event/3]). -export([reachable/2, unreachable/2, quarantine/2, dropped/2]). -record(state, { name :: binary(), ip :: binary(), port :: integer(), quarantine_after :: integer(), max_quarantined :: integer(), drop_unreachable_after :: integer(), secret :: binary(), last_heard :: integer(), membership :: pid() }). start_link(Config, MemberName, Ip, Port, Heartbeat, Secret) -> gen_fsm:start_link(?MODULE, [Config, MemberName, Ip, Port, Heartbeat, Secret], []). init([Config, MemberName, Ip, Port, Heartbeat, Secret]) -> gossiperl_log:info("[MEMBER][~p] Added as new.", [ MemberName ]), State = #state{ name = MemberName, ip = Ip, port = Port, secret = Secret, quarantine_after = Config#overlayConfig.quarantine_after, max_quarantined = Config#overlayConfig.max_quarantined, drop_unreachable_after = Config#overlayConfig.drop_unreachable_after, last_heard = Heartbeat, membership = ?MEMBERSHIP(Config) }, gen_server:cast( ?MEMBERSHIP(Config), { member_state_change, <<"member_in">>, MemberName } ), { ok, reachable, State, ?MEMBER_CHECK_STATE_EVERY }. handle_info(_AnyInfo, State, LoopData) -> { next_state, State, LoopData }. handle_event(stop, _StateName, StateData) -> {stop, normal, StateData}. handle_sync_event({ leave }, From, _State, S) -> gen_fsm:reply(From, ok), { next_state, dropped, S, 0 }; handle_sync_event({ member_info }, From, State, S=#state{ name=MemberName, ip=Ip, port=Port, last_heard=LastHeardOf }) -> gen_fsm:reply(From, { case Ip of <<"127.0.0.1">> -> local; <<"::1">> -> local; _ -> remote end, State, MemberName, Ip, Port, LastHeardOf }), { next_state, State, S, ?MEMBER_CHECK_STATE_EVERY }; handle_sync_event({ is_secret_valid, OtherSecret }, From, State, S=#state{ secret=Secret }) -> gen_fsm:reply(From, ( OtherSecret =:= Secret )), { next_state, State, S, ?MEMBER_CHECK_STATE_EVERY }; handle_sync_event(_Msg, _From, State, LoopData) -> { next_state, State, LoopData, ?MEMBER_CHECK_STATE_EVERY }. code_change(_OldVsn, StateName, StateData, _Extra) -> {ok, StateName, StateData}. terminate(_Reason, _State, _LoopData) -> {ok}. reachable(timeout, S=#state{ quarantine_after=QuarantineAfter, last_heard=LastHeardOf, name=MemberName, membership = MembershipPid }) -> Timestamp = gossiperl_common:get_timestamp(), if ( Timestamp - LastHeardOf >= QuarantineAfter ) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_quarantine">>, MemberName } ), { next_state, quarantine, S, 0 }; true -> { next_state, reachable, S, ?MEMBER_CHECK_STATE_EVERY } end; reachable({reachable, Heartbeat}, S=#state{}) -> { next_state, reachable, S#state{ last_heard=Heartbeat }, ?MEMBER_CHECK_STATE_EVERY }. quarantine(timeout, S=#state{ quarantine_after=QuarantineAfter, max_quarantined=MaxQuarantined, name=MemberName, last_heard=LastHeardOf, membership = MembershipPid }) -> Timestamp = gossiperl_common:get_timestamp(), if ( Timestamp - LastHeardOf >= ( QuarantineAfter + MaxQuarantined ) ) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_unreachable">>, MemberName } ), { next_state, unreachable, S, 0 }; true -> { next_state, quarantine, S, ?MEMBER_CHECK_STATE_EVERY } end; quarantine({reachable, Heartbeat}, S=#state{ name=MemberName, membership=MembershipPid }) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_rejoin">>, MemberName } ), { next_state, reachable, S#state{ last_heard=Heartbeat }, ?MEMBER_CHECK_STATE_EVERY }. unreachable(timeout, S=#state{ drop_unreachable_after=DropUnrechableAfter }) when DropUnrechableAfter =:= 0 -> { next_state, unreachable, S, ?MEMBER_CHECK_STATE_EVERY }; unreachable(timeout, S=#state{ drop_unreachable_after=DropUnrechableAfter, last_heard=LastHeardOf, name=MemberName, membership = MembershipPid }) when DropUnrechableAfter > 0 -> Timestamp = gossiperl_common:get_timestamp(), if ( Timestamp - LastHeardOf >= DropUnrechableAfter ) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_drop">>, MemberName } ), { next_state, dropped, S, 0 }; true -> { next_state, unreachable, S, ?MEMBER_CHECK_STATE_EVERY } end; unreachable({reachable, Heartbeat}, S=#state{ name=MemberName, membership=MembershipPid }) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_rejoin">>, MemberName } ), { next_state, reachable, S#state{ last_heard=Heartbeat }, ?MEMBER_CHECK_STATE_EVERY }. dropped(_, #state{ name=MemberName, ip=MemberIp }) -> exit({dropped, MemberName, MemberIp}).
null
https://raw.githubusercontent.com/gossiperl/gossiperl/0e7a3806bdec94016ba12f069d1699037c477c29/src/gossiperl_member_fsm.erl
erlang
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.
Copyright ( c ) 2014 < > 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 , -module(gossiperl_member_fsm). -behaviour(gen_fsm). -include("gossiperl.hrl"). -export([start_link/6, init/1, handle_info/3, terminate/3, code_change/4, handle_sync_event/4, handle_event/3]). -export([reachable/2, unreachable/2, quarantine/2, dropped/2]). -record(state, { name :: binary(), ip :: binary(), port :: integer(), quarantine_after :: integer(), max_quarantined :: integer(), drop_unreachable_after :: integer(), secret :: binary(), last_heard :: integer(), membership :: pid() }). start_link(Config, MemberName, Ip, Port, Heartbeat, Secret) -> gen_fsm:start_link(?MODULE, [Config, MemberName, Ip, Port, Heartbeat, Secret], []). init([Config, MemberName, Ip, Port, Heartbeat, Secret]) -> gossiperl_log:info("[MEMBER][~p] Added as new.", [ MemberName ]), State = #state{ name = MemberName, ip = Ip, port = Port, secret = Secret, quarantine_after = Config#overlayConfig.quarantine_after, max_quarantined = Config#overlayConfig.max_quarantined, drop_unreachable_after = Config#overlayConfig.drop_unreachable_after, last_heard = Heartbeat, membership = ?MEMBERSHIP(Config) }, gen_server:cast( ?MEMBERSHIP(Config), { member_state_change, <<"member_in">>, MemberName } ), { ok, reachable, State, ?MEMBER_CHECK_STATE_EVERY }. handle_info(_AnyInfo, State, LoopData) -> { next_state, State, LoopData }. handle_event(stop, _StateName, StateData) -> {stop, normal, StateData}. handle_sync_event({ leave }, From, _State, S) -> gen_fsm:reply(From, ok), { next_state, dropped, S, 0 }; handle_sync_event({ member_info }, From, State, S=#state{ name=MemberName, ip=Ip, port=Port, last_heard=LastHeardOf }) -> gen_fsm:reply(From, { case Ip of <<"127.0.0.1">> -> local; <<"::1">> -> local; _ -> remote end, State, MemberName, Ip, Port, LastHeardOf }), { next_state, State, S, ?MEMBER_CHECK_STATE_EVERY }; handle_sync_event({ is_secret_valid, OtherSecret }, From, State, S=#state{ secret=Secret }) -> gen_fsm:reply(From, ( OtherSecret =:= Secret )), { next_state, State, S, ?MEMBER_CHECK_STATE_EVERY }; handle_sync_event(_Msg, _From, State, LoopData) -> { next_state, State, LoopData, ?MEMBER_CHECK_STATE_EVERY }. code_change(_OldVsn, StateName, StateData, _Extra) -> {ok, StateName, StateData}. terminate(_Reason, _State, _LoopData) -> {ok}. reachable(timeout, S=#state{ quarantine_after=QuarantineAfter, last_heard=LastHeardOf, name=MemberName, membership = MembershipPid }) -> Timestamp = gossiperl_common:get_timestamp(), if ( Timestamp - LastHeardOf >= QuarantineAfter ) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_quarantine">>, MemberName } ), { next_state, quarantine, S, 0 }; true -> { next_state, reachable, S, ?MEMBER_CHECK_STATE_EVERY } end; reachable({reachable, Heartbeat}, S=#state{}) -> { next_state, reachable, S#state{ last_heard=Heartbeat }, ?MEMBER_CHECK_STATE_EVERY }. quarantine(timeout, S=#state{ quarantine_after=QuarantineAfter, max_quarantined=MaxQuarantined, name=MemberName, last_heard=LastHeardOf, membership = MembershipPid }) -> Timestamp = gossiperl_common:get_timestamp(), if ( Timestamp - LastHeardOf >= ( QuarantineAfter + MaxQuarantined ) ) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_unreachable">>, MemberName } ), { next_state, unreachable, S, 0 }; true -> { next_state, quarantine, S, ?MEMBER_CHECK_STATE_EVERY } end; quarantine({reachable, Heartbeat}, S=#state{ name=MemberName, membership=MembershipPid }) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_rejoin">>, MemberName } ), { next_state, reachable, S#state{ last_heard=Heartbeat }, ?MEMBER_CHECK_STATE_EVERY }. unreachable(timeout, S=#state{ drop_unreachable_after=DropUnrechableAfter }) when DropUnrechableAfter =:= 0 -> { next_state, unreachable, S, ?MEMBER_CHECK_STATE_EVERY }; unreachable(timeout, S=#state{ drop_unreachable_after=DropUnrechableAfter, last_heard=LastHeardOf, name=MemberName, membership = MembershipPid }) when DropUnrechableAfter > 0 -> Timestamp = gossiperl_common:get_timestamp(), if ( Timestamp - LastHeardOf >= DropUnrechableAfter ) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_drop">>, MemberName } ), { next_state, dropped, S, 0 }; true -> { next_state, unreachable, S, ?MEMBER_CHECK_STATE_EVERY } end; unreachable({reachable, Heartbeat}, S=#state{ name=MemberName, membership=MembershipPid }) -> gen_server:cast( MembershipPid, { member_state_change, <<"member_rejoin">>, MemberName } ), { next_state, reachable, S#state{ last_heard=Heartbeat }, ?MEMBER_CHECK_STATE_EVERY }. dropped(_, #state{ name=MemberName, ip=MemberIp }) -> exit({dropped, MemberName, MemberIp}).
bec0fea418117fd1f67981281671f4d63b91a6f8f0f3e3bc43de3f129d691fc2
Rober-t/apxr_run
apxr_run_app.erl
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright ( C ) 2018 ApproximateReality %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%---------------------------------------------------------------------------- @doc ApxrRun top level application . %%% @end %%%---------------------------------------------------------------------------- -module(apxr_run_app). -behaviour(application). %% Application callbacks -export([ start/2, stop/1 ]). %%%============================================================================ %%% API %%%============================================================================ %%----------------------------------------------------------------------------- @private %% @doc This function is called whenever an application is started using %% application:start, and should start the processes of the %% application. Since this application is structured according to the OTP %% design principles as a supervision tree, this means starting the %% top supervisor of the tree. %% @end %%----------------------------------------------------------------------------- -spec start(normal | {takeover, node()} | {failover, node()}, any()) -> {ok, pid()}. start(_StartType, _StartArgs) -> apxr_run_sup:start_link(). %%----------------------------------------------------------------------------- @private %% @doc This function is called whenever an application has stopped. It %% is intended to be the opposite of Module:start and should do %% any necessary cleaning up. The return value is ignored. %% @end %%----------------------------------------------------------------------------- -spec stop(term()) -> ok. stop(_State) -> init:stop(). %%%============================================================================ Internal functions %%%============================================================================
null
https://raw.githubusercontent.com/Rober-t/apxr_run/9c62ab028af7ff3768ffe3f27b8eef1799540f05/src/apxr_run_app.erl
erlang
---------------------------------------------------------------------------- @end ---------------------------------------------------------------------------- Application callbacks ============================================================================ API ============================================================================ ----------------------------------------------------------------------------- @doc This function is called whenever an application is started using application:start, and should start the processes of the application. Since this application is structured according to the OTP design principles as a supervision tree, this means starting the top supervisor of the tree. @end ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- @doc This function is called whenever an application has stopped. It is intended to be the opposite of Module:start and should do any necessary cleaning up. The return value is ignored. @end ----------------------------------------------------------------------------- ============================================================================ ============================================================================
Copyright ( C ) 2018 ApproximateReality @doc ApxrRun top level application . -module(apxr_run_app). -behaviour(application). -export([ start/2, stop/1 ]). @private -spec start(normal | {takeover, node()} | {failover, node()}, any()) -> {ok, pid()}. start(_StartType, _StartArgs) -> apxr_run_sup:start_link(). @private -spec stop(term()) -> ok. stop(_State) -> init:stop(). Internal functions
ad2862b67599bbd16ac36f3fe692c34067ce5478e44f157fd4bb9eae8d782f12
tweag/asterius
CmpWord8.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE MagicHash # module Main where import Data.Word import Data.List import GHC.Prim import GHC.Exts Having a wrapper gives us two things : -- * it's easier to test everything (no need for code using raw primops) -- * we test the deriving mechanism for Word8# data TestWord8 = T8 Word8# deriving (Eq, Ord) mkT8 :: Word -> TestWord8 mkT8 (W# a) = T8 (narrowWord8# a) main :: IO () main = do let input = [ (a, b) | a <- allWord8, b <- allWord8 ] -- -- (==) -- let expected = [ a == b | (a, b) <- input ] actual = [ mkT8 a == mkT8 b | (a, b) <- input ] checkResults "(==)" input expected actual -- -- (/=) -- let expected = [ a /= b | (a, b) <- input ] actual = [ mkT8 a /= mkT8 b | (a, b) <- input ] checkResults "(/=)" input expected actual -- -- (<) -- let expected = [ a < b | (a, b) <- input ] actual = [ mkT8 a < mkT8 b | (a, b) <- input ] checkResults "(<)" input expected actual -- -- (>) -- let expected = [ a > b | (a, b) <- input ] actual = [ mkT8 a > mkT8 b | (a, b) <- input ] checkResults "(>)" input expected actual -- -- (<=) -- let expected = [ a <= b | (a, b) <- input ] actual = [ mkT8 a <= mkT8 b | (a, b) <- input ] checkResults "(<=)" input expected actual -- -- (>=) -- let expected = [ a >= b | (a, b) <- input ] actual = [ mkT8 a >= mkT8 b | (a, b) <- input ] checkResults "(>=)" input expected actual checkResults :: (Eq a, Eq b, Show a, Show b) => String -> [a] -> [b] -> [b] -> IO () checkResults test inputs expected actual = case findIndex (\(e, a) -> e /= a) (zip expected actual) of Nothing -> putStrLn $ "Pass: " ++ test Just i -> error $ "FAILED: " ++ test ++ " for input: " ++ show (inputs !! i) ++ " expected: " ++ show (expected !! i) ++ " but got: " ++ show (actual !! i) allWord8 :: [Word] allWord8 = [ minWord8 .. maxWord8 ] minWord8 :: Word minWord8 = fromIntegral (minBound :: Word8) maxWord8 :: Word maxWord8 = fromIntegral (maxBound :: Word8)
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/primops/CmpWord8.hs
haskell
# LANGUAGE BangPatterns # * it's easier to test everything (no need for code using raw primops) * we test the deriving mechanism for Word8# (==) (/=) (<) (>) (<=) (>=)
# LANGUAGE MagicHash # module Main where import Data.Word import Data.List import GHC.Prim import GHC.Exts Having a wrapper gives us two things : data TestWord8 = T8 Word8# deriving (Eq, Ord) mkT8 :: Word -> TestWord8 mkT8 (W# a) = T8 (narrowWord8# a) main :: IO () main = do let input = [ (a, b) | a <- allWord8, b <- allWord8 ] let expected = [ a == b | (a, b) <- input ] actual = [ mkT8 a == mkT8 b | (a, b) <- input ] checkResults "(==)" input expected actual let expected = [ a /= b | (a, b) <- input ] actual = [ mkT8 a /= mkT8 b | (a, b) <- input ] checkResults "(/=)" input expected actual let expected = [ a < b | (a, b) <- input ] actual = [ mkT8 a < mkT8 b | (a, b) <- input ] checkResults "(<)" input expected actual let expected = [ a > b | (a, b) <- input ] actual = [ mkT8 a > mkT8 b | (a, b) <- input ] checkResults "(>)" input expected actual let expected = [ a <= b | (a, b) <- input ] actual = [ mkT8 a <= mkT8 b | (a, b) <- input ] checkResults "(<=)" input expected actual let expected = [ a >= b | (a, b) <- input ] actual = [ mkT8 a >= mkT8 b | (a, b) <- input ] checkResults "(>=)" input expected actual checkResults :: (Eq a, Eq b, Show a, Show b) => String -> [a] -> [b] -> [b] -> IO () checkResults test inputs expected actual = case findIndex (\(e, a) -> e /= a) (zip expected actual) of Nothing -> putStrLn $ "Pass: " ++ test Just i -> error $ "FAILED: " ++ test ++ " for input: " ++ show (inputs !! i) ++ " expected: " ++ show (expected !! i) ++ " but got: " ++ show (actual !! i) allWord8 :: [Word] allWord8 = [ minWord8 .. maxWord8 ] minWord8 :: Word minWord8 = fromIntegral (minBound :: Word8) maxWord8 :: Word maxWord8 = fromIntegral (maxBound :: Word8)
d39228c922471ba91504c82c3a78196d30a456a12aae68c2dae9d6f8f97b7f9b
TGOlson/blockchain
Mining.hs
module Data.Blockchain.Mining ( module Data.Blockchain.Mining.Block , module Data.Blockchain.Mining.Blockchain ) where import Data.Blockchain.Mining.Block import Data.Blockchain.Mining.Blockchain
null
https://raw.githubusercontent.com/TGOlson/blockchain/da53ad888589b5a2f3fd2c53c33a399fefb48ab1/lib/Data/Blockchain/Mining.hs
haskell
module Data.Blockchain.Mining ( module Data.Blockchain.Mining.Block , module Data.Blockchain.Mining.Blockchain ) where import Data.Blockchain.Mining.Block import Data.Blockchain.Mining.Blockchain
50b5c6cff804495ef0cf769f62603cbaa6a31373a80523d49a2eed181e969029
tari3x/csec-modex
pitranslweak.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * and * * * * Copyright ( C ) INRIA , LIENS , 2000 - 2009 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * Bruno Blanchet and Xavier Allamigeon * * * * Copyright (C) INRIA, LIENS, MPII 2000-2009 * * * *************************************************************) 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 ( in file LICENSE ) . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA This 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 (in file LICENSE). 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 *) open Parsing_helper open Types open Pitypes (* Find the minimum phase in which choice is used *) let rec has_choice = function Var _ -> false | FunApp(f,l) -> (f.f_cat == Choice) || (List.exists has_choice l) let min_choice_phase = ref max_int let rec find_min_choice_phase current_phase = function Nil -> () | Par(p,q) -> find_min_choice_phase current_phase p; find_min_choice_phase current_phase q | Repl (p,_) -> find_min_choice_phase current_phase p | Restr(n,p) -> find_min_choice_phase current_phase p | Test(t1,t2,p,q,_) -> if has_choice t1 || has_choice t2 then begin if current_phase < !min_choice_phase then min_choice_phase := current_phase end; find_min_choice_phase current_phase p; find_min_choice_phase current_phase q | Input(tc,pat,p,_) -> if has_choice tc then begin if current_phase < !min_choice_phase then min_choice_phase := current_phase end; find_min_choice_phase current_phase p | Output(tc,t,p,_) -> if has_choice tc || has_choice t then begin if current_phase < !min_choice_phase then min_choice_phase := current_phase end; find_min_choice_phase current_phase p | Let(pat,t,p,q,_) -> if has_choice t then begin if current_phase < !min_choice_phase then min_choice_phase := current_phase end; find_min_choice_phase current_phase p; find_min_choice_phase current_phase q | LetFilter(vlist,f,p,q,_) -> user_error "Predicates are currently incompatible with non-interference.\n" | Event(_,p,_) -> find_min_choice_phase current_phase p | Insert(_,p,_) -> find_min_choice_phase current_phase p | Get(_,_,p,_) -> find_min_choice_phase current_phase p | Phase(n,p) -> find_min_choice_phase n p (* Rule base *) let nrule = ref 0 let red_rules = ref ([] : reduction list) let mergelr = function Pred(p,[t1;t2]) as x -> begin match p.p_info with [AttackerBin(i,t)] -> if i >= (!min_choice_phase) then x else let att1_i = Param.get_pred (Attacker(i,t)) in Terms.unify t1 t2; Pred(att1_i, [t1]) | [TableBin(i)] -> if i >= (!min_choice_phase) then x else let tbl1_i = Param.get_pred (Table(i)) in Terms.unify t1 t2; Pred(tbl1_i, [t1]) | [InputPBin(i)] -> if i >= (!min_choice_phase) then x else let input1_i = Param.get_pred (InputP(i)) in Terms.unify t1 t2; Pred(input1_i, [t1]) | [OutputPBin(i)] -> if i >= (!min_choice_phase) then x else let output1_i = Param.get_pred (OutputP(i)) in Terms.unify t1 t2; Pred(output1_i, [t1]) | _ -> x end | Pred(p,[t1;t2;t3;t4]) as x -> begin match p.p_info with [MessBin(i,t)] -> if i >= (!min_choice_phase) then x else let mess1_i = Param.get_pred (Mess(i,t)) in Terms.unify t1 t3; Terms.unify t2 t4; Pred(mess1_i, [t1;t2]) | _ -> x end | x -> x let add_rule hyp concl constra tags = if !min_choice_phase > 0 then begin if !Terms.current_bound_vars != [] then Parsing_helper.internal_error "bound vars should be cleaned up (pitranslweak4)"; try let hyp' = List.map mergelr hyp in let concl' = mergelr concl in let hyp'' = List.map Terms.copy_fact2 hyp' in let concl'' = Terms.copy_fact2 concl' in let constra'' = List.map Terms.copy_constra2 constra in let tags'' = match tags with ProcessRule _ -> Parsing_helper.internal_error "ProcessRule should not be generated by pitranslweak" | ProcessRule2(hsl, nl1, nl2) -> ProcessRule2(hsl, List.map Terms.copy_term2 nl1, List.map Terms.copy_term2 nl2) | x -> x in Terms.cleanup(); let constra'' = Rules.simplify_constra_list (concl''::hyp'') constra'' in red_rules := (hyp'', concl'', Rule (!nrule, tags'', hyp'', concl'', constra''), constra'') :: (!red_rules); incr nrule with Terms.Unify -> Terms.cleanup() | Rules.FalseConstraint -> () end else begin red_rules := (hyp, concl, Rule (!nrule, tags, hyp, concl, constra), constra) :: (!red_rules); incr nrule end type transl_state = { hypothesis : fact list; (* Current hypotheses of the rule *) constra : constraints list list; (* Current constraints of the rule *) unif : (term * term) list; (* Current unifications to do *) last_step_unif_left : (term * term) list; last_step_unif_right : (term * term) list; Unifications to do for the last group of destructor applications . last_step_unif will be appended to before emitting clauses . The separation between last_step_unif and is useful only for non - interference . last_step_unif will be appended to unif before emitting clauses. The separation between last_step_unif and unif is useful only for non-interference. *) success_conditions_left : (term * term) list list ref option; success_conditions_right : (term * term) list list ref option; (* List of constraints that should be false for the evaluation of destructors to succeed *) name_params_left : term list; (* List of parameters of names *) name_params_right : term list; name_params_meaning : string list; repl_count : int; input_pred : predicate; output_pred : predicate; cur_phase : int; (* Current phase *) hyp_tags : hypspec list } let att_fact phase t1 t2 = Pred(Param.get_pred (AttackerBin(phase, Terms.get_term_type t1)), [t1; t2]) let mess_fact phase tc1 tm1 tc2 tm2 = Pred(Param.get_pred (MessBin(phase, Terms.get_term_type tm1)), [tc1;tm1;tc2;tm2]) let table_fact phase t1 t2 = Pred(Param.get_pred (TableBin(phase)), [t1;t2]) let output_rule { hypothesis = prev_input; constra = constra; unif = unif; last_step_unif_left = lsu_l; last_step_unif_right = lsu_r; name_params_left = name_params_left; name_params_right = name_params_right; hyp_tags = hyp_tags } out_fact = try if (lsu_l != []) || (lsu_r != []) then Parsing_helper.internal_error "last_step_unif should have been appended to unif"; if !Terms.current_bound_vars != [] then Parsing_helper.internal_error "bound vars should be cleaned up (pitranslweak2)"; List.iter (fun (p1,p2) -> Terms.unify p1 p2) unif; let hyp = List.map Terms.copy_fact2 prev_input in let concl = Terms.copy_fact2 out_fact in let constra2 = List.map Terms.copy_constra2 constra in let name_params_left2 = List.map Terms.copy_term2 name_params_left in let name_params_right2 = List.map Terms.copy_term2 name_params_right in Terms.cleanup(); begin try add_rule hyp concl (Rules.simplify_constra_list (concl::hyp) constra2) (ProcessRule2(hyp_tags, name_params_left2, name_params_right2)) with Rules.FalseConstraint -> () end with Terms.Unify -> Terms.cleanup() (* For non-interference *) let start_destructor_group next_f occ cur_state = if (cur_state.last_step_unif_left != []) || (cur_state.last_step_unif_right != []) then Parsing_helper.internal_error "last_step_unif should have been appended to unif (start_destructor_group)"; let sc_left = ref [] in let sc_right = ref [] in next_f { cur_state with success_conditions_left = Some sc_left; success_conditions_right = Some sc_right }; if List.memq [] (!sc_left) && List.memq [] (!sc_right) then begin (* Both sides always succeed: the condition so that both side fail is false *) [[]] end else begin Get all vars in cur_state.hypothesis/unif/constra let var_list = ref [] in List.iter (Terms.get_vars_fact var_list) cur_state.hypothesis; List.iter (fun (t1,t2) -> Terms.get_vars var_list t1; Terms.get_vars var_list t2) cur_state.unif; List.iter (List.iter (Terms.get_vars_constra var_list)) cur_state.constra; all vars not in cur_state.hypothesis/unif/constra let l_l = List.map (List.map (fun (t1,t2) -> Neq(Terms.generalize_vars_not_in (!var_list) t1, Terms.generalize_vars_not_in (!var_list) t2))) (!sc_left) in let l_r = List.map (List.map (fun (t1,t2) -> Neq(Terms.generalize_vars_not_in (!var_list) t1, Terms.generalize_vars_not_in (!var_list) t2))) (!sc_right) in Terms.cleanup(); (* When the phase is smaller than min_choice_phase, both sides behave the same way by definition so it is not necessary to generate the clauses below *) if cur_state.cur_phase >= !min_choice_phase then begin (* Left side succeeds, right side fails *) List.iter (fun u_left -> output_rule { cur_state with unif = u_left @ cur_state.unif; constra = l_r @ cur_state.constra; hyp_tags = TestUnifTag2(occ):: cur_state.hyp_tags } (Pred(Param.bad_pred, [])) ) (!sc_left); (* Right side succeeds, left side fails *) List.iter (fun u_right -> output_rule { cur_state with unif = u_right @ cur_state.unif; constra = l_l @ cur_state.constra; hyp_tags = TestUnifTag2(occ):: cur_state.hyp_tags } (Pred(Param.bad_pred, [])) ) (!sc_right) end; (* Conditions so that both sides fail *) l_l @ l_r end let start_destructor_group_i next_f occ cur_state = ignore (start_destructor_group next_f occ cur_state) let end_destructor_group next_f cur_state = next_f { cur_state with unif = cur_state.last_step_unif_right @ cur_state.last_step_unif_left @ cur_state.unif; last_step_unif_left = []; last_step_unif_right = []; success_conditions_left = None; success_conditions_right = None }; begin match cur_state.success_conditions_left with None -> internal_error "Group ended but not started" | Some r -> r:= cur_state.last_step_unif_left :: (!r) end; begin match cur_state.success_conditions_right with None -> internal_error "Group ended but not started" | Some r -> r:= cur_state.last_step_unif_right :: (!r) end (* Functions that modify last_step_unif, and that should therefore be followed by a call to end_destructor_group transl_term transl_term_list transl_term_incl_destructor transl_term_list_incl_destructor transl_pat *) (* Translate term *) next_f takes a state and two patterns as parameter let rec transl_term next_f cur_state = function Var v -> begin match v.link with TLink (FunApp(_, [t1;t2])) -> next_f cur_state t1 t2 | _ -> internal_error "unexpected link in transl_term" end | FunApp(f,l) -> let transl_red red_rules = transl_term_list (fun cur_state1 patlist1 patlist2 -> if cur_state.cur_phase < !min_choice_phase then List.iter (fun red_rule -> let (left_list1, right1) = Terms.copy_red red_rule in let (left_list2, right2) = Terms.copy_red red_rule in next_f { cur_state1 with last_step_unif_left = List.fold_left2(fun accu_unif pat left -> (pat,left)::accu_unif) cur_state1.last_step_unif_left patlist1 left_list1; last_step_unif_right = List.fold_left2(fun accu_unif pat left -> (pat,left)::accu_unif) cur_state1.last_step_unif_right patlist2 left_list2} right1 right2 ) red_rules else List.iter (fun red_rule1 -> List.iter (fun red_rule2 -> let (left_list1, right1) = Terms.copy_red red_rule1 in let (left_list2, right2) = Terms.copy_red red_rule2 in next_f { cur_state1 with last_step_unif_left = List.fold_left2(fun accu_unif pat left -> (pat,left)::accu_unif) cur_state1.last_step_unif_left patlist1 left_list1; last_step_unif_right = List.fold_left2(fun accu_unif pat left -> (pat,left)::accu_unif) cur_state1.last_step_unif_right patlist2 left_list2} right1 right2 ) red_rules ) red_rules ) cur_state l in match f.f_cat with Name n -> begin match n.prev_inputs with Some (FunApp(_, [t1;t2])) -> next_f cur_state t1 t2 | _ -> internal_error "unexpected prev_inputs in transl_term" end | Tuple -> transl_term_list (fun cur_state1 patlist1 patlist2 -> next_f cur_state1 (FunApp(f, patlist1)) (FunApp(f, patlist2))) cur_state l | Eq red_rules -> let vars1 = Terms.var_gen (fst f.f_type) in transl_red ((vars1, FunApp(f, vars1)) :: red_rules) | Red red_rules -> transl_red red_rules | Choice -> begin match l with [t1;t2] -> transl_term (fun cur_state1 t11 t12 -> transl_term (fun cur_state2 t21 t22 -> next_f { cur_state2 with last_step_unif_left = cur_state1.last_step_unif_left } t11 t22 ) { cur_state1 with last_step_unif_right = cur_state.last_step_unif_right } t2 ) cur_state t1 | _ -> Parsing_helper.internal_error "Choice should have two arguments" end | _ -> Parsing_helper.internal_error "function symbols of these categories should not appear in input terms" next_f takes a state and two lists of patterns as parameter and transl_term_list next_f cur_state = function [] -> next_f cur_state [] [] | (a::l) -> transl_term (fun cur_state1 p1 p2 -> transl_term_list (fun cur_state2 patlist1 patlist2 -> next_f cur_state2 (p1::patlist1) (p2::patlist2)) cur_state1 l) cur_state a let rec check_several_types = function Var _ -> false | FunApp(f,l) -> (List.exists check_several_types l) || (if !Param.eq_in_names then (* Re-allow an old setting, which was faster on some examples *) match f.f_cat with Red rules -> List.length rules > 1 | Eq rules -> List.length rules > 0 | _ -> false else match f.f_initial_cat with Red rules -> List.length rules > 1 | _ -> false) let transl_term_incl_destructor f t cur_state = let may_have_several_types = check_several_types t in transl_term (fun cur_state1 pat1 pat2 -> if may_have_several_types then f pat1 pat2 { cur_state1 with name_params_left = pat1::cur_state1.name_params_left; name_params_right = pat2::cur_state1.name_params_right; name_params_meaning = "" :: cur_state1.name_params_meaning } else f pat1 pat2 cur_state1 ) cur_state t let transl_term_list_incl_destructor f tl cur_state = let may_have_several_types = List.exists check_several_types tl in transl_term_list ( fun cur_state1 if then f patlist1 patlist2 { cur_state1 with name_params_left = patlist1 @ cur_state1.name_params_left ; name_params_right = patlist2 @ ; name_params_meaning = ( List.map ( fun _ - > " " ) patlist1 ) @ cur_state1.name_params_meaning } else f patlist1 patlist2 cur_state1 ) cur_state tl let transl_term_list_incl_destructor f tl cur_state = let may_have_several_types = List.exists check_several_types tl in transl_term_list (fun cur_state1 patlist1 patlist2 -> if may_have_several_types then f patlist1 patlist2 { cur_state1 with name_params_left = patlist1 @ cur_state1.name_params_left; name_params_right = patlist2 @ cur_state1.name_params_right; name_params_meaning = (List.map (fun _ -> "") patlist1) @ cur_state1.name_params_meaning } else f patlist1 patlist2 cur_state1 ) cur_state tl *) (* Translate pattern *) let rec transl_pat put_var f pat pat1' pat2' cur_state = match pat with PatVar b -> b.link <- TLink (FunApp(Param.choice_fun b.btype, [pat1'; pat2'])); f (if put_var then { cur_state with name_params_left = pat1' :: cur_state.name_params_left; name_params_right = pat2' :: cur_state.name_params_right; name_params_meaning = b.sname :: cur_state.name_params_meaning } else cur_state); b.link <- NoLink | PatTuple (fsymb,patlist) -> let patlist1' = List.map Reduction_helper.new_var_pat patlist in let patlist2' = List.map Reduction_helper.new_var_pat patlist in let pat21 = FunApp(fsymb, patlist1') in let pat22 = FunApp(fsymb, patlist2') in transl_pat_list put_var f patlist patlist1' patlist2' { cur_state with last_step_unif_left = (pat1', pat21)::cur_state.last_step_unif_left; last_step_unif_right = (pat2', pat22)::cur_state.last_step_unif_right }; | PatEqual t -> transl_term_incl_destructor (fun pat1 pat2 cur_state -> f { cur_state with last_step_unif_left = (pat1,pat1')::cur_state.last_step_unif_left; last_step_unif_right = (pat2,pat2')::cur_state.last_step_unif_right; } ) t cur_state and transl_pat_list put_var f patlist patlist1' patlist2' cur_state = match (patlist, patlist1', patlist2') with ([],[],[]) -> f cur_state | (p::pl, p1'::pl1', p2'::pl2') -> transl_pat_list put_var (transl_pat put_var f p p1' p2') pl pl1' pl2' cur_state | _ -> internal_error "not same length in transl_pat_list" Translate process let rec transl_process cur_state = function Nil -> () | Par(p,q) -> transl_process cur_state p; transl_process cur_state q | Repl (p,occ) -> (* Always introduce session identifiers ! *) let v1 = Terms.new_var "sid" Param.sid_type in transl_process { cur_state with repl_count = cur_state.repl_count + 1; name_params_left = (Var v1) :: cur_state.name_params_left; name_params_right = (Var v1) :: cur_state.name_params_right; name_params_meaning = ("!" ^ (string_of_int (cur_state.repl_count+1))) :: cur_state.name_params_meaning; hyp_tags = (ReplTag(occ, List.length cur_state.name_params_left)) :: cur_state.hyp_tags } p | Restr(n,p) -> begin match n.f_cat with Name r -> let ntype = List.map Terms.get_term_type cur_state.name_params_left in if fst n.f_type == Param.tmp_type then begin n.f_type <- ntype, snd n.f_type; r.prev_inputs_meaning <- cur_state.name_params_meaning end else if not (Terms.eq_lists (fst n.f_type) ntype) then internal_error ("Name " ^ n.f_name ^ " has bad arity"); r.prev_inputs <- Some (FunApp(Param.choice_fun (snd n.f_type), [ FunApp(n, cur_state.name_params_left); FunApp(n, cur_state.name_params_right)])); transl_process cur_state p; r.prev_inputs <- None | _ -> internal_error "A restriction should have a name as parameter" end | Test(t1,t2,p,q,occ) -> start_destructor_group_i (fun cur_state -> transl_term_incl_destructor (fun pat1_l pat1_r cur_state1 -> transl_term_incl_destructor (fun pat2_l pat2_r cur_state2 -> end_destructor_group (fun cur_state3 -> output_rule { cur_state3 with unif = (pat1_l, pat2_l) :: cur_state3.unif; constra = [Neq(pat1_r,pat2_r)] :: cur_state3.constra; hyp_tags = TestUnifTag2(occ) :: cur_state3.hyp_tags } (Pred(Param.bad_pred, [])); output_rule { cur_state3 with unif = (pat1_r, pat2_r) :: cur_state3.unif; constra = [Neq(pat1_l,pat2_l)] :: cur_state3.constra; hyp_tags = TestUnifTag2(occ) :: cur_state3.hyp_tags } (Pred(Param.bad_pred, [])); transl_process { cur_state3 with unif = (pat1_l,pat2_l) :: (pat2_r,pat2_r) :: cur_state3.unif; hyp_tags = (TestTag occ) :: cur_state3.hyp_tags } p; transl_process { cur_state3 with constra = [Neq(pat1_l, pat2_l)] :: [Neq(pat1_r,pat2_r)] :: cur_state3.constra; hyp_tags = (TestTag occ) :: cur_state3.hyp_tags } q ) cur_state2 ) t2 cur_state1 ) t1 cur_state ) occ cur_state | Input(tc,pat,p,occ) -> let v1 = Reduction_helper.new_var_pat pat in let v2 = Reduction_helper.new_var_pat pat in begin match tc with FunApp({ f_cat = Name _; f_private = false },_) when !Param.active_attacker -> start_destructor_group_i (fun cur_state -> transl_pat true ( end_destructor_group (fun cur_state1 -> transl_process cur_state1 p) ) pat v1 v2 { cur_state with hypothesis = (att_fact cur_state.cur_phase v1 v2) :: cur_state.hypothesis; hyp_tags = (InputTag(occ)) :: cur_state.hyp_tags } ) occ cur_state When the channel is a public name , and the same name a on both sides , generating h - > input2 : a , a is useless since attacker2 : a , a and attacker2 :x , x ' - > input2 :x , x ' generating h -> input2:a,a is useless since attacker2:a,a and attacker2:x,x' -> input2:x,x' *) | _ -> start_destructor_group_i (fun cur_state -> transl_term_incl_destructor (fun pat1 pat2 cur_state1 -> end_destructor_group (fun cur_state2 -> start_destructor_group_i (fun cur_state2 -> transl_pat true (end_destructor_group (fun cur_state3 -> transl_process cur_state3 p)) pat v1 v2 { cur_state2 with hypothesis = (mess_fact cur_state.cur_phase pat1 v1 pat2 v2) :: cur_state2.hypothesis; hyp_tags = (InputTag(occ)) :: cur_state2.hyp_tags }; output_rule { cur_state2 with hyp_tags = (InputPTag(occ)) :: cur_state2.hyp_tags } (Pred(cur_state.input_pred, [pat1; pat2])) ) occ cur_state2 ) cur_state1 ) tc cur_state ) occ cur_state end | Output(tc,t,p,occ) -> begin match tc with FunApp({ f_cat = Name _; f_private = false },_) when !Param.active_attacker -> (* Same remark as for input *) start_destructor_group_i (fun cur_state -> transl_term (fun cur_state1 pat1 pat2 -> end_destructor_group (fun cur_state2 -> output_rule { cur_state2 with hyp_tags = (OutputTag occ) :: cur_state2.hyp_tags } (att_fact cur_state.cur_phase pat1 pat2) ) cur_state1 ) cur_state t ) occ cur_state | _ -> start_destructor_group_i (fun cur_state -> transl_term (fun cur_state1 patc1 patc2 -> transl_term (fun cur_state2 pat1 pat2 -> end_destructor_group (fun cur_state3 -> output_rule { cur_state3 with hyp_tags = (OutputPTag occ) :: cur_state3.hyp_tags } (Pred(cur_state.output_pred, [patc1; patc2])); output_rule { cur_state3 with hypothesis = cur_state3.hypothesis; hyp_tags = (OutputTag occ) :: cur_state2.hyp_tags } (mess_fact cur_state.cur_phase patc1 pat1 patc2 pat2) ) cur_state2 ) cur_state1 t ) cur_state tc ) occ cur_state end; transl_process { cur_state with hyp_tags = (OutputTag occ) :: cur_state.hyp_tags } p | Let(pat,t,p,p',occ) -> let failure_conditions = start_destructor_group (fun cur_state -> transl_term_incl_destructor (fun pat1 pat2 cur_state1 -> transl_pat false (end_destructor_group (fun cur_state2 -> transl_process cur_state2 p)) pat pat1 pat2 cur_state1 ) t cur_state ) occ { cur_state with hyp_tags = (LetTag occ) :: cur_state.hyp_tags } in transl_process { cur_state with constra = failure_conditions @ cur_state.constra; hyp_tags = (LetTag occ) :: cur_state.hyp_tags } p' | LetFilter(vlist,f,p,q,occ) -> user_error "Predicates are currently incompatible with non-interference.\n" | Event(_, p, _) -> transl_process cur_state p | Insert(t,p,occ) -> start_destructor_group_i (fun cur_state -> transl_term (fun cur_state1 pat1 pat2 -> end_destructor_group (fun cur_state2 -> output_rule { cur_state2 with hyp_tags = (InsertTag occ) :: cur_state2.hyp_tags } (table_fact cur_state.cur_phase pat1 pat2) ) cur_state1 ) cur_state t ) occ cur_state; transl_process { cur_state with hyp_tags = (InsertTag occ) :: cur_state.hyp_tags } p | Get(pat,t,p,occ) -> let v1 = Reduction_helper.new_var_pat pat in let v2 = Reduction_helper.new_var_pat pat in start_destructor_group_i (fun cur_state -> transl_pat true (fun cur_state1 -> transl_term (fun cur_state2 patt1 patt2 -> end_destructor_group (fun cur_state3 -> transl_process cur_state3 p) { cur_state2 with last_step_unif_left = (patt1, FunApp(Terms.true_cst, [])) :: cur_state2.last_step_unif_left; last_step_unif_right = (patt2, FunApp(Terms.true_cst, [])) :: cur_state2.last_step_unif_right } ) cur_state1 t ) pat v1 v2 { cur_state with hypothesis = (table_fact cur_state.cur_phase v1 v2) :: cur_state.hypothesis; hyp_tags = (GetTag(occ)) :: cur_state.hyp_tags } ) occ cur_state | Phase(n,p) -> transl_process { cur_state with input_pred = Param.get_pred (InputPBin(n)); output_pred = Param.get_pred (OutputPBin(n)); cur_phase = n } p let rules_for_red f phase red_rules = let res_pred = Param.get_pred (AttackerBin(phase, snd f.f_type)) in if phase < !min_choice_phase then (* Optimize generation when no choice in the current phase *) List.iter (fun red1 -> let (hyp1, concl1) = Terms.copy_red red1 in add_rule (List.map (fun t -> att_fact phase t t) hyp1) (att_fact phase concl1 concl1) [] (Apply(Func(f), res_pred)) ) red_rules else List.iter (fun red1 -> List.iter (fun red2 -> let (hyp1, concl1) = Terms.copy_red red1 in let (hyp2, concl2) = Terms.copy_red red2 in add_rule (List.map2 (att_fact phase) hyp1 hyp2) (att_fact phase concl1 concl2) [] (Apply(Func(f), res_pred)) ) red_rules ) red_rules let rules_for_function phase _ f = if not f.f_private then let res_pred = Param.get_pred (AttackerBin(phase, snd f.f_type)) in match f.f_cat with Eq red_rules -> let vars1 = Terms.var_gen (fst f.f_type) in rules_for_red f phase ((vars1, FunApp(f, vars1)) :: red_rules) | Red red_rules -> rules_for_red f phase red_rules; List.iter (fun red -> let (hyp, _) = Terms.copy_red red in let vlist = List.map Terms.new_var_def (List.map Terms.get_term_type hyp) in let make_constra red = let (hyp, _) = Terms.copy_red red in if !Terms.current_bound_vars != [] then Parsing_helper.internal_error "bound vars should be cleaned up (pitranslweak3)"; let hyp' = List.map (Terms.generalize_vars_not_in []) hyp in Terms.cleanup(); List.map2 (fun v t -> Neq(v,t)) vlist hyp' in add_rule (List.map2 (att_fact phase) hyp vlist) (Pred(Param.bad_pred, [])) (List.map make_constra red_rules) (TestApply(Func(f), res_pred)); let (hyp, _) = Terms.copy_red red in let vlist = List.map Terms.new_var_def (List.map Terms.get_term_type hyp) in let make_constra red = let (hyp, _) = Terms.copy_red red in if !Terms.current_bound_vars != [] then Parsing_helper.internal_error "bound vars should be cleaned up (pitranslweak3)"; let hyp' = List.map (Terms.generalize_vars_not_in []) hyp in Terms.cleanup(); List.map2 (fun v t -> Neq(v,t)) vlist hyp' in add_rule (List.map2 (att_fact phase) vlist hyp) (Pred(Param.bad_pred, [])) (List.map make_constra red_rules) (TestApply(Func(f), res_pred)) ) red_rules | Tuple -> (* For tuple constructor *) let vars1 = Terms.var_gen (fst f.f_type) in let vars2 = Terms.var_gen (fst f.f_type) in add_rule (List.map2 (att_fact phase) vars1 vars2) (att_fact phase (FunApp(f, vars1)) (FunApp(f, vars2))) [] (Apply(Func(f), res_pred)); (* For corresponding projections *) for n = 0 to (List.length (fst f.f_type))-1 do let vars1 = Terms.var_gen (fst f.f_type) in let vars2 = Terms.var_gen (fst f.f_type) in let v1 = List.nth vars1 n in let v2 = List.nth vars2 n in add_rule [att_fact phase (FunApp(f, vars1)) (FunApp(f, vars2))] (att_fact phase v1 v2) [] (Apply(Proj(f,n),res_pred)) done; let vars1 = Terms.var_gen (fst f.f_type) in let v = Terms.new_var_def (snd f.f_type) in let gvars1 = List.map (fun ty -> FunApp(Terms.new_gen_var ty,[])) (fst f.f_type) in add_rule [att_fact phase (FunApp(f, vars1)) v] (Pred(Param.bad_pred, [])) [[Neq(v, FunApp(f, gvars1))]] (TestApply(Proj(f,0),res_pred)); let vars1 = Terms.var_gen (fst f.f_type) in let v = Terms.new_var_def (snd f.f_type) in let gvars1 = List.map (fun ty -> FunApp(Terms.new_gen_var ty,[])) (fst f.f_type) in add_rule [att_fact phase v (FunApp(f, vars1))] (Pred(Param.bad_pred, [])) [[Neq(v, FunApp(f, gvars1))]] (TestApply(Proj(f,0),res_pred)) | _ -> () let transl_attacker phase = (* The attacker can apply all functions, including tuples *) Hashtbl.iter (rules_for_function phase) Param.fun_decls; Hashtbl.iter (rules_for_function phase) Terms.tuple_table; List.iter (fun t -> let att_pred = Param.get_pred (AttackerBin(phase,t)) in let mess_pred = Param.get_pred (MessBin(phase,t)) in (* The attacker has any message sent on a channel he has *) let v1 = Terms.new_var_def t in let vc1 = Terms.new_var_def Param.channel_type in let v2 = Terms.new_var_def t in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(mess_pred, [vc1; v1; vc2; v2]); att_fact phase vc1 vc2] (Pred(att_pred, [v1; v2])) [] (Rl(att_pred, mess_pred)); if (!Param.active_attacker) then begin (* The attacker can send any message he has on any channel he has *) let v1 = Terms.new_var_def t in let vc1 = Terms.new_var_def Param.channel_type in let v2 = Terms.new_var_def t in let vc2 = Terms.new_var_def Param.channel_type in add_rule [att_fact phase vc1 vc2; Pred(att_pred, [v1; v2])] (Pred(mess_pred, [vc1; v1; vc2; v2])) [] (Rs(att_pred, mess_pred)) end; (* Clauses for equality *) let v = Terms.new_var_def t in add_rule [] (Pred(Param.get_pred (Equal(t)), [v;v])) [] LblEq ) (if !Param.ignore_types then [Param.any_type] else !Param.all_types); if phase >= !min_choice_phase then begin let att_pred = Param.get_pred (AttackerBin(phase,Param.channel_type)) in let input_pred = Param.get_pred (InputPBin(phase)) in let output_pred = Param.get_pred (OutputPBin(phase)) in (* The attacker can do communications *) let vc1 = Terms.new_var_def Param.channel_type in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(att_pred, [vc1; vc2])] (Pred(input_pred, [vc1;vc2])) [] (Ri(att_pred, input_pred)); let vc1 = Terms.new_var_def Param.channel_type in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(att_pred, [vc1; vc2])] (Pred(output_pred, [vc1; vc2])) [] (Ro(att_pred, output_pred)); (* Check communications do not reveal secrets *) let vc = Terms.new_var_def Param.channel_type in let vc1 = Terms.new_var_def Param.channel_type in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(input_pred, [vc; vc1]); Pred(output_pred, [vc; vc2])] (Pred(Param.bad_pred, [])) [[Neq(vc1,vc2)]] (TestComm(input_pred, output_pred)); let vc = Terms.new_var_def Param.channel_type in let vc1 = Terms.new_var_def Param.channel_type in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(input_pred, [vc1; vc]); Pred(output_pred, [vc2; vc])] (Pred(Param.bad_pred, [])) [[Neq(vc1,vc2)]] (TestComm(input_pred, output_pred)) end (* Global translation *) let transl p = Rules.reset (); Reduction_helper.main_process := p; nrule := 0; red_rules := []; List.iter ( fun ( hyp1 , , , tag1 ) - > TermsEq.close_rule_destr_eq ( fun ( hyp , concl , constra ) - > add_rule hyp concl constra tag1 ) ( hyp1 , , constra1 ) ) ( ! Pisyntax.red_rules ) ; List.iter (fun (hyp1, concl1, constra1, tag1) -> TermsEq.close_rule_destr_eq (fun (hyp, concl, constra) -> add_rule hyp concl constra tag1) (hyp1, concl1, constra1)) (!Pisyntax.red_rules); *) find_min_choice_phase 0 p; Reduction_helper.min_choice_phase := !min_choice_phase; Initialize the selection function . In particular , when there is a predicate member :x , y - > member :x , cons(z , y ) we would like , y It is important to initialize this very early , so that the simplification of the initial rules is performed with the good selection function . In particular, when there is a predicate member:x,y -> member:x,cons(z,y) we would like nounif member:*x,y It is important to initialize this very early, so that the simplification of the initial rules is performed with the good selection function. *) List.iter (fun r -> ignore(Selfun.selection_fun r)) (!red_rules); for i = 0 to !Param.max_used_phase do transl_attacker i; List.iter (fun t -> let att_i = Param.get_pred (AttackerBin(i,t)) in if i < !min_choice_phase then begin (* Phase coded by unary predicates *) let v = Terms.new_var Param.def_var_name t in let att_i = Param.get_pred (Attacker(i,t)) in Selfun.add_no_unif (att_i, [FVar v]) Selfun.never_select_weight end else begin (* Phase coded by binary predicates *) let v1 = Terms.new_var Param.def_var_name t in let v2 = Terms.new_var Param.def_var_name t in Selfun.add_no_unif (att_i, [FVar v1; FVar v2]) Selfun.never_select_weight end; if i > 0 then let w1 = Terms.new_var_def t in let w2 = Terms.new_var_def t in let att_im1 = Param.get_pred (AttackerBin(i-1,t)) in add_rule [Pred(att_im1, [w1; w2])] (Pred(att_i, [w1; w2])) [] PhaseChange ) (if !Param.ignore_types || !Param.untyped_attacker then [Param.any_type] else !Param.all_types); if i > 0 then let w1 = Terms.new_var_def Param.table_type in let w2 = Terms.new_var_def Param.table_type in let tbl_i = Param.get_pred (TableBin(i)) in let tbl_im1 = Param.get_pred (TableBin(i-1)) in add_rule [Pred(tbl_im1, [w1; w2])] (Pred(tbl_i, [w1; w2])) [] TblPhaseChange done; (* Knowing the free names and creating new names is necessary only in phase 0. The subsequent phases will get them by attacker'_i(x,y) -> attacker'_{i+1}(x,y) *) (* The attacker has the public free names *) List.iter (fun ch -> if not ch.f_private then add_rule [] (att_fact 0 (FunApp(ch, [])) (FunApp(ch, []))) [] Init) (!Param.freenames); List.iter (fun t -> (* The attacker can create new names *) let v1 = Terms.new_var_def Param.sid_type in let new_name_fun = Terms.new_name_fun t in add_rule [] (att_fact 0 (FunApp(new_name_fun, [v1])) (FunApp(new_name_fun, [v1]))) [] (Rn (Param.get_pred (AttackerBin(0, t)))); (* Rules that derive bad are necessary only in the last phase. Previous phases will get them by attacker'_i(x,y) -> attacker'_{i+1}(x,y) *) let att_pred = Param.get_pred (AttackerBin(!Param.max_used_phase, t)) in (* The attacker can perform equality tests *) let v1 = Terms.new_var_def t in let v2 = Terms.new_var_def t in let v3 = Terms.new_var_def t in add_rule [Pred(att_pred, [v1; v2]); Pred(att_pred, [v1; v3])] (Pred(Param.bad_pred, [])) [[Neq(v2,v3)]] (TestEq(att_pred)); let v1 = Terms.new_var_def t in let v2 = Terms.new_var_def t in let v3 = Terms.new_var_def t in add_rule [Pred(att_pred, [v2; v1]); Pred(att_pred, [v3; v1])] (Pred(Param.bad_pred, [])) [[Neq(v2,v3)]] (TestEq(att_pred)) ) (if !Param.ignore_types || !Param.untyped_attacker then [Param.any_type] else !Param.all_types); List.iter (fun ch -> match ch.f_cat with Name r -> r.prev_inputs <- Some (FunApp(Param.choice_fun (snd ch.f_type), [FunApp(ch, []); FunApp(ch, [])])) | _ -> internal_error "should be a name 1") (!Param.freenames); transl_process { hypothesis = []; constra = []; unif = []; last_step_unif_left = []; last_step_unif_right = []; success_conditions_left = None; success_conditions_right = None; name_params_left = []; name_params_right = []; name_params_meaning = []; repl_count = 0; input_pred = Param.get_pred (InputPBin(0)); output_pred = Param.get_pred (OutputPBin(0)); cur_phase = 0; hyp_tags = [] } p; List.iter (fun ch -> match ch.f_cat with Name r -> r.prev_inputs <- None | _ -> internal_error "should be a name 2") (!Param.freenames); List.iter (function QFact({ p_info = [Attacker(i,ty)] },[t]) -> (* For attacker: not declarations, the not declaration is also valid in previous phases, because of the implication attacker_p(i):x => attacker_p(i+1):x Furthermore, we have to translate unary to binary not declarations *) for j = 0 to i do if j < !min_choice_phase then (* Phase coded by unary predicate, since it does not use choice *) let att_j = Param.get_pred (Attacker(j,ty)) in Rules.add_not(Pred(att_j,[t])) else (* Phase coded by binary predicate *) let att2_j = Param.get_pred (AttackerBin(j,ty)) in Rules.add_not(Pred(att2_j,[t;t])) done | QFact({ p_info = [Mess(i,ty)] } as p,[t1;t2]) -> (* translate unary to binary not declarations *) if i < !min_choice_phase then (* Phase coded by unary predicate, since it does not use choice *) Rules.add_not(Pred(p, [t1;t2])) else (* Phase coded by binary predicate *) let mess2_i = Param.get_pred (MessBin(i,ty)) in Rules.add_not(Pred(mess2_i,[t1;t2;t1;t2])) | _ -> Parsing_helper.user_error "The only allowed facts in \"not\" declarations are attacker: and mess: predicates (for process equivalences, user-defined predicates are forbidden)." ) (if !Param.typed_frontend then Pitsyntax.get_not() else Pisyntax.get_not()); List.iter (function (f,n) -> (* translate unary to binary nounif declarations *) match f with ({ p_info = [Attacker(i,ty)] }, [t]) -> if i < !min_choice_phase then (* Phase coded by unary predicate, since it does not use choice *) Selfun.add_no_unif f n else (* Phase coded by binary predicate *) let att2_i = Param.get_pred (AttackerBin(i,ty)) in Selfun.add_no_unif (att2_i, [t;t]) n | ({ p_info = [Mess(i,ty)] }, [t1;t2]) -> if i < !min_choice_phase then (* Phase coded by unary predicate, since it does not use choice *) Selfun.add_no_unif f n else (* Phase coded by binary predicate *) let mess2_i = Param.get_pred (MessBin(i,ty)) in Selfun.add_no_unif (mess2_i,[t1;t2;t1;t2]) n | _ -> Parsing_helper.user_error "The only allowed facts in \"nounif\" declarations are attacker: and mess: predicates (for process equivalences, user-defined predicates are forbidden)." ) (if !Param.typed_frontend then Pitsyntax.get_nounif() else Pisyntax.get_nounif()); List.rev (!red_rules)
null
https://raw.githubusercontent.com/tari3x/csec-modex/5ab2aa18ef308b4d18ac479e5ab14476328a6a50/deps/proverif1.84/src/pitranslweak.ml
ocaml
Find the minimum phase in which choice is used Rule base Current hypotheses of the rule Current constraints of the rule Current unifications to do List of constraints that should be false for the evaluation of destructors to succeed List of parameters of names Current phase For non-interference Both sides always succeed: the condition so that both side fail is false When the phase is smaller than min_choice_phase, both sides behave the same way by definition so it is not necessary to generate the clauses below Left side succeeds, right side fails Right side succeeds, left side fails Conditions so that both sides fail Functions that modify last_step_unif, and that should therefore be followed by a call to end_destructor_group transl_term transl_term_list transl_term_incl_destructor transl_term_list_incl_destructor transl_pat Translate term Re-allow an old setting, which was faster on some examples Translate pattern Always introduce session identifiers ! Same remark as for input Optimize generation when no choice in the current phase For tuple constructor For corresponding projections The attacker can apply all functions, including tuples The attacker has any message sent on a channel he has The attacker can send any message he has on any channel he has Clauses for equality The attacker can do communications Check communications do not reveal secrets Global translation Phase coded by unary predicates Phase coded by binary predicates Knowing the free names and creating new names is necessary only in phase 0. The subsequent phases will get them by attacker'_i(x,y) -> attacker'_{i+1}(x,y) The attacker has the public free names The attacker can create new names Rules that derive bad are necessary only in the last phase. Previous phases will get them by attacker'_i(x,y) -> attacker'_{i+1}(x,y) The attacker can perform equality tests For attacker: not declarations, the not declaration is also valid in previous phases, because of the implication attacker_p(i):x => attacker_p(i+1):x Furthermore, we have to translate unary to binary not declarations Phase coded by unary predicate, since it does not use choice Phase coded by binary predicate translate unary to binary not declarations Phase coded by unary predicate, since it does not use choice Phase coded by binary predicate translate unary to binary nounif declarations Phase coded by unary predicate, since it does not use choice Phase coded by binary predicate Phase coded by unary predicate, since it does not use choice Phase coded by binary predicate
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * and * * * * Copyright ( C ) INRIA , LIENS , 2000 - 2009 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cryptographic protocol verifier * * * * Bruno Blanchet and Xavier Allamigeon * * * * Copyright (C) INRIA, LIENS, MPII 2000-2009 * * * *************************************************************) 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 ( in file LICENSE ) . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA This 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 (in file LICENSE). 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 *) open Parsing_helper open Types open Pitypes let rec has_choice = function Var _ -> false | FunApp(f,l) -> (f.f_cat == Choice) || (List.exists has_choice l) let min_choice_phase = ref max_int let rec find_min_choice_phase current_phase = function Nil -> () | Par(p,q) -> find_min_choice_phase current_phase p; find_min_choice_phase current_phase q | Repl (p,_) -> find_min_choice_phase current_phase p | Restr(n,p) -> find_min_choice_phase current_phase p | Test(t1,t2,p,q,_) -> if has_choice t1 || has_choice t2 then begin if current_phase < !min_choice_phase then min_choice_phase := current_phase end; find_min_choice_phase current_phase p; find_min_choice_phase current_phase q | Input(tc,pat,p,_) -> if has_choice tc then begin if current_phase < !min_choice_phase then min_choice_phase := current_phase end; find_min_choice_phase current_phase p | Output(tc,t,p,_) -> if has_choice tc || has_choice t then begin if current_phase < !min_choice_phase then min_choice_phase := current_phase end; find_min_choice_phase current_phase p | Let(pat,t,p,q,_) -> if has_choice t then begin if current_phase < !min_choice_phase then min_choice_phase := current_phase end; find_min_choice_phase current_phase p; find_min_choice_phase current_phase q | LetFilter(vlist,f,p,q,_) -> user_error "Predicates are currently incompatible with non-interference.\n" | Event(_,p,_) -> find_min_choice_phase current_phase p | Insert(_,p,_) -> find_min_choice_phase current_phase p | Get(_,_,p,_) -> find_min_choice_phase current_phase p | Phase(n,p) -> find_min_choice_phase n p let nrule = ref 0 let red_rules = ref ([] : reduction list) let mergelr = function Pred(p,[t1;t2]) as x -> begin match p.p_info with [AttackerBin(i,t)] -> if i >= (!min_choice_phase) then x else let att1_i = Param.get_pred (Attacker(i,t)) in Terms.unify t1 t2; Pred(att1_i, [t1]) | [TableBin(i)] -> if i >= (!min_choice_phase) then x else let tbl1_i = Param.get_pred (Table(i)) in Terms.unify t1 t2; Pred(tbl1_i, [t1]) | [InputPBin(i)] -> if i >= (!min_choice_phase) then x else let input1_i = Param.get_pred (InputP(i)) in Terms.unify t1 t2; Pred(input1_i, [t1]) | [OutputPBin(i)] -> if i >= (!min_choice_phase) then x else let output1_i = Param.get_pred (OutputP(i)) in Terms.unify t1 t2; Pred(output1_i, [t1]) | _ -> x end | Pred(p,[t1;t2;t3;t4]) as x -> begin match p.p_info with [MessBin(i,t)] -> if i >= (!min_choice_phase) then x else let mess1_i = Param.get_pred (Mess(i,t)) in Terms.unify t1 t3; Terms.unify t2 t4; Pred(mess1_i, [t1;t2]) | _ -> x end | x -> x let add_rule hyp concl constra tags = if !min_choice_phase > 0 then begin if !Terms.current_bound_vars != [] then Parsing_helper.internal_error "bound vars should be cleaned up (pitranslweak4)"; try let hyp' = List.map mergelr hyp in let concl' = mergelr concl in let hyp'' = List.map Terms.copy_fact2 hyp' in let concl'' = Terms.copy_fact2 concl' in let constra'' = List.map Terms.copy_constra2 constra in let tags'' = match tags with ProcessRule _ -> Parsing_helper.internal_error "ProcessRule should not be generated by pitranslweak" | ProcessRule2(hsl, nl1, nl2) -> ProcessRule2(hsl, List.map Terms.copy_term2 nl1, List.map Terms.copy_term2 nl2) | x -> x in Terms.cleanup(); let constra'' = Rules.simplify_constra_list (concl''::hyp'') constra'' in red_rules := (hyp'', concl'', Rule (!nrule, tags'', hyp'', concl'', constra''), constra'') :: (!red_rules); incr nrule with Terms.Unify -> Terms.cleanup() | Rules.FalseConstraint -> () end else begin red_rules := (hyp, concl, Rule (!nrule, tags, hyp, concl, constra), constra) :: (!red_rules); incr nrule end type transl_state = last_step_unif_left : (term * term) list; last_step_unif_right : (term * term) list; Unifications to do for the last group of destructor applications . last_step_unif will be appended to before emitting clauses . The separation between last_step_unif and is useful only for non - interference . last_step_unif will be appended to unif before emitting clauses. The separation between last_step_unif and unif is useful only for non-interference. *) success_conditions_left : (term * term) list list ref option; success_conditions_right : (term * term) list list ref option; name_params_right : term list; name_params_meaning : string list; repl_count : int; input_pred : predicate; output_pred : predicate; hyp_tags : hypspec list } let att_fact phase t1 t2 = Pred(Param.get_pred (AttackerBin(phase, Terms.get_term_type t1)), [t1; t2]) let mess_fact phase tc1 tm1 tc2 tm2 = Pred(Param.get_pred (MessBin(phase, Terms.get_term_type tm1)), [tc1;tm1;tc2;tm2]) let table_fact phase t1 t2 = Pred(Param.get_pred (TableBin(phase)), [t1;t2]) let output_rule { hypothesis = prev_input; constra = constra; unif = unif; last_step_unif_left = lsu_l; last_step_unif_right = lsu_r; name_params_left = name_params_left; name_params_right = name_params_right; hyp_tags = hyp_tags } out_fact = try if (lsu_l != []) || (lsu_r != []) then Parsing_helper.internal_error "last_step_unif should have been appended to unif"; if !Terms.current_bound_vars != [] then Parsing_helper.internal_error "bound vars should be cleaned up (pitranslweak2)"; List.iter (fun (p1,p2) -> Terms.unify p1 p2) unif; let hyp = List.map Terms.copy_fact2 prev_input in let concl = Terms.copy_fact2 out_fact in let constra2 = List.map Terms.copy_constra2 constra in let name_params_left2 = List.map Terms.copy_term2 name_params_left in let name_params_right2 = List.map Terms.copy_term2 name_params_right in Terms.cleanup(); begin try add_rule hyp concl (Rules.simplify_constra_list (concl::hyp) constra2) (ProcessRule2(hyp_tags, name_params_left2, name_params_right2)) with Rules.FalseConstraint -> () end with Terms.Unify -> Terms.cleanup() let start_destructor_group next_f occ cur_state = if (cur_state.last_step_unif_left != []) || (cur_state.last_step_unif_right != []) then Parsing_helper.internal_error "last_step_unif should have been appended to unif (start_destructor_group)"; let sc_left = ref [] in let sc_right = ref [] in next_f { cur_state with success_conditions_left = Some sc_left; success_conditions_right = Some sc_right }; if List.memq [] (!sc_left) && List.memq [] (!sc_right) then begin [[]] end else begin Get all vars in cur_state.hypothesis/unif/constra let var_list = ref [] in List.iter (Terms.get_vars_fact var_list) cur_state.hypothesis; List.iter (fun (t1,t2) -> Terms.get_vars var_list t1; Terms.get_vars var_list t2) cur_state.unif; List.iter (List.iter (Terms.get_vars_constra var_list)) cur_state.constra; all vars not in cur_state.hypothesis/unif/constra let l_l = List.map (List.map (fun (t1,t2) -> Neq(Terms.generalize_vars_not_in (!var_list) t1, Terms.generalize_vars_not_in (!var_list) t2))) (!sc_left) in let l_r = List.map (List.map (fun (t1,t2) -> Neq(Terms.generalize_vars_not_in (!var_list) t1, Terms.generalize_vars_not_in (!var_list) t2))) (!sc_right) in Terms.cleanup(); if cur_state.cur_phase >= !min_choice_phase then begin List.iter (fun u_left -> output_rule { cur_state with unif = u_left @ cur_state.unif; constra = l_r @ cur_state.constra; hyp_tags = TestUnifTag2(occ):: cur_state.hyp_tags } (Pred(Param.bad_pred, [])) ) (!sc_left); List.iter (fun u_right -> output_rule { cur_state with unif = u_right @ cur_state.unif; constra = l_l @ cur_state.constra; hyp_tags = TestUnifTag2(occ):: cur_state.hyp_tags } (Pred(Param.bad_pred, [])) ) (!sc_right) end; l_l @ l_r end let start_destructor_group_i next_f occ cur_state = ignore (start_destructor_group next_f occ cur_state) let end_destructor_group next_f cur_state = next_f { cur_state with unif = cur_state.last_step_unif_right @ cur_state.last_step_unif_left @ cur_state.unif; last_step_unif_left = []; last_step_unif_right = []; success_conditions_left = None; success_conditions_right = None }; begin match cur_state.success_conditions_left with None -> internal_error "Group ended but not started" | Some r -> r:= cur_state.last_step_unif_left :: (!r) end; begin match cur_state.success_conditions_right with None -> internal_error "Group ended but not started" | Some r -> r:= cur_state.last_step_unif_right :: (!r) end next_f takes a state and two patterns as parameter let rec transl_term next_f cur_state = function Var v -> begin match v.link with TLink (FunApp(_, [t1;t2])) -> next_f cur_state t1 t2 | _ -> internal_error "unexpected link in transl_term" end | FunApp(f,l) -> let transl_red red_rules = transl_term_list (fun cur_state1 patlist1 patlist2 -> if cur_state.cur_phase < !min_choice_phase then List.iter (fun red_rule -> let (left_list1, right1) = Terms.copy_red red_rule in let (left_list2, right2) = Terms.copy_red red_rule in next_f { cur_state1 with last_step_unif_left = List.fold_left2(fun accu_unif pat left -> (pat,left)::accu_unif) cur_state1.last_step_unif_left patlist1 left_list1; last_step_unif_right = List.fold_left2(fun accu_unif pat left -> (pat,left)::accu_unif) cur_state1.last_step_unif_right patlist2 left_list2} right1 right2 ) red_rules else List.iter (fun red_rule1 -> List.iter (fun red_rule2 -> let (left_list1, right1) = Terms.copy_red red_rule1 in let (left_list2, right2) = Terms.copy_red red_rule2 in next_f { cur_state1 with last_step_unif_left = List.fold_left2(fun accu_unif pat left -> (pat,left)::accu_unif) cur_state1.last_step_unif_left patlist1 left_list1; last_step_unif_right = List.fold_left2(fun accu_unif pat left -> (pat,left)::accu_unif) cur_state1.last_step_unif_right patlist2 left_list2} right1 right2 ) red_rules ) red_rules ) cur_state l in match f.f_cat with Name n -> begin match n.prev_inputs with Some (FunApp(_, [t1;t2])) -> next_f cur_state t1 t2 | _ -> internal_error "unexpected prev_inputs in transl_term" end | Tuple -> transl_term_list (fun cur_state1 patlist1 patlist2 -> next_f cur_state1 (FunApp(f, patlist1)) (FunApp(f, patlist2))) cur_state l | Eq red_rules -> let vars1 = Terms.var_gen (fst f.f_type) in transl_red ((vars1, FunApp(f, vars1)) :: red_rules) | Red red_rules -> transl_red red_rules | Choice -> begin match l with [t1;t2] -> transl_term (fun cur_state1 t11 t12 -> transl_term (fun cur_state2 t21 t22 -> next_f { cur_state2 with last_step_unif_left = cur_state1.last_step_unif_left } t11 t22 ) { cur_state1 with last_step_unif_right = cur_state.last_step_unif_right } t2 ) cur_state t1 | _ -> Parsing_helper.internal_error "Choice should have two arguments" end | _ -> Parsing_helper.internal_error "function symbols of these categories should not appear in input terms" next_f takes a state and two lists of patterns as parameter and transl_term_list next_f cur_state = function [] -> next_f cur_state [] [] | (a::l) -> transl_term (fun cur_state1 p1 p2 -> transl_term_list (fun cur_state2 patlist1 patlist2 -> next_f cur_state2 (p1::patlist1) (p2::patlist2)) cur_state1 l) cur_state a let rec check_several_types = function Var _ -> false | FunApp(f,l) -> (List.exists check_several_types l) || (if !Param.eq_in_names then match f.f_cat with Red rules -> List.length rules > 1 | Eq rules -> List.length rules > 0 | _ -> false else match f.f_initial_cat with Red rules -> List.length rules > 1 | _ -> false) let transl_term_incl_destructor f t cur_state = let may_have_several_types = check_several_types t in transl_term (fun cur_state1 pat1 pat2 -> if may_have_several_types then f pat1 pat2 { cur_state1 with name_params_left = pat1::cur_state1.name_params_left; name_params_right = pat2::cur_state1.name_params_right; name_params_meaning = "" :: cur_state1.name_params_meaning } else f pat1 pat2 cur_state1 ) cur_state t let transl_term_list_incl_destructor f tl cur_state = let may_have_several_types = List.exists check_several_types tl in transl_term_list ( fun cur_state1 if then f patlist1 patlist2 { cur_state1 with name_params_left = patlist1 @ cur_state1.name_params_left ; name_params_right = patlist2 @ ; name_params_meaning = ( List.map ( fun _ - > " " ) patlist1 ) @ cur_state1.name_params_meaning } else f patlist1 patlist2 cur_state1 ) cur_state tl let transl_term_list_incl_destructor f tl cur_state = let may_have_several_types = List.exists check_several_types tl in transl_term_list (fun cur_state1 patlist1 patlist2 -> if may_have_several_types then f patlist1 patlist2 { cur_state1 with name_params_left = patlist1 @ cur_state1.name_params_left; name_params_right = patlist2 @ cur_state1.name_params_right; name_params_meaning = (List.map (fun _ -> "") patlist1) @ cur_state1.name_params_meaning } else f patlist1 patlist2 cur_state1 ) cur_state tl *) let rec transl_pat put_var f pat pat1' pat2' cur_state = match pat with PatVar b -> b.link <- TLink (FunApp(Param.choice_fun b.btype, [pat1'; pat2'])); f (if put_var then { cur_state with name_params_left = pat1' :: cur_state.name_params_left; name_params_right = pat2' :: cur_state.name_params_right; name_params_meaning = b.sname :: cur_state.name_params_meaning } else cur_state); b.link <- NoLink | PatTuple (fsymb,patlist) -> let patlist1' = List.map Reduction_helper.new_var_pat patlist in let patlist2' = List.map Reduction_helper.new_var_pat patlist in let pat21 = FunApp(fsymb, patlist1') in let pat22 = FunApp(fsymb, patlist2') in transl_pat_list put_var f patlist patlist1' patlist2' { cur_state with last_step_unif_left = (pat1', pat21)::cur_state.last_step_unif_left; last_step_unif_right = (pat2', pat22)::cur_state.last_step_unif_right }; | PatEqual t -> transl_term_incl_destructor (fun pat1 pat2 cur_state -> f { cur_state with last_step_unif_left = (pat1,pat1')::cur_state.last_step_unif_left; last_step_unif_right = (pat2,pat2')::cur_state.last_step_unif_right; } ) t cur_state and transl_pat_list put_var f patlist patlist1' patlist2' cur_state = match (patlist, patlist1', patlist2') with ([],[],[]) -> f cur_state | (p::pl, p1'::pl1', p2'::pl2') -> transl_pat_list put_var (transl_pat put_var f p p1' p2') pl pl1' pl2' cur_state | _ -> internal_error "not same length in transl_pat_list" Translate process let rec transl_process cur_state = function Nil -> () | Par(p,q) -> transl_process cur_state p; transl_process cur_state q | Repl (p,occ) -> let v1 = Terms.new_var "sid" Param.sid_type in transl_process { cur_state with repl_count = cur_state.repl_count + 1; name_params_left = (Var v1) :: cur_state.name_params_left; name_params_right = (Var v1) :: cur_state.name_params_right; name_params_meaning = ("!" ^ (string_of_int (cur_state.repl_count+1))) :: cur_state.name_params_meaning; hyp_tags = (ReplTag(occ, List.length cur_state.name_params_left)) :: cur_state.hyp_tags } p | Restr(n,p) -> begin match n.f_cat with Name r -> let ntype = List.map Terms.get_term_type cur_state.name_params_left in if fst n.f_type == Param.tmp_type then begin n.f_type <- ntype, snd n.f_type; r.prev_inputs_meaning <- cur_state.name_params_meaning end else if not (Terms.eq_lists (fst n.f_type) ntype) then internal_error ("Name " ^ n.f_name ^ " has bad arity"); r.prev_inputs <- Some (FunApp(Param.choice_fun (snd n.f_type), [ FunApp(n, cur_state.name_params_left); FunApp(n, cur_state.name_params_right)])); transl_process cur_state p; r.prev_inputs <- None | _ -> internal_error "A restriction should have a name as parameter" end | Test(t1,t2,p,q,occ) -> start_destructor_group_i (fun cur_state -> transl_term_incl_destructor (fun pat1_l pat1_r cur_state1 -> transl_term_incl_destructor (fun pat2_l pat2_r cur_state2 -> end_destructor_group (fun cur_state3 -> output_rule { cur_state3 with unif = (pat1_l, pat2_l) :: cur_state3.unif; constra = [Neq(pat1_r,pat2_r)] :: cur_state3.constra; hyp_tags = TestUnifTag2(occ) :: cur_state3.hyp_tags } (Pred(Param.bad_pred, [])); output_rule { cur_state3 with unif = (pat1_r, pat2_r) :: cur_state3.unif; constra = [Neq(pat1_l,pat2_l)] :: cur_state3.constra; hyp_tags = TestUnifTag2(occ) :: cur_state3.hyp_tags } (Pred(Param.bad_pred, [])); transl_process { cur_state3 with unif = (pat1_l,pat2_l) :: (pat2_r,pat2_r) :: cur_state3.unif; hyp_tags = (TestTag occ) :: cur_state3.hyp_tags } p; transl_process { cur_state3 with constra = [Neq(pat1_l, pat2_l)] :: [Neq(pat1_r,pat2_r)] :: cur_state3.constra; hyp_tags = (TestTag occ) :: cur_state3.hyp_tags } q ) cur_state2 ) t2 cur_state1 ) t1 cur_state ) occ cur_state | Input(tc,pat,p,occ) -> let v1 = Reduction_helper.new_var_pat pat in let v2 = Reduction_helper.new_var_pat pat in begin match tc with FunApp({ f_cat = Name _; f_private = false },_) when !Param.active_attacker -> start_destructor_group_i (fun cur_state -> transl_pat true ( end_destructor_group (fun cur_state1 -> transl_process cur_state1 p) ) pat v1 v2 { cur_state with hypothesis = (att_fact cur_state.cur_phase v1 v2) :: cur_state.hypothesis; hyp_tags = (InputTag(occ)) :: cur_state.hyp_tags } ) occ cur_state When the channel is a public name , and the same name a on both sides , generating h - > input2 : a , a is useless since attacker2 : a , a and attacker2 :x , x ' - > input2 :x , x ' generating h -> input2:a,a is useless since attacker2:a,a and attacker2:x,x' -> input2:x,x' *) | _ -> start_destructor_group_i (fun cur_state -> transl_term_incl_destructor (fun pat1 pat2 cur_state1 -> end_destructor_group (fun cur_state2 -> start_destructor_group_i (fun cur_state2 -> transl_pat true (end_destructor_group (fun cur_state3 -> transl_process cur_state3 p)) pat v1 v2 { cur_state2 with hypothesis = (mess_fact cur_state.cur_phase pat1 v1 pat2 v2) :: cur_state2.hypothesis; hyp_tags = (InputTag(occ)) :: cur_state2.hyp_tags }; output_rule { cur_state2 with hyp_tags = (InputPTag(occ)) :: cur_state2.hyp_tags } (Pred(cur_state.input_pred, [pat1; pat2])) ) occ cur_state2 ) cur_state1 ) tc cur_state ) occ cur_state end | Output(tc,t,p,occ) -> begin match tc with FunApp({ f_cat = Name _; f_private = false },_) when !Param.active_attacker -> start_destructor_group_i (fun cur_state -> transl_term (fun cur_state1 pat1 pat2 -> end_destructor_group (fun cur_state2 -> output_rule { cur_state2 with hyp_tags = (OutputTag occ) :: cur_state2.hyp_tags } (att_fact cur_state.cur_phase pat1 pat2) ) cur_state1 ) cur_state t ) occ cur_state | _ -> start_destructor_group_i (fun cur_state -> transl_term (fun cur_state1 patc1 patc2 -> transl_term (fun cur_state2 pat1 pat2 -> end_destructor_group (fun cur_state3 -> output_rule { cur_state3 with hyp_tags = (OutputPTag occ) :: cur_state3.hyp_tags } (Pred(cur_state.output_pred, [patc1; patc2])); output_rule { cur_state3 with hypothesis = cur_state3.hypothesis; hyp_tags = (OutputTag occ) :: cur_state2.hyp_tags } (mess_fact cur_state.cur_phase patc1 pat1 patc2 pat2) ) cur_state2 ) cur_state1 t ) cur_state tc ) occ cur_state end; transl_process { cur_state with hyp_tags = (OutputTag occ) :: cur_state.hyp_tags } p | Let(pat,t,p,p',occ) -> let failure_conditions = start_destructor_group (fun cur_state -> transl_term_incl_destructor (fun pat1 pat2 cur_state1 -> transl_pat false (end_destructor_group (fun cur_state2 -> transl_process cur_state2 p)) pat pat1 pat2 cur_state1 ) t cur_state ) occ { cur_state with hyp_tags = (LetTag occ) :: cur_state.hyp_tags } in transl_process { cur_state with constra = failure_conditions @ cur_state.constra; hyp_tags = (LetTag occ) :: cur_state.hyp_tags } p' | LetFilter(vlist,f,p,q,occ) -> user_error "Predicates are currently incompatible with non-interference.\n" | Event(_, p, _) -> transl_process cur_state p | Insert(t,p,occ) -> start_destructor_group_i (fun cur_state -> transl_term (fun cur_state1 pat1 pat2 -> end_destructor_group (fun cur_state2 -> output_rule { cur_state2 with hyp_tags = (InsertTag occ) :: cur_state2.hyp_tags } (table_fact cur_state.cur_phase pat1 pat2) ) cur_state1 ) cur_state t ) occ cur_state; transl_process { cur_state with hyp_tags = (InsertTag occ) :: cur_state.hyp_tags } p | Get(pat,t,p,occ) -> let v1 = Reduction_helper.new_var_pat pat in let v2 = Reduction_helper.new_var_pat pat in start_destructor_group_i (fun cur_state -> transl_pat true (fun cur_state1 -> transl_term (fun cur_state2 patt1 patt2 -> end_destructor_group (fun cur_state3 -> transl_process cur_state3 p) { cur_state2 with last_step_unif_left = (patt1, FunApp(Terms.true_cst, [])) :: cur_state2.last_step_unif_left; last_step_unif_right = (patt2, FunApp(Terms.true_cst, [])) :: cur_state2.last_step_unif_right } ) cur_state1 t ) pat v1 v2 { cur_state with hypothesis = (table_fact cur_state.cur_phase v1 v2) :: cur_state.hypothesis; hyp_tags = (GetTag(occ)) :: cur_state.hyp_tags } ) occ cur_state | Phase(n,p) -> transl_process { cur_state with input_pred = Param.get_pred (InputPBin(n)); output_pred = Param.get_pred (OutputPBin(n)); cur_phase = n } p let rules_for_red f phase red_rules = let res_pred = Param.get_pred (AttackerBin(phase, snd f.f_type)) in if phase < !min_choice_phase then List.iter (fun red1 -> let (hyp1, concl1) = Terms.copy_red red1 in add_rule (List.map (fun t -> att_fact phase t t) hyp1) (att_fact phase concl1 concl1) [] (Apply(Func(f), res_pred)) ) red_rules else List.iter (fun red1 -> List.iter (fun red2 -> let (hyp1, concl1) = Terms.copy_red red1 in let (hyp2, concl2) = Terms.copy_red red2 in add_rule (List.map2 (att_fact phase) hyp1 hyp2) (att_fact phase concl1 concl2) [] (Apply(Func(f), res_pred)) ) red_rules ) red_rules let rules_for_function phase _ f = if not f.f_private then let res_pred = Param.get_pred (AttackerBin(phase, snd f.f_type)) in match f.f_cat with Eq red_rules -> let vars1 = Terms.var_gen (fst f.f_type) in rules_for_red f phase ((vars1, FunApp(f, vars1)) :: red_rules) | Red red_rules -> rules_for_red f phase red_rules; List.iter (fun red -> let (hyp, _) = Terms.copy_red red in let vlist = List.map Terms.new_var_def (List.map Terms.get_term_type hyp) in let make_constra red = let (hyp, _) = Terms.copy_red red in if !Terms.current_bound_vars != [] then Parsing_helper.internal_error "bound vars should be cleaned up (pitranslweak3)"; let hyp' = List.map (Terms.generalize_vars_not_in []) hyp in Terms.cleanup(); List.map2 (fun v t -> Neq(v,t)) vlist hyp' in add_rule (List.map2 (att_fact phase) hyp vlist) (Pred(Param.bad_pred, [])) (List.map make_constra red_rules) (TestApply(Func(f), res_pred)); let (hyp, _) = Terms.copy_red red in let vlist = List.map Terms.new_var_def (List.map Terms.get_term_type hyp) in let make_constra red = let (hyp, _) = Terms.copy_red red in if !Terms.current_bound_vars != [] then Parsing_helper.internal_error "bound vars should be cleaned up (pitranslweak3)"; let hyp' = List.map (Terms.generalize_vars_not_in []) hyp in Terms.cleanup(); List.map2 (fun v t -> Neq(v,t)) vlist hyp' in add_rule (List.map2 (att_fact phase) vlist hyp) (Pred(Param.bad_pred, [])) (List.map make_constra red_rules) (TestApply(Func(f), res_pred)) ) red_rules | Tuple -> let vars1 = Terms.var_gen (fst f.f_type) in let vars2 = Terms.var_gen (fst f.f_type) in add_rule (List.map2 (att_fact phase) vars1 vars2) (att_fact phase (FunApp(f, vars1)) (FunApp(f, vars2))) [] (Apply(Func(f), res_pred)); for n = 0 to (List.length (fst f.f_type))-1 do let vars1 = Terms.var_gen (fst f.f_type) in let vars2 = Terms.var_gen (fst f.f_type) in let v1 = List.nth vars1 n in let v2 = List.nth vars2 n in add_rule [att_fact phase (FunApp(f, vars1)) (FunApp(f, vars2))] (att_fact phase v1 v2) [] (Apply(Proj(f,n),res_pred)) done; let vars1 = Terms.var_gen (fst f.f_type) in let v = Terms.new_var_def (snd f.f_type) in let gvars1 = List.map (fun ty -> FunApp(Terms.new_gen_var ty,[])) (fst f.f_type) in add_rule [att_fact phase (FunApp(f, vars1)) v] (Pred(Param.bad_pred, [])) [[Neq(v, FunApp(f, gvars1))]] (TestApply(Proj(f,0),res_pred)); let vars1 = Terms.var_gen (fst f.f_type) in let v = Terms.new_var_def (snd f.f_type) in let gvars1 = List.map (fun ty -> FunApp(Terms.new_gen_var ty,[])) (fst f.f_type) in add_rule [att_fact phase v (FunApp(f, vars1))] (Pred(Param.bad_pred, [])) [[Neq(v, FunApp(f, gvars1))]] (TestApply(Proj(f,0),res_pred)) | _ -> () let transl_attacker phase = Hashtbl.iter (rules_for_function phase) Param.fun_decls; Hashtbl.iter (rules_for_function phase) Terms.tuple_table; List.iter (fun t -> let att_pred = Param.get_pred (AttackerBin(phase,t)) in let mess_pred = Param.get_pred (MessBin(phase,t)) in let v1 = Terms.new_var_def t in let vc1 = Terms.new_var_def Param.channel_type in let v2 = Terms.new_var_def t in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(mess_pred, [vc1; v1; vc2; v2]); att_fact phase vc1 vc2] (Pred(att_pred, [v1; v2])) [] (Rl(att_pred, mess_pred)); if (!Param.active_attacker) then begin let v1 = Terms.new_var_def t in let vc1 = Terms.new_var_def Param.channel_type in let v2 = Terms.new_var_def t in let vc2 = Terms.new_var_def Param.channel_type in add_rule [att_fact phase vc1 vc2; Pred(att_pred, [v1; v2])] (Pred(mess_pred, [vc1; v1; vc2; v2])) [] (Rs(att_pred, mess_pred)) end; let v = Terms.new_var_def t in add_rule [] (Pred(Param.get_pred (Equal(t)), [v;v])) [] LblEq ) (if !Param.ignore_types then [Param.any_type] else !Param.all_types); if phase >= !min_choice_phase then begin let att_pred = Param.get_pred (AttackerBin(phase,Param.channel_type)) in let input_pred = Param.get_pred (InputPBin(phase)) in let output_pred = Param.get_pred (OutputPBin(phase)) in let vc1 = Terms.new_var_def Param.channel_type in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(att_pred, [vc1; vc2])] (Pred(input_pred, [vc1;vc2])) [] (Ri(att_pred, input_pred)); let vc1 = Terms.new_var_def Param.channel_type in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(att_pred, [vc1; vc2])] (Pred(output_pred, [vc1; vc2])) [] (Ro(att_pred, output_pred)); let vc = Terms.new_var_def Param.channel_type in let vc1 = Terms.new_var_def Param.channel_type in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(input_pred, [vc; vc1]); Pred(output_pred, [vc; vc2])] (Pred(Param.bad_pred, [])) [[Neq(vc1,vc2)]] (TestComm(input_pred, output_pred)); let vc = Terms.new_var_def Param.channel_type in let vc1 = Terms.new_var_def Param.channel_type in let vc2 = Terms.new_var_def Param.channel_type in add_rule [Pred(input_pred, [vc1; vc]); Pred(output_pred, [vc2; vc])] (Pred(Param.bad_pred, [])) [[Neq(vc1,vc2)]] (TestComm(input_pred, output_pred)) end let transl p = Rules.reset (); Reduction_helper.main_process := p; nrule := 0; red_rules := []; List.iter ( fun ( hyp1 , , , tag1 ) - > TermsEq.close_rule_destr_eq ( fun ( hyp , concl , constra ) - > add_rule hyp concl constra tag1 ) ( hyp1 , , constra1 ) ) ( ! Pisyntax.red_rules ) ; List.iter (fun (hyp1, concl1, constra1, tag1) -> TermsEq.close_rule_destr_eq (fun (hyp, concl, constra) -> add_rule hyp concl constra tag1) (hyp1, concl1, constra1)) (!Pisyntax.red_rules); *) find_min_choice_phase 0 p; Reduction_helper.min_choice_phase := !min_choice_phase; Initialize the selection function . In particular , when there is a predicate member :x , y - > member :x , cons(z , y ) we would like , y It is important to initialize this very early , so that the simplification of the initial rules is performed with the good selection function . In particular, when there is a predicate member:x,y -> member:x,cons(z,y) we would like nounif member:*x,y It is important to initialize this very early, so that the simplification of the initial rules is performed with the good selection function. *) List.iter (fun r -> ignore(Selfun.selection_fun r)) (!red_rules); for i = 0 to !Param.max_used_phase do transl_attacker i; List.iter (fun t -> let att_i = Param.get_pred (AttackerBin(i,t)) in if i < !min_choice_phase then begin let v = Terms.new_var Param.def_var_name t in let att_i = Param.get_pred (Attacker(i,t)) in Selfun.add_no_unif (att_i, [FVar v]) Selfun.never_select_weight end else begin let v1 = Terms.new_var Param.def_var_name t in let v2 = Terms.new_var Param.def_var_name t in Selfun.add_no_unif (att_i, [FVar v1; FVar v2]) Selfun.never_select_weight end; if i > 0 then let w1 = Terms.new_var_def t in let w2 = Terms.new_var_def t in let att_im1 = Param.get_pred (AttackerBin(i-1,t)) in add_rule [Pred(att_im1, [w1; w2])] (Pred(att_i, [w1; w2])) [] PhaseChange ) (if !Param.ignore_types || !Param.untyped_attacker then [Param.any_type] else !Param.all_types); if i > 0 then let w1 = Terms.new_var_def Param.table_type in let w2 = Terms.new_var_def Param.table_type in let tbl_i = Param.get_pred (TableBin(i)) in let tbl_im1 = Param.get_pred (TableBin(i-1)) in add_rule [Pred(tbl_im1, [w1; w2])] (Pred(tbl_i, [w1; w2])) [] TblPhaseChange done; List.iter (fun ch -> if not ch.f_private then add_rule [] (att_fact 0 (FunApp(ch, [])) (FunApp(ch, []))) [] Init) (!Param.freenames); List.iter (fun t -> let v1 = Terms.new_var_def Param.sid_type in let new_name_fun = Terms.new_name_fun t in add_rule [] (att_fact 0 (FunApp(new_name_fun, [v1])) (FunApp(new_name_fun, [v1]))) [] (Rn (Param.get_pred (AttackerBin(0, t)))); let att_pred = Param.get_pred (AttackerBin(!Param.max_used_phase, t)) in let v1 = Terms.new_var_def t in let v2 = Terms.new_var_def t in let v3 = Terms.new_var_def t in add_rule [Pred(att_pred, [v1; v2]); Pred(att_pred, [v1; v3])] (Pred(Param.bad_pred, [])) [[Neq(v2,v3)]] (TestEq(att_pred)); let v1 = Terms.new_var_def t in let v2 = Terms.new_var_def t in let v3 = Terms.new_var_def t in add_rule [Pred(att_pred, [v2; v1]); Pred(att_pred, [v3; v1])] (Pred(Param.bad_pred, [])) [[Neq(v2,v3)]] (TestEq(att_pred)) ) (if !Param.ignore_types || !Param.untyped_attacker then [Param.any_type] else !Param.all_types); List.iter (fun ch -> match ch.f_cat with Name r -> r.prev_inputs <- Some (FunApp(Param.choice_fun (snd ch.f_type), [FunApp(ch, []); FunApp(ch, [])])) | _ -> internal_error "should be a name 1") (!Param.freenames); transl_process { hypothesis = []; constra = []; unif = []; last_step_unif_left = []; last_step_unif_right = []; success_conditions_left = None; success_conditions_right = None; name_params_left = []; name_params_right = []; name_params_meaning = []; repl_count = 0; input_pred = Param.get_pred (InputPBin(0)); output_pred = Param.get_pred (OutputPBin(0)); cur_phase = 0; hyp_tags = [] } p; List.iter (fun ch -> match ch.f_cat with Name r -> r.prev_inputs <- None | _ -> internal_error "should be a name 2") (!Param.freenames); List.iter (function QFact({ p_info = [Attacker(i,ty)] },[t]) -> for j = 0 to i do if j < !min_choice_phase then let att_j = Param.get_pred (Attacker(j,ty)) in Rules.add_not(Pred(att_j,[t])) else let att2_j = Param.get_pred (AttackerBin(j,ty)) in Rules.add_not(Pred(att2_j,[t;t])) done | QFact({ p_info = [Mess(i,ty)] } as p,[t1;t2]) -> if i < !min_choice_phase then Rules.add_not(Pred(p, [t1;t2])) else let mess2_i = Param.get_pred (MessBin(i,ty)) in Rules.add_not(Pred(mess2_i,[t1;t2;t1;t2])) | _ -> Parsing_helper.user_error "The only allowed facts in \"not\" declarations are attacker: and mess: predicates (for process equivalences, user-defined predicates are forbidden)." ) (if !Param.typed_frontend then Pitsyntax.get_not() else Pisyntax.get_not()); List.iter (function (f,n) -> match f with ({ p_info = [Attacker(i,ty)] }, [t]) -> if i < !min_choice_phase then Selfun.add_no_unif f n else let att2_i = Param.get_pred (AttackerBin(i,ty)) in Selfun.add_no_unif (att2_i, [t;t]) n | ({ p_info = [Mess(i,ty)] }, [t1;t2]) -> if i < !min_choice_phase then Selfun.add_no_unif f n else let mess2_i = Param.get_pred (MessBin(i,ty)) in Selfun.add_no_unif (mess2_i,[t1;t2;t1;t2]) n | _ -> Parsing_helper.user_error "The only allowed facts in \"nounif\" declarations are attacker: and mess: predicates (for process equivalences, user-defined predicates are forbidden)." ) (if !Param.typed_frontend then Pitsyntax.get_nounif() else Pisyntax.get_nounif()); List.rev (!red_rules)
150ac9188c895d4d37e14e52a8176a2f6b7e4b2593bf32591c605ec5d24e5d39
epiccastle/spire
upload.clj
(ns spire.module.upload (:require [spire.output.core :as output] [spire.ssh :as ssh] [spire.facts :as facts] [spire.scp :as scp] [spire.utils :as utils] [spire.local :as local] [spire.state :as state] [spire.remote :as remote] [spire.compare :as compare] [spire.context :as context] [spire.module.attrs :as attrs] [clojure.java.io :as io] [clojure.string :as string])) (def debug false) (def failed-result {:exit 1 :out "" :err "" :result :failed}) (defn preflight [{:keys [src content dest owner group mode attrs dir-mode preserve recurse force] :as opts}] (or (facts/check-bins-present #{:scp}) (cond (not (or src content)) (assoc failed-result :exit 3 :err ":src or :content must be provided") (not dest) (assoc failed-result :exit 3 :err ":dest must be provided") (and src content) (assoc failed-result :exit 3 :err ":src and :content cannot both be specified") (and preserve (or mode dir-mode)) (assoc failed-result :exit 3 :err "when providing :preverse you cannot also specify :mode or :dir-mode") (and content (utils/content-recursive? content) (not recurse)) (assoc failed-result :exit 3 :err ":recurse must be true when :content specifies a directory.") (and src (utils/content-recursive? (io/file src)) (not recurse)) (assoc failed-result :exit 3 :err ":recurse must be true when :src specifies a directory.")))) (defn process-result [opts copy-result attr-result] (let [result {:result :failed :attr-result attr-result :copy-result copy-result}] (cond (= :failed (:result copy-result)) result (= :failed (:result attr-result)) result (or (= :changed (:result copy-result)) (= :changed (:result attr-result))) (assoc result :result :changed) (and (= :ok (:result copy-result)) (= :ok (:result attr-result))) (assoc result :result :ok) :else (dissoc result :result) ))) (defmacro scp-result [& body] `(let [res# (do ~@body)] (if res# {:result :changed} {:result :ok})) #_ (catch Exception e# {:result :failed :exception e#})) (defn process-md5-out ([line] (process-md5-out (facts/get-fact [:system :os]) line)) ([os line] (cond (#{:linux} os) (vec (string/split line #"\s+" 2)) :else (let [[_ filename hash] (re-matches #"MD5\s+\((.+)\)\s*=\s*([0-9a-fA-F]+)" line)] [hash filename]) ))) (utils/defmodule upload* [source-code-file form form-meta {:keys [src content dest owner group mode attrs dir-mode preserve recurse force] :as opts}] [host-config session {:keys [exec exec-fn sudo] :as shell-context}] (or (preflight opts) (let [run (fn [command] (let [{:keys [out exit err]} (exec-fn session "bash" command "UTF-8" {:sudo sudo})] #_(when debug (println "-------") (prn 'sudo sudo) (prn 'command command) (prn 'exit exit) (prn 'out out) (prn 'err err)) (if (zero? exit) (string/trim out) ""))) content? content ;; analyse local and remote paths local-file? (when-not content (local/is-file? src)) remote-file? (remote/is-file? run dest) remote-dir? (remote/is-dir? run dest) remote-writable? (if (not (string/ends-with? dest "/")) (remote/is-writable? run (utils/containing-folder dest)) (remote/is-writable? run dest)) content (or content (let [src-file (io/file src)] (if (.isAbsolute src-file) src-file (io/file (utils/current-file-parent) src)))) ] (cond (and (not force) (or local-file? content?) (not (string/ends-with? dest "/")) remote-dir?) {:result :failed :err ":src is a single file while :dest is a folder. Append '/' to dest to write into directory or set :force to true to delete destination folder and write as file." :exit 1 :out ""} (and recurse remote-file? (not force)) {:result :failed :err "Cannot copy :src directory over :dest. Destination is a file. Use :force to delete destination file and replace." :exit 1 :out ""} (not remote-writable?) {:result :failed :err "destination path :dest is unwritable" :exit 1 :out ""} :else (let [remote-file? (remote/is-file? run dest) transfers (compare/compare-full-info (str content) run dest #_(if local-file? dest (io/file dest (.getName (io/file (str content)))))) {:keys [local local-to-remote identical-content remote]} transfers total-size (if content? (utils/content-size content) (->> local-to-remote (map (comp :size local)) (apply +))) max-filename-length (if content? (count (utils/content-display-name content)) (->> local-to-remote (map (comp count #(.getName %) io/file :filename local)) (apply max 0))) progress-fn (fn [file bytes total frac context] (output/print-progress (context/deref* state/output-module) source-code-file form form-meta host-config (utils/progress-stats file bytes total frac total-size max-filename-length context) )) copied? (if recurse (let [identical-content (->> identical-content (map #(.getPath (io/file src %))) (into #{})) remote-folder-exists? (and (remote "") (= :dir (:type (remote "")))) ] (comment (prn "identical:" identical-content) (prn "local:" local) (prn "remote:" remote) (prn "lkeys:" (keys local))) (cond force (do (run (format "rm -rf \"%s\"" dest)) (scp-result (scp/scp-to session content dest :progress-fn progress-fn :preserve preserve :dir-mode (or dir-mode 0755) :mode (or mode 0644) :recurse true :skip-files #{} :exec exec :exec-fn exec-fn :sudo sudo ))) (not remote-file?) (scp-result (when (not= (count identical-content) (count (filter #(= :file (:type (second %))) local)) ) (scp/scp-to session (if remote-folder-exists? (mapv #(.getPath %) (.listFiles (io/file content))) content ) dest :progress-fn progress-fn :preserve preserve :dir-mode (or dir-mode 0755) :mode (or mode 0644) :recurse true :skip-files identical-content :exec exec :exec-fn exec-fn :sudo sudo ))))) ;; straight single copy (if content? ;; content upload (let [local-md5 (utils/md5 content) remote-md5 (some-> (facts/on-shell :csh (run (format "%s \"%s\"" (facts/md5) dest)) :else (run (format "%s \"%s\"" (facts/md5) dest))) process-md5-out first) ] (scp-result (when (not= local-md5 remote-md5) (scp/scp-content-to session content dest :progress-fn progress-fn :preserve preserve :dir-mode (or dir-mode 0755) :mode (or mode 0644) :exec exec :exec-fn exec-fn :sudo sudo )))) ;; file upload (let [local-md5 (utils/md5-file (.getPath content)) remote-md5 (some-> (facts/on-shell :csh (run (format "%s \"%s\"" (facts/md5) dest)) :else (run (format "%s \"%s\"" (facts/md5) dest))) process-md5-out first) _ ( println " l : " local - md5 " r : " remote - md5 ) ;; _ (do (println "\n\n\n")) ] (comment (prn "local-md5:" local-md5) (prn "remote-md5:" remote-md5)) (scp-result (when (not= local-md5 remote-md5) (scp/scp-to session [(.getPath content)] dest :progress-fn progress-fn :preserve preserve :dir-mode (or dir-mode 0755) :mode (or mode 0644) :exec exec :exec-fn exec-fn :sudo sudo )))))) passed-attrs? (or owner group dir-mode mode attrs) {:keys [exit err out]} (cond ;; generally we assume that if a copy happened, all attributes ;; and modes are correctly setup. (and (= :ok (:result copied?)) passed-attrs?) (attrs/set-attrs session {:path dest :owner owner :group group :mode (or mode 0644) :dir-mode (or dir-mode 0755) :attrs attrs :recurse recurse}) preserve (attrs/set-attrs-preserve session src dest))] (process-result opts copied? (cond (= 0 exit) {:result :ok} (= 255 exit) {:result :changed} (nil? exit) {:result :ok} :else {:result :failed :exit exit :err err :out out})))) ))) (defmacro upload "transfer files and directories from the local client to the remote machines. (upload options) given: `options`: A hashmap of options `:src` A path to a file or directory on the local machine `:content` Alternatively specify content to upload. Can be a string, a `java.io.File` instance or a `byte-array` `:dest` A remote path to copy the files into `:recurse` If the local path is a directory, recurse through all the file and directories `:preserve` Preserve the local files' modification flags when copying them to the remote filesystem `:dir-mode` If `:preserve` is `false`, this specifies the modification parameters created directories will have. `:mode` If `:preserve` is `false`, this specifies the modification parameters of copied files. `:owner` If specified the local files and directories will be owned by this user. `:group` If specified the local files and directories will be owned by this group. `:force` Force the copy operation to overwrite incompatible content. Such as a file upload overwriting a directory or a directory copy overwriting a file. `:attrs` Set the file or files special attributes. Provided as a string that is accepted to the chattr shell command. " [& args] `(utils/wrap-report ~&form (upload* ~(utils/current-file) (quote ~&form) ~(meta &form) ~@args))) (def documentation { :module "upload" :blurb "upload files to remote systems" :description [ "This module uploads files from the local machine to the remote machine." "Files are verified with md5 checksums before transfer and files that are already present and intact on the remote machine are not recopied." "Use the download module to gather files from remote filesystem to the local machine."] :form "(upload options)" :args [{:arg "options" :desc "A hashmap of options. All available option keys and their values are described below"}] :opts [[:src {:description ["A path to a file or directory on the local machine that you want to copy to the remote machine." "If this option is specified then `:content` cannot be specified." "If this path is a directory the `:recurse` must be true."] :type :string}] [:content {:description ["Some content to upload to a file. Can be a `String`, a `java.io.File` object or a `byte array`." "If this option is specified then `:src` cannot be specified." ] :type [:string :bytearray :file]}] [:dest {:description ["The destination path to copy the file or directory into." "If :recurse is true and :dest path ends in a slash; indicates that destination is a directory and the contents of :src are to be copied into the directory." "If :recurse is true and :dest path does not end in a slash; indicates that the :src directory is to be copies as the specified path."] :type :string}] [:owner {:description ["Make the destination file or files owned by this user." "Can be specified as a username or as a uid."] :type [:integer :string]}] [:group {:description ["Make the destination file or files owned by this group." "Can be specified as a group name or as a gid."] :type [:integer :string]}] [:mode {:description ["Set the access mode of this file or files." "Can be specified as an octal value of the form 0xxx, as a decimal value, or as a change string as is accepted by the system chmod command (eg. \"u+rwx\")."] :type [:integer :string]}] [:attrs {:description ["Set the file or files special attributes." "Provide as a string that is accepted to the chattr shell command"] :type :string}] [:dir-mode {:description ["When doing a recursive copy, set the access mode of directories to this mode." "Can be specified as an octal value of the form 0xxx, as a decimal value, or as a change string as is accepted by the system chmod command (eg. \"u+rwx\")."] :type [:integer :string]}] [:preserve {:description ["Preserve the access mode and file timestamps of the original source file."] :type :boolean}] [:recurse {:description ["Perform a recursive copy to transfer the entire directory contents"] :type :boolean}] [:force {:description ["Force the copy operation to overwrite other content." "If the destination path already exists as a file, and the upload is to recursively copy a directory, delete the destination file before copying the directory."] :type :boolean}]] :examples [ {:description "Copy a local file to the destination server" :form " (upload {:src \"./project.clj\" :dest \"/tmp/project.clj\" :owner \"john\" :group \"users\" :mode 0755 :dir-mode 0644})"} {:description "Recursively copy parent directory to the destination server preserving file permissions" :form " (upload {:src \"../\" :dest \"/tmp/folder-path\" :recurse true :preserve true}) "} {:description "Alternative way to copy a file to the server" :form " (upload {:content (clojure.java.io/file \"/usr/local/bin/spire\") :dest \"/usr/local/bin/\" :mode \"a+x\"}) "} {:description "Render a template and place it on the server" :form " (upload {:content (selmer \"nginx.conf\" (edn \"webserver.edn\")) :dest \"/etc/nginx/nginx.conf\"}) "} {:description "Create a binary file on the server from a byte array" :form " (upload {:content (byte-array [0x01 0x02 0x03 0x04]) :dest \"small.bin\"}) "} ] })
null
https://raw.githubusercontent.com/epiccastle/spire/f1161ae5ff74124d603c1679507fc0a1b31c26eb/src/clj/spire/module/upload.clj
clojure
analyse local and remote paths straight single copy content upload file upload _ (do (println "\n\n\n")) generally we assume that if a copy happened, all attributes and modes are correctly setup.
(ns spire.module.upload (:require [spire.output.core :as output] [spire.ssh :as ssh] [spire.facts :as facts] [spire.scp :as scp] [spire.utils :as utils] [spire.local :as local] [spire.state :as state] [spire.remote :as remote] [spire.compare :as compare] [spire.context :as context] [spire.module.attrs :as attrs] [clojure.java.io :as io] [clojure.string :as string])) (def debug false) (def failed-result {:exit 1 :out "" :err "" :result :failed}) (defn preflight [{:keys [src content dest owner group mode attrs dir-mode preserve recurse force] :as opts}] (or (facts/check-bins-present #{:scp}) (cond (not (or src content)) (assoc failed-result :exit 3 :err ":src or :content must be provided") (not dest) (assoc failed-result :exit 3 :err ":dest must be provided") (and src content) (assoc failed-result :exit 3 :err ":src and :content cannot both be specified") (and preserve (or mode dir-mode)) (assoc failed-result :exit 3 :err "when providing :preverse you cannot also specify :mode or :dir-mode") (and content (utils/content-recursive? content) (not recurse)) (assoc failed-result :exit 3 :err ":recurse must be true when :content specifies a directory.") (and src (utils/content-recursive? (io/file src)) (not recurse)) (assoc failed-result :exit 3 :err ":recurse must be true when :src specifies a directory.")))) (defn process-result [opts copy-result attr-result] (let [result {:result :failed :attr-result attr-result :copy-result copy-result}] (cond (= :failed (:result copy-result)) result (= :failed (:result attr-result)) result (or (= :changed (:result copy-result)) (= :changed (:result attr-result))) (assoc result :result :changed) (and (= :ok (:result copy-result)) (= :ok (:result attr-result))) (assoc result :result :ok) :else (dissoc result :result) ))) (defmacro scp-result [& body] `(let [res# (do ~@body)] (if res# {:result :changed} {:result :ok})) #_ (catch Exception e# {:result :failed :exception e#})) (defn process-md5-out ([line] (process-md5-out (facts/get-fact [:system :os]) line)) ([os line] (cond (#{:linux} os) (vec (string/split line #"\s+" 2)) :else (let [[_ filename hash] (re-matches #"MD5\s+\((.+)\)\s*=\s*([0-9a-fA-F]+)" line)] [hash filename]) ))) (utils/defmodule upload* [source-code-file form form-meta {:keys [src content dest owner group mode attrs dir-mode preserve recurse force] :as opts}] [host-config session {:keys [exec exec-fn sudo] :as shell-context}] (or (preflight opts) (let [run (fn [command] (let [{:keys [out exit err]} (exec-fn session "bash" command "UTF-8" {:sudo sudo})] #_(when debug (println "-------") (prn 'sudo sudo) (prn 'command command) (prn 'exit exit) (prn 'out out) (prn 'err err)) (if (zero? exit) (string/trim out) ""))) content? content local-file? (when-not content (local/is-file? src)) remote-file? (remote/is-file? run dest) remote-dir? (remote/is-dir? run dest) remote-writable? (if (not (string/ends-with? dest "/")) (remote/is-writable? run (utils/containing-folder dest)) (remote/is-writable? run dest)) content (or content (let [src-file (io/file src)] (if (.isAbsolute src-file) src-file (io/file (utils/current-file-parent) src)))) ] (cond (and (not force) (or local-file? content?) (not (string/ends-with? dest "/")) remote-dir?) {:result :failed :err ":src is a single file while :dest is a folder. Append '/' to dest to write into directory or set :force to true to delete destination folder and write as file." :exit 1 :out ""} (and recurse remote-file? (not force)) {:result :failed :err "Cannot copy :src directory over :dest. Destination is a file. Use :force to delete destination file and replace." :exit 1 :out ""} (not remote-writable?) {:result :failed :err "destination path :dest is unwritable" :exit 1 :out ""} :else (let [remote-file? (remote/is-file? run dest) transfers (compare/compare-full-info (str content) run dest #_(if local-file? dest (io/file dest (.getName (io/file (str content)))))) {:keys [local local-to-remote identical-content remote]} transfers total-size (if content? (utils/content-size content) (->> local-to-remote (map (comp :size local)) (apply +))) max-filename-length (if content? (count (utils/content-display-name content)) (->> local-to-remote (map (comp count #(.getName %) io/file :filename local)) (apply max 0))) progress-fn (fn [file bytes total frac context] (output/print-progress (context/deref* state/output-module) source-code-file form form-meta host-config (utils/progress-stats file bytes total frac total-size max-filename-length context) )) copied? (if recurse (let [identical-content (->> identical-content (map #(.getPath (io/file src %))) (into #{})) remote-folder-exists? (and (remote "") (= :dir (:type (remote "")))) ] (comment (prn "identical:" identical-content) (prn "local:" local) (prn "remote:" remote) (prn "lkeys:" (keys local))) (cond force (do (run (format "rm -rf \"%s\"" dest)) (scp-result (scp/scp-to session content dest :progress-fn progress-fn :preserve preserve :dir-mode (or dir-mode 0755) :mode (or mode 0644) :recurse true :skip-files #{} :exec exec :exec-fn exec-fn :sudo sudo ))) (not remote-file?) (scp-result (when (not= (count identical-content) (count (filter #(= :file (:type (second %))) local)) ) (scp/scp-to session (if remote-folder-exists? (mapv #(.getPath %) (.listFiles (io/file content))) content ) dest :progress-fn progress-fn :preserve preserve :dir-mode (or dir-mode 0755) :mode (or mode 0644) :recurse true :skip-files identical-content :exec exec :exec-fn exec-fn :sudo sudo ))))) (if content? (let [local-md5 (utils/md5 content) remote-md5 (some-> (facts/on-shell :csh (run (format "%s \"%s\"" (facts/md5) dest)) :else (run (format "%s \"%s\"" (facts/md5) dest))) process-md5-out first) ] (scp-result (when (not= local-md5 remote-md5) (scp/scp-content-to session content dest :progress-fn progress-fn :preserve preserve :dir-mode (or dir-mode 0755) :mode (or mode 0644) :exec exec :exec-fn exec-fn :sudo sudo )))) (let [local-md5 (utils/md5-file (.getPath content)) remote-md5 (some-> (facts/on-shell :csh (run (format "%s \"%s\"" (facts/md5) dest)) :else (run (format "%s \"%s\"" (facts/md5) dest))) process-md5-out first) _ ( println " l : " local - md5 " r : " remote - md5 ) ] (comment (prn "local-md5:" local-md5) (prn "remote-md5:" remote-md5)) (scp-result (when (not= local-md5 remote-md5) (scp/scp-to session [(.getPath content)] dest :progress-fn progress-fn :preserve preserve :dir-mode (or dir-mode 0755) :mode (or mode 0644) :exec exec :exec-fn exec-fn :sudo sudo )))))) passed-attrs? (or owner group dir-mode mode attrs) {:keys [exit err out]} (cond (and (= :ok (:result copied?)) passed-attrs?) (attrs/set-attrs session {:path dest :owner owner :group group :mode (or mode 0644) :dir-mode (or dir-mode 0755) :attrs attrs :recurse recurse}) preserve (attrs/set-attrs-preserve session src dest))] (process-result opts copied? (cond (= 0 exit) {:result :ok} (= 255 exit) {:result :changed} (nil? exit) {:result :ok} :else {:result :failed :exit exit :err err :out out})))) ))) (defmacro upload "transfer files and directories from the local client to the remote machines. (upload options) given: `options`: A hashmap of options `:src` A path to a file or directory on the local machine `:content` Alternatively specify content to upload. Can be a string, a `java.io.File` instance or a `byte-array` `:dest` A remote path to copy the files into `:recurse` If the local path is a directory, recurse through all the file and directories `:preserve` Preserve the local files' modification flags when copying them to the remote filesystem `:dir-mode` If `:preserve` is `false`, this specifies the modification parameters created directories will have. `:mode` If `:preserve` is `false`, this specifies the modification parameters of copied files. `:owner` If specified the local files and directories will be owned by this user. `:group` If specified the local files and directories will be owned by this group. `:force` Force the copy operation to overwrite incompatible content. Such as a file upload overwriting a directory or a directory copy overwriting a file. `:attrs` Set the file or files special attributes. Provided as a string that is accepted to the chattr shell command. " [& args] `(utils/wrap-report ~&form (upload* ~(utils/current-file) (quote ~&form) ~(meta &form) ~@args))) (def documentation { :module "upload" :blurb "upload files to remote systems" :description [ "This module uploads files from the local machine to the remote machine." "Files are verified with md5 checksums before transfer and files that are already present and intact on the remote machine are not recopied." "Use the download module to gather files from remote filesystem to the local machine."] :form "(upload options)" :args [{:arg "options" :desc "A hashmap of options. All available option keys and their values are described below"}] :opts [[:src {:description ["A path to a file or directory on the local machine that you want to copy to the remote machine." "If this option is specified then `:content` cannot be specified." "If this path is a directory the `:recurse` must be true."] :type :string}] [:content {:description ["Some content to upload to a file. Can be a `String`, a `java.io.File` object or a `byte array`." "If this option is specified then `:src` cannot be specified." ] :type [:string :bytearray :file]}] [:dest {:description ["The destination path to copy the file or directory into." "If :recurse is true and :dest path ends in a slash; indicates that destination is a directory and the contents of :src are to be copied into the directory." "If :recurse is true and :dest path does not end in a slash; indicates that the :src directory is to be copies as the specified path."] :type :string}] [:owner {:description ["Make the destination file or files owned by this user." "Can be specified as a username or as a uid."] :type [:integer :string]}] [:group {:description ["Make the destination file or files owned by this group." "Can be specified as a group name or as a gid."] :type [:integer :string]}] [:mode {:description ["Set the access mode of this file or files." "Can be specified as an octal value of the form 0xxx, as a decimal value, or as a change string as is accepted by the system chmod command (eg. \"u+rwx\")."] :type [:integer :string]}] [:attrs {:description ["Set the file or files special attributes." "Provide as a string that is accepted to the chattr shell command"] :type :string}] [:dir-mode {:description ["When doing a recursive copy, set the access mode of directories to this mode." "Can be specified as an octal value of the form 0xxx, as a decimal value, or as a change string as is accepted by the system chmod command (eg. \"u+rwx\")."] :type [:integer :string]}] [:preserve {:description ["Preserve the access mode and file timestamps of the original source file."] :type :boolean}] [:recurse {:description ["Perform a recursive copy to transfer the entire directory contents"] :type :boolean}] [:force {:description ["Force the copy operation to overwrite other content." "If the destination path already exists as a file, and the upload is to recursively copy a directory, delete the destination file before copying the directory."] :type :boolean}]] :examples [ {:description "Copy a local file to the destination server" :form " (upload {:src \"./project.clj\" :dest \"/tmp/project.clj\" :owner \"john\" :group \"users\" :mode 0755 :dir-mode 0644})"} {:description "Recursively copy parent directory to the destination server preserving file permissions" :form " (upload {:src \"../\" :dest \"/tmp/folder-path\" :recurse true :preserve true}) "} {:description "Alternative way to copy a file to the server" :form " (upload {:content (clojure.java.io/file \"/usr/local/bin/spire\") :dest \"/usr/local/bin/\" :mode \"a+x\"}) "} {:description "Render a template and place it on the server" :form " (upload {:content (selmer \"nginx.conf\" (edn \"webserver.edn\")) :dest \"/etc/nginx/nginx.conf\"}) "} {:description "Create a binary file on the server from a byte array" :form " (upload {:content (byte-array [0x01 0x02 0x03 0x04]) :dest \"small.bin\"}) "} ] })
b59480c873e888a91083f60cdf7c5d2de909aebab0a7400f5a511dbd830347bf
Nayshins/ocaml-tic-tac-toe
testMain.ml
open Core.Std open OUnit2 let tests = "Suite" >::: [TokenTest.tests; BoardTest.tests; RulesTest.tests; PlayerTest.tests; BoardPresenterTest.tests; NegamaxTest.tests; SimpleComputerTest.tests; HumanTest.tests; ConsoleIOTest.tests; GameTest.tests; SetupTest.tests;] let _ = run_test_tt_main tests
null
https://raw.githubusercontent.com/Nayshins/ocaml-tic-tac-toe/a177feed4938552ce7df79f0e4d09b24cdcb3667/test/testMain.ml
ocaml
open Core.Std open OUnit2 let tests = "Suite" >::: [TokenTest.tests; BoardTest.tests; RulesTest.tests; PlayerTest.tests; BoardPresenterTest.tests; NegamaxTest.tests; SimpleComputerTest.tests; HumanTest.tests; ConsoleIOTest.tests; GameTest.tests; SetupTest.tests;] let _ = run_test_tt_main tests
8b4c28317262649063bc6847d718ae6e7d403cb4ff2a80bd3a549be6b76393df
softwarelanguageslab/maf
R5RS_gambit_matrix-4.scm
; Changes: * removed : 0 * added : 0 * swaps : 0 * negated predicates : 1 ; * swapped branches: 0 * calls to i d fun : 10 (letrec ((map2 (lambda (f l1 l2) (if (let ((__or_res (null? l1))) (if __or_res __or_res (null? l2))) () (if (if (pair? l1) (pair? l2) #f) (cons (f (car l1) (car l2)) (map2 f (cdr l1) (cdr l2))) (error "Cannot map2 over a non-list"))))) (chez-box (lambda (x) (cons x ()))) (chez-unbox (lambda (x) (car x))) (chez-set-box! (lambda (x y) (set-car! x y))) (maximal? (lambda (mat) (<change> ((letrec ((pick-first-row (lambda (first-row-perm) (if first-row-perm (if (zunda first-row-perm mat) (pick-first-row (first-row-perm 'brother)) #f) #t)))) pick-first-row) (gen-perms mat)) ((lambda (x) x) ((letrec ((pick-first-row (lambda (first-row-perm) (if first-row-perm (if (zunda first-row-perm mat) (pick-first-row (first-row-perm 'brother)) #f) #t)))) pick-first-row) (gen-perms mat)))))) (zunda (lambda (first-row-perm mat) (<change> (let* ((first-row (first-row-perm 'now)) (number-of-cols (length first-row)) (make-row->func (lambda (if-equal if-different) (lambda (row) (let ((vec (make-vector number-of-cols 0))) (letrec ((__do_loop (lambda (i first row) (if (= i number-of-cols) #f (begin (vector-set! vec i (if (= (car first) (car row)) if-equal if-different)) (__do_loop (+ i 1) (cdr first) (cdr row))))))) (__do_loop 0 first-row row)) (lambda (i) (vector-ref vec i)))))) (mat (cdr mat))) (zebra (first-row-perm 'child) (make-row->func 1 -1) (make-row->func -1 1) mat number-of-cols)) ((lambda (x) x) (let* ((first-row (first-row-perm 'now)) (number-of-cols (length first-row)) (make-row->func (lambda (if-equal if-different) (lambda (row) (let ((vec (make-vector number-of-cols 0))) (<change> (letrec ((__do_loop (lambda (i first row) (if (= i number-of-cols) #f (begin (vector-set! vec i (if (= (car first) (car row)) if-equal if-different)) (__do_loop (+ i 1) (cdr first) (cdr row))))))) (__do_loop 0 first-row row)) ((lambda (x) x) (letrec ((__do_loop (lambda (i first row) (if (= i number-of-cols) #f (begin (vector-set! vec i (if (= (car first) (car row)) if-equal if-different)) (__do_loop (+ i 1) (cdr first) (cdr row))))))) (__do_loop 0 first-row row)))) (lambda (i) (vector-ref vec i)))))) (mat (cdr mat))) (zebra (first-row-perm 'child) (make-row->func 1 -1) (make-row->func -1 1) mat number-of-cols)))))) (zebra (lambda (row-perm row->func+ row->func- mat number-of-cols) ((letrec ((_-*- (lambda (row-perm mat partitions) (let ((__or_res (not row-perm))) (if __or_res __or_res (if (zulu (car mat) (row->func+ (row-perm 'now)) partitions (lambda (new-partitions) (_-*- (row-perm 'child) (cdr mat) new-partitions))) (if (zulu (car mat) (row->func- (row-perm 'now)) partitions (lambda (new-partitions) (_-*- (row-perm 'child) (cdr mat) new-partitions))) (let ((new-row-perm (row-perm 'brother))) (let ((__or_res (not new-row-perm))) (if __or_res __or_res (_-*- new-row-perm mat partitions)))) #f) #f)))))) _-*-) row-perm mat (list (miota number-of-cols))))) (zulu (let ((cons-if-not-null (lambda (lhs rhs) (<change> (if (null? lhs) rhs (cons lhs rhs)) ((lambda (x) x) (if (null? lhs) rhs (cons lhs rhs))))))) (lambda (old-row new-row-func partitions equal-cont) ((letrec ((_-*- (lambda (p-in old-row rev-p-out) ((letrec ((_-split- (lambda (partition old-row plus minus) (if (null? partition) ((letrec ((_-minus- (lambda (old-row m) (if (null? m) (let ((rev-p-out (cons-if-not-null minus (cons-if-not-null plus rev-p-out))) (p-in (cdr p-in))) (if (null? p-in) (equal-cont (reverse rev-p-out)) (_-*- p-in old-row rev-p-out))) (let ((__or_res (= 1 (car old-row)))) (if __or_res __or_res (_-minus- (cdr old-row) (cdr m)))))))) _-minus-) old-row minus) (let ((next (car partition))) (let ((__case-atom-key (new-row-func next))) (if (eq? __case-atom-key 1) (if (= 1 (car old-row)) (_-split- (cdr partition) (cdr old-row) (cons next plus) minus) #f) (if (eq? __case-atom-key -1) (_-split- (cdr partition) old-row plus (cons next minus)) #f)))))))) _-split-) (car p-in) old-row () ())))) _-*-) partitions old-row ())))) (all? (lambda (ok? lst) ((letrec ((_-*- (lambda (lst) (let ((__or_res (null? lst))) (if __or_res __or_res (if (ok? (car lst)) (_-*- (cdr lst)) #f)))))) _-*-) lst))) (gen-perms (lambda (objects) ((letrec ((_-*- (lambda (zulu-future past) (if (null? zulu-future) #f (lambda (msg) (if (eq? msg 'now) (car zulu-future) (if (eq? msg 'brother) (_-*- (cdr zulu-future) (cons (car zulu-future) past)) (if (eq? msg 'child) (gen-perms (fold past cons (cdr zulu-future))) (if (eq? msg 'puke) (cons (car zulu-future) (fold past cons (cdr zulu-future))) (error gen-perms "Bad msg: ~a" msg)))))))))) _-*-) objects ()))) (fold (lambda (lst folder state) ((letrec ((_-*- (lambda (lst state) (if (null? lst) state (_-*- (cdr lst) (folder (car lst) state)))))) _-*-) lst state))) (miota (lambda (len) ((letrec ((_-*- (lambda (i) (if (= i len) () (cons i (_-*- (+ i 1))))))) _-*-) 0))) (proc->vector (lambda (size proc) (let ((res (make-vector size 0))) (<change> (letrec ((__do_loop (lambda (i) (if (= i size) #f (begin (vector-set! res i (proc i)) (__do_loop (+ i 1))))))) (__do_loop 0)) ((lambda (x) x) (letrec ((__do_loop (lambda (i) (if (<change> (= i size) (not (= i size))) #f (begin (vector-set! res i (proc i)) (__do_loop (+ i 1))))))) (__do_loop 0)))) res))) (make-modular (lambda (modulus) (let* ((reduce (lambda (x) (modulo x modulus))) (coef-zero? (lambda (x) (zero? (reduce x)))) (coef-+ (lambda (x y) (reduce (+ x y)))) (coef-negate (lambda (x) (reduce (- x)))) (coef-* (lambda (x y) (reduce (* x y)))) (coef-recip (let ((inverses (proc->vector (- modulus 1) (lambda (i) (extended-gcd (+ i 1) modulus (lambda (gcd inverse ignore) inverse)))))) (lambda (x) (let ((x (reduce x))) (vector-ref inverses (- x 1))))))) (<change> (lambda (maker) (maker 0 1 coef-zero? coef-+ coef-negate coef-* coef-recip)) ((lambda (x) x) (lambda (maker) (maker 0 1 coef-zero? coef-+ coef-negate coef-* coef-recip))))))) (extended-gcd (let ((n->sgn/abs (lambda (x cont) (if (>= x 0) (cont 1 x) (cons -1 (- x)))))) (lambda (a b cont) (n->sgn/abs a (lambda (p-a p) (n->sgn/abs b (lambda (q-b q) ((letrec ((_-*- (lambda (p p-a p-b q q-a q-b) (if (zero? q) (cont p p-a p-b) (let ((mult (quotient p q))) (_-*- q q-a q-b (- p (* mult q)) (- p-a (* mult q-a)) (- p-b (* mult q-b)))))))) _-*-) p p-a 0 q 0 q-b)))))))) (make-row-reduce (lambda (coef-zero coef-one coef-zero? coef-+ coef-negate coef-* coef-recip) (lambda (mat) ((letrec ((_-*- (lambda (mat) (if (let ((__or_res (null? mat))) (if __or_res __or_res (null? (car mat)))) () ((letrec ((_-**- (lambda (in out) (if (null? in) (map (lambda (x) (cons coef-zero x)) (_-*- out)) (let* ((prow (car in)) (pivot (car prow)) (prest (cdr prow)) (in (cdr in))) (if (coef-zero? pivot) (_-**- in (cons prest out)) (let ((zap-row (map (let ((mult (coef-recip pivot))) (lambda (x) (coef-* mult x))) prest))) (cons (cons coef-one zap-row) (map (lambda (x) (cons coef-zero x)) (_-*- (fold in (lambda (row mat) (cons (let ((first-col (car row)) (rest-row (cdr row))) (if (coef-zero? first-col) rest-row (map2 (let ((mult (coef-negate first-col))) (lambda (f z) (coef-+ f (coef-* mult z)))) rest-row zap-row))) mat)) out))))))))))) _-**-) mat ()))))) _-*-) mat)))) (make-in-row-space? (lambda (coef-zero coef-one coef-zero? coef-+ coef-negate coef-* coef-recip) (<change> (let ((row-reduce (make-row-reduce coef-zero coef-one coef-zero? coef-+ coef-negate coef-* coef-recip))) (lambda (mat) (let ((mat (row-reduce mat))) (lambda (row) ((letrec ((_-*- (lambda (row mat) (if (null? row) #t (let ((r-first (car row)) (r-rest (cdr row))) (if (coef-zero? r-first) (_-*- r-rest (map cdr (if (let ((__or_res (null? mat))) (if __or_res __or_res (coef-zero? (caar mat)))) mat (cdr mat)))) (if (null? mat) #f (let* ((zap-row (car mat)) (z-first (car zap-row)) (z-rest (cdr zap-row)) (mat (cdr mat))) (if (coef-zero? z-first) #f (_-*- (map2 (let ((mult (coef-negate r-first))) (lambda (r z) (coef-+ r (coef-* mult z)))) r-rest z-rest) (map cdr mat))))))))))) _-*-) row mat))))) ((lambda (x) x) (let ((row-reduce (make-row-reduce coef-zero coef-one coef-zero? coef-+ coef-negate coef-* coef-recip))) (lambda (mat) (let ((mat (row-reduce mat))) (lambda (row) ((letrec ((_-*- (lambda (row mat) (if (null? row) #t (let ((r-first (car row)) (r-rest (cdr row))) (if (coef-zero? r-first) (_-*- r-rest (map cdr (if (let ((__or_res (null? mat))) (if __or_res __or_res (coef-zero? (caar mat)))) mat (cdr mat)))) (if (null? mat) #f (let* ((zap-row (car mat)) (z-first (car zap-row)) (z-rest (cdr zap-row)) (mat (cdr mat))) (if (coef-zero? z-first) #f (_-*- (map2 (let ((mult (coef-negate r-first))) (lambda (r z) (coef-+ r (coef-* mult z)))) r-rest z-rest) (map cdr mat))))))))))) _-*-) row mat))))))))) (make-modular-row-reduce (lambda (modulus) ((make-modular modulus) make-row-reduce))) (make-modular-in-row-space? (lambda (modulus) (<change> ((make-modular modulus) make-in-row-space?) ((lambda (x) x) ((make-modular modulus) make-in-row-space?))))) (find-prime (lambda (bound) (let* ((primes (list 2)) (last (chez-box primes)) (is-next-prime? (lambda (trial) ((letrec ((_-*- (lambda (primes) (let ((__or_res (null? primes))) (if __or_res __or_res (let ((p (car primes))) (let ((__or_res (< trial (* p p)))) (if __or_res __or_res (if (not (zero? (modulo trial p))) (_-*- (cdr primes)) #f))))))))) _-*-) primes)))) (if (> 2 bound) 2 ((letrec ((_-*- (lambda (trial) (if (is-next-prime? trial) (let ((entry (list trial))) (set-cdr! (chez-unbox last) entry) (chez-set-box! last entry) (if (> trial bound) trial (_-*- (+ trial 2)))) (_-*- (+ trial 2)))))) _-*-) 3))))) (det-upper-bound (lambda (size) (let ((main-part (expt size (quotient size 2)))) (if (even? size) main-part (* main-part (letrec ((__do_loop (lambda (i) (if (>= (* i i) size) i (__do_loop (+ i 1)))))) (__do_loop 0))))))) (go (lambda (number-of-cols inv-size folder state) (let* ((in-row-space? (make-modular-in-row-space? (find-prime (det-upper-bound inv-size)))) (make-tester (lambda (mat) (<change> (let ((tests (let ((old-mat (cdr mat)) (new-row (car mat))) (fold-over-subs-of-size old-mat (- inv-size 2) (lambda (sub tests) (cons (in-row-space? (cons new-row sub)) tests)) ())))) (lambda (row) ((letrec ((_-*- (lambda (tests) (if (not (null? tests)) (let ((__or_res ((car tests) row))) (if __or_res __or_res (_-*- (cdr tests)))) #f)))) _-*-) tests))) ((lambda (x) x) (let ((tests (let ((old-mat (cdr mat)) (new-row (car mat))) (fold-over-subs-of-size old-mat (- inv-size 2) (lambda (sub tests) (cons (in-row-space? (cons new-row sub)) tests)) ())))) (lambda (row) ((letrec ((_-*- (lambda (tests) (if (not (null? tests)) (let ((__or_res ((car tests) row))) (if __or_res __or_res (_-*- (cdr tests)))) #f)))) _-*-) tests))))))) (all-rows (fold (fold-over-rows (- number-of-cols 1) cons ()) (lambda (row rows) (cons (cons 1 row) rows)) ()))) ((letrec ((_-*- (lambda (number-of-rows rev-mat possible-future state) (let ((zulu-future (remove-in-order (if (< number-of-rows inv-size) (in-row-space? rev-mat) (make-tester rev-mat)) possible-future))) (if (null? zulu-future) (folder (reverse rev-mat) state) ((letrec ((_-**- (lambda (zulu-future state) (if (null? zulu-future) state (let ((rest-of-future (cdr zulu-future))) (_-**- rest-of-future (let* ((first (car zulu-future)) (new-rev-mat (cons first rev-mat))) (if (maximal? (reverse new-rev-mat)) (_-*- (+ number-of-rows 1) new-rev-mat rest-of-future state) state)))))))) _-**-) zulu-future state)))))) _-*-) 1 (list (car all-rows)) (cdr all-rows) state)))) (go-folder (lambda (mat bsize.blen.blist) (let ((bsize (car bsize.blen.blist)) (size (length mat))) (if (< size bsize) bsize.blen.blist (let ((blen (cadr bsize.blen.blist)) (blist (cddr bsize.blen.blist))) (if (= size bsize) (let ((blen (+ blen 1))) (cons bsize (cons blen (if (< blen 3000) (cons mat blist) (if (= blen 3000) (cons "..." blist) blist))))) (list size 1 mat))))))) (really-go (lambda (number-of-cols inv-size) (cddr (go number-of-cols inv-size go-folder (list -1 -1))))) (remove-in-order (lambda (remove? lst) (reverse (fold lst (lambda (e lst) (if (remove? e) lst (cons e lst))) ())))) (fold-over-rows (lambda (number-of-cols folder state) (if (zero? number-of-cols) (folder () state) (fold-over-rows (- number-of-cols 1) (lambda (tail state) (folder (cons -1 tail) state)) (fold-over-rows (- number-of-cols 1) (lambda (tail state) (folder (cons 1 tail) state)) state))))) (fold-over-subs-of-size (lambda (universe size folder state) (let ((usize (length universe))) (if (< usize size) state ((letrec ((_-*- (lambda (size universe folder csize state) (if (zero? csize) (folder universe state) (if (zero? size) (folder () state) (let ((first-u (car universe)) (rest-u (cdr universe))) (_-*- size rest-u folder (- csize 1) (_-*- (- size 1) rest-u (lambda (tail state) (folder (cons first-u tail) state)) csize state)))))))) _-*-) size universe folder (- usize size) state)))))) (<change> (equal? (really-go 5 5) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) ())))))) ())))))) ((lambda (x) x) (equal? (really-go 5 5) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) ())))))) ())))))))))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_gambit_matrix-4.scm
scheme
Changes: * swapped branches: 0
* removed : 0 * added : 0 * swaps : 0 * negated predicates : 1 * calls to i d fun : 10 (letrec ((map2 (lambda (f l1 l2) (if (let ((__or_res (null? l1))) (if __or_res __or_res (null? l2))) () (if (if (pair? l1) (pair? l2) #f) (cons (f (car l1) (car l2)) (map2 f (cdr l1) (cdr l2))) (error "Cannot map2 over a non-list"))))) (chez-box (lambda (x) (cons x ()))) (chez-unbox (lambda (x) (car x))) (chez-set-box! (lambda (x y) (set-car! x y))) (maximal? (lambda (mat) (<change> ((letrec ((pick-first-row (lambda (first-row-perm) (if first-row-perm (if (zunda first-row-perm mat) (pick-first-row (first-row-perm 'brother)) #f) #t)))) pick-first-row) (gen-perms mat)) ((lambda (x) x) ((letrec ((pick-first-row (lambda (first-row-perm) (if first-row-perm (if (zunda first-row-perm mat) (pick-first-row (first-row-perm 'brother)) #f) #t)))) pick-first-row) (gen-perms mat)))))) (zunda (lambda (first-row-perm mat) (<change> (let* ((first-row (first-row-perm 'now)) (number-of-cols (length first-row)) (make-row->func (lambda (if-equal if-different) (lambda (row) (let ((vec (make-vector number-of-cols 0))) (letrec ((__do_loop (lambda (i first row) (if (= i number-of-cols) #f (begin (vector-set! vec i (if (= (car first) (car row)) if-equal if-different)) (__do_loop (+ i 1) (cdr first) (cdr row))))))) (__do_loop 0 first-row row)) (lambda (i) (vector-ref vec i)))))) (mat (cdr mat))) (zebra (first-row-perm 'child) (make-row->func 1 -1) (make-row->func -1 1) mat number-of-cols)) ((lambda (x) x) (let* ((first-row (first-row-perm 'now)) (number-of-cols (length first-row)) (make-row->func (lambda (if-equal if-different) (lambda (row) (let ((vec (make-vector number-of-cols 0))) (<change> (letrec ((__do_loop (lambda (i first row) (if (= i number-of-cols) #f (begin (vector-set! vec i (if (= (car first) (car row)) if-equal if-different)) (__do_loop (+ i 1) (cdr first) (cdr row))))))) (__do_loop 0 first-row row)) ((lambda (x) x) (letrec ((__do_loop (lambda (i first row) (if (= i number-of-cols) #f (begin (vector-set! vec i (if (= (car first) (car row)) if-equal if-different)) (__do_loop (+ i 1) (cdr first) (cdr row))))))) (__do_loop 0 first-row row)))) (lambda (i) (vector-ref vec i)))))) (mat (cdr mat))) (zebra (first-row-perm 'child) (make-row->func 1 -1) (make-row->func -1 1) mat number-of-cols)))))) (zebra (lambda (row-perm row->func+ row->func- mat number-of-cols) ((letrec ((_-*- (lambda (row-perm mat partitions) (let ((__or_res (not row-perm))) (if __or_res __or_res (if (zulu (car mat) (row->func+ (row-perm 'now)) partitions (lambda (new-partitions) (_-*- (row-perm 'child) (cdr mat) new-partitions))) (if (zulu (car mat) (row->func- (row-perm 'now)) partitions (lambda (new-partitions) (_-*- (row-perm 'child) (cdr mat) new-partitions))) (let ((new-row-perm (row-perm 'brother))) (let ((__or_res (not new-row-perm))) (if __or_res __or_res (_-*- new-row-perm mat partitions)))) #f) #f)))))) _-*-) row-perm mat (list (miota number-of-cols))))) (zulu (let ((cons-if-not-null (lambda (lhs rhs) (<change> (if (null? lhs) rhs (cons lhs rhs)) ((lambda (x) x) (if (null? lhs) rhs (cons lhs rhs))))))) (lambda (old-row new-row-func partitions equal-cont) ((letrec ((_-*- (lambda (p-in old-row rev-p-out) ((letrec ((_-split- (lambda (partition old-row plus minus) (if (null? partition) ((letrec ((_-minus- (lambda (old-row m) (if (null? m) (let ((rev-p-out (cons-if-not-null minus (cons-if-not-null plus rev-p-out))) (p-in (cdr p-in))) (if (null? p-in) (equal-cont (reverse rev-p-out)) (_-*- p-in old-row rev-p-out))) (let ((__or_res (= 1 (car old-row)))) (if __or_res __or_res (_-minus- (cdr old-row) (cdr m)))))))) _-minus-) old-row minus) (let ((next (car partition))) (let ((__case-atom-key (new-row-func next))) (if (eq? __case-atom-key 1) (if (= 1 (car old-row)) (_-split- (cdr partition) (cdr old-row) (cons next plus) minus) #f) (if (eq? __case-atom-key -1) (_-split- (cdr partition) old-row plus (cons next minus)) #f)))))))) _-split-) (car p-in) old-row () ())))) _-*-) partitions old-row ())))) (all? (lambda (ok? lst) ((letrec ((_-*- (lambda (lst) (let ((__or_res (null? lst))) (if __or_res __or_res (if (ok? (car lst)) (_-*- (cdr lst)) #f)))))) _-*-) lst))) (gen-perms (lambda (objects) ((letrec ((_-*- (lambda (zulu-future past) (if (null? zulu-future) #f (lambda (msg) (if (eq? msg 'now) (car zulu-future) (if (eq? msg 'brother) (_-*- (cdr zulu-future) (cons (car zulu-future) past)) (if (eq? msg 'child) (gen-perms (fold past cons (cdr zulu-future))) (if (eq? msg 'puke) (cons (car zulu-future) (fold past cons (cdr zulu-future))) (error gen-perms "Bad msg: ~a" msg)))))))))) _-*-) objects ()))) (fold (lambda (lst folder state) ((letrec ((_-*- (lambda (lst state) (if (null? lst) state (_-*- (cdr lst) (folder (car lst) state)))))) _-*-) lst state))) (miota (lambda (len) ((letrec ((_-*- (lambda (i) (if (= i len) () (cons i (_-*- (+ i 1))))))) _-*-) 0))) (proc->vector (lambda (size proc) (let ((res (make-vector size 0))) (<change> (letrec ((__do_loop (lambda (i) (if (= i size) #f (begin (vector-set! res i (proc i)) (__do_loop (+ i 1))))))) (__do_loop 0)) ((lambda (x) x) (letrec ((__do_loop (lambda (i) (if (<change> (= i size) (not (= i size))) #f (begin (vector-set! res i (proc i)) (__do_loop (+ i 1))))))) (__do_loop 0)))) res))) (make-modular (lambda (modulus) (let* ((reduce (lambda (x) (modulo x modulus))) (coef-zero? (lambda (x) (zero? (reduce x)))) (coef-+ (lambda (x y) (reduce (+ x y)))) (coef-negate (lambda (x) (reduce (- x)))) (coef-* (lambda (x y) (reduce (* x y)))) (coef-recip (let ((inverses (proc->vector (- modulus 1) (lambda (i) (extended-gcd (+ i 1) modulus (lambda (gcd inverse ignore) inverse)))))) (lambda (x) (let ((x (reduce x))) (vector-ref inverses (- x 1))))))) (<change> (lambda (maker) (maker 0 1 coef-zero? coef-+ coef-negate coef-* coef-recip)) ((lambda (x) x) (lambda (maker) (maker 0 1 coef-zero? coef-+ coef-negate coef-* coef-recip))))))) (extended-gcd (let ((n->sgn/abs (lambda (x cont) (if (>= x 0) (cont 1 x) (cons -1 (- x)))))) (lambda (a b cont) (n->sgn/abs a (lambda (p-a p) (n->sgn/abs b (lambda (q-b q) ((letrec ((_-*- (lambda (p p-a p-b q q-a q-b) (if (zero? q) (cont p p-a p-b) (let ((mult (quotient p q))) (_-*- q q-a q-b (- p (* mult q)) (- p-a (* mult q-a)) (- p-b (* mult q-b)))))))) _-*-) p p-a 0 q 0 q-b)))))))) (make-row-reduce (lambda (coef-zero coef-one coef-zero? coef-+ coef-negate coef-* coef-recip) (lambda (mat) ((letrec ((_-*- (lambda (mat) (if (let ((__or_res (null? mat))) (if __or_res __or_res (null? (car mat)))) () ((letrec ((_-**- (lambda (in out) (if (null? in) (map (lambda (x) (cons coef-zero x)) (_-*- out)) (let* ((prow (car in)) (pivot (car prow)) (prest (cdr prow)) (in (cdr in))) (if (coef-zero? pivot) (_-**- in (cons prest out)) (let ((zap-row (map (let ((mult (coef-recip pivot))) (lambda (x) (coef-* mult x))) prest))) (cons (cons coef-one zap-row) (map (lambda (x) (cons coef-zero x)) (_-*- (fold in (lambda (row mat) (cons (let ((first-col (car row)) (rest-row (cdr row))) (if (coef-zero? first-col) rest-row (map2 (let ((mult (coef-negate first-col))) (lambda (f z) (coef-+ f (coef-* mult z)))) rest-row zap-row))) mat)) out))))))))))) _-**-) mat ()))))) _-*-) mat)))) (make-in-row-space? (lambda (coef-zero coef-one coef-zero? coef-+ coef-negate coef-* coef-recip) (<change> (let ((row-reduce (make-row-reduce coef-zero coef-one coef-zero? coef-+ coef-negate coef-* coef-recip))) (lambda (mat) (let ((mat (row-reduce mat))) (lambda (row) ((letrec ((_-*- (lambda (row mat) (if (null? row) #t (let ((r-first (car row)) (r-rest (cdr row))) (if (coef-zero? r-first) (_-*- r-rest (map cdr (if (let ((__or_res (null? mat))) (if __or_res __or_res (coef-zero? (caar mat)))) mat (cdr mat)))) (if (null? mat) #f (let* ((zap-row (car mat)) (z-first (car zap-row)) (z-rest (cdr zap-row)) (mat (cdr mat))) (if (coef-zero? z-first) #f (_-*- (map2 (let ((mult (coef-negate r-first))) (lambda (r z) (coef-+ r (coef-* mult z)))) r-rest z-rest) (map cdr mat))))))))))) _-*-) row mat))))) ((lambda (x) x) (let ((row-reduce (make-row-reduce coef-zero coef-one coef-zero? coef-+ coef-negate coef-* coef-recip))) (lambda (mat) (let ((mat (row-reduce mat))) (lambda (row) ((letrec ((_-*- (lambda (row mat) (if (null? row) #t (let ((r-first (car row)) (r-rest (cdr row))) (if (coef-zero? r-first) (_-*- r-rest (map cdr (if (let ((__or_res (null? mat))) (if __or_res __or_res (coef-zero? (caar mat)))) mat (cdr mat)))) (if (null? mat) #f (let* ((zap-row (car mat)) (z-first (car zap-row)) (z-rest (cdr zap-row)) (mat (cdr mat))) (if (coef-zero? z-first) #f (_-*- (map2 (let ((mult (coef-negate r-first))) (lambda (r z) (coef-+ r (coef-* mult z)))) r-rest z-rest) (map cdr mat))))))))))) _-*-) row mat))))))))) (make-modular-row-reduce (lambda (modulus) ((make-modular modulus) make-row-reduce))) (make-modular-in-row-space? (lambda (modulus) (<change> ((make-modular modulus) make-in-row-space?) ((lambda (x) x) ((make-modular modulus) make-in-row-space?))))) (find-prime (lambda (bound) (let* ((primes (list 2)) (last (chez-box primes)) (is-next-prime? (lambda (trial) ((letrec ((_-*- (lambda (primes) (let ((__or_res (null? primes))) (if __or_res __or_res (let ((p (car primes))) (let ((__or_res (< trial (* p p)))) (if __or_res __or_res (if (not (zero? (modulo trial p))) (_-*- (cdr primes)) #f))))))))) _-*-) primes)))) (if (> 2 bound) 2 ((letrec ((_-*- (lambda (trial) (if (is-next-prime? trial) (let ((entry (list trial))) (set-cdr! (chez-unbox last) entry) (chez-set-box! last entry) (if (> trial bound) trial (_-*- (+ trial 2)))) (_-*- (+ trial 2)))))) _-*-) 3))))) (det-upper-bound (lambda (size) (let ((main-part (expt size (quotient size 2)))) (if (even? size) main-part (* main-part (letrec ((__do_loop (lambda (i) (if (>= (* i i) size) i (__do_loop (+ i 1)))))) (__do_loop 0))))))) (go (lambda (number-of-cols inv-size folder state) (let* ((in-row-space? (make-modular-in-row-space? (find-prime (det-upper-bound inv-size)))) (make-tester (lambda (mat) (<change> (let ((tests (let ((old-mat (cdr mat)) (new-row (car mat))) (fold-over-subs-of-size old-mat (- inv-size 2) (lambda (sub tests) (cons (in-row-space? (cons new-row sub)) tests)) ())))) (lambda (row) ((letrec ((_-*- (lambda (tests) (if (not (null? tests)) (let ((__or_res ((car tests) row))) (if __or_res __or_res (_-*- (cdr tests)))) #f)))) _-*-) tests))) ((lambda (x) x) (let ((tests (let ((old-mat (cdr mat)) (new-row (car mat))) (fold-over-subs-of-size old-mat (- inv-size 2) (lambda (sub tests) (cons (in-row-space? (cons new-row sub)) tests)) ())))) (lambda (row) ((letrec ((_-*- (lambda (tests) (if (not (null? tests)) (let ((__or_res ((car tests) row))) (if __or_res __or_res (_-*- (cdr tests)))) #f)))) _-*-) tests))))))) (all-rows (fold (fold-over-rows (- number-of-cols 1) cons ()) (lambda (row rows) (cons (cons 1 row) rows)) ()))) ((letrec ((_-*- (lambda (number-of-rows rev-mat possible-future state) (let ((zulu-future (remove-in-order (if (< number-of-rows inv-size) (in-row-space? rev-mat) (make-tester rev-mat)) possible-future))) (if (null? zulu-future) (folder (reverse rev-mat) state) ((letrec ((_-**- (lambda (zulu-future state) (if (null? zulu-future) state (let ((rest-of-future (cdr zulu-future))) (_-**- rest-of-future (let* ((first (car zulu-future)) (new-rev-mat (cons first rev-mat))) (if (maximal? (reverse new-rev-mat)) (_-*- (+ number-of-rows 1) new-rev-mat rest-of-future state) state)))))))) _-**-) zulu-future state)))))) _-*-) 1 (list (car all-rows)) (cdr all-rows) state)))) (go-folder (lambda (mat bsize.blen.blist) (let ((bsize (car bsize.blen.blist)) (size (length mat))) (if (< size bsize) bsize.blen.blist (let ((blen (cadr bsize.blen.blist)) (blist (cddr bsize.blen.blist))) (if (= size bsize) (let ((blen (+ blen 1))) (cons bsize (cons blen (if (< blen 3000) (cons mat blist) (if (= blen 3000) (cons "..." blist) blist))))) (list size 1 mat))))))) (really-go (lambda (number-of-cols inv-size) (cddr (go number-of-cols inv-size go-folder (list -1 -1))))) (remove-in-order (lambda (remove? lst) (reverse (fold lst (lambda (e lst) (if (remove? e) lst (cons e lst))) ())))) (fold-over-rows (lambda (number-of-cols folder state) (if (zero? number-of-cols) (folder () state) (fold-over-rows (- number-of-cols 1) (lambda (tail state) (folder (cons -1 tail) state)) (fold-over-rows (- number-of-cols 1) (lambda (tail state) (folder (cons 1 tail) state)) state))))) (fold-over-subs-of-size (lambda (universe size folder state) (let ((usize (length universe))) (if (< usize size) state ((letrec ((_-*- (lambda (size universe folder csize state) (if (zero? csize) (folder universe state) (if (zero? size) (folder () state) (let ((first-u (car universe)) (rest-u (cdr universe))) (_-*- size rest-u folder (- csize 1) (_-*- (- size 1) rest-u (lambda (tail state) (folder (cons first-u tail) state)) csize state)))))))) _-*-) size universe folder (- usize size) state)))))) (<change> (equal? (really-go 5 5) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) ())))))) ())))))) ((lambda (x) x) (equal? (really-go 5 5) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) ())))))) (__toplevel_cons (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons 1 (__toplevel_cons 1 (__toplevel_cons 1 ()))))) (__toplevel_cons (__toplevel_cons 1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 (__toplevel_cons -1 ()))))) ())))))) ())))))))))
2130223231dd618a738bf46490b5f150669234339e372e5cca7a8a03448be85e
vii/teepeedee2
dispatcher.lisp
(in-package #:tpd2.http) (defstruct dispatcher canonical-name (canonical-protocol "http://") (paths (make-hash-table :test 'equalp)) (error-responder 'default-http-error-page)) (defun dispatch-servestate (con done *servestate*) (dispatcher-respond (find-dispatcher (first (servestate-host*))) con done)) (defun-speedy start-http-response (&key (banner (force-byte-vector "200 OK")) (content-type #.(byte-vector-cat "Content-Type: text/html;charset=utf-8" tpd2.io:+newline+))) (setf (servestate-response*) (with-sendbuf () "HTTP/1.1 " banner +newline+ content-type))) (defun-speedy map-http-params (func) (declare (dynamic-extent func) (type (function (simple-byte-vector simple-byte-vector) t) func)) (labels ( (f (name value) (funcall func (url-encoding-decode name) (url-encoding-decode value))) (parse-params (str) (when str (match-bind ( (* name "=" value (or (last) "&") '(f name value))) str))) (parse-cookie-params (cookies) (loop for str in cookies do (match-bind ( (* name "=" value (or (last) "," ";") '(f name value))) str)))) (declare (inline parse-cookie-params parse-params f) (dynamic-extent #'parse-params #'parse-cookie-params #'f)) (parse-params (servestate-query-string*)) (parse-params (servestate-post-parameters*)) (parse-cookie-params (servestate-cookie*)))) (defmacro with-http-params (bindings &body body) (with-unique-names (f pname pvalue) `(let ,(loop for b in bindings for (n default) = (force-list b) collect `(,n ,default)) (flet ((,f (,pname ,pvalue) (declare (type simple-byte-vector ,pname ,pvalue)) (case-match-fold-ascii-case ,pname ,@(loop for b in bindings collect (destructuring-bind (var &optional default &key conv (name (force-byte-vector var))) (force-list b) (declare (ignore default)) `(,(force-byte-vector name) (setf ,var ,(if conv `(,conv ,pvalue) pvalue))) ))))) (declare (inline ,f) (dynamic-extent #',f)) (map-http-params #',f) (locally ,@body))))) (defmacro with-http-headers (() &body body) `(with-sendbuf-continue ((servestate-response-as-sendbuf*)) ,@body)) (defun-speedy send-http-response (con done body) (declare (type sendbuf body)) (with-http-headers () "Content-Length: " (sendbuf-len body) +newline+ +newline+ body) (send con done (servestate-response-as-sendbuf*))) (defun-speedy respond-http (con done &key banner body) (start-http-response :banner banner) (send-http-response con done body)) (my-defun dispatcher respond (con done) (let ((f (gethash (servestate-path*) (my paths)))) (handler-case (cond (f (locally (declare (optimize speed) (type function f)) (funcall f me con done) (values))) (t ( format * error - output * " LOST ~A~ & " ( strcat ( my canonical - name ) " / " path ) ) (respond-http con done :banner (force-byte-vector "404 Not found") :body (funcall (my error-responder) me)))) (error (e) (format *error-output* "~&PAGE ERROR ~A~&--- ~A~&-AGAIN PAGE ERROR ~A~&" (strcat (my canonical-name) (servestate-path*)) (backtrace-description e) e) (respond-http con done :body (with-sendbuf () "<h1>I programmed this thoughtlessly. Sorry for the inconvenience.</h1>") :banner (force-byte-vector "500 Internal error")))))) (my-defun dispatcher register-path (path func) (setf (gethash (force-byte-vector path) (my paths)) (alexandria:ensure-function func))) (my-defun dispatcher 'default-http-error-page () (format *trace-output* "~&Page ~A not found~&" (strcat (my canonical-name) (servestate-path*))) (with-sendbuf () "<h1>I made a mistake. Sorry for the inconvenience.</h1>")) (defvar *default-dispatcher* (make-dispatcher)) (defvar *dispatchers* nil) (defun find-dispatcher-go (host) (alist-get *dispatchers* host :test #'equalp)) (defun find-dispatcher (host) (or (find-dispatcher-go host) *default-dispatcher*)) (defun find-or-make-dispatcher (host &rest args) (let ((host (force-byte-vector host))) (or (find-dispatcher-go host) (let ((it (apply 'make-dispatcher :canonical-name host args))) (push (cons host it) *dispatchers*) it)))) (defun dispatcher-add-alias (dispatcher alias) (check-type dispatcher dispatcher) (setf (alist-get *dispatchers* (force-byte-vector alias)) dispatcher)) (my-defun dispatcher 'print-object (stream) (print-unreadable-object (me stream :type t :identity t) (format stream "~S" (force-string (my canonical-name))) (loop for p being the hash-keys of (my paths) do (format stream " ~A" (force-string p))))) (defun describe-dispatchers (&optional (*standard-output* *standard-output*)) TODO print a list of hostnames for each dispatcher (loop for (path . dispatcher) in *dispatchers* do (format t "~&~S -> ~A~&" (force-string path) dispatcher)) (format t "~&DEFAULT -> ~A~&" *default-dispatcher*))
null
https://raw.githubusercontent.com/vii/teepeedee2/a2ed78c51d782993591c3284562daeed3aba3d40/src/http/dispatcher.lisp
lisp
(in-package #:tpd2.http) (defstruct dispatcher canonical-name (canonical-protocol "http://") (paths (make-hash-table :test 'equalp)) (error-responder 'default-http-error-page)) (defun dispatch-servestate (con done *servestate*) (dispatcher-respond (find-dispatcher (first (servestate-host*))) con done)) (defun-speedy start-http-response (&key (banner (force-byte-vector "200 OK")) (content-type #.(byte-vector-cat "Content-Type: text/html;charset=utf-8" tpd2.io:+newline+))) (setf (servestate-response*) (with-sendbuf () "HTTP/1.1 " banner +newline+ content-type))) (defun-speedy map-http-params (func) (declare (dynamic-extent func) (type (function (simple-byte-vector simple-byte-vector) t) func)) (labels ( (f (name value) (funcall func (url-encoding-decode name) (url-encoding-decode value))) (parse-params (str) (when str (match-bind ( (* name "=" value (or (last) "&") '(f name value))) str))) (parse-cookie-params (cookies) (loop for str in cookies do (match-bind ( (* name "=" value (or (last) "," ";") '(f name value))) str)))) (declare (inline parse-cookie-params parse-params f) (dynamic-extent #'parse-params #'parse-cookie-params #'f)) (parse-params (servestate-query-string*)) (parse-params (servestate-post-parameters*)) (parse-cookie-params (servestate-cookie*)))) (defmacro with-http-params (bindings &body body) (with-unique-names (f pname pvalue) `(let ,(loop for b in bindings for (n default) = (force-list b) collect `(,n ,default)) (flet ((,f (,pname ,pvalue) (declare (type simple-byte-vector ,pname ,pvalue)) (case-match-fold-ascii-case ,pname ,@(loop for b in bindings collect (destructuring-bind (var &optional default &key conv (name (force-byte-vector var))) (force-list b) (declare (ignore default)) `(,(force-byte-vector name) (setf ,var ,(if conv `(,conv ,pvalue) pvalue))) ))))) (declare (inline ,f) (dynamic-extent #',f)) (map-http-params #',f) (locally ,@body))))) (defmacro with-http-headers (() &body body) `(with-sendbuf-continue ((servestate-response-as-sendbuf*)) ,@body)) (defun-speedy send-http-response (con done body) (declare (type sendbuf body)) (with-http-headers () "Content-Length: " (sendbuf-len body) +newline+ +newline+ body) (send con done (servestate-response-as-sendbuf*))) (defun-speedy respond-http (con done &key banner body) (start-http-response :banner banner) (send-http-response con done body)) (my-defun dispatcher respond (con done) (let ((f (gethash (servestate-path*) (my paths)))) (handler-case (cond (f (locally (declare (optimize speed) (type function f)) (funcall f me con done) (values))) (t ( format * error - output * " LOST ~A~ & " ( strcat ( my canonical - name ) " / " path ) ) (respond-http con done :banner (force-byte-vector "404 Not found") :body (funcall (my error-responder) me)))) (error (e) (format *error-output* "~&PAGE ERROR ~A~&--- ~A~&-AGAIN PAGE ERROR ~A~&" (strcat (my canonical-name) (servestate-path*)) (backtrace-description e) e) (respond-http con done :body (with-sendbuf () "<h1>I programmed this thoughtlessly. Sorry for the inconvenience.</h1>") :banner (force-byte-vector "500 Internal error")))))) (my-defun dispatcher register-path (path func) (setf (gethash (force-byte-vector path) (my paths)) (alexandria:ensure-function func))) (my-defun dispatcher 'default-http-error-page () (format *trace-output* "~&Page ~A not found~&" (strcat (my canonical-name) (servestate-path*))) (with-sendbuf () "<h1>I made a mistake. Sorry for the inconvenience.</h1>")) (defvar *default-dispatcher* (make-dispatcher)) (defvar *dispatchers* nil) (defun find-dispatcher-go (host) (alist-get *dispatchers* host :test #'equalp)) (defun find-dispatcher (host) (or (find-dispatcher-go host) *default-dispatcher*)) (defun find-or-make-dispatcher (host &rest args) (let ((host (force-byte-vector host))) (or (find-dispatcher-go host) (let ((it (apply 'make-dispatcher :canonical-name host args))) (push (cons host it) *dispatchers*) it)))) (defun dispatcher-add-alias (dispatcher alias) (check-type dispatcher dispatcher) (setf (alist-get *dispatchers* (force-byte-vector alias)) dispatcher)) (my-defun dispatcher 'print-object (stream) (print-unreadable-object (me stream :type t :identity t) (format stream "~S" (force-string (my canonical-name))) (loop for p being the hash-keys of (my paths) do (format stream " ~A" (force-string p))))) (defun describe-dispatchers (&optional (*standard-output* *standard-output*)) TODO print a list of hostnames for each dispatcher (loop for (path . dispatcher) in *dispatchers* do (format t "~&~S -> ~A~&" (force-string path) dispatcher)) (format t "~&DEFAULT -> ~A~&" *default-dispatcher*))
0e9af661c7f3968b56ce35cd1ccb383e708d2a4ed7b62a4c447dc76c9109f961
craigfe/sink
eq.ml
module type S = sig type t val equal : t -> t -> bool [@@infix ( = )] end [@@deriving typeclass, infix] type 'a ty = 'a t let poly (type a) (Proxy.T : a Proxy.t) : a t = { equal = Stdlib.( = ) } module type S1 = sig type 'a t val equal : 'a ty -> 'a t -> 'a t -> bool end module type S2 = sig type ('a, 'b) t val equal : 'a ty -> 'b ty -> ('a, 'b) t -> ('a, 'b) t -> bool end module type S3 = sig type ('a, 'b, 'c) t val equal : 'a ty -> 'b ty -> 'c ty -> ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> bool end module type S4 = sig type ('a, 'b, 'c, 'd) t val equal : 'a ty -> 'b ty -> 'c ty -> 'd ty -> ('a, 'b, 'c, 'd) t -> ('a, 'b, 'c, 'd) t -> bool end
null
https://raw.githubusercontent.com/craigfe/sink/c5431edfa1b06f1a09845a481c4afcb3e92f0667/src/sink/eq.ml
ocaml
module type S = sig type t val equal : t -> t -> bool [@@infix ( = )] end [@@deriving typeclass, infix] type 'a ty = 'a t let poly (type a) (Proxy.T : a Proxy.t) : a t = { equal = Stdlib.( = ) } module type S1 = sig type 'a t val equal : 'a ty -> 'a t -> 'a t -> bool end module type S2 = sig type ('a, 'b) t val equal : 'a ty -> 'b ty -> ('a, 'b) t -> ('a, 'b) t -> bool end module type S3 = sig type ('a, 'b, 'c) t val equal : 'a ty -> 'b ty -> 'c ty -> ('a, 'b, 'c) t -> ('a, 'b, 'c) t -> bool end module type S4 = sig type ('a, 'b, 'c, 'd) t val equal : 'a ty -> 'b ty -> 'c ty -> 'd ty -> ('a, 'b, 'c, 'd) t -> ('a, 'b, 'c, 'd) t -> bool end
d4dae3a17565389b5825fff5024c0e20b0e97344025f01264b52bd77b687f0c0
janestreet/core_bench
display_column.ml
type t = [ `Name | `Speedup | `Percentage | `Samples ] [@@deriving compare, sexp] let equal = [%compare.equal: t]
null
https://raw.githubusercontent.com/janestreet/core_bench/746d2440aa10795f1ef286df64be46e7d4ff768c/internals/display_column.ml
ocaml
type t = [ `Name | `Speedup | `Percentage | `Samples ] [@@deriving compare, sexp] let equal = [%compare.equal: t]
34247098b0ab41ea688814500e6c5179269830d970a3a9da7ecc9e3334e82eb5
PacktWorkshops/The-Clojure-Workshop
update_delete_data.clj
(ns packt-clj.exercises.update-delete-data (:require [clojure.java.jdbc :as jdbc])) (defn update-agassi [db] (jdbc/update! db :app_user {:weight 78} ["first_name = 'Andre' and surname = 'Agassi'"])) (defn delete-agassi [db] (jdbc/delete! db :app_user ["first_name = 'Andre' and surname = 'Agassi'"])) (defn all-users [db] (jdbc/query db ["select * from app_user"])) (defn all-activities [db] (jdbc/query db ["select * from activity"]))
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter13/Exercise13.07/src/packt_clj/exercises/update_delete_data.clj
clojure
(ns packt-clj.exercises.update-delete-data (:require [clojure.java.jdbc :as jdbc])) (defn update-agassi [db] (jdbc/update! db :app_user {:weight 78} ["first_name = 'Andre' and surname = 'Agassi'"])) (defn delete-agassi [db] (jdbc/delete! db :app_user ["first_name = 'Andre' and surname = 'Agassi'"])) (defn all-users [db] (jdbc/query db ["select * from app_user"])) (defn all-activities [db] (jdbc/query db ["select * from activity"]))
1776189f8f239434f8651a40592040b800228ca5772f73314120d57574fffb4b
janestreet/universe
raised_exn.ml
open Core_kernel open! Import type t = { exn : exn ; backtrace : Backtrace.t } [@@deriving sexp_of] let create exn = { exn; backtrace = Backtrace.Exn.most_recent () }
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/incremental/src/raised_exn.ml
ocaml
open Core_kernel open! Import type t = { exn : exn ; backtrace : Backtrace.t } [@@deriving sexp_of] let create exn = { exn; backtrace = Backtrace.Exn.most_recent () }
bc50ba31d353928e275414af17d1f0eafb5e9910b4d5500f3039e7c93f24dd55
ocaml/opam
opamListCommand.mli
(**************************************************************************) (* *) Copyright 2012 - 2019 OCamlPro Copyright 2012 INRIA (* *) (* 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. *) (* *) (**************************************************************************) (** Functions handling the "opam list" subcommand *) open OpamParserTypes.FullPos open OpamTypes open OpamStateTypes (** Switches to determine what to include when querying (reverse) dependencies *) type dependency_toggles = { recursive: bool; depopts: bool; build: bool; post: bool; test: bool; dev_setup: bool; doc: bool; dev: bool; } val default_dependency_toggles: dependency_toggles type pattern_selector = { case_sensitive: bool; exact: bool; glob: bool; fields: string list; ext_fields: bool; (** Match on raw strings in [x-foo] fields *) } val default_pattern_selector: pattern_selector (** Package selectors used to filter the set of packages *) type selector = | Any | Installed | Root | Compiler | Available | Installable | Pinned | Depends_on of dependency_toggles * atom list | Required_by of dependency_toggles * atom list | Conflicts_with of package list | Coinstallable_with of dependency_toggles * package list | Solution of dependency_toggles * atom list | Pattern of pattern_selector * string | Atoms of atom list | Flag of package_flag | Tag of string | From_repository of repository_name list | Owns_file of filename (** Applies a formula of selectors to filter the package from a given switch state *) val filter: base:package_set -> 'a switch_state -> selector OpamFormula.formula -> package_set (** Or-filter on package patterns (NAME or NAME.VERSION) *) val pattern_selector: string list -> selector OpamFormula.formula (** Get the aggregated active external dependencies of the given packages *) val get_depexts: 'a switch_state -> package_set -> OpamSysPkg.Set.t (** Lists the given aggregated active external dependencies of the given packages *) val print_depexts: OpamSysPkg.Set.t -> unit * Element of package information to be printed . : should be part of the run - time man ! run-time man! *) type output_format = | Name (** Name without version *) | Version (** Version of the currently looked-at package *) | Package (** [name.version] *) * One - line package description | Synopsis_or_target (** Pinning target if pinned, synopsis otherwise *) | Description (** The package description, excluding synopsis *) | Field of string (** The value of the given opam-file field *) | Raw_field of string (** The raw value of the given opam-file field *) | Installed_version (** Installed version or "--" if none *) | Pinning_target (** Empty string if not pinned *) | Source_hash (** The VC-reported ident of current version, for dev packages. Empty if not available *) | Raw (** The full contents of the opam file (reformatted) *) | All_installed_versions (** List of the installed versions in all switches with the corresponding switches in brackets *) * List of the available versions ( currently installed one in bold if color enabled ) one in bold if color enabled) *) | All_versions (** List of the existing package versions (installed, installed in current switch and unavailable colored specifically if color enabled) *) | Repository (** The repository the package was found in (may be empty for pinned packages) *) | Installed_files (** The list of files that the installed package added to the system *) | VC_ref (** The version-control branch or tag the package url is bound to, if any *) | Depexts (** The external dependencies *) val default_list_format: output_format list (** Gets either the current switch state, if a switch is selected, or a virtual state corresponding to the configured repos *) val get_switch_state: 'a global_state -> 'a repos_state -> unlocked switch_state * For documentation , includes a dummy ' < field > : ' for the [ Field ] format . Used for the --columns argument . Used for the --columns argument. *) val raw_field_names: (output_format * string) list (** For documentation, includes a dummy '<field>:' and '<field>' for the [Field] format. Used for the --field argument. *) val field_names: (output_format * string) list val string_of_field: ?raw:bool -> output_format -> string val field_of_string: raw:bool -> string -> output_format type package_listing_format = { short: bool; header: bool; columns: output_format list; all_versions: bool; wrap: [`Wrap of string | `Truncate | `None] option; separator: string; value_printer: [`Normal | `Pretty | `Normalised]; order: [`Standard | `Dependency | `Custom of package -> package -> int]; } val default_package_listing_format: package_listing_format (** Outputs a list of packages as a table according to the formatting options. [normalise] supersedes [prettify] and uses a canonical way of displaying package definition file fields. [prettify] uses a nicer to read format for the package definition file fields. *) val display: 'a switch_state -> package_listing_format -> package_set -> unit (** Display a general summary of a collection of packages. *) val info: 'a switch_state -> fields:string list -> raw:bool -> where:bool -> ?normalise:bool -> ?show_empty:bool -> ?all_versions:bool -> ?sort:bool -> atom list -> unit (** Prints the value of an opam field in a shortened way (with [prettify] -- the default -- puts lists of strings in a format that is easier to read *) val mini_field_printer: ?prettify:bool -> ?normalise:bool -> value -> string val string_of_formula: selector OpamFormula.formula -> string
null
https://raw.githubusercontent.com/ocaml/opam/3159618528d6240d0c146e94e8a8eb81e6b8df69/src/client/opamListCommand.mli
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ * Functions handling the "opam list" subcommand * Switches to determine what to include when querying (reverse) dependencies * Match on raw strings in [x-foo] fields * Package selectors used to filter the set of packages * Applies a formula of selectors to filter the package from a given switch state * Or-filter on package patterns (NAME or NAME.VERSION) * Get the aggregated active external dependencies of the given packages * Lists the given aggregated active external dependencies of the given packages * Name without version * Version of the currently looked-at package * [name.version] * Pinning target if pinned, synopsis otherwise * The package description, excluding synopsis * The value of the given opam-file field * The raw value of the given opam-file field * Installed version or "--" if none * Empty string if not pinned * The VC-reported ident of current version, for dev packages. Empty if not available * The full contents of the opam file (reformatted) * List of the installed versions in all switches with the corresponding switches in brackets * List of the existing package versions (installed, installed in current switch and unavailable colored specifically if color enabled) * The repository the package was found in (may be empty for pinned packages) * The list of files that the installed package added to the system * The version-control branch or tag the package url is bound to, if any * The external dependencies * Gets either the current switch state, if a switch is selected, or a virtual state corresponding to the configured repos * For documentation, includes a dummy '<field>:' and '<field>' for the [Field] format. Used for the --field argument. * Outputs a list of packages as a table according to the formatting options. [normalise] supersedes [prettify] and uses a canonical way of displaying package definition file fields. [prettify] uses a nicer to read format for the package definition file fields. * Display a general summary of a collection of packages. * Prints the value of an opam field in a shortened way (with [prettify] -- the default -- puts lists of strings in a format that is easier to read
Copyright 2012 - 2019 OCamlPro Copyright 2012 INRIA GNU Lesser General Public License version 2.1 , with the special open OpamParserTypes.FullPos open OpamTypes open OpamStateTypes type dependency_toggles = { recursive: bool; depopts: bool; build: bool; post: bool; test: bool; dev_setup: bool; doc: bool; dev: bool; } val default_dependency_toggles: dependency_toggles type pattern_selector = { case_sensitive: bool; exact: bool; glob: bool; fields: string list; } val default_pattern_selector: pattern_selector type selector = | Any | Installed | Root | Compiler | Available | Installable | Pinned | Depends_on of dependency_toggles * atom list | Required_by of dependency_toggles * atom list | Conflicts_with of package list | Coinstallable_with of dependency_toggles * package list | Solution of dependency_toggles * atom list | Pattern of pattern_selector * string | Atoms of atom list | Flag of package_flag | Tag of string | From_repository of repository_name list | Owns_file of filename val filter: base:package_set -> 'a switch_state -> selector OpamFormula.formula -> package_set val pattern_selector: string list -> selector OpamFormula.formula val get_depexts: 'a switch_state -> package_set -> OpamSysPkg.Set.t val print_depexts: OpamSysPkg.Set.t -> unit * Element of package information to be printed . : should be part of the run - time man ! run-time man! *) type output_format = * One - line package description * List of the available versions ( currently installed one in bold if color enabled ) one in bold if color enabled) *) val default_list_format: output_format list val get_switch_state: 'a global_state -> 'a repos_state -> unlocked switch_state * For documentation , includes a dummy ' < field > : ' for the [ Field ] format . Used for the --columns argument . Used for the --columns argument. *) val raw_field_names: (output_format * string) list val field_names: (output_format * string) list val string_of_field: ?raw:bool -> output_format -> string val field_of_string: raw:bool -> string -> output_format type package_listing_format = { short: bool; header: bool; columns: output_format list; all_versions: bool; wrap: [`Wrap of string | `Truncate | `None] option; separator: string; value_printer: [`Normal | `Pretty | `Normalised]; order: [`Standard | `Dependency | `Custom of package -> package -> int]; } val default_package_listing_format: package_listing_format val display: 'a switch_state -> package_listing_format -> package_set -> unit val info: 'a switch_state -> fields:string list -> raw:bool -> where:bool -> ?normalise:bool -> ?show_empty:bool -> ?all_versions:bool -> ?sort:bool -> atom list -> unit val mini_field_printer: ?prettify:bool -> ?normalise:bool -> value -> string val string_of_formula: selector OpamFormula.formula -> string
763d6769b9159f7b0783d4d52b31d34a53c4cf55597d69b7a963ef65d310fdd6
pedestal/samples
server.clj
Copyright 2013 Relevance , Inc. ; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( ) ; which can be found in the file epl-v10.html at the root of this distribution. ; ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; ; You must not remove this notice, or any other, from this software. (ns ring-middleware.server (:require [ring-middleware.service :as service] [io.pedestal.service.http :as bootstrap])) (def service-instance "Global var to hold service instance." nil) (defn create-server "Standalone dev/prod mode." [& [opts]] (alter-var-root #'service-instance (constantly (bootstrap/create-server (merge service/service opts))))) (defn -main [& args] (println "Creating server...") (create-server) (println "Server created. Awaiting connections.") (bootstrap/start service-instance)) Container prod mode for use with the pedestal.servlet . ClojureVarServlet class . (defn servlet-init [this config] (require 'ring-middleware.service) (alter-var-root #'service-instance (bootstrap/create-servlet service/service)) (bootstrap/start service-instance) (.init (::bootstrap/servlet service-instance) config)) (defn servlet-destroy [this] (bootstrap/stop service-instance) (alter-var-root #'service-instance nil)) (defn servlet-service [this servlet-req servlet-resp] (.service ^javax.servlet.Servlet (::bootstrap/servlet service-instance) servlet-req servlet-resp))
null
https://raw.githubusercontent.com/pedestal/samples/caaf04afe255586f8f4e1235deeb0c1904179355/ring-middleware/src/ring_middleware/server.clj
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright 2013 Relevance , Inc. Eclipse Public License 1.0 ( ) (ns ring-middleware.server (:require [ring-middleware.service :as service] [io.pedestal.service.http :as bootstrap])) (def service-instance "Global var to hold service instance." nil) (defn create-server "Standalone dev/prod mode." [& [opts]] (alter-var-root #'service-instance (constantly (bootstrap/create-server (merge service/service opts))))) (defn -main [& args] (println "Creating server...") (create-server) (println "Server created. Awaiting connections.") (bootstrap/start service-instance)) Container prod mode for use with the pedestal.servlet . ClojureVarServlet class . (defn servlet-init [this config] (require 'ring-middleware.service) (alter-var-root #'service-instance (bootstrap/create-servlet service/service)) (bootstrap/start service-instance) (.init (::bootstrap/servlet service-instance) config)) (defn servlet-destroy [this] (bootstrap/stop service-instance) (alter-var-root #'service-instance nil)) (defn servlet-service [this servlet-req servlet-resp] (.service ^javax.servlet.Servlet (::bootstrap/servlet service-instance) servlet-req servlet-resp))
061da91d40af284e9f29d2df46a01690c74ef5d90cd36af4c48540b6d8781863
rollacaster/sketches
own_force.cljs
(ns sketches.nature-of-code.forces.own-force (:require [quil.core :as q :include-macros true] [quil.middleware :as md] [sketches.vector :as v] [sketches.mover :as m])) (defn compute-position [{:keys [acceleration velocity location] :as mover}] (let [velocity (v/add acceleration velocity) location (v/add velocity location)] (-> mover (assoc :acceleration [0 0]) (assoc :velocity velocity) (assoc :location location)))) (defn setup [] {:movers (map (fn [x] {:mass (+ 1 (rand-int 50)) :location [(rand-int 500) (rand-int 500)] :velocity [0 0] :acceleration [0 0]}) (range 0 10)) :attractors (map (fn [x] {:mass (rand-int 20) :location [(rand-int 500) (rand-int 500)]}) (range 0 5))}) (defn attract [mover attractor] (let [{loc1 :location} attractor {loc2 :location} mover vectorBetween (v/sub loc1 loc2) distanceBetween (q/constrain (v/mag vectorBetween) 5.0 25.0) G 0.4 strength (/ (* distanceBetween distanceBetween) (* G (:mass attractor) (:mass mover)))] (v/mult (v/normalize vectorBetween) strength))) (defn update-mover [attractors mover] (compute-position (reduce #(m/apply-force %1 (attract %1 %2)) mover attractors))) (defn update-state [{:keys [movers attractors] :as state}] (update state :movers (partial map (partial update-mover attractors)))) (defn draw [{:keys [attractors movers]}] (q/clear) (q/background 255) (doseq [{:keys [mass] [x y] :location} movers] (q/ellipse x y mass mass)) (doseq [{:keys [mass] [x y] :location} attractors] (q/rect x y mass mass))) (defn run [host] (q/defsketch own-force :host host :setup setup :draw draw :update update-state :middleware [md/fun-mode] :size [300 300]))
null
https://raw.githubusercontent.com/rollacaster/sketches/ba79fccf2a37139de9193ed2ea7a6cc04b63fad0/src/sketches/nature_of_code/forces/own_force.cljs
clojure
(ns sketches.nature-of-code.forces.own-force (:require [quil.core :as q :include-macros true] [quil.middleware :as md] [sketches.vector :as v] [sketches.mover :as m])) (defn compute-position [{:keys [acceleration velocity location] :as mover}] (let [velocity (v/add acceleration velocity) location (v/add velocity location)] (-> mover (assoc :acceleration [0 0]) (assoc :velocity velocity) (assoc :location location)))) (defn setup [] {:movers (map (fn [x] {:mass (+ 1 (rand-int 50)) :location [(rand-int 500) (rand-int 500)] :velocity [0 0] :acceleration [0 0]}) (range 0 10)) :attractors (map (fn [x] {:mass (rand-int 20) :location [(rand-int 500) (rand-int 500)]}) (range 0 5))}) (defn attract [mover attractor] (let [{loc1 :location} attractor {loc2 :location} mover vectorBetween (v/sub loc1 loc2) distanceBetween (q/constrain (v/mag vectorBetween) 5.0 25.0) G 0.4 strength (/ (* distanceBetween distanceBetween) (* G (:mass attractor) (:mass mover)))] (v/mult (v/normalize vectorBetween) strength))) (defn update-mover [attractors mover] (compute-position (reduce #(m/apply-force %1 (attract %1 %2)) mover attractors))) (defn update-state [{:keys [movers attractors] :as state}] (update state :movers (partial map (partial update-mover attractors)))) (defn draw [{:keys [attractors movers]}] (q/clear) (q/background 255) (doseq [{:keys [mass] [x y] :location} movers] (q/ellipse x y mass mass)) (doseq [{:keys [mass] [x y] :location} attractors] (q/rect x y mass mass))) (defn run [host] (q/defsketch own-force :host host :setup setup :draw draw :update update-state :middleware [md/fun-mode] :size [300 300]))
7f580b9abe5eb2d80851bf9b5127e822af9d0c40f8e5d52b509bb8c7a1fea2c2
cchalmers/circuit-notation
unittests.hs
{-# LANGUAGE Arrows #-} -- This option is a test by itself: if we were to export a plugin with the wrong type or name , GHC would refuse to compile this file . {-# OPTIONS -fplugin=CircuitNotation #-} module Main where main :: IO () main = pure ()
null
https://raw.githubusercontent.com/cchalmers/circuit-notation/d8f691faea696248c4621a6bd7b8cbef1687b0b7/tests/unittests.hs
haskell
# LANGUAGE Arrows # This option is a test by itself: if we were to export a plugin with the # OPTIONS -fplugin=CircuitNotation #
wrong type or name , GHC would refuse to compile this file . module Main where main :: IO () main = pure ()
3db08080b160779f860d9538264a7ddb65ba3a484cf845bd95fe91ed55114ae6
nuprl/gradual-typing-performance
cards.rkt
#lang racket (require "cards/cards.rkt") (provide (all-from-out "cards/cards.rkt"))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/gofish/base/cards.rkt
racket
#lang racket (require "cards/cards.rkt") (provide (all-from-out "cards/cards.rkt"))