_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
17bea8ac663449a67bac7ad3ef02a2742e305baffddd9e6da610f93a42acc4e8
jtkristensen/Jeopardy
Main.hs
module Main where -- In the future, the driver program goes here, but for now it is just used -- for experimentation {^o^}. import Core.Parser (Source, parseString, program_) import Transformations.Labeling import Analysis.ImplicitArguments fromRight :: Either a b -> b fromRight (Right b) = b fromRight _ = undefined fibProgram :: Source fibProgram = "data nat = [zero] [suc nat]." ++ "data pair = [pair nat nat]." ++ "first ([pair a _] : pair) : nat = a." ++ "second ([pair _ b] : pair) : nat = b." ++ "add (p : pair) : nat =" ++ " case second p : nat of" ++ " ; n ->" ++ " case first p : nat of" ++ " ; [zero] -> n" ++ " ; [suc k] -> add [pair k [suc n]]." ++ "fibber (p : pair) : pair =" ++ " case first p : nat of" ++ " ; m ->" ++ " case add p : nat of" ++ " ; sum -> [pair sum m]." ++ "fib_pair (n : nat) : pair =" ++ " case n : nat of" ++ " ; [zero ] -> [pair [suc [zero]] [suc [zero]]]" ++ " ; [suc n-1] ->" ++ " case fib_pair n-1 : pair of" ++ " ; p -> fibber p." ++ "fib (n : nat) : pair =" ++ " case fib_pair n : pair of" ++ " ; p ->" ++ " case first p : nat of" ++ " ; fib-n -> [pair n fib-n]." ++ "main fib." fibonacciProgram :: Source fibonacciProgram = "data nat = [zero] [suc nat]." ++ "data pair = [pair nat nat]." ++ "add ([pair m n] : pair) : nat =" ++ " case m : nat of" ++ " ; [zero] -> n" ++ " ; [suc k] -> add [pair k [suc n]]." ++ "fibber ([pair m n] : pair) : pair =" ++ " case add [pair m n] : nat of" ++ " ; sum -> [pair sum m]." ++ "fib_pair (n : nat) : pair =" ++ " case n : nat of" ++ " ; [zero ] -> [pair [suc [zero]] [suc [zero]]]" ++ " ; [suc n-1] ->" ++ " case fib_pair n-1 : pair of" ++ " ; p -> fibber p." ++ "fibbonaci (n : nat) : pair =" ++ " case fib_pair n : pair of" ++ " ; [pair _ fib-n] -> [pair n fib-n]." ++ "main fibbonaci." unswapProgram :: Source unswapProgram = "data nat = [zero] [suc nat]." ++ "data pair = [pair nat nat]." ++ "first ([pair a _] : pair) : nat = a." ++ "second ([pair _ b] : pair) : nat = b." ++ "unswap ([pair b a] : pair) : pair =" ++ " case (invert second) b : pair of" ++ " ; _p ->" ++ " case (invert first) a : pair of" ++ " ; _p -> _p." ++ "main unswap." -- Implicit arguments. main :: IO () main = do print $ implicitArgumentsAnalysis program print program where program = fmap snd $ fresh id $ fromRight $ parseString program_ fibonacciProgram -- main = print "Driver not yet implemented."
null
https://raw.githubusercontent.com/jtkristensen/Jeopardy/23be4d30592b1e9e9db640d1618ec76c54362d8b/app/Main.hs
haskell
In the future, the driver program goes here, but for now it is just used for experimentation {^o^}. Implicit arguments. main = print "Driver not yet implemented."
module Main where import Core.Parser (Source, parseString, program_) import Transformations.Labeling import Analysis.ImplicitArguments fromRight :: Either a b -> b fromRight (Right b) = b fromRight _ = undefined fibProgram :: Source fibProgram = "data nat = [zero] [suc nat]." ++ "data pair = [pair nat nat]." ++ "first ([pair a _] : pair) : nat = a." ++ "second ([pair _ b] : pair) : nat = b." ++ "add (p : pair) : nat =" ++ " case second p : nat of" ++ " ; n ->" ++ " case first p : nat of" ++ " ; [zero] -> n" ++ " ; [suc k] -> add [pair k [suc n]]." ++ "fibber (p : pair) : pair =" ++ " case first p : nat of" ++ " ; m ->" ++ " case add p : nat of" ++ " ; sum -> [pair sum m]." ++ "fib_pair (n : nat) : pair =" ++ " case n : nat of" ++ " ; [zero ] -> [pair [suc [zero]] [suc [zero]]]" ++ " ; [suc n-1] ->" ++ " case fib_pair n-1 : pair of" ++ " ; p -> fibber p." ++ "fib (n : nat) : pair =" ++ " case fib_pair n : pair of" ++ " ; p ->" ++ " case first p : nat of" ++ " ; fib-n -> [pair n fib-n]." ++ "main fib." fibonacciProgram :: Source fibonacciProgram = "data nat = [zero] [suc nat]." ++ "data pair = [pair nat nat]." ++ "add ([pair m n] : pair) : nat =" ++ " case m : nat of" ++ " ; [zero] -> n" ++ " ; [suc k] -> add [pair k [suc n]]." ++ "fibber ([pair m n] : pair) : pair =" ++ " case add [pair m n] : nat of" ++ " ; sum -> [pair sum m]." ++ "fib_pair (n : nat) : pair =" ++ " case n : nat of" ++ " ; [zero ] -> [pair [suc [zero]] [suc [zero]]]" ++ " ; [suc n-1] ->" ++ " case fib_pair n-1 : pair of" ++ " ; p -> fibber p." ++ "fibbonaci (n : nat) : pair =" ++ " case fib_pair n : pair of" ++ " ; [pair _ fib-n] -> [pair n fib-n]." ++ "main fibbonaci." unswapProgram :: Source unswapProgram = "data nat = [zero] [suc nat]." ++ "data pair = [pair nat nat]." ++ "first ([pair a _] : pair) : nat = a." ++ "second ([pair _ b] : pair) : nat = b." ++ "unswap ([pair b a] : pair) : pair =" ++ " case (invert second) b : pair of" ++ " ; _p ->" ++ " case (invert first) a : pair of" ++ " ; _p -> _p." ++ "main unswap." main :: IO () main = do print $ implicitArgumentsAnalysis program print program where program = fmap snd $ fresh id $ fromRight $ parseString program_ fibonacciProgram
ec362b544cc9a603bb922b382084e9b1c21a8e1c88d704cf3891195e80ba1cc0
MinaProtocol/mina
mina_base_call_stack_digest.mli
open Utils module Types : sig module type S = sig module V1 : sig type t = private Mina_base_zkapp_basic.F.V1.t end end end module type Concrete = sig module V1 : sig type t = Pasta_bindings.Fp.t end end module M : sig module V1 : sig type t = private Mina_base_zkapp_basic.F.V1.t end end module type Local_sig = Signature(Types).S module Make (Signature : Local_sig) (_ : functor (A : Concrete) -> Signature(A).S) : Signature(M).S include Types.S with module V1 = M.V1
null
https://raw.githubusercontent.com/MinaProtocol/mina/7a380064e215dc6aa152b76a7c3254949e383b1f/src/lib/mina_wire_types/mina_base/mina_base_call_stack_digest.mli
ocaml
open Utils module Types : sig module type S = sig module V1 : sig type t = private Mina_base_zkapp_basic.F.V1.t end end end module type Concrete = sig module V1 : sig type t = Pasta_bindings.Fp.t end end module M : sig module V1 : sig type t = private Mina_base_zkapp_basic.F.V1.t end end module type Local_sig = Signature(Types).S module Make (Signature : Local_sig) (_ : functor (A : Concrete) -> Signature(A).S) : Signature(M).S include Types.S with module V1 = M.V1
097086b37b951601cce27b58ebaf043cf3de7263508d572f0fc7f610134b2600
bmeurer/ocaml-arm
vivi2.ml
let rec p i = [< '1; '2; p (i + 1) >] let vivi = [|3|]
null
https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/ocamlbuild/test/test2/vivi2.ml
ocaml
let rec p i = [< '1; '2; p (i + 1) >] let vivi = [|3|]
aeae24a30eee78a8249a7531165498da7c7627b07f51154dc3e4595217eca42c
daypack-dev/daypack-lib
duration.mli
type t = { days : int; hours : int; minutes : int; seconds : int; } val zero : t val of_seconds : int64 -> (t, unit) result val to_seconds : t -> int64 val normalize : t -> t val duration_expr_parser : (t, unit) MParser.t val of_string : string -> (t, string) result module To_string : sig val human_readable_string_of_duration : t -> string end
null
https://raw.githubusercontent.com/daypack-dev/daypack-lib/63fa5d85007eca73aa6c51874a839636dd0403d3/src/duration.mli
ocaml
type t = { days : int; hours : int; minutes : int; seconds : int; } val zero : t val of_seconds : int64 -> (t, unit) result val to_seconds : t -> int64 val normalize : t -> t val duration_expr_parser : (t, unit) MParser.t val of_string : string -> (t, string) result module To_string : sig val human_readable_string_of_duration : t -> string end
4f12cc278f45293996433e97e192c7a701db006b6ab823ee35fce266dbd5af7d
abyala/advent-2021-clojure
day05.clj
(ns advent-2021-clojure.day05 (:require [advent-2021-clojure.point :as p] [advent-2021-clojure.utils :refer [parse-int]] [clojure.string :as str])) (defn parse-line [line] (let [[x1 y1 x2 y2] (->> (re-matches #"(\d+),(\d+) -> (\d+),(\d+)" line) rest (map parse-int))] [[x1 y1] [x2 y2]])) (defn parse-vents [input] (->> input str/split-lines (map parse-line))) (defn solve [input pred] (->> (parse-vents input) (filter pred) (map p/inclusive-line-between) (apply concat) frequencies (filter #(> (val %) 1)) count)) (defn part1 [input] (solve input (some-fn p/horizontal-line? p/vertical-line?))) (defn part2 [input] (solve input identity))
null
https://raw.githubusercontent.com/abyala/advent-2021-clojure/b4e68291e42c2813f7b512c141e8a1b53716efee/src/advent_2021_clojure/day05.clj
clojure
(ns advent-2021-clojure.day05 (:require [advent-2021-clojure.point :as p] [advent-2021-clojure.utils :refer [parse-int]] [clojure.string :as str])) (defn parse-line [line] (let [[x1 y1 x2 y2] (->> (re-matches #"(\d+),(\d+) -> (\d+),(\d+)" line) rest (map parse-int))] [[x1 y1] [x2 y2]])) (defn parse-vents [input] (->> input str/split-lines (map parse-line))) (defn solve [input pred] (->> (parse-vents input) (filter pred) (map p/inclusive-line-between) (apply concat) frequencies (filter #(> (val %) 1)) count)) (defn part1 [input] (solve input (some-fn p/horizontal-line? p/vertical-line?))) (defn part2 [input] (solve input identity))
f78fb1e681d0903cad804bbff24d0578f66b2d7657fae1c3d0f103878af270d5
SFML-haskell/SFML
SFCopyable.hs
module SFML.SFCopyable where class SFCopyable a where | Copy the given SFML resource . copy :: a -> IO a
null
https://raw.githubusercontent.com/SFML-haskell/SFML/1d1ceee6bc782f4f194853fbd0cc4acb33b86d41/src/SFML/SFCopyable.hs
haskell
module SFML.SFCopyable where class SFCopyable a where | Copy the given SFML resource . copy :: a -> IO a
f986dce9f711209533c64e50b4f2497360c63fa231c1c00e2e475abbee199c05
janestreet/core_kernel
weak_pointer.ml
(* We implement a weak pointer using a [Weak_array.t]. *) open! Base type 'a t = 'a Weak_array.t let create () = Weak_array.create ~len:1 We use a weak array of length 1 , so the weak pointer is at index 0 . let index = 0 let get t = Weak_array.get t index let sexp_of_t sexp_of_a t = [%sexp (get t : a Heap_block.t option)] let is_none t = Weak_array.is_none t index let is_some t = Weak_array.is_some t index let set t block = Weak_array.set t index (Some block)
null
https://raw.githubusercontent.com/janestreet/core_kernel/597299d11c2ee99f219592d89a5890f8f0b6dfe7/weak_pointer/src/weak_pointer.ml
ocaml
We implement a weak pointer using a [Weak_array.t].
open! Base type 'a t = 'a Weak_array.t let create () = Weak_array.create ~len:1 We use a weak array of length 1 , so the weak pointer is at index 0 . let index = 0 let get t = Weak_array.get t index let sexp_of_t sexp_of_a t = [%sexp (get t : a Heap_block.t option)] let is_none t = Weak_array.is_none t index let is_some t = Weak_array.is_some t index let set t block = Weak_array.set t index (Some block)
ac15ecda13cef595cd3f8b2828faec9c7e569c0738e555581a0c9c84549ac8f0
scrintal/heroicons-reagent
cloud_arrow_down.cljs
(ns com.scrintal.heroicons.solid.cloud-arrow-down) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M10.5 3.75a6 6 0 00-5.98 6.496A5.25 5.25 0 006.75 20.25H18a4.5 4.5 0 002.206-8.423 3.75 3.75 0 00-4.133-4.303A6.001 6.001 0 0010.5 3.75zm2.25 6a.75.75 0 00-1.5 0v4.94l-1.72-1.72a.75.75 0 00-1.06 1.06l3 3a.75.75 0 001.06 0l3-3a.75.75 0 10-1.06-1.06l-1.72 1.72V9.75z" :clipRule "evenodd"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/cloud_arrow_down.cljs
clojure
(ns com.scrintal.heroicons.solid.cloud-arrow-down) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M10.5 3.75a6 6 0 00-5.98 6.496A5.25 5.25 0 006.75 20.25H18a4.5 4.5 0 002.206-8.423 3.75 3.75 0 00-4.133-4.303A6.001 6.001 0 0010.5 3.75zm2.25 6a.75.75 0 00-1.5 0v4.94l-1.72-1.72a.75.75 0 00-1.06 1.06l3 3a.75.75 0 001.06 0l3-3a.75.75 0 10-1.06-1.06l-1.72 1.72V9.75z" :clipRule "evenodd"}]])
005e282457323db571c1d5201684ffb24fd4ba486586c42714aec30f5ae395cb
joaomilho/apalachin
auth_lib.erl
-module(auth_lib). -compile(export_all). redirect_to_signin() -> {redirect, "/signin"}. signin(Email, Password) -> boss_db:find(person, [{email, Email}, {password, Password}]). auth(UserId) -> case find_user_by_id(UserId) of undefined -> redirect_to_signin(); User -> {ok, User} end. find_user_by_session(SessionId) -> find_user_by_id(get_user_id_by_session(SessionId)). find_user_by_id(UserId) -> case boss_db:find(UserId) of {error, _} -> undefined; undefined -> undefined; User -> User end. get_user_id_by_session(SessionId) -> case SessionId of undefined -> undefined; _ -> boss_session:get_session_data(binary_to_list(SessionId), user_id) end.
null
https://raw.githubusercontent.com/joaomilho/apalachin/fdbcf43cf03d828d62463c219e0348c3b35a6a4c/src/lib/auth_lib.erl
erlang
-module(auth_lib). -compile(export_all). redirect_to_signin() -> {redirect, "/signin"}. signin(Email, Password) -> boss_db:find(person, [{email, Email}, {password, Password}]). auth(UserId) -> case find_user_by_id(UserId) of undefined -> redirect_to_signin(); User -> {ok, User} end. find_user_by_session(SessionId) -> find_user_by_id(get_user_id_by_session(SessionId)). find_user_by_id(UserId) -> case boss_db:find(UserId) of {error, _} -> undefined; undefined -> undefined; User -> User end. get_user_id_by_session(SessionId) -> case SessionId of undefined -> undefined; _ -> boss_session:get_session_data(binary_to_list(SessionId), user_id) end.
9df30768dd373e642ddb128f3e19bdc566cbf1a4b5cbbf18c0f971c518f90a07
marigold-dev/deku
michelson_primitives.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Metastate AG < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Helpers open Tezos_micheline open Micheline type error = | Unknown_primitive_name of string | Invalid_case of string | Invalid_primitive_name of ((string Micheline.canonical * Micheline.canonical_location)[@opaque]) [@@deriving show] type prim = | K_parameter | K_storage | K_code | K_view | D_False | D_Elt | D_Left | D_None | D_Pair | D_Right | D_Some | D_True | D_Unit | I_PACK | I_UNPACK | I_BLAKE2B | I_SHA256 | I_SHA512 | I_ABS | I_ADD | I_AMOUNT | I_AND | I_BALANCE | I_CAR | I_CDR | I_CHAIN_ID | I_CHECK_SIGNATURE | I_COMPARE | I_CONCAT | I_CONS | I_CREATE_ACCOUNT | I_CREATE_CONTRACT | I_IMPLICIT_ACCOUNT | I_DIP | I_DROP | I_DUP | I_VIEW | I_EDIV | I_EMPTY_BIG_MAP | I_EMPTY_MAP | I_EMPTY_SET | I_EQ | I_EXEC | I_APPLY | I_FAILWITH | I_GE | I_GET | I_GET_AND_UPDATE | I_GT | I_HASH_KEY | I_IF | I_IF_CONS | I_IF_LEFT | I_IF_NONE | I_INT | I_LAMBDA | I_LE | I_LEFT | I_LEVEL | I_LOOP | I_LSL | I_LSR | I_LT | I_MAP | I_MEM | I_MUL | I_NEG | I_NEQ | I_NIL | I_NONE | I_NOT | I_NOW | I_OR | I_PAIR | I_UNPAIR | I_PUSH | I_RIGHT | I_SIZE | I_SOME | I_SOURCE | I_SENDER | I_SELF | I_SELF_ADDRESS | I_SLICE | I_STEPS_TO_QUOTA | I_SUB | I_SUB_MUTEZ | I_SWAP | I_TRANSFER_TOKENS | I_SET_DELEGATE | I_UNIT | I_UPDATE | I_XOR | I_ITER | I_LOOP_LEFT | I_ADDRESS | I_CONTRACT | I_ISNAT | I_CAST | I_RENAME | I_SAPLING_EMPTY_STATE | I_SAPLING_VERIFY_UPDATE | I_DIG | I_DUG | I_NEVER | I_VOTING_POWER | I_TOTAL_VOTING_POWER | I_KECCAK | I_SHA3 | I_PAIRING_CHECK | I_TICKET | I_READ_TICKET | I_SPLIT_TICKET | I_JOIN_TICKETS | I_OPEN_CHEST | T_bool | T_contract | T_int | T_key | T_key_hash | T_lambda | T_list | T_map | T_big_map | T_nat | T_option | T_or | T_pair | T_set | T_signature | T_string | T_bytes | T_mutez | T_timestamp | T_unit | T_operation | T_address | T_sapling_transaction | T_sapling_state | T_chain_id | T_never | T_bls12_381_g1 | T_bls12_381_g2 | T_bls12_381_fr | T_ticket | T_chest_key | T_chest | H_constant (* Auxiliary types for error documentation. All the prim constructor prefixes must match their namespace. *) type namespace = | (* prefix "T" *) Type_namespace | (* prefix "D" *) Constant_namespace | (* prefix "I" *) Instr_namespace | (* prefix "K" *) Keyword_namespace | (* prefix "H" *) Constant_hash_namespace let namespace = function | K_code | K_view | K_parameter | K_storage -> Keyword_namespace | D_Elt | D_False | D_Left | D_None | D_Pair | D_Right | D_Some | D_True | D_Unit -> Constant_namespace | I_ABS | I_ADD | I_ADDRESS | I_AMOUNT | I_AND | I_APPLY | I_BALANCE | I_BLAKE2B | I_CAR | I_CAST | I_CDR | I_CHAIN_ID | I_CHECK_SIGNATURE | I_COMPARE | I_CONCAT | I_CONS | I_CONTRACT | I_CREATE_ACCOUNT | I_CREATE_CONTRACT | I_DIG | I_DIP | I_DROP | I_DUG | I_DUP | I_VIEW | I_EDIV | I_EMPTY_BIG_MAP | I_EMPTY_MAP | I_EMPTY_SET | I_EQ | I_EXEC | I_FAILWITH | I_GE | I_GET | I_GET_AND_UPDATE | I_GT | I_HASH_KEY | I_IF | I_IF_CONS | I_IF_LEFT | I_IF_NONE | I_IMPLICIT_ACCOUNT | I_INT | I_ISNAT | I_ITER | I_JOIN_TICKETS | I_KECCAK | I_LAMBDA | I_LE | I_LEFT | I_LEVEL | I_LOOP | I_LOOP_LEFT | I_LSL | I_LSR | I_LT | I_MAP | I_MEM | I_MUL | I_NEG | I_NEQ | I_NEVER | I_NIL | I_NONE | I_NOT | I_NOW | I_OR | I_PACK | I_PAIR | I_PAIRING_CHECK | I_PUSH | I_READ_TICKET | I_RENAME | I_RIGHT | I_SAPLING_EMPTY_STATE | I_SAPLING_VERIFY_UPDATE | I_SELF | I_SELF_ADDRESS | I_SENDER | I_SET_DELEGATE | I_SHA256 | I_SHA512 | I_SHA3 | I_SIZE | I_SLICE | I_SOME | I_SOURCE | I_SPLIT_TICKET | I_STEPS_TO_QUOTA | I_SUB | I_SUB_MUTEZ | I_SWAP | I_TICKET | I_TOTAL_VOTING_POWER | I_TRANSFER_TOKENS | I_UNIT | I_UNPACK | I_UNPAIR | I_UPDATE | I_VOTING_POWER | I_XOR | I_OPEN_CHEST -> Instr_namespace | T_address | T_big_map | T_bool | T_bytes | T_chain_id | T_contract | T_int | T_key | T_key_hash | T_lambda | T_list | T_map | T_mutez | T_nat | T_never | T_operation | T_option | T_or | T_pair | T_sapling_state | T_sapling_transaction | T_set | T_signature | T_string | T_timestamp | T_unit | T_bls12_381_fr | T_bls12_381_g1 | T_bls12_381_g2 | T_ticket | T_chest_key | T_chest -> Type_namespace | H_constant -> Constant_hash_namespace let valid_case name = let is_lower = function '_' | 'a' .. 'z' -> true | _ -> false in let is_upper = function '_' | 'A' .. 'Z' -> true | _ -> false in let rec for_all a b f = a > b || (f a && for_all (a + 1) b f) in let len = String.length name in Int.(equal len 0 |> not) && Char.(equal name.[0] '_' |> not) && ((is_upper name.[0] && for_all 1 (len - 1) (fun i -> is_upper name.[i])) || (is_upper name.[0] && for_all 1 (len - 1) (fun i -> is_lower name.[i])) || (is_lower name.[0] && for_all 1 (len - 1) (fun i -> is_lower name.[i])) ) let string_of_prim = function | K_parameter -> "parameter" | K_storage -> "storage" | K_code -> "code" | K_view -> "view" | D_False -> "False" | D_Elt -> "Elt" | D_Left -> "Left" | D_None -> "None" | D_Pair -> "Pair" | D_Right -> "Right" | D_Some -> "Some" | D_True -> "True" | D_Unit -> "Unit" | I_PACK -> "PACK" | I_UNPACK -> "UNPACK" | I_BLAKE2B -> "BLAKE2B" | I_SHA256 -> "SHA256" | I_SHA512 -> "SHA512" | I_ABS -> "ABS" | I_ADD -> "ADD" | I_AMOUNT -> "AMOUNT" | I_AND -> "AND" | I_BALANCE -> "BALANCE" | I_CAR -> "CAR" | I_CDR -> "CDR" | I_CHAIN_ID -> "CHAIN_ID" | I_CHECK_SIGNATURE -> "CHECK_SIGNATURE" | I_COMPARE -> "COMPARE" | I_CONCAT -> "CONCAT" | I_CONS -> "CONS" | I_CREATE_ACCOUNT -> "CREATE_ACCOUNT" | I_CREATE_CONTRACT -> "CREATE_CONTRACT" | I_IMPLICIT_ACCOUNT -> "IMPLICIT_ACCOUNT" | I_DIP -> "DIP" | I_DROP -> "DROP" | I_DUP -> "DUP" | I_EDIV -> "EDIV" | I_EMPTY_BIG_MAP -> "EMPTY_BIG_MAP" | I_EMPTY_MAP -> "EMPTY_MAP" | I_EMPTY_SET -> "EMPTY_SET" | I_EQ -> "EQ" | I_EXEC -> "EXEC" | I_APPLY -> "APPLY" | I_FAILWITH -> "FAILWITH" | I_GE -> "GE" | I_GET -> "GET" | I_GET_AND_UPDATE -> "GET_AND_UPDATE" | I_GT -> "GT" | I_HASH_KEY -> "HASH_KEY" | I_IF -> "IF" | I_IF_CONS -> "IF_CONS" | I_IF_LEFT -> "IF_LEFT" | I_IF_NONE -> "IF_NONE" | I_INT -> "INT" | I_LAMBDA -> "LAMBDA" | I_LE -> "LE" | I_LEFT -> "LEFT" | I_LEVEL -> "LEVEL" | I_LOOP -> "LOOP" | I_LSL -> "LSL" | I_LSR -> "LSR" | I_LT -> "LT" | I_MAP -> "MAP" | I_MEM -> "MEM" | I_MUL -> "MUL" | I_NEG -> "NEG" | I_NEQ -> "NEQ" | I_NIL -> "NIL" | I_NONE -> "NONE" | I_NOT -> "NOT" | I_NOW -> "NOW" | I_OR -> "OR" | I_PAIR -> "PAIR" | I_PUSH -> "PUSH" | I_RIGHT -> "RIGHT" | I_SIZE -> "SIZE" | I_SOME -> "SOME" | I_SOURCE -> "SOURCE" | I_SENDER -> "SENDER" | I_SELF -> "SELF" | I_SELF_ADDRESS -> "SELF_ADDRESS" | I_SLICE -> "SLICE" | I_STEPS_TO_QUOTA -> "STEPS_TO_QUOTA" | I_SUB -> "SUB" | I_SUB_MUTEZ -> "SUB_MUTEZ" | I_SWAP -> "SWAP" | I_TRANSFER_TOKENS -> "TRANSFER_TOKENS" | I_SET_DELEGATE -> "SET_DELEGATE" | I_UNIT -> "UNIT" | I_UNPAIR -> "UNPAIR" | I_UPDATE -> "UPDATE" | I_XOR -> "XOR" | I_ITER -> "ITER" | I_LOOP_LEFT -> "LOOP_LEFT" | I_ADDRESS -> "ADDRESS" | I_CONTRACT -> "CONTRACT" | I_ISNAT -> "ISNAT" | I_CAST -> "CAST" | I_RENAME -> "RENAME" | I_SAPLING_EMPTY_STATE -> "SAPLING_EMPTY_STATE" | I_SAPLING_VERIFY_UPDATE -> "SAPLING_VERIFY_UPDATE" | I_DIG -> "DIG" | I_DUG -> "DUG" | I_NEVER -> "NEVER" | I_VOTING_POWER -> "VOTING_POWER" | I_TOTAL_VOTING_POWER -> "TOTAL_VOTING_POWER" | I_KECCAK -> "KECCAK" | I_SHA3 -> "SHA3" | I_PAIRING_CHECK -> "PAIRING_CHECK" | I_TICKET -> "TICKET" | I_READ_TICKET -> "READ_TICKET" | I_SPLIT_TICKET -> "SPLIT_TICKET" | I_JOIN_TICKETS -> "JOIN_TICKETS" | I_OPEN_CHEST -> "OPEN_CHEST" | I_VIEW -> "VIEW" | T_bool -> "bool" | T_contract -> "contract" | T_int -> "int" | T_key -> "key" | T_key_hash -> "key_hash" | T_lambda -> "lambda" | T_list -> "list" | T_map -> "map" | T_big_map -> "big_map" | T_nat -> "nat" | T_option -> "option" | T_or -> "or" | T_pair -> "pair" | T_set -> "set" | T_signature -> "signature" | T_string -> "string" | T_bytes -> "bytes" | T_mutez -> "mutez" | T_timestamp -> "timestamp" | T_unit -> "unit" | T_operation -> "operation" | T_address -> "address" | T_sapling_state -> "sapling_state" | T_sapling_transaction -> "sapling_transaction" | T_chain_id -> "chain_id" | T_never -> "never" | T_bls12_381_g1 -> "bls12_381_g1" | T_bls12_381_g2 -> "bls12_381_g2" | T_bls12_381_fr -> "bls12_381_fr" | T_ticket -> "ticket" | T_chest_key -> "chest_key" | T_chest -> "chest" | H_constant -> "constant" let prim_of_string = let ok = Result.ok in let error = Result.error in function | "parameter" -> ok K_parameter | "storage" -> ok K_storage | "code" -> ok K_code | "view" -> ok K_view | "False" -> ok D_False | "Elt" -> ok D_Elt | "Left" -> ok D_Left | "None" -> ok D_None | "Pair" -> ok D_Pair | "Right" -> ok D_Right | "Some" -> ok D_Some | "True" -> ok D_True | "Unit" -> ok D_Unit | "PACK" -> ok I_PACK | "UNPACK" -> ok I_UNPACK | "BLAKE2B" -> ok I_BLAKE2B | "SHA256" -> ok I_SHA256 | "SHA512" -> ok I_SHA512 | "ABS" -> ok I_ABS | "ADD" -> ok I_ADD | "AMOUNT" -> ok I_AMOUNT | "AND" -> ok I_AND | "BALANCE" -> ok I_BALANCE | "CAR" -> ok I_CAR | "CDR" -> ok I_CDR | "CHAIN_ID" -> ok I_CHAIN_ID | "CHECK_SIGNATURE" -> ok I_CHECK_SIGNATURE | "COMPARE" -> ok I_COMPARE | "CONCAT" -> ok I_CONCAT | "CONS" -> ok I_CONS | "CREATE_ACCOUNT" -> ok I_CREATE_ACCOUNT | "CREATE_CONTRACT" -> ok I_CREATE_CONTRACT | "IMPLICIT_ACCOUNT" -> ok I_IMPLICIT_ACCOUNT | "DIP" -> ok I_DIP | "DROP" -> ok I_DROP | "DUP" -> ok I_DUP | "VIEW" -> ok I_VIEW | "EDIV" -> ok I_EDIV | "EMPTY_BIG_MAP" -> ok I_EMPTY_BIG_MAP | "EMPTY_MAP" -> ok I_EMPTY_MAP | "EMPTY_SET" -> ok I_EMPTY_SET | "EQ" -> ok I_EQ | "EXEC" -> ok I_EXEC | "APPLY" -> ok I_APPLY | "FAILWITH" -> ok I_FAILWITH | "GE" -> ok I_GE | "GET" -> ok I_GET | "GET_AND_UPDATE" -> ok I_GET_AND_UPDATE | "GT" -> ok I_GT | "HASH_KEY" -> ok I_HASH_KEY | "IF" -> ok I_IF | "IF_CONS" -> ok I_IF_CONS | "IF_LEFT" -> ok I_IF_LEFT | "IF_NONE" -> ok I_IF_NONE | "INT" -> ok I_INT | "KECCAK" -> ok I_KECCAK | "LAMBDA" -> ok I_LAMBDA | "LE" -> ok I_LE | "LEFT" -> ok I_LEFT | "LEVEL" -> ok I_LEVEL | "LOOP" -> ok I_LOOP | "LSL" -> ok I_LSL | "LSR" -> ok I_LSR | "LT" -> ok I_LT | "MAP" -> ok I_MAP | "MEM" -> ok I_MEM | "MUL" -> ok I_MUL | "NEG" -> ok I_NEG | "NEQ" -> ok I_NEQ | "NIL" -> ok I_NIL | "NONE" -> ok I_NONE | "NOT" -> ok I_NOT | "NOW" -> ok I_NOW | "OR" -> ok I_OR | "PAIR" -> ok I_PAIR | "UNPAIR" -> ok I_UNPAIR | "PAIRING_CHECK" -> ok I_PAIRING_CHECK | "PUSH" -> ok I_PUSH | "RIGHT" -> ok I_RIGHT | "SHA3" -> ok I_SHA3 | "SIZE" -> ok I_SIZE | "SOME" -> ok I_SOME | "SOURCE" -> ok I_SOURCE | "SENDER" -> ok I_SENDER | "SELF" -> ok I_SELF | "SELF_ADDRESS" -> ok I_SELF_ADDRESS | "SLICE" -> ok I_SLICE | "STEPS_TO_QUOTA" -> ok I_STEPS_TO_QUOTA | "SUB" -> ok I_SUB | "SUB_MUTEZ" -> ok I_SUB_MUTEZ | "SWAP" -> ok I_SWAP | "TRANSFER_TOKENS" -> ok I_TRANSFER_TOKENS | "SET_DELEGATE" -> ok I_SET_DELEGATE | "UNIT" -> ok I_UNIT | "UPDATE" -> ok I_UPDATE | "XOR" -> ok I_XOR | "ITER" -> ok I_ITER | "LOOP_LEFT" -> ok I_LOOP_LEFT | "ADDRESS" -> ok I_ADDRESS | "CONTRACT" -> ok I_CONTRACT | "ISNAT" -> ok I_ISNAT | "CAST" -> ok I_CAST | "RENAME" -> ok I_RENAME | "SAPLING_EMPTY_STATE" -> ok I_SAPLING_EMPTY_STATE | "SAPLING_VERIFY_UPDATE" -> ok I_SAPLING_VERIFY_UPDATE | "DIG" -> ok I_DIG | "DUG" -> ok I_DUG | "NEVER" -> ok I_NEVER | "VOTING_POWER" -> ok I_VOTING_POWER | "TOTAL_VOTING_POWER" -> ok I_TOTAL_VOTING_POWER | "TICKET" -> ok I_TICKET | "READ_TICKET" -> ok I_READ_TICKET | "SPLIT_TICKET" -> ok I_SPLIT_TICKET | "JOIN_TICKETS" -> ok I_JOIN_TICKETS | "OPEN_CHEST" -> ok I_OPEN_CHEST | "bool" -> ok T_bool | "contract" -> ok T_contract | "int" -> ok T_int | "key" -> ok T_key | "key_hash" -> ok T_key_hash | "lambda" -> ok T_lambda | "list" -> ok T_list | "map" -> ok T_map | "big_map" -> ok T_big_map | "nat" -> ok T_nat | "option" -> ok T_option | "or" -> ok T_or | "pair" -> ok T_pair | "set" -> ok T_set | "signature" -> ok T_signature | "string" -> ok T_string | "bytes" -> ok T_bytes | "mutez" -> ok T_mutez | "timestamp" -> ok T_timestamp | "unit" -> ok T_unit | "operation" -> ok T_operation | "address" -> ok T_address | "sapling_state" -> ok T_sapling_state | "sapling_transaction" -> ok T_sapling_transaction | "chain_id" -> ok T_chain_id | "never" -> ok T_never | "bls12_381_g1" -> ok T_bls12_381_g1 | "bls12_381_g2" -> ok T_bls12_381_g2 | "bls12_381_fr" -> ok T_bls12_381_fr | "ticket" -> ok T_ticket | "chest_key" -> ok T_chest_key | "chest" -> ok T_chest | "constant" -> ok H_constant | n -> if valid_case n then error (Unknown_primitive_name n) else error (Invalid_case n) module type MONAD = sig type 'a t val return : 'a -> 'a t val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t end module Traverse (M : MONAD) = struct open M let traverse f l = let rec aux f acc l = match l with | [] -> return (List.rev acc) | x :: tail -> f x >>= fun x' -> aux f (x' :: acc) tail in aux f [] l end let prims_of_strings expr = let module Lt = Traverse (struct include Result type nonrec 'a t = ('a, error) t let return t = Ok t let ( >>= ) = Result.bind end) in let open Result.Let_syntax in let rec convert = function | (Int _ | String _ | Bytes _) as expr -> Result.ok expr | Prim (loc, prim, args, annot) -> let* prim = prim_of_string prim |> Result.map_error (fun _ -> Invalid_primitive_name (expr, loc)) in Lt.traverse convert args |> Result.map (fun args -> Prim (loc, prim, args, annot)) | Seq (loc, args) -> Lt.traverse convert args |> Result.map (fun args -> Seq (loc, args)) in convert (root expr) |> Result.map (fun expr -> strip_locations expr) let strings_of_prims expr = let rec convert = function | (Int _ | String _ | Bytes _) as expr -> expr | Prim (loc, prim, args, annot) -> let prim = string_of_prim prim in let args = List.map convert args in Prim (loc, prim, args, annot) | Seq (loc, args) -> let args = List.map convert args in Seq (loc, args) in strip_locations (convert (root expr)) let prim_encoding = let open Data_encoding in def "michelson.v1.primitives" @@ string_enum Add the comment below every 10 lines [ /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("parameter", K_parameter); ("storage", K_storage); ("code", K_code); ("False", D_False); ("Elt", D_Elt); ("Left", D_Left); ("None", D_None); ("Pair", D_Pair); ("Right", D_Right); ("Some", D_Some); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("True", D_True); ("Unit", D_Unit); ("PACK", I_PACK); ("UNPACK", I_UNPACK); ("BLAKE2B", I_BLAKE2B); ("SHA256", I_SHA256); ("SHA512", I_SHA512); ("ABS", I_ABS); ("ADD", I_ADD); ("AMOUNT", I_AMOUNT); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("AND", I_AND); ("BALANCE", I_BALANCE); ("CAR", I_CAR); ("CDR", I_CDR); ("CHECK_SIGNATURE", I_CHECK_SIGNATURE); ("COMPARE", I_COMPARE); ("CONCAT", I_CONCAT); ("CONS", I_CONS); ("CREATE_ACCOUNT", I_CREATE_ACCOUNT); ("CREATE_CONTRACT", I_CREATE_CONTRACT); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("IMPLICIT_ACCOUNT", I_IMPLICIT_ACCOUNT); ("DIP", I_DIP); ("DROP", I_DROP); ("DUP", I_DUP); ("EDIV", I_EDIV); ("EMPTY_MAP", I_EMPTY_MAP); ("EMPTY_SET", I_EMPTY_SET); ("EQ", I_EQ); ("EXEC", I_EXEC); ("FAILWITH", I_FAILWITH); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("GE", I_GE); ("GET", I_GET); ("GT", I_GT); ("HASH_KEY", I_HASH_KEY); ("IF", I_IF); ("IF_CONS", I_IF_CONS); ("IF_LEFT", I_IF_LEFT); ("IF_NONE", I_IF_NONE); ("INT", I_INT); ("LAMBDA", I_LAMBDA); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("LE", I_LE); ("LEFT", I_LEFT); ("LOOP", I_LOOP); ("LSL", I_LSL); ("LSR", I_LSR); ("LT", I_LT); ("MAP", I_MAP); ("MEM", I_MEM); ("MUL", I_MUL); ("NEG", I_NEG); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("NEQ", I_NEQ); ("NIL", I_NIL); ("NONE", I_NONE); ("NOT", I_NOT); ("NOW", I_NOW); ("OR", I_OR); ("PAIR", I_PAIR); ("PUSH", I_PUSH); ("RIGHT", I_RIGHT); ("SIZE", I_SIZE); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("SOME", I_SOME); ("SOURCE", I_SOURCE); ("SENDER", I_SENDER); ("SELF", I_SELF); ("STEPS_TO_QUOTA", I_STEPS_TO_QUOTA); ("SUB", I_SUB); ("SWAP", I_SWAP); ("TRANSFER_TOKENS", I_TRANSFER_TOKENS); ("SET_DELEGATE", I_SET_DELEGATE); ("UNIT", I_UNIT); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("UPDATE", I_UPDATE); ("XOR", I_XOR); ("ITER", I_ITER); ("LOOP_LEFT", I_LOOP_LEFT); ("ADDRESS", I_ADDRESS); ("CONTRACT", I_CONTRACT); ("ISNAT", I_ISNAT); ("CAST", I_CAST); ("RENAME", I_RENAME); ("bool", T_bool); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("contract", T_contract); ("int", T_int); ("key", T_key); ("key_hash", T_key_hash); ("lambda", T_lambda); ("list", T_list); ("map", T_map); ("big_map", T_big_map); ("nat", T_nat); ("option", T_option); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("or", T_or); ("pair", T_pair); ("set", T_set); ("signature", T_signature); ("string", T_string); ("bytes", T_bytes); ("mutez", T_mutez); ("timestamp", T_timestamp); ("unit", T_unit); ("operation", T_operation); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("address", T_address); (* Alpha_002 addition *) ("SLICE", I_SLICE); Alpha_005 addition ("DIG", I_DIG); ("DUG", I_DUG); ("EMPTY_BIG_MAP", I_EMPTY_BIG_MAP); ("APPLY", I_APPLY); ("chain_id", T_chain_id); ("CHAIN_ID", I_CHAIN_ID); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . (* Alpha_008 addition *) ("LEVEL", I_LEVEL); ("SELF_ADDRESS", I_SELF_ADDRESS); ("never", T_never); ("NEVER", I_NEVER); ("UNPAIR", I_UNPAIR); ("VOTING_POWER", I_VOTING_POWER); ("TOTAL_VOTING_POWER", I_TOTAL_VOTING_POWER); ("KECCAK", I_KECCAK); ("SHA3", I_SHA3); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . (* Alpha_008 addition *) ("PAIRING_CHECK", I_PAIRING_CHECK); ("bls12_381_g1", T_bls12_381_g1); ("bls12_381_g2", T_bls12_381_g2); ("bls12_381_fr", T_bls12_381_fr); ("sapling_state", T_sapling_state); ("sapling_transaction", T_sapling_transaction); ("SAPLING_EMPTY_STATE", I_SAPLING_EMPTY_STATE); ("SAPLING_VERIFY_UPDATE", I_SAPLING_VERIFY_UPDATE); ("ticket", T_ticket); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . (* Alpha_008 addition *) ("TICKET", I_TICKET); ("READ_TICKET", I_READ_TICKET); ("SPLIT_TICKET", I_SPLIT_TICKET); ("JOIN_TICKETS", I_JOIN_TICKETS); ("GET_AND_UPDATE", I_GET_AND_UPDATE); (* Alpha_011 addition *) ("chest", T_chest); ("chest_key", T_chest_key); ("OPEN_CHEST", I_OPEN_CHEST); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("VIEW", I_VIEW); ("view", K_view); ("constant", H_constant); (* Alpha_012 addition *) ("SUB_MUTEZ", I_SUB_MUTEZ) (* New instructions must be added here, for backward compatibility of the encoding. *) (* Keep the comment above at the end of the list *); ] let string_of_namespace = function | Type_namespace -> "T" | Constant_namespace -> "D" | Instr_namespace -> "I" | Keyword_namespace -> "K" | Constant_hash_namespace -> "H"
null
https://raw.githubusercontent.com/marigold-dev/deku/5d578d6a6124ade1deff4ed88eac71de17a065fd/deku-c/tunac/lib/michelson_primitives.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** Auxiliary types for error documentation. All the prim constructor prefixes must match their namespace. prefix "T" prefix "D" prefix "I" prefix "K" prefix "H" Alpha_002 addition Alpha_008 addition Alpha_008 addition Alpha_008 addition Alpha_011 addition Alpha_012 addition New instructions must be added here, for backward compatibility of the encoding. Keep the comment above at the end of the list
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Metastate AG < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Helpers open Tezos_micheline open Micheline type error = | Unknown_primitive_name of string | Invalid_case of string | Invalid_primitive_name of ((string Micheline.canonical * Micheline.canonical_location)[@opaque]) [@@deriving show] type prim = | K_parameter | K_storage | K_code | K_view | D_False | D_Elt | D_Left | D_None | D_Pair | D_Right | D_Some | D_True | D_Unit | I_PACK | I_UNPACK | I_BLAKE2B | I_SHA256 | I_SHA512 | I_ABS | I_ADD | I_AMOUNT | I_AND | I_BALANCE | I_CAR | I_CDR | I_CHAIN_ID | I_CHECK_SIGNATURE | I_COMPARE | I_CONCAT | I_CONS | I_CREATE_ACCOUNT | I_CREATE_CONTRACT | I_IMPLICIT_ACCOUNT | I_DIP | I_DROP | I_DUP | I_VIEW | I_EDIV | I_EMPTY_BIG_MAP | I_EMPTY_MAP | I_EMPTY_SET | I_EQ | I_EXEC | I_APPLY | I_FAILWITH | I_GE | I_GET | I_GET_AND_UPDATE | I_GT | I_HASH_KEY | I_IF | I_IF_CONS | I_IF_LEFT | I_IF_NONE | I_INT | I_LAMBDA | I_LE | I_LEFT | I_LEVEL | I_LOOP | I_LSL | I_LSR | I_LT | I_MAP | I_MEM | I_MUL | I_NEG | I_NEQ | I_NIL | I_NONE | I_NOT | I_NOW | I_OR | I_PAIR | I_UNPAIR | I_PUSH | I_RIGHT | I_SIZE | I_SOME | I_SOURCE | I_SENDER | I_SELF | I_SELF_ADDRESS | I_SLICE | I_STEPS_TO_QUOTA | I_SUB | I_SUB_MUTEZ | I_SWAP | I_TRANSFER_TOKENS | I_SET_DELEGATE | I_UNIT | I_UPDATE | I_XOR | I_ITER | I_LOOP_LEFT | I_ADDRESS | I_CONTRACT | I_ISNAT | I_CAST | I_RENAME | I_SAPLING_EMPTY_STATE | I_SAPLING_VERIFY_UPDATE | I_DIG | I_DUG | I_NEVER | I_VOTING_POWER | I_TOTAL_VOTING_POWER | I_KECCAK | I_SHA3 | I_PAIRING_CHECK | I_TICKET | I_READ_TICKET | I_SPLIT_TICKET | I_JOIN_TICKETS | I_OPEN_CHEST | T_bool | T_contract | T_int | T_key | T_key_hash | T_lambda | T_list | T_map | T_big_map | T_nat | T_option | T_or | T_pair | T_set | T_signature | T_string | T_bytes | T_mutez | T_timestamp | T_unit | T_operation | T_address | T_sapling_transaction | T_sapling_state | T_chain_id | T_never | T_bls12_381_g1 | T_bls12_381_g2 | T_bls12_381_fr | T_ticket | T_chest_key | T_chest | H_constant type namespace = let namespace = function | K_code | K_view | K_parameter | K_storage -> Keyword_namespace | D_Elt | D_False | D_Left | D_None | D_Pair | D_Right | D_Some | D_True | D_Unit -> Constant_namespace | I_ABS | I_ADD | I_ADDRESS | I_AMOUNT | I_AND | I_APPLY | I_BALANCE | I_BLAKE2B | I_CAR | I_CAST | I_CDR | I_CHAIN_ID | I_CHECK_SIGNATURE | I_COMPARE | I_CONCAT | I_CONS | I_CONTRACT | I_CREATE_ACCOUNT | I_CREATE_CONTRACT | I_DIG | I_DIP | I_DROP | I_DUG | I_DUP | I_VIEW | I_EDIV | I_EMPTY_BIG_MAP | I_EMPTY_MAP | I_EMPTY_SET | I_EQ | I_EXEC | I_FAILWITH | I_GE | I_GET | I_GET_AND_UPDATE | I_GT | I_HASH_KEY | I_IF | I_IF_CONS | I_IF_LEFT | I_IF_NONE | I_IMPLICIT_ACCOUNT | I_INT | I_ISNAT | I_ITER | I_JOIN_TICKETS | I_KECCAK | I_LAMBDA | I_LE | I_LEFT | I_LEVEL | I_LOOP | I_LOOP_LEFT | I_LSL | I_LSR | I_LT | I_MAP | I_MEM | I_MUL | I_NEG | I_NEQ | I_NEVER | I_NIL | I_NONE | I_NOT | I_NOW | I_OR | I_PACK | I_PAIR | I_PAIRING_CHECK | I_PUSH | I_READ_TICKET | I_RENAME | I_RIGHT | I_SAPLING_EMPTY_STATE | I_SAPLING_VERIFY_UPDATE | I_SELF | I_SELF_ADDRESS | I_SENDER | I_SET_DELEGATE | I_SHA256 | I_SHA512 | I_SHA3 | I_SIZE | I_SLICE | I_SOME | I_SOURCE | I_SPLIT_TICKET | I_STEPS_TO_QUOTA | I_SUB | I_SUB_MUTEZ | I_SWAP | I_TICKET | I_TOTAL_VOTING_POWER | I_TRANSFER_TOKENS | I_UNIT | I_UNPACK | I_UNPAIR | I_UPDATE | I_VOTING_POWER | I_XOR | I_OPEN_CHEST -> Instr_namespace | T_address | T_big_map | T_bool | T_bytes | T_chain_id | T_contract | T_int | T_key | T_key_hash | T_lambda | T_list | T_map | T_mutez | T_nat | T_never | T_operation | T_option | T_or | T_pair | T_sapling_state | T_sapling_transaction | T_set | T_signature | T_string | T_timestamp | T_unit | T_bls12_381_fr | T_bls12_381_g1 | T_bls12_381_g2 | T_ticket | T_chest_key | T_chest -> Type_namespace | H_constant -> Constant_hash_namespace let valid_case name = let is_lower = function '_' | 'a' .. 'z' -> true | _ -> false in let is_upper = function '_' | 'A' .. 'Z' -> true | _ -> false in let rec for_all a b f = a > b || (f a && for_all (a + 1) b f) in let len = String.length name in Int.(equal len 0 |> not) && Char.(equal name.[0] '_' |> not) && ((is_upper name.[0] && for_all 1 (len - 1) (fun i -> is_upper name.[i])) || (is_upper name.[0] && for_all 1 (len - 1) (fun i -> is_lower name.[i])) || (is_lower name.[0] && for_all 1 (len - 1) (fun i -> is_lower name.[i])) ) let string_of_prim = function | K_parameter -> "parameter" | K_storage -> "storage" | K_code -> "code" | K_view -> "view" | D_False -> "False" | D_Elt -> "Elt" | D_Left -> "Left" | D_None -> "None" | D_Pair -> "Pair" | D_Right -> "Right" | D_Some -> "Some" | D_True -> "True" | D_Unit -> "Unit" | I_PACK -> "PACK" | I_UNPACK -> "UNPACK" | I_BLAKE2B -> "BLAKE2B" | I_SHA256 -> "SHA256" | I_SHA512 -> "SHA512" | I_ABS -> "ABS" | I_ADD -> "ADD" | I_AMOUNT -> "AMOUNT" | I_AND -> "AND" | I_BALANCE -> "BALANCE" | I_CAR -> "CAR" | I_CDR -> "CDR" | I_CHAIN_ID -> "CHAIN_ID" | I_CHECK_SIGNATURE -> "CHECK_SIGNATURE" | I_COMPARE -> "COMPARE" | I_CONCAT -> "CONCAT" | I_CONS -> "CONS" | I_CREATE_ACCOUNT -> "CREATE_ACCOUNT" | I_CREATE_CONTRACT -> "CREATE_CONTRACT" | I_IMPLICIT_ACCOUNT -> "IMPLICIT_ACCOUNT" | I_DIP -> "DIP" | I_DROP -> "DROP" | I_DUP -> "DUP" | I_EDIV -> "EDIV" | I_EMPTY_BIG_MAP -> "EMPTY_BIG_MAP" | I_EMPTY_MAP -> "EMPTY_MAP" | I_EMPTY_SET -> "EMPTY_SET" | I_EQ -> "EQ" | I_EXEC -> "EXEC" | I_APPLY -> "APPLY" | I_FAILWITH -> "FAILWITH" | I_GE -> "GE" | I_GET -> "GET" | I_GET_AND_UPDATE -> "GET_AND_UPDATE" | I_GT -> "GT" | I_HASH_KEY -> "HASH_KEY" | I_IF -> "IF" | I_IF_CONS -> "IF_CONS" | I_IF_LEFT -> "IF_LEFT" | I_IF_NONE -> "IF_NONE" | I_INT -> "INT" | I_LAMBDA -> "LAMBDA" | I_LE -> "LE" | I_LEFT -> "LEFT" | I_LEVEL -> "LEVEL" | I_LOOP -> "LOOP" | I_LSL -> "LSL" | I_LSR -> "LSR" | I_LT -> "LT" | I_MAP -> "MAP" | I_MEM -> "MEM" | I_MUL -> "MUL" | I_NEG -> "NEG" | I_NEQ -> "NEQ" | I_NIL -> "NIL" | I_NONE -> "NONE" | I_NOT -> "NOT" | I_NOW -> "NOW" | I_OR -> "OR" | I_PAIR -> "PAIR" | I_PUSH -> "PUSH" | I_RIGHT -> "RIGHT" | I_SIZE -> "SIZE" | I_SOME -> "SOME" | I_SOURCE -> "SOURCE" | I_SENDER -> "SENDER" | I_SELF -> "SELF" | I_SELF_ADDRESS -> "SELF_ADDRESS" | I_SLICE -> "SLICE" | I_STEPS_TO_QUOTA -> "STEPS_TO_QUOTA" | I_SUB -> "SUB" | I_SUB_MUTEZ -> "SUB_MUTEZ" | I_SWAP -> "SWAP" | I_TRANSFER_TOKENS -> "TRANSFER_TOKENS" | I_SET_DELEGATE -> "SET_DELEGATE" | I_UNIT -> "UNIT" | I_UNPAIR -> "UNPAIR" | I_UPDATE -> "UPDATE" | I_XOR -> "XOR" | I_ITER -> "ITER" | I_LOOP_LEFT -> "LOOP_LEFT" | I_ADDRESS -> "ADDRESS" | I_CONTRACT -> "CONTRACT" | I_ISNAT -> "ISNAT" | I_CAST -> "CAST" | I_RENAME -> "RENAME" | I_SAPLING_EMPTY_STATE -> "SAPLING_EMPTY_STATE" | I_SAPLING_VERIFY_UPDATE -> "SAPLING_VERIFY_UPDATE" | I_DIG -> "DIG" | I_DUG -> "DUG" | I_NEVER -> "NEVER" | I_VOTING_POWER -> "VOTING_POWER" | I_TOTAL_VOTING_POWER -> "TOTAL_VOTING_POWER" | I_KECCAK -> "KECCAK" | I_SHA3 -> "SHA3" | I_PAIRING_CHECK -> "PAIRING_CHECK" | I_TICKET -> "TICKET" | I_READ_TICKET -> "READ_TICKET" | I_SPLIT_TICKET -> "SPLIT_TICKET" | I_JOIN_TICKETS -> "JOIN_TICKETS" | I_OPEN_CHEST -> "OPEN_CHEST" | I_VIEW -> "VIEW" | T_bool -> "bool" | T_contract -> "contract" | T_int -> "int" | T_key -> "key" | T_key_hash -> "key_hash" | T_lambda -> "lambda" | T_list -> "list" | T_map -> "map" | T_big_map -> "big_map" | T_nat -> "nat" | T_option -> "option" | T_or -> "or" | T_pair -> "pair" | T_set -> "set" | T_signature -> "signature" | T_string -> "string" | T_bytes -> "bytes" | T_mutez -> "mutez" | T_timestamp -> "timestamp" | T_unit -> "unit" | T_operation -> "operation" | T_address -> "address" | T_sapling_state -> "sapling_state" | T_sapling_transaction -> "sapling_transaction" | T_chain_id -> "chain_id" | T_never -> "never" | T_bls12_381_g1 -> "bls12_381_g1" | T_bls12_381_g2 -> "bls12_381_g2" | T_bls12_381_fr -> "bls12_381_fr" | T_ticket -> "ticket" | T_chest_key -> "chest_key" | T_chest -> "chest" | H_constant -> "constant" let prim_of_string = let ok = Result.ok in let error = Result.error in function | "parameter" -> ok K_parameter | "storage" -> ok K_storage | "code" -> ok K_code | "view" -> ok K_view | "False" -> ok D_False | "Elt" -> ok D_Elt | "Left" -> ok D_Left | "None" -> ok D_None | "Pair" -> ok D_Pair | "Right" -> ok D_Right | "Some" -> ok D_Some | "True" -> ok D_True | "Unit" -> ok D_Unit | "PACK" -> ok I_PACK | "UNPACK" -> ok I_UNPACK | "BLAKE2B" -> ok I_BLAKE2B | "SHA256" -> ok I_SHA256 | "SHA512" -> ok I_SHA512 | "ABS" -> ok I_ABS | "ADD" -> ok I_ADD | "AMOUNT" -> ok I_AMOUNT | "AND" -> ok I_AND | "BALANCE" -> ok I_BALANCE | "CAR" -> ok I_CAR | "CDR" -> ok I_CDR | "CHAIN_ID" -> ok I_CHAIN_ID | "CHECK_SIGNATURE" -> ok I_CHECK_SIGNATURE | "COMPARE" -> ok I_COMPARE | "CONCAT" -> ok I_CONCAT | "CONS" -> ok I_CONS | "CREATE_ACCOUNT" -> ok I_CREATE_ACCOUNT | "CREATE_CONTRACT" -> ok I_CREATE_CONTRACT | "IMPLICIT_ACCOUNT" -> ok I_IMPLICIT_ACCOUNT | "DIP" -> ok I_DIP | "DROP" -> ok I_DROP | "DUP" -> ok I_DUP | "VIEW" -> ok I_VIEW | "EDIV" -> ok I_EDIV | "EMPTY_BIG_MAP" -> ok I_EMPTY_BIG_MAP | "EMPTY_MAP" -> ok I_EMPTY_MAP | "EMPTY_SET" -> ok I_EMPTY_SET | "EQ" -> ok I_EQ | "EXEC" -> ok I_EXEC | "APPLY" -> ok I_APPLY | "FAILWITH" -> ok I_FAILWITH | "GE" -> ok I_GE | "GET" -> ok I_GET | "GET_AND_UPDATE" -> ok I_GET_AND_UPDATE | "GT" -> ok I_GT | "HASH_KEY" -> ok I_HASH_KEY | "IF" -> ok I_IF | "IF_CONS" -> ok I_IF_CONS | "IF_LEFT" -> ok I_IF_LEFT | "IF_NONE" -> ok I_IF_NONE | "INT" -> ok I_INT | "KECCAK" -> ok I_KECCAK | "LAMBDA" -> ok I_LAMBDA | "LE" -> ok I_LE | "LEFT" -> ok I_LEFT | "LEVEL" -> ok I_LEVEL | "LOOP" -> ok I_LOOP | "LSL" -> ok I_LSL | "LSR" -> ok I_LSR | "LT" -> ok I_LT | "MAP" -> ok I_MAP | "MEM" -> ok I_MEM | "MUL" -> ok I_MUL | "NEG" -> ok I_NEG | "NEQ" -> ok I_NEQ | "NIL" -> ok I_NIL | "NONE" -> ok I_NONE | "NOT" -> ok I_NOT | "NOW" -> ok I_NOW | "OR" -> ok I_OR | "PAIR" -> ok I_PAIR | "UNPAIR" -> ok I_UNPAIR | "PAIRING_CHECK" -> ok I_PAIRING_CHECK | "PUSH" -> ok I_PUSH | "RIGHT" -> ok I_RIGHT | "SHA3" -> ok I_SHA3 | "SIZE" -> ok I_SIZE | "SOME" -> ok I_SOME | "SOURCE" -> ok I_SOURCE | "SENDER" -> ok I_SENDER | "SELF" -> ok I_SELF | "SELF_ADDRESS" -> ok I_SELF_ADDRESS | "SLICE" -> ok I_SLICE | "STEPS_TO_QUOTA" -> ok I_STEPS_TO_QUOTA | "SUB" -> ok I_SUB | "SUB_MUTEZ" -> ok I_SUB_MUTEZ | "SWAP" -> ok I_SWAP | "TRANSFER_TOKENS" -> ok I_TRANSFER_TOKENS | "SET_DELEGATE" -> ok I_SET_DELEGATE | "UNIT" -> ok I_UNIT | "UPDATE" -> ok I_UPDATE | "XOR" -> ok I_XOR | "ITER" -> ok I_ITER | "LOOP_LEFT" -> ok I_LOOP_LEFT | "ADDRESS" -> ok I_ADDRESS | "CONTRACT" -> ok I_CONTRACT | "ISNAT" -> ok I_ISNAT | "CAST" -> ok I_CAST | "RENAME" -> ok I_RENAME | "SAPLING_EMPTY_STATE" -> ok I_SAPLING_EMPTY_STATE | "SAPLING_VERIFY_UPDATE" -> ok I_SAPLING_VERIFY_UPDATE | "DIG" -> ok I_DIG | "DUG" -> ok I_DUG | "NEVER" -> ok I_NEVER | "VOTING_POWER" -> ok I_VOTING_POWER | "TOTAL_VOTING_POWER" -> ok I_TOTAL_VOTING_POWER | "TICKET" -> ok I_TICKET | "READ_TICKET" -> ok I_READ_TICKET | "SPLIT_TICKET" -> ok I_SPLIT_TICKET | "JOIN_TICKETS" -> ok I_JOIN_TICKETS | "OPEN_CHEST" -> ok I_OPEN_CHEST | "bool" -> ok T_bool | "contract" -> ok T_contract | "int" -> ok T_int | "key" -> ok T_key | "key_hash" -> ok T_key_hash | "lambda" -> ok T_lambda | "list" -> ok T_list | "map" -> ok T_map | "big_map" -> ok T_big_map | "nat" -> ok T_nat | "option" -> ok T_option | "or" -> ok T_or | "pair" -> ok T_pair | "set" -> ok T_set | "signature" -> ok T_signature | "string" -> ok T_string | "bytes" -> ok T_bytes | "mutez" -> ok T_mutez | "timestamp" -> ok T_timestamp | "unit" -> ok T_unit | "operation" -> ok T_operation | "address" -> ok T_address | "sapling_state" -> ok T_sapling_state | "sapling_transaction" -> ok T_sapling_transaction | "chain_id" -> ok T_chain_id | "never" -> ok T_never | "bls12_381_g1" -> ok T_bls12_381_g1 | "bls12_381_g2" -> ok T_bls12_381_g2 | "bls12_381_fr" -> ok T_bls12_381_fr | "ticket" -> ok T_ticket | "chest_key" -> ok T_chest_key | "chest" -> ok T_chest | "constant" -> ok H_constant | n -> if valid_case n then error (Unknown_primitive_name n) else error (Invalid_case n) module type MONAD = sig type 'a t val return : 'a -> 'a t val ( >>= ) : 'a t -> ('a -> 'b t) -> 'b t end module Traverse (M : MONAD) = struct open M let traverse f l = let rec aux f acc l = match l with | [] -> return (List.rev acc) | x :: tail -> f x >>= fun x' -> aux f (x' :: acc) tail in aux f [] l end let prims_of_strings expr = let module Lt = Traverse (struct include Result type nonrec 'a t = ('a, error) t let return t = Ok t let ( >>= ) = Result.bind end) in let open Result.Let_syntax in let rec convert = function | (Int _ | String _ | Bytes _) as expr -> Result.ok expr | Prim (loc, prim, args, annot) -> let* prim = prim_of_string prim |> Result.map_error (fun _ -> Invalid_primitive_name (expr, loc)) in Lt.traverse convert args |> Result.map (fun args -> Prim (loc, prim, args, annot)) | Seq (loc, args) -> Lt.traverse convert args |> Result.map (fun args -> Seq (loc, args)) in convert (root expr) |> Result.map (fun expr -> strip_locations expr) let strings_of_prims expr = let rec convert = function | (Int _ | String _ | Bytes _) as expr -> expr | Prim (loc, prim, args, annot) -> let prim = string_of_prim prim in let args = List.map convert args in Prim (loc, prim, args, annot) | Seq (loc, args) -> let args = List.map convert args in Seq (loc, args) in strip_locations (convert (root expr)) let prim_encoding = let open Data_encoding in def "michelson.v1.primitives" @@ string_enum Add the comment below every 10 lines [ /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("parameter", K_parameter); ("storage", K_storage); ("code", K_code); ("False", D_False); ("Elt", D_Elt); ("Left", D_Left); ("None", D_None); ("Pair", D_Pair); ("Right", D_Right); ("Some", D_Some); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("True", D_True); ("Unit", D_Unit); ("PACK", I_PACK); ("UNPACK", I_UNPACK); ("BLAKE2B", I_BLAKE2B); ("SHA256", I_SHA256); ("SHA512", I_SHA512); ("ABS", I_ABS); ("ADD", I_ADD); ("AMOUNT", I_AMOUNT); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("AND", I_AND); ("BALANCE", I_BALANCE); ("CAR", I_CAR); ("CDR", I_CDR); ("CHECK_SIGNATURE", I_CHECK_SIGNATURE); ("COMPARE", I_COMPARE); ("CONCAT", I_CONCAT); ("CONS", I_CONS); ("CREATE_ACCOUNT", I_CREATE_ACCOUNT); ("CREATE_CONTRACT", I_CREATE_CONTRACT); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("IMPLICIT_ACCOUNT", I_IMPLICIT_ACCOUNT); ("DIP", I_DIP); ("DROP", I_DROP); ("DUP", I_DUP); ("EDIV", I_EDIV); ("EMPTY_MAP", I_EMPTY_MAP); ("EMPTY_SET", I_EMPTY_SET); ("EQ", I_EQ); ("EXEC", I_EXEC); ("FAILWITH", I_FAILWITH); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("GE", I_GE); ("GET", I_GET); ("GT", I_GT); ("HASH_KEY", I_HASH_KEY); ("IF", I_IF); ("IF_CONS", I_IF_CONS); ("IF_LEFT", I_IF_LEFT); ("IF_NONE", I_IF_NONE); ("INT", I_INT); ("LAMBDA", I_LAMBDA); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("LE", I_LE); ("LEFT", I_LEFT); ("LOOP", I_LOOP); ("LSL", I_LSL); ("LSR", I_LSR); ("LT", I_LT); ("MAP", I_MAP); ("MEM", I_MEM); ("MUL", I_MUL); ("NEG", I_NEG); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("NEQ", I_NEQ); ("NIL", I_NIL); ("NONE", I_NONE); ("NOT", I_NOT); ("NOW", I_NOW); ("OR", I_OR); ("PAIR", I_PAIR); ("PUSH", I_PUSH); ("RIGHT", I_RIGHT); ("SIZE", I_SIZE); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("SOME", I_SOME); ("SOURCE", I_SOURCE); ("SENDER", I_SENDER); ("SELF", I_SELF); ("STEPS_TO_QUOTA", I_STEPS_TO_QUOTA); ("SUB", I_SUB); ("SWAP", I_SWAP); ("TRANSFER_TOKENS", I_TRANSFER_TOKENS); ("SET_DELEGATE", I_SET_DELEGATE); ("UNIT", I_UNIT); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("UPDATE", I_UPDATE); ("XOR", I_XOR); ("ITER", I_ITER); ("LOOP_LEFT", I_LOOP_LEFT); ("ADDRESS", I_ADDRESS); ("CONTRACT", I_CONTRACT); ("ISNAT", I_ISNAT); ("CAST", I_CAST); ("RENAME", I_RENAME); ("bool", T_bool); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("contract", T_contract); ("int", T_int); ("key", T_key); ("key_hash", T_key_hash); ("lambda", T_lambda); ("list", T_list); ("map", T_map); ("big_map", T_big_map); ("nat", T_nat); ("option", T_option); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("or", T_or); ("pair", T_pair); ("set", T_set); ("signature", T_signature); ("string", T_string); ("bytes", T_bytes); ("mutez", T_mutez); ("timestamp", T_timestamp); ("unit", T_unit); ("operation", T_operation); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("address", T_address); ("SLICE", I_SLICE); Alpha_005 addition ("DIG", I_DIG); ("DUG", I_DUG); ("EMPTY_BIG_MAP", I_EMPTY_BIG_MAP); ("APPLY", I_APPLY); ("chain_id", T_chain_id); ("CHAIN_ID", I_CHAIN_ID); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("LEVEL", I_LEVEL); ("SELF_ADDRESS", I_SELF_ADDRESS); ("never", T_never); ("NEVER", I_NEVER); ("UNPAIR", I_UNPAIR); ("VOTING_POWER", I_VOTING_POWER); ("TOTAL_VOTING_POWER", I_TOTAL_VOTING_POWER); ("KECCAK", I_KECCAK); ("SHA3", I_SHA3); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("PAIRING_CHECK", I_PAIRING_CHECK); ("bls12_381_g1", T_bls12_381_g1); ("bls12_381_g2", T_bls12_381_g2); ("bls12_381_fr", T_bls12_381_fr); ("sapling_state", T_sapling_state); ("sapling_transaction", T_sapling_transaction); ("SAPLING_EMPTY_STATE", I_SAPLING_EMPTY_STATE); ("SAPLING_VERIFY_UPDATE", I_SAPLING_VERIFY_UPDATE); ("ticket", T_ticket); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("TICKET", I_TICKET); ("READ_TICKET", I_READ_TICKET); ("SPLIT_TICKET", I_SPLIT_TICKET); ("JOIN_TICKETS", I_JOIN_TICKETS); ("GET_AND_UPDATE", I_GET_AND_UPDATE); ("chest", T_chest); ("chest_key", T_chest_key); ("OPEN_CHEST", I_OPEN_CHEST); /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM , FOR BACKWARD COMPATIBILITY OF THE ENCODING . ("VIEW", I_VIEW); ("view", K_view); ("constant", H_constant); ("SUB_MUTEZ", I_SUB_MUTEZ) ] let string_of_namespace = function | Type_namespace -> "T" | Constant_namespace -> "D" | Instr_namespace -> "I" | Keyword_namespace -> "K" | Constant_hash_namespace -> "H"
43f5ce7e991efe371124bb381ccfd22792fc9dddf4c49e29d1d54f4b5ea4cc59
GNOME/aisleriot
sir-tommy.scm
AisleRiot - sir_tommy.scm Copyright ( C ) 2001 < > ; ; 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 3 of the License , or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; You should have received a copy of the GNU General Public License ; along with this program. If not, see </>. (use-modules (aisleriot interface) (aisleriot api)) (define (new-game) (initialize-playing-area) (set-ace-low) (make-standard-deck) (shuffle-deck) (add-normal-slot DECK 'stock) (add-normal-slot '() 'waste) (add-blank-slot) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-carriage-return-slot) (add-blank-slot) (add-blank-slot) (add-blank-slot) (add-extended-slot '() down 'reserve) (add-extended-slot '() down 'reserve) (add-extended-slot '() down 'reserve) (add-extended-slot '() down 'reserve) (give-status-message) (list 7 4)) (define (give-status-message) (set-statusbar-message (get-stock-no-string))) (define (get-stock-no-string) (string-append (G_"Stock left:") " " (number->string (length (get-cards 0))))) (define (button-pressed slot-id card-list) (and (not (empty-slot? slot-id)) (= (length card-list) 1) (or (= slot-id 1) (> slot-id 5)))) (define (droppable? start-slot card-list end-slot) (cond ((> end-slot 5) (= start-slot 1)) ((> end-slot 1) (or (and (= (get-value (car card-list)) ace) (empty-slot? end-slot)) (and (not (empty-slot? end-slot)) (= (get-value (car card-list)) (+ 1 (get-value (get-top-card end-slot))))))) (#t #f))) (define (button-released start-slot card-list end-slot) (and (droppable? start-slot card-list end-slot) (cond ((> end-slot 5) (move-n-cards! start-slot end-slot card-list)) ((> end-slot 1) (begin (move-n-cards! start-slot end-slot card-list) (add-to-score! 1))) (#t #f)))) (define (button-clicked slot-id) (and (= slot-id 0) (not (empty-slot? 0)) (empty-slot? 1) (deal-cards-face-up 0 '(1)))) (define (check-top-card slot f-slot) (cond ((= f-slot 6) #f) ((and (not (empty-slot? f-slot)) (= (get-value (get-top-card slot)) (+ 1 (get-value (get-top-card f-slot))))) (list f-slot)) ((and (= (get-value (get-top-card slot)) ace) (empty-slot? f-slot)) (list f-slot)) (#t (check-top-card slot (+ 1 f-slot))))) (define (button-double-clicked slot-id) (and (not (empty-slot? slot-id)) (or (= slot-id 1) (> slot-id 5)) (check-top-card slot-id 2) (deal-cards slot-id (check-top-card slot-id 2)) (add-to-score! 1))) (define (game-continuable) (give-status-message) (and (not (game-won)) (get-hint))) (define (game-won) (and (= (length (get-cards 2)) 13) (= (length (get-cards 3)) 13) (= (length (get-cards 4)) 13) (= (length (get-cards 5)) 13))) (define (check-to-foundation slot) (cond ((= slot 10) #f) ((= slot 2) (check-to-foundation 6)) ((and (not (empty-slot? slot)) (check-top-card slot 2)) (hint-move slot 1 (car (check-top-card slot 2)))) (#t (check-to-foundation (+ 1 slot))))) (define (move-waste) (and (not (empty-slot? 1)) (not (empty-slot? 0)) (list 0 (G_"Move waste on to a reserve slot")))) (define (dealable?) (and (not (empty-slot? 0)) (list 0 (G_"Deal another card")))) (define (get-hint) (or (check-to-foundation 1) (move-waste) (dealable?))) (define (get-options) #f) (define (apply-options options) #f) (define (timeout) #f) (set-features droppable-feature) (set-lambda new-game button-pressed button-released button-clicked button-double-clicked game-continuable game-won get-hint get-options apply-options timeout droppable?)
null
https://raw.githubusercontent.com/GNOME/aisleriot/5b04e58ba5f8df8223a3830d2c61325527d52237/games/sir-tommy.scm
scheme
This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>.
AisleRiot - sir_tommy.scm Copyright ( C ) 2001 < > it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (use-modules (aisleriot interface) (aisleriot api)) (define (new-game) (initialize-playing-area) (set-ace-low) (make-standard-deck) (shuffle-deck) (add-normal-slot DECK 'stock) (add-normal-slot '() 'waste) (add-blank-slot) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-normal-slot '() 'foundation) (add-carriage-return-slot) (add-blank-slot) (add-blank-slot) (add-blank-slot) (add-extended-slot '() down 'reserve) (add-extended-slot '() down 'reserve) (add-extended-slot '() down 'reserve) (add-extended-slot '() down 'reserve) (give-status-message) (list 7 4)) (define (give-status-message) (set-statusbar-message (get-stock-no-string))) (define (get-stock-no-string) (string-append (G_"Stock left:") " " (number->string (length (get-cards 0))))) (define (button-pressed slot-id card-list) (and (not (empty-slot? slot-id)) (= (length card-list) 1) (or (= slot-id 1) (> slot-id 5)))) (define (droppable? start-slot card-list end-slot) (cond ((> end-slot 5) (= start-slot 1)) ((> end-slot 1) (or (and (= (get-value (car card-list)) ace) (empty-slot? end-slot)) (and (not (empty-slot? end-slot)) (= (get-value (car card-list)) (+ 1 (get-value (get-top-card end-slot))))))) (#t #f))) (define (button-released start-slot card-list end-slot) (and (droppable? start-slot card-list end-slot) (cond ((> end-slot 5) (move-n-cards! start-slot end-slot card-list)) ((> end-slot 1) (begin (move-n-cards! start-slot end-slot card-list) (add-to-score! 1))) (#t #f)))) (define (button-clicked slot-id) (and (= slot-id 0) (not (empty-slot? 0)) (empty-slot? 1) (deal-cards-face-up 0 '(1)))) (define (check-top-card slot f-slot) (cond ((= f-slot 6) #f) ((and (not (empty-slot? f-slot)) (= (get-value (get-top-card slot)) (+ 1 (get-value (get-top-card f-slot))))) (list f-slot)) ((and (= (get-value (get-top-card slot)) ace) (empty-slot? f-slot)) (list f-slot)) (#t (check-top-card slot (+ 1 f-slot))))) (define (button-double-clicked slot-id) (and (not (empty-slot? slot-id)) (or (= slot-id 1) (> slot-id 5)) (check-top-card slot-id 2) (deal-cards slot-id (check-top-card slot-id 2)) (add-to-score! 1))) (define (game-continuable) (give-status-message) (and (not (game-won)) (get-hint))) (define (game-won) (and (= (length (get-cards 2)) 13) (= (length (get-cards 3)) 13) (= (length (get-cards 4)) 13) (= (length (get-cards 5)) 13))) (define (check-to-foundation slot) (cond ((= slot 10) #f) ((= slot 2) (check-to-foundation 6)) ((and (not (empty-slot? slot)) (check-top-card slot 2)) (hint-move slot 1 (car (check-top-card slot 2)))) (#t (check-to-foundation (+ 1 slot))))) (define (move-waste) (and (not (empty-slot? 1)) (not (empty-slot? 0)) (list 0 (G_"Move waste on to a reserve slot")))) (define (dealable?) (and (not (empty-slot? 0)) (list 0 (G_"Deal another card")))) (define (get-hint) (or (check-to-foundation 1) (move-waste) (dealable?))) (define (get-options) #f) (define (apply-options options) #f) (define (timeout) #f) (set-features droppable-feature) (set-lambda new-game button-pressed button-released button-clicked button-double-clicked game-continuable game-won get-hint get-options apply-options timeout droppable?)
6303794b06e63414dc72a7d92406ff5cd67b5f0825c961362c1a894d1f71f74a
tov/dssl2
parser.rkt
#lang racket/base (provide parse-dssl2) (require "lexer.rkt" "names.rkt" (only-in parser-tools/lex position-line position-col position-offset) parser-tools/yacc syntax/readerr) (require (for-syntax racket/base (only-in racket/syntax format-id))) (define (parse-dssl2 src port interactive?) ((dssl2-parser src) (new-dssl2-lexer src port interactive?))) (define (dssl2-parser src) (define (parser-error tok-ok? tok-name tok-value start-pos end-pos) (raise-read-error (format "Syntax error: unexpected token ‘~a’" (or tok-value tok-name)) src (position-line start-pos) (position-col start-pos) (position-offset start-pos) (max 1 (- (position-offset end-pos) (position-offset start-pos))))) (define (locate start end sexp) (datum->syntax #false sexp (list src (position-line start) (position-col start) (position-offset start) (- (position-offset end) (position-offset start))))) (define-syntax (loc stx) (syntax-case stx () [(_ sexp start-name end-name) (with-syntax ([start (format-id #'sexp "~a-start-pos" #'start-name)] [end (format-id #'sexp "~a-end-pos" #'end-name)]) #'(locate start end sexp))] [(_ sexp both) #'(loc sexp both both)] [(_ sexp) #'(loc sexp $1 $n)])) (define (locate/symbol sym pos) (let ([port (open-input-string (format "~s" sym))]) (port-count-lines! port) (set-port-next-location! port (position-line pos) (position-col pos) (position-offset pos)) (read-syntax src port))) (define-syntax (loc/head stx) (syntax-case stx () [(_ sexp pos) (with-syntax [(start (datum->syntax #'sexp '$1-start-pos)) (end (datum->syntax #'sexp '$n-end-pos)) (head (datum->syntax #'sexp (syntax-e #'pos)))] #'(let ([svalue sexp]) (locate start end (cons (locate/symbol (car svalue) head) (cdr svalue)))))])) (define-syntax-rule (loc/1 sexp) (loc/head sexp $1-start-pos)) (define-syntax-rule (loc/2 sexp) (loc/head sexp $2-start-pos)) (define-syntax-rule (loc/3 sexp) (loc/head sexp $3-start-pos)) (parser (tokens dssl2-empty-tokens dssl2-tokens) (src-pos) (suppress) (error parser-error) (start <program>) (end EOF) (grammar (<program> [(<whitespace>) eof] [(<whitespace> <statements> <whitespace>) (loc `(begin ,@$2))]) (<whitespace> [() #true] [(INDENT <whitespace> DEDENT <whitespace>) #true] [(NEWLINE <whitespace>) #true]) (<statements> [(<statement> <newlines>) $1] [(<statement> <newlines> <statements>) (append $1 $3)]) (<newlines> [() #true] [(NEWLINE <newlines>) #true]) (<newlines+> [(NEWLINE <newlines>) #true]) (<statement> [(<simple-statements> NEWLINE) $1] [(<compound-statement>) (list $1)]) (<compound-statement> [(<mix-statement/large>) $1] [(WHILE <expr0> COLON <suite>) (loc/1 `(while ,$2 ,@$4))] [(FOR <ident> IN <expr> COLON <suite>) (loc/1 `(for [,$2 ,$4] ,@$6))] [(FOR <ident> COMMA <ident> IN <expr> COLON <suite>) (loc/1 `(for [(,$2 ,$4) ,$6] ,@$8))] [(DEF <ident> <foralls> LPAREN <contract-formals> RPAREN <result> COLON <suite>) (loc/1 `(def (,$2 ,@$3 ,@$5) ,@$7 ,@$9))] [(STRUCT <ident> COLON <struct-suite>) (loc/1 `(struct ,$2 ,@$4))] [(CLASS <ident> <foralls> <implemented-interfaces> COLON <class-suite>) (loc/1 `(class ,$2 ,@$3 ,@$4 ,@$6))] [(INTERFACE <ident> <foralls> <extended-interfaces> COLON <interface-suite>) (loc/1 `(interface ,$2 ,@$3 ,$4 ,@$6))] [(TEST <expr> <opt-timeout> COLON <suite>) (loc/1 `(test ,$2 ,@$3 ,@$5))] [(TEST <opt-timeout> COLON <suite>) (loc/1 `(test ,(anonymous-block 'test $1-start-pos) ,@$2 ,@$4))]) (<simple-statements> [(<simple-statement> <more-simple-statements>) (cons $1 $2)]) (<more-simple-statements> [() `()] [(SEMICOLON <simple-statement> <more-simple-statements>) (cons $2 $3)]) (<simple-statement> [(<mix-statement/small>) $1] [(LET <contract-formal>) (loc/1 `(let ,$2))] [(BREAK) (loc/1 `(break))] [(CONTINUE) (loc/1 `(continue))] [(IMPORT <ident>) (loc/1 `(import ,$2))] [(IMPORT STRING-LITERAL) (loc/1 `(import ,$2))] [(RETURN) (loc/1 `(return))] [(ASSERT <timeout>) (loc/1 `(assert ,@$2))] [(ASSERT <expr> <opt-timeout>) (loc/1 `(assert ,$2 ,@$3))] [(ASSERT-ERROR <expr> <opt-timeout>) (loc/1 `(assert_error ,$2 ,@$3))] [(ASSERT-ERROR <expr> COMMA STRING-LITERAL <opt-timeout>) (loc/1 `(assert_error ,$2 ,$4 ,@$5))] [(PASS) (loc/1 `(pass))] [(TEST <timeout>) (loc/1 `(test ,@$2))] [(TEST EQUALS <expr>) (loc/1 `(test #:points ,$3))]) ; These statements are large if they contain large expressions… (<mix-statement/large> [(<large-expression>) $1] [(LET <contract-formal> EQUALS <large-expression>) (loc/1 `(let ,$2 ,$4))] [(RETURN <large-expression>) (loc/1 `(return ,$2))] [(<lvalue> EQUALS <large-expression>) (loc/2 `(= ,$1 ,$3))]) ; …but small if they contain small expressions. (<mix-statement/small> [(<expr>) $1] [(LET <contract-formal> EQUALS <expr>) (loc/1 `(let ,$2 ,$4))] [(RETURN <expr>) (loc/1 `(return ,$2))] [(<lvalue> EQUALS <expr>) (loc/2 `(= ,$1 ,$3))]) (<elifs> [() `()] [(<elif> <elifs>) (cons $1 $2)]) (<elif> [(ELIF <expr0> COLON <suite>) (loc/1 `[elif ,$2 ,@$4])]) (<maybe-else> [() `[else (pass)]] [(ELSE COLON <suite>) (loc/1 `[else ,@$3])]) (<result> [(ARROW <expr>) `(#:-> ,$2)] [() `()]) (<implemented-interfaces> [(LPAREN <formals> RPAREN) `(#:implements ,$2)] [() `()]) (<extended-interfaces> [(LPAREN <instantiated-interface-list> RPAREN) $2] [() '()]) (<instantiated-interface-list> [() '()] [(<instantiated-interface>) (loc (list $1))] [(<instantiated-interface> COMMA <instantiated-interface-list>) (loc (cons $1 $3))]) (<instantiated-interface> [(<ident>) $1] [(<ident> LBRACK <formals> RBRACK) (loc (cons $1 $3))]) (<suite> [(<simple-statements> NEWLINE) $1] [(NEWLINE INDENT <statements> DEDENT) $3]) (<struct-suite> [(NEWLINE INDENT PASS NEWLINE DEDENT) '()] [(PASS NEWLINE) '()] [(NEWLINE INDENT <class-or-struct-fields> DEDENT) $3]) (<class-suite> [(NEWLINE INDENT <class-statements> DEDENT) $3]) (<class-statements> [(<class-or-struct-fields> <class-methods>) (append $1 $2)]) (<class-or-struct-fields> [() '()] [(<class-or-struct-field> SEMICOLON <class-or-struct-fields>) (cons $1 $3)] [(<class-or-struct-field> <newlines+> <class-or-struct-fields>) (cons $1 $3)]) (<class-or-struct-field> [(LET <contract-formal>) (loc/1 `(let ,$2))]) (<class-methods> [(<class-method>) (list $1)] [(<class-method> <newlines> <class-methods>) (cons $1 $3)]) (<class-method> [(DEF <ident> <foralls> LPAREN <method-formals> RPAREN <result> COLON <suite>) (loc/1 `(def (,$2 ,@$3 ,@$5) ,@$7 ,@$9))]) (<method-formals> [(<ident>) (list $1)] [(<ident> COMMA <contract-formals>) (cons $1 $3)]) (<interface-suite> [(NEWLINE INDENT PASS NEWLINE DEDENT) '()] [(PASS NEWLINE) '()] [(NEWLINE INDENT <interface-methods> DEDENT) $3]) (<interface-methods> [(<interface-method> <newlines+>) (list $1)] [(<interface-method> SEMICOLON <interface-methods>) (cons $1 $3)] [(<interface-method> <newlines+> <interface-methods>) (cons $1 $3)]) (<interface-method> [(DEF <ident> <foralls> LPAREN <method-formals> RPAREN <result>) (loc/1 `(def (,$2 ,@$3 ,@$5) ,@$7))]) (<foralls> [() `()] [(LBRACK <formals> RBRACK) `(#:forall ,$2)]) (<contract-formals> [() `()] [(<contract-formal>) (loc (list $1))] [(<contract-formal> COMMA <contract-formals>) (loc (cons $1 $3))]) (<contract-formal> [(<ident> COLON <expr>) (loc (list $1 $3))] [(<ident>) $1]) (<formals> [() `()] [(<ident>) (loc (list $1))] [(<ident> COMMA <formals>) (loc (cons $1 $3))]) (<ident> [(IDENT) (locate/symbol $1 $1-start-pos)]) (<lvalue> [(<ident>) $1] [(<atom> PERIOD <ident>) (loc `(struct-ref ,$1 ,$3))] [(<atom> LBRACK <non-empty-actuals> RBRACK) (loc `(vec-ref ,$1 ,@$3))]) (<string-literal> [(STRING-LITERAL) $1] [(STRING-LITERAL <string-literal>) (string-append $1 $2)]) (<atom> [(<lvalue>) $1] [(<string-literal>) (loc $1)] [(LITERAL) (loc $1)] [(<atom> LPAREN <actuals> RPAREN) (loc `(,$1 ,@$3))] [(LBRACK <actuals> RBRACK) (loc `(vec-lit ,@$2))] [(LBRACK <expr> SEMICOLON <expr> RBRACK) (loc `(make-vec ,$4 ,$2))] [(LBRACK <expr> FOR <ident> IN <expr0> RBRACK) (loc `(for/vec [,$4 ,$6] ,$2))] [(LBRACK <expr> FOR <ident> COMMA <ident> IN <expr0> RBRACK) (loc `(for/vec [(,$4 ,$6) ,$8] ,$2))] [(LBRACK <expr> FOR <ident> IN <expr0> IF <expr> RBRACK) (loc `(for/vec [,$4 ,$6] #:when ,$8 ,$2))] [(LBRACK <expr> FOR <ident> COMMA <ident> IN <expr0> IF <expr> RBRACK) (loc `(for/vec [(,$4 ,$6) ,$8] #:when ,$10 ,$2))] [(<ident> LBRACE <fields> RBRACE) (loc `(,(struct-special-name/located $1) ,@$3))] [(LPAREN <expr> RPAREN) (loc $2)]) (<non-empty-actuals> [(<expr>) (list $1)] [(<expr> COMMA <non-empty-actuals>) (cons $1 $3)]) (<actuals> [() `()] [(<expr>) (list $1)] [(<expr> COMMA <actuals>) (cons $1 $3)]) (<fields> [() `()] [(<field>) (list $1)] [(<field> COMMA <fields>) (cons $1 $3)]) (<field> [(<ident> COLON <expr>) (loc `[,$1 ,$3])] [(<ident>) (loc `[,$1 ,$1])]) (<opt-timeout> [() '()] [(COMMA <timeout>) (list (loc $2 $2))]) (<timeout> [(TIME OP-LESS <expr>) (list '#:timeout $3)]) (<op2> [(OP2) $1] [(NOT) 'not]) (<op3> [(OP3) $1] [(OP-LESS) $1] [(IN) 'in] [(IS) 'is] [(NOT-IN) '∉] [(IS NOT) '|is not|] [(NOT IN) '|not in|]) (<op8> [(OP8) $1] [(PLUS) '+] [(MINUS) '-]) (<op10> [(OP10) $1] [(PLUS) '+] [(MINUS) '-]) (<large-expression> [(TIME <expr> COLON <suite>) (loc/1 `(time ,$2 ,@$4))] [(TIME COLON <suite>) (loc/1 `(time ,(anonymous-block 'time $1-start-pos) ,@$3))] [(LAMBDA <formals> COLON <suite>) (loc/1 `(lambda ,$2 ,@$4))] [(IF <expr0> COLON <suite> <elifs> <maybe-else>) (loc/1 `(if [,$2 ,@$4] ,@$5 ,$6))]) (<expr> [(TIME <expr> COLON <simple-statements>) (loc/1 `(time ,$2 ,@$4))] [(TIME COLON <simple-statements>) (loc/1 `(time ,(anonymous-block 'time $1-start-pos) ,@$3))] [(LAMBDA <formals> COLON <simple-statements>) (loc/1 `(lambda ,$2 ,@$4))] [(<expr0> IF <expr0> ELSE <expr>) (loc `(if-e ,$3 ,$1 ,$5))] [(<expr0>) $1]) (<expr0> [(<expr0> OP0 <expr1>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr1>) $1]) (<expr1> [(<expr1> OP1 <expr2>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr2>) $1]) (<expr2> [(<op2> <expr2>) (loc/1 `(,$1 ,$2))] [(<expr3>) $1]) (<expr3> [(<expr4> <op3> <expr4>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr4>) $1]) (<expr4> [(<expr4> OP4 <expr5>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr5>) $1]) (<expr5> [(<expr5> OP5 <expr6>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr6>) $1]) (<expr6> [(<expr6> OP6 <expr7>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr7>) $1]) (<expr7> [(<expr7> OP7 <expr8>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr8>) $1]) (<expr8> [(<expr8> <op8> <expr9>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr9>) $1]) (<expr9> [(<expr9> OP9 <expr10>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr10>) $1]) (<expr10> [(<op10> <expr10>) (loc/1 `(,$1 ,$2))] [(<expr11>) $1]) (<expr11> [(<atom> OP11 <expr11>) (loc/2 `(,$2 ,$1 ,$3))] [(<atom>) $1])))) (define (anonymous-block kind pos) (format "<~a@~a>" kind (position-line pos)))
null
https://raw.githubusercontent.com/tov/dssl2/105d18069465781bd9b87466f8336d5ce9e9a0f3/private/parser.rkt
racket
These statements are large if they contain large expressions… …but small if they contain small expressions.
#lang racket/base (provide parse-dssl2) (require "lexer.rkt" "names.rkt" (only-in parser-tools/lex position-line position-col position-offset) parser-tools/yacc syntax/readerr) (require (for-syntax racket/base (only-in racket/syntax format-id))) (define (parse-dssl2 src port interactive?) ((dssl2-parser src) (new-dssl2-lexer src port interactive?))) (define (dssl2-parser src) (define (parser-error tok-ok? tok-name tok-value start-pos end-pos) (raise-read-error (format "Syntax error: unexpected token ‘~a’" (or tok-value tok-name)) src (position-line start-pos) (position-col start-pos) (position-offset start-pos) (max 1 (- (position-offset end-pos) (position-offset start-pos))))) (define (locate start end sexp) (datum->syntax #false sexp (list src (position-line start) (position-col start) (position-offset start) (- (position-offset end) (position-offset start))))) (define-syntax (loc stx) (syntax-case stx () [(_ sexp start-name end-name) (with-syntax ([start (format-id #'sexp "~a-start-pos" #'start-name)] [end (format-id #'sexp "~a-end-pos" #'end-name)]) #'(locate start end sexp))] [(_ sexp both) #'(loc sexp both both)] [(_ sexp) #'(loc sexp $1 $n)])) (define (locate/symbol sym pos) (let ([port (open-input-string (format "~s" sym))]) (port-count-lines! port) (set-port-next-location! port (position-line pos) (position-col pos) (position-offset pos)) (read-syntax src port))) (define-syntax (loc/head stx) (syntax-case stx () [(_ sexp pos) (with-syntax [(start (datum->syntax #'sexp '$1-start-pos)) (end (datum->syntax #'sexp '$n-end-pos)) (head (datum->syntax #'sexp (syntax-e #'pos)))] #'(let ([svalue sexp]) (locate start end (cons (locate/symbol (car svalue) head) (cdr svalue)))))])) (define-syntax-rule (loc/1 sexp) (loc/head sexp $1-start-pos)) (define-syntax-rule (loc/2 sexp) (loc/head sexp $2-start-pos)) (define-syntax-rule (loc/3 sexp) (loc/head sexp $3-start-pos)) (parser (tokens dssl2-empty-tokens dssl2-tokens) (src-pos) (suppress) (error parser-error) (start <program>) (end EOF) (grammar (<program> [(<whitespace>) eof] [(<whitespace> <statements> <whitespace>) (loc `(begin ,@$2))]) (<whitespace> [() #true] [(INDENT <whitespace> DEDENT <whitespace>) #true] [(NEWLINE <whitespace>) #true]) (<statements> [(<statement> <newlines>) $1] [(<statement> <newlines> <statements>) (append $1 $3)]) (<newlines> [() #true] [(NEWLINE <newlines>) #true]) (<newlines+> [(NEWLINE <newlines>) #true]) (<statement> [(<simple-statements> NEWLINE) $1] [(<compound-statement>) (list $1)]) (<compound-statement> [(<mix-statement/large>) $1] [(WHILE <expr0> COLON <suite>) (loc/1 `(while ,$2 ,@$4))] [(FOR <ident> IN <expr> COLON <suite>) (loc/1 `(for [,$2 ,$4] ,@$6))] [(FOR <ident> COMMA <ident> IN <expr> COLON <suite>) (loc/1 `(for [(,$2 ,$4) ,$6] ,@$8))] [(DEF <ident> <foralls> LPAREN <contract-formals> RPAREN <result> COLON <suite>) (loc/1 `(def (,$2 ,@$3 ,@$5) ,@$7 ,@$9))] [(STRUCT <ident> COLON <struct-suite>) (loc/1 `(struct ,$2 ,@$4))] [(CLASS <ident> <foralls> <implemented-interfaces> COLON <class-suite>) (loc/1 `(class ,$2 ,@$3 ,@$4 ,@$6))] [(INTERFACE <ident> <foralls> <extended-interfaces> COLON <interface-suite>) (loc/1 `(interface ,$2 ,@$3 ,$4 ,@$6))] [(TEST <expr> <opt-timeout> COLON <suite>) (loc/1 `(test ,$2 ,@$3 ,@$5))] [(TEST <opt-timeout> COLON <suite>) (loc/1 `(test ,(anonymous-block 'test $1-start-pos) ,@$2 ,@$4))]) (<simple-statements> [(<simple-statement> <more-simple-statements>) (cons $1 $2)]) (<more-simple-statements> [() `()] [(SEMICOLON <simple-statement> <more-simple-statements>) (cons $2 $3)]) (<simple-statement> [(<mix-statement/small>) $1] [(LET <contract-formal>) (loc/1 `(let ,$2))] [(BREAK) (loc/1 `(break))] [(CONTINUE) (loc/1 `(continue))] [(IMPORT <ident>) (loc/1 `(import ,$2))] [(IMPORT STRING-LITERAL) (loc/1 `(import ,$2))] [(RETURN) (loc/1 `(return))] [(ASSERT <timeout>) (loc/1 `(assert ,@$2))] [(ASSERT <expr> <opt-timeout>) (loc/1 `(assert ,$2 ,@$3))] [(ASSERT-ERROR <expr> <opt-timeout>) (loc/1 `(assert_error ,$2 ,@$3))] [(ASSERT-ERROR <expr> COMMA STRING-LITERAL <opt-timeout>) (loc/1 `(assert_error ,$2 ,$4 ,@$5))] [(PASS) (loc/1 `(pass))] [(TEST <timeout>) (loc/1 `(test ,@$2))] [(TEST EQUALS <expr>) (loc/1 `(test #:points ,$3))]) (<mix-statement/large> [(<large-expression>) $1] [(LET <contract-formal> EQUALS <large-expression>) (loc/1 `(let ,$2 ,$4))] [(RETURN <large-expression>) (loc/1 `(return ,$2))] [(<lvalue> EQUALS <large-expression>) (loc/2 `(= ,$1 ,$3))]) (<mix-statement/small> [(<expr>) $1] [(LET <contract-formal> EQUALS <expr>) (loc/1 `(let ,$2 ,$4))] [(RETURN <expr>) (loc/1 `(return ,$2))] [(<lvalue> EQUALS <expr>) (loc/2 `(= ,$1 ,$3))]) (<elifs> [() `()] [(<elif> <elifs>) (cons $1 $2)]) (<elif> [(ELIF <expr0> COLON <suite>) (loc/1 `[elif ,$2 ,@$4])]) (<maybe-else> [() `[else (pass)]] [(ELSE COLON <suite>) (loc/1 `[else ,@$3])]) (<result> [(ARROW <expr>) `(#:-> ,$2)] [() `()]) (<implemented-interfaces> [(LPAREN <formals> RPAREN) `(#:implements ,$2)] [() `()]) (<extended-interfaces> [(LPAREN <instantiated-interface-list> RPAREN) $2] [() '()]) (<instantiated-interface-list> [() '()] [(<instantiated-interface>) (loc (list $1))] [(<instantiated-interface> COMMA <instantiated-interface-list>) (loc (cons $1 $3))]) (<instantiated-interface> [(<ident>) $1] [(<ident> LBRACK <formals> RBRACK) (loc (cons $1 $3))]) (<suite> [(<simple-statements> NEWLINE) $1] [(NEWLINE INDENT <statements> DEDENT) $3]) (<struct-suite> [(NEWLINE INDENT PASS NEWLINE DEDENT) '()] [(PASS NEWLINE) '()] [(NEWLINE INDENT <class-or-struct-fields> DEDENT) $3]) (<class-suite> [(NEWLINE INDENT <class-statements> DEDENT) $3]) (<class-statements> [(<class-or-struct-fields> <class-methods>) (append $1 $2)]) (<class-or-struct-fields> [() '()] [(<class-or-struct-field> SEMICOLON <class-or-struct-fields>) (cons $1 $3)] [(<class-or-struct-field> <newlines+> <class-or-struct-fields>) (cons $1 $3)]) (<class-or-struct-field> [(LET <contract-formal>) (loc/1 `(let ,$2))]) (<class-methods> [(<class-method>) (list $1)] [(<class-method> <newlines> <class-methods>) (cons $1 $3)]) (<class-method> [(DEF <ident> <foralls> LPAREN <method-formals> RPAREN <result> COLON <suite>) (loc/1 `(def (,$2 ,@$3 ,@$5) ,@$7 ,@$9))]) (<method-formals> [(<ident>) (list $1)] [(<ident> COMMA <contract-formals>) (cons $1 $3)]) (<interface-suite> [(NEWLINE INDENT PASS NEWLINE DEDENT) '()] [(PASS NEWLINE) '()] [(NEWLINE INDENT <interface-methods> DEDENT) $3]) (<interface-methods> [(<interface-method> <newlines+>) (list $1)] [(<interface-method> SEMICOLON <interface-methods>) (cons $1 $3)] [(<interface-method> <newlines+> <interface-methods>) (cons $1 $3)]) (<interface-method> [(DEF <ident> <foralls> LPAREN <method-formals> RPAREN <result>) (loc/1 `(def (,$2 ,@$3 ,@$5) ,@$7))]) (<foralls> [() `()] [(LBRACK <formals> RBRACK) `(#:forall ,$2)]) (<contract-formals> [() `()] [(<contract-formal>) (loc (list $1))] [(<contract-formal> COMMA <contract-formals>) (loc (cons $1 $3))]) (<contract-formal> [(<ident> COLON <expr>) (loc (list $1 $3))] [(<ident>) $1]) (<formals> [() `()] [(<ident>) (loc (list $1))] [(<ident> COMMA <formals>) (loc (cons $1 $3))]) (<ident> [(IDENT) (locate/symbol $1 $1-start-pos)]) (<lvalue> [(<ident>) $1] [(<atom> PERIOD <ident>) (loc `(struct-ref ,$1 ,$3))] [(<atom> LBRACK <non-empty-actuals> RBRACK) (loc `(vec-ref ,$1 ,@$3))]) (<string-literal> [(STRING-LITERAL) $1] [(STRING-LITERAL <string-literal>) (string-append $1 $2)]) (<atom> [(<lvalue>) $1] [(<string-literal>) (loc $1)] [(LITERAL) (loc $1)] [(<atom> LPAREN <actuals> RPAREN) (loc `(,$1 ,@$3))] [(LBRACK <actuals> RBRACK) (loc `(vec-lit ,@$2))] [(LBRACK <expr> SEMICOLON <expr> RBRACK) (loc `(make-vec ,$4 ,$2))] [(LBRACK <expr> FOR <ident> IN <expr0> RBRACK) (loc `(for/vec [,$4 ,$6] ,$2))] [(LBRACK <expr> FOR <ident> COMMA <ident> IN <expr0> RBRACK) (loc `(for/vec [(,$4 ,$6) ,$8] ,$2))] [(LBRACK <expr> FOR <ident> IN <expr0> IF <expr> RBRACK) (loc `(for/vec [,$4 ,$6] #:when ,$8 ,$2))] [(LBRACK <expr> FOR <ident> COMMA <ident> IN <expr0> IF <expr> RBRACK) (loc `(for/vec [(,$4 ,$6) ,$8] #:when ,$10 ,$2))] [(<ident> LBRACE <fields> RBRACE) (loc `(,(struct-special-name/located $1) ,@$3))] [(LPAREN <expr> RPAREN) (loc $2)]) (<non-empty-actuals> [(<expr>) (list $1)] [(<expr> COMMA <non-empty-actuals>) (cons $1 $3)]) (<actuals> [() `()] [(<expr>) (list $1)] [(<expr> COMMA <actuals>) (cons $1 $3)]) (<fields> [() `()] [(<field>) (list $1)] [(<field> COMMA <fields>) (cons $1 $3)]) (<field> [(<ident> COLON <expr>) (loc `[,$1 ,$3])] [(<ident>) (loc `[,$1 ,$1])]) (<opt-timeout> [() '()] [(COMMA <timeout>) (list (loc $2 $2))]) (<timeout> [(TIME OP-LESS <expr>) (list '#:timeout $3)]) (<op2> [(OP2) $1] [(NOT) 'not]) (<op3> [(OP3) $1] [(OP-LESS) $1] [(IN) 'in] [(IS) 'is] [(NOT-IN) '∉] [(IS NOT) '|is not|] [(NOT IN) '|not in|]) (<op8> [(OP8) $1] [(PLUS) '+] [(MINUS) '-]) (<op10> [(OP10) $1] [(PLUS) '+] [(MINUS) '-]) (<large-expression> [(TIME <expr> COLON <suite>) (loc/1 `(time ,$2 ,@$4))] [(TIME COLON <suite>) (loc/1 `(time ,(anonymous-block 'time $1-start-pos) ,@$3))] [(LAMBDA <formals> COLON <suite>) (loc/1 `(lambda ,$2 ,@$4))] [(IF <expr0> COLON <suite> <elifs> <maybe-else>) (loc/1 `(if [,$2 ,@$4] ,@$5 ,$6))]) (<expr> [(TIME <expr> COLON <simple-statements>) (loc/1 `(time ,$2 ,@$4))] [(TIME COLON <simple-statements>) (loc/1 `(time ,(anonymous-block 'time $1-start-pos) ,@$3))] [(LAMBDA <formals> COLON <simple-statements>) (loc/1 `(lambda ,$2 ,@$4))] [(<expr0> IF <expr0> ELSE <expr>) (loc `(if-e ,$3 ,$1 ,$5))] [(<expr0>) $1]) (<expr0> [(<expr0> OP0 <expr1>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr1>) $1]) (<expr1> [(<expr1> OP1 <expr2>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr2>) $1]) (<expr2> [(<op2> <expr2>) (loc/1 `(,$1 ,$2))] [(<expr3>) $1]) (<expr3> [(<expr4> <op3> <expr4>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr4>) $1]) (<expr4> [(<expr4> OP4 <expr5>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr5>) $1]) (<expr5> [(<expr5> OP5 <expr6>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr6>) $1]) (<expr6> [(<expr6> OP6 <expr7>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr7>) $1]) (<expr7> [(<expr7> OP7 <expr8>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr8>) $1]) (<expr8> [(<expr8> <op8> <expr9>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr9>) $1]) (<expr9> [(<expr9> OP9 <expr10>) (loc/2 `(,$2 ,$1 ,$3))] [(<expr10>) $1]) (<expr10> [(<op10> <expr10>) (loc/1 `(,$1 ,$2))] [(<expr11>) $1]) (<expr11> [(<atom> OP11 <expr11>) (loc/2 `(,$2 ,$1 ,$3))] [(<atom>) $1])))) (define (anonymous-block kind pos) (format "<~a@~a>" kind (position-line pos)))
8c627ab48b282bc3aa72b0ec8b48b87e484509198d6fc0f49f187fd811278a8e
racket/racket7
test-runtime.rkt
#lang racket/load (require "test-harness.rkt" racket/private/unit-runtime) ;; check-unit (test-runtime-error exn:fail:contract? "result of unit expression was not a unit" (check-unit 1 'check-unit)) (test (void) (check-unit (make-unit 1 2 3 4 5) 'check-unit)) ;; check-helper (define sub-vector #((a . #((t . r1) (t . r2) (t . r3))) (a . #((#f . r1) (#f . r2) (#f . r3))))) (test (void) (check-helper sub-vector #() 'check-helper #f)) (test (void) (check-helper sub-vector sub-vector 'check-helper #f)) (test (void) (check-helper sub-vector #((d . #((t . r2) (t . r3)))) 'check-helper #f)) (test-runtime-error exn:fail:contract? "expects a unit with an export for tag t with signature c, which the given unit does not supply" (check-helper sub-vector #((c . #((t . r4) (t . r1) (t . r2) (t . r3)))) 'check-helper #f)) (define sub-vector2 #((a . #((t . r5) (t . r2) (t . r3))) (b . #((t . r1) (t . r2) (t . r3))))) (test (void) (check-helper sub-vector2 sub-vector2 'check-helper #f)) (test (void) (check-helper sub-vector2 #((a . #((t . r5) (t . r2) (t . r3)))) 'check-helper #f)) (test-runtime-error exn:fail:contract? "expects a unit with an export for tag t with signature c, which the given unit supplies multiple times" (check-helper sub-vector2 #((c . #((t . r2) (t . r3)))) 'check-helper #f)) ;; check-deps UNTESTED
null
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/pkgs/racket-test/tests/units/test-runtime.rkt
racket
check-unit check-helper check-deps
#lang racket/load (require "test-harness.rkt" racket/private/unit-runtime) (test-runtime-error exn:fail:contract? "result of unit expression was not a unit" (check-unit 1 'check-unit)) (test (void) (check-unit (make-unit 1 2 3 4 5) 'check-unit)) (define sub-vector #((a . #((t . r1) (t . r2) (t . r3))) (a . #((#f . r1) (#f . r2) (#f . r3))))) (test (void) (check-helper sub-vector #() 'check-helper #f)) (test (void) (check-helper sub-vector sub-vector 'check-helper #f)) (test (void) (check-helper sub-vector #((d . #((t . r2) (t . r3)))) 'check-helper #f)) (test-runtime-error exn:fail:contract? "expects a unit with an export for tag t with signature c, which the given unit does not supply" (check-helper sub-vector #((c . #((t . r4) (t . r1) (t . r2) (t . r3)))) 'check-helper #f)) (define sub-vector2 #((a . #((t . r5) (t . r2) (t . r3))) (b . #((t . r1) (t . r2) (t . r3))))) (test (void) (check-helper sub-vector2 sub-vector2 'check-helper #f)) (test (void) (check-helper sub-vector2 #((a . #((t . r5) (t . r2) (t . r3)))) 'check-helper #f)) (test-runtime-error exn:fail:contract? "expects a unit with an export for tag t with signature c, which the given unit supplies multiple times" (check-helper sub-vector2 #((c . #((t . r2) (t . r3)))) 'check-helper #f)) UNTESTED
77e1ab788922a84462da16cfb1645f0c08a2c3d900d3d9c852b897b145de0e0b
oliyh/slacky
nav.cljs
(ns slacky.nav (:require [goog.events :as events] [secretary.core :as secretary]) (:import [goog.history Html5History EventType] [goog History])) taken from -client-side-routing-with-secretary-and-goog-history (aset js/goog.history.Html5History.prototype "getUrl_" (fn [token] (this-as this (if (.-useFragment_ this) (str "#" token) (str (.-pathPrefix_ this) token))))) (defn get-token [] (if (Html5History.isSupported) (str js/window.location.pathname js/window.location.search) (if (= js/window.location.pathname "/") (.substring js/window.location.hash 1) (str js/window.location.pathname js/window.location.search)))) (defn- make-history [] (if (Html5History.isSupported) (doto (Html5History.) (.setPathPrefix (str js/window.location.protocol "//" js/window.location.host)) (.setUseFragment false)) (if (not= "/" js/window.location.pathname) (aset js/window "location" (str "/#" (get-token))) (History.)))) (defn handle-url-change [e] (when-not (.-isNavigation e) ;; set programmatically ) (secretary/dispatch! (get-token))) (defonce history (doto (make-history) (goog.events/listen EventType.NAVIGATE #(handle-url-change %)) (.setEnabled true))) (defn nav! [token] (fn [event] (do (when event (.preventDefault event)) (.setToken history token) ( js / window.scrollTo 0 0 ) ; ; optional , make it look like a new page load )))
null
https://raw.githubusercontent.com/oliyh/slacky/909110e0555b7e443c3cf014c7c34b00b31c1a18/src/cljs/slacky/nav.cljs
clojure
set programmatically ; optional , make it look like a new page load
(ns slacky.nav (:require [goog.events :as events] [secretary.core :as secretary]) (:import [goog.history Html5History EventType] [goog History])) taken from -client-side-routing-with-secretary-and-goog-history (aset js/goog.history.Html5History.prototype "getUrl_" (fn [token] (this-as this (if (.-useFragment_ this) (str "#" token) (str (.-pathPrefix_ this) token))))) (defn get-token [] (if (Html5History.isSupported) (str js/window.location.pathname js/window.location.search) (if (= js/window.location.pathname "/") (.substring js/window.location.hash 1) (str js/window.location.pathname js/window.location.search)))) (defn- make-history [] (if (Html5History.isSupported) (doto (Html5History.) (.setPathPrefix (str js/window.location.protocol "//" js/window.location.host)) (.setUseFragment false)) (if (not= "/" js/window.location.pathname) (aset js/window "location" (str "/#" (get-token))) (History.)))) (defn handle-url-change [e] (when-not (.-isNavigation e) ) (secretary/dispatch! (get-token))) (defonce history (doto (make-history) (goog.events/listen EventType.NAVIGATE #(handle-url-change %)) (.setEnabled true))) (defn nav! [token] (fn [event] (do (when event (.preventDefault event)) (.setToken history token) )))
b7658eabd0be4e1b19ae912fe9b0cb1959f9ba5086bc8f21c33f7db1a534301f
janestreet/camlp4-to-ppx
camlp4_to_ppx.ml
open Printf open StdLabels open Camlp4.PreCast open Syntax let module M = Camlp4OCamlParser.Make(Camlp4OCamlRevisedParser.Make(Camlp4.PreCast.Syntax)) in () let program_name = Filename.basename Sys.executable_name let input_file = match Sys.argv with | [| _; fname |] -> fname | _ -> Printf.eprintf "Usage: %s FILE\n" program_name; exit 2 type kind = Signature | Structure let kind = if Filename.check_suffix input_file ".mli" then Signature else if Filename.check_suffix input_file ".ml" then Structure else begin Printf.eprintf "%s: unknown suffix in filename: %s\n" program_name input_file; exit 2 end let file_contents = let ic = open_in input_file in let len = in_channel_length ic in let str = Bytes.create len in really_input ic str 0 len; Bytes.to_string str type subst = { start : int ; stop : int ; repl : string } let substs = ref [] let do_output () = let rec loop pos substs = match substs with | [] -> output_substring stdout file_contents pos (String.length file_contents - pos) | { start; stop; repl } :: rest -> assert (pos <= start && start <= stop); output_substring stdout file_contents pos (start - pos); output_string stdout repl; loop stop rest in let substs = List.sort !substs ~cmp:(fun a b -> let d = compare a.start b.start in if d = 0 then (* This happens with 0-length substitutions *) compare a.stop b.stop else d) in loop 0 substs ;; let add_subst ~start ~stop ~repl = substs := { start; stop; repl } :: !substs let replace loc s = add_subst ~start:(Loc.start_off loc) ~stop:(Loc.stop_off loc) ~repl:s let print_at ~pos s = add_subst ~start:pos ~stop:pos ~repl:s let print_before loc s = print_at ~pos:(Loc.start_off loc) s let print_after loc s = print_at ~pos:(Loc.stop_off loc) s let erase_keyword loc = let start = Loc.start_off loc in let stop = Loc.stop_off loc in if start > 0 && file_contents.[start - 1] = ' ' && stop < String.length file_contents && file_contents.[stop ] = ' ' then add_subst ~start ~stop:(stop + 1) ~repl:"" else add_subst ~start ~stop ~repl:"" let skip_trailing_semi loc = let stop = Loc.stop_off loc in if stop > 0 && file_contents.[stop - 1] = ';' then add_subst ~start:(stop-1) ~stop ~repl:"" DELETE_RULE Gram let_binding: ipatt; fun_binding END [ let _ a = a ] is a syntax error in ocaml because a single underscore is a pattern , but not an identifier as required by the ocaml parser in a function - style binding . However , if is used to preprocess , the illegal syntax is masked by 's more permissive grammar . In effect the example gets rewritten as [ let _ = fun a - > a ] We do the same translation as . but not an identifier as required by the ocaml parser in a function-style binding. However, if camlp4 is used to preprocess, the illegal syntax is masked by camlp4's more permissive grammar. In effect the example gets rewritten as [let _ = fun a -> a] We do the same translation as camlp4. *) EXTEND Gram GLOBAL: let_binding; equal: [ [ "=" -> _loc ] ]; unquoted_typevars: [ LEFTA [ SELF; SELF -> () | a_ident -> () ] ] ; cvalue_binding: [ [ l = equal; expr -> l | ":"; "type"; unquoted_typevars; "." ; ctyp ; l = equal; expr -> l | ":"; poly_type; l = equal; expr -> l | ":"; poly_type; ":>"; ctyp; l = equal; expr -> l | ":>"; ctyp; l = equal; expr -> l ] ]; fun_binding: [ RIGHTA [ TRY ["("; "type"]; a_LIDENT; ")"; (n, x) = SELF -> (n + 1, x) | TRY labeled_ipatt; (n, x) = SELF -> (n + 1, x) | x = cvalue_binding -> (0, x) ] ]; let_binding: [ [ p = ipatt; (n, loc_eq) = fun_binding -> begin match p with | <:patt@ploc< _ >> when n > 0 -> print_after ploc " = fun"; replace loc_eq "->" | _ -> () end; <:binding< >> ] ] ; END DELETE_RULE Gram expr: `LABEL _; SELF END; EXTEND Gram GLOBAL: expr; located_expr: [[expr -> _loc]]; expr: LEVEL "label" [[ `LABEL _; expr LEVEL "." -> <:expr< >> | `LABEL _; e_loc = located_expr -> begin if not (file_contents.[Loc.start_off e_loc] = '(') then ( print_before e_loc "("; print_after e_loc ")"; ); <:expr< >> end ]]; END type payload_kind = Str | Typ | Pat let payload_kinds = Hashtbl.create 128 let set_payload_kind ~quotation_name kind = Hashtbl.add payload_kinds quotation_name kind (* Update quotations *) let () = DELETE_RULE Gram expr: `QUOTATION _ END EXTEND Gram expr: LEVEL "simple" [[ `QUOTATION q -> let { Camlp4.Sig. q_name; q_contents; q_loc=_; q_shift=_ } = q in let kind_marker = match Hashtbl.find payload_kinds q_name with | exception Not_found -> ":" | Typ -> ":" | Pat -> "?" | Str -> "" in let start = Loc.start_off _loc in let stop = Loc.stop_off _loc in add_subst ~start ~stop:(start + 2) ~repl:"[%"; (let start = start + 2 + String.length q_name in add_subst ~start ~stop:(start + 1) ~repl:kind_marker); add_subst ~start:(stop - 2) ~stop ~repl:"]"; <:expr< >> ]]; END external not_filtered : 'a -> 'a Gram.not_filtered = "%identity" external filtered : 'a Gram.not_filtered -> 'a = "%identity" let fix_lexer_stream stream = let maybe_last = ref None in (* Fix the Camlp4 lexer. Start locations are often wrong but end locations are always correct. *) let next _i = [ loc ] is this location , [ loc ' ] is the last location let tok, loc = Stream.next stream in match !maybe_last with | None -> maybe_last := Some loc; Some (tok, loc) | Some loc' -> maybe_last := Some loc; if Loc.file_name loc' = Loc.file_name loc then let _, _, _, _, a, b, c, _ = Loc.to_tuple loc' and n, _, _, _, d, e, f, g = Loc.to_tuple loc in Some (tok, Loc.of_tuple (n, a, b, c, d, e, f, g)) else Some (tok, loc) in Stream.from next let rec parse entry token_stream = let _, stopped_at_directive = Gram.parse_tokens_before_filter entry token_stream in match stopped_at_directive with | Some (_ : Loc.t) -> parse entry token_stream | None -> () let main_internal () = let token_stream = Gram.lex_string (Loc.mk input_file) file_contents in let token_stream = token_stream |> filtered |> fix_lexer_stream |> not_filtered in (match kind with | Structure -> parse Syntax.implem token_stream | Signature -> parse Syntax.interf token_stream); do_output() let main () = try main_internal () with exn -> Format.eprintf "@[<v0>%a@]@." Camlp4.ErrorHandler.print exn; exit 2
null
https://raw.githubusercontent.com/janestreet/camlp4-to-ppx/5dc1cf5a3dc9e1d206d07c91a2468fd31df01e05/lib/camlp4_to_ppx.ml
ocaml
This happens with 0-length substitutions Update quotations Fix the Camlp4 lexer. Start locations are often wrong but end locations are always correct.
open Printf open StdLabels open Camlp4.PreCast open Syntax let module M = Camlp4OCamlParser.Make(Camlp4OCamlRevisedParser.Make(Camlp4.PreCast.Syntax)) in () let program_name = Filename.basename Sys.executable_name let input_file = match Sys.argv with | [| _; fname |] -> fname | _ -> Printf.eprintf "Usage: %s FILE\n" program_name; exit 2 type kind = Signature | Structure let kind = if Filename.check_suffix input_file ".mli" then Signature else if Filename.check_suffix input_file ".ml" then Structure else begin Printf.eprintf "%s: unknown suffix in filename: %s\n" program_name input_file; exit 2 end let file_contents = let ic = open_in input_file in let len = in_channel_length ic in let str = Bytes.create len in really_input ic str 0 len; Bytes.to_string str type subst = { start : int ; stop : int ; repl : string } let substs = ref [] let do_output () = let rec loop pos substs = match substs with | [] -> output_substring stdout file_contents pos (String.length file_contents - pos) | { start; stop; repl } :: rest -> assert (pos <= start && start <= stop); output_substring stdout file_contents pos (start - pos); output_string stdout repl; loop stop rest in let substs = List.sort !substs ~cmp:(fun a b -> let d = compare a.start b.start in if d = 0 then compare a.stop b.stop else d) in loop 0 substs ;; let add_subst ~start ~stop ~repl = substs := { start; stop; repl } :: !substs let replace loc s = add_subst ~start:(Loc.start_off loc) ~stop:(Loc.stop_off loc) ~repl:s let print_at ~pos s = add_subst ~start:pos ~stop:pos ~repl:s let print_before loc s = print_at ~pos:(Loc.start_off loc) s let print_after loc s = print_at ~pos:(Loc.stop_off loc) s let erase_keyword loc = let start = Loc.start_off loc in let stop = Loc.stop_off loc in if start > 0 && file_contents.[start - 1] = ' ' && stop < String.length file_contents && file_contents.[stop ] = ' ' then add_subst ~start ~stop:(stop + 1) ~repl:"" else add_subst ~start ~stop ~repl:"" let skip_trailing_semi loc = let stop = Loc.stop_off loc in if stop > 0 && file_contents.[stop - 1] = ';' then add_subst ~start:(stop-1) ~stop ~repl:"" DELETE_RULE Gram let_binding: ipatt; fun_binding END [ let _ a = a ] is a syntax error in ocaml because a single underscore is a pattern , but not an identifier as required by the ocaml parser in a function - style binding . However , if is used to preprocess , the illegal syntax is masked by 's more permissive grammar . In effect the example gets rewritten as [ let _ = fun a - > a ] We do the same translation as . but not an identifier as required by the ocaml parser in a function-style binding. However, if camlp4 is used to preprocess, the illegal syntax is masked by camlp4's more permissive grammar. In effect the example gets rewritten as [let _ = fun a -> a] We do the same translation as camlp4. *) EXTEND Gram GLOBAL: let_binding; equal: [ [ "=" -> _loc ] ]; unquoted_typevars: [ LEFTA [ SELF; SELF -> () | a_ident -> () ] ] ; cvalue_binding: [ [ l = equal; expr -> l | ":"; "type"; unquoted_typevars; "." ; ctyp ; l = equal; expr -> l | ":"; poly_type; l = equal; expr -> l | ":"; poly_type; ":>"; ctyp; l = equal; expr -> l | ":>"; ctyp; l = equal; expr -> l ] ]; fun_binding: [ RIGHTA [ TRY ["("; "type"]; a_LIDENT; ")"; (n, x) = SELF -> (n + 1, x) | TRY labeled_ipatt; (n, x) = SELF -> (n + 1, x) | x = cvalue_binding -> (0, x) ] ]; let_binding: [ [ p = ipatt; (n, loc_eq) = fun_binding -> begin match p with | <:patt@ploc< _ >> when n > 0 -> print_after ploc " = fun"; replace loc_eq "->" | _ -> () end; <:binding< >> ] ] ; END DELETE_RULE Gram expr: `LABEL _; SELF END; EXTEND Gram GLOBAL: expr; located_expr: [[expr -> _loc]]; expr: LEVEL "label" [[ `LABEL _; expr LEVEL "." -> <:expr< >> | `LABEL _; e_loc = located_expr -> begin if not (file_contents.[Loc.start_off e_loc] = '(') then ( print_before e_loc "("; print_after e_loc ")"; ); <:expr< >> end ]]; END type payload_kind = Str | Typ | Pat let payload_kinds = Hashtbl.create 128 let set_payload_kind ~quotation_name kind = Hashtbl.add payload_kinds quotation_name kind let () = DELETE_RULE Gram expr: `QUOTATION _ END EXTEND Gram expr: LEVEL "simple" [[ `QUOTATION q -> let { Camlp4.Sig. q_name; q_contents; q_loc=_; q_shift=_ } = q in let kind_marker = match Hashtbl.find payload_kinds q_name with | exception Not_found -> ":" | Typ -> ":" | Pat -> "?" | Str -> "" in let start = Loc.start_off _loc in let stop = Loc.stop_off _loc in add_subst ~start ~stop:(start + 2) ~repl:"[%"; (let start = start + 2 + String.length q_name in add_subst ~start ~stop:(start + 1) ~repl:kind_marker); add_subst ~start:(stop - 2) ~stop ~repl:"]"; <:expr< >> ]]; END external not_filtered : 'a -> 'a Gram.not_filtered = "%identity" external filtered : 'a Gram.not_filtered -> 'a = "%identity" let fix_lexer_stream stream = let maybe_last = ref None in let next _i = [ loc ] is this location , [ loc ' ] is the last location let tok, loc = Stream.next stream in match !maybe_last with | None -> maybe_last := Some loc; Some (tok, loc) | Some loc' -> maybe_last := Some loc; if Loc.file_name loc' = Loc.file_name loc then let _, _, _, _, a, b, c, _ = Loc.to_tuple loc' and n, _, _, _, d, e, f, g = Loc.to_tuple loc in Some (tok, Loc.of_tuple (n, a, b, c, d, e, f, g)) else Some (tok, loc) in Stream.from next let rec parse entry token_stream = let _, stopped_at_directive = Gram.parse_tokens_before_filter entry token_stream in match stopped_at_directive with | Some (_ : Loc.t) -> parse entry token_stream | None -> () let main_internal () = let token_stream = Gram.lex_string (Loc.mk input_file) file_contents in let token_stream = token_stream |> filtered |> fix_lexer_stream |> not_filtered in (match kind with | Structure -> parse Syntax.implem token_stream | Signature -> parse Syntax.interf token_stream); do_output() let main () = try main_internal () with exn -> Format.eprintf "@[<v0>%a@]@." Camlp4.ErrorHandler.print exn; exit 2
da6616e48828d3c3af8e2580ad489ff731cc22799d2f863d5bb5268bb204a176
music-suite/music-suite
Generic.hs
# OPTIONS_GHC -fno - warn - orphans # -- | Provides ` GHC.Generic ` instances for ` Midi ` . module Codec.Midi.Generic where import GHC.Generics (Generic) import Codec.Midi (Midi(..), Message(..), TimeDiv(..), FileType(..)) deriving instance Generic Midi deriving instance Generic Message deriving instance Generic TimeDiv deriving instance Generic FileType
null
https://raw.githubusercontent.com/music-suite/music-suite/1856fece1152bd650449ff46bc2a4498d7a12dde/vendor/Codec/Midi/Generic.hs
haskell
|
# OPTIONS_GHC -fno - warn - orphans # Provides ` GHC.Generic ` instances for ` Midi ` . module Codec.Midi.Generic where import GHC.Generics (Generic) import Codec.Midi (Midi(..), Message(..), TimeDiv(..), FileType(..)) deriving instance Generic Midi deriving instance Generic Message deriving instance Generic TimeDiv deriving instance Generic FileType
aa9a7cc17a1e159816a9b4b366a07c92e6ca461121b276e4e7768970788fb3d2
tonsky/grumpy
macros.cljs
(ns grumpy.core.macros (:require-macros grumpy.core.macros))
null
https://raw.githubusercontent.com/tonsky/grumpy/5d4876535cd1fd6ab2b5a2c6e21f522a9c3e4e21/src/grumpy/core/macros.cljs
clojure
(ns grumpy.core.macros (:require-macros grumpy.core.macros))
ffecbecdb43bc8cd9cc61831dda5f390fa1f5322ec7bafce504459397764bc07
naoiwata/sicp
q2.65.scm
;; @author naoiwata SICP Chapter2 question 2.65 (add-load-path "." :relative) (load "pages/2.3.3.scm") ; intersection-set (load "q2.62.scm") ; union-set tree->list (load "q2.64.scm") ; list->tree (define (make-tree f tree-a tree-b) (let ((list-a (tree->list-2 tree-a)) (list-b (tree->list-2 tree-b))) (list->tree (f list-a list-b)))) (define (union-set-tree tree-a tree-b) (make-tree union-set tree-a tree-b)) (define (intersection-set-tree tree-a tree-b) (make-tree intersection-set tree-a tree-b)) ; END
null
https://raw.githubusercontent.com/naoiwata/sicp/7314136c5892de402015acfe4b9148a3558b1211/chapter2/q2.65.scm
scheme
@author naoiwata intersection-set union-set list->tree END
SICP Chapter2 question 2.65 (add-load-path "." :relative) tree->list (define (make-tree f tree-a tree-b) (let ((list-a (tree->list-2 tree-a)) (list-b (tree->list-2 tree-b))) (list->tree (f list-a list-b)))) (define (union-set-tree tree-a tree-b) (make-tree union-set tree-a tree-b)) (define (intersection-set-tree tree-a tree-b) (make-tree intersection-set tree-a tree-b))
9d34c20db4ec0258deca53640c11f465ff12afa82b74449685f5d3b294c92d01
f-o-a-m/kepler
Server.hs
module Network.ABCI.Server where import Data.Conduit (runConduit, (.|)) import qualified Data.Conduit.List as CL import Data.Conduit.Network (AppData, ServerSettings, appSink, appSource, runTCPServer, serverSettings) import Data.String (fromString) import Network.ABCI.Server.App (App (..)) import qualified Network.ABCI.Server.App as App -- | Default ABCI app network settings for serving on localhost at the -- standard port. defaultLocalSettings :: ServerSettings defaultLocalSettings = serverSettings 26658 $ fromString "0.0.0.0" -- | Serve an ABCI application with custom 'ServerSettings' and a custom -- action to perform on acquiring the socket resource. serveAppWith :: ServerSettings -> (AppData -> IO ()) -> App IO -> IO () serveAppWith cfg onAquire app = runTCPServer cfg $ \appData -> do onAquire appData runConduit $ appSource appData .| CL.mapM (fmap App.unLPByteStrings . App.runApp app . App.LPByteStrings) .| appSink appData -- | Serve an ABCI application with default local 'ServerSettings' -- and a no-op on acquiring the socket resource. serveApp :: App IO -> IO () serveApp = serveAppWith defaultLocalSettings mempty
null
https://raw.githubusercontent.com/f-o-a-m/kepler/6c1ad7f37683f509c2f1660e3561062307d3056b/hs-abci-server/src/Network/ABCI/Server.hs
haskell
| Default ABCI app network settings for serving on localhost at the standard port. | Serve an ABCI application with custom 'ServerSettings' and a custom action to perform on acquiring the socket resource. | Serve an ABCI application with default local 'ServerSettings' and a no-op on acquiring the socket resource.
module Network.ABCI.Server where import Data.Conduit (runConduit, (.|)) import qualified Data.Conduit.List as CL import Data.Conduit.Network (AppData, ServerSettings, appSink, appSource, runTCPServer, serverSettings) import Data.String (fromString) import Network.ABCI.Server.App (App (..)) import qualified Network.ABCI.Server.App as App defaultLocalSettings :: ServerSettings defaultLocalSettings = serverSettings 26658 $ fromString "0.0.0.0" serveAppWith :: ServerSettings -> (AppData -> IO ()) -> App IO -> IO () serveAppWith cfg onAquire app = runTCPServer cfg $ \appData -> do onAquire appData runConduit $ appSource appData .| CL.mapM (fmap App.unLPByteStrings . App.runApp app . App.LPByteStrings) .| appSink appData serveApp :: App IO -> IO () serveApp = serveAppWith defaultLocalSettings mempty
7df8f802dbab7dd3215d2424b9b9aae74a26da483e9415e7bd36a16efac489ba
aaronc/fx-clj
core.clj
(ns fx-clj.core (:refer-clojure :exclude [run!]) (:require [potemkin :refer [import-vars]] [fx-clj.core.run] [fx-clj.core.pset] [fx-clj.hiccup] [fx-clj.enlive] [fx-clj.elements] [fx-clj.css] [fx-clj.core.i18n] [fx-clj.util] [fx-clj.sandbox] [fx-clj.core.transforms] [fx-clj.core.extensibility] [fx-clj.core.binding] [clojure.string :as str])) (import-vars [fx-clj.core.run run! run<! run<!!] [fx-clj.core.pset pset!] [fx-clj.hiccup compile-fx build] [fx-clj.enlive at!] [fx-clj.sandbox sandbox] [fx-clj.css set-global-css!] [fx-clj.core.i18n with-locale with-resource-bundle get-resource-bundle get-locale get-resource] [fx-clj.util event-handler callback lookup] [fx-clj.core.binding property-ref observable-property bind<- bind<-> bind->]) (defn import-all [ns-sym] (eval `(potemkin/import-vars [~ns-sym ~@(keys (ns-publics (find-ns ns-sym)))]))) (import-all 'fx-clj.elements) (import-all 'fx-clj.core.transforms) (comment (defn available-transforms "Prints information on available transform functions for use primarily in the [[at!]] function." {:doc/format :markdown} [] (doseq [xform @fx-clj.core.extensibility/defined-transforms] (let [{:keys [doc]} (meta xform)] (println xform) (println doc) (println)))) (alter-meta! #'fx-clj.core/at! update-in [:doc] (fn [doc] (str doc (str/join "\n" (for [xform @fx-clj.core.extensibility/defined-transforms] (let [{:keys [ns name]} (meta xform)] (str " [[" name "]]"))))))))
null
https://raw.githubusercontent.com/aaronc/fx-clj/29639356d8d1253438ecf61e123caacefa9269ec/src/fx_clj/core.clj
clojure
(ns fx-clj.core (:refer-clojure :exclude [run!]) (:require [potemkin :refer [import-vars]] [fx-clj.core.run] [fx-clj.core.pset] [fx-clj.hiccup] [fx-clj.enlive] [fx-clj.elements] [fx-clj.css] [fx-clj.core.i18n] [fx-clj.util] [fx-clj.sandbox] [fx-clj.core.transforms] [fx-clj.core.extensibility] [fx-clj.core.binding] [clojure.string :as str])) (import-vars [fx-clj.core.run run! run<! run<!!] [fx-clj.core.pset pset!] [fx-clj.hiccup compile-fx build] [fx-clj.enlive at!] [fx-clj.sandbox sandbox] [fx-clj.css set-global-css!] [fx-clj.core.i18n with-locale with-resource-bundle get-resource-bundle get-locale get-resource] [fx-clj.util event-handler callback lookup] [fx-clj.core.binding property-ref observable-property bind<- bind<-> bind->]) (defn import-all [ns-sym] (eval `(potemkin/import-vars [~ns-sym ~@(keys (ns-publics (find-ns ns-sym)))]))) (import-all 'fx-clj.elements) (import-all 'fx-clj.core.transforms) (comment (defn available-transforms "Prints information on available transform functions for use primarily in the [[at!]] function." {:doc/format :markdown} [] (doseq [xform @fx-clj.core.extensibility/defined-transforms] (let [{:keys [doc]} (meta xform)] (println xform) (println doc) (println)))) (alter-meta! #'fx-clj.core/at! update-in [:doc] (fn [doc] (str doc (str/join "\n" (for [xform @fx-clj.core.extensibility/defined-transforms] (let [{:keys [ns name]} (meta xform)] (str " [[" name "]]"))))))))
c0da2437aa9462909a102cec7330805ba232b53bba0e7193f6045b74d2f95d84
lisp/de.setf.xml
schema.lisp
20100512T202630Z00 ;;; from #<doc-node -guide/food.rdf #x181415E6> (common-lisp:in-package "-owl-guide-20030818/food#") (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|BlandFish| (|-owl-guide-20031209/food#|:|Fish|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|BlandFishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|CheeseNutsDessert| (|-owl-guide-20031209/food#|::|Dessert|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|CheeseNutsDessertCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|ConsumableThing| nil ((|-owl-guide-20031209/food#|:|madeFromFruit| :type |-owl-guide-20031209/food#|:|Fruit|))) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|DarkMeatFowl| (|-owl-guide-20031209/food#|:|Fowl|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|DarkMeatFowlCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Dessert| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|DessertCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|EatingGrape| (|-owl-guide-20031209/food#|::|Grape|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|EdibleThing| (|-owl-guide-20031209/food#|::|ConsumableThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Fish| (|-owl-guide-20031209/food#|:|Seafood|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|FishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Fowl| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Fruit| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|FruitCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Grape| (|-owl-guide-20031209/food#|:|SweetFruit|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Juice| (|-owl-guide-20031209/food#|::|PotableLiquid|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|LightMeatFowl| (|-owl-guide-20031209/food#|:|Fowl|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|LightMeatFowlCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Meal| (|-owl-guide-20031209/food#|::|ConsumableThing|) ((|-owl-guide-20031209/food#|:|course| :type |-owl-guide-20031209/food#|::|MealCourse|))) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|MealCourse| (|-owl-guide-20031209/food#|::|ConsumableThing|) ((|-owl-guide-20031209/food#|:|hasDrink| :type |-owl-guide-20031209/food#|::|PotableLiquid|) (|-owl-guide-20031209/food#|:|hasFood| :type |-owl-guide-20031209/food#|::|EdibleThing|))) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Meat| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonBlandFish| (|-owl-guide-20031209/food#|:|Fish|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonBlandFishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonConsumableThing| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonOysterShellfish| (|-owl-guide-20031209/food#|:|Shellfish|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonOysterShellfishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonRedMeat| (|-owl-guide-20031209/food#|:|Meat|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonRedMeatCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonSpicyRedMeat| (|-owl-guide-20031209/food#|:|RedMeat|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonSpicyRedMeatCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonSweetFruit| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonSweetFruitCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|OtherTomatoBasedFood| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|OtherTomatoBasedFoodCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|OysterShellfish| (|-owl-guide-20031209/food#|:|Shellfish|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|OysterShellfishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Pasta| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithHeavyCreamCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithHeavyCreamSauce| (|-owl-guide-20031209/food#|::|PastaWithWhiteSauce|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithLightCreamCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithLightCreamSauce| (|-owl-guide-20031209/food#|::|PastaWithWhiteSauce|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithNonSpicyRedSauce| (|-owl-guide-20031209/food#|:|PastaWithRedSauce|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithNonSpicyRedSauceCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|PastaWithRedSauce| (|-owl-guide-20031209/food#|::|Pasta|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithSpicyRedSauce| (|-owl-guide-20031209/food#|:|PastaWithRedSauce|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithSpicyRedSauceCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithWhiteSauce| (|-owl-guide-20031209/food#|::|Pasta|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PotableLiquid| (|-owl-guide-20031209/food#|::|ConsumableThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|RedMeat| (|-owl-guide-20031209/food#|:|Meat|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|RedMeatCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Seafood| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SeafoodCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Shellfish| (|-owl-guide-20031209/food#|:|Seafood|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|ShellfishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SpicyRedMeat| (|-owl-guide-20031209/food#|:|RedMeat|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SpicyRedMeatCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SweetDessert| (|-owl-guide-20031209/food#|::|Dessert|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SweetDessertCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|SweetFruit| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SweetFruitCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Wine| nil nil)
null
https://raw.githubusercontent.com/lisp/de.setf.xml/827681c969342096c3b95735d84b447befa69fa6/namespaces/www-w3-org/TR/2003/CR-owl-guide-20030818/food/schema.lisp
lisp
from #<doc-node -guide/food.rdf #x181415E6>
20100512T202630Z00 (common-lisp:in-package "-owl-guide-20030818/food#") (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|BlandFish| (|-owl-guide-20031209/food#|:|Fish|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|BlandFishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|CheeseNutsDessert| (|-owl-guide-20031209/food#|::|Dessert|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|CheeseNutsDessertCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|ConsumableThing| nil ((|-owl-guide-20031209/food#|:|madeFromFruit| :type |-owl-guide-20031209/food#|:|Fruit|))) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|DarkMeatFowl| (|-owl-guide-20031209/food#|:|Fowl|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|DarkMeatFowlCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Dessert| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|DessertCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|EatingGrape| (|-owl-guide-20031209/food#|::|Grape|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|EdibleThing| (|-owl-guide-20031209/food#|::|ConsumableThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Fish| (|-owl-guide-20031209/food#|:|Seafood|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|FishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Fowl| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Fruit| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|FruitCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Grape| (|-owl-guide-20031209/food#|:|SweetFruit|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Juice| (|-owl-guide-20031209/food#|::|PotableLiquid|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|LightMeatFowl| (|-owl-guide-20031209/food#|:|Fowl|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|LightMeatFowlCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Meal| (|-owl-guide-20031209/food#|::|ConsumableThing|) ((|-owl-guide-20031209/food#|:|course| :type |-owl-guide-20031209/food#|::|MealCourse|))) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|MealCourse| (|-owl-guide-20031209/food#|::|ConsumableThing|) ((|-owl-guide-20031209/food#|:|hasDrink| :type |-owl-guide-20031209/food#|::|PotableLiquid|) (|-owl-guide-20031209/food#|:|hasFood| :type |-owl-guide-20031209/food#|::|EdibleThing|))) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Meat| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonBlandFish| (|-owl-guide-20031209/food#|:|Fish|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonBlandFishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonConsumableThing| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonOysterShellfish| (|-owl-guide-20031209/food#|:|Shellfish|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonOysterShellfishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonRedMeat| (|-owl-guide-20031209/food#|:|Meat|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonRedMeatCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonSpicyRedMeat| (|-owl-guide-20031209/food#|:|RedMeat|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonSpicyRedMeatCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonSweetFruit| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|NonSweetFruitCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|OtherTomatoBasedFood| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|OtherTomatoBasedFoodCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|OysterShellfish| (|-owl-guide-20031209/food#|:|Shellfish|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|OysterShellfishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Pasta| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithHeavyCreamCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithHeavyCreamSauce| (|-owl-guide-20031209/food#|::|PastaWithWhiteSauce|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithLightCreamCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithLightCreamSauce| (|-owl-guide-20031209/food#|::|PastaWithWhiteSauce|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithNonSpicyRedSauce| (|-owl-guide-20031209/food#|:|PastaWithRedSauce|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithNonSpicyRedSauceCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|PastaWithRedSauce| (|-owl-guide-20031209/food#|::|Pasta|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithSpicyRedSauce| (|-owl-guide-20031209/food#|:|PastaWithRedSauce|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithSpicyRedSauceCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PastaWithWhiteSauce| (|-owl-guide-20031209/food#|::|Pasta|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|PotableLiquid| (|-owl-guide-20031209/food#|::|ConsumableThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|RedMeat| (|-owl-guide-20031209/food#|:|Meat|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|RedMeatCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Seafood| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SeafoodCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|Shellfish| (|-owl-guide-20031209/food#|:|Seafood|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|ShellfishCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SpicyRedMeat| (|-owl-guide-20031209/food#|:|RedMeat|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SpicyRedMeatCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SweetDessert| (|-owl-guide-20031209/food#|::|Dessert|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SweetDessertCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|:|SweetFruit| (|-owl-guide-20031209/food#|::|EdibleThing|) nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|SweetFruitCourse| nil nil) (de.setf.resource.schema:defclass |-owl-guide-20031209/food#|::|Wine| nil nil)
34a0d60fbc91cc56cfde64387aeb1a7d79a2945dfbbb534593ffb3bf72952141
ekmett/linear-haskell
Array.hs
{-# LANGUAGE LinearTypes #-} # LANGUAGE ImportQualifiedPost # # LANGUAGE NoImplicitPrelude # -- | Same API as @Data . Array . Mutable . Linear@ , but freeze exports a Prim . Array -- rather than a Vector, and the constructor is exposed to match the -- @primitive@ API's style module Data.Primitive.Linear.Array ( -- * Mutable Linear Arrays Array(Array), -- * Performing Computations with Arrays alloc, allocBeside, fromList, -- * Modifications set, unsafeSet, resize, map, -- * Accessors get, unsafeGet, size, slice, toList, freeze, -- * Mutable-style interface read, unsafeRead, write, unsafeWrite ) where import Data.Unrestricted.Linear import Data.Array.Mutable.Linear hiding (freeze) import Data.Array.Mutable.Linear.Internal (Array(Array)) import Data.Array.Mutable.Unlifted.Linear qualified as Unlifted import Data.Primitive.Array qualified as Prim freeze :: (Prim.Array a -> b) -> Array a %1 -> Ur b freeze f (Array arr) = Unlifted.freeze (\m -> f (Prim.Array m)) arr
null
https://raw.githubusercontent.com/ekmett/linear-haskell/6f9e5c0e96d0c99d064ae027086db48c4fcfc63c/linear-primitive/src/Data/Primitive/Linear/Array.hs
haskell
# LANGUAGE LinearTypes # | rather than a Vector, and the constructor is exposed to match the @primitive@ API's style * Mutable Linear Arrays * Performing Computations with Arrays * Modifications * Accessors * Mutable-style interface
# LANGUAGE ImportQualifiedPost # # LANGUAGE NoImplicitPrelude # Same API as @Data . Array . Mutable . Linear@ , but freeze exports a Prim . Array module Data.Primitive.Linear.Array Array(Array), alloc, allocBeside, fromList, set, unsafeSet, resize, map, get, unsafeGet, size, slice, toList, freeze, read, unsafeRead, write, unsafeWrite ) where import Data.Unrestricted.Linear import Data.Array.Mutable.Linear hiding (freeze) import Data.Array.Mutable.Linear.Internal (Array(Array)) import Data.Array.Mutable.Unlifted.Linear qualified as Unlifted import Data.Primitive.Array qualified as Prim freeze :: (Prim.Array a -> b) -> Array a %1 -> Ur b freeze f (Array arr) = Unlifted.freeze (\m -> f (Prim.Array m)) arr
391bb6b535506374543f9278a280d9a4229736818b6766874f8530edfcaefdd2
Clozure/ccl-tests
pathname-version.lsp
;-*- Mode: Lisp -*- Author : Created : Sat Dec 6 14:45:16 2003 ;;;; Contains: Tests for PATHNAME-VERSION (in-package :cl-test) (compile-and-load "pathnames-aux.lsp") (deftest pathname-version.1 (loop for p in *pathnames* for version = (pathname-version p) unless (or (integerp version) (symbolp version)) collect (list p version)) nil) ;;; section 19.3.2.1 (deftest pathname-version.2 (loop for p in *logical-pathnames* when (eq (pathname-version p) :unspecific) collect p) nil) (deftest pathname-version.3 (do-special-strings (s "" nil) (pathname-version s)) nil) (deftest pathname-version.error.1 (signals-error (pathname-version) program-error) t) (deftest pathname-version.error.2 (signals-error (pathname-version *default-pathname-defaults* nil) program-error) t) (deftest pathname-version.error.3 (check-type-error #'pathname-version #'could-be-pathname-designator) nil)
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/pathname-version.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests for PATHNAME-VERSION section 19.3.2.1
Author : Created : Sat Dec 6 14:45:16 2003 (in-package :cl-test) (compile-and-load "pathnames-aux.lsp") (deftest pathname-version.1 (loop for p in *pathnames* for version = (pathname-version p) unless (or (integerp version) (symbolp version)) collect (list p version)) nil) (deftest pathname-version.2 (loop for p in *logical-pathnames* when (eq (pathname-version p) :unspecific) collect p) nil) (deftest pathname-version.3 (do-special-strings (s "" nil) (pathname-version s)) nil) (deftest pathname-version.error.1 (signals-error (pathname-version) program-error) t) (deftest pathname-version.error.2 (signals-error (pathname-version *default-pathname-defaults* nil) program-error) t) (deftest pathname-version.error.3 (check-type-error #'pathname-version #'could-be-pathname-designator) nil)
22334353619042f1ad7f96ffa97366a68caa91f67af63fcf35c714b879f79883
Decentralized-Pictures/T4L3NT
tenderbake.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Nomadic Labs < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) Testing ------- Component : Tenderbake Invocation : dune exec / tests / main.exe -- --file tenderbake.ml Subject : Basic test for and related newly added API components ------- Component: Tenderbake Invocation: dune exec tezt/tests/main.exe -- --file tenderbake.ml Subject: Basic test for Tenderbake and related newly added API components *) (* ------------------------------------------------------------------------- *) (* Typedefs *) let transfer_data = (Constant.bootstrap1.alias, Tez.one, Constant.bootstrap2.alias) let baker = Constant.bootstrap5.alias let default_overrides = [ (* ensure that blocks must be endorsed *) (["consensus_threshold"], Some "6"); ] let init ?(overrides = default_overrides) protocol = let* sandbox_node = Node.init [Synchronisation_threshold 0; Private_mode] in let sandbox_endpoint = Client.Node sandbox_node in let* sandbox_client = Client.init ~endpoint:sandbox_endpoint () in let* parameter_file = let base = Either.Right (protocol, None) in Protocol.write_parameter_file ~base overrides in let* () = activate in the past - let timestamp_delay be the default value of 1 year Client.activate_protocol ~protocol sandbox_client ~parameter_file in Log.info "Activated protocol." ; return @@ ( Tezos_crypto.Protocol_hash.of_b58check_exn (Protocol.hash protocol), sandbox_endpoint, sandbox_client ) let bootstrap_accounts = List.tl Constant.all_secret_keys let endorsers = [ Constant.bootstrap1.alias; Constant.bootstrap2.alias; Constant.bootstrap3.alias; Constant.bootstrap4.alias; Constant.bootstrap5.alias; ] let endorse endpoint protocol client endorsers = Client.endorse_for ~endpoint ~protocol ~key:endorsers ~force:true client let preendorse endpoint protocol client preendorsers = Client.preendorse_for ~endpoint ~protocol ~key:preendorsers ~force:true client let test_bake_two = Protocol.register_test ~__FILE__ ~title:"Tenderbake transfer - baking 2" ~tags:["baking"; "tenderbake"] @@ fun protocol -> let* (_proto_hash, endpoint, client) = init protocol in let end_idx = List.length bootstrap_accounts in let rec loop i = if i = end_idx then Lwt.return_unit else let baker = [ (List.nth bootstrap_accounts i).alias; (List.nth bootstrap_accounts ((i + 3) mod end_idx)).alias; ] in let amount = Tez.of_int (i + 1) in let giver = (List.nth bootstrap_accounts ((i + 1) mod end_idx)).alias in let receiver = (List.nth bootstrap_accounts ((i + 2) mod end_idx)).alias in Log.info "Phase %d" i ; let* () = Client.transfer ~amount ~giver ~receiver client in let* () = Client.bake_for ~endpoint ~protocol ~keys:baker client in loop (i + 1) in loop 0 let test_low_level_commands = Protocol.register_test ~__FILE__ ~title:"Tenderbake low level commands" ~tags:["propose"; "endorse"; "preendorse"; "tenderbake"; "low_level"] @@ fun protocol -> let* (_proto_hash, endpoint, client) = init protocol in Log.info "Doing a propose -> preendorse -> endorse cycle" ; let proposer = endorsers in let preendorsers = endorsers in let* () = Client.transfer ~amount:(Tez.of_int 3) ~giver:Constant.bootstrap1.alias ~receiver:Constant.bootstrap2.alias client in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in let* () = preendorse endpoint protocol client preendorsers in let* () = endorse endpoint protocol client endorsers in let* () = Client.transfer ~amount:(Tez.of_int 2) ~giver:Constant.bootstrap1.alias ~receiver:Constant.bootstrap2.alias client in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in let* () = preendorse endpoint protocol client preendorsers in let* () = endorse endpoint protocol client endorsers in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in Lwt.return_unit let test_repropose = Protocol.register_test ~__FILE__ ~title:"Tenderbake low level repropose" ~tags: [ "propose"; "endorse"; "preendorse"; "tenderbake"; "low_level"; "repropose"; ] @@ fun protocol -> let* (_proto_hash, endpoint, client) = init protocol in Log.info "Doing a propose -> preendorse -> endorse cycle" ; let proposer = endorsers in let preendorsers = endorsers in let* () = Client.transfer ~amount:(Tez.of_int 3) ~giver:Constant.bootstrap1.alias ~receiver:Constant.bootstrap2.alias client in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in let* () = preendorse endpoint protocol client preendorsers in let* () = endorse endpoint protocol client endorsers in let* () = Client.transfer ~amount:(Tez.of_int 2) ~giver:Constant.bootstrap1.alias ~receiver:Constant.bootstrap2.alias client in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in let sleeping_time = 5. in Log.debug "Waiting %.0fs so that the previous round ends" sleeping_time ; let* () = Lwt_unix.sleep sleeping_time in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in Lwt.return_unit let register ~protocols = test_bake_two ~protocols ; test_low_level_commands ~protocols ; test_repropose ~protocols
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/tezt/tests/tenderbake.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** ------------------------------------------------------------------------- Typedefs ensure that blocks must be endorsed
Copyright ( c ) 2021 Nomadic Labs < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING Testing ------- Component : Tenderbake Invocation : dune exec / tests / main.exe -- --file tenderbake.ml Subject : Basic test for and related newly added API components ------- Component: Tenderbake Invocation: dune exec tezt/tests/main.exe -- --file tenderbake.ml Subject: Basic test for Tenderbake and related newly added API components *) let transfer_data = (Constant.bootstrap1.alias, Tez.one, Constant.bootstrap2.alias) let baker = Constant.bootstrap5.alias let default_overrides = [ ] let init ?(overrides = default_overrides) protocol = let* sandbox_node = Node.init [Synchronisation_threshold 0; Private_mode] in let sandbox_endpoint = Client.Node sandbox_node in let* sandbox_client = Client.init ~endpoint:sandbox_endpoint () in let* parameter_file = let base = Either.Right (protocol, None) in Protocol.write_parameter_file ~base overrides in let* () = activate in the past - let timestamp_delay be the default value of 1 year Client.activate_protocol ~protocol sandbox_client ~parameter_file in Log.info "Activated protocol." ; return @@ ( Tezos_crypto.Protocol_hash.of_b58check_exn (Protocol.hash protocol), sandbox_endpoint, sandbox_client ) let bootstrap_accounts = List.tl Constant.all_secret_keys let endorsers = [ Constant.bootstrap1.alias; Constant.bootstrap2.alias; Constant.bootstrap3.alias; Constant.bootstrap4.alias; Constant.bootstrap5.alias; ] let endorse endpoint protocol client endorsers = Client.endorse_for ~endpoint ~protocol ~key:endorsers ~force:true client let preendorse endpoint protocol client preendorsers = Client.preendorse_for ~endpoint ~protocol ~key:preendorsers ~force:true client let test_bake_two = Protocol.register_test ~__FILE__ ~title:"Tenderbake transfer - baking 2" ~tags:["baking"; "tenderbake"] @@ fun protocol -> let* (_proto_hash, endpoint, client) = init protocol in let end_idx = List.length bootstrap_accounts in let rec loop i = if i = end_idx then Lwt.return_unit else let baker = [ (List.nth bootstrap_accounts i).alias; (List.nth bootstrap_accounts ((i + 3) mod end_idx)).alias; ] in let amount = Tez.of_int (i + 1) in let giver = (List.nth bootstrap_accounts ((i + 1) mod end_idx)).alias in let receiver = (List.nth bootstrap_accounts ((i + 2) mod end_idx)).alias in Log.info "Phase %d" i ; let* () = Client.transfer ~amount ~giver ~receiver client in let* () = Client.bake_for ~endpoint ~protocol ~keys:baker client in loop (i + 1) in loop 0 let test_low_level_commands = Protocol.register_test ~__FILE__ ~title:"Tenderbake low level commands" ~tags:["propose"; "endorse"; "preendorse"; "tenderbake"; "low_level"] @@ fun protocol -> let* (_proto_hash, endpoint, client) = init protocol in Log.info "Doing a propose -> preendorse -> endorse cycle" ; let proposer = endorsers in let preendorsers = endorsers in let* () = Client.transfer ~amount:(Tez.of_int 3) ~giver:Constant.bootstrap1.alias ~receiver:Constant.bootstrap2.alias client in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in let* () = preendorse endpoint protocol client preendorsers in let* () = endorse endpoint protocol client endorsers in let* () = Client.transfer ~amount:(Tez.of_int 2) ~giver:Constant.bootstrap1.alias ~receiver:Constant.bootstrap2.alias client in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in let* () = preendorse endpoint protocol client preendorsers in let* () = endorse endpoint protocol client endorsers in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in Lwt.return_unit let test_repropose = Protocol.register_test ~__FILE__ ~title:"Tenderbake low level repropose" ~tags: [ "propose"; "endorse"; "preendorse"; "tenderbake"; "low_level"; "repropose"; ] @@ fun protocol -> let* (_proto_hash, endpoint, client) = init protocol in Log.info "Doing a propose -> preendorse -> endorse cycle" ; let proposer = endorsers in let preendorsers = endorsers in let* () = Client.transfer ~amount:(Tez.of_int 3) ~giver:Constant.bootstrap1.alias ~receiver:Constant.bootstrap2.alias client in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in let* () = preendorse endpoint protocol client preendorsers in let* () = endorse endpoint protocol client endorsers in let* () = Client.transfer ~amount:(Tez.of_int 2) ~giver:Constant.bootstrap1.alias ~receiver:Constant.bootstrap2.alias client in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in let sleeping_time = 5. in Log.debug "Waiting %.0fs so that the previous round ends" sleeping_time ; let* () = Lwt_unix.sleep sleeping_time in let* () = Client.propose_for client ~protocol ~endpoint ~key:proposer in Lwt.return_unit let register ~protocols = test_bake_two ~protocols ; test_low_level_commands ~protocols ; test_repropose ~protocols
7bf4e2d0efd5fcda23435066e5a0f1fdf3c6c1e97d8861523770adabcea79b15
sheyll/mediabus
StreamSpec.hs
module Data.MediaBus.Conduit.StreamSpec (spec) where import Conduit import Control.Lens import Control.Monad.Logger import Data.Conduit.List import Data.MediaBus import Test.Hspec import Test.QuickCheck spec :: Spec spec = do describe "Stream functions" $ do describe "isStartFrame" $ it "returns True for start frames and False otherwise" $ do isStartFrame (MkStream (Start (MkFrameCtx () () () ()))) `shouldBe` True isStartFrame (MkStream (Next (MkFrame () () ()))) `shouldBe` False describe "isPayloadFrame" $ it "returns True for payload frames and False otherwise" $ do isPayloadFrame (MkStream (Start (MkFrameCtx () () () ()))) `shouldBe` False isPayloadFrame (MkStream (Next (MkFrame () () ()))) `shouldBe` True describe "Stream conduits" $ do describe "logStreamC" $ do it "passes through the values when no logging is performced" $ property $ \(inputs :: [Stream Bool Int Int Int Int]) -> ioProperty $ do outputs <- runNoLoggingT . runResourceT . runConduit $ (yieldMany inputs .| logStreamC "test-log-source" (const Nothing) "test" .| consume) return (inputs === outputs) it "passes through the values when logging is performced" $ property $ \(inputs :: [Stream Bool Int Int Int Int]) -> ioProperty $ do outputs <- runNoLoggingT . runResourceT . runConduit $ (yieldMany inputs .| logStreamC "test-log-source" (const (Just LevelWarn)) "test" .| consume) return (inputs === outputs) describe "assumeSynchronized" $ it "removes sequence numbers and timestamps but passes all buffers untouched" $ property $ \(inputs :: [Stream Bool Int Int Int Int]) -> let outputs = runConduitPure (yieldMany inputs .| assumeSynchronizedC .| sinkList) in length inputs === length outputs .&&. toListOf (each . eachFramePayload) inputs === toListOf (each . eachFramePayload) outputs
null
https://raw.githubusercontent.com/sheyll/mediabus/2bc01544956b2c30dedbb0bb61dc115eef6aa689/specs/Data/MediaBus/Conduit/StreamSpec.hs
haskell
module Data.MediaBus.Conduit.StreamSpec (spec) where import Conduit import Control.Lens import Control.Monad.Logger import Data.Conduit.List import Data.MediaBus import Test.Hspec import Test.QuickCheck spec :: Spec spec = do describe "Stream functions" $ do describe "isStartFrame" $ it "returns True for start frames and False otherwise" $ do isStartFrame (MkStream (Start (MkFrameCtx () () () ()))) `shouldBe` True isStartFrame (MkStream (Next (MkFrame () () ()))) `shouldBe` False describe "isPayloadFrame" $ it "returns True for payload frames and False otherwise" $ do isPayloadFrame (MkStream (Start (MkFrameCtx () () () ()))) `shouldBe` False isPayloadFrame (MkStream (Next (MkFrame () () ()))) `shouldBe` True describe "Stream conduits" $ do describe "logStreamC" $ do it "passes through the values when no logging is performced" $ property $ \(inputs :: [Stream Bool Int Int Int Int]) -> ioProperty $ do outputs <- runNoLoggingT . runResourceT . runConduit $ (yieldMany inputs .| logStreamC "test-log-source" (const Nothing) "test" .| consume) return (inputs === outputs) it "passes through the values when logging is performced" $ property $ \(inputs :: [Stream Bool Int Int Int Int]) -> ioProperty $ do outputs <- runNoLoggingT . runResourceT . runConduit $ (yieldMany inputs .| logStreamC "test-log-source" (const (Just LevelWarn)) "test" .| consume) return (inputs === outputs) describe "assumeSynchronized" $ it "removes sequence numbers and timestamps but passes all buffers untouched" $ property $ \(inputs :: [Stream Bool Int Int Int Int]) -> let outputs = runConduitPure (yieldMany inputs .| assumeSynchronizedC .| sinkList) in length inputs === length outputs .&&. toListOf (each . eachFramePayload) inputs === toListOf (each . eachFramePayload) outputs
bb5ac345131124a5ce7f20d03c13f50ec7bd92a31d6ad88a221ec6667e484192
rurban/clisp
x-sequence.lisp
Copyright ( C ) 2002 - 2004 , < > ;; ALL RIGHTS RESERVED. ;; $ I d : x - sequence.lisp , v 1.11 2004/02/20 07:23:42 yuji Exp $ ;; ;; 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. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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. (HANDLER-CASE (PROGN (SUBSEQ '(0 1 . 2) 1)) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (SUBSEQ '#1=(0 1 . #1#) 3)) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (MAP 'LIST #'+ '(0 1 . 2) '(1 0 -1 -2))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(1 . 2))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '#1=(1 2 3 4 5 6 7 8 9 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G H . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G H I . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G H I J . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G H I J K . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A . B))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '#1=(0 1 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(1 . 2))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '#1=(1 2 3 4 5 6 7 8 9 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G H . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G H I . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G H I J . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G H I J K . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A . B))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '#1=(0 1 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '#1=(1 2 3 4 5 6 7 8 9 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G H . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G H I . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G H I J . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G H I J K . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (NREVERSE (CONS 'A 'B))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LET ((A (LIST 0 1))) (SETF (CDDR A) A) (NREVERSE A))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LET ((A (LIST 0 1 2 3))) (SETF (CDR (NTHCDR 3 A)) A) (NREVERSE A))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LET ((A (LIST 0 1 2 3 4))) (SETF (CDR (NTHCDR 4 A)) (CDDR A)) (NREVERSE A))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND 'ITEM '(A B . C))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND-IF (CONSTANTLY NIL) '(A B . C))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND-IF-NOT (CONSTANTLY T) '(A B . C))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND 'ITEM '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND-IF (CONSTANTLY NIL) '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND-IF-NOT (CONSTANTLY T) '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (POSITION 'ITEM '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (POSITION-IF (CONSTANTLY NIL) '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (POSITION-IF-NOT (CONSTANTLY T) '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
null
https://raw.githubusercontent.com/rurban/clisp/75ed2995ff8f5364bcc18727cde9438cca4e7c2c/sacla-tests/x-sequence.lisp
lisp
ALL RIGHTS RESERVED. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright ( C ) 2002 - 2004 , < > $ I d : x - sequence.lisp , v 1.11 2004/02/20 07:23:42 yuji Exp $ " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (HANDLER-CASE (PROGN (SUBSEQ '(0 1 . 2) 1)) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (SUBSEQ '#1=(0 1 . #1#) 3)) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (MAP 'LIST #'+ '(0 1 . 2) '(1 0 -1 -2))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(1 . 2))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '#1=(1 2 3 4 5 6 7 8 9 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G H . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G H I . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G H I J . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(A B C D E F G H I J K . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A . B))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '#1=(0 1 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '(1 . 2))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REDUCE #'LIST '#1=(1 2 3 4 5 6 7 8 9 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G H . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G H I . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G H I J . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LENGTH '(A B C D E F G H I J K . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A . B))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '#1=(0 1 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '#1=(1 2 3 4 5 6 7 8 9 . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G H . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G H I . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G H I J . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (REVERSE '(A B C D E F G H I J K . #1=(1 2 3 4 5 6 7 8 9 . #1#)))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (NREVERSE (CONS 'A 'B))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LET ((A (LIST 0 1))) (SETF (CDDR A) A) (NREVERSE A))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LET ((A (LIST 0 1 2 3))) (SETF (CDR (NTHCDR 3 A)) A) (NREVERSE A))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (LET ((A (LIST 0 1 2 3 4))) (SETF (CDR (NTHCDR 4 A)) (CDDR A)) (NREVERSE A))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND 'ITEM '(A B . C))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND-IF (CONSTANTLY NIL) '(A B . C))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND-IF-NOT (CONSTANTLY T) '(A B . C))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND 'ITEM '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND-IF (CONSTANTLY NIL) '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (FIND-IF-NOT (CONSTANTLY T) '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (POSITION 'ITEM '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (POSITION-IF (CONSTANTLY NIL) '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL)) (HANDLER-CASE (PROGN (POSITION-IF-NOT (CONSTANTLY T) '#1=(A B . #1#))) (TYPE-ERROR NIL T) (ERROR NIL NIL) (:NO-ERROR (&REST REST) (DECLARE (IGNORE REST)) NIL))
baaf69caea10f23ce46a52596ad6d1feb0048538daaa02c91fd783ee841cb671
BillHallahan/G2
Test5.hs
module Combined ( List , test_nearest) where import Prelude hiding (length, replicate, foldr, foldr1, map, concat, zipWith, repeat) import qualified Data.List as L infixr 9 :+: {-@ die :: {v:String | false} -> a @-} die str = error ("Oops, I died!" ++ str) data List a = Emp | (:+:) a (List a) deriving (Eq, Ord, Show) @ measure size : : List a - > Int size ( Emp ) = 0 size ( (: + :) x xs ) = 1 + size xs @ size (Emp) = 0 size ((:+:) x xs) = 1 + size xs @-} {-@ invariant {v:List a | 0 <= size v} @-} @ type ListN a N = { v : List a | size v = N } @ empty :: List a empty = Emp add :: a -> List a -> List a add x xs = x :+: xs foldr :: (a -> b -> b) -> b -> List a -> b foldr _ b Emp = b foldr op b (x :+: xs) = x `op` foldr op b xs zipWith :: List a -> List a -> List a zipWith Emp Emp = Emp zipWith (x :+: xs) (y :+: ys) = x :+: zipWith xs ys zipWith _ _ = die "Bad call to zipWith" distance :: List Double -> List Double -> Double distance px py = foldr (+) 0 $ zipWith px py {-@ nearest :: Map Int {_ : (List Double) | false} -> (List Double) -> (Int, List Double) @-} nearest :: Map Int (List Double) -> List Double -> (Int, List Double) nearest centers p = minimumBy f keyList where keyList = toList centers f x1 x2 = compare (distance (snd x1) p) (distance (snd x2) p) test_nearest = nearest (fromList [(0, p0), (1, p1)]) p where p, p0, p1 :: List Double p0 = add 0.0 empty p1 = add 0.0 empty p = add 1.1 empty data Map k a = Assocs [(k, a)] fromList :: Ord k => [(k,a)] -> Map k a fromList kas = Assocs (sby keycmp $ reverse kas) where keycmp (k1, _) (k2, _) = k1 `compare` k2 iby _ x [] = [x] iby cmp x ys@(y:ys') = case cmp x y of GT -> y : iby cmp x ys' _ -> x : ys sby cmp = L.foldr (iby cmp) [] toList :: Map k a -> [(k,a)] toList (Assocs kas) = kas minimumBy :: (a -> a -> Ordering) -> [a] -> a minimumBy cmp xs = foldl1 minBy xs where minBy x y = case cmp x y of GT -> y _ -> x
null
https://raw.githubusercontent.com/BillHallahan/G2/21c648d38c380041a9036d0e375ec1d54120f6b4/tests_lh/test_files/Neg/Test5.hs
haskell
@ die :: {v:String | false} -> a @ @ invariant {v:List a | 0 <= size v} @ @ nearest :: Map Int {_ : (List Double) | false} -> (List Double) -> (Int, List Double) @
module Combined ( List , test_nearest) where import Prelude hiding (length, replicate, foldr, foldr1, map, concat, zipWith, repeat) import qualified Data.List as L infixr 9 :+: die str = error ("Oops, I died!" ++ str) data List a = Emp | (:+:) a (List a) deriving (Eq, Ord, Show) @ measure size : : List a - > Int size ( Emp ) = 0 size ( (: + :) x xs ) = 1 + size xs @ size (Emp) = 0 size ((:+:) x xs) = 1 + size xs @-} @ type ListN a N = { v : List a | size v = N } @ empty :: List a empty = Emp add :: a -> List a -> List a add x xs = x :+: xs foldr :: (a -> b -> b) -> b -> List a -> b foldr _ b Emp = b foldr op b (x :+: xs) = x `op` foldr op b xs zipWith :: List a -> List a -> List a zipWith Emp Emp = Emp zipWith (x :+: xs) (y :+: ys) = x :+: zipWith xs ys zipWith _ _ = die "Bad call to zipWith" distance :: List Double -> List Double -> Double distance px py = foldr (+) 0 $ zipWith px py nearest :: Map Int (List Double) -> List Double -> (Int, List Double) nearest centers p = minimumBy f keyList where keyList = toList centers f x1 x2 = compare (distance (snd x1) p) (distance (snd x2) p) test_nearest = nearest (fromList [(0, p0), (1, p1)]) p where p, p0, p1 :: List Double p0 = add 0.0 empty p1 = add 0.0 empty p = add 1.1 empty data Map k a = Assocs [(k, a)] fromList :: Ord k => [(k,a)] -> Map k a fromList kas = Assocs (sby keycmp $ reverse kas) where keycmp (k1, _) (k2, _) = k1 `compare` k2 iby _ x [] = [x] iby cmp x ys@(y:ys') = case cmp x y of GT -> y : iby cmp x ys' _ -> x : ys sby cmp = L.foldr (iby cmp) [] toList :: Map k a -> [(k,a)] toList (Assocs kas) = kas minimumBy :: (a -> a -> Ordering) -> [a] -> a minimumBy cmp xs = foldl1 minBy xs where minBy x y = case cmp x y of GT -> y _ -> x
8ff4ff0ba1cf00b95fe71686152b88992828965f9d3856cdd0b39f611ecf945b
FranklinChen/hugs98-plus-Sep2006
Types.hs
# OPTIONS_GHC -fno - implicit - prelude # ----------------------------------------------------------------------------- -- | Module : System . . Types Copyright : ( c ) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : provisional -- Portability : non-portable (requires POSIX) -- POSIX data types : equivalents of the types defined by the -- @\<sys\/types.h>@ C header on a POSIX system. -- ----------------------------------------------------------------------------- #include "HsBaseConfig.h" module System.Posix.Types ( -- * POSIX data types #if defined(HTYPE_DEV_T) CDev, #endif #if defined(HTYPE_INO_T) CIno, #endif #if defined(HTYPE_MODE_T) CMode, #endif #if defined(HTYPE_OFF_T) COff, #endif #if defined(HTYPE_PID_T) CPid, #endif #if defined(HTYPE_SSIZE_T) CSsize, #endif #if defined(HTYPE_GID_T) CGid, #endif #if defined(HTYPE_NLINK_T) CNlink, #endif #if defined(HTYPE_UID_T) CUid, #endif #if defined(HTYPE_CC_T) CCc, #endif #if defined(HTYPE_SPEED_T) CSpeed, #endif #if defined(HTYPE_TCFLAG_T) CTcflag, #endif #if defined(HTYPE_RLIM_T) CRLim, #endif Fd(..), #if defined(HTYPE_NLINK_T) LinkCount, #endif #if defined(HTYPE_UID_T) UserID, #endif #if defined(HTYPE_GID_T) GroupID, #endif ByteCount, ClockTick, EpochTime, FileOffset, ProcessID, ProcessGroupID, DeviceID, FileID, FileMode, Limit ) where import Foreign import Foreign.C import Data.Typeable import Data.Bits #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.Enum import GHC.Num import GHC.Real import GHC.Prim import GHC.Read import GHC.Show #else import Control.Monad #endif #include "CTypes.h" #if defined(HTYPE_DEV_T) ARITHMETIC_TYPE(CDev,tyConCDev,"CDev",HTYPE_DEV_T) #endif #if defined(HTYPE_INO_T) INTEGRAL_TYPE(CIno,tyConCIno,"CIno",HTYPE_INO_T) #endif #if defined(HTYPE_MODE_T) INTEGRAL_TYPE(CMode,tyConCMode,"CMode",HTYPE_MODE_T) #endif #if defined(HTYPE_OFF_T) INTEGRAL_TYPE(COff,tyConCOff,"COff",HTYPE_OFF_T) #endif #if defined(HTYPE_PID_T) INTEGRAL_TYPE(CPid,tyConCPid,"CPid",HTYPE_PID_T) #endif #if defined(HTYPE_SSIZE_T) INTEGRAL_TYPE(CSsize,tyConCSsize,"CSsize",HTYPE_SSIZE_T) #endif #if defined(HTYPE_GID_T) INTEGRAL_TYPE(CGid,tyConCGid,"CGid",HTYPE_GID_T) #endif #if defined(HTYPE_NLINK_T) INTEGRAL_TYPE(CNlink,tyConCNlink,"CNlink",HTYPE_NLINK_T) #endif #if defined(HTYPE_UID_T) INTEGRAL_TYPE(CUid,tyConCUid,"CUid",HTYPE_UID_T) #endif #if defined(HTYPE_CC_T) ARITHMETIC_TYPE(CCc,tyConCCc,"CCc",HTYPE_CC_T) #endif #if defined(HTYPE_SPEED_T) ARITHMETIC_TYPE(CSpeed,tyConCSpeed,"CSpeed",HTYPE_SPEED_T) #endif #if defined(HTYPE_TCFLAG_T) INTEGRAL_TYPE(CTcflag,tyConCTcflag,"CTcflag",HTYPE_TCFLAG_T) #endif #if defined(HTYPE_RLIM_T) INTEGRAL_TYPE(CRLim,tyConCRlim,"CRLim",HTYPE_RLIM_T) #endif ToDo : blksize_t , clockid_t , blkcnt_t , fsblkcnt_t , fsfilcnt_t , id_t , key_t -- suseconds_t, timer_t, useconds_t Make an Fd type rather than using CInt everywhere INTEGRAL_TYPE(Fd,tyConFd,"Fd",CInt) -- nicer names, and backwards compatibility with POSIX library: #if defined(HTYPE_NLINK_T) type LinkCount = CNlink #endif #if defined(HTYPE_UID_T) type UserID = CUid #endif #if defined(HTYPE_GID_T) type GroupID = CGid #endif type ByteCount = CSize type ClockTick = CClock type EpochTime = CTime type DeviceID = CDev type FileID = CIno type FileMode = CMode type ProcessID = CPid type FileOffset = COff type ProcessGroupID = CPid type Limit = CLong
null
https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/base/System/Posix/Types.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : provisional Portability : non-portable (requires POSIX) @\<sys\/types.h>@ C header on a POSIX system. --------------------------------------------------------------------------- * POSIX data types suseconds_t, timer_t, useconds_t nicer names, and backwards compatibility with POSIX library:
# OPTIONS_GHC -fno - implicit - prelude # Module : System . . Types Copyright : ( c ) The University of Glasgow 2002 POSIX data types : equivalents of the types defined by the #include "HsBaseConfig.h" module System.Posix.Types ( #if defined(HTYPE_DEV_T) CDev, #endif #if defined(HTYPE_INO_T) CIno, #endif #if defined(HTYPE_MODE_T) CMode, #endif #if defined(HTYPE_OFF_T) COff, #endif #if defined(HTYPE_PID_T) CPid, #endif #if defined(HTYPE_SSIZE_T) CSsize, #endif #if defined(HTYPE_GID_T) CGid, #endif #if defined(HTYPE_NLINK_T) CNlink, #endif #if defined(HTYPE_UID_T) CUid, #endif #if defined(HTYPE_CC_T) CCc, #endif #if defined(HTYPE_SPEED_T) CSpeed, #endif #if defined(HTYPE_TCFLAG_T) CTcflag, #endif #if defined(HTYPE_RLIM_T) CRLim, #endif Fd(..), #if defined(HTYPE_NLINK_T) LinkCount, #endif #if defined(HTYPE_UID_T) UserID, #endif #if defined(HTYPE_GID_T) GroupID, #endif ByteCount, ClockTick, EpochTime, FileOffset, ProcessID, ProcessGroupID, DeviceID, FileID, FileMode, Limit ) where import Foreign import Foreign.C import Data.Typeable import Data.Bits #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.Enum import GHC.Num import GHC.Real import GHC.Prim import GHC.Read import GHC.Show #else import Control.Monad #endif #include "CTypes.h" #if defined(HTYPE_DEV_T) ARITHMETIC_TYPE(CDev,tyConCDev,"CDev",HTYPE_DEV_T) #endif #if defined(HTYPE_INO_T) INTEGRAL_TYPE(CIno,tyConCIno,"CIno",HTYPE_INO_T) #endif #if defined(HTYPE_MODE_T) INTEGRAL_TYPE(CMode,tyConCMode,"CMode",HTYPE_MODE_T) #endif #if defined(HTYPE_OFF_T) INTEGRAL_TYPE(COff,tyConCOff,"COff",HTYPE_OFF_T) #endif #if defined(HTYPE_PID_T) INTEGRAL_TYPE(CPid,tyConCPid,"CPid",HTYPE_PID_T) #endif #if defined(HTYPE_SSIZE_T) INTEGRAL_TYPE(CSsize,tyConCSsize,"CSsize",HTYPE_SSIZE_T) #endif #if defined(HTYPE_GID_T) INTEGRAL_TYPE(CGid,tyConCGid,"CGid",HTYPE_GID_T) #endif #if defined(HTYPE_NLINK_T) INTEGRAL_TYPE(CNlink,tyConCNlink,"CNlink",HTYPE_NLINK_T) #endif #if defined(HTYPE_UID_T) INTEGRAL_TYPE(CUid,tyConCUid,"CUid",HTYPE_UID_T) #endif #if defined(HTYPE_CC_T) ARITHMETIC_TYPE(CCc,tyConCCc,"CCc",HTYPE_CC_T) #endif #if defined(HTYPE_SPEED_T) ARITHMETIC_TYPE(CSpeed,tyConCSpeed,"CSpeed",HTYPE_SPEED_T) #endif #if defined(HTYPE_TCFLAG_T) INTEGRAL_TYPE(CTcflag,tyConCTcflag,"CTcflag",HTYPE_TCFLAG_T) #endif #if defined(HTYPE_RLIM_T) INTEGRAL_TYPE(CRLim,tyConCRlim,"CRLim",HTYPE_RLIM_T) #endif ToDo : blksize_t , clockid_t , blkcnt_t , fsblkcnt_t , fsfilcnt_t , id_t , key_t Make an Fd type rather than using CInt everywhere INTEGRAL_TYPE(Fd,tyConFd,"Fd",CInt) #if defined(HTYPE_NLINK_T) type LinkCount = CNlink #endif #if defined(HTYPE_UID_T) type UserID = CUid #endif #if defined(HTYPE_GID_T) type GroupID = CGid #endif type ByteCount = CSize type ClockTick = CClock type EpochTime = CTime type DeviceID = CDev type FileID = CIno type FileMode = CMode type ProcessID = CPid type FileOffset = COff type ProcessGroupID = CPid type Limit = CLong
5d1286dbce6b9f2bfb673433eb3b34f15798b8b49a6cb405b23caa0aa12b5487
simplegeo/erlang
array.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2007 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% @author < > @author < > %% @version 1.0 %% @doc Functional, extendible arrays. Arrays can have fixed size, or %% can grow automatically as needed. A default value is used for entries %% that have not been explicitly set. %% Arrays uses < b > > based indexing . This is a deliberate design choice and differs from other erlang datastructures , e.g. tuples . %% %% Unless specified by the user when the array is created, the default %% value is the atom `undefined'. There is no difference between an %% unset entry and an entry which has been explicitly set to the same %% value as the default one (cf. {@link reset/2}). If you need to %% differentiate between unset and set entries, you must make sure that %% the default value cannot be confused with the values of set entries. %% %% The array never shrinks automatically; if an index `I' has been used %% successfully to set an entry, all indices in the range [0,`I'] will %% stay accessible unless the array size is explicitly changed by %% calling {@link resize/2}. %% %% Examples: %% ``` % % Create a fixed - size array with entries 0 - 9 set to ' undefined ' %% A0 = array:new(10). 10 = array : size(A0 ) . %% % % Create an extendible array and set entry 17 to ' true ' , %% %% causing the array to grow automatically %% A1 = array:set(17, true, array:new()). 18 = array : size(A1 ) . %% %% %% Read back a stored value %% true = array:get(17, A1). %% %% %% Accessing an unset entry returns the default value %% undefined = array:get(3, A1). %% %% %% Accessing an entry beyond the last set entry also returns the %% %% default value, if the array does not have fixed size %% undefined = array:get(18, A1). %% %% %% "sparse" functions ignore default-valued entries %% A2 = array:set(4, false, A1). [ { 4 , false } , { 17 , true } ] = array : sparse_to_orddict(A2 ) . %% %% %% An extendible array can be made fixed-size later %% A3 = array:fix(A2). %% %% %% A fixed-size array does not grow automatically and does not %% %% allow accesses beyond the last set entry { ' EXIT',{badarg , _ } } = ( catch array : set(18 , true , A3 ) ) . %% {'EXIT',{badarg,_}} = (catch array:get(18, A3)). %% ''' %% @type array(). A functional, extendible array. The representation is %% not documented and is subject to change without notice. Note that %% arrays cannot be directly compared for equality. -module(array). -export([new/0, new/1, new/2, is_array/1, set/3, get/2, size/1, sparse_size/1, default/1, reset/2, to_list/1, sparse_to_list/1, from_list/1, from_list/2, to_orddict/1, sparse_to_orddict/1, from_orddict/1, from_orddict/2, map/2, sparse_map/2, foldl/3, foldr/3, sparse_foldl/3, sparse_foldr/3, fix/1, relax/1, is_fix/1, resize/1, resize/2]). ) . -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. %% Developers: %% For OTP devs : Both tests and documentation is extracted from this %% file, keep and update this file, %% test are extracted with array_SUITE:extract_tests(). Doc with docb_gen array.erl %% %% The key to speed is to minimize the number of tests, on %% large input. Always make the most probable path as short as possible. %% In particular, keep in mind that for large trees, the probability of %% a leaf node is small relative to that of an internal node. %% %% If you try to tweak the set_1 and get_1 loops: Measure, look at the %% generated Beam code, and measure again! The argument order matters! %% Representation: %% %% A tree is either a leaf, with LEAFSIZE elements (the "base"), an internal node with elements , or an unexpanded tree , %% represented by a single integer: the number of elements that may be %% stored in the tree when it is expanded. The last element of an %% internal node caches the number of elements that may be stored in %% each of its subtrees. %% Note that to update an entry in a tree of height h = log[b ] n , the %% total number of written words is (b+1)+(h-1)*(b+2), since tuples use a header word on the heap . 4 is the optimal base for minimizing the %% number of words written, but causes higher trees, which takes time. %% The best compromise between speed and memory usage seems to lie %% around 8-10. Measurements indicate that the optimum base for speed is 24 - above that , it gets slower again due to the high memory usage . Base 10 is a good choice , giving 2/3 of the possible speedup from base 4 , but only using 1/3 more memory . ( Base 24 uses 65 % more memory per write than base 10 , but the speedup is only 21 % . ) -define(DEFAULT, undefined). -define(LEAFSIZE, 10). % the "base" -define(NODESIZE, ?LEAFSIZE). % (no reason to have a different size) NODESIZE+1 elements ! -define(NEW_NODE(S), % beware of argument duplication! setelement((?NODESIZE+1),erlang:make_tuple((?NODESIZE+1),(S)),(S))). -define(NEW_LEAF(D), erlang:make_tuple(?LEAFSIZE,(D))). -define(NODELEAFS, ?NODESIZE*?LEAFSIZE). %% These make the code a little easier to experiment with. %% It turned out that using shifts (when NODESIZE=2^n) was not faster. -define(reduce(X), ((X) div (?NODESIZE))). -define(extend(X), ((X) * (?NODESIZE))). %%-------------------------------------------------------------------------- -record(array, {size :: non_neg_integer(), %% number of defined entries max :: non_neg_integer(), %% maximum number of entries %% in current tree default, %% the default value (usually 'undefined') elements %% the tuple tree }). %% A declaration equivalent to the following one is hard-coded in erl_types. %% That declaration contains hard-coded information about the #array{} %% structure and the types of its fields. So, please make sure that any %% changes to its structure are also propagated to erl_types.erl. %% %% -opaque array() :: #array{}. %% %% Types %% -type array_indx() :: non_neg_integer(). -type array_opt() :: 'fixed' | non_neg_integer() | {'default', term()} | {'fixed', boolean()} | {'size', non_neg_integer()}. -type array_opts() :: array_opt() | [array_opt()]. -type indx_pair() :: {array_indx(), term()}. -type indx_pairs() :: [indx_pair()]. %%-------------------------------------------------------------------------- ( ) - > array ( ) @doc Create a new , extendible array with initial size zero . %% @equiv new([]) %% @see new/1 @see -spec new() -> array(). new() -> new([]). %% @spec (Options::term()) -> array() %% @doc Create a new array according to the given options. By default, the array is extendible and has initial size zero . Array indices %% start at 0. %% %% `Options' is a single term or a list of terms, selected from the %% following: %% <dl> %% <dt>`N::integer()' or `{size, N::integer()}'</dt> %% <dd>Specifies the initial size of the array; this also implies %% `{fixed, true}'. If `N' is not a nonnegative integer, the call %% fails with reason `badarg'.</dd> %% <dt>`fixed' or `{fixed, true}'</dt> < dd > Creates a fixed - size array ; see also { @link fix/1}.</dd > %% <dt>`{fixed, false}'</dt> < dd > Creates an extendible ( non fixed - size ) array.</dd > %% <dt>`{default, Value}'</dt> < dd > Sets the default value for the array to ` Value'.</dd > %% </dl> %% Options are processed in the order they occur in the list, i.e., %% later options have higher precedence. %% %% The default value is used as the value of uninitialized entries, and %% cannot be changed once the array has been created. %% %% Examples: ` ` ` array : new(100 ) '' ' creates a fixed - size array of size 100 . %% ```array:new({default,0})''' creates an empty, extendible array %% whose default value is 0. %% ```array:new([{size,10},{fixed,false},{default,-1}])''' creates an extendible array with initial size 10 whose default value is -1 . %% @see new/0 @see @see set/3 @see get/2 %% @see from_list/2 %% @see fix/1 -spec new(array_opts()) -> array(). new(Options) -> new_0(Options, 0, false). ( Size::integer ( ) , Options::term ( ) ) - > array ( ) %% @doc Create a new array according to the given size and options. If %% `Size' is not a nonnegative integer, the call fails with reason %% `badarg'. By default, the array has fixed size. Note that any size %% specifications in `Options' will override the `Size' parameter. %% %% If `Options' is a list, this is simply equivalent to `new([{size, %% Size} | Options]', otherwise it is equivalent to `new([{size, Size} | %% [Options]]'. However, using this function directly is more efficient. %% %% Example: %% ```array:new(100, {default,0})''' creates a fixed-size array of size 100 , whose default value is 0 . %% @see new/1 -spec new(non_neg_integer(), array_opts()) -> array(). new(Size, Options) when is_integer(Size), Size >= 0 -> new_0(Options, Size, true); new(_, _) -> erlang:error(badarg). new_0(Options, Size, Fixed) when is_list(Options) -> new_1(Options, Size, Fixed, ?DEFAULT); new_0(Options, Size, Fixed) -> new_1([Options], Size, Fixed, ?DEFAULT). new_1([fixed | Options], Size, _, Default) -> new_1(Options, Size, true, Default); new_1([{fixed, Fixed} | Options], Size, _, Default) when is_boolean(Fixed) -> new_1(Options, Size, Fixed, Default); new_1([{default, Default} | Options], Size, Fixed, _) -> new_1(Options, Size, Fixed, Default); new_1([{size, Size} | Options], _, _, Default) when is_integer(Size), Size >= 0 -> new_1(Options, Size, true, Default); new_1([Size | Options], _, _, Default) when is_integer(Size), Size >= 0 -> new_1(Options, Size, true, Default); new_1([], Size, Fixed, Default) -> new(Size, Fixed, Default); new_1(_Options, _Size, _Fixed, _Default) -> erlang:error(badarg). new(0, false, undefined) -> %% Constant empty array #array{size=0, max=?LEAFSIZE, elements=?LEAFSIZE}; new(Size, Fixed, Default) -> E = find_max(Size - 1, ?LEAFSIZE), M = if Fixed -> 0; true -> E end, #array{size = Size, max = M, default = Default, elements = E}. -spec find_max(integer(), integer()) -> integer(). find_max(I, M) when I >= M -> find_max(I, ?extend(M)); find_max(_I, M) -> M. ( X::term ( ) ) - > boolean ( ) %% @doc Returns `true' if `X' appears to be an array, otherwise `false'. %% Note that the check is only shallow; there is no guarantee that `X' %% is a well-formed array representation even if this function returns %% `true'. -spec is_array(term()) -> boolean(). is_array(#array{size = Size, max = Max}) when is_integer(Size), is_integer(Max) -> true; is_array(_) -> false. ( array ( ) ) - > integer ( ) %% @doc Get the number of entries in the array. Entries are numbered from 0 to ` size(Array)-1 ' ; hence , this is also the index of the first %% entry that is guaranteed to not have been previously set. @see set/3 %% @see sparse_size/1 -spec size(array()) -> non_neg_integer(). size(#array{size = N}) -> N; size(_) -> erlang:error(badarg). ( array ( ) ) - > term ( ) %% @doc Get the value used for uninitialized entries. %% @see -spec default(array()) -> term(). default(#array{default = D}) -> D; default(_) -> erlang:error(badarg). -ifdef(EUNIT). new_test_() -> N0 = ?LEAFSIZE, N01 = N0+1, N1 = ?NODESIZE*N0, N11 = N1+1, N2 = ?NODESIZE*N1, [?_test(new()), ?_test(new([])), ?_test(new(10)), ?_test(new({size,10})), ?_test(new(fixed)), ?_test(new({fixed,true})), ?_test(new({fixed,false})), ?_test(new({default,undefined})), ?_test(new([{size,100},{fixed,false},{default,undefined}])), ?_test(new([100,fixed,{default,0}])), ?_assert(new() =:= new([])), ?_assert(new() =:= new([{size,0},{default,undefined},{fixed,false}])), ?_assert(new() =:= new(0, {fixed,false})), ?_assert(new(fixed) =:= new(0)), ?_assert(new(fixed) =:= new(0, [])), ?_assert(new(10) =:= new([{size,0},{size,5},{size,10}])), ?_assert(new(10) =:= new(0, {size,10})), ?_assert(new(10, []) =:= new(10, [{default,undefined},{fixed,true}])), ?_assertError(badarg, new(-1)), ?_assertError(badarg, new(10.0)), ?_assertError(badarg, new(undefined)), ?_assertError(badarg, new([undefined])), ?_assertError(badarg, new([{default,0} | fixed])), ?_assertError(badarg, new(-1, [])), ?_assertError(badarg, new(10.0, [])), ?_assertError(badarg, new(undefined, [])), ?_assertMatch(#array{size=0,max=N0,default=undefined,elements=N0}, new()), ?_assertMatch(#array{size=0,max=0,default=undefined,elements=N0}, new(fixed)), ?_assertMatch(#array{size=N0,max=N0,elements=N0}, new(N0, {fixed,false})), ?_assertMatch(#array{size=N01,max=N1,elements=N1}, new(N01, {fixed,false})), ?_assertMatch(#array{size=N1,max=N1,elements=N1}, new(N1, {fixed,false})), ?_assertMatch(#array{size=N11,max=N2,elements=N2}, new(N11, {fixed,false})), ?_assertMatch(#array{size=N2, max=N2, default=42,elements=N2}, new(N2, [{fixed,false},{default,42}])), ?_assert(0 =:= array:size(new())), ?_assert(17 =:= array:size(new(17))), ?_assert(100 =:= array:size(array:set(99,0,new()))), ?_assertError(badarg, array:size({bad_data,gives_error})), ?_assert(undefined =:= default(new())), ?_assert(4711 =:= default(new({default,4711}))), ?_assert(0 =:= default(new(10, {default,0}))), ?_assertError(badarg, default({bad_data,gives_error})), ?_assert(is_array(new())), ?_assert(false =:= is_array({foobar, 23, 23})), ?_assert(false =:= is_array(#array{size=bad})), ?_assert(false =:= is_array(#array{max=bad})), ?_assert(is_array(new(10))), ?_assert(is_array(new(10, {fixed,false}))) ]. -endif. ( array ( ) ) - > array ( ) %% @doc Fix the size of the array. This prevents it from growing %% automatically upon insertion; see also {@link set/3}. @see relax/1 -spec fix(array()) -> array(). fix(#array{}=A) -> A#array{max = 0}. ( array ( ) ) - > boolean ( ) %% @doc Check if the array has fixed size. %% Returns `true' if the array is fixed, otherwise `false'. %% @see fix/1 -spec is_fix(array()) -> boolean(). is_fix(#array{max = 0}) -> true; is_fix(#array{}) -> false. -ifdef(EUNIT). fix_test_() -> [?_assert(is_array(fix(new()))), ?_assert(fix(new()) =:= new(fixed)), ?_assertNot(is_fix(new())), ?_assertNot(is_fix(new([]))), ?_assertNot(is_fix(new({fixed,false}))), ?_assertNot(is_fix(new(10, {fixed,false}))), ?_assert(is_fix(new({fixed,true}))), ?_assert(is_fix(new(fixed))), ?_assert(is_fix(new(10))), ?_assert(is_fix(new(10, []))), ?_assert(is_fix(new(10, {fixed,true}))), ?_assert(is_fix(fix(new()))), ?_assert(is_fix(fix(new({fixed,false})))), ?_test(set(0, 17, new())), ?_assertError(badarg, set(0, 17, new(fixed))), ?_assertError(badarg, set(1, 42, fix(set(0, 17, new())))), ?_test(set(9, 17, new(10))), ?_assertError(badarg, set(10, 17, new(10))), ?_assertError(badarg, set(10, 17, fix(new(10, {fixed,false})))) ]. -endif. ( array ( ) ) - > array ( ) %% @doc Make the array resizable. (Reverses the effects of {@link %% fix/1}.) %% @see fix/1 -spec relax(array()) -> array(). relax(#array{size = N}=A) -> A#array{max = find_max(N-1, ?LEAFSIZE)}. -ifdef(EUNIT). relax_test_() -> [?_assert(is_array(relax(new(fixed)))), ?_assertNot(is_fix(relax(fix(new())))), ?_assertNot(is_fix(relax(new(fixed)))), ?_assert(new() =:= relax(new(fixed))), ?_assert(new() =:= relax(new(0))), ?_assert(new(17, {fixed,false}) =:= relax(new(17))), ?_assert(new(100, {fixed,false}) =:= relax(fix(new(100, {fixed,false})))) ]. -endif. %% @spec (integer(), array()) -> array() %% @doc Change the size of the array. If `Size' is not a nonnegative %% integer, the call fails with reason `badarg'. If the given array has %% fixed size, the resulting array will also have fixed size. -spec resize(non_neg_integer(), array()) -> array(). resize(Size, #array{size = N, max = M, elements = E}=A) when is_integer(Size), Size >= 0 -> if Size > N -> {E1, M1} = grow(Size-1, E, if M > 0 -> M; true -> find_max(N-1, ?LEAFSIZE) end), A#array{size = Size, max = if M > 0 -> M1; true -> M end, elements = E1}; Size < N -> %% TODO: shrink physical representation when shrinking the array A#array{size = Size}; true -> A end; resize(_Size, _) -> erlang:error(badarg). ( array ( ) ) - > array ( ) %% @doc Change the size of the array to that reported by {@link %% sparse_size/1}. If the given array has fixed size, the resulting %% array will also have fixed size. %% @equiv resize(sparse_size(Array), Array) %% @see resize/2 %% @see sparse_size/1 -spec resize(array()) -> array(). resize(Array) -> resize(sparse_size(Array), Array). -ifdef(EUNIT). resize_test_() -> [?_assert(resize(0, new()) =:= new()), ?_assert(resize(99, new(99)) =:= new(99)), ?_assert(resize(99, relax(new(99))) =:= relax(new(99))), ?_assert(is_fix(resize(100, new(10)))), ?_assertNot(is_fix(resize(100, relax(new(10))))), ?_assert(array:size(resize(100, new())) =:= 100), ?_assert(array:size(resize(0, new(100))) =:= 0), ?_assert(array:size(resize(99, new(10))) =:= 99), ?_assert(array:size(resize(99, new(1000))) =:= 99), ?_assertError(badarg, set(99, 17, new(10))), ?_test(set(99, 17, resize(100, new(10)))), ?_assertError(badarg, set(100, 17, resize(100, new(10)))), ?_assert(array:size(resize(new())) =:= 0), ?_assert(array:size(resize(new(8))) =:= 0), ?_assert(array:size(resize(array:set(7, 0, new()))) =:= 8), ?_assert(array:size(resize(array:set(7, 0, new(10)))) =:= 8), ?_assert(array:size(resize(array:set(99, 0, new(10,{fixed,false})))) =:= 100), ?_assert(array:size(resize(array:set(7, undefined, new()))) =:= 0), ?_assert(array:size(resize(array:from_list([1,2,3,undefined]))) =:= 3), ?_assert(array:size( resize(array:from_orddict([{3,0},{17,0},{99,undefined}]))) =:= 18), ?_assertError(badarg, resize(foo, bad_argument)) ]. -endif. %% @spec (integer(), term(), array()) -> array() %% @doc Set entry `I' of the array to `Value'. If `I' is not a %% nonnegative integer, or if the array has fixed size and `I' is larger %% than the maximum index, the call fails with reason `badarg'. %% %% If the array does not have fixed size, and `I' is greater than ` size(Array)-1 ' , the array will grow to size ` I+1 ' . %% @see get/2 %% @see reset/2 -spec set(array_indx(), term(), array()) -> array(). set(I, Value, #array{size = N, max = M, default = D, elements = E}=A) when is_integer(I), I >= 0 -> if I < N -> A#array{elements = set_1(I, E, Value, D)}; I < M -> %% (note that this cannot happen if M == 0, since N >= 0) A#array{size = I+1, elements = set_1(I, E, Value, D)}; M > 0 -> {E1, M1} = grow(I, E, M), A#array{size = I+1, max = M1, elements = set_1(I, E1, Value, D)}; true -> erlang:error(badarg) end; set(_I, _V, _A) -> erlang:error(badarg). See get_1/3 for details about switching and the NODEPATTERN macro . set_1(I, E=?NODEPATTERN(S), X, D) -> I1 = I div S + 1, setelement(I1, E, set_1(I rem S, element(I1, E), X, D)); set_1(I, E, X, D) when is_integer(E) -> expand(I, E, X, D); set_1(I, E, X, _D) -> setelement(I+1, E, X). %% Enlarging the array upwards to accommodate an index `I' grow(I, E, _M) when is_integer(E) -> M1 = find_max(I, E), {M1, M1}; grow(I, E, M) -> grow_1(I, E, M). grow_1(I, E, M) when I >= M -> grow(I, setelement(1, ?NEW_NODE(M), E), ?extend(M)); grow_1(_I, E, M) -> {E, M}. %% Insert an element in an unexpanded node, expanding it as necessary. expand(I, S, X, D) when S > ?LEAFSIZE -> S1 = ?reduce(S), setelement(I div S1 + 1, ?NEW_NODE(S1), expand(I rem S1, S1, X, D)); expand(I, _S, X, D) -> setelement(I+1, ?NEW_LEAF(D), X). %% @spec (integer(), array()) -> term() %% @doc Get the value of entry `I'. If `I' is not a nonnegative %% integer, or if the array has fixed size and `I' is larger than the %% maximum index, the call fails with reason `badarg'. %% %% If the array does not have fixed size, this function will return the default value for any index ` I ' greater than ` size(Array)-1 ' . @see set/3 -spec get(array_indx(), array()) -> term(). get(I, #array{size = N, max = M, elements = E, default = D}) when is_integer(I), I >= 0 -> if I < N -> get_1(I, E, D); M > 0 -> D; true -> erlang:error(badarg) end; get(_I, _A) -> erlang:error(badarg). The use of NODEPATTERN(S ) to select the right clause is just a hack , %% but it is the only way to get the maximum speed out of this loop ( using the Beam compiler in OTP 11 ) . get_1(I, E=?NODEPATTERN(S), D) -> get_1(I rem S, element(I div S + 1, E), D); get_1(_I, E, D) when is_integer(E) -> D; get_1(I, E, _D) -> element(I+1, E). %% @spec (integer(), array()) -> array() %% @doc Reset entry `I' to the default value for the array. %% If the value of entry `I' is the default value the array will be %% returned unchanged. Reset will never change size of the array. %% Shrinking can be done explicitly by calling {@link resize/2}. %% %% If `I' is not a nonnegative integer, or if the array has fixed size %% and `I' is larger than the maximum index, the call fails with reason %% `badarg'; cf. {@link set/3} %% @see @see set/3 %% TODO: a reset_range function -spec reset(array_indx(), array()) -> array(). reset(I, #array{size = N, max = M, default = D, elements = E}=A) when is_integer(I), I >= 0 -> if I < N -> try A#array{elements = reset_1(I, E, D)} catch throw:default -> A end; M > 0 -> A; true -> erlang:error(badarg) end; reset(_I, _A) -> erlang:error(badarg). reset_1(I, E=?NODEPATTERN(S), D) -> I1 = I div S + 1, setelement(I1, E, reset_1(I rem S, element(I1, E), D)); reset_1(_I, E, _D) when is_integer(E) -> throw(default); reset_1(I, E, D) -> Indx = I+1, case element(Indx, E) of D -> throw(default); _ -> setelement(I+1, E, D) end. -ifdef(EUNIT). set_get_test_() -> N0 = ?LEAFSIZE, N1 = ?NODESIZE*N0, [?_assert(array:get(0, new()) =:= undefined), ?_assert(array:get(1, new()) =:= undefined), ?_assert(array:get(99999, new()) =:= undefined), ?_assert(array:get(0, new(1)) =:= undefined), ?_assert(array:get(0, new(1,{default,0})) =:= 0), ?_assert(array:get(9, new(10)) =:= undefined), ?_assertError(badarg, array:get(0, new(fixed))), ?_assertError(badarg, array:get(1, new(1))), ?_assertError(badarg, array:get(-1, new(1))), ?_assertError(badarg, array:get(10, new(10))), ?_assertError(badarg, array:set(-1, foo, new(10))), ?_assertError(badarg, array:set(10, foo, no_array)), ?_assert(array:size(set(0, 17, new())) =:= 1), ?_assert(array:size(set(N1-1, 17, new())) =:= N1), ?_assert(array:size(set(0, 42, set(0, 17, new()))) =:= 1), ?_assert(array:size(set(9, 42, set(0, 17, new()))) =:= 10), ?_assert(array:get(0, set(0, 17, new())) =:= 17), ?_assert(array:get(0, set(1, 17, new())) =:= undefined), ?_assert(array:get(1, set(1, 17, new())) =:= 17), ?_assert(array:get(0, fix(set(0, 17, new()))) =:= 17), ?_assertError(badarg, array:get(1, fix(set(0, 17, new())))), ?_assert(array:get(N1-2, set(N1-1, 17, new())) =:= undefined), ?_assert(array:get(N1-1, set(N1-1, 17, new())) =:= 17), ?_assertError(badarg, array:get(N1, fix(set(N1-1, 17, new())))), ?_assert(array:get(0, set(0, 42, set(0, 17, new()))) =:= 42), ?_assert(array:get(0, reset(0, new())) =:= undefined), ?_assert(array:get(0, reset(0, set(0, 17, new()))) =:= undefined), ?_assert(array:get(0, reset(0, new({default,42}))) =:= 42), ?_assert(array:get(0, reset(0, set(0, 17, new({default,42})))) =:= 42) ]. -endif. ( array ( ) ) - > list ( ) %% @doc Converts the array to a list. %% %% @see from_list/2 %% @see sparse_to_list/1 -spec to_list(array()) -> list(). to_list(#array{size = 0}) -> []; to_list(#array{size = N, elements = E, default = D}) -> to_list_1(E, D, N - 1); to_list(_) -> erlang:error(badarg). %% this part handles the rightmost subtrees to_list_1(E=?NODEPATTERN(S), D, I) -> N = I div S, to_list_3(N, D, to_list_1(element(N+1, E), D, I rem S), E); to_list_1(E, D, I) when is_integer(E) -> push(I+1, D, []); to_list_1(E, _D, I) -> push_tuple(I+1, E, []). %% this part handles full trees only to_list_2(E=?NODEPATTERN(_S), D, L) -> to_list_3(?NODESIZE, D, L, E); to_list_2(E, D, L) when is_integer(E) -> push(E, D, L); to_list_2(E, _D, L) -> push_tuple(?LEAFSIZE, E, L). to_list_3(0, _D, L, _E) -> L; to_list_3(N, D, L, E) -> to_list_3(N-1, D, to_list_2(element(N, E), D, L), E). push(0, _E, L) -> L; push(N, E, L) -> push(N - 1, E, [E | L]). push_tuple(0, _T, L) -> L; push_tuple(N, T, L) -> push_tuple(N - 1, T, [element(N, T) | L]). -ifdef(EUNIT). to_list_test_() -> N0 = ?LEAFSIZE, [?_assert([] =:= to_list(new())), ?_assert([undefined] =:= to_list(new(1))), ?_assert([undefined,undefined] =:= to_list(new(2))), ?_assert(lists:duplicate(N0,0) =:= to_list(new(N0,{default,0}))), ?_assert(lists:duplicate(N0+1,1) =:= to_list(new(N0+1,{default,1}))), ?_assert(lists:duplicate(N0+2,2) =:= to_list(new(N0+2,{default,2}))), ?_assert(lists:duplicate(666,6) =:= to_list(new(666,{default,6}))), ?_assert([1,2,3] =:= to_list(set(2,3,set(1,2,set(0,1,new()))))), ?_assert([3,2,1] =:= to_list(set(0,3,set(1,2,set(2,1,new()))))), ?_assert([1|lists:duplicate(N0-2,0)++[1]] =:= to_list(set(N0-1,1,set(0,1,new({default,0}))))), ?_assert([1|lists:duplicate(N0-1,0)++[1]] =:= to_list(set(N0,1,set(0,1,new({default,0}))))), ?_assert([1|lists:duplicate(N0,0)++[1]] =:= to_list(set(N0+1,1,set(0,1,new({default,0}))))), ?_assert([1|lists:duplicate(N0*3,0)++[1]] =:= to_list(set((N0*3)+1,1,set(0,1,new({default,0}))))), ?_assertError(badarg, to_list(no_array)) ]. -endif. ( array ( ) ) - > list ( ) %% @doc Converts the array to a list, skipping default-valued entries. %% %% @see to_list/1 -spec sparse_to_list(array()) -> list(). sparse_to_list(#array{size = 0}) -> []; sparse_to_list(#array{size = N, elements = E, default = D}) -> sparse_to_list_1(E, D, N - 1); sparse_to_list(_) -> erlang:error(badarg). %% see to_list/1 for details sparse_to_list_1(E=?NODEPATTERN(S), D, I) -> N = I div S, sparse_to_list_3(N, D, sparse_to_list_1(element(N+1, E), D, I rem S), E); sparse_to_list_1(E, _D, _I) when is_integer(E) -> []; sparse_to_list_1(E, D, I) -> sparse_push_tuple(I+1, D, E, []). sparse_to_list_2(E=?NODEPATTERN(_S), D, L) -> sparse_to_list_3(?NODESIZE, D, L, E); sparse_to_list_2(E, _D, L) when is_integer(E) -> L; sparse_to_list_2(E, D, L) -> sparse_push_tuple(?LEAFSIZE, D, E, L). sparse_to_list_3(0, _D, L, _E) -> L; sparse_to_list_3(N, D, L, E) -> sparse_to_list_3(N-1, D, sparse_to_list_2(element(N, E), D, L), E). sparse_push_tuple(0, _D, _T, L) -> L; sparse_push_tuple(N, D, T, L) -> case element(N, T) of D -> sparse_push_tuple(N - 1, D, T, L); E -> sparse_push_tuple(N - 1, D, T, [E | L]) end. -ifdef(EUNIT). sparse_to_list_test_() -> N0 = ?LEAFSIZE, [?_assert([] =:= sparse_to_list(new())), ?_assert([] =:= sparse_to_list(new(1))), ?_assert([] =:= sparse_to_list(new(1,{default,0}))), ?_assert([] =:= sparse_to_list(new(2))), ?_assert([] =:= sparse_to_list(new(2,{default,0}))), ?_assert([] =:= sparse_to_list(new(N0,{default,0}))), ?_assert([] =:= sparse_to_list(new(N0+1,{default,1}))), ?_assert([] =:= sparse_to_list(new(N0+2,{default,2}))), ?_assert([] =:= sparse_to_list(new(666,{default,6}))), ?_assert([1,2,3] =:= sparse_to_list(set(2,3,set(1,2,set(0,1,new()))))), ?_assert([3,2,1] =:= sparse_to_list(set(0,3,set(1,2,set(2,1,new()))))), ?_assert([0,1] =:= sparse_to_list(set(N0-1,1,set(0,0,new())))), ?_assert([0,1] =:= sparse_to_list(set(N0,1,set(0,0,new())))), ?_assert([0,1] =:= sparse_to_list(set(N0+1,1,set(0,0,new())))), ?_assert([0,1,2] =:= sparse_to_list(set(N0*10+1,2,set(N0*2+1,1,set(0,0,new()))))), ?_assertError(badarg, sparse_to_list(no_array)) ]. -endif. ( list ( ) ) - > array ( ) %% @equiv from_list(List, undefined) -spec from_list(list()) -> array(). from_list(List) -> from_list(List, undefined). ( list ( ) , term ( ) ) - > array ( ) %% @doc Convert a list to an extendible array. `Default' is used as the value %% for uninitialized entries of the array. If `List' is not a proper list, %% the call fails with reason `badarg'. %% @see %% @see to_list/1 -spec from_list(list(), term()) -> array(). from_list([], Default) -> new({default,Default}); from_list(List, Default) when is_list(List) -> {E, N, M} = from_list_1(?LEAFSIZE, List, Default, 0, [], []), #array{size = N, max = M, default = Default, elements = E}; from_list(_, _) -> erlang:error(badarg). Note : A cleaner but slower algorithm is to first take the length of %% the list and compute the max size of the final tree, and then %% decompose the list. The below algorithm is almost twice as fast, %% however. %% Building the leaf nodes (padding the last one as necessary) and %% counting the total number of elements. from_list_1(0, Xs, D, N, As, Es) -> E = list_to_tuple(lists:reverse(As)), case Xs of [] -> case Es of [] -> {E, N, ?LEAFSIZE}; _ -> from_list_2_0(N, [E | Es], ?LEAFSIZE) end; [_|_] -> from_list_1(?LEAFSIZE, Xs, D, N, [], [E | Es]); _ -> erlang:error(badarg) end; from_list_1(I, Xs, D, N, As, Es) -> case Xs of [X | Xs1] -> from_list_1(I-1, Xs1, D, N+1, [X | As], Es); _ -> from_list_1(I-1, Xs, D, N, [D | As], Es) end. %% Building the internal nodes (note that the input is reversed). from_list_2_0(N, Es, S) -> from_list_2(?NODESIZE, pad((N-1) div S + 1, ?NODESIZE, S, Es), S, N, [S], []). from_list_2(0, Xs, S, N, As, Es) -> E = list_to_tuple(As), case Xs of [] -> case Es of [] -> {E, N, ?extend(S)}; _ -> from_list_2_0(N, lists:reverse([E | Es]), ?extend(S)) end; _ -> from_list_2(?NODESIZE, Xs, S, N, [S], [E | Es]) end; from_list_2(I, [X | Xs], S, N, As, Es) -> from_list_2(I-1, Xs, S, N, [X | As], Es). %% left-padding a list Es with elements P to the nearest multiple of K elements from N ( adding 0 to K-1 elements ) . pad(N, K, P, Es) -> push((K - (N rem K)) rem K, P, Es). -ifdef(EUNIT). from_list_test_() -> N0 = ?LEAFSIZE, N1 = ?NODESIZE*N0, N2 = ?NODESIZE*N1, N3 = ?NODESIZE*N2, N4 = ?NODESIZE*N3, [?_assert(array:size(from_list([])) =:= 0), ?_assert(array:is_fix(from_list([])) =:= false), ?_assert(array:size(from_list([undefined])) =:= 1), ?_assert(array:is_fix(from_list([undefined])) =:= false), ?_assert(array:size(from_list(lists:seq(1,N1))) =:= N1), ?_assert(to_list(from_list(lists:seq(1,N0))) =:= lists:seq(1,N0)), ?_assert(to_list(from_list(lists:seq(1,N0+1))) =:= lists:seq(1,N0+1)), ?_assert(to_list(from_list(lists:seq(1,N0+2))) =:= lists:seq(1,N0+2)), ?_assert(to_list(from_list(lists:seq(1,N2))) =:= lists:seq(1,N2)), ?_assert(to_list(from_list(lists:seq(1,N2+1))) =:= lists:seq(1,N2+1)), ?_assert(to_list(from_list(lists:seq(0,N3))) =:= lists:seq(0,N3)), ?_assert(to_list(from_list(lists:seq(0,N4))) =:= lists:seq(0,N4)), ?_assertError(badarg, from_list([a,b,a,c|d])), ?_assertError(badarg, from_list(no_array)) ]. -endif. ( array ( ) ) - > [ { Index::integer ( ) , Value::term ( ) } ] %% @doc Convert the array to an ordered list of pairs `{Index, Value}'. %% @see from_orddict/2 %% @see sparse_to_orddict/1 -spec to_orddict(array()) -> indx_pairs(). to_orddict(#array{size = 0}) -> []; to_orddict(#array{size = N, elements = E, default = D}) -> I = N - 1, to_orddict_1(E, I, D, I); to_orddict(_) -> erlang:error(badarg). %% see to_list/1 for comparison to_orddict_1(E=?NODEPATTERN(S), R, D, I) -> N = I div S, I1 = I rem S, to_orddict_3(N, R - I1 - 1, D, to_orddict_1(element(N+1, E), R, D, I1), E, S); to_orddict_1(E, R, D, I) when is_integer(E) -> push_pairs(I+1, R, D, []); to_orddict_1(E, R, _D, I) -> push_tuple_pairs(I+1, R, E, []). to_orddict_2(E=?NODEPATTERN(S), R, D, L) -> to_orddict_3(?NODESIZE, R, D, L, E, S); to_orddict_2(E, R, D, L) when is_integer(E) -> push_pairs(E, R, D, L); to_orddict_2(E, R, _D, L) -> push_tuple_pairs(?LEAFSIZE, R, E, L). to_orddict_3(0, _R, _D, L, _E, _S) -> %% when is_integer(R) -> L; to_orddict_3(N, R, D, L, E, S) -> to_orddict_3(N-1, R - S, D, to_orddict_2(element(N, E), R, D, L), E, S). -spec push_pairs(non_neg_integer(), array_indx(), term(), indx_pairs()) -> indx_pairs(). push_pairs(0, _I, _E, L) -> L; push_pairs(N, I, E, L) -> push_pairs(N-1, I-1, E, [{I, E} | L]). -spec push_tuple_pairs(non_neg_integer(), array_indx(), term(), indx_pairs()) -> indx_pairs(). push_tuple_pairs(0, _I, _T, L) -> L; push_tuple_pairs(N, I, T, L) -> push_tuple_pairs(N-1, I-1, T, [{I, element(N, T)} | L]). -ifdef(EUNIT). to_orddict_test_() -> N0 = ?LEAFSIZE, [?_assert([] =:= to_orddict(new())), ?_assert([{0,undefined}] =:= to_orddict(new(1))), ?_assert([{0,undefined},{1,undefined}] =:= to_orddict(new(2))), ?_assert([{N,0}||N<-lists:seq(0,N0-1)] =:= to_orddict(new(N0,{default,0}))), ?_assert([{N,1}||N<-lists:seq(0,N0)] =:= to_orddict(new(N0+1,{default,1}))), ?_assert([{N,2}||N<-lists:seq(0,N0+1)] =:= to_orddict(new(N0+2,{default,2}))), ?_assert([{N,6}||N<-lists:seq(0,665)] =:= to_orddict(new(666,{default,6}))), ?_assert([{0,1},{1,2},{2,3}] =:= to_orddict(set(2,3,set(1,2,set(0,1,new()))))), ?_assert([{0,3},{1,2},{2,1}] =:= to_orddict(set(0,3,set(1,2,set(2,1,new()))))), ?_assert([{0,1}|[{N,0}||N<-lists:seq(1,N0-2)]++[{N0-1,1}]] =:= to_orddict(set(N0-1,1,set(0,1,new({default,0}))))), ?_assert([{0,1}|[{N,0}||N<-lists:seq(1,N0-1)]++[{N0,1}]] =:= to_orddict(set(N0,1,set(0,1,new({default,0}))))), ?_assert([{0,1}|[{N,0}||N<-lists:seq(1,N0)]++[{N0+1,1}]] =:= to_orddict(set(N0+1,1,set(0,1,new({default,0}))))), ?_assert([{0,0} | [{N,undefined}||N<-lists:seq(1,N0*2)]] ++ [{N0*2+1,1} | [{N,undefined}||N<-lists:seq(N0*2+2,N0*10)]] ++ [{N0*10+1,2}] =:= to_orddict(set(N0*10+1,2,set(N0*2+1,1,set(0,0,new()))))), ?_assertError(badarg, to_orddict(no_array)) ]. -endif. ( array ( ) ) - > [ { Index::integer ( ) , Value::term ( ) } ] %% @doc Convert the array to an ordered list of pairs `{Index, Value}', %% skipping default-valued entries. %% @see -spec sparse_to_orddict(array()) -> indx_pairs(). sparse_to_orddict(#array{size = 0}) -> []; sparse_to_orddict(#array{size = N, elements = E, default = D}) -> I = N - 1, sparse_to_orddict_1(E, I, D, I); sparse_to_orddict(_) -> erlang:error(badarg). see for details sparse_to_orddict_1(E=?NODEPATTERN(S), R, D, I) -> N = I div S, I1 = I rem S, sparse_to_orddict_3(N, R - I1 - 1, D, sparse_to_orddict_1(element(N+1, E), R, D, I1), E, S); sparse_to_orddict_1(E, _R, _D, _I) when is_integer(E) -> []; sparse_to_orddict_1(E, R, D, I) -> sparse_push_tuple_pairs(I+1, R, D, E, []). sparse_to_orddict_2(E=?NODEPATTERN(S), R, D, L) -> sparse_to_orddict_3(?NODESIZE, R, D, L, E, S); sparse_to_orddict_2(E, _R, _D, L) when is_integer(E) -> L; sparse_to_orddict_2(E, R, D, L) -> sparse_push_tuple_pairs(?LEAFSIZE, R, D, E, L). sparse_to_orddict_3(0, _R, _D, L, _E, _S) -> % when is_integer(R) -> L; sparse_to_orddict_3(N, R, D, L, E, S) -> sparse_to_orddict_3(N-1, R - S, D, sparse_to_orddict_2(element(N, E), R, D, L), E, S). -spec sparse_push_tuple_pairs(non_neg_integer(), array_indx(), _, _, indx_pairs()) -> indx_pairs(). sparse_push_tuple_pairs(0, _I, _D, _T, L) -> L; sparse_push_tuple_pairs(N, I, D, T, L) -> case element(N, T) of D -> sparse_push_tuple_pairs(N-1, I-1, D, T, L); E -> sparse_push_tuple_pairs(N-1, I-1, D, T, [{I, E} | L]) end. -ifdef(EUNIT). sparse_to_orddict_test_() -> N0 = ?LEAFSIZE, [?_assert([] =:= sparse_to_orddict(new())), ?_assert([] =:= sparse_to_orddict(new(1))), ?_assert([] =:= sparse_to_orddict(new(1,{default,0}))), ?_assert([] =:= sparse_to_orddict(new(2))), ?_assert([] =:= sparse_to_orddict(new(2,{default,0}))), ?_assert([] =:= sparse_to_orddict(new(N0,{default,0}))), ?_assert([] =:= sparse_to_orddict(new(N0+1,{default,1}))), ?_assert([] =:= sparse_to_orddict(new(N0+2,{default,2}))), ?_assert([] =:= sparse_to_orddict(new(666,{default,6}))), ?_assert([{0,1},{1,2},{2,3}] =:= sparse_to_orddict(set(2,3,set(1,2,set(0,1,new()))))), ?_assert([{0,3},{1,2},{2,1}] =:= sparse_to_orddict(set(0,3,set(1,2,set(2,1,new()))))), ?_assert([{0,1},{N0-1,1}] =:= sparse_to_orddict(set(N0-1,1,set(0,1,new({default,0}))))), ?_assert([{0,1},{N0,1}] =:= sparse_to_orddict(set(N0,1,set(0,1,new({default,0}))))), ?_assert([{0,1},{N0+1,1}] =:= sparse_to_orddict(set(N0+1,1,set(0,1,new({default,0}))))), ?_assert([{0,0},{N0*2+1,1},{N0*10+1,2}] =:= sparse_to_orddict(set(N0*10+1,2,set(N0*2+1,1,set(0,0,new()))))), ?_assertError(badarg, sparse_to_orddict(no_array)) ]. -endif. ( list ( ) ) - > array ( ) %% @equiv from_orddict(Orddict, undefined) -spec from_orddict(indx_pairs()) -> array(). from_orddict(Orddict) -> from_orddict(Orddict, undefined). ( list ( ) , term ( ) ) - > array ( ) %% @doc Convert an ordered list of pairs `{Index, Value}' to a %% corresponding extendible array. `Default' is used as the value for %% uninitialized entries of the array. If `List' is not a proper, ordered list of pairs whose first elements are nonnegative %% integers, the call fails with reason `badarg'. %% @see @see -spec from_orddict(indx_pairs(), term()) -> array(). from_orddict([], Default) -> new({default,Default}); from_orddict(List, Default) when is_list(List) -> {E, N, M} = from_orddict_0(List, 0, ?LEAFSIZE, Default, []), #array{size = N, max = M, default = Default, elements = E}; from_orddict(_, _) -> erlang:error(badarg). 2 pass implementation , first pass builds the needed leaf nodes %% and adds hole sizes. %% (inserts default elements for missing list entries in the leafs %% and pads the last tuple if necessary). Second pass builds the tree from the leafs and the holes . %% %% Doesn't build/expand unnecessary leaf nodes which costs memory %% and time for sparse arrays. from_orddict_0([], N, _Max, _D, Es) -> %% Finished, build the resulting tree case Es of [E] -> {E, N, ?LEAFSIZE}; _ -> collect_leafs(N, Es, ?LEAFSIZE) end; from_orddict_0(Xs=[{Ix1, _}|_], Ix, Max0, D, Es0) when Ix1 > Max0, is_integer(Ix1) -> %% We have a hole larger than a leaf Hole = Ix1-Ix, Step = Hole - (Hole rem ?LEAFSIZE), Next = Ix+Step, from_orddict_0(Xs, Next, Next+?LEAFSIZE, D, [Step|Es0]); from_orddict_0(Xs0=[{_, _}|_], Ix0, Max, D, Es) -> %% Fill a leaf {Xs,E,Ix} = from_orddict_1(Ix0, Max, Xs0, Ix0, D, []), from_orddict_0(Xs, Ix, Ix+?LEAFSIZE, D, [E|Es]); from_orddict_0(Xs, _, _, _,_) -> erlang:error({badarg, Xs}). from_orddict_1(Ix, Ix, Xs, N, _D, As) -> %% Leaf is full E = list_to_tuple(lists:reverse(As)), {Xs, E, N}; from_orddict_1(Ix, Max, Xs, N0, D, As) -> case Xs of [{Ix, Val} | Xs1] -> N = Ix+1, from_orddict_1(N, Max, Xs1, N, D, [Val | As]); [{Ix1, _} | _] when is_integer(Ix1), Ix1 > Ix -> N = Ix+1, from_orddict_1(N, Max, Xs, N, D, [D | As]); [_ | _] -> erlang:error({badarg, Xs}); _ -> from_orddict_1(Ix+1, Max, Xs, N0, D, [D | As]) end. %% Es is reversed i.e. starting from the largest leafs collect_leafs(N, Es, S) -> I = (N-1) div S + 1, Pad = ((?NODESIZE - (I rem ?NODESIZE)) rem ?NODESIZE) * S, case Pad of 0 -> collect_leafs(?NODESIZE, Es, S, N, [S], []); _ -> %% Pad the end collect_leafs(?NODESIZE, [Pad|Es], S, N, [S], []) end. collect_leafs(0, Xs, S, N, As, Es) -> E = list_to_tuple(As), case Xs of [] -> case Es of [] -> {E, N, ?extend(S)}; _ -> collect_leafs(N, lists:reverse([E | Es]), ?extend(S)) end; _ -> collect_leafs(?NODESIZE, Xs, S, N, [S], [E | Es]) end; collect_leafs(I, [X | Xs], S, N, As0, Es0) when is_integer(X) -> %% A hole, pad accordingly. Step0 = (X div S), if Step0 < I -> As = push(Step0, S, As0), collect_leafs(I-Step0, Xs, S, N, As, Es0); I =:= ?NODESIZE -> Step = Step0 rem ?NODESIZE, As = push(Step, S, As0), collect_leafs(I-Step, Xs, S, N, As, [X|Es0]); I =:= Step0 -> As = push(I, S, As0), collect_leafs(0, Xs, S, N, As, Es0); true -> As = push(I, S, As0), Step = Step0 - I, collect_leafs(0, [Step*S|Xs], S, N, As, Es0) end; collect_leafs(I, [X | Xs], S, N, As, Es) -> collect_leafs(I-1, Xs, S, N, [X | As], Es); collect_leafs(?NODESIZE, [], S, N, [_], Es) -> collect_leafs(N, lists:reverse(Es), ?extend(S)). -ifdef(EUNIT). from_orddict_test_() -> N0 = ?LEAFSIZE, N1 = ?NODESIZE*N0, N2 = ?NODESIZE*N1, N3 = ?NODESIZE*N2, N4 = ?NODESIZE*N3, [?_assert(array:size(from_orddict([])) =:= 0), ?_assert(array:is_fix(from_orddict([])) =:= false), ?_assert(array:size(from_orddict([{0,undefined}])) =:= 1), ?_assert(array:is_fix(from_orddict([{0,undefined}])) =:= false), ?_assert(array:size(from_orddict([{N0-1,undefined}])) =:= N0), ?_assert(array:size(from_orddict([{N,0}||N<-lists:seq(0,N1-1)])) =:= N1), ?_assertError({badarg,_}, from_orddict([foo])), ?_assertError({badarg,_}, from_orddict([{200,foo},{1,bar}])), ?_assertError({badarg,_}, from_orddict([{N,0}||N<-lists:seq(0,N0-1)] ++ not_a_list)), ?_assertError(badarg, from_orddict(no_array)), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N0-1)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N0)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N2-1)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N2)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N3-1)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N4-1)], L =:= to_orddict(from_orddict(L)))), %% Hole in the begining ?_assert(?LET(L, [{0,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N0,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N3,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N4,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N0-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N1-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N3-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N4-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), %% Hole in middle ?_assert(?LET(L, [{0,0},{N0,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N3,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N4,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N0-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N1-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N3-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N4-1,0}], L =:= sparse_to_orddict(from_orddict(L)))) ]. -endif. %% @spec (Function, array()) -> array() Function = ( Index::integer ( ) , Value::term ( ) ) - > term ( ) %% @doc Map the given function onto each element of the array. The %% elements are visited in order from the lowest index to the highest. %% If `Function' is not a function, the call fails with reason `badarg'. %% %% @see foldl/3 %% @see foldr/3 @see sparse_map/2 -spec map(fun((array_indx(), _) -> _), array()) -> array(). map(Function, Array=#array{size = N, elements = E, default = D}) when is_function(Function, 2) -> if N > 0 -> kill reference , for GC A#array{elements = map_1(N-1, E, 0, Function, D)}; true -> Array end; map(_, _) -> erlang:error(badarg). %% It might be simpler to traverse the array right-to-left, as done e.g. in the function , but it is better to guarantee %% left-to-right application over the elements - that is more likely to %% be a generally useful property. map_1(N, E=?NODEPATTERN(S), Ix, F, D) -> list_to_tuple(lists:reverse([S | map_2(1, E, Ix, F, D, [], N div S + 1, N rem S, S)])); map_1(N, E, Ix, F, D) when is_integer(E) -> map_1(N, unfold(E, D), Ix, F, D); map_1(N, E, Ix, F, D) -> list_to_tuple(lists:reverse(map_3(1, E, Ix, F, D, N+1, []))). map_2(I, E, Ix, F, D, L, I, R, _S) -> map_2_1(I+1, E, [map_1(R, element(I, E), Ix, F, D) | L]); map_2(I, E, Ix, F, D, L, N, R, S) -> map_2(I+1, E, Ix + S, F, D, [map_1(S-1, element(I, E), Ix, F, D) | L], N, R, S). map_2_1(I, E, L) when I =< ?NODESIZE -> map_2_1(I+1, E, [element(I, E) | L]); map_2_1(_I, _E, L) -> L. -spec map_3(pos_integer(), _, array_indx(), fun((array_indx(),_) -> _), _, non_neg_integer(), [X]) -> [X]. map_3(I, E, Ix, F, D, N, L) when I =< N -> map_3(I+1, E, Ix+1, F, D, N, [F(Ix, element(I, E)) | L]); map_3(I, E, Ix, F, D, N, L) when I =< ?LEAFSIZE -> map_3(I+1, E, Ix+1, F, D, N, [D | L]); map_3(_I, _E, _Ix, _F, _D, _N, L) -> L. unfold(S, _D) when S > ?LEAFSIZE -> ?NEW_NODE(?reduce(S)); unfold(_S, D) -> ?NEW_LEAF(D). -ifdef(EUNIT). map_test_() -> N0 = ?LEAFSIZE, Id = fun (_,X) -> X end, Plus = fun(N) -> fun (_,X) -> X+N end end, Default = fun(_K,undefined) -> no_value; (K,V) -> K+V end, [?_assertError(badarg, map([], new())), ?_assertError(badarg, map([], new(10))), ?_assert(to_list(map(Id, new())) =:= []), ?_assert(to_list(map(Id, new(1))) =:= [undefined]), ?_assert(to_list(map(Id, new(5,{default,0}))) =:= [0,0,0,0,0]), ?_assert(to_list(map(Id, from_list([1,2,3,4]))) =:= [1,2,3,4]), ?_assert(to_list(map(Plus(1), from_list([0,1,2,3]))) =:= [1,2,3,4]), ?_assert(to_list(map(Plus(-1), from_list(lists:seq(1,11)))) =:= lists:seq(0,10)), ?_assert(to_list(map(Plus(11), from_list(lists:seq(0,99999)))) =:= lists:seq(11,100010)), ?_assert([{0,0},{N0*2+1,N0*2+1+1},{N0*100+1,N0*100+1+2}] =:= sparse_to_orddict((map(Default, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new())))))#array{default = no_value})) ]. -endif. %% @spec (Function, array()) -> array() Function = ( Index::integer ( ) , Value::term ( ) ) - > term ( ) %% @doc Map the given function onto each element of the array, skipping %% default-valued entries. The elements are visited in order from the %% lowest index to the highest. If `Function' is not a function, the %% call fails with reason `badarg'. %% @see map/2 -spec sparse_map(fun((array_indx(), _) -> _), array()) -> array(). sparse_map(Function, Array=#array{size = N, elements = E, default = D}) when is_function(Function, 2) -> if N > 0 -> kill reference , for GC A#array{elements = sparse_map_1(N-1, E, 0, Function, D)}; true -> Array end; sparse_map(_, _) -> erlang:error(badarg). see map/2 for details %% TODO: we can probably optimize away the use of div/rem here sparse_map_1(N, E=?NODEPATTERN(S), Ix, F, D) -> list_to_tuple(lists:reverse([S | sparse_map_2(1, E, Ix, F, D, [], N div S + 1, N rem S, S)])); sparse_map_1(_N, E, _Ix, _F, _D) when is_integer(E) -> E; sparse_map_1(_N, E, Ix, F, D) -> list_to_tuple(lists:reverse(sparse_map_3(1, E, Ix, F, D, []))). sparse_map_2(I, E, Ix, F, D, L, I, R, _S) -> sparse_map_2_1(I+1, E, [sparse_map_1(R, element(I, E), Ix, F, D) | L]); sparse_map_2(I, E, Ix, F, D, L, N, R, S) -> sparse_map_2(I+1, E, Ix + S, F, D, [sparse_map_1(S-1, element(I, E), Ix, F, D) | L], N, R, S). sparse_map_2_1(I, E, L) when I =< ?NODESIZE -> sparse_map_2_1(I+1, E, [element(I, E) | L]); sparse_map_2_1(_I, _E, L) -> L. -spec sparse_map_3(pos_integer(), _, array_indx(), fun((array_indx(),_) -> _), _, [X]) -> [X]. sparse_map_3(I, T, Ix, F, D, L) when I =< ?LEAFSIZE -> case element(I, T) of D -> sparse_map_3(I+1, T, Ix+1, F, D, [D | L]); E -> sparse_map_3(I+1, T, Ix+1, F, D, [F(Ix, E) | L]) end; sparse_map_3(_I, _E, _Ix, _F, _D, L) -> L. -ifdef(EUNIT). sparse_map_test_() -> N0 = ?LEAFSIZE, Id = fun (_,X) -> X end, Plus = fun(N) -> fun (_,X) -> X+N end end, KeyPlus = fun (K,X) -> K+X end, [?_assertError(badarg, sparse_map([], new())), ?_assertError(badarg, sparse_map([], new(10))), ?_assert(to_list(sparse_map(Id, new())) =:= []), ?_assert(to_list(sparse_map(Id, new(1))) =:= [undefined]), ?_assert(to_list(sparse_map(Id, new(5,{default,0}))) =:= [0,0,0,0,0]), ?_assert(to_list(sparse_map(Id, from_list([1,2,3,4]))) =:= [1,2,3,4]), ?_assert(to_list(sparse_map(Plus(1), from_list([0,1,2,3]))) =:= [1,2,3,4]), ?_assert(to_list(sparse_map(Plus(-1), from_list(lists:seq(1,11)))) =:= lists:seq(0,10)), ?_assert(to_list(sparse_map(Plus(11), from_list(lists:seq(0,99999)))) =:= lists:seq(11,100010)), ?_assert(to_list(sparse_map(Plus(1), set(1,1,new({default,0})))) =:= [0,2]), ?_assert(to_list(sparse_map(Plus(1), set(3,4,set(0,1,new({default,0}))))) =:= [2,0,0,5]), ?_assert(to_list(sparse_map(Plus(1), set(9,9,set(1,1,new({default,0}))))) =:= [0,2,0,0,0,0,0,0,0,10]), ?_assert([{0,0},{N0*2+1,N0*2+1+1},{N0*100+1,N0*100+1+2}] =:= sparse_to_orddict(sparse_map(KeyPlus, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new())))))) ]. -endif. %% @spec (Function, InitialAcc::term(), array()) -> term() Function = ( Index::integer ( ) , Value::term ( ) , Acc::term ( ) ) - > %% term() @doc Fold the elements of the array using the given function and %% initial accumulator value. The elements are visited in order from the %% lowest index to the highest. If `Function' is not a function, the %% call fails with reason `badarg'. %% %% @see foldr/3 @see map/2 @see sparse_foldl/3 -spec foldl(fun((array_indx(), _, A) -> B), A, array()) -> B. foldl(Function, A, #array{size = N, elements = E, default = D}) when is_function(Function, 3) -> if N > 0 -> foldl_1(N-1, E, A, 0, Function, D); true -> A end; foldl(_, _, _) -> erlang:error(badarg). foldl_1(N, E=?NODEPATTERN(S), A, Ix, F, D) -> foldl_2(1, E, A, Ix, F, D, N div S + 1, N rem S, S); foldl_1(N, E, A, Ix, F, D) when is_integer(E) -> foldl_1(N, unfold(E, D), A, Ix, F, D); foldl_1(N, E, A, Ix, F, _D) -> foldl_3(1, E, A, Ix, F, N+1). foldl_2(I, E, A, Ix, F, D, I, R, _S) -> foldl_1(R, element(I, E), A, Ix, F, D); foldl_2(I, E, A, Ix, F, D, N, R, S) -> foldl_2(I+1, E, foldl_1(S-1, element(I, E), A, Ix, F, D), Ix + S, F, D, N, R, S). -spec foldl_3(pos_integer(), _, A, array_indx(), fun((array_indx, _, A) -> B), integer()) -> B. foldl_3(I, E, A, Ix, F, N) when I =< N -> foldl_3(I+1, E, F(Ix, element(I, E), A), Ix+1, F, N); foldl_3(_I, _E, A, _Ix, _F, _N) -> A. -ifdef(EUNIT). foldl_test_() -> N0 = ?LEAFSIZE, Count = fun (_,_,N) -> N+1 end, Sum = fun (_,X,N) -> N+X end, Reverse = fun (_,X,L) -> [X|L] end, Vals = fun(_K,undefined,{C,L}) -> {C+1,L}; (K,X,{C,L}) -> {C,[K+X|L]} end, [?_assertError(badarg, foldl([], 0, new())), ?_assertError(badarg, foldl([], 0, new(10))), ?_assert(foldl(Count, 0, new()) =:= 0), ?_assert(foldl(Count, 0, new(1)) =:= 1), ?_assert(foldl(Count, 0, new(10)) =:= 10), ?_assert(foldl(Count, 0, from_list([1,2,3,4])) =:= 4), ?_assert(foldl(Count, 10, from_list([0,1,2,3,4,5,6,7,8,9])) =:= 20), ?_assert(foldl(Count, 1000, from_list(lists:seq(0,999))) =:= 2000), ?_assert(foldl(Sum, 0, from_list(lists:seq(0,10))) =:= 55), ?_assert(foldl(Reverse, [], from_list(lists:seq(0,1000))) =:= lists:reverse(lists:seq(0,1000))), ?_assert({999,[N0*100+1+2,N0*2+1+1,0]} =:= foldl(Vals, {0,[]}, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new()))))) ]. -endif. %% @spec (Function, InitialAcc::term(), array()) -> term() Function = ( Index::integer ( ) , Value::term ( ) , Acc::term ( ) ) - > %% term() @doc Fold the elements of the array using the given function and %% initial accumulator value, skipping default-valued entries. The %% elements are visited in order from the lowest index to the highest. %% If `Function' is not a function, the call fails with reason `badarg'. %% %% @see foldl/3 %% @see sparse_foldr/3 -spec sparse_foldl(fun((array_indx(), _, A) -> B), A, array()) -> B. sparse_foldl(Function, A, #array{size = N, elements = E, default = D}) when is_function(Function, 3) -> if N > 0 -> sparse_foldl_1(N-1, E, A, 0, Function, D); true -> A end; sparse_foldl(_, _, _) -> erlang:error(badarg). %% see foldl/3 for details %% TODO: this can be optimized sparse_foldl_1(N, E=?NODEPATTERN(S), A, Ix, F, D) -> sparse_foldl_2(1, E, A, Ix, F, D, N div S + 1, N rem S, S); sparse_foldl_1(_N, E, A, _Ix, _F, _D) when is_integer(E) -> A; sparse_foldl_1(N, E, A, Ix, F, D) -> sparse_foldl_3(1, E, A, Ix, F, D, N+1). sparse_foldl_2(I, E, A, Ix, F, D, I, R, _S) -> sparse_foldl_1(R, element(I, E), A, Ix, F, D); sparse_foldl_2(I, E, A, Ix, F, D, N, R, S) -> sparse_foldl_2(I+1, E, sparse_foldl_1(S-1, element(I, E), A, Ix, F, D), Ix + S, F, D, N, R, S). sparse_foldl_3(I, T, A, Ix, F, D, N) when I =< N -> case element(I, T) of D -> sparse_foldl_3(I+1, T, A, Ix+1, F, D, N); E -> sparse_foldl_3(I+1, T, F(Ix, E, A), Ix+1, F, D, N) end; sparse_foldl_3(_I, _T, A, _Ix, _F, _D, _N) -> A. -ifdef(EUNIT). sparse_foldl_test_() -> N0 = ?LEAFSIZE, Count = fun (_,_,N) -> N+1 end, Sum = fun (_,X,N) -> N+X end, Reverse = fun (_,X,L) -> [X|L] end, Vals = fun(_K,undefined,{C,L}) -> {C+1,L}; (K,X,{C,L}) -> {C,[K+X|L]} end, [?_assertError(badarg, sparse_foldl([], 0, new())), ?_assertError(badarg, sparse_foldl([], 0, new(10))), ?_assert(sparse_foldl(Count, 0, new()) =:= 0), ?_assert(sparse_foldl(Count, 0, new(1)) =:= 0), ?_assert(sparse_foldl(Count, 0, new(10,{default,1})) =:= 0), ?_assert(sparse_foldl(Count, 0, from_list([0,1,2,3,4],0)) =:= 4), ?_assert(sparse_foldl(Count, 0, from_list([0,1,2,3,4,5,6,7,8,9,0],0)) =:= 9), ?_assert(sparse_foldl(Count, 0, from_list(lists:seq(0,999),0)) =:= 999), ?_assert(sparse_foldl(Sum, 0, from_list(lists:seq(0,10), 5)) =:= 50), ?_assert(sparse_foldl(Reverse, [], from_list(lists:seq(0,1000), 0)) =:= lists:reverse(lists:seq(1,1000))), ?_assert({0,[N0*100+1+2,N0*2+1+1,0]} =:= sparse_foldl(Vals, {0,[]}, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new()))))) ]. -endif. %% @spec (Function, InitialAcc::term(), array()) -> term() Function = ( Index::integer ( ) , Value::term ( ) , Acc::term ( ) ) - > %% term() @doc Fold the elements of the array right - to - left using the given %% function and initial accumulator value. The elements are visited in %% order from the highest index to the lowest. If `Function' is not a %% function, the call fails with reason `badarg'. %% %% @see foldl/3 @see map/2 -spec foldr(fun((array_indx(), _, A) -> B), A, array()) -> B. foldr(Function, A, #array{size = N, elements = E, default = D}) when is_function(Function, 3) -> if N > 0 -> I = N - 1, foldr_1(I, E, I, A, Function, D); true -> A end; foldr(_, _, _) -> erlang:error(badarg). this is based on foldr_1(I, E=?NODEPATTERN(S), Ix, A, F, D) -> foldr_2(I div S + 1, E, Ix, A, F, D, I rem S, S-1); foldr_1(I, E, Ix, A, F, D) when is_integer(E) -> foldr_1(I, unfold(E, D), Ix, A, F, D); foldr_1(I, E, Ix, A, F, _D) -> I1 = I+1, foldr_3(I1, E, Ix-I1, A, F). foldr_2(0, _E, _Ix, A, _F, _D, _R, _R0) -> A; foldr_2(I, E, Ix, A, F, D, R, R0) -> foldr_2(I-1, E, Ix - R - 1, foldr_1(R, element(I, E), Ix, A, F, D), F, D, R0, R0). -spec foldr_3(array_indx(), term(), integer(), A, fun((array_indx(), _, A) -> B)) -> B. foldr_3(0, _E, _Ix, A, _F) -> A; foldr_3(I, E, Ix, A, F) -> foldr_3(I-1, E, Ix, F(Ix+I, element(I, E), A), F). -ifdef(EUNIT). foldr_test_() -> N0 = ?LEAFSIZE, Count = fun (_,_,N) -> N+1 end, Sum = fun (_,X,N) -> N+X end, List = fun (_,X,L) -> [X|L] end, Vals = fun(_K,undefined,{C,L}) -> {C+1,L}; (K,X,{C,L}) -> {C,[K+X|L]} end, [?_assertError(badarg, foldr([], 0, new())), ?_assertError(badarg, foldr([], 0, new(10))), ?_assert(foldr(Count, 0, new()) =:= 0), ?_assert(foldr(Count, 0, new(1)) =:= 1), ?_assert(foldr(Count, 0, new(10)) =:= 10), ?_assert(foldr(Count, 0, from_list([1,2,3,4])) =:= 4), ?_assert(foldr(Count, 10, from_list([0,1,2,3,4,5,6,7,8,9])) =:= 20), ?_assert(foldr(Count, 1000, from_list(lists:seq(0,999))) =:= 2000), ?_assert(foldr(Sum, 0, from_list(lists:seq(0,10))) =:= 55), ?_assert(foldr(List, [], from_list(lists:seq(0,1000))) =:= lists:seq(0,1000)), ?_assert({999,[0,N0*2+1+1,N0*100+1+2]} =:= foldr(Vals, {0,[]}, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new()))))) ]. -endif. %% @spec (Function, InitialAcc::term(), array()) -> term() Function = ( Index::integer ( ) , Value::term ( ) , Acc::term ( ) ) - > %% term() @doc Fold the elements of the array right - to - left using the given %% function and initial accumulator value, skipping default-valued %% entries. The elements are visited in order from the highest index to %% the lowest. If `Function' is not a function, the call fails with %% reason `badarg'. %% %% @see foldr/3 @see sparse_foldl/3 -spec sparse_foldr(fun((array_indx(), _, A) -> B), A, array()) -> B. sparse_foldr(Function, A, #array{size = N, elements = E, default = D}) when is_function(Function, 3) -> if N > 0 -> I = N - 1, sparse_foldr_1(I, E, I, A, Function, D); true -> A end; sparse_foldr(_, _, _) -> erlang:error(badarg). %% see foldr/3 for details %% TODO: this can be optimized sparse_foldr_1(I, E=?NODEPATTERN(S), Ix, A, F, D) -> sparse_foldr_2(I div S + 1, E, Ix, A, F, D, I rem S, S-1); sparse_foldr_1(_I, E, _Ix, A, _F, _D) when is_integer(E) -> A; sparse_foldr_1(I, E, Ix, A, F, D) -> I1 = I+1, sparse_foldr_3(I1, E, Ix-I1, A, F, D). sparse_foldr_2(0, _E, _Ix, A, _F, _D, _R, _R0) -> A; sparse_foldr_2(I, E, Ix, A, F, D, R, R0) -> sparse_foldr_2(I-1, E, Ix - R - 1, sparse_foldr_1(R, element(I, E), Ix, A, F, D), F, D, R0, R0). -spec sparse_foldr_3(array_indx(), _, array_indx(), A, fun((array_indx(), _, A) -> B), _) -> B. sparse_foldr_3(0, _T, _Ix, A, _F, _D) -> A; sparse_foldr_3(I, T, Ix, A, F, D) -> case element(I, T) of D -> sparse_foldr_3(I-1, T, Ix, A, F, D); E -> sparse_foldr_3(I-1, T, Ix, F(Ix+I, E, A), F, D) end. ( array ( ) ) - > integer ( ) %% @doc Get the number of entries in the array up until the last %% non-default valued entry. In other words, returns `I+1' if `I' is the last non - default valued entry in the array , or zero if no such entry %% exists. %% @see size/1 %% @see resize/1 -spec sparse_size(array()) -> non_neg_integer(). sparse_size(A) -> F = fun (I, _V, _A) -> throw({value, I}) end, try sparse_foldr(F, [], A) of [] -> 0 catch {value, I} -> I + 1 end. -ifdef(EUNIT). sparse_foldr_test_() -> N0 = ?LEAFSIZE, Count = fun (_,_,N) -> N+1 end, Sum = fun (_,X,N) -> N+X end, List = fun (_,X,L) -> [X|L] end, Vals = fun(_K,undefined,{C,L}) -> {C+1,L}; (K,X,{C,L}) -> {C,[K+X|L]} end, [?_assertError(badarg, sparse_foldr([], 0, new())), ?_assertError(badarg, sparse_foldr([], 0, new(10))), ?_assert(sparse_foldr(Count, 0, new()) =:= 0), ?_assert(sparse_foldr(Count, 0, new(1)) =:= 0), ?_assert(sparse_foldr(Count, 0, new(10,{default,1})) =:= 0), ?_assert(sparse_foldr(Count, 0, from_list([0,1,2,3,4],0)) =:= 4), ?_assert(sparse_foldr(Count, 0, from_list([0,1,2,3,4,5,6,7,8,9,0],0)) =:= 9), ?_assert(sparse_foldr(Count, 0, from_list(lists:seq(0,999),0)) =:= 999), ?_assert(sparse_foldr(Sum, 0, from_list(lists:seq(0,10),5)) =:= 50), ?_assert(sparse_foldr(List, [], from_list(lists:seq(0,1000),0)) =:= lists:seq(1,1000)), ?_assert(sparse_size(new()) =:= 0), ?_assert(sparse_size(new(8)) =:= 0), ?_assert(sparse_size(array:set(7, 0, new())) =:= 8), ?_assert(sparse_size(array:set(7, 0, new(10))) =:= 8), ?_assert(sparse_size(array:set(99, 0, new(10,{fixed,false}))) =:= 100), ?_assert(sparse_size(array:set(7, undefined, new())) =:= 0), ?_assert(sparse_size(array:from_list([1,2,3,undefined])) =:= 3), ?_assert(sparse_size(array:from_orddict([{3,0},{17,0},{99,undefined}])) =:= 18), ?_assert({0,[0,N0*2+1+1,N0*100+1+2]} =:= sparse_foldr(Vals, {0,[]}, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new()))))) ]. -endif.
null
https://raw.githubusercontent.com/simplegeo/erlang/15eda8de27ba73d176c7eeb3a70a64167f50e2c4/lib/stdlib/src/array.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% @version 1.0 @doc Functional, extendible arrays. Arrays can have fixed size, or can grow automatically as needed. A default value is used for entries that have not been explicitly set. Unless specified by the user when the array is created, the default value is the atom `undefined'. There is no difference between an unset entry and an entry which has been explicitly set to the same value as the default one (cf. {@link reset/2}). If you need to differentiate between unset and set entries, you must make sure that the default value cannot be confused with the values of set entries. The array never shrinks automatically; if an index `I' has been used successfully to set an entry, all indices in the range [0,`I'] will stay accessible unless the array size is explicitly changed by calling {@link resize/2}. Examples: ``` % Create a fixed - size array with entries 0 - 9 set to ' undefined ' A0 = array:new(10). % Create an extendible array and set entry 17 to ' true ' , %% causing the array to grow automatically A1 = array:set(17, true, array:new()). %% Read back a stored value true = array:get(17, A1). %% Accessing an unset entry returns the default value undefined = array:get(3, A1). %% Accessing an entry beyond the last set entry also returns the %% default value, if the array does not have fixed size undefined = array:get(18, A1). %% "sparse" functions ignore default-valued entries A2 = array:set(4, false, A1). %% An extendible array can be made fixed-size later A3 = array:fix(A2). %% A fixed-size array does not grow automatically and does not %% allow accesses beyond the last set entry {'EXIT',{badarg,_}} = (catch array:get(18, A3)). ''' @type array(). A functional, extendible array. The representation is not documented and is subject to change without notice. Note that arrays cannot be directly compared for equality. Developers: file, keep and update this file, test are extracted with array_SUITE:extract_tests(). The key to speed is to minimize the number of tests, on large input. Always make the most probable path as short as possible. In particular, keep in mind that for large trees, the probability of a leaf node is small relative to that of an internal node. If you try to tweak the set_1 and get_1 loops: Measure, look at the generated Beam code, and measure again! The argument order matters! Representation: A tree is either a leaf, with LEAFSIZE elements (the "base"), an represented by a single integer: the number of elements that may be stored in the tree when it is expanded. The last element of an internal node caches the number of elements that may be stored in each of its subtrees. total number of written words is (b+1)+(h-1)*(b+2), since tuples use number of words written, but causes higher trees, which takes time. The best compromise between speed and memory usage seems to lie around 8-10. Measurements indicate that the optimum base for speed is more memory . ) the "base" (no reason to have a different size) beware of argument duplication! These make the code a little easier to experiment with. It turned out that using shifts (when NODESIZE=2^n) was not faster. -------------------------------------------------------------------------- number of defined entries maximum number of entries in current tree the default value (usually 'undefined') the tuple tree A declaration equivalent to the following one is hard-coded in erl_types. That declaration contains hard-coded information about the #array{} structure and the types of its fields. So, please make sure that any changes to its structure are also propagated to erl_types.erl. -opaque array() :: #array{}. Types -------------------------------------------------------------------------- @equiv new([]) @spec (Options::term()) -> array() @doc Create a new array according to the given options. By default, start at 0. `Options' is a single term or a list of terms, selected from the following: <dl> <dt>`N::integer()' or `{size, N::integer()}'</dt> <dd>Specifies the initial size of the array; this also implies `{fixed, true}'. If `N' is not a nonnegative integer, the call fails with reason `badarg'.</dd> <dt>`fixed' or `{fixed, true}'</dt> <dt>`{fixed, false}'</dt> <dt>`{default, Value}'</dt> </dl> Options are processed in the order they occur in the list, i.e., later options have higher precedence. The default value is used as the value of uninitialized entries, and cannot be changed once the array has been created. Examples: ```array:new({default,0})''' creates an empty, extendible array whose default value is 0. ```array:new([{size,10},{fixed,false},{default,-1}])''' creates an @see from_list/2 @see fix/1 @doc Create a new array according to the given size and options. If `Size' is not a nonnegative integer, the call fails with reason `badarg'. By default, the array has fixed size. Note that any size specifications in `Options' will override the `Size' parameter. If `Options' is a list, this is simply equivalent to `new([{size, Size} | Options]', otherwise it is equivalent to `new([{size, Size} | [Options]]'. However, using this function directly is more efficient. Example: ```array:new(100, {default,0})''' creates a fixed-size array of size Constant empty array @doc Returns `true' if `X' appears to be an array, otherwise `false'. Note that the check is only shallow; there is no guarantee that `X' is a well-formed array representation even if this function returns `true'. @doc Get the number of entries in the array. Entries are numbered entry that is guaranteed to not have been previously set. @see sparse_size/1 @doc Get the value used for uninitialized entries. @doc Fix the size of the array. This prevents it from growing automatically upon insertion; see also {@link set/3}. @doc Check if the array has fixed size. Returns `true' if the array is fixed, otherwise `false'. @see fix/1 @doc Make the array resizable. (Reverses the effects of {@link fix/1}.) @see fix/1 @spec (integer(), array()) -> array() @doc Change the size of the array. If `Size' is not a nonnegative integer, the call fails with reason `badarg'. If the given array has fixed size, the resulting array will also have fixed size. TODO: shrink physical representation when shrinking the array @doc Change the size of the array to that reported by {@link sparse_size/1}. If the given array has fixed size, the resulting array will also have fixed size. @equiv resize(sparse_size(Array), Array) @see resize/2 @see sparse_size/1 @spec (integer(), term(), array()) -> array() @doc Set entry `I' of the array to `Value'. If `I' is not a nonnegative integer, or if the array has fixed size and `I' is larger than the maximum index, the call fails with reason `badarg'. If the array does not have fixed size, and `I' is greater than @see reset/2 (note that this cannot happen if M == 0, since N >= 0) Enlarging the array upwards to accommodate an index `I' Insert an element in an unexpanded node, expanding it as necessary. @spec (integer(), array()) -> term() @doc Get the value of entry `I'. If `I' is not a nonnegative integer, or if the array has fixed size and `I' is larger than the maximum index, the call fails with reason `badarg'. If the array does not have fixed size, this function will return the but it is the only way to get the maximum speed out of this loop @spec (integer(), array()) -> array() @doc Reset entry `I' to the default value for the array. If the value of entry `I' is the default value the array will be returned unchanged. Reset will never change size of the array. Shrinking can be done explicitly by calling {@link resize/2}. If `I' is not a nonnegative integer, or if the array has fixed size and `I' is larger than the maximum index, the call fails with reason `badarg'; cf. {@link set/3} TODO: a reset_range function @doc Converts the array to a list. @see from_list/2 @see sparse_to_list/1 this part handles the rightmost subtrees this part handles full trees only @doc Converts the array to a list, skipping default-valued entries. @see to_list/1 see to_list/1 for details @equiv from_list(List, undefined) @doc Convert a list to an extendible array. `Default' is used as the value for uninitialized entries of the array. If `List' is not a proper list, the call fails with reason `badarg'. @see to_list/1 the list and compute the max size of the final tree, and then decompose the list. The below algorithm is almost twice as fast, however. Building the leaf nodes (padding the last one as necessary) and counting the total number of elements. Building the internal nodes (note that the input is reversed). left-padding a list Es with elements P to the nearest multiple of K @doc Convert the array to an ordered list of pairs `{Index, Value}'. @see sparse_to_orddict/1 see to_list/1 for comparison when is_integer(R) -> @doc Convert the array to an ordered list of pairs `{Index, Value}', skipping default-valued entries. when is_integer(R) -> @equiv from_orddict(Orddict, undefined) @doc Convert an ordered list of pairs `{Index, Value}' to a corresponding extendible array. `Default' is used as the value for uninitialized entries of the array. If `List' is not a proper, integers, the call fails with reason `badarg'. and adds hole sizes. (inserts default elements for missing list entries in the leafs and pads the last tuple if necessary). Doesn't build/expand unnecessary leaf nodes which costs memory and time for sparse arrays. Finished, build the resulting tree We have a hole larger than a leaf Fill a leaf Leaf is full Es is reversed i.e. starting from the largest leafs Pad the end A hole, pad accordingly. Hole in the begining Hole in middle @spec (Function, array()) -> array() @doc Map the given function onto each element of the array. The elements are visited in order from the lowest index to the highest. If `Function' is not a function, the call fails with reason `badarg'. @see foldl/3 @see foldr/3 It might be simpler to traverse the array right-to-left, as done e.g. left-to-right application over the elements - that is more likely to be a generally useful property. @spec (Function, array()) -> array() @doc Map the given function onto each element of the array, skipping default-valued entries. The elements are visited in order from the lowest index to the highest. If `Function' is not a function, the call fails with reason `badarg'. TODO: we can probably optimize away the use of div/rem here @spec (Function, InitialAcc::term(), array()) -> term() term() initial accumulator value. The elements are visited in order from the lowest index to the highest. If `Function' is not a function, the call fails with reason `badarg'. @see foldr/3 @spec (Function, InitialAcc::term(), array()) -> term() term() initial accumulator value, skipping default-valued entries. The elements are visited in order from the lowest index to the highest. If `Function' is not a function, the call fails with reason `badarg'. @see foldl/3 @see sparse_foldr/3 see foldl/3 for details TODO: this can be optimized @spec (Function, InitialAcc::term(), array()) -> term() term() function and initial accumulator value. The elements are visited in order from the highest index to the lowest. If `Function' is not a function, the call fails with reason `badarg'. @see foldl/3 @spec (Function, InitialAcc::term(), array()) -> term() term() function and initial accumulator value, skipping default-valued entries. The elements are visited in order from the highest index to the lowest. If `Function' is not a function, the call fails with reason `badarg'. @see foldr/3 see foldr/3 for details TODO: this can be optimized @doc Get the number of entries in the array up until the last non-default valued entry. In other words, returns `I+1' if `I' is the exists. @see size/1 @see resize/1
Copyright Ericsson AB 2007 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " @author < > @author < > Arrays uses < b > > based indexing . This is a deliberate design choice and differs from other erlang datastructures , e.g. tuples . 10 = array : size(A0 ) . 18 = array : size(A1 ) . [ { 4 , false } , { 17 , true } ] = array : sparse_to_orddict(A2 ) . { ' EXIT',{badarg , _ } } = ( catch array : set(18 , true , A3 ) ) . -module(array). -export([new/0, new/1, new/2, is_array/1, set/3, get/2, size/1, sparse_size/1, default/1, reset/2, to_list/1, sparse_to_list/1, from_list/1, from_list/2, to_orddict/1, sparse_to_orddict/1, from_orddict/1, from_orddict/2, map/2, sparse_map/2, foldl/3, foldr/3, sparse_foldl/3, sparse_foldr/3, fix/1, relax/1, is_fix/1, resize/1, resize/2]). ) . -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. For OTP devs : Both tests and documentation is extracted from this Doc with docb_gen array.erl internal node with elements , or an unexpanded tree , Note that to update an entry in a tree of height h = log[b ] n , the a header word on the heap . 4 is the optimal base for minimizing the 24 - above that , it gets slower again due to the high memory usage . Base 10 is a good choice , giving 2/3 of the possible speedup from -define(DEFAULT, undefined). NODESIZE+1 elements ! setelement((?NODESIZE+1),erlang:make_tuple((?NODESIZE+1),(S)),(S))). -define(NEW_LEAF(D), erlang:make_tuple(?LEAFSIZE,(D))). -define(NODELEAFS, ?NODESIZE*?LEAFSIZE). -define(reduce(X), ((X) div (?NODESIZE))). -define(extend(X), ((X) * (?NODESIZE))). }). -type array_indx() :: non_neg_integer(). -type array_opt() :: 'fixed' | non_neg_integer() | {'default', term()} | {'fixed', boolean()} | {'size', non_neg_integer()}. -type array_opts() :: array_opt() | [array_opt()]. -type indx_pair() :: {array_indx(), term()}. -type indx_pairs() :: [indx_pair()]. ( ) - > array ( ) @doc Create a new , extendible array with initial size zero . @see new/1 @see -spec new() -> array(). new() -> new([]). the array is extendible and has initial size zero . Array indices < dd > Creates a fixed - size array ; see also { @link fix/1}.</dd > < dd > Creates an extendible ( non fixed - size ) array.</dd > < dd > Sets the default value for the array to ` Value'.</dd > ` ` ` array : new(100 ) '' ' creates a fixed - size array of size 100 . extendible array with initial size 10 whose default value is -1 . @see new/0 @see @see set/3 @see get/2 -spec new(array_opts()) -> array(). new(Options) -> new_0(Options, 0, false). ( Size::integer ( ) , Options::term ( ) ) - > array ( ) 100 , whose default value is 0 . @see new/1 -spec new(non_neg_integer(), array_opts()) -> array(). new(Size, Options) when is_integer(Size), Size >= 0 -> new_0(Options, Size, true); new(_, _) -> erlang:error(badarg). new_0(Options, Size, Fixed) when is_list(Options) -> new_1(Options, Size, Fixed, ?DEFAULT); new_0(Options, Size, Fixed) -> new_1([Options], Size, Fixed, ?DEFAULT). new_1([fixed | Options], Size, _, Default) -> new_1(Options, Size, true, Default); new_1([{fixed, Fixed} | Options], Size, _, Default) when is_boolean(Fixed) -> new_1(Options, Size, Fixed, Default); new_1([{default, Default} | Options], Size, Fixed, _) -> new_1(Options, Size, Fixed, Default); new_1([{size, Size} | Options], _, _, Default) when is_integer(Size), Size >= 0 -> new_1(Options, Size, true, Default); new_1([Size | Options], _, _, Default) when is_integer(Size), Size >= 0 -> new_1(Options, Size, true, Default); new_1([], Size, Fixed, Default) -> new(Size, Fixed, Default); new_1(_Options, _Size, _Fixed, _Default) -> erlang:error(badarg). new(0, false, undefined) -> #array{size=0, max=?LEAFSIZE, elements=?LEAFSIZE}; new(Size, Fixed, Default) -> E = find_max(Size - 1, ?LEAFSIZE), M = if Fixed -> 0; true -> E end, #array{size = Size, max = M, default = Default, elements = E}. -spec find_max(integer(), integer()) -> integer(). find_max(I, M) when I >= M -> find_max(I, ?extend(M)); find_max(_I, M) -> M. ( X::term ( ) ) - > boolean ( ) -spec is_array(term()) -> boolean(). is_array(#array{size = Size, max = Max}) when is_integer(Size), is_integer(Max) -> true; is_array(_) -> false. ( array ( ) ) - > integer ( ) from 0 to ` size(Array)-1 ' ; hence , this is also the index of the first @see set/3 -spec size(array()) -> non_neg_integer(). size(#array{size = N}) -> N; size(_) -> erlang:error(badarg). ( array ( ) ) - > term ( ) @see -spec default(array()) -> term(). default(#array{default = D}) -> D; default(_) -> erlang:error(badarg). -ifdef(EUNIT). new_test_() -> N0 = ?LEAFSIZE, N01 = N0+1, N1 = ?NODESIZE*N0, N11 = N1+1, N2 = ?NODESIZE*N1, [?_test(new()), ?_test(new([])), ?_test(new(10)), ?_test(new({size,10})), ?_test(new(fixed)), ?_test(new({fixed,true})), ?_test(new({fixed,false})), ?_test(new({default,undefined})), ?_test(new([{size,100},{fixed,false},{default,undefined}])), ?_test(new([100,fixed,{default,0}])), ?_assert(new() =:= new([])), ?_assert(new() =:= new([{size,0},{default,undefined},{fixed,false}])), ?_assert(new() =:= new(0, {fixed,false})), ?_assert(new(fixed) =:= new(0)), ?_assert(new(fixed) =:= new(0, [])), ?_assert(new(10) =:= new([{size,0},{size,5},{size,10}])), ?_assert(new(10) =:= new(0, {size,10})), ?_assert(new(10, []) =:= new(10, [{default,undefined},{fixed,true}])), ?_assertError(badarg, new(-1)), ?_assertError(badarg, new(10.0)), ?_assertError(badarg, new(undefined)), ?_assertError(badarg, new([undefined])), ?_assertError(badarg, new([{default,0} | fixed])), ?_assertError(badarg, new(-1, [])), ?_assertError(badarg, new(10.0, [])), ?_assertError(badarg, new(undefined, [])), ?_assertMatch(#array{size=0,max=N0,default=undefined,elements=N0}, new()), ?_assertMatch(#array{size=0,max=0,default=undefined,elements=N0}, new(fixed)), ?_assertMatch(#array{size=N0,max=N0,elements=N0}, new(N0, {fixed,false})), ?_assertMatch(#array{size=N01,max=N1,elements=N1}, new(N01, {fixed,false})), ?_assertMatch(#array{size=N1,max=N1,elements=N1}, new(N1, {fixed,false})), ?_assertMatch(#array{size=N11,max=N2,elements=N2}, new(N11, {fixed,false})), ?_assertMatch(#array{size=N2, max=N2, default=42,elements=N2}, new(N2, [{fixed,false},{default,42}])), ?_assert(0 =:= array:size(new())), ?_assert(17 =:= array:size(new(17))), ?_assert(100 =:= array:size(array:set(99,0,new()))), ?_assertError(badarg, array:size({bad_data,gives_error})), ?_assert(undefined =:= default(new())), ?_assert(4711 =:= default(new({default,4711}))), ?_assert(0 =:= default(new(10, {default,0}))), ?_assertError(badarg, default({bad_data,gives_error})), ?_assert(is_array(new())), ?_assert(false =:= is_array({foobar, 23, 23})), ?_assert(false =:= is_array(#array{size=bad})), ?_assert(false =:= is_array(#array{max=bad})), ?_assert(is_array(new(10))), ?_assert(is_array(new(10, {fixed,false}))) ]. -endif. ( array ( ) ) - > array ( ) @see relax/1 -spec fix(array()) -> array(). fix(#array{}=A) -> A#array{max = 0}. ( array ( ) ) - > boolean ( ) -spec is_fix(array()) -> boolean(). is_fix(#array{max = 0}) -> true; is_fix(#array{}) -> false. -ifdef(EUNIT). fix_test_() -> [?_assert(is_array(fix(new()))), ?_assert(fix(new()) =:= new(fixed)), ?_assertNot(is_fix(new())), ?_assertNot(is_fix(new([]))), ?_assertNot(is_fix(new({fixed,false}))), ?_assertNot(is_fix(new(10, {fixed,false}))), ?_assert(is_fix(new({fixed,true}))), ?_assert(is_fix(new(fixed))), ?_assert(is_fix(new(10))), ?_assert(is_fix(new(10, []))), ?_assert(is_fix(new(10, {fixed,true}))), ?_assert(is_fix(fix(new()))), ?_assert(is_fix(fix(new({fixed,false})))), ?_test(set(0, 17, new())), ?_assertError(badarg, set(0, 17, new(fixed))), ?_assertError(badarg, set(1, 42, fix(set(0, 17, new())))), ?_test(set(9, 17, new(10))), ?_assertError(badarg, set(10, 17, new(10))), ?_assertError(badarg, set(10, 17, fix(new(10, {fixed,false})))) ]. -endif. ( array ( ) ) - > array ( ) -spec relax(array()) -> array(). relax(#array{size = N}=A) -> A#array{max = find_max(N-1, ?LEAFSIZE)}. -ifdef(EUNIT). relax_test_() -> [?_assert(is_array(relax(new(fixed)))), ?_assertNot(is_fix(relax(fix(new())))), ?_assertNot(is_fix(relax(new(fixed)))), ?_assert(new() =:= relax(new(fixed))), ?_assert(new() =:= relax(new(0))), ?_assert(new(17, {fixed,false}) =:= relax(new(17))), ?_assert(new(100, {fixed,false}) =:= relax(fix(new(100, {fixed,false})))) ]. -endif. -spec resize(non_neg_integer(), array()) -> array(). resize(Size, #array{size = N, max = M, elements = E}=A) when is_integer(Size), Size >= 0 -> if Size > N -> {E1, M1} = grow(Size-1, E, if M > 0 -> M; true -> find_max(N-1, ?LEAFSIZE) end), A#array{size = Size, max = if M > 0 -> M1; true -> M end, elements = E1}; Size < N -> A#array{size = Size}; true -> A end; resize(_Size, _) -> erlang:error(badarg). ( array ( ) ) - > array ( ) -spec resize(array()) -> array(). resize(Array) -> resize(sparse_size(Array), Array). -ifdef(EUNIT). resize_test_() -> [?_assert(resize(0, new()) =:= new()), ?_assert(resize(99, new(99)) =:= new(99)), ?_assert(resize(99, relax(new(99))) =:= relax(new(99))), ?_assert(is_fix(resize(100, new(10)))), ?_assertNot(is_fix(resize(100, relax(new(10))))), ?_assert(array:size(resize(100, new())) =:= 100), ?_assert(array:size(resize(0, new(100))) =:= 0), ?_assert(array:size(resize(99, new(10))) =:= 99), ?_assert(array:size(resize(99, new(1000))) =:= 99), ?_assertError(badarg, set(99, 17, new(10))), ?_test(set(99, 17, resize(100, new(10)))), ?_assertError(badarg, set(100, 17, resize(100, new(10)))), ?_assert(array:size(resize(new())) =:= 0), ?_assert(array:size(resize(new(8))) =:= 0), ?_assert(array:size(resize(array:set(7, 0, new()))) =:= 8), ?_assert(array:size(resize(array:set(7, 0, new(10)))) =:= 8), ?_assert(array:size(resize(array:set(99, 0, new(10,{fixed,false})))) =:= 100), ?_assert(array:size(resize(array:set(7, undefined, new()))) =:= 0), ?_assert(array:size(resize(array:from_list([1,2,3,undefined]))) =:= 3), ?_assert(array:size( resize(array:from_orddict([{3,0},{17,0},{99,undefined}]))) =:= 18), ?_assertError(badarg, resize(foo, bad_argument)) ]. -endif. ` size(Array)-1 ' , the array will grow to size ` I+1 ' . @see get/2 -spec set(array_indx(), term(), array()) -> array(). set(I, Value, #array{size = N, max = M, default = D, elements = E}=A) when is_integer(I), I >= 0 -> if I < N -> A#array{elements = set_1(I, E, Value, D)}; I < M -> A#array{size = I+1, elements = set_1(I, E, Value, D)}; M > 0 -> {E1, M1} = grow(I, E, M), A#array{size = I+1, max = M1, elements = set_1(I, E1, Value, D)}; true -> erlang:error(badarg) end; set(_I, _V, _A) -> erlang:error(badarg). See get_1/3 for details about switching and the NODEPATTERN macro . set_1(I, E=?NODEPATTERN(S), X, D) -> I1 = I div S + 1, setelement(I1, E, set_1(I rem S, element(I1, E), X, D)); set_1(I, E, X, D) when is_integer(E) -> expand(I, E, X, D); set_1(I, E, X, _D) -> setelement(I+1, E, X). grow(I, E, _M) when is_integer(E) -> M1 = find_max(I, E), {M1, M1}; grow(I, E, M) -> grow_1(I, E, M). grow_1(I, E, M) when I >= M -> grow(I, setelement(1, ?NEW_NODE(M), E), ?extend(M)); grow_1(_I, E, M) -> {E, M}. expand(I, S, X, D) when S > ?LEAFSIZE -> S1 = ?reduce(S), setelement(I div S1 + 1, ?NEW_NODE(S1), expand(I rem S1, S1, X, D)); expand(I, _S, X, D) -> setelement(I+1, ?NEW_LEAF(D), X). default value for any index ` I ' greater than ` size(Array)-1 ' . @see set/3 -spec get(array_indx(), array()) -> term(). get(I, #array{size = N, max = M, elements = E, default = D}) when is_integer(I), I >= 0 -> if I < N -> get_1(I, E, D); M > 0 -> D; true -> erlang:error(badarg) end; get(_I, _A) -> erlang:error(badarg). The use of NODEPATTERN(S ) to select the right clause is just a hack , ( using the Beam compiler in OTP 11 ) . get_1(I, E=?NODEPATTERN(S), D) -> get_1(I rem S, element(I div S + 1, E), D); get_1(_I, E, D) when is_integer(E) -> D; get_1(I, E, _D) -> element(I+1, E). @see @see set/3 -spec reset(array_indx(), array()) -> array(). reset(I, #array{size = N, max = M, default = D, elements = E}=A) when is_integer(I), I >= 0 -> if I < N -> try A#array{elements = reset_1(I, E, D)} catch throw:default -> A end; M > 0 -> A; true -> erlang:error(badarg) end; reset(_I, _A) -> erlang:error(badarg). reset_1(I, E=?NODEPATTERN(S), D) -> I1 = I div S + 1, setelement(I1, E, reset_1(I rem S, element(I1, E), D)); reset_1(_I, E, _D) when is_integer(E) -> throw(default); reset_1(I, E, D) -> Indx = I+1, case element(Indx, E) of D -> throw(default); _ -> setelement(I+1, E, D) end. -ifdef(EUNIT). set_get_test_() -> N0 = ?LEAFSIZE, N1 = ?NODESIZE*N0, [?_assert(array:get(0, new()) =:= undefined), ?_assert(array:get(1, new()) =:= undefined), ?_assert(array:get(99999, new()) =:= undefined), ?_assert(array:get(0, new(1)) =:= undefined), ?_assert(array:get(0, new(1,{default,0})) =:= 0), ?_assert(array:get(9, new(10)) =:= undefined), ?_assertError(badarg, array:get(0, new(fixed))), ?_assertError(badarg, array:get(1, new(1))), ?_assertError(badarg, array:get(-1, new(1))), ?_assertError(badarg, array:get(10, new(10))), ?_assertError(badarg, array:set(-1, foo, new(10))), ?_assertError(badarg, array:set(10, foo, no_array)), ?_assert(array:size(set(0, 17, new())) =:= 1), ?_assert(array:size(set(N1-1, 17, new())) =:= N1), ?_assert(array:size(set(0, 42, set(0, 17, new()))) =:= 1), ?_assert(array:size(set(9, 42, set(0, 17, new()))) =:= 10), ?_assert(array:get(0, set(0, 17, new())) =:= 17), ?_assert(array:get(0, set(1, 17, new())) =:= undefined), ?_assert(array:get(1, set(1, 17, new())) =:= 17), ?_assert(array:get(0, fix(set(0, 17, new()))) =:= 17), ?_assertError(badarg, array:get(1, fix(set(0, 17, new())))), ?_assert(array:get(N1-2, set(N1-1, 17, new())) =:= undefined), ?_assert(array:get(N1-1, set(N1-1, 17, new())) =:= 17), ?_assertError(badarg, array:get(N1, fix(set(N1-1, 17, new())))), ?_assert(array:get(0, set(0, 42, set(0, 17, new()))) =:= 42), ?_assert(array:get(0, reset(0, new())) =:= undefined), ?_assert(array:get(0, reset(0, set(0, 17, new()))) =:= undefined), ?_assert(array:get(0, reset(0, new({default,42}))) =:= 42), ?_assert(array:get(0, reset(0, set(0, 17, new({default,42})))) =:= 42) ]. -endif. ( array ( ) ) - > list ( ) -spec to_list(array()) -> list(). to_list(#array{size = 0}) -> []; to_list(#array{size = N, elements = E, default = D}) -> to_list_1(E, D, N - 1); to_list(_) -> erlang:error(badarg). to_list_1(E=?NODEPATTERN(S), D, I) -> N = I div S, to_list_3(N, D, to_list_1(element(N+1, E), D, I rem S), E); to_list_1(E, D, I) when is_integer(E) -> push(I+1, D, []); to_list_1(E, _D, I) -> push_tuple(I+1, E, []). to_list_2(E=?NODEPATTERN(_S), D, L) -> to_list_3(?NODESIZE, D, L, E); to_list_2(E, D, L) when is_integer(E) -> push(E, D, L); to_list_2(E, _D, L) -> push_tuple(?LEAFSIZE, E, L). to_list_3(0, _D, L, _E) -> L; to_list_3(N, D, L, E) -> to_list_3(N-1, D, to_list_2(element(N, E), D, L), E). push(0, _E, L) -> L; push(N, E, L) -> push(N - 1, E, [E | L]). push_tuple(0, _T, L) -> L; push_tuple(N, T, L) -> push_tuple(N - 1, T, [element(N, T) | L]). -ifdef(EUNIT). to_list_test_() -> N0 = ?LEAFSIZE, [?_assert([] =:= to_list(new())), ?_assert([undefined] =:= to_list(new(1))), ?_assert([undefined,undefined] =:= to_list(new(2))), ?_assert(lists:duplicate(N0,0) =:= to_list(new(N0,{default,0}))), ?_assert(lists:duplicate(N0+1,1) =:= to_list(new(N0+1,{default,1}))), ?_assert(lists:duplicate(N0+2,2) =:= to_list(new(N0+2,{default,2}))), ?_assert(lists:duplicate(666,6) =:= to_list(new(666,{default,6}))), ?_assert([1,2,3] =:= to_list(set(2,3,set(1,2,set(0,1,new()))))), ?_assert([3,2,1] =:= to_list(set(0,3,set(1,2,set(2,1,new()))))), ?_assert([1|lists:duplicate(N0-2,0)++[1]] =:= to_list(set(N0-1,1,set(0,1,new({default,0}))))), ?_assert([1|lists:duplicate(N0-1,0)++[1]] =:= to_list(set(N0,1,set(0,1,new({default,0}))))), ?_assert([1|lists:duplicate(N0,0)++[1]] =:= to_list(set(N0+1,1,set(0,1,new({default,0}))))), ?_assert([1|lists:duplicate(N0*3,0)++[1]] =:= to_list(set((N0*3)+1,1,set(0,1,new({default,0}))))), ?_assertError(badarg, to_list(no_array)) ]. -endif. ( array ( ) ) - > list ( ) -spec sparse_to_list(array()) -> list(). sparse_to_list(#array{size = 0}) -> []; sparse_to_list(#array{size = N, elements = E, default = D}) -> sparse_to_list_1(E, D, N - 1); sparse_to_list(_) -> erlang:error(badarg). sparse_to_list_1(E=?NODEPATTERN(S), D, I) -> N = I div S, sparse_to_list_3(N, D, sparse_to_list_1(element(N+1, E), D, I rem S), E); sparse_to_list_1(E, _D, _I) when is_integer(E) -> []; sparse_to_list_1(E, D, I) -> sparse_push_tuple(I+1, D, E, []). sparse_to_list_2(E=?NODEPATTERN(_S), D, L) -> sparse_to_list_3(?NODESIZE, D, L, E); sparse_to_list_2(E, _D, L) when is_integer(E) -> L; sparse_to_list_2(E, D, L) -> sparse_push_tuple(?LEAFSIZE, D, E, L). sparse_to_list_3(0, _D, L, _E) -> L; sparse_to_list_3(N, D, L, E) -> sparse_to_list_3(N-1, D, sparse_to_list_2(element(N, E), D, L), E). sparse_push_tuple(0, _D, _T, L) -> L; sparse_push_tuple(N, D, T, L) -> case element(N, T) of D -> sparse_push_tuple(N - 1, D, T, L); E -> sparse_push_tuple(N - 1, D, T, [E | L]) end. -ifdef(EUNIT). sparse_to_list_test_() -> N0 = ?LEAFSIZE, [?_assert([] =:= sparse_to_list(new())), ?_assert([] =:= sparse_to_list(new(1))), ?_assert([] =:= sparse_to_list(new(1,{default,0}))), ?_assert([] =:= sparse_to_list(new(2))), ?_assert([] =:= sparse_to_list(new(2,{default,0}))), ?_assert([] =:= sparse_to_list(new(N0,{default,0}))), ?_assert([] =:= sparse_to_list(new(N0+1,{default,1}))), ?_assert([] =:= sparse_to_list(new(N0+2,{default,2}))), ?_assert([] =:= sparse_to_list(new(666,{default,6}))), ?_assert([1,2,3] =:= sparse_to_list(set(2,3,set(1,2,set(0,1,new()))))), ?_assert([3,2,1] =:= sparse_to_list(set(0,3,set(1,2,set(2,1,new()))))), ?_assert([0,1] =:= sparse_to_list(set(N0-1,1,set(0,0,new())))), ?_assert([0,1] =:= sparse_to_list(set(N0,1,set(0,0,new())))), ?_assert([0,1] =:= sparse_to_list(set(N0+1,1,set(0,0,new())))), ?_assert([0,1,2] =:= sparse_to_list(set(N0*10+1,2,set(N0*2+1,1,set(0,0,new()))))), ?_assertError(badarg, sparse_to_list(no_array)) ]. -endif. ( list ( ) ) - > array ( ) -spec from_list(list()) -> array(). from_list(List) -> from_list(List, undefined). ( list ( ) , term ( ) ) - > array ( ) @see -spec from_list(list(), term()) -> array(). from_list([], Default) -> new({default,Default}); from_list(List, Default) when is_list(List) -> {E, N, M} = from_list_1(?LEAFSIZE, List, Default, 0, [], []), #array{size = N, max = M, default = Default, elements = E}; from_list(_, _) -> erlang:error(badarg). Note : A cleaner but slower algorithm is to first take the length of from_list_1(0, Xs, D, N, As, Es) -> E = list_to_tuple(lists:reverse(As)), case Xs of [] -> case Es of [] -> {E, N, ?LEAFSIZE}; _ -> from_list_2_0(N, [E | Es], ?LEAFSIZE) end; [_|_] -> from_list_1(?LEAFSIZE, Xs, D, N, [], [E | Es]); _ -> erlang:error(badarg) end; from_list_1(I, Xs, D, N, As, Es) -> case Xs of [X | Xs1] -> from_list_1(I-1, Xs1, D, N+1, [X | As], Es); _ -> from_list_1(I-1, Xs, D, N, [D | As], Es) end. from_list_2_0(N, Es, S) -> from_list_2(?NODESIZE, pad((N-1) div S + 1, ?NODESIZE, S, Es), S, N, [S], []). from_list_2(0, Xs, S, N, As, Es) -> E = list_to_tuple(As), case Xs of [] -> case Es of [] -> {E, N, ?extend(S)}; _ -> from_list_2_0(N, lists:reverse([E | Es]), ?extend(S)) end; _ -> from_list_2(?NODESIZE, Xs, S, N, [S], [E | Es]) end; from_list_2(I, [X | Xs], S, N, As, Es) -> from_list_2(I-1, Xs, S, N, [X | As], Es). elements from N ( adding 0 to K-1 elements ) . pad(N, K, P, Es) -> push((K - (N rem K)) rem K, P, Es). -ifdef(EUNIT). from_list_test_() -> N0 = ?LEAFSIZE, N1 = ?NODESIZE*N0, N2 = ?NODESIZE*N1, N3 = ?NODESIZE*N2, N4 = ?NODESIZE*N3, [?_assert(array:size(from_list([])) =:= 0), ?_assert(array:is_fix(from_list([])) =:= false), ?_assert(array:size(from_list([undefined])) =:= 1), ?_assert(array:is_fix(from_list([undefined])) =:= false), ?_assert(array:size(from_list(lists:seq(1,N1))) =:= N1), ?_assert(to_list(from_list(lists:seq(1,N0))) =:= lists:seq(1,N0)), ?_assert(to_list(from_list(lists:seq(1,N0+1))) =:= lists:seq(1,N0+1)), ?_assert(to_list(from_list(lists:seq(1,N0+2))) =:= lists:seq(1,N0+2)), ?_assert(to_list(from_list(lists:seq(1,N2))) =:= lists:seq(1,N2)), ?_assert(to_list(from_list(lists:seq(1,N2+1))) =:= lists:seq(1,N2+1)), ?_assert(to_list(from_list(lists:seq(0,N3))) =:= lists:seq(0,N3)), ?_assert(to_list(from_list(lists:seq(0,N4))) =:= lists:seq(0,N4)), ?_assertError(badarg, from_list([a,b,a,c|d])), ?_assertError(badarg, from_list(no_array)) ]. -endif. ( array ( ) ) - > [ { Index::integer ( ) , Value::term ( ) } ] @see from_orddict/2 -spec to_orddict(array()) -> indx_pairs(). to_orddict(#array{size = 0}) -> []; to_orddict(#array{size = N, elements = E, default = D}) -> I = N - 1, to_orddict_1(E, I, D, I); to_orddict(_) -> erlang:error(badarg). to_orddict_1(E=?NODEPATTERN(S), R, D, I) -> N = I div S, I1 = I rem S, to_orddict_3(N, R - I1 - 1, D, to_orddict_1(element(N+1, E), R, D, I1), E, S); to_orddict_1(E, R, D, I) when is_integer(E) -> push_pairs(I+1, R, D, []); to_orddict_1(E, R, _D, I) -> push_tuple_pairs(I+1, R, E, []). to_orddict_2(E=?NODEPATTERN(S), R, D, L) -> to_orddict_3(?NODESIZE, R, D, L, E, S); to_orddict_2(E, R, D, L) when is_integer(E) -> push_pairs(E, R, D, L); to_orddict_2(E, R, _D, L) -> push_tuple_pairs(?LEAFSIZE, R, E, L). L; to_orddict_3(N, R, D, L, E, S) -> to_orddict_3(N-1, R - S, D, to_orddict_2(element(N, E), R, D, L), E, S). -spec push_pairs(non_neg_integer(), array_indx(), term(), indx_pairs()) -> indx_pairs(). push_pairs(0, _I, _E, L) -> L; push_pairs(N, I, E, L) -> push_pairs(N-1, I-1, E, [{I, E} | L]). -spec push_tuple_pairs(non_neg_integer(), array_indx(), term(), indx_pairs()) -> indx_pairs(). push_tuple_pairs(0, _I, _T, L) -> L; push_tuple_pairs(N, I, T, L) -> push_tuple_pairs(N-1, I-1, T, [{I, element(N, T)} | L]). -ifdef(EUNIT). to_orddict_test_() -> N0 = ?LEAFSIZE, [?_assert([] =:= to_orddict(new())), ?_assert([{0,undefined}] =:= to_orddict(new(1))), ?_assert([{0,undefined},{1,undefined}] =:= to_orddict(new(2))), ?_assert([{N,0}||N<-lists:seq(0,N0-1)] =:= to_orddict(new(N0,{default,0}))), ?_assert([{N,1}||N<-lists:seq(0,N0)] =:= to_orddict(new(N0+1,{default,1}))), ?_assert([{N,2}||N<-lists:seq(0,N0+1)] =:= to_orddict(new(N0+2,{default,2}))), ?_assert([{N,6}||N<-lists:seq(0,665)] =:= to_orddict(new(666,{default,6}))), ?_assert([{0,1},{1,2},{2,3}] =:= to_orddict(set(2,3,set(1,2,set(0,1,new()))))), ?_assert([{0,3},{1,2},{2,1}] =:= to_orddict(set(0,3,set(1,2,set(2,1,new()))))), ?_assert([{0,1}|[{N,0}||N<-lists:seq(1,N0-2)]++[{N0-1,1}]] =:= to_orddict(set(N0-1,1,set(0,1,new({default,0}))))), ?_assert([{0,1}|[{N,0}||N<-lists:seq(1,N0-1)]++[{N0,1}]] =:= to_orddict(set(N0,1,set(0,1,new({default,0}))))), ?_assert([{0,1}|[{N,0}||N<-lists:seq(1,N0)]++[{N0+1,1}]] =:= to_orddict(set(N0+1,1,set(0,1,new({default,0}))))), ?_assert([{0,0} | [{N,undefined}||N<-lists:seq(1,N0*2)]] ++ [{N0*2+1,1} | [{N,undefined}||N<-lists:seq(N0*2+2,N0*10)]] ++ [{N0*10+1,2}] =:= to_orddict(set(N0*10+1,2,set(N0*2+1,1,set(0,0,new()))))), ?_assertError(badarg, to_orddict(no_array)) ]. -endif. ( array ( ) ) - > [ { Index::integer ( ) , Value::term ( ) } ] @see -spec sparse_to_orddict(array()) -> indx_pairs(). sparse_to_orddict(#array{size = 0}) -> []; sparse_to_orddict(#array{size = N, elements = E, default = D}) -> I = N - 1, sparse_to_orddict_1(E, I, D, I); sparse_to_orddict(_) -> erlang:error(badarg). see for details sparse_to_orddict_1(E=?NODEPATTERN(S), R, D, I) -> N = I div S, I1 = I rem S, sparse_to_orddict_3(N, R - I1 - 1, D, sparse_to_orddict_1(element(N+1, E), R, D, I1), E, S); sparse_to_orddict_1(E, _R, _D, _I) when is_integer(E) -> []; sparse_to_orddict_1(E, R, D, I) -> sparse_push_tuple_pairs(I+1, R, D, E, []). sparse_to_orddict_2(E=?NODEPATTERN(S), R, D, L) -> sparse_to_orddict_3(?NODESIZE, R, D, L, E, S); sparse_to_orddict_2(E, _R, _D, L) when is_integer(E) -> L; sparse_to_orddict_2(E, R, D, L) -> sparse_push_tuple_pairs(?LEAFSIZE, R, D, E, L). L; sparse_to_orddict_3(N, R, D, L, E, S) -> sparse_to_orddict_3(N-1, R - S, D, sparse_to_orddict_2(element(N, E), R, D, L), E, S). -spec sparse_push_tuple_pairs(non_neg_integer(), array_indx(), _, _, indx_pairs()) -> indx_pairs(). sparse_push_tuple_pairs(0, _I, _D, _T, L) -> L; sparse_push_tuple_pairs(N, I, D, T, L) -> case element(N, T) of D -> sparse_push_tuple_pairs(N-1, I-1, D, T, L); E -> sparse_push_tuple_pairs(N-1, I-1, D, T, [{I, E} | L]) end. -ifdef(EUNIT). sparse_to_orddict_test_() -> N0 = ?LEAFSIZE, [?_assert([] =:= sparse_to_orddict(new())), ?_assert([] =:= sparse_to_orddict(new(1))), ?_assert([] =:= sparse_to_orddict(new(1,{default,0}))), ?_assert([] =:= sparse_to_orddict(new(2))), ?_assert([] =:= sparse_to_orddict(new(2,{default,0}))), ?_assert([] =:= sparse_to_orddict(new(N0,{default,0}))), ?_assert([] =:= sparse_to_orddict(new(N0+1,{default,1}))), ?_assert([] =:= sparse_to_orddict(new(N0+2,{default,2}))), ?_assert([] =:= sparse_to_orddict(new(666,{default,6}))), ?_assert([{0,1},{1,2},{2,3}] =:= sparse_to_orddict(set(2,3,set(1,2,set(0,1,new()))))), ?_assert([{0,3},{1,2},{2,1}] =:= sparse_to_orddict(set(0,3,set(1,2,set(2,1,new()))))), ?_assert([{0,1},{N0-1,1}] =:= sparse_to_orddict(set(N0-1,1,set(0,1,new({default,0}))))), ?_assert([{0,1},{N0,1}] =:= sparse_to_orddict(set(N0,1,set(0,1,new({default,0}))))), ?_assert([{0,1},{N0+1,1}] =:= sparse_to_orddict(set(N0+1,1,set(0,1,new({default,0}))))), ?_assert([{0,0},{N0*2+1,1},{N0*10+1,2}] =:= sparse_to_orddict(set(N0*10+1,2,set(N0*2+1,1,set(0,0,new()))))), ?_assertError(badarg, sparse_to_orddict(no_array)) ]. -endif. ( list ( ) ) - > array ( ) -spec from_orddict(indx_pairs()) -> array(). from_orddict(Orddict) -> from_orddict(Orddict, undefined). ( list ( ) , term ( ) ) - > array ( ) ordered list of pairs whose first elements are nonnegative @see @see -spec from_orddict(indx_pairs(), term()) -> array(). from_orddict([], Default) -> new({default,Default}); from_orddict(List, Default) when is_list(List) -> {E, N, M} = from_orddict_0(List, 0, ?LEAFSIZE, Default, []), #array{size = N, max = M, default = Default, elements = E}; from_orddict(_, _) -> erlang:error(badarg). 2 pass implementation , first pass builds the needed leaf nodes Second pass builds the tree from the leafs and the holes . from_orddict_0([], N, _Max, _D, Es) -> case Es of [E] -> {E, N, ?LEAFSIZE}; _ -> collect_leafs(N, Es, ?LEAFSIZE) end; from_orddict_0(Xs=[{Ix1, _}|_], Ix, Max0, D, Es0) when Ix1 > Max0, is_integer(Ix1) -> Hole = Ix1-Ix, Step = Hole - (Hole rem ?LEAFSIZE), Next = Ix+Step, from_orddict_0(Xs, Next, Next+?LEAFSIZE, D, [Step|Es0]); from_orddict_0(Xs0=[{_, _}|_], Ix0, Max, D, Es) -> {Xs,E,Ix} = from_orddict_1(Ix0, Max, Xs0, Ix0, D, []), from_orddict_0(Xs, Ix, Ix+?LEAFSIZE, D, [E|Es]); from_orddict_0(Xs, _, _, _,_) -> erlang:error({badarg, Xs}). from_orddict_1(Ix, Ix, Xs, N, _D, As) -> E = list_to_tuple(lists:reverse(As)), {Xs, E, N}; from_orddict_1(Ix, Max, Xs, N0, D, As) -> case Xs of [{Ix, Val} | Xs1] -> N = Ix+1, from_orddict_1(N, Max, Xs1, N, D, [Val | As]); [{Ix1, _} | _] when is_integer(Ix1), Ix1 > Ix -> N = Ix+1, from_orddict_1(N, Max, Xs, N, D, [D | As]); [_ | _] -> erlang:error({badarg, Xs}); _ -> from_orddict_1(Ix+1, Max, Xs, N0, D, [D | As]) end. collect_leafs(N, Es, S) -> I = (N-1) div S + 1, Pad = ((?NODESIZE - (I rem ?NODESIZE)) rem ?NODESIZE) * S, case Pad of 0 -> collect_leafs(?NODESIZE, Es, S, N, [S], []); collect_leafs(?NODESIZE, [Pad|Es], S, N, [S], []) end. collect_leafs(0, Xs, S, N, As, Es) -> E = list_to_tuple(As), case Xs of [] -> case Es of [] -> {E, N, ?extend(S)}; _ -> collect_leafs(N, lists:reverse([E | Es]), ?extend(S)) end; _ -> collect_leafs(?NODESIZE, Xs, S, N, [S], [E | Es]) end; collect_leafs(I, [X | Xs], S, N, As0, Es0) when is_integer(X) -> Step0 = (X div S), if Step0 < I -> As = push(Step0, S, As0), collect_leafs(I-Step0, Xs, S, N, As, Es0); I =:= ?NODESIZE -> Step = Step0 rem ?NODESIZE, As = push(Step, S, As0), collect_leafs(I-Step, Xs, S, N, As, [X|Es0]); I =:= Step0 -> As = push(I, S, As0), collect_leafs(0, Xs, S, N, As, Es0); true -> As = push(I, S, As0), Step = Step0 - I, collect_leafs(0, [Step*S|Xs], S, N, As, Es0) end; collect_leafs(I, [X | Xs], S, N, As, Es) -> collect_leafs(I-1, Xs, S, N, [X | As], Es); collect_leafs(?NODESIZE, [], S, N, [_], Es) -> collect_leafs(N, lists:reverse(Es), ?extend(S)). -ifdef(EUNIT). from_orddict_test_() -> N0 = ?LEAFSIZE, N1 = ?NODESIZE*N0, N2 = ?NODESIZE*N1, N3 = ?NODESIZE*N2, N4 = ?NODESIZE*N3, [?_assert(array:size(from_orddict([])) =:= 0), ?_assert(array:is_fix(from_orddict([])) =:= false), ?_assert(array:size(from_orddict([{0,undefined}])) =:= 1), ?_assert(array:is_fix(from_orddict([{0,undefined}])) =:= false), ?_assert(array:size(from_orddict([{N0-1,undefined}])) =:= N0), ?_assert(array:size(from_orddict([{N,0}||N<-lists:seq(0,N1-1)])) =:= N1), ?_assertError({badarg,_}, from_orddict([foo])), ?_assertError({badarg,_}, from_orddict([{200,foo},{1,bar}])), ?_assertError({badarg,_}, from_orddict([{N,0}||N<-lists:seq(0,N0-1)] ++ not_a_list)), ?_assertError(badarg, from_orddict(no_array)), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N0-1)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N0)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N2-1)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N2)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N3-1)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N,0}||N<-lists:seq(0,N4-1)], L =:= to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N0,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N3,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N4,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N0-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N1-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N3-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{N4-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N0,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N3,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N4,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N0-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N1-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N3-1,0}], L =:= sparse_to_orddict(from_orddict(L)))), ?_assert(?LET(L, [{0,0},{N4-1,0}], L =:= sparse_to_orddict(from_orddict(L)))) ]. -endif. Function = ( Index::integer ( ) , Value::term ( ) ) - > term ( ) @see sparse_map/2 -spec map(fun((array_indx(), _) -> _), array()) -> array(). map(Function, Array=#array{size = N, elements = E, default = D}) when is_function(Function, 2) -> if N > 0 -> kill reference , for GC A#array{elements = map_1(N-1, E, 0, Function, D)}; true -> Array end; map(_, _) -> erlang:error(badarg). in the function , but it is better to guarantee map_1(N, E=?NODEPATTERN(S), Ix, F, D) -> list_to_tuple(lists:reverse([S | map_2(1, E, Ix, F, D, [], N div S + 1, N rem S, S)])); map_1(N, E, Ix, F, D) when is_integer(E) -> map_1(N, unfold(E, D), Ix, F, D); map_1(N, E, Ix, F, D) -> list_to_tuple(lists:reverse(map_3(1, E, Ix, F, D, N+1, []))). map_2(I, E, Ix, F, D, L, I, R, _S) -> map_2_1(I+1, E, [map_1(R, element(I, E), Ix, F, D) | L]); map_2(I, E, Ix, F, D, L, N, R, S) -> map_2(I+1, E, Ix + S, F, D, [map_1(S-1, element(I, E), Ix, F, D) | L], N, R, S). map_2_1(I, E, L) when I =< ?NODESIZE -> map_2_1(I+1, E, [element(I, E) | L]); map_2_1(_I, _E, L) -> L. -spec map_3(pos_integer(), _, array_indx(), fun((array_indx(),_) -> _), _, non_neg_integer(), [X]) -> [X]. map_3(I, E, Ix, F, D, N, L) when I =< N -> map_3(I+1, E, Ix+1, F, D, N, [F(Ix, element(I, E)) | L]); map_3(I, E, Ix, F, D, N, L) when I =< ?LEAFSIZE -> map_3(I+1, E, Ix+1, F, D, N, [D | L]); map_3(_I, _E, _Ix, _F, _D, _N, L) -> L. unfold(S, _D) when S > ?LEAFSIZE -> ?NEW_NODE(?reduce(S)); unfold(_S, D) -> ?NEW_LEAF(D). -ifdef(EUNIT). map_test_() -> N0 = ?LEAFSIZE, Id = fun (_,X) -> X end, Plus = fun(N) -> fun (_,X) -> X+N end end, Default = fun(_K,undefined) -> no_value; (K,V) -> K+V end, [?_assertError(badarg, map([], new())), ?_assertError(badarg, map([], new(10))), ?_assert(to_list(map(Id, new())) =:= []), ?_assert(to_list(map(Id, new(1))) =:= [undefined]), ?_assert(to_list(map(Id, new(5,{default,0}))) =:= [0,0,0,0,0]), ?_assert(to_list(map(Id, from_list([1,2,3,4]))) =:= [1,2,3,4]), ?_assert(to_list(map(Plus(1), from_list([0,1,2,3]))) =:= [1,2,3,4]), ?_assert(to_list(map(Plus(-1), from_list(lists:seq(1,11)))) =:= lists:seq(0,10)), ?_assert(to_list(map(Plus(11), from_list(lists:seq(0,99999)))) =:= lists:seq(11,100010)), ?_assert([{0,0},{N0*2+1,N0*2+1+1},{N0*100+1,N0*100+1+2}] =:= sparse_to_orddict((map(Default, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new())))))#array{default = no_value})) ]. -endif. Function = ( Index::integer ( ) , Value::term ( ) ) - > term ( ) @see map/2 -spec sparse_map(fun((array_indx(), _) -> _), array()) -> array(). sparse_map(Function, Array=#array{size = N, elements = E, default = D}) when is_function(Function, 2) -> if N > 0 -> kill reference , for GC A#array{elements = sparse_map_1(N-1, E, 0, Function, D)}; true -> Array end; sparse_map(_, _) -> erlang:error(badarg). see map/2 for details sparse_map_1(N, E=?NODEPATTERN(S), Ix, F, D) -> list_to_tuple(lists:reverse([S | sparse_map_2(1, E, Ix, F, D, [], N div S + 1, N rem S, S)])); sparse_map_1(_N, E, _Ix, _F, _D) when is_integer(E) -> E; sparse_map_1(_N, E, Ix, F, D) -> list_to_tuple(lists:reverse(sparse_map_3(1, E, Ix, F, D, []))). sparse_map_2(I, E, Ix, F, D, L, I, R, _S) -> sparse_map_2_1(I+1, E, [sparse_map_1(R, element(I, E), Ix, F, D) | L]); sparse_map_2(I, E, Ix, F, D, L, N, R, S) -> sparse_map_2(I+1, E, Ix + S, F, D, [sparse_map_1(S-1, element(I, E), Ix, F, D) | L], N, R, S). sparse_map_2_1(I, E, L) when I =< ?NODESIZE -> sparse_map_2_1(I+1, E, [element(I, E) | L]); sparse_map_2_1(_I, _E, L) -> L. -spec sparse_map_3(pos_integer(), _, array_indx(), fun((array_indx(),_) -> _), _, [X]) -> [X]. sparse_map_3(I, T, Ix, F, D, L) when I =< ?LEAFSIZE -> case element(I, T) of D -> sparse_map_3(I+1, T, Ix+1, F, D, [D | L]); E -> sparse_map_3(I+1, T, Ix+1, F, D, [F(Ix, E) | L]) end; sparse_map_3(_I, _E, _Ix, _F, _D, L) -> L. -ifdef(EUNIT). sparse_map_test_() -> N0 = ?LEAFSIZE, Id = fun (_,X) -> X end, Plus = fun(N) -> fun (_,X) -> X+N end end, KeyPlus = fun (K,X) -> K+X end, [?_assertError(badarg, sparse_map([], new())), ?_assertError(badarg, sparse_map([], new(10))), ?_assert(to_list(sparse_map(Id, new())) =:= []), ?_assert(to_list(sparse_map(Id, new(1))) =:= [undefined]), ?_assert(to_list(sparse_map(Id, new(5,{default,0}))) =:= [0,0,0,0,0]), ?_assert(to_list(sparse_map(Id, from_list([1,2,3,4]))) =:= [1,2,3,4]), ?_assert(to_list(sparse_map(Plus(1), from_list([0,1,2,3]))) =:= [1,2,3,4]), ?_assert(to_list(sparse_map(Plus(-1), from_list(lists:seq(1,11)))) =:= lists:seq(0,10)), ?_assert(to_list(sparse_map(Plus(11), from_list(lists:seq(0,99999)))) =:= lists:seq(11,100010)), ?_assert(to_list(sparse_map(Plus(1), set(1,1,new({default,0})))) =:= [0,2]), ?_assert(to_list(sparse_map(Plus(1), set(3,4,set(0,1,new({default,0}))))) =:= [2,0,0,5]), ?_assert(to_list(sparse_map(Plus(1), set(9,9,set(1,1,new({default,0}))))) =:= [0,2,0,0,0,0,0,0,0,10]), ?_assert([{0,0},{N0*2+1,N0*2+1+1},{N0*100+1,N0*100+1+2}] =:= sparse_to_orddict(sparse_map(KeyPlus, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new())))))) ]. -endif. Function = ( Index::integer ( ) , Value::term ( ) , Acc::term ( ) ) - > @doc Fold the elements of the array using the given function and @see map/2 @see sparse_foldl/3 -spec foldl(fun((array_indx(), _, A) -> B), A, array()) -> B. foldl(Function, A, #array{size = N, elements = E, default = D}) when is_function(Function, 3) -> if N > 0 -> foldl_1(N-1, E, A, 0, Function, D); true -> A end; foldl(_, _, _) -> erlang:error(badarg). foldl_1(N, E=?NODEPATTERN(S), A, Ix, F, D) -> foldl_2(1, E, A, Ix, F, D, N div S + 1, N rem S, S); foldl_1(N, E, A, Ix, F, D) when is_integer(E) -> foldl_1(N, unfold(E, D), A, Ix, F, D); foldl_1(N, E, A, Ix, F, _D) -> foldl_3(1, E, A, Ix, F, N+1). foldl_2(I, E, A, Ix, F, D, I, R, _S) -> foldl_1(R, element(I, E), A, Ix, F, D); foldl_2(I, E, A, Ix, F, D, N, R, S) -> foldl_2(I+1, E, foldl_1(S-1, element(I, E), A, Ix, F, D), Ix + S, F, D, N, R, S). -spec foldl_3(pos_integer(), _, A, array_indx(), fun((array_indx, _, A) -> B), integer()) -> B. foldl_3(I, E, A, Ix, F, N) when I =< N -> foldl_3(I+1, E, F(Ix, element(I, E), A), Ix+1, F, N); foldl_3(_I, _E, A, _Ix, _F, _N) -> A. -ifdef(EUNIT). foldl_test_() -> N0 = ?LEAFSIZE, Count = fun (_,_,N) -> N+1 end, Sum = fun (_,X,N) -> N+X end, Reverse = fun (_,X,L) -> [X|L] end, Vals = fun(_K,undefined,{C,L}) -> {C+1,L}; (K,X,{C,L}) -> {C,[K+X|L]} end, [?_assertError(badarg, foldl([], 0, new())), ?_assertError(badarg, foldl([], 0, new(10))), ?_assert(foldl(Count, 0, new()) =:= 0), ?_assert(foldl(Count, 0, new(1)) =:= 1), ?_assert(foldl(Count, 0, new(10)) =:= 10), ?_assert(foldl(Count, 0, from_list([1,2,3,4])) =:= 4), ?_assert(foldl(Count, 10, from_list([0,1,2,3,4,5,6,7,8,9])) =:= 20), ?_assert(foldl(Count, 1000, from_list(lists:seq(0,999))) =:= 2000), ?_assert(foldl(Sum, 0, from_list(lists:seq(0,10))) =:= 55), ?_assert(foldl(Reverse, [], from_list(lists:seq(0,1000))) =:= lists:reverse(lists:seq(0,1000))), ?_assert({999,[N0*100+1+2,N0*2+1+1,0]} =:= foldl(Vals, {0,[]}, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new()))))) ]. -endif. Function = ( Index::integer ( ) , Value::term ( ) , Acc::term ( ) ) - > @doc Fold the elements of the array using the given function and -spec sparse_foldl(fun((array_indx(), _, A) -> B), A, array()) -> B. sparse_foldl(Function, A, #array{size = N, elements = E, default = D}) when is_function(Function, 3) -> if N > 0 -> sparse_foldl_1(N-1, E, A, 0, Function, D); true -> A end; sparse_foldl(_, _, _) -> erlang:error(badarg). sparse_foldl_1(N, E=?NODEPATTERN(S), A, Ix, F, D) -> sparse_foldl_2(1, E, A, Ix, F, D, N div S + 1, N rem S, S); sparse_foldl_1(_N, E, A, _Ix, _F, _D) when is_integer(E) -> A; sparse_foldl_1(N, E, A, Ix, F, D) -> sparse_foldl_3(1, E, A, Ix, F, D, N+1). sparse_foldl_2(I, E, A, Ix, F, D, I, R, _S) -> sparse_foldl_1(R, element(I, E), A, Ix, F, D); sparse_foldl_2(I, E, A, Ix, F, D, N, R, S) -> sparse_foldl_2(I+1, E, sparse_foldl_1(S-1, element(I, E), A, Ix, F, D), Ix + S, F, D, N, R, S). sparse_foldl_3(I, T, A, Ix, F, D, N) when I =< N -> case element(I, T) of D -> sparse_foldl_3(I+1, T, A, Ix+1, F, D, N); E -> sparse_foldl_3(I+1, T, F(Ix, E, A), Ix+1, F, D, N) end; sparse_foldl_3(_I, _T, A, _Ix, _F, _D, _N) -> A. -ifdef(EUNIT). sparse_foldl_test_() -> N0 = ?LEAFSIZE, Count = fun (_,_,N) -> N+1 end, Sum = fun (_,X,N) -> N+X end, Reverse = fun (_,X,L) -> [X|L] end, Vals = fun(_K,undefined,{C,L}) -> {C+1,L}; (K,X,{C,L}) -> {C,[K+X|L]} end, [?_assertError(badarg, sparse_foldl([], 0, new())), ?_assertError(badarg, sparse_foldl([], 0, new(10))), ?_assert(sparse_foldl(Count, 0, new()) =:= 0), ?_assert(sparse_foldl(Count, 0, new(1)) =:= 0), ?_assert(sparse_foldl(Count, 0, new(10,{default,1})) =:= 0), ?_assert(sparse_foldl(Count, 0, from_list([0,1,2,3,4],0)) =:= 4), ?_assert(sparse_foldl(Count, 0, from_list([0,1,2,3,4,5,6,7,8,9,0],0)) =:= 9), ?_assert(sparse_foldl(Count, 0, from_list(lists:seq(0,999),0)) =:= 999), ?_assert(sparse_foldl(Sum, 0, from_list(lists:seq(0,10), 5)) =:= 50), ?_assert(sparse_foldl(Reverse, [], from_list(lists:seq(0,1000), 0)) =:= lists:reverse(lists:seq(1,1000))), ?_assert({0,[N0*100+1+2,N0*2+1+1,0]} =:= sparse_foldl(Vals, {0,[]}, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new()))))) ]. -endif. Function = ( Index::integer ( ) , Value::term ( ) , Acc::term ( ) ) - > @doc Fold the elements of the array right - to - left using the given @see map/2 -spec foldr(fun((array_indx(), _, A) -> B), A, array()) -> B. foldr(Function, A, #array{size = N, elements = E, default = D}) when is_function(Function, 3) -> if N > 0 -> I = N - 1, foldr_1(I, E, I, A, Function, D); true -> A end; foldr(_, _, _) -> erlang:error(badarg). this is based on foldr_1(I, E=?NODEPATTERN(S), Ix, A, F, D) -> foldr_2(I div S + 1, E, Ix, A, F, D, I rem S, S-1); foldr_1(I, E, Ix, A, F, D) when is_integer(E) -> foldr_1(I, unfold(E, D), Ix, A, F, D); foldr_1(I, E, Ix, A, F, _D) -> I1 = I+1, foldr_3(I1, E, Ix-I1, A, F). foldr_2(0, _E, _Ix, A, _F, _D, _R, _R0) -> A; foldr_2(I, E, Ix, A, F, D, R, R0) -> foldr_2(I-1, E, Ix - R - 1, foldr_1(R, element(I, E), Ix, A, F, D), F, D, R0, R0). -spec foldr_3(array_indx(), term(), integer(), A, fun((array_indx(), _, A) -> B)) -> B. foldr_3(0, _E, _Ix, A, _F) -> A; foldr_3(I, E, Ix, A, F) -> foldr_3(I-1, E, Ix, F(Ix+I, element(I, E), A), F). -ifdef(EUNIT). foldr_test_() -> N0 = ?LEAFSIZE, Count = fun (_,_,N) -> N+1 end, Sum = fun (_,X,N) -> N+X end, List = fun (_,X,L) -> [X|L] end, Vals = fun(_K,undefined,{C,L}) -> {C+1,L}; (K,X,{C,L}) -> {C,[K+X|L]} end, [?_assertError(badarg, foldr([], 0, new())), ?_assertError(badarg, foldr([], 0, new(10))), ?_assert(foldr(Count, 0, new()) =:= 0), ?_assert(foldr(Count, 0, new(1)) =:= 1), ?_assert(foldr(Count, 0, new(10)) =:= 10), ?_assert(foldr(Count, 0, from_list([1,2,3,4])) =:= 4), ?_assert(foldr(Count, 10, from_list([0,1,2,3,4,5,6,7,8,9])) =:= 20), ?_assert(foldr(Count, 1000, from_list(lists:seq(0,999))) =:= 2000), ?_assert(foldr(Sum, 0, from_list(lists:seq(0,10))) =:= 55), ?_assert(foldr(List, [], from_list(lists:seq(0,1000))) =:= lists:seq(0,1000)), ?_assert({999,[0,N0*2+1+1,N0*100+1+2]} =:= foldr(Vals, {0,[]}, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new()))))) ]. -endif. Function = ( Index::integer ( ) , Value::term ( ) , Acc::term ( ) ) - > @doc Fold the elements of the array right - to - left using the given @see sparse_foldl/3 -spec sparse_foldr(fun((array_indx(), _, A) -> B), A, array()) -> B. sparse_foldr(Function, A, #array{size = N, elements = E, default = D}) when is_function(Function, 3) -> if N > 0 -> I = N - 1, sparse_foldr_1(I, E, I, A, Function, D); true -> A end; sparse_foldr(_, _, _) -> erlang:error(badarg). sparse_foldr_1(I, E=?NODEPATTERN(S), Ix, A, F, D) -> sparse_foldr_2(I div S + 1, E, Ix, A, F, D, I rem S, S-1); sparse_foldr_1(_I, E, _Ix, A, _F, _D) when is_integer(E) -> A; sparse_foldr_1(I, E, Ix, A, F, D) -> I1 = I+1, sparse_foldr_3(I1, E, Ix-I1, A, F, D). sparse_foldr_2(0, _E, _Ix, A, _F, _D, _R, _R0) -> A; sparse_foldr_2(I, E, Ix, A, F, D, R, R0) -> sparse_foldr_2(I-1, E, Ix - R - 1, sparse_foldr_1(R, element(I, E), Ix, A, F, D), F, D, R0, R0). -spec sparse_foldr_3(array_indx(), _, array_indx(), A, fun((array_indx(), _, A) -> B), _) -> B. sparse_foldr_3(0, _T, _Ix, A, _F, _D) -> A; sparse_foldr_3(I, T, Ix, A, F, D) -> case element(I, T) of D -> sparse_foldr_3(I-1, T, Ix, A, F, D); E -> sparse_foldr_3(I-1, T, Ix, F(Ix+I, E, A), F, D) end. ( array ( ) ) - > integer ( ) last non - default valued entry in the array , or zero if no such entry -spec sparse_size(array()) -> non_neg_integer(). sparse_size(A) -> F = fun (I, _V, _A) -> throw({value, I}) end, try sparse_foldr(F, [], A) of [] -> 0 catch {value, I} -> I + 1 end. -ifdef(EUNIT). sparse_foldr_test_() -> N0 = ?LEAFSIZE, Count = fun (_,_,N) -> N+1 end, Sum = fun (_,X,N) -> N+X end, List = fun (_,X,L) -> [X|L] end, Vals = fun(_K,undefined,{C,L}) -> {C+1,L}; (K,X,{C,L}) -> {C,[K+X|L]} end, [?_assertError(badarg, sparse_foldr([], 0, new())), ?_assertError(badarg, sparse_foldr([], 0, new(10))), ?_assert(sparse_foldr(Count, 0, new()) =:= 0), ?_assert(sparse_foldr(Count, 0, new(1)) =:= 0), ?_assert(sparse_foldr(Count, 0, new(10,{default,1})) =:= 0), ?_assert(sparse_foldr(Count, 0, from_list([0,1,2,3,4],0)) =:= 4), ?_assert(sparse_foldr(Count, 0, from_list([0,1,2,3,4,5,6,7,8,9,0],0)) =:= 9), ?_assert(sparse_foldr(Count, 0, from_list(lists:seq(0,999),0)) =:= 999), ?_assert(sparse_foldr(Sum, 0, from_list(lists:seq(0,10),5)) =:= 50), ?_assert(sparse_foldr(List, [], from_list(lists:seq(0,1000),0)) =:= lists:seq(1,1000)), ?_assert(sparse_size(new()) =:= 0), ?_assert(sparse_size(new(8)) =:= 0), ?_assert(sparse_size(array:set(7, 0, new())) =:= 8), ?_assert(sparse_size(array:set(7, 0, new(10))) =:= 8), ?_assert(sparse_size(array:set(99, 0, new(10,{fixed,false}))) =:= 100), ?_assert(sparse_size(array:set(7, undefined, new())) =:= 0), ?_assert(sparse_size(array:from_list([1,2,3,undefined])) =:= 3), ?_assert(sparse_size(array:from_orddict([{3,0},{17,0},{99,undefined}])) =:= 18), ?_assert({0,[0,N0*2+1+1,N0*100+1+2]} =:= sparse_foldr(Vals, {0,[]}, set(N0*100+1,2, set(N0*2+1,1, set(0,0,new()))))) ]. -endif.
b221d8acc3461c8c3365da1269fc88192f3970365a636d8e1c8050dee4f37a64
dktr0/estuary
ClientTests.hs
{-# LANGUAGE OverloadedStrings #-} import Test.Microspec import Data.Text (Text) import Data.Either import Data.Time import Data.IntMap as IntMap import Estuary.Types.Tempo import Estuary.Languages.CineCer0.Signal import Estuary.Languages.CineCer0.VideoSpec import Estuary.Languages.CineCer0.Parser import Estuary.Languages.CineCer0.Spec import Estuary.Types.Terminal as Terminal import Estuary.Types.View main :: IO () main = microspec $ do describe "the terminal command parser" $ do isLeft ( Terminal.parseCommand " " ) ` shouldBe ` True it "parses an empty string after a '!' producing an error msg" $ isLeft (Terminal.parseCommand "! ") `shouldBe` True it "parses a chat that begins with a non-! character" $ Terminal.parseCommand "hello" `shouldBe` Right (Terminal.Chat "hello") it "parses a resetzones command" $ Terminal.parseCommand "!resetzones" `shouldBe` Right Terminal.ResetZones it "parses a resetviews command" $ Terminal.parseCommand "!resetviews" `shouldBe` Right Terminal.ResetViews it "parses a resettempo command" $ Terminal.parseCommand "!resettempo" `shouldBe` Right Terminal.ResetTempo it "parses a reset command" $ Terminal.parseCommand "!reset" `shouldBe` Right Terminal.Reset it "parses a presetview command with an identifier as argument" $ Terminal.parseCommand "!presetview twocolumns" `shouldBe` Right (Terminal.PresetView "twocolumns") it "parses a presetview command with a text as argument" $ Terminal.parseCommand "!presetview \"twocolumns\"" `shouldBe` Right (Terminal.PresetView "twocolumns") it "parses a presetview command with an identifier as argument" $ Terminal.parseCommand "!publishview def" `shouldBe` Right (Terminal.PublishView "def") it "parses a publishview command with a text as argument" $ Terminal.parseCommand "!publishview \"def\"" `shouldBe` Right (Terminal.PublishView "def") it "parses a publishdefaultview command" $ Terminal.parseCommand "!publishdefaultview" `shouldBe` Right (Terminal.PublishView "def") it "parses an activeview command with a text as argument" $ Terminal.parseCommand "!activeview" `shouldBe` Right (Terminal.ActiveView) it "parses a localview command" $ Terminal.parseCommand "!localview (grid 2 3 [[label 1,code 2 0],[label 3,code 4 0],[label 5,code 6 0],[label 7,code 8 0],[label 9,code 10 0],[label 11,code 12 0]])" `shouldBe` Right (Terminal.LocalView $ GridView 2 3 [(Views [LabelView 1, CodeView 2 0]), (Views [LabelView 3, CodeView 4 0]), (Views [LabelView 5, CodeView 6 0]), (Views [LabelView 7, CodeView 8 0]), (Views [LabelView 9, CodeView 10 0]), (Views [LabelView 11, CodeView 12 0])]) it "parses a listviews command" $ Terminal.parseCommand "!listviews" `shouldBe` Right Terminal.ListViews it "parses a dumpview command" $ Terminal.parseCommand "!dumpview" `shouldBe` Right Terminal.DumpView it "parses a startstreaming command" $ Terminal.parseCommand "!startstreaming" `shouldBe` Right Terminal.StartStreaming it "parses a streamid command" $ Terminal.parseCommand "!streamid" `shouldBe` Right Terminal.StreamId it "parses a delay command with a double as argument" $ Terminal.parseCommand "!delay 0.5" `shouldBe` Right (Terminal.Delay 0.5) it "parses a delay command with an int as argument" $ Terminal.parseCommand "!delay 1" `shouldBe` Right (Terminal.Delay 1) it "parses a deletethisensemble command" $ Terminal.parseCommand "!deletethisensemble \"mypassword123\"" `shouldBe` Right (Terminal.DeleteThisEnsemble "mypassword123") it "parses a deleteensemble command" $ Terminal.parseCommand "!deleteensemble \"testEnsemble\" \"mypassword123\"" `shouldBe` Right (Terminal.DeleteEnsemble "testEnsemble" "mypassword123") -- no access to moderator password though EStuary's interface! it "parses a ancienttempo command" $ Terminal.parseCommand "!ancienttempo" `shouldBe` Right Terminal.AncientTempo it "parses a showtempo command" $ Terminal.parseCommand "!showtempo" `shouldBe` Right Terminal.ShowTempo it "parses a setcps command with a double as argument" $ Terminal.parseCommand "!setcps 0.5" `shouldBe` Right (Terminal.SetCPS 0.5) it "parses a setcps command with an int as argument" $ Terminal.parseCommand "!setcps 1" `shouldBe` Right (Terminal.SetCPS 1) it "parses a setbpm command with a double as argument" $ Terminal.parseCommand "!setbpm 60.45" `shouldBe` Right (Terminal.SetBPM 60.45) it "parses a setbpm command with an int as argument" $ Terminal.parseCommand "!setbpm 60" `shouldBe` Right (Terminal.SetBPM 60) it "parses a insertaudioresource command" $ Terminal.parseCommand "!insertaudioresource \"-samples/tree/main/teclado\" miteclado 0" `shouldBe` Right (Terminal.InsertAudioResource "-samples/tree/main/teclado" "miteclado" 0 ) it "parses a deleteaudioresource command" $ Terminal.parseCommand "!deleteaudioresource miteclado 0" `shouldBe` Right (Terminal.DeleteAudioResource "miteclado" 0 ) it "parses a appendaudioresource command" $ Terminal.parseCommand "!appendaudioresource \"-samples/tree/main/teclado\" miteclado" `shouldBe` Right (Terminal.AppendAudioResource "-samples/tree/main/teclado" "miteclado" ) describe "the CineCer0 parser" $ do it "parses an empty string" $ fmap (IntMap.null . layerSpecMap) (cineCer0 eTime "") `shouldBe` Right True it "parses a comment" $ fmap (IntMap.null . layerSpecMap) (cineCer0 eTime "-- my comment") `shouldBe` Right True it "parses empty statements" $ fmap (IntMap.null . layerSpecMap) (cineCer0 eTime ";;") `shouldBe` Right True it "parses the name of a video" $ fmap (fmap layer . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "\"myMovie.mov\"") `shouldBe` Right (Just $ Right "myMovie.mov") it "parses the name of a video using the function 'video'" $ fmap (fmap layer . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "video \"myMovie.mov\"") `shouldBe` Right (Just $ Right "myMovie.mov") it "parses the volume command" $ fmap (fmap (\vs -> fieldFromLayerSpec (volume vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "vol 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it " parses a mute command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( mute vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " mute $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just True ) it "parses the ramp command" $ fmap (fmap (\vs -> fieldFromLayerSpec (volume vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "vol (ramp 10 0 1) $ \"myMovie.mov\"") `shouldBe` Right (Just 0) it "parses the fadeIn command" $ fmap (fmap (\vs -> fieldFromLayerSpec (volume vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "vol (fadeIn 8) $ \"myMovie.mov\"") `shouldBe` Right (Just 0) it "parses the fadeOut command" $ fmap (fmap (\vs -> fieldFromLayerSpec (volume vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "vol (fadeOut 8) $ \"myMovie.mov\"") `shouldBe` Right (Just 1) it "parses the posX command" $ fmap (fmap (\vs -> fieldFromLayerSpec (posX vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setPosX 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it "parses the posY command" $ fmap (fmap (\vs -> fieldFromLayerSpec (posY vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setPosY 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it "parses the sin command" $ fmap (fmap (\vs -> fieldFromLayerSpec (posY vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setPosY (sin 0.1) $ \"myMovie.mov\"") `shouldBe` Right (Just 0) it "parses the width command" $ fmap (fmap (\vs -> fieldFromLayerSpec (width vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "width 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it "parses the height command" $ fmap (fmap (\vs -> fieldFromLayerSpec (height vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "height 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it "parses the opacity command" $ fmap (fmap (\vs -> fieldFromLayerSpec (opacity vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "opacity 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setOpacity command" $ fmap (fmap (\vs -> fieldFromLayerSpec (opacity vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setOpacity 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftOpacity command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( opacity vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftOpacity 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the blur command" $ fmap (fmap (\vs -> fieldFromLayerSpec (blur vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "blur 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setBlur command" $ fmap (fmap (\vs -> fieldFromLayerSpec (blur vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setBlur 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftBlur command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( blur vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftBlur 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the brightness command" $ fmap (fmap (\vs -> fieldFromLayerSpec (brightness vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "brightness 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setBrightness command" $ fmap (fmap (\vs -> fieldFromLayerSpec (brightness vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setBrightness 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftBrightness command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( brightness vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftBrightness 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the contrast command" $ fmap (fmap (\vs -> fieldFromLayerSpec (contrast vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "contrast 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setContrast command" $ fmap (fmap (\vs -> fieldFromLayerSpec (contrast vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setContrast 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftContrast command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( contrast vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftContrast 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the grayscale command" $ fmap (fmap (\vs -> fieldFromLayerSpec (grayscale vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "grayscale 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setGrayscale command" $ fmap (fmap (\vs -> fieldFromLayerSpec (grayscale vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setGrayscale 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftGrayscale command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( grayscale vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftGrayscale 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the saturate command" $ fmap (fmap (\vs -> fieldFromLayerSpec (saturate vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "saturate 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setSaturate command" $ fmap (fmap (\vs -> fieldFromLayerSpec (saturate vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setSaturate 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftSaturate command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( saturate vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftSaturate ' 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the every command" $ fmap (fmap (\vs -> (fieldFromLayerSpec (playbackPosition vs), fieldFromLayerSpec (playbackRate vs))) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "every 2 10 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0, Just 3.125)) masks receive values from 0 - 1 it "parses the 'cirlceMask' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (mask vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "circleMask 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just "clip-path:circle(35.5% at 50% 50%);") it "parses the 'sqrMask' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (mask vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "sqrMask 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just "clip-path: inset(25.0%);") it "parses the 'rectMask' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (mask vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "rectMask 0.5 0.5 1 1 $ \"myMovie.mov\"") `shouldBe` Right (Just "clip-path: inset(50.0% 50.0% 100.0% 100.0%);") text it "parses the 'text' command" $ fmap (fmap layer . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "text \"my text\"") `shouldBe` Right (Just $ Left "my text") it "parses the 'font' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (fontFamily vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "font \"Arial\" $ text \"my text\"") `shouldBe` Right (Just "Arial") it "parses the 'fontSize' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (fontSize vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "fontSize 4 $ text \"my text\"") `shouldBe` Right (Just 4.0) it "parses the 'strike' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (strike vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "strike $ text \"my text\"") `shouldBe` Right (Just True) it "parses the 'bold' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (bold vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "bold $ text \"my text\"") `shouldBe` Right (Just True) it "parses the 'italic' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (italic vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "italic $ text \"my text\"") `shouldBe` Right (Just True) it "parses the 'border' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (border vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "border $ text \"my text\"") `shouldBe` Right (Just True) it " parses the ' colour ' command " $ ( fmap ( fmap ( \vs - > ( colour . fieldFromLayerSpec vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " colour \"magenta\ " $ text \"my text\ " " ) ) ` shouldBe ` Right ( Just " magenta " ) it " parses the ' rgb ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " rgb 0.7 0 0.9 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 0.7 0 0.9 ) it " parses the ' hsl ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " hsl 1 1 0.7 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 1 1 0.7 ) it " parses the ' hsv ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " hsv 1 1 0.7 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 1 1 0.7 ) it " parses the ' rgba ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " rgba 0.7 0 0.9 0.5 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 0.7 0 0.9 0.5 ) it " parses the ' hsla ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " hsla 1 1 0.7 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 1 1 0.7 0.5 ) it " parses the ' hsva ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " hsva 1 1 0.7 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 1 1 0.7 0.5 ) -- f :: Either String (Maybe Colour) -> Either String (Maybe (Signal String)) -- Either String (Maybe (Signal String)) -- f (Right (Just (Colour x))) = Right $ Just x -- f _ = Right $ Nothing fieldFromLayerSpec f = f tempoTest vidlen rTime eTime aTime hoy = fromGregorian 2019 05 04 unMes = fromGregorian 2019 06 04 timeTempo = UTCTime hoy 0 -- time in which the tempo mark starts counting one month later the render time is introduced one month later the evaltime is introduced aTime = defaultAnchor myTempo eTime -- calculated from the tempo and the evaltime tempoTest = Tempo { freq= 0.5, time= timeTempo, count= 100} vidlen = realToFrac 12.5 :: NominalDiffTime mark ndt utc = addUTCTime ndt utc
null
https://raw.githubusercontent.com/dktr0/estuary/0b29526e1183fe81bb7885f9e9bfd728e926b3d1/client/tests/ClientTests.hs
haskell
# LANGUAGE OverloadedStrings # no access to moderator password though EStuary's interface! f :: Either String (Maybe Colour) -> Either String (Maybe (Signal String)) -- Either String (Maybe (Signal String)) f (Right (Just (Colour x))) = Right $ Just x f _ = Right $ Nothing time in which the tempo mark starts counting calculated from the tempo and the evaltime
import Test.Microspec import Data.Text (Text) import Data.Either import Data.Time import Data.IntMap as IntMap import Estuary.Types.Tempo import Estuary.Languages.CineCer0.Signal import Estuary.Languages.CineCer0.VideoSpec import Estuary.Languages.CineCer0.Parser import Estuary.Languages.CineCer0.Spec import Estuary.Types.Terminal as Terminal import Estuary.Types.View main :: IO () main = microspec $ do describe "the terminal command parser" $ do isLeft ( Terminal.parseCommand " " ) ` shouldBe ` True it "parses an empty string after a '!' producing an error msg" $ isLeft (Terminal.parseCommand "! ") `shouldBe` True it "parses a chat that begins with a non-! character" $ Terminal.parseCommand "hello" `shouldBe` Right (Terminal.Chat "hello") it "parses a resetzones command" $ Terminal.parseCommand "!resetzones" `shouldBe` Right Terminal.ResetZones it "parses a resetviews command" $ Terminal.parseCommand "!resetviews" `shouldBe` Right Terminal.ResetViews it "parses a resettempo command" $ Terminal.parseCommand "!resettempo" `shouldBe` Right Terminal.ResetTempo it "parses a reset command" $ Terminal.parseCommand "!reset" `shouldBe` Right Terminal.Reset it "parses a presetview command with an identifier as argument" $ Terminal.parseCommand "!presetview twocolumns" `shouldBe` Right (Terminal.PresetView "twocolumns") it "parses a presetview command with a text as argument" $ Terminal.parseCommand "!presetview \"twocolumns\"" `shouldBe` Right (Terminal.PresetView "twocolumns") it "parses a presetview command with an identifier as argument" $ Terminal.parseCommand "!publishview def" `shouldBe` Right (Terminal.PublishView "def") it "parses a publishview command with a text as argument" $ Terminal.parseCommand "!publishview \"def\"" `shouldBe` Right (Terminal.PublishView "def") it "parses a publishdefaultview command" $ Terminal.parseCommand "!publishdefaultview" `shouldBe` Right (Terminal.PublishView "def") it "parses an activeview command with a text as argument" $ Terminal.parseCommand "!activeview" `shouldBe` Right (Terminal.ActiveView) it "parses a localview command" $ Terminal.parseCommand "!localview (grid 2 3 [[label 1,code 2 0],[label 3,code 4 0],[label 5,code 6 0],[label 7,code 8 0],[label 9,code 10 0],[label 11,code 12 0]])" `shouldBe` Right (Terminal.LocalView $ GridView 2 3 [(Views [LabelView 1, CodeView 2 0]), (Views [LabelView 3, CodeView 4 0]), (Views [LabelView 5, CodeView 6 0]), (Views [LabelView 7, CodeView 8 0]), (Views [LabelView 9, CodeView 10 0]), (Views [LabelView 11, CodeView 12 0])]) it "parses a listviews command" $ Terminal.parseCommand "!listviews" `shouldBe` Right Terminal.ListViews it "parses a dumpview command" $ Terminal.parseCommand "!dumpview" `shouldBe` Right Terminal.DumpView it "parses a startstreaming command" $ Terminal.parseCommand "!startstreaming" `shouldBe` Right Terminal.StartStreaming it "parses a streamid command" $ Terminal.parseCommand "!streamid" `shouldBe` Right Terminal.StreamId it "parses a delay command with a double as argument" $ Terminal.parseCommand "!delay 0.5" `shouldBe` Right (Terminal.Delay 0.5) it "parses a delay command with an int as argument" $ Terminal.parseCommand "!delay 1" `shouldBe` Right (Terminal.Delay 1) it "parses a deletethisensemble command" $ Terminal.parseCommand "!deletethisensemble \"mypassword123\"" `shouldBe` Right (Terminal.DeleteThisEnsemble "mypassword123") it "parses a ancienttempo command" $ Terminal.parseCommand "!ancienttempo" `shouldBe` Right Terminal.AncientTempo it "parses a showtempo command" $ Terminal.parseCommand "!showtempo" `shouldBe` Right Terminal.ShowTempo it "parses a setcps command with a double as argument" $ Terminal.parseCommand "!setcps 0.5" `shouldBe` Right (Terminal.SetCPS 0.5) it "parses a setcps command with an int as argument" $ Terminal.parseCommand "!setcps 1" `shouldBe` Right (Terminal.SetCPS 1) it "parses a setbpm command with a double as argument" $ Terminal.parseCommand "!setbpm 60.45" `shouldBe` Right (Terminal.SetBPM 60.45) it "parses a setbpm command with an int as argument" $ Terminal.parseCommand "!setbpm 60" `shouldBe` Right (Terminal.SetBPM 60) it "parses a insertaudioresource command" $ Terminal.parseCommand "!insertaudioresource \"-samples/tree/main/teclado\" miteclado 0" `shouldBe` Right (Terminal.InsertAudioResource "-samples/tree/main/teclado" "miteclado" 0 ) it "parses a deleteaudioresource command" $ Terminal.parseCommand "!deleteaudioresource miteclado 0" `shouldBe` Right (Terminal.DeleteAudioResource "miteclado" 0 ) it "parses a appendaudioresource command" $ Terminal.parseCommand "!appendaudioresource \"-samples/tree/main/teclado\" miteclado" `shouldBe` Right (Terminal.AppendAudioResource "-samples/tree/main/teclado" "miteclado" ) describe "the CineCer0 parser" $ do it "parses an empty string" $ fmap (IntMap.null . layerSpecMap) (cineCer0 eTime "") `shouldBe` Right True it "parses a comment" $ fmap (IntMap.null . layerSpecMap) (cineCer0 eTime "-- my comment") `shouldBe` Right True it "parses empty statements" $ fmap (IntMap.null . layerSpecMap) (cineCer0 eTime ";;") `shouldBe` Right True it "parses the name of a video" $ fmap (fmap layer . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "\"myMovie.mov\"") `shouldBe` Right (Just $ Right "myMovie.mov") it "parses the name of a video using the function 'video'" $ fmap (fmap layer . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "video \"myMovie.mov\"") `shouldBe` Right (Just $ Right "myMovie.mov") it "parses the volume command" $ fmap (fmap (\vs -> fieldFromLayerSpec (volume vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "vol 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it " parses a mute command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( mute vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " mute $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just True ) it "parses the ramp command" $ fmap (fmap (\vs -> fieldFromLayerSpec (volume vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "vol (ramp 10 0 1) $ \"myMovie.mov\"") `shouldBe` Right (Just 0) it "parses the fadeIn command" $ fmap (fmap (\vs -> fieldFromLayerSpec (volume vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "vol (fadeIn 8) $ \"myMovie.mov\"") `shouldBe` Right (Just 0) it "parses the fadeOut command" $ fmap (fmap (\vs -> fieldFromLayerSpec (volume vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "vol (fadeOut 8) $ \"myMovie.mov\"") `shouldBe` Right (Just 1) it "parses the posX command" $ fmap (fmap (\vs -> fieldFromLayerSpec (posX vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setPosX 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it "parses the posY command" $ fmap (fmap (\vs -> fieldFromLayerSpec (posY vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setPosY 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it "parses the sin command" $ fmap (fmap (\vs -> fieldFromLayerSpec (posY vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setPosY (sin 0.1) $ \"myMovie.mov\"") `shouldBe` Right (Just 0) it "parses the width command" $ fmap (fmap (\vs -> fieldFromLayerSpec (width vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "width 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it "parses the height command" $ fmap (fmap (\vs -> fieldFromLayerSpec (height vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "height 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just 0.5) it "parses the opacity command" $ fmap (fmap (\vs -> fieldFromLayerSpec (opacity vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "opacity 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setOpacity command" $ fmap (fmap (\vs -> fieldFromLayerSpec (opacity vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setOpacity 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftOpacity command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( opacity vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftOpacity 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the blur command" $ fmap (fmap (\vs -> fieldFromLayerSpec (blur vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "blur 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setBlur command" $ fmap (fmap (\vs -> fieldFromLayerSpec (blur vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setBlur 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftBlur command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( blur vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftBlur 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the brightness command" $ fmap (fmap (\vs -> fieldFromLayerSpec (brightness vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "brightness 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setBrightness command" $ fmap (fmap (\vs -> fieldFromLayerSpec (brightness vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setBrightness 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftBrightness command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( brightness vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftBrightness 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the contrast command" $ fmap (fmap (\vs -> fieldFromLayerSpec (contrast vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "contrast 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setContrast command" $ fmap (fmap (\vs -> fieldFromLayerSpec (contrast vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setContrast 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftContrast command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( contrast vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftContrast 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the grayscale command" $ fmap (fmap (\vs -> fieldFromLayerSpec (grayscale vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "grayscale 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setGrayscale command" $ fmap (fmap (\vs -> fieldFromLayerSpec (grayscale vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setGrayscale 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftGrayscale command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( grayscale vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftGrayscale 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the saturate command" $ fmap (fmap (\vs -> fieldFromLayerSpec (saturate vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "saturate 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it "parses the setSaturate command" $ fmap (fmap (\vs -> fieldFromLayerSpec (saturate vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "setSaturate 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0.5)) it " parses the shiftSaturate command " $ fmap ( fmap ( \vs - > fieldFromLayerSpec ( saturate vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " shiftSaturate ' 0.5 $ \"myMovie.mov\ " " ) ` shouldBe ` Right ( Just ( Just 0.5 ) ) it "parses the every command" $ fmap (fmap (\vs -> (fieldFromLayerSpec (playbackPosition vs), fieldFromLayerSpec (playbackRate vs))) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "every 2 10 $ \"myMovie.mov\"") `shouldBe` Right (Just (Just 0, Just 3.125)) masks receive values from 0 - 1 it "parses the 'cirlceMask' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (mask vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "circleMask 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just "clip-path:circle(35.5% at 50% 50%);") it "parses the 'sqrMask' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (mask vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "sqrMask 0.5 $ \"myMovie.mov\"") `shouldBe` Right (Just "clip-path: inset(25.0%);") it "parses the 'rectMask' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (mask vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "rectMask 0.5 0.5 1 1 $ \"myMovie.mov\"") `shouldBe` Right (Just "clip-path: inset(50.0% 50.0% 100.0% 100.0%);") text it "parses the 'text' command" $ fmap (fmap layer . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "text \"my text\"") `shouldBe` Right (Just $ Left "my text") it "parses the 'font' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (fontFamily vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "font \"Arial\" $ text \"my text\"") `shouldBe` Right (Just "Arial") it "parses the 'fontSize' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (fontSize vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "fontSize 4 $ text \"my text\"") `shouldBe` Right (Just 4.0) it "parses the 'strike' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (strike vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "strike $ text \"my text\"") `shouldBe` Right (Just True) it "parses the 'bold' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (bold vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "bold $ text \"my text\"") `shouldBe` Right (Just True) it "parses the 'italic' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (italic vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "italic $ text \"my text\"") `shouldBe` Right (Just True) it "parses the 'border' command" $ fmap (fmap (\vs -> fieldFromLayerSpec (border vs)) . IntMap.lookup 0 . layerSpecMap) (cineCer0 eTime "border $ text \"my text\"") `shouldBe` Right (Just True) it " parses the ' colour ' command " $ ( fmap ( fmap ( \vs - > ( colour . fieldFromLayerSpec vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " colour \"magenta\ " $ text \"my text\ " " ) ) ` shouldBe ` Right ( Just " magenta " ) it " parses the ' rgb ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " rgb 0.7 0 0.9 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 0.7 0 0.9 ) it " parses the ' hsl ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " hsl 1 1 0.7 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 1 1 0.7 ) it " parses the ' hsv ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " hsv 1 1 0.7 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 1 1 0.7 ) it " parses the ' rgba ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " rgba 0.7 0 0.9 0.5 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 0.7 0 0.9 0.5 ) it " parses the ' hsla ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " hsla 1 1 0.7 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 1 1 0.7 0.5 ) it " parses the ' hsva ' command " $ fmap ( fmap ( \vs - > ( colour vs ) ) . IntMap.lookup 0 . layerSpecMap ) ( cineCer0 eTime " hsva 1 1 0.7 $ text \"my text\ " " ) ` shouldBe ` Right ( Just 1 1 0.7 0.5 ) fieldFromLayerSpec f = f tempoTest vidlen rTime eTime aTime hoy = fromGregorian 2019 05 04 unMes = fromGregorian 2019 06 04 one month later the render time is introduced one month later the evaltime is introduced tempoTest = Tempo { freq= 0.5, time= timeTempo, count= 100} vidlen = realToFrac 12.5 :: NominalDiffTime mark ndt utc = addUTCTime ndt utc
948018c9e456b74616b9110f39aae06fc8d9911b770d6f498cece7d8b162c040
justinmeiners/exercises
2_09.scm
; Addition and subtraction ; [a, b] + [c, d] = [a + c, b + d] ; w1 = b - a ; w2 = d - c ; w3 = (b + d) - (a + c) ; = (b - a) + (d - c) = w1 + w2 ; [a, b] + -[c, d] = [a, b] + [-d, -c] = [a - d, b - c] ; w3 = (b - c) - (a - d) ; = (b - a) - c + d ; = (b - a) + (d - c) = w1 + w2 ; Multiplication [ 0 , 1 ] * [ 2 , 3 ] = [ 0 , 3 ] w1 = 1 , w2 = 1 , w3 = 3 ; however: [ 0 , 1 ] * [ 0 , 1 = [ 0 , 1 ] ] w1 = 1 , w2 = 1 , w3 = 1 ; so w3 is not a function of w1 and w2
null
https://raw.githubusercontent.com/justinmeiners/exercises/ad4a752d429e0c5a37846b029d7022ee6a42e853/sicp/2/2_09.scm
scheme
Addition and subtraction [a, b] + [c, d] = [a + c, b + d] w1 = b - a w2 = d - c w3 = (b + d) - (a + c) = (b - a) + (d - c) = w1 + w2 [a, b] + -[c, d] = [a, b] + [-d, -c] = [a - d, b - c] w3 = (b - c) - (a - d) = (b - a) - c + d = (b - a) + (d - c) = w1 + w2 Multiplication however: so w3 is not a function of w1 and w2
[ 0 , 1 ] * [ 2 , 3 ] = [ 0 , 3 ] w1 = 1 , w2 = 1 , w3 = 3 [ 0 , 1 ] * [ 0 , 1 = [ 0 , 1 ] ] w1 = 1 , w2 = 1 , w3 = 1
0683c79292fded24910e27fce54dbd731bfd28164ff09a206e50d600b8243370
mfoemmel/erlang-otp
filename.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1997 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(filename). %% Purpose: Provides generic manipulation of filenames. %% %% Generally, these functions accept filenames in the native format for the current operating system ( Unix or Windows ) . %% Deep characters lists (as returned by io_lib:format()) are accepted; %% resulting strings will always be flat. %% %% Implementation note: We used to only flatten if the list turned out %% to be deep. Now that atoms are allowed in deep lists, in most cases %% we flatten the arguments immediately on function entry as that makes %% it easier to ensure that the code works. -export([absname/1, absname/2, absname_join/2, basename/1, basename/2, dirname/1, extension/1, join/1, join/2, pathtype/1, rootname/1, rootname/2, split/1, nativename/1]). -export([find_src/1, find_src/2, flatten/1]). %% Undocumented and unsupported exports. -export([append/2]). -include_lib("kernel/include/file.hrl"). %% Converts a relative filename to an absolute filename %% or the filename itself if it already is an absolute filename %% Note that no attempt is made to create the most beatiful %% absolute name since this can give incorrect results on %% file systems which allows links. %% Examples: Assume ( for UNIX ) current directory " /usr / local " Assume ( for ) current directory " D:/usr / local " %% %% (for Unix) : absname("foo") -> "/usr/local/foo" ( for ): " ) - > " D:/usr / local / foo " %% (for Unix) : absname("../x") -> "/usr/local/../x" ( for ): absname(" .. /x " ) - > " D:/usr / local/ .. /x " %% (for Unix) : absname("/") -> "/" ( for ): absname("/ " ) - > " D:/ " -spec absname(name()) -> string(). absname(Name) -> {ok, Cwd} = file:get_cwd(), absname(Name, Cwd). -spec absname(name(), string()) -> string(). absname(Name, AbsBase) -> case pathtype(Name) of relative -> absname_join(AbsBase, Name); absolute -> We must flatten the filename before passing it into , %% or we will get slashes inserted into the wrong places. join([flatten(Name)]); volumerelative -> absname_vr(split(Name), split(AbsBase), AbsBase) end. Handles volumerelative names ( on Windows only ) . absname_vr(["/"|Rest1], [Volume|_], _AbsBase) -> %% Absolute path on current drive. join([Volume|Rest1]); absname_vr([[X, $:]|Rest1], [[X|_]|_], AbsBase) -> %% Relative to current directory on current drive. absname(join(Rest1), AbsBase); absname_vr([[X, $:]|Name], _, _AbsBase) -> %% Relative to current directory on another drive. Dcwd = case file:get_cwd([X, $:]) of {ok, Dir} -> Dir; {error, _} -> [X, $:, $/] end, absname(join(Name), Dcwd). Joins a relative filename to an absolute base . For the %% resulting name is fixed to minimize the length by collapsing %% ".." directories. %% For other systems this is just a join/2, but assumes that %% AbsBase must be absolute and Name must be relative. -spec absname_join(string(), name()) -> string(). absname_join(AbsBase, Name) -> case major_os_type() of vxworks -> absname_pretty(AbsBase, split(Name), lists:reverse(split(AbsBase))); _Else -> join(AbsBase, flatten(Name)) end. Handles absolute filenames for - these are ' pretty - printed ' , %% since a C function call chdir("/erlang/lib/../bin") really sets cwd to ' / lib/ .. /bin ' which also works , but the long term %% effect is potentially not so good ... %% %% absname_pretty("../bin", "/erlang/lib") -> "/erlang/bin" absname_pretty(" .. / .. / .. / .. " , " /erlang " ) - > " /erlang " absname_pretty(Abspath, Relpath, []) -> AbsBase _ must _ begin with a device name {device, _Rest, Dev} = vxworks_first(Abspath), absname_pretty(Abspath, Relpath, [lists:reverse(Dev)]); absname_pretty(_Abspath, [], AbsBase) -> join(lists:reverse(AbsBase)); absname_pretty(Abspath, [[$.]|Rest], AbsBase) -> absname_pretty(Abspath, Rest, AbsBase); absname_pretty(Abspath, [[$.,$.]|Rest], [_|AbsRest]) -> absname_pretty(Abspath, Rest, AbsRest); absname_pretty(Abspath, [First|Rest], AbsBase) -> absname_pretty(Abspath, Rest, [First|AbsBase]). %% Returns the part of the filename after the last directory separator, %% or the filename itself if it has no separators. %% %% Examples: basename("foo") -> "foo" %% basename("/usr/foo") -> "foo" %% basename("/usr/foo/") -> "foo" (trailing slashes ignored) %% basename("/") -> [] -spec basename(name()) -> string(). basename(Name0) -> Name = flatten(Name0), {DirSep2, DrvSep} = separators(), basename1(skip_prefix(Name, DrvSep), [], DirSep2). basename1([$/|[]], Tail, DirSep2) -> basename1([], Tail, DirSep2); basename1([$/|Rest], _Tail, DirSep2) -> basename1(Rest, [], DirSep2); basename1([[_|_]=List|Rest], Tail, DirSep2) -> basename1(List++Rest, Tail, DirSep2); basename1([DirSep2|Rest], Tail, DirSep2) when is_integer(DirSep2) -> basename1([$/|Rest], Tail, DirSep2); basename1([Char|Rest], Tail, DirSep2) when is_integer(Char) -> basename1(Rest, [Char|Tail], DirSep2); basename1([], Tail, _DirSep2) -> lists:reverse(Tail). No prefix for unix , but for . case major_os_type() of vxworks -> case vxworks_first(Name) of {device, Rest, _Device} -> Rest; {not_device, _Rest, _First} -> Name end; _Else -> Name end; skip_prefix(Name, DrvSep) -> skip_prefix1(Name, DrvSep). skip_prefix1([L, DrvSep|Name], DrvSep) when is_integer(L) -> Name; skip_prefix1([L], _) when is_integer(L) -> [L]; skip_prefix1(Name, _) -> Name. %% Returns the last component of the filename, with the given %% extension stripped. Use this function if you want %% to remove an extension that might or might not be there. %% Use rootname(basename(File)) if you want to remove an extension %% that you know exists, but you are not sure which one it is. %% %% Example: basename("~/src/kalle.erl", ".erl") -> "kalle" basename("~/src / kalle.jam " , " .erl " ) - > " kalle.jam " / kalle.old.erl " , " .erl " ) - > " kalle.old " %% %% rootname(basename("xxx.jam")) -> "xxx" %% rootname(basename("xxx.erl")) -> "xxx" -spec basename(name(), name()) -> string(). basename(Name0, Ext0) -> Name = flatten(Name0), Ext = flatten(Ext0), {DirSep2,DrvSep} = separators(), NoPrefix = skip_prefix(Name, DrvSep), basename(NoPrefix, Ext, [], DirSep2). basename(Ext, Ext, Tail, _DrvSep2) -> lists:reverse(Tail); basename([$/|[]], Ext, Tail, DrvSep2) -> basename([], Ext, Tail, DrvSep2); basename([$/|Rest], Ext, _Tail, DrvSep2) -> basename(Rest, Ext, [], DrvSep2); basename([$\\|Rest], Ext, Tail, DirSep2) when is_integer(DirSep2) -> basename([$/|Rest], Ext, Tail, DirSep2); basename([Char|Rest], Ext, Tail, DrvSep2) when is_integer(Char) -> basename(Rest, Ext, [Char|Tail], DrvSep2); basename([], _Ext, Tail, _DrvSep2) -> lists:reverse(Tail). %% Returns the directory part of a pathname. %% %% Example: dirname("/usr/src/kalle.erl") -> "/usr/src", %% dirname("kalle.erl") -> "." -spec dirname(name()) -> string(). dirname(Name0) -> Name = flatten(Name0), case os:type() of vxworks -> {Devicep, Restname, FirstComp} = vxworks_first(Name), case Devicep of device -> dirname(Restname, FirstComp, [], separators()); _ -> dirname(Name, [], [], separators()) end; _ -> dirname(Name, [], [], separators()) end. dirname([[_|_]=List|Rest], Dir, File, Seps) -> dirname(List++Rest, Dir, File, Seps); dirname([$/|Rest], Dir, File, Seps) -> dirname(Rest, File++Dir, [$/], Seps); dirname([DirSep|Rest], Dir, File, {DirSep,_}=Seps) when is_integer(DirSep) -> dirname(Rest, File++Dir, [$/], Seps); dirname([Dl,DrvSep|Rest], [], [], {_,DrvSep}=Seps) when is_integer(DrvSep), ((($a =< Dl) and (Dl =< $z)) or (($A =< Dl) and (Dl =< $Z))) -> dirname(Rest, [DrvSep,Dl], [], Seps); dirname([Char|Rest], Dir, File, Seps) when is_integer(Char) -> dirname(Rest, Dir, [Char|File], Seps); dirname([], [], File, _Seps) -> case lists:reverse(File) of [$/|_] -> [$/]; _ -> "." end; dirname([], [$/|Rest], File, Seps) -> dirname([], Rest, File, Seps); dirname([], [DrvSep,Dl], File, {_,DrvSep}) -> case lists:reverse(File) of [$/|_] -> [Dl,DrvSep,$/]; _ -> [Dl,DrvSep] end; dirname([], Dir, _, _) -> lists:reverse(Dir). %% Given a filename string, returns the file extension, %% including the period. Returns an empty list if there %% is no extension. %% %% Example: extension("foo.erl") -> ".erl" %% extension("jam.src/kalle") -> "" %% On Windows : fn : / kalle.erl " ) - > " /usr / src " -spec extension(name()) -> string(). extension(Name0) -> Name = flatten(Name0), extension(Name, [], major_os_type()). extension([$.|Rest], _Result, OsType) -> extension(Rest, [$.], OsType); extension([Char|Rest], [], OsType) when is_integer(Char) -> extension(Rest, [], OsType); extension([$/|Rest], _Result, OsType) -> extension(Rest, [], OsType); extension([$\\|Rest], _Result, win32) -> extension(Rest, [], win32); extension([$\\|Rest], _Result, vxworks) -> extension(Rest, [], vxworks); extension([Char|Rest], Result, OsType) when is_integer(Char) -> extension(Rest, [Char|Result], OsType); extension([], Result, _OsType) -> lists:reverse(Result). %% Joins a list of filenames with directory separators. -spec join([string()]) -> string(). join([Name1, Name2|Rest]) -> join([join(Name1, Name2)|Rest]); join([Name]) when is_list(Name) -> join1(Name, [], [], major_os_type()); join([Name]) when is_atom(Name) -> join([atom_to_list(Name)]). Joins two filenames with directory separators . -spec join(string(), string()) -> string(). join(Name1, Name2) when is_list(Name1), is_list(Name2) -> OsType = major_os_type(), case pathtype(Name2) of relative -> join1(Name1, Name2, [], OsType); _Other -> join1(Name2, [], [], OsType) end; join(Name1, Name2) when is_atom(Name1) -> join(atom_to_list(Name1), Name2); join(Name1, Name2) when is_atom(Name2) -> join(Name1, atom_to_list(Name2)). %% Internal function to join an absolute name and a relative name. It is the responsibility of the caller to ensure that RelativeName %% is relative. join1([UcLetter, $:|Rest], RelativeName, [], win32) when is_integer(UcLetter), UcLetter >= $A, UcLetter =< $Z -> join1(Rest, RelativeName, [$:, UcLetter+$a-$A], win32); join1([$\\|Rest], RelativeName, Result, win32) -> join1([$/|Rest], RelativeName, Result, win32); join1([$\\|Rest], RelativeName, Result, vxworks) -> join1([$/|Rest], RelativeName, Result, vxworks); join1([$/|Rest], RelativeName, [$., $/|Result], OsType) -> join1(Rest, RelativeName, [$/|Result], OsType); join1([$/|Rest], RelativeName, [$/|Result], OsType) -> join1(Rest, RelativeName, [$/|Result], OsType); join1([], [], Result, OsType) -> maybe_remove_dirsep(Result, OsType); join1([], RelativeName, [$:|Rest], win32) -> join1(RelativeName, [], [$:|Rest], win32); join1([], RelativeName, [$/|Result], OsType) -> join1(RelativeName, [], [$/|Result], OsType); join1([], RelativeName, Result, OsType) -> join1(RelativeName, [], [$/|Result], OsType); join1([[_|_]=List|Rest], RelativeName, Result, OsType) -> join1(List++Rest, RelativeName, Result, OsType); join1([[]|Rest], RelativeName, Result, OsType) -> join1(Rest, RelativeName, Result, OsType); join1([Char|Rest], RelativeName, Result, OsType) when is_integer(Char) -> join1(Rest, RelativeName, [Char|Result], OsType); join1([Atom|Rest], RelativeName, Result, OsType) when is_atom(Atom) -> join1(atom_to_list(Atom)++Rest, RelativeName, Result, OsType). maybe_remove_dirsep([$/, $:, Letter], win32) -> [Letter, $:, $/]; maybe_remove_dirsep([$/], _) -> [$/]; maybe_remove_dirsep([$/|Name], _) -> lists:reverse(Name); maybe_remove_dirsep(Name, _) -> lists:reverse(Name). %% Appends a directory separator and a pathname component to %% a given base directory, which is is assumed to be normalised %% by a previous call to join/{1,2}. append(Dir, Name) -> Dir ++ [$/|Name]. Returns one of absolute , relative or volumerelative . %% %% absolute The pathname refers to a specific file on a specific %% volume. Example: /usr/local/bin/ (on Unix), h:/port_test ( on Windows ) . %% relative The pathname is relative to the current working directory %% on the current volume. Example: foo/bar, ../src volumerelative The pathname is relative to the current working directory %% on the specified volume, or is a specific file on the %% current working volume. (Windows only) %% Example: a:bar.erl, /temp/foo.erl -spec pathtype(name()) -> 'absolute' | 'relative' | 'volumerelative'. pathtype(Atom) when is_atom(Atom) -> pathtype(atom_to_list(Atom)); pathtype(Name) when is_list(Name) -> case os:type() of {unix, _} -> unix_pathtype(Name); {win32, _} -> win32_pathtype(Name); vxworks -> case vxworks_first(Name) of {device, _Rest, _Dev} -> absolute; _ -> relative end; {ose,_} -> unix_pathtype(Name) end. unix_pathtype([$/|_]) -> absolute; unix_pathtype([List|Rest]) when is_list(List) -> unix_pathtype(List++Rest); unix_pathtype([Atom|Rest]) when is_atom(Atom) -> unix_pathtype(atom_to_list(Atom)++Rest); unix_pathtype(_) -> relative. win32_pathtype([List|Rest]) when is_list(List) -> win32_pathtype(List++Rest); win32_pathtype([Atom|Rest]) when is_atom(Atom) -> win32_pathtype(atom_to_list(Atom)++Rest); win32_pathtype([Char, List|Rest]) when is_list(List) -> win32_pathtype([Char|List++Rest]); win32_pathtype([$/, $/|_]) -> absolute; win32_pathtype([$\\, $/|_]) -> absolute; win32_pathtype([$/, $\\|_]) -> absolute; win32_pathtype([$\\, $\\|_]) -> absolute; win32_pathtype([$/|_]) -> volumerelative; win32_pathtype([$\\|_]) -> volumerelative; win32_pathtype([C1, C2, List|Rest]) when is_list(List) -> pathtype([C1, C2|List++Rest]); win32_pathtype([_Letter, $:, $/|_]) -> absolute; win32_pathtype([_Letter, $:, $\\|_]) -> absolute; win32_pathtype([_Letter, $:|_]) -> volumerelative; win32_pathtype(_) -> relative. %% Returns all characters in the filename, except the extension. %% %% Examples: rootname("/jam.src/kalle") -> "/jam.src/kalle" %% rootname("/jam.src/foo.erl") -> "/jam.src/foo" -spec rootname(name()) -> string(). rootname(Name0) -> Name = flatten(Name0), rootname(Name, [], [], major_os_type()). -spec rootname(name(), name()) -> string(). rootname([$/|Rest], Root, Ext, OsType) -> rootname(Rest, [$/]++Ext++Root, [], OsType); rootname([$\\|Rest], Root, Ext, win32) -> rootname(Rest, [$/]++Ext++Root, [], win32); rootname([$\\|Rest], Root, Ext, vxworks) -> rootname(Rest, [$/]++Ext++Root, [], vxworks); rootname([$.|Rest], Root, [], OsType) -> rootname(Rest, Root, ".", OsType); rootname([$.|Rest], Root, Ext, OsType) -> rootname(Rest, Ext++Root, ".", OsType); rootname([Char|Rest], Root, [], OsType) when is_integer(Char) -> rootname(Rest, [Char|Root], [], OsType); rootname([Char|Rest], Root, Ext, OsType) when is_integer(Char) -> rootname(Rest, Root, [Char|Ext], OsType); rootname([], Root, _Ext, _OsType) -> lists:reverse(Root). %% Returns all characters in the filename, except the given extension. %% If the filename has another extension, the complete filename is %% returned. %% %% Examples: rootname("/jam.src/kalle.jam", ".erl") -> "/jam.src/kalle.jam" %% rootname("/jam.src/foo.erl", ".erl") -> "/jam.src/foo" rootname(Name0, Ext0) -> Name = flatten(Name0), Ext = flatten(Ext0), rootname2(Name, Ext, []). rootname2(Ext, Ext, Result) -> lists:reverse(Result); rootname2([], _Ext, Result) -> lists:reverse(Result); rootname2([Char|Rest], Ext, Result) when is_integer(Char) -> rootname2(Rest, Ext, [Char|Result]). %% Returns a list whose elements are the path components in the filename. %% %% Examples: %% split("/usr/local/bin") -> ["/", "usr", "local", "bin"] %% split("foo/bar") -> ["foo", "bar"] %% split("a:\\msdev\\include") -> ["a:/", "msdev", "include"] -spec split(name()) -> [string()]. split(Name0) -> Name = flatten(Name0), case os:type() of {unix, _} -> unix_split(Name); {win32, _} -> win32_split(Name); vxworks -> vxworks_split(Name); {ose,_} -> unix_split(Name) end. If a filename starts with ' [ /\].*[^/\ ] ' ' [ /\ ] . * : ' or ' . * : ' %% that part of the filename is considered a device. %% The rest of the name is interpreted exactly as for win32. %% XXX - dirty solution to make filename:split([]) return the same thing on %% VxWorks as on unix and win32. vxworks_split([]) -> []; vxworks_split(L) -> {_Devicep, Rest, FirstComp} = vxworks_first(L), split(Rest, [], [lists:reverse(FirstComp)], win32). unix_split(Name) -> split(Name, [], unix). win32_split([$\\|Rest]) -> win32_split([$/|Rest]); win32_split([X, $\\|Rest]) when is_integer(X) -> win32_split([X, $/|Rest]); win32_split([X, Y, $\\|Rest]) when is_integer(X), is_integer(Y) -> win32_split([X, Y, $/|Rest]); win32_split([$/, $/|Rest]) -> split(Rest, [], [[$/, $/]]); win32_split([UcLetter, $:|Rest]) when UcLetter >= $A, UcLetter =< $Z -> win32_split([UcLetter+$a-$A, $:|Rest]); win32_split([Letter, $:, $/|Rest]) -> split(Rest, [], [[Letter, $:, $/]], win32); win32_split([Letter, $:|Rest]) -> split(Rest, [], [[Letter, $:]], win32); win32_split(Name) -> split(Name, [], win32). split([$/|Rest], Components, OsType) -> split(Rest, [], [[$/]|Components], OsType); split([$\\|Rest], Components, win32) -> split(Rest, [], [[$/]|Components], win32); split(RelativeName, Components, OsType) -> split(RelativeName, [], Components, OsType). split([$\\|Rest], Comp, Components, win32) -> split([$/|Rest], Comp, Components, win32); split([$/|Rest], [], Components, OsType) -> split(Rest, [], Components, OsType); split([$/|Rest], Comp, Components, OsType) -> split(Rest, [], [lists:reverse(Comp)|Components], OsType); split([Char|Rest], Comp, Components, OsType) when is_integer(Char) -> split(Rest, [Char|Comp], Components, OsType); split([List|Rest], Comp, Components, OsType) when is_list(List) -> split(List++Rest, Comp, Components, OsType); split([], [], Components, _OsType) -> lists:reverse(Components); split([], Comp, Components, OsType) -> split([], [], [lists:reverse(Comp)|Components], OsType). %% Converts a filename to a form accepedt by the command shell and native applications on the current platform . On Windows , forward slashes %% will be converted to backslashes. On all platforms, the name will be normalized as done by . -spec nativename(string()) -> string(). nativename(Name0) -> Name = join([Name0]), %Normalize. case os:type() of {win32, _} -> win32_nativename(Name); _ -> Name end. win32_nativename([$/|Rest]) -> [$\\|win32_nativename(Rest)]; win32_nativename([C|Rest]) -> [C|win32_nativename(Rest)]; win32_nativename([]) -> []. separators() -> case os:type() of {unix, _} -> {false, false}; {win32, _} -> {$\\, $:}; vxworks -> {$\\, false}; {ose,_} -> {false, false} end. %% find_src(Module) -- %% find_src(Module, Rules) -- %% %% Finds the source file name and compilation options for a compiled %% module. The result can be fed to compile:file/2 to compile the %% file again. %% %% The Module argument (which can be a string or an atom) specifies %% either the module name or the path to the source code, with or %% without the ".erl" extension. In either case the module must be known by the code manager , i.e. code : should succeed . %% %% Rules describes how the source directory should be found given %% the directory for the object code. Each rule is on the form %% {BinSuffix, SourceSuffix}, and is interpreted like this: %% If the end of directory name where the object is located matches BinSuffix , then the suffix will be replaced with SourceSuffix %% in the directory name. If the source file in the resulting %% directory, the next rule will be tried. %% %% Returns: {SourceFile, Options} %% %% SourceFile is the absolute path to the source file (but without the ".erl" %% extension) and Options are the necessary options to compile the file with compile : file/2 , but does n't include options like ' report ' or %% 'verbose' that doesn't change the way code is generated. %% The paths in the {outdir, Path} and {i, Path} options are guaranteed %% to be absolute. -type rule() :: {string(), string()}. -type ecode() :: 'non_existing' | 'preloaded' | 'interpreted'. -type option() :: {'i', string()} | {'outdir', string()} | {'d', atom()}. -spec find_src(atom() | string()) -> {string(), [option()]} | {'error', {ecode(), atom()}}. find_src(Mod) -> Default = [{"", ""}, {"ebin", "src"}, {"ebin", "esrc"}], Rules = case application:get_env(kernel, source_search_rules) of undefined -> Default; {ok, []} -> Default; {ok, R} when is_list(R) -> R end, find_src(Mod, Rules). -spec find_src(atom() | string(), [rule()]) -> {string(), [option()]} | {'error', {ecode(), atom()}}. find_src(Mod, Rules) when is_atom(Mod) -> find_src(atom_to_list(Mod), Rules); find_src(File0, Rules) when is_list(File0) -> Mod = list_to_atom(basename(File0, ".erl")), File = rootname(File0, ".erl"), case readable_file(File++".erl") of true -> try_file(File, Mod, Rules); false -> try_file(undefined, Mod, Rules) end. try_file(File, Mod, Rules) -> case code:which(Mod) of Possibly_Rel_Path when is_list(Possibly_Rel_Path) -> {ok, Cwd} = file:get_cwd(), Path = join(Cwd, Possibly_Rel_Path), try_file(File, Path, Mod, Rules); : : ( ) {error, {Ecode, Mod}} end. At this point , the is known to be valid . %% If the source name is not known, find it. %% Then get the compilation options. Returns : { SrcFile , Options } try_file(undefined, ObjFilename, Mod, Rules) -> case get_source_file(ObjFilename, Mod, Rules) of {ok, File} -> try_file(File, ObjFilename, Mod, Rules); Error -> Error end; try_file(Src, _ObjFilename, Mod, _Rules) -> List = Mod:module_info(compile), {value, {options, Options}} = lists:keysearch(options, 1, List), {ok, Cwd} = file:get_cwd(), AbsPath = make_abs_path(Cwd, Src), {AbsPath, filter_options(dirname(AbsPath), Options, [])}. %% Filters the options. %% 1 ) Remove options that have no effect on the generated code , %% such as report and verbose. %% 2 ) The paths found in { i , Path } and Path } are converted %% to absolute paths. When doing this, it is assumed that relatives %% paths are relative to directory where the source code is located. %% This is not necessarily true. It would be safer if the compiler would emit absolute paths in the first place . filter_options(Base, [{outdir, Path}|Rest], Result) -> filter_options(Base, Rest, [{outdir, make_abs_path(Base, Path)}|Result]); filter_options(Base, [{i, Path}|Rest], Result) -> filter_options(Base, Rest, [{i, make_abs_path(Base, Path)}|Result]); filter_options(Base, [Option|Rest], Result) when Option =:= trace -> filter_options(Base, Rest, [Option|Result]); filter_options(Base, [Option|Rest], Result) when Option =:= export_all -> filter_options(Base, Rest, [Option|Result]); filter_options(Base, [Option|Rest], Result) when Option =:= binary -> filter_options(Base, Rest, [Option|Result]); filter_options(Base, [Option|Rest], Result) when Option =:= fast -> filter_options(Base, Rest, [Option|Result]); filter_options(Base, [Tuple|Rest], Result) when element(1, Tuple) =:= d -> filter_options(Base, Rest, [Tuple|Result]); filter_options(Base, [Tuple|Rest], Result) when element(1, Tuple) =:= parse_transform -> filter_options(Base, Rest, [Tuple|Result]); filter_options(Base, [_|Rest], Result) -> filter_options(Base, Rest, Result); filter_options(_Base, [], Result) -> Result. %% Gets the source file given path of object code and module name. get_source_file(Obj, Mod, Rules) -> case catch Mod:module_info(source_file) of {'EXIT', _Reason} -> source_by_rules(dirname(Obj), packages:last(Mod), Rules); File -> {ok, File} end. source_by_rules(Dir, Base, [{From, To}|Rest]) -> case try_rule(Dir, Base, From, To) of {ok, File} -> {ok, File}; error -> source_by_rules(Dir, Base, Rest) end; source_by_rules(_Dir, _Base, []) -> {error, source_file_not_found}. try_rule(Dir, Base, From, To) -> case lists:suffix(From, Dir) of true -> NewDir = lists:sublist(Dir, 1, length(Dir)-length(From))++To, Src = join(NewDir, Base), case readable_file(Src++".erl") of true -> {ok, Src}; false -> error end; false -> error end. readable_file(File) -> case file:read_file_info(File) of {ok, #file_info{type=regular, access=read}} -> true; {ok, #file_info{type=regular, access=read_write}} -> true; _Other -> false end. make_abs_path(BasePath, Path) -> join(BasePath, Path). major_os_type() -> case os:type() of {OsT, _} -> OsT; OsT -> OsT end. Need to take care of the first pathname component separately due to less than good device naming rules . ( i.e. this is specific ... ) The following four all starts with device names %% elrond:/foo -> elrond: %% elrond:\\foo.bar -> elrond: %% /DISK1:foo -> /DISK1: %% /usr/include -> /usr %% This one doesn't: %% foo/bar vxworks_first([]) -> {not_device, [], []}; vxworks_first([$/|T]) -> vxworks_first2(device, T, [$/]); vxworks_first([$\\|T]) -> vxworks_first2(device, T, [$/]); vxworks_first([H|T]) when is_list(H) -> vxworks_first(H++T); vxworks_first([H|T]) -> vxworks_first2(not_device, T, [H]). vxworks_first2(Devicep, [], FirstComp) -> {Devicep, [], FirstComp}; vxworks_first2(Devicep, [$/|T], FirstComp) -> {Devicep, [$/|T], FirstComp}; vxworks_first2(Devicep, [$\\|T], FirstComp) -> {Devicep, [$/|T], FirstComp}; vxworks_first2(_Devicep, [$:|T], FirstComp)-> {device, T, [$:|FirstComp]}; vxworks_first2(Devicep, [H|T], FirstComp) when is_list(H) -> vxworks_first2(Devicep, H++T, FirstComp); vxworks_first2(Devicep, [H|T], FirstComp) -> vxworks_first2(Devicep, T, [H|FirstComp]). %% flatten(List) %% Flatten a list, also accepting atoms. -spec flatten(name()) -> string(). flatten(List) -> do_flatten(List, []). do_flatten([H|T], Tail) when is_list(H) -> do_flatten(H, do_flatten(T, Tail)); do_flatten([H|T], Tail) when is_atom(H) -> atom_to_list(H) ++ do_flatten(T, Tail); do_flatten([H|T], Tail) -> [H|do_flatten(T, Tail)]; do_flatten([], Tail) -> Tail; do_flatten(Atom, Tail) when is_atom(Atom) -> atom_to_list(Atom) ++ flatten(Tail).
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/stdlib/src/filename.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% Purpose: Provides generic manipulation of filenames. Generally, these functions accept filenames in the native format Deep characters lists (as returned by io_lib:format()) are accepted; resulting strings will always be flat. Implementation note: We used to only flatten if the list turned out to be deep. Now that atoms are allowed in deep lists, in most cases we flatten the arguments immediately on function entry as that makes it easier to ensure that the code works. Undocumented and unsupported exports. Converts a relative filename to an absolute filename or the filename itself if it already is an absolute filename Note that no attempt is made to create the most beatiful absolute name since this can give incorrect results on file systems which allows links. Examples: (for Unix) : absname("foo") -> "/usr/local/foo" (for Unix) : absname("../x") -> "/usr/local/../x" (for Unix) : absname("/") -> "/" or we will get slashes inserted into the wrong places. Absolute path on current drive. Relative to current directory on current drive. Relative to current directory on another drive. resulting name is fixed to minimize the length by collapsing ".." directories. For other systems this is just a join/2, but assumes that AbsBase must be absolute and Name must be relative. since a C function call chdir("/erlang/lib/../bin") really sets effect is potentially not so good ... absname_pretty("../bin", "/erlang/lib") -> "/erlang/bin" Returns the part of the filename after the last directory separator, or the filename itself if it has no separators. Examples: basename("foo") -> "foo" basename("/usr/foo") -> "foo" basename("/usr/foo/") -> "foo" (trailing slashes ignored) basename("/") -> [] Returns the last component of the filename, with the given extension stripped. Use this function if you want to remove an extension that might or might not be there. Use rootname(basename(File)) if you want to remove an extension that you know exists, but you are not sure which one it is. Example: basename("~/src/kalle.erl", ".erl") -> "kalle" rootname(basename("xxx.jam")) -> "xxx" rootname(basename("xxx.erl")) -> "xxx" Returns the directory part of a pathname. Example: dirname("/usr/src/kalle.erl") -> "/usr/src", dirname("kalle.erl") -> "." Given a filename string, returns the file extension, including the period. Returns an empty list if there is no extension. Example: extension("foo.erl") -> ".erl" extension("jam.src/kalle") -> "" Joins a list of filenames with directory separators. Internal function to join an absolute name and a relative name. is relative. Appends a directory separator and a pathname component to a given base directory, which is is assumed to be normalised by a previous call to join/{1,2}. absolute The pathname refers to a specific file on a specific volume. Example: /usr/local/bin/ (on Unix), relative The pathname is relative to the current working directory on the current volume. Example: foo/bar, ../src on the specified volume, or is a specific file on the current working volume. (Windows only) Example: a:bar.erl, /temp/foo.erl Returns all characters in the filename, except the extension. Examples: rootname("/jam.src/kalle") -> "/jam.src/kalle" rootname("/jam.src/foo.erl") -> "/jam.src/foo" Returns all characters in the filename, except the given extension. If the filename has another extension, the complete filename is returned. Examples: rootname("/jam.src/kalle.jam", ".erl") -> "/jam.src/kalle.jam" rootname("/jam.src/foo.erl", ".erl") -> "/jam.src/foo" Returns a list whose elements are the path components in the filename. Examples: split("/usr/local/bin") -> ["/", "usr", "local", "bin"] split("foo/bar") -> ["foo", "bar"] split("a:\\msdev\\include") -> ["a:/", "msdev", "include"] that part of the filename is considered a device. The rest of the name is interpreted exactly as for win32. XXX - dirty solution to make filename:split([]) return the same thing on VxWorks as on unix and win32. Converts a filename to a form accepedt by the command shell and native will be converted to backslashes. On all platforms, the Normalize. find_src(Module) -- find_src(Module, Rules) -- Finds the source file name and compilation options for a compiled module. The result can be fed to compile:file/2 to compile the file again. The Module argument (which can be a string or an atom) specifies either the module name or the path to the source code, with or without the ".erl" extension. In either case the module must be Rules describes how the source directory should be found given the directory for the object code. Each rule is on the form {BinSuffix, SourceSuffix}, and is interpreted like this: If the end of directory name where the object is located matches in the directory name. If the source file in the resulting directory, the next rule will be tried. Returns: {SourceFile, Options} SourceFile is the absolute path to the source file (but without the ".erl" extension) and Options are the necessary options to compile the file 'verbose' that doesn't change the way code is generated. The paths in the {outdir, Path} and {i, Path} options are guaranteed to be absolute. If the source name is not known, find it. Then get the compilation options. Filters the options. such as report and verbose. to absolute paths. When doing this, it is assumed that relatives paths are relative to directory where the source code is located. This is not necessarily true. It would be safer if the compiler Gets the source file given path of object code and module name. elrond:/foo -> elrond: elrond:\\foo.bar -> elrond: /DISK1:foo -> /DISK1: /usr/include -> /usr This one doesn't: foo/bar flatten(List) Flatten a list, also accepting atoms.
Copyright Ericsson AB 1997 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(filename). for the current operating system ( Unix or Windows ) . -export([absname/1, absname/2, absname_join/2, basename/1, basename/2, dirname/1, extension/1, join/1, join/2, pathtype/1, rootname/1, rootname/2, split/1, nativename/1]). -export([find_src/1, find_src/2, flatten/1]). -export([append/2]). -include_lib("kernel/include/file.hrl"). Assume ( for UNIX ) current directory " /usr / local " Assume ( for ) current directory " D:/usr / local " ( for ): " ) - > " D:/usr / local / foo " ( for ): absname(" .. /x " ) - > " D:/usr / local/ .. /x " ( for ): absname("/ " ) - > " D:/ " -spec absname(name()) -> string(). absname(Name) -> {ok, Cwd} = file:get_cwd(), absname(Name, Cwd). -spec absname(name(), string()) -> string(). absname(Name, AbsBase) -> case pathtype(Name) of relative -> absname_join(AbsBase, Name); absolute -> We must flatten the filename before passing it into , join([flatten(Name)]); volumerelative -> absname_vr(split(Name), split(AbsBase), AbsBase) end. Handles volumerelative names ( on Windows only ) . absname_vr(["/"|Rest1], [Volume|_], _AbsBase) -> join([Volume|Rest1]); absname_vr([[X, $:]|Rest1], [[X|_]|_], AbsBase) -> absname(join(Rest1), AbsBase); absname_vr([[X, $:]|Name], _, _AbsBase) -> Dcwd = case file:get_cwd([X, $:]) of {ok, Dir} -> Dir; {error, _} -> [X, $:, $/] end, absname(join(Name), Dcwd). Joins a relative filename to an absolute base . For the -spec absname_join(string(), name()) -> string(). absname_join(AbsBase, Name) -> case major_os_type() of vxworks -> absname_pretty(AbsBase, split(Name), lists:reverse(split(AbsBase))); _Else -> join(AbsBase, flatten(Name)) end. Handles absolute filenames for - these are ' pretty - printed ' , cwd to ' / lib/ .. /bin ' which also works , but the long term absname_pretty(" .. / .. / .. / .. " , " /erlang " ) - > " /erlang " absname_pretty(Abspath, Relpath, []) -> AbsBase _ must _ begin with a device name {device, _Rest, Dev} = vxworks_first(Abspath), absname_pretty(Abspath, Relpath, [lists:reverse(Dev)]); absname_pretty(_Abspath, [], AbsBase) -> join(lists:reverse(AbsBase)); absname_pretty(Abspath, [[$.]|Rest], AbsBase) -> absname_pretty(Abspath, Rest, AbsBase); absname_pretty(Abspath, [[$.,$.]|Rest], [_|AbsRest]) -> absname_pretty(Abspath, Rest, AbsRest); absname_pretty(Abspath, [First|Rest], AbsBase) -> absname_pretty(Abspath, Rest, [First|AbsBase]). -spec basename(name()) -> string(). basename(Name0) -> Name = flatten(Name0), {DirSep2, DrvSep} = separators(), basename1(skip_prefix(Name, DrvSep), [], DirSep2). basename1([$/|[]], Tail, DirSep2) -> basename1([], Tail, DirSep2); basename1([$/|Rest], _Tail, DirSep2) -> basename1(Rest, [], DirSep2); basename1([[_|_]=List|Rest], Tail, DirSep2) -> basename1(List++Rest, Tail, DirSep2); basename1([DirSep2|Rest], Tail, DirSep2) when is_integer(DirSep2) -> basename1([$/|Rest], Tail, DirSep2); basename1([Char|Rest], Tail, DirSep2) when is_integer(Char) -> basename1(Rest, [Char|Tail], DirSep2); basename1([], Tail, _DirSep2) -> lists:reverse(Tail). No prefix for unix , but for . case major_os_type() of vxworks -> case vxworks_first(Name) of {device, Rest, _Device} -> Rest; {not_device, _Rest, _First} -> Name end; _Else -> Name end; skip_prefix(Name, DrvSep) -> skip_prefix1(Name, DrvSep). skip_prefix1([L, DrvSep|Name], DrvSep) when is_integer(L) -> Name; skip_prefix1([L], _) when is_integer(L) -> [L]; skip_prefix1(Name, _) -> Name. basename("~/src / kalle.jam " , " .erl " ) - > " kalle.jam " / kalle.old.erl " , " .erl " ) - > " kalle.old " -spec basename(name(), name()) -> string(). basename(Name0, Ext0) -> Name = flatten(Name0), Ext = flatten(Ext0), {DirSep2,DrvSep} = separators(), NoPrefix = skip_prefix(Name, DrvSep), basename(NoPrefix, Ext, [], DirSep2). basename(Ext, Ext, Tail, _DrvSep2) -> lists:reverse(Tail); basename([$/|[]], Ext, Tail, DrvSep2) -> basename([], Ext, Tail, DrvSep2); basename([$/|Rest], Ext, _Tail, DrvSep2) -> basename(Rest, Ext, [], DrvSep2); basename([$\\|Rest], Ext, Tail, DirSep2) when is_integer(DirSep2) -> basename([$/|Rest], Ext, Tail, DirSep2); basename([Char|Rest], Ext, Tail, DrvSep2) when is_integer(Char) -> basename(Rest, Ext, [Char|Tail], DrvSep2); basename([], _Ext, Tail, _DrvSep2) -> lists:reverse(Tail). -spec dirname(name()) -> string(). dirname(Name0) -> Name = flatten(Name0), case os:type() of vxworks -> {Devicep, Restname, FirstComp} = vxworks_first(Name), case Devicep of device -> dirname(Restname, FirstComp, [], separators()); _ -> dirname(Name, [], [], separators()) end; _ -> dirname(Name, [], [], separators()) end. dirname([[_|_]=List|Rest], Dir, File, Seps) -> dirname(List++Rest, Dir, File, Seps); dirname([$/|Rest], Dir, File, Seps) -> dirname(Rest, File++Dir, [$/], Seps); dirname([DirSep|Rest], Dir, File, {DirSep,_}=Seps) when is_integer(DirSep) -> dirname(Rest, File++Dir, [$/], Seps); dirname([Dl,DrvSep|Rest], [], [], {_,DrvSep}=Seps) when is_integer(DrvSep), ((($a =< Dl) and (Dl =< $z)) or (($A =< Dl) and (Dl =< $Z))) -> dirname(Rest, [DrvSep,Dl], [], Seps); dirname([Char|Rest], Dir, File, Seps) when is_integer(Char) -> dirname(Rest, Dir, [Char|File], Seps); dirname([], [], File, _Seps) -> case lists:reverse(File) of [$/|_] -> [$/]; _ -> "." end; dirname([], [$/|Rest], File, Seps) -> dirname([], Rest, File, Seps); dirname([], [DrvSep,Dl], File, {_,DrvSep}) -> case lists:reverse(File) of [$/|_] -> [Dl,DrvSep,$/]; _ -> [Dl,DrvSep] end; dirname([], Dir, _, _) -> lists:reverse(Dir). On Windows : fn : / kalle.erl " ) - > " /usr / src " -spec extension(name()) -> string(). extension(Name0) -> Name = flatten(Name0), extension(Name, [], major_os_type()). extension([$.|Rest], _Result, OsType) -> extension(Rest, [$.], OsType); extension([Char|Rest], [], OsType) when is_integer(Char) -> extension(Rest, [], OsType); extension([$/|Rest], _Result, OsType) -> extension(Rest, [], OsType); extension([$\\|Rest], _Result, win32) -> extension(Rest, [], win32); extension([$\\|Rest], _Result, vxworks) -> extension(Rest, [], vxworks); extension([Char|Rest], Result, OsType) when is_integer(Char) -> extension(Rest, [Char|Result], OsType); extension([], Result, _OsType) -> lists:reverse(Result). -spec join([string()]) -> string(). join([Name1, Name2|Rest]) -> join([join(Name1, Name2)|Rest]); join([Name]) when is_list(Name) -> join1(Name, [], [], major_os_type()); join([Name]) when is_atom(Name) -> join([atom_to_list(Name)]). Joins two filenames with directory separators . -spec join(string(), string()) -> string(). join(Name1, Name2) when is_list(Name1), is_list(Name2) -> OsType = major_os_type(), case pathtype(Name2) of relative -> join1(Name1, Name2, [], OsType); _Other -> join1(Name2, [], [], OsType) end; join(Name1, Name2) when is_atom(Name1) -> join(atom_to_list(Name1), Name2); join(Name1, Name2) when is_atom(Name2) -> join(Name1, atom_to_list(Name2)). It is the responsibility of the caller to ensure that RelativeName join1([UcLetter, $:|Rest], RelativeName, [], win32) when is_integer(UcLetter), UcLetter >= $A, UcLetter =< $Z -> join1(Rest, RelativeName, [$:, UcLetter+$a-$A], win32); join1([$\\|Rest], RelativeName, Result, win32) -> join1([$/|Rest], RelativeName, Result, win32); join1([$\\|Rest], RelativeName, Result, vxworks) -> join1([$/|Rest], RelativeName, Result, vxworks); join1([$/|Rest], RelativeName, [$., $/|Result], OsType) -> join1(Rest, RelativeName, [$/|Result], OsType); join1([$/|Rest], RelativeName, [$/|Result], OsType) -> join1(Rest, RelativeName, [$/|Result], OsType); join1([], [], Result, OsType) -> maybe_remove_dirsep(Result, OsType); join1([], RelativeName, [$:|Rest], win32) -> join1(RelativeName, [], [$:|Rest], win32); join1([], RelativeName, [$/|Result], OsType) -> join1(RelativeName, [], [$/|Result], OsType); join1([], RelativeName, Result, OsType) -> join1(RelativeName, [], [$/|Result], OsType); join1([[_|_]=List|Rest], RelativeName, Result, OsType) -> join1(List++Rest, RelativeName, Result, OsType); join1([[]|Rest], RelativeName, Result, OsType) -> join1(Rest, RelativeName, Result, OsType); join1([Char|Rest], RelativeName, Result, OsType) when is_integer(Char) -> join1(Rest, RelativeName, [Char|Result], OsType); join1([Atom|Rest], RelativeName, Result, OsType) when is_atom(Atom) -> join1(atom_to_list(Atom)++Rest, RelativeName, Result, OsType). maybe_remove_dirsep([$/, $:, Letter], win32) -> [Letter, $:, $/]; maybe_remove_dirsep([$/], _) -> [$/]; maybe_remove_dirsep([$/|Name], _) -> lists:reverse(Name); maybe_remove_dirsep(Name, _) -> lists:reverse(Name). append(Dir, Name) -> Dir ++ [$/|Name]. Returns one of absolute , relative or volumerelative . h:/port_test ( on Windows ) . volumerelative The pathname is relative to the current working directory -spec pathtype(name()) -> 'absolute' | 'relative' | 'volumerelative'. pathtype(Atom) when is_atom(Atom) -> pathtype(atom_to_list(Atom)); pathtype(Name) when is_list(Name) -> case os:type() of {unix, _} -> unix_pathtype(Name); {win32, _} -> win32_pathtype(Name); vxworks -> case vxworks_first(Name) of {device, _Rest, _Dev} -> absolute; _ -> relative end; {ose,_} -> unix_pathtype(Name) end. unix_pathtype([$/|_]) -> absolute; unix_pathtype([List|Rest]) when is_list(List) -> unix_pathtype(List++Rest); unix_pathtype([Atom|Rest]) when is_atom(Atom) -> unix_pathtype(atom_to_list(Atom)++Rest); unix_pathtype(_) -> relative. win32_pathtype([List|Rest]) when is_list(List) -> win32_pathtype(List++Rest); win32_pathtype([Atom|Rest]) when is_atom(Atom) -> win32_pathtype(atom_to_list(Atom)++Rest); win32_pathtype([Char, List|Rest]) when is_list(List) -> win32_pathtype([Char|List++Rest]); win32_pathtype([$/, $/|_]) -> absolute; win32_pathtype([$\\, $/|_]) -> absolute; win32_pathtype([$/, $\\|_]) -> absolute; win32_pathtype([$\\, $\\|_]) -> absolute; win32_pathtype([$/|_]) -> volumerelative; win32_pathtype([$\\|_]) -> volumerelative; win32_pathtype([C1, C2, List|Rest]) when is_list(List) -> pathtype([C1, C2|List++Rest]); win32_pathtype([_Letter, $:, $/|_]) -> absolute; win32_pathtype([_Letter, $:, $\\|_]) -> absolute; win32_pathtype([_Letter, $:|_]) -> volumerelative; win32_pathtype(_) -> relative. -spec rootname(name()) -> string(). rootname(Name0) -> Name = flatten(Name0), rootname(Name, [], [], major_os_type()). -spec rootname(name(), name()) -> string(). rootname([$/|Rest], Root, Ext, OsType) -> rootname(Rest, [$/]++Ext++Root, [], OsType); rootname([$\\|Rest], Root, Ext, win32) -> rootname(Rest, [$/]++Ext++Root, [], win32); rootname([$\\|Rest], Root, Ext, vxworks) -> rootname(Rest, [$/]++Ext++Root, [], vxworks); rootname([$.|Rest], Root, [], OsType) -> rootname(Rest, Root, ".", OsType); rootname([$.|Rest], Root, Ext, OsType) -> rootname(Rest, Ext++Root, ".", OsType); rootname([Char|Rest], Root, [], OsType) when is_integer(Char) -> rootname(Rest, [Char|Root], [], OsType); rootname([Char|Rest], Root, Ext, OsType) when is_integer(Char) -> rootname(Rest, Root, [Char|Ext], OsType); rootname([], Root, _Ext, _OsType) -> lists:reverse(Root). rootname(Name0, Ext0) -> Name = flatten(Name0), Ext = flatten(Ext0), rootname2(Name, Ext, []). rootname2(Ext, Ext, Result) -> lists:reverse(Result); rootname2([], _Ext, Result) -> lists:reverse(Result); rootname2([Char|Rest], Ext, Result) when is_integer(Char) -> rootname2(Rest, Ext, [Char|Result]). -spec split(name()) -> [string()]. split(Name0) -> Name = flatten(Name0), case os:type() of {unix, _} -> unix_split(Name); {win32, _} -> win32_split(Name); vxworks -> vxworks_split(Name); {ose,_} -> unix_split(Name) end. If a filename starts with ' [ /\].*[^/\ ] ' ' [ /\ ] . * : ' or ' . * : ' vxworks_split([]) -> []; vxworks_split(L) -> {_Devicep, Rest, FirstComp} = vxworks_first(L), split(Rest, [], [lists:reverse(FirstComp)], win32). unix_split(Name) -> split(Name, [], unix). win32_split([$\\|Rest]) -> win32_split([$/|Rest]); win32_split([X, $\\|Rest]) when is_integer(X) -> win32_split([X, $/|Rest]); win32_split([X, Y, $\\|Rest]) when is_integer(X), is_integer(Y) -> win32_split([X, Y, $/|Rest]); win32_split([$/, $/|Rest]) -> split(Rest, [], [[$/, $/]]); win32_split([UcLetter, $:|Rest]) when UcLetter >= $A, UcLetter =< $Z -> win32_split([UcLetter+$a-$A, $:|Rest]); win32_split([Letter, $:, $/|Rest]) -> split(Rest, [], [[Letter, $:, $/]], win32); win32_split([Letter, $:|Rest]) -> split(Rest, [], [[Letter, $:]], win32); win32_split(Name) -> split(Name, [], win32). split([$/|Rest], Components, OsType) -> split(Rest, [], [[$/]|Components], OsType); split([$\\|Rest], Components, win32) -> split(Rest, [], [[$/]|Components], win32); split(RelativeName, Components, OsType) -> split(RelativeName, [], Components, OsType). split([$\\|Rest], Comp, Components, win32) -> split([$/|Rest], Comp, Components, win32); split([$/|Rest], [], Components, OsType) -> split(Rest, [], Components, OsType); split([$/|Rest], Comp, Components, OsType) -> split(Rest, [], [lists:reverse(Comp)|Components], OsType); split([Char|Rest], Comp, Components, OsType) when is_integer(Char) -> split(Rest, [Char|Comp], Components, OsType); split([List|Rest], Comp, Components, OsType) when is_list(List) -> split(List++Rest, Comp, Components, OsType); split([], [], Components, _OsType) -> lists:reverse(Components); split([], Comp, Components, OsType) -> split([], [], [lists:reverse(Comp)|Components], OsType). applications on the current platform . On Windows , forward slashes name will be normalized as done by . -spec nativename(string()) -> string(). nativename(Name0) -> case os:type() of {win32, _} -> win32_nativename(Name); _ -> Name end. win32_nativename([$/|Rest]) -> [$\\|win32_nativename(Rest)]; win32_nativename([C|Rest]) -> [C|win32_nativename(Rest)]; win32_nativename([]) -> []. separators() -> case os:type() of {unix, _} -> {false, false}; {win32, _} -> {$\\, $:}; vxworks -> {$\\, false}; {ose,_} -> {false, false} end. known by the code manager , i.e. code : should succeed . BinSuffix , then the suffix will be replaced with SourceSuffix with compile : file/2 , but does n't include options like ' report ' or -type rule() :: {string(), string()}. -type ecode() :: 'non_existing' | 'preloaded' | 'interpreted'. -type option() :: {'i', string()} | {'outdir', string()} | {'d', atom()}. -spec find_src(atom() | string()) -> {string(), [option()]} | {'error', {ecode(), atom()}}. find_src(Mod) -> Default = [{"", ""}, {"ebin", "src"}, {"ebin", "esrc"}], Rules = case application:get_env(kernel, source_search_rules) of undefined -> Default; {ok, []} -> Default; {ok, R} when is_list(R) -> R end, find_src(Mod, Rules). -spec find_src(atom() | string(), [rule()]) -> {string(), [option()]} | {'error', {ecode(), atom()}}. find_src(Mod, Rules) when is_atom(Mod) -> find_src(atom_to_list(Mod), Rules); find_src(File0, Rules) when is_list(File0) -> Mod = list_to_atom(basename(File0, ".erl")), File = rootname(File0, ".erl"), case readable_file(File++".erl") of true -> try_file(File, Mod, Rules); false -> try_file(undefined, Mod, Rules) end. try_file(File, Mod, Rules) -> case code:which(Mod) of Possibly_Rel_Path when is_list(Possibly_Rel_Path) -> {ok, Cwd} = file:get_cwd(), Path = join(Cwd, Possibly_Rel_Path), try_file(File, Path, Mod, Rules); : : ( ) {error, {Ecode, Mod}} end. At this point , the is known to be valid . Returns : { SrcFile , Options } try_file(undefined, ObjFilename, Mod, Rules) -> case get_source_file(ObjFilename, Mod, Rules) of {ok, File} -> try_file(File, ObjFilename, Mod, Rules); Error -> Error end; try_file(Src, _ObjFilename, Mod, _Rules) -> List = Mod:module_info(compile), {value, {options, Options}} = lists:keysearch(options, 1, List), {ok, Cwd} = file:get_cwd(), AbsPath = make_abs_path(Cwd, Src), {AbsPath, filter_options(dirname(AbsPath), Options, [])}. 1 ) Remove options that have no effect on the generated code , 2 ) The paths found in { i , Path } and Path } are converted would emit absolute paths in the first place . filter_options(Base, [{outdir, Path}|Rest], Result) -> filter_options(Base, Rest, [{outdir, make_abs_path(Base, Path)}|Result]); filter_options(Base, [{i, Path}|Rest], Result) -> filter_options(Base, Rest, [{i, make_abs_path(Base, Path)}|Result]); filter_options(Base, [Option|Rest], Result) when Option =:= trace -> filter_options(Base, Rest, [Option|Result]); filter_options(Base, [Option|Rest], Result) when Option =:= export_all -> filter_options(Base, Rest, [Option|Result]); filter_options(Base, [Option|Rest], Result) when Option =:= binary -> filter_options(Base, Rest, [Option|Result]); filter_options(Base, [Option|Rest], Result) when Option =:= fast -> filter_options(Base, Rest, [Option|Result]); filter_options(Base, [Tuple|Rest], Result) when element(1, Tuple) =:= d -> filter_options(Base, Rest, [Tuple|Result]); filter_options(Base, [Tuple|Rest], Result) when element(1, Tuple) =:= parse_transform -> filter_options(Base, Rest, [Tuple|Result]); filter_options(Base, [_|Rest], Result) -> filter_options(Base, Rest, Result); filter_options(_Base, [], Result) -> Result. get_source_file(Obj, Mod, Rules) -> case catch Mod:module_info(source_file) of {'EXIT', _Reason} -> source_by_rules(dirname(Obj), packages:last(Mod), Rules); File -> {ok, File} end. source_by_rules(Dir, Base, [{From, To}|Rest]) -> case try_rule(Dir, Base, From, To) of {ok, File} -> {ok, File}; error -> source_by_rules(Dir, Base, Rest) end; source_by_rules(_Dir, _Base, []) -> {error, source_file_not_found}. try_rule(Dir, Base, From, To) -> case lists:suffix(From, Dir) of true -> NewDir = lists:sublist(Dir, 1, length(Dir)-length(From))++To, Src = join(NewDir, Base), case readable_file(Src++".erl") of true -> {ok, Src}; false -> error end; false -> error end. readable_file(File) -> case file:read_file_info(File) of {ok, #file_info{type=regular, access=read}} -> true; {ok, #file_info{type=regular, access=read_write}} -> true; _Other -> false end. make_abs_path(BasePath, Path) -> join(BasePath, Path). major_os_type() -> case os:type() of {OsT, _} -> OsT; OsT -> OsT end. Need to take care of the first pathname component separately due to less than good device naming rules . ( i.e. this is specific ... ) The following four all starts with device names vxworks_first([]) -> {not_device, [], []}; vxworks_first([$/|T]) -> vxworks_first2(device, T, [$/]); vxworks_first([$\\|T]) -> vxworks_first2(device, T, [$/]); vxworks_first([H|T]) when is_list(H) -> vxworks_first(H++T); vxworks_first([H|T]) -> vxworks_first2(not_device, T, [H]). vxworks_first2(Devicep, [], FirstComp) -> {Devicep, [], FirstComp}; vxworks_first2(Devicep, [$/|T], FirstComp) -> {Devicep, [$/|T], FirstComp}; vxworks_first2(Devicep, [$\\|T], FirstComp) -> {Devicep, [$/|T], FirstComp}; vxworks_first2(_Devicep, [$:|T], FirstComp)-> {device, T, [$:|FirstComp]}; vxworks_first2(Devicep, [H|T], FirstComp) when is_list(H) -> vxworks_first2(Devicep, H++T, FirstComp); vxworks_first2(Devicep, [H|T], FirstComp) -> vxworks_first2(Devicep, T, [H|FirstComp]). -spec flatten(name()) -> string(). flatten(List) -> do_flatten(List, []). do_flatten([H|T], Tail) when is_list(H) -> do_flatten(H, do_flatten(T, Tail)); do_flatten([H|T], Tail) when is_atom(H) -> atom_to_list(H) ++ do_flatten(T, Tail); do_flatten([H|T], Tail) -> [H|do_flatten(T, Tail)]; do_flatten([], Tail) -> Tail; do_flatten(Atom, Tail) when is_atom(Atom) -> atom_to_list(Atom) ++ flatten(Tail).
c4a6cec102d05a1a50bcde16afc59a08d536a54a96ceff381f3dfe106663e479
erleans/pgo
pgo_app.erl
%%%------------------------------------------------------------------- %% @doc pgo application %% @end %%%------------------------------------------------------------------- -module(pgo_app). -behaviour(application). -export([start/2, stop/1]). %%==================================================================== %% API %%==================================================================== start(_StartType, _StartArgs) -> pgo_query_cache:start_link(), Pools = application:get_env(pgo, pools, []), {ok, Pid} = pgo_sup:start_link(), [{ok, _} = pgo_sup:start_child(Name, PoolConfig) || {Name, PoolConfig} <- Pools], {ok, Pid}. %%-------------------------------------------------------------------- stop(_State) -> ok. %%==================================================================== Internal functions %%====================================================================
null
https://raw.githubusercontent.com/erleans/pgo/1c9a0992bc41f2ecd0328fbee1151b75843ac979/src/pgo_app.erl
erlang
------------------------------------------------------------------- @doc pgo application @end ------------------------------------------------------------------- ==================================================================== API ==================================================================== -------------------------------------------------------------------- ==================================================================== ====================================================================
-module(pgo_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> pgo_query_cache:start_link(), Pools = application:get_env(pgo, pools, []), {ok, Pid} = pgo_sup:start_link(), [{ok, _} = pgo_sup:start_child(Name, PoolConfig) || {Name, PoolConfig} <- Pools], {ok, Pid}. stop(_State) -> ok. Internal functions
721304a17d433e0795d5ec295da2304991223c60759aa3c131b4246171459c3b
typelead/intellij-eta
ModuleChunk.hs
module FFI.Org.JetBrains.JPS.ModuleChunk where import P import Java.Collections import FFI.Org.JetBrains.JPS.Model.Module.JpsModule Start org.jetbrains.jps . ModuleChunk data ModuleChunk = ModuleChunk @org.jetbrains.jps.ModuleChunk deriving Class foreign import java unsafe getModule :: Java ModuleChunk (Set JpsModule) End org.jetbrains.jps . ModuleChunk
null
https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/main/eta/FFI/Org/JetBrains/JPS/ModuleChunk.hs
haskell
module FFI.Org.JetBrains.JPS.ModuleChunk where import P import Java.Collections import FFI.Org.JetBrains.JPS.Model.Module.JpsModule Start org.jetbrains.jps . ModuleChunk data ModuleChunk = ModuleChunk @org.jetbrains.jps.ModuleChunk deriving Class foreign import java unsafe getModule :: Java ModuleChunk (Set JpsModule) End org.jetbrains.jps . ModuleChunk
077f4d3cadeca4f63d4b671d3266153ec66c5d7b7287d773d28893b18d877791
bos/llvm
CodeGen.hs
# LANGUAGE ScopedTypeVariables , MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances , TypeSynonymInstances , UndecidableInstances , FlexibleContexts , ScopedTypeVariables , DeriveDataTypeable , Rank2Types # module LLVM.Core.CodeGen( -- * Module creation newModule, newNamedModule, defineModule, createModule, getModuleValues, ModuleValue, castModuleValue, -- * Globals Linkage(..), Visibility(..), -- * Function creation Function, newFunction, newNamedFunction, defineFunction, createFunction, createNamedFunction, setFuncCallConv, addAttributes, FFI.Attribute(..), externFunction, staticFunction, FunctionArgs, FunctionRet, TFunction, -- * Global variable creation Global, newGlobal, newNamedGlobal, defineGlobal, createGlobal, createNamedGlobal, TGlobal, externGlobal, staticGlobal, -- * Values Value(..), ConstValue(..), IsConst(..), valueOf, value, zero, allOnes, undef, createString, createStringNul, withString, withStringNul, constVector, constArray, constStruct, constPackedStruct, -- * Basic blocks BasicBlock(..), newBasicBlock, newNamedBasicBlock, defineBasicBlock, createBasicBlock, createNamedBasicBlock, getCurrentBasicBlock, fromLabel, toLabel, -- * Misc withCurrentBuilder ) where import Data.Typeable import Control.Monad(liftM, when) import Data.Int import Data.Word import Foreign.StablePtr (StablePtr, castStablePtrToPtr) import Foreign.Ptr(minusPtr, nullPtr, castPtr, FunPtr, castFunPtrToPtr) import Foreign.Storable(sizeOf) import Data.TypeLevel hiding (Bool, Eq, (+), (==)) import LLVM.Core.CodeGenMonad import qualified LLVM.FFI.Core as FFI import LLVM.FFI.Core(Linkage(..), Visibility(..)) import qualified LLVM.Core.Util as U import LLVM.Core.Type import LLVM.Core.Data -------------------------------------- -- | Create a new module. newModule :: IO U.Module newModule = newNamedModule "_module" -- XXX should generate a name -- | Create a new explicitely named module. newNamedModule :: String -- ^ module name -> IO U.Module newNamedModule = U.createModule -- | Give the body for a module. defineModule :: U.Module -- ^ module that is defined -> CodeGenModule a -- ^ module body -> IO a defineModule = runCodeGenModule -- | Create a new module with the given body. createModule :: CodeGenModule a -- ^ module body -> IO a createModule cgm = newModule >>= \ m -> defineModule m cgm -------------------------------------- newtype ModuleValue = ModuleValue FFI.ValueRef deriving (Show, Typeable) getModuleValues :: U.Module -> IO [(String, ModuleValue)] getModuleValues = liftM (map (\ (s,p) -> (s, ModuleValue p))) . U.getModuleValues castModuleValue :: forall a . (IsType a) => ModuleValue -> Maybe (Value a) castModuleValue (ModuleValue f) = if U.valueHasType f (typeRef (undefined :: a)) then Just (Value f) else Nothing -------------------------------------- newtype Value a = Value { unValue :: FFI.ValueRef } deriving (Show, Typeable) newtype ConstValue a = ConstValue { unConstValue :: FFI.ValueRef } deriving (Show, Typeable) XXX merge with IsArithmetic ? class IsConst a where constOf :: a -> ConstValue a instance IsConst Bool where constOf = constEnum (typeRef True) instance where constOf = constEnum ( typeRef ( 0::Word8 ) ) -- XXX Unicode instance IsConst Word8 where constOf = constI instance IsConst Word16 where constOf = constI instance IsConst Word32 where constOf = constI instance IsConst Word64 where constOf = constI instance IsConst Int8 where constOf = constI instance IsConst Int16 where constOf = constI instance IsConst Int32 where constOf = constI instance IsConst Int64 where constOf = constI instance IsConst Float where constOf = constF instance IsConst Double where constOf = constF instance IsConst FP128 where constOf = constF constOfPtr :: (IsType a) => a -> Ptr b -> ConstValue a constOfPtr proto p = let ip = p `minusPtr` nullPtr inttoptrC (ConstValue v) = ConstValue $ FFI.constIntToPtr v (typeRef proto) in if sizeOf p == 4 then inttoptrC $ constOf (fromIntegral ip :: Word32) else if sizeOf p == 8 then inttoptrC $ constOf (fromIntegral ip :: Word64) else error "constOf Ptr: pointer size not 4 or 8" -- This instance doesn't belong here, but mutually recursive modules are painful. instance (IsType a) => IsConst (Ptr a) where constOf p = constOfPtr p p instance IsConst (StablePtr a) where constOf p = constOfPtr p (castStablePtrToPtr p) instance (IsPrimitive a, IsConst a, Pos n) => IsConst (Vector n a) where constOf (Vector xs) = constVector (map constOf xs) instance (IsConst a, IsSized a s, Nat n) => IsConst (Array n a) where constOf (Array xs) = constArray (map constOf xs) instance (IsConstFields a) => IsConst (Struct a) where constOf (Struct a) = ConstValue $ U.constStruct (constFieldsOf a) False instance (IsConstFields a) => IsConst (PackedStruct a) where constOf (PackedStruct a) = ConstValue $ U.constStruct (constFieldsOf a) True class IsConstFields a where constFieldsOf :: a -> [FFI.ValueRef] instance (IsConst a, IsConstFields as) => IsConstFields (a, as) where constFieldsOf (a, as) = unConstValue (constOf a) : constFieldsOf as instance IsConstFields () where constFieldsOf _ = [] constEnum :: (Enum a) => FFI.TypeRef -> a -> ConstValue a constEnum t i = ConstValue $ FFI.constInt t (fromIntegral $ fromEnum i) 0 constI :: (IsInteger a, Integral a) => a -> ConstValue a constI i = ConstValue $ FFI.constInt (typeRef i) (fromIntegral i) (fromIntegral $ fromEnum $ isSigned i) constF :: (IsFloating a, Real a) => a -> ConstValue a constF i = ConstValue $ FFI.constReal (typeRef i) (realToFrac i) valueOf :: (IsConst a) => a -> Value a valueOf = value . constOf value :: ConstValue a -> Value a value (ConstValue a) = Value a zero :: forall a . (IsType a) => ConstValue a zero = ConstValue $ FFI.constNull $ typeRef (undefined :: a) allOnes :: forall a . (IsInteger a) => ConstValue a allOnes = ConstValue $ FFI.constAllOnes $ typeRef (undefined :: a) undef :: forall a . (IsType a) => ConstValue a undef = ConstValue $ FFI.getUndef $ typeRef (undefined :: a) createString : : String - > ConstValue ( DynamicArray Word8 ) createString = ConstValue . U.constString constStringNul : : String - > ConstValue ( DynamicArray Word8 ) constStringNul = ConstValue . U.constStringNul createString :: String -> ConstValue (DynamicArray Word8) createString = ConstValue . U.constString constStringNul :: String -> ConstValue (DynamicArray Word8) constStringNul = ConstValue . U.constStringNul -} -------------------------------------- type FunctionRef = FFI.ValueRef -- |A function is simply a pointer to the function. type Function a = Value (Ptr a) -- | Create a new named function. newNamedFunction :: forall a . (IsFunction a) => Linkage -> String -- ^ Function name -> CodeGenModule (Function a) newNamedFunction linkage name = do modul <- getModule let typ = typeRef (undefined :: a) liftIO $ liftM Value $ U.addFunction modul linkage name typ -- | Create a new function. Use 'newNamedFunction' to create a function with external linkage, since -- it needs a known name. newFunction :: forall a . (IsFunction a) => Linkage -> CodeGenModule (Function a) newFunction linkage = genMSym "fun" >>= newNamedFunction linkage -- | Define a function body. The basic block returned by the function is the function entry point. defineFunction :: forall f g r . (FunctionArgs f g r) ^ Function to define ( created by ' newFunction ' ) . -> g -- ^ Function body. -> CodeGenModule () defineFunction (Value fn) body = do bld <- liftIO $ U.createBuilder let body' = do l <- newBasicBlock defineBasicBlock l applyArgs fn body :: CodeGenFunction r () runCodeGenFunction bld fn body' return () -- | Create a new function with the given body. createFunction :: (IsFunction f, FunctionArgs f g r) => Linkage -> g -- ^ Function body. -> CodeGenModule (Function f) createFunction linkage body = do f <- newFunction linkage defineFunction f body return f -- | Create a new function with the given body. createNamedFunction :: (IsFunction f, FunctionArgs f g r) => Linkage -> String -> g -- ^ Function body. -> CodeGenModule (Function f) createNamedFunction linkage name body = do f <- newNamedFunction linkage name defineFunction f body return f -- | Set the calling convention of a function. By default it is the -- C calling convention. setFuncCallConv :: Function a -> FFI.CallingConvention -> CodeGenModule () setFuncCallConv (Value f) cc = do liftIO $ FFI.setFunctionCallConv f (FFI.fromCallingConvention cc) return () -- | Add attributes to a value. Beware, what attributes are allowed depends on -- what kind of value it is. addAttributes :: Value a -> Int -> [FFI.Attribute] -> CodeGenFunction r () addAttributes (Value f) i as = do liftIO $ FFI.addInstrAttribute f (fromIntegral i) (sum $ map FFI.fromAttribute as) -- Convert a function of type f = t1->t2->...-> IO r to -- g = Value t1 -> Value t2 -> ... CodeGenFunction r () class FunctionArgs f g r | f -> g r, g r -> f where apArgs :: Int -> FunctionRef -> g -> FA r applyArgs :: (FunctionArgs f g r) => FunctionRef -> g -> FA r applyArgs = apArgs 0 instance (FunctionArgs b b' r) => FunctionArgs (a -> b) (Value a -> b') r where apArgs n f g = apArgs (n+1) f (g $ Value $ U.getParam f n) -- XXX instances for all IsFirstClass functions, because ca n't deal with the context and the FD type FA a = CodeGenFunction a () instance FunctionArgs (IO Float) (FA Float) Float where apArgs _ _ g = g instance FunctionArgs (IO Double) (FA Double) Double where apArgs _ _ g = g instance FunctionArgs (IO FP128) (FA FP128) FP128 where apArgs _ _ g = g instance (Pos n) => FunctionArgs (IO (IntN n)) (FA (IntN n)) (IntN n) where apArgs _ _ g = g instance (Pos n) => FunctionArgs (IO (WordN n)) (FA (WordN n)) (WordN n) where apArgs _ _ g = g instance FunctionArgs (IO Bool) (FA Bool) Bool where apArgs _ _ g = g instance FunctionArgs (IO Int8) (FA Int8) Int8 where apArgs _ _ g = g instance FunctionArgs (IO Int16) (FA Int16) Int16 where apArgs _ _ g = g instance FunctionArgs (IO Int32) (FA Int32) Int32 where apArgs _ _ g = g instance FunctionArgs (IO Int64) (FA Int64) Int64 where apArgs _ _ g = g instance FunctionArgs (IO Word8) (FA Word8) Word8 where apArgs _ _ g = g instance FunctionArgs (IO Word16) (FA Word16) Word16 where apArgs _ _ g = g instance FunctionArgs (IO Word32) (FA Word32) Word32 where apArgs _ _ g = g instance FunctionArgs (IO Word64) (FA Word64) Word64 where apArgs _ _ g = g instance FunctionArgs (IO ()) (FA ()) () where apArgs _ _ g = g instance (Pos n, IsPrimitive a) => FunctionArgs (IO (Vector n a)) (FA (Vector n a)) (Vector n a) where apArgs _ _ g = g instance StructFields as => FunctionArgs (IO (Struct as)) (FA (Struct as)) (Struct as) where apArgs _ _ g = g instance (IsType a) => FunctionArgs (IO (Ptr a)) (FA (Ptr a)) (Ptr a) where apArgs _ _ g = g instance FunctionArgs (IO (StablePtr a)) (FA (StablePtr a)) (StablePtr a) where apArgs _ _ g = g -- |This class is just to simplify contexts. class (FunctionArgs (IO a) (CodeGenFunction a ()) a) => FunctionRet a instance (FunctionArgs (IO a) (CodeGenFunction a ()) a) => FunctionRet a -------------------------------------- -- |A basic block is a sequence of non-branching instructions, terminated by a control flow instruction. newtype BasicBlock = BasicBlock FFI.BasicBlockRef deriving (Show, Typeable) createBasicBlock :: CodeGenFunction r BasicBlock createBasicBlock = do b <- newBasicBlock defineBasicBlock b return b createNamedBasicBlock :: String -> CodeGenFunction r BasicBlock createNamedBasicBlock name = do b <- newNamedBasicBlock name defineBasicBlock b return b newBasicBlock :: CodeGenFunction r BasicBlock newBasicBlock = genFSym >>= newNamedBasicBlock newNamedBasicBlock :: String -> CodeGenFunction r BasicBlock newNamedBasicBlock name = do fn <- getFunction liftIO $ liftM BasicBlock $ U.appendBasicBlock fn name defineBasicBlock :: BasicBlock -> CodeGenFunction r () defineBasicBlock (BasicBlock l) = do bld <- getBuilder liftIO $ U.positionAtEnd bld l getCurrentBasicBlock :: CodeGenFunction r BasicBlock getCurrentBasicBlock = do bld <- getBuilder liftIO $ liftM BasicBlock $ U.getInsertBlock bld toLabel :: BasicBlock -> Value Label toLabel (BasicBlock ptr) = Value (FFI.basicBlockAsValue ptr) fromLabel :: Value Label -> BasicBlock fromLabel (Value ptr) = BasicBlock (FFI.valueAsBasicBlock ptr) -------------------------------------- --- XXX: the functions in this section (and addGlobalMapping) don't actually use any -- Function state so should really be in the CodeGenModule monad -- | Create a reference to an external function while code generating for a function. If can not resolve its name , then you may try ' staticFunction ' . externFunction :: forall a r . (IsFunction a) => String -> CodeGenFunction r (Function a) externFunction name = externCore name $ fmap (unValue :: Function a -> FFI.ValueRef) . newNamedFunction ExternalLinkage -- | As 'externFunction', but for 'Global's rather than 'Function's externGlobal :: forall a r . (IsType a) => Bool -> String -> CodeGenFunction r (Global a) externGlobal isConst name = externCore name $ fmap (unValue :: Global a -> FFI.ValueRef) . newNamedGlobal isConst ExternalLinkage externCore :: forall a r . String -> (String -> CodeGenModule FFI.ValueRef) -> CodeGenFunction r (Global a) externCore name act = do es <- getExterns case lookup name es of Just f -> return $ Value f Nothing -> do f <- liftCodeGenModule $ act name putExterns ((name, f) : es) return $ Value f | Make an external C function with a fixed address callable from LLVM code . This callback function can also be a function , that was imported like > foreign import ccall " & nextElement " > nextElementFunPtr : : FunPtr ( StablePtr ( IORef [ Word32 ] ) - > IO ) See @examples\/List.hs@. When you only use ' externFunction ' , then can not resolve the name . ( However , I do not know why . ) Thus ' staticFunction ' manages a list of static functions . This list is automatically installed by ' ExecutionEngine.simpleFunction ' and can be manually obtained by ' getGlobalMappings ' and installed by ' ExecutionEngine.addGlobalMappings ' . \"Installing\ " means calling 's @addGlobalMapping@ according to < -with-external-functions-td7769793.html > . Make an external C function with a fixed address callable from LLVM code. This callback function can also be a Haskell function, that was imported like > foreign import ccall "&nextElement" > nextElementFunPtr :: FunPtr (StablePtr (IORef [Word32]) -> IO Word32) See @examples\/List.hs@. When you only use 'externFunction', then LLVM cannot resolve the name. (However, I do not know why.) Thus 'staticFunction' manages a list of static functions. This list is automatically installed by 'ExecutionEngine.simpleFunction' and can be manually obtained by 'getGlobalMappings' and installed by 'ExecutionEngine.addGlobalMappings'. \"Installing\" means calling LLVM's @addGlobalMapping@ according to <-with-external-functions-td7769793.html>. -} staticFunction :: forall f r. (IsFunction f) => FunPtr f -> CodeGenFunction r (Function f) staticFunction func = liftCodeGenModule $ do val <- newNamedFunction ExternalLinkage "" addGlobalMapping (unValue (val :: Function f)) (castFunPtrToPtr func) return val -- | As 'staticFunction', but for 'Global's rather than 'Function's staticGlobal :: forall a r. (IsType a) => Bool -> Ptr a -> CodeGenFunction r (Global a) staticGlobal isConst gbl = liftCodeGenModule $ do val <- newNamedGlobal isConst ExternalLinkage "" addGlobalMapping (unValue (val :: Global a)) (castPtr gbl) return val -------------------------------------- withCurrentBuilder :: (FFI.BuilderRef -> IO a) -> CodeGenFunction r a withCurrentBuilder body = do bld <- getBuilder liftIO $ U.withBuilder bld body -------------------------------------- -- Mark all block terminating instructions. Not used yet. --data Terminate = Terminate -------------------------------------- type Global a = Value (Ptr a) -- | Create a new named global variable. newNamedGlobal :: forall a . (IsType a) => Bool -- ^Constant? -> Linkage -- ^Visibility -> String -- ^Name -> TGlobal a newNamedGlobal isConst linkage name = do modul <- getModule let typ = typeRef (undefined :: a) liftIO $ liftM Value $ do g <- U.addGlobal modul linkage name typ when isConst $ FFI.setGlobalConstant g 1 return g -- | Create a new global variable. newGlobal :: forall a . (IsType a) => Bool -> Linkage -> TGlobal a newGlobal isConst linkage = genMSym "glb" >>= newNamedGlobal isConst linkage -- | Give a global variable a (constant) value. defineGlobal :: Global a -> ConstValue a -> CodeGenModule () defineGlobal (Value g) (ConstValue v) = liftIO $ FFI.setInitializer g v -- | Create and define a global variable. createGlobal :: (IsType a) => Bool -> Linkage -> ConstValue a -> TGlobal a createGlobal isConst linkage con = do g <- newGlobal isConst linkage defineGlobal g con return g -- | Create and define a named global variable. createNamedGlobal :: (IsType a) => Bool -> Linkage -> String -> ConstValue a -> TGlobal a createNamedGlobal isConst linkage name con = do g <- newNamedGlobal isConst linkage name defineGlobal g con return g type TFunction a = CodeGenModule (Function a) type TGlobal a = CodeGenModule (Global a) -- Special string creators {-# DEPRECATED createString "use withString instead" #-} createString :: String -> TGlobal (Array n Word8) createString s = let (cstr, n) = U.constString s in string n cstr # DEPRECATED createStringNul " use instead " # createStringNul :: String -> TGlobal (Array n Word8) createStringNul s = let (cstr, n) = U.constStringNul s in string n cstr class WithString a where withString :: String -> (forall n . Nat n => Global (Array n Word8) -> a) -> a withStringNul :: String -> (forall n . Nat n => Global (Array n Word8) -> a) -> a instance WithString (CodeGenModule a) where withString s act = let (cstr, n) = U.constString s in reifyIntegral n (\tn -> do arr <- string n cstr act (fixArraySize tn arr)) withStringNul s act = let (cstr, n) = U.constStringNul s in reifyIntegral n (\tn -> do arr <- string n cstr act (fixArraySize tn arr)) instance WithString (CodeGenFunction r b) where withString s act = let (cstr, n) = U.constString s in reifyIntegral n (\tn -> do arr <- liftCodeGenModule $ string n cstr act (fixArraySize tn arr)) withStringNul s act = let (cstr, n) = U.constStringNul s in reifyIntegral n (\tn -> do arr <- liftCodeGenModule $ string n cstr act (fixArraySize tn arr)) fixArraySize :: n -> Global (Array n a) -> Global (Array n a) fixArraySize _ = id string :: Int -> FFI.ValueRef -> TGlobal (Array n Word8) string n s = do modul <- getModule name <- genMSym "str" let typ = FFI.arrayType (typeRef (undefined :: Word8)) (fromIntegral n) liftIO $ liftM Value $ do g <- U.addGlobal modul InternalLinkage name typ FFI.setGlobalConstant g 1 FFI.setInitializer g s return g -------------------------------------- |Make a constant vector . Replicates or truncates the list to get length /n/. constVector :: forall a n . (Pos n) => [ConstValue a] -> ConstValue (Vector n a) constVector xs = ConstValue $ U.constVector (toNum (undefined :: n)) [ v | ConstValue v <- xs ] |Make a constant array . Replicates or truncates the list to get length /n/. constArray :: forall a n s . (IsSized a s, Nat n) => [ConstValue a] -> ConstValue (Array n a) constArray xs = ConstValue $ U.constArray (typeRef (undefined :: a)) (toNum (undefined :: n)) [ v | ConstValue v <- xs ] -- |Make a constant struct. constStruct :: (IsConstStruct c a) => c -> ConstValue (Struct a) constStruct struct = ConstValue $ U.constStruct (constValueFieldsOf struct) False -- |Make a constant packed struct. constPackedStruct :: (IsConstStruct c a) => c -> ConstValue (PackedStruct a) constPackedStruct struct = ConstValue $ U.constStruct (constValueFieldsOf struct) True class IsConstStruct c a | a -> c, c -> a where constValueFieldsOf :: c -> [FFI.ValueRef] instance (IsConst a, IsConstStruct cs as) => IsConstStruct (ConstValue a, cs) (a, as) where constValueFieldsOf (a, as) = unConstValue a : constValueFieldsOf as instance IsConstStruct () () where constValueFieldsOf _ = []
null
https://raw.githubusercontent.com/bos/llvm/819b94d048c9d7787ce41cd7c71b84424e894f64/LLVM/Core/CodeGen.hs
haskell
* Module creation * Globals * Function creation * Global variable creation * Values * Basic blocks * Misc ------------------------------------ | Create a new module. XXX should generate a name | Create a new explicitely named module. ^ module name | Give the body for a module. ^ module that is defined ^ module body | Create a new module with the given body. ^ module body ------------------------------------ ------------------------------------ XXX Unicode This instance doesn't belong here, but mutually recursive modules are painful. ------------------------------------ |A function is simply a pointer to the function. | Create a new named function. ^ Function name | Create a new function. Use 'newNamedFunction' to create a function with external linkage, since it needs a known name. | Define a function body. The basic block returned by the function is the function entry point. ^ Function body. | Create a new function with the given body. ^ Function body. | Create a new function with the given body. ^ Function body. | Set the calling convention of a function. By default it is the C calling convention. | Add attributes to a value. Beware, what attributes are allowed depends on what kind of value it is. Convert a function of type f = t1->t2->...-> IO r to g = Value t1 -> Value t2 -> ... CodeGenFunction r () XXX instances for all IsFirstClass functions, |This class is just to simplify contexts. ------------------------------------ |A basic block is a sequence of non-branching instructions, terminated by a control flow instruction. ------------------------------------ - XXX: the functions in this section (and addGlobalMapping) don't actually use any Function state so should really be in the CodeGenModule monad | Create a reference to an external function while code generating for a function. | As 'externFunction', but for 'Global's rather than 'Function's | As 'staticFunction', but for 'Global's rather than 'Function's ------------------------------------ ------------------------------------ Mark all block terminating instructions. Not used yet. data Terminate = Terminate ------------------------------------ | Create a new named global variable. ^Constant? ^Visibility ^Name | Create a new global variable. | Give a global variable a (constant) value. | Create and define a global variable. | Create and define a named global variable. Special string creators # DEPRECATED createString "use withString instead" # ------------------------------------ |Make a constant struct. |Make a constant packed struct.
# LANGUAGE ScopedTypeVariables , MultiParamTypeClasses , FunctionalDependencies , FlexibleInstances , TypeSynonymInstances , UndecidableInstances , FlexibleContexts , ScopedTypeVariables , DeriveDataTypeable , Rank2Types # module LLVM.Core.CodeGen( newModule, newNamedModule, defineModule, createModule, getModuleValues, ModuleValue, castModuleValue, Linkage(..), Visibility(..), Function, newFunction, newNamedFunction, defineFunction, createFunction, createNamedFunction, setFuncCallConv, addAttributes, FFI.Attribute(..), externFunction, staticFunction, FunctionArgs, FunctionRet, TFunction, Global, newGlobal, newNamedGlobal, defineGlobal, createGlobal, createNamedGlobal, TGlobal, externGlobal, staticGlobal, Value(..), ConstValue(..), IsConst(..), valueOf, value, zero, allOnes, undef, createString, createStringNul, withString, withStringNul, constVector, constArray, constStruct, constPackedStruct, BasicBlock(..), newBasicBlock, newNamedBasicBlock, defineBasicBlock, createBasicBlock, createNamedBasicBlock, getCurrentBasicBlock, fromLabel, toLabel, withCurrentBuilder ) where import Data.Typeable import Control.Monad(liftM, when) import Data.Int import Data.Word import Foreign.StablePtr (StablePtr, castStablePtrToPtr) import Foreign.Ptr(minusPtr, nullPtr, castPtr, FunPtr, castFunPtrToPtr) import Foreign.Storable(sizeOf) import Data.TypeLevel hiding (Bool, Eq, (+), (==)) import LLVM.Core.CodeGenMonad import qualified LLVM.FFI.Core as FFI import LLVM.FFI.Core(Linkage(..), Visibility(..)) import qualified LLVM.Core.Util as U import LLVM.Core.Type import LLVM.Core.Data newModule :: IO U.Module -> IO U.Module newNamedModule = U.createModule -> IO a defineModule = runCodeGenModule -> IO a createModule cgm = newModule >>= \ m -> defineModule m cgm newtype ModuleValue = ModuleValue FFI.ValueRef deriving (Show, Typeable) getModuleValues :: U.Module -> IO [(String, ModuleValue)] getModuleValues = liftM (map (\ (s,p) -> (s, ModuleValue p))) . U.getModuleValues castModuleValue :: forall a . (IsType a) => ModuleValue -> Maybe (Value a) castModuleValue (ModuleValue f) = if U.valueHasType f (typeRef (undefined :: a)) then Just (Value f) else Nothing newtype Value a = Value { unValue :: FFI.ValueRef } deriving (Show, Typeable) newtype ConstValue a = ConstValue { unConstValue :: FFI.ValueRef } deriving (Show, Typeable) XXX merge with IsArithmetic ? class IsConst a where constOf :: a -> ConstValue a instance IsConst Bool where constOf = constEnum (typeRef True) instance IsConst Word8 where constOf = constI instance IsConst Word16 where constOf = constI instance IsConst Word32 where constOf = constI instance IsConst Word64 where constOf = constI instance IsConst Int8 where constOf = constI instance IsConst Int16 where constOf = constI instance IsConst Int32 where constOf = constI instance IsConst Int64 where constOf = constI instance IsConst Float where constOf = constF instance IsConst Double where constOf = constF instance IsConst FP128 where constOf = constF constOfPtr :: (IsType a) => a -> Ptr b -> ConstValue a constOfPtr proto p = let ip = p `minusPtr` nullPtr inttoptrC (ConstValue v) = ConstValue $ FFI.constIntToPtr v (typeRef proto) in if sizeOf p == 4 then inttoptrC $ constOf (fromIntegral ip :: Word32) else if sizeOf p == 8 then inttoptrC $ constOf (fromIntegral ip :: Word64) else error "constOf Ptr: pointer size not 4 or 8" instance (IsType a) => IsConst (Ptr a) where constOf p = constOfPtr p p instance IsConst (StablePtr a) where constOf p = constOfPtr p (castStablePtrToPtr p) instance (IsPrimitive a, IsConst a, Pos n) => IsConst (Vector n a) where constOf (Vector xs) = constVector (map constOf xs) instance (IsConst a, IsSized a s, Nat n) => IsConst (Array n a) where constOf (Array xs) = constArray (map constOf xs) instance (IsConstFields a) => IsConst (Struct a) where constOf (Struct a) = ConstValue $ U.constStruct (constFieldsOf a) False instance (IsConstFields a) => IsConst (PackedStruct a) where constOf (PackedStruct a) = ConstValue $ U.constStruct (constFieldsOf a) True class IsConstFields a where constFieldsOf :: a -> [FFI.ValueRef] instance (IsConst a, IsConstFields as) => IsConstFields (a, as) where constFieldsOf (a, as) = unConstValue (constOf a) : constFieldsOf as instance IsConstFields () where constFieldsOf _ = [] constEnum :: (Enum a) => FFI.TypeRef -> a -> ConstValue a constEnum t i = ConstValue $ FFI.constInt t (fromIntegral $ fromEnum i) 0 constI :: (IsInteger a, Integral a) => a -> ConstValue a constI i = ConstValue $ FFI.constInt (typeRef i) (fromIntegral i) (fromIntegral $ fromEnum $ isSigned i) constF :: (IsFloating a, Real a) => a -> ConstValue a constF i = ConstValue $ FFI.constReal (typeRef i) (realToFrac i) valueOf :: (IsConst a) => a -> Value a valueOf = value . constOf value :: ConstValue a -> Value a value (ConstValue a) = Value a zero :: forall a . (IsType a) => ConstValue a zero = ConstValue $ FFI.constNull $ typeRef (undefined :: a) allOnes :: forall a . (IsInteger a) => ConstValue a allOnes = ConstValue $ FFI.constAllOnes $ typeRef (undefined :: a) undef :: forall a . (IsType a) => ConstValue a undef = ConstValue $ FFI.getUndef $ typeRef (undefined :: a) createString : : String - > ConstValue ( DynamicArray Word8 ) createString = ConstValue . U.constString constStringNul : : String - > ConstValue ( DynamicArray Word8 ) constStringNul = ConstValue . U.constStringNul createString :: String -> ConstValue (DynamicArray Word8) createString = ConstValue . U.constString constStringNul :: String -> ConstValue (DynamicArray Word8) constStringNul = ConstValue . U.constStringNul -} type FunctionRef = FFI.ValueRef type Function a = Value (Ptr a) newNamedFunction :: forall a . (IsFunction a) => Linkage -> CodeGenModule (Function a) newNamedFunction linkage name = do modul <- getModule let typ = typeRef (undefined :: a) liftIO $ liftM Value $ U.addFunction modul linkage name typ newFunction :: forall a . (IsFunction a) => Linkage -> CodeGenModule (Function a) newFunction linkage = genMSym "fun" >>= newNamedFunction linkage defineFunction :: forall f g r . (FunctionArgs f g r) ^ Function to define ( created by ' newFunction ' ) . -> CodeGenModule () defineFunction (Value fn) body = do bld <- liftIO $ U.createBuilder let body' = do l <- newBasicBlock defineBasicBlock l applyArgs fn body :: CodeGenFunction r () runCodeGenFunction bld fn body' return () createFunction :: (IsFunction f, FunctionArgs f g r) => Linkage -> CodeGenModule (Function f) createFunction linkage body = do f <- newFunction linkage defineFunction f body return f createNamedFunction :: (IsFunction f, FunctionArgs f g r) => Linkage -> String -> CodeGenModule (Function f) createNamedFunction linkage name body = do f <- newNamedFunction linkage name defineFunction f body return f setFuncCallConv :: Function a -> FFI.CallingConvention -> CodeGenModule () setFuncCallConv (Value f) cc = do liftIO $ FFI.setFunctionCallConv f (FFI.fromCallingConvention cc) return () addAttributes :: Value a -> Int -> [FFI.Attribute] -> CodeGenFunction r () addAttributes (Value f) i as = do liftIO $ FFI.addInstrAttribute f (fromIntegral i) (sum $ map FFI.fromAttribute as) class FunctionArgs f g r | f -> g r, g r -> f where apArgs :: Int -> FunctionRef -> g -> FA r applyArgs :: (FunctionArgs f g r) => FunctionRef -> g -> FA r applyArgs = apArgs 0 instance (FunctionArgs b b' r) => FunctionArgs (a -> b) (Value a -> b') r where apArgs n f g = apArgs (n+1) f (g $ Value $ U.getParam f n) because ca n't deal with the context and the FD type FA a = CodeGenFunction a () instance FunctionArgs (IO Float) (FA Float) Float where apArgs _ _ g = g instance FunctionArgs (IO Double) (FA Double) Double where apArgs _ _ g = g instance FunctionArgs (IO FP128) (FA FP128) FP128 where apArgs _ _ g = g instance (Pos n) => FunctionArgs (IO (IntN n)) (FA (IntN n)) (IntN n) where apArgs _ _ g = g instance (Pos n) => FunctionArgs (IO (WordN n)) (FA (WordN n)) (WordN n) where apArgs _ _ g = g instance FunctionArgs (IO Bool) (FA Bool) Bool where apArgs _ _ g = g instance FunctionArgs (IO Int8) (FA Int8) Int8 where apArgs _ _ g = g instance FunctionArgs (IO Int16) (FA Int16) Int16 where apArgs _ _ g = g instance FunctionArgs (IO Int32) (FA Int32) Int32 where apArgs _ _ g = g instance FunctionArgs (IO Int64) (FA Int64) Int64 where apArgs _ _ g = g instance FunctionArgs (IO Word8) (FA Word8) Word8 where apArgs _ _ g = g instance FunctionArgs (IO Word16) (FA Word16) Word16 where apArgs _ _ g = g instance FunctionArgs (IO Word32) (FA Word32) Word32 where apArgs _ _ g = g instance FunctionArgs (IO Word64) (FA Word64) Word64 where apArgs _ _ g = g instance FunctionArgs (IO ()) (FA ()) () where apArgs _ _ g = g instance (Pos n, IsPrimitive a) => FunctionArgs (IO (Vector n a)) (FA (Vector n a)) (Vector n a) where apArgs _ _ g = g instance StructFields as => FunctionArgs (IO (Struct as)) (FA (Struct as)) (Struct as) where apArgs _ _ g = g instance (IsType a) => FunctionArgs (IO (Ptr a)) (FA (Ptr a)) (Ptr a) where apArgs _ _ g = g instance FunctionArgs (IO (StablePtr a)) (FA (StablePtr a)) (StablePtr a) where apArgs _ _ g = g class (FunctionArgs (IO a) (CodeGenFunction a ()) a) => FunctionRet a instance (FunctionArgs (IO a) (CodeGenFunction a ()) a) => FunctionRet a newtype BasicBlock = BasicBlock FFI.BasicBlockRef deriving (Show, Typeable) createBasicBlock :: CodeGenFunction r BasicBlock createBasicBlock = do b <- newBasicBlock defineBasicBlock b return b createNamedBasicBlock :: String -> CodeGenFunction r BasicBlock createNamedBasicBlock name = do b <- newNamedBasicBlock name defineBasicBlock b return b newBasicBlock :: CodeGenFunction r BasicBlock newBasicBlock = genFSym >>= newNamedBasicBlock newNamedBasicBlock :: String -> CodeGenFunction r BasicBlock newNamedBasicBlock name = do fn <- getFunction liftIO $ liftM BasicBlock $ U.appendBasicBlock fn name defineBasicBlock :: BasicBlock -> CodeGenFunction r () defineBasicBlock (BasicBlock l) = do bld <- getBuilder liftIO $ U.positionAtEnd bld l getCurrentBasicBlock :: CodeGenFunction r BasicBlock getCurrentBasicBlock = do bld <- getBuilder liftIO $ liftM BasicBlock $ U.getInsertBlock bld toLabel :: BasicBlock -> Value Label toLabel (BasicBlock ptr) = Value (FFI.basicBlockAsValue ptr) fromLabel :: Value Label -> BasicBlock fromLabel (Value ptr) = BasicBlock (FFI.valueAsBasicBlock ptr) If can not resolve its name , then you may try ' staticFunction ' . externFunction :: forall a r . (IsFunction a) => String -> CodeGenFunction r (Function a) externFunction name = externCore name $ fmap (unValue :: Function a -> FFI.ValueRef) . newNamedFunction ExternalLinkage externGlobal :: forall a r . (IsType a) => Bool -> String -> CodeGenFunction r (Global a) externGlobal isConst name = externCore name $ fmap (unValue :: Global a -> FFI.ValueRef) . newNamedGlobal isConst ExternalLinkage externCore :: forall a r . String -> (String -> CodeGenModule FFI.ValueRef) -> CodeGenFunction r (Global a) externCore name act = do es <- getExterns case lookup name es of Just f -> return $ Value f Nothing -> do f <- liftCodeGenModule $ act name putExterns ((name, f) : es) return $ Value f | Make an external C function with a fixed address callable from LLVM code . This callback function can also be a function , that was imported like > foreign import ccall " & nextElement " > nextElementFunPtr : : FunPtr ( StablePtr ( IORef [ Word32 ] ) - > IO ) See @examples\/List.hs@. When you only use ' externFunction ' , then can not resolve the name . ( However , I do not know why . ) Thus ' staticFunction ' manages a list of static functions . This list is automatically installed by ' ExecutionEngine.simpleFunction ' and can be manually obtained by ' getGlobalMappings ' and installed by ' ExecutionEngine.addGlobalMappings ' . \"Installing\ " means calling 's @addGlobalMapping@ according to < -with-external-functions-td7769793.html > . Make an external C function with a fixed address callable from LLVM code. This callback function can also be a Haskell function, that was imported like > foreign import ccall "&nextElement" > nextElementFunPtr :: FunPtr (StablePtr (IORef [Word32]) -> IO Word32) See @examples\/List.hs@. When you only use 'externFunction', then LLVM cannot resolve the name. (However, I do not know why.) Thus 'staticFunction' manages a list of static functions. This list is automatically installed by 'ExecutionEngine.simpleFunction' and can be manually obtained by 'getGlobalMappings' and installed by 'ExecutionEngine.addGlobalMappings'. \"Installing\" means calling LLVM's @addGlobalMapping@ according to <-with-external-functions-td7769793.html>. -} staticFunction :: forall f r. (IsFunction f) => FunPtr f -> CodeGenFunction r (Function f) staticFunction func = liftCodeGenModule $ do val <- newNamedFunction ExternalLinkage "" addGlobalMapping (unValue (val :: Function f)) (castFunPtrToPtr func) return val staticGlobal :: forall a r. (IsType a) => Bool -> Ptr a -> CodeGenFunction r (Global a) staticGlobal isConst gbl = liftCodeGenModule $ do val <- newNamedGlobal isConst ExternalLinkage "" addGlobalMapping (unValue (val :: Global a)) (castPtr gbl) return val withCurrentBuilder :: (FFI.BuilderRef -> IO a) -> CodeGenFunction r a withCurrentBuilder body = do bld <- getBuilder liftIO $ U.withBuilder bld body type Global a = Value (Ptr a) newNamedGlobal :: forall a . (IsType a) -> TGlobal a newNamedGlobal isConst linkage name = do modul <- getModule let typ = typeRef (undefined :: a) liftIO $ liftM Value $ do g <- U.addGlobal modul linkage name typ when isConst $ FFI.setGlobalConstant g 1 return g newGlobal :: forall a . (IsType a) => Bool -> Linkage -> TGlobal a newGlobal isConst linkage = genMSym "glb" >>= newNamedGlobal isConst linkage defineGlobal :: Global a -> ConstValue a -> CodeGenModule () defineGlobal (Value g) (ConstValue v) = liftIO $ FFI.setInitializer g v createGlobal :: (IsType a) => Bool -> Linkage -> ConstValue a -> TGlobal a createGlobal isConst linkage con = do g <- newGlobal isConst linkage defineGlobal g con return g createNamedGlobal :: (IsType a) => Bool -> Linkage -> String -> ConstValue a -> TGlobal a createNamedGlobal isConst linkage name con = do g <- newNamedGlobal isConst linkage name defineGlobal g con return g type TFunction a = CodeGenModule (Function a) type TGlobal a = CodeGenModule (Global a) createString :: String -> TGlobal (Array n Word8) createString s = let (cstr, n) = U.constString s in string n cstr # DEPRECATED createStringNul " use instead " # createStringNul :: String -> TGlobal (Array n Word8) createStringNul s = let (cstr, n) = U.constStringNul s in string n cstr class WithString a where withString :: String -> (forall n . Nat n => Global (Array n Word8) -> a) -> a withStringNul :: String -> (forall n . Nat n => Global (Array n Word8) -> a) -> a instance WithString (CodeGenModule a) where withString s act = let (cstr, n) = U.constString s in reifyIntegral n (\tn -> do arr <- string n cstr act (fixArraySize tn arr)) withStringNul s act = let (cstr, n) = U.constStringNul s in reifyIntegral n (\tn -> do arr <- string n cstr act (fixArraySize tn arr)) instance WithString (CodeGenFunction r b) where withString s act = let (cstr, n) = U.constString s in reifyIntegral n (\tn -> do arr <- liftCodeGenModule $ string n cstr act (fixArraySize tn arr)) withStringNul s act = let (cstr, n) = U.constStringNul s in reifyIntegral n (\tn -> do arr <- liftCodeGenModule $ string n cstr act (fixArraySize tn arr)) fixArraySize :: n -> Global (Array n a) -> Global (Array n a) fixArraySize _ = id string :: Int -> FFI.ValueRef -> TGlobal (Array n Word8) string n s = do modul <- getModule name <- genMSym "str" let typ = FFI.arrayType (typeRef (undefined :: Word8)) (fromIntegral n) liftIO $ liftM Value $ do g <- U.addGlobal modul InternalLinkage name typ FFI.setGlobalConstant g 1 FFI.setInitializer g s return g |Make a constant vector . Replicates or truncates the list to get length /n/. constVector :: forall a n . (Pos n) => [ConstValue a] -> ConstValue (Vector n a) constVector xs = ConstValue $ U.constVector (toNum (undefined :: n)) [ v | ConstValue v <- xs ] |Make a constant array . Replicates or truncates the list to get length /n/. constArray :: forall a n s . (IsSized a s, Nat n) => [ConstValue a] -> ConstValue (Array n a) constArray xs = ConstValue $ U.constArray (typeRef (undefined :: a)) (toNum (undefined :: n)) [ v | ConstValue v <- xs ] constStruct :: (IsConstStruct c a) => c -> ConstValue (Struct a) constStruct struct = ConstValue $ U.constStruct (constValueFieldsOf struct) False constPackedStruct :: (IsConstStruct c a) => c -> ConstValue (PackedStruct a) constPackedStruct struct = ConstValue $ U.constStruct (constValueFieldsOf struct) True class IsConstStruct c a | a -> c, c -> a where constValueFieldsOf :: c -> [FFI.ValueRef] instance (IsConst a, IsConstStruct cs as) => IsConstStruct (ConstValue a, cs) (a, as) where constValueFieldsOf (a, as) = unConstValue a : constValueFieldsOf as instance IsConstStruct () () where constValueFieldsOf _ = []
ca287622b5fa43a1928b45e78b6447cc84cfb67c60ba30c93bce4456ce22b431
skynet-gh/skylobby
flag_icon_test.clj
(ns skylobby.fx.flag-icon-test (:require [clojure.test :refer [deftest is]] [skylobby.fx.flag-icon :as fx.flag-icon])) (set! *warn-on-reflection* true) (deftest flag-icon (is (map? (fx.flag-icon/flag-icon {:country-code "US"}))))
null
https://raw.githubusercontent.com/skynet-gh/skylobby/7895ad30d992b790ffbffcd2d7be2cf17f8df794/test/clj/skylobby/fx/flag_icon_test.clj
clojure
(ns skylobby.fx.flag-icon-test (:require [clojure.test :refer [deftest is]] [skylobby.fx.flag-icon :as fx.flag-icon])) (set! *warn-on-reflection* true) (deftest flag-icon (is (map? (fx.flag-icon/flag-icon {:country-code "US"}))))
92b5bcf653d9275ee826ff5efc85501298d917a9bf7eeaba7ec74dc9b473cca5
metaocaml/ber-metaocaml
inner.ml
type a = int
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/tool-ocamldoc-open/inner.ml
ocaml
type a = int
0e7b3bdb8878a57b7cfa4d4285cf21f2e9a70c57ef7622f1c7f8385233e9edce
datacraft-dsc/starfish-clj
demo.clj
(ns starfish.samples.demo (:use [starfish.core :refer :all]) (:require [clojure.repl :refer :all] [clojure.pprint :refer [pprint]] [clojure.data.json :as json ]) (:import [sg.dex.starfish.util DDOUtil JSON])) (fn [] ;; Quick hack to compile this file without executing on load ;; ====================================================================================== ;; BASIC ASSETS ;; Let's talk about assets ;; create a new asset (def as1 (memory-asset ;; type of asset to construct "This is a test") ;; content (as a String)) ) ;; display the metadata (pprint (metadata as1)) ;; validate the content hash (digest "This is a test") ;; Print the content (println (to-string (content as1))) ;; ====================================================================================== ;; USING REMOTE AGENTS Agents are remote services providing asset and capabilities to the Ocean ecosystem (def my-agent (let [did (random-did) ddostring (create-ddo ":8080")] (remote-agent did ddostring "Aladdin" "OpenSesame"))) ;; agents have a DID (str (did my-agent)) ;; Get an asset (def as2 (get-asset my-agent "4b95d8956ab9a503540d62ac7db2fbcaa99f7f78b2d4f4d8edd6d9d19d750403")) ;; assets also have a DID, starting with the DID of the agent (str (did as2)) ;; Upload an asset (def as3 (upload my-agent as1)) (get-asset my-agent (asset-id as3)) ;; ====================================================================================== Operations ;; define a new operation (def op (create-operation [:input] (fn [{input :input}] {:output (memory-asset (str (count (to-string input))))}))) (pprint (metadata op)) ;; compute the result, getting the output asset from the result map (def as4 (:output (invoke-result op {:input as1}))) ;; see the reuslt (println (to-string (content as4))) ;; ====================================================================================== Register new asset on our agent ;; upload the result of our invoke (def as5 (upload my-agent (memory-asset "Remote test asset data"))) ;; asset now has a full remote DID (str (did as5)) ;; double check remote content (println (to-string (content as5))) ;; ====================================================================================== ;;invoke a remote operation (def invkres (let [oper (get-asset my-agent "f994e155382044caedd76bd2af2f8a1244aa31ad9818b955848032c8ecb9dabb") res (get-result (invoke oper {"input" "Supercalifragilisticexpialidocious"}))] res)) ;;response is a map (-> invkres) )
null
https://raw.githubusercontent.com/datacraft-dsc/starfish-clj/d199c0f7c96f5dd6941507556bc3070396eb3a04/src/test/clojure/starfish/samples/demo.clj
clojure
Quick hack to compile this file without executing on load ====================================================================================== BASIC ASSETS Let's talk about assets create a new asset type of asset to construct content (as a String)) display the metadata validate the content hash Print the content ====================================================================================== USING REMOTE AGENTS agents have a DID Get an asset assets also have a DID, starting with the DID of the agent Upload an asset ====================================================================================== define a new operation compute the result, getting the output asset from the result map see the reuslt ====================================================================================== upload the result of our invoke asset now has a full remote DID double check remote content ====================================================================================== invoke a remote operation response is a map
(ns starfish.samples.demo (:use [starfish.core :refer :all]) (:require [clojure.repl :refer :all] [clojure.pprint :refer [pprint]] [clojure.data.json :as json ]) (:import [sg.dex.starfish.util DDOUtil JSON])) ) (pprint (metadata as1)) (digest "This is a test") (println (to-string (content as1))) Agents are remote services providing asset and capabilities to the Ocean ecosystem (def my-agent (let [did (random-did) ddostring (create-ddo ":8080")] (remote-agent did ddostring "Aladdin" "OpenSesame"))) (str (did my-agent)) (def as2 (get-asset my-agent "4b95d8956ab9a503540d62ac7db2fbcaa99f7f78b2d4f4d8edd6d9d19d750403")) (str (did as2)) (def as3 (upload my-agent as1)) (get-asset my-agent (asset-id as3)) Operations (def op (create-operation [:input] (fn [{input :input}] {:output (memory-asset (str (count (to-string input))))}))) (pprint (metadata op)) (def as4 (:output (invoke-result op {:input as1}))) (println (to-string (content as4))) Register new asset on our agent (def as5 (upload my-agent (memory-asset "Remote test asset data"))) (str (did as5)) (println (to-string (content as5))) (def invkres (let [oper (get-asset my-agent "f994e155382044caedd76bd2af2f8a1244aa31ad9818b955848032c8ecb9dabb") res (get-result (invoke oper {"input" "Supercalifragilisticexpialidocious"}))] res)) (-> invkres) )
20b7e95d01317dea29779d8fe6b12ccd55bd0da5b91f44db174adf94630e077b
CompSciCabal/SMRTYPRTY
exercises_1.3.1.rkt
#lang racket Provided from SICP (define (gcd m n) (cond ((< m n) (gcd n m)) ((= n 0) m) (else (gcd n (remainder m n))))) (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) (define (even? x) (= (remainder x 2) 0)) (define (square x) (* x x)) (define (cube x) (* x x x)) (define (inc x) (+ x 1)) (define (identity x) x) From section 1.2 Exercises (define (fermat-test n) (define (try-it a) (= (expmod a n n) a)) (try-it (+ 1 (random (- n 1))))) (define (fast-prime? n times) (cond ((= times 0) true) ((= n 1) false) ((fermat-test n) (fast-prime? n (- times 1))) (else false))) (define (prime? n) (fast-prime? n 100)) ;; fast-expt p45 (define (fast-expt b n) (cond ((= n 0) 1) ((even? n) (square (fast-expt b (/ n 2)))) (else (* b (fast-expt b (- n 1)))))) (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (displayln "exercise 1.29") (define (simpsons-integral fn lower upper steps) (define h (/ (- upper lower) steps)) (define (yk k) (fn (+ lower (* k h)))) (define (multfor k) (cond [(or (= k 0) (= k steps)) 1] [(= (remainder k 2) 1) 4] [else 2])) (define (simpson-term k) (* (multfor k) (yk k))) (* (/ h 3) (sum simpson-term 0 inc steps))) (simpsons-integral cube 0 1 100) (simpsons-integral cube 0 1 1000) (displayln "exercise 1.30") (define (tail-rec-sum term a next b) (define (iter a result) (if (> a b) result (iter (next a) (+ (term a) result)))) (iter a 0)) (displayln "exercise 1.31 a.") (define (product term a next b) (if (> a b) 1 (* (term a) (product term (next a) next b)))) (define (factorial n) (product identity 1 inc n)) (factorial 3) (factorial 10) (define (pi-term x) (if (even? x) (/ (+ x 2) (+ x 1)) (/ (+ x 1) (+ x 2)))) (* (product pi-term 1 inc 6) 4) (* (product pi-term 1 inc 100) 4) (displayln "exercise 1.31 b.") (define (tail-rec-product term a next b) (define (iter a result) (if (> a b) result (iter (next a) (* (term a) result)))) (iter a 1)) (* (tail-rec-product pi-term 1 inc 6) 4) (* (tail-rec-product pi-term 1 inc 100) 4) (displayln "exercise 1.32 a.") (define (accumulate combiner null-value term a next b) (if (> a b) null-value (combiner (term a) (accumulate combiner null-value term (next a) next b)))) (define (accum-sum term a next b) (accumulate + 0 term a next b)) (define (accum-prod term a next b) (accumulate * 1 term a next b)) (displayln "1.32 a. before redifining sum") (simpsons-integral cube 0 1 100) (simpsons-integral cube 0 1 1000) (displayln "1.32 a. after redifining sum") (set! sum accum-sum) (simpsons-integral cube 0 1 100) (simpsons-integral cube 0 1 1000) (displayln "1.32 a. before redifining product") (factorial 3) (factorial 10) (displayln "1.32 a. after redifining product") (set! product accum-prod) (factorial 3) (factorial 10) (displayln "1.32 b.") (define (tail-rec-accum combiner term a next b result) (if (> a b) result (tail-rec-accum combiner term (next a) next b (combiner (term a) result)))) (define (tr-accum-prod term a next b) (tail-rec-accum * term a next b 1)) (set! product tr-accum-prod) (factorial 3) (factorial 10) (displayln "exercise 1.33") (define (filtered-accumulate combiner filterfn null-value term a next b) (define (no-more?) (> a b)) (if (no-more?) null-value (combiner (if (filterfn a) (term a) null-value) (filtered-accumulate combiner filterfn null-value term (next a) next b)))) (displayln "exercise 1.33 a.") (define (sum-of-square-primes a b) (filtered-accumulate + prime? 0 square a inc b)) (sum-of-square-primes 1 5) (displayln "exercise 1.33 b.") (define (relative-prime? m n) (= (gcd m n) 1)) (define (product-of-relative-primes n) (define (filter x) (relative-prime? x n)) (filtered-accumulate * filter 1 identity 1 inc n)) (product-of-relative-primes 10)
null
https://raw.githubusercontent.com/CompSciCabal/SMRTYPRTY/4a5550789c997c20fb7256b81469de1f1fce3514/sicp/v2/1.3/csaunders/exercises_1.3.1.rkt
racket
fast-expt p45
#lang racket Provided from SICP (define (gcd m n) (cond ((< m n) (gcd n m)) ((= n 0) m) (else (gcd n (remainder m n))))) (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) (define (even? x) (= (remainder x 2) 0)) (define (square x) (* x x)) (define (cube x) (* x x x)) (define (inc x) (+ x 1)) (define (identity x) x) From section 1.2 Exercises (define (fermat-test n) (define (try-it a) (= (expmod a n n) a)) (try-it (+ 1 (random (- n 1))))) (define (fast-prime? n times) (cond ((= times 0) true) ((= n 1) false) ((fermat-test n) (fast-prime? n (- times 1))) (else false))) (define (prime? n) (fast-prime? n 100)) (define (fast-expt b n) (cond ((= n 0) 1) ((even? n) (square (fast-expt b (/ n 2)))) (else (* b (fast-expt b (- n 1)))))) (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m)))) (displayln "exercise 1.29") (define (simpsons-integral fn lower upper steps) (define h (/ (- upper lower) steps)) (define (yk k) (fn (+ lower (* k h)))) (define (multfor k) (cond [(or (= k 0) (= k steps)) 1] [(= (remainder k 2) 1) 4] [else 2])) (define (simpson-term k) (* (multfor k) (yk k))) (* (/ h 3) (sum simpson-term 0 inc steps))) (simpsons-integral cube 0 1 100) (simpsons-integral cube 0 1 1000) (displayln "exercise 1.30") (define (tail-rec-sum term a next b) (define (iter a result) (if (> a b) result (iter (next a) (+ (term a) result)))) (iter a 0)) (displayln "exercise 1.31 a.") (define (product term a next b) (if (> a b) 1 (* (term a) (product term (next a) next b)))) (define (factorial n) (product identity 1 inc n)) (factorial 3) (factorial 10) (define (pi-term x) (if (even? x) (/ (+ x 2) (+ x 1)) (/ (+ x 1) (+ x 2)))) (* (product pi-term 1 inc 6) 4) (* (product pi-term 1 inc 100) 4) (displayln "exercise 1.31 b.") (define (tail-rec-product term a next b) (define (iter a result) (if (> a b) result (iter (next a) (* (term a) result)))) (iter a 1)) (* (tail-rec-product pi-term 1 inc 6) 4) (* (tail-rec-product pi-term 1 inc 100) 4) (displayln "exercise 1.32 a.") (define (accumulate combiner null-value term a next b) (if (> a b) null-value (combiner (term a) (accumulate combiner null-value term (next a) next b)))) (define (accum-sum term a next b) (accumulate + 0 term a next b)) (define (accum-prod term a next b) (accumulate * 1 term a next b)) (displayln "1.32 a. before redifining sum") (simpsons-integral cube 0 1 100) (simpsons-integral cube 0 1 1000) (displayln "1.32 a. after redifining sum") (set! sum accum-sum) (simpsons-integral cube 0 1 100) (simpsons-integral cube 0 1 1000) (displayln "1.32 a. before redifining product") (factorial 3) (factorial 10) (displayln "1.32 a. after redifining product") (set! product accum-prod) (factorial 3) (factorial 10) (displayln "1.32 b.") (define (tail-rec-accum combiner term a next b result) (if (> a b) result (tail-rec-accum combiner term (next a) next b (combiner (term a) result)))) (define (tr-accum-prod term a next b) (tail-rec-accum * term a next b 1)) (set! product tr-accum-prod) (factorial 3) (factorial 10) (displayln "exercise 1.33") (define (filtered-accumulate combiner filterfn null-value term a next b) (define (no-more?) (> a b)) (if (no-more?) null-value (combiner (if (filterfn a) (term a) null-value) (filtered-accumulate combiner filterfn null-value term (next a) next b)))) (displayln "exercise 1.33 a.") (define (sum-of-square-primes a b) (filtered-accumulate + prime? 0 square a inc b)) (sum-of-square-primes 1 5) (displayln "exercise 1.33 b.") (define (relative-prime? m n) (= (gcd m n) 1)) (define (product-of-relative-primes n) (define (filter x) (relative-prime? x n)) (filtered-accumulate * filter 1 identity 1 inc n)) (product-of-relative-primes 10)
a1a374bb4f8d39b272a81d9a2be966dc636fc7be01ab47b656de989923c3bad8
cljfx/cljfx
lighting.clj
(ns cljfx.fx.lighting "Part of a public API" (:require [cljfx.composite :as composite] [cljfx.lifecycle :as lifecycle]) (:import [javafx.scene.effect Lighting])) (set! *warn-on-reflection* true) (def props (composite/props Lighting :light [:setter lifecycle/dynamic] :bump-input [:setter lifecycle/dynamic] :content-input [:setter lifecycle/dynamic] :diffuse-constant [:setter lifecycle/scalar :coerce double :default 1] :specular-constant [:setter lifecycle/scalar :coerce double :default 0.3] :specular-exponent [:setter lifecycle/scalar :coerce double :default 0.3] :surface-scale [:setter lifecycle/scalar :coerce double :default 1.5])) (def lifecycle (lifecycle/annotate (composite/describe Lighting :ctor [] :props props) :lighting))
null
https://raw.githubusercontent.com/cljfx/cljfx/543f7409290051e9444771d2cd86dadeb8cdce33/src/cljfx/fx/lighting.clj
clojure
(ns cljfx.fx.lighting "Part of a public API" (:require [cljfx.composite :as composite] [cljfx.lifecycle :as lifecycle]) (:import [javafx.scene.effect Lighting])) (set! *warn-on-reflection* true) (def props (composite/props Lighting :light [:setter lifecycle/dynamic] :bump-input [:setter lifecycle/dynamic] :content-input [:setter lifecycle/dynamic] :diffuse-constant [:setter lifecycle/scalar :coerce double :default 1] :specular-constant [:setter lifecycle/scalar :coerce double :default 0.3] :specular-exponent [:setter lifecycle/scalar :coerce double :default 0.3] :surface-scale [:setter lifecycle/scalar :coerce double :default 1.5])) (def lifecycle (lifecycle/annotate (composite/describe Lighting :ctor [] :props props) :lighting))
28b05c1166fd73e4b1420c49d751832f377796bcf3642797d3e338f9c487e559
samsergey/formica
monad-sequential-tests.rkt
#lang racket/base (require "../monad.rkt" "../formal.rkt" "../rewrite.rkt" "../tools.rkt" "../types.rkt" rackunit racket/sequence) (test-case "zip tests" (check-equal? (zip '(a b c) '(1 2 3)) '((a 1) (b 2) (c 3))) (check-equal? (zip '(a b c) '(1 2)) '((a 1) (b 2))) (check-equal? (zip '(a b) '(1 2 3)) '((a 1) (b 2))) (check-equal? (sequence->list (zip '(a b) 3)) '((a 0) (b 1)))) (test-case "listable? tests" (check-false (listable? 3)) (check-false (listable? 0)) (check-true (listable? "abc")) (check-true (listable? (in-range 3))) (check-true (listable? (in-naturals))) (check-true (listable? '(a b c))) (check-true (listable? (set 'a 'b 'c))) (check-true (listable? (stream 'a 'b 'c))) (check-true (listable? '(g x))) (check-false (listable? -1)) (check-false (listable? 'x)) (define-formal f) (check-false (listable? (f 'x))) (check-false (listable? (f 'x 'y)))) (test-case "Monad List" (using-monad List) (define-formal f g) (define (F x) (return (f 1 x) (f 2 x))) (define (G x) (return (g 1 x) (g 2 x))) (define (Z x) mzero) ; the basic monadic functions (check-equal? (return 'x) (list 'x)) (check-equal? (return 'x 'y 'x) (list 'x 'y 'x)) (check-equal? mzero null) (check-equal? (mplus '(1 2) '(2 3)) '(1 2 2 3)) ; the monad laws (check-equal? (bind (return 'x) >>= (lift f)) (return (f 'x))) (check-equal? (bind (return 'x) >>= F) (return (f 1 'x) (f 2 'x))) (check-equal? (bind (return 'x 'y 'z) >>= (lift f)) (return (f 'x) (f 'y) (f 'z))) (check-equal? (bind (return 'x 'y 'z) >>= F) (return (f 1 'x) (f 2 'x) (f 1 'y) (f 2 'y) (f 1 'z) (f 2 'z))) (check-equal? (bind (return 'x) >>= return) (return 'x)) (check-equal? (bind (return 'x 'y 'z) >>= return) (return 'x 'y 'z)) (check-equal? (bind (bind (return 'x) >>= (lift f)) >>= (lift g)) (bind (return 'x) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-equal? (bind (bind (return 'x 'y) >>= (lift f)) >>= (lift g)) (bind (return 'x 'y) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-equal? (bind (bind (return 'x) >>= F) >>= G) (bind (return 'x) >>= (λ (x) (bind (F x) >>= G)))) (check-equal? (bind (bind (return 'x 'y) >>= F) >>= G) (bind (return 'x 'y) >>= (λ (x) (bind (F x) >>= G)))) ;the additive monad laws (check-equal? (bind mzero >>= (lift f)) mzero) (check-equal? (bind mzero >>= F) mzero) (check-equal? (bind (return 'x) >>= (λ (_) mzero)) mzero) (check-equal? (bind (return 'x 'y) >>= (λ (_) mzero)) mzero) (check-equal? (mplus mzero (return 'x)) (return 'x)) (check-equal? (mplus mzero (return 'x 'y)) (return 'x 'y)) (check-equal? (mplus (return 'x) mzero) (return 'x)) (check-equal? (mplus (return 'x 'y) mzero) (return 'x 'y)) ; guarding (check-equal? (bind (return 'x) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x))) (check-equal? (bind (return 'x 'y) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x) (g 'y))) (check-equal? (bind (return 'x) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x))) (check-equal? (bind (return 'x 'y) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-equal? (bind (return 'x) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-equal? (bind (return 'x 'y) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-equal? (bind (return 'x) >>= (guardf (const #f)) >>= G) mzero) (check-equal? (bind (return 'x 'y) >>= (guardf (const #f)) >>= G) mzero) (check-equal? (do [x <-: 'x] (guard #t) (return (g x))) (return (g 'x))) (check-equal? (do [x <- (return 'x 'y)] (guard #t) (return (g x))) (return (g 'x) (g 'y))) (check-equal? (do [x <-: 'x] (guard #t) (G x)) (return (g 1 'x) (g 2 'x))) (check-equal? (do [x <- (return 'x 'y)] (guard #t) (G x)) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) ; monadic composition (check-equal? ((compose/m (lift f) (lift g)) 'x) (return (f (g 'x)))) (check-equal? ((compose/m (lift f) (lift g)) 'x 'y) (return (f (g 'x)) (f (g 'y)))) (check-equal? ((compose/m F (lift g)) 'x) (return (f 1 (g 'x)) (f 2 (g 'x)))) (check-equal? ((compose/m (lift f) G) 'x) (return (f (g 1 'x)) (f (g 2 'x)))) (check-equal? ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-equal? ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-equal? ((compose/m Z G) 'x) mzero) (check-equal? ((compose/m F Z) 'x) mzero) ; monadic lifting (check-equal? (lift/m f (return 'x)) (return (f 'x))) (check-equal? (lift/m f (return 'x 'y)) (return (f 'x) (f 'y))) (check-equal? (lift/m f (return 'x) (return 'y)) (return (f 'x 'y))) (check-equal? (lift/m f (return 'x 'y) (return 'z)) (return (f 'x 'z) (f 'y 'z))) (check-equal? (lift/m f (return 'x 'y) mzero) mzero) (check-equal? (lift/m f (return 'x 'y) mzero (return 'z)) mzero) ;monadic folding (check-equal? (fold/m (lift f) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))))) (check-equal? (fold/m (λ (x y) (return (f x y) (g x y))) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))) (g 'c (f 'b (f 'a 'x))) (f 'c (g 'b (f 'a 'x))) (g 'c (g 'b (f 'a 'x))) (f 'c (f 'b (g 'a 'x))) (g 'c (f 'b (g 'a 'x))) (f 'c (g 'b (g 'a 'x))) (g 'c (g 'b (g 'a 'x))))) ; monadic filtering (check-equal? (filter/m (lift (const #t)) '(a b c)) (return '(a b c))) (check-equal? (filter/m (lift (const #f)) '(a b c)) (return '())) (check-equal? (filter/m (lift (/. 'b --> #f)) '(a b c d)) (return '(a c d))) (check-equal? (filter/m (lift odd?) '(1 2 3 4 5)) (return '(1 3 5))) (check-equal? (filter/m (lift odd?) '(1 2 3 4 5 6)) (return '(1 3 5))) (check-equal? (filter/m (λ (x) (return #t #f)) '(1 2 3)) (return '(1 2 3) '(1 2) '(1 3) '(1) '(2 3) '(2) '(3) '())) ; monadic mapping (check-equal? (map/m (lift f) '(a b c)) (return '((f a) (f b) (f c)))) (check-equal? (map/m F '(a b)) (return '((f 1 a) (f 1 b)) '((f 1 a) (f 2 b)) '((f 2 a) (f 1 b)) '((f 2 a) (f 2 b)))) ; monadic sequencing (check-equal? (sequence/m (list (return 'a) (return 'b) (return 'c))) (return '(a b c))) (check-equal? (sequence/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return '(a c d) '(a c e) '(b c d) '(b c e))) (check-equal? (sequence/m (list (return 'a) mzero (return 'c))) mzero) (check-equal? (sequence/m (list (return 'a 'b) mzero (return 'c))) mzero) ; monadic sum (check-equal? (sum/m (list (return 'a) (return 'b) (return 'c))) (return 'a 'b 'c)) (check-equal? (sum/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return 'a 'b 'c 'd 'e)) (check-equal? (sum/m (list (return 'a 'b) mzero (return 'd 'e))) (return 'a 'b 'd 'e)) ; failure (check-equal? (do [1 <- '(1 2 3 2 1 2 3)] (return 'y)) (return 'y 'y)) (check-equal? (collect x [(? odd? x) <- '(1 2 3 2 1 2 3)]) (return 1 3 1 3)) (check-equal? (collect x [(? odd? x) <- (range 5)]) (return 1 3)) ; zipping #;(check-equal? (collect (cons x y) [(list x y) <- (stream->list (zip '(a b c) (in-naturals)))]) (return '(a . 0) '(b . 1) '(c . 2))) ; type checking (check-exn exn:fail:contract? (λ () (bind 'x >>= (lift f)))) (check-exn exn:fail:contract? (λ () (bind 'x >>= f))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m f (lift g)) 'x)))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m (lift f) g) 'x)))) (check-exn exn:fail:contract? (λ () (lift/m f 'x))) (check-exn exn:fail:contract? (λ () (fold/m f 'x '(a b c)))) (check-exn exn:fail:contract? (λ () (map/m f '(a b c)))) (check-exn exn:fail:contract? (λ () (sequence/m (list (return 'x) 'y)))) (check-exn exn:fail:contract? (λ () (sum/m (list (return 'x) 'y))))) #;(require "../examples/nondeterministic.rkt") (define-syntax-rule (check-stream-equal? s1 s2) (check-equal? (stream->list s1) (stream->list s2))) (test-case "Monad Stream" (using-monad Stream) (define-formal f g) (define (F x) (return (f 1 x) (f 2 x))) (define (G x) (return (g 1 x) (g 2 x))) (define (Z x) mzero) ; the basic monadic functions (check-stream-equal? (return 'x) (stream 'x)) (check-stream-equal? mzero (stream)) (check-stream-equal? (mplus (stream 1 2) (stream 3 4)) (stream 1 2 3 4)) ; the monad laws (check-stream-equal? (bind (return 'x) >>= (lift f)) (return (f 'x))) (check-stream-equal? (bind (return 'x) >>= F) (return (f 1 'x) (f 2 'x))) (check-stream-equal? (bind (return 'x 'y 'z) >>= (lift f)) (return (f 'x) (f 'y) (f 'z))) (check-stream-equal? (bind (return 'x 'y 'z) >>= F) (stream (f 1 'x) (f 2 'x) (f 1 'y) (f 2 'y) (f 1 'z) (f 2 'z))) (check-stream-equal? (bind (return 'x) >>= return) (return 'x)) (check-stream-equal? (bind (return 'x 'y 'z) >>= return) (return 'x 'y 'z)) (check-stream-equal? (bind (bind (return 'x) >>= (lift f)) >>= (lift g)) (bind (return 'x) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-stream-equal? (bind (bind (return 'x 'y) >>= (lift f)) >>= (lift g)) (bind (return 'x 'y) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-stream-equal? (bind (bind (return 'x) >>= F) >>= G) (bind (return 'x) >>= (λ (x) (bind (F x) >>= G)))) (check-stream-equal? (bind (bind (return 'x 'y) >>= F) >>= G) (bind (return 'x 'y) >>= (λ (x) (bind (F x) >>= G)))) ;the additive monad laws (check-stream-equal? (bind mzero >>= (lift f)) mzero) (check-stream-equal? (bind mzero >>= F) mzero) (check-stream-equal? (bind (return 'x) >>= (λ (_) mzero)) mzero) (check-stream-equal? (bind (return 'x 'y) >>= (λ (_) mzero)) mzero) (check-stream-equal? (mplus mzero (return 'x)) (return 'x)) (check-stream-equal? (mplus mzero (return 'x 'y)) (return 'x 'y)) (check-stream-equal? (mplus (return 'x) mzero) (return 'x)) (check-stream-equal? (mplus (return 'x 'y) mzero) (return 'x 'y)) ; guarding (check-stream-equal? (bind (return 'x) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x))) (check-stream-equal? (bind (return 'x 'y) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x) (g 'y))) (check-stream-equal? (bind (return 'x) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x))) (check-stream-equal? (bind (return 'x 'y) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-stream-equal? (bind (return 'x) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-stream-equal? (bind (return 'x 'y) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-stream-equal? (bind (return 'x) >>= (guardf (const #f)) >>= G) mzero) (check-stream-equal? (bind (return 'x 'y) >>= (guardf (const #f)) >>= G) mzero) (check-stream-equal? (do [x <-: 'x] (guard #t) (return (g x))) (return (g 'x))) (check-stream-equal? (do [x <- (return 'x 'y)] (guard #t) (return (g x))) (return (g 'x) (g 'y))) (check-stream-equal? (do [x <-: 'x] (guard #t) (G x)) (return (g 1 'x) (g 2 'x))) (check-stream-equal? (do [x <- (return 'x 'y)] (guard #t) (G x)) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) ; monadic composition (check-stream-equal? ((compose/m (lift f) (lift g)) 'x) (return (f (g 'x)))) (check-stream-equal? ((compose/m (lift f) (lift g)) 'x 'y) (return (f (g 'x)) (f (g 'y)))) (check-stream-equal? ((compose/m F (lift g)) 'x) (return (f 1 (g 'x)) (f 2 (g 'x)))) (check-stream-equal? ((compose/m (lift f) G) 'x) (return (f (g 1 'x)) (f (g 2 'x)))) (check-stream-equal? ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-stream-equal? ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-stream-equal? ((compose/m Z G) 'x) mzero) (check-stream-equal? ((compose/m F Z) 'x) mzero) ; monadic lifting (check-stream-equal? (lift/m f (return 'x)) (return (f 'x))) (check-stream-equal? (lift/m f (return 'x 'y)) (return (f 'x) (f 'y))) (check-stream-equal? (lift/m f (return 'x) (return 'y)) (return (f 'x 'y))) (check-stream-equal? (lift/m f (return 'x 'y) (return 'z)) (return (f 'x 'z) (f 'y 'z))) (check-stream-equal? (lift/m f (return 'x 'y) mzero) mzero) (check-stream-equal? (lift/m f (return 'x 'y) mzero (return 'z)) mzero) ;monadic folding (check-stream-equal? (fold/m (lift f) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))))) (check-stream-equal? (fold/m (λ (x y) (return (f x y) (g x y))) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))) (g 'c (f 'b (f 'a 'x))) (f 'c (g 'b (f 'a 'x))) (g 'c (g 'b (f 'a 'x))) (f 'c (f 'b (g 'a 'x))) (g 'c (f 'b (g 'a 'x))) (f 'c (g 'b (g 'a 'x))) (g 'c (g 'b (g 'a 'x))))) ; monadic filtering (check-stream-equal? (filter/m (lift (const #t)) '(a b c)) (return '(a b c))) (check-stream-equal? (filter/m (lift (const #f)) '(a b c)) (return '())) (check-stream-equal? (filter/m (lift (/. 'b --> #f)) '(a b c d)) (return '(a c d))) (check-stream-equal? (filter/m (lift odd?) '(1 2 3 4 5)) (return '(1 3 5))) (check-stream-equal? (filter/m (lift odd?) '(1 2 3 4 5 6)) (return '(1 3 5))) (check-stream-equal? (filter/m (λ (x) (return #t #f)) '(1 2 3)) (return '(1 2 3) '(1 2) '(1 3) '(1) '(2 3) '(2) '(3) '())) ; monadic mapping (check-stream-equal? (map/m (lift f) '(a b c)) (return '((f a) (f b) (f c)))) (check-stream-equal? (map/m F '(a b)) (return '((f 1 a) (f 1 b)) '((f 1 a) (f 2 b)) '((f 2 a) (f 1 b)) '((f 2 a) (f 2 b)))) ; monadic sequencing (check-stream-equal? (sequence/m (list (return 'a) (return 'b) (return 'c))) (return '(a b c))) (check-stream-equal? (sequence/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return '(a c d) '(a c e) '(b c d) '(b c e))) (check-stream-equal? (sequence/m (list (return 'a) mzero (return 'c))) mzero) (check-stream-equal? (sequence/m (list (return 'a 'b) mzero (return 'c))) mzero) ; monadic sum (check-stream-equal? (sum/m (list (return 'a) (return 'b) (return 'c))) (return 'a 'b 'c)) (check-stream-equal? (sum/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return 'a 'b 'c 'd 'e)) (check-stream-equal? (sum/m (list (return 'a 'b) mzero (return 'd 'e))) (return 'a 'b 'd 'e)) ; failure (check-stream-equal? (do [1 <- (in-list '(1 2 3 2 1 2 3))] (return 'y)) (return 'y 'y)) (check-stream-equal? (collect x [(? odd? x) <- (return 1 2 3 2 1 2 3)]) (return 1 3 1 3)) (check-stream-equal? (collect x [(? odd? x) <- (in-range 5)]) (return 1 3)) ; zipping #;(check-stream-equal? (collect (cons x y) [(list x y) <- (zip '(a b c) (in-naturals))]) (return '(a . 0) '(b . 1) '(c . 2))) ; type checking (check-exn exn:fail:contract? (λ () (bind 'x >>= (lift f)))) (check-exn exn:fail:contract? (λ () (bind 'x >>= f))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m f (lift g)) 'x)))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m (lift f) g) 'x)))) (check-exn exn:fail:contract? (λ () (lift/m f 'x))) (check-exn exn:fail:contract? (λ () (fold/m f 'x '(a b c)))) (check-exn exn:fail:contract? (λ () (map/m f '(a b c)))) (check-exn exn:fail:contract? (λ () (stream-first (sequence/m (list (return 'x) 'y))))) (check-exn exn:fail:contract? (λ () (stream->list (sum/m (list (return 'x) 'y))))) ; lazyness (check-equal? (stream-ref (bind (return 1 0 2) >>= (lift /)) 0) 1) (check-exn exn:fail? (λ () (stream-ref (bind (return 1 0 2) >>= (lift /)) 1))) (check-equal? (stream-ref (bind (return 1 0 2) >>= (lift /) >>= (lift g)) 0) (g 1)) (check-equal? (stream-first ((compose/m (lift /) (lift (curry * 2))) 1 0)) 1/2) (check-exn exn:fail? (λ () (stream-ref ((compose/m (lift /) (lift (curry * 2))) 1 0) 1))) (check-equal? (stream-first (lift/m / (return 1) (return 1 0))) 1) (check-exn exn:fail? (λ () (stream-ref (lift/m / (return 1) (return 1 0)) 1))) (check-equal? (stream-first (sequence/m (list (return 1) (stream 0 (/ 0))))) '(1 0)) (check-exn exn:fail? (λ () (stream-ref (sequence/m (list (return 1) (stream 0 (/ 0)))) 1))) (check-equal? (stream-ref (bind (stream 1 0 2) >>= (lift /)) 0) 1) (check-exn exn:fail? (λ () (stream-ref (bind (stream 1 0 2) >>= (lift /)) 1))) (check-equal? (stream-ref (bind (stream 1 0 2) >>= (lift /) >>= (lift g)) 0) (g 1)) (check-equal? (stream-first ((compose/m (lift log) (lift (curry + 1))) 0 -1)) 0) (check-exn exn:fail? (λ () (stream-ref ((compose/m (lift log) (lift (curry + 1))) 0 -1) 1))) (check-equal? (stream-first (lift/m / (stream 1) (stream 1 0))) 1) (check-exn exn:fail? (λ () (stream-ref (lift/m / (stream 1) (stream 1 0)) 1))) (check-equal? (stream-first (sequence/m (list (stream 1) (stream 0 (/ 0))))) '(1 0)) (check-exn exn:fail? (λ () (stream-ref (sequence/m (list (stream 1) (stream 0 (/ 0)))) 1))) (check-equal? (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 0) '(1 0 3)) (check-equal? (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 1) '(1 0 1/3)) (check-exn exn:fail? (λ () (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 2))) (check-equal? (stream-first (filter/m (λ (x) (stream x (/ x))) '(1 0 3))) '(1 0 3)) (check-exn exn:fail? (λ () (stream-ref (filter/m (λ (x) (stream x (/ x))) '(1 0 3)) 2))) (check-equal? (stream-first (fold/m (λ (x y) (stream (+ x y) (+ (/ x) y))) 1 '(1 0 2))) 4) (check-equal? (stream-ref (fold/m (λ (x y) (stream (+ x y) (+ (/ x) y))) 1 '(1 0 2)) 1) 5/2) (check-exn exn:fail? (λ () (stream-ref (fold/m (λ (x y) (stream (+ x y) (+ (/ x) y))) 1 '(1 0 2)) 2))) ; using eager function return instead of lazy form stream as constructor destroys lazyness. (check-exn exn:fail? (λ () (stream-first (map/m (λ (x) (return x (/ x))) '(1 2 0 3))))) (check-exn exn:fail? (λ () (stream-first (filter/m (λ (x) (return x (/ x))) '(1 0 3))))) (check-exn exn:fail? (λ () (stream-first (fold/m (λ (x y) (return (f x y) (f (/ x) y))) 1 (return 1 0 2))))) ) (define-syntax-rule (check-stream-equal?* s1 s2) (check-equal? (sort (stream->list s1) ordered?) (sort (stream->list s2) ordered?))) #;(test-case "Monad Amb" (using-monad Amb) (define-formal f g) (define (F x) (return (f 1 x) (f 2 x))) (define (G x) (return (g 1 x) (g 2 x))) (define (Z x) mzero) ; the basic monadic functions (check-stream-equal?* (return 'x) (stream 'x)) (check-stream-equal?* (return 'x 'y) (stream 'x 'y)) (check-stream-equal?* (return 'x 'y 'z) (stream 'x 'y 'z)) (check-stream-equal?* (return 'x 'y 'x) (stream 'x 'y)) (check-stream-equal?* mzero (stream)) (check-stream-equal?* (mplus (stream 1 2) (stream 2 3)) (stream 1 2 3)) ; the monad laws (check-stream-equal?* (bind (return 'x) >>= (lift f)) (return (f 'x))) (check-stream-equal?* (bind (return 'x) >>= F) (return (f 1 'x) (f 2 'x))) (check-stream-equal?* (bind (return 'x 'y 'z) >>= (lift f)) (return (f 'x) (f 'y) (f 'z))) (check-stream-equal?* (bind (return 'x 'y 'z) >>= F) (stream (f 1 'x) (f 2 'x) (f 1 'y) (f 2 'y) (f 1 'z) (f 2 'z))) (check-stream-equal?* (bind (return 'x) >>= return) (return 'x)) (check-stream-equal?* (bind (return 'x 'y 'z) >>= return) (return 'x 'y 'z)) (check-stream-equal?* (bind (bind (return 'x) >>= (lift f)) >>= (lift g)) (bind (return 'x) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-stream-equal?* (bind (bind (return 'x 'y) >>= (lift f)) >>= (lift g)) (bind (return 'x 'y) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-stream-equal?* (bind (bind (return 'x) >>= F) >>= G) (bind (return 'x) >>= (λ (x) (bind (F x) >>= G)))) (check-stream-equal?* (bind (bind (return 'x 'y) >>= F) >>= G) (bind (return 'x 'y) >>= (λ (x) (bind (F x) >>= G)))) ;the additive monad laws (check-stream-equal?* (bind mzero >>= (lift f)) mzero) (check-stream-equal?* (bind mzero >>= F) mzero) (check-stream-equal?* (bind (return 'x) >>= (λ (_) mzero)) mzero) (check-stream-equal?* (bind (return 'x 'y) >>= (λ (_) mzero)) mzero) (check-stream-equal?* (mplus mzero (return 'x)) (return 'x)) (check-stream-equal?* (mplus mzero (return 'x 'y)) (return 'x 'y)) (check-stream-equal?* (mplus (return 'x) mzero) (return 'x)) (check-stream-equal?* (mplus (return 'x 'y) mzero) (return 'x 'y)) ; guarding (check-stream-equal?* (bind (return 'x) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x))) (check-stream-equal?* (bind (return 'x 'y) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x) (g 'y))) (check-stream-equal?* (bind (return 'x) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x))) (check-stream-equal?* (bind (return 'x 'y) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-stream-equal?* (bind (return 'x) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-stream-equal?* (bind (return 'x 'y) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-stream-equal?* (bind (return 'x) >>= (guardf (const #f)) >>= G) mzero) (check-stream-equal?* (bind (return 'x 'y) >>= (guardf (const #f)) >>= G) mzero) (check-stream-equal?* (do [x <-: 'x] (guard #t) (return (g x))) (return (g 'x))) (check-stream-equal?* (do [x <- (return 'x 'y)] (guard #t) (return (g x))) (return (g 'x) (g 'y))) (check-stream-equal?* (do [x <-: 'x] (guard #t) (G x)) (return (g 1 'x) (g 2 'x))) (check-stream-equal?* (do [x <- (return 'x 'y)] (guard #t) (G x)) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) ; monadic composition (check-stream-equal?* ((compose/m (lift f) (lift g)) 'x) (return (f (g 'x)))) (check-stream-equal?* ((compose/m (lift f) (lift g)) 'x 'y) (return (f (g 'x)) (f (g 'y)))) (check-stream-equal?* ((compose/m F (lift g)) 'x) (return (f 1 (g 'x)) (f 2 (g 'x)))) (check-stream-equal?* ((compose/m (lift f) G) 'x) (return (f (g 1 'x)) (f (g 2 'x)))) (check-stream-equal?* ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-stream-equal?* ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-stream-equal?* ((compose/m Z G) 'x) mzero) (check-stream-equal?* ((compose/m F Z) 'x) mzero) ; monadic lifting (check-stream-equal?* (lift/m f (return 'x)) (return (f 'x))) (check-stream-equal?* (lift/m f (return 'x 'y)) (return (f 'x) (f 'y))) (check-stream-equal?* (lift/m f (return 'x) (return 'y)) (return (f 'x 'y))) (check-stream-equal?* (lift/m f (return 'x 'y) (return 'z)) (return (f 'x 'z) (f 'y 'z))) (check-stream-equal?* (lift/m f (return 'x 'y) mzero) mzero) (check-stream-equal?* (lift/m f (return 'x 'y) mzero (return 'z)) mzero) ;monadic folding (check-stream-equal?* (fold/m (lift f) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))))) (check-stream-equal?* (fold/m (λ (x y) (return (f x y) (g x y))) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))) (g 'c (f 'b (f 'a 'x))) (f 'c (g 'b (f 'a 'x))) (g 'c (g 'b (f 'a 'x))) (f 'c (f 'b (g 'a 'x))) (g 'c (f 'b (g 'a 'x))) (f 'c (g 'b (g 'a 'x))) (g 'c (g 'b (g 'a 'x))))) ; monadic filtering (check-stream-equal?* (filter/m (lift (const #t)) '(a b c)) (return '(a b c))) (check-stream-equal?* (filter/m (lift (const #f)) '(a b c)) (return '())) (check-stream-equal?* (filter/m (lift (/. 'b --> #f)) '(a b c d)) (return '(a c d))) (check-stream-equal?* (filter/m (lift odd?) '(1 2 3 4 5)) (return '(1 3 5))) (check-stream-equal?* (filter/m (lift odd?) '(1 2 3 4 5 6)) (return '(1 3 5))) (check-stream-equal?* (filter/m (λ (x) (return #t #f)) '(1 2 3)) (return '(1 2 3) '(1 2) '(1 3) '(1) '(2 3) '(2) '(3) '())) ; monadic mapping (check-stream-equal?* (map/m (lift f) '(a b c)) (return '((f a) (f b) (f c)))) (check-stream-equal?* (map/m F '(a b)) (return '((f 1 a) (f 1 b)) '((f 1 a) (f 2 b)) '((f 2 a) (f 1 b)) '((f 2 a) (f 2 b)))) ; monadic sequencing (check-stream-equal?* (sequence/m (list (return 'a) (return 'b) (return 'c))) (return '(a b c))) (check-stream-equal?* (sequence/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return '(a c d) '(a c e) '(b c d) '(b c e))) (check-stream-equal?* (sequence/m (list (return 'a) mzero (return 'c))) mzero) (check-stream-equal?* (sequence/m (list (return 'a 'b) mzero (return 'c))) mzero) ; monadic sum (check-stream-equal?* (sum/m (list (return 'a) (return 'b) (return 'c))) (return 'a 'b 'c)) (check-stream-equal?* (sum/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return 'a 'b 'c 'd 'e)) (check-stream-equal?* (sum/m (list (return 'a 'b) mzero (return 'd 'e))) (return 'a 'b 'd 'e)) ; failure (check-stream-equal?* (do [1 <- '(1 2 3 2 1 2 3)] (return 'y)) (return 'y 'y)) (check-stream-equal?* (collect x [(? odd? x) <- '(1 2 3 2 1 2 3)]) (return 1 3 1 3)) (check-stream-equal?* (collect x [(? odd? x) <- 5]) (return 1 3)) ; zipping (check-stream-equal?* (collect (cons x y) [(list x y) <- (zip '(a b c) (in-naturals))]) (return '(a . 0) '(b . 1) '(c . 2))) ; type checking (check-exn exn:fail:contract? (λ () (bind 'x >>= (lift f)))) (check-exn exn:fail:contract? (λ () (bind 'x >>= f))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m f (lift g)) 'x)))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m (lift f) g) 'x)))) (check-exn exn:fail:contract? (λ () (lift/m f 'x))) (check-exn exn:fail:contract? (λ () (fold/m f 'x '(a b c)))) (check-exn exn:fail:contract? (λ () (map/m f '(a b c)))) (check-exn exn:fail:contract? (λ () (stream-first (sequence/m (list (return 'x) 'y))))) (check-exn exn:fail:contract? (λ () (stream->list (sum/m (list (return 'x) 'y))))) ; lazyness (check-equal? (stream-ref (bind (amb 1 0 2) >>= (lift /)) 0) 1) (check-exn exn:fail? (λ () (stream-ref (bind (amb 1 0 2) >>= (lift /)) 1))) (check-equal? (stream-ref (bind (amb 1 0 2) >>= (lift /) >>= (lift g)) 0) (g 1)) (check-equal? (stream-first ((compose/m (lift log) (lift (curry + 1))) 0 -1)) 0) (check-exn exn:fail? (λ () (stream-ref ((compose/m (lift log) (lift (curry + 1))) 0 -1) 1))) (check-equal? (stream-first (lift/m / (amb 1) (amb 1 0))) 1) (check-exn exn:fail? (λ () (stream-ref (lift/m / (amb 1) (amb 1 0)) 1))) (check-equal? (stream-first (sequence/m (list (amb 1) (amb 0 (/ 0))))) '(1 0)) (check-exn exn:fail? (λ () (stream-ref (sequence/m (list (amb 1) (amb 0 (/ 0)))) 1))) (check-equal? (stream-ref (map/m (λ (x) (amb x (/ x))) '(1 0 3)) 0) '(1 0 3)) (check-equal? (stream-ref (map/m (λ (x) (amb x (/ x))) '(1 0 3)) 1) '(1 0 1/3)) (check-exn exn:fail? (λ () (stream-ref (map/m (λ (x) (amb x (/ x))) '(1 0 3)) 2))) (check-equal? (stream-first (filter/m (λ (x) (amb x (/ x))) '(1 0 3))) '(1 0 3)) (check-exn exn:fail? (λ () (stream-ref (filter/m (λ (x) (amb x (/ x))) '(1 0 3)) 1))) (check-equal? (stream-first (fold/m (λ (x y) (amb (+ x y) (+ (/ x) y))) 1 '(1 0 2))) 4) (check-equal? (stream-ref (fold/m (λ (x y) (amb (+ x y) (+ (/ x) y))) 1 '(1 0 2)) 1) 5/2) (check-exn exn:fail? (λ () (stream-ref (fold/m (λ (x y) (amb (+ x y) (+ (/ x) y))) 1 '(1 0 2)) 2))) )
null
https://raw.githubusercontent.com/samsergey/formica/b4410b4b6da63ecb15b4c25080951a7ba4d90d2c/tests/monad-sequential-tests.rkt
racket
the basic monadic functions the monad laws the additive monad laws guarding monadic composition monadic lifting monadic folding monadic filtering monadic mapping monadic sequencing monadic sum failure zipping (check-equal? (collect (cons x y) [(list x y) <- type checking (require "../examples/nondeterministic.rkt") the basic monadic functions the monad laws the additive monad laws guarding monadic composition monadic lifting monadic folding monadic filtering monadic mapping monadic sequencing monadic sum failure zipping (check-stream-equal? (collect (cons x y) [(list x y) <- (zip '(a b c) (in-naturals))]) type checking lazyness using eager function return instead of lazy form stream as constructor destroys lazyness. (test-case the basic monadic functions the monad laws the additive monad laws guarding monadic composition monadic lifting monadic folding monadic filtering monadic mapping monadic sequencing monadic sum failure zipping type checking lazyness
#lang racket/base (require "../monad.rkt" "../formal.rkt" "../rewrite.rkt" "../tools.rkt" "../types.rkt" rackunit racket/sequence) (test-case "zip tests" (check-equal? (zip '(a b c) '(1 2 3)) '((a 1) (b 2) (c 3))) (check-equal? (zip '(a b c) '(1 2)) '((a 1) (b 2))) (check-equal? (zip '(a b) '(1 2 3)) '((a 1) (b 2))) (check-equal? (sequence->list (zip '(a b) 3)) '((a 0) (b 1)))) (test-case "listable? tests" (check-false (listable? 3)) (check-false (listable? 0)) (check-true (listable? "abc")) (check-true (listable? (in-range 3))) (check-true (listable? (in-naturals))) (check-true (listable? '(a b c))) (check-true (listable? (set 'a 'b 'c))) (check-true (listable? (stream 'a 'b 'c))) (check-true (listable? '(g x))) (check-false (listable? -1)) (check-false (listable? 'x)) (define-formal f) (check-false (listable? (f 'x))) (check-false (listable? (f 'x 'y)))) (test-case "Monad List" (using-monad List) (define-formal f g) (define (F x) (return (f 1 x) (f 2 x))) (define (G x) (return (g 1 x) (g 2 x))) (define (Z x) mzero) (check-equal? (return 'x) (list 'x)) (check-equal? (return 'x 'y 'x) (list 'x 'y 'x)) (check-equal? mzero null) (check-equal? (mplus '(1 2) '(2 3)) '(1 2 2 3)) (check-equal? (bind (return 'x) >>= (lift f)) (return (f 'x))) (check-equal? (bind (return 'x) >>= F) (return (f 1 'x) (f 2 'x))) (check-equal? (bind (return 'x 'y 'z) >>= (lift f)) (return (f 'x) (f 'y) (f 'z))) (check-equal? (bind (return 'x 'y 'z) >>= F) (return (f 1 'x) (f 2 'x) (f 1 'y) (f 2 'y) (f 1 'z) (f 2 'z))) (check-equal? (bind (return 'x) >>= return) (return 'x)) (check-equal? (bind (return 'x 'y 'z) >>= return) (return 'x 'y 'z)) (check-equal? (bind (bind (return 'x) >>= (lift f)) >>= (lift g)) (bind (return 'x) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-equal? (bind (bind (return 'x 'y) >>= (lift f)) >>= (lift g)) (bind (return 'x 'y) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-equal? (bind (bind (return 'x) >>= F) >>= G) (bind (return 'x) >>= (λ (x) (bind (F x) >>= G)))) (check-equal? (bind (bind (return 'x 'y) >>= F) >>= G) (bind (return 'x 'y) >>= (λ (x) (bind (F x) >>= G)))) (check-equal? (bind mzero >>= (lift f)) mzero) (check-equal? (bind mzero >>= F) mzero) (check-equal? (bind (return 'x) >>= (λ (_) mzero)) mzero) (check-equal? (bind (return 'x 'y) >>= (λ (_) mzero)) mzero) (check-equal? (mplus mzero (return 'x)) (return 'x)) (check-equal? (mplus mzero (return 'x 'y)) (return 'x 'y)) (check-equal? (mplus (return 'x) mzero) (return 'x)) (check-equal? (mplus (return 'x 'y) mzero) (return 'x 'y)) (check-equal? (bind (return 'x) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x))) (check-equal? (bind (return 'x 'y) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x) (g 'y))) (check-equal? (bind (return 'x) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x))) (check-equal? (bind (return 'x 'y) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-equal? (bind (return 'x) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-equal? (bind (return 'x 'y) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-equal? (bind (return 'x) >>= (guardf (const #f)) >>= G) mzero) (check-equal? (bind (return 'x 'y) >>= (guardf (const #f)) >>= G) mzero) (check-equal? (do [x <-: 'x] (guard #t) (return (g x))) (return (g 'x))) (check-equal? (do [x <- (return 'x 'y)] (guard #t) (return (g x))) (return (g 'x) (g 'y))) (check-equal? (do [x <-: 'x] (guard #t) (G x)) (return (g 1 'x) (g 2 'x))) (check-equal? (do [x <- (return 'x 'y)] (guard #t) (G x)) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-equal? ((compose/m (lift f) (lift g)) 'x) (return (f (g 'x)))) (check-equal? ((compose/m (lift f) (lift g)) 'x 'y) (return (f (g 'x)) (f (g 'y)))) (check-equal? ((compose/m F (lift g)) 'x) (return (f 1 (g 'x)) (f 2 (g 'x)))) (check-equal? ((compose/m (lift f) G) 'x) (return (f (g 1 'x)) (f (g 2 'x)))) (check-equal? ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-equal? ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-equal? ((compose/m Z G) 'x) mzero) (check-equal? ((compose/m F Z) 'x) mzero) (check-equal? (lift/m f (return 'x)) (return (f 'x))) (check-equal? (lift/m f (return 'x 'y)) (return (f 'x) (f 'y))) (check-equal? (lift/m f (return 'x) (return 'y)) (return (f 'x 'y))) (check-equal? (lift/m f (return 'x 'y) (return 'z)) (return (f 'x 'z) (f 'y 'z))) (check-equal? (lift/m f (return 'x 'y) mzero) mzero) (check-equal? (lift/m f (return 'x 'y) mzero (return 'z)) mzero) (check-equal? (fold/m (lift f) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))))) (check-equal? (fold/m (λ (x y) (return (f x y) (g x y))) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))) (g 'c (f 'b (f 'a 'x))) (f 'c (g 'b (f 'a 'x))) (g 'c (g 'b (f 'a 'x))) (f 'c (f 'b (g 'a 'x))) (g 'c (f 'b (g 'a 'x))) (f 'c (g 'b (g 'a 'x))) (g 'c (g 'b (g 'a 'x))))) (check-equal? (filter/m (lift (const #t)) '(a b c)) (return '(a b c))) (check-equal? (filter/m (lift (const #f)) '(a b c)) (return '())) (check-equal? (filter/m (lift (/. 'b --> #f)) '(a b c d)) (return '(a c d))) (check-equal? (filter/m (lift odd?) '(1 2 3 4 5)) (return '(1 3 5))) (check-equal? (filter/m (lift odd?) '(1 2 3 4 5 6)) (return '(1 3 5))) (check-equal? (filter/m (λ (x) (return #t #f)) '(1 2 3)) (return '(1 2 3) '(1 2) '(1 3) '(1) '(2 3) '(2) '(3) '())) (check-equal? (map/m (lift f) '(a b c)) (return '((f a) (f b) (f c)))) (check-equal? (map/m F '(a b)) (return '((f 1 a) (f 1 b)) '((f 1 a) (f 2 b)) '((f 2 a) (f 1 b)) '((f 2 a) (f 2 b)))) (check-equal? (sequence/m (list (return 'a) (return 'b) (return 'c))) (return '(a b c))) (check-equal? (sequence/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return '(a c d) '(a c e) '(b c d) '(b c e))) (check-equal? (sequence/m (list (return 'a) mzero (return 'c))) mzero) (check-equal? (sequence/m (list (return 'a 'b) mzero (return 'c))) mzero) (check-equal? (sum/m (list (return 'a) (return 'b) (return 'c))) (return 'a 'b 'c)) (check-equal? (sum/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return 'a 'b 'c 'd 'e)) (check-equal? (sum/m (list (return 'a 'b) mzero (return 'd 'e))) (return 'a 'b 'd 'e)) (check-equal? (do [1 <- '(1 2 3 2 1 2 3)] (return 'y)) (return 'y 'y)) (check-equal? (collect x [(? odd? x) <- '(1 2 3 2 1 2 3)]) (return 1 3 1 3)) (check-equal? (collect x [(? odd? x) <- (range 5)]) (return 1 3)) (stream->list (zip '(a b c) (in-naturals)))]) (return '(a . 0) '(b . 1) '(c . 2))) (check-exn exn:fail:contract? (λ () (bind 'x >>= (lift f)))) (check-exn exn:fail:contract? (λ () (bind 'x >>= f))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m f (lift g)) 'x)))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m (lift f) g) 'x)))) (check-exn exn:fail:contract? (λ () (lift/m f 'x))) (check-exn exn:fail:contract? (λ () (fold/m f 'x '(a b c)))) (check-exn exn:fail:contract? (λ () (map/m f '(a b c)))) (check-exn exn:fail:contract? (λ () (sequence/m (list (return 'x) 'y)))) (check-exn exn:fail:contract? (λ () (sum/m (list (return 'x) 'y))))) (define-syntax-rule (check-stream-equal? s1 s2) (check-equal? (stream->list s1) (stream->list s2))) (test-case "Monad Stream" (using-monad Stream) (define-formal f g) (define (F x) (return (f 1 x) (f 2 x))) (define (G x) (return (g 1 x) (g 2 x))) (define (Z x) mzero) (check-stream-equal? (return 'x) (stream 'x)) (check-stream-equal? mzero (stream)) (check-stream-equal? (mplus (stream 1 2) (stream 3 4)) (stream 1 2 3 4)) (check-stream-equal? (bind (return 'x) >>= (lift f)) (return (f 'x))) (check-stream-equal? (bind (return 'x) >>= F) (return (f 1 'x) (f 2 'x))) (check-stream-equal? (bind (return 'x 'y 'z) >>= (lift f)) (return (f 'x) (f 'y) (f 'z))) (check-stream-equal? (bind (return 'x 'y 'z) >>= F) (stream (f 1 'x) (f 2 'x) (f 1 'y) (f 2 'y) (f 1 'z) (f 2 'z))) (check-stream-equal? (bind (return 'x) >>= return) (return 'x)) (check-stream-equal? (bind (return 'x 'y 'z) >>= return) (return 'x 'y 'z)) (check-stream-equal? (bind (bind (return 'x) >>= (lift f)) >>= (lift g)) (bind (return 'x) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-stream-equal? (bind (bind (return 'x 'y) >>= (lift f)) >>= (lift g)) (bind (return 'x 'y) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-stream-equal? (bind (bind (return 'x) >>= F) >>= G) (bind (return 'x) >>= (λ (x) (bind (F x) >>= G)))) (check-stream-equal? (bind (bind (return 'x 'y) >>= F) >>= G) (bind (return 'x 'y) >>= (λ (x) (bind (F x) >>= G)))) (check-stream-equal? (bind mzero >>= (lift f)) mzero) (check-stream-equal? (bind mzero >>= F) mzero) (check-stream-equal? (bind (return 'x) >>= (λ (_) mzero)) mzero) (check-stream-equal? (bind (return 'x 'y) >>= (λ (_) mzero)) mzero) (check-stream-equal? (mplus mzero (return 'x)) (return 'x)) (check-stream-equal? (mplus mzero (return 'x 'y)) (return 'x 'y)) (check-stream-equal? (mplus (return 'x) mzero) (return 'x)) (check-stream-equal? (mplus (return 'x 'y) mzero) (return 'x 'y)) (check-stream-equal? (bind (return 'x) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x))) (check-stream-equal? (bind (return 'x 'y) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x) (g 'y))) (check-stream-equal? (bind (return 'x) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x))) (check-stream-equal? (bind (return 'x 'y) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-stream-equal? (bind (return 'x) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-stream-equal? (bind (return 'x 'y) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-stream-equal? (bind (return 'x) >>= (guardf (const #f)) >>= G) mzero) (check-stream-equal? (bind (return 'x 'y) >>= (guardf (const #f)) >>= G) mzero) (check-stream-equal? (do [x <-: 'x] (guard #t) (return (g x))) (return (g 'x))) (check-stream-equal? (do [x <- (return 'x 'y)] (guard #t) (return (g x))) (return (g 'x) (g 'y))) (check-stream-equal? (do [x <-: 'x] (guard #t) (G x)) (return (g 1 'x) (g 2 'x))) (check-stream-equal? (do [x <- (return 'x 'y)] (guard #t) (G x)) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-stream-equal? ((compose/m (lift f) (lift g)) 'x) (return (f (g 'x)))) (check-stream-equal? ((compose/m (lift f) (lift g)) 'x 'y) (return (f (g 'x)) (f (g 'y)))) (check-stream-equal? ((compose/m F (lift g)) 'x) (return (f 1 (g 'x)) (f 2 (g 'x)))) (check-stream-equal? ((compose/m (lift f) G) 'x) (return (f (g 1 'x)) (f (g 2 'x)))) (check-stream-equal? ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-stream-equal? ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-stream-equal? ((compose/m Z G) 'x) mzero) (check-stream-equal? ((compose/m F Z) 'x) mzero) (check-stream-equal? (lift/m f (return 'x)) (return (f 'x))) (check-stream-equal? (lift/m f (return 'x 'y)) (return (f 'x) (f 'y))) (check-stream-equal? (lift/m f (return 'x) (return 'y)) (return (f 'x 'y))) (check-stream-equal? (lift/m f (return 'x 'y) (return 'z)) (return (f 'x 'z) (f 'y 'z))) (check-stream-equal? (lift/m f (return 'x 'y) mzero) mzero) (check-stream-equal? (lift/m f (return 'x 'y) mzero (return 'z)) mzero) (check-stream-equal? (fold/m (lift f) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))))) (check-stream-equal? (fold/m (λ (x y) (return (f x y) (g x y))) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))) (g 'c (f 'b (f 'a 'x))) (f 'c (g 'b (f 'a 'x))) (g 'c (g 'b (f 'a 'x))) (f 'c (f 'b (g 'a 'x))) (g 'c (f 'b (g 'a 'x))) (f 'c (g 'b (g 'a 'x))) (g 'c (g 'b (g 'a 'x))))) (check-stream-equal? (filter/m (lift (const #t)) '(a b c)) (return '(a b c))) (check-stream-equal? (filter/m (lift (const #f)) '(a b c)) (return '())) (check-stream-equal? (filter/m (lift (/. 'b --> #f)) '(a b c d)) (return '(a c d))) (check-stream-equal? (filter/m (lift odd?) '(1 2 3 4 5)) (return '(1 3 5))) (check-stream-equal? (filter/m (lift odd?) '(1 2 3 4 5 6)) (return '(1 3 5))) (check-stream-equal? (filter/m (λ (x) (return #t #f)) '(1 2 3)) (return '(1 2 3) '(1 2) '(1 3) '(1) '(2 3) '(2) '(3) '())) (check-stream-equal? (map/m (lift f) '(a b c)) (return '((f a) (f b) (f c)))) (check-stream-equal? (map/m F '(a b)) (return '((f 1 a) (f 1 b)) '((f 1 a) (f 2 b)) '((f 2 a) (f 1 b)) '((f 2 a) (f 2 b)))) (check-stream-equal? (sequence/m (list (return 'a) (return 'b) (return 'c))) (return '(a b c))) (check-stream-equal? (sequence/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return '(a c d) '(a c e) '(b c d) '(b c e))) (check-stream-equal? (sequence/m (list (return 'a) mzero (return 'c))) mzero) (check-stream-equal? (sequence/m (list (return 'a 'b) mzero (return 'c))) mzero) (check-stream-equal? (sum/m (list (return 'a) (return 'b) (return 'c))) (return 'a 'b 'c)) (check-stream-equal? (sum/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return 'a 'b 'c 'd 'e)) (check-stream-equal? (sum/m (list (return 'a 'b) mzero (return 'd 'e))) (return 'a 'b 'd 'e)) (check-stream-equal? (do [1 <- (in-list '(1 2 3 2 1 2 3))] (return 'y)) (return 'y 'y)) (check-stream-equal? (collect x [(? odd? x) <- (return 1 2 3 2 1 2 3)]) (return 1 3 1 3)) (check-stream-equal? (collect x [(? odd? x) <- (in-range 5)]) (return 1 3)) (return '(a . 0) '(b . 1) '(c . 2))) (check-exn exn:fail:contract? (λ () (bind 'x >>= (lift f)))) (check-exn exn:fail:contract? (λ () (bind 'x >>= f))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m f (lift g)) 'x)))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m (lift f) g) 'x)))) (check-exn exn:fail:contract? (λ () (lift/m f 'x))) (check-exn exn:fail:contract? (λ () (fold/m f 'x '(a b c)))) (check-exn exn:fail:contract? (λ () (map/m f '(a b c)))) (check-exn exn:fail:contract? (λ () (stream-first (sequence/m (list (return 'x) 'y))))) (check-exn exn:fail:contract? (λ () (stream->list (sum/m (list (return 'x) 'y))))) (check-equal? (stream-ref (bind (return 1 0 2) >>= (lift /)) 0) 1) (check-exn exn:fail? (λ () (stream-ref (bind (return 1 0 2) >>= (lift /)) 1))) (check-equal? (stream-ref (bind (return 1 0 2) >>= (lift /) >>= (lift g)) 0) (g 1)) (check-equal? (stream-first ((compose/m (lift /) (lift (curry * 2))) 1 0)) 1/2) (check-exn exn:fail? (λ () (stream-ref ((compose/m (lift /) (lift (curry * 2))) 1 0) 1))) (check-equal? (stream-first (lift/m / (return 1) (return 1 0))) 1) (check-exn exn:fail? (λ () (stream-ref (lift/m / (return 1) (return 1 0)) 1))) (check-equal? (stream-first (sequence/m (list (return 1) (stream 0 (/ 0))))) '(1 0)) (check-exn exn:fail? (λ () (stream-ref (sequence/m (list (return 1) (stream 0 (/ 0)))) 1))) (check-equal? (stream-ref (bind (stream 1 0 2) >>= (lift /)) 0) 1) (check-exn exn:fail? (λ () (stream-ref (bind (stream 1 0 2) >>= (lift /)) 1))) (check-equal? (stream-ref (bind (stream 1 0 2) >>= (lift /) >>= (lift g)) 0) (g 1)) (check-equal? (stream-first ((compose/m (lift log) (lift (curry + 1))) 0 -1)) 0) (check-exn exn:fail? (λ () (stream-ref ((compose/m (lift log) (lift (curry + 1))) 0 -1) 1))) (check-equal? (stream-first (lift/m / (stream 1) (stream 1 0))) 1) (check-exn exn:fail? (λ () (stream-ref (lift/m / (stream 1) (stream 1 0)) 1))) (check-equal? (stream-first (sequence/m (list (stream 1) (stream 0 (/ 0))))) '(1 0)) (check-exn exn:fail? (λ () (stream-ref (sequence/m (list (stream 1) (stream 0 (/ 0)))) 1))) (check-equal? (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 0) '(1 0 3)) (check-equal? (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 1) '(1 0 1/3)) (check-exn exn:fail? (λ () (stream-ref (map/m (λ (x) (stream x (/ x))) '(1 0 3)) 2))) (check-equal? (stream-first (filter/m (λ (x) (stream x (/ x))) '(1 0 3))) '(1 0 3)) (check-exn exn:fail? (λ () (stream-ref (filter/m (λ (x) (stream x (/ x))) '(1 0 3)) 2))) (check-equal? (stream-first (fold/m (λ (x y) (stream (+ x y) (+ (/ x) y))) 1 '(1 0 2))) 4) (check-equal? (stream-ref (fold/m (λ (x y) (stream (+ x y) (+ (/ x) y))) 1 '(1 0 2)) 1) 5/2) (check-exn exn:fail? (λ () (stream-ref (fold/m (λ (x y) (stream (+ x y) (+ (/ x) y))) 1 '(1 0 2)) 2))) (check-exn exn:fail? (λ () (stream-first (map/m (λ (x) (return x (/ x))) '(1 2 0 3))))) (check-exn exn:fail? (λ () (stream-first (filter/m (λ (x) (return x (/ x))) '(1 0 3))))) (check-exn exn:fail? (λ () (stream-first (fold/m (λ (x y) (return (f x y) (f (/ x) y))) 1 (return 1 0 2))))) ) (define-syntax-rule (check-stream-equal?* s1 s2) (check-equal? (sort (stream->list s1) ordered?) (sort (stream->list s2) ordered?))) "Monad Amb" (using-monad Amb) (define-formal f g) (define (F x) (return (f 1 x) (f 2 x))) (define (G x) (return (g 1 x) (g 2 x))) (define (Z x) mzero) (check-stream-equal?* (return 'x) (stream 'x)) (check-stream-equal?* (return 'x 'y) (stream 'x 'y)) (check-stream-equal?* (return 'x 'y 'z) (stream 'x 'y 'z)) (check-stream-equal?* (return 'x 'y 'x) (stream 'x 'y)) (check-stream-equal?* mzero (stream)) (check-stream-equal?* (mplus (stream 1 2) (stream 2 3)) (stream 1 2 3)) (check-stream-equal?* (bind (return 'x) >>= (lift f)) (return (f 'x))) (check-stream-equal?* (bind (return 'x) >>= F) (return (f 1 'x) (f 2 'x))) (check-stream-equal?* (bind (return 'x 'y 'z) >>= (lift f)) (return (f 'x) (f 'y) (f 'z))) (check-stream-equal?* (bind (return 'x 'y 'z) >>= F) (stream (f 1 'x) (f 2 'x) (f 1 'y) (f 2 'y) (f 1 'z) (f 2 'z))) (check-stream-equal?* (bind (return 'x) >>= return) (return 'x)) (check-stream-equal?* (bind (return 'x 'y 'z) >>= return) (return 'x 'y 'z)) (check-stream-equal?* (bind (bind (return 'x) >>= (lift f)) >>= (lift g)) (bind (return 'x) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-stream-equal?* (bind (bind (return 'x 'y) >>= (lift f)) >>= (lift g)) (bind (return 'x 'y) >>= (λ (x) (bind (return (f x)) >>= (lift g))))) (check-stream-equal?* (bind (bind (return 'x) >>= F) >>= G) (bind (return 'x) >>= (λ (x) (bind (F x) >>= G)))) (check-stream-equal?* (bind (bind (return 'x 'y) >>= F) >>= G) (bind (return 'x 'y) >>= (λ (x) (bind (F x) >>= G)))) (check-stream-equal?* (bind mzero >>= (lift f)) mzero) (check-stream-equal?* (bind mzero >>= F) mzero) (check-stream-equal?* (bind (return 'x) >>= (λ (_) mzero)) mzero) (check-stream-equal?* (bind (return 'x 'y) >>= (λ (_) mzero)) mzero) (check-stream-equal?* (mplus mzero (return 'x)) (return 'x)) (check-stream-equal?* (mplus mzero (return 'x 'y)) (return 'x 'y)) (check-stream-equal?* (mplus (return 'x) mzero) (return 'x)) (check-stream-equal?* (mplus (return 'x 'y) mzero) (return 'x 'y)) (check-stream-equal?* (bind (return 'x) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x))) (check-stream-equal?* (bind (return 'x 'y) >>= (guardf (const #t)) >>= (lift g)) (return (g 'x) (g 'y))) (check-stream-equal?* (bind (return 'x) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x))) (check-stream-equal?* (bind (return 'x 'y) >>= (guardf (const #t)) >>= G) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-stream-equal?* (bind (return 'x) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-stream-equal?* (bind (return 'x 'y) >>= (guardf (const #f)) >>= (lift g)) mzero) (check-stream-equal?* (bind (return 'x) >>= (guardf (const #f)) >>= G) mzero) (check-stream-equal?* (bind (return 'x 'y) >>= (guardf (const #f)) >>= G) mzero) (check-stream-equal?* (do [x <-: 'x] (guard #t) (return (g x))) (return (g 'x))) (check-stream-equal?* (do [x <- (return 'x 'y)] (guard #t) (return (g x))) (return (g 'x) (g 'y))) (check-stream-equal?* (do [x <-: 'x] (guard #t) (G x)) (return (g 1 'x) (g 2 'x))) (check-stream-equal?* (do [x <- (return 'x 'y)] (guard #t) (G x)) (return (g 1 'x) (g 2 'x) (g 1 'y) (g 2 'y))) (check-stream-equal?* ((compose/m (lift f) (lift g)) 'x) (return (f (g 'x)))) (check-stream-equal?* ((compose/m (lift f) (lift g)) 'x 'y) (return (f (g 'x)) (f (g 'y)))) (check-stream-equal?* ((compose/m F (lift g)) 'x) (return (f 1 (g 'x)) (f 2 (g 'x)))) (check-stream-equal?* ((compose/m (lift f) G) 'x) (return (f (g 1 'x)) (f (g 2 'x)))) (check-stream-equal?* ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-stream-equal?* ((compose/m F G) 'x) (return (f 1 (g 1 'x)) (f 2 (g 1 'x)) (f 1 (g 2 'x)) (f 2 (g 2 'x)))) (check-stream-equal?* ((compose/m Z G) 'x) mzero) (check-stream-equal?* ((compose/m F Z) 'x) mzero) (check-stream-equal?* (lift/m f (return 'x)) (return (f 'x))) (check-stream-equal?* (lift/m f (return 'x 'y)) (return (f 'x) (f 'y))) (check-stream-equal?* (lift/m f (return 'x) (return 'y)) (return (f 'x 'y))) (check-stream-equal?* (lift/m f (return 'x 'y) (return 'z)) (return (f 'x 'z) (f 'y 'z))) (check-stream-equal?* (lift/m f (return 'x 'y) mzero) mzero) (check-stream-equal?* (lift/m f (return 'x 'y) mzero (return 'z)) mzero) (check-stream-equal?* (fold/m (lift f) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))))) (check-stream-equal?* (fold/m (λ (x y) (return (f x y) (g x y))) 'x '(a b c)) (return (f 'c (f 'b (f 'a 'x))) (g 'c (f 'b (f 'a 'x))) (f 'c (g 'b (f 'a 'x))) (g 'c (g 'b (f 'a 'x))) (f 'c (f 'b (g 'a 'x))) (g 'c (f 'b (g 'a 'x))) (f 'c (g 'b (g 'a 'x))) (g 'c (g 'b (g 'a 'x))))) (check-stream-equal?* (filter/m (lift (const #t)) '(a b c)) (return '(a b c))) (check-stream-equal?* (filter/m (lift (const #f)) '(a b c)) (return '())) (check-stream-equal?* (filter/m (lift (/. 'b --> #f)) '(a b c d)) (return '(a c d))) (check-stream-equal?* (filter/m (lift odd?) '(1 2 3 4 5)) (return '(1 3 5))) (check-stream-equal?* (filter/m (lift odd?) '(1 2 3 4 5 6)) (return '(1 3 5))) (check-stream-equal?* (filter/m (λ (x) (return #t #f)) '(1 2 3)) (return '(1 2 3) '(1 2) '(1 3) '(1) '(2 3) '(2) '(3) '())) (check-stream-equal?* (map/m (lift f) '(a b c)) (return '((f a) (f b) (f c)))) (check-stream-equal?* (map/m F '(a b)) (return '((f 1 a) (f 1 b)) '((f 1 a) (f 2 b)) '((f 2 a) (f 1 b)) '((f 2 a) (f 2 b)))) (check-stream-equal?* (sequence/m (list (return 'a) (return 'b) (return 'c))) (return '(a b c))) (check-stream-equal?* (sequence/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return '(a c d) '(a c e) '(b c d) '(b c e))) (check-stream-equal?* (sequence/m (list (return 'a) mzero (return 'c))) mzero) (check-stream-equal?* (sequence/m (list (return 'a 'b) mzero (return 'c))) mzero) (check-stream-equal?* (sum/m (list (return 'a) (return 'b) (return 'c))) (return 'a 'b 'c)) (check-stream-equal?* (sum/m (list (return 'a 'b) (return 'c) (return 'd 'e))) (return 'a 'b 'c 'd 'e)) (check-stream-equal?* (sum/m (list (return 'a 'b) mzero (return 'd 'e))) (return 'a 'b 'd 'e)) (check-stream-equal?* (do [1 <- '(1 2 3 2 1 2 3)] (return 'y)) (return 'y 'y)) (check-stream-equal?* (collect x [(? odd? x) <- '(1 2 3 2 1 2 3)]) (return 1 3 1 3)) (check-stream-equal?* (collect x [(? odd? x) <- 5]) (return 1 3)) (check-stream-equal?* (collect (cons x y) [(list x y) <- (zip '(a b c) (in-naturals))]) (return '(a . 0) '(b . 1) '(c . 2))) (check-exn exn:fail:contract? (λ () (bind 'x >>= (lift f)))) (check-exn exn:fail:contract? (λ () (bind 'x >>= f))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m f (lift g)) 'x)))) (check-exn exn:fail:contract? (λ () (stream-first ((compose/m (lift f) g) 'x)))) (check-exn exn:fail:contract? (λ () (lift/m f 'x))) (check-exn exn:fail:contract? (λ () (fold/m f 'x '(a b c)))) (check-exn exn:fail:contract? (λ () (map/m f '(a b c)))) (check-exn exn:fail:contract? (λ () (stream-first (sequence/m (list (return 'x) 'y))))) (check-exn exn:fail:contract? (λ () (stream->list (sum/m (list (return 'x) 'y))))) (check-equal? (stream-ref (bind (amb 1 0 2) >>= (lift /)) 0) 1) (check-exn exn:fail? (λ () (stream-ref (bind (amb 1 0 2) >>= (lift /)) 1))) (check-equal? (stream-ref (bind (amb 1 0 2) >>= (lift /) >>= (lift g)) 0) (g 1)) (check-equal? (stream-first ((compose/m (lift log) (lift (curry + 1))) 0 -1)) 0) (check-exn exn:fail? (λ () (stream-ref ((compose/m (lift log) (lift (curry + 1))) 0 -1) 1))) (check-equal? (stream-first (lift/m / (amb 1) (amb 1 0))) 1) (check-exn exn:fail? (λ () (stream-ref (lift/m / (amb 1) (amb 1 0)) 1))) (check-equal? (stream-first (sequence/m (list (amb 1) (amb 0 (/ 0))))) '(1 0)) (check-exn exn:fail? (λ () (stream-ref (sequence/m (list (amb 1) (amb 0 (/ 0)))) 1))) (check-equal? (stream-ref (map/m (λ (x) (amb x (/ x))) '(1 0 3)) 0) '(1 0 3)) (check-equal? (stream-ref (map/m (λ (x) (amb x (/ x))) '(1 0 3)) 1) '(1 0 1/3)) (check-exn exn:fail? (λ () (stream-ref (map/m (λ (x) (amb x (/ x))) '(1 0 3)) 2))) (check-equal? (stream-first (filter/m (λ (x) (amb x (/ x))) '(1 0 3))) '(1 0 3)) (check-exn exn:fail? (λ () (stream-ref (filter/m (λ (x) (amb x (/ x))) '(1 0 3)) 1))) (check-equal? (stream-first (fold/m (λ (x y) (amb (+ x y) (+ (/ x) y))) 1 '(1 0 2))) 4) (check-equal? (stream-ref (fold/m (λ (x y) (amb (+ x y) (+ (/ x) y))) 1 '(1 0 2)) 1) 5/2) (check-exn exn:fail? (λ () (stream-ref (fold/m (λ (x y) (amb (+ x y) (+ (/ x) y))) 1 '(1 0 2)) 2))) )
a525434155620486dc257f9a87605820026b08b263f46925ae9b23e5cffd3128
factisresearch/mq-demo
List.hs
# OPTIONS_GHC -F -pgmF htfpp # {-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # module Mgw.Util.List ( groupOn , groupOn' , groupUnsortedOn , groupUnsortedOn' , extractLast , lastElems , find , ungroupMay , makeMapping , monotone , sconcatBy , stripSuffix , htf_thisModulesTests ) where #include "src/macros.h" ---------------------------------------- -- LOCAL ---------------------------------------- import Mgw.Util.Misc ---------------------------------------- -- SITE-PACKAGES ---------------------------------------- import Data.Hashable (Hashable) import Test.Framework import qualified Data.HashSet as HashSet import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.List.NonEmpty as NL import qualified Data.Semigroup as S ---------------------------------------- -- STDLIB ---------------------------------------- import Data.Ord import Data.Function import Control.Arrow (second) import Data.Foldable (Foldable) import qualified Data.List as L import qualified Data.Foldable as F -- O(n) requires a list sorted by the group key groupOn :: Eq b => (a -> b) -> [a] -> [(b,[a])] groupOn _ [] = [] groupOn proj (x:xs) = (x', (x:ys)) : groupOn proj zs where x' = proj x (ys,zs) = span ((==x') . proj) xs groupUnsortedOn :: Ord b => (a -> b) -> [a] -> [(b,[a])] groupUnsortedOn proj = groupOn proj . L.sortBy (comparing proj) -- O(n) requires a list sorted by the group key groupOn' :: Eq b => (a -> (b,c)) -> [a] -> [(b,[c])] groupOn' proj = map (second (map (snd . proj))) . groupOn (fst . proj) groupUnsortedOn' :: Ord b => (a -> (b,c)) -> [a] -> [(b,[c])] groupUnsortedOn' proj = groupOn' proj . L.sortBy (comparing (fst . proj)) sconcatBy :: (Ord b, Foldable f, S.Semigroup s) => (a -> b) -> (a -> s) -> f a -> [(b,s)] sconcatBy p1 p2 = fmap proj . NL.groupBy ((==) `on` p1) . L.sortBy (comparing p1) . F.toList where proj gr = (p1 $ NL.head gr, S.sconcat $ NL.map p2 gr) extractLast :: a -> [a] -> ([a], a) extractLast x xs = case reverse xs of [] -> ([], x) y:ys -> (x : reverse ys, y) lastElems :: Int -> [a] -> [a] lastElems n = reverse . take n . reverse find :: (Monad m, Foldable f) => (a -> Bool) -> f a -> m a find f xs = maybeToFail "findM: no match" (F.find f xs) ungroupMay :: [(a,[b])] -> Maybe [(a,b)] ungroupMay [] = Just [] ungroupMay ((_,[]):_) = Nothing ungroupMay ((a,bs):rest) = do r <- ungroupMay rest return (map ((,) a) bs ++ r) -- Returns false if and only if there are elements in decreasing order in the list. monotone :: (Ord a) => [a] -> Bool monotone (x0:x1:xs) | x0 <= x1 = monotone (x1:xs) | otherwise = False monotone _ = True -- makeMapping takes a list of pairs and create a list of key-value pairs -- such that each key appears only once in the result list. Moreover, -- the result list contains the pairs in the same order as the input list. -- Example: [(k1, v1), (k2, v2), (k1, v3)] --> [(k2, v2), (k1, v3)] makeMapping :: (Eq a, Hashable a) => [(a, b)] -> [(a, b)] makeMapping l = go (reverse l) HashSet.empty [] where go [] _ acc = acc go (x@(k, _) : xs) done acc = if k `HashSet.member` done then go xs done acc else go xs (HashSet.insert k done) (x:acc) test_ungroup = do assertEqual (Just [("a","1"),("a","2"),("a","3"),("b","4")]) $ ungroupMay [("a",["1","2","3"]),("b",["4"])] test_ungroupGroup = do let list = [("x","1"),("y","1"),("y","3"),("y","1")] assertEqual (Just list) (ungroupMay $ groupOn' id list) test_stripSuffix = do assertEqual (Just "foo") $ stripSuffix "bar" "foobar" assertEqual (Just "") $ stripSuffix "bar" "bar" assertEqual Nothing $ stripSuffix "bar" "foobars" stripSuffix :: (Eq a) => [a] -> [a] -> Maybe [a] stripSuffix s = (fmap reverse) . L.stripPrefix (reverse s) . reverse test_monotone = do assertEqual True $ monotone [1,2,3] assertEqual False $ monotone [-1,0,3,2] assertEqual True $ monotone [1] assertEqual True $ monotone ([] :: [Int]) test_lastElems = do assertEqual ([]::[Int]) (lastElems 100 []) assertEqual [1,2,3] (lastElems 5 [1,2,3]) assertEqual [1,2,3] (lastElems 3 [1,2,3]) assertEqual [2,3] (lastElems 2 [1,2,3]) prop_lastElems :: [Int] -> Int -> Bool prop_lastElems l n = lastElems n l `L.isSuffixOf` l test_makeMapping :: IO () test_makeMapping = do assertEqual [] (makeMapping ([]::[(Int, String)])) let l = [(1::Int, "one"), (2, "two")] in assertEqual l (makeMapping l) assertEqual [(2::Int, "two"), (1, "three")] (makeMapping [(1, "one"), (2, "two"), (1, "three")]) assertEqual [(1::Int, "x")] (makeMapping [(1,"x"),(1,"x")]) prop_makeMappingConcat :: [(Int, String)] -> Bool prop_makeMappingConcat l = makeMapping l == makeMapping (l ++ l) prop_makeMappingKeysUnique :: [(Int, String)] -> Bool prop_makeMappingKeysUnique l = length (map fst (makeMapping l)) == Set.size (Set.fromList (map fst l)) prop_makeMappingKeyValsOk :: [(Int, String)] -> Bool prop_makeMappingKeyValsOk l = Map.fromList (makeMapping l) == Map.fromList l prop_makeMappingOrderingOk :: [(Int, String)] -> Bool prop_makeMappingOrderingOk l = checkOrder (makeMapping l) l where checkOrder [] [] = True checkOrder (x:xs) (y:ys) | x == y = checkOrder xs (dropWhile (x==) ys) | otherwise = checkOrder (x:xs) ys checkOrder _ _ = False
null
https://raw.githubusercontent.com/factisresearch/mq-demo/0efa1991ca647a86a8c22e516a7a1fb392ab4596/server/src/lib/Mgw/Util/List.hs
haskell
# LANGUAGE BangPatterns # -------------------------------------- LOCAL -------------------------------------- -------------------------------------- SITE-PACKAGES -------------------------------------- -------------------------------------- STDLIB -------------------------------------- O(n) requires a list sorted by the group key O(n) requires a list sorted by the group key Returns false if and only if there are elements in decreasing order in the list. makeMapping takes a list of pairs and create a list of key-value pairs such that each key appears only once in the result list. Moreover, the result list contains the pairs in the same order as the input list. Example: [(k1, v1), (k2, v2), (k1, v3)] --> [(k2, v2), (k1, v3)]
# OPTIONS_GHC -F -pgmF htfpp # # LANGUAGE CPP # module Mgw.Util.List ( groupOn , groupOn' , groupUnsortedOn , groupUnsortedOn' , extractLast , lastElems , find , ungroupMay , makeMapping , monotone , sconcatBy , stripSuffix , htf_thisModulesTests ) where #include "src/macros.h" import Mgw.Util.Misc import Data.Hashable (Hashable) import Test.Framework import qualified Data.HashSet as HashSet import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.List.NonEmpty as NL import qualified Data.Semigroup as S import Data.Ord import Data.Function import Control.Arrow (second) import Data.Foldable (Foldable) import qualified Data.List as L import qualified Data.Foldable as F groupOn :: Eq b => (a -> b) -> [a] -> [(b,[a])] groupOn _ [] = [] groupOn proj (x:xs) = (x', (x:ys)) : groupOn proj zs where x' = proj x (ys,zs) = span ((==x') . proj) xs groupUnsortedOn :: Ord b => (a -> b) -> [a] -> [(b,[a])] groupUnsortedOn proj = groupOn proj . L.sortBy (comparing proj) groupOn' :: Eq b => (a -> (b,c)) -> [a] -> [(b,[c])] groupOn' proj = map (second (map (snd . proj))) . groupOn (fst . proj) groupUnsortedOn' :: Ord b => (a -> (b,c)) -> [a] -> [(b,[c])] groupUnsortedOn' proj = groupOn' proj . L.sortBy (comparing (fst . proj)) sconcatBy :: (Ord b, Foldable f, S.Semigroup s) => (a -> b) -> (a -> s) -> f a -> [(b,s)] sconcatBy p1 p2 = fmap proj . NL.groupBy ((==) `on` p1) . L.sortBy (comparing p1) . F.toList where proj gr = (p1 $ NL.head gr, S.sconcat $ NL.map p2 gr) extractLast :: a -> [a] -> ([a], a) extractLast x xs = case reverse xs of [] -> ([], x) y:ys -> (x : reverse ys, y) lastElems :: Int -> [a] -> [a] lastElems n = reverse . take n . reverse find :: (Monad m, Foldable f) => (a -> Bool) -> f a -> m a find f xs = maybeToFail "findM: no match" (F.find f xs) ungroupMay :: [(a,[b])] -> Maybe [(a,b)] ungroupMay [] = Just [] ungroupMay ((_,[]):_) = Nothing ungroupMay ((a,bs):rest) = do r <- ungroupMay rest return (map ((,) a) bs ++ r) monotone :: (Ord a) => [a] -> Bool monotone (x0:x1:xs) | x0 <= x1 = monotone (x1:xs) | otherwise = False monotone _ = True makeMapping :: (Eq a, Hashable a) => [(a, b)] -> [(a, b)] makeMapping l = go (reverse l) HashSet.empty [] where go [] _ acc = acc go (x@(k, _) : xs) done acc = if k `HashSet.member` done then go xs done acc else go xs (HashSet.insert k done) (x:acc) test_ungroup = do assertEqual (Just [("a","1"),("a","2"),("a","3"),("b","4")]) $ ungroupMay [("a",["1","2","3"]),("b",["4"])] test_ungroupGroup = do let list = [("x","1"),("y","1"),("y","3"),("y","1")] assertEqual (Just list) (ungroupMay $ groupOn' id list) test_stripSuffix = do assertEqual (Just "foo") $ stripSuffix "bar" "foobar" assertEqual (Just "") $ stripSuffix "bar" "bar" assertEqual Nothing $ stripSuffix "bar" "foobars" stripSuffix :: (Eq a) => [a] -> [a] -> Maybe [a] stripSuffix s = (fmap reverse) . L.stripPrefix (reverse s) . reverse test_monotone = do assertEqual True $ monotone [1,2,3] assertEqual False $ monotone [-1,0,3,2] assertEqual True $ monotone [1] assertEqual True $ monotone ([] :: [Int]) test_lastElems = do assertEqual ([]::[Int]) (lastElems 100 []) assertEqual [1,2,3] (lastElems 5 [1,2,3]) assertEqual [1,2,3] (lastElems 3 [1,2,3]) assertEqual [2,3] (lastElems 2 [1,2,3]) prop_lastElems :: [Int] -> Int -> Bool prop_lastElems l n = lastElems n l `L.isSuffixOf` l test_makeMapping :: IO () test_makeMapping = do assertEqual [] (makeMapping ([]::[(Int, String)])) let l = [(1::Int, "one"), (2, "two")] in assertEqual l (makeMapping l) assertEqual [(2::Int, "two"), (1, "three")] (makeMapping [(1, "one"), (2, "two"), (1, "three")]) assertEqual [(1::Int, "x")] (makeMapping [(1,"x"),(1,"x")]) prop_makeMappingConcat :: [(Int, String)] -> Bool prop_makeMappingConcat l = makeMapping l == makeMapping (l ++ l) prop_makeMappingKeysUnique :: [(Int, String)] -> Bool prop_makeMappingKeysUnique l = length (map fst (makeMapping l)) == Set.size (Set.fromList (map fst l)) prop_makeMappingKeyValsOk :: [(Int, String)] -> Bool prop_makeMappingKeyValsOk l = Map.fromList (makeMapping l) == Map.fromList l prop_makeMappingOrderingOk :: [(Int, String)] -> Bool prop_makeMappingOrderingOk l = checkOrder (makeMapping l) l where checkOrder [] [] = True checkOrder (x:xs) (y:ys) | x == y = checkOrder xs (dropWhile (x==) ys) | otherwise = checkOrder (x:xs) ys checkOrder _ _ = False
991b533b8d2e714f83d0eebd9f834e2cb122af7833a5a057e3df6d032beeb43e
oliyh/martian
schema.cljc
(ns martian.schema (:require #?(:clj [schema.core :as s] :cljs [schema.core :as s :refer [AnythingSchema Maybe EnumSchema EqSchema]]) #?(:cljs [goog.Uri]) [schema.coerce :as sc] [schema-tools.core :as st] [schema-tools.coerce :as stc] [martian.parameter-aliases :refer [unalias-data]]) #?(:clj (:import [schema.core AnythingSchema Maybe EnumSchema EqSchema]))) (defn- keyword->string [s] (if (keyword? s) (name s) s)) (defn- string-enum-matcher [schema] (when (or (and (instance? EnumSchema schema) (every? string? (.-vs ^EnumSchema schema))) (and (instance? EqSchema schema) (string? (.-v ^EqSchema schema)))) keyword->string)) (defn coercion-matchers [schema] (or (sc/string-coercion-matcher schema) ({s/Str keyword->string} schema) (string-enum-matcher schema))) (defn build-coercion-matchers [use-defaults?] (if use-defaults? (fn [schema] (or (stc/default-matcher schema) (coercion-matchers schema))) coercion-matchers)) (defn- from-maybe [s] (if (instance? Maybe s) (:schema s) s)) (defn coerce-data "Extracts the data referred to by the schema's keys and coerces it" [schema data & [parameter-aliases use-defaults?]] (let [coercion-matchers (build-coercion-matchers use-defaults?)] (when-let [s (from-maybe schema)] (cond (or (coercion-matchers schema) (instance? AnythingSchema s)) ((sc/coercer! schema coercion-matchers) data) (map? s) (stc/coerce (unalias-data parameter-aliases data) s (stc/forwarding-matcher coercion-matchers stc/map-filter-matcher)) (coll? s) ;; primitives, arrays, arrays of maps ((sc/coercer! schema coercion-matchers) (map #(if (map? %) (unalias-data parameter-aliases %) %) data)) :else ((sc/coercer! schema coercion-matchers) data))))) (declare make-schema) (defn schemas-for-parameters "Given a collection of swagger parameters returns a schema map" [ref-lookup parameters] (->> parameters (map (fn [{:keys [name required] :as param}] {(cond-> (keyword name) (not required) s/optional-key) (make-schema ref-lookup param)})) (into {}))) (defn- resolve-ref [ref-lookup ref] (let [[_ category k] (re-find #"#/(definitions|parameters)/(.*)" ref)] (get-in ref-lookup [(keyword category) (keyword k)]))) (def URI #?(:clj java.net.URI :cljs goog.Uri)) (defn leaf-schema [{:keys [type enum format]}] (cond enum (apply s/enum enum) (= "string" type) (case format "uuid" (s/cond-pre s/Str s/Uuid) "uri" (s/cond-pre s/Str URI) "date-time" (s/cond-pre s/Str s/Inst) "int-or-string" (s/cond-pre s/Str s/Int) s/Str) (= "integer" type) s/Int (= "number" type) s/Num (= "boolean" type) s/Bool :else s/Any)) (defn wrap-default [{:keys [default]} schema] (if (some? default) (st/default schema default) schema)) (defn- schema-type [ref-lookup {:keys [type $ref] :as param}] (let [schema (if (or (= "object" type) $ref) (make-schema ref-lookup param) (leaf-schema param))] (wrap-default param schema))) (def ^:dynamic *visited-refs* #{}) (defn- denormalise-object-properties [{:keys [required properties] :as s}] (map (fn [[parameter-name param]] (assoc (if (= "object" (:type param)) (assoc param :properties (into {} (map (juxt :name identity) (denormalise-object-properties param)))) param) :name parameter-name :required (or (when-not (= "object" (:type param)) (:required param)) (and (coll? required) (contains? (set required) (name parameter-name)))))) properties)) (defn- make-object-schema [ref-lookup {:keys [additionalProperties] :as schema}] ;; It's possible for an 'object' to omit properties and ;; additionalProperties. If this is the case - anything is allowed. (if (or (contains? schema :properties) (contains? schema :additionalProperties)) (cond-> (schemas-for-parameters ref-lookup (denormalise-object-properties schema)) additionalProperties (assoc s/Any s/Any)) {s/Any s/Any})) (defn make-schema "Takes a swagger parameter and returns a schema" [ref-lookup {:keys [required type schema $ref items] :as param}] (if (let [ref (or $ref (:$ref schema))] (and ref (contains? *visited-refs* ref))) s/Any ;; avoid potential recursive loops (cond $ref (binding [*visited-refs* (conj *visited-refs* $ref)] (make-schema ref-lookup (-> (dissoc param :$ref) (merge (resolve-ref ref-lookup $ref))))) (:$ref schema) (binding [*visited-refs* (conj *visited-refs* (:$ref schema))] (make-schema ref-lookup (-> (dissoc param :schema) (merge (resolve-ref ref-lookup (:$ref schema)))))) :else (cond-> (cond (= "array" type) [(schema-type ref-lookup (assoc items :required true))] (= "array" (:type schema)) [(schema-type ref-lookup (assoc (:items schema) :required true))] (= "object" type) (make-object-schema ref-lookup param) (= "object" (:type schema)) (make-object-schema ref-lookup schema) :else (schema-type ref-lookup param)) (and (not required) (not= "array" type) (not= "array" (:type schema))) s/maybe))))
null
https://raw.githubusercontent.com/oliyh/martian/9bd47c7df64be544bcb549ce5dfc3c33e85f3193/core/src/martian/schema.cljc
clojure
primitives, arrays, arrays of maps It's possible for an 'object' to omit properties and additionalProperties. If this is the case - anything is allowed. avoid potential recursive loops
(ns martian.schema (:require #?(:clj [schema.core :as s] :cljs [schema.core :as s :refer [AnythingSchema Maybe EnumSchema EqSchema]]) #?(:cljs [goog.Uri]) [schema.coerce :as sc] [schema-tools.core :as st] [schema-tools.coerce :as stc] [martian.parameter-aliases :refer [unalias-data]]) #?(:clj (:import [schema.core AnythingSchema Maybe EnumSchema EqSchema]))) (defn- keyword->string [s] (if (keyword? s) (name s) s)) (defn- string-enum-matcher [schema] (when (or (and (instance? EnumSchema schema) (every? string? (.-vs ^EnumSchema schema))) (and (instance? EqSchema schema) (string? (.-v ^EqSchema schema)))) keyword->string)) (defn coercion-matchers [schema] (or (sc/string-coercion-matcher schema) ({s/Str keyword->string} schema) (string-enum-matcher schema))) (defn build-coercion-matchers [use-defaults?] (if use-defaults? (fn [schema] (or (stc/default-matcher schema) (coercion-matchers schema))) coercion-matchers)) (defn- from-maybe [s] (if (instance? Maybe s) (:schema s) s)) (defn coerce-data "Extracts the data referred to by the schema's keys and coerces it" [schema data & [parameter-aliases use-defaults?]] (let [coercion-matchers (build-coercion-matchers use-defaults?)] (when-let [s (from-maybe schema)] (cond (or (coercion-matchers schema) (instance? AnythingSchema s)) ((sc/coercer! schema coercion-matchers) data) (map? s) (stc/coerce (unalias-data parameter-aliases data) s (stc/forwarding-matcher coercion-matchers stc/map-filter-matcher)) ((sc/coercer! schema coercion-matchers) (map #(if (map? %) (unalias-data parameter-aliases %) %) data)) :else ((sc/coercer! schema coercion-matchers) data))))) (declare make-schema) (defn schemas-for-parameters "Given a collection of swagger parameters returns a schema map" [ref-lookup parameters] (->> parameters (map (fn [{:keys [name required] :as param}] {(cond-> (keyword name) (not required) s/optional-key) (make-schema ref-lookup param)})) (into {}))) (defn- resolve-ref [ref-lookup ref] (let [[_ category k] (re-find #"#/(definitions|parameters)/(.*)" ref)] (get-in ref-lookup [(keyword category) (keyword k)]))) (def URI #?(:clj java.net.URI :cljs goog.Uri)) (defn leaf-schema [{:keys [type enum format]}] (cond enum (apply s/enum enum) (= "string" type) (case format "uuid" (s/cond-pre s/Str s/Uuid) "uri" (s/cond-pre s/Str URI) "date-time" (s/cond-pre s/Str s/Inst) "int-or-string" (s/cond-pre s/Str s/Int) s/Str) (= "integer" type) s/Int (= "number" type) s/Num (= "boolean" type) s/Bool :else s/Any)) (defn wrap-default [{:keys [default]} schema] (if (some? default) (st/default schema default) schema)) (defn- schema-type [ref-lookup {:keys [type $ref] :as param}] (let [schema (if (or (= "object" type) $ref) (make-schema ref-lookup param) (leaf-schema param))] (wrap-default param schema))) (def ^:dynamic *visited-refs* #{}) (defn- denormalise-object-properties [{:keys [required properties] :as s}] (map (fn [[parameter-name param]] (assoc (if (= "object" (:type param)) (assoc param :properties (into {} (map (juxt :name identity) (denormalise-object-properties param)))) param) :name parameter-name :required (or (when-not (= "object" (:type param)) (:required param)) (and (coll? required) (contains? (set required) (name parameter-name)))))) properties)) (defn- make-object-schema [ref-lookup {:keys [additionalProperties] :as schema}] (if (or (contains? schema :properties) (contains? schema :additionalProperties)) (cond-> (schemas-for-parameters ref-lookup (denormalise-object-properties schema)) additionalProperties (assoc s/Any s/Any)) {s/Any s/Any})) (defn make-schema "Takes a swagger parameter and returns a schema" [ref-lookup {:keys [required type schema $ref items] :as param}] (if (let [ref (or $ref (:$ref schema))] (and ref (contains? *visited-refs* ref))) (cond $ref (binding [*visited-refs* (conj *visited-refs* $ref)] (make-schema ref-lookup (-> (dissoc param :$ref) (merge (resolve-ref ref-lookup $ref))))) (:$ref schema) (binding [*visited-refs* (conj *visited-refs* (:$ref schema))] (make-schema ref-lookup (-> (dissoc param :schema) (merge (resolve-ref ref-lookup (:$ref schema)))))) :else (cond-> (cond (= "array" type) [(schema-type ref-lookup (assoc items :required true))] (= "array" (:type schema)) [(schema-type ref-lookup (assoc (:items schema) :required true))] (= "object" type) (make-object-schema ref-lookup param) (= "object" (:type schema)) (make-object-schema ref-lookup schema) :else (schema-type ref-lookup param)) (and (not required) (not= "array" type) (not= "array" (:type schema))) s/maybe))))
3d92bd797e8fc34c31c38e2e82ee14d7e915a9bc2531a403e66b7f97890a4f3a
skrah/minicaml
test40.ml
Example from 's " Modern Compiler Implementation in ML " , translated to . to Caml. *) (* Type mismatch *) let _ = let g (a : unit) = a in g 2
null
https://raw.githubusercontent.com/skrah/minicaml/e5f5cad7fdbcfc11561f717042fae73fa743823f/test/test40.ml
ocaml
Type mismatch
Example from 's " Modern Compiler Implementation in ML " , translated to . to Caml. *) let _ = let g (a : unit) = a in g 2
4945b4bf0e15f6d625d0704822f7bcb25b434d5f65170dd5a5a9fa9b0455daf2
realworldocaml/book
ctypes_stubs.ml
open Import let cflags_sexp ~external_library_name = sprintf "%s__c_flags.sexp" (External_lib_name.to_string external_library_name) let c_generated_functions_cout_no_ext ~external_library_name ~functor_ ~instance = sprintf "%s__c_cout_generated_functions__%s__%s" (External_lib_name.to_string external_library_name) (Module_name.to_string functor_ |> String.lowercase) (Module_name.to_string instance |> String.lowercase) let c_library_flags ~external_library_name = sprintf "%s__c_library_flags.sexp" (External_lib_name.to_string external_library_name) let lib_deps_of_strings ~loc lst = List.map lst ~f:(fun lib -> Lib_dep.Direct (loc, Lib_name.of_string lib)) let libraries_needed_for_ctypes ~loc = let libraries = [ "ctypes"; "ctypes.stubs" ] in lib_deps_of_strings ~loc libraries let add ~loc ~parsing_context ~external_library_name ~add_stubs ~functor_ ~instance ~foreign_stubs = let pos = ("", 0, 0, 0) in let flags = let cflags_sexp_include = Ordered_set_lang.Unexpanded.include_single ~context:parsing_context ~pos (cflags_sexp ~external_library_name) in Ordered_set_lang.Unexpanded.concat ~context:parsing_context ~pos Ordered_set_lang.Unexpanded.standard cflags_sexp_include in add_stubs Foreign_language.C ~loc ~names: (Some (Ordered_set_lang.of_atoms ~loc [ c_generated_functions_cout_no_ext ~external_library_name ~functor_ ~instance ])) ~flags:(Some flags) foreign_stubs
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/ctypes_stubs.ml
ocaml
open Import let cflags_sexp ~external_library_name = sprintf "%s__c_flags.sexp" (External_lib_name.to_string external_library_name) let c_generated_functions_cout_no_ext ~external_library_name ~functor_ ~instance = sprintf "%s__c_cout_generated_functions__%s__%s" (External_lib_name.to_string external_library_name) (Module_name.to_string functor_ |> String.lowercase) (Module_name.to_string instance |> String.lowercase) let c_library_flags ~external_library_name = sprintf "%s__c_library_flags.sexp" (External_lib_name.to_string external_library_name) let lib_deps_of_strings ~loc lst = List.map lst ~f:(fun lib -> Lib_dep.Direct (loc, Lib_name.of_string lib)) let libraries_needed_for_ctypes ~loc = let libraries = [ "ctypes"; "ctypes.stubs" ] in lib_deps_of_strings ~loc libraries let add ~loc ~parsing_context ~external_library_name ~add_stubs ~functor_ ~instance ~foreign_stubs = let pos = ("", 0, 0, 0) in let flags = let cflags_sexp_include = Ordered_set_lang.Unexpanded.include_single ~context:parsing_context ~pos (cflags_sexp ~external_library_name) in Ordered_set_lang.Unexpanded.concat ~context:parsing_context ~pos Ordered_set_lang.Unexpanded.standard cflags_sexp_include in add_stubs Foreign_language.C ~loc ~names: (Some (Ordered_set_lang.of_atoms ~loc [ c_generated_functions_cout_no_ext ~external_library_name ~functor_ ~instance ])) ~flags:(Some flags) foreign_stubs
d93a0d54be9773e0950b1dc520a3b0f53175cad7f9dafd18d2ffdd6810eca725
DSiSc/why3
ocaml_printer.ml
(********************************************************************) (* *) The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University (* *) (* This software is distributed under the terms of the GNU Lesser *) General Public License version 2.1 , with the special exception (* on linking described in file LICENSE. *) (* *) (********************************************************************) (** Printer for extracted OCaml code *) open Compile open Format open Ident open Pp open Ity open Term open Expr open Ty open Theory open Pmodule open Wstdlib open Pdecl open Printer type info = { info_syn : syntax_map; info_convert : syntax_map; info_literal : syntax_map; info_current_th : Theory.theory; info_current_mo : Pmodule.pmodule option; info_th_known_map : Decl.known_map; info_mo_known_map : Pdecl.known_map; info_fname : string option; info_flat : bool; info_current_ph : string list; (* current path *) } module Print = struct open Mltree (* extraction attributes *) let optional_arg = create_attribute "ocaml:optional" let named_arg = create_attribute "ocaml:named" let ocaml_remove = create_attribute "ocaml:remove" let is_optional ~attrs = Sattr.mem optional_arg attrs let is_named ~attrs = Sattr.mem named_arg attrs let is_ocaml_remove ~attrs = Ident.Sattr.mem ocaml_remove attrs let ocaml_keywords = ["and"; "as"; "assert"; "asr"; "begin"; "class"; "constraint"; "do"; "done"; "downto"; "else"; "end"; "exception"; "external"; "false"; "for"; "fun"; "function"; "functor"; "if"; "in"; "include"; "inherit"; "initializer"; "land"; "lazy"; "let"; "lor"; "lsl"; "lsr"; "lxor"; "match"; "method"; "mod"; "module"; "mutable"; "new"; "object"; "of"; "open"; "or"; "private"; "rec"; "sig"; "struct"; "then"; "to"; "true"; "try"; "type"; "val"; "virtual"; "when"; "while"; "with"; "raise";] let _is_ocaml_keyword = let h = Hstr.create 16 in List.iter (fun s -> Hstr.add h s ()) ocaml_keywords; Hstr.mem h (* iprinter: local names aprinter: type variables tprinter: toplevel definitions *) let iprinter, aprinter, tprinter = let isanitize = sanitizer char_to_alpha char_to_alnumus in let lsanitize = sanitizer char_to_lalpha char_to_alnumus in create_ident_printer ocaml_keywords ~sanitizer:isanitize, create_ident_printer ocaml_keywords ~sanitizer:lsanitize, create_ident_printer ocaml_keywords ~sanitizer:lsanitize let forget_id id = forget_id iprinter id let _forget_ids = List.iter forget_id let forget_var (id, _, _) = forget_id id let forget_vars = List.iter forget_var let forget_let_defn = function | Lvar (v,_) -> forget_id v.pv_vs.vs_name | Lsym (s,_,_,_) | Lany (s,_,_) -> forget_rs s | Lrec rdl -> List.iter (fun fd -> forget_rs fd.rec_sym) rdl let rec forget_pat = function | Pwild -> () | Pvar {vs_name=id} -> forget_id id | Papp (_, pl) | Ptuple pl -> List.iter forget_pat pl | Por (p1, p2) -> forget_pat p1; forget_pat p2 | Pas (p, _) -> forget_pat p let print_global_ident ~sanitizer fmt id = let s = id_unique ~sanitizer tprinter id in Ident.forget_id tprinter id; fprintf fmt "%s" s let print_path ~sanitizer fmt (q, id) = assert (List.length q >= 1); match Lists.chop_last q with | [], _ -> print_global_ident ~sanitizer fmt id | q, _ -> fprintf fmt "%a.%a" (print_list dot string) q (print_global_ident ~sanitizer) id let rec remove_prefix acc current_path = match acc, current_path with | [], _ | _, [] -> acc | p1 :: _, p2 :: _ when p1 <> p2 -> acc | _ :: r1, _ :: r2 -> remove_prefix r1 r2 let is_local_id info id = Sid.mem id info.info_current_th.th_local || Opt.fold (fun _ m -> Sid.mem id m.Pmodule.mod_local) false info.info_current_mo exception Local let print_qident ~sanitizer info fmt id = try if info.info_flat then raise Not_found; if is_local_id info id then raise Local; let p, t, q = try Pmodule.restore_path id with Not_found -> Theory.restore_path id in let fname = if p = [] then info.info_fname else None in let m = Strings.capitalize (module_name ?fname p t) in fprintf fmt "%s.%a" m (print_path ~sanitizer) (q, id) with | Not_found -> let s = id_unique ~sanitizer iprinter id in fprintf fmt "%s" s | Local -> let _, _, q = try Pmodule.restore_path id with Not_found -> Theory.restore_path id in let q = remove_prefix q (List.rev info.info_current_ph) in print_path ~sanitizer fmt (q, id) let print_lident = print_qident ~sanitizer:Strings.uncapitalize let print_uident = print_qident ~sanitizer:Strings.capitalize let print_tv fmt tv = fprintf fmt "'%s" (id_unique aprinter tv.tv_name) let protect_on b s = if b then "(" ^^ s ^^ ")" else s let star fmt () = fprintf fmt " *@ " let rec print_list2 sep sep_m print1 print2 fmt (l1, l2) = match l1, l2 with | [x1], [x2] -> print1 fmt x1; sep_m fmt (); print2 fmt x2 | x1 :: r1, x2 :: r2 -> print1 fmt x1; sep_m fmt (); print2 fmt x2; sep fmt (); print_list2 sep sep_m print1 print2 fmt (r1, r2) | _ -> () let print_rs info fmt rs = fprintf fmt "%a" (print_lident info) rs.rs_name (** Types *) let rec print_ty ?(paren=false) info fmt = function | Tvar tv -> print_tv fmt tv | Ttuple [] -> fprintf fmt "unit" | Ttuple [t] -> print_ty ~paren info fmt t | Ttuple tl -> fprintf fmt (protect_on paren "@[%a@]") (print_list star (print_ty ~paren:true info)) tl | Tapp (ts, tl) -> match query_syntax info.info_syn ts with | Some s -> fprintf fmt (protect_on paren "%a") (syntax_arguments s (print_ty ~paren:true info)) tl | None -> match tl with | [] -> (print_lident info) fmt ts | [ty] -> fprintf fmt (protect_on paren "%a@ %a") (print_ty ~paren:true info) ty (print_lident info) ts | tl -> fprintf fmt (protect_on paren "(%a)@ %a") (print_list comma (print_ty ~paren:false info)) tl (print_lident info) ts let print_vsty_opt info fmt id ty = fprintf fmt "?%s:(%a:@ %a)" id.id_string (print_lident info) id (print_ty ~paren:false info) ty let print_vsty_named info fmt id ty = fprintf fmt "~%s:(%a:@ %a)" id.id_string (print_lident info) id (print_ty ~paren:false info) ty let print_vsty info fmt (id, ty, _) = let attrs = id.id_attrs in if is_optional ~attrs then print_vsty_opt info fmt id ty else if is_named ~attrs then print_vsty_named info fmt id ty else fprintf fmt "(%a:@ %a)" (print_lident info) id (print_ty ~paren:false info) ty let print_tv_arg = print_tv let print_tv_args fmt = function | [] -> () | [tv] -> fprintf fmt "%a@ " print_tv_arg tv | tvl -> fprintf fmt "(%a)@ " (print_list comma print_tv_arg) tvl let print_vs_arg info fmt vs = fprintf fmt "@[%a@]" (print_vsty info) vs let get_record info rs = match Mid.find_opt rs.rs_name info.info_mo_known_map with | Some {pd_node = PDtype itdl} -> let eq_rs {itd_constructors} = List.exists (rs_equal rs) itd_constructors in let itd = List.find eq_rs itdl in List.filter (fun e -> not (rs_ghost e)) itd.itd_fields | _ -> [] let rec print_pat info fmt = function | Pwild -> fprintf fmt "_" | Pvar {vs_name=id} -> (print_lident info) fmt id | Pas (p, {vs_name=id}) -> fprintf fmt "%a as %a" (print_pat info) p (print_lident info) id | Por (p1, p2) -> fprintf fmt "%a | %a" (print_pat info) p1 (print_pat info) p2 | Ptuple pl -> fprintf fmt "(%a)" (print_list comma (print_pat info)) pl | Papp (ls, pl) -> match query_syntax info.info_syn ls.ls_name, pl with | Some s, _ -> syntax_arguments s (print_pat info) fmt pl | None, pl -> let pjl = let rs = restore_rs ls in get_record info rs in match pjl with | [] -> print_papp info ls fmt pl | pjl -> fprintf fmt "@[<hov 2>{ %a }@]" (print_list2 semi equal (print_rs info) (print_pat info)) (pjl, pl) and print_papp info ls fmt = function | [] -> fprintf fmt "%a" (print_uident info) ls.ls_name | [p] -> fprintf fmt "%a %a" (print_uident info) ls.ls_name (print_pat info) p | pl -> fprintf fmt "%a (%a)" (print_uident info) ls.ls_name (print_list comma (print_pat info)) pl (** Expressions *) let pv_name pv = pv.pv_vs.vs_name let print_pv info fmt pv = print_lident info fmt (pv_name pv) let ht_rs = Hrs.create 7 (* rec_rsym -> rec_sym *) FIXME put these in Compile let is_true e = match e.e_node with | Eapp (s, []) -> rs_equal s rs_true | _ -> false let is_false e = match e.e_node with | Eapp (s, []) -> rs_equal s rs_false | _ -> false let check_val_in_drv info ({rs_name = {id_loc = loc}} as rs) = (* here [rs] refers to a [val] declaration *) match query_syntax info.info_convert rs.rs_name, query_syntax info.info_syn rs.rs_name with | None, None (* when info.info_flat *) -> Loc.errorm ?loc "Function %a cannot be extracted" Expr.print_rs rs | _ -> () let is_mapped_to_int info ity = match ity.ity_node with | Ityapp ({ its_ts = ts }, _, _) -> query_syntax info.info_syn ts.ts_name = Some "int" | _ -> false let print_constant fmt e = begin match e.e_node with | Econst c -> let s = BigInt.to_string (Number.compute_int_constant c) in if c.Number.ic_negative then fprintf fmt "(%s)" s else fprintf fmt "%s" s | _ -> assert false end let print_for_direction fmt = function | To -> fprintf fmt "to" | DownTo -> fprintf fmt "downto" let rec print_apply_args info fmt = function | expr :: exprl, pv :: pvl -> if is_optional ~attrs:(pv_name pv).id_attrs then begin match expr.e_node with | Eapp (rs, _) when query_syntax info.info_syn rs.rs_name = Some "None" -> () | _ -> fprintf fmt "?%s:%a" (pv_name pv).id_string (print_expr ~paren:true info) expr end else if is_named ~attrs:(pv_name pv).id_attrs then fprintf fmt "~%s:%a" (pv_name pv).id_string (print_expr ~paren:true info) expr else fprintf fmt "%a" (print_expr ~paren:true info) expr; if exprl <> [] then fprintf fmt "@ "; print_apply_args info fmt (exprl, pvl) | expr :: exprl, [] -> fprintf fmt "%a" (print_expr ~paren:true info) expr; print_apply_args info fmt (exprl, []) | [], _ -> () and print_apply info rs fmt pvl = let isfield = match rs.rs_field with | None -> false | Some _ -> true in let isconstructor () = match Mid.find_opt rs.rs_name info.info_mo_known_map with | Some {pd_node = PDtype its} -> let is_constructor its = List.exists (rs_equal rs) its.itd_constructors in List.exists is_constructor its | _ -> false in match query_syntax info.info_convert rs.rs_name, query_syntax info.info_syn rs.rs_name, pvl with | Some s, _, [{e_node = Econst _}] -> syntax_arguments s print_constant fmt pvl | _, Some s, _ (* when is_local_id info rs.rs_name *)-> syntax_arguments s (print_expr ~paren:true info) fmt pvl; | _, None, tl when is_rs_tuple rs -> fprintf fmt "@[(%a)@]" (print_list comma (print_expr info)) tl | _, None, [t1] when isfield -> fprintf fmt "%a.%a" (print_expr info) t1 (print_lident info) rs.rs_name | _, None, tl when isconstructor () -> let pjl = get_record info rs in begin match pjl, tl with | [], [] -> (print_uident info) fmt rs.rs_name | [], [t] -> fprintf fmt "@[<hov 2>%a %a@]" (print_uident info) rs.rs_name (print_expr ~paren:true info) t | [], tl -> fprintf fmt "@[<hov 2>%a (%a)@]" (print_uident info) rs.rs_name (print_list comma (print_expr ~paren:true info)) tl | pjl, tl -> let equal fmt () = fprintf fmt " =@ " in fprintf fmt "@[<hov 2>{ %a }@]" (print_list2 semi equal (print_rs info) (print_expr ~paren:true info)) (pjl, tl) end | _, None, [] -> (print_lident info) fmt rs.rs_name | _, _, tl -> fprintf fmt "@[<hov 2>%a %a@]" (print_lident info) rs.rs_name (print_apply_args info) (tl, rs.rs_cty.cty_args) (* (print_list space (print_expr ~paren:true info)) tl *) and print_svar fmt s = Stv.iter (fun tv -> fprintf fmt "%a " print_tv tv) s and print_fun_type_args info fmt (args, s, res, e) = if Stv.is_empty s then fprintf fmt "@[%a@] :@ %a@ =@ %a" (print_list space (print_vs_arg info)) args (print_ty info) res (print_expr info) e else let ty_args = List.map (fun (_, ty, _) -> ty) args in let id_args = List.map (fun (id, _, _) -> id) args in let arrow fmt () = fprintf fmt " ->@ " in fprintf fmt ":@ @[<h>@[%a@]. @[%a ->@ %a@]@] =@ \ @[<hov 2>fun @[%a@]@ ->@ %a@]" print_svar s (print_list arrow (print_ty ~paren:true info)) ty_args (print_ty ~paren:true info) res (print_list space (print_lident info)) id_args (print_expr info) e and print_let_def ?(functor_arg=false) info fmt = function | Lvar (pv, {e_node = Eany ty}) when functor_arg -> fprintf fmt "@[<hov 2>val %a : %a@]" (print_lident info) (pv_name pv) (print_ty info) ty; | Lvar (pv, e) -> fprintf fmt "@[<hov 2>let %a =@ %a@]" (print_lident info) (pv_name pv) (print_expr info) e; | Lsym (rs, res, args, ef) -> fprintf fmt "@[<hov 2>let %a @[%a@] : %a@ =@ @[%a@]@]" (print_lident info) rs.rs_name (print_list space (print_vs_arg info)) args (print_ty info) res (print_expr info) ef; forget_vars args | Lrec rdef -> let print_one fst fmt = function | { rec_sym = rs1; rec_args = args; rec_exp = e; rec_res = res; rec_svar = s } -> fprintf fmt "@[<hov 2>%s %a %a@]" (if fst then "let rec" else "and") (print_lident info) rs1.rs_name (print_fun_type_args info) (args, s, res, e); forget_vars args in List.iter (fun fd -> Hrs.replace ht_rs fd.rec_rsym fd.rec_sym) rdef; print_list_next newline print_one fmt rdef; List.iter (fun fd -> Hrs.remove ht_rs fd.rec_rsym) rdef | Lany (rs, res, []) when functor_arg -> fprintf fmt "@[<hov 2>val %a : %a@]" (print_lident info) rs.rs_name (print_ty info) res; | Lany (rs, res, args) when functor_arg -> let print_ty_arg info fmt (_, ty, _) = fprintf fmt "@[%a@]" (print_ty info) ty in fprintf fmt "@[<hov 2>val %a : @[%a@] ->@ %a@]" (print_lident info) rs.rs_name (print_list arrow (print_ty_arg info)) args (print_ty info) res; forget_vars args | Lany (rs, _, _) -> check_val_in_drv info rs and print_expr ?(paren=false) info fmt e = match e.e_node with | Econst c -> let n = Number.compute_int_constant c in let n = BigInt.to_string n in let id = match e.e_ity with | I { ity_node = Ityapp ({its_ts = ts},_,_) } -> ts.ts_name | _ -> assert false in (match query_syntax info.info_literal id with | Some s -> syntax_arguments s print_constant fmt [e] | None when n = "0" -> fprintf fmt "Z.zero" | None when n = "1" -> fprintf fmt "Z.one" | None -> fprintf fmt (protect_on paren "Z.of_string \"%s\"") n) | Evar pvs -> (print_lident info) fmt (pv_name pvs) | Elet (let_def, e) -> fprintf fmt (protect_on paren "@[%a@] in@ @[%a@]") (print_let_def info) let_def (print_expr info) e; forget_let_defn let_def | Eabsurd -> fprintf fmt (protect_on paren "assert false (* absurd *)") | Ehole -> () | Eany _ -> assert false | Eapp (rs, []) when rs_equal rs rs_true -> fprintf fmt "true" | Eapp (rs, []) when rs_equal rs rs_false -> fprintf fmt "false" | Eapp (rs, []) -> (* avoids parenthesis around values *) fprintf fmt "%a" (print_apply info (Hrs.find_def ht_rs rs rs)) [] | Eapp (rs, pvl) -> begin match query_syntax info.info_convert rs.rs_name, pvl with | Some s, [{e_node = Econst _}] -> syntax_arguments s print_constant fmt pvl | _ -> fprintf fmt (protect_on paren "%a") (print_apply info (Hrs.find_def ht_rs rs rs)) pvl end | Ematch (e1, [p, e2], []) -> fprintf fmt (protect_on paren "let %a =@ %a in@ %a") (print_pat info) p (print_expr info) e1 (print_expr info) e2 | Ematch (e, pl, []) -> fprintf fmt (protect_on paren "begin match @[%a@] with@\n@[<hov>%a@]@\nend") (print_expr info) e (print_list newline (print_branch info)) pl | Eassign al -> let assign fmt (rho, rs, pv) = fprintf fmt "@[<hov 2>%a.%a <-@ %a@]" (print_lident info) (pv_name rho) (print_lident info) rs.rs_name (print_lident info) (pv_name pv) in begin match al with | [] -> assert false | [a] -> assign fmt a | al -> fprintf fmt "@[begin %a end@]" (print_list semi assign) al end | Eif (e1, e2, {e_node = Eblock []}) -> fprintf fmt (protect_on paren "@[<hv>@[<hov 2>if@ %a@]@ then begin@;<1 2>@[%a@] end@]") (print_expr info) e1 (print_expr info) e2 | Eif (e1, e2, e3) when is_false e2 && is_true e3 -> fprintf fmt (protect_on paren "not %a") (print_expr info ~paren:true) e1 | Eif (e1, e2, e3) when is_true e2 -> fprintf fmt (protect_on paren "@[<hv>%a || %a@]") (print_expr info ~paren:true) e1 (print_expr info ~paren:true) e3 | Eif (e1, e2, e3) when is_false e3 -> fprintf fmt (protect_on paren "@[<hv>%a && %a@]") (print_expr info ~paren:true) e1 (print_expr info ~paren:true) e2 | Eif (e1, e2, e3) -> fprintf fmt (protect_on paren "@[<hv>@[<hov 2>if@ %a@ then@ begin@ @[%a@] end@]\ @;<1 0>else@ begin@;<1 2>@[%a@] end@]") (print_expr info) e1 (print_expr info) e2 (print_expr info) e3 | Eblock [] -> fprintf fmt "()" | Eblock [e] -> print_expr info fmt e | Eblock el -> fprintf fmt "@[<hv>begin@;<1 2>@[%a@]@ end@]" (print_list semi (print_expr info)) el | Efun (varl, e) -> fprintf fmt (protect_on paren "@[<hov 2>fun %a ->@ %a@]") (print_list space (print_vs_arg info)) varl (print_expr info) e | Ewhile (e1, e2) -> fprintf fmt "@[<hov 2>while %a do@\n%a@ done@]" (print_expr info) e1 (print_expr info) e2 | Eraise (xs, e_opt) -> print_raise ~paren info xs fmt e_opt | Efor (pv1, pv2, dir, pv3, e) -> if is_mapped_to_int info pv1.pv_ity then fprintf fmt "@[<hov 2>for %a = %a %a %a do@ @[%a@]@ done@]" (print_lident info) (pv_name pv1) (print_lident info) (pv_name pv2) print_for_direction dir (print_lident info) (pv_name pv3) (print_expr info) e else let for_id = id_register (id_fresh "for_loop_to") in let cmp, op = match dir with | To -> "Z.leq", "Z.succ" | DownTo -> "Z.geq", "Z.pred" in fprintf fmt (protect_on paren "@[<hov 2>let rec %a %a =@ if %s %a %a then \ begin@ %a; %a (%s %a) end@ in@ %a %a@]") (* let rec *) (print_lident info) for_id (print_pv info) pv1 (* if *) cmp (print_pv info) pv1 (print_pv info) pv3 (* then *) (print_expr info) e (print_lident info) for_id op (print_pv info) pv1 (* in *) (print_lident info) for_id (print_pv info) pv2 | Ematch (e, [], xl) -> fprintf fmt "@[<hv>@[<hov 2>begin@ try@ %a@] with@]@\n@[<hov>%a@]@\nend" (print_expr info) e (print_list newline (print_xbranch info false)) xl | Ematch (e, bl, xl) -> fprintf fmt (protect_on paren "begin match @[%a@] with@\n@[<hov>%a@\n%a@]@\nend") (print_expr info) e (print_list newline (print_branch info)) bl (print_list newline (print_xbranch info true)) xl | Eexn (xs, None, e) -> fprintf fmt "@[<hv>let exception %a in@\n%a@]" (print_uident info) xs.xs_name (print_expr info) e | Eexn (xs, Some t, e) -> fprintf fmt "@[<hv>let exception %a of %a in@\n%a@]" (print_uident info) xs.xs_name (print_ty ~paren:true info) t (print_expr info) e | Eignore e -> fprintf fmt "ignore (%a)" (print_expr info) e and print_branch info fmt (p, e) = fprintf fmt "@[<hov 2>| %a ->@ @[%a@]@]" (print_pat info) p (print_expr info) e; forget_pat p and print_raise ~paren info xs fmt e_opt = match query_syntax info.info_syn xs.xs_name, e_opt with | Some s, None -> fprintf fmt "raise (%s)" s | Some s, Some e -> fprintf fmt (protect_on paren "raise (%a)") (syntax_arguments s (print_expr info)) [e] | None, None -> fprintf fmt (protect_on paren "raise %a") (print_uident info) xs.xs_name | None, Some e -> fprintf fmt (protect_on paren "raise (%a %a)") (print_uident info) xs.xs_name (print_expr ~paren:true info) e and print_xbranch info case fmt (xs, pvl, e) = let print_exn fmt () = if case then fprintf fmt "exception " else fprintf fmt "" in let print_var fmt pv = print_lident info fmt (pv_name pv) in match query_syntax info.info_syn xs.xs_name, pvl with | Some s, _ -> fprintf fmt "@[<hov 4>| %a%a ->@ %a@]" print_exn () (syntax_arguments s print_var) pvl (print_expr info ~paren:true) e | None, [] -> fprintf fmt "@[<hov 4>| %a%a ->@ %a@]" print_exn () (print_uident info) xs.xs_name (print_expr info) e | None, [pv] -> fprintf fmt "@[<hov 4>| %a%a %a ->@ %a@]" print_exn () (print_uident info) xs.xs_name print_var pv (print_expr info) e | None, pvl -> fprintf fmt "@[<hov 4>| %a%a (%a) ->@ %a@]" print_exn () (print_uident info) xs.xs_name (print_list comma print_var) pvl (print_expr info) e let print_type_decl info fst fmt its = let print_constr fmt (id, cs_args) = match cs_args with | [] -> fprintf fmt "@[<hov 4>| %a@]" (print_uident info) id | l -> fprintf fmt "@[<hov 4>| %a of %a@]" (print_uident info) id (print_list star (print_ty ~paren:false info)) l in let print_field fmt (is_mutable, id, ty) = fprintf fmt "%s%a: @[%a@];" (if is_mutable then "mutable " else "") (print_lident info) id (print_ty ~paren:false info) ty in let print_def fmt = function | None -> () | Some (Ddata csl) -> fprintf fmt " =@\n%a" (print_list newline print_constr) csl | Some (Drecord fl) -> fprintf fmt " = %s{@\n%a@\n}" (if its.its_private then "private " else "") (print_list newline print_field) fl | Some (Dalias ty) -> fprintf fmt " =@ %a" (print_ty ~paren:false info) ty | Some (Drange _) -> fprintf fmt " =@ Z.t" | Some (Dfloat _) -> TODO in let attrs = its.its_name.id_attrs in if not (is_ocaml_remove ~attrs) then fprintf fmt "@[<hov 2>@[%s %a%a@]%a@]" (if fst then "type" else "and") print_tv_args its.its_args (print_lident info) its.its_name print_def its.its_def let rec is_signature_decl info = function | Dtype _ -> true | Dlet (Lany _) -> true | Dlet (Lvar (_, {e_node = Eany _})) -> true | Dlet _ -> false | Dexn _ -> true | Dmodule (_, dl) -> is_signature info dl and is_signature info dl = List.for_all (is_signature_decl info) dl let extract_functor_args info dl = let rec extract args = function FIXME remove empty args ? | ( _ , [ ] ) : : dl - > extract args dl | Dmodule (x, dlx) :: dl when is_signature info dlx -> extract ((x, dlx) :: args) dl | dl -> List.rev args, dl in extract [] dl let rec print_decl ?(functor_arg=false) info fmt = function | Dlet ldef -> print_let_def info ~functor_arg fmt ldef | Dtype dl -> print_list_next newline (print_type_decl info) fmt dl | Dexn (xs, None) -> fprintf fmt "exception %a" (print_uident info) xs.xs_name | Dexn (xs, Some t)-> fprintf fmt "@[<hov 2>exception %a of %a@]" (print_uident info) xs.xs_name (print_ty ~paren:true info) t | Dmodule (s, dl) -> let args, dl = extract_functor_args info dl in let info = { info with info_current_ph = s :: info.info_current_ph } in fprintf fmt "@[@[<hov 2>module %s%a@ =@]@\n@[<hov 2>struct@ %a@]@ end" s (print_functor_args info) args (print_list newline2 (print_decl info)) dl and print_functor_args info fmt args = let print_sig info fmt dl = fprintf fmt "sig@ %a@ end" (print_list newline (print_decl info ~functor_arg:true)) dl in let print_pair fmt (s, dl) = let info = { info with info_current_ph = s :: info.info_current_ph } in fprintf fmt "(%s:@ %a)" s (print_sig info) dl in fprintf fmt "%a" (print_list space print_pair) args let print_decl info fmt decl = (* avoids printing the same decl for mutually recursive decls *) let memo = Hashtbl.create 64 in let decl_name = get_decl_name decl in let decide_print id = if query_syntax info.info_syn id = None && not (Hashtbl.mem memo decl) then begin Hashtbl.add memo decl (); print_decl info fmt decl; fprintf fmt "@\n@." end in List.iter decide_print decl_name end let print_decl = let memo = Hashtbl.create 16 in fun pargs ?old ?fname ~flat ({mod_theory = th} as m) fmt d -> ignore (old); let info = { info_syn = pargs.Pdriver.syntax; info_convert = pargs.Pdriver.converter; info_literal = pargs.Pdriver.literal; info_current_th = th; info_current_mo = Some m; info_th_known_map = th.th_known; info_mo_known_map = m.mod_known; info_fname = Opt.map Compile.clean_name fname; info_flat = flat; info_current_ph = []; } in if not (Hashtbl.mem memo d) then begin Hashtbl.add memo d (); Print.print_decl info fmt d end let ng suffix ?fname m = let mod_name = m.mod_theory.th_name.id_string in let path = m.mod_theory.th_path in (module_name ?fname path mod_name) ^ suffix let file_gen = ng ".ml" let mli_gen = ng ".mli" open Pdriver let ocaml_printer = { desc = "printer for Ocaml code"; file_gen = file_gen; decl_printer = print_decl; interf_gen = Some mli_gen; interf_printer = None; prelude_printer = print_empty_prelude } let () = Pdriver.register_printer "ocaml" ocaml_printer
null
https://raw.githubusercontent.com/DSiSc/why3/8ba9c2287224b53075adc51544bc377bc8ea5c75/src/mlw/ocaml_printer.ml
ocaml
****************************************************************** This software is distributed under the terms of the GNU Lesser on linking described in file LICENSE. ****************************************************************** * Printer for extracted OCaml code current path extraction attributes iprinter: local names aprinter: type variables tprinter: toplevel definitions * Types * Expressions rec_rsym -> rec_sym here [rs] refers to a [val] declaration when info.info_flat when is_local_id info rs.rs_name (print_list space (print_expr ~paren:true info)) tl avoids parenthesis around values let rec if then in avoids printing the same decl for mutually recursive decls
The Why3 Verification Platform / The Why3 Development Team Copyright 2010 - 2018 -- Inria - CNRS - Paris - Sud University General Public License version 2.1 , with the special exception open Compile open Format open Ident open Pp open Ity open Term open Expr open Ty open Theory open Pmodule open Wstdlib open Pdecl open Printer type info = { info_syn : syntax_map; info_convert : syntax_map; info_literal : syntax_map; info_current_th : Theory.theory; info_current_mo : Pmodule.pmodule option; info_th_known_map : Decl.known_map; info_mo_known_map : Pdecl.known_map; info_fname : string option; info_flat : bool; } module Print = struct open Mltree let optional_arg = create_attribute "ocaml:optional" let named_arg = create_attribute "ocaml:named" let ocaml_remove = create_attribute "ocaml:remove" let is_optional ~attrs = Sattr.mem optional_arg attrs let is_named ~attrs = Sattr.mem named_arg attrs let is_ocaml_remove ~attrs = Ident.Sattr.mem ocaml_remove attrs let ocaml_keywords = ["and"; "as"; "assert"; "asr"; "begin"; "class"; "constraint"; "do"; "done"; "downto"; "else"; "end"; "exception"; "external"; "false"; "for"; "fun"; "function"; "functor"; "if"; "in"; "include"; "inherit"; "initializer"; "land"; "lazy"; "let"; "lor"; "lsl"; "lsr"; "lxor"; "match"; "method"; "mod"; "module"; "mutable"; "new"; "object"; "of"; "open"; "or"; "private"; "rec"; "sig"; "struct"; "then"; "to"; "true"; "try"; "type"; "val"; "virtual"; "when"; "while"; "with"; "raise";] let _is_ocaml_keyword = let h = Hstr.create 16 in List.iter (fun s -> Hstr.add h s ()) ocaml_keywords; Hstr.mem h let iprinter, aprinter, tprinter = let isanitize = sanitizer char_to_alpha char_to_alnumus in let lsanitize = sanitizer char_to_lalpha char_to_alnumus in create_ident_printer ocaml_keywords ~sanitizer:isanitize, create_ident_printer ocaml_keywords ~sanitizer:lsanitize, create_ident_printer ocaml_keywords ~sanitizer:lsanitize let forget_id id = forget_id iprinter id let _forget_ids = List.iter forget_id let forget_var (id, _, _) = forget_id id let forget_vars = List.iter forget_var let forget_let_defn = function | Lvar (v,_) -> forget_id v.pv_vs.vs_name | Lsym (s,_,_,_) | Lany (s,_,_) -> forget_rs s | Lrec rdl -> List.iter (fun fd -> forget_rs fd.rec_sym) rdl let rec forget_pat = function | Pwild -> () | Pvar {vs_name=id} -> forget_id id | Papp (_, pl) | Ptuple pl -> List.iter forget_pat pl | Por (p1, p2) -> forget_pat p1; forget_pat p2 | Pas (p, _) -> forget_pat p let print_global_ident ~sanitizer fmt id = let s = id_unique ~sanitizer tprinter id in Ident.forget_id tprinter id; fprintf fmt "%s" s let print_path ~sanitizer fmt (q, id) = assert (List.length q >= 1); match Lists.chop_last q with | [], _ -> print_global_ident ~sanitizer fmt id | q, _ -> fprintf fmt "%a.%a" (print_list dot string) q (print_global_ident ~sanitizer) id let rec remove_prefix acc current_path = match acc, current_path with | [], _ | _, [] -> acc | p1 :: _, p2 :: _ when p1 <> p2 -> acc | _ :: r1, _ :: r2 -> remove_prefix r1 r2 let is_local_id info id = Sid.mem id info.info_current_th.th_local || Opt.fold (fun _ m -> Sid.mem id m.Pmodule.mod_local) false info.info_current_mo exception Local let print_qident ~sanitizer info fmt id = try if info.info_flat then raise Not_found; if is_local_id info id then raise Local; let p, t, q = try Pmodule.restore_path id with Not_found -> Theory.restore_path id in let fname = if p = [] then info.info_fname else None in let m = Strings.capitalize (module_name ?fname p t) in fprintf fmt "%s.%a" m (print_path ~sanitizer) (q, id) with | Not_found -> let s = id_unique ~sanitizer iprinter id in fprintf fmt "%s" s | Local -> let _, _, q = try Pmodule.restore_path id with Not_found -> Theory.restore_path id in let q = remove_prefix q (List.rev info.info_current_ph) in print_path ~sanitizer fmt (q, id) let print_lident = print_qident ~sanitizer:Strings.uncapitalize let print_uident = print_qident ~sanitizer:Strings.capitalize let print_tv fmt tv = fprintf fmt "'%s" (id_unique aprinter tv.tv_name) let protect_on b s = if b then "(" ^^ s ^^ ")" else s let star fmt () = fprintf fmt " *@ " let rec print_list2 sep sep_m print1 print2 fmt (l1, l2) = match l1, l2 with | [x1], [x2] -> print1 fmt x1; sep_m fmt (); print2 fmt x2 | x1 :: r1, x2 :: r2 -> print1 fmt x1; sep_m fmt (); print2 fmt x2; sep fmt (); print_list2 sep sep_m print1 print2 fmt (r1, r2) | _ -> () let print_rs info fmt rs = fprintf fmt "%a" (print_lident info) rs.rs_name let rec print_ty ?(paren=false) info fmt = function | Tvar tv -> print_tv fmt tv | Ttuple [] -> fprintf fmt "unit" | Ttuple [t] -> print_ty ~paren info fmt t | Ttuple tl -> fprintf fmt (protect_on paren "@[%a@]") (print_list star (print_ty ~paren:true info)) tl | Tapp (ts, tl) -> match query_syntax info.info_syn ts with | Some s -> fprintf fmt (protect_on paren "%a") (syntax_arguments s (print_ty ~paren:true info)) tl | None -> match tl with | [] -> (print_lident info) fmt ts | [ty] -> fprintf fmt (protect_on paren "%a@ %a") (print_ty ~paren:true info) ty (print_lident info) ts | tl -> fprintf fmt (protect_on paren "(%a)@ %a") (print_list comma (print_ty ~paren:false info)) tl (print_lident info) ts let print_vsty_opt info fmt id ty = fprintf fmt "?%s:(%a:@ %a)" id.id_string (print_lident info) id (print_ty ~paren:false info) ty let print_vsty_named info fmt id ty = fprintf fmt "~%s:(%a:@ %a)" id.id_string (print_lident info) id (print_ty ~paren:false info) ty let print_vsty info fmt (id, ty, _) = let attrs = id.id_attrs in if is_optional ~attrs then print_vsty_opt info fmt id ty else if is_named ~attrs then print_vsty_named info fmt id ty else fprintf fmt "(%a:@ %a)" (print_lident info) id (print_ty ~paren:false info) ty let print_tv_arg = print_tv let print_tv_args fmt = function | [] -> () | [tv] -> fprintf fmt "%a@ " print_tv_arg tv | tvl -> fprintf fmt "(%a)@ " (print_list comma print_tv_arg) tvl let print_vs_arg info fmt vs = fprintf fmt "@[%a@]" (print_vsty info) vs let get_record info rs = match Mid.find_opt rs.rs_name info.info_mo_known_map with | Some {pd_node = PDtype itdl} -> let eq_rs {itd_constructors} = List.exists (rs_equal rs) itd_constructors in let itd = List.find eq_rs itdl in List.filter (fun e -> not (rs_ghost e)) itd.itd_fields | _ -> [] let rec print_pat info fmt = function | Pwild -> fprintf fmt "_" | Pvar {vs_name=id} -> (print_lident info) fmt id | Pas (p, {vs_name=id}) -> fprintf fmt "%a as %a" (print_pat info) p (print_lident info) id | Por (p1, p2) -> fprintf fmt "%a | %a" (print_pat info) p1 (print_pat info) p2 | Ptuple pl -> fprintf fmt "(%a)" (print_list comma (print_pat info)) pl | Papp (ls, pl) -> match query_syntax info.info_syn ls.ls_name, pl with | Some s, _ -> syntax_arguments s (print_pat info) fmt pl | None, pl -> let pjl = let rs = restore_rs ls in get_record info rs in match pjl with | [] -> print_papp info ls fmt pl | pjl -> fprintf fmt "@[<hov 2>{ %a }@]" (print_list2 semi equal (print_rs info) (print_pat info)) (pjl, pl) and print_papp info ls fmt = function | [] -> fprintf fmt "%a" (print_uident info) ls.ls_name | [p] -> fprintf fmt "%a %a" (print_uident info) ls.ls_name (print_pat info) p | pl -> fprintf fmt "%a (%a)" (print_uident info) ls.ls_name (print_list comma (print_pat info)) pl let pv_name pv = pv.pv_vs.vs_name let print_pv info fmt pv = print_lident info fmt (pv_name pv) FIXME put these in Compile let is_true e = match e.e_node with | Eapp (s, []) -> rs_equal s rs_true | _ -> false let is_false e = match e.e_node with | Eapp (s, []) -> rs_equal s rs_false | _ -> false let check_val_in_drv info ({rs_name = {id_loc = loc}} as rs) = match query_syntax info.info_convert rs.rs_name, query_syntax info.info_syn rs.rs_name with Loc.errorm ?loc "Function %a cannot be extracted" Expr.print_rs rs | _ -> () let is_mapped_to_int info ity = match ity.ity_node with | Ityapp ({ its_ts = ts }, _, _) -> query_syntax info.info_syn ts.ts_name = Some "int" | _ -> false let print_constant fmt e = begin match e.e_node with | Econst c -> let s = BigInt.to_string (Number.compute_int_constant c) in if c.Number.ic_negative then fprintf fmt "(%s)" s else fprintf fmt "%s" s | _ -> assert false end let print_for_direction fmt = function | To -> fprintf fmt "to" | DownTo -> fprintf fmt "downto" let rec print_apply_args info fmt = function | expr :: exprl, pv :: pvl -> if is_optional ~attrs:(pv_name pv).id_attrs then begin match expr.e_node with | Eapp (rs, _) when query_syntax info.info_syn rs.rs_name = Some "None" -> () | _ -> fprintf fmt "?%s:%a" (pv_name pv).id_string (print_expr ~paren:true info) expr end else if is_named ~attrs:(pv_name pv).id_attrs then fprintf fmt "~%s:%a" (pv_name pv).id_string (print_expr ~paren:true info) expr else fprintf fmt "%a" (print_expr ~paren:true info) expr; if exprl <> [] then fprintf fmt "@ "; print_apply_args info fmt (exprl, pvl) | expr :: exprl, [] -> fprintf fmt "%a" (print_expr ~paren:true info) expr; print_apply_args info fmt (exprl, []) | [], _ -> () and print_apply info rs fmt pvl = let isfield = match rs.rs_field with | None -> false | Some _ -> true in let isconstructor () = match Mid.find_opt rs.rs_name info.info_mo_known_map with | Some {pd_node = PDtype its} -> let is_constructor its = List.exists (rs_equal rs) its.itd_constructors in List.exists is_constructor its | _ -> false in match query_syntax info.info_convert rs.rs_name, query_syntax info.info_syn rs.rs_name, pvl with | Some s, _, [{e_node = Econst _}] -> syntax_arguments s print_constant fmt pvl syntax_arguments s (print_expr ~paren:true info) fmt pvl; | _, None, tl when is_rs_tuple rs -> fprintf fmt "@[(%a)@]" (print_list comma (print_expr info)) tl | _, None, [t1] when isfield -> fprintf fmt "%a.%a" (print_expr info) t1 (print_lident info) rs.rs_name | _, None, tl when isconstructor () -> let pjl = get_record info rs in begin match pjl, tl with | [], [] -> (print_uident info) fmt rs.rs_name | [], [t] -> fprintf fmt "@[<hov 2>%a %a@]" (print_uident info) rs.rs_name (print_expr ~paren:true info) t | [], tl -> fprintf fmt "@[<hov 2>%a (%a)@]" (print_uident info) rs.rs_name (print_list comma (print_expr ~paren:true info)) tl | pjl, tl -> let equal fmt () = fprintf fmt " =@ " in fprintf fmt "@[<hov 2>{ %a }@]" (print_list2 semi equal (print_rs info) (print_expr ~paren:true info)) (pjl, tl) end | _, None, [] -> (print_lident info) fmt rs.rs_name | _, _, tl -> fprintf fmt "@[<hov 2>%a %a@]" (print_lident info) rs.rs_name (print_apply_args info) (tl, rs.rs_cty.cty_args) and print_svar fmt s = Stv.iter (fun tv -> fprintf fmt "%a " print_tv tv) s and print_fun_type_args info fmt (args, s, res, e) = if Stv.is_empty s then fprintf fmt "@[%a@] :@ %a@ =@ %a" (print_list space (print_vs_arg info)) args (print_ty info) res (print_expr info) e else let ty_args = List.map (fun (_, ty, _) -> ty) args in let id_args = List.map (fun (id, _, _) -> id) args in let arrow fmt () = fprintf fmt " ->@ " in fprintf fmt ":@ @[<h>@[%a@]. @[%a ->@ %a@]@] =@ \ @[<hov 2>fun @[%a@]@ ->@ %a@]" print_svar s (print_list arrow (print_ty ~paren:true info)) ty_args (print_ty ~paren:true info) res (print_list space (print_lident info)) id_args (print_expr info) e and print_let_def ?(functor_arg=false) info fmt = function | Lvar (pv, {e_node = Eany ty}) when functor_arg -> fprintf fmt "@[<hov 2>val %a : %a@]" (print_lident info) (pv_name pv) (print_ty info) ty; | Lvar (pv, e) -> fprintf fmt "@[<hov 2>let %a =@ %a@]" (print_lident info) (pv_name pv) (print_expr info) e; | Lsym (rs, res, args, ef) -> fprintf fmt "@[<hov 2>let %a @[%a@] : %a@ =@ @[%a@]@]" (print_lident info) rs.rs_name (print_list space (print_vs_arg info)) args (print_ty info) res (print_expr info) ef; forget_vars args | Lrec rdef -> let print_one fst fmt = function | { rec_sym = rs1; rec_args = args; rec_exp = e; rec_res = res; rec_svar = s } -> fprintf fmt "@[<hov 2>%s %a %a@]" (if fst then "let rec" else "and") (print_lident info) rs1.rs_name (print_fun_type_args info) (args, s, res, e); forget_vars args in List.iter (fun fd -> Hrs.replace ht_rs fd.rec_rsym fd.rec_sym) rdef; print_list_next newline print_one fmt rdef; List.iter (fun fd -> Hrs.remove ht_rs fd.rec_rsym) rdef | Lany (rs, res, []) when functor_arg -> fprintf fmt "@[<hov 2>val %a : %a@]" (print_lident info) rs.rs_name (print_ty info) res; | Lany (rs, res, args) when functor_arg -> let print_ty_arg info fmt (_, ty, _) = fprintf fmt "@[%a@]" (print_ty info) ty in fprintf fmt "@[<hov 2>val %a : @[%a@] ->@ %a@]" (print_lident info) rs.rs_name (print_list arrow (print_ty_arg info)) args (print_ty info) res; forget_vars args | Lany (rs, _, _) -> check_val_in_drv info rs and print_expr ?(paren=false) info fmt e = match e.e_node with | Econst c -> let n = Number.compute_int_constant c in let n = BigInt.to_string n in let id = match e.e_ity with | I { ity_node = Ityapp ({its_ts = ts},_,_) } -> ts.ts_name | _ -> assert false in (match query_syntax info.info_literal id with | Some s -> syntax_arguments s print_constant fmt [e] | None when n = "0" -> fprintf fmt "Z.zero" | None when n = "1" -> fprintf fmt "Z.one" | None -> fprintf fmt (protect_on paren "Z.of_string \"%s\"") n) | Evar pvs -> (print_lident info) fmt (pv_name pvs) | Elet (let_def, e) -> fprintf fmt (protect_on paren "@[%a@] in@ @[%a@]") (print_let_def info) let_def (print_expr info) e; forget_let_defn let_def | Eabsurd -> fprintf fmt (protect_on paren "assert false (* absurd *)") | Ehole -> () | Eany _ -> assert false | Eapp (rs, []) when rs_equal rs rs_true -> fprintf fmt "true" | Eapp (rs, []) when rs_equal rs rs_false -> fprintf fmt "false" fprintf fmt "%a" (print_apply info (Hrs.find_def ht_rs rs rs)) [] | Eapp (rs, pvl) -> begin match query_syntax info.info_convert rs.rs_name, pvl with | Some s, [{e_node = Econst _}] -> syntax_arguments s print_constant fmt pvl | _ -> fprintf fmt (protect_on paren "%a") (print_apply info (Hrs.find_def ht_rs rs rs)) pvl end | Ematch (e1, [p, e2], []) -> fprintf fmt (protect_on paren "let %a =@ %a in@ %a") (print_pat info) p (print_expr info) e1 (print_expr info) e2 | Ematch (e, pl, []) -> fprintf fmt (protect_on paren "begin match @[%a@] with@\n@[<hov>%a@]@\nend") (print_expr info) e (print_list newline (print_branch info)) pl | Eassign al -> let assign fmt (rho, rs, pv) = fprintf fmt "@[<hov 2>%a.%a <-@ %a@]" (print_lident info) (pv_name rho) (print_lident info) rs.rs_name (print_lident info) (pv_name pv) in begin match al with | [] -> assert false | [a] -> assign fmt a | al -> fprintf fmt "@[begin %a end@]" (print_list semi assign) al end | Eif (e1, e2, {e_node = Eblock []}) -> fprintf fmt (protect_on paren "@[<hv>@[<hov 2>if@ %a@]@ then begin@;<1 2>@[%a@] end@]") (print_expr info) e1 (print_expr info) e2 | Eif (e1, e2, e3) when is_false e2 && is_true e3 -> fprintf fmt (protect_on paren "not %a") (print_expr info ~paren:true) e1 | Eif (e1, e2, e3) when is_true e2 -> fprintf fmt (protect_on paren "@[<hv>%a || %a@]") (print_expr info ~paren:true) e1 (print_expr info ~paren:true) e3 | Eif (e1, e2, e3) when is_false e3 -> fprintf fmt (protect_on paren "@[<hv>%a && %a@]") (print_expr info ~paren:true) e1 (print_expr info ~paren:true) e2 | Eif (e1, e2, e3) -> fprintf fmt (protect_on paren "@[<hv>@[<hov 2>if@ %a@ then@ begin@ @[%a@] end@]\ @;<1 0>else@ begin@;<1 2>@[%a@] end@]") (print_expr info) e1 (print_expr info) e2 (print_expr info) e3 | Eblock [] -> fprintf fmt "()" | Eblock [e] -> print_expr info fmt e | Eblock el -> fprintf fmt "@[<hv>begin@;<1 2>@[%a@]@ end@]" (print_list semi (print_expr info)) el | Efun (varl, e) -> fprintf fmt (protect_on paren "@[<hov 2>fun %a ->@ %a@]") (print_list space (print_vs_arg info)) varl (print_expr info) e | Ewhile (e1, e2) -> fprintf fmt "@[<hov 2>while %a do@\n%a@ done@]" (print_expr info) e1 (print_expr info) e2 | Eraise (xs, e_opt) -> print_raise ~paren info xs fmt e_opt | Efor (pv1, pv2, dir, pv3, e) -> if is_mapped_to_int info pv1.pv_ity then fprintf fmt "@[<hov 2>for %a = %a %a %a do@ @[%a@]@ done@]" (print_lident info) (pv_name pv1) (print_lident info) (pv_name pv2) print_for_direction dir (print_lident info) (pv_name pv3) (print_expr info) e else let for_id = id_register (id_fresh "for_loop_to") in let cmp, op = match dir with | To -> "Z.leq", "Z.succ" | DownTo -> "Z.geq", "Z.pred" in fprintf fmt (protect_on paren "@[<hov 2>let rec %a %a =@ if %s %a %a then \ begin@ %a; %a (%s %a) end@ in@ %a %a@]") op (print_pv info) pv1 | Ematch (e, [], xl) -> fprintf fmt "@[<hv>@[<hov 2>begin@ try@ %a@] with@]@\n@[<hov>%a@]@\nend" (print_expr info) e (print_list newline (print_xbranch info false)) xl | Ematch (e, bl, xl) -> fprintf fmt (protect_on paren "begin match @[%a@] with@\n@[<hov>%a@\n%a@]@\nend") (print_expr info) e (print_list newline (print_branch info)) bl (print_list newline (print_xbranch info true)) xl | Eexn (xs, None, e) -> fprintf fmt "@[<hv>let exception %a in@\n%a@]" (print_uident info) xs.xs_name (print_expr info) e | Eexn (xs, Some t, e) -> fprintf fmt "@[<hv>let exception %a of %a in@\n%a@]" (print_uident info) xs.xs_name (print_ty ~paren:true info) t (print_expr info) e | Eignore e -> fprintf fmt "ignore (%a)" (print_expr info) e and print_branch info fmt (p, e) = fprintf fmt "@[<hov 2>| %a ->@ @[%a@]@]" (print_pat info) p (print_expr info) e; forget_pat p and print_raise ~paren info xs fmt e_opt = match query_syntax info.info_syn xs.xs_name, e_opt with | Some s, None -> fprintf fmt "raise (%s)" s | Some s, Some e -> fprintf fmt (protect_on paren "raise (%a)") (syntax_arguments s (print_expr info)) [e] | None, None -> fprintf fmt (protect_on paren "raise %a") (print_uident info) xs.xs_name | None, Some e -> fprintf fmt (protect_on paren "raise (%a %a)") (print_uident info) xs.xs_name (print_expr ~paren:true info) e and print_xbranch info case fmt (xs, pvl, e) = let print_exn fmt () = if case then fprintf fmt "exception " else fprintf fmt "" in let print_var fmt pv = print_lident info fmt (pv_name pv) in match query_syntax info.info_syn xs.xs_name, pvl with | Some s, _ -> fprintf fmt "@[<hov 4>| %a%a ->@ %a@]" print_exn () (syntax_arguments s print_var) pvl (print_expr info ~paren:true) e | None, [] -> fprintf fmt "@[<hov 4>| %a%a ->@ %a@]" print_exn () (print_uident info) xs.xs_name (print_expr info) e | None, [pv] -> fprintf fmt "@[<hov 4>| %a%a %a ->@ %a@]" print_exn () (print_uident info) xs.xs_name print_var pv (print_expr info) e | None, pvl -> fprintf fmt "@[<hov 4>| %a%a (%a) ->@ %a@]" print_exn () (print_uident info) xs.xs_name (print_list comma print_var) pvl (print_expr info) e let print_type_decl info fst fmt its = let print_constr fmt (id, cs_args) = match cs_args with | [] -> fprintf fmt "@[<hov 4>| %a@]" (print_uident info) id | l -> fprintf fmt "@[<hov 4>| %a of %a@]" (print_uident info) id (print_list star (print_ty ~paren:false info)) l in let print_field fmt (is_mutable, id, ty) = fprintf fmt "%s%a: @[%a@];" (if is_mutable then "mutable " else "") (print_lident info) id (print_ty ~paren:false info) ty in let print_def fmt = function | None -> () | Some (Ddata csl) -> fprintf fmt " =@\n%a" (print_list newline print_constr) csl | Some (Drecord fl) -> fprintf fmt " = %s{@\n%a@\n}" (if its.its_private then "private " else "") (print_list newline print_field) fl | Some (Dalias ty) -> fprintf fmt " =@ %a" (print_ty ~paren:false info) ty | Some (Drange _) -> fprintf fmt " =@ Z.t" | Some (Dfloat _) -> TODO in let attrs = its.its_name.id_attrs in if not (is_ocaml_remove ~attrs) then fprintf fmt "@[<hov 2>@[%s %a%a@]%a@]" (if fst then "type" else "and") print_tv_args its.its_args (print_lident info) its.its_name print_def its.its_def let rec is_signature_decl info = function | Dtype _ -> true | Dlet (Lany _) -> true | Dlet (Lvar (_, {e_node = Eany _})) -> true | Dlet _ -> false | Dexn _ -> true | Dmodule (_, dl) -> is_signature info dl and is_signature info dl = List.for_all (is_signature_decl info) dl let extract_functor_args info dl = let rec extract args = function FIXME remove empty args ? | ( _ , [ ] ) : : dl - > extract args dl | Dmodule (x, dlx) :: dl when is_signature info dlx -> extract ((x, dlx) :: args) dl | dl -> List.rev args, dl in extract [] dl let rec print_decl ?(functor_arg=false) info fmt = function | Dlet ldef -> print_let_def info ~functor_arg fmt ldef | Dtype dl -> print_list_next newline (print_type_decl info) fmt dl | Dexn (xs, None) -> fprintf fmt "exception %a" (print_uident info) xs.xs_name | Dexn (xs, Some t)-> fprintf fmt "@[<hov 2>exception %a of %a@]" (print_uident info) xs.xs_name (print_ty ~paren:true info) t | Dmodule (s, dl) -> let args, dl = extract_functor_args info dl in let info = { info with info_current_ph = s :: info.info_current_ph } in fprintf fmt "@[@[<hov 2>module %s%a@ =@]@\n@[<hov 2>struct@ %a@]@ end" s (print_functor_args info) args (print_list newline2 (print_decl info)) dl and print_functor_args info fmt args = let print_sig info fmt dl = fprintf fmt "sig@ %a@ end" (print_list newline (print_decl info ~functor_arg:true)) dl in let print_pair fmt (s, dl) = let info = { info with info_current_ph = s :: info.info_current_ph } in fprintf fmt "(%s:@ %a)" s (print_sig info) dl in fprintf fmt "%a" (print_list space print_pair) args let print_decl info fmt decl = let memo = Hashtbl.create 64 in let decl_name = get_decl_name decl in let decide_print id = if query_syntax info.info_syn id = None && not (Hashtbl.mem memo decl) then begin Hashtbl.add memo decl (); print_decl info fmt decl; fprintf fmt "@\n@." end in List.iter decide_print decl_name end let print_decl = let memo = Hashtbl.create 16 in fun pargs ?old ?fname ~flat ({mod_theory = th} as m) fmt d -> ignore (old); let info = { info_syn = pargs.Pdriver.syntax; info_convert = pargs.Pdriver.converter; info_literal = pargs.Pdriver.literal; info_current_th = th; info_current_mo = Some m; info_th_known_map = th.th_known; info_mo_known_map = m.mod_known; info_fname = Opt.map Compile.clean_name fname; info_flat = flat; info_current_ph = []; } in if not (Hashtbl.mem memo d) then begin Hashtbl.add memo d (); Print.print_decl info fmt d end let ng suffix ?fname m = let mod_name = m.mod_theory.th_name.id_string in let path = m.mod_theory.th_path in (module_name ?fname path mod_name) ^ suffix let file_gen = ng ".ml" let mli_gen = ng ".mli" open Pdriver let ocaml_printer = { desc = "printer for Ocaml code"; file_gen = file_gen; decl_printer = print_decl; interf_gen = Some mli_gen; interf_printer = None; prelude_printer = print_empty_prelude } let () = Pdriver.register_printer "ocaml" ocaml_printer
b31036c6b0d065b48d54b9576d8575cf34f3fd5d3037731d946d0c948179ff02
bluemont/kria
put.clj
(ns kria.pb.object.put (:require [kria.conversions :refer [byte-string<-utf8-string]] [kria.pb.content :refer [pb->Content Content->pb]]) (:import [com.basho.riak.protobuf RiakKvPB$RpbPutReq RiakKvPB$RpbPutResp])) (defrecord PutReq [bucket ; required bytes key ; optional bytes vclock ; optional bytes required RpbContent optional uint32 optional uint32 return-body ; optional bool optional uint32 if-not-modified ; optional bool if-none-match ; optional bool return-head ; optional bool optional uint32 as-is ; optional bool sloppy-quorum ; optional bool optional uint32 type ; optional bytes ]) (defn ^RiakKvPB$RpbPutReq PutReq->pb [m] (let [b (RiakKvPB$RpbPutReq/newBuilder)] (let [x (:bucket m)] (.setBucket b x)) (if-let [x (:key m)] (.setKey b x)) (if-let [x (:vclock m)] (.setVclock b x)) (let [x (:content m)] (.setContent b (Content->pb x))) (if-let [x (:w m)] (.setW b x)) (if-let [x (:dw m)] (.setDw b x)) (if-let [x (:return-body m)] (.setReturnBody b x)) (if-let [x (:pw m)] (.setPw b x)) (if-let [x (:if-not-modified m)] (.setIfNotModified b x)) (if-let [x (:if-none-match m)] (.setIfNoneMatch b x)) (if-let [x (:return-head m)] (.setReturnHead b x)) (if-let [x (:as-is m)] (.setAsis b x)) (if-let [x (:timeout m)] (.setTimeout b x)) (if-let [x (:sloppy-quorum m)] (.setSloppyQuorum b x)) (if-let [x (:n-val m)] (.setNVal b x)) (if-let [x (:type m)] (.setType b (byte-string<-utf8-string x))) (.build b))) (defn PutReq->bytes [m] (.toByteArray (PutReq->pb m))) (defrecord PutResp repeated RpbContent vclock ; optional bytes key ; optional bytes ]) (defn pb->PutResp [^RiakKvPB$RpbPutResp pb] (->PutResp (mapv pb->Content (.getContentList pb)) (.getVclock pb) (.getKey pb))) (defn bytes->PutResp [^bytes x] (pb->PutResp (RiakKvPB$RpbPutResp/parseFrom x)))
null
https://raw.githubusercontent.com/bluemont/kria/8ed7fb1ebda8bfa1a2a6d7a3acf05e2255fcf0f0/src/clojure/kria/pb/object/put.clj
clojure
required bytes optional bytes optional bytes optional bool optional bool optional bool optional bool optional bool optional bool optional bytes optional bytes optional bytes
(ns kria.pb.object.put (:require [kria.conversions :refer [byte-string<-utf8-string]] [kria.pb.content :refer [pb->Content Content->pb]]) (:import [com.basho.riak.protobuf RiakKvPB$RpbPutReq RiakKvPB$RpbPutResp])) (defrecord PutReq required RpbContent optional uint32 optional uint32 optional uint32 optional uint32 optional uint32 ]) (defn ^RiakKvPB$RpbPutReq PutReq->pb [m] (let [b (RiakKvPB$RpbPutReq/newBuilder)] (let [x (:bucket m)] (.setBucket b x)) (if-let [x (:key m)] (.setKey b x)) (if-let [x (:vclock m)] (.setVclock b x)) (let [x (:content m)] (.setContent b (Content->pb x))) (if-let [x (:w m)] (.setW b x)) (if-let [x (:dw m)] (.setDw b x)) (if-let [x (:return-body m)] (.setReturnBody b x)) (if-let [x (:pw m)] (.setPw b x)) (if-let [x (:if-not-modified m)] (.setIfNotModified b x)) (if-let [x (:if-none-match m)] (.setIfNoneMatch b x)) (if-let [x (:return-head m)] (.setReturnHead b x)) (if-let [x (:as-is m)] (.setAsis b x)) (if-let [x (:timeout m)] (.setTimeout b x)) (if-let [x (:sloppy-quorum m)] (.setSloppyQuorum b x)) (if-let [x (:n-val m)] (.setNVal b x)) (if-let [x (:type m)] (.setType b (byte-string<-utf8-string x))) (.build b))) (defn PutReq->bytes [m] (.toByteArray (PutReq->pb m))) (defrecord PutResp repeated RpbContent ]) (defn pb->PutResp [^RiakKvPB$RpbPutResp pb] (->PutResp (mapv pb->Content (.getContentList pb)) (.getVclock pb) (.getKey pb))) (defn bytes->PutResp [^bytes x] (pb->PutResp (RiakKvPB$RpbPutResp/parseFrom x)))
089c223f6f68e3b5ba213df31b6fd2f52b0ffb8f5137ba92d061143ad7baa458
dergraf/epmdpxy
epmdpxy_listener.erl
-module(epmdpxy_listener). -behaviour(gen_server). %% API -export([start_link/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {listener_socket}). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Initializes the server %% ) - > { ok , State } | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> {ok, ListenerPort} = application:get_env(epmdpxy, port), {ok, ListenerSocket} = gen_tcp:listen(ListenerPort, [binary, {reuseaddr, true}, {active, false}]), {ok, #state{listener_socket=ListenerSocket}, 0}. %%-------------------------------------------------------------------- @private %% @doc %% Handling call messages %% , From , State ) - > %% {reply, Reply, State} | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling cast messages %% @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- @private %% @doc %% Handling all non call/cast messages %% , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(timeout, #state{listener_socket=ListenerSocket} = State) -> {ok, Sock} = gen_tcp:accept(ListenerSocket), {ok, _Pid} = epmdpxy_conn_sup:start_conn(Sock), {noreply, State, 0}. %%-------------------------------------------------------------------- @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates with . The return value is ignored . %% , State ) - > void ( ) %% @end %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- @private %% @doc %% Convert process state when code is changed %% , State , Extra ) - > { ok , NewState } %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/dergraf/epmdpxy/646506ba2117cb5ac81b9d37c2fe5cb7f042b043/src/epmdpxy_listener.erl
erlang
API gen_server callbacks =================================================================== API =================================================================== -------------------------------------------------------------------- @doc Starts the server @end -------------------------------------------------------------------- =================================================================== gen_server callbacks =================================================================== -------------------------------------------------------------------- @doc Initializes the server ignore | {stop, Reason} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling call messages {reply, Reply, State} | {stop, Reason, Reply, State} | {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling all non call/cast messages {stop, Reason, State} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Convert process state when code is changed @end -------------------------------------------------------------------- =================================================================== ===================================================================
-module(epmdpxy_listener). -behaviour(gen_server). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {listener_socket}). ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). @private ) - > { ok , State } | { ok , State , Timeout } | init([]) -> {ok, ListenerPort} = application:get_env(epmdpxy, port), {ok, ListenerSocket} = gen_tcp:listen(ListenerPort, [binary, {reuseaddr, true}, {active, false}]), {ok, #state{listener_socket=ListenerSocket}, 0}. @private , From , State ) - > { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. @private @spec handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. @private , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info(timeout, #state{listener_socket=ListenerSocket} = State) -> {ok, Sock} = gen_tcp:accept(ListenerSocket), {ok, _Pid} = epmdpxy_conn_sup:start_conn(Sock), {noreply, State, 0}. @private with . The return value is ignored . , State ) - > void ( ) terminate(_Reason, _State) -> ok. @private , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions
80f45a2d69d305f0b7d7501bf8e796ecaa0201f9a0678fb37f4ed25eb91b0c62
twosigma/waiter
reporters_integration_test.clj
;; Copyright ( c ) Two Sigma Open Source , LLC ;; 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. ;; (ns waiter.reporters-integration-test (:require [clojure.test :refer :all] [waiter.status-codes :refer :all] [waiter.util.client-tools :refer :all] [waiter.util.date-utils :as du] [waiter.util.utils :as utils])) (defn- get-graphite-reporter-state [waiter-url cookies] (let [{:keys [body] :as response} (make-request waiter-url "/state/codahale-reporters" :method :get :cookies cookies)] (assert-response-status response http-200-ok) (-> body str try-parse-json (get-in ["state" "graphite"])))) (defn- retrieve-graphite-reporter-last-event-time-ms [router-url cookies] (let [state (get-graphite-reporter-state router-url cookies) {:strs [last-connect-failed-time last-flush-failed-time last-reporting-time last-send-failed-time]} state last-event-time (->> [last-connect-failed-time last-flush-failed-time last-reporting-time last-send-failed-time] (map #(some-> % du/str-to-date .getMillis)) (reduce utils/nil-safe-max))] last-event-time)) (defn- wait-for-period [period-ms fun] (let [wait-for-delay (/ period-ms 2)] (wait-for fun :interval wait-for-delay :timeout (* period-ms 2) :unit-multiplier 1))) (deftest ^:parallel ^:integration-fast test-graphite-metrics-reporting (testing-using-waiter-url (let [cookies (all-cookies waiter-url)] (doseq [router-url (vals (routers waiter-url))] (let [{:keys [graphite]} (get-in (waiter-settings router-url :cookies cookies) [:metrics-config :codahale-reporters])] (when graphite (let [{:keys [period-ms]} graphite] (is (wait-for-period period-ms #(-> (get-graphite-reporter-state router-url cookies) (get "last-report-successful") some?))) (let [last-event-time-ms (retrieve-graphite-reporter-last-event-time-ms router-url cookies) _ (is last-event-time-ms) next-last-event-time-ms (wait-for-period period-ms #(let [next-last-event-time-ms (retrieve-graphite-reporter-last-event-time-ms router-url cookies)] (when (not= next-last-event-time-ms last-event-time-ms) next-last-event-time-ms))) expected precision for system " sleep " calls . a sleep call will sleep the right duration within 500 ms . sleep_precision 2000] (is next-last-event-time-ms) (when next-last-event-time-ms (is (< (Math/abs (- next-last-event-time-ms last-event-time-ms period-ms)) sleep_precision)))))))))))
null
https://raw.githubusercontent.com/twosigma/waiter/97a4389cd9d34709999527afcf24db802e741b7a/waiter/integration/waiter/reporters_integration_test.clj
clojure
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 ) Two Sigma Open Source , LLC distributed under the License is distributed on an " AS IS " BASIS , (ns waiter.reporters-integration-test (:require [clojure.test :refer :all] [waiter.status-codes :refer :all] [waiter.util.client-tools :refer :all] [waiter.util.date-utils :as du] [waiter.util.utils :as utils])) (defn- get-graphite-reporter-state [waiter-url cookies] (let [{:keys [body] :as response} (make-request waiter-url "/state/codahale-reporters" :method :get :cookies cookies)] (assert-response-status response http-200-ok) (-> body str try-parse-json (get-in ["state" "graphite"])))) (defn- retrieve-graphite-reporter-last-event-time-ms [router-url cookies] (let [state (get-graphite-reporter-state router-url cookies) {:strs [last-connect-failed-time last-flush-failed-time last-reporting-time last-send-failed-time]} state last-event-time (->> [last-connect-failed-time last-flush-failed-time last-reporting-time last-send-failed-time] (map #(some-> % du/str-to-date .getMillis)) (reduce utils/nil-safe-max))] last-event-time)) (defn- wait-for-period [period-ms fun] (let [wait-for-delay (/ period-ms 2)] (wait-for fun :interval wait-for-delay :timeout (* period-ms 2) :unit-multiplier 1))) (deftest ^:parallel ^:integration-fast test-graphite-metrics-reporting (testing-using-waiter-url (let [cookies (all-cookies waiter-url)] (doseq [router-url (vals (routers waiter-url))] (let [{:keys [graphite]} (get-in (waiter-settings router-url :cookies cookies) [:metrics-config :codahale-reporters])] (when graphite (let [{:keys [period-ms]} graphite] (is (wait-for-period period-ms #(-> (get-graphite-reporter-state router-url cookies) (get "last-report-successful") some?))) (let [last-event-time-ms (retrieve-graphite-reporter-last-event-time-ms router-url cookies) _ (is last-event-time-ms) next-last-event-time-ms (wait-for-period period-ms #(let [next-last-event-time-ms (retrieve-graphite-reporter-last-event-time-ms router-url cookies)] (when (not= next-last-event-time-ms last-event-time-ms) next-last-event-time-ms))) expected precision for system " sleep " calls . a sleep call will sleep the right duration within 500 ms . sleep_precision 2000] (is next-last-event-time-ms) (when next-last-event-time-ms (is (< (Math/abs (- next-last-event-time-ms last-event-time-ms period-ms)) sleep_precision)))))))))))
f26c156fa6f4f928b79a1699e8a60cb0daedfb22df076e4f84bc8aaa650a4d3e
orx/ocaml-orx
tutorial_02_clock.ml
Adaptation of the clock tutorial from This example is a direct adaptation of the 02_Clock.c tutorial from module State = struct module Clock_map = Map.Make (Orx.Clock) type t = Orx.Object.t Clock_map.t ref let state : t = ref Clock_map.empty let get () = !state let add (clock : Orx.Clock.t) (o : Orx.Object.t) : unit = state := Clock_map.add clock o !state end let update (clock_info : Orx.Clock.Info.t) = Orx.Config.push_section "Main"; if Orx.Config.get_bool "DisplayLog" then Orx.Log.log "<%s>: Time = %.3f / DT = %.3f" (Orx.Clock.get_name (Orx.Clock.Info.get_clock clock_info |> Option.get)) (Orx.Clock.Info.get_time clock_info) (Orx.Clock.Info.get_dt clock_info); Orx.Config.pop_section (); let clock = Orx.Clock.Info.get_clock clock_info |> Option.get in let obj = State.Clock_map.find clock (State.get ()) in Orx.Object.set_rotation obj (Float.pi *. Orx.Clock.Info.get_time clock_info) let input_update (_clock_info : Orx.Clock.Info.t) = Orx.Config.push_section "Main"; if Orx.Input.has_been_activated "Log" then Orx.Config.set_bool "DisplayLog" (not (Orx.Config.get_bool "DisplayLog")); Orx.Config.pop_section (); match Orx.Clock.get "Clock1" with | None -> () | Some clock -> if Orx.Input.is_active "Faster" then Orx.Clock.set_modifier clock Multiply 4.0 else if Orx.Input.is_active "Slower" then Orx.Clock.set_modifier clock Multiply 0.25 else if Orx.Input.is_active "Normal" then Orx.Clock.set_modifier clock Multiply 0.0 let init () = let get_name (binding : string) : string = let (type_, id, mode) = Orx.Input.get_binding binding 0 |> Result.get_ok in Orx.Input.get_binding_name type_ id mode in Orx.Log.log ("@.- Press '%s' to toggle log display@." ^^ "- To stretch time for the first clock (updating the box):@." ^^ " . Press numpad '%s' to set it 4 times faster@." ^^ " . Press numpad '%s' to set it 4 times slower@." ^^ " . Press numpad '%s' to set it back to normal" ) (get_name "Log") (get_name "Faster") (get_name "Slower") (get_name "Normal"); let (_viewport : Orx.Viewport.t) = Orx.Viewport.create_from_config_exn "Viewport" in let object1 = Orx.Object.create_from_config_exn "Object1" in let object2 = Orx.Object.create_from_config_exn "Object2" in let clock1 = Orx.Clock.create_from_config_exn "Clock1" in let clock2 = Orx.Clock.create_from_config_exn "Clock2" in State.add clock1 object1; State.add clock2 object2; Orx.Clock.register clock1 update; Orx.Clock.register clock2 update; let main_clock = Orx.Clock.get_core () in Orx.Clock.register main_clock input_update; Ok () let run () = if Orx.Input.is_active "Quit" then Orx.Status.error else Orx.Status.ok let () = Orx.Main.start ~config_dir:"examples/tutorial/data" ~init ~run "02_Clock"
null
https://raw.githubusercontent.com/orx/ocaml-orx/b1cf7d0efb958c72fbb9568905c81242593ff19d/examples/tutorial/tutorial_02_clock.ml
ocaml
Adaptation of the clock tutorial from This example is a direct adaptation of the 02_Clock.c tutorial from module State = struct module Clock_map = Map.Make (Orx.Clock) type t = Orx.Object.t Clock_map.t ref let state : t = ref Clock_map.empty let get () = !state let add (clock : Orx.Clock.t) (o : Orx.Object.t) : unit = state := Clock_map.add clock o !state end let update (clock_info : Orx.Clock.Info.t) = Orx.Config.push_section "Main"; if Orx.Config.get_bool "DisplayLog" then Orx.Log.log "<%s>: Time = %.3f / DT = %.3f" (Orx.Clock.get_name (Orx.Clock.Info.get_clock clock_info |> Option.get)) (Orx.Clock.Info.get_time clock_info) (Orx.Clock.Info.get_dt clock_info); Orx.Config.pop_section (); let clock = Orx.Clock.Info.get_clock clock_info |> Option.get in let obj = State.Clock_map.find clock (State.get ()) in Orx.Object.set_rotation obj (Float.pi *. Orx.Clock.Info.get_time clock_info) let input_update (_clock_info : Orx.Clock.Info.t) = Orx.Config.push_section "Main"; if Orx.Input.has_been_activated "Log" then Orx.Config.set_bool "DisplayLog" (not (Orx.Config.get_bool "DisplayLog")); Orx.Config.pop_section (); match Orx.Clock.get "Clock1" with | None -> () | Some clock -> if Orx.Input.is_active "Faster" then Orx.Clock.set_modifier clock Multiply 4.0 else if Orx.Input.is_active "Slower" then Orx.Clock.set_modifier clock Multiply 0.25 else if Orx.Input.is_active "Normal" then Orx.Clock.set_modifier clock Multiply 0.0 let init () = let get_name (binding : string) : string = let (type_, id, mode) = Orx.Input.get_binding binding 0 |> Result.get_ok in Orx.Input.get_binding_name type_ id mode in Orx.Log.log ("@.- Press '%s' to toggle log display@." ^^ "- To stretch time for the first clock (updating the box):@." ^^ " . Press numpad '%s' to set it 4 times faster@." ^^ " . Press numpad '%s' to set it 4 times slower@." ^^ " . Press numpad '%s' to set it back to normal" ) (get_name "Log") (get_name "Faster") (get_name "Slower") (get_name "Normal"); let (_viewport : Orx.Viewport.t) = Orx.Viewport.create_from_config_exn "Viewport" in let object1 = Orx.Object.create_from_config_exn "Object1" in let object2 = Orx.Object.create_from_config_exn "Object2" in let clock1 = Orx.Clock.create_from_config_exn "Clock1" in let clock2 = Orx.Clock.create_from_config_exn "Clock2" in State.add clock1 object1; State.add clock2 object2; Orx.Clock.register clock1 update; Orx.Clock.register clock2 update; let main_clock = Orx.Clock.get_core () in Orx.Clock.register main_clock input_update; Ok () let run () = if Orx.Input.is_active "Quit" then Orx.Status.error else Orx.Status.ok let () = Orx.Main.start ~config_dir:"examples/tutorial/data" ~init ~run "02_Clock"
567d069548a4ec4ceb1368d6ccc2568a24bdcd6715ab537c5e0105dbb46ab59f
tolitius/mount
on_reload.cljc
(ns mount.test.on-reload (:require #?@(:cljs [[cljs.test :as t :refer-macros [is are deftest testing use-fixtures]] [mount.core :as mount :refer-macros [defstate]] [tapp.websockets :refer [system-a]] [tapp.conf :refer [config]] [tapp.audit-log :refer [log]]] :clj [[clojure.test :as t :refer [is are deftest testing use-fixtures]] [mount.core :as mount :refer [defstate]] [tapp.example]]) [mount.test.helper :refer [dval helper forty-two counter inc-counter]] [mount.test.on-reload-helper :refer [a b c]])) #?(:clj (alter-meta! *ns* assoc ::load false)) #?(:clj (defn abc [f] (mount/start #'mount.test.on-reload-helper/a #'mount.test.on-reload-helper/b #'mount.test.on-reload-helper/c) (f) (mount/stop))) (use-fixtures :each #?(:cljs {:before #(mount/start #'mount.test.on-reload-helper/a #'mount.test.on-reload-helper/b #'mount.test.on-reload-helper/c) :after mount/stop} :clj abc)) #?(:clj (deftest restart-by-default (is (= '(:started) (distinct (map dval [a b c])))) (let [pre-reload @counter] (require 'mount.test.on-reload-helper :reload) ;; "a" is marked as :noop on reload ;; previous behavior left a stale reference =>>> ;; (is (instance? mount.core.NotStartedState (dval a))) ;; (!) stale reference of old a is still there somewhere (is (= :started (dval a))) ;; make sure a still has the same instance as before reload (is (= (-> pre-reload :a) ;; and the start was not called: the counter did not change (-> @counter :a))) ;; "b" is marked as :stop on reload (is (instance? mount.core.NotStartedState (dval b))) (is (= (-> pre-reload :b :started) (-> @counter :b :started))) (is (= (inc (-> pre-reload :b :stopped)) (-> @counter :b :stopped))) ;; "c" is not marked on reload, using "restart" as default (is (= :started (dval c))) (is (= (inc (-> pre-reload :c :started)) (-> @counter :c :started))) (is (= (inc (-> pre-reload :c :stopped)) (-> @counter :c :stopped))))))
null
https://raw.githubusercontent.com/tolitius/mount/c85da6149ceab96c903c1574106ec56f78338b5f/test/core/mount/test/on_reload.cljc
clojure
"a" is marked as :noop on reload previous behavior left a stale reference =>>> ;; (is (instance? mount.core.NotStartedState (dval a))) ;; (!) stale reference of old a is still there somewhere make sure a still has the same instance as before reload and the start was not called: the counter did not change "b" is marked as :stop on reload "c" is not marked on reload, using "restart" as default
(ns mount.test.on-reload (:require #?@(:cljs [[cljs.test :as t :refer-macros [is are deftest testing use-fixtures]] [mount.core :as mount :refer-macros [defstate]] [tapp.websockets :refer [system-a]] [tapp.conf :refer [config]] [tapp.audit-log :refer [log]]] :clj [[clojure.test :as t :refer [is are deftest testing use-fixtures]] [mount.core :as mount :refer [defstate]] [tapp.example]]) [mount.test.helper :refer [dval helper forty-two counter inc-counter]] [mount.test.on-reload-helper :refer [a b c]])) #?(:clj (alter-meta! *ns* assoc ::load false)) #?(:clj (defn abc [f] (mount/start #'mount.test.on-reload-helper/a #'mount.test.on-reload-helper/b #'mount.test.on-reload-helper/c) (f) (mount/stop))) (use-fixtures :each #?(:cljs {:before #(mount/start #'mount.test.on-reload-helper/a #'mount.test.on-reload-helper/b #'mount.test.on-reload-helper/c) :after mount/stop} :clj abc)) #?(:clj (deftest restart-by-default (is (= '(:started) (distinct (map dval [a b c])))) (let [pre-reload @counter] (require 'mount.test.on-reload-helper :reload) (-> @counter :a))) (is (instance? mount.core.NotStartedState (dval b))) (is (= (-> pre-reload :b :started) (-> @counter :b :started))) (is (= (inc (-> pre-reload :b :stopped)) (-> @counter :b :stopped))) (is (= :started (dval c))) (is (= (inc (-> pre-reload :c :started)) (-> @counter :c :started))) (is (= (inc (-> pre-reload :c :stopped)) (-> @counter :c :stopped))))))
a7877ddde0c5b625913caec65bcd31108950eb1c4cce7dfb1c3e4f86ce1fac6d
manuel-serrano/bigloo
hello.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / api / libuv / examples / hello.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Tue May 6 12:10:13 2014 * / * Last change : Tue May 6 12:11:02 2014 ( serrano ) * / * Copyright : 2014 * / ;* ------------------------------------------------------------- */ * hello world * / ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module libuv_hello (library libuv) (main main)) ;*---------------------------------------------------------------------*/ ;* main ... */ ;*---------------------------------------------------------------------*/ (define (main args) (let ((loop (instantiate::UvLoop))) (display "New quitting.\n") (uv-run loop)))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/d315487d6a97ef7b4483e919d1823a408337bd07/api/libbacktrace/examples/hello.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * main ... */ *---------------------------------------------------------------------*/
* serrano / prgm / project / bigloo / api / libuv / examples / hello.scm * / * Author : * / * Creation : Tue May 6 12:10:13 2014 * / * Last change : Tue May 6 12:11:02 2014 ( serrano ) * / * Copyright : 2014 * / * hello world * / (module libuv_hello (library libuv) (main main)) (define (main args) (let ((loop (instantiate::UvLoop))) (display "New quitting.\n") (uv-run loop)))
3dfbd27af5eebcf841b698ea0a8c1eb27b0bb8ac5f0388686fd74b3c1b3de669
janestreet/rpc_parallel
rpc_direct_pipe.ml
open Core open Async module Sum_worker = struct module T = struct type 'worker functions = { sum : ('worker, int, string) Rpc_parallel.Function.Direct_pipe.t } module Worker_state = struct type init_arg = unit [@@deriving bin_io] type t = unit end module Connection_state = struct type init_arg = unit [@@deriving bin_io] type t = unit end module Functions (C : Rpc_parallel.Creator with type worker_state := Worker_state.t and type connection_state := Connection_state.t) = struct let sum_impl ~worker_state:() ~conn_state:() arg writer = let _sum = List.fold ~init:0 ~f:(fun acc x -> let acc = acc + x in let output = sprintf "Sum_worker.sum: %i\n" acc in let (_ : [ `Closed | `Flushed of unit Deferred.t ]) = Rpc.Pipe_rpc.Direct_stream_writer.write writer output in acc) (List.init arg ~f:Fn.id) in Rpc.Pipe_rpc.Direct_stream_writer.close writer; Deferred.unit ;; let sum = C.create_direct_pipe ~f:sum_impl ~bin_input:Int.bin_t ~bin_output:String.bin_t () ;; let functions = { sum } let init_worker_state () = return () let init_connection_state ~connection:_ ~worker_state:_ = return end end include Rpc_parallel.Make (T) end let main max log_dir () = let redirect_stdout, redirect_stderr = match log_dir with | None -> `Dev_null, `Dev_null | Some _ -> `File_append "sum.out", `File_append "sum.err" in Sum_worker.spawn ~on_failure:Error.raise ?cd:log_dir ~shutdown_on:Connection_closed ~redirect_stdout ~redirect_stderr ~connection_state_init_arg:() () >>=? fun conn -> let on_write = function | Rpc.Pipe_rpc.Pipe_message.Closed _ -> Rpc.Pipe_rpc.Pipe_response.Continue | Update s -> Core.print_string s; Rpc.Pipe_rpc.Pipe_response.Continue in Sum_worker.Connection.run conn ~f:Sum_worker.functions.sum ~arg:(max, on_write) >>|? fun _ -> () ;; let command = Command.async_spec_or_error ~summary:"Simple use of Async Rpc_parallel V2" Command.Spec.( empty +> flag "max" (required int) ~doc:"" +> flag "log-dir" (optional string) ~doc:" Folder to write worker logs to") main ~behave_nicely_in_pipeline:false ;; let () = Rpc_parallel_krb_public.start_app ~krb_mode:For_unit_test command
null
https://raw.githubusercontent.com/janestreet/rpc_parallel/b37ce51ddfd9d9b6f96d285c81db7fc36d66a1d5/example/rpc_direct_pipe.ml
ocaml
open Core open Async module Sum_worker = struct module T = struct type 'worker functions = { sum : ('worker, int, string) Rpc_parallel.Function.Direct_pipe.t } module Worker_state = struct type init_arg = unit [@@deriving bin_io] type t = unit end module Connection_state = struct type init_arg = unit [@@deriving bin_io] type t = unit end module Functions (C : Rpc_parallel.Creator with type worker_state := Worker_state.t and type connection_state := Connection_state.t) = struct let sum_impl ~worker_state:() ~conn_state:() arg writer = let _sum = List.fold ~init:0 ~f:(fun acc x -> let acc = acc + x in let output = sprintf "Sum_worker.sum: %i\n" acc in let (_ : [ `Closed | `Flushed of unit Deferred.t ]) = Rpc.Pipe_rpc.Direct_stream_writer.write writer output in acc) (List.init arg ~f:Fn.id) in Rpc.Pipe_rpc.Direct_stream_writer.close writer; Deferred.unit ;; let sum = C.create_direct_pipe ~f:sum_impl ~bin_input:Int.bin_t ~bin_output:String.bin_t () ;; let functions = { sum } let init_worker_state () = return () let init_connection_state ~connection:_ ~worker_state:_ = return end end include Rpc_parallel.Make (T) end let main max log_dir () = let redirect_stdout, redirect_stderr = match log_dir with | None -> `Dev_null, `Dev_null | Some _ -> `File_append "sum.out", `File_append "sum.err" in Sum_worker.spawn ~on_failure:Error.raise ?cd:log_dir ~shutdown_on:Connection_closed ~redirect_stdout ~redirect_stderr ~connection_state_init_arg:() () >>=? fun conn -> let on_write = function | Rpc.Pipe_rpc.Pipe_message.Closed _ -> Rpc.Pipe_rpc.Pipe_response.Continue | Update s -> Core.print_string s; Rpc.Pipe_rpc.Pipe_response.Continue in Sum_worker.Connection.run conn ~f:Sum_worker.functions.sum ~arg:(max, on_write) >>|? fun _ -> () ;; let command = Command.async_spec_or_error ~summary:"Simple use of Async Rpc_parallel V2" Command.Spec.( empty +> flag "max" (required int) ~doc:"" +> flag "log-dir" (optional string) ~doc:" Folder to write worker logs to") main ~behave_nicely_in_pipeline:false ;; let () = Rpc_parallel_krb_public.start_app ~krb_mode:For_unit_test command
a0776fe68c4974fdccec7344dbb037d89744411cc8fdf7661abbba2ad6848d90
NorfairKing/mergeful
Item.hs
# OPTIONS_GHC -fno - warn - orphans # module Data.GenValidity.Mergeful.Item where import Data.GenValidity import Data.GenValidity.Mergeful.Timed () import Data.Mergeful.Item instance GenValid a => GenValid (ItemMergeResult a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering instance GenValid a => GenValid (ClientItem a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering instance GenValid a => GenValid (ServerItem a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering instance GenValid a => GenValid (ItemSyncRequest a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering instance GenValid a => GenValid (ItemSyncResponse a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
null
https://raw.githubusercontent.com/NorfairKing/mergeful/7dc80c96de7937dea539cd8ec2d7c03fb74f8b9c/genvalidity-mergeful/src/Data/GenValidity/Mergeful/Item.hs
haskell
# OPTIONS_GHC -fno - warn - orphans # module Data.GenValidity.Mergeful.Item where import Data.GenValidity import Data.GenValidity.Mergeful.Timed () import Data.Mergeful.Item instance GenValid a => GenValid (ItemMergeResult a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering instance GenValid a => GenValid (ClientItem a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering instance GenValid a => GenValid (ServerItem a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering instance GenValid a => GenValid (ItemSyncRequest a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering instance GenValid a => GenValid (ItemSyncResponse a) where genValid = genValidStructurallyWithoutExtraChecking shrinkValid = shrinkValidStructurallyWithoutExtraFiltering
dd8d8f106df3639923f43ee18164fcd56866b32ebae8121ed6941d777b1b2edc
jeapostrophe/mode-lambda
gl.rkt
#lang racket/base (require ffi/cvector ffi/unsafe/cvector (only-in ffi/vector u32vector list->s32vector s32vector-ref) mode-lambda/backend/gl/util mode-lambda/backend/lib mode-lambda/core mode-lambda/sprite-index racket/contract racket/list racket/match web-server/templates opengl scheme/nest racket/require (for-syntax racket/base) racket/flonum racket/fixnum (only-in ffi/unsafe ctype-sizeof _float)) (define QUAD_VERTS 4) (define LAYER-VALUES 12) (define (layer-config->bytes how-many-layers layer-config) (define lc-bytes-per-value (ctype-sizeof _float)) (define lc-bs (make-bytes (* LAYER-VALUES how-many-layers lc-bytes-per-value))) (for ([i (in-naturals)] [lc (in-vector layer-config)]) (match-define (layer-data Lcx Lcy Lhw Lhh Lmx Lmy Ltheta mode7-coeff horizon fov wrap-x? wrap-y?) (or lc default-layer)) (for ([o (in-naturals)] [v (in-list (list Lcx Lcy Lhw Lhh Lmx Lmy Ltheta mode7-coeff horizon fov (if wrap-x? 1.0 0.0) (if wrap-y? 1.0 0.0)))]) (real->floating-point-bytes v lc-bytes-per-value (system-big-endian?) lc-bs (+ (* LAYER-VALUES lc-bytes-per-value i) (* lc-bytes-per-value o))))) lc-bs) (define VERTEX_SPEC_L (for*/list ([xc '(-1 0 +1)] [yc '(-1 0 +1)]) (list "ivec2(" xc "," yc ")"))) (define INSTANCES_PER_SPR (length VERTEX_SPEC_L)) (define VERTEX_SPEC (add-between VERTEX_SPEC_L ",")) (define (make-draw csd width.fx height.fx how-many-layers screen-mode smoothing?) (define width (fx->fl width.fx)) (define height (fx->fl height.fx)) (eprintf "You are using OpenGL ~v with gl-backend-version of ~v\n" (gl-version) (gl-backend-version)) (define shot! (gl-screenshot!)) (match-define (compiled-sprite-db atlas-size atlas-bs spr->idx idx->w*h*tx*ty pal-size pal-bs pal->idx) csd) (define LayerConfigId (make-2dtexture)) (define update-layer-config! (let () (define last-layer-config #f) (λ (layer-config) (unless (equal? layer-config last-layer-config) (set! last-layer-config layer-config) (with-texture (GL_TEXTURE3 LayerConfigId) (load-texture/float-bytes LAYER-VALUES how-many-layers (layer-config->bytes how-many-layers layer-config))))))) (define render-layers! (let () ;; xxx allow these to be updated (define SpriteAtlasId (make-2dtexture)) (with-texture (GL_TEXTURE0 SpriteAtlasId) (load-texture/bytes atlas-size atlas-size atlas-bs) (when smoothing? (glGenerateMipmap GL_TEXTURE_2D) (glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER GL_LINEAR) (glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER GL_LINEAR_MIPMAP_LINEAR))) (define PaletteAtlasId (make-2dtexture)) (with-texture (GL_TEXTURE0 PaletteAtlasId) (load-texture/bytes PALETTE-DEPTH pal-size pal-bs)) (define SpriteIndexId (make-2dtexture)) (with-texture (GL_TEXTURE0 SpriteIndexId) (load-texture/float-bytes INDEX-VALUES (vector-length idx->w*h*tx*ty) (sprite-index->bytes idx->w*h*tx*ty))) (define layer-program (glCreateProgram)) (bind-attribs/cstruct-info layer-program _sprite-data:info) (define-shader-source layer-vert "gl/ngl.vertex.glsl") (define-shader-source layer-fragment "gl/ngl.fragment.glsl") (compile-shader GL_VERTEX_SHADER layer-program layer-vert) (compile-shader GL_FRAGMENT_SHADER layer-program layer-fragment) (define tmp-vao (glGen glGenVertexArrays)) (with-vertexarray (tmp-vao) (glLinkProgram& layer-program 'layer) (with-program (layer-program) (glUniform1i (glGetUniformLocation layer-program "SpriteAtlasTex") (gl-texture-index GL_TEXTURE0)) (glUniform1i (glGetUniformLocation layer-program "PaletteAtlasTex") (gl-texture-index GL_TEXTURE1)) (glUniform1i (glGetUniformLocation layer-program "SpriteIndexTex") (gl-texture-index GL_TEXTURE2)) (glUniform1i (glGetUniformLocation layer-program "LayerConfigTex") (gl-texture-index GL_TEXTURE3)) (glValidateProgram& layer-program 'layer))) (glDeleteVertexArrays 1 (u32vector tmp-vao)) (define layer-dfbos (for/list ([i (in-range 2)]) (make-delayed-fbo how-many-layers))) (define (make-sprite-draw!) (define layer-vao (glGen glGenVertexArrays)) (define layer-vbo (glGen glGenBuffers)) (nest ([with-vertexarray (layer-vao)] [with-arraybuffer (layer-vbo)]) (define-attribs/cstruct-info INSTANCES_PER_SPR _sprite-data:info)) (define actual-update! (make-update-vbo-buffer-with-objects! _sprite-data layer-vbo)) (define update! (let () (define last-objects #f) (define last-count 0) (λ (objects) (cond [(eq? last-objects objects) last-count] [else (set! last-objects objects) (define early-count (actual-update! objects)) (set! last-count early-count) early-count])))) (λ (objects) (define obj-count (update! objects)) (nest ([with-vertexarray (layer-vao)] [with-vertex-attributes ((length _sprite-data:info))]) (glDrawArraysInstanced GL_TRIANGLE_STRIP 0 QUAD_VERTS (fx* INSTANCES_PER_SPR obj-count))))) (define draw-static! (make-sprite-draw!)) (define draw-dynamic! (make-sprite-draw!)) (define front? #f) (λ (update-scale? the-scale-info static-st dynamic-st) (when update-scale? (for ([layer-dfbo (in-list layer-dfbos)]) (initialize-dfbo! layer-dfbo the-scale-info))) (define layer-dfbo (list-ref layer-dfbos (if front? 0 1))) (set! front? (not front?)) (for ([active-layeri (in-range how-many-layers)]) (nest ([with-framebuffer ((delayed-fbo-fbo layer-dfbo active-layeri))] [with-texture (GL_TEXTURE0 SpriteAtlasId)] [with-texture (GL_TEXTURE1 PaletteAtlasId)] [with-texture (GL_TEXTURE2 SpriteIndexId)] [with-texture (GL_TEXTURE3 LayerConfigId)] [with-feature (GL_BLEND)] [with-program (layer-program)]) (set-uniform-scale-info! layer-program the-scale-info) (glUniform1f (glGetUniformLocation layer-program "ActiveLayer") (real->double-flonum active-layeri)) (glClearColor 0.0 0.0 0.0 0.0) (glBlendFunc GL_ONE GL_ONE_MINUS_SRC_ALPHA) (glClear GL_COLOR_BUFFER_BIT) (set-viewport/fpair! (scale-info-texture the-scale-info)) (draw-static! static-st) (draw-dynamic! dynamic-st))) (delayed-fbo-tex layer-dfbo)))) (define combine-layers! (let () (define combine-vao (glGen glGenVertexArrays)) (define combine-program (glCreateProgram)) (define-shader-source combine-vert "gl/combine.vertex.glsl") (define-shader-source combine-fragment "gl/combine.fragment.glsl") (compile-shader GL_VERTEX_SHADER combine-program combine-vert) (compile-shader GL_FRAGMENT_SHADER combine-program combine-fragment) (with-vertexarray (combine-vao) (glLinkProgram& combine-program 'combine) (with-program (combine-program) (glUniform1i (glGetUniformLocation combine-program "LayerConfigTex") (gl-texture-index GL_TEXTURE0)) (glUniform1i (glGetUniformLocation combine-program "LayerTargets") (gl-texture-index GL_TEXTURE1)) (glValidateProgram& combine-program 'combine))) (define combine-dfbos (for/list ([i (in-range 2)]) (make-delayed-fbo 1))) (define front? #f) (λ (update-scale? the-scale-info LayerTargetsTex r g b) (when update-scale? (for ([combine-dfbo (in-list combine-dfbos)]) (initialize-dfbo! combine-dfbo the-scale-info))) (define combine-dfbo (list-ref combine-dfbos (if front? 0 1))) (set! front? (not front?)) (nest ([with-framebuffer ((delayed-fbo-fbo combine-dfbo 0))] [with-vertexarray (combine-vao)] [with-texture (GL_TEXTURE0 LayerConfigId)] [with-texture-array (GL_TEXTURE1 LayerTargetsTex)] [with-program (combine-program)]) (set-uniform-scale-info! combine-program the-scale-info) (glUniform3f (glGetUniformLocation combine-program "BackgroundColor") (fl/ (fx->fl r) 255.0) (fl/ (fx->fl g) 255.0) (fl/ (fx->fl b) 255.0)) (glClearColor 0.0 0.0 0.0 0.0) (glClear GL_COLOR_BUFFER_BIT) (set-viewport/fpair! (scale-info-texture the-scale-info)) (glDrawArrays GL_TRIANGLE_STRIP 0 QUAD_VERTS)) (delayed-fbo-tex combine-dfbo)))) (define draw-screen! (let () (define screen-vao (glGen glGenVertexArrays)) (define screen-program (glCreateProgram)) (define-shader-source crt-fragment "gl/crt.fragment.glsl") (define-shader-source crt-vert "gl/crt.vertex.glsl") (define-shader-source std-fragment "gl/std.fragment.glsl") (define-shader-source std-vert "gl/std.vertex.glsl") (define-values (screen-fragment screen-vert) (match screen-mode ['crt (values crt-fragment crt-vert)] ['std (values std-fragment std-vert)])) (compile-shader GL_FRAGMENT_SHADER screen-program screen-fragment) (compile-shader GL_VERTEX_SHADER screen-program screen-vert) (with-vertexarray (screen-vao) (glLinkProgram& screen-program 'screen) (with-program (screen-program) (glUniform1i (glGetUniformLocation screen-program "CombinedTex") (gl-texture-index GL_TEXTURE0)) (glValidateProgram& screen-program 'screen))) (λ (update-scale? the-scale-info combine-tex) (nest ([with-program (screen-program)] [with-texture (GL_TEXTURE0 combine-tex)] [with-vertexarray (screen-vao)]) (set-uniform-scale-info! screen-program the-scale-info) (glClearColor 0.0 0.0 0.0 0.0) (glClear GL_COLOR_BUFFER_BIT) (set-viewport/fpair! (scale-info-screen the-scale-info)) (glDrawArrays GL_TRIANGLE_STRIP 0 QUAD_VERTS))))) (define LogicalSize (pair->fpair width height)) (define the-scale-info #f) (λ (screen-width.fx screen-height.fx layer-config static-st dynamic-st r g b) (define screen-width (fx->fl screen-width.fx)) (define screen-height (fx->fl screen-height.fx)) If this were 8/7 , then we 'd have the same PAR as the NES on a ;; CRT and thus get non-square pixels. The problem with this is ;; that I get non-uniform pixel sizes as we go across the screen, so it looks really bad . So for now I 'll leave it at 1.0 , but I ;; have the dormant code here to come back to it. ;; ;; What I'd really like is a screen so big that I can draw each pixels as an 8x7 rectangle . On a 1080 screen , that 's 240x154 , ;; which is too small. A UHD screen would give 480x308, which would be big enough for a full NES screen . Of course , drawing ;; that way would have to be done differently, including ;; differently specifying the center of sprites, which would ;; stink. (define CRT-PIXEL-ASPECT-RATIO? #f) (define pixel-aspect-ratio (if CRT-PIXEL-ASPECT-RATIO? (fl/ 8.0 7.0) 1.0)) (define scale (compute-nice-scale pixel-aspect-ratio screen-width.fx width.fx screen-height.fx height.fx)) (define update-scale? (not (and the-scale-info (fl= (scale-info-y-scale the-scale-info) scale)))) (when update-scale? (define x-scale (fl* pixel-aspect-ratio scale)) (define y-scale scale) (define sca-width (fl* x-scale width)) (define sca-height (fl* y-scale height)) (define ScaledSize (pair->fpair sca-width sca-height)) (define tex-width (flceiling sca-width)) (define tex-height (flceiling sca-height)) (define TextureSize (pair->fpair tex-width tex-height)) (define ScreenSize (pair->fpair screen-width screen-height)) (set! the-scale-info (scale-info LogicalSize x-scale y-scale ScaledSize TextureSize ScreenSize)) (eprintf "~v\n" (vector (vector width height) (vector x-scale y-scale) (vector sca-width sca-height) (vector tex-width tex-height) (vector screen-width screen-height)))) (update-layer-config! layer-config) (define LayerTargetsTex (render-layers! update-scale? the-scale-info static-st dynamic-st)) (define combine-tex (combine-layers! update-scale? the-scale-info LayerTargetsTex r g b)) (when shot! (local-require ffi/vector racket/file) (define the-fp (scale-info-texture the-scale-info)) (define w (fl->fx (f32vector-ref the-fp 0))) (define h (fl->fx (f32vector-ref the-fp 1))) (define bs (make-bytes (fx* 4 (fx* w h)))) (for ([i (in-naturals)] ;; XXX Figure out how to screenshot from texture array LayerTargets ) ) ] ) (with-texture (GL_TEXTURE0 t) (glGetTexImage GL_TEXTURE_2D 0 GL_RGBA GL_UNSIGNED_BYTE bs)) (rgba->argb! bs) (shot! i w h bs))) (draw-screen! update-scale? the-scale-info combine-tex))) (define-make-delayed-render stage-draw/dc make-draw (csd width height how-many-layers) ((gl-filter-mode) (gl-smoothing?)) (layer-config static-st dynamic-st)) (define gl-filter-mode (make-parameter 'std)) (define gl-smoothing? (make-parameter #f)) (define gl-screenshot! (make-parameter #f)) (define gui-mode 'gl-core) (provide (contract-out [gl-backend-version (parameter/c (apply or/c valid-gl-backends))] [gl-filter-mode (parameter/c symbol?)] [gl-smoothing? (parameter/c (or/c #f #t))] [gl-screenshot! (parameter/c (-> exact-nonnegative-integer? exact-nonnegative-integer? exact-nonnegative-integer? bytes? void?))] [gui-mode symbol?] [stage-draw/dc (stage-backend/c draw/dc/c)]))
null
https://raw.githubusercontent.com/jeapostrophe/mode-lambda/64b5ae81f457ded7664458cd9935ce7d3ebfc449/mode-lambda/backend/gl.rkt
racket
xxx allow these to be updated CRT and thus get non-square pixels. The problem with this is that I get non-uniform pixel sizes as we go across the screen, have the dormant code here to come back to it. What I'd really like is a screen so big that I can draw each which is too small. A UHD screen would give 480x308, which that way would have to be done differently, including differently specifying the center of sprites, which would stink. XXX Figure out how to screenshot from texture array
#lang racket/base (require ffi/cvector ffi/unsafe/cvector (only-in ffi/vector u32vector list->s32vector s32vector-ref) mode-lambda/backend/gl/util mode-lambda/backend/lib mode-lambda/core mode-lambda/sprite-index racket/contract racket/list racket/match web-server/templates opengl scheme/nest racket/require (for-syntax racket/base) racket/flonum racket/fixnum (only-in ffi/unsafe ctype-sizeof _float)) (define QUAD_VERTS 4) (define LAYER-VALUES 12) (define (layer-config->bytes how-many-layers layer-config) (define lc-bytes-per-value (ctype-sizeof _float)) (define lc-bs (make-bytes (* LAYER-VALUES how-many-layers lc-bytes-per-value))) (for ([i (in-naturals)] [lc (in-vector layer-config)]) (match-define (layer-data Lcx Lcy Lhw Lhh Lmx Lmy Ltheta mode7-coeff horizon fov wrap-x? wrap-y?) (or lc default-layer)) (for ([o (in-naturals)] [v (in-list (list Lcx Lcy Lhw Lhh Lmx Lmy Ltheta mode7-coeff horizon fov (if wrap-x? 1.0 0.0) (if wrap-y? 1.0 0.0)))]) (real->floating-point-bytes v lc-bytes-per-value (system-big-endian?) lc-bs (+ (* LAYER-VALUES lc-bytes-per-value i) (* lc-bytes-per-value o))))) lc-bs) (define VERTEX_SPEC_L (for*/list ([xc '(-1 0 +1)] [yc '(-1 0 +1)]) (list "ivec2(" xc "," yc ")"))) (define INSTANCES_PER_SPR (length VERTEX_SPEC_L)) (define VERTEX_SPEC (add-between VERTEX_SPEC_L ",")) (define (make-draw csd width.fx height.fx how-many-layers screen-mode smoothing?) (define width (fx->fl width.fx)) (define height (fx->fl height.fx)) (eprintf "You are using OpenGL ~v with gl-backend-version of ~v\n" (gl-version) (gl-backend-version)) (define shot! (gl-screenshot!)) (match-define (compiled-sprite-db atlas-size atlas-bs spr->idx idx->w*h*tx*ty pal-size pal-bs pal->idx) csd) (define LayerConfigId (make-2dtexture)) (define update-layer-config! (let () (define last-layer-config #f) (λ (layer-config) (unless (equal? layer-config last-layer-config) (set! last-layer-config layer-config) (with-texture (GL_TEXTURE3 LayerConfigId) (load-texture/float-bytes LAYER-VALUES how-many-layers (layer-config->bytes how-many-layers layer-config))))))) (define render-layers! (let () (define SpriteAtlasId (make-2dtexture)) (with-texture (GL_TEXTURE0 SpriteAtlasId) (load-texture/bytes atlas-size atlas-size atlas-bs) (when smoothing? (glGenerateMipmap GL_TEXTURE_2D) (glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER GL_LINEAR) (glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER GL_LINEAR_MIPMAP_LINEAR))) (define PaletteAtlasId (make-2dtexture)) (with-texture (GL_TEXTURE0 PaletteAtlasId) (load-texture/bytes PALETTE-DEPTH pal-size pal-bs)) (define SpriteIndexId (make-2dtexture)) (with-texture (GL_TEXTURE0 SpriteIndexId) (load-texture/float-bytes INDEX-VALUES (vector-length idx->w*h*tx*ty) (sprite-index->bytes idx->w*h*tx*ty))) (define layer-program (glCreateProgram)) (bind-attribs/cstruct-info layer-program _sprite-data:info) (define-shader-source layer-vert "gl/ngl.vertex.glsl") (define-shader-source layer-fragment "gl/ngl.fragment.glsl") (compile-shader GL_VERTEX_SHADER layer-program layer-vert) (compile-shader GL_FRAGMENT_SHADER layer-program layer-fragment) (define tmp-vao (glGen glGenVertexArrays)) (with-vertexarray (tmp-vao) (glLinkProgram& layer-program 'layer) (with-program (layer-program) (glUniform1i (glGetUniformLocation layer-program "SpriteAtlasTex") (gl-texture-index GL_TEXTURE0)) (glUniform1i (glGetUniformLocation layer-program "PaletteAtlasTex") (gl-texture-index GL_TEXTURE1)) (glUniform1i (glGetUniformLocation layer-program "SpriteIndexTex") (gl-texture-index GL_TEXTURE2)) (glUniform1i (glGetUniformLocation layer-program "LayerConfigTex") (gl-texture-index GL_TEXTURE3)) (glValidateProgram& layer-program 'layer))) (glDeleteVertexArrays 1 (u32vector tmp-vao)) (define layer-dfbos (for/list ([i (in-range 2)]) (make-delayed-fbo how-many-layers))) (define (make-sprite-draw!) (define layer-vao (glGen glGenVertexArrays)) (define layer-vbo (glGen glGenBuffers)) (nest ([with-vertexarray (layer-vao)] [with-arraybuffer (layer-vbo)]) (define-attribs/cstruct-info INSTANCES_PER_SPR _sprite-data:info)) (define actual-update! (make-update-vbo-buffer-with-objects! _sprite-data layer-vbo)) (define update! (let () (define last-objects #f) (define last-count 0) (λ (objects) (cond [(eq? last-objects objects) last-count] [else (set! last-objects objects) (define early-count (actual-update! objects)) (set! last-count early-count) early-count])))) (λ (objects) (define obj-count (update! objects)) (nest ([with-vertexarray (layer-vao)] [with-vertex-attributes ((length _sprite-data:info))]) (glDrawArraysInstanced GL_TRIANGLE_STRIP 0 QUAD_VERTS (fx* INSTANCES_PER_SPR obj-count))))) (define draw-static! (make-sprite-draw!)) (define draw-dynamic! (make-sprite-draw!)) (define front? #f) (λ (update-scale? the-scale-info static-st dynamic-st) (when update-scale? (for ([layer-dfbo (in-list layer-dfbos)]) (initialize-dfbo! layer-dfbo the-scale-info))) (define layer-dfbo (list-ref layer-dfbos (if front? 0 1))) (set! front? (not front?)) (for ([active-layeri (in-range how-many-layers)]) (nest ([with-framebuffer ((delayed-fbo-fbo layer-dfbo active-layeri))] [with-texture (GL_TEXTURE0 SpriteAtlasId)] [with-texture (GL_TEXTURE1 PaletteAtlasId)] [with-texture (GL_TEXTURE2 SpriteIndexId)] [with-texture (GL_TEXTURE3 LayerConfigId)] [with-feature (GL_BLEND)] [with-program (layer-program)]) (set-uniform-scale-info! layer-program the-scale-info) (glUniform1f (glGetUniformLocation layer-program "ActiveLayer") (real->double-flonum active-layeri)) (glClearColor 0.0 0.0 0.0 0.0) (glBlendFunc GL_ONE GL_ONE_MINUS_SRC_ALPHA) (glClear GL_COLOR_BUFFER_BIT) (set-viewport/fpair! (scale-info-texture the-scale-info)) (draw-static! static-st) (draw-dynamic! dynamic-st))) (delayed-fbo-tex layer-dfbo)))) (define combine-layers! (let () (define combine-vao (glGen glGenVertexArrays)) (define combine-program (glCreateProgram)) (define-shader-source combine-vert "gl/combine.vertex.glsl") (define-shader-source combine-fragment "gl/combine.fragment.glsl") (compile-shader GL_VERTEX_SHADER combine-program combine-vert) (compile-shader GL_FRAGMENT_SHADER combine-program combine-fragment) (with-vertexarray (combine-vao) (glLinkProgram& combine-program 'combine) (with-program (combine-program) (glUniform1i (glGetUniformLocation combine-program "LayerConfigTex") (gl-texture-index GL_TEXTURE0)) (glUniform1i (glGetUniformLocation combine-program "LayerTargets") (gl-texture-index GL_TEXTURE1)) (glValidateProgram& combine-program 'combine))) (define combine-dfbos (for/list ([i (in-range 2)]) (make-delayed-fbo 1))) (define front? #f) (λ (update-scale? the-scale-info LayerTargetsTex r g b) (when update-scale? (for ([combine-dfbo (in-list combine-dfbos)]) (initialize-dfbo! combine-dfbo the-scale-info))) (define combine-dfbo (list-ref combine-dfbos (if front? 0 1))) (set! front? (not front?)) (nest ([with-framebuffer ((delayed-fbo-fbo combine-dfbo 0))] [with-vertexarray (combine-vao)] [with-texture (GL_TEXTURE0 LayerConfigId)] [with-texture-array (GL_TEXTURE1 LayerTargetsTex)] [with-program (combine-program)]) (set-uniform-scale-info! combine-program the-scale-info) (glUniform3f (glGetUniformLocation combine-program "BackgroundColor") (fl/ (fx->fl r) 255.0) (fl/ (fx->fl g) 255.0) (fl/ (fx->fl b) 255.0)) (glClearColor 0.0 0.0 0.0 0.0) (glClear GL_COLOR_BUFFER_BIT) (set-viewport/fpair! (scale-info-texture the-scale-info)) (glDrawArrays GL_TRIANGLE_STRIP 0 QUAD_VERTS)) (delayed-fbo-tex combine-dfbo)))) (define draw-screen! (let () (define screen-vao (glGen glGenVertexArrays)) (define screen-program (glCreateProgram)) (define-shader-source crt-fragment "gl/crt.fragment.glsl") (define-shader-source crt-vert "gl/crt.vertex.glsl") (define-shader-source std-fragment "gl/std.fragment.glsl") (define-shader-source std-vert "gl/std.vertex.glsl") (define-values (screen-fragment screen-vert) (match screen-mode ['crt (values crt-fragment crt-vert)] ['std (values std-fragment std-vert)])) (compile-shader GL_FRAGMENT_SHADER screen-program screen-fragment) (compile-shader GL_VERTEX_SHADER screen-program screen-vert) (with-vertexarray (screen-vao) (glLinkProgram& screen-program 'screen) (with-program (screen-program) (glUniform1i (glGetUniformLocation screen-program "CombinedTex") (gl-texture-index GL_TEXTURE0)) (glValidateProgram& screen-program 'screen))) (λ (update-scale? the-scale-info combine-tex) (nest ([with-program (screen-program)] [with-texture (GL_TEXTURE0 combine-tex)] [with-vertexarray (screen-vao)]) (set-uniform-scale-info! screen-program the-scale-info) (glClearColor 0.0 0.0 0.0 0.0) (glClear GL_COLOR_BUFFER_BIT) (set-viewport/fpair! (scale-info-screen the-scale-info)) (glDrawArrays GL_TRIANGLE_STRIP 0 QUAD_VERTS))))) (define LogicalSize (pair->fpair width height)) (define the-scale-info #f) (λ (screen-width.fx screen-height.fx layer-config static-st dynamic-st r g b) (define screen-width (fx->fl screen-width.fx)) (define screen-height (fx->fl screen-height.fx)) If this were 8/7 , then we 'd have the same PAR as the NES on a so it looks really bad . So for now I 'll leave it at 1.0 , but I pixels as an 8x7 rectangle . On a 1080 screen , that 's 240x154 , would be big enough for a full NES screen . Of course , drawing (define CRT-PIXEL-ASPECT-RATIO? #f) (define pixel-aspect-ratio (if CRT-PIXEL-ASPECT-RATIO? (fl/ 8.0 7.0) 1.0)) (define scale (compute-nice-scale pixel-aspect-ratio screen-width.fx width.fx screen-height.fx height.fx)) (define update-scale? (not (and the-scale-info (fl= (scale-info-y-scale the-scale-info) scale)))) (when update-scale? (define x-scale (fl* pixel-aspect-ratio scale)) (define y-scale scale) (define sca-width (fl* x-scale width)) (define sca-height (fl* y-scale height)) (define ScaledSize (pair->fpair sca-width sca-height)) (define tex-width (flceiling sca-width)) (define tex-height (flceiling sca-height)) (define TextureSize (pair->fpair tex-width tex-height)) (define ScreenSize (pair->fpair screen-width screen-height)) (set! the-scale-info (scale-info LogicalSize x-scale y-scale ScaledSize TextureSize ScreenSize)) (eprintf "~v\n" (vector (vector width height) (vector x-scale y-scale) (vector sca-width sca-height) (vector tex-width tex-height) (vector screen-width screen-height)))) (update-layer-config! layer-config) (define LayerTargetsTex (render-layers! update-scale? the-scale-info static-st dynamic-st)) (define combine-tex (combine-layers! update-scale? the-scale-info LayerTargetsTex r g b)) (when shot! (local-require ffi/vector racket/file) (define the-fp (scale-info-texture the-scale-info)) (define w (fl->fx (f32vector-ref the-fp 0))) (define h (fl->fx (f32vector-ref the-fp 1))) (define bs (make-bytes (fx* 4 (fx* w h)))) (for ([i (in-naturals)] LayerTargets ) ) ] ) (with-texture (GL_TEXTURE0 t) (glGetTexImage GL_TEXTURE_2D 0 GL_RGBA GL_UNSIGNED_BYTE bs)) (rgba->argb! bs) (shot! i w h bs))) (draw-screen! update-scale? the-scale-info combine-tex))) (define-make-delayed-render stage-draw/dc make-draw (csd width height how-many-layers) ((gl-filter-mode) (gl-smoothing?)) (layer-config static-st dynamic-st)) (define gl-filter-mode (make-parameter 'std)) (define gl-smoothing? (make-parameter #f)) (define gl-screenshot! (make-parameter #f)) (define gui-mode 'gl-core) (provide (contract-out [gl-backend-version (parameter/c (apply or/c valid-gl-backends))] [gl-filter-mode (parameter/c symbol?)] [gl-smoothing? (parameter/c (or/c #f #t))] [gl-screenshot! (parameter/c (-> exact-nonnegative-integer? exact-nonnegative-integer? exact-nonnegative-integer? bytes? void?))] [gui-mode symbol?] [stage-draw/dc (stage-backend/c draw/dc/c)]))
e00dfb7df3310026362dc6b869632cf0d4717207dd6fda76c02e2aa90dc50664
YoshikuniJujo/test_haskell
try-logo.hs
# , OverloadedStrings # # LANGUAGE TypeApplications # # OPTIONS_GHC -Wall -fno - warn - tabs # module Main where import Foreign.C.Types import Control.Monad import Data.Maybe import Data.Bool import Data.Color import Data.CairoContext import Graphics.Cairo.Drawing.CairoT import Graphics.Cairo.Drawing.CairoT.Setting import Graphics.Cairo.Drawing.CairoT.CairoOperatorT import Graphics.Cairo.Drawing.Paths import Graphics.Cairo.Drawing.Transformations import Graphics.Pango.Basic.Fonts.PangoFontDescription import Graphics.Pango.Basic.LayoutObjects.PangoLayout import Graphics.Pango.Basic.GlyphStorage import Graphics.Pango.Rendering.Cairo import MakePng import qualified Data.Text as T rotate :: CairoTIO s -> CDouble -> IO () rotate cr a = do cairoTranslate cr 128 128 cairoRotate cr a cairoTranslate cr (- 128) (- 128) put :: CairoTIO s -> PangoFontDescriptionNullable -> CDouble -> T.Text -> IO PangoFixed put cr fd a t = do rotate cr a cairoMoveTo cr 116 16 pl <- pangoCairoCreateLayout cr pangoLayoutSet pl fd pangoLayoutSet pl t pl' <- pangoLayoutFreeze pl print . pangoRectangleFixedWidth . extentsLogicalRect =<< pangoLayoutInfo pl' pangoCairoShowLayout cr pl' cairoIdentityMatrix cr w <- pangoRectangleFixedWidth . extentsLogicalRect <$> pangoLayoutInfo pl' pure $ bool w (w * 1 / 2) $ t == " " layoutArc :: CairoTIO s -> PangoFontDescriptionNullable -> CDouble -> String -> IO () layoutArc cr fd a0 cs = (\f -> foldM_ f a0 cs) \a c -> do w <- put cr fd a $ T.singleton c pure $ a + (pi / 16) * (realToFrac w / 16) layoutArc cr fd for _ ( [ a0 , a0 + ( pi / 16 ) .. ] ` zip ` cs ) \(a , c ) - > put cr fd a $ T.singleton c layoutArc cr fd a0 cs = for_ ([a0, a0 + (pi / 16) ..] `zip` cs) \(a, c) -> put cr fd a $ T.singleton c -} main :: IO () main = pngWith "pngs/try-logo.png" 256 256 \cr -> do -- cairoSetSourceRgb cr . fromJust $ rgbDouble 0.3 0.3 0.3 -- cairoPaint cr cairoSetSourceRgb cr . fromJust $ rgbDouble 0.15 0.15 0.15 cairoArc cr 128 128 128 0 (2 * pi) cairoFill cr cairoSetSourceRgb cr . fromJust $ rgbDouble 0.8 0.8 0.8 cairoArc cr 128 128 80 0 (2 * pi) cairoFill cr cairoSetSourceRgb cr . fromJust $ rgbDouble 0.15 0.15 0.15 cairoSet cr OperatorClear cairoSet cr $ LineWidth 12 cairoSet cr LineCapRound cairoSet cr $ Dash [32, 20] 0 cairoArc cr 128 128 68 (- pi / 2) (3 / 2 * pi) cairoStroke cr cairoSet cr OperatorOver cairoSetSourceRgb cr . fromJust $ rgbDouble 0.8 0.8 0.8 fd_ <- pangoFontDescriptionNew pangoFontDescriptionSet fd_ $ Family "sans" pangoFontDescriptionSet fd_ PangoWeightBold pangoFontDescriptionSet fd_ $ Size 16 fd <- pangoFontDescriptionToNullable . Just <$> pangoFontDescriptionFreeze fd_ layoutArc cr fd 0 "WAKAYAMA UNIVERSITY" layoutArc cr fd (5 / 4 * pi) "RACINGTEAM" rotate cr $ pi / 2 pl < - pangoCairoCreateLayout cr pangoLayoutSet pl . pangoFontDescriptionToNullable . Just = < < pangoFontDescriptionFreeze fd pangoLayoutSet @T.Text pl " \x01f9a5ナマケモノ " cairoSetSourceRgb cr . fromJust $ rgbDouble 0.5 0.5 0.05 cr 24 32 pangoCairoShowLayout cr = < < pangoLayoutFreeze pl cairoSetSourceRgb cr . fromJust $ rgbDouble 0.0 0.7 0.0 cr 24 96 pangoCairoShowLayout cr = < < pangoLayoutFreeze pl cairoSetSourceRgb cr . fromJust $ rgbDouble 0.6 0.4 0.2 cr 24 160 pangoCairoShowLayout cr = < < pangoLayoutFreeze pl rotate cr $ pi / 2 pl <- pangoCairoCreateLayout cr pangoLayoutSet pl . pangoFontDescriptionToNullable . Just =<< pangoFontDescriptionFreeze fd pangoLayoutSet @T.Text pl "\x01f9a5ナマケモノ" cairoSetSourceRgb cr . fromJust $ rgbDouble 0.5 0.5 0.05 cairoMoveTo cr 24 32 pangoCairoShowLayout cr =<< pangoLayoutFreeze pl cairoSetSourceRgb cr . fromJust $ rgbDouble 0.0 0.7 0.0 cairoMoveTo cr 24 96 pangoCairoShowLayout cr =<< pangoLayoutFreeze pl cairoSetSourceRgb cr . fromJust $ rgbDouble 0.6 0.4 0.2 cairoMoveTo cr 24 160 pangoCairoShowLayout cr =<< pangoLayoutFreeze pl -}
null
https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/1df355420c431c4597f82c5b3362f5db3718ef70/themes/gui/cairo/try-simple-cairo-new/app/try-logo.hs
haskell
cairoSetSourceRgb cr . fromJust $ rgbDouble 0.3 0.3 0.3 cairoPaint cr
# , OverloadedStrings # # LANGUAGE TypeApplications # # OPTIONS_GHC -Wall -fno - warn - tabs # module Main where import Foreign.C.Types import Control.Monad import Data.Maybe import Data.Bool import Data.Color import Data.CairoContext import Graphics.Cairo.Drawing.CairoT import Graphics.Cairo.Drawing.CairoT.Setting import Graphics.Cairo.Drawing.CairoT.CairoOperatorT import Graphics.Cairo.Drawing.Paths import Graphics.Cairo.Drawing.Transformations import Graphics.Pango.Basic.Fonts.PangoFontDescription import Graphics.Pango.Basic.LayoutObjects.PangoLayout import Graphics.Pango.Basic.GlyphStorage import Graphics.Pango.Rendering.Cairo import MakePng import qualified Data.Text as T rotate :: CairoTIO s -> CDouble -> IO () rotate cr a = do cairoTranslate cr 128 128 cairoRotate cr a cairoTranslate cr (- 128) (- 128) put :: CairoTIO s -> PangoFontDescriptionNullable -> CDouble -> T.Text -> IO PangoFixed put cr fd a t = do rotate cr a cairoMoveTo cr 116 16 pl <- pangoCairoCreateLayout cr pangoLayoutSet pl fd pangoLayoutSet pl t pl' <- pangoLayoutFreeze pl print . pangoRectangleFixedWidth . extentsLogicalRect =<< pangoLayoutInfo pl' pangoCairoShowLayout cr pl' cairoIdentityMatrix cr w <- pangoRectangleFixedWidth . extentsLogicalRect <$> pangoLayoutInfo pl' pure $ bool w (w * 1 / 2) $ t == " " layoutArc :: CairoTIO s -> PangoFontDescriptionNullable -> CDouble -> String -> IO () layoutArc cr fd a0 cs = (\f -> foldM_ f a0 cs) \a c -> do w <- put cr fd a $ T.singleton c pure $ a + (pi / 16) * (realToFrac w / 16) layoutArc cr fd for _ ( [ a0 , a0 + ( pi / 16 ) .. ] ` zip ` cs ) \(a , c ) - > put cr fd a $ T.singleton c layoutArc cr fd a0 cs = for_ ([a0, a0 + (pi / 16) ..] `zip` cs) \(a, c) -> put cr fd a $ T.singleton c -} main :: IO () main = pngWith "pngs/try-logo.png" 256 256 \cr -> do cairoSetSourceRgb cr . fromJust $ rgbDouble 0.15 0.15 0.15 cairoArc cr 128 128 128 0 (2 * pi) cairoFill cr cairoSetSourceRgb cr . fromJust $ rgbDouble 0.8 0.8 0.8 cairoArc cr 128 128 80 0 (2 * pi) cairoFill cr cairoSetSourceRgb cr . fromJust $ rgbDouble 0.15 0.15 0.15 cairoSet cr OperatorClear cairoSet cr $ LineWidth 12 cairoSet cr LineCapRound cairoSet cr $ Dash [32, 20] 0 cairoArc cr 128 128 68 (- pi / 2) (3 / 2 * pi) cairoStroke cr cairoSet cr OperatorOver cairoSetSourceRgb cr . fromJust $ rgbDouble 0.8 0.8 0.8 fd_ <- pangoFontDescriptionNew pangoFontDescriptionSet fd_ $ Family "sans" pangoFontDescriptionSet fd_ PangoWeightBold pangoFontDescriptionSet fd_ $ Size 16 fd <- pangoFontDescriptionToNullable . Just <$> pangoFontDescriptionFreeze fd_ layoutArc cr fd 0 "WAKAYAMA UNIVERSITY" layoutArc cr fd (5 / 4 * pi) "RACINGTEAM" rotate cr $ pi / 2 pl < - pangoCairoCreateLayout cr pangoLayoutSet pl . pangoFontDescriptionToNullable . Just = < < pangoFontDescriptionFreeze fd pangoLayoutSet @T.Text pl " \x01f9a5ナマケモノ " cairoSetSourceRgb cr . fromJust $ rgbDouble 0.5 0.5 0.05 cr 24 32 pangoCairoShowLayout cr = < < pangoLayoutFreeze pl cairoSetSourceRgb cr . fromJust $ rgbDouble 0.0 0.7 0.0 cr 24 96 pangoCairoShowLayout cr = < < pangoLayoutFreeze pl cairoSetSourceRgb cr . fromJust $ rgbDouble 0.6 0.4 0.2 cr 24 160 pangoCairoShowLayout cr = < < pangoLayoutFreeze pl rotate cr $ pi / 2 pl <- pangoCairoCreateLayout cr pangoLayoutSet pl . pangoFontDescriptionToNullable . Just =<< pangoFontDescriptionFreeze fd pangoLayoutSet @T.Text pl "\x01f9a5ナマケモノ" cairoSetSourceRgb cr . fromJust $ rgbDouble 0.5 0.5 0.05 cairoMoveTo cr 24 32 pangoCairoShowLayout cr =<< pangoLayoutFreeze pl cairoSetSourceRgb cr . fromJust $ rgbDouble 0.0 0.7 0.0 cairoMoveTo cr 24 96 pangoCairoShowLayout cr =<< pangoLayoutFreeze pl cairoSetSourceRgb cr . fromJust $ rgbDouble 0.6 0.4 0.2 cairoMoveTo cr 24 160 pangoCairoShowLayout cr =<< pangoLayoutFreeze pl -}
e0e14a8e2cb9afc9dd15f3f94326c76ae4ba3362642ba4303a7112e657333550
jasonkuhrt-archive/hpfp-answers
Intermission.hs
-- 1 Kind of `a`? -- a -> a -- Answer: -- a = * 2 Kinds of ` b ` and ` T ` ? -- a -> b a -> T (b a) -- Answers: -- a = * -- b = * -> * -- T = * -> * -- 3 Kind of `c`? -- c a b -> c b a -- Answer: -- c = * -> * -> *
null
https://raw.githubusercontent.com/jasonkuhrt-archive/hpfp-answers/c03ae936f208cfa3ca1eb0e720a5527cebe4c034/chapter-16-functor/Intermission.hs
haskell
1 Kind of `a`? a -> a Answer: a = * a -> b a -> T (b a) Answers: a = * b = * -> * T = * -> * 3 Kind of `c`? c a b -> c b a Answer: c = * -> * -> *
2 Kinds of ` b ` and ` T ` ?
40b8f299397cda3984b13f3a5a7c3eb569064d0b3be2570774f82c33f3e25e38
mgrabmueller/harpy
X86Disassembler.hs
-------------------------------------------------------------------------- -- | Module : Harpy . X86Disassembler Copyright : ( c ) and -- License : BSD3 -- -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Disassembler for x86 machine code. -- This is a module for compatibility with earlier Harpy releases . It -- re-exports the disassembler from the disassembler package. -------------------------------------------------------------------------- module Harpy.X86Disassembler( -- * Types Opcode, Operand(..), InstrOperandSize(..), Instruction(..), ShowStyle(..), -- * Functions disassembleBlock, disassembleList, disassembleArray, showIntel, showAtt ) where import Text.Disassembler.X86Disassembler
null
https://raw.githubusercontent.com/mgrabmueller/harpy/6df8f480e568a02c98e20d95effc5f35f204bff6/Harpy/X86Disassembler.hs
haskell
------------------------------------------------------------------------ | License : BSD3 Maintainer : Stability : provisional Portability : portable Disassembler for x86 machine code. re-exports the disassembler from the disassembler package. ------------------------------------------------------------------------ * Types * Functions
Module : Harpy . X86Disassembler Copyright : ( c ) and This is a module for compatibility with earlier Harpy releases . It module Harpy.X86Disassembler( Opcode, Operand(..), InstrOperandSize(..), Instruction(..), ShowStyle(..), disassembleBlock, disassembleList, disassembleArray, showIntel, showAtt ) where import Text.Disassembler.X86Disassembler
7a2871a3a6105c41ffce934e48ef7e4f6efdcdd0a44716f232ba41c68225c042
mmottl/gsl-ocaml
histo_ex.ml
open Gsl let pprint_histo { Histo.n = n ; Histo.range = r ; Histo.bin = b } = for i=0 to pred n do Printf.printf "%g %g %g\n" r.(i) r.(succ i) b.(i) done let main xmin xmax n = let h = Histo.make n in Histo.set_ranges_uniform h ~xmin ~xmax ; begin try while true do Scanf.scanf "%g" (fun x -> Histo.accumulate h x) done with End_of_file -> () end ; pprint_histo h let _ = if Array.length Sys.argv <> 4 then ( Printf.printf "Usage: gsl-histogram xmin xmax n\n" ; Printf.printf "Computes a histogram of the data on \ stdin using n bins from xmin to xmax\n" ; exit 1 ) ; main (float_of_string Sys.argv.(1)) (float_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
null
https://raw.githubusercontent.com/mmottl/gsl-ocaml/76f8d93cccc1f23084f4a33d3e0a8f1289450580/examples/histo_ex.ml
ocaml
open Gsl let pprint_histo { Histo.n = n ; Histo.range = r ; Histo.bin = b } = for i=0 to pred n do Printf.printf "%g %g %g\n" r.(i) r.(succ i) b.(i) done let main xmin xmax n = let h = Histo.make n in Histo.set_ranges_uniform h ~xmin ~xmax ; begin try while true do Scanf.scanf "%g" (fun x -> Histo.accumulate h x) done with End_of_file -> () end ; pprint_histo h let _ = if Array.length Sys.argv <> 4 then ( Printf.printf "Usage: gsl-histogram xmin xmax n\n" ; Printf.printf "Computes a histogram of the data on \ stdin using n bins from xmin to xmax\n" ; exit 1 ) ; main (float_of_string Sys.argv.(1)) (float_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
a9075ce65ce8f597f54b3ecf68dc8a54e264d8bdfc7299fce101620873a04d4a
xmppjingle/snatch
claws_lp.erl
-module(claws_lp). -behaviour(gen_server). -behaviour(claws). -export([start_link/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([send/2, send/3]). -export([read_chunk/3]). -include_lib("fast_xml/include/fxml.hrl"). -record(state, { url :: string(), channel :: httpc:request_id(), params, pid :: pid(), buffer = <<>> :: binary(), size = -1 :: integer() }). -define(EOL, <<"\r\n">>). start_link(Params) -> gen_server:start_link({local, ?MODULE}, ?MODULE, Params, []). init(#{url := URL}) -> gen_server:cast(?MODULE, connect), {ok, #state{url = URL}}. handle_call(_Request, _From, State) -> {reply, ignored, State}. handle_cast(connect, #state{url = URL} = State) -> Opts = [{sync, false}, {stream, self}, {full_result, false}, {socket_opts, [{nodelay, true}]}], case httpc:request(get, {URL, []}, [], Opts) of {ok, Channel} -> {noreply, State#state{channel = Channel, params = undefined}}; _ -> {noreply, State#state{channel = undefined, params = undefined}} end; handle_cast(_Msg, State) -> {noreply, State}. handle_info({http, {_Pid, stream_start, Params}}, State) -> snatch:connected(?MODULE), {noreply, State#state{params = Params}}; handle_info({http, {_Pid, stream_start, Params, Pid}}, State) -> snatch:connected(?MODULE), httpc:stream_next(Pid), {noreply, State#state{params = Params, pid = Pid}}; handle_info({http, {_Pid, stream_end, Params}}, State) -> snatch:disconnected(?MODULE), {noreply, State#state{params = Params, channel = undefined}}; handle_info({http, {_Pid, {error, _Reason}}}, State) -> snatch:disconnected(?MODULE), gen_server:cast(?MODULE, connect), {noreply, State#state{channel = undefined}}; handle_info({http, {_Pid, stream, Data}}, #state{buffer = Buffer, size = Size, pid = Pid} = State) -> NState = case read_chunk(Size, Buffer, Data) of {wait, NSize, NBuffer} -> State#state{buffer = NBuffer, size = NSize}; {chunk, _S, Packet, Rem} -> snatch:received(Packet), State#state{buffer = Rem, size = -1} end, httpc:stream_next(Pid), {noreply, NState}; handle_info(refresh, #state{pid = Pid} = State) -> httpc:stream_next(Pid), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, #state{channel = Channel}) when Channel /= undefined -> httpc:cancel_request(Channel), ok; terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. send(Data, JID) -> gen_server:cast(?MODULE, {send, Data, JID}). send(Data, JID, _ID) -> gen_server:cast(?MODULE, {send, Data, JID}). read_chunk(-1, Buffer, Data) -> Bin = <<Buffer/binary, Data/binary>>, {I, J} = binary:match(Bin, ?EOL), SizeBin = binary:part(Bin, {0, I + J - byte_size(?EOL)}), Size = erlang:binary_to_integer(SizeBin, 16), Offset = I + J, Chunk = binary:part(Bin, {Offset, byte_size(Bin) - Offset}), read_chunk(Size, Chunk, <<>>); read_chunk(Size, Buffer, Data) when byte_size(Buffer) + byte_size(Data) >= Size -> Bin = <<Buffer/binary, Data/binary>>, SizeBin = binary:part(Bin, {0, Size}), Chunk = binary:part(Bin, {Size, byte_size(Bin) - Size}), {chunk, Size, SizeBin, Chunk}; read_chunk(Size, Buffer, Data) -> {wait, Size, <<Buffer/binary, Data/binary>>}.
null
https://raw.githubusercontent.com/xmppjingle/snatch/da32ed1f17a05685461ec092800c4cb111a05f0b/src/claws_lp.erl
erlang
-module(claws_lp). -behaviour(gen_server). -behaviour(claws). -export([start_link/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([send/2, send/3]). -export([read_chunk/3]). -include_lib("fast_xml/include/fxml.hrl"). -record(state, { url :: string(), channel :: httpc:request_id(), params, pid :: pid(), buffer = <<>> :: binary(), size = -1 :: integer() }). -define(EOL, <<"\r\n">>). start_link(Params) -> gen_server:start_link({local, ?MODULE}, ?MODULE, Params, []). init(#{url := URL}) -> gen_server:cast(?MODULE, connect), {ok, #state{url = URL}}. handle_call(_Request, _From, State) -> {reply, ignored, State}. handle_cast(connect, #state{url = URL} = State) -> Opts = [{sync, false}, {stream, self}, {full_result, false}, {socket_opts, [{nodelay, true}]}], case httpc:request(get, {URL, []}, [], Opts) of {ok, Channel} -> {noreply, State#state{channel = Channel, params = undefined}}; _ -> {noreply, State#state{channel = undefined, params = undefined}} end; handle_cast(_Msg, State) -> {noreply, State}. handle_info({http, {_Pid, stream_start, Params}}, State) -> snatch:connected(?MODULE), {noreply, State#state{params = Params}}; handle_info({http, {_Pid, stream_start, Params, Pid}}, State) -> snatch:connected(?MODULE), httpc:stream_next(Pid), {noreply, State#state{params = Params, pid = Pid}}; handle_info({http, {_Pid, stream_end, Params}}, State) -> snatch:disconnected(?MODULE), {noreply, State#state{params = Params, channel = undefined}}; handle_info({http, {_Pid, {error, _Reason}}}, State) -> snatch:disconnected(?MODULE), gen_server:cast(?MODULE, connect), {noreply, State#state{channel = undefined}}; handle_info({http, {_Pid, stream, Data}}, #state{buffer = Buffer, size = Size, pid = Pid} = State) -> NState = case read_chunk(Size, Buffer, Data) of {wait, NSize, NBuffer} -> State#state{buffer = NBuffer, size = NSize}; {chunk, _S, Packet, Rem} -> snatch:received(Packet), State#state{buffer = Rem, size = -1} end, httpc:stream_next(Pid), {noreply, NState}; handle_info(refresh, #state{pid = Pid} = State) -> httpc:stream_next(Pid), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, #state{channel = Channel}) when Channel /= undefined -> httpc:cancel_request(Channel), ok; terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. send(Data, JID) -> gen_server:cast(?MODULE, {send, Data, JID}). send(Data, JID, _ID) -> gen_server:cast(?MODULE, {send, Data, JID}). read_chunk(-1, Buffer, Data) -> Bin = <<Buffer/binary, Data/binary>>, {I, J} = binary:match(Bin, ?EOL), SizeBin = binary:part(Bin, {0, I + J - byte_size(?EOL)}), Size = erlang:binary_to_integer(SizeBin, 16), Offset = I + J, Chunk = binary:part(Bin, {Offset, byte_size(Bin) - Offset}), read_chunk(Size, Chunk, <<>>); read_chunk(Size, Buffer, Data) when byte_size(Buffer) + byte_size(Data) >= Size -> Bin = <<Buffer/binary, Data/binary>>, SizeBin = binary:part(Bin, {0, Size}), Chunk = binary:part(Bin, {Size, byte_size(Bin) - Size}), {chunk, Size, SizeBin, Chunk}; read_chunk(Size, Buffer, Data) -> {wait, Size, <<Buffer/binary, Data/binary>>}.
99dcf1037a8388664af869730eeee87a164d7731d5683a5ff0dd8b2f20bb708a
aerolang/aero
aero_scan.erl
-module(aero_scan). -export([scan/1]). %% ----------------------------------------------------------------------------- %% Public API %% ----------------------------------------------------------------------------- -spec scan(binary()) -> {ok, [aero_token:t()]} | {error, term()}. scan(Input) -> scan(string:to_graphemes(Input), {0, 1, 1}, []). %% ----------------------------------------------------------------------------- Tokenizing %% ----------------------------------------------------------------------------- -define(is_digit(S1), (S1 >= $0 andalso S1 =< $9)). -define(is_hex(S1), (?is_digit(S1) orelse (S1 >= $a andalso S1 =< $f) orelse (S1 >= $A andalso S1 =< $F))). -define(is_oct(S1), (S1 >= $0 andalso S1 =< $8)). -define(is_bin(S1), (S1 =:= $0 orelse S1 =:= $1)). -define(is_ident_start(S1), (S1 =:= $_ orelse (S1 >= $a andalso S1 =< $z) orelse (S1 >= $A andalso S1 =< $Z))). -define(is_ident_continue(S1), (?is_ident_start(S1) orelse ?is_digit(S1))). -define(is_ident_op(S), S =:= 'if'; S =:= else; S =:= 'and'; S =:= 'or'; S =:= 'not'; S =:= for; S =:= while; S =:= where; S =:= as; S =:= match). -define(is_whitespace_start_1(S), S =:= "\s"; S =:= "\t"; S =:= "\n"; S =:= ["\r\n"]; S =:= ";"). -define(is_whitespace_start_2(S), S =:= "//"). -define(is_op_1(S), S =:= "("; S =:= ")"; S =:= "{"; S =:= "}"; S =:= "["; S =:= "]"; S =:= "+"; S =:= "-"; S =:= "*"; S =:= "/"; S =:= "%"; S =:= "<"; S =:= ">"; S =:= ","; S =:= "$"; S =:= ":"; S =:= "="; S =:= "^"; S =:= "&"; S =:= "|"; S =:= "?"; S =:= "!"; S =:= "."; S =:= "#"; S =:= "@"). -define(is_op_2(S), S =:= "#("; S =:= "#{"; S =:= "#["; S =:= "=="; S =:= "/="; S =:= "<="; S =:= ">="; S =:= "->"; S =:= "<-"; S =:= "=>"; S =:= "::"; S =:= "++"; S =:= "??"; S =:= "!!"; S =:= "?."; S =:= "!."; S =:= ".."). -define(is_op_3(S), S =:= "#!["; S =:= "&&&"; S =:= "|||"; S =:= "^^^"; S =:= "<<<"; S =:= ">>>"; S =:= "~~~"; S =:= "->>"; S =:= "<<-"; S =:= "..."; S =:= "..<"). -define(is_op_4(S), S =:= "...<"). scan(Input, Pos, Tokens) -> case next_token(Input, Pos) of {token, Rest, NewPos, Token} -> scan(Rest, NewPos, [Token | Tokens]); {end_token, _, Token} -> {ok, lists:reverse([Token | Tokens])}; {error, Error} -> {error, Error} end. %% Numeric literals. next_token("0b" ++ Cont, Pos) -> {Bin, Rest} = lists:splitwith(fun(S1) -> ?is_bin(S1) orelse S1 =:= $_ end, Cont), integer_token(Rest, Pos, Bin, 2, "0b"); next_token("0o" ++ Cont, Pos) -> {Oct, Rest} = lists:splitwith(fun(S1) -> ?is_oct(S1) orelse S1 =:= $_ end, Cont), integer_token(Rest, Pos, Oct, 8, "0o"); next_token("0x" ++ Cont, Pos) -> {Hex, Rest} = lists:splitwith(fun(S1) -> ?is_hex(S1) orelse S1 =:= $_ end, Cont), integer_token(Rest, Pos, Hex, 16, "0x"); next_token([S1 | _] = Input, Pos) when ?is_digit(S1) -> % A single `.` and `e` result in a float being made. Double `..` is tokenized % as an integer for a range. case lists:splitwith(fun(S2) -> ?is_digit(S2) orelse S2 =:= $_ end, Input) of {Int, [$., $. | _] = Rest} -> integer_token(Rest, Pos, Int, 10, ""); {IntPart, [$. | _] = Rest} -> float_token(Rest, Pos, IntPart); {IntPart, [$e | _] = Rest} -> float_token(Rest, Pos, IntPart); {Int, Rest} -> integer_token(Rest, Pos, Int, 10, "") end; %% Symbols. next_token([$:, S2 | _] = Input, Pos) when ?is_ident_start(S2); S2 =:= $" -> symbol_token(Input, Pos); %% Strings. next_token([$" | _] = Input, Pos) -> string_token(Input, Pos); %% Identifiers, type parameters, blanks, and operator-like identifiers. next_token([S1 | _] = Input, Pos) when ?is_ident_start(S1) -> case ident_token(Input, Pos) of {token, Rest, _, {ident, _, '_'}} -> blank_token(Rest, Pos); {token, Rest, _, {ident, _, Ident}} when ?is_ident_op(Ident) -> op_token(Rest, Pos, Ident, length(atom_to_list(Ident))); {token, _, _, _} = IdentToken -> IdentToken end; next_token([$', S2 | _] = Input, Pos) when ?is_ident_start(S2) -> type_param_token(Input, Pos); Whitespace . next_token([S1, S2 | _] = Input, Pos) when ?is_whitespace_start_2([S1, S2]) -> whitespace_token(Input, Pos); next_token([S1 | _] = Input, Pos) when ?is_whitespace_start_1([S1]) -> whitespace_token(Input, Pos); Operators . next_token([S1, S2, S3, S4 | Rest], Pos) when ?is_op_4([S1, S2, S3, S4]) -> op_token(Rest, Pos, list_to_atom([S1, S2, S3, S4]), 4); next_token([S1, S2, S3 | Rest], Pos) when ?is_op_3([S1, S2, S3]) -> op_token(Rest, Pos, list_to_atom([S1, S2, S3]), 3); next_token([S1, S2 | Rest], Pos) when ?is_op_2([S1, S2]) -> op_token(Rest, Pos, list_to_atom([S1, S2]), 2); next_token([S1 | Rest], Pos) when ?is_op_1([S1]) -> op_token(Rest, Pos, list_to_atom([S1]), 1); Eof . next_token([], Pos) -> eof_token(Pos); %% Anything else. next_token([S | _], Pos) -> {error, {unexpected_char, unicode:characters_to_binary([S]), Pos}}. %% ----------------------------------------------------------------------------- %% Token Types %% ----------------------------------------------------------------------------- integer_token(Rest, Pos, Source, Base, Prefix) -> Length = length(Source) + length(Prefix), NewPos = shift(Pos, Length, 0, Length), case drop_underscores(Source) of [] when Rest =:= [] -> {error, {unexpected_eof, Pos}}; Filtered when Filtered =:= []; ?is_ident_start(hd(Rest)) -> % No numbers after underscore, unexpected alpha, or number out of range. {error, {unexpected_char, unicode:characters_to_binary([hd(Rest)]), NewPos}}; Filtered -> {token, Rest, NewPos, {int_lit, meta(Pos, Length), list_to_integer(Filtered, Base)}} end. float_token([$. | Cont], Pos, IntSource) -> {FractSource, Rest} = lists:splitwith(fun(S1) -> ?is_digit(S1) orelse S1 =:= $_ end, Cont), Length = length(IntSource) + length(FractSource) + 1, NewPos = shift(Pos, Length, 0, Length), case drop_underscores(FractSource) of [] when Rest =:= [] -> {error, {unexpected_eof, Pos}}; FractFiltered when FractFiltered =:= []; ?is_ident_start(hd(Rest)), hd(Rest) =/= $e -> % No numbers after underscore, unexpected alpha, or number out of range. {error, {unexpected_char, unicode:characters_to_binary([hd(Rest)]), NewPos}}; FractFiltered when Rest =:= []; hd(Rest) =/= $e -> % No exponent: simple float. FloatFiltered = drop_underscores(IntSource) ++ "." ++ FractFiltered, {token, Rest, NewPos, {float_lit, meta(Pos, Length), list_to_float(FloatFiltered)}}; _-> % Continuing with exponent. float_token(Rest, Pos, IntSource, "." ++ FractSource) end; float_token([$e | _] = Rest, Pos, IntSource) -> float_token(Rest, Pos, IntSource, ""). % Adding on exponent (with "e" in front). float_token([$e, $+ | Cont], Pos, IntSource, FractSource) -> float_token(Cont, Pos, IntSource, FractSource, "e+"); float_token([$e, $- | Cont], Pos, IntSource, FractSource) -> float_token(Cont, Pos, IntSource, FractSource, "e-"); float_token([$e | Cont], Pos, IntSource, FractSource) -> float_token(Cont, Pos, IntSource, FractSource, "e"). float_token(Rest, Pos, IntSource, FractSource, SignSource) -> {ExpSource, Rest2} = lists:splitwith(fun(S1) -> ?is_digit(S1) orelse S1 =:= $_ end, Rest), Length = length(IntSource) + length(FractSource) + length(SignSource) + length(ExpSource), NewPos = shift(Pos, Length, 0, Length), case drop_underscores(ExpSource) of [] when Rest =:= [] -> {error, {unexpected_eof, Pos}}; ExpFiltered when ExpFiltered =:= []; ?is_ident_start(hd(Rest2)) -> % No numbers after underscore, unexpected alpha, or number out of range. {error, {unexpected_char, unicode:characters_to_binary([hd(Rest2)]), NewPos}}; ExpFiltered -> Erlang float parser needs a fractional part . Mantissa = case FractSource of "" -> drop_underscores(IntSource) ++ ".0"; _ -> drop_underscores(IntSource ++ FractSource) end, FloatFiltered = Mantissa ++ SignSource ++ ExpFiltered, {token, Rest2, NewPos, {float_lit, meta(Pos, Length), list_to_float(FloatFiltered)}} end. symbol_token([$: | Cont], Pos) when hd(Cont) =:= $" -> {token, Rest, NewPos, {str_lit, Meta, String}} = string_token(Cont, shift(Pos, 1, 0, 1)), {token, Rest, NewPos, {sym_lit, meta(Pos, span_size(Meta) + 1), binary_to_atom(String, utf8)}}; symbol_token([$: | Cont], Pos) -> {token, Rest, NewPos, {ident, Meta, Ident}} = ident_token(Cont, shift(Pos, 1, 0, 1)), {token, Rest, NewPos, {sym_lit, meta(Pos, span_size(Meta) + 1), Ident}}. string_token([$" | Cont], Pos) -> string_token(Cont, shift(Pos, 1, 0, 1), Pos, ""). string_token(Input, {Index, _, _} = Pos, {StartIndex, _, _} = StartPos, Acc) -> case Input of [$" | Rest] -> NewPos = shift(Pos, 1, 0, 1), Meta = meta(StartPos, Index + 1 - StartIndex), {token, Rest, NewPos, {str_lit, Meta, unicode:characters_to_binary(lists:reverse(Acc))}}; [$\\, $x, S3, S4 | Cont] when ?is_hex(S3), ?is_hex(S4) -> case escape_unicode([S3, S4]) of none -> {error, {invalid_str_escape, <<"x">>, shift(Pos, 1, 0, 1)}}; [Escaped] -> string_token(Cont, shift(Pos, 4, 0, 4), StartPos, [Escaped | Acc]) end; [$\\, $u, ${, S4, S5, S6, S7, $} | Cont] when ?is_hex(S4); ?is_hex(S5); ?is_hex(S6); ?is_hex(S7) -> case escape_unicode([S4, S5, S6, S7]) of none -> {error, {invalid_str_escape, <<"u">>, shift(Pos, 1, 0, 1)}}; [Escaped] -> string_token(Cont, shift(Pos, 8, 0, 8), StartPos, [Escaped | Acc]) end; [$\\, $u, ${, S4, S5, S6, S7, S8, S9, $} | Cont] when ?is_hex(S4); ?is_hex(S5); ?is_hex(S6); ?is_hex(S7); ?is_hex(S8); ?is_hex(S9) -> case escape_unicode([S4, S5, S6, S7, S8, S9]) of none -> {error, {invalid_str_escape, <<"u">>, shift(Pos, 1, 0, 1)}}; [Escaped] -> string_token(Cont, shift(Pos, 10, 0, 10), StartPos, [Escaped | Acc]) end; [$\\, S2 | Cont] -> case escape_char(S2) of none -> {error, {invalid_str_escape, unicode:characters_to_binary([S2]), shift(Pos, 1, 0, 1)}}; Escaped -> string_token(Cont, shift(Pos, 2, 0, 2), StartPos, [Escaped | Acc]) end; [S1 | _] when S1 =:= $\n; S1 =:= "\r\n" -> {error, {unexpected_char, unicode:characters_to_binary([S1]), Pos}}; [S1 | Cont] -> string_token(Cont, shift(Pos, input_size([S1]), 0, 1), StartPos, [S1 | Acc]); [] -> {error, {unexpected_eof, Pos}} end. ident_token([S1 | Cont], Pos) when ?is_ident_start(S1) -> {Tail, Rest} = lists:splitwith(fun(S2) -> ?is_ident_continue(S2) end, Cont), Ident = list_to_atom(unicode:characters_to_list([S1 | Tail])), Length = length([S1 | Tail]), Size = input_size([S1 | Tail]), NewPos = shift(Pos, Size, 0, Length), {token, Rest, NewPos, {ident, meta(Pos, Size), Ident}}. type_param_token([$' | Cont], Pos) -> {token, Rest, NewPos, {ident, Meta, Ident}} = ident_token(Cont, Pos), {token, Rest, NewPos, {type_param, meta(Pos, span_size(Meta)), Ident}}. blank_token(Rest, Pos) -> {token, Rest, shift(Pos, 1, 0, 1), {blank, meta(Pos, 1)}}. op_token(Rest, Pos, Op, Length) -> {token, Rest, shift(Pos, Length, 0, Length), {op, meta(Pos, Length), Op}}. whitespace_token(Input, Pos) -> whitespace_token(Input, Pos, Pos, none). whitespace_token(Input, {Index, _, _} = Pos, {StartIndex, _, _} = StartPos, Type) -> case Input of [$\s | Rest] -> whitespace_token(Rest, shift(Pos, 1, 0, 1), StartPos, Type); [$\t | Rest] -> whitespace_token(Rest, shift(Pos, 1, 0, 2), StartPos, Type); [$\n | Rest] when Type =:= semicolon -> whitespace_token(Rest, shift(Pos, 1, 1, 0), StartPos, semicolon); [$\n | Rest] -> whitespace_token(Rest, shift(Pos, 1, 1, 0), StartPos, newline); ["\r\n" | Rest] when Type =:= semicolon -> whitespace_token(Rest, shift(Pos, 2, 1, 0), StartPos, semicolon); ["\r\n" | Rest] -> whitespace_token(Rest, shift(Pos, 2, 1, 0), StartPos, newline); [$\\, $\n | Rest] -> whitespace_token(Rest, shift(Pos, 2, 1, 0), StartPos, Type); [$\\, "\r\n" | Rest] -> whitespace_token(Rest, shift(Pos, 3, 1, 0), StartPos, Type); [$; | Rest] -> whitespace_token(Rest, shift(Pos, 1, 0, 1), StartPos, semicolon); [$/, $/ | Cont] -> {Trimmed, Rest} = lists:splitwith(fun(S) -> S =/= $\n andalso S =/= "\r\n" end, Cont), NewPos = shift(Pos, input_size(Trimmed) + 2, 0, length(Trimmed) + 2), whitespace_token(Rest, NewPos, StartPos, Type); _ when Type =:= semicolon; Type =:= newline, (Input =:= [] orelse hd(Input) =/= $|) -> {token, Input, Pos, {newline, meta(StartPos, Index - StartIndex)}}; _ -> {token, Input, Pos, {space, meta(StartPos, Index - StartIndex)}} end. eof_token(Pos) -> {end_token, Pos, {eof, meta(Pos, 0)}}. %% ----------------------------------------------------------------------------- Utilities %% ----------------------------------------------------------------------------- drop_underscores(Source) -> lists:filter(fun(S1) -> S1 =/= $_ end, Source). escape_char($0) -> 0; escape_char($a) -> 7; escape_char($b) -> $\b; escape_char($e) -> 27; escape_char($f) -> $\f; escape_char($n) -> $\n; escape_char($r) -> $\r; escape_char($t) -> $\t; escape_char($v) -> $\v; escape_char($\\) -> $\\; escape_char($") -> $\"; escape_char(_) -> none. escape_unicode(Input) -> case unicode:characters_to_list([list_to_integer(Input, 16)]) of {error, _, _} -> none; {incomplete, _, _} -> none; String -> String end. input_size(Input) -> byte_size(unicode:characters_to_binary(Input)). shift({Index, Line, Column}, IndexIncr, 0, ColumnIncr) -> {Index + IndexIncr, Line, Column + ColumnIncr}; shift({Index, Line, _Column}, IndexIncr, LineIncr, 0) -> {Index + IndexIncr, Line + LineIncr, 1}. meta({Index, Line, Column}, Length) -> [ {line, Line}, {column, Column}, {span, aero_span:new(Index, Index + Length)} ]. span_size(Meta) -> Span = proplists:get_value(span, Meta), aero_span:stop(Span) - aero_span:start(Span).
null
https://raw.githubusercontent.com/aerolang/aero/c6bf662cbfc4f2af2910ddef47aec7484e3aa522/src/aero_scan.erl
erlang
----------------------------------------------------------------------------- Public API ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Numeric literals. A single `.` and `e` result in a float being made. Double `..` is tokenized as an integer for a range. Symbols. Strings. Identifiers, type parameters, blanks, and operator-like identifiers. Anything else. ----------------------------------------------------------------------------- Token Types ----------------------------------------------------------------------------- No numbers after underscore, unexpected alpha, or number out of range. No numbers after underscore, unexpected alpha, or number out of range. No exponent: simple float. Continuing with exponent. Adding on exponent (with "e" in front). No numbers after underscore, unexpected alpha, or number out of range. ----------------------------------------------------------------------------- -----------------------------------------------------------------------------
-module(aero_scan). -export([scan/1]). -spec scan(binary()) -> {ok, [aero_token:t()]} | {error, term()}. scan(Input) -> scan(string:to_graphemes(Input), {0, 1, 1}, []). Tokenizing -define(is_digit(S1), (S1 >= $0 andalso S1 =< $9)). -define(is_hex(S1), (?is_digit(S1) orelse (S1 >= $a andalso S1 =< $f) orelse (S1 >= $A andalso S1 =< $F))). -define(is_oct(S1), (S1 >= $0 andalso S1 =< $8)). -define(is_bin(S1), (S1 =:= $0 orelse S1 =:= $1)). -define(is_ident_start(S1), (S1 =:= $_ orelse (S1 >= $a andalso S1 =< $z) orelse (S1 >= $A andalso S1 =< $Z))). -define(is_ident_continue(S1), (?is_ident_start(S1) orelse ?is_digit(S1))). -define(is_ident_op(S), S =:= 'if'; S =:= else; S =:= 'and'; S =:= 'or'; S =:= 'not'; S =:= for; S =:= while; S =:= where; S =:= as; S =:= match). -define(is_whitespace_start_1(S), S =:= "\s"; S =:= "\t"; S =:= "\n"; S =:= ["\r\n"]; S =:= ";"). -define(is_whitespace_start_2(S), S =:= "//"). -define(is_op_1(S), S =:= "("; S =:= ")"; S =:= "{"; S =:= "}"; S =:= "["; S =:= "]"; S =:= "+"; S =:= "-"; S =:= "*"; S =:= "/"; S =:= "%"; S =:= "<"; S =:= ">"; S =:= ","; S =:= "$"; S =:= ":"; S =:= "="; S =:= "^"; S =:= "&"; S =:= "|"; S =:= "?"; S =:= "!"; S =:= "."; S =:= "#"; S =:= "@"). -define(is_op_2(S), S =:= "#("; S =:= "#{"; S =:= "#["; S =:= "=="; S =:= "/="; S =:= "<="; S =:= ">="; S =:= "->"; S =:= "<-"; S =:= "=>"; S =:= "::"; S =:= "++"; S =:= "??"; S =:= "!!"; S =:= "?."; S =:= "!."; S =:= ".."). -define(is_op_3(S), S =:= "#!["; S =:= "&&&"; S =:= "|||"; S =:= "^^^"; S =:= "<<<"; S =:= ">>>"; S =:= "~~~"; S =:= "->>"; S =:= "<<-"; S =:= "..."; S =:= "..<"). -define(is_op_4(S), S =:= "...<"). scan(Input, Pos, Tokens) -> case next_token(Input, Pos) of {token, Rest, NewPos, Token} -> scan(Rest, NewPos, [Token | Tokens]); {end_token, _, Token} -> {ok, lists:reverse([Token | Tokens])}; {error, Error} -> {error, Error} end. next_token("0b" ++ Cont, Pos) -> {Bin, Rest} = lists:splitwith(fun(S1) -> ?is_bin(S1) orelse S1 =:= $_ end, Cont), integer_token(Rest, Pos, Bin, 2, "0b"); next_token("0o" ++ Cont, Pos) -> {Oct, Rest} = lists:splitwith(fun(S1) -> ?is_oct(S1) orelse S1 =:= $_ end, Cont), integer_token(Rest, Pos, Oct, 8, "0o"); next_token("0x" ++ Cont, Pos) -> {Hex, Rest} = lists:splitwith(fun(S1) -> ?is_hex(S1) orelse S1 =:= $_ end, Cont), integer_token(Rest, Pos, Hex, 16, "0x"); next_token([S1 | _] = Input, Pos) when ?is_digit(S1) -> case lists:splitwith(fun(S2) -> ?is_digit(S2) orelse S2 =:= $_ end, Input) of {Int, [$., $. | _] = Rest} -> integer_token(Rest, Pos, Int, 10, ""); {IntPart, [$. | _] = Rest} -> float_token(Rest, Pos, IntPart); {IntPart, [$e | _] = Rest} -> float_token(Rest, Pos, IntPart); {Int, Rest} -> integer_token(Rest, Pos, Int, 10, "") end; next_token([$:, S2 | _] = Input, Pos) when ?is_ident_start(S2); S2 =:= $" -> symbol_token(Input, Pos); next_token([$" | _] = Input, Pos) -> string_token(Input, Pos); next_token([S1 | _] = Input, Pos) when ?is_ident_start(S1) -> case ident_token(Input, Pos) of {token, Rest, _, {ident, _, '_'}} -> blank_token(Rest, Pos); {token, Rest, _, {ident, _, Ident}} when ?is_ident_op(Ident) -> op_token(Rest, Pos, Ident, length(atom_to_list(Ident))); {token, _, _, _} = IdentToken -> IdentToken end; next_token([$', S2 | _] = Input, Pos) when ?is_ident_start(S2) -> type_param_token(Input, Pos); Whitespace . next_token([S1, S2 | _] = Input, Pos) when ?is_whitespace_start_2([S1, S2]) -> whitespace_token(Input, Pos); next_token([S1 | _] = Input, Pos) when ?is_whitespace_start_1([S1]) -> whitespace_token(Input, Pos); Operators . next_token([S1, S2, S3, S4 | Rest], Pos) when ?is_op_4([S1, S2, S3, S4]) -> op_token(Rest, Pos, list_to_atom([S1, S2, S3, S4]), 4); next_token([S1, S2, S3 | Rest], Pos) when ?is_op_3([S1, S2, S3]) -> op_token(Rest, Pos, list_to_atom([S1, S2, S3]), 3); next_token([S1, S2 | Rest], Pos) when ?is_op_2([S1, S2]) -> op_token(Rest, Pos, list_to_atom([S1, S2]), 2); next_token([S1 | Rest], Pos) when ?is_op_1([S1]) -> op_token(Rest, Pos, list_to_atom([S1]), 1); Eof . next_token([], Pos) -> eof_token(Pos); next_token([S | _], Pos) -> {error, {unexpected_char, unicode:characters_to_binary([S]), Pos}}. integer_token(Rest, Pos, Source, Base, Prefix) -> Length = length(Source) + length(Prefix), NewPos = shift(Pos, Length, 0, Length), case drop_underscores(Source) of [] when Rest =:= [] -> {error, {unexpected_eof, Pos}}; Filtered when Filtered =:= []; ?is_ident_start(hd(Rest)) -> {error, {unexpected_char, unicode:characters_to_binary([hd(Rest)]), NewPos}}; Filtered -> {token, Rest, NewPos, {int_lit, meta(Pos, Length), list_to_integer(Filtered, Base)}} end. float_token([$. | Cont], Pos, IntSource) -> {FractSource, Rest} = lists:splitwith(fun(S1) -> ?is_digit(S1) orelse S1 =:= $_ end, Cont), Length = length(IntSource) + length(FractSource) + 1, NewPos = shift(Pos, Length, 0, Length), case drop_underscores(FractSource) of [] when Rest =:= [] -> {error, {unexpected_eof, Pos}}; FractFiltered when FractFiltered =:= []; ?is_ident_start(hd(Rest)), hd(Rest) =/= $e -> {error, {unexpected_char, unicode:characters_to_binary([hd(Rest)]), NewPos}}; FractFiltered when Rest =:= []; hd(Rest) =/= $e -> FloatFiltered = drop_underscores(IntSource) ++ "." ++ FractFiltered, {token, Rest, NewPos, {float_lit, meta(Pos, Length), list_to_float(FloatFiltered)}}; _-> float_token(Rest, Pos, IntSource, "." ++ FractSource) end; float_token([$e | _] = Rest, Pos, IntSource) -> float_token(Rest, Pos, IntSource, ""). float_token([$e, $+ | Cont], Pos, IntSource, FractSource) -> float_token(Cont, Pos, IntSource, FractSource, "e+"); float_token([$e, $- | Cont], Pos, IntSource, FractSource) -> float_token(Cont, Pos, IntSource, FractSource, "e-"); float_token([$e | Cont], Pos, IntSource, FractSource) -> float_token(Cont, Pos, IntSource, FractSource, "e"). float_token(Rest, Pos, IntSource, FractSource, SignSource) -> {ExpSource, Rest2} = lists:splitwith(fun(S1) -> ?is_digit(S1) orelse S1 =:= $_ end, Rest), Length = length(IntSource) + length(FractSource) + length(SignSource) + length(ExpSource), NewPos = shift(Pos, Length, 0, Length), case drop_underscores(ExpSource) of [] when Rest =:= [] -> {error, {unexpected_eof, Pos}}; ExpFiltered when ExpFiltered =:= []; ?is_ident_start(hd(Rest2)) -> {error, {unexpected_char, unicode:characters_to_binary([hd(Rest2)]), NewPos}}; ExpFiltered -> Erlang float parser needs a fractional part . Mantissa = case FractSource of "" -> drop_underscores(IntSource) ++ ".0"; _ -> drop_underscores(IntSource ++ FractSource) end, FloatFiltered = Mantissa ++ SignSource ++ ExpFiltered, {token, Rest2, NewPos, {float_lit, meta(Pos, Length), list_to_float(FloatFiltered)}} end. symbol_token([$: | Cont], Pos) when hd(Cont) =:= $" -> {token, Rest, NewPos, {str_lit, Meta, String}} = string_token(Cont, shift(Pos, 1, 0, 1)), {token, Rest, NewPos, {sym_lit, meta(Pos, span_size(Meta) + 1), binary_to_atom(String, utf8)}}; symbol_token([$: | Cont], Pos) -> {token, Rest, NewPos, {ident, Meta, Ident}} = ident_token(Cont, shift(Pos, 1, 0, 1)), {token, Rest, NewPos, {sym_lit, meta(Pos, span_size(Meta) + 1), Ident}}. string_token([$" | Cont], Pos) -> string_token(Cont, shift(Pos, 1, 0, 1), Pos, ""). string_token(Input, {Index, _, _} = Pos, {StartIndex, _, _} = StartPos, Acc) -> case Input of [$" | Rest] -> NewPos = shift(Pos, 1, 0, 1), Meta = meta(StartPos, Index + 1 - StartIndex), {token, Rest, NewPos, {str_lit, Meta, unicode:characters_to_binary(lists:reverse(Acc))}}; [$\\, $x, S3, S4 | Cont] when ?is_hex(S3), ?is_hex(S4) -> case escape_unicode([S3, S4]) of none -> {error, {invalid_str_escape, <<"x">>, shift(Pos, 1, 0, 1)}}; [Escaped] -> string_token(Cont, shift(Pos, 4, 0, 4), StartPos, [Escaped | Acc]) end; [$\\, $u, ${, S4, S5, S6, S7, $} | Cont] when ?is_hex(S4); ?is_hex(S5); ?is_hex(S6); ?is_hex(S7) -> case escape_unicode([S4, S5, S6, S7]) of none -> {error, {invalid_str_escape, <<"u">>, shift(Pos, 1, 0, 1)}}; [Escaped] -> string_token(Cont, shift(Pos, 8, 0, 8), StartPos, [Escaped | Acc]) end; [$\\, $u, ${, S4, S5, S6, S7, S8, S9, $} | Cont] when ?is_hex(S4); ?is_hex(S5); ?is_hex(S6); ?is_hex(S7); ?is_hex(S8); ?is_hex(S9) -> case escape_unicode([S4, S5, S6, S7, S8, S9]) of none -> {error, {invalid_str_escape, <<"u">>, shift(Pos, 1, 0, 1)}}; [Escaped] -> string_token(Cont, shift(Pos, 10, 0, 10), StartPos, [Escaped | Acc]) end; [$\\, S2 | Cont] -> case escape_char(S2) of none -> {error, {invalid_str_escape, unicode:characters_to_binary([S2]), shift(Pos, 1, 0, 1)}}; Escaped -> string_token(Cont, shift(Pos, 2, 0, 2), StartPos, [Escaped | Acc]) end; [S1 | _] when S1 =:= $\n; S1 =:= "\r\n" -> {error, {unexpected_char, unicode:characters_to_binary([S1]), Pos}}; [S1 | Cont] -> string_token(Cont, shift(Pos, input_size([S1]), 0, 1), StartPos, [S1 | Acc]); [] -> {error, {unexpected_eof, Pos}} end. ident_token([S1 | Cont], Pos) when ?is_ident_start(S1) -> {Tail, Rest} = lists:splitwith(fun(S2) -> ?is_ident_continue(S2) end, Cont), Ident = list_to_atom(unicode:characters_to_list([S1 | Tail])), Length = length([S1 | Tail]), Size = input_size([S1 | Tail]), NewPos = shift(Pos, Size, 0, Length), {token, Rest, NewPos, {ident, meta(Pos, Size), Ident}}. type_param_token([$' | Cont], Pos) -> {token, Rest, NewPos, {ident, Meta, Ident}} = ident_token(Cont, Pos), {token, Rest, NewPos, {type_param, meta(Pos, span_size(Meta)), Ident}}. blank_token(Rest, Pos) -> {token, Rest, shift(Pos, 1, 0, 1), {blank, meta(Pos, 1)}}. op_token(Rest, Pos, Op, Length) -> {token, Rest, shift(Pos, Length, 0, Length), {op, meta(Pos, Length), Op}}. whitespace_token(Input, Pos) -> whitespace_token(Input, Pos, Pos, none). whitespace_token(Input, {Index, _, _} = Pos, {StartIndex, _, _} = StartPos, Type) -> case Input of [$\s | Rest] -> whitespace_token(Rest, shift(Pos, 1, 0, 1), StartPos, Type); [$\t | Rest] -> whitespace_token(Rest, shift(Pos, 1, 0, 2), StartPos, Type); [$\n | Rest] when Type =:= semicolon -> whitespace_token(Rest, shift(Pos, 1, 1, 0), StartPos, semicolon); [$\n | Rest] -> whitespace_token(Rest, shift(Pos, 1, 1, 0), StartPos, newline); ["\r\n" | Rest] when Type =:= semicolon -> whitespace_token(Rest, shift(Pos, 2, 1, 0), StartPos, semicolon); ["\r\n" | Rest] -> whitespace_token(Rest, shift(Pos, 2, 1, 0), StartPos, newline); [$\\, $\n | Rest] -> whitespace_token(Rest, shift(Pos, 2, 1, 0), StartPos, Type); [$\\, "\r\n" | Rest] -> whitespace_token(Rest, shift(Pos, 3, 1, 0), StartPos, Type); [$; | Rest] -> whitespace_token(Rest, shift(Pos, 1, 0, 1), StartPos, semicolon); [$/, $/ | Cont] -> {Trimmed, Rest} = lists:splitwith(fun(S) -> S =/= $\n andalso S =/= "\r\n" end, Cont), NewPos = shift(Pos, input_size(Trimmed) + 2, 0, length(Trimmed) + 2), whitespace_token(Rest, NewPos, StartPos, Type); _ when Type =:= semicolon; Type =:= newline, (Input =:= [] orelse hd(Input) =/= $|) -> {token, Input, Pos, {newline, meta(StartPos, Index - StartIndex)}}; _ -> {token, Input, Pos, {space, meta(StartPos, Index - StartIndex)}} end. eof_token(Pos) -> {end_token, Pos, {eof, meta(Pos, 0)}}. Utilities drop_underscores(Source) -> lists:filter(fun(S1) -> S1 =/= $_ end, Source). escape_char($0) -> 0; escape_char($a) -> 7; escape_char($b) -> $\b; escape_char($e) -> 27; escape_char($f) -> $\f; escape_char($n) -> $\n; escape_char($r) -> $\r; escape_char($t) -> $\t; escape_char($v) -> $\v; escape_char($\\) -> $\\; escape_char($") -> $\"; escape_char(_) -> none. escape_unicode(Input) -> case unicode:characters_to_list([list_to_integer(Input, 16)]) of {error, _, _} -> none; {incomplete, _, _} -> none; String -> String end. input_size(Input) -> byte_size(unicode:characters_to_binary(Input)). shift({Index, Line, Column}, IndexIncr, 0, ColumnIncr) -> {Index + IndexIncr, Line, Column + ColumnIncr}; shift({Index, Line, _Column}, IndexIncr, LineIncr, 0) -> {Index + IndexIncr, Line + LineIncr, 1}. meta({Index, Line, Column}, Length) -> [ {line, Line}, {column, Column}, {span, aero_span:new(Index, Index + Length)} ]. span_size(Meta) -> Span = proplists:get_value(span, Meta), aero_span:stop(Span) - aero_span:start(Span).
95cb61c096adb6bedc192e6e791605bbeda05bdecec54e58a636fb9aa7aacf4a
mattjbray/ocaml-decoders
util.ml
module My_result = struct type ('good, 'bad) t = ('good, 'bad) Belt.Result.t = | Ok of 'good | Error of 'bad let return x = Ok x let map : ('a -> 'b) -> ('a, 'err) t -> ('b, 'err) t = fun f x -> Belt.Result.map x f let map_err : ('err1 -> 'err2) -> ('a, 'err1) t -> ('a, 'err2) t = fun f -> function Ok x -> Ok x | Error e -> Error (f e) let combine_l (results : ('a, 'e) result list) : ('a list, 'e list) result = let rec aux combined = function | [] -> ( match combined with | Ok xs -> Ok (List.rev xs) | Error es -> Error (List.rev es) ) | result :: rest -> let combined = match (result, combined) with | Ok x, Ok xs -> Ok (x :: xs) | Error e, Error es -> Error (e :: es) | Error e, Ok _ -> Error [ e ] | Ok _, Error es -> Error es in aux combined rest in aux (Ok []) results module Infix = struct let ( >|= ) : ('a, 'err) t -> ('a -> 'b) -> ('b, 'err) t = Belt.Result.map let ( >>= ) : ('a, 'err) t -> ('a -> ('b, 'err) t) -> ('b, 'err) t = Belt.Result.flatMap end end module My_opt = struct let return x = Some x let map f x = Belt.Option.map x f let flat_map f x = Belt.Option.flatMap x f end module My_list = struct let take i xs = xs |. Belt.List.take i |. Belt.Option.getWithDefault [] let map f xs = Belt.List.map xs f let mapi f xs = Belt.List.mapWithIndex xs f let filter_mapi f l = let rec recurse (acc, i) l = match l with | [] -> List.rev acc | x :: l' -> let acc' = match f i x with None -> acc | Some y -> y :: acc in recurse (acc', i + 1) l' in recurse ([], 0) l let filter_map f xs = filter_mapi (fun _i x -> f x) xs let find_map f xs = xs |. Belt.List.getBy (fun x -> match f x with Some _ -> true | None -> false ) |. Belt.Option.flatMap f let fold_left f init xs = Belt.List.reduce xs init f end
null
https://raw.githubusercontent.com/mattjbray/ocaml-decoders/00d930a516805f1bb8965fed36971920766dce60/src-bs/util.ml
ocaml
module My_result = struct type ('good, 'bad) t = ('good, 'bad) Belt.Result.t = | Ok of 'good | Error of 'bad let return x = Ok x let map : ('a -> 'b) -> ('a, 'err) t -> ('b, 'err) t = fun f x -> Belt.Result.map x f let map_err : ('err1 -> 'err2) -> ('a, 'err1) t -> ('a, 'err2) t = fun f -> function Ok x -> Ok x | Error e -> Error (f e) let combine_l (results : ('a, 'e) result list) : ('a list, 'e list) result = let rec aux combined = function | [] -> ( match combined with | Ok xs -> Ok (List.rev xs) | Error es -> Error (List.rev es) ) | result :: rest -> let combined = match (result, combined) with | Ok x, Ok xs -> Ok (x :: xs) | Error e, Error es -> Error (e :: es) | Error e, Ok _ -> Error [ e ] | Ok _, Error es -> Error es in aux combined rest in aux (Ok []) results module Infix = struct let ( >|= ) : ('a, 'err) t -> ('a -> 'b) -> ('b, 'err) t = Belt.Result.map let ( >>= ) : ('a, 'err) t -> ('a -> ('b, 'err) t) -> ('b, 'err) t = Belt.Result.flatMap end end module My_opt = struct let return x = Some x let map f x = Belt.Option.map x f let flat_map f x = Belt.Option.flatMap x f end module My_list = struct let take i xs = xs |. Belt.List.take i |. Belt.Option.getWithDefault [] let map f xs = Belt.List.map xs f let mapi f xs = Belt.List.mapWithIndex xs f let filter_mapi f l = let rec recurse (acc, i) l = match l with | [] -> List.rev acc | x :: l' -> let acc' = match f i x with None -> acc | Some y -> y :: acc in recurse (acc', i + 1) l' in recurse ([], 0) l let filter_map f xs = filter_mapi (fun _i x -> f x) xs let find_map f xs = xs |. Belt.List.getBy (fun x -> match f x with Some _ -> true | None -> false ) |. Belt.Option.flatMap f let fold_left f init xs = Belt.List.reduce xs init f end
a33e46fe9340bd01547841277539283b6c47ea15a838381377160127a334e7e1
oriansj/mes-m2
mescc.scm
GNU --- Maxwell Equations of Software Copyright © 2016,2017,2018,2019,2020 Jan ( janneke ) Nieuwenhuizen < > ;;; This file is part of GNU . ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; GNU is distributed in the hope that it will be useful , but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (mescc mescc) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:use-module (ice-9 pretty-print) #:use-module (ice-9 getopt-long) #:use-module (mes mes-0) #:use-module (mes misc) #:use-module (mescc info) #:use-module (mescc armv4 info) #:use-module (mescc i386 info) #:use-module (mescc x86_64 info) #:use-module (mescc preprocess) #:use-module (mescc compile) #:use-module (mescc M1) #:export (count-opt mescc:preprocess mescc:get-host mescc:compile mescc:assemble mescc:link multi-opt)) (define GUILE-with-output-to-file with-output-to-file) (define (with-output-to-file file-name thunk) (if (equal? file-name "-") (thunk) (GUILE-with-output-to-file file-name thunk))) (define (mescc:preprocess options) (let* ((pretty-print/write (string->symbol (option-ref options 'write (if guile? "pretty-print" "write")))) (pretty-print/write (if (eq? pretty-print/write 'pretty-print) pretty-print write)) (files (option-ref options '() '("a.c"))) (input-file-name (car files)) (input-base (basename input-file-name)) (ast-file-name (cond ((and (option-ref options 'preprocess #f) (option-ref options 'output #f))) (else (replace-suffix input-base ".E")))) (dir (dirname input-file-name)) (defines (reverse (filter-map (multi-opt 'define) options))) (includes (reverse (filter-map (multi-opt 'include) options))) (includes (cons (option-ref options 'includedir #f) includes)) (includes (cons dir includes)) (prefix (option-ref options 'prefix "")) (machine (option-ref options 'machine "32")) (arch (arch-get options)) (defines (append (arch-get-defines options) defines)) (verbose? (count-opt options 'verbose))) (with-output-to-file ast-file-name (lambda _ (for-each (cut c->ast prefix defines includes arch pretty-print/write verbose? <>) files))))) (define (c->ast prefix defines includes arch write verbose? file-name) (with-input-from-file file-name (cut write (c99-input->ast #:prefix prefix #:defines defines #:includes includes #:arch arch #:verbose? verbose?)))) (define (mescc:compile options) (let* ((files (option-ref options '() '("a.c"))) (input-file-name (car files)) (input-base (basename input-file-name)) (M1-file-name (cond ((and (option-ref options 'compile #f) (option-ref options 'output #f))) ((string-suffix? ".S" input-file-name) input-file-name) (else (replace-suffix input-base ".s")))) (infos (map (cut file->info options <>) files)) (verbose? (count-opt options 'verbose)) (numbered-arch? (option-ref options 'numbered-arch? #f)) (align (filter-map (multi-opt 'align) options)) (align (if (null? align) '(functions) (map string->symbol align))) (align (if (not numbered-arch?) align function alignment not supported by MesCC - Tools 0.5.2 (filter (negate (cut eq? <> 'functions)) align)))) (when verbose? (format (current-error-port) "dumping: ~a\n" M1-file-name)) (with-output-to-file M1-file-name (cut infos->M1 M1-file-name infos #:align align #:verbose? verbose?)) M1-file-name)) (define (file->info options file-name) (cond ((.c? file-name) (c->info options file-name)) ((.E? file-name) (E->info options file-name)))) (define (c->info options file-name) (let* ((dir (dirname file-name)) (defines (reverse (filter-map (multi-opt 'define) options))) (includes (reverse (filter-map (multi-opt 'include) options))) (includes (cons (option-ref options 'includedir #f) includes)) (includes (cons dir includes)) (prefix (option-ref options 'prefix "")) (defines (append (arch-get-defines options) defines)) (arch (arch-get options)) (verbose? (count-opt options 'verbose))) (with-input-from-file file-name (cut c99-input->info (arch-get-info options) #:prefix prefix #:defines defines #:includes includes #:arch arch #:verbose? verbose?)))) (define (E->info options file-name) (let ((ast (with-input-from-file file-name read)) (verbose? (count-opt options 'verbose))) (c99-ast->info (arch-get-info options) ast #:verbose? verbose?))) (define (mescc:assemble options) (let* ((files (option-ref options '() '("a.c"))) (input-file-name (car files)) (input-base (basename input-file-name)) (hex2-file-name (cond ((and (option-ref options 'assemble #f) (option-ref options 'output #f))) (else (replace-suffix input-base ".o")))) (s-files (filter .s? files)) FIXME (source-files (filter (disjoin .c? .E?) files)) (infos (map (cut file->info options <>) source-files))) (if (and (pair? s-files) (pair? infos)) (error "mixing source and object not supported:" source-files s-files)) (when (pair? s-files) (M1->hex2 options s-files)) (when (pair? infos) (infos->hex2 options hex2-file-name infos)) hex2-file-name)) (define (mescc:link options) (let* ((files (option-ref options '() '("a.c"))) (source-files (filter (disjoin .c? .E?) files)) (input-file-name (car files)) (hex2-file-name (if (or (string-suffix? ".hex2" input-file-name) (string-suffix? ".o" input-file-name)) input-file-name (replace-suffix input-file-name ".o"))) (infos (map (cut file->info options <>) source-files)) (s-files (filter .s? files)) (hex2-files (filter .o? files)) (hex2-files (if (null? s-files) hex2-files (append hex2-files (list (M1->hex2 options s-files))))) (hex2-files (if (null? infos) hex2-files (append hex2-files (list (infos->hex2 options hex2-file-name infos))))) (default-libraries (if (or (option-ref options 'nodefaultlibs #f) (option-ref options 'nostdlib #f)) '() '("mescc" "c"))) (libraries (filter-map (multi-opt 'library) options)) (libraries (delete-duplicates (append libraries default-libraries))) (hex2-libraries (map (cut find-library options ".a" <>) libraries)) (hex2-files (append hex2-files hex2-libraries)) (s-files (append s-files (map (cut find-library options ".s" <>) libraries))) (debug-info? (option-ref options 'debug-info #f)) (s-files (if (string-suffix? ".S" input-file-name) s-files (cons (replace-suffix input-file-name ".s") s-files))) (elf-footer (and debug-info? (or (M1->blood-elf options s-files) (exit 1))))) (or (hex2->elf options hex2-files #:elf-footer elf-footer) (exit 1)))) (define (infos->hex2 options hex2-file-name infos) (let* ((input-file-name (car (option-ref options '() '("a.c")))) (M1-file-name (replace-suffix hex2-file-name ".s")) (options (acons 'compile #t options)) ; ugh (options (acons 'output hex2-file-name options)) (verbose? (count-opt options 'verbose)) (numbered-arch? (option-ref options 'numbered-arch? #f)) (align (filter-map (multi-opt 'align) options)) (align (if (null? align) '(functions) (map string->symbol align))) (align (if (not numbered-arch?) align function alignment not supported by MesCC - Tools 0.5.2 (filter (negate (cut eq? <> 'functions)) align)))) (when verbose? (format (current-error-port) "dumping: ~a\n" M1-file-name)) (with-output-to-file M1-file-name (cut infos->M1 M1-file-name infos #:align align)) (or (M1->hex2 options (list M1-file-name)) (exit 1)))) (define (M1->hex2 options M1-files) (let* ((input-file-name (car (option-ref options '() '("a.c")))) (input-base (basename input-file-name)) (M1-file-name (car M1-files)) (hex2-file-name (cond ((and (option-ref options 'assemble #f) (option-ref options 'output #f))) ((option-ref options 'assemble #f) (replace-suffix input-base ".o")) (else (replace-suffix M1-file-name ".o")))) (verbose? (count-opt options 'verbose)) (M1 (or (getenv "M1") "M1")) (command `(,M1 "--little-endian" ,@(arch-get-architecture options) "-f" ,(arch-find options (arch-get-m1-macros options)) ,@(append-map (cut list "-f" <>) M1-files) "-o" ,hex2-file-name))) (when (and verbose? (> verbose? 1)) (format (current-error-port) "~a\n" (string-join command))) (and (zero? (apply assert-system* command)) hex2-file-name))) (define* (hex2->elf options hex2-files #:key elf-footer) (let* ((input-file-name (car (option-ref options '() '("a.c")))) (elf-file-name (cond ((option-ref options 'output #f)) (else "a.out"))) (verbose? (count-opt options 'verbose)) (hex2 (or (getenv "HEX2") "hex2")) (base-address (option-ref options 'base-address "0x1000000")) (machine (arch-get-machine options)) (elf-footer (or elf-footer (kernel-find options (string-append "elf" machine "-footer-single-main.hex2")))) (start-files (if (or (option-ref options 'nostartfiles #f) (option-ref options 'nostdlib #f)) '() `("-f" ,(arch-find options "crt1.o")))) (command `(,hex2 "--little-endian" ,@(arch-get-architecture options) "--base-address" ,base-address "-f" ,(kernel-find options (string-append "elf" machine "-header.hex2")) ,@start-files ,@(append-map (cut list "-f" <>) hex2-files) "-f" ,elf-footer "--exec_enable" "-o" ,elf-file-name))) (when (and verbose? (> verbose? 1)) (format (current-error-port) "~a\n" (string-join command))) (and (zero? (apply assert-system* command)) elf-file-name))) (define (M1->blood-elf options M1-files) (let* ((M1-file-name (car M1-files)) (M1-blood-elf-footer (string-append M1-file-name ".blood-elf")) (hex2-file-name (replace-suffix M1-file-name ".o")) (blood-elf-footer (string-append hex2-file-name ".blood-elf")) (verbose? (count-opt options 'verbose)) (blood-elf (or (getenv "BLOOD_ELF") "blood-elf")) (command `(,blood-elf "-f" ,(arch-find options (arch-get-m1-macros options)) ,@(append-map (cut list "-f" <>) M1-files) "-o" ,M1-blood-elf-footer))) (when (and verbose? (> verbose? 1)) (format (current-error-port) "~a\n" (string-join command))) (and (zero? (apply assert-system* command)) (let* ((options (acons 'compile #t options)) ; ugh (options (acons 'output blood-elf-footer options))) (M1->hex2 options (list M1-blood-elf-footer)))))) (define (replace-suffix file-name suffix) (let* ((parts (string-split file-name #\.)) (base (if (pair? (cdr parts)) (drop-right parts 1) (list file-name))) (old-suffix (if (pair? (cdr parts)) (last parts) "")) (program-prefix (cond ((string-prefix? "arm-mes-" old-suffix) ".arm-mes-") ((string-prefix? "x86-mes-" old-suffix) ".x86-mes-") ((string-prefix? "x86_64-mes-" old-suffix) ".x86_64-mes-") (else ".")))) (if (string-null? suffix) (if (string-null? program-prefix) (string-join base ".") (string-append (string-drop program-prefix 1) (string-join base "."))) (string-append (string-join base ".") program-prefix (string-drop suffix 1))))) (define (find-library options ext o) (arch-find options (string-append "lib" o ext))) (define* (arch-find options file-name #:key kernel) (let* ((srcdest (or (getenv "srcdest") "")) (srcdir-lib (string-append srcdest "lib")) (srcdir-mescc-lib (string-append srcdest "mescc-lib")) (libdir (option-ref options 'libdir "lib")) (libdir-mescc (string-append (dirname (option-ref options 'libdir "lib")) "/mescc-lib")) (arch (string-append (arch-get options) "-mes")) (path (append (if (getenv "MES_UNINSTALLED") (list srcdir-mescc-lib srcdir-lib libdir-mescc) '()) (list libdir) (or (and=> (getenv "LIBRARY_PATH") (cut string-split <> #\:)) '()) (filter-map (multi-opt 'library-dir) options))) (arch-file-name (string-append arch "/" file-name)) (arch-file-name (if kernel (string-append kernel "/" arch-file-name) arch-file-name)) (verbose? (count-opt options 'verbose))) (let ((file (search-path path arch-file-name))) (when (and verbose? (> verbose? 1)) (format (current-error-port) "arch-find=~s\n" arch-file-name) (format (current-error-port) " path=~s\n" path) (format (current-error-port) " => ~s\n" file)) (or file (error (format #f "mescc: file not found: ~s" arch-file-name)))))) (define (kernel-find options file-name) (let ((kernel (option-ref options 'kernel "linux"))) (or (arch-find options file-name #:kernel kernel) (arch-find options file-name)))) (define (assert-system* . args) (let ((status (apply system* args))) (when (not (zero? status)) (format (current-error-port) "mescc: failed: ~a\n" (string-join args)) (exit (status:exit-val status))) status)) (define (arch-get options) (let* ((machine (option-ref options 'machine #f)) (arch (option-ref options 'arch #f))) (if machine (cond ((member arch '("x86" "x86_64")) (cond ((equal? machine "32") "x86") ((equal? machine "64") "x86_64"))) ((equal? arch "arm") (cond ((equal? machine "32") "arm") ((equal? machine "arm") "arm")))) arch))) (define (mescc:get-host options) (let ((cpu (arch-get options)) (kernel (option-ref options 'kernel "linux"))) (string-join (list cpu kernel "mes") "-"))) (define (arch-get-info options) (let ((arch (arch-get options))) (cond ((equal? arch "arm") (armv4-info)) ((equal? arch "x86") (x86-info)) ((equal? arch "x86_64") (x86_64-info))))) (define (arch-get-defines options) (let* ((arch (arch-get options)) (info (arch-get-info options)) (types (.types info))) (define (sizeof type) (type:size (assoc-ref types type))) (let ((int (sizeof "int")) (long (sizeof "long")) (long-long (sizeof "long long"))) (cons (cond ((equal? arch "arm") "__arm__=1") ((equal? arch "x86") "__i386__=1") ((equal? arch "x86_64") "__x86_64__=1")) `(,(string-append "__SIZEOF_INT__=" (number->string int)) ,(string-append "__SIZEOF_LONG__=" (number->string long)) C99 : long long must be > = 8 '("__SIZEOF_LONG_LONG__=8"))))))) (define (arch-get-machine options) (let* ((machine (option-ref options 'machine #f)) (arch (option-ref options 'arch #f))) (or machine (if (member arch '("x86_64")) "64" "32")))) (define (arch-get-m1-macros options) (let ((arch (arch-get options))) (cond ((equal? arch "arm") "arm.M1") ((equal? arch "x86") "x86.M1") ((equal? arch "x86_64") "x86_64.M1")))) (define (arch-get-architecture options) (let* ((arch (arch-get options)) (numbered-arch? (option-ref options 'numbered-arch? #f)) (flag (if numbered-arch? "--Architecture" "--architecture"))) (list flag (cond ((equal? arch "arm") (if numbered-arch? "40" "armv7l")) ((equal? arch "x86") (if numbered-arch? "1" "x86")) ((equal? arch "x86_64") (if numbered-arch? "2" "amd64")))))) (define (multi-opt option-name) (lambda (o) (and (eq? (car o) option-name) (cdr o)))) (define (count-opt options option-name) (let ((lst (filter-map (multi-opt option-name) options))) (and (pair? lst) (length lst)))) (define (.c? o) (or (string-suffix? ".c" o) (string-suffix? ".M2" o))) (define (.E? o) (or (string-suffix? ".E" o) (string-suffix? ".mes-E" o) (string-suffix? ".arm-mes-E" o) (string-suffix? ".x86-mes-E" o) (string-suffix? ".x86_64-mes-E" o))) (define (.s? o) (or (string-suffix? ".s" o) (string-suffix? ".S" o) (string-suffix? ".mes-S" o) (string-suffix? ".arm-mes-S" o) (string-suffix? ".x86-mes-S" o) (string-suffix? ".x86_64-mes-S" o) (string-suffix? ".M1" o))) (define (.o? o) (or (string-suffix? ".o" o) (string-suffix? ".mes-o" o) (string-suffix? ".arm-mes-o" o) (string-suffix? ".x86-mes-o" o) (string-suffix? ".x86_64-mes-o" o) (string-suffix? ".hex2" o)))
null
https://raw.githubusercontent.com/oriansj/mes-m2/75a50911d89a84b7aa5ebabab52eb09795c0d61b/module/mescc/mescc.scm
scheme
you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. 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. ugh ugh
GNU --- Maxwell Equations of Software Copyright © 2016,2017,2018,2019,2020 Jan ( janneke ) Nieuwenhuizen < > This file is part of GNU . under the terms of the GNU General Public License as published by GNU is distributed in the hope that it will be useful , but You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (mescc mescc) #:use-module (srfi srfi-1) #:use-module (srfi srfi-26) #:use-module (ice-9 pretty-print) #:use-module (ice-9 getopt-long) #:use-module (mes mes-0) #:use-module (mes misc) #:use-module (mescc info) #:use-module (mescc armv4 info) #:use-module (mescc i386 info) #:use-module (mescc x86_64 info) #:use-module (mescc preprocess) #:use-module (mescc compile) #:use-module (mescc M1) #:export (count-opt mescc:preprocess mescc:get-host mescc:compile mescc:assemble mescc:link multi-opt)) (define GUILE-with-output-to-file with-output-to-file) (define (with-output-to-file file-name thunk) (if (equal? file-name "-") (thunk) (GUILE-with-output-to-file file-name thunk))) (define (mescc:preprocess options) (let* ((pretty-print/write (string->symbol (option-ref options 'write (if guile? "pretty-print" "write")))) (pretty-print/write (if (eq? pretty-print/write 'pretty-print) pretty-print write)) (files (option-ref options '() '("a.c"))) (input-file-name (car files)) (input-base (basename input-file-name)) (ast-file-name (cond ((and (option-ref options 'preprocess #f) (option-ref options 'output #f))) (else (replace-suffix input-base ".E")))) (dir (dirname input-file-name)) (defines (reverse (filter-map (multi-opt 'define) options))) (includes (reverse (filter-map (multi-opt 'include) options))) (includes (cons (option-ref options 'includedir #f) includes)) (includes (cons dir includes)) (prefix (option-ref options 'prefix "")) (machine (option-ref options 'machine "32")) (arch (arch-get options)) (defines (append (arch-get-defines options) defines)) (verbose? (count-opt options 'verbose))) (with-output-to-file ast-file-name (lambda _ (for-each (cut c->ast prefix defines includes arch pretty-print/write verbose? <>) files))))) (define (c->ast prefix defines includes arch write verbose? file-name) (with-input-from-file file-name (cut write (c99-input->ast #:prefix prefix #:defines defines #:includes includes #:arch arch #:verbose? verbose?)))) (define (mescc:compile options) (let* ((files (option-ref options '() '("a.c"))) (input-file-name (car files)) (input-base (basename input-file-name)) (M1-file-name (cond ((and (option-ref options 'compile #f) (option-ref options 'output #f))) ((string-suffix? ".S" input-file-name) input-file-name) (else (replace-suffix input-base ".s")))) (infos (map (cut file->info options <>) files)) (verbose? (count-opt options 'verbose)) (numbered-arch? (option-ref options 'numbered-arch? #f)) (align (filter-map (multi-opt 'align) options)) (align (if (null? align) '(functions) (map string->symbol align))) (align (if (not numbered-arch?) align function alignment not supported by MesCC - Tools 0.5.2 (filter (negate (cut eq? <> 'functions)) align)))) (when verbose? (format (current-error-port) "dumping: ~a\n" M1-file-name)) (with-output-to-file M1-file-name (cut infos->M1 M1-file-name infos #:align align #:verbose? verbose?)) M1-file-name)) (define (file->info options file-name) (cond ((.c? file-name) (c->info options file-name)) ((.E? file-name) (E->info options file-name)))) (define (c->info options file-name) (let* ((dir (dirname file-name)) (defines (reverse (filter-map (multi-opt 'define) options))) (includes (reverse (filter-map (multi-opt 'include) options))) (includes (cons (option-ref options 'includedir #f) includes)) (includes (cons dir includes)) (prefix (option-ref options 'prefix "")) (defines (append (arch-get-defines options) defines)) (arch (arch-get options)) (verbose? (count-opt options 'verbose))) (with-input-from-file file-name (cut c99-input->info (arch-get-info options) #:prefix prefix #:defines defines #:includes includes #:arch arch #:verbose? verbose?)))) (define (E->info options file-name) (let ((ast (with-input-from-file file-name read)) (verbose? (count-opt options 'verbose))) (c99-ast->info (arch-get-info options) ast #:verbose? verbose?))) (define (mescc:assemble options) (let* ((files (option-ref options '() '("a.c"))) (input-file-name (car files)) (input-base (basename input-file-name)) (hex2-file-name (cond ((and (option-ref options 'assemble #f) (option-ref options 'output #f))) (else (replace-suffix input-base ".o")))) (s-files (filter .s? files)) FIXME (source-files (filter (disjoin .c? .E?) files)) (infos (map (cut file->info options <>) source-files))) (if (and (pair? s-files) (pair? infos)) (error "mixing source and object not supported:" source-files s-files)) (when (pair? s-files) (M1->hex2 options s-files)) (when (pair? infos) (infos->hex2 options hex2-file-name infos)) hex2-file-name)) (define (mescc:link options) (let* ((files (option-ref options '() '("a.c"))) (source-files (filter (disjoin .c? .E?) files)) (input-file-name (car files)) (hex2-file-name (if (or (string-suffix? ".hex2" input-file-name) (string-suffix? ".o" input-file-name)) input-file-name (replace-suffix input-file-name ".o"))) (infos (map (cut file->info options <>) source-files)) (s-files (filter .s? files)) (hex2-files (filter .o? files)) (hex2-files (if (null? s-files) hex2-files (append hex2-files (list (M1->hex2 options s-files))))) (hex2-files (if (null? infos) hex2-files (append hex2-files (list (infos->hex2 options hex2-file-name infos))))) (default-libraries (if (or (option-ref options 'nodefaultlibs #f) (option-ref options 'nostdlib #f)) '() '("mescc" "c"))) (libraries (filter-map (multi-opt 'library) options)) (libraries (delete-duplicates (append libraries default-libraries))) (hex2-libraries (map (cut find-library options ".a" <>) libraries)) (hex2-files (append hex2-files hex2-libraries)) (s-files (append s-files (map (cut find-library options ".s" <>) libraries))) (debug-info? (option-ref options 'debug-info #f)) (s-files (if (string-suffix? ".S" input-file-name) s-files (cons (replace-suffix input-file-name ".s") s-files))) (elf-footer (and debug-info? (or (M1->blood-elf options s-files) (exit 1))))) (or (hex2->elf options hex2-files #:elf-footer elf-footer) (exit 1)))) (define (infos->hex2 options hex2-file-name infos) (let* ((input-file-name (car (option-ref options '() '("a.c")))) (M1-file-name (replace-suffix hex2-file-name ".s")) (options (acons 'output hex2-file-name options)) (verbose? (count-opt options 'verbose)) (numbered-arch? (option-ref options 'numbered-arch? #f)) (align (filter-map (multi-opt 'align) options)) (align (if (null? align) '(functions) (map string->symbol align))) (align (if (not numbered-arch?) align function alignment not supported by MesCC - Tools 0.5.2 (filter (negate (cut eq? <> 'functions)) align)))) (when verbose? (format (current-error-port) "dumping: ~a\n" M1-file-name)) (with-output-to-file M1-file-name (cut infos->M1 M1-file-name infos #:align align)) (or (M1->hex2 options (list M1-file-name)) (exit 1)))) (define (M1->hex2 options M1-files) (let* ((input-file-name (car (option-ref options '() '("a.c")))) (input-base (basename input-file-name)) (M1-file-name (car M1-files)) (hex2-file-name (cond ((and (option-ref options 'assemble #f) (option-ref options 'output #f))) ((option-ref options 'assemble #f) (replace-suffix input-base ".o")) (else (replace-suffix M1-file-name ".o")))) (verbose? (count-opt options 'verbose)) (M1 (or (getenv "M1") "M1")) (command `(,M1 "--little-endian" ,@(arch-get-architecture options) "-f" ,(arch-find options (arch-get-m1-macros options)) ,@(append-map (cut list "-f" <>) M1-files) "-o" ,hex2-file-name))) (when (and verbose? (> verbose? 1)) (format (current-error-port) "~a\n" (string-join command))) (and (zero? (apply assert-system* command)) hex2-file-name))) (define* (hex2->elf options hex2-files #:key elf-footer) (let* ((input-file-name (car (option-ref options '() '("a.c")))) (elf-file-name (cond ((option-ref options 'output #f)) (else "a.out"))) (verbose? (count-opt options 'verbose)) (hex2 (or (getenv "HEX2") "hex2")) (base-address (option-ref options 'base-address "0x1000000")) (machine (arch-get-machine options)) (elf-footer (or elf-footer (kernel-find options (string-append "elf" machine "-footer-single-main.hex2")))) (start-files (if (or (option-ref options 'nostartfiles #f) (option-ref options 'nostdlib #f)) '() `("-f" ,(arch-find options "crt1.o")))) (command `(,hex2 "--little-endian" ,@(arch-get-architecture options) "--base-address" ,base-address "-f" ,(kernel-find options (string-append "elf" machine "-header.hex2")) ,@start-files ,@(append-map (cut list "-f" <>) hex2-files) "-f" ,elf-footer "--exec_enable" "-o" ,elf-file-name))) (when (and verbose? (> verbose? 1)) (format (current-error-port) "~a\n" (string-join command))) (and (zero? (apply assert-system* command)) elf-file-name))) (define (M1->blood-elf options M1-files) (let* ((M1-file-name (car M1-files)) (M1-blood-elf-footer (string-append M1-file-name ".blood-elf")) (hex2-file-name (replace-suffix M1-file-name ".o")) (blood-elf-footer (string-append hex2-file-name ".blood-elf")) (verbose? (count-opt options 'verbose)) (blood-elf (or (getenv "BLOOD_ELF") "blood-elf")) (command `(,blood-elf "-f" ,(arch-find options (arch-get-m1-macros options)) ,@(append-map (cut list "-f" <>) M1-files) "-o" ,M1-blood-elf-footer))) (when (and verbose? (> verbose? 1)) (format (current-error-port) "~a\n" (string-join command))) (and (zero? (apply assert-system* command)) (options (acons 'output blood-elf-footer options))) (M1->hex2 options (list M1-blood-elf-footer)))))) (define (replace-suffix file-name suffix) (let* ((parts (string-split file-name #\.)) (base (if (pair? (cdr parts)) (drop-right parts 1) (list file-name))) (old-suffix (if (pair? (cdr parts)) (last parts) "")) (program-prefix (cond ((string-prefix? "arm-mes-" old-suffix) ".arm-mes-") ((string-prefix? "x86-mes-" old-suffix) ".x86-mes-") ((string-prefix? "x86_64-mes-" old-suffix) ".x86_64-mes-") (else ".")))) (if (string-null? suffix) (if (string-null? program-prefix) (string-join base ".") (string-append (string-drop program-prefix 1) (string-join base "."))) (string-append (string-join base ".") program-prefix (string-drop suffix 1))))) (define (find-library options ext o) (arch-find options (string-append "lib" o ext))) (define* (arch-find options file-name #:key kernel) (let* ((srcdest (or (getenv "srcdest") "")) (srcdir-lib (string-append srcdest "lib")) (srcdir-mescc-lib (string-append srcdest "mescc-lib")) (libdir (option-ref options 'libdir "lib")) (libdir-mescc (string-append (dirname (option-ref options 'libdir "lib")) "/mescc-lib")) (arch (string-append (arch-get options) "-mes")) (path (append (if (getenv "MES_UNINSTALLED") (list srcdir-mescc-lib srcdir-lib libdir-mescc) '()) (list libdir) (or (and=> (getenv "LIBRARY_PATH") (cut string-split <> #\:)) '()) (filter-map (multi-opt 'library-dir) options))) (arch-file-name (string-append arch "/" file-name)) (arch-file-name (if kernel (string-append kernel "/" arch-file-name) arch-file-name)) (verbose? (count-opt options 'verbose))) (let ((file (search-path path arch-file-name))) (when (and verbose? (> verbose? 1)) (format (current-error-port) "arch-find=~s\n" arch-file-name) (format (current-error-port) " path=~s\n" path) (format (current-error-port) " => ~s\n" file)) (or file (error (format #f "mescc: file not found: ~s" arch-file-name)))))) (define (kernel-find options file-name) (let ((kernel (option-ref options 'kernel "linux"))) (or (arch-find options file-name #:kernel kernel) (arch-find options file-name)))) (define (assert-system* . args) (let ((status (apply system* args))) (when (not (zero? status)) (format (current-error-port) "mescc: failed: ~a\n" (string-join args)) (exit (status:exit-val status))) status)) (define (arch-get options) (let* ((machine (option-ref options 'machine #f)) (arch (option-ref options 'arch #f))) (if machine (cond ((member arch '("x86" "x86_64")) (cond ((equal? machine "32") "x86") ((equal? machine "64") "x86_64"))) ((equal? arch "arm") (cond ((equal? machine "32") "arm") ((equal? machine "arm") "arm")))) arch))) (define (mescc:get-host options) (let ((cpu (arch-get options)) (kernel (option-ref options 'kernel "linux"))) (string-join (list cpu kernel "mes") "-"))) (define (arch-get-info options) (let ((arch (arch-get options))) (cond ((equal? arch "arm") (armv4-info)) ((equal? arch "x86") (x86-info)) ((equal? arch "x86_64") (x86_64-info))))) (define (arch-get-defines options) (let* ((arch (arch-get options)) (info (arch-get-info options)) (types (.types info))) (define (sizeof type) (type:size (assoc-ref types type))) (let ((int (sizeof "int")) (long (sizeof "long")) (long-long (sizeof "long long"))) (cons (cond ((equal? arch "arm") "__arm__=1") ((equal? arch "x86") "__i386__=1") ((equal? arch "x86_64") "__x86_64__=1")) `(,(string-append "__SIZEOF_INT__=" (number->string int)) ,(string-append "__SIZEOF_LONG__=" (number->string long)) C99 : long long must be > = 8 '("__SIZEOF_LONG_LONG__=8"))))))) (define (arch-get-machine options) (let* ((machine (option-ref options 'machine #f)) (arch (option-ref options 'arch #f))) (or machine (if (member arch '("x86_64")) "64" "32")))) (define (arch-get-m1-macros options) (let ((arch (arch-get options))) (cond ((equal? arch "arm") "arm.M1") ((equal? arch "x86") "x86.M1") ((equal? arch "x86_64") "x86_64.M1")))) (define (arch-get-architecture options) (let* ((arch (arch-get options)) (numbered-arch? (option-ref options 'numbered-arch? #f)) (flag (if numbered-arch? "--Architecture" "--architecture"))) (list flag (cond ((equal? arch "arm") (if numbered-arch? "40" "armv7l")) ((equal? arch "x86") (if numbered-arch? "1" "x86")) ((equal? arch "x86_64") (if numbered-arch? "2" "amd64")))))) (define (multi-opt option-name) (lambda (o) (and (eq? (car o) option-name) (cdr o)))) (define (count-opt options option-name) (let ((lst (filter-map (multi-opt option-name) options))) (and (pair? lst) (length lst)))) (define (.c? o) (or (string-suffix? ".c" o) (string-suffix? ".M2" o))) (define (.E? o) (or (string-suffix? ".E" o) (string-suffix? ".mes-E" o) (string-suffix? ".arm-mes-E" o) (string-suffix? ".x86-mes-E" o) (string-suffix? ".x86_64-mes-E" o))) (define (.s? o) (or (string-suffix? ".s" o) (string-suffix? ".S" o) (string-suffix? ".mes-S" o) (string-suffix? ".arm-mes-S" o) (string-suffix? ".x86-mes-S" o) (string-suffix? ".x86_64-mes-S" o) (string-suffix? ".M1" o))) (define (.o? o) (or (string-suffix? ".o" o) (string-suffix? ".mes-o" o) (string-suffix? ".arm-mes-o" o) (string-suffix? ".x86-mes-o" o) (string-suffix? ".x86_64-mes-o" o) (string-suffix? ".hex2" o)))
b92f2c51ec60245246e594e914acc9915c47452beeb25de589c848eacf930f2e
janestreet/merlin-jst
mtyper.mli
* { 1 Result of typechecker } [ Mtyper ] essentially produces a typedtree , but to make sense of it the OCaml typechecker need to be in a specific state . The [ result ] type wraps a snapshot of this state with the typedtree to ensure correct accesses . [Mtyper] essentially produces a typedtree, but to make sense of it the OCaml typechecker need to be in a specific state. The [result] type wraps a snapshot of this state with the typedtree to ensure correct accesses. *) type result type typedtree = [ | `Interface of Typedtree.signature | `Implementation of Typedtree.structure ] val run : Mconfig.t -> Mreader.parsetree -> result val get_env : ?pos:Msource.position -> result -> Env.t val get_typedtree : result -> typedtree val get_errors : result -> exn list val initial_env : result -> Env.t * Heuristic to find suitable environment to complete / type at given position . * 1 . Try to find environment near given cursor . * 2 . Check if there is an invalid construct between found env and cursor : * Case a. * > let x = valid_expr || * The env found is the right most env from valid_expr , it 's a correct * answer . * Case b. * > let x = valid_expr * > let y = invalid_construction|| * In this case , the env found is the same as in case a , however it is * preferable to use env from enclosing module rather than an env from * inside x definition . * 1. Try to find environment near given cursor. * 2. Check if there is an invalid construct between found env and cursor : * Case a. * > let x = valid_expr || * The env found is the right most env from valid_expr, it's a correct * answer. * Case b. * > let x = valid_expr * > let y = invalid_construction|| * In this case, the env found is the same as in case a, however it is * preferable to use env from enclosing module rather than an env from * inside x definition. *) val node_at : ?skip_recovered:bool -> result -> Lexing.position -> Mbrowse.t
null
https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/src/kernel/mtyper.mli
ocaml
* { 1 Result of typechecker } [ Mtyper ] essentially produces a typedtree , but to make sense of it the OCaml typechecker need to be in a specific state . The [ result ] type wraps a snapshot of this state with the typedtree to ensure correct accesses . [Mtyper] essentially produces a typedtree, but to make sense of it the OCaml typechecker need to be in a specific state. The [result] type wraps a snapshot of this state with the typedtree to ensure correct accesses. *) type result type typedtree = [ | `Interface of Typedtree.signature | `Implementation of Typedtree.structure ] val run : Mconfig.t -> Mreader.parsetree -> result val get_env : ?pos:Msource.position -> result -> Env.t val get_typedtree : result -> typedtree val get_errors : result -> exn list val initial_env : result -> Env.t * Heuristic to find suitable environment to complete / type at given position . * 1 . Try to find environment near given cursor . * 2 . Check if there is an invalid construct between found env and cursor : * Case a. * > let x = valid_expr || * The env found is the right most env from valid_expr , it 's a correct * answer . * Case b. * > let x = valid_expr * > let y = invalid_construction|| * In this case , the env found is the same as in case a , however it is * preferable to use env from enclosing module rather than an env from * inside x definition . * 1. Try to find environment near given cursor. * 2. Check if there is an invalid construct between found env and cursor : * Case a. * > let x = valid_expr || * The env found is the right most env from valid_expr, it's a correct * answer. * Case b. * > let x = valid_expr * > let y = invalid_construction|| * In this case, the env found is the same as in case a, however it is * preferable to use env from enclosing module rather than an env from * inside x definition. *) val node_at : ?skip_recovered:bool -> result -> Lexing.position -> Mbrowse.t
b0fd8ccb9c769d527a6690843228224e70d7ecf62a20802b6329d10b20c0a911
ThoughtWorksInc/stonecutter
common.clj
(ns stonecutter.controller.common (:require [ring.util.response :as response] [stonecutter.routes :as r] [stonecutter.db.token :as token] [stonecutter.session :as session])) (defn sign-in-user ([response token-store user] (sign-in-user response token-store user {})) ([response token-store user existing-session] (-> response (session/replace-session-with existing-session) (session/set-user-login (:login user)) (session/set-user-role (:role user)) (session/set-access-token (token/generate-login-access-token token-store user))))) (defn sign-in-to-index ([token-store user] (sign-in-to-index token-store user {})) ([token-store user existing-session] (-> (response/redirect (r/path :index)) (sign-in-user token-store user existing-session)))) (defn signed-in? [request] (and (session/request->user-login request) (session/request->access-token request)))
null
https://raw.githubusercontent.com/ThoughtWorksInc/stonecutter/37ed22dd276ac652176c4d880e0f1b0c1e27abfe/src/stonecutter/controller/common.clj
clojure
(ns stonecutter.controller.common (:require [ring.util.response :as response] [stonecutter.routes :as r] [stonecutter.db.token :as token] [stonecutter.session :as session])) (defn sign-in-user ([response token-store user] (sign-in-user response token-store user {})) ([response token-store user existing-session] (-> response (session/replace-session-with existing-session) (session/set-user-login (:login user)) (session/set-user-role (:role user)) (session/set-access-token (token/generate-login-access-token token-store user))))) (defn sign-in-to-index ([token-store user] (sign-in-to-index token-store user {})) ([token-store user existing-session] (-> (response/redirect (r/path :index)) (sign-in-user token-store user existing-session)))) (defn signed-in? [request] (and (session/request->user-login request) (session/request->access-token request)))
262deaca62ca3cb156c9a966a167c66eacbb2ad1a0006be8981ea7bb491c9085
b1412/clojure-web-admin
project.clj
(defproject clojure-web "0.1.0-SNAPSHOT" :description "A metadata-driven clojure web admin app" :url "-web-admin" :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.trace "0.7.9"] [org.clojure/core.cache "0.6.4"] [clj-time "0.11.0"] [clojure-humanize "0.1.0"] [inflections "0.10.0"] ;;partern match [defun "0.3.0-alapha"] ;;orm [korma "0.4.0"] [superstring "2.1.0"] ;;exception [slingshot "0.12.2"] ;;log [com.taoensso/timbre "4.1.1"] ;;I18n&L10n [com.taoensso/tower "3.1.0-beta4"] ;;schedual jobs [clojurewerkz/quartzite "2.0.0"] [pandect "0.5.4"] [environ "1.0.1"] [com.infolace/excel-templates "0.3.1"] [dk.ative/docjure "1.9.0"] [ring-webjars "0.1.1"] [cljsjs/react "0.14.0-1"] [cljsjs/react-bootstrap "0.25.1-0"] [org.webjars/bootstrap "3.3.5"] [org.webjars/jquery "2.1.4"] [org.webjars.bower/bootstrap-treeview "1.2.0"] [org.webjars.bower/bootstrap-table "1.9.1"] [org.webjars.bower/bootstrap-fileinput "4.2.7"] [org.webjars.npm/react "0.14.2"] [org.webjars.bower/eonasdan-bootstrap-datetimepicker "4.17.37"] [org.webjars.bower/bootstrap3-dialog "1.34.4"] [ring/ring-defaults "0.1.5"] [ring "1.4.0"] [metosin/ring-middleware-format "0.6.0"] [metosin/ring-http-response "0.6.5"] [bouncer "0.3.3"] [prone "0.8.2"] [org.clojure/tools.nrepl "0.2.11"] [org.clojure/clojurescript "1.7.145" :scope "provided"] [shodan "0.4.2"] [org.clojure/tools.reader "0.9.2"] [reagent "0.5.1"] [re-frame "0.4.1"] [re-com "0.7.0"] [reagent-forms "0.5.13"] [garden "1.3.0"] [secretary "1.2.3"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] [metosin/compojure-api "0.24.0"] [metosin/ring-swagger-ui "2.1.2"] [org.clojure/data.json "0.2.6"] [hiccup "1.0.5"] [cljs-http "0.1.37"] [hiccup-bridge "1.0.1"] [crypto-password "0.1.3"] [com.alibaba/druid "1.0.16"] [mysql/mysql-connector-java "5.1.6"]] :source-paths ["src/clj" "src/cljc"] :min-lein-version "2.0.0" :uberjar-name "clojure-web.jar" :jvm-opts ["-server" "-Duser.timezone=UTC" "-XX:-OmitStackTraceInFastThrow"] :main clojure-web.core :plugins [[lein-environ "1.0.1"] [hiccup-bridge "1.0.1"] [lein-garden "0.2.6"] [lein-cljsbuild "1.1.0"] [com.palletops/uberimage "0.4.1"]] :cljfmt {} :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :cljsbuild {:builds {:app {:source-paths ["src/cljs" "src/cljc"] :compiler {:output-to "resources/public/js/app.js" :externs ["react/externs/react.js"] :pretty-print true}}}} :global-vars {*warn-on-reflection* false} :profiles {:uberjar {:omit-source true :env {:production true} :hooks [leiningen.cljsbuild] :cljsbuild {:jar true :builds {:app {:source-paths ["env/prod/cljs"] :compiler {:optimizations :advanced :pretty-print false}}}} :aot :all} :dev [:project/dev :profiles/dev] :test [:project/test :profiles/test] :project/dev {:dependencies [[ring/ring-mock "0.3.0"] [ring/ring-devel "1.4.0"] [pjstadig/humane-test-output "0.7.0"] [midje "1.6.3"] [figwheel "0.2.5"] [figwheel-sidecar "0.2.5"] [com.cemerick/piggieback "0.1.5"] [weasel "0.6.0"]] :repl-options {:init-ns clojure-web.core :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :plugins [[lein-figwheel "0.4.1"]] :cljsbuild {:builds {:app {:source-paths ["env/dev/cljs"] :compiler {:source-map true}}}} :garden {:builds [{:id "screen" :source-paths ["src/clj"] :stylesheet clojure-web.css/customize :compiler {:output-to "resources/public/assets/css/customize.css.new" :pretty-print? true}}]} :figwheel {:http-server-root "public" :server-port 3449 :nrepl-port 7002 :css-dirs ["resources/public/css"] :ring-handler clojure-web.handler/app} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)] :env {:dev true :port 3000 :nrepl-port 7000}} :project/test {:env {:test true :port 3001 :nrepl-port 7001}}})
null
https://raw.githubusercontent.com/b1412/clojure-web-admin/018161dcdb364cc168d6f5a56ceb798005a0701f/project.clj
clojure
partern match orm exception log I18n&L10n schedual jobs
(defproject clojure-web "0.1.0-SNAPSHOT" :description "A metadata-driven clojure web admin app" :url "-web-admin" :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.trace "0.7.9"] [org.clojure/core.cache "0.6.4"] [clj-time "0.11.0"] [clojure-humanize "0.1.0"] [inflections "0.10.0"] [defun "0.3.0-alapha"] [korma "0.4.0"] [superstring "2.1.0"] [slingshot "0.12.2"] [com.taoensso/timbre "4.1.1"] [com.taoensso/tower "3.1.0-beta4"] [clojurewerkz/quartzite "2.0.0"] [pandect "0.5.4"] [environ "1.0.1"] [com.infolace/excel-templates "0.3.1"] [dk.ative/docjure "1.9.0"] [ring-webjars "0.1.1"] [cljsjs/react "0.14.0-1"] [cljsjs/react-bootstrap "0.25.1-0"] [org.webjars/bootstrap "3.3.5"] [org.webjars/jquery "2.1.4"] [org.webjars.bower/bootstrap-treeview "1.2.0"] [org.webjars.bower/bootstrap-table "1.9.1"] [org.webjars.bower/bootstrap-fileinput "4.2.7"] [org.webjars.npm/react "0.14.2"] [org.webjars.bower/eonasdan-bootstrap-datetimepicker "4.17.37"] [org.webjars.bower/bootstrap3-dialog "1.34.4"] [ring/ring-defaults "0.1.5"] [ring "1.4.0"] [metosin/ring-middleware-format "0.6.0"] [metosin/ring-http-response "0.6.5"] [bouncer "0.3.3"] [prone "0.8.2"] [org.clojure/tools.nrepl "0.2.11"] [org.clojure/clojurescript "1.7.145" :scope "provided"] [shodan "0.4.2"] [org.clojure/tools.reader "0.9.2"] [reagent "0.5.1"] [re-frame "0.4.1"] [re-com "0.7.0"] [reagent-forms "0.5.13"] [garden "1.3.0"] [secretary "1.2.3"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] [metosin/compojure-api "0.24.0"] [metosin/ring-swagger-ui "2.1.2"] [org.clojure/data.json "0.2.6"] [hiccup "1.0.5"] [cljs-http "0.1.37"] [hiccup-bridge "1.0.1"] [crypto-password "0.1.3"] [com.alibaba/druid "1.0.16"] [mysql/mysql-connector-java "5.1.6"]] :source-paths ["src/clj" "src/cljc"] :min-lein-version "2.0.0" :uberjar-name "clojure-web.jar" :jvm-opts ["-server" "-Duser.timezone=UTC" "-XX:-OmitStackTraceInFastThrow"] :main clojure-web.core :plugins [[lein-environ "1.0.1"] [hiccup-bridge "1.0.1"] [lein-garden "0.2.6"] [lein-cljsbuild "1.1.0"] [com.palletops/uberimage "0.4.1"]] :cljfmt {} :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :cljsbuild {:builds {:app {:source-paths ["src/cljs" "src/cljc"] :compiler {:output-to "resources/public/js/app.js" :externs ["react/externs/react.js"] :pretty-print true}}}} :global-vars {*warn-on-reflection* false} :profiles {:uberjar {:omit-source true :env {:production true} :hooks [leiningen.cljsbuild] :cljsbuild {:jar true :builds {:app {:source-paths ["env/prod/cljs"] :compiler {:optimizations :advanced :pretty-print false}}}} :aot :all} :dev [:project/dev :profiles/dev] :test [:project/test :profiles/test] :project/dev {:dependencies [[ring/ring-mock "0.3.0"] [ring/ring-devel "1.4.0"] [pjstadig/humane-test-output "0.7.0"] [midje "1.6.3"] [figwheel "0.2.5"] [figwheel-sidecar "0.2.5"] [com.cemerick/piggieback "0.1.5"] [weasel "0.6.0"]] :repl-options {:init-ns clojure-web.core :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :plugins [[lein-figwheel "0.4.1"]] :cljsbuild {:builds {:app {:source-paths ["env/dev/cljs"] :compiler {:source-map true}}}} :garden {:builds [{:id "screen" :source-paths ["src/clj"] :stylesheet clojure-web.css/customize :compiler {:output-to "resources/public/assets/css/customize.css.new" :pretty-print? true}}]} :figwheel {:http-server-root "public" :server-port 3449 :nrepl-port 7002 :css-dirs ["resources/public/css"] :ring-handler clojure-web.handler/app} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)] :env {:dev true :port 3000 :nrepl-port 7000}} :project/test {:env {:test true :port 3001 :nrepl-port 7001}}})
002d67696d5b28d148d663cf923c0cc412a75e9519c197a9a876627114707d5b
int28h/HaskellTasks
0031.hs
Используя функцию foldr , напишите реализацию функции lengthList , вычисляющей количество элементов в списке . GHCi > lengthList [ 7,6,5 ] 3 Используя функцию foldr, напишите реализацию функции lengthList, вычисляющей количество элементов в списке. GHCi> lengthList [7,6,5] 3 -} lengthList :: [a] -> Int lengthList = foldr (\x s -> 1 + s) 0
null
https://raw.githubusercontent.com/int28h/HaskellTasks/38aa6c1d461ca5774350c68fa7dd631932f10f84/src/0031.hs
haskell
Используя функцию foldr , напишите реализацию функции lengthList , вычисляющей количество элементов в списке . GHCi > lengthList [ 7,6,5 ] 3 Используя функцию foldr, напишите реализацию функции lengthList, вычисляющей количество элементов в списке. GHCi> lengthList [7,6,5] 3 -} lengthList :: [a] -> Int lengthList = foldr (\x s -> 1 + s) 0
24a8eb1cf337e9ea629b0b9d6d119d67062484dc0243fc9956e2f08bd1595856
avsm/platform
zed_utf8.ml
* zed_utf8.ml * ----------- * Copyright : ( c ) 2011 , < > * Licence : BSD3 * * This file is a part of , an editor engine . * zed_utf8.ml * ----------- * Copyright : (c) 2011, Jeremie Dimino <> * Licence : BSD3 * * This file is a part of Zed, an editor engine. *) open CamomileLibraryDefault.Camomile type t = string exception Invalid of string * string exception Out_of_bounds let fail str pos msg = raise (Invalid(Printf.sprintf "at position %d: %s" pos msg, str)) let byte str i = Char.code (String.unsafe_get str i) let set_byte str i n = Bytes.unsafe_set str i (Char.unsafe_chr n) (* +-----------------------------------------------------------------+ | Validation | +-----------------------------------------------------------------+ *) type check_result = | Correct of int | Message of string let next_error s i = let len = String.length s in let rec main i ulen = if i = len then (i, ulen, "") else let ch = String.unsafe_get s i in match ch with | '\x00' .. '\x7f' -> main (i + 1) (ulen + 1) | '\xc0' .. '\xdf' -> if i + 1 >= len then (i, ulen, "premature end of UTF8 sequence") else begin let byte1 = Char.code (String.unsafe_get s (i + 1)) in if byte1 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if ((Char.code ch land 0x1f) lsl 6) lor (byte1 land 0x3f) < 0x80 then (i, ulen, "overlong UTF8 sequence") else main (i + 2) (ulen + 1) end | '\xe0' .. '\xef' -> if i + 2 >= len then (i, ulen, "premature end of UTF8 sequence") else begin let byte1 = Char.code (String.unsafe_get s (i + 1)) and byte2 = Char.code (String.unsafe_get s (i + 2)) in if byte1 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if byte2 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if ((Char.code ch land 0x0f) lsl 12) lor ((byte1 land 0x3f) lsl 6) lor (byte2 land 0x3f) < 0x800 then (i, ulen, "overlong UTF8 sequence") else main (i + 3) (ulen + 1) end | '\xf0' .. '\xf7' -> if i + 3 >= len then (i, ulen, "premature end of UTF8 sequence") else begin let byte1 = Char.code (String.unsafe_get s (i + 1)) and byte2 = Char.code (String.unsafe_get s (i + 2)) and byte3 = Char.code (String.unsafe_get s (i + 3)) in if byte1 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if byte2 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if byte3 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if ((Char.code ch land 0x07) lsl 18) lor ((byte1 land 0x3f) lsl 12) lor ((byte2 land 0x3f) lsl 6) lor (byte3 land 0x3f) < 0x10000 then (i, ulen, "overlong UTF8 sequence") else main (i + 4) (ulen + 1) end | _ -> (i, ulen, "invalid start of UTF8 sequence") in main i 0 let check str = let ofs, len, msg = next_error str 0 in if ofs = String.length str then Correct len else Message (Printf.sprintf "at position %d: %s" ofs msg) let validate str = let ofs, len, msg = next_error str 0 in if ofs = String.length str then len else fail str ofs msg (* +-----------------------------------------------------------------+ | Unsafe UTF-8 manipulation | +-----------------------------------------------------------------+ *) let unsafe_next str ofs = match String.unsafe_get str ofs with | '\x00' .. '\x7f' -> ofs + 1 | '\xc0' .. '\xdf' -> if ofs + 2 > String.length str then fail str ofs "unterminated UTF-8 sequence" else ofs + 2 | '\xe0' .. '\xef' -> if ofs + 3 > String.length str then fail str ofs "unterminated UTF-8 sequence" else ofs + 3 | '\xf0' .. '\xf7' -> if ofs + 4 > String.length str then fail str ofs "unterminated UTF-8 sequence" else ofs + 4 | _ -> fail str ofs "invalid start of UTF-8 sequence" let unsafe_prev str ofs = match String.unsafe_get str (ofs - 1) with | '\x00' .. '\x7f' -> ofs - 1 | '\x80' .. '\xbf' -> if ofs >= 2 then match String.unsafe_get str (ofs - 2) with | '\xc0' .. '\xdf' -> ofs - 2 | '\x80' .. '\xbf' -> if ofs >= 3 then match String.unsafe_get str (ofs - 3) with | '\xe0' .. '\xef' -> ofs - 3 | '\x80' .. '\xbf' -> if ofs >= 4 then match String.unsafe_get str (ofs - 4) with | '\xf0' .. '\xf7' -> ofs - 4 | _ -> fail str (ofs - 4) "invalid start of UTF-8 sequence" else fail str (ofs - 3) "invalid start of UTF-8 string" | _ -> fail str (ofs - 3) "invalid middle of UTF-8 sequence" else fail str (ofs - 2) "invaild start of UTF-8 string" | _ -> fail str (ofs - 2) "invalid middle of UTF-8 sequence" else fail str (ofs - 1) "invalid start of UTF-8 string" | _ -> fail str (ofs - 1) "invalid end of UTF-8 sequence" let unsafe_extract str ofs = let ch = String.unsafe_get str ofs in match ch with | '\x00' .. '\x7f' -> UChar.of_char ch | '\xc0' .. '\xdf' -> if ofs + 2 > String.length str then fail str ofs "unterminated UTF-8 sequence" else UChar.of_int (((Char.code ch land 0x1f) lsl 6) lor (byte str (ofs + 1) land 0x3f)) | '\xe0' .. '\xef' -> if ofs + 3 > String.length str then fail str ofs "unterminated UTF-8 sequence" else UChar.of_int (((Char.code ch land 0x0f) lsl 12) lor ((byte str (ofs + 1) land 0x3f) lsl 6) lor (byte str (ofs + 2) land 0x3f)) | '\xf0' .. '\xf7' -> if ofs + 4 > String.length str then fail str ofs "unterminated UTF-8 sequence" else UChar.of_int (((Char.code ch land 0x07) lsl 18) lor ((byte str (ofs + 1) land 0x3f) lsl 12) lor ((byte str (ofs + 2) land 0x3f) lsl 6) lor (byte str (ofs + 3) land 0x3f)) | _ -> fail str ofs "invalid start of UTF-8 sequence" let unsafe_extract_next str ofs = let ch = String.unsafe_get str ofs in match ch with | '\x00' .. '\x7f' -> (UChar.of_char ch, ofs + 1) | '\xc0' .. '\xdf' -> if ofs + 2 > String.length str then fail str ofs "unterminated UTF-8 sequence" else (UChar.of_int (((Char.code ch land 0x1f) lsl 6) lor (byte str (ofs + 1) land 0x3f)), ofs + 2) | '\xe0' .. '\xef' -> if ofs + 3 > String.length str then fail str ofs "unterminated UTF-8 sequence" else (UChar.of_int (((Char.code ch land 0x0f) lsl 12) lor ((byte str (ofs + 1) land 0x3f) lsl 6) lor (byte str (ofs + 2) land 0x3f)), ofs + 3) | '\xf0' .. '\xf7' -> if ofs + 4 > String.length str then fail str ofs "unterminated UTF-8 sequence" else (UChar.of_int (((Char.code ch land 0x07) lsl 18) lor ((byte str (ofs + 1) land 0x3f) lsl 12) lor ((byte str (ofs + 2) land 0x3f) lsl 6) lor (byte str (ofs + 3) land 0x3f)), ofs + 4) | _ -> fail str ofs "invalid start of UTF-8 sequence" let unsafe_extract_prev str ofs = let ch1 = String.unsafe_get str (ofs - 1) in match ch1 with | '\x00' .. '\x7f' -> (UChar.of_char ch1, ofs - 1) | '\x80' .. '\xbf' -> if ofs >= 2 then let ch2 = String.unsafe_get str (ofs - 2) in match ch2 with | '\xc0' .. '\xdf' -> (UChar.of_int (((Char.code ch2 land 0x1f) lsl 6) lor (Char.code ch1 land 0x3f)), ofs - 2) | '\x80' .. '\xbf' -> if ofs >= 3 then let ch3 = String.unsafe_get str (ofs - 3) in match ch3 with | '\xe0' .. '\xef' -> (UChar.of_int (((Char.code ch3 land 0x0f) lsl 12) lor ((Char.code ch2 land 0x3f) lsl 6) lor (Char.code ch1 land 0x3f)), ofs - 3) | '\x80' .. '\xbf' -> if ofs >= 4 then let ch4 = String.unsafe_get str (ofs - 4) in match ch4 with | '\xf0' .. '\xf7' -> (UChar.of_int (((Char.code ch4 land 0x07) lsl 18) lor ((Char.code ch3 land 0x3f) lsl 12) lor ((Char.code ch2 land 0x3f) lsl 6) lor (Char.code ch1 land 0x3f)), ofs - 4) | _ -> fail str (ofs - 4) "invalid start of UTF-8 sequence" else fail str (ofs - 3) "invalid start of UTF-8 string" | _ -> fail str (ofs - 3) "invalid middle of UTF-8 sequence" else fail str (ofs - 2) "invaild start of UTF-8 string" | _ -> fail str (ofs - 2) "invalid middle of UTF-8 sequence" else fail str (ofs - 1) "invalid start of UTF-8 string" | _ -> fail str (ofs - 1) "invalid end of UTF-8 sequence" let rec move_l str ofs len = if len = 0 then ofs else if ofs = String.length str then raise Out_of_bounds else move_l str (unsafe_next str ofs) (len - 1) let unsafe_sub str ofs len = let res = Bytes.create len in String.unsafe_blit str ofs res 0 len; Bytes.unsafe_to_string res (* +-----------------------------------------------------------------+ | Construction | +-----------------------------------------------------------------+ *) let singleton char = let code = UChar.code char in Bytes.unsafe_to_string @@ if code < 0x80 then begin let s = Bytes.create 1 in set_byte s 0 code; s end else if code <= 0x800 then begin let s = Bytes.create 2 in set_byte s 0 ((code lsr 6) lor 0xc0); set_byte s 1 ((code land 0x3f) lor 0x80); s end else if code <= 0x10000 then begin let s = Bytes.create 3 in set_byte s 0 ((code lsr 12) lor 0xe0); set_byte s 1 (((code lsr 6) land 0x3f) lor 0x80); set_byte s 2 ((code land 0x3f) lor 0x80); s end else if code <= 0x10ffff then begin let s = Bytes.create 4 in set_byte s 0 ((code lsr 18) lor 0xf0); set_byte s 1 (((code lsr 12) land 0x3f) lor 0x80); set_byte s 2 (((code lsr 6) land 0x3f) lor 0x80); set_byte s 3 ((code land 0x3f) lor 0x80); s end else (* Camomile allow characters with code-point greater than 0x10ffff *) invalid_arg "Zed_utf8.singleton" let make n code = let str = singleton code in let len = String.length str in let res = Bytes.create (n * len) in let ofs = ref 0 in for _ = 1 to n do String.unsafe_blit str 0 res !ofs len; ofs := !ofs + len done; Bytes.unsafe_to_string res let init n f = let buf = Buffer.create n in for i = 0 to n - 1 do Buffer.add_string buf (singleton (f i)) done; Buffer.contents buf let rev_init n f = let buf = Buffer.create n in for i = n - 1 downto 0 do Buffer.add_string buf (singleton (f i)) done; Buffer.contents buf (* +-----------------------------------------------------------------+ | Informations | +-----------------------------------------------------------------+ *) let rec length_rec str ofs len = if ofs = String.length str then len else length_rec str (unsafe_next str ofs) (len + 1) let length str = length_rec str 0 0 (* +-----------------------------------------------------------------+ | Comparison | +-----------------------------------------------------------------+ *) let rec compare_rec str1 ofs1 str2 ofs2 = if ofs1 = String.length str1 then if ofs2 = String.length str2 then 0 else -1 else if ofs2 = String.length str2 then 1 else let code1, ofs1 = unsafe_extract_next str1 ofs1 and code2, ofs2 = unsafe_extract_next str2 ofs2 in let d = UChar.code code1 - UChar.code code2 in if d <> 0 then d else compare_rec str1 ofs1 str2 ofs2 let compare str1 str2 = compare_rec str1 0 str2 0 (* +-----------------------------------------------------------------+ | Random access | +-----------------------------------------------------------------+ *) let get str idx = if idx < 0 then raise Out_of_bounds else unsafe_extract str (move_l str 0 idx) (* +-----------------------------------------------------------------+ | Manipulation | +-----------------------------------------------------------------+ *) let sub str idx len = if idx < 0 || len < 0 then raise Out_of_bounds else let ofs1 = move_l str 0 idx in let ofs2 = move_l str ofs1 len in unsafe_sub str ofs1 (ofs2 - ofs1) let break str idx = if idx < 0 then raise Out_of_bounds else let ofs = move_l str 0 idx in (unsafe_sub str 0 ofs, unsafe_sub str ofs (String.length str - ofs)) let before str idx = if idx < 0 then raise Out_of_bounds else let ofs = move_l str 0 idx in unsafe_sub str 0 ofs let after str idx = if idx < 0 then raise Out_of_bounds else let ofs = move_l str 0 idx in unsafe_sub str ofs (String.length str - ofs) let concat3 a b c = let lena = String.length a and lenb = String.length b and lenc = String.length c in let res = Bytes.create (lena + lenb + lenc) in String.unsafe_blit a 0 res 0 lena; String.unsafe_blit b 0 res lena lenb; String.unsafe_blit c 0 res (lena + lenb) lenc; Bytes.unsafe_to_string res let insert str idx sub = let a, b = break str idx in concat3 a sub b let remove str idx len = if idx < 0 || len < 0 then raise Out_of_bounds else let ofs1 = move_l str 0 idx in let ofs2 = move_l str ofs1 len in unsafe_sub str 0 ofs1 ^ unsafe_sub str ofs2 (String.length str - ofs2) let replace str idx len repl = if idx < 0 || len < 0 then raise Out_of_bounds else let ofs1 = move_l str 0 idx in let ofs2 = move_l str ofs1 len in concat3 (unsafe_sub str 0 ofs1) repl (unsafe_sub str ofs2 (String.length str - ofs2)) (* +-----------------------------------------------------------------+ | Exploding and imploding | +-----------------------------------------------------------------+ *) let rec rev_rec (res : Bytes.t) str ofs_src ofs_dst = if ofs_src = String.length str then Bytes.unsafe_to_string res else begin let ofs_src' = unsafe_next str ofs_src in let len = ofs_src' - ofs_src in let ofs_dst = ofs_dst - len in String.unsafe_blit str ofs_src res ofs_dst len; rev_rec res str ofs_src' ofs_dst end let rev str = let len = String.length str in rev_rec (Bytes.create len) str 0 len let concat sep l = match l with | [] -> "" | x :: l -> let sep_len = String.length sep in let len = List.fold_left (fun len str -> len + sep_len + String.length str) (String.length x) l in let res = Bytes.create len in String.unsafe_blit x 0 res 0 (String.length x); ignore (List.fold_left (fun ofs str -> String.unsafe_blit sep 0 res ofs sep_len; let ofs = ofs + sep_len in let len = String.length str in String.unsafe_blit str 0 res ofs len; ofs + len) (String.length x) l); Bytes.unsafe_to_string res let rev_concat sep l = match l with | [] -> "" | x :: l -> let sep_len = String.length sep in let len = List.fold_left (fun len str -> len + sep_len + String.length str) (String.length x) l in let res = Bytes.create len in let ofs = len - String.length x in String.unsafe_blit x 0 res ofs (String.length x); ignore (List.fold_left (fun ofs str -> let ofs = ofs - sep_len in String.unsafe_blit sep 0 res ofs sep_len; let len = String.length str in let ofs = ofs - len in String.unsafe_blit str 0 res ofs len; ofs) ofs l); Bytes.unsafe_to_string res let rec explode_rec str ofs acc = if ofs = 0 then acc else let x, ofs = unsafe_extract_prev str ofs in explode_rec str ofs (x :: acc) let explode str = explode_rec str (String.length str) [] let rec rev_explode_rec str ofs acc = if ofs = String.length str then acc else let x, ofs = unsafe_extract_next str ofs in rev_explode_rec str ofs (x :: acc) let rev_explode str = rev_explode_rec str 0 [] let implode l = let l = List.map singleton l in let len = List.fold_left (fun len str -> len + String.length str) 0 l in let res = Bytes.create len in ignore (List.fold_left (fun ofs str -> let len = String.length str in String.unsafe_blit str 0 res ofs len; ofs + len) 0 l); Bytes.unsafe_to_string res let rev_implode l = let l = List.map singleton l in let len = List.fold_left (fun len str -> len + String.length str) 0 l in let res = Bytes.create len in ignore (List.fold_left (fun ofs str -> let len = String.length str in let ofs = ofs - len in String.unsafe_blit str 0 res ofs len; ofs) len l); Bytes.unsafe_to_string res (* +-----------------------------------------------------------------+ | Text transversal | +-----------------------------------------------------------------+ *) let rec iter_rec f str ofs = if ofs = String.length str then () else begin let chr, ofs = unsafe_extract_next str ofs in f chr; iter_rec f str ofs end let iter f str = iter_rec f str 0 let rec rev_iter_rec f str ofs = if ofs = 0 then () else begin let chr, ofs = unsafe_extract_prev str ofs in f chr; rev_iter_rec f str ofs end let rev_iter f str = rev_iter_rec f str (String.length str) let rec fold_rec f str ofs acc = if ofs = String.length str then acc else begin let chr, ofs = unsafe_extract_next str ofs in fold_rec f str ofs (f chr acc) end let fold f str acc = fold_rec f str 0 acc let rec rev_fold_rec f str ofs acc = if ofs = 0 then acc else begin let chr, ofs = unsafe_extract_prev str ofs in rev_fold_rec f str ofs (f chr acc) end let rev_fold f str acc = rev_fold_rec f str (String.length str) acc let rec map_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in Buffer.add_string buf (singleton (f chr)); map_rec buf f str ofs end let map f str = map_rec (Buffer.create (String.length str)) f str 0 let rec map_concat_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in Buffer.add_string buf (f chr); map_concat_rec buf f str ofs end let map_concat f str = map_concat_rec (Buffer.create (String.length str)) f str 0 let rec rev_map_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in Buffer.add_string buf (singleton (f chr)); rev_map_rec buf f str ofs end let rev_map f str = rev_map_rec (Buffer.create (String.length str)) f str (String.length str) let rec rev_map_concat_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in Buffer.add_string buf (f chr); rev_map_concat_rec buf f str ofs end let rev_map_concat f str = rev_map_concat_rec (Buffer.create (String.length str)) f str (String.length str) let rec filter_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in if f chr then Buffer.add_string buf (singleton chr); filter_rec buf f str ofs end let filter f str = filter_rec (Buffer.create (String.length str)) f str 0 let rec rev_filter_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in if f chr then Buffer.add_string buf (singleton chr); rev_filter_rec buf f str ofs end let rev_filter f str = rev_filter_rec (Buffer.create (String.length str)) f str (String.length str) let rec filter_map_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in (match f chr with | Some chr -> Buffer.add_string buf (singleton chr) | None -> ()); filter_map_rec buf f str ofs end let filter_map f str = filter_map_rec (Buffer.create (String.length str)) f str 0 let rec filter_map_concat_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in (match f chr with | Some txt -> Buffer.add_string buf txt | None -> ()); filter_map_concat_rec buf f str ofs end let filter_map_concat f str = filter_map_concat_rec (Buffer.create (String.length str)) f str 0 let rec rev_filter_map_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in (match f chr with | Some chr -> Buffer.add_string buf (singleton chr) | None -> ()); rev_filter_map_rec buf f str ofs end let rev_filter_map f str = rev_filter_map_rec (Buffer.create (String.length str)) f str (String.length str) let rec rev_filter_map_concat_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in (match f chr with | Some txt -> Buffer.add_string buf txt | None -> ()); rev_filter_map_concat_rec buf f str ofs end let rev_filter_map_concat f str = rev_filter_map_concat_rec (Buffer.create (String.length str)) f str (String.length str) (* +-----------------------------------------------------------------+ | Scanning | +-----------------------------------------------------------------+ *) let rec for_all_rec f str ofs = if ofs = String.length str then true else let chr, ofs = unsafe_extract_next str ofs in f chr && for_all_rec f str ofs let for_all f str = for_all_rec f str 0 let rec exists_rec f str ofs = if ofs = String.length str then false else let chr, ofs = unsafe_extract_next str ofs in f chr || exists_rec f str ofs let exists f str = exists_rec f str 0 let rec count_rec f str ofs n = if ofs = String.length str then n else let chr, ofs = unsafe_extract_next str ofs in count_rec f str ofs (if f chr then n + 1 else n) let count f str = count_rec f str 0 0 (* +-----------------------------------------------------------------+ | Tests | +-----------------------------------------------------------------+ *) let rec unsafe_sub_equal str ofs sub ofs_sub = if ofs_sub = String.length sub then true else (String.unsafe_get str ofs = String.unsafe_get sub ofs_sub) && unsafe_sub_equal str (ofs + 1) sub (ofs_sub + 1) let rec contains_rec str sub ofs = if ofs + String.length sub > String.length str then false else unsafe_sub_equal str ofs sub 0 || contains_rec str sub (unsafe_next str ofs) let contains str sub = contains_rec str sub 0 let starts_with str prefix = if String.length prefix > String.length str then false else unsafe_sub_equal str 0 prefix 0 let ends_with str suffix = let ofs = String.length str - String.length suffix in if ofs < 0 then false else unsafe_sub_equal str ofs suffix 0 (* +-----------------------------------------------------------------+ | Stripping | +-----------------------------------------------------------------+ *) let rec lfind predicate str ofs = if ofs = String.length str then ofs else let chr, ofs' = unsafe_extract_next str ofs in if predicate chr then lfind predicate str ofs' else ofs let rec rfind predicate str ofs = if ofs = 0 then 0 else let chr, ofs' = unsafe_extract_prev str ofs in if predicate chr then rfind predicate str ofs' else ofs let spaces = UCharInfo.load_property_tbl `White_Space let is_space ch = UCharTbl.Bool.get spaces ch let strip ?(predicate=is_space) str = let lofs = lfind predicate str 0 and rofs = rfind predicate str (String.length str) in if lofs < rofs then unsafe_sub str lofs (rofs - lofs) else "" let lstrip ?(predicate=is_space) str = let lofs = lfind predicate str 0 in unsafe_sub str lofs (String.length str - lofs) let rstrip ?(predicate=is_space) str = let rofs = rfind predicate str (String.length str) in unsafe_sub str 0 rofs let lchop = function | "" -> "" | str -> let ofs = unsafe_next str 0 in unsafe_sub str ofs (String.length str - ofs) let rchop = function | "" -> "" | str -> let ofs = unsafe_prev str (String.length str) in unsafe_sub str 0 ofs (* +-----------------------------------------------------------------+ | Buffers | +-----------------------------------------------------------------+ *) let add buf char = let code = UChar.code char in if code < 0x80 then Buffer.add_char buf (Char.unsafe_chr code) else if code <= 0x800 then begin Buffer.add_char buf (Char.unsafe_chr ((code lsr 6) lor 0xc0)); Buffer.add_char buf (Char.unsafe_chr ((code land 0x3f) lor 0x80)) end else if code <= 0x10000 then begin Buffer.add_char buf (Char.unsafe_chr ((code lsr 12) lor 0xe0)); Buffer.add_char buf (Char.unsafe_chr (((code lsr 6) land 0x3f) lor 0x80)); Buffer.add_char buf (Char.unsafe_chr ((code land 0x3f) lor 0x80)) end else if code <= 0x10ffff then begin Buffer.add_char buf (Char.unsafe_chr ((code lsr 18) lor 0xf0)); Buffer.add_char buf (Char.unsafe_chr (((code lsr 12) land 0x3f) lor 0x80)); Buffer.add_char buf (Char.unsafe_chr (((code lsr 6) land 0x3f) lor 0x80)); Buffer.add_char buf (Char.unsafe_chr ((code land 0x3f) lor 0x80)) end else invalid_arg "Zed_utf8.add" (* +-----------------------------------------------------------------+ | Offset API | +-----------------------------------------------------------------+ *) let extract str ofs = if ofs < 0 || ofs >= String.length str then raise Out_of_bounds else unsafe_extract str ofs let next str ofs = if ofs < 0 || ofs >= String.length str then raise Out_of_bounds else unsafe_next str ofs let extract_next str ofs = if ofs < 0 || ofs >= String.length str then raise Out_of_bounds else unsafe_extract_next str ofs let prev str ofs = if ofs <= 0 || ofs > String.length str then raise Out_of_bounds else unsafe_prev str ofs let extract_prev str ofs = if ofs <= 0 || ofs > String.length str then raise Out_of_bounds else unsafe_extract_prev str ofs (* +-----------------------------------------------------------------+ | Escaping | +-----------------------------------------------------------------+ *) let alphabetic = UCharInfo.load_property_tbl `Alphabetic let escaped_char ch = match UChar.code ch with | 7 -> "\\a" | 8 -> "\\b" | 9 -> "\\t" | 10 -> "\\n" | 11 -> "\\v" | 12 -> "\\f" | 13 -> "\\r" | 27 -> "\\e" | 92 -> "\\\\" | code when code >= 32 && code <= 126 -> String.make 1 (Char.chr code) | _ when UCharTbl.Bool.get alphabetic ch -> singleton ch | code when code <= 127 -> Printf.sprintf "\\x%02x" code | code when code <= 0xffff -> Printf.sprintf "\\u%04x" code | code -> Printf.sprintf "\\U%06x" code let add_escaped_char buf ch = match UChar.code ch with | 7 -> Buffer.add_string buf "\\a" | 8 -> Buffer.add_string buf "\\b" | 9 -> Buffer.add_string buf "\\t" | 10 -> Buffer.add_string buf "\\n" | 11 -> Buffer.add_string buf "\\v" | 12 -> Buffer.add_string buf "\\f" | 13 -> Buffer.add_string buf "\\r" | 27 -> Buffer.add_string buf "\\e" | 92 -> Buffer.add_string buf "\\\\" | code when code >= 32 && code <= 126 -> Buffer.add_char buf (Char.chr code) | _ when UCharTbl.Bool.get alphabetic ch -> add buf ch | code when code <= 127 -> Printf.bprintf buf "\\x%02x" code | code when code <= 0xffff -> Printf.bprintf buf "\\u%04x" code | code -> Printf.bprintf buf "\\U%06x" code let escaped str = let buf = Buffer.create (String.length str) in iter (add_escaped_char buf) str; Buffer.contents buf let add_escaped buf str = iter (add_escaped_char buf) str let add_escaped_string buf enc str = match try Some (CharEncoding.recode_string ~in_enc:enc ~out_enc:CharEncoding.utf8 str) with CharEncoding.Malformed_code -> None with | Some str -> add_escaped buf str | None -> String.iter (function | '\x20' .. '\x7e' as ch -> Buffer.add_char buf ch | ch -> Printf.bprintf buf "\\y%02x" (Char.code ch)) str let escaped_string enc str = let buf = Buffer.create (String.length str) in add_escaped_string buf enc str; Buffer.contents buf
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/zed.2.0.3/src/zed_utf8.ml
ocaml
+-----------------------------------------------------------------+ | Validation | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Unsafe UTF-8 manipulation | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Construction | +-----------------------------------------------------------------+ Camomile allow characters with code-point greater than 0x10ffff +-----------------------------------------------------------------+ | Informations | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Comparison | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Random access | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Manipulation | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Exploding and imploding | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Text transversal | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Scanning | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Tests | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Stripping | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Buffers | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Offset API | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Escaping | +-----------------------------------------------------------------+
* zed_utf8.ml * ----------- * Copyright : ( c ) 2011 , < > * Licence : BSD3 * * This file is a part of , an editor engine . * zed_utf8.ml * ----------- * Copyright : (c) 2011, Jeremie Dimino <> * Licence : BSD3 * * This file is a part of Zed, an editor engine. *) open CamomileLibraryDefault.Camomile type t = string exception Invalid of string * string exception Out_of_bounds let fail str pos msg = raise (Invalid(Printf.sprintf "at position %d: %s" pos msg, str)) let byte str i = Char.code (String.unsafe_get str i) let set_byte str i n = Bytes.unsafe_set str i (Char.unsafe_chr n) type check_result = | Correct of int | Message of string let next_error s i = let len = String.length s in let rec main i ulen = if i = len then (i, ulen, "") else let ch = String.unsafe_get s i in match ch with | '\x00' .. '\x7f' -> main (i + 1) (ulen + 1) | '\xc0' .. '\xdf' -> if i + 1 >= len then (i, ulen, "premature end of UTF8 sequence") else begin let byte1 = Char.code (String.unsafe_get s (i + 1)) in if byte1 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if ((Char.code ch land 0x1f) lsl 6) lor (byte1 land 0x3f) < 0x80 then (i, ulen, "overlong UTF8 sequence") else main (i + 2) (ulen + 1) end | '\xe0' .. '\xef' -> if i + 2 >= len then (i, ulen, "premature end of UTF8 sequence") else begin let byte1 = Char.code (String.unsafe_get s (i + 1)) and byte2 = Char.code (String.unsafe_get s (i + 2)) in if byte1 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if byte2 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if ((Char.code ch land 0x0f) lsl 12) lor ((byte1 land 0x3f) lsl 6) lor (byte2 land 0x3f) < 0x800 then (i, ulen, "overlong UTF8 sequence") else main (i + 3) (ulen + 1) end | '\xf0' .. '\xf7' -> if i + 3 >= len then (i, ulen, "premature end of UTF8 sequence") else begin let byte1 = Char.code (String.unsafe_get s (i + 1)) and byte2 = Char.code (String.unsafe_get s (i + 2)) and byte3 = Char.code (String.unsafe_get s (i + 3)) in if byte1 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if byte2 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if byte3 land 0xc0 != 0x80 then (i, ulen, "malformed UTF8 sequence") else if ((Char.code ch land 0x07) lsl 18) lor ((byte1 land 0x3f) lsl 12) lor ((byte2 land 0x3f) lsl 6) lor (byte3 land 0x3f) < 0x10000 then (i, ulen, "overlong UTF8 sequence") else main (i + 4) (ulen + 1) end | _ -> (i, ulen, "invalid start of UTF8 sequence") in main i 0 let check str = let ofs, len, msg = next_error str 0 in if ofs = String.length str then Correct len else Message (Printf.sprintf "at position %d: %s" ofs msg) let validate str = let ofs, len, msg = next_error str 0 in if ofs = String.length str then len else fail str ofs msg let unsafe_next str ofs = match String.unsafe_get str ofs with | '\x00' .. '\x7f' -> ofs + 1 | '\xc0' .. '\xdf' -> if ofs + 2 > String.length str then fail str ofs "unterminated UTF-8 sequence" else ofs + 2 | '\xe0' .. '\xef' -> if ofs + 3 > String.length str then fail str ofs "unterminated UTF-8 sequence" else ofs + 3 | '\xf0' .. '\xf7' -> if ofs + 4 > String.length str then fail str ofs "unterminated UTF-8 sequence" else ofs + 4 | _ -> fail str ofs "invalid start of UTF-8 sequence" let unsafe_prev str ofs = match String.unsafe_get str (ofs - 1) with | '\x00' .. '\x7f' -> ofs - 1 | '\x80' .. '\xbf' -> if ofs >= 2 then match String.unsafe_get str (ofs - 2) with | '\xc0' .. '\xdf' -> ofs - 2 | '\x80' .. '\xbf' -> if ofs >= 3 then match String.unsafe_get str (ofs - 3) with | '\xe0' .. '\xef' -> ofs - 3 | '\x80' .. '\xbf' -> if ofs >= 4 then match String.unsafe_get str (ofs - 4) with | '\xf0' .. '\xf7' -> ofs - 4 | _ -> fail str (ofs - 4) "invalid start of UTF-8 sequence" else fail str (ofs - 3) "invalid start of UTF-8 string" | _ -> fail str (ofs - 3) "invalid middle of UTF-8 sequence" else fail str (ofs - 2) "invaild start of UTF-8 string" | _ -> fail str (ofs - 2) "invalid middle of UTF-8 sequence" else fail str (ofs - 1) "invalid start of UTF-8 string" | _ -> fail str (ofs - 1) "invalid end of UTF-8 sequence" let unsafe_extract str ofs = let ch = String.unsafe_get str ofs in match ch with | '\x00' .. '\x7f' -> UChar.of_char ch | '\xc0' .. '\xdf' -> if ofs + 2 > String.length str then fail str ofs "unterminated UTF-8 sequence" else UChar.of_int (((Char.code ch land 0x1f) lsl 6) lor (byte str (ofs + 1) land 0x3f)) | '\xe0' .. '\xef' -> if ofs + 3 > String.length str then fail str ofs "unterminated UTF-8 sequence" else UChar.of_int (((Char.code ch land 0x0f) lsl 12) lor ((byte str (ofs + 1) land 0x3f) lsl 6) lor (byte str (ofs + 2) land 0x3f)) | '\xf0' .. '\xf7' -> if ofs + 4 > String.length str then fail str ofs "unterminated UTF-8 sequence" else UChar.of_int (((Char.code ch land 0x07) lsl 18) lor ((byte str (ofs + 1) land 0x3f) lsl 12) lor ((byte str (ofs + 2) land 0x3f) lsl 6) lor (byte str (ofs + 3) land 0x3f)) | _ -> fail str ofs "invalid start of UTF-8 sequence" let unsafe_extract_next str ofs = let ch = String.unsafe_get str ofs in match ch with | '\x00' .. '\x7f' -> (UChar.of_char ch, ofs + 1) | '\xc0' .. '\xdf' -> if ofs + 2 > String.length str then fail str ofs "unterminated UTF-8 sequence" else (UChar.of_int (((Char.code ch land 0x1f) lsl 6) lor (byte str (ofs + 1) land 0x3f)), ofs + 2) | '\xe0' .. '\xef' -> if ofs + 3 > String.length str then fail str ofs "unterminated UTF-8 sequence" else (UChar.of_int (((Char.code ch land 0x0f) lsl 12) lor ((byte str (ofs + 1) land 0x3f) lsl 6) lor (byte str (ofs + 2) land 0x3f)), ofs + 3) | '\xf0' .. '\xf7' -> if ofs + 4 > String.length str then fail str ofs "unterminated UTF-8 sequence" else (UChar.of_int (((Char.code ch land 0x07) lsl 18) lor ((byte str (ofs + 1) land 0x3f) lsl 12) lor ((byte str (ofs + 2) land 0x3f) lsl 6) lor (byte str (ofs + 3) land 0x3f)), ofs + 4) | _ -> fail str ofs "invalid start of UTF-8 sequence" let unsafe_extract_prev str ofs = let ch1 = String.unsafe_get str (ofs - 1) in match ch1 with | '\x00' .. '\x7f' -> (UChar.of_char ch1, ofs - 1) | '\x80' .. '\xbf' -> if ofs >= 2 then let ch2 = String.unsafe_get str (ofs - 2) in match ch2 with | '\xc0' .. '\xdf' -> (UChar.of_int (((Char.code ch2 land 0x1f) lsl 6) lor (Char.code ch1 land 0x3f)), ofs - 2) | '\x80' .. '\xbf' -> if ofs >= 3 then let ch3 = String.unsafe_get str (ofs - 3) in match ch3 with | '\xe0' .. '\xef' -> (UChar.of_int (((Char.code ch3 land 0x0f) lsl 12) lor ((Char.code ch2 land 0x3f) lsl 6) lor (Char.code ch1 land 0x3f)), ofs - 3) | '\x80' .. '\xbf' -> if ofs >= 4 then let ch4 = String.unsafe_get str (ofs - 4) in match ch4 with | '\xf0' .. '\xf7' -> (UChar.of_int (((Char.code ch4 land 0x07) lsl 18) lor ((Char.code ch3 land 0x3f) lsl 12) lor ((Char.code ch2 land 0x3f) lsl 6) lor (Char.code ch1 land 0x3f)), ofs - 4) | _ -> fail str (ofs - 4) "invalid start of UTF-8 sequence" else fail str (ofs - 3) "invalid start of UTF-8 string" | _ -> fail str (ofs - 3) "invalid middle of UTF-8 sequence" else fail str (ofs - 2) "invaild start of UTF-8 string" | _ -> fail str (ofs - 2) "invalid middle of UTF-8 sequence" else fail str (ofs - 1) "invalid start of UTF-8 string" | _ -> fail str (ofs - 1) "invalid end of UTF-8 sequence" let rec move_l str ofs len = if len = 0 then ofs else if ofs = String.length str then raise Out_of_bounds else move_l str (unsafe_next str ofs) (len - 1) let unsafe_sub str ofs len = let res = Bytes.create len in String.unsafe_blit str ofs res 0 len; Bytes.unsafe_to_string res let singleton char = let code = UChar.code char in Bytes.unsafe_to_string @@ if code < 0x80 then begin let s = Bytes.create 1 in set_byte s 0 code; s end else if code <= 0x800 then begin let s = Bytes.create 2 in set_byte s 0 ((code lsr 6) lor 0xc0); set_byte s 1 ((code land 0x3f) lor 0x80); s end else if code <= 0x10000 then begin let s = Bytes.create 3 in set_byte s 0 ((code lsr 12) lor 0xe0); set_byte s 1 (((code lsr 6) land 0x3f) lor 0x80); set_byte s 2 ((code land 0x3f) lor 0x80); s end else if code <= 0x10ffff then begin let s = Bytes.create 4 in set_byte s 0 ((code lsr 18) lor 0xf0); set_byte s 1 (((code lsr 12) land 0x3f) lor 0x80); set_byte s 2 (((code lsr 6) land 0x3f) lor 0x80); set_byte s 3 ((code land 0x3f) lor 0x80); s end else invalid_arg "Zed_utf8.singleton" let make n code = let str = singleton code in let len = String.length str in let res = Bytes.create (n * len) in let ofs = ref 0 in for _ = 1 to n do String.unsafe_blit str 0 res !ofs len; ofs := !ofs + len done; Bytes.unsafe_to_string res let init n f = let buf = Buffer.create n in for i = 0 to n - 1 do Buffer.add_string buf (singleton (f i)) done; Buffer.contents buf let rev_init n f = let buf = Buffer.create n in for i = n - 1 downto 0 do Buffer.add_string buf (singleton (f i)) done; Buffer.contents buf let rec length_rec str ofs len = if ofs = String.length str then len else length_rec str (unsafe_next str ofs) (len + 1) let length str = length_rec str 0 0 let rec compare_rec str1 ofs1 str2 ofs2 = if ofs1 = String.length str1 then if ofs2 = String.length str2 then 0 else -1 else if ofs2 = String.length str2 then 1 else let code1, ofs1 = unsafe_extract_next str1 ofs1 and code2, ofs2 = unsafe_extract_next str2 ofs2 in let d = UChar.code code1 - UChar.code code2 in if d <> 0 then d else compare_rec str1 ofs1 str2 ofs2 let compare str1 str2 = compare_rec str1 0 str2 0 let get str idx = if idx < 0 then raise Out_of_bounds else unsafe_extract str (move_l str 0 idx) let sub str idx len = if idx < 0 || len < 0 then raise Out_of_bounds else let ofs1 = move_l str 0 idx in let ofs2 = move_l str ofs1 len in unsafe_sub str ofs1 (ofs2 - ofs1) let break str idx = if idx < 0 then raise Out_of_bounds else let ofs = move_l str 0 idx in (unsafe_sub str 0 ofs, unsafe_sub str ofs (String.length str - ofs)) let before str idx = if idx < 0 then raise Out_of_bounds else let ofs = move_l str 0 idx in unsafe_sub str 0 ofs let after str idx = if idx < 0 then raise Out_of_bounds else let ofs = move_l str 0 idx in unsafe_sub str ofs (String.length str - ofs) let concat3 a b c = let lena = String.length a and lenb = String.length b and lenc = String.length c in let res = Bytes.create (lena + lenb + lenc) in String.unsafe_blit a 0 res 0 lena; String.unsafe_blit b 0 res lena lenb; String.unsafe_blit c 0 res (lena + lenb) lenc; Bytes.unsafe_to_string res let insert str idx sub = let a, b = break str idx in concat3 a sub b let remove str idx len = if idx < 0 || len < 0 then raise Out_of_bounds else let ofs1 = move_l str 0 idx in let ofs2 = move_l str ofs1 len in unsafe_sub str 0 ofs1 ^ unsafe_sub str ofs2 (String.length str - ofs2) let replace str idx len repl = if idx < 0 || len < 0 then raise Out_of_bounds else let ofs1 = move_l str 0 idx in let ofs2 = move_l str ofs1 len in concat3 (unsafe_sub str 0 ofs1) repl (unsafe_sub str ofs2 (String.length str - ofs2)) let rec rev_rec (res : Bytes.t) str ofs_src ofs_dst = if ofs_src = String.length str then Bytes.unsafe_to_string res else begin let ofs_src' = unsafe_next str ofs_src in let len = ofs_src' - ofs_src in let ofs_dst = ofs_dst - len in String.unsafe_blit str ofs_src res ofs_dst len; rev_rec res str ofs_src' ofs_dst end let rev str = let len = String.length str in rev_rec (Bytes.create len) str 0 len let concat sep l = match l with | [] -> "" | x :: l -> let sep_len = String.length sep in let len = List.fold_left (fun len str -> len + sep_len + String.length str) (String.length x) l in let res = Bytes.create len in String.unsafe_blit x 0 res 0 (String.length x); ignore (List.fold_left (fun ofs str -> String.unsafe_blit sep 0 res ofs sep_len; let ofs = ofs + sep_len in let len = String.length str in String.unsafe_blit str 0 res ofs len; ofs + len) (String.length x) l); Bytes.unsafe_to_string res let rev_concat sep l = match l with | [] -> "" | x :: l -> let sep_len = String.length sep in let len = List.fold_left (fun len str -> len + sep_len + String.length str) (String.length x) l in let res = Bytes.create len in let ofs = len - String.length x in String.unsafe_blit x 0 res ofs (String.length x); ignore (List.fold_left (fun ofs str -> let ofs = ofs - sep_len in String.unsafe_blit sep 0 res ofs sep_len; let len = String.length str in let ofs = ofs - len in String.unsafe_blit str 0 res ofs len; ofs) ofs l); Bytes.unsafe_to_string res let rec explode_rec str ofs acc = if ofs = 0 then acc else let x, ofs = unsafe_extract_prev str ofs in explode_rec str ofs (x :: acc) let explode str = explode_rec str (String.length str) [] let rec rev_explode_rec str ofs acc = if ofs = String.length str then acc else let x, ofs = unsafe_extract_next str ofs in rev_explode_rec str ofs (x :: acc) let rev_explode str = rev_explode_rec str 0 [] let implode l = let l = List.map singleton l in let len = List.fold_left (fun len str -> len + String.length str) 0 l in let res = Bytes.create len in ignore (List.fold_left (fun ofs str -> let len = String.length str in String.unsafe_blit str 0 res ofs len; ofs + len) 0 l); Bytes.unsafe_to_string res let rev_implode l = let l = List.map singleton l in let len = List.fold_left (fun len str -> len + String.length str) 0 l in let res = Bytes.create len in ignore (List.fold_left (fun ofs str -> let len = String.length str in let ofs = ofs - len in String.unsafe_blit str 0 res ofs len; ofs) len l); Bytes.unsafe_to_string res let rec iter_rec f str ofs = if ofs = String.length str then () else begin let chr, ofs = unsafe_extract_next str ofs in f chr; iter_rec f str ofs end let iter f str = iter_rec f str 0 let rec rev_iter_rec f str ofs = if ofs = 0 then () else begin let chr, ofs = unsafe_extract_prev str ofs in f chr; rev_iter_rec f str ofs end let rev_iter f str = rev_iter_rec f str (String.length str) let rec fold_rec f str ofs acc = if ofs = String.length str then acc else begin let chr, ofs = unsafe_extract_next str ofs in fold_rec f str ofs (f chr acc) end let fold f str acc = fold_rec f str 0 acc let rec rev_fold_rec f str ofs acc = if ofs = 0 then acc else begin let chr, ofs = unsafe_extract_prev str ofs in rev_fold_rec f str ofs (f chr acc) end let rev_fold f str acc = rev_fold_rec f str (String.length str) acc let rec map_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in Buffer.add_string buf (singleton (f chr)); map_rec buf f str ofs end let map f str = map_rec (Buffer.create (String.length str)) f str 0 let rec map_concat_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in Buffer.add_string buf (f chr); map_concat_rec buf f str ofs end let map_concat f str = map_concat_rec (Buffer.create (String.length str)) f str 0 let rec rev_map_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in Buffer.add_string buf (singleton (f chr)); rev_map_rec buf f str ofs end let rev_map f str = rev_map_rec (Buffer.create (String.length str)) f str (String.length str) let rec rev_map_concat_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in Buffer.add_string buf (f chr); rev_map_concat_rec buf f str ofs end let rev_map_concat f str = rev_map_concat_rec (Buffer.create (String.length str)) f str (String.length str) let rec filter_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in if f chr then Buffer.add_string buf (singleton chr); filter_rec buf f str ofs end let filter f str = filter_rec (Buffer.create (String.length str)) f str 0 let rec rev_filter_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in if f chr then Buffer.add_string buf (singleton chr); rev_filter_rec buf f str ofs end let rev_filter f str = rev_filter_rec (Buffer.create (String.length str)) f str (String.length str) let rec filter_map_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in (match f chr with | Some chr -> Buffer.add_string buf (singleton chr) | None -> ()); filter_map_rec buf f str ofs end let filter_map f str = filter_map_rec (Buffer.create (String.length str)) f str 0 let rec filter_map_concat_rec buf f str ofs = if ofs = String.length str then Buffer.contents buf else begin let chr, ofs = unsafe_extract_next str ofs in (match f chr with | Some txt -> Buffer.add_string buf txt | None -> ()); filter_map_concat_rec buf f str ofs end let filter_map_concat f str = filter_map_concat_rec (Buffer.create (String.length str)) f str 0 let rec rev_filter_map_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in (match f chr with | Some chr -> Buffer.add_string buf (singleton chr) | None -> ()); rev_filter_map_rec buf f str ofs end let rev_filter_map f str = rev_filter_map_rec (Buffer.create (String.length str)) f str (String.length str) let rec rev_filter_map_concat_rec buf f str ofs = if ofs = 0 then Buffer.contents buf else begin let chr, ofs = unsafe_extract_prev str ofs in (match f chr with | Some txt -> Buffer.add_string buf txt | None -> ()); rev_filter_map_concat_rec buf f str ofs end let rev_filter_map_concat f str = rev_filter_map_concat_rec (Buffer.create (String.length str)) f str (String.length str) let rec for_all_rec f str ofs = if ofs = String.length str then true else let chr, ofs = unsafe_extract_next str ofs in f chr && for_all_rec f str ofs let for_all f str = for_all_rec f str 0 let rec exists_rec f str ofs = if ofs = String.length str then false else let chr, ofs = unsafe_extract_next str ofs in f chr || exists_rec f str ofs let exists f str = exists_rec f str 0 let rec count_rec f str ofs n = if ofs = String.length str then n else let chr, ofs = unsafe_extract_next str ofs in count_rec f str ofs (if f chr then n + 1 else n) let count f str = count_rec f str 0 0 let rec unsafe_sub_equal str ofs sub ofs_sub = if ofs_sub = String.length sub then true else (String.unsafe_get str ofs = String.unsafe_get sub ofs_sub) && unsafe_sub_equal str (ofs + 1) sub (ofs_sub + 1) let rec contains_rec str sub ofs = if ofs + String.length sub > String.length str then false else unsafe_sub_equal str ofs sub 0 || contains_rec str sub (unsafe_next str ofs) let contains str sub = contains_rec str sub 0 let starts_with str prefix = if String.length prefix > String.length str then false else unsafe_sub_equal str 0 prefix 0 let ends_with str suffix = let ofs = String.length str - String.length suffix in if ofs < 0 then false else unsafe_sub_equal str ofs suffix 0 let rec lfind predicate str ofs = if ofs = String.length str then ofs else let chr, ofs' = unsafe_extract_next str ofs in if predicate chr then lfind predicate str ofs' else ofs let rec rfind predicate str ofs = if ofs = 0 then 0 else let chr, ofs' = unsafe_extract_prev str ofs in if predicate chr then rfind predicate str ofs' else ofs let spaces = UCharInfo.load_property_tbl `White_Space let is_space ch = UCharTbl.Bool.get spaces ch let strip ?(predicate=is_space) str = let lofs = lfind predicate str 0 and rofs = rfind predicate str (String.length str) in if lofs < rofs then unsafe_sub str lofs (rofs - lofs) else "" let lstrip ?(predicate=is_space) str = let lofs = lfind predicate str 0 in unsafe_sub str lofs (String.length str - lofs) let rstrip ?(predicate=is_space) str = let rofs = rfind predicate str (String.length str) in unsafe_sub str 0 rofs let lchop = function | "" -> "" | str -> let ofs = unsafe_next str 0 in unsafe_sub str ofs (String.length str - ofs) let rchop = function | "" -> "" | str -> let ofs = unsafe_prev str (String.length str) in unsafe_sub str 0 ofs let add buf char = let code = UChar.code char in if code < 0x80 then Buffer.add_char buf (Char.unsafe_chr code) else if code <= 0x800 then begin Buffer.add_char buf (Char.unsafe_chr ((code lsr 6) lor 0xc0)); Buffer.add_char buf (Char.unsafe_chr ((code land 0x3f) lor 0x80)) end else if code <= 0x10000 then begin Buffer.add_char buf (Char.unsafe_chr ((code lsr 12) lor 0xe0)); Buffer.add_char buf (Char.unsafe_chr (((code lsr 6) land 0x3f) lor 0x80)); Buffer.add_char buf (Char.unsafe_chr ((code land 0x3f) lor 0x80)) end else if code <= 0x10ffff then begin Buffer.add_char buf (Char.unsafe_chr ((code lsr 18) lor 0xf0)); Buffer.add_char buf (Char.unsafe_chr (((code lsr 12) land 0x3f) lor 0x80)); Buffer.add_char buf (Char.unsafe_chr (((code lsr 6) land 0x3f) lor 0x80)); Buffer.add_char buf (Char.unsafe_chr ((code land 0x3f) lor 0x80)) end else invalid_arg "Zed_utf8.add" let extract str ofs = if ofs < 0 || ofs >= String.length str then raise Out_of_bounds else unsafe_extract str ofs let next str ofs = if ofs < 0 || ofs >= String.length str then raise Out_of_bounds else unsafe_next str ofs let extract_next str ofs = if ofs < 0 || ofs >= String.length str then raise Out_of_bounds else unsafe_extract_next str ofs let prev str ofs = if ofs <= 0 || ofs > String.length str then raise Out_of_bounds else unsafe_prev str ofs let extract_prev str ofs = if ofs <= 0 || ofs > String.length str then raise Out_of_bounds else unsafe_extract_prev str ofs let alphabetic = UCharInfo.load_property_tbl `Alphabetic let escaped_char ch = match UChar.code ch with | 7 -> "\\a" | 8 -> "\\b" | 9 -> "\\t" | 10 -> "\\n" | 11 -> "\\v" | 12 -> "\\f" | 13 -> "\\r" | 27 -> "\\e" | 92 -> "\\\\" | code when code >= 32 && code <= 126 -> String.make 1 (Char.chr code) | _ when UCharTbl.Bool.get alphabetic ch -> singleton ch | code when code <= 127 -> Printf.sprintf "\\x%02x" code | code when code <= 0xffff -> Printf.sprintf "\\u%04x" code | code -> Printf.sprintf "\\U%06x" code let add_escaped_char buf ch = match UChar.code ch with | 7 -> Buffer.add_string buf "\\a" | 8 -> Buffer.add_string buf "\\b" | 9 -> Buffer.add_string buf "\\t" | 10 -> Buffer.add_string buf "\\n" | 11 -> Buffer.add_string buf "\\v" | 12 -> Buffer.add_string buf "\\f" | 13 -> Buffer.add_string buf "\\r" | 27 -> Buffer.add_string buf "\\e" | 92 -> Buffer.add_string buf "\\\\" | code when code >= 32 && code <= 126 -> Buffer.add_char buf (Char.chr code) | _ when UCharTbl.Bool.get alphabetic ch -> add buf ch | code when code <= 127 -> Printf.bprintf buf "\\x%02x" code | code when code <= 0xffff -> Printf.bprintf buf "\\u%04x" code | code -> Printf.bprintf buf "\\U%06x" code let escaped str = let buf = Buffer.create (String.length str) in iter (add_escaped_char buf) str; Buffer.contents buf let add_escaped buf str = iter (add_escaped_char buf) str let add_escaped_string buf enc str = match try Some (CharEncoding.recode_string ~in_enc:enc ~out_enc:CharEncoding.utf8 str) with CharEncoding.Malformed_code -> None with | Some str -> add_escaped buf str | None -> String.iter (function | '\x20' .. '\x7e' as ch -> Buffer.add_char buf ch | ch -> Printf.bprintf buf "\\y%02x" (Char.code ch)) str let escaped_string enc str = let buf = Buffer.create (String.length str) in add_escaped_string buf enc str; Buffer.contents buf
519f3c1f0a95ae4bd63d9eb6a2eff7551be7dd9a551bd61a73b8dd45f579f583
bobzhang/fan
operators.ml
let _ : int = 42 let (+) = M.(+) let (+) = M.(+) in 42 let (+) : int -> int -> int = (+) let (+) : int -> int -> int = (+) in 42 let None = None let None : int option = None
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/fixtures/operators.ml
ocaml
let _ : int = 42 let (+) = M.(+) let (+) = M.(+) in 42 let (+) : int -> int -> int = (+) let (+) : int -> int -> int = (+) in 42 let None = None let None : int option = None
d1607c98c4296da97635ba738c720d9fa368ee2beaa9ddb3978b932e9221be3d
wh5a/thih
HaskellPrims.hs
----------------------------------------------------------------------------- HaskellPrims : Typing assumptions for primitives in the Hugs prelude -- Part of ` Typing Haskell in ' , version of November 23 , 2000 Copyright ( c ) and the Oregon Graduate Institute of Science and Technology , 1999 - 2000 -- This program is distributed as Free Software under the terms -- in the file "License" that is included in the distribution -- of this software, copies of which may be obtained from: -- /~mpj/thih/ -- ----------------------------------------------------------------------------- module HaskellPrims where import Testbed import StaticPrelude defnsHaskellPrims = [ "_concmp" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TGen 0 `fn` tOrdering))), "_range" :>: (Forall [Star] ([] :=> (TAp (TAp tTuple2 (TGen 0)) (TGen 0) `fn` TAp tList (TGen 0)))), "_index" :>: (Forall [Star] ([] :=> (TAp (TAp tTuple2 (TGen 0)) (TGen 0) `fn` TGen 0 `fn` tInt))), "_inRange" :>: (Forall [Star] ([] :=> (TAp (TAp tTuple2 (TGen 0)) (TGen 0) `fn` TGen 0 `fn` tBool))), "_ToEnum" :>: (Forall [Star] ([] :=> (TGen 0 `fn` tInt `fn` TGen 0))), "_FrEnum" :>: (Forall [Star] ([] :=> (TGen 0 `fn` tInt))), "_From" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TAp tList (TGen 0)))), "_FromTo" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TGen 0 `fn` TAp tList (TGen 0)))), "_FromThen" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TGen 0 `fn` TAp tList (TGen 0)))), "error" :>: (Forall [Star] ([] :=> (tString `fn` TGen 0))), "primIntToFloat" :>: (Forall [] ([] :=> (tInt `fn` tFloat))), "primIntToInteger" :>: (Forall [] ([] :=> (tInt `fn` tInteger))), "ioeGetErrorString" :>: (Forall [] ([] :=> (tIOError `fn` tString))), "readFile" :>: (Forall [] ([] :=> (tFilePath `fn` TAp tIO tString))), "appendFile" :>: (Forall [] ([] :=> (tFilePath `fn` tString `fn` TAp tIO tUnit))), "writeFile" :>: (Forall [] ([] :=> (tFilePath `fn` tString `fn` TAp tIO tUnit))), "getContents" :>: (Forall [] ([] :=> (TAp tIO tString))), "userError" :>: (Forall [] ([] :=> (tString `fn` tIOError))), "getChar" :>: (Forall [] ([] :=> (TAp tIO tChar))), "putStr" :>: (Forall [] ([] :=> (tString `fn` TAp tIO tUnit))), "putChar" :>: (Forall [] ([] :=> (tChar `fn` TAp tIO tUnit))), "ioError" :>: (Forall [Star] ([] :=> (tIOError `fn` TAp tIO (TGen 0)))), "catch" :>: (Forall [Star] ([] :=> (TAp tIO (TGen 0) `fn` (tIOError `fn` TAp tIO (TGen 0)) `fn` TAp tIO (TGen 0)))), "primretIO" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TAp tIO (TGen 0)))), "primbindIO" :>: (Forall [Star, Star] ([] :=> (TAp tIO (TGen 0) `fn` (TGen 0 `fn` TAp tIO (TGen 1)) `fn` TAp tIO (TGen 1)))), "primShowsDouble" :>: (Forall [] ([] :=> (tInt `fn` tDouble `fn` tShowS))), "primShowsFloat" :>: (Forall [] ([] :=> (tInt `fn` tFloat `fn` tShowS))), "primDoubleDecode" :>: (Forall [] ([] :=> (tDouble `fn` TAp (TAp tTuple2 tInteger) tInt))), "primDoubleEncode" :>: (Forall [] ([] :=> (tInteger `fn` tInt `fn` tDouble))), "primDoubleMaxExp" :>: (Forall [] ([] :=> tInt)), "primDoubleMinExp" :>: (Forall [] ([] :=> tInt)), "primDoubleDigits" :>: (Forall [] ([] :=> tInt)), "primDoubleRadix" :>: (Forall [] ([] :=> tInteger)), "primFloatDecode" :>: (Forall [] ([] :=> (tFloat `fn` TAp (TAp tTuple2 tInteger) tInt))), "primFloatEncode" :>: (Forall [] ([] :=> (tInteger `fn` tInt `fn` tFloat))), "primFloatMaxExp" :>: (Forall [] ([] :=> tInt)), "primFloatMinExp" :>: (Forall [] ([] :=> tInt)), "primFloatDigits" :>: (Forall [] ([] :=> tInt)), "primFloatRadix" :>: (Forall [] ([] :=> tInteger)), "primSqrtDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primExpDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primLogDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primAtanDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primTanDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primAcosDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primCosDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primAsinDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primSinDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primSqrtFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primExpFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primLogFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primAtanFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primTanFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primAcosFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primCosFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primAsinFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primSinFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primRationalToDouble" :>: (Forall [] ([] :=> (tRational `fn` tDouble))), "primRationalToFloat" :>: (Forall [] ([] :=> (tRational `fn` tFloat))), "primDivDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tDouble))), "doubleToFloat" :>: (Forall [] ([] :=> (tDouble `fn` tFloat))), "primDivFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tFloat))), "primIntegerToDouble" :>: (Forall [] ([] :=> (tInteger `fn` tDouble))), "primIntToDouble" :>: (Forall [] ([] :=> (tInt `fn` tDouble))), "primNegDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primMulDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tDouble))), "primMinusDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tDouble))), "primPlusDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tDouble))), "primIntegerToFloat" :>: (Forall [] ([] :=> (tInteger `fn` tFloat))), "primNegFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primMulFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tFloat))), "primMinusFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tFloat))), "primPlusFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tFloat))), "primCmpDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tOrdering))), "primEqDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tBool))), "primCmpFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tOrdering))), "primEqFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tBool))), "primShowsInteger" :>: (Forall [] ([] :=> (tInt `fn` tInteger `fn` tShowS))), "primShowsInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tShowS))), "primEvenInteger" :>: (Forall [] ([] :=> (tInteger `fn` tBool))), "primQrmInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` TAp (TAp tTuple2 tInteger) tInteger))), "primEvenInt" :>: (Forall [] ([] :=> (tInt `fn` tBool))), "primQrmInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` TAp (TAp tTuple2 tInt) tInt))), "primModInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primRemInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primQuotInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primDivInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primNegInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger))), "primMulInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tInteger))), "primMinusInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tInteger))), "primPlusInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tInteger))), "primMaxInt" :>: (Forall [] ([] :=> tInt)), "primMinInt" :>: (Forall [] ([] :=> tInt)), "primIntegerToInt" :>: (Forall [] ([] :=> (tInteger `fn` tInt))), "primNegInt" :>: (Forall [] ([] :=> (tInt `fn` tInt))), "primMulInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primMinusInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primPlusInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primCmpInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tOrdering))), "primEqInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tBool))), "primCmpInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tOrdering))), "primEqInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tBool))), "primIntToChar" :>: (Forall [] ([] :=> (tInt `fn` tChar))), "primCharToInt" :>: (Forall [] ([] :=> (tChar `fn` tInt))), "primCmpChar" :>: (Forall [] ([] :=> (tChar `fn` tChar `fn` tOrdering))), "primEqChar" :>: (Forall [] ([] :=> (tChar `fn` tChar `fn` tBool))), "$!" :>: (Forall [Star, Star] ([] :=> ((TGen 0 `fn` TGen 1) `fn` TGen 0 `fn` TGen 1))), "seq" :>: (Forall [Star, Star] ([] :=> (TGen 0 `fn` TGen 1 `fn` TGen 1))) ] -----------------------------------------------------------------------------
null
https://raw.githubusercontent.com/wh5a/thih/dc5cb16ba4e998097135beb0c7b0b416cac7bfae/src/HaskellPrims.hs
haskell
--------------------------------------------------------------------------- in the file "License" that is included in the distribution of this software, copies of which may be obtained from: /~mpj/thih/ --------------------------------------------------------------------------- ---------------------------------------------------------------------------
HaskellPrims : Typing assumptions for primitives in the Hugs prelude Part of ` Typing Haskell in ' , version of November 23 , 2000 Copyright ( c ) and the Oregon Graduate Institute of Science and Technology , 1999 - 2000 This program is distributed as Free Software under the terms module HaskellPrims where import Testbed import StaticPrelude defnsHaskellPrims = [ "_concmp" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TGen 0 `fn` tOrdering))), "_range" :>: (Forall [Star] ([] :=> (TAp (TAp tTuple2 (TGen 0)) (TGen 0) `fn` TAp tList (TGen 0)))), "_index" :>: (Forall [Star] ([] :=> (TAp (TAp tTuple2 (TGen 0)) (TGen 0) `fn` TGen 0 `fn` tInt))), "_inRange" :>: (Forall [Star] ([] :=> (TAp (TAp tTuple2 (TGen 0)) (TGen 0) `fn` TGen 0 `fn` tBool))), "_ToEnum" :>: (Forall [Star] ([] :=> (TGen 0 `fn` tInt `fn` TGen 0))), "_FrEnum" :>: (Forall [Star] ([] :=> (TGen 0 `fn` tInt))), "_From" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TAp tList (TGen 0)))), "_FromTo" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TGen 0 `fn` TAp tList (TGen 0)))), "_FromThen" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TGen 0 `fn` TAp tList (TGen 0)))), "error" :>: (Forall [Star] ([] :=> (tString `fn` TGen 0))), "primIntToFloat" :>: (Forall [] ([] :=> (tInt `fn` tFloat))), "primIntToInteger" :>: (Forall [] ([] :=> (tInt `fn` tInteger))), "ioeGetErrorString" :>: (Forall [] ([] :=> (tIOError `fn` tString))), "readFile" :>: (Forall [] ([] :=> (tFilePath `fn` TAp tIO tString))), "appendFile" :>: (Forall [] ([] :=> (tFilePath `fn` tString `fn` TAp tIO tUnit))), "writeFile" :>: (Forall [] ([] :=> (tFilePath `fn` tString `fn` TAp tIO tUnit))), "getContents" :>: (Forall [] ([] :=> (TAp tIO tString))), "userError" :>: (Forall [] ([] :=> (tString `fn` tIOError))), "getChar" :>: (Forall [] ([] :=> (TAp tIO tChar))), "putStr" :>: (Forall [] ([] :=> (tString `fn` TAp tIO tUnit))), "putChar" :>: (Forall [] ([] :=> (tChar `fn` TAp tIO tUnit))), "ioError" :>: (Forall [Star] ([] :=> (tIOError `fn` TAp tIO (TGen 0)))), "catch" :>: (Forall [Star] ([] :=> (TAp tIO (TGen 0) `fn` (tIOError `fn` TAp tIO (TGen 0)) `fn` TAp tIO (TGen 0)))), "primretIO" :>: (Forall [Star] ([] :=> (TGen 0 `fn` TAp tIO (TGen 0)))), "primbindIO" :>: (Forall [Star, Star] ([] :=> (TAp tIO (TGen 0) `fn` (TGen 0 `fn` TAp tIO (TGen 1)) `fn` TAp tIO (TGen 1)))), "primShowsDouble" :>: (Forall [] ([] :=> (tInt `fn` tDouble `fn` tShowS))), "primShowsFloat" :>: (Forall [] ([] :=> (tInt `fn` tFloat `fn` tShowS))), "primDoubleDecode" :>: (Forall [] ([] :=> (tDouble `fn` TAp (TAp tTuple2 tInteger) tInt))), "primDoubleEncode" :>: (Forall [] ([] :=> (tInteger `fn` tInt `fn` tDouble))), "primDoubleMaxExp" :>: (Forall [] ([] :=> tInt)), "primDoubleMinExp" :>: (Forall [] ([] :=> tInt)), "primDoubleDigits" :>: (Forall [] ([] :=> tInt)), "primDoubleRadix" :>: (Forall [] ([] :=> tInteger)), "primFloatDecode" :>: (Forall [] ([] :=> (tFloat `fn` TAp (TAp tTuple2 tInteger) tInt))), "primFloatEncode" :>: (Forall [] ([] :=> (tInteger `fn` tInt `fn` tFloat))), "primFloatMaxExp" :>: (Forall [] ([] :=> tInt)), "primFloatMinExp" :>: (Forall [] ([] :=> tInt)), "primFloatDigits" :>: (Forall [] ([] :=> tInt)), "primFloatRadix" :>: (Forall [] ([] :=> tInteger)), "primSqrtDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primExpDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primLogDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primAtanDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primTanDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primAcosDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primCosDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primAsinDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primSinDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primSqrtFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primExpFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primLogFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primAtanFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primTanFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primAcosFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primCosFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primAsinFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primSinFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primRationalToDouble" :>: (Forall [] ([] :=> (tRational `fn` tDouble))), "primRationalToFloat" :>: (Forall [] ([] :=> (tRational `fn` tFloat))), "primDivDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tDouble))), "doubleToFloat" :>: (Forall [] ([] :=> (tDouble `fn` tFloat))), "primDivFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tFloat))), "primIntegerToDouble" :>: (Forall [] ([] :=> (tInteger `fn` tDouble))), "primIntToDouble" :>: (Forall [] ([] :=> (tInt `fn` tDouble))), "primNegDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble))), "primMulDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tDouble))), "primMinusDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tDouble))), "primPlusDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tDouble))), "primIntegerToFloat" :>: (Forall [] ([] :=> (tInteger `fn` tFloat))), "primNegFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat))), "primMulFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tFloat))), "primMinusFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tFloat))), "primPlusFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tFloat))), "primCmpDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tOrdering))), "primEqDouble" :>: (Forall [] ([] :=> (tDouble `fn` tDouble `fn` tBool))), "primCmpFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tOrdering))), "primEqFloat" :>: (Forall [] ([] :=> (tFloat `fn` tFloat `fn` tBool))), "primShowsInteger" :>: (Forall [] ([] :=> (tInt `fn` tInteger `fn` tShowS))), "primShowsInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tShowS))), "primEvenInteger" :>: (Forall [] ([] :=> (tInteger `fn` tBool))), "primQrmInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` TAp (TAp tTuple2 tInteger) tInteger))), "primEvenInt" :>: (Forall [] ([] :=> (tInt `fn` tBool))), "primQrmInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` TAp (TAp tTuple2 tInt) tInt))), "primModInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primRemInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primQuotInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primDivInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primNegInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger))), "primMulInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tInteger))), "primMinusInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tInteger))), "primPlusInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tInteger))), "primMaxInt" :>: (Forall [] ([] :=> tInt)), "primMinInt" :>: (Forall [] ([] :=> tInt)), "primIntegerToInt" :>: (Forall [] ([] :=> (tInteger `fn` tInt))), "primNegInt" :>: (Forall [] ([] :=> (tInt `fn` tInt))), "primMulInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primMinusInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primPlusInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tInt))), "primCmpInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tOrdering))), "primEqInteger" :>: (Forall [] ([] :=> (tInteger `fn` tInteger `fn` tBool))), "primCmpInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tOrdering))), "primEqInt" :>: (Forall [] ([] :=> (tInt `fn` tInt `fn` tBool))), "primIntToChar" :>: (Forall [] ([] :=> (tInt `fn` tChar))), "primCharToInt" :>: (Forall [] ([] :=> (tChar `fn` tInt))), "primCmpChar" :>: (Forall [] ([] :=> (tChar `fn` tChar `fn` tOrdering))), "primEqChar" :>: (Forall [] ([] :=> (tChar `fn` tChar `fn` tBool))), "$!" :>: (Forall [Star, Star] ([] :=> ((TGen 0 `fn` TGen 1) `fn` TGen 0 `fn` TGen 1))), "seq" :>: (Forall [Star, Star] ([] :=> (TGen 0 `fn` TGen 1 `fn` TGen 1))) ]
589dbd91b6c5c24dea19af40f7e49a14b7dbc172d0e5ecc4ebdacbf8212c73cd
gafiatulin/codewars
Pangram.hs
Detect / module Pangram where import Data.Char (toLower) isPangram :: String -> Bool isPangram str = all (`elem` map toLower str) ['a'..'z']
null
https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/6%20kyu/Pangram.hs
haskell
Detect / module Pangram where import Data.Char (toLower) isPangram :: String -> Bool isPangram str = all (`elem` map toLower str) ['a'..'z']
615a957cd3b9504fa3ad68f2eb1403da742bf3768c269d83d648c62ceb571a68
janegca/htdp2e
Exercise-298-find.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname Exercise-292-find) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) Exercise 298 . ; ; Design find?. The function consumes a Dir and a file name and determines ; whether or not a file with this name occurs in the directory tree. (require htdp/dir) ; Dir File -> Boolean ; true if the file is found in the directory structure (check-expect (find? (make-dir 'Test empty empty) '|King Lear.pdf|) #false) (check-expect (find? (make-dir 'Test (list (make-dir 'T2 empty empty)) empty) '|King Lear.pdf|) #false) (check-expect (find? (make-dir 'Test empty (list (make-file '|King Lear.pdf| 20 ""))) '|King Lear.pdf|) #true) (check-expect (find? (make-dir 'Test (list (make-dir 'T2 empty (list (make-file '|King Lear.pdf| 20 "")))) empty) '|King Lear.pdf|) #true) (check-expect (find? (make-dir 'Test empty (list (make-file 'read1 10 "") (make-file '|King Lear.pdf| 20 ""))) '|King Lear.pdf|) #true) (define (find? root file) LOF - > Boolean ; true if file is found in the list of files (define (found-file? f*) (ormap (lambda (f) (eq? file (file-name f))) f*))) (or (found-file? (dir-files root)) ; check all sub-directories (ormap (lambda (d) (found-file? (dir-files d))) (dir-dirs root)))))
null
https://raw.githubusercontent.com/janegca/htdp2e/2d50378135edc2b8b1816204021f8763f8b2707b/04-Intertwined%20Data/Exercise-298-find.rkt
racket
about the language level of this file in a form that our tools can easily process. Design find?. The function consumes a Dir and a file name and determines whether or not a file with this name occurs in the directory tree. Dir File -> Boolean true if the file is found in the directory structure true if file is found in the list of files check all sub-directories
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname Exercise-292-find) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) Exercise 298 . (require htdp/dir) (check-expect (find? (make-dir 'Test empty empty) '|King Lear.pdf|) #false) (check-expect (find? (make-dir 'Test (list (make-dir 'T2 empty empty)) empty) '|King Lear.pdf|) #false) (check-expect (find? (make-dir 'Test empty (list (make-file '|King Lear.pdf| 20 ""))) '|King Lear.pdf|) #true) (check-expect (find? (make-dir 'Test (list (make-dir 'T2 empty (list (make-file '|King Lear.pdf| 20 "")))) empty) '|King Lear.pdf|) #true) (check-expect (find? (make-dir 'Test empty (list (make-file 'read1 10 "") (make-file '|King Lear.pdf| 20 ""))) '|King Lear.pdf|) #true) (define (find? root file) LOF - > Boolean (define (found-file? f*) (ormap (lambda (f) (eq? file (file-name f))) f*))) (or (found-file? (dir-files root)) (ormap (lambda (d) (found-file? (dir-files d))) (dir-dirs root)))))
e750e82fad886f56ba6fa903d35bdb17f20878857914ee6093cc66899dda8239
MastodonC/kixi.datastore
metadatastore_test.clj
(ns kixi.unit.metadatastore-test (:require [clojure.test :refer :all] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.data :as data] [kixi.datastore.schemastore.utils :as sh] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [environ.core :refer [env]] [kixi.datastore.metadatastore :as md] [taoensso [timbre :as timbre :refer [error]]])) (deftest name-check (let [r (keep #(when-not (s/valid? ::md/name %) %) (gen/sample (s/gen ::md/name) 1000))] (is (empty? r) (pr-str r))) (is (not (s/valid? ::md/name ""))) (is (not (s/valid? ::md/name "$"))) (is (s/valid? ::md/name "1")) (is (s/valid? ::md/name "Z")))
null
https://raw.githubusercontent.com/MastodonC/kixi.datastore/f33bba4b1fdd8c56cc7ac0f559ffe35254c9ca99/test/kixi/unit/metadatastore_test.clj
clojure
(ns kixi.unit.metadatastore-test (:require [clojure.test :refer :all] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen] [clojure.data :as data] [kixi.datastore.schemastore.utils :as sh] [com.gfredericks.test.chuck.clojure-test :refer [checking]] [environ.core :refer [env]] [kixi.datastore.metadatastore :as md] [taoensso [timbre :as timbre :refer [error]]])) (deftest name-check (let [r (keep #(when-not (s/valid? ::md/name %) %) (gen/sample (s/gen ::md/name) 1000))] (is (empty? r) (pr-str r))) (is (not (s/valid? ::md/name ""))) (is (not (s/valid? ::md/name "$"))) (is (s/valid? ::md/name "1")) (is (s/valid? ::md/name "Z")))
e9f214914f009dcfa69709907c00a8865f2cadd0667cc81cdcbd3b374a9c0659
jyh/metaprl
lf_kind.mli
* Valid kinds . * * ---------------------------------------------------------------- * * This file is part of MetaPRL , a modular , higher order * logical framework that provides a logical programming * environment for OCaml and other languages . * * See the file doc / htmlman / default.html or visit / * for more information . * * Copyright ( C ) 1998 , Cornell University * * This program is free software ; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation ; either version 2 * of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . * * Author : * * Valid kinds. * * ---------------------------------------------------------------- * * This file is part of MetaPRL, a modular, higher order * logical framework that provides a logical programming * environment for OCaml and other languages. * * See the file doc/htmlman/default.html or visit / * for more information. * * Copyright (C) 1998 Jason Hickey, Cornell University * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Jason Hickey * *) extends Lf_sig;; declare equal{'A; 'B};; (* * Const family. *) rule const_fam 'S 'C : ctx{'S1[hyp{'K; c. 'S2[nil_sig; 'c]}]; 'C[nil_ctx]} --> sequent { <S1>; c. 'K; <S2['c]>; <C['c]> >- mem{'c; 'K}};; (* * Kind equality. *) rule conv_fam 'S 'C : sequent { <S>; <C> >- mem{'A; 'K1 } } --> sequent { <S>; <C> >- 'K2 } --> sequent { <S>; <C> >- equal{'K1; 'K2} } --> sequent { <S>; <C> >- mem{'A; 'K2} };; (* * -*- * Local Variables: * Caml-master: "editor.run" * End: * -*- *)
null
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/lf/lf_kind.mli
ocaml
* Const family. * Kind equality. * -*- * Local Variables: * Caml-master: "editor.run" * End: * -*-
* Valid kinds . * * ---------------------------------------------------------------- * * This file is part of MetaPRL , a modular , higher order * logical framework that provides a logical programming * environment for OCaml and other languages . * * See the file doc / htmlman / default.html or visit / * for more information . * * Copyright ( C ) 1998 , Cornell University * * This program is free software ; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation ; either version 2 * of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . * * Author : * * Valid kinds. * * ---------------------------------------------------------------- * * This file is part of MetaPRL, a modular, higher order * logical framework that provides a logical programming * environment for OCaml and other languages. * * See the file doc/htmlman/default.html or visit / * for more information. * * Copyright (C) 1998 Jason Hickey, Cornell University * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Author: Jason Hickey * *) extends Lf_sig;; declare equal{'A; 'B};; rule const_fam 'S 'C : ctx{'S1[hyp{'K; c. 'S2[nil_sig; 'c]}]; 'C[nil_ctx]} --> sequent { <S1>; c. 'K; <S2['c]>; <C['c]> >- mem{'c; 'K}};; rule conv_fam 'S 'C : sequent { <S>; <C> >- mem{'A; 'K1 } } --> sequent { <S>; <C> >- 'K2 } --> sequent { <S>; <C> >- equal{'K1; 'K2} } --> sequent { <S>; <C> >- mem{'A; 'K2} };;
8ac0fae62b9134d40179c4cfcbd186349a2a20d22bd01c639ff7e6082ca824f7
ixy-languages/ixy.hs
Queue.hs
-- | -- Module : Lib.Ixgbe.Queue Copyright : 2018 -- License : BSD3 -- -- Maintainer : -- Stability : experimental -- Portability : unknown -- -- Description -- module Lib.Ixgbe.Queue ( RxQueue(..) , TxQueue(..) , ReceiveDescriptor(..) , TransmitDescriptor(..) , mkRxQueue , mkTxQueue , numRxQueueEntries , numTxQueueEntries , nullReceiveDescriptor , isDone , isEndOfPacket , nullTransmitDescriptor , bufferSize , rxMap , rxGetMapping , txMap , txGetMapping ) where import Lib.Memory import Lib.Prelude import Control.Monad.Catch ( MonadThrow ) import Control.Monad.Logger import qualified Data.Array.IO as Array import Data.IORef import Foreign.Ptr ( castPtr , plusPtr ) import Foreign.Storable ( sizeOf , alignment , peek , poke , peekByteOff , pokeByteOff ) import Foreign.Marshal.Utils ( fillBytes ) numRxQueueEntries :: Int numRxQueueEntries = 512 numTxQueueEntries :: Int numTxQueueEntries = 512 bufferSize :: Int bufferSize = 2048 -- $ Queues data RxQueue = RxQueue { rxqDescriptor :: Int -> Ptr ReceiveDescriptor , rxqMemPool :: !MemPool , rxqMap :: !(Array.IOUArray Int Int) , rxqIndexRef :: !(IORef Int) } mkRxQueue :: (MonadThrow m, MonadIO m, MonadLogger m) => m RxQueue mkRxQueue = do -- Setup the descriptors and buffers. memPool <- mkMemPool $ (numRxQueueEntries + numTxQueueEntries) * 2 descPtr <- allocateDescriptors (numRxQueueEntries * sizeOf nullReceiveDescriptor) let descriptor i = descPtr `plusPtr` (i * sizeOf nullReceiveDescriptor) ids <- mapM (setupDescriptor memPool) [ descriptor i | i <- [0 .. numRxQueueEntries - 1] ] indexRef <- liftIO $ newIORef (0 :: Int) m <- liftIO $ Array.newListArray (0, numRxQueueEntries - 1) ids return $! RxQueue { rxqDescriptor = descriptor , rxqMemPool = memPool , rxqMap = m , rxqIndexRef = indexRef } where setupDescriptor memPool ptr = liftIO $ do buf <- peek =<< allocateBuf memPool let PhysAddr physAddr = pbAddr buf poke ptr ReceiveRead {rdBufPhysAddr = physAddr, rdHeaderAddr = 0} return $ pbId buf rxMap :: RxQueue -> Int -> Int -> IO () rxMap queue = Array.writeArray (rxqMap queue) rxGetMapping :: RxQueue -> Int -> IO Int rxGetMapping queue = Array.readArray (rxqMap queue) data TxQueue = TxQueue { txqDescriptor :: Int -> Ptr TransmitDescriptor , txqMap :: !(Array.IOUArray Int Int) , txqIndexRef :: !(IORef Int) , txqCleanRef :: !(IORef Int)} mkTxQueue :: (MonadThrow m, MonadIO m, MonadLogger m) => m TxQueue mkTxQueue = do descPtr <- allocateDescriptors (numTxQueueEntries * sizeOf nullTransmitDescriptor) indexRef <- liftIO $ newIORef (0 :: Int) cleanRef <- liftIO $ newIORef (0 :: Int) m <- liftIO $ Array.newArray_ (0, numTxQueueEntries - 1) let descriptor i = descPtr `plusPtr` (i * sizeOf nullTransmitDescriptor) return $! TxQueue { txqDescriptor = descriptor , txqMap = m , txqIndexRef = indexRef , txqCleanRef = cleanRef } txMap :: TxQueue -> Int -> Int -> IO () txMap queue = Array.writeArray (txqMap queue) txGetMapping :: TxQueue -> Int -> IO Int txGetMapping queue = Array.readArray (txqMap queue) -- $ Descriptors data ReceiveDescriptor = ReceiveRead { rdBufPhysAddr :: {-# UNPACK #-} !Word64 , rdHeaderAddr :: {-# UNPACK #-} !Word64 } | ReceiveWriteback { rdStatus :: {-# UNPACK #-} !Word32 , rdLength :: {-# UNPACK #-} !Word16} instance Storable ReceiveDescriptor where sizeOf _ = 16 alignment = sizeOf peek ptr = do status <- peekByteOff ptr 8 len <- peekByteOff ptr 12 return ReceiveWriteback {rdStatus=status, rdLength=len} poke ptr (ReceiveRead bufPhysAddr headerAddr) = do poke (castPtr ptr) bufPhysAddr pokeByteOff ptr 8 headerAddr poke _ (ReceiveWriteback _ _) = return $ panic "Cannot poke a writeback descriptor." nullReceiveDescriptor :: ReceiveDescriptor nullReceiveDescriptor = ReceiveRead {rdBufPhysAddr = 0, rdHeaderAddr = 0} isDone :: ReceiveDescriptor -> Bool isDone desc = testBit (rdStatus desc) 0 isEndOfPacket :: ReceiveDescriptor -> Bool isEndOfPacket desc = testBit (rdStatus desc) 1 data TransmitDescriptor = TransmitRead { tdBufPhysAddr :: {-# UNPACK #-} !Word64 , tdCmdTypeLen :: {-# UNPACK #-} !Word32 , tdOlInfoStatus :: {-# UNPACK #-} !Word32 } | TransmitWriteback { tdStatus :: {-# UNPACK #-} !Word32 } instance Storable TransmitDescriptor where sizeOf _ = 16 alignment = sizeOf peek ptr = do status <- peekByteOff ptr 12 return TransmitWriteback {tdStatus = status} poke ptr (TransmitRead bufPhysAddr cmdTypeLen olInfoStatus) = do poke (castPtr ptr) bufPhysAddr pokeByteOff ptr 8 cmdTypeLen pokeByteOff ptr 12 olInfoStatus poke _ (TransmitWriteback _) = return $ panic "Cannot poke a writeback descriptor." nullTransmitDescriptor :: TransmitDescriptor nullTransmitDescriptor = TransmitRead {tdBufPhysAddr = 0, tdCmdTypeLen = 0, tdOlInfoStatus = 0} -- $ Memory allocateDescriptors :: (MonadThrow m, MonadIO m, MonadLogger m) => Int -> m (Ptr a) allocateDescriptors size = do descPtr <- allocateMem size True liftIO $ fillBytes descPtr 0xFF size return descPtr
null
https://raw.githubusercontent.com/ixy-languages/ixy.hs/4a24031adf9ba0737cebe1bb4f86bdf11fbf61c3/src/Lib/Ixgbe/Queue.hs
haskell
| Module : Lib.Ixgbe.Queue License : BSD3 Maintainer : Stability : experimental Portability : unknown Description $ Queues Setup the descriptors and buffers. $ Descriptors # UNPACK # # UNPACK # # UNPACK # # UNPACK # # UNPACK # # UNPACK # # UNPACK # # UNPACK # $ Memory
Copyright : 2018 module Lib.Ixgbe.Queue ( RxQueue(..) , TxQueue(..) , ReceiveDescriptor(..) , TransmitDescriptor(..) , mkRxQueue , mkTxQueue , numRxQueueEntries , numTxQueueEntries , nullReceiveDescriptor , isDone , isEndOfPacket , nullTransmitDescriptor , bufferSize , rxMap , rxGetMapping , txMap , txGetMapping ) where import Lib.Memory import Lib.Prelude import Control.Monad.Catch ( MonadThrow ) import Control.Monad.Logger import qualified Data.Array.IO as Array import Data.IORef import Foreign.Ptr ( castPtr , plusPtr ) import Foreign.Storable ( sizeOf , alignment , peek , poke , peekByteOff , pokeByteOff ) import Foreign.Marshal.Utils ( fillBytes ) numRxQueueEntries :: Int numRxQueueEntries = 512 numTxQueueEntries :: Int numTxQueueEntries = 512 bufferSize :: Int bufferSize = 2048 data RxQueue = RxQueue { rxqDescriptor :: Int -> Ptr ReceiveDescriptor , rxqMemPool :: !MemPool , rxqMap :: !(Array.IOUArray Int Int) , rxqIndexRef :: !(IORef Int) } mkRxQueue :: (MonadThrow m, MonadIO m, MonadLogger m) => m RxQueue mkRxQueue = do memPool <- mkMemPool $ (numRxQueueEntries + numTxQueueEntries) * 2 descPtr <- allocateDescriptors (numRxQueueEntries * sizeOf nullReceiveDescriptor) let descriptor i = descPtr `plusPtr` (i * sizeOf nullReceiveDescriptor) ids <- mapM (setupDescriptor memPool) [ descriptor i | i <- [0 .. numRxQueueEntries - 1] ] indexRef <- liftIO $ newIORef (0 :: Int) m <- liftIO $ Array.newListArray (0, numRxQueueEntries - 1) ids return $! RxQueue { rxqDescriptor = descriptor , rxqMemPool = memPool , rxqMap = m , rxqIndexRef = indexRef } where setupDescriptor memPool ptr = liftIO $ do buf <- peek =<< allocateBuf memPool let PhysAddr physAddr = pbAddr buf poke ptr ReceiveRead {rdBufPhysAddr = physAddr, rdHeaderAddr = 0} return $ pbId buf rxMap :: RxQueue -> Int -> Int -> IO () rxMap queue = Array.writeArray (rxqMap queue) rxGetMapping :: RxQueue -> Int -> IO Int rxGetMapping queue = Array.readArray (rxqMap queue) data TxQueue = TxQueue { txqDescriptor :: Int -> Ptr TransmitDescriptor , txqMap :: !(Array.IOUArray Int Int) , txqIndexRef :: !(IORef Int) , txqCleanRef :: !(IORef Int)} mkTxQueue :: (MonadThrow m, MonadIO m, MonadLogger m) => m TxQueue mkTxQueue = do descPtr <- allocateDescriptors (numTxQueueEntries * sizeOf nullTransmitDescriptor) indexRef <- liftIO $ newIORef (0 :: Int) cleanRef <- liftIO $ newIORef (0 :: Int) m <- liftIO $ Array.newArray_ (0, numTxQueueEntries - 1) let descriptor i = descPtr `plusPtr` (i * sizeOf nullTransmitDescriptor) return $! TxQueue { txqDescriptor = descriptor , txqMap = m , txqIndexRef = indexRef , txqCleanRef = cleanRef } txMap :: TxQueue -> Int -> Int -> IO () txMap queue = Array.writeArray (txqMap queue) txGetMapping :: TxQueue -> Int -> IO Int txGetMapping queue = Array.readArray (txqMap queue) instance Storable ReceiveDescriptor where sizeOf _ = 16 alignment = sizeOf peek ptr = do status <- peekByteOff ptr 8 len <- peekByteOff ptr 12 return ReceiveWriteback {rdStatus=status, rdLength=len} poke ptr (ReceiveRead bufPhysAddr headerAddr) = do poke (castPtr ptr) bufPhysAddr pokeByteOff ptr 8 headerAddr poke _ (ReceiveWriteback _ _) = return $ panic "Cannot poke a writeback descriptor." nullReceiveDescriptor :: ReceiveDescriptor nullReceiveDescriptor = ReceiveRead {rdBufPhysAddr = 0, rdHeaderAddr = 0} isDone :: ReceiveDescriptor -> Bool isDone desc = testBit (rdStatus desc) 0 isEndOfPacket :: ReceiveDescriptor -> Bool isEndOfPacket desc = testBit (rdStatus desc) 1 instance Storable TransmitDescriptor where sizeOf _ = 16 alignment = sizeOf peek ptr = do status <- peekByteOff ptr 12 return TransmitWriteback {tdStatus = status} poke ptr (TransmitRead bufPhysAddr cmdTypeLen olInfoStatus) = do poke (castPtr ptr) bufPhysAddr pokeByteOff ptr 8 cmdTypeLen pokeByteOff ptr 12 olInfoStatus poke _ (TransmitWriteback _) = return $ panic "Cannot poke a writeback descriptor." nullTransmitDescriptor :: TransmitDescriptor nullTransmitDescriptor = TransmitRead {tdBufPhysAddr = 0, tdCmdTypeLen = 0, tdOlInfoStatus = 0} allocateDescriptors :: (MonadThrow m, MonadIO m, MonadLogger m) => Int -> m (Ptr a) allocateDescriptors size = do descPtr <- allocateMem size True liftIO $ fillBytes descPtr 0xFF size return descPtr
d4b7cc6790c79a4dfc107049e90c03637264335bf03da3eeb78fdfcae68fae2d
alanz/ghc-exactprint
ModuleOnly.hs
module ModuleOnly where
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc710/ModuleOnly.hs
haskell
module ModuleOnly where
53a368f2b699fdef24771551a8a058fee38faaf128a29d73fda24d99c4a27700
nvim-treesitter/nvim-treesitter
injections.scm
[ (block_comment) (line_comment) ] @comment
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/f8595b13bff62d5c64d54840e16678b9ad843620/queries/java/injections.scm
scheme
[ (block_comment) (line_comment) ] @comment
8c9c316a985dd1e9091ea810d3bfd51c2afd19ef39d7049b30ae5d43cad34930
conreality/conreality
networking.ml
(* This is free and unencumbered software released into the public domain. *) open Prelude module UDP = struct #include "networking/udp.ml" end
null
https://raw.githubusercontent.com/conreality/conreality/e03328ef1f0056b58e4ffe181a279a1dc776e094/src/consensus/networking.ml
ocaml
This is free and unencumbered software released into the public domain.
open Prelude module UDP = struct #include "networking/udp.ml" end
396de98d2035cd5e1a5f2840a9bf1fb765fa27361b0d4ec1498cd0cdea2c3e42
bollu/koans
stm.hs
import Control.Monad.STM
null
https://raw.githubusercontent.com/bollu/koans/0204e9bb5ef9c541fe161523acac3cacae5d07fe/stm.hs
haskell
import Control.Monad.STM
02c970ae1ae2ee3f32442cc34e0aab2b05ff62e104bbdc3c9246eb6811814024
haskell-suite/base
Dynamic.hs
# LANGUAGE Trustworthy # # LANGUAGE CPP , NoImplicitPrelude # #ifdef __GLASGOW_HASKELL__ {-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Dynamic Copyright : ( c ) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- The Dynamic interface provides basic support for dynamic types . -- Operations for injecting values of arbitrary type into a dynamically typed value , Dynamic , are provided , together -- with operations for converting dynamic values into a concrete -- (monomorphic) type. -- ----------------------------------------------------------------------------- module Data.Dynamic ( Module Data . re - exported for convenience module Data.Typeable, -- * The @Dynamic@ type abstract , instance of : Show , -- * Converting to and from @Dynamic@ toDyn, fromDyn, fromDynamic, -- * Applying functions of dynamic type dynApply, dynApp, dynTypeRep ) where import Data.Typeable import Data.Maybe import Unsafe.Coerce #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.Show import GHC.Exception #endif #ifdef __HUGS__ import Hugs.Prelude import Hugs.IO import Hugs.IORef import Hugs.IOExts #endif #include "Typeable.h" ------------------------------------------------------------- -- The type Dynamic -- ------------------------------------------------------------- {-| A value of type 'Dynamic' is an object encapsulated together with its type. A 'Dynamic' may only represent a monomorphic value; an attempt to create a value of type 'Dynamic' from a polymorphically-typed expression will result in an ambiguity error (see 'toDyn'). 'Show'ing a value of type 'Dynamic' returns a pretty-printed representation of the object\'s type; useful for debugging. -} #ifndef __HUGS__ data Dynamic = Dynamic TypeRep Obj #endif INSTANCE_TYPEABLE0(Dynamic,dynamicTc,"Dynamic") instance Show Dynamic where -- the instance just prints the type representation. showsPrec _ (Dynamic t _) = showString "<<" . showsPrec 0 t . showString ">>" #ifdef __GLASGOW_HASKELL__ -- here so that it isn't an orphan: instance Exception Dynamic #endif #ifdef __GLASGOW_HASKELL__ type Obj = Any Use GHC 's primitive ' Any ' type to hold the dynamically typed value . -- In GHC 's new eval / apply execution model this type must not look like a data type . If it did , GHC would use the constructor convention -- when evaluating it, and this will go wrong if the object is really a function . Using Any forces GHC to use -- a fallback convention for evaluating it that works for all types. #elif !defined(__HUGS__) data Obj = Obj #endif -- | Converts an arbitrary value into an object of type 'Dynamic'. -- The type of the object must be an instance of ' ' , which -- ensures that only monomorphically-typed objects may be converted to -- 'Dynamic'. To convert a polymorphic object into 'Dynamic', give it -- a monomorphic type signature. For example: -- -- > toDyn (id :: Int -> Int) -- toDyn :: Typeable a => a -> Dynamic toDyn v = Dynamic (typeOf v) (unsafeCoerce v) | Converts a ' Dynamic ' object back into an ordinary value of -- the correct type. See also 'fromDynamic'. fromDyn :: Typeable a => Dynamic -- ^ the dynamically-typed object -> a -- ^ a default value ^ returns : the value of the first argument , if -- it has the correct type, otherwise the value of the second argument . fromDyn (Dynamic t v) def | typeOf def == t = unsafeCoerce v | otherwise = def | Converts a ' Dynamic ' object back into an ordinary value of -- the correct type. See also 'fromDyn'. fromDynamic :: Typeable a => Dynamic -- ^ the dynamically-typed object -> Maybe a -- ^ returns: @'Just' a@, if the dynamically-typed -- object has the correct type (and @a@ is its value), -- or 'Nothing' otherwise. fromDynamic (Dynamic t v) = case unsafeCoerce v of r | t == typeOf r -> Just r | otherwise -> Nothing ( f::(a->b ) ) ` dynApply ` ( x::a ) = ( f dynApply :: Dynamic -> Dynamic -> Maybe Dynamic dynApply (Dynamic t1 f) (Dynamic t2 x) = case funResultTy t1 t2 of Just t3 -> Just (Dynamic t3 ((unsafeCoerce f) x)) Nothing -> Nothing dynApp :: Dynamic -> Dynamic -> Dynamic dynApp f x = case dynApply f x of Just r -> r Nothing -> error ("Type error in dynamic application.\n" ++ "Can't apply function " ++ show f ++ " to argument " ++ show x) dynTypeRep :: Dynamic -> TypeRep dynTypeRep (Dynamic tr _) = tr
null
https://raw.githubusercontent.com/haskell-suite/base/1ee14681910c76d0a5a436c33ecf3289443e65ed/Data/Dynamic.hs
haskell
# LANGUAGE DeriveDataTypeable, StandaloneDeriving # --------------------------------------------------------------------------- | Module : Data.Dynamic License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : portable with operations for converting dynamic values into a concrete (monomorphic) type. --------------------------------------------------------------------------- * The @Dynamic@ type * Converting to and from @Dynamic@ * Applying functions of dynamic type ----------------------------------------------------------- ----------------------------------------------------------- | A value of type 'Dynamic' is an object encapsulated together with its type. A 'Dynamic' may only represent a monomorphic value; an attempt to create a value of type 'Dynamic' from a polymorphically-typed expression will result in an ambiguity error (see 'toDyn'). 'Show'ing a value of type 'Dynamic' returns a pretty-printed representation of the object\'s type; useful for debugging. the instance just prints the type representation. here so that it isn't an orphan: when evaluating it, and this will go wrong if the object is really a a fallback convention for evaluating it that works for all types. | Converts an arbitrary value into an object of type 'Dynamic'. ensures that only monomorphically-typed objects may be converted to 'Dynamic'. To convert a polymorphic object into 'Dynamic', give it a monomorphic type signature. For example: > toDyn (id :: Int -> Int) the correct type. See also 'fromDynamic'. ^ the dynamically-typed object ^ a default value it has the correct type, otherwise the value of the correct type. See also 'fromDyn'. ^ the dynamically-typed object ^ returns: @'Just' a@, if the dynamically-typed object has the correct type (and @a@ is its value), or 'Nothing' otherwise.
# LANGUAGE Trustworthy # # LANGUAGE CPP , NoImplicitPrelude # #ifdef __GLASGOW_HASKELL__ #endif Copyright : ( c ) The University of Glasgow 2001 The Dynamic interface provides basic support for dynamic types . Operations for injecting values of arbitrary type into a dynamically typed value , Dynamic , are provided , together module Data.Dynamic ( Module Data . re - exported for convenience module Data.Typeable, abstract , instance of : Show , toDyn, fromDyn, fromDynamic, dynApply, dynApp, dynTypeRep ) where import Data.Typeable import Data.Maybe import Unsafe.Coerce #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.Show import GHC.Exception #endif #ifdef __HUGS__ import Hugs.Prelude import Hugs.IO import Hugs.IORef import Hugs.IOExts #endif #include "Typeable.h" The type Dynamic #ifndef __HUGS__ data Dynamic = Dynamic TypeRep Obj #endif INSTANCE_TYPEABLE0(Dynamic,dynamicTc,"Dynamic") instance Show Dynamic where showsPrec _ (Dynamic t _) = showString "<<" . showsPrec 0 t . showString ">>" #ifdef __GLASGOW_HASKELL__ instance Exception Dynamic #endif #ifdef __GLASGOW_HASKELL__ type Obj = Any Use GHC 's primitive ' Any ' type to hold the dynamically typed value . In GHC 's new eval / apply execution model this type must not look like a data type . If it did , GHC would use the constructor convention function . Using Any forces GHC to use #elif !defined(__HUGS__) data Obj = Obj #endif The type of the object must be an instance of ' ' , which toDyn :: Typeable a => a -> Dynamic toDyn v = Dynamic (typeOf v) (unsafeCoerce v) | Converts a ' Dynamic ' object back into an ordinary value of fromDyn :: Typeable a ^ returns : the value of the first argument , if the second argument . fromDyn (Dynamic t v) def | typeOf def == t = unsafeCoerce v | otherwise = def | Converts a ' Dynamic ' object back into an ordinary value of fromDynamic :: Typeable a fromDynamic (Dynamic t v) = case unsafeCoerce v of r | t == typeOf r -> Just r | otherwise -> Nothing ( f::(a->b ) ) ` dynApply ` ( x::a ) = ( f dynApply :: Dynamic -> Dynamic -> Maybe Dynamic dynApply (Dynamic t1 f) (Dynamic t2 x) = case funResultTy t1 t2 of Just t3 -> Just (Dynamic t3 ((unsafeCoerce f) x)) Nothing -> Nothing dynApp :: Dynamic -> Dynamic -> Dynamic dynApp f x = case dynApply f x of Just r -> r Nothing -> error ("Type error in dynamic application.\n" ++ "Can't apply function " ++ show f ++ " to argument " ++ show x) dynTypeRep :: Dynamic -> TypeRep dynTypeRep (Dynamic tr _) = tr
2dddd6b0b1a6cc5fa784cdd2a6b50c9b112d2e6a76240ca69fdaac535b64143b
prepor/condo
condo_docker.mli
open! Core.Std open! Async.Std type t type id [@@deriving sexp, yojson] val create : endpoint:Async_http.addr -> config_path:string option -> t Deferred.t val reload_config : t -> unit Deferred.t val start : t -> name:string -> spec:Yojson.Safe.json -> (id, string) Result.t Deferred.t val stop : t -> id -> timeout:int -> unit Deferred.t val wait_healthchecks : t -> id -> timeout:int -> [`Passed | `Not_passed] Deferred.t val is_running : t -> id -> bool Deferred.t
null
https://raw.githubusercontent.com/prepor/condo/b9a16829e6ffef10df2fefdadf143b56d33f0b97/src/condo_docker.mli
ocaml
open! Core.Std open! Async.Std type t type id [@@deriving sexp, yojson] val create : endpoint:Async_http.addr -> config_path:string option -> t Deferred.t val reload_config : t -> unit Deferred.t val start : t -> name:string -> spec:Yojson.Safe.json -> (id, string) Result.t Deferred.t val stop : t -> id -> timeout:int -> unit Deferred.t val wait_healthchecks : t -> id -> timeout:int -> [`Passed | `Not_passed] Deferred.t val is_running : t -> id -> bool Deferred.t
1b8a2d561ffc6a28fb259d162080c0f6782b06157a3509b281c6631176883164
gregwebs/Shelly.hs
FailureSpec.hs
module FailureSpec ( failureSpec ) where import TestInit failureSpec :: Spec failureSpec = do let discardException action = shellyFailDir $ catchany_sh action (\_ -> return ()) describe "failure set to stderr" $ it "writes a failure message to stderr" $ do shellyFailDir $ discardException $ liftIO $ shelly $ do test_d ".shelly" >>= liftIO . assert . not echo "testing" error "bam!" assert . not =<< shellyFailDir (test_d ".shelly") describe "failure set to directory" $ it "writes a failure message to a .shelly directory" $ do shellyFailDir $ discardException $ shellyFailDir $ do test_d ".shelly" >>= liftIO . assert . not echo "testing" error "bam!" assert =<< shellyFailDir ( do exists <- test_d ".shelly" rm_rf ".shelly" return exists )
null
https://raw.githubusercontent.com/gregwebs/Shelly.hs/f11409cf565b782f05576a489b137fd98d3877ca/test/src/FailureSpec.hs
haskell
module FailureSpec ( failureSpec ) where import TestInit failureSpec :: Spec failureSpec = do let discardException action = shellyFailDir $ catchany_sh action (\_ -> return ()) describe "failure set to stderr" $ it "writes a failure message to stderr" $ do shellyFailDir $ discardException $ liftIO $ shelly $ do test_d ".shelly" >>= liftIO . assert . not echo "testing" error "bam!" assert . not =<< shellyFailDir (test_d ".shelly") describe "failure set to directory" $ it "writes a failure message to a .shelly directory" $ do shellyFailDir $ discardException $ shellyFailDir $ do test_d ".shelly" >>= liftIO . assert . not echo "testing" error "bam!" assert =<< shellyFailDir ( do exists <- test_d ".shelly" rm_rf ".shelly" return exists )
75d8f8612d05e2ca8a69dda1e9ee80e6693ca5677991019b5435ccc9be9fcf1c
adomokos/haskell-katas
Ex11_FlowRecursionsSpec.hs
module Solutions.Ex11_FlowRecursionsSpec ( spec ) where import Test.Hspec main :: IO () main = hspec spec maximum' :: (Ord a) => [a] -> a maximum' [x] = x maximum' (x:xs) = x `max` maximum' xs replicate' :: Int -> a -> [a] replicate' 1 x = [x] replicate' n x = x : replicate' (n - 1) x take' :: Int -> [a] -> [a] take' 0 _ = [] take' n (x:xs) = x : take' (n - 1) xs reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = reverse' xs ++ [x] repeat' :: a -> [a] repeat' x = x : repeat' x zip' :: [a] -> [b] -> [(a, b)] zip' [] _ = [] zip' _ [] = [] zip' (x:xs) (y:ys) = (x, y) : zip' xs ys myElem :: (Eq a) => a -> [a] -> Bool myElem _ [] = False myElem x (y:ys) = (x == y) || myElem x ys quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = lowersorted ++ [x] ++ highersorted where lowersorted = quicksort [a | a <- xs, a <= x] highersorted = quicksort [a | a <- xs, a > x] spec :: Spec spec = describe "Recursion" $ do it "calculates maximum" $ maximum' [2, 5, 1] `shouldBe` 5 it "replicates items" $ replicate' 5 'a' `shouldBe` "aaaaa" it "takes from a collection" $ take' 3 "abcde" `shouldBe` "abc" it "reverses a collection" $ reverse' [1, 2, 3] `shouldBe` [3, 2, 1] it "can repeat items" $ take' 3 (repeat' 'a') `shouldBe` "aaa" it "can zip items" $ zip' [1, 2, 3] ['a', 'b'] `shouldBe` [(1, 'a'), (2, 'b')] it "can check if an item is an element of a list" $ myElem 3 [1, 2, 3] `shouldBe` True it "can do QuickSort - easily" $ do quicksort [3, 1, 2] `shouldBe` [1, 2, 3] quicksort "attila" `shouldBe` "aailtt"
null
https://raw.githubusercontent.com/adomokos/haskell-katas/be06d23192e6aca4297814455247fc74814ccbf1/test/Solutions/Ex11_FlowRecursionsSpec.hs
haskell
module Solutions.Ex11_FlowRecursionsSpec ( spec ) where import Test.Hspec main :: IO () main = hspec spec maximum' :: (Ord a) => [a] -> a maximum' [x] = x maximum' (x:xs) = x `max` maximum' xs replicate' :: Int -> a -> [a] replicate' 1 x = [x] replicate' n x = x : replicate' (n - 1) x take' :: Int -> [a] -> [a] take' 0 _ = [] take' n (x:xs) = x : take' (n - 1) xs reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = reverse' xs ++ [x] repeat' :: a -> [a] repeat' x = x : repeat' x zip' :: [a] -> [b] -> [(a, b)] zip' [] _ = [] zip' _ [] = [] zip' (x:xs) (y:ys) = (x, y) : zip' xs ys myElem :: (Eq a) => a -> [a] -> Bool myElem _ [] = False myElem x (y:ys) = (x == y) || myElem x ys quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = lowersorted ++ [x] ++ highersorted where lowersorted = quicksort [a | a <- xs, a <= x] highersorted = quicksort [a | a <- xs, a > x] spec :: Spec spec = describe "Recursion" $ do it "calculates maximum" $ maximum' [2, 5, 1] `shouldBe` 5 it "replicates items" $ replicate' 5 'a' `shouldBe` "aaaaa" it "takes from a collection" $ take' 3 "abcde" `shouldBe` "abc" it "reverses a collection" $ reverse' [1, 2, 3] `shouldBe` [3, 2, 1] it "can repeat items" $ take' 3 (repeat' 'a') `shouldBe` "aaa" it "can zip items" $ zip' [1, 2, 3] ['a', 'b'] `shouldBe` [(1, 'a'), (2, 'b')] it "can check if an item is an element of a list" $ myElem 3 [1, 2, 3] `shouldBe` True it "can do QuickSort - easily" $ do quicksort [3, 1, 2] `shouldBe` [1, 2, 3] quicksort "attila" `shouldBe` "aailtt"
d919add3dd01d82e48ad146d3080c22e8cdc15d7790266ef333e6ee7f43b5bbd
jordanthayer/ocaml-search
mean_sol_time.ml
* @author jtd7 @since 2012 - 01 - 24 @author jtd7 @since 2012-01-24 *) let get_mean_time dset = let times = Dataset.get_values float_of_string "raw cpu time" dset in let values = ref [] in for i = ((Array.length times) - 1) downto 1 do values := (times.(i) -. times.(i-1))::!values done; (1800. -. times.((Array.length times) - 1))::!values let sol_count dset = let times = Dataset.get_values float_of_string "raw cpu time" dset in Array.length times let rec append l1 = function | [] -> l1 | hd::tl -> append (hd::l1) tl let do_alg_time dset = let dsets = Dataset.group_by [|"num"|] dset in let values = List.map get_mean_time dsets in let all_vals = List.fold_left append [] values in let total = List.fold_left (+.) 0. all_vals in total /. (float (List.length all_vals)) let do_alg_count dset = let dsets = Dataset.group_by [|"num"|] dset in let values = List.map sol_count dsets in let total = List.fold_left (+) 0 values in (float total) /. (float (List.length values)) let do_domain_time loader alg_list = let dsets = List.map (fun alg -> loader ["alg", alg] alg) alg_list in List.iter2 (fun dset nm -> let mean = do_alg_time dset in Printf.printf "%s\t%f\n%!" nm mean) dsets alg_list let do_domain_count loader alg_list = let dsets = List.map (fun alg -> loader ["alg", alg] alg) alg_list in List.iter2 (fun dset nm -> let mean = do_alg_count dset in Printf.printf "%s\t%f\n%!" nm mean) dsets alg_list
null
https://raw.githubusercontent.com/jordanthayer/ocaml-search/57cfc85417aa97ee5d8fbcdb84c333aae148175f/spt_plot/scripts/jtd7/mean_sol_time.ml
ocaml
* @author jtd7 @since 2012 - 01 - 24 @author jtd7 @since 2012-01-24 *) let get_mean_time dset = let times = Dataset.get_values float_of_string "raw cpu time" dset in let values = ref [] in for i = ((Array.length times) - 1) downto 1 do values := (times.(i) -. times.(i-1))::!values done; (1800. -. times.((Array.length times) - 1))::!values let sol_count dset = let times = Dataset.get_values float_of_string "raw cpu time" dset in Array.length times let rec append l1 = function | [] -> l1 | hd::tl -> append (hd::l1) tl let do_alg_time dset = let dsets = Dataset.group_by [|"num"|] dset in let values = List.map get_mean_time dsets in let all_vals = List.fold_left append [] values in let total = List.fold_left (+.) 0. all_vals in total /. (float (List.length all_vals)) let do_alg_count dset = let dsets = Dataset.group_by [|"num"|] dset in let values = List.map sol_count dsets in let total = List.fold_left (+) 0 values in (float total) /. (float (List.length values)) let do_domain_time loader alg_list = let dsets = List.map (fun alg -> loader ["alg", alg] alg) alg_list in List.iter2 (fun dset nm -> let mean = do_alg_time dset in Printf.printf "%s\t%f\n%!" nm mean) dsets alg_list let do_domain_count loader alg_list = let dsets = List.map (fun alg -> loader ["alg", alg] alg) alg_list in List.iter2 (fun dset nm -> let mean = do_alg_count dset in Printf.printf "%s\t%f\n%!" nm mean) dsets alg_list
1c92478e2d87004d7a6419bcf13d527ea403b49817f73eaaab2e27791085dc1d
blambo/accelerate-repa
Evaluations.hs
# LANGUAGE CPP , GADTs , BangPatterns , TypeOperators , PatternGuards # # LANGUAGE TypeFamilies , ScopedTypeVariables , FlexibleContexts # # LANGUAGE TypeSynonymInstances , FlexibleInstances , RankNTypes # -- | Module : Data . Array . Accelerate . . Evaluations -- Maintainer : < blambo+ > -- Defines the code generation for Acc , Exp and Fun nodes into code module Data.Array.Accelerate.Repa.Evaluations ( evalAcc ) where import Data.Typeable import Text.PrettyPrint import Data.Array.Accelerate.AST import Data.Array.Accelerate.Array.Sugar as Sugar import Data.Array.Accelerate.Tuple import Data.Array.Accelerate.Type import qualified Data.Array.Accelerate.Array.Representation as Repr import Data.Array.Accelerate.Repa.Evaluations.Prim import Data.Array.Accelerate.Repa.Traverse --------------- ACC NODES -- --------------- evalAcc :: forall a. Acc a -> Doc evalAcc acc = parsedS where RepaAcc parsedS = evalOpenAcc acc 0 | Unpacks AST by removing ' OpenAcc ' shell evalOpenAcc :: forall aenv a. OpenAcc aenv a -> Int -> RepaAcc evalOpenAcc (OpenAcc acc) = evalPreOpenAcc acc -- | Traverses over AST evalPreOpenAcc :: forall aenv a. PreOpenAcc OpenAcc aenv a -> Int -> RepaAcc evalPreOpenAcc (Let acc1 acc2) letLevel = RepaAcc returnDoc where RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 (letLevel+1) var = char 'y' <> int letLevel returnDoc = text "let" <+> var <+> equals <+> parens arr1 $$ text "in" $$ nest 1 arr2 evalPreOpenAcc (Let2 acc1 acc2) letLevel = RepaAcc returnDoc where RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 (letLevel+2) var1 = char 'y' <> int letLevel var2 = char 'y' <> int (letLevel + 1) returnDoc = text "let" <+> parens (var1 <> comma <+> var2) <+> equals <+> (parens $ nest 1 arr1) $$ text "in" $$ nest 1 arr2 evalPreOpenAcc (PairArrays acc1 acc2) letLevel = RepaAcc returnDoc where RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 letLevel returnDoc = parens (parens arr1 <> comma <+> parens arr2) evalPreOpenAcc (Avar idx) letLevel = RepaAcc var where var = char 'y' <> int (letLevel - varNum - 1) varNum = getVarNum idx evalPreOpenAcc (Apply (Alam (Abody funAcc)) acc) letLevel = RepaAcc $ returnDoc where RepaAcc fun = evalOpenAcc funAcc (1) RepaAcc arr = evalOpenAcc acc letLevel var = char 'y' <> int 0 tempVar = char 'y' returnDoc = text "let" <+> tempVar <+> equals <+> parens arr $$ text "in" $$ nest 1 (text "let" <+> var <+> equals <+> tempVar $$ text "in" $$ nest 1 fun) evalPreOpenAcc (Apply _afun _acc) _letLevel = error "GHC pattern matching does not detect that this case is impossible" evalPreOpenAcc (Acond cond acc1 acc2) letLevel = RepaAcc returnDoc where exp = toDoc $ evalExp cond letLevel RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 letLevel returnDoc = text "if" <+> exp $$ text "then" $$ (nest 1 arr1) $$ text "else" $$ (nest 1 arr2) evalPreOpenAcc (Use arr@(Array sh e)) letLevel = RepaAcc returnDoc where shS = printShape sh arrL = toList arr arrData = text $ show $ arrL listType = text $ (showsTypeRep $ typeOf $ arrL) "" returnDoc = text "fromListUnboxed" <+> parens shS <+> parens (arrData <+> colon <> colon <+> listType) evalPreOpenAcc (Unit e) letLevel = RepaAcc returnDoc where exp = toDoc $ evalExp e letLevel returnDoc = text "fromListUnboxed Z" <+> brackets exp evalPreOpenAcc (Reshape e acc) letLevel = RepaAcc returnDoc where RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "reshape" <+> parens exp <+> parens arr evalPreOpenAcc (Generate sh f) letLevel = RepaAcc returnDoc where exp = toDoc $ evalExp sh letLevel RepaAcc fun = evalFun f letLevel returnDoc = text "fromFunction" <+> parens exp <+> parens fun -- Not sure why sliceIndex is not required? evalPreOpenAcc (Replicate sliceIndex slix acc) letLevel = RepaAcc $ returnDoc where slixD = toDoc $ evalExp slix letLevel RepaAcc arrD = evalOpenAcc acc letLevel returnDoc = text "extend" <+> parens slixD <+> parens arrD -- Not sure why sliceIndex is not required? evalPreOpenAcc (Index sliceIndex acc slix) letLevel = RepaAcc $ returnDoc where slixD = toDoc $ evalExp slix letLevel RepaAcc arrD = evalOpenAcc acc letLevel returnDoc = text "slice" <+> parens arrD <+> parens slixD evalPreOpenAcc (Map f acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel returnDoc = text "Repa.map" <+> (parens fun $$ parens arr) Reversing order of acc1 and acc2 seems to fix some issues , will need to -- test more extensively with differing typed arrays to insure no errors evalPreOpenAcc (ZipWith f acc1 acc2) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 letLevel returnDoc = text "Repa.zipWith" <+> (parens fun $$ parens arr2 $$ parens arr1) TODO : Specialise to parallel fold ' foldP ' as 's restrictions for this fold is same as Accelerate 's evalPreOpenAcc (Fold f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel exp = toDoc $ evalExp e letLevel RepaAcc arr = evalOpenAcc acc letLevel returnDoc = text "fold" <+> (parens fun $$ parens exp $$ parens arr) TODO : No foldr1 function in Repa 3 , change to foldP ? evalPreOpenAcc (Fold1 f acc) letLevel = RepaAcc $ returnDoc where RepaAcc combD = evalFun f letLevel RepaAcc srcArrD = evalOpenAcc acc letLevel newShapeD = parens $ text "\\(sh:._) -> sh" genElemD = parens $ text "\\lookup pos ->" <+> (text "let (_:.end) = extent srcArr" $$ text "in foldr1 comb" $$ nest 1 (text "$ Prelude.map (lookup) [(pos:.i) | i <- [0..(end-1)]]")) returnDoc = text "let" <+> (text "srcArr =" <+> srcArrD $$ text "comb =" <+> combD) $$ text "in traverse" <+> (parens srcArrD $$ newShapeD $$ genElemD) -- TODO: Tidy generated code evalPreOpenAcc (FoldSeg f e acc1 acc2) letLevel = RepaAcc $ returnDoc where RepaAcc funD = evalFun f letLevel expD = toDoc $ evalExp e letLevel RepaAcc arrD = evalOpenAcc acc1 letLevel RepaAcc segD = evalOpenAcc acc2 letLevel returnDoc = letD $$ foldSegD letD = text "let" <+> (text "arr =" <+> arrD $$ text "f =" <+> funD $$ text "seg =" <+> segD $$ text "e =" <+> expD $$ helpers) $$ text "in" foldSegD = text "traverse arr (\\_ -> (sh:.ix)) foldOne" helpers = text "(sh:._) = arrayExtent arr" $$ text "(_:.ix) = arrayExtent seg" $$ text "starts :: Array DIM1 Int" $$ text "starts =" <+> (text "let res =" <+> (text "traverse seg (\\(Z:.i) -> (Z:.(i+1)))" $$ parens (text "let newVal orig (Z:.pos)" <+> (text "| pos == 0 = 0" $$ text "| otherwise = (newVal orig (Z:.(pos-1))) + (orig (Z:.(pos-1)))") $$ text "in newVal")) $$ text "in" $$ nest 1 (text "traverse res (\\(Z:.i) -> (Z:.(i-1))) (\\orig (Z:.pos) -> orig (Z:.pos))")) $$ text "foldOne lookup (sh:.ix) =" <+> (text "let" <+> (text "start = starts ! (Z:.ix)" $$ text "len = seg ! (Z:.ix)") $$ text "in foldSeg' sh e start (start+len)") $$ text "foldSeg' sh val start end" $$ nest 1 (text "| start >= end = val" $$ text "| otherwise = foldSeg' sh (f val (arr ! (sh:.start))) (start+1) end") -- TODO: Tidy up code evalPreOpenAcc (Fold1Seg f acc1 acc2) letLevel = RepaAcc $ returnDoc where RepaAcc funD = evalFun f letLevel RepaAcc arrD = evalOpenAcc acc1 letLevel RepaAcc segD = evalOpenAcc acc2 letLevel returnDoc = letD $$ fold1SegD letD = text "let" <+> (text "arr =" <+> arrD $$ text "f =" <+> funD $$ text "seg =" <+> segD $$ helpers) $$ text "in" fold1SegD = text "traverse arr (\\_ -> (sh:.ix)) foldOne" helpers = text "(sh:._) = arrayExtent arr" $$ text "(_:.ix) = arrayExtent seg" $$ text "starts :: Array DIM1 Int" $$ text "starts =" <+> (text "let res =" <+> (text "traverse seg (\\(Z:.i) -> (Z:.(i+1)))" $$ parens (text "let newVal orig (Z:.pos)" <+> (text "| pos == 0 = 0" $$ text "| otherwise = (newVal orig (Z:.(pos-1))) + (orig (Z:.(pos-1)))") $$ text "in newVal")) $$ text "in" $$ nest 1 (text "traverse res (\\(Z:.i) -> (Z:.(i-1))) (\\orig (Z:.pos) -> orig (Z:.pos))")) $$ text "foldOne lookup (sh:.ix) =" <+> (text "let" <+> (text "start = starts ! (Z:.ix)" $$ text "len = seg ! (Z:.ix)") $$ text "in foldSeg' sh (arr ! (sh:.start)) (start+1) (start+len)") $$ text "foldSeg' sh val start end" $$ nest 1 (text "| start >= end = val" $$ text "| otherwise = foldSeg' sh (f val (arr ! (sh:.start))) (start+1) end") evalPreOpenAcc (Scanl f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "traverse" <+> (parens arr $$ parens shapeDoc $$ parens newValDoc) shapeDoc = text "\\(Z:.i) -> (Z:.(i+1))" newValDoc = text "let newVal orig (Z:.pos)" <+> ((text "| pos == 0" <+> equals <+> exp) $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos-1))") $$ parens (text "orig (Z:.(pos-1))")))) $$ text "in newVal" evalPreOpenAcc (Scanl' f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "let res = traverse" <+> (parens arr $$ parens shapeDoc $$ parens newValDoc) $$ text "in" <+> tuple tuple = parens (first <> comma <+> second) first = text "traverse res (\\(Z:.i) -> (Z:.(i-1))) (\\orig sh -> orig sh)" second = text "fromList Z [(res!(Z:.((size $ extent res)-1)))]" shapeDoc = text "\\(Z:.i) -> (Z:.(i+1))" newValDoc = text "let newVal orig (Z:.pos)" <+> ((text "| pos == 0" <+> equals <+> exp) $$ nest 1 (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos-1))") $$ parens (text "orig (Z:.(pos-1))")))) $$ text "in newVal" evalPreOpenAcc (Scanl1 f acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel returnDoc = text "traverse" <+> (parens arr $$ text "(id)" $$ parens newValDoc) newValDoc = text "let newVal orig sh@(Z:.pos)" <+> ((text "| pos == 0" <+> equals <+> text "orig sh") $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos-1))") $$ parens (text "orig sh")))) $$ text "in newVal" evalPreOpenAcc (Scanr f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "traverse" <+> (parens arr $$ shapeDoc $$ parens newValDoc) shapeDoc = parens $ text "\\(Z:.i) -> (Z:.(i+1))" newValDoc = text "let newVal orig sh@(Z:.pos)" <+> ((text "| pos ==" <+> last <+> equals <+> exp) $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos+1))") $$ parens (text "orig sh")))) $$ text "in newVal" last = parens $ text "size $ extent $" <+> arr evalPreOpenAcc (Scanr' f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "let res" <+> equals <+> text "traverse" <+> (parens arr $$ parens shapeDoc $$ parens newVarDoc) $$ text "in" <+> tuple tuple = parens (first $$ comma $$ second) first = text "traverse res (\\(Z:.i) -> (Z:.(i-1)))" <+> (parens $ text "\\orig (Z:.pos) -> orig (Z:.(pos+1))") second = text "fromList Z [(res!(Z:.0))]" shapeDoc = text "\\(Z:.i) -> (Z:.(i+1))" newVarDoc = text "let newVal orig sh@(Z:.pos)" <+> ((text "| pos ==" <+> last <+> equals <+> exp) $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos+1))") $$ parens (text "orig sh")))) $$ text "in newVal" last = parens $ text "size $ extent $" <+> arr evalPreOpenAcc (Scanr1 f acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel returnDoc = text "traverse" <+> (parens arr $$ shapeDoc $$ parens newVarDoc) shapeDoc = parens $ text "id" newVarDoc = text "let newVal orig sh@(Z:.pos)" <+> ((text "| pos ==" <+> parens last <+> text "- 1" <+> equals <+> text "orig sh") $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos+1))") $$ parens (text "orig sh")))) $$ text "in newVal" last = parens $ text "size $ extent $" <+> arr evalPreOpenAcc (Permute f dftAcc p acc) letLevel = RepaAcc $ returnDoc where RepaAcc dftArrD = evalOpenAcc dftAcc letLevel RepaAcc srcArrD = evalOpenAcc acc letLevel RepaAcc combD = evalFun f letLevel RepaAcc permD = evalFun p letLevel returnDoc = text "let" <+> (text "srcArr =" <+> srcArrD $$ text "dftArr =" <+> dftArrD $$ text "perm =" <+> (parens permD) $$ text "comb =" <+> (parens combD) $$ permuteDoc) $$ text "in" $$ nest 1 (text "permute 0 comb dftArr perm srcArr") permuteDoc = text "permute idx comb dftArr perm srcArr" $$ nest 1 (text "| idx >= (size $ extent srcArr) = dftArr" $$ text "| otherwise =" <+> permuteArgsDoc) permuteArgsDoc = text "let" <+> (text "(Z:.srcIdx) = fromIndex (extent srcArr) idx" $$ text "newArr = fromFunction" <+> (text "(extent dftArr)" $$ text "(\\sh -> case sh == (perm srcIdx) of" $$ nest 1 (text "True -> (dftArr ! (perm srcIdx)) `comb`" <+> text "(srcArr ! (Z:.srcIdx))" $$ text "False -> index dftArr sh)"))) $$ text "in permute (idx+1) comb newArr perm srcArr" evalPreOpenAcc (Backpermute e p acc) letLevel = RepaAcc $ returnDoc where returnDoc = text "backpermute" <+> parens expD <+> parens permD <+> parens srcArrD expD = toDoc $ evalExp e letLevel RepaAcc permD = evalFun p letLevel RepaAcc srcArrD = evalOpenAcc acc letLevel evalPreOpenAcc (Stencil sten bndy acc) letLevel = RepaAcc $ returnDoc where RepaAcc funD = evalFun sten letLevel RepaAcc arrD = evalOpenAcc acc letLevel bndyD = evalBoundary acc bndy returnDoc = letD $$ traverseD letD = text "let" <+> (text "arr =" <+> arrD $$ text "bndy =" <+> bndyD $$ text "sten =" <+> parens funD) $$ text "in" traverseD = text "traverse" <+> (text "arr" $$ text "id" $$ text "(\\lookup curr -> sten $ stencilData (bound lookup bndy (arrayExtent arr)) curr)") evalPreOpenAcc (Stencil2 sten bndy1 acc1 bndy2 acc2) letLevel = RepaAcc $ returnDoc where RepaAcc stenD = evalFun sten letLevel RepaAcc arr1D = evalOpenAcc acc1 letLevel RepaAcc arr2D = evalOpenAcc acc2 letLevel bndy1D = evalBoundary acc1 bndy1 bndy2D = evalBoundary acc2 bndy2 returnDoc = letD $$ traverseD letD = text "let" <+> (text "arr1 =" <+> arr1D $$ text "bndy1 =" <+> bndy1D $$ text "arr2 =" <+> arr2D $$ text "bndy2 =" <+> bndy2D $$ text "sten =" <+> parens stenD) $$ text "in" traverseD = text "traverse2" <+> (text "arr1" $$ text "arr2" $$ text "(\\a _ -> a)" $$ parens (text "\\lookup1 lookup2 curr ->" <+> (text "sten" <+> (parens (text "stencilData (bound lookup1 bndy1 (arrayExtent arr1)) curr") $$ parens (text "stencilData (bound lookup2 bndy2 (arrayExtent arr2)) curr"))))) evalPreOpenAcc _ _ = RepaAcc $ text "<UNDEFINED>" -------------------- -- FUNCTION NODES -- -------------------- evalFun :: Fun aenv t -> Int -> RepaAcc evalFun f letL = evalOpenFun f 0 letL empty evalOpenFun :: OpenFun env aenv t -> Int -> Int -> Doc -> RepaAcc evalOpenFun (Body e) lamL letL binds = RepaAcc $ binds <+> parens (toDoc $ evalOpenExp e lamL letL) evalOpenFun (Lam f) lamL letL binds = funD where funD = evalOpenFun f (lamL+1) letL (varBind <+> binds) varBind = text "\\x" <> int lamL <+> text "->" ---------------------- EXPRESSION NODES -- ---------------------- -- Evaluate an open expression evalOpenExp :: forall a env aenv . OpenExp env aenv a -> Int -> Int -> RepaExp evalOpenExp var@(Var idx) lamL letL -- = RepaExp $ parens (char 'x' <> int varNum <+> colon <> colon <+> typeD) = RepaExp $ parens (char 'x' <> int varNum) where varNum = lamL - (getVarNum idx) - 1 typeD = expToString (var) evalOpenExp (Const c) _ _ = RepaExp $ val where val = let val' = text $ show ((Sugar.toElt c) :: a) in case typeS of ('D':'a':'t':'a':_) -> val' otherwise -> val' <+> colon <> colon <+> (text typeS) typeS = (showsTypeRep $ typeOf ((Sugar.toElt c) :: a)) "" evalOpenExp (Tuple tup) lamL letL = evalTuple tup lamL letL evalOpenExp (Prj idx e) lamL letL = RepaExp $ text "let" <+> parens prjS <+> equals <+> parens expS <+> text "in" <+> prjVarName where prjS = evalPrj (tupSize $ parseTupleType $ expType e) (tupIdx idx) expS = toDoc $ evalOpenExp e lamL letL evalOpenExp IndexNil _ _ = RepaExp $ char 'Z' evalOpenExp (IndexCons sh i) lamL letL = RepaExp $ shS <+> text ":." <+> parens ix where shS = toDoc $ evalOpenExp sh lamL letL ix = toDoc $ evalOpenExp i lamL letL evalOpenExp (IndexHead ix) lamL letL = RepaExp $ text "case" <+> parens exp <+> text "of (_:.h) -> h" where exp = toDoc $ evalOpenExp ix lamL letL evalOpenExp (IndexTail ix) lamL letL = RepaExp $ text "case" <+> parens exp <+> text "of (t:._) -> t" where exp = toDoc $ evalOpenExp ix lamL letL evalOpenExp (IndexAny) _ _ = RepaExp $ text "Any" evalOpenExp (Cond c t e) lamL letL = RepaExp $ text "if" <+> parens cond $$ (nest 1 $ text "then" <+> parens exp1) $$ (nest 1 $ text "else" <+> parens exp2) where cond = toDoc $ evalOpenExp c lamL letL exp1 = toDoc $ evalOpenExp t lamL letL exp2 = toDoc $ evalOpenExp e lamL letL evalOpenExp (PrimConst c) _ _ = RepaExp $ evalPrimConst c evalOpenExp (PrimApp p arg) lamL letL = RepaExp $ evalPrim p argS where argS = evalOpenExp arg lamL letL evalOpenExp (IndexScalar acc ix) lamL letL = RepaExp $ parens arr <+> char '!' <+> case render idx of "Z" -> idx otherwise -> parens (text "Z:." <> idx) where RepaAcc arr = evalOpenAcc acc letL RepaExp idx = evalOpenExp ix lamL letL evalOpenExp (Shape acc) lamL letL = RepaExp $ text "extent" <+> parens arr where RepaAcc arr = evalOpenAcc acc letL evalOpenExp (Size acc) _lamL letL = RepaExp $ text "Repa.size $ Repa.extent" <+> parens arr where RepaAcc arr = evalOpenAcc acc letL evalOpenExp _ _ _ = RepaExp $ text "<UNDEFINED>" -- Evaluate a closed expression -- evalExp :: PreExp OpenAcc aenv t -> Int -> RepaExp evalExp e letL = evalOpenExp e 0 letL ------------ -- TUPLES -- ------------ evalTuple :: Tuple (OpenExp env aenv) t -> Int -> Int -> RepaExp evalTuple tup lamL letL = RepaTuple $ evalTuple' tup lamL letL evalTuple' :: Tuple (OpenExp env aenv) t -> Int -> Int -> [Doc] evalTuple' NilTup _ _ = [] evalTuple' (e1 `SnocTup` e2) lamL letL = tup ++ [t] where t = toDoc $ evalOpenExp e2 lamL letL tup = evalTuple' e1 lamL letL --------------------- -- VARIABLE HELPER -- --------------------- getVarNum :: Idx env t -> Int getVarNum ZeroIdx = 0 getVarNum (SuccIdx idx) = 1 + (getVarNum idx) ------------------ -- SHAPE STRING -- ------------------ printShape :: Repr.Shape sh => sh -> Doc printShape sh = text (printShape' $ Repr.shapeToList sh) printShape' :: [Int] -> String printShape' (x:xs) = (printShape' xs) ++ " :. (" ++ (show x) ++ " :: Int)" printShape' [] = "Z" ------------------------------- EVAL BOUNDARY EXPRESSIONS -- ------------------------------- evalBoundary :: forall aenv sh e. (Elt e) => OpenAcc aenv (Array sh e) -> Boundary (EltRepr e) -> Doc evalBoundary _ bndy = case bndy of Clamp -> text "Clamp" Mirror -> text "Mirror" Wrap -> text "Wrap" Constant a -> text "Constant" <+> text (show ((Sugar.toElt a) :: e)) ------------------------- -- EVAL PRJ EXPRESSION -- ------------------------- evalPrj :: Int -> Int -> Doc evalPrj tup 0 = parens $ evalPrj' (tup-1) (-1) <+> prjVarName evalPrj tup idx = parens $ evalPrj' (tup-1) (idx-1) <+> char '_' evalPrj' :: Int -> Int -> Doc evalPrj' 1 0 = prjVarName <> comma evalPrj' 1 idx = char '_' <> comma evalPrj' tup 0 = evalPrj' (tup-1) (-1) <+> prjVarName <> comma evalPrj' tup idx = evalPrj' (tup-1) (idx-1) <+> char '_' <> comma prjVarName :: Doc prjVarName = text "tVar" ----------------------------- -- TYPING HELPER FUNCTIONS -- ----------------------------- -- Creates a Doc for the given expression expToString :: OpenExp env aenv a -> Doc expToString exp = {-parens $-} tupleTypeToString $ expType exp tupleTypeToString :: TupleType a -> Doc tupleTypeToString UnitTuple = empty tupleTypeToString (PairTuple a b) = parens $ tupleType'ToString $ parseTupleType (PairTuple a b) tupleTypeToString (SingleTuple a) = text $ show a tupleType'ToString :: TupleType' a -> Doc tupleType'ToString UnitTuple' = empty tupleType'ToString (Single a) = text $ show a tupleType'ToString (FlatTuple a b) = case a of UnitTuple' -> parens (tupleType'ToString b) otherwise -> tupleType'ToString a <> comma <+> parens (tupleType'ToString b) tupleType'ToString (NestedTuple i a b) = case a of (FlatTuple _ _) -> parens (tupleType'ToString a) <> comma <+> parens (tupleType'ToString b) (NestedTuple i' _ _) -> if i == i' then tupleType'ToString a <> comma <+> parens (tupleType'ToString b) else parens (tupleType'ToString a) <> comma <+> parens (tupleType'ToString b) otherwise -> parens (tupleType'ToString a) <> comma <+> parens (tupleType'ToString b) -- New tuple type for annotating nesting of tuples data TupleType' a where UnitTuple' :: TupleType' () Single :: ScalarType a -> TupleType' a FlatTuple :: TupleType' a -> TupleType' b -> TupleType' (a, b) NestedTuple :: Int -> TupleType' a -> TupleType' b -> TupleType' (a, b) parseTupleType :: TupleType a -> TupleType' a parseTupleType UnitTuple = UnitTuple' parseTupleType (SingleTuple a) = Single a parseTupleType (PairTuple a' b') = let a = parseTupleType a' b = parseTupleType b' in case a of UnitTuple' -> FlatTuple a b (Single _) -> error "Currently unknown Tuple indent case" (FlatTuple _ _) -> case b of UnitTuple' -> FlatTuple a b (Single _) -> FlatTuple a b (FlatTuple _ _) -> NestedTuple 1 a b (NestedTuple _ _ _) -> FlatTuple a b (NestedTuple i _ _) -> case b of UnitTuple' -> NestedTuple i a b (Single _) -> NestedTuple i a b (FlatTuple _ _) -> NestedTuple i a b (NestedTuple i' _ _) -> if i == i' then NestedTuple (i+1) a b else NestedTuple i a b -- Returns the number of members in a tuple tupSize :: TupleType' a -> Int tupSize UnitTuple' = 0 tupSize (Single _) = 0 tupSize (FlatTuple a _) = 1 + case a of (FlatTuple _ _) -> tupSize a otherwise -> 0 tupSize (NestedTuple i a _) = 1 + case a of (NestedTuple i' _ _) -> if i == i' then tupSize a else if i == (i'+1) then 1 else 0 (FlatTuple _ _) -> if i == 1 then 1 else 0 otherwise -> 0 -- Returns how many members of a tuple from the 'left' we are referencing tupIdx :: TupleIdx t e -> Int tupIdx (SuccTupIdx idx) = 1 + tupIdx idx tupIdx ZeroTupIdx = 0 -- Copied from Data.Array.Accelerate.Analysis.Type tupleIdxType :: forall t e. TupleIdx t e -> TupleType (EltRepr e) tupleIdxType ZeroTupIdx = eltType (undefined::e) tupleIdxType (SuccTupIdx idx) = tupleIdxType idx -- Adapted from Data.Array.Accelerate.Analysis.Type expType :: OpenExp aenv env t -> TupleType (EltRepr t) expType = preExpType preExpType :: forall acc aenv env t. PreOpenExp acc aenv env t -> TupleType (EltRepr t) preExpType e = case e of Var _ -> eltType (undefined::t) Const _ -> eltType (undefined::t) Tuple _ -> eltType (undefined::t) Prj idx _ -> tupleIdxType idx IndexNil -> eltType (undefined::t) IndexCons _ _ -> eltType (undefined::t) IndexHead _ -> eltType (undefined::t) IndexTail _ -> eltType (undefined::t) IndexAny -> eltType (undefined::t) Cond _ t _ -> preExpType t PrimConst _ -> eltType (undefined::t) PrimApp _ _ -> eltType (undefined::t) Shape _ -> eltType (undefined::t) Size _ -> eltType (undefined::t) otherwise -> error "Typing error"
null
https://raw.githubusercontent.com/blambo/accelerate-repa/5ea4d40ebcca50d5b952e8783a56749cea4431a4/Data/Array/Accelerate/Repa/Evaluations.hs
haskell
| ------------- ------------- | Traverses over AST Not sure why sliceIndex is not required? Not sure why sliceIndex is not required? test more extensively with differing typed arrays to insure no errors TODO: Tidy generated code TODO: Tidy up code ------------------ FUNCTION NODES -- ------------------ -------------------- -------------------- Evaluate an open expression = RepaExp $ parens (char 'x' <> int varNum <+> colon <> colon <+> typeD) Evaluate a closed expression ---------- TUPLES -- ---------- ------------------- VARIABLE HELPER -- ------------------- ---------------- SHAPE STRING -- ---------------- ----------------------------- ----------------------------- ----------------------- EVAL PRJ EXPRESSION -- ----------------------- --------------------------- TYPING HELPER FUNCTIONS -- --------------------------- Creates a Doc for the given expression parens $ New tuple type for annotating nesting of tuples Returns the number of members in a tuple Returns how many members of a tuple from the 'left' we are referencing Copied from Data.Array.Accelerate.Analysis.Type Adapted from Data.Array.Accelerate.Analysis.Type
# LANGUAGE CPP , GADTs , BangPatterns , TypeOperators , PatternGuards # # LANGUAGE TypeFamilies , ScopedTypeVariables , FlexibleContexts # # LANGUAGE TypeSynonymInstances , FlexibleInstances , RankNTypes # Module : Data . Array . Accelerate . . Evaluations Maintainer : < blambo+ > Defines the code generation for Acc , Exp and Fun nodes into code module Data.Array.Accelerate.Repa.Evaluations ( evalAcc ) where import Data.Typeable import Text.PrettyPrint import Data.Array.Accelerate.AST import Data.Array.Accelerate.Array.Sugar as Sugar import Data.Array.Accelerate.Tuple import Data.Array.Accelerate.Type import qualified Data.Array.Accelerate.Array.Representation as Repr import Data.Array.Accelerate.Repa.Evaluations.Prim import Data.Array.Accelerate.Repa.Traverse evalAcc :: forall a. Acc a -> Doc evalAcc acc = parsedS where RepaAcc parsedS = evalOpenAcc acc 0 | Unpacks AST by removing ' OpenAcc ' shell evalOpenAcc :: forall aenv a. OpenAcc aenv a -> Int -> RepaAcc evalOpenAcc (OpenAcc acc) = evalPreOpenAcc acc evalPreOpenAcc :: forall aenv a. PreOpenAcc OpenAcc aenv a -> Int -> RepaAcc evalPreOpenAcc (Let acc1 acc2) letLevel = RepaAcc returnDoc where RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 (letLevel+1) var = char 'y' <> int letLevel returnDoc = text "let" <+> var <+> equals <+> parens arr1 $$ text "in" $$ nest 1 arr2 evalPreOpenAcc (Let2 acc1 acc2) letLevel = RepaAcc returnDoc where RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 (letLevel+2) var1 = char 'y' <> int letLevel var2 = char 'y' <> int (letLevel + 1) returnDoc = text "let" <+> parens (var1 <> comma <+> var2) <+> equals <+> (parens $ nest 1 arr1) $$ text "in" $$ nest 1 arr2 evalPreOpenAcc (PairArrays acc1 acc2) letLevel = RepaAcc returnDoc where RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 letLevel returnDoc = parens (parens arr1 <> comma <+> parens arr2) evalPreOpenAcc (Avar idx) letLevel = RepaAcc var where var = char 'y' <> int (letLevel - varNum - 1) varNum = getVarNum idx evalPreOpenAcc (Apply (Alam (Abody funAcc)) acc) letLevel = RepaAcc $ returnDoc where RepaAcc fun = evalOpenAcc funAcc (1) RepaAcc arr = evalOpenAcc acc letLevel var = char 'y' <> int 0 tempVar = char 'y' returnDoc = text "let" <+> tempVar <+> equals <+> parens arr $$ text "in" $$ nest 1 (text "let" <+> var <+> equals <+> tempVar $$ text "in" $$ nest 1 fun) evalPreOpenAcc (Apply _afun _acc) _letLevel = error "GHC pattern matching does not detect that this case is impossible" evalPreOpenAcc (Acond cond acc1 acc2) letLevel = RepaAcc returnDoc where exp = toDoc $ evalExp cond letLevel RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 letLevel returnDoc = text "if" <+> exp $$ text "then" $$ (nest 1 arr1) $$ text "else" $$ (nest 1 arr2) evalPreOpenAcc (Use arr@(Array sh e)) letLevel = RepaAcc returnDoc where shS = printShape sh arrL = toList arr arrData = text $ show $ arrL listType = text $ (showsTypeRep $ typeOf $ arrL) "" returnDoc = text "fromListUnboxed" <+> parens shS <+> parens (arrData <+> colon <> colon <+> listType) evalPreOpenAcc (Unit e) letLevel = RepaAcc returnDoc where exp = toDoc $ evalExp e letLevel returnDoc = text "fromListUnboxed Z" <+> brackets exp evalPreOpenAcc (Reshape e acc) letLevel = RepaAcc returnDoc where RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "reshape" <+> parens exp <+> parens arr evalPreOpenAcc (Generate sh f) letLevel = RepaAcc returnDoc where exp = toDoc $ evalExp sh letLevel RepaAcc fun = evalFun f letLevel returnDoc = text "fromFunction" <+> parens exp <+> parens fun evalPreOpenAcc (Replicate sliceIndex slix acc) letLevel = RepaAcc $ returnDoc where slixD = toDoc $ evalExp slix letLevel RepaAcc arrD = evalOpenAcc acc letLevel returnDoc = text "extend" <+> parens slixD <+> parens arrD evalPreOpenAcc (Index sliceIndex acc slix) letLevel = RepaAcc $ returnDoc where slixD = toDoc $ evalExp slix letLevel RepaAcc arrD = evalOpenAcc acc letLevel returnDoc = text "slice" <+> parens arrD <+> parens slixD evalPreOpenAcc (Map f acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel returnDoc = text "Repa.map" <+> (parens fun $$ parens arr) Reversing order of acc1 and acc2 seems to fix some issues , will need to evalPreOpenAcc (ZipWith f acc1 acc2) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr1 = evalOpenAcc acc1 letLevel RepaAcc arr2 = evalOpenAcc acc2 letLevel returnDoc = text "Repa.zipWith" <+> (parens fun $$ parens arr2 $$ parens arr1) TODO : Specialise to parallel fold ' foldP ' as 's restrictions for this fold is same as Accelerate 's evalPreOpenAcc (Fold f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel exp = toDoc $ evalExp e letLevel RepaAcc arr = evalOpenAcc acc letLevel returnDoc = text "fold" <+> (parens fun $$ parens exp $$ parens arr) TODO : No foldr1 function in Repa 3 , change to foldP ? evalPreOpenAcc (Fold1 f acc) letLevel = RepaAcc $ returnDoc where RepaAcc combD = evalFun f letLevel RepaAcc srcArrD = evalOpenAcc acc letLevel newShapeD = parens $ text "\\(sh:._) -> sh" genElemD = parens $ text "\\lookup pos ->" <+> (text "let (_:.end) = extent srcArr" $$ text "in foldr1 comb" $$ nest 1 (text "$ Prelude.map (lookup) [(pos:.i) | i <- [0..(end-1)]]")) returnDoc = text "let" <+> (text "srcArr =" <+> srcArrD $$ text "comb =" <+> combD) $$ text "in traverse" <+> (parens srcArrD $$ newShapeD $$ genElemD) evalPreOpenAcc (FoldSeg f e acc1 acc2) letLevel = RepaAcc $ returnDoc where RepaAcc funD = evalFun f letLevel expD = toDoc $ evalExp e letLevel RepaAcc arrD = evalOpenAcc acc1 letLevel RepaAcc segD = evalOpenAcc acc2 letLevel returnDoc = letD $$ foldSegD letD = text "let" <+> (text "arr =" <+> arrD $$ text "f =" <+> funD $$ text "seg =" <+> segD $$ text "e =" <+> expD $$ helpers) $$ text "in" foldSegD = text "traverse arr (\\_ -> (sh:.ix)) foldOne" helpers = text "(sh:._) = arrayExtent arr" $$ text "(_:.ix) = arrayExtent seg" $$ text "starts :: Array DIM1 Int" $$ text "starts =" <+> (text "let res =" <+> (text "traverse seg (\\(Z:.i) -> (Z:.(i+1)))" $$ parens (text "let newVal orig (Z:.pos)" <+> (text "| pos == 0 = 0" $$ text "| otherwise = (newVal orig (Z:.(pos-1))) + (orig (Z:.(pos-1)))") $$ text "in newVal")) $$ text "in" $$ nest 1 (text "traverse res (\\(Z:.i) -> (Z:.(i-1))) (\\orig (Z:.pos) -> orig (Z:.pos))")) $$ text "foldOne lookup (sh:.ix) =" <+> (text "let" <+> (text "start = starts ! (Z:.ix)" $$ text "len = seg ! (Z:.ix)") $$ text "in foldSeg' sh e start (start+len)") $$ text "foldSeg' sh val start end" $$ nest 1 (text "| start >= end = val" $$ text "| otherwise = foldSeg' sh (f val (arr ! (sh:.start))) (start+1) end") evalPreOpenAcc (Fold1Seg f acc1 acc2) letLevel = RepaAcc $ returnDoc where RepaAcc funD = evalFun f letLevel RepaAcc arrD = evalOpenAcc acc1 letLevel RepaAcc segD = evalOpenAcc acc2 letLevel returnDoc = letD $$ fold1SegD letD = text "let" <+> (text "arr =" <+> arrD $$ text "f =" <+> funD $$ text "seg =" <+> segD $$ helpers) $$ text "in" fold1SegD = text "traverse arr (\\_ -> (sh:.ix)) foldOne" helpers = text "(sh:._) = arrayExtent arr" $$ text "(_:.ix) = arrayExtent seg" $$ text "starts :: Array DIM1 Int" $$ text "starts =" <+> (text "let res =" <+> (text "traverse seg (\\(Z:.i) -> (Z:.(i+1)))" $$ parens (text "let newVal orig (Z:.pos)" <+> (text "| pos == 0 = 0" $$ text "| otherwise = (newVal orig (Z:.(pos-1))) + (orig (Z:.(pos-1)))") $$ text "in newVal")) $$ text "in" $$ nest 1 (text "traverse res (\\(Z:.i) -> (Z:.(i-1))) (\\orig (Z:.pos) -> orig (Z:.pos))")) $$ text "foldOne lookup (sh:.ix) =" <+> (text "let" <+> (text "start = starts ! (Z:.ix)" $$ text "len = seg ! (Z:.ix)") $$ text "in foldSeg' sh (arr ! (sh:.start)) (start+1) (start+len)") $$ text "foldSeg' sh val start end" $$ nest 1 (text "| start >= end = val" $$ text "| otherwise = foldSeg' sh (f val (arr ! (sh:.start))) (start+1) end") evalPreOpenAcc (Scanl f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "traverse" <+> (parens arr $$ parens shapeDoc $$ parens newValDoc) shapeDoc = text "\\(Z:.i) -> (Z:.(i+1))" newValDoc = text "let newVal orig (Z:.pos)" <+> ((text "| pos == 0" <+> equals <+> exp) $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos-1))") $$ parens (text "orig (Z:.(pos-1))")))) $$ text "in newVal" evalPreOpenAcc (Scanl' f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "let res = traverse" <+> (parens arr $$ parens shapeDoc $$ parens newValDoc) $$ text "in" <+> tuple tuple = parens (first <> comma <+> second) first = text "traverse res (\\(Z:.i) -> (Z:.(i-1))) (\\orig sh -> orig sh)" second = text "fromList Z [(res!(Z:.((size $ extent res)-1)))]" shapeDoc = text "\\(Z:.i) -> (Z:.(i+1))" newValDoc = text "let newVal orig (Z:.pos)" <+> ((text "| pos == 0" <+> equals <+> exp) $$ nest 1 (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos-1))") $$ parens (text "orig (Z:.(pos-1))")))) $$ text "in newVal" evalPreOpenAcc (Scanl1 f acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel returnDoc = text "traverse" <+> (parens arr $$ text "(id)" $$ parens newValDoc) newValDoc = text "let newVal orig sh@(Z:.pos)" <+> ((text "| pos == 0" <+> equals <+> text "orig sh") $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos-1))") $$ parens (text "orig sh")))) $$ text "in newVal" evalPreOpenAcc (Scanr f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "traverse" <+> (parens arr $$ shapeDoc $$ parens newValDoc) shapeDoc = parens $ text "\\(Z:.i) -> (Z:.(i+1))" newValDoc = text "let newVal orig sh@(Z:.pos)" <+> ((text "| pos ==" <+> last <+> equals <+> exp) $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos+1))") $$ parens (text "orig sh")))) $$ text "in newVal" last = parens $ text "size $ extent $" <+> arr evalPreOpenAcc (Scanr' f e acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel exp = toDoc $ evalExp e letLevel returnDoc = text "let res" <+> equals <+> text "traverse" <+> (parens arr $$ parens shapeDoc $$ parens newVarDoc) $$ text "in" <+> tuple tuple = parens (first $$ comma $$ second) first = text "traverse res (\\(Z:.i) -> (Z:.(i-1)))" <+> (parens $ text "\\orig (Z:.pos) -> orig (Z:.(pos+1))") second = text "fromList Z [(res!(Z:.0))]" shapeDoc = text "\\(Z:.i) -> (Z:.(i+1))" newVarDoc = text "let newVal orig sh@(Z:.pos)" <+> ((text "| pos ==" <+> last <+> equals <+> exp) $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos+1))") $$ parens (text "orig sh")))) $$ text "in newVal" last = parens $ text "size $ extent $" <+> arr evalPreOpenAcc (Scanr1 f acc) letLevel = RepaAcc returnDoc where RepaAcc fun = evalFun f letLevel RepaAcc arr = evalOpenAcc acc letLevel returnDoc = text "traverse" <+> (parens arr $$ shapeDoc $$ parens newVarDoc) shapeDoc = parens $ text "id" newVarDoc = text "let newVal orig sh@(Z:.pos)" <+> ((text "| pos ==" <+> parens last <+> text "- 1" <+> equals <+> text "orig sh") $$ (text "| otherwise" <+> equals <+> (parens fun $$ parens (text "newVal orig (Z:.(pos+1))") $$ parens (text "orig sh")))) $$ text "in newVal" last = parens $ text "size $ extent $" <+> arr evalPreOpenAcc (Permute f dftAcc p acc) letLevel = RepaAcc $ returnDoc where RepaAcc dftArrD = evalOpenAcc dftAcc letLevel RepaAcc srcArrD = evalOpenAcc acc letLevel RepaAcc combD = evalFun f letLevel RepaAcc permD = evalFun p letLevel returnDoc = text "let" <+> (text "srcArr =" <+> srcArrD $$ text "dftArr =" <+> dftArrD $$ text "perm =" <+> (parens permD) $$ text "comb =" <+> (parens combD) $$ permuteDoc) $$ text "in" $$ nest 1 (text "permute 0 comb dftArr perm srcArr") permuteDoc = text "permute idx comb dftArr perm srcArr" $$ nest 1 (text "| idx >= (size $ extent srcArr) = dftArr" $$ text "| otherwise =" <+> permuteArgsDoc) permuteArgsDoc = text "let" <+> (text "(Z:.srcIdx) = fromIndex (extent srcArr) idx" $$ text "newArr = fromFunction" <+> (text "(extent dftArr)" $$ text "(\\sh -> case sh == (perm srcIdx) of" $$ nest 1 (text "True -> (dftArr ! (perm srcIdx)) `comb`" <+> text "(srcArr ! (Z:.srcIdx))" $$ text "False -> index dftArr sh)"))) $$ text "in permute (idx+1) comb newArr perm srcArr" evalPreOpenAcc (Backpermute e p acc) letLevel = RepaAcc $ returnDoc where returnDoc = text "backpermute" <+> parens expD <+> parens permD <+> parens srcArrD expD = toDoc $ evalExp e letLevel RepaAcc permD = evalFun p letLevel RepaAcc srcArrD = evalOpenAcc acc letLevel evalPreOpenAcc (Stencil sten bndy acc) letLevel = RepaAcc $ returnDoc where RepaAcc funD = evalFun sten letLevel RepaAcc arrD = evalOpenAcc acc letLevel bndyD = evalBoundary acc bndy returnDoc = letD $$ traverseD letD = text "let" <+> (text "arr =" <+> arrD $$ text "bndy =" <+> bndyD $$ text "sten =" <+> parens funD) $$ text "in" traverseD = text "traverse" <+> (text "arr" $$ text "id" $$ text "(\\lookup curr -> sten $ stencilData (bound lookup bndy (arrayExtent arr)) curr)") evalPreOpenAcc (Stencil2 sten bndy1 acc1 bndy2 acc2) letLevel = RepaAcc $ returnDoc where RepaAcc stenD = evalFun sten letLevel RepaAcc arr1D = evalOpenAcc acc1 letLevel RepaAcc arr2D = evalOpenAcc acc2 letLevel bndy1D = evalBoundary acc1 bndy1 bndy2D = evalBoundary acc2 bndy2 returnDoc = letD $$ traverseD letD = text "let" <+> (text "arr1 =" <+> arr1D $$ text "bndy1 =" <+> bndy1D $$ text "arr2 =" <+> arr2D $$ text "bndy2 =" <+> bndy2D $$ text "sten =" <+> parens stenD) $$ text "in" traverseD = text "traverse2" <+> (text "arr1" $$ text "arr2" $$ text "(\\a _ -> a)" $$ parens (text "\\lookup1 lookup2 curr ->" <+> (text "sten" <+> (parens (text "stencilData (bound lookup1 bndy1 (arrayExtent arr1)) curr") $$ parens (text "stencilData (bound lookup2 bndy2 (arrayExtent arr2)) curr"))))) evalPreOpenAcc _ _ = RepaAcc $ text "<UNDEFINED>" evalFun :: Fun aenv t -> Int -> RepaAcc evalFun f letL = evalOpenFun f 0 letL empty evalOpenFun :: OpenFun env aenv t -> Int -> Int -> Doc -> RepaAcc evalOpenFun (Body e) lamL letL binds = RepaAcc $ binds <+> parens (toDoc $ evalOpenExp e lamL letL) evalOpenFun (Lam f) lamL letL binds = funD where funD = evalOpenFun f (lamL+1) letL (varBind <+> binds) varBind = text "\\x" <> int lamL <+> text "->" evalOpenExp :: forall a env aenv . OpenExp env aenv a -> Int -> Int -> RepaExp evalOpenExp var@(Var idx) lamL letL = RepaExp $ parens (char 'x' <> int varNum) where varNum = lamL - (getVarNum idx) - 1 typeD = expToString (var) evalOpenExp (Const c) _ _ = RepaExp $ val where val = let val' = text $ show ((Sugar.toElt c) :: a) in case typeS of ('D':'a':'t':'a':_) -> val' otherwise -> val' <+> colon <> colon <+> (text typeS) typeS = (showsTypeRep $ typeOf ((Sugar.toElt c) :: a)) "" evalOpenExp (Tuple tup) lamL letL = evalTuple tup lamL letL evalOpenExp (Prj idx e) lamL letL = RepaExp $ text "let" <+> parens prjS <+> equals <+> parens expS <+> text "in" <+> prjVarName where prjS = evalPrj (tupSize $ parseTupleType $ expType e) (tupIdx idx) expS = toDoc $ evalOpenExp e lamL letL evalOpenExp IndexNil _ _ = RepaExp $ char 'Z' evalOpenExp (IndexCons sh i) lamL letL = RepaExp $ shS <+> text ":." <+> parens ix where shS = toDoc $ evalOpenExp sh lamL letL ix = toDoc $ evalOpenExp i lamL letL evalOpenExp (IndexHead ix) lamL letL = RepaExp $ text "case" <+> parens exp <+> text "of (_:.h) -> h" where exp = toDoc $ evalOpenExp ix lamL letL evalOpenExp (IndexTail ix) lamL letL = RepaExp $ text "case" <+> parens exp <+> text "of (t:._) -> t" where exp = toDoc $ evalOpenExp ix lamL letL evalOpenExp (IndexAny) _ _ = RepaExp $ text "Any" evalOpenExp (Cond c t e) lamL letL = RepaExp $ text "if" <+> parens cond $$ (nest 1 $ text "then" <+> parens exp1) $$ (nest 1 $ text "else" <+> parens exp2) where cond = toDoc $ evalOpenExp c lamL letL exp1 = toDoc $ evalOpenExp t lamL letL exp2 = toDoc $ evalOpenExp e lamL letL evalOpenExp (PrimConst c) _ _ = RepaExp $ evalPrimConst c evalOpenExp (PrimApp p arg) lamL letL = RepaExp $ evalPrim p argS where argS = evalOpenExp arg lamL letL evalOpenExp (IndexScalar acc ix) lamL letL = RepaExp $ parens arr <+> char '!' <+> case render idx of "Z" -> idx otherwise -> parens (text "Z:." <> idx) where RepaAcc arr = evalOpenAcc acc letL RepaExp idx = evalOpenExp ix lamL letL evalOpenExp (Shape acc) lamL letL = RepaExp $ text "extent" <+> parens arr where RepaAcc arr = evalOpenAcc acc letL evalOpenExp (Size acc) _lamL letL = RepaExp $ text "Repa.size $ Repa.extent" <+> parens arr where RepaAcc arr = evalOpenAcc acc letL evalOpenExp _ _ _ = RepaExp $ text "<UNDEFINED>" evalExp :: PreExp OpenAcc aenv t -> Int -> RepaExp evalExp e letL = evalOpenExp e 0 letL evalTuple :: Tuple (OpenExp env aenv) t -> Int -> Int -> RepaExp evalTuple tup lamL letL = RepaTuple $ evalTuple' tup lamL letL evalTuple' :: Tuple (OpenExp env aenv) t -> Int -> Int -> [Doc] evalTuple' NilTup _ _ = [] evalTuple' (e1 `SnocTup` e2) lamL letL = tup ++ [t] where t = toDoc $ evalOpenExp e2 lamL letL tup = evalTuple' e1 lamL letL getVarNum :: Idx env t -> Int getVarNum ZeroIdx = 0 getVarNum (SuccIdx idx) = 1 + (getVarNum idx) printShape :: Repr.Shape sh => sh -> Doc printShape sh = text (printShape' $ Repr.shapeToList sh) printShape' :: [Int] -> String printShape' (x:xs) = (printShape' xs) ++ " :. (" ++ (show x) ++ " :: Int)" printShape' [] = "Z" evalBoundary :: forall aenv sh e. (Elt e) => OpenAcc aenv (Array sh e) -> Boundary (EltRepr e) -> Doc evalBoundary _ bndy = case bndy of Clamp -> text "Clamp" Mirror -> text "Mirror" Wrap -> text "Wrap" Constant a -> text "Constant" <+> text (show ((Sugar.toElt a) :: e)) evalPrj :: Int -> Int -> Doc evalPrj tup 0 = parens $ evalPrj' (tup-1) (-1) <+> prjVarName evalPrj tup idx = parens $ evalPrj' (tup-1) (idx-1) <+> char '_' evalPrj' :: Int -> Int -> Doc evalPrj' 1 0 = prjVarName <> comma evalPrj' 1 idx = char '_' <> comma evalPrj' tup 0 = evalPrj' (tup-1) (-1) <+> prjVarName <> comma evalPrj' tup idx = evalPrj' (tup-1) (idx-1) <+> char '_' <> comma prjVarName :: Doc prjVarName = text "tVar" expToString :: OpenExp env aenv a -> Doc tupleTypeToString :: TupleType a -> Doc tupleTypeToString UnitTuple = empty tupleTypeToString (PairTuple a b) = parens $ tupleType'ToString $ parseTupleType (PairTuple a b) tupleTypeToString (SingleTuple a) = text $ show a tupleType'ToString :: TupleType' a -> Doc tupleType'ToString UnitTuple' = empty tupleType'ToString (Single a) = text $ show a tupleType'ToString (FlatTuple a b) = case a of UnitTuple' -> parens (tupleType'ToString b) otherwise -> tupleType'ToString a <> comma <+> parens (tupleType'ToString b) tupleType'ToString (NestedTuple i a b) = case a of (FlatTuple _ _) -> parens (tupleType'ToString a) <> comma <+> parens (tupleType'ToString b) (NestedTuple i' _ _) -> if i == i' then tupleType'ToString a <> comma <+> parens (tupleType'ToString b) else parens (tupleType'ToString a) <> comma <+> parens (tupleType'ToString b) otherwise -> parens (tupleType'ToString a) <> comma <+> parens (tupleType'ToString b) data TupleType' a where UnitTuple' :: TupleType' () Single :: ScalarType a -> TupleType' a FlatTuple :: TupleType' a -> TupleType' b -> TupleType' (a, b) NestedTuple :: Int -> TupleType' a -> TupleType' b -> TupleType' (a, b) parseTupleType :: TupleType a -> TupleType' a parseTupleType UnitTuple = UnitTuple' parseTupleType (SingleTuple a) = Single a parseTupleType (PairTuple a' b') = let a = parseTupleType a' b = parseTupleType b' in case a of UnitTuple' -> FlatTuple a b (Single _) -> error "Currently unknown Tuple indent case" (FlatTuple _ _) -> case b of UnitTuple' -> FlatTuple a b (Single _) -> FlatTuple a b (FlatTuple _ _) -> NestedTuple 1 a b (NestedTuple _ _ _) -> FlatTuple a b (NestedTuple i _ _) -> case b of UnitTuple' -> NestedTuple i a b (Single _) -> NestedTuple i a b (FlatTuple _ _) -> NestedTuple i a b (NestedTuple i' _ _) -> if i == i' then NestedTuple (i+1) a b else NestedTuple i a b tupSize :: TupleType' a -> Int tupSize UnitTuple' = 0 tupSize (Single _) = 0 tupSize (FlatTuple a _) = 1 + case a of (FlatTuple _ _) -> tupSize a otherwise -> 0 tupSize (NestedTuple i a _) = 1 + case a of (NestedTuple i' _ _) -> if i == i' then tupSize a else if i == (i'+1) then 1 else 0 (FlatTuple _ _) -> if i == 1 then 1 else 0 otherwise -> 0 tupIdx :: TupleIdx t e -> Int tupIdx (SuccTupIdx idx) = 1 + tupIdx idx tupIdx ZeroTupIdx = 0 tupleIdxType :: forall t e. TupleIdx t e -> TupleType (EltRepr e) tupleIdxType ZeroTupIdx = eltType (undefined::e) tupleIdxType (SuccTupIdx idx) = tupleIdxType idx expType :: OpenExp aenv env t -> TupleType (EltRepr t) expType = preExpType preExpType :: forall acc aenv env t. PreOpenExp acc aenv env t -> TupleType (EltRepr t) preExpType e = case e of Var _ -> eltType (undefined::t) Const _ -> eltType (undefined::t) Tuple _ -> eltType (undefined::t) Prj idx _ -> tupleIdxType idx IndexNil -> eltType (undefined::t) IndexCons _ _ -> eltType (undefined::t) IndexHead _ -> eltType (undefined::t) IndexTail _ -> eltType (undefined::t) IndexAny -> eltType (undefined::t) Cond _ t _ -> preExpType t PrimConst _ -> eltType (undefined::t) PrimApp _ _ -> eltType (undefined::t) Shape _ -> eltType (undefined::t) Size _ -> eltType (undefined::t) otherwise -> error "Typing error"
33c42eeea801595ac89e0b9767a4659725f6a7654bd58843b5266f5c8621a70b
pyr/warp
router.cljs
(ns warp.client.router (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [goog.events :as events] [goog.history.EventType :as EventType] [cljs.core.async :as a] [warp.client.state :refer [app]] [bidi.bidi :refer [match-route]]) (:import goog.History)) (defonce route-events (a/chan 10)) (def router (atom {:routes nil :handlers nil})) (defn set-router! [routes handlers] (reset! router {:routes routes :handlers handlers})) (defn route-update [event] (let [token (.-token event)] (a/put! route-events token))) (defonce history (doto (History.) (events/listen EventType/NAVIGATE route-update) (.setEnabled true))) (defn route-dispatcher [] (go-loop [location (a/<! route-events)] (when-let [routes (:routes @router)] (swap! app assoc :route (match-route routes location))) (recur (a/<! route-events))) (let [{:keys [handler route-params]} (:route @app) component (or (get (:handlers @router) handler) (get (:handlers @router) :default))] (println "got handler:" handler ", and params:" route-params) (if route-params [component route-params] [component]))) (defn redirect [location] (.setToken history location))
null
https://raw.githubusercontent.com/pyr/warp/c3ee96d90b233a47c1104b4339fed071ec8afe68/src/warp/client/router.cljs
clojure
(ns warp.client.router (:require-macros [cljs.core.async.macros :refer [go go-loop]]) (:require [goog.events :as events] [goog.history.EventType :as EventType] [cljs.core.async :as a] [warp.client.state :refer [app]] [bidi.bidi :refer [match-route]]) (:import goog.History)) (defonce route-events (a/chan 10)) (def router (atom {:routes nil :handlers nil})) (defn set-router! [routes handlers] (reset! router {:routes routes :handlers handlers})) (defn route-update [event] (let [token (.-token event)] (a/put! route-events token))) (defonce history (doto (History.) (events/listen EventType/NAVIGATE route-update) (.setEnabled true))) (defn route-dispatcher [] (go-loop [location (a/<! route-events)] (when-let [routes (:routes @router)] (swap! app assoc :route (match-route routes location))) (recur (a/<! route-events))) (let [{:keys [handler route-params]} (:route @app) component (or (get (:handlers @router) handler) (get (:handlers @router) :default))] (println "got handler:" handler ", and params:" route-params) (if route-params [component route-params] [component]))) (defn redirect [location] (.setToken history location))
4e386c8d032daba6c555d9744faf9f7dfb4306c7b14efb20eb7c48cd85fd0c90
wireapp/wire-server
SQS.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. -- Disabling for HasCallStack {-# OPTIONS_GHC -Wno-redundant-constraints #-} | TODO : most of this module is deprecated ; use " Util . Test . SQS " from the types - common - aws package -- instead. module API.SQS where import Control.Lens hiding ((.=)) import Data.ByteString.Lazy (fromStrict) import qualified Data.Currency as Currency import Data.Id import qualified Data.Set as Set import Data.Text (pack) import qualified Data.UUID as UUID import qualified Galley.Aws as Aws import Galley.Options (JournalOpts) import Imports import Network.HTTP.Client import Network.HTTP.Client.OpenSSL import OpenSSL.Session as Ssl import Proto.TeamEvents as E import Proto.TeamEvents_Fields as E import Ssl.Util import qualified System.Logger.Class as L import Test.Tasty.HUnit import TestSetup import qualified Util.Test.SQS as SQS withTeamEventWatcher :: HasCallStack => (SQS.SQSWatcher TeamEvent -> TestM ()) -> TestM () withTeamEventWatcher action = do view tsTeamEventWatcher >>= \case Nothing -> pure () Just w -> action w assertIfWatcher :: HasCallStack => String -> (TeamEvent -> Bool) -> (String -> Maybe TeamEvent -> TestM ()) -> TestM () assertIfWatcher l matcher assertion = view tsTeamEventWatcher >>= \case Nothing -> pure () Just w -> SQS.assertMessage w l matcher assertion tActivateWithCurrency :: (HasCallStack, MonadIO m) => Maybe Currency.Alpha -> String -> Maybe E.TeamEvent -> m () tActivateWithCurrency c l (Just e) = liftIO $ do assertEqual (l <> ": eventType") E.TeamEvent'TEAM_ACTIVATE (e ^. eventType) assertEqual "count" 1 (e ^. eventData . memberCount) -- NOTE: protobuf used to decodes absent, optional fields as (Just "") but not when using `maybe'<field>` let cur = pack . show <$> c assertEqual "currency" cur (e ^. eventData . maybe'currency) tActivateWithCurrency _ l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamActivate, got nothing" assertTeamActivateWithCurrency :: HasCallStack => String -> TeamId -> Maybe Currency.Alpha -> TestM () assertTeamActivateWithCurrency l tid c = assertIfWatcher l (teamActivateMatcher tid) (tActivateWithCurrency c) tActivate :: (HasCallStack, MonadIO m) => String -> Maybe E.TeamEvent -> m () tActivate l (Just e) = liftIO $ do assertEqual (l <> ": eventType") E.TeamEvent'TEAM_ACTIVATE (e ^. eventType) assertEqual "count" 1 (e ^. eventData . memberCount) tActivate l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamActivate, got nothing" assertTeamActivate :: HasCallStack => String -> TeamId -> TestM () assertTeamActivate l tid = assertIfWatcher l (teamActivateMatcher tid) tActivate teamActivateMatcher :: TeamId -> TeamEvent -> Bool teamActivateMatcher tid e = e ^. eventType == E.TeamEvent'TEAM_ACTIVATE && decodeIdFromBS (e ^. teamId) == tid tDelete :: (HasCallStack, MonadIO m) => String -> Maybe E.TeamEvent -> m () tDelete l (Just e) = liftIO $ assertEqual (l <> ": eventType") E.TeamEvent'TEAM_DELETE (e ^. eventType) tDelete l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamDelete, got nothing" assertTeamDelete :: HasCallStack => Int -> String -> TeamId -> TestM () assertTeamDelete maxWaitSeconds l tid = withTeamEventWatcher $ \w -> do mEvent <- SQS.waitForMessage w maxWaitSeconds (\e -> e ^. eventType == E.TeamEvent'TEAM_DELETE && decodeIdFromBS (e ^. teamId) == tid) tDelete l mEvent tSuspend :: (HasCallStack, MonadIO m) => String -> Maybe E.TeamEvent -> m () tSuspend l (Just e) = liftIO $ assertEqual (l <> "eventType") E.TeamEvent'TEAM_SUSPEND (e ^. eventType) tSuspend l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamSuspend, got nothing" assertTeamSuspend :: HasCallStack => String -> TeamId -> TestM () assertTeamSuspend l tid = assertIfWatcher l (\e -> e ^. eventType == E.TeamEvent'TEAM_SUSPEND && decodeIdFromBS (e ^. teamId) == tid) tSuspend tUpdate :: (HasCallStack, MonadIO m) => Int32 -> [UserId] -> String -> Maybe E.TeamEvent -> m () tUpdate expectedCount uids l (Just e) = liftIO $ do assertEqual (l <> ": eventType") E.TeamEvent'TEAM_UPDATE (e ^. eventType) assertEqual (l <> ": member count") expectedCount (e ^. eventData . memberCount) let maybeBillingUserIds = map (UUID.fromByteString . fromStrict) (e ^. eventData . billingUser) assertBool "Invalid UUID found" (all isJust maybeBillingUserIds) let billingUserIds = catMaybes maybeBillingUserIds assertEqual (l <> ": billing users") (Set.fromList $ toUUID <$> uids) (Set.fromList $ billingUserIds) tUpdate _ _ l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamUpdate, got nothing" updateMatcher :: TeamId -> TeamEvent -> Bool updateMatcher tid e = e ^. eventType == E.TeamEvent'TEAM_UPDATE && decodeIdFromBS (e ^. teamId) == tid assertTeamUpdate :: HasCallStack => String -> TeamId -> Int32 -> [UserId] -> TestM () assertTeamUpdate l tid c uids = assertIfWatcher l (\e -> e ^. eventType == E.TeamEvent'TEAM_UPDATE && decodeIdFromBS (e ^. teamId) == tid) $ tUpdate c uids initHttpManager :: IO Manager initHttpManager = do ctx <- Ssl.context Ssl.contextSetVerificationMode ctx $ Ssl.VerifyPeer True True Nothing Ssl.contextAddOption ctx SSL_OP_NO_SSLv2 Ssl.contextAddOption ctx SSL_OP_NO_SSLv3 Ssl.contextAddOption ctx SSL_OP_NO_TLSv1 Ssl.contextSetCiphers ctx rsaCiphers Ssl.contextSetDefaultVerifyPaths ctx newManager (opensslManagerSettings (pure ctx)) -- see Note [SSL context] { managerResponseTimeout = responseTimeoutMicro 10000000, managerConnCount = 100, managerIdleConnectionCount = 300 } mkAWSEnv :: JournalOpts -> IO Aws.Env mkAWSEnv opts = do l <- L.new $ L.setOutput L.StdOut . L.setFormat Nothing $ L.defSettings -- TODO: use mkLogger'? mgr <- initHttpManager Aws.mkEnv l mgr opts decodeIdFromBS :: ByteString -> Id a decodeIdFromBS = Id . fromMaybe (error "failed to decode userId") . UUID.fromByteString . fromStrict
null
https://raw.githubusercontent.com/wireapp/wire-server/72a03a776d4a8607b0a9c3e622003467be914894/services/galley/test/integration/API/SQS.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>. Disabling for HasCallStack # OPTIONS_GHC -Wno-redundant-constraints # instead. NOTE: protobuf used to decodes absent, optional fields as (Just "") but not when using `maybe'<field>` see Note [SSL context] TODO: use mkLogger'?
Copyright ( C ) 2022 Wire Swiss GmbH < > the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along | TODO : most of this module is deprecated ; use " Util . Test . SQS " from the types - common - aws package module API.SQS where import Control.Lens hiding ((.=)) import Data.ByteString.Lazy (fromStrict) import qualified Data.Currency as Currency import Data.Id import qualified Data.Set as Set import Data.Text (pack) import qualified Data.UUID as UUID import qualified Galley.Aws as Aws import Galley.Options (JournalOpts) import Imports import Network.HTTP.Client import Network.HTTP.Client.OpenSSL import OpenSSL.Session as Ssl import Proto.TeamEvents as E import Proto.TeamEvents_Fields as E import Ssl.Util import qualified System.Logger.Class as L import Test.Tasty.HUnit import TestSetup import qualified Util.Test.SQS as SQS withTeamEventWatcher :: HasCallStack => (SQS.SQSWatcher TeamEvent -> TestM ()) -> TestM () withTeamEventWatcher action = do view tsTeamEventWatcher >>= \case Nothing -> pure () Just w -> action w assertIfWatcher :: HasCallStack => String -> (TeamEvent -> Bool) -> (String -> Maybe TeamEvent -> TestM ()) -> TestM () assertIfWatcher l matcher assertion = view tsTeamEventWatcher >>= \case Nothing -> pure () Just w -> SQS.assertMessage w l matcher assertion tActivateWithCurrency :: (HasCallStack, MonadIO m) => Maybe Currency.Alpha -> String -> Maybe E.TeamEvent -> m () tActivateWithCurrency c l (Just e) = liftIO $ do assertEqual (l <> ": eventType") E.TeamEvent'TEAM_ACTIVATE (e ^. eventType) assertEqual "count" 1 (e ^. eventData . memberCount) let cur = pack . show <$> c assertEqual "currency" cur (e ^. eventData . maybe'currency) tActivateWithCurrency _ l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamActivate, got nothing" assertTeamActivateWithCurrency :: HasCallStack => String -> TeamId -> Maybe Currency.Alpha -> TestM () assertTeamActivateWithCurrency l tid c = assertIfWatcher l (teamActivateMatcher tid) (tActivateWithCurrency c) tActivate :: (HasCallStack, MonadIO m) => String -> Maybe E.TeamEvent -> m () tActivate l (Just e) = liftIO $ do assertEqual (l <> ": eventType") E.TeamEvent'TEAM_ACTIVATE (e ^. eventType) assertEqual "count" 1 (e ^. eventData . memberCount) tActivate l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamActivate, got nothing" assertTeamActivate :: HasCallStack => String -> TeamId -> TestM () assertTeamActivate l tid = assertIfWatcher l (teamActivateMatcher tid) tActivate teamActivateMatcher :: TeamId -> TeamEvent -> Bool teamActivateMatcher tid e = e ^. eventType == E.TeamEvent'TEAM_ACTIVATE && decodeIdFromBS (e ^. teamId) == tid tDelete :: (HasCallStack, MonadIO m) => String -> Maybe E.TeamEvent -> m () tDelete l (Just e) = liftIO $ assertEqual (l <> ": eventType") E.TeamEvent'TEAM_DELETE (e ^. eventType) tDelete l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamDelete, got nothing" assertTeamDelete :: HasCallStack => Int -> String -> TeamId -> TestM () assertTeamDelete maxWaitSeconds l tid = withTeamEventWatcher $ \w -> do mEvent <- SQS.waitForMessage w maxWaitSeconds (\e -> e ^. eventType == E.TeamEvent'TEAM_DELETE && decodeIdFromBS (e ^. teamId) == tid) tDelete l mEvent tSuspend :: (HasCallStack, MonadIO m) => String -> Maybe E.TeamEvent -> m () tSuspend l (Just e) = liftIO $ assertEqual (l <> "eventType") E.TeamEvent'TEAM_SUSPEND (e ^. eventType) tSuspend l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamSuspend, got nothing" assertTeamSuspend :: HasCallStack => String -> TeamId -> TestM () assertTeamSuspend l tid = assertIfWatcher l (\e -> e ^. eventType == E.TeamEvent'TEAM_SUSPEND && decodeIdFromBS (e ^. teamId) == tid) tSuspend tUpdate :: (HasCallStack, MonadIO m) => Int32 -> [UserId] -> String -> Maybe E.TeamEvent -> m () tUpdate expectedCount uids l (Just e) = liftIO $ do assertEqual (l <> ": eventType") E.TeamEvent'TEAM_UPDATE (e ^. eventType) assertEqual (l <> ": member count") expectedCount (e ^. eventData . memberCount) let maybeBillingUserIds = map (UUID.fromByteString . fromStrict) (e ^. eventData . billingUser) assertBool "Invalid UUID found" (all isJust maybeBillingUserIds) let billingUserIds = catMaybes maybeBillingUserIds assertEqual (l <> ": billing users") (Set.fromList $ toUUID <$> uids) (Set.fromList $ billingUserIds) tUpdate _ _ l Nothing = liftIO $ assertFailure $ l <> ": Expected 1 TeamUpdate, got nothing" updateMatcher :: TeamId -> TeamEvent -> Bool updateMatcher tid e = e ^. eventType == E.TeamEvent'TEAM_UPDATE && decodeIdFromBS (e ^. teamId) == tid assertTeamUpdate :: HasCallStack => String -> TeamId -> Int32 -> [UserId] -> TestM () assertTeamUpdate l tid c uids = assertIfWatcher l (\e -> e ^. eventType == E.TeamEvent'TEAM_UPDATE && decodeIdFromBS (e ^. teamId) == tid) $ tUpdate c uids initHttpManager :: IO Manager initHttpManager = do ctx <- Ssl.context Ssl.contextSetVerificationMode ctx $ Ssl.VerifyPeer True True Nothing Ssl.contextAddOption ctx SSL_OP_NO_SSLv2 Ssl.contextAddOption ctx SSL_OP_NO_SSLv3 Ssl.contextAddOption ctx SSL_OP_NO_TLSv1 Ssl.contextSetCiphers ctx rsaCiphers Ssl.contextSetDefaultVerifyPaths ctx newManager { managerResponseTimeout = responseTimeoutMicro 10000000, managerConnCount = 100, managerIdleConnectionCount = 300 } mkAWSEnv :: JournalOpts -> IO Aws.Env mkAWSEnv opts = do mgr <- initHttpManager Aws.mkEnv l mgr opts decodeIdFromBS :: ByteString -> Id a decodeIdFromBS = Id . fromMaybe (error "failed to decode userId") . UUID.fromByteString . fromStrict
9b9f071a04398e3393426b0c79e117a3ac29b690f97831a50d72cdc0dfd82468
haskell/time
MonthOfYear.hs
module Test.Calendar.MonthOfYear ( testMonthOfYear, ) where import Data.Foldable import Data.Time.Calendar import Test.Tasty import Test.Tasty.HUnit matchMonthOfYear :: MonthOfYear -> Int matchMonthOfYear m = case m of January -> 1 February -> 2 March -> 3 April -> 4 May -> 5 June -> 6 July -> 7 August -> 8 September -> 9 October -> 10 November -> 11 December -> 12 testMonthOfYear :: TestTree testMonthOfYear = testCase "MonthOfYear" $ for_ [1 .. 12] $ \m -> assertEqual (show m) m $ matchMonthOfYear m
null
https://raw.githubusercontent.com/haskell/time/c310f2f9de662e2db0509f6acb53c1d46b2cfe3e/test/main/Test/Calendar/MonthOfYear.hs
haskell
module Test.Calendar.MonthOfYear ( testMonthOfYear, ) where import Data.Foldable import Data.Time.Calendar import Test.Tasty import Test.Tasty.HUnit matchMonthOfYear :: MonthOfYear -> Int matchMonthOfYear m = case m of January -> 1 February -> 2 March -> 3 April -> 4 May -> 5 June -> 6 July -> 7 August -> 8 September -> 9 October -> 10 November -> 11 December -> 12 testMonthOfYear :: TestTree testMonthOfYear = testCase "MonthOfYear" $ for_ [1 .. 12] $ \m -> assertEqual (show m) m $ matchMonthOfYear m
56168691d5835045501207d24cb6a52b4740aca06c60c01cf4568478a096f910
MinaProtocol/mina
common.ml
open Core_kernel open Mina_base type invalid = [ `Invalid_keys of Signature_lib.Public_key.Compressed.Stable.Latest.t list | `Invalid_signature of Signature_lib.Public_key.Compressed.Stable.Latest.t list | `Invalid_proof of (Error.t[@to_yojson Error_json.error_to_yojson]) | `Missing_verification_key of Signature_lib.Public_key.Compressed.Stable.Latest.t list | `Unexpected_verification_key of Signature_lib.Public_key.Compressed.Stable.Latest.t list | `Mismatched_authorization_kind of Signature_lib.Public_key.Compressed.Stable.Latest.t list ] [@@deriving bin_io_unversioned, to_yojson] let invalid_to_error (invalid : invalid) : Error.t = let keys_to_string keys = List.map keys ~f:(fun key -> Signature_lib.Public_key.Compressed.to_base58_check key ) |> String.concat ~sep:";" in match invalid with | `Invalid_keys keys -> Error.createf "Invalid_keys: [%s]" (keys_to_string keys) | `Invalid_signature keys -> Error.createf "Invalid_signature: [%s]" (keys_to_string keys) | `Missing_verification_key keys -> Error.createf "Missing_verification_key: [%s]" (keys_to_string keys) | `Unexpected_verification_key keys -> Error.createf "Unexpected_verification_key: [%s]" (keys_to_string keys) | `Mismatched_authorization_kind keys -> Error.createf "Mismatched_authorization_kind: [%s]" (keys_to_string keys) | `Invalid_proof err -> Error.tag ~tag:"Invalid_proof" err let check : User_command.Verifiable.t With_status.t -> [ `Valid of User_command.Valid.t | `Valid_assuming of User_command.Valid.t * _ list | invalid ] = function | { With_status.data = User_command.Signed_command c; status = _ } -> ( if not (Signed_command.check_valid_keys c) then `Invalid_keys (Signed_command.public_keys c) else match Signed_command.check_only_for_signature c with | Some c -> `Valid (User_command.Signed_command c) | None -> `Invalid_signature (Signed_command.public_keys c) ) | { With_status.data = Zkapp_command ({ fee_payer; account_updates; memo } as zkapp_command_with_vk) ; status } -> with_return (fun { return } -> let account_updates_hash = Zkapp_command.Call_forest.hash account_updates in let tx_commitment = Zkapp_command.Transaction_commitment.create ~account_updates_hash in let full_tx_commitment = Zkapp_command.Transaction_commitment.create_complete tx_commitment ~memo_hash:(Signed_command_memo.hash memo) ~fee_payer_hash: (Zkapp_command.Digest.Account_update.create (Account_update.of_fee_payer fee_payer) ) in let check_signature s pk msg = match Signature_lib.Public_key.decompress pk with | None -> return (`Invalid_keys [ pk ]) | Some pk -> if not (Signature_lib.Schnorr.Chunked.verify s (Backend.Tick.Inner_curve.of_affine pk) (Random_oracle_input.Chunked.field msg) ) then return (`Invalid_signature [ Signature_lib.Public_key.compress pk ]) else () in check_signature fee_payer.authorization fee_payer.body.public_key full_tx_commitment ; let zkapp_command_with_hashes_list = account_updates |> Zkapp_statement.zkapp_statements_of_forest' |> Zkapp_command.Call_forest.With_hashes_and_data .to_zkapp_command_with_hashes_list in let valid_assuming = List.filter_map zkapp_command_with_hashes_list ~f:(fun ((p, (vk_opt, stmt)), _at_account_update) -> let commitment = if p.body.use_full_commitment then full_tx_commitment else tx_commitment in match (p.authorization, p.body.authorization_kind) with | Signature s, Signature -> check_signature s p.body.public_key commitment ; None | None_given, None_given -> None | Proof pi, Proof vk_hash -> ( match status with | Applied -> ( match vk_opt with | None -> return (`Missing_verification_key [ Account_id.public_key @@ Account_update.account_id p ] ) | Some (vk : _ With_hash.t) -> if (* check that vk expected for proof is the one being used *) Snark_params.Tick.Field.equal vk_hash (With_hash.hash vk) then Some (vk.data, stmt, pi) else return (`Unexpected_verification_key [ Account_id.public_key @@ Account_update.account_id p ] ) ) | Failed _ -> (* Don't verify the proof if it has failed. *) None ) | _ -> return (`Mismatched_authorization_kind [ Account_id.public_key @@ Account_update.account_id p ] ) ) in let v : User_command.Valid.t = (* Verification keys should be present if it reaches here *) let zkapp_command = Zkapp_command.Valid.of_verifiable zkapp_command_with_vk in User_command.Poly.Zkapp_command zkapp_command in match valid_assuming with | [] -> `Valid v | _ :: _ -> `Valid_assuming (v, valid_assuming) )
null
https://raw.githubusercontent.com/MinaProtocol/mina/3cece748c078b9d63020e7eed5114f87dd167f68/src/lib/verifier/common.ml
ocaml
check that vk expected for proof is the one being used Don't verify the proof if it has failed. Verification keys should be present if it reaches here
open Core_kernel open Mina_base type invalid = [ `Invalid_keys of Signature_lib.Public_key.Compressed.Stable.Latest.t list | `Invalid_signature of Signature_lib.Public_key.Compressed.Stable.Latest.t list | `Invalid_proof of (Error.t[@to_yojson Error_json.error_to_yojson]) | `Missing_verification_key of Signature_lib.Public_key.Compressed.Stable.Latest.t list | `Unexpected_verification_key of Signature_lib.Public_key.Compressed.Stable.Latest.t list | `Mismatched_authorization_kind of Signature_lib.Public_key.Compressed.Stable.Latest.t list ] [@@deriving bin_io_unversioned, to_yojson] let invalid_to_error (invalid : invalid) : Error.t = let keys_to_string keys = List.map keys ~f:(fun key -> Signature_lib.Public_key.Compressed.to_base58_check key ) |> String.concat ~sep:";" in match invalid with | `Invalid_keys keys -> Error.createf "Invalid_keys: [%s]" (keys_to_string keys) | `Invalid_signature keys -> Error.createf "Invalid_signature: [%s]" (keys_to_string keys) | `Missing_verification_key keys -> Error.createf "Missing_verification_key: [%s]" (keys_to_string keys) | `Unexpected_verification_key keys -> Error.createf "Unexpected_verification_key: [%s]" (keys_to_string keys) | `Mismatched_authorization_kind keys -> Error.createf "Mismatched_authorization_kind: [%s]" (keys_to_string keys) | `Invalid_proof err -> Error.tag ~tag:"Invalid_proof" err let check : User_command.Verifiable.t With_status.t -> [ `Valid of User_command.Valid.t | `Valid_assuming of User_command.Valid.t * _ list | invalid ] = function | { With_status.data = User_command.Signed_command c; status = _ } -> ( if not (Signed_command.check_valid_keys c) then `Invalid_keys (Signed_command.public_keys c) else match Signed_command.check_only_for_signature c with | Some c -> `Valid (User_command.Signed_command c) | None -> `Invalid_signature (Signed_command.public_keys c) ) | { With_status.data = Zkapp_command ({ fee_payer; account_updates; memo } as zkapp_command_with_vk) ; status } -> with_return (fun { return } -> let account_updates_hash = Zkapp_command.Call_forest.hash account_updates in let tx_commitment = Zkapp_command.Transaction_commitment.create ~account_updates_hash in let full_tx_commitment = Zkapp_command.Transaction_commitment.create_complete tx_commitment ~memo_hash:(Signed_command_memo.hash memo) ~fee_payer_hash: (Zkapp_command.Digest.Account_update.create (Account_update.of_fee_payer fee_payer) ) in let check_signature s pk msg = match Signature_lib.Public_key.decompress pk with | None -> return (`Invalid_keys [ pk ]) | Some pk -> if not (Signature_lib.Schnorr.Chunked.verify s (Backend.Tick.Inner_curve.of_affine pk) (Random_oracle_input.Chunked.field msg) ) then return (`Invalid_signature [ Signature_lib.Public_key.compress pk ]) else () in check_signature fee_payer.authorization fee_payer.body.public_key full_tx_commitment ; let zkapp_command_with_hashes_list = account_updates |> Zkapp_statement.zkapp_statements_of_forest' |> Zkapp_command.Call_forest.With_hashes_and_data .to_zkapp_command_with_hashes_list in let valid_assuming = List.filter_map zkapp_command_with_hashes_list ~f:(fun ((p, (vk_opt, stmt)), _at_account_update) -> let commitment = if p.body.use_full_commitment then full_tx_commitment else tx_commitment in match (p.authorization, p.body.authorization_kind) with | Signature s, Signature -> check_signature s p.body.public_key commitment ; None | None_given, None_given -> None | Proof pi, Proof vk_hash -> ( match status with | Applied -> ( match vk_opt with | None -> return (`Missing_verification_key [ Account_id.public_key @@ Account_update.account_id p ] ) | Some (vk : _ With_hash.t) -> if Snark_params.Tick.Field.equal vk_hash (With_hash.hash vk) then Some (vk.data, stmt, pi) else return (`Unexpected_verification_key [ Account_id.public_key @@ Account_update.account_id p ] ) ) | Failed _ -> None ) | _ -> return (`Mismatched_authorization_kind [ Account_id.public_key @@ Account_update.account_id p ] ) ) in let v : User_command.Valid.t = let zkapp_command = Zkapp_command.Valid.of_verifiable zkapp_command_with_vk in User_command.Poly.Zkapp_command zkapp_command in match valid_assuming with | [] -> `Valid v | _ :: _ -> `Valid_assuming (v, valid_assuming) )
1059984db7150983e84876008e7200e9e72c3feb42ebb76e72e57f890c83610a
Ericson2314/lighthouse
Chance.hs
module LwConc.Scheduler.Chance ( getNextThread , schedule , timeUp , dumpQueueLengths ) where -- This is a multi-level queue scheduler, taking priority into account. -- To select a priority level , it starts with maxBound , and rolls a die . If < 10 , it moves to a lower level , and starts over . import System.IO.Unsafe (unsafePerformIO) import Data.Sequence as Seq import GHC.Arr as Array import LwConc.PTM import LwConc.Threads import GHC.Float(double2Int, int2Double) Introducing the world 's worst random number generator ( 32 - bit only ) -- randomX :: PVar Integer randomX = unsafePerformIO $ newPVarIO 42133786 -- just some seed random :: PTM Int random = do x <- readPVar randomX let x' = (1103515245 * x + 12345) `mod` 4294967296 writePVar randomX x' return (fromInteger x') |Returns a random number between 0 and 99 ... probably . d100 :: PTM Int d100 = do x <- random return $ double2Int ((int2Double x) * 100 / 4294967296) timeUp :: IO Bool timeUp = return True type ReadyQ = PVar (Seq Thread) -- |An array of ready queues, indexed by priority. readyQs :: Array Priority ReadyQ readyQs = listArray (minBound, maxBound) (unsafePerformIO $ sequence [newPVarIO Seq.empty | p <- [minBound .. maxBound :: Priority]]) -- |Returns which priority to pull the next thread from, and updates the countdown for next time. getNextPriority :: PTM Priority getNextPriority = helper maxBound where helper x | x == minBound = return x helper x = do r <- d100 if r < 10 -- % chance of trying a lower priority. then helper (pred x) else return x -- |Returns the next ready thread, or Nothing. getNextThread :: PTM (Maybe Thread) getNextThread = do priority <- getNextPriority tryAt priority where tryAt priority = do let readyQ = readyQs ! priority q <- readPVar readyQ case viewl q of (t :< ts) -> do writePVar readyQ ts return (Just t) EmptyL -> if priority == minBound then return Nothing else tryAt (pred priority) -- nothing to run at this priority, try something lower. -- |Marks a thread "ready" and schedules it for some future time. schedule :: Thread -> PTM () schedule thread@(Thread tcb _) = do priority <- getPriority tcb let readyQ = readyQs ! priority q <- readPVar readyQ writePVar readyQ (q |> thread) dumpQueueLengths :: (String -> IO ()) -> IO () dumpQueueLengths cPrint = mapM_ dumpQL [minBound .. maxBound] where dumpQL :: Priority -> IO () dumpQL p = do len <- atomically $ do q <- readPVar (readyQs ! p) return (Seq.length q) cPrint ("|readyQ[" ++ show p ++ "]| = " ++ show len ++ "\n")
null
https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/base/LwConc/Scheduler/Chance.hs
haskell
This is a multi-level queue scheduler, taking priority into account. just some seed |An array of ready queues, indexed by priority. |Returns which priority to pull the next thread from, and updates the countdown for next time. % chance of trying a lower priority. |Returns the next ready thread, or Nothing. nothing to run at this priority, try something lower. |Marks a thread "ready" and schedules it for some future time.
module LwConc.Scheduler.Chance ( getNextThread , schedule , timeUp , dumpQueueLengths ) where To select a priority level , it starts with maxBound , and rolls a die . If < 10 , it moves to a lower level , and starts over . import System.IO.Unsafe (unsafePerformIO) import Data.Sequence as Seq import GHC.Arr as Array import LwConc.PTM import LwConc.Threads import GHC.Float(double2Int, int2Double) Introducing the world 's worst random number generator ( 32 - bit only ) randomX :: PVar Integer random :: PTM Int random = do x <- readPVar randomX let x' = (1103515245 * x + 12345) `mod` 4294967296 writePVar randomX x' return (fromInteger x') |Returns a random number between 0 and 99 ... probably . d100 :: PTM Int d100 = do x <- random return $ double2Int ((int2Double x) * 100 / 4294967296) timeUp :: IO Bool timeUp = return True type ReadyQ = PVar (Seq Thread) readyQs :: Array Priority ReadyQ readyQs = listArray (minBound, maxBound) (unsafePerformIO $ sequence [newPVarIO Seq.empty | p <- [minBound .. maxBound :: Priority]]) getNextPriority :: PTM Priority getNextPriority = helper maxBound where helper x | x == minBound = return x helper x = do r <- d100 then helper (pred x) else return x getNextThread :: PTM (Maybe Thread) getNextThread = do priority <- getNextPriority tryAt priority where tryAt priority = do let readyQ = readyQs ! priority q <- readPVar readyQ case viewl q of (t :< ts) -> do writePVar readyQ ts return (Just t) EmptyL -> if priority == minBound then return Nothing schedule :: Thread -> PTM () schedule thread@(Thread tcb _) = do priority <- getPriority tcb let readyQ = readyQs ! priority q <- readPVar readyQ writePVar readyQ (q |> thread) dumpQueueLengths :: (String -> IO ()) -> IO () dumpQueueLengths cPrint = mapM_ dumpQL [minBound .. maxBound] where dumpQL :: Priority -> IO () dumpQL p = do len <- atomically $ do q <- readPVar (readyQs ! p) return (Seq.length q) cPrint ("|readyQ[" ++ show p ++ "]| = " ++ show len ++ "\n")
66b3951f5f721b36bbf35cf848cbeaf7e0f0930d20e057af8cdb86ed8e3d5206
conal/Fran
ShowFunctions.hs
From QuickCheck distribution . module ShowFunctions where instance Show (a->b) where show f = "<function>"
null
https://raw.githubusercontent.com/conal/Fran/a113693cfab23f9ac9704cfee9c610c5edc13d9d/src/ShowFunctions.hs
haskell
From QuickCheck distribution . module ShowFunctions where instance Show (a->b) where show f = "<function>"
648cac60821b5f7ef747307f2978a2002d7b54c41e75c273ea0fbd0158cb01d4
sfx/schema-contrib
gen.clj
(ns schema-contrib.gen (:import (java.util Locale)) (:require [clojure.string :as string] [clojure.test.check.generators :as gen])) (def country (gen/elements (Locale/getISOCountries))) (def country-keyword (->> (Locale/getISOCountries) (map keyword) gen/elements)) (def language (gen/elements (Locale/getISOLanguages))) (def language-keyword (->> (Locale/getISOLanguages) (map keyword) gen/elements))
null
https://raw.githubusercontent.com/sfx/schema-contrib/02cac012a982b40de570f9d5e432b58de54fa24c/src/schema_contrib/gen.clj
clojure
(ns schema-contrib.gen (:import (java.util Locale)) (:require [clojure.string :as string] [clojure.test.check.generators :as gen])) (def country (gen/elements (Locale/getISOCountries))) (def country-keyword (->> (Locale/getISOCountries) (map keyword) gen/elements)) (def language (gen/elements (Locale/getISOLanguages))) (def language-keyword (->> (Locale/getISOLanguages) (map keyword) gen/elements))
e9e7376ad87e15fd25613beac5215c273fbe92bd91714af635c7a3487335cfcd
fukamachi/clozure-cl
l1-boot-3.lisp
-*- Mode : Lisp ; Package : CCL -*- ;;; Copyright ( C ) 2009 Clozure Associates Copyright ( C ) 1994 - 2001 Digitool , Inc This file is part of Clozure CL . ;;; Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the ;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL, which is distributed with Clozure CL as the file " LGPL " . Where these ;;; conflict, the preamble takes precedence. ;;; ;;; Clozure CL is referenced in the preamble as the "LIBRARY." ;;; ;;; The LLGPL is also available online at ;;; ;;; l1-boot-3.lisp Third part of l1 - boot (in-package "CCL") Register Emacs - friendly aliases for some character encodings . ;;; This could go on forever; try to recognize at least some common ;;; cases. (The precise set of encoding/coding-system names supported by Emacs likely depends on Emacs version , loaded Emacs packages , etc . ) (dotimes (i 16) (let* ((key (find-symbol (format nil "LATIN~d" i) :keyword)) (existing (and key (lookup-character-encoding key)))) (when existing (define-character-encoding-alias (intern (format nil "LATIN-~d" i) :keyword) existing) (define-character-encoding-alias (intern (format nil "ISO-LATIN-~d" i) :keyword) existing)))) (define-character-encoding-alias :mule-utf-8 :utf-8) (catch :toplevel (or (find-package "COMMON-LISP-USER") (make-package "COMMON-LISP-USER" :use '("COMMON-LISP" "CCL") :NICKNAMES '("CL-USER"))) ) (set-periodic-task-interval .33) (setq cmain xcmain) (setq %err-disp %xerr-disp) end of l1-boot-3.lisp
null
https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/level-1/l1-boot-3.lisp
lisp
Package : CCL -*- file "LICENSE". The LLGPL consists of a preamble and the LGPL, conflict, the preamble takes precedence. Clozure CL is referenced in the preamble as the "LIBRARY." The LLGPL is also available online at l1-boot-3.lisp This could go on forever; try to recognize at least some common cases. (The precise set of encoding/coding-system names supported
Copyright ( C ) 2009 Clozure Associates Copyright ( C ) 1994 - 2001 Digitool , Inc This file is part of Clozure CL . Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the which is distributed with Clozure CL as the file " LGPL " . Where these Third part of l1 - boot (in-package "CCL") Register Emacs - friendly aliases for some character encodings . by Emacs likely depends on Emacs version , loaded Emacs packages , etc . ) (dotimes (i 16) (let* ((key (find-symbol (format nil "LATIN~d" i) :keyword)) (existing (and key (lookup-character-encoding key)))) (when existing (define-character-encoding-alias (intern (format nil "LATIN-~d" i) :keyword) existing) (define-character-encoding-alias (intern (format nil "ISO-LATIN-~d" i) :keyword) existing)))) (define-character-encoding-alias :mule-utf-8 :utf-8) (catch :toplevel (or (find-package "COMMON-LISP-USER") (make-package "COMMON-LISP-USER" :use '("COMMON-LISP" "CCL") :NICKNAMES '("CL-USER"))) ) (set-periodic-task-interval .33) (setq cmain xcmain) (setq %err-disp %xerr-disp) end of l1-boot-3.lisp
d2c5a1e55fc50e9ffc9b4b05483d2347225c467e9feaabd1b18ed496689702c2
gowthamk/ocaml-irmin
test_counter.ml
open Icounter open Counter (* Utility functions *) U is a module with two functions module U = struct let string_of_list f l = "[ " ^ List.fold_left (fun a b -> a ^ (f b) ^ "; ") "" l ^ "]" let print_header h = Printf.printf "%s" ("\n" ^ h ^ "\n") end (* Set - AVL Tree *) let _ = U.print_header "Counter"; let module MkConfig (Vars: sig val root: string end) : Icounter.Config = struct let root = Vars.root let shared = "/tmp/repos/shared.git" let init () = let _ = Sys.command (Printf.sprintf "rm -rf %s" root) in let _ = Sys.command (Printf.sprintf "mkdir -p %s" root) in () end in let module CInit = MkConfig(struct let root = "/tmp/repos/init.git" end) in let module MInit = Icounter.MakeVersioned(CInit) in let module M = Counter.Make in let module Vpst = MInit.Vpst in let (>>=) = Vpst.bind in let thread2_f : unit Vpst.t = Vpst.get_latest_version () >>= fun c0 -> Thread2 increments the counter once by 10 let c0' = M.inc c0 10 in (* Thread2 syncs with master. Observes no changes. *) Vpst.sync_next_version ~v:c0' >>= fun c1 -> Thread2 blocks for 0.5s Vpst.liftLwt @@ Lwt_unix.sleep 0.5 >>= fun () -> Thread2 decrements by 9 . let c1' = M.dec c1 9 in * Syncs with master . Merges master 's counter * value ( 11 ) with the local value ( 1 ) . The common * ancestor is 10 . The final value is 2 . * Syncs with master. Merges master's counter * value (11) with the local value (1). The common * ancestor is 10. The final value is 2. *) Vpst.sync_next_version ~v:c1' >>= fun c2 -> let _ = Printf.printf "thread2 (before exiting): %d\n" c2 in Vpst.return () in let thread1_f : unit Vpst.t = Vpst.get_latest_version () >>= fun c0 -> (* Thread1 forks thread2 *) Vpst.fork_version thread2_f >>= fun () -> Thread1 blocks for 0.1s Vpst.liftLwt @@ Lwt_unix.sleep 0.1 >>= fun () -> Increments the counter twice - by 2 and 3 , resp . let c0' = M.inc (M.inc c0 2) 3 in Syncs with master . Merges the current local value * ( 5 ) with master 's value ( 10 ) . The common ancestor * is 0 . The result 15 . * (5) with master's value (10). The common ancestor * is 0. The result 15. *) Vpst.sync_next_version ~v:c0' >>= fun c1 -> (* Thread1 blocks on some operation *) Vpst.liftLwt @@ Lwt_unix.sleep 0.1 >>= fun () -> Decrements by 4 . let c1' = M.dec c1 4 in Syncs with the master again . Publishes 11 . Vpst.sync_next_version ~v:c1' >>= fun c2 -> let _ = Printf.printf "thread1: %d\n" c2 in Vpst.liftLwt @@ Lwt_unix.sleep 1.1 >>= fun () -> Vpst.sync_next_version ~v:c2 >>= fun c3-> let _ = Printf.printf "thread1 (before exiting): %d\n" c3 in Vpst.return () in let main () = * starts with a blank canvas . * thread1 starts with a blank canvas. *) Vpst.with_init_version_do 0 thread1_f in main ();;
null
https://raw.githubusercontent.com/gowthamk/ocaml-irmin/54775f6c3012e87d2d0308f37a2ec7b27477e887/counter/test_counter.ml
ocaml
Utility functions Set - AVL Tree Thread2 syncs with master. Observes no changes. Thread1 forks thread2 Thread1 blocks on some operation
open Icounter open Counter U is a module with two functions module U = struct let string_of_list f l = "[ " ^ List.fold_left (fun a b -> a ^ (f b) ^ "; ") "" l ^ "]" let print_header h = Printf.printf "%s" ("\n" ^ h ^ "\n") end let _ = U.print_header "Counter"; let module MkConfig (Vars: sig val root: string end) : Icounter.Config = struct let root = Vars.root let shared = "/tmp/repos/shared.git" let init () = let _ = Sys.command (Printf.sprintf "rm -rf %s" root) in let _ = Sys.command (Printf.sprintf "mkdir -p %s" root) in () end in let module CInit = MkConfig(struct let root = "/tmp/repos/init.git" end) in let module MInit = Icounter.MakeVersioned(CInit) in let module M = Counter.Make in let module Vpst = MInit.Vpst in let (>>=) = Vpst.bind in let thread2_f : unit Vpst.t = Vpst.get_latest_version () >>= fun c0 -> Thread2 increments the counter once by 10 let c0' = M.inc c0 10 in Vpst.sync_next_version ~v:c0' >>= fun c1 -> Thread2 blocks for 0.5s Vpst.liftLwt @@ Lwt_unix.sleep 0.5 >>= fun () -> Thread2 decrements by 9 . let c1' = M.dec c1 9 in * Syncs with master . Merges master 's counter * value ( 11 ) with the local value ( 1 ) . The common * ancestor is 10 . The final value is 2 . * Syncs with master. Merges master's counter * value (11) with the local value (1). The common * ancestor is 10. The final value is 2. *) Vpst.sync_next_version ~v:c1' >>= fun c2 -> let _ = Printf.printf "thread2 (before exiting): %d\n" c2 in Vpst.return () in let thread1_f : unit Vpst.t = Vpst.get_latest_version () >>= fun c0 -> Vpst.fork_version thread2_f >>= fun () -> Thread1 blocks for 0.1s Vpst.liftLwt @@ Lwt_unix.sleep 0.1 >>= fun () -> Increments the counter twice - by 2 and 3 , resp . let c0' = M.inc (M.inc c0 2) 3 in Syncs with master . Merges the current local value * ( 5 ) with master 's value ( 10 ) . The common ancestor * is 0 . The result 15 . * (5) with master's value (10). The common ancestor * is 0. The result 15. *) Vpst.sync_next_version ~v:c0' >>= fun c1 -> Vpst.liftLwt @@ Lwt_unix.sleep 0.1 >>= fun () -> Decrements by 4 . let c1' = M.dec c1 4 in Syncs with the master again . Publishes 11 . Vpst.sync_next_version ~v:c1' >>= fun c2 -> let _ = Printf.printf "thread1: %d\n" c2 in Vpst.liftLwt @@ Lwt_unix.sleep 1.1 >>= fun () -> Vpst.sync_next_version ~v:c2 >>= fun c3-> let _ = Printf.printf "thread1 (before exiting): %d\n" c3 in Vpst.return () in let main () = * starts with a blank canvas . * thread1 starts with a blank canvas. *) Vpst.with_init_version_do 0 thread1_f in main ();;
a5d9b0e1093765d5eba1ded1395ffb44669eba226b5599d3cf1131d0544b77c9
arttuka/reagent-material-ui
swipeable_drawer.cljs
(ns reagent-mui.material.swipeable-drawer "Imports @mui/material/SwipeableDrawer as a Reagent component. Original documentation is at -ui/api/swipeable-drawer/ ." (:require [reagent.core :as r] ["@mui/material/SwipeableDrawer" :as MuiSwipeableDrawer])) (def swipeable-drawer (r/adapt-react-class (.-default MuiSwipeableDrawer)))
null
https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/core/reagent_mui/material/swipeable_drawer.cljs
clojure
(ns reagent-mui.material.swipeable-drawer "Imports @mui/material/SwipeableDrawer as a Reagent component. Original documentation is at -ui/api/swipeable-drawer/ ." (:require [reagent.core :as r] ["@mui/material/SwipeableDrawer" :as MuiSwipeableDrawer])) (def swipeable-drawer (r/adapt-react-class (.-default MuiSwipeableDrawer)))
843b4c13b69792e8abbc585fff7644cc7db0fe9270db59bb105e403db25f9a26
mainland/dph
DistST.hs
{-# OPTIONS -Wall -fno-warn-orphans -fno-warn-missing-signatures #-} # LANGUAGE ScopedTypeVariables # -- | Distributed ST computations. -- -- Computations of type 'DistST' are data-parallel computations which -- are run on each thread of a gang. At the moment, they can only access the -- element of a (possibly mutable) distributed value owned by the current -- thread. -- -- /TODO:/ Add facilities for implementing parallel scans etc. -- -- TODO: -- module Data.Array.Parallel.Unlifted.Distributed.Primitive.DistST ( DistST -- * Primitives. , stToDistST , distST_, distST , runDistST, runDistST_seq , myIndex , myD , readMyMD, writeMyMD * Monadic combinators , mapDST_, mapDST, zipWithDST_, zipWithDST) where import qualified Data.Array.Parallel.Unlifted.Distributed.What as W import Data.Array.Parallel.Unlifted.Distributed.Primitive.DT import Data.Array.Parallel.Unlifted.Distributed.Primitive.Gang import Data.Array.Parallel.Unlifted.Distributed.Data.Tuple import Data.Array.Parallel.Base (ST, runST) import Control.Monad (liftM) -- | Data-parallel computations. -- When applied to a thread gang, the computation implicitly knows the index -- of the thread it's working on. Alternatively, if we know the thread index -- then we can make a regular ST computation. newtype DistST s a = DistST { unDistST :: Int -> ST s a } instance Monad (DistST s) where # INLINE return # return = DistST . const . return {-# INLINE (>>=) #-} DistST p >>= f = DistST $ \i -> do x <- p i unDistST (f x) i -- Primitives ----------------------------------------------------------------- -- | Yields the index of the current thread within its gang. myIndex :: DistST s Int myIndex = DistST return {-# INLINE myIndex #-} -- | Lifts an 'ST' computation into the 'DistST' monad. -- The lifted computation should be data parallel. stToDistST :: ST s a -> DistST s a stToDistST p = DistST $ \_ -> p # INLINE stToDistST # -- | Yields the 'Dist' element owned by the current thread. myD :: DT a => Dist a -> DistST s a myD dt = liftM (indexD "myD" dt) myIndex # NOINLINE myD # | Yields the ' MDist ' element owned by the current thread . readMyMD :: DT a => MDist a s -> DistST s a readMyMD mdt = do i <- myIndex stToDistST $ readMD mdt i # NOINLINE readMyMD # | Writes the ' MDist ' element owned by the current thread . writeMyMD :: DT a => MDist a s -> a -> DistST s () writeMyMD mdt x = do i <- myIndex stToDistST $ writeMD mdt i x # NOINLINE writeMyMD # -- Running -------------------------------------------------------------------- -- | Run a data-parallel computation, yielding the distributed result. runDistST :: DT a => W.Comp -> Gang -> (forall s. DistST s a) -> Dist a runDistST comp g p = runST $ distST comp g p # NOINLINE runDistST # runDistST_seq :: forall a. DT a => Gang -> (forall s. DistST s a) -> Dist a runDistST_seq g p = runST $ do md <- newMD g go md 0 unsafeFreezeMD md where !n = gangSize g go :: forall s. MDist a s -> Int -> ST s () go md i | i < n = do writeMD md i =<< unDistST p i go md (i+1) | otherwise = return () # NOINLINE runDistST_seq # -- | Execute a data-parallel computation, yielding the distributed result. distST :: DT a => W.Comp -> Gang -> DistST s a -> ST s (Dist a) distST comp g p = do md <- newMD g distST_ comp g $ writeMyMD md =<< p unsafeFreezeMD md {-# INLINE distST #-} -- | Execute a data-parallel computation on a 'Gang'. -- The same DistST comutation runs on each thread. distST_ :: W.Comp -> Gang -> DistST s () -> ST s () distST_ comp gang proc = gangST gang (show comp) (workloadOfComp comp) $ unDistST proc {-# INLINE distST_ #-} workloadOfComp :: W.Comp -> Workload workloadOfComp cc = case cc of W.CDist w -> workloadOfWhat w _ -> WorkUnknown workloadOfWhat :: W.What -> Workload workloadOfWhat ww = case ww of W.WJoinCopy elems -> WorkCopy elems _ -> WorkUnknown -- Combinators ---------------------------------------------------------------- -- Versions that work on DistST ----------------------------------------------- NOTE : The following combinators must be strict in the Dists because if they -- are not, the Dist might be evaluated (in parallel) when it is requested in -- the current computation which, again, is parallel. This would break our -- model andlead to a deadlock. Hence the bangs. mapDST :: (DT a, DT b) => W.What -> Gang -> (a -> DistST s b) -> Dist a -> ST s (Dist b) mapDST what g p !d = mapDST' what g (\x -> x `deepSeqD` p x) d # INLINE mapDST # mapDST_ :: DT a => W.What -> Gang -> (a -> DistST s ()) -> Dist a -> ST s () mapDST_ what g p !d = mapDST_' what g (\x -> x `deepSeqD` p x) d {-# INLINE mapDST_ #-} mapDST' :: (DT a, DT b) => W.What -> Gang -> (a -> DistST s b) -> Dist a -> ST s (Dist b) mapDST' what g p !d = distST (W.CDist what) g (myD d >>= p) # INLINE mapDST ' # mapDST_' :: DT a => W.What -> Gang -> (a -> DistST s ()) -> Dist a -> ST s () mapDST_' what g p !d = distST_ (W.CDist what) g (myD d >>= p) {-# INLINE mapDST_' #-} zipWithDST :: (DT a, DT b, DT c) => W.What -> Gang -> (a -> b -> DistST s c) -> Dist a -> Dist b -> ST s (Dist c) zipWithDST what g p !dx !dy = mapDST what g (uncurry p) (zipD dx dy) # INLINE zipWithDST # zipWithDST_ :: (DT a, DT b) => W.What -> Gang -> (a -> b -> DistST s ()) -> Dist a -> Dist b -> ST s () zipWithDST_ what g p !dx !dy = mapDST_ what g (uncurry p) (zipD dx dy) # INLINE zipWithDST _ #
null
https://raw.githubusercontent.com/mainland/dph/742078c9e18b7dcf6526348e08d2dd16e2334739/dph-prim-par/Data/Array/Parallel/Unlifted/Distributed/Primitive/DistST.hs
haskell
# OPTIONS -Wall -fno-warn-orphans -fno-warn-missing-signatures # | Distributed ST computations. Computations of type 'DistST' are data-parallel computations which are run on each thread of a gang. At the moment, they can only access the element of a (possibly mutable) distributed value owned by the current thread. /TODO:/ Add facilities for implementing parallel scans etc. TODO: * Primitives. | Data-parallel computations. When applied to a thread gang, the computation implicitly knows the index of the thread it's working on. Alternatively, if we know the thread index then we can make a regular ST computation. # INLINE (>>=) # Primitives ----------------------------------------------------------------- | Yields the index of the current thread within its gang. # INLINE myIndex # | Lifts an 'ST' computation into the 'DistST' monad. The lifted computation should be data parallel. | Yields the 'Dist' element owned by the current thread. Running -------------------------------------------------------------------- | Run a data-parallel computation, yielding the distributed result. | Execute a data-parallel computation, yielding the distributed result. # INLINE distST # | Execute a data-parallel computation on a 'Gang'. The same DistST comutation runs on each thread. # INLINE distST_ # Combinators ---------------------------------------------------------------- Versions that work on DistST ----------------------------------------------- are not, the Dist might be evaluated (in parallel) when it is requested in the current computation which, again, is parallel. This would break our model andlead to a deadlock. Hence the bangs. # INLINE mapDST_ # # INLINE mapDST_' #
# LANGUAGE ScopedTypeVariables # module Data.Array.Parallel.Unlifted.Distributed.Primitive.DistST ( DistST , stToDistST , distST_, distST , runDistST, runDistST_seq , myIndex , myD , readMyMD, writeMyMD * Monadic combinators , mapDST_, mapDST, zipWithDST_, zipWithDST) where import qualified Data.Array.Parallel.Unlifted.Distributed.What as W import Data.Array.Parallel.Unlifted.Distributed.Primitive.DT import Data.Array.Parallel.Unlifted.Distributed.Primitive.Gang import Data.Array.Parallel.Unlifted.Distributed.Data.Tuple import Data.Array.Parallel.Base (ST, runST) import Control.Monad (liftM) newtype DistST s a = DistST { unDistST :: Int -> ST s a } instance Monad (DistST s) where # INLINE return # return = DistST . const . return DistST p >>= f = DistST $ \i -> do x <- p i unDistST (f x) i myIndex :: DistST s Int myIndex = DistST return stToDistST :: ST s a -> DistST s a stToDistST p = DistST $ \_ -> p # INLINE stToDistST # myD :: DT a => Dist a -> DistST s a myD dt = liftM (indexD "myD" dt) myIndex # NOINLINE myD # | Yields the ' MDist ' element owned by the current thread . readMyMD :: DT a => MDist a s -> DistST s a readMyMD mdt = do i <- myIndex stToDistST $ readMD mdt i # NOINLINE readMyMD # | Writes the ' MDist ' element owned by the current thread . writeMyMD :: DT a => MDist a s -> a -> DistST s () writeMyMD mdt x = do i <- myIndex stToDistST $ writeMD mdt i x # NOINLINE writeMyMD # runDistST :: DT a => W.Comp -> Gang -> (forall s. DistST s a) -> Dist a runDistST comp g p = runST $ distST comp g p # NOINLINE runDistST # runDistST_seq :: forall a. DT a => Gang -> (forall s. DistST s a) -> Dist a runDistST_seq g p = runST $ do md <- newMD g go md 0 unsafeFreezeMD md where !n = gangSize g go :: forall s. MDist a s -> Int -> ST s () go md i | i < n = do writeMD md i =<< unDistST p i go md (i+1) | otherwise = return () # NOINLINE runDistST_seq # distST :: DT a => W.Comp -> Gang -> DistST s a -> ST s (Dist a) distST comp g p = do md <- newMD g distST_ comp g $ writeMyMD md =<< p unsafeFreezeMD md distST_ :: W.Comp -> Gang -> DistST s () -> ST s () distST_ comp gang proc = gangST gang (show comp) (workloadOfComp comp) $ unDistST proc workloadOfComp :: W.Comp -> Workload workloadOfComp cc = case cc of W.CDist w -> workloadOfWhat w _ -> WorkUnknown workloadOfWhat :: W.What -> Workload workloadOfWhat ww = case ww of W.WJoinCopy elems -> WorkCopy elems _ -> WorkUnknown NOTE : The following combinators must be strict in the Dists because if they mapDST :: (DT a, DT b) => W.What -> Gang -> (a -> DistST s b) -> Dist a -> ST s (Dist b) mapDST what g p !d = mapDST' what g (\x -> x `deepSeqD` p x) d # INLINE mapDST # mapDST_ :: DT a => W.What -> Gang -> (a -> DistST s ()) -> Dist a -> ST s () mapDST_ what g p !d = mapDST_' what g (\x -> x `deepSeqD` p x) d mapDST' :: (DT a, DT b) => W.What -> Gang -> (a -> DistST s b) -> Dist a -> ST s (Dist b) mapDST' what g p !d = distST (W.CDist what) g (myD d >>= p) # INLINE mapDST ' # mapDST_' :: DT a => W.What -> Gang -> (a -> DistST s ()) -> Dist a -> ST s () mapDST_' what g p !d = distST_ (W.CDist what) g (myD d >>= p) zipWithDST :: (DT a, DT b, DT c) => W.What -> Gang -> (a -> b -> DistST s c) -> Dist a -> Dist b -> ST s (Dist c) zipWithDST what g p !dx !dy = mapDST what g (uncurry p) (zipD dx dy) # INLINE zipWithDST # zipWithDST_ :: (DT a, DT b) => W.What -> Gang -> (a -> b -> DistST s ()) -> Dist a -> Dist b -> ST s () zipWithDST_ what g p !dx !dy = mapDST_ what g (uncurry p) (zipD dx dy) # INLINE zipWithDST _ #
e8ce7c29307a5b8b0cae5771c5b318e4fabad0d680621100a8cd83255f4ddc9a
binaryage/cljs-devtools
runner.clj
(ns devtools.runner) (defmacro emit-clojure-version [] (clojure-version))
null
https://raw.githubusercontent.com/binaryage/cljs-devtools/d07fc6d404479b1ddd32cecc105009de77e3cba7/test/src/tests/devtools/runner.clj
clojure
(ns devtools.runner) (defmacro emit-clojure-version [] (clojure-version))
3358fdda76d965830f732e02e5ec8d22fd2a857bb1a3070614e32e58d600def5
CoNarrative/precept
figwheel.clj
(ns precept.figwheel (:require [figwheel-sidecar.repl-api :as ra])) (defn start-fw [] (ra/start-figwheel!)) (defn stop-fw [] (ra/stop-figwheel!)) (defn cljs [] (ra/cljs-repl))
null
https://raw.githubusercontent.com/CoNarrative/precept/6078286cae641b924a2bffca4ecba19dcc304dde/dev/clj/precept/figwheel.clj
clojure
(ns precept.figwheel (:require [figwheel-sidecar.repl-api :as ra])) (defn start-fw [] (ra/start-figwheel!)) (defn stop-fw [] (ra/stop-figwheel!)) (defn cljs [] (ra/cljs-repl))
7924a738dcca7e52b11fab9a41077190f6d05a68d66073f2ce1e334090cb33a0
conjure-cp/conjure
gen.hs
import Data.List nbCons :: [Int] nbCons = [0,10..100] main :: IO () main = do mapM_ (gen "set" ) nbCons mapM_ (gen "mset") nbCons gen :: String -> Int -> IO () gen setOrMSet n = writeFile (setOrMSet ++ "-" ++ pad 3 (show n) ++ ".essence") $ unlines $ [ "language Essence 1.3" , "given n, a, b " ++ concatMap (", "++ ) vals ++ ": int" , "find x : " ++ setOrMSet ++ " (size n) of int(a..b)" , "such that" ] ++ [ " " ++ val ++ " in x," | val <- vals ] ++ [" true"] where vals = map ("p"++) $ map show [1..n] pad :: Int -> String -> String pad n s = replicate (n - length s) '0' ++ s
null
https://raw.githubusercontent.com/conjure-cp/conjure/dd5a27df138af2ccbbb970274c2b8f22ac6b26a0/experiments/scaling/numberOfCons/gen.hs
haskell
import Data.List nbCons :: [Int] nbCons = [0,10..100] main :: IO () main = do mapM_ (gen "set" ) nbCons mapM_ (gen "mset") nbCons gen :: String -> Int -> IO () gen setOrMSet n = writeFile (setOrMSet ++ "-" ++ pad 3 (show n) ++ ".essence") $ unlines $ [ "language Essence 1.3" , "given n, a, b " ++ concatMap (", "++ ) vals ++ ": int" , "find x : " ++ setOrMSet ++ " (size n) of int(a..b)" , "such that" ] ++ [ " " ++ val ++ " in x," | val <- vals ] ++ [" true"] where vals = map ("p"++) $ map show [1..n] pad :: Int -> String -> String pad n s = replicate (n - length s) '0' ++ s
d967cca81437dc6d1f13abda381d022701f22be5df58873a2ebc2529ad5114bb
may-liu/qtalk
ejabberd_xml2pb_message.erl
-module(ejabberd_xml2pb_message). -include("message_pb.hrl"). -include("jlib.hrl"). -include("logger.hrl"). -export([xml2pb_msg/3]). encode_pb_xmpp_msg(Msg_Type,Client_Type,Read_Type,Client_version,Msg_ID,Channel_ID,Ex_INFO,Backup_info,Carbon,Message,ID,Time) -> Msg_Body = #messagebody{headers = ejabberd_xml2pb_public:encode_pb_stringheaders( [{<<"chatid">>,Msg_ID}, {<<"channelid">>,Channel_ID}, {<<"extendInfo">>,Ex_INFO}, {<<"backupinfo">>,Backup_info}, {<<"read_type">>,Read_Type}, {<<"carbon_message">>,Carbon}]), value = Message}, Xmpp = #xmppmessage{ messagetype = Msg_Type, clienttype = Client_Type, clientversion = Client_version, messageid = ID, body = Msg_Body, receivedtime = Time}, message_pb:encode_xmppmessage(Xmpp). struct_pb_xmpp_msg(From,To,Type,Msg_Type,Client_Type,Read_Type,Client_version,Msg_ID,Channel_ID,Ex_INFO,Backup_info,Carbon,Message,ID,Time) -> ?DEBUG("struct_pb_xmpp_msg 1111 ~p,Message ~p ~n",[Type,Message]), Msg = list_to_binary( encode_pb_xmpp_msg(message_pb:enum_to_int(messagetype,Msg_Type), message_pb:enum_to_int(clienttype,Client_Type), Read_Type,Client_version,Msg_ID,Channel_ID,Ex_INFO,Backup_info,Carbon,Message,ID,Time)), ?DEBUG("struct_pb_xmpp_msg Msg ~p ~n",[Msg]), Pb_Msg = list_to_binary(ejabberd_xml2pb_public:encode_pb_protomessage(From,To,Type,0,Msg)), Opt = ejabberd_xml2pb_public:get_proto_header_opt(Pb_Msg), list_to_binary(ejabberd_xml2pb_public:encode_pb_protoheader(Opt,Pb_Msg)). xml2pb_msg(From,To,Packet) -> case xml:get_attr(<<"type">>,Packet#xmlel.attrs) of false -> <<"">>; {Value,Type} -> Msg_ID = proplists:get_value(<<"id">>,Packet#xmlel.attrs,<<"1">>), Client_Type = proplists:get_value(<<"client_type">>,Packet#xmlel.attrs,<<"">>), Client_Ver = proplists:get_value(<<"client_ver">>,Packet#xmlel.attrs,<<"0">>), Carbon_Flag = proplists:get_value(<<"carbon_message">>,Packet#xmlel.attrs,<<"">>), Read_type = proplists:get_value(<<"read_type">>,Packet#xmlel.attrs,<<"">>), case xml:get_subtag(Packet,<<"body">>) of false -> case Type of <<"stat">> -> struct_pb_xmpp_msg(From,To,ejabberd_xml2pb_public:set_type(Type),ejabberd_xml2pb_public:set_msg_type(<<"1">>), ejabberd_xml2pb_public:set_client_type(<<"">>),<<"">>, binary_to_integer(Client_Ver),Msg_ID,<<"">>,<<"">>,<<"">>, <<"">>,<<"">>,<<"">>, mod_time:get_exact_timestamp()); _ -> <<"">> end; Body -> Msg_Type = proplists:get_value(<<"msgType">>,Body#xmlel.attrs,<<"1">>), Channel_ID = proplists:get_value(<<"channelid">>,Body#xmlel.attrs,<<"">>), Ex_INFO = proplists:get_value(<<"extendInfo">>,Body#xmlel.attrs,<<"">>), Backup_info = proplists:get_value(<<"backupinfo">>,Body#xmlel.attrs,<<"">>), Time = proplists:get_value(<<"msec_times">>,Body#xmlel.attrs,mod_time:get_exact_timestamp()), ID = case proplists:get_value(<<"id">>,Body#xmlel.attrs) of I when is_binary(I) -> I; _ -> list_to_binary("http_" ++ integer_to_list(random:uniform(65536)) ++ integer_to_list(mod_time:get_exact_timestamp())) end, ?DEBUG("from ~p,To ~p ,Body ~p ~n",[From,To,Packet]), Message = xml:get_subtag_cdata(Packet,<<"body">>), ?DEBUG("message ~p,Type ~p ~n",[Message,Msg_Type]), struct_pb_xmpp_msg(From,To,ejabberd_xml2pb_public:set_type(Type),ejabberd_xml2pb_public:set_msg_type(Msg_Type), ejabberd_xml2pb_public:set_client_type(Client_Type),Read_type, binary_to_integer(Client_Ver),Msg_ID,Channel_ID,Ex_INFO,Backup_info,Carbon_Flag, Message,ID,Time) end end.
null
https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/ejabberd_xml2pb_message.erl
erlang
-module(ejabberd_xml2pb_message). -include("message_pb.hrl"). -include("jlib.hrl"). -include("logger.hrl"). -export([xml2pb_msg/3]). encode_pb_xmpp_msg(Msg_Type,Client_Type,Read_Type,Client_version,Msg_ID,Channel_ID,Ex_INFO,Backup_info,Carbon,Message,ID,Time) -> Msg_Body = #messagebody{headers = ejabberd_xml2pb_public:encode_pb_stringheaders( [{<<"chatid">>,Msg_ID}, {<<"channelid">>,Channel_ID}, {<<"extendInfo">>,Ex_INFO}, {<<"backupinfo">>,Backup_info}, {<<"read_type">>,Read_Type}, {<<"carbon_message">>,Carbon}]), value = Message}, Xmpp = #xmppmessage{ messagetype = Msg_Type, clienttype = Client_Type, clientversion = Client_version, messageid = ID, body = Msg_Body, receivedtime = Time}, message_pb:encode_xmppmessage(Xmpp). struct_pb_xmpp_msg(From,To,Type,Msg_Type,Client_Type,Read_Type,Client_version,Msg_ID,Channel_ID,Ex_INFO,Backup_info,Carbon,Message,ID,Time) -> ?DEBUG("struct_pb_xmpp_msg 1111 ~p,Message ~p ~n",[Type,Message]), Msg = list_to_binary( encode_pb_xmpp_msg(message_pb:enum_to_int(messagetype,Msg_Type), message_pb:enum_to_int(clienttype,Client_Type), Read_Type,Client_version,Msg_ID,Channel_ID,Ex_INFO,Backup_info,Carbon,Message,ID,Time)), ?DEBUG("struct_pb_xmpp_msg Msg ~p ~n",[Msg]), Pb_Msg = list_to_binary(ejabberd_xml2pb_public:encode_pb_protomessage(From,To,Type,0,Msg)), Opt = ejabberd_xml2pb_public:get_proto_header_opt(Pb_Msg), list_to_binary(ejabberd_xml2pb_public:encode_pb_protoheader(Opt,Pb_Msg)). xml2pb_msg(From,To,Packet) -> case xml:get_attr(<<"type">>,Packet#xmlel.attrs) of false -> <<"">>; {Value,Type} -> Msg_ID = proplists:get_value(<<"id">>,Packet#xmlel.attrs,<<"1">>), Client_Type = proplists:get_value(<<"client_type">>,Packet#xmlel.attrs,<<"">>), Client_Ver = proplists:get_value(<<"client_ver">>,Packet#xmlel.attrs,<<"0">>), Carbon_Flag = proplists:get_value(<<"carbon_message">>,Packet#xmlel.attrs,<<"">>), Read_type = proplists:get_value(<<"read_type">>,Packet#xmlel.attrs,<<"">>), case xml:get_subtag(Packet,<<"body">>) of false -> case Type of <<"stat">> -> struct_pb_xmpp_msg(From,To,ejabberd_xml2pb_public:set_type(Type),ejabberd_xml2pb_public:set_msg_type(<<"1">>), ejabberd_xml2pb_public:set_client_type(<<"">>),<<"">>, binary_to_integer(Client_Ver),Msg_ID,<<"">>,<<"">>,<<"">>, <<"">>,<<"">>,<<"">>, mod_time:get_exact_timestamp()); _ -> <<"">> end; Body -> Msg_Type = proplists:get_value(<<"msgType">>,Body#xmlel.attrs,<<"1">>), Channel_ID = proplists:get_value(<<"channelid">>,Body#xmlel.attrs,<<"">>), Ex_INFO = proplists:get_value(<<"extendInfo">>,Body#xmlel.attrs,<<"">>), Backup_info = proplists:get_value(<<"backupinfo">>,Body#xmlel.attrs,<<"">>), Time = proplists:get_value(<<"msec_times">>,Body#xmlel.attrs,mod_time:get_exact_timestamp()), ID = case proplists:get_value(<<"id">>,Body#xmlel.attrs) of I when is_binary(I) -> I; _ -> list_to_binary("http_" ++ integer_to_list(random:uniform(65536)) ++ integer_to_list(mod_time:get_exact_timestamp())) end, ?DEBUG("from ~p,To ~p ,Body ~p ~n",[From,To,Packet]), Message = xml:get_subtag_cdata(Packet,<<"body">>), ?DEBUG("message ~p,Type ~p ~n",[Message,Msg_Type]), struct_pb_xmpp_msg(From,To,ejabberd_xml2pb_public:set_type(Type),ejabberd_xml2pb_public:set_msg_type(Msg_Type), ejabberd_xml2pb_public:set_client_type(Client_Type),Read_type, binary_to_integer(Client_Ver),Msg_ID,Channel_ID,Ex_INFO,Backup_info,Carbon_Flag, Message,ID,Time) end end.