_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 |
|---|---|---|---|---|---|---|---|---|
5db9fe499daa3934f5d57257f6af5cfa2f0595e707baf59d996cd55eb209c590 | Decentralized-Pictures/T4L3NT | michelson_v1_gas.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2019 - 2020 Nomadic Labs < >
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 Alpha_context
open Gas
module S = Saturation_repr
module Cost_of = struct
module S_syntax = struct
This is a good enough approximation . S.numbits 0 = 0
let log2 x = S.safe_int (1 + S.numbits x)
let ( + ) = S.add
let ( * ) = S.mul
let ( lsr ) = S.shift_right
end
let z_bytes (z : Z.t) =
let bits = Z.numbits z in
(7 + bits) / 8
let int_bytes (z : 'a Script_int.num) = z_bytes (Script_int.to_zint z)
let manager_operation = step_cost @@ S.safe_int 1_000
module Generated_costs = struct
(* Automatically generated costs functions. *)
model N_IAbs_int
(* Approximating 0.065045 x term *)
let cost_N_IAbs_int size = S.safe_int (25 + (size lsr 4))
(* model N_IAdd_bls12_381_fr *)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IAdd_bls12_381_fr = S.safe_int 45
(* model N_IAdd_bls12_381_g1 *)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IAdd_bls12_381_g1 = S.safe_int 925
model N_IAdd_bls12_381_g2
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IAdd_bls12_381_g2 = S.safe_int 2_520
let cost_linear_op_int size1 size2 =
let open S_syntax in
let v0 = S.safe_int (Compare.Int.max size1 size2) in
S.safe_int 55 + ((v0 lsr 4) + (v0 lsr 7))
model N_IAdd_int
(* Approximating 0.078154 x term *)
let cost_N_IAdd_int = cost_linear_op_int
(* model N_IAdd_nat *)
(* Approximating 0.077807 x term *)
let cost_N_IAdd_nat = cost_linear_op_int
model N_IAdd_seconds_to_timestamp
(* Approximating 0.078056 x term *)
let cost_N_IAdd_seconds_to_timestamp = cost_linear_op_int
model N_IAdd_tez
let cost_N_IAdd_tez = S.safe_int 20
model N_IAdd_timestamp_to_seconds
(* Approximating 0.077771 x term *)
let cost_N_IAdd_timestamp_to_seconds = cost_linear_op_int
model N_IAddress
let cost_N_IAddress = S.safe_int 10
model N_IAmount
let cost_N_IAmount = S.safe_int 15
model
let cost_N_IAnd = S.safe_int 20
(* model N_IAnd_int_nat *)
Approximating 0.076804 x 2 x term
let cost_N_IAnd_int_nat size1 size2 =
let open S_syntax in
let v0 = S.safe_int (Compare.Int.min size1 size2) in
S.safe_int 50 + ((v0 lsr 3) + (v0 lsr 6))
model N_IAnd_nat
(* Approximating 0.076804 x term *)
The difference with ` cost_N_IAnd_int_nat ` comes from Zarith , where the
complexity of ` Z.logand ` depends on the sign of the argument .
complexity of `Z.logand` depends on the sign of the argument. *)
let cost_N_IAnd_nat size1 size2 =
let open S_syntax in
let v0 = S.safe_int (Compare.Int.min size1 size2) in
S.safe_int 50 + ((v0 lsr 4) + (v0 lsr 7))
model
let cost_N_IApply = S.safe_int 160
(* model N_IBlake2b *)
Approximating 1.120804 x term
let cost_N_IBlake2b size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 430 + v0 + (v0 lsr 3)
(* model N_IBytes_size *)
let cost_N_IBytes_size = S.safe_int 15
model
let cost_N_ICar = S.safe_int 10
model N_ICdr
let cost_N_ICdr = S.safe_int 10
(* model N_IChainId *)
let cost_N_IChainId = S.safe_int 15
model
Approximating 1.123507 x term
let cost_N_ICheck_signature_ed25519 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 65_800 + (v0 + (v0 lsr 3))
(* model N_ICheck_signature_p256 *)
Approximating 1.111539 x term
let cost_N_ICheck_signature_p256 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 990_000 + (v0 + (v0 lsr 3))
model
Approximating 1.125404 x term
let cost_N_ICheck_signature_secp256k1 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 51_600 + (v0 + (v0 lsr 3))
model N_IComb
Approximating 3.531001 x term
Note : size > = 2 , so the cost is never 0
let cost_N_IComb size =
let open S_syntax in
let v0 = S.safe_int size in
(S.safe_int 3 * v0) + (v0 lsr 1) + (v0 lsr 5)
(* model N_IComb_get *)
(* Approximating 0.573180 x term *)
let cost_N_IComb_get size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 30 + (v0 lsr 1) + (v0 lsr 4)
(* model N_IComb_set *)
Approximating 1.287531 x term
let cost_N_IComb_set size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 40 + (v0 + (v0 lsr 2) + (v0 lsr 5))
Model N_ICompare
Approximating 0.024413 x term
let cost_N_ICompare size1 size2 =
let open S_syntax in
let v0 = S.safe_int (Compare.Int.min size1 size2) in
S.safe_int 35 + ((v0 lsr 6) + (v0 lsr 7))
model N_IConcat_bytes_pair
Approximating 0.065017 x term
let cost_N_IConcat_bytes_pair size1 size2 =
let open S_syntax in
let v0 = S.safe_int size1 + S.safe_int size2 in
S.safe_int 65 + (v0 lsr 4)
model N_IConcat_string_pair
(* Approximating 0.061402 x term *)
let cost_N_IConcat_string_pair size1 size2 =
let open S_syntax in
let v0 = S.safe_int size1 + S.safe_int size2 in
S.safe_int 65 + (v0 lsr 4)
(* model N_ICons_list *)
let cost_N_ICons_list = S.safe_int 15
model N_ICons_none
let cost_N_ICons_none = S.safe_int 15
model N_ICons_pair
let cost_N_ICons_pair = S.safe_int 15
model N_ICons_some
let cost_N_ICons_some = S.safe_int 15
model N_IConst
let cost_N_IConst = S.safe_int 10
model N_IContract
let cost_N_IContract = S.safe_int 30
(* model N_ICreate_contract *)
let cost_N_ICreate_contract = S.safe_int 30
model N_IDiff_timestamps
(* Approximating 0.077922 x term *)
let cost_N_IDiff_timestamps = cost_linear_op_int
(* model N_IDig *)
Approximating 6.750442 x term
let cost_N_IDig size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + ((S.safe_int 6 * v0) + (v0 lsr 1) + (v0 lsr 2))
(* model N_IDip *)
let cost_N_IDip = S.safe_int 15
model
Approximating 1.708122 x term
let cost_N_IDipN size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 45 + (v0 + (v0 lsr 1) + (v0 lsr 3))
model N_IView
let cost_N_IView = S.safe_int 1460
model N_IDrop
let cost_N_IDrop = S.safe_int 10
model N_IDropN
(* Approximating 2.713108 x term *)
let cost_N_IDropN size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + (S.safe_int 2 * v0) + (v0 lsr 1) + (v0 lsr 3)
(* model N_IDug *)
Approximating 6.718396 x term
let cost_N_IDug size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + ((S.safe_int 6 * v0) + (v0 lsr 1) + (v0 lsr 2))
model
let cost_N_IDup = S.safe_int 10
(* model N_IDupN *)
Approximating 1.129785 x term
let cost_N_IDupN size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 20 + v0 + (v0 lsr 3)
let cost_div_int size1 size2 =
let q = size1 - size2 in
if Compare.Int.(q < 0) then S.safe_int 140
else
let open S_syntax in
let v0 = S.safe_int q * S.safe_int size2 in
S.safe_int 140 + (v0 lsr 10) + (v0 lsr 11) + (v0 lsr 13)
(* model N_IEdiv_int *)
Approximating 0.001591 x term
let cost_N_IEdiv_int = cost_div_int
(* model N_IEdiv_nat *)
Approximating 0.001605 x term
let cost_N_IEdiv_nat = cost_div_int
(* model N_IEdiv_tez *)
let cost_N_IEdiv_tez = S.safe_int 140
model N_IEdiv_teznat
let cost_N_IEdiv_teznat = S.safe_int 140
(* model N_IEmpty_big_map *)
let cost_N_IEmpty_big_map = S.safe_int 15
model
let cost_N_IEmpty_map = S.safe_int 220
(* model N_IEmpty_set *)
let cost_N_IEmpty_set = S.safe_int 220
(* model N_IEq *)
let cost_N_IEq = S.safe_int 15
model N_IExec
let cost_N_IExec = S.safe_int 15
(* model N_IFailwith *)
let = S.safe_int 105
model N_IGe
let cost_N_IGe = S.safe_int 15
model N_IGt
let cost_N_IGt = S.safe_int 15
(* model N_IHalt *)
let cost_N_IHalt = S.safe_int 15
(* model N_IHash_key *)
let cost_N_IHash_key = S.safe_int 655
(* model N_IIf *)
let cost_N_IIf = S.safe_int 10
(* model N_IIf_cons *)
let cost_N_IIf_cons = S.safe_int 10
(* model N_IIf_left *)
let cost_N_IIf_left = S.safe_int 10
(* model N_IIf_none *)
let cost_N_IIf_none = S.safe_int 10
(* model N_IOpt_map *)
let cost_opt_map = S.safe_int 15
(* model N_IImplicit_account *)
let cost_N_IImplicit_account = S.safe_int 10
model N_IInt_bls12_381_z_fr
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IInt_bls12_381_z_fr = S.safe_int 125
model N_IInt_nat
let cost_N_IInt_nat = S.safe_int 15
model N_IIs_nat
let cost_N_IIs_nat = S.safe_int 15
(* model N_IKeccak *)
Approximating 8.276352 x term
let cost_N_IKeccak size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 1350 + ((S.safe_int 8 * v0) + (v0 lsr 2))
(* model N_ILambda *)
let cost_N_ILambda = S.safe_int 10
(* model N_ILe *)
let cost_N_ILe = S.safe_int 15
(* model N_ILeft *)
let cost_N_ILeft = S.safe_int 15
model N_ILevel
let cost_N_ILevel = S.safe_int 15
(* model N_IList_iter *)
let cost_N_IList_iter _ = S.safe_int 25
(* model N_IList_map *)
let cost_N_IList_map _ = S.safe_int 25
model N_IList_size
let cost_N_IList_size = S.safe_int 15
(* model N_ILoop *)
let cost_N_ILoop = S.safe_int 10
model N_ILoop_left
let cost_N_ILoop_left = S.safe_int 10
model N_ILsl_nat
Approximating 0.115642 x term
let cost_N_ILsl_nat size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + ((v0 lsr 4) + (v0 lsr 5) + (v0 lsr 6))
model N_ILsr_nat
Approximating 0.115565 x term
let cost_N_ILsr_nat size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + ((v0 lsr 4) + (v0 lsr 5) + (v0 lsr 6))
(* model N_ILt *)
let cost_N_ILt = S.safe_int 15
model N_IMap_get
Approximating 0.048359 x term
let cost_N_IMap_get size1 size2 =
let open S_syntax in
let v0 = size1 * log2 size2 in
S.safe_int 110 + (v0 lsr 5) + (v0 lsr 6)
model N_IMap_get_and_update
Approximating 0.145661 x term
let cost_N_IMap_get_and_update size1 size2 =
let open S_syntax in
let v0 = size1 * log2 size2 in
S.safe_int 135 + (v0 lsr 3) + (v0 lsr 6)
model
(* Approximating 7.621331 x term *)
let cost_N_IMap_iter size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 70 + (S.safe_int 7 * v0) + (v0 lsr 1) + (v0 lsr 3)
model N_IMap_map
Approximating 7.46280485884 x term
let cost_N_IMap_map size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 265 + ((S.safe_int 7 * v0) + (v0 lsr 1))
(* model N_IMap_mem *)
(* Approximating 0.048446 x term *)
let cost_N_IMap_mem size1 size2 =
let open S_syntax in
let v0 = size1 * log2 size2 in
S.safe_int 110 + (v0 lsr 5) + (v0 lsr 6)
(* model N_IMap_size *)
let cost_N_IMap_size = S.safe_int 15
model N_IMap_update
Approximating 0.097072 x term
let cost_N_IMap_update size1 size2 =
let open S_syntax in
let v0 = size1 * log2 size2 in
S.safe_int 130 + (v0 lsr 4) + (v0 lsr 5)
model N_IMul_bls12_381_fr
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_fr = S.safe_int 65
model
(* Approximating 1.059386 x term *)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_fr_z size1 =
let open S_syntax in
let v0 = S.safe_int size1 in
S.safe_int 330 + v0 + (v0 lsr 4)
(* model N_IMul_bls12_381_g1 *)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_g1 = S.safe_int 103_000
(* model N_IMul_bls12_381_g2 *)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_g2 = S.safe_int 220_000
model
Approximating 1.068674 x term
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_z_fr size1 =
let open S_syntax in
let v0 = S.safe_int size1 in
S.safe_int 330 + v0 + (v0 lsr 4)
let cost_mul size1 size2 =
let open S_syntax in
let a = S.add (S.safe_int size1) (S.safe_int size2) in
let v0 = a * log2 a in
S.safe_int 100 + (v0 lsr 1) + (v0 lsr 2) + (v0 lsr 4)
model N_IMul_int
(* Approximating 0.857931 x term *)
let cost_N_IMul_int = cost_mul
model N_IMul_nat
Approximating 0.861823 x term
let cost_N_IMul_nat = cost_mul
model
let cost_N_IMul_nattez = S.safe_int 50
model
let cost_N_IMul_teznat = S.safe_int 50
model N_INeg_bls12_381_fr
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_INeg_bls12_381_fr = S.safe_int 45
model
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_INeg_bls12_381_g1 = S.safe_int 60
model N_INeg_bls12_381_g2
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_INeg_bls12_381_g2 = S.safe_int 85
(* model N_INeg *)
Approximating 0.066076 x term
let cost_N_INeg size =
let open S_syntax in
S.safe_int 40 + (S.safe_int size lsr 4)
model
let cost_N_INeq = S.safe_int 15
model N_INil
let cost_N_INil = S.safe_int 15
model N_INot
let cost_N_INot = S.safe_int 10
model N_INot_int
(* Approximating 0.075541 x term *)
let cost_N_INot_int size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 50 + ((v0 lsr 4) + (v0 lsr 7))
(* model N_INow *)
let cost_N_INow = S.safe_int 15
(* model N_IOpen_chest *)
612000 + chest * 19 + time * 19050
let cost_N_IOpen_chest ~chest ~time =
let open S_syntax in
let v0 = S.safe_int chest in
let v1 = S.safe_int time in
S.safe_int 612_000 + (S.safe_int 19 * v0) + (S.safe_int 19050 * v1)
(* model N_IOr *)
let cost_N_IOr = S.safe_int 15
model N_IOr_nat
Approximating 0.075758 x term
let cost_N_IOr_nat = cost_linear_op_int
(* model N_IPairing_check_bls12_381 *)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IPairing_check_bls12_381 size =
S.add (S.safe_int 450_000) (S.mul (S.safe_int 342_500) (S.safe_int size))
model
let cost_N_IRead_ticket = S.safe_int 15
model N_IRight
let cost_N_IRight = S.safe_int 15
model N_ISapling_empty_state
let cost_N_ISapling_empty_state = S.safe_int 15
model N_ISapling_verify_update
(* Approximating 1.27167 x term *)
Approximating 38.72115 x term
let cost_N_ISapling_verify_update size1 size2 =
let open S_syntax in
let v1 = S.safe_int size1 in
let v0 = S.safe_int size2 in
S.safe_int 84_050 + (v1 + (v1 lsr 2)) + (S.safe_int 39 * v0)
(* model N_ISelf_address *)
let cost_N_ISelf_address = S.safe_int 15
(* model N_ISelf *)
let cost_N_ISelf = S.safe_int 15
(* model N_ISender *)
let cost_N_ISender = S.safe_int 15
model N_ISet_delegate
let cost_N_ISet_delegate = S.safe_int 40
(* model N_ISet_iter *)
(* Approximating 7.633555 x term *)
let cost_N_ISet_iter size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 70 + (S.safe_int 7 * v0) + (v0 lsr 1) + (v0 lsr 3)
model N_ISet_size
let cost_N_ISet_size = S.safe_int 15
(* model N_ISha256 *)
Approximating 4.763264 x term
let cost_N_ISha256 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 600 + ((S.safe_int 4 * v0) + (v0 lsr 1) + (v0 lsr 2))
model N_ISha3
Approximating 8.362339 x term
let cost_N_ISha3 = cost_N_IKeccak
model N_ISha512
Approximating 3.074641 x term
let cost_N_ISha512 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 680 + (S.safe_int 3 * v0)
(* model N_ISlice_bytes *)
(* Approximating 0.065752 x term *)
let cost_N_ISlice_bytes size =
let open S_syntax in
S.safe_int 40 + (S.safe_int size lsr 4)
(* model N_ISlice_string *)
(* Approximating 0.065688 x term *)
let cost_N_ISlice_string size =
let open S_syntax in
S.safe_int 40 + (S.safe_int size lsr 4)
model N_ISource
let cost_N_ISource = S.safe_int 15
(* model N_ISplit_ticket *)
(* Approximating 0.132362 x term *)
let cost_N_ISplit_ticket size1 size2 =
let open S_syntax in
let v1 = S.safe_int (Compare.Int.max size1 size2) in
S.safe_int 55 + (v1 lsr 3)
(* model N_IString_size *)
let cost_N_IString_size = S.safe_int 15
(* model N_ISub_int *)
(* Approximating 0.077849 x term *)
let cost_N_ISub_int = cost_linear_op_int
model N_ISub_tez
let cost_N_ISub_tez = S.safe_int 20
(* model N_ISub_tez_legacy *)
let cost_N_ISub_tez_legacy = S.safe_int 20
(* model N_ISub_timestamp_seconds *)
Approximating 0.077794 x term
let cost_N_ISub_timestamp_seconds = cost_linear_op_int
(* model N_ISwap *)
let cost_N_ISwap = S.safe_int 10
model
let cost_N_ITicket = S.safe_int 15
model N_ITotal_voting_power
let cost_N_ITotal_voting_power = S.safe_int 370
(* model N_ITransfer_tokens *)
let cost_N_ITransfer_tokens = S.safe_int 30
model
Approximating 3.944710 x term
let cost_N_IUncomb size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 25 + (S.safe_int 4 * v0)
(* model N_IUnpair *)
let cost_N_IUnpair = S.safe_int 10
(* model N_IVoting_power *)
let cost_N_IVoting_power = S.safe_int 530
model
let cost_N_IXor = S.safe_int 20
model
Approximating 0.075601 x term
let cost_N_IXor_nat = cost_linear_op_int
model
let cost_N_KCons = S.safe_int 15
(* model N_KIter *)
let cost_N_KIter = S.safe_int 20
(* model N_KList_enter_body *)
(* Approximating 1.672196 x term *)
let cost_N_KList_enter_body xs size_ys =
match xs with
| [] ->
let open S_syntax in
let v0 = S.safe_int size_ys in
S.safe_int 40 + (v0 + (v0 lsr 1) + (v0 lsr 3))
| _ :: _ -> S.safe_int 70
model N_KList_exit_body
let cost_N_KList_exit_body = S.safe_int 30
model N_KLoop_in
let cost_N_KLoop_in = S.safe_int 15
model
let cost_N_KLoop_in_left = S.safe_int 15
(* model N_KMap_enter_body *)
let cost_N_KMap_enter_body = S.safe_int 165
model
let cost_N_KNil = S.safe_int 20
(* model N_KReturn *)
let cost_N_KReturn = S.safe_int 15
(* model N_KView_exit *)
let cost_N_KView_exit = S.safe_int 20
model
let const_N_KMap_head = S.safe_int 20
model N_KUndip
let cost_N_KUndip = S.safe_int 15
model DECODING_BLS_FR
when benchmarking , compile bls12 - 381 - unix without ADX , see
-bls12-381/-/blob/71d0b4d467fbfaa6452d702fcc408d7a70916a80/README.md#install
-bls12-381/-/blob/71d0b4d467fbfaa6452d702fcc408d7a70916a80/README.md#install
*)
let cost_DECODING_BLS_FR = S.safe_int 150
(* model DECODING_BLS_G1 *)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_DECODING_BLS_G1 = S.safe_int 65_300
(* model DECODING_BLS_G2 *)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_DECODING_BLS_G2 = S.safe_int 73_300
model B58CHECK_DECODING_CHAIN_ID
let cost_B58CHECK_DECODING_CHAIN_ID = S.safe_int 1_600
model B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519
let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519 = S.safe_int 3_300
(* model B58CHECK_DECODING_PUBLIC_KEY_HASH_p256 *)
let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_p256 = S.safe_int 3_300
(* model B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1 *)
let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1 = S.safe_int 3_300
model
let cost_B58CHECK_DECODING_PUBLIC_KEY_ed25519 = S.safe_int 4_200
(* model B58CHECK_DECODING_PUBLIC_KEY_p256 *)
let cost_B58CHECK_DECODING_PUBLIC_KEY_p256 = S.safe_int 325_000
(* model B58CHECK_DECODING_PUBLIC_KEY_secp256k1 *)
let cost_B58CHECK_DECODING_PUBLIC_KEY_secp256k1 = S.safe_int 9_000
(* model B58CHECK_DECODING_SIGNATURE_ed25519 *)
let cost_B58CHECK_DECODING_SIGNATURE_ed25519 = S.safe_int 6_400
(* model B58CHECK_DECODING_SIGNATURE_p256 *)
let cost_B58CHECK_DECODING_SIGNATURE_p256 = S.safe_int 6_400
model
let cost_B58CHECK_DECODING_SIGNATURE_secp256k1 = S.safe_int 6_400
model ENCODING_BLS_FR
let cost_ENCODING_BLS_FR = S.safe_int 80
model ENCODING_BLS_G1
let cost_ENCODING_BLS_G1 = S.safe_int 3200
model ENCODING_BLS_G2
let cost_ENCODING_BLS_G2 = S.safe_int 3900
model B58CHECK_ENCODING_CHAIN_ID
let cost_B58CHECK_ENCODING_CHAIN_ID = S.safe_int 1_800
(* model B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519 *)
let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519 = S.safe_int 3_200
(* model B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256 *)
let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256 = S.safe_int 3_200
(* model B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1 *)
let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1 = S.safe_int 3_200
model B58CHECK_ENCODING_PUBLIC_KEY_ed25519
let cost_B58CHECK_ENCODING_PUBLIC_KEY_ed25519 = S.safe_int 4_500
model
let cost_B58CHECK_ENCODING_PUBLIC_KEY_p256 = S.safe_int 4_550
(* model B58CHECK_ENCODING_PUBLIC_KEY_secp256k1 *)
let cost_B58CHECK_ENCODING_PUBLIC_KEY_secp256k1 = S.safe_int 4_950
model B58CHECK_ENCODING_SIGNATURE_ed25519
let cost_B58CHECK_ENCODING_SIGNATURE_ed25519 = S.safe_int 8_300
(* model B58CHECK_ENCODING_SIGNATURE_p256 *)
let cost_B58CHECK_ENCODING_SIGNATURE_p256 = S.safe_int 8_300
(* model B58CHECK_ENCODING_SIGNATURE_secp256k1 *)
let cost_B58CHECK_ENCODING_SIGNATURE_secp256k1 = S.safe_int 8_300
model DECODING_CHAIN_ID
let cost_DECODING_CHAIN_ID = S.safe_int 50
model
let cost_DECODING_PUBLIC_KEY_HASH_ed25519 = S.safe_int 50
model DECODING_PUBLIC_KEY_HASH_p256
let cost_DECODING_PUBLIC_KEY_HASH_p256 = S.safe_int 50
model DECODING_PUBLIC_KEY_HASH_secp256k1
let cost_DECODING_PUBLIC_KEY_HASH_secp256k1 = S.safe_int 50
model
let cost_DECODING_PUBLIC_KEY_ed25519 = S.safe_int 60
model DECODING_PUBLIC_KEY_p256
let cost_DECODING_PUBLIC_KEY_p256 = S.safe_int 320_000
model DECODING_PUBLIC_KEY_secp256k1
let cost_DECODING_PUBLIC_KEY_secp256k1 = S.safe_int 4_900
model DECODING_SIGNATURE_ed25519
let cost_DECODING_SIGNATURE_ed25519 = S.safe_int 35
(* model DECODING_SIGNATURE_p256 *)
let cost_DECODING_SIGNATURE_p256 = S.safe_int 35
(* model DECODING_SIGNATURE_secp256k1 *)
let cost_DECODING_SIGNATURE_secp256k1 = S.safe_int 35
model DECODING_Chest_key
let cost_DECODING_Chest_key = S.safe_int 5900
(* model DECODING_Chest *)
(* Approximating 0.039349 x term *)
let cost_DECODING_Chest ~bytes =
let open S_syntax in
let v0 = S.safe_int bytes in
S.safe_int 7400 + (v0 lsr 5) + (v0 lsr 7)
model ENCODING_CHAIN_ID
let cost_ENCODING_CHAIN_ID = S.safe_int 50
(* model ENCODING_PUBLIC_KEY_HASH_ed25519 *)
let cost_ENCODING_PUBLIC_KEY_HASH_ed25519 = S.safe_int 70
(* model ENCODING_PUBLIC_KEY_HASH_p256 *)
let cost_ENCODING_PUBLIC_KEY_HASH_p256 = S.safe_int 70
model ENCODING_PUBLIC_KEY_HASH_secp256k1
let cost_ENCODING_PUBLIC_KEY_HASH_secp256k1 = S.safe_int 70
model
let cost_ENCODING_PUBLIC_KEY_ed25519 = S.safe_int 80
model ENCODING_PUBLIC_KEY_p256
let cost_ENCODING_PUBLIC_KEY_p256 = S.safe_int 90
(* model ENCODING_PUBLIC_KEY_secp256k1 *)
let cost_ENCODING_PUBLIC_KEY_secp256k1 = S.safe_int 455
(* model ENCODING_SIGNATURE_ed25519 *)
let cost_ENCODING_SIGNATURE_ed25519 = S.safe_int 45
(* model ENCODING_SIGNATURE_p256 *)
let cost_ENCODING_SIGNATURE_p256 = S.safe_int 45
(* model ENCODING_SIGNATURE_secp256k1 *)
let cost_ENCODING_SIGNATURE_secp256k1 = S.safe_int 45
(* model ENCODING_Chest_key *)
let cost_ENCODING_Chest_key = S.safe_int 13500
(* model ENCODING_Chest *)
Approximating 0.120086 x term
let cost_ENCODING_Chest ~plaintext_size =
let open S_syntax in
let v0 = S.safe_int plaintext_size in
S.safe_int 16630 + (v0 lsr 3)
model TIMESTAMP_READABLE_DECODING
let cost_TIMESTAMP_READABLE_DECODING = S.safe_int 100
(* model TIMESTAMP_READABLE_ENCODING *)
let cost_TIMESTAMP_READABLE_ENCODING = S.safe_int 820
model CHECK_PRINTABLE
let cost_CHECK_PRINTABLE size =
let open S_syntax in
S.safe_int 14 + (S.safe_int 10 * S.safe_int size)
TODO : /-/issues/2264
Rerun benchmarks due to faster gas monad .
With the the redesign of the gas - monad this needs to be benchmarked again .
Rerun benchmarks due to faster gas monad.
With the the redesign of the gas-monad this needs to be benchmarked again.
*)
model MERGE_TYPES
This is the estimated cost of one iteration of merge_types , extracted
and copied manually from the parameter fit for the MERGE_TYPES benchmark
( the model is parametric on the size of the type , which we do n't have
access to in O(1 ) ) .
This is the estimated cost of one iteration of merge_types, extracted
and copied manually from the parameter fit for the MERGE_TYPES benchmark
(the model is parametric on the size of the type, which we don't have
access to in O(1)). *)
let cost_MERGE_TYPES = S.safe_int 220
model TYPECHECKING_CODE
This is the cost of one iteration of parse_instr , extracted by hand from the
parameter fit for the TYPECHECKING_CODE benchmark .
This is the cost of one iteration of parse_instr, extracted by hand from the
parameter fit for the TYPECHECKING_CODE benchmark. *)
let cost_TYPECHECKING_CODE = S.safe_int 220
model UNPARSING_CODE
This is the cost of one iteration of unparse_instr , extracted by hand from the
parameter fit for the UNPARSING_CODE benchmark .
This is the cost of one iteration of unparse_instr, extracted by hand from the
parameter fit for the UNPARSING_CODE benchmark. *)
let cost_UNPARSING_CODE = S.safe_int 115
model TYPECHECKING_DATA
This is the cost of one iteration of parse_data , extracted by hand from the
parameter fit for the TYPECHECKING_DATA benchmark .
This is the cost of one iteration of parse_data, extracted by hand from the
parameter fit for the TYPECHECKING_DATA benchmark. *)
let cost_TYPECHECKING_DATA = S.safe_int 100
model UNPARSING_DATA
This is the cost of one iteration of unparse_data , extracted by hand from the
parameter fit for the UNPARSING_DATA benchmark .
This is the cost of one iteration of unparse_data, extracted by hand from the
parameter fit for the UNPARSING_DATA benchmark. *)
let cost_UNPARSING_DATA = S.safe_int 45
model PARSE_TYPE
This is the cost of one iteration of parse_ty , extracted by hand from the
parameter fit for the PARSE_TYPE benchmark .
This is the cost of one iteration of parse_ty, extracted by hand from the
parameter fit for the PARSE_TYPE benchmark. *)
let cost_PARSE_TYPE = S.safe_int 60
model UNPARSE_TYPE
This is the cost of one iteration of unparse_ty , extracted by hand from the
parameter fit for the UNPARSE_TYPE benchmark .
This is the cost of one iteration of unparse_ty, extracted by hand from the
parameter fit for the UNPARSE_TYPE benchmark. *)
let cost_UNPARSE_TYPE type_size = S.mul (S.safe_int 20) type_size
TODO : Add benchmarked value from [ Unparse_comparable_type_benchmark ] .
let cost_UNPARSE_COMPARABLE_TYPE type_size = S.mul (S.safe_int 20) type_size
(* TODO: benchmark *)
let cost_COMPARABLE_TY_OF_TY = S.safe_int 120
(* model SAPLING_TRANSACTION_ENCODING *)
let cost_SAPLING_TRANSACTION_ENCODING ~inputs ~outputs =
S.safe_int (1500 + (inputs * 160) + (outputs * 320))
(* model SAPLING_DIFF_ENCODING *)
let cost_SAPLING_DIFF_ENCODING ~nfs ~cms =
S.safe_int ((nfs * 22) + (cms * 215))
end
module Interpreter = struct
open Generated_costs
let drop = atomic_step_cost cost_N_IDrop
let dup = atomic_step_cost cost_N_IDup
let swap = atomic_step_cost cost_N_ISwap
let cons_some = atomic_step_cost cost_N_ICons_some
let cons_none = atomic_step_cost cost_N_ICons_none
let if_none = atomic_step_cost cost_N_IIf_none
let opt_map = atomic_step_cost cost_opt_map
let cons_pair = atomic_step_cost cost_N_ICons_pair
let unpair = atomic_step_cost cost_N_IUnpair
let car = atomic_step_cost cost_N_ICar
let cdr = atomic_step_cost cost_N_ICdr
let cons_left = atomic_step_cost cost_N_ILeft
let cons_right = atomic_step_cost cost_N_IRight
let if_left = atomic_step_cost cost_N_IIf_left
let cons_list = atomic_step_cost cost_N_ICons_list
let nil = atomic_step_cost cost_N_INil
let if_cons = atomic_step_cost cost_N_IIf_cons
let list_map : 'a Script_typed_ir.boxed_list -> Gas.cost =
fun {length; _} -> atomic_step_cost (cost_N_IList_map length)
let list_size = atomic_step_cost cost_N_IList_size
let list_iter : 'a Script_typed_ir.boxed_list -> Gas.cost =
fun {length; _} -> atomic_step_cost (cost_N_IList_iter length)
let empty_set = atomic_step_cost cost_N_IEmpty_set
let set_iter (type a) ((module Box) : a Script_typed_ir.set) =
atomic_step_cost (cost_N_ISet_iter Box.size)
let set_size = atomic_step_cost cost_N_ISet_size
let empty_map = atomic_step_cost cost_N_IEmpty_map
let map_map (type k v) ((module Box) : (k, v) Script_typed_ir.map) =
atomic_step_cost (cost_N_IMap_map Box.size)
let map_iter (type k v) ((module Box) : (k, v) Script_typed_ir.map) =
atomic_step_cost (cost_N_IMap_iter Box.size)
let map_size = atomic_step_cost cost_N_IMap_size
let big_map_elt_size = S.safe_int Script_expr_hash.size
let big_map_mem ({size; _} : _ Script_typed_ir.big_map_overlay) =
atomic_step_cost (cost_N_IMap_mem big_map_elt_size (S.safe_int size))
let big_map_get ({size; _} : _ Script_typed_ir.big_map_overlay) =
atomic_step_cost (cost_N_IMap_get big_map_elt_size (S.safe_int size))
let big_map_update ({size; _} : _ Script_typed_ir.big_map_overlay) =
atomic_step_cost (cost_N_IMap_update big_map_elt_size (S.safe_int size))
let big_map_get_and_update ({size; _} : _ Script_typed_ir.big_map_overlay) =
atomic_step_cost
(cost_N_IMap_get_and_update big_map_elt_size (S.safe_int size))
let add_seconds_timestamp :
'a Script_int.num -> Script_timestamp.t -> Gas.cost =
fun seconds timestamp ->
let seconds_bytes = int_bytes seconds in
let timestamp_bytes = z_bytes (Script_timestamp.to_zint timestamp) in
atomic_step_cost
(cost_N_IAdd_seconds_to_timestamp seconds_bytes timestamp_bytes)
let add_timestamp_seconds :
Script_timestamp.t -> 'a Script_int.num -> Gas.cost =
fun timestamp seconds ->
let seconds_bytes = int_bytes seconds in
let timestamp_bytes = z_bytes (Script_timestamp.to_zint timestamp) in
atomic_step_cost
(cost_N_IAdd_timestamp_to_seconds timestamp_bytes seconds_bytes)
let sub_timestamp_seconds :
Script_timestamp.t -> 'a Script_int.num -> Gas.cost =
fun timestamp seconds ->
let seconds_bytes = int_bytes seconds in
let timestamp_bytes = z_bytes (Script_timestamp.to_zint timestamp) in
atomic_step_cost
(cost_N_ISub_timestamp_seconds timestamp_bytes seconds_bytes)
let diff_timestamps t1 t2 =
let t1_bytes = z_bytes (Script_timestamp.to_zint t1) in
let t2_bytes = z_bytes (Script_timestamp.to_zint t2) in
atomic_step_cost (cost_N_IDiff_timestamps t1_bytes t2_bytes)
let concat_string_pair s1 s2 =
atomic_step_cost
(cost_N_IConcat_string_pair
(Script_string.length s1)
(Script_string.length s2))
let slice_string s =
atomic_step_cost (cost_N_ISlice_string (Script_string.length s))
let string_size = atomic_step_cost cost_N_IString_size
let concat_bytes_pair b1 b2 =
atomic_step_cost
(cost_N_IConcat_bytes_pair (Bytes.length b1) (Bytes.length b2))
let slice_bytes b = atomic_step_cost (cost_N_ISlice_bytes (Bytes.length b))
let bytes_size = atomic_step_cost cost_N_IBytes_size
let add_tez = atomic_step_cost cost_N_IAdd_tez
let sub_tez = atomic_step_cost cost_N_ISub_tez
let sub_tez_legacy = atomic_step_cost cost_N_ISub_tez_legacy
let mul_teznat = atomic_step_cost cost_N_IMul_teznat
let mul_nattez = atomic_step_cost cost_N_IMul_nattez
let bool_or = atomic_step_cost cost_N_IOr
let bool_and = atomic_step_cost cost_N_IAnd
let bool_xor = atomic_step_cost cost_N_IXor
let bool_not = atomic_step_cost cost_N_INot
let is_nat = atomic_step_cost cost_N_IIs_nat
let abs_int i = atomic_step_cost (cost_N_IAbs_int (int_bytes i))
let int_nat = atomic_step_cost cost_N_IInt_nat
let neg i = atomic_step_cost (cost_N_INeg (int_bytes i))
let add_int i1 i2 =
atomic_step_cost (cost_N_IAdd_int (int_bytes i1) (int_bytes i2))
let add_nat i1 i2 =
atomic_step_cost (cost_N_IAdd_nat (int_bytes i1) (int_bytes i2))
let sub_int i1 i2 =
atomic_step_cost (cost_N_ISub_int (int_bytes i1) (int_bytes i2))
let mul_int i1 i2 =
atomic_step_cost (cost_N_IMul_int (int_bytes i1) (int_bytes i2))
let mul_nat i1 i2 =
atomic_step_cost (cost_N_IMul_nat (int_bytes i1) (int_bytes i2))
let ediv_teznat _tez _n = atomic_step_cost cost_N_IEdiv_teznat
let ediv_tez = atomic_step_cost cost_N_IEdiv_tez
let ediv_int i1 i2 =
atomic_step_cost (cost_N_IEdiv_int (int_bytes i1) (int_bytes i2))
let ediv_nat i1 i2 =
atomic_step_cost (cost_N_IEdiv_nat (int_bytes i1) (int_bytes i2))
let eq = atomic_step_cost cost_N_IEq
let lsl_nat shifted = atomic_step_cost (cost_N_ILsl_nat (int_bytes shifted))
let lsr_nat shifted = atomic_step_cost (cost_N_ILsr_nat (int_bytes shifted))
let or_nat n1 n2 =
atomic_step_cost (cost_N_IOr_nat (int_bytes n1) (int_bytes n2))
let and_nat n1 n2 =
atomic_step_cost (cost_N_IAnd_nat (int_bytes n1) (int_bytes n2))
let and_int_nat n1 n2 =
atomic_step_cost (cost_N_IAnd_int_nat (int_bytes n1) (int_bytes n2))
let xor_nat n1 n2 =
atomic_step_cost (cost_N_IXor_nat (int_bytes n1) (int_bytes n2))
let not_int i = atomic_step_cost (cost_N_INot_int (int_bytes i))
let if_ = atomic_step_cost cost_N_IIf
let loop = atomic_step_cost cost_N_ILoop
let loop_left = atomic_step_cost cost_N_ILoop_left
let dip = atomic_step_cost cost_N_IDip
let view = atomic_step_cost cost_N_IView
let check_signature (pkey : Signature.public_key) b =
let cost =
match pkey with
| Ed25519 _ -> cost_N_ICheck_signature_ed25519 (Bytes.length b)
| Secp256k1 _ -> cost_N_ICheck_signature_secp256k1 (Bytes.length b)
| P256 _ -> cost_N_ICheck_signature_p256 (Bytes.length b)
in
atomic_step_cost cost
let blake2b b = atomic_step_cost (cost_N_IBlake2b (Bytes.length b))
let sha256 b = atomic_step_cost (cost_N_ISha256 (Bytes.length b))
let sha512 b = atomic_step_cost (cost_N_ISha512 (Bytes.length b))
let dign n = atomic_step_cost (cost_N_IDig n)
let dugn n = atomic_step_cost (cost_N_IDug n)
let dipn n = atomic_step_cost (cost_N_IDipN n)
let dropn n = atomic_step_cost (cost_N_IDropN n)
let voting_power = atomic_step_cost cost_N_IVoting_power
let total_voting_power = atomic_step_cost cost_N_ITotal_voting_power
let keccak b = atomic_step_cost (cost_N_IKeccak (Bytes.length b))
let sha3 b = atomic_step_cost (cost_N_ISha3 (Bytes.length b))
let add_bls12_381_g1 = atomic_step_cost cost_N_IAdd_bls12_381_g1
let add_bls12_381_g2 = atomic_step_cost cost_N_IAdd_bls12_381_g2
let add_bls12_381_fr = atomic_step_cost cost_N_IAdd_bls12_381_fr
let mul_bls12_381_g1 = atomic_step_cost cost_N_IMul_bls12_381_g1
let mul_bls12_381_g2 = atomic_step_cost cost_N_IMul_bls12_381_g2
let mul_bls12_381_fr = atomic_step_cost cost_N_IMul_bls12_381_fr
let mul_bls12_381_fr_z z =
atomic_step_cost (cost_N_IMul_bls12_381_fr_z (int_bytes z))
let mul_bls12_381_z_fr z =
atomic_step_cost (cost_N_IMul_bls12_381_z_fr (int_bytes z))
let int_bls12_381_fr = atomic_step_cost cost_N_IInt_bls12_381_z_fr
let neg_bls12_381_g1 = atomic_step_cost cost_N_INeg_bls12_381_g1
let neg_bls12_381_g2 = atomic_step_cost cost_N_INeg_bls12_381_g2
let neg_bls12_381_fr = atomic_step_cost cost_N_INeg_bls12_381_fr
let neq = atomic_step_cost cost_N_INeq
let pairing_check_bls12_381 (l : 'a Script_typed_ir.boxed_list) =
atomic_step_cost (cost_N_IPairing_check_bls12_381 l.length)
let comb n = atomic_step_cost (cost_N_IComb n)
let uncomb n = atomic_step_cost (cost_N_IUncomb n)
let comb_get n = atomic_step_cost (cost_N_IComb_get n)
let comb_set n = atomic_step_cost (cost_N_IComb_set n)
let dupn n = atomic_step_cost (cost_N_IDupN n)
let sapling_verify_update ~inputs ~outputs =
atomic_step_cost (cost_N_ISapling_verify_update inputs outputs)
let sapling_empty_state = atomic_step_cost cost_N_ISapling_empty_state
let halt = atomic_step_cost cost_N_IHalt
let const = atomic_step_cost cost_N_IConst
let empty_big_map = atomic_step_cost cost_N_IEmpty_big_map
let lt = atomic_step_cost cost_N_ILt
let le = atomic_step_cost cost_N_ILe
let gt = atomic_step_cost cost_N_IGt
let ge = atomic_step_cost cost_N_IGe
let exec = atomic_step_cost cost_N_IExec
let apply = atomic_step_cost cost_N_IApply
let lambda = atomic_step_cost cost_N_ILambda
let address = atomic_step_cost cost_N_IAddress
let contract = atomic_step_cost cost_N_IContract
let transfer_tokens = atomic_step_cost cost_N_ITransfer_tokens
let implicit_account = atomic_step_cost cost_N_IImplicit_account
let create_contract = atomic_step_cost cost_N_ICreate_contract
let set_delegate = atomic_step_cost cost_N_ISet_delegate
let level = atomic_step_cost cost_N_ILevel
let now = atomic_step_cost cost_N_INow
let source = atomic_step_cost cost_N_ISource
let sender = atomic_step_cost cost_N_ISender
let self = atomic_step_cost cost_N_ISelf
let self_address = atomic_step_cost cost_N_ISelf_address
let amount = atomic_step_cost cost_N_IAmount
let chain_id = atomic_step_cost cost_N_IChainId
let ticket = atomic_step_cost cost_N_ITicket
let read_ticket = atomic_step_cost cost_N_IRead_ticket
let hash_key _ = atomic_step_cost cost_N_IHash_key
let split_ticket _ amount_a amount_b =
atomic_step_cost
(cost_N_ISplit_ticket (int_bytes amount_a) (int_bytes amount_b))
let open_chest ~chest ~time =
let plaintext = Timelock.get_plaintext_size chest in
let log_time = Z.log2 Z.(add one time) in
atomic_step_cost (cost_N_IOpen_chest ~chest:plaintext ~time:log_time)
(* --------------------------------------------------------------------- *)
(* Semi-hand-crafted models *)
let compare_unit = atomic_step_cost (S.safe_int 10)
let compare_pair_tag = atomic_step_cost (S.safe_int 10)
let compare_union_tag = atomic_step_cost (S.safe_int 10)
let compare_option_tag = atomic_step_cost (S.safe_int 10)
let compare_bool = atomic_step_cost (cost_N_ICompare 1 1)
let compare_signature = atomic_step_cost (S.safe_int 92)
let compare_string s1 s2 =
atomic_step_cost
(cost_N_ICompare (Script_string.length s1) (Script_string.length s2))
let compare_bytes b1 b2 =
atomic_step_cost (cost_N_ICompare (Bytes.length b1) (Bytes.length b2))
let compare_mutez = atomic_step_cost (cost_N_ICompare 8 8)
let compare_int i1 i2 =
atomic_step_cost (cost_N_ICompare (int_bytes i1) (int_bytes i2))
let compare_nat n1 n2 =
atomic_step_cost (cost_N_ICompare (int_bytes n1) (int_bytes n2))
let compare_key_hash =
let sz = Signature.Public_key_hash.size in
atomic_step_cost (cost_N_ICompare sz sz)
let compare_key = atomic_step_cost (S.safe_int 92)
let compare_timestamp t1 t2 =
atomic_step_cost
(cost_N_ICompare
(z_bytes (Script_timestamp.to_zint t1))
(z_bytes (Script_timestamp.to_zint t2)))
(* Maximum size of an entrypoint in bytes *)
let entrypoint_size = 31
let compare_address =
let sz = Signature.Public_key_hash.size + entrypoint_size in
atomic_step_cost (cost_N_ICompare sz sz)
let compare_chain_id = atomic_step_cost (S.safe_int 30)
(* Defunctionalized CPS *)
type cont =
| Compare : 'a Script_typed_ir.comparable_ty * 'a * 'a * cont -> cont
| Return : cont
let compare : type a. a Script_typed_ir.comparable_ty -> a -> a -> cost =
fun ty x y ->
let rec compare :
type a.
a Script_typed_ir.comparable_ty -> a -> a -> cost -> cont -> cost =
fun ty x y acc k ->
match ty with
| Unit_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_unit) k
| Never_key _ -> ( match x with _ -> .)
| Bool_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_bool) k
| String_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_string x y) k
| Signature_key _ ->
(apply [@tailcall]) Gas.(acc +@ compare_signature) k
| Bytes_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_bytes x y) k
| Mutez_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_mutez) k
| Int_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_int x y) k
| Nat_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_nat x y) k
| Key_hash_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_key_hash) k
| Key_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_key) k
| Timestamp_key _ ->
(apply [@tailcall]) Gas.(acc +@ compare_timestamp x y) k
| Address_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_address) k
| Chain_id_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_chain_id) k
| Pair_key ((tl, _), (tr, _), _) ->
(* Reasonable over-approximation of the cost of lexicographic comparison. *)
let (xl, xr) = x in
let (yl, yr) = y in
(compare [@tailcall])
tl
xl
yl
Gas.(acc +@ compare_pair_tag)
(Compare (tr, xr, yr, k))
| Union_key ((tl, _), (tr, _), _) -> (
match (x, y) with
| (L x, L y) ->
(compare [@tailcall]) tl x y Gas.(acc +@ compare_union_tag) k
| (L _, R _) -> (apply [@tailcall]) Gas.(acc +@ compare_union_tag) k
| (R _, L _) -> (apply [@tailcall]) Gas.(acc +@ compare_union_tag) k
| (R x, R y) ->
(compare [@tailcall]) tr x y Gas.(acc +@ compare_union_tag) k)
| Option_key (t, _) -> (
match (x, y) with
| (None, None) ->
(apply [@tailcall]) Gas.(acc +@ compare_option_tag) k
| (None, Some _) ->
(apply [@tailcall]) Gas.(acc +@ compare_option_tag) k
| (Some _, None) ->
(apply [@tailcall]) Gas.(acc +@ compare_option_tag) k
| (Some x, Some y) ->
(compare [@tailcall]) t x y Gas.(acc +@ compare_option_tag) k)
and apply cost k =
match k with
| Compare (ty, x, y, k) -> (compare [@tailcall]) ty x y cost k
| Return -> cost
in
compare ty x y Gas.free Return
[@@coq_axiom_with_reason "non top-level mutually recursive function"]
let view_mem (elt : Script_string.t)
(m : Script_typed_ir.view Script_typed_ir.SMap.t) =
let open S_syntax in
let per_elt_cost =
compare (Script_typed_ir.string_key ~annot:None) elt elt
in
let size = S.safe_int (Script_typed_ir.SMap.cardinal m) in
let intercept = atomic_step_cost (S.safe_int 80) in
Gas.(intercept +@ (log2 size *@ per_elt_cost))
let view_get = view_mem
let view_update (elt : Script_string.t)
(m : Script_typed_ir.view Script_typed_ir.SMap.t) =
let open S_syntax in
let per_elt_cost =
compare (Script_typed_ir.string_key ~annot:None) elt elt
in
let size = S.safe_int (Script_typed_ir.SMap.cardinal m) in
let intercept = atomic_step_cost (S.safe_int 80) in
Gas.(intercept +@ (S.safe_int 2 * log2 size *@ per_elt_cost))
let set_mem (type a) (elt : a) ((module Box) : a Script_typed_ir.set) =
let open S_syntax in
let per_elt_cost = compare Box.elt_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 115) in
Gas.(intercept +@ (log2 size *@ per_elt_cost))
let set_update (type a) (elt : a) ((module Box) : a Script_typed_ir.set) =
let open S_syntax in
let per_elt_cost = compare Box.elt_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 130) in
The 2 factor reflects the update vs mem overhead as benchmarked
on non - structured data
on non-structured data *)
Gas.(intercept +@ (S.safe_int 2 * log2 size *@ per_elt_cost))
let map_mem (type k v) (elt : k) ((module Box) : (k, v) Script_typed_ir.map)
=
let open S_syntax in
let per_elt_cost = compare Box.key_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 80) in
Gas.(intercept +@ (log2 size *@ per_elt_cost))
let map_get = map_mem
let map_update (type k v) (elt : k)
((module Box) : (k, v) Script_typed_ir.map) =
let open S_syntax in
let per_elt_cost = compare Box.key_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 80) in
The 2 factor reflects the update vs mem overhead as benchmarked
on non - structured data
on non-structured data *)
Gas.(intercept +@ (S.safe_int 2 * log2 size *@ per_elt_cost))
let map_get_and_update (type k v) (elt : k)
((module Box) : (k, v) Script_typed_ir.map) =
let open S_syntax in
let per_elt_cost = compare Box.key_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 80) in
The 3 factor reflects the update vs mem overhead as benchmarked
on non - structured data
on non-structured data *)
Gas.(intercept +@ (S.safe_int 3 * log2 size *@ per_elt_cost))
let join_tickets :
'a Script_typed_ir.comparable_ty ->
'a Script_typed_ir.ticket ->
'a Script_typed_ir.ticket ->
Gas.cost =
fun ty ticket_a ticket_b ->
let contents_comparison =
compare ty ticket_a.contents ticket_b.contents
in
Gas.(
contents_comparison +@ compare_address
+@ add_nat ticket_a.amount ticket_b.amount)
(* Continuations *)
module Control = struct
let nil = atomic_step_cost cost_N_KNil
let cons = atomic_step_cost cost_N_KCons
let return = atomic_step_cost cost_N_KReturn
let view_exit = atomic_step_cost cost_N_KView_exit
let map_head = atomic_step_cost const_N_KMap_head
let undip = atomic_step_cost cost_N_KUndip
let loop_in = atomic_step_cost cost_N_KLoop_in
let loop_in_left = atomic_step_cost cost_N_KLoop_in_left
let iter = atomic_step_cost cost_N_KIter
let list_enter_body xs ys_len =
atomic_step_cost (cost_N_KList_enter_body xs ys_len)
let list_exit_body = atomic_step_cost cost_N_KList_exit_body
let map_enter_body = atomic_step_cost cost_N_KMap_enter_body
let map_exit_body (type k v) (key : k) (map : (k, v) Script_typed_ir.map)
=
map_update key map
end
(* --------------------------------------------------------------------- *)
(* Hand-crafted models *)
(* The cost functions below where not benchmarked, a cost model was derived
from looking at similar instructions. *)
Cost for Concat_string is paid in two steps : when entering the interpreter ,
the user pays for the cost of computing the information necessary to compute
the actual gas ( so it 's meta - gas ): indeed , one needs to run through the
list of strings to compute the total allocated cost .
[ concat_string_precheck ] corresponds to the meta - gas cost of this computation .
the user pays for the cost of computing the information necessary to compute
the actual gas (so it's meta-gas): indeed, one needs to run through the
list of strings to compute the total allocated cost.
[concat_string_precheck] corresponds to the meta-gas cost of this computation.
*)
let concat_string_precheck (l : 'a Script_typed_ir.boxed_list) =
(* we set the precheck to be slightly more expensive than cost_N_IList_iter *)
atomic_step_cost (S.mul (S.safe_int l.length) (S.safe_int 10))
(* This is the cost of allocating a string and blitting existing ones into it. *)
let concat_string total_bytes =
atomic_step_cost
S.(add (S.safe_int 100) (S.ediv total_bytes (S.safe_int 10)))
Same story as Concat_string .
let concat_bytes total_bytes =
atomic_step_cost
S.(add (S.safe_int 100) (S.ediv total_bytes (S.safe_int 10)))
Cost of access taken care of in Contract_storage.get_balance_carbonated
let balance = Gas.free
Cost of Unpack pays two integer comparisons , and a Bytes slice
let unpack bytes =
let blen = Bytes.length bytes in
let open S_syntax in
atomic_step_cost (S.safe_int 260 + (S.safe_int blen lsr 3))
TODO benchmark
FIXME : imported from 006 , needs proper benchmarks
let unpack_failed bytes =
We can not instrument failed deserialization ,
so we take worst case fees : a set of size 1 bytes values .
so we take worst case fees: a set of size 1 bytes values. *)
let blen = String.length bytes in
let len = S.safe_int blen in
let d = Z.numbits (Z.of_int blen) in
(len *@ alloc_mbytes_cost 1)
+@ len
*@ (S.safe_int d *@ (alloc_cost (S.safe_int 3) +@ step_cost S.one))
end
module Typechecking = struct
open Generated_costs
let public_key_optimized =
atomic_step_cost
@@ S.(
max
cost_DECODING_PUBLIC_KEY_ed25519
(max
cost_DECODING_PUBLIC_KEY_secp256k1
cost_DECODING_PUBLIC_KEY_p256))
let public_key_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_DECODING_PUBLIC_KEY_ed25519
(max
cost_B58CHECK_DECODING_PUBLIC_KEY_secp256k1
cost_B58CHECK_DECODING_PUBLIC_KEY_p256))
let key_hash_optimized =
atomic_step_cost
@@ S.(
max
cost_DECODING_PUBLIC_KEY_HASH_ed25519
(max
cost_DECODING_PUBLIC_KEY_HASH_secp256k1
cost_DECODING_PUBLIC_KEY_HASH_p256))
let key_hash_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519
(max
cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1
cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_p256))
let signature_optimized =
atomic_step_cost
@@ S.(
max
cost_DECODING_SIGNATURE_ed25519
(max
cost_DECODING_SIGNATURE_secp256k1
cost_DECODING_SIGNATURE_p256))
let signature_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_DECODING_SIGNATURE_ed25519
(max
cost_B58CHECK_DECODING_SIGNATURE_secp256k1
cost_B58CHECK_DECODING_SIGNATURE_p256))
let chain_id_optimized = atomic_step_cost cost_DECODING_CHAIN_ID
let chain_id_readable = atomic_step_cost cost_B58CHECK_DECODING_CHAIN_ID
(* Reasonable approximation *)
let address_optimized = key_hash_optimized
(* Reasonable approximation *)
let contract_optimized = key_hash_optimized
(* Reasonable approximation *)
let contract_readable = key_hash_readable
let bls12_381_g1 = atomic_step_cost cost_DECODING_BLS_G1
let bls12_381_g2 = atomic_step_cost cost_DECODING_BLS_G2
let bls12_381_fr = atomic_step_cost cost_DECODING_BLS_FR
let check_printable s =
atomic_step_cost (cost_CHECK_PRINTABLE (String.length s))
let merge_cycle = atomic_step_cost cost_MERGE_TYPES
let parse_type_cycle = atomic_step_cost cost_PARSE_TYPE
let parse_instr_cycle = atomic_step_cost cost_TYPECHECKING_CODE
let parse_data_cycle = atomic_step_cost cost_TYPECHECKING_DATA
let comparable_ty_of_ty_cycle = atomic_step_cost cost_COMPARABLE_TY_OF_TY
(* Cost of a cycle of checking that a type is dupable *)
(* TODO: bench *)
let check_dupable_cycle = atomic_step_cost cost_TYPECHECKING_DATA
let bool = free
let unit = free
let timestamp_readable = atomic_step_cost cost_TIMESTAMP_READABLE_DECODING
(* Reasonable estimate. *)
let contract = Gas.(S.safe_int 2 *@ public_key_readable)
Balance stored at /contracts / index / hash / balance , on 64 bits
let contract_exists =
Gas.cost_of_repr @@ Storage_costs.read_access ~path_length:4 ~read_bytes:8
(* Constructing proof arguments consists in a decreasing loop in the result
monad, allocating at each step. We charge a reasonable overapproximation. *)
let proof_argument n =
atomic_step_cost (S.mul (S.safe_int n) (S.safe_int 50))
let chest_key = atomic_step_cost cost_DECODING_Chest_key
let chest ~bytes = atomic_step_cost (cost_DECODING_Chest ~bytes)
end
module Unparsing = struct
open Generated_costs
let public_key_optimized =
atomic_step_cost
@@ S.(
max
cost_ENCODING_PUBLIC_KEY_ed25519
(max
cost_ENCODING_PUBLIC_KEY_secp256k1
cost_ENCODING_PUBLIC_KEY_p256))
let public_key_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_ENCODING_PUBLIC_KEY_ed25519
(max
cost_B58CHECK_ENCODING_PUBLIC_KEY_secp256k1
cost_B58CHECK_ENCODING_PUBLIC_KEY_p256))
let key_hash_optimized =
atomic_step_cost
@@ S.(
max
cost_ENCODING_PUBLIC_KEY_HASH_ed25519
(max
cost_ENCODING_PUBLIC_KEY_HASH_secp256k1
cost_ENCODING_PUBLIC_KEY_HASH_p256))
let key_hash_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519
(max
cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1
cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256))
let signature_optimized =
atomic_step_cost
@@ S.(
max
cost_ENCODING_SIGNATURE_ed25519
(max
cost_ENCODING_SIGNATURE_secp256k1
cost_ENCODING_SIGNATURE_p256))
let signature_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_ENCODING_SIGNATURE_ed25519
(max
cost_B58CHECK_ENCODING_SIGNATURE_secp256k1
cost_B58CHECK_ENCODING_SIGNATURE_p256))
let chain_id_optimized = atomic_step_cost cost_ENCODING_CHAIN_ID
let chain_id_readable = atomic_step_cost cost_B58CHECK_ENCODING_CHAIN_ID
let timestamp_readable = atomic_step_cost cost_TIMESTAMP_READABLE_ENCODING
(* Reasonable approximation *)
let address_optimized = key_hash_optimized
(* Reasonable approximation *)
let contract_optimized = key_hash_optimized
(* Reasonable approximation *)
let contract_readable = key_hash_readable
let bls12_381_g1 = atomic_step_cost cost_ENCODING_BLS_G1
let bls12_381_g2 = atomic_step_cost cost_ENCODING_BLS_G2
let bls12_381_fr = atomic_step_cost cost_ENCODING_BLS_FR
let unparse_type ty =
atomic_step_cost
@@ cost_UNPARSE_TYPE Script_typed_ir.(ty_size ty |> Type_size.to_int)
let unparse_comparable_type comp_ty =
atomic_step_cost
@@ cost_UNPARSE_COMPARABLE_TYPE
Script_typed_ir.(comparable_ty_size comp_ty |> Type_size.to_int)
let unparse_instr_cycle = atomic_step_cost cost_UNPARSING_CODE
let unparse_data_cycle = atomic_step_cost cost_UNPARSING_DATA
let unit = Gas.free
(* Reasonable estimate. *)
let contract = Gas.(S.safe_int 2 *@ public_key_readable)
Reuse 006 costs .
let operation bytes = Script.bytes_node_cost bytes
let sapling_transaction (t : Sapling.transaction) =
let inputs = List.length t.inputs in
let outputs = List.length t.outputs in
atomic_step_cost (cost_SAPLING_TRANSACTION_ENCODING ~inputs ~outputs)
let sapling_diff (d : Sapling.diff) =
let nfs = List.length d.nullifiers in
let cms = List.length d.commitments_and_ciphertexts in
atomic_step_cost (cost_SAPLING_DIFF_ENCODING ~nfs ~cms)
let chest_key = atomic_step_cost cost_ENCODING_Chest_key
let chest ~plaintext_size =
atomic_step_cost (cost_ENCODING_Chest ~plaintext_size)
end
end
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_alpha/lib_protocol/michelson_v1_gas.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.
***************************************************************************
Automatically generated costs functions.
Approximating 0.065045 x term
model N_IAdd_bls12_381_fr
model N_IAdd_bls12_381_g1
Approximating 0.078154 x term
model N_IAdd_nat
Approximating 0.077807 x term
Approximating 0.078056 x term
Approximating 0.077771 x term
model N_IAnd_int_nat
Approximating 0.076804 x term
model N_IBlake2b
model N_IBytes_size
model N_IChainId
model N_ICheck_signature_p256
model N_IComb_get
Approximating 0.573180 x term
model N_IComb_set
Approximating 0.061402 x term
model N_ICons_list
model N_ICreate_contract
Approximating 0.077922 x term
model N_IDig
model N_IDip
Approximating 2.713108 x term
model N_IDug
model N_IDupN
model N_IEdiv_int
model N_IEdiv_nat
model N_IEdiv_tez
model N_IEmpty_big_map
model N_IEmpty_set
model N_IEq
model N_IFailwith
model N_IHalt
model N_IHash_key
model N_IIf
model N_IIf_cons
model N_IIf_left
model N_IIf_none
model N_IOpt_map
model N_IImplicit_account
model N_IKeccak
model N_ILambda
model N_ILe
model N_ILeft
model N_IList_iter
model N_IList_map
model N_ILoop
model N_ILt
Approximating 7.621331 x term
model N_IMap_mem
Approximating 0.048446 x term
model N_IMap_size
Approximating 1.059386 x term
model N_IMul_bls12_381_g1
model N_IMul_bls12_381_g2
Approximating 0.857931 x term
model N_INeg
Approximating 0.075541 x term
model N_INow
model N_IOpen_chest
model N_IOr
model N_IPairing_check_bls12_381
Approximating 1.27167 x term
model N_ISelf_address
model N_ISelf
model N_ISender
model N_ISet_iter
Approximating 7.633555 x term
model N_ISha256
model N_ISlice_bytes
Approximating 0.065752 x term
model N_ISlice_string
Approximating 0.065688 x term
model N_ISplit_ticket
Approximating 0.132362 x term
model N_IString_size
model N_ISub_int
Approximating 0.077849 x term
model N_ISub_tez_legacy
model N_ISub_timestamp_seconds
model N_ISwap
model N_ITransfer_tokens
model N_IUnpair
model N_IVoting_power
model N_KIter
model N_KList_enter_body
Approximating 1.672196 x term
model N_KMap_enter_body
model N_KReturn
model N_KView_exit
model DECODING_BLS_G1
model DECODING_BLS_G2
model B58CHECK_DECODING_PUBLIC_KEY_HASH_p256
model B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1
model B58CHECK_DECODING_PUBLIC_KEY_p256
model B58CHECK_DECODING_PUBLIC_KEY_secp256k1
model B58CHECK_DECODING_SIGNATURE_ed25519
model B58CHECK_DECODING_SIGNATURE_p256
model B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519
model B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256
model B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1
model B58CHECK_ENCODING_PUBLIC_KEY_secp256k1
model B58CHECK_ENCODING_SIGNATURE_p256
model B58CHECK_ENCODING_SIGNATURE_secp256k1
model DECODING_SIGNATURE_p256
model DECODING_SIGNATURE_secp256k1
model DECODING_Chest
Approximating 0.039349 x term
model ENCODING_PUBLIC_KEY_HASH_ed25519
model ENCODING_PUBLIC_KEY_HASH_p256
model ENCODING_PUBLIC_KEY_secp256k1
model ENCODING_SIGNATURE_ed25519
model ENCODING_SIGNATURE_p256
model ENCODING_SIGNATURE_secp256k1
model ENCODING_Chest_key
model ENCODING_Chest
model TIMESTAMP_READABLE_ENCODING
TODO: benchmark
model SAPLING_TRANSACTION_ENCODING
model SAPLING_DIFF_ENCODING
---------------------------------------------------------------------
Semi-hand-crafted models
Maximum size of an entrypoint in bytes
Defunctionalized CPS
Reasonable over-approximation of the cost of lexicographic comparison.
Continuations
---------------------------------------------------------------------
Hand-crafted models
The cost functions below where not benchmarked, a cost model was derived
from looking at similar instructions.
we set the precheck to be slightly more expensive than cost_N_IList_iter
This is the cost of allocating a string and blitting existing ones into it.
Reasonable approximation
Reasonable approximation
Reasonable approximation
Cost of a cycle of checking that a type is dupable
TODO: bench
Reasonable estimate.
Constructing proof arguments consists in a decreasing loop in the result
monad, allocating at each step. We charge a reasonable overapproximation.
Reasonable approximation
Reasonable approximation
Reasonable approximation
Reasonable estimate. | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2019 - 2020 Nomadic Labs < >
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 Alpha_context
open Gas
module S = Saturation_repr
module Cost_of = struct
module S_syntax = struct
This is a good enough approximation . S.numbits 0 = 0
let log2 x = S.safe_int (1 + S.numbits x)
let ( + ) = S.add
let ( * ) = S.mul
let ( lsr ) = S.shift_right
end
let z_bytes (z : Z.t) =
let bits = Z.numbits z in
(7 + bits) / 8
let int_bytes (z : 'a Script_int.num) = z_bytes (Script_int.to_zint z)
let manager_operation = step_cost @@ S.safe_int 1_000
module Generated_costs = struct
model N_IAbs_int
let cost_N_IAbs_int size = S.safe_int (25 + (size lsr 4))
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IAdd_bls12_381_fr = S.safe_int 45
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IAdd_bls12_381_g1 = S.safe_int 925
model N_IAdd_bls12_381_g2
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IAdd_bls12_381_g2 = S.safe_int 2_520
let cost_linear_op_int size1 size2 =
let open S_syntax in
let v0 = S.safe_int (Compare.Int.max size1 size2) in
S.safe_int 55 + ((v0 lsr 4) + (v0 lsr 7))
model N_IAdd_int
let cost_N_IAdd_int = cost_linear_op_int
let cost_N_IAdd_nat = cost_linear_op_int
model N_IAdd_seconds_to_timestamp
let cost_N_IAdd_seconds_to_timestamp = cost_linear_op_int
model N_IAdd_tez
let cost_N_IAdd_tez = S.safe_int 20
model N_IAdd_timestamp_to_seconds
let cost_N_IAdd_timestamp_to_seconds = cost_linear_op_int
model N_IAddress
let cost_N_IAddress = S.safe_int 10
model N_IAmount
let cost_N_IAmount = S.safe_int 15
model
let cost_N_IAnd = S.safe_int 20
Approximating 0.076804 x 2 x term
let cost_N_IAnd_int_nat size1 size2 =
let open S_syntax in
let v0 = S.safe_int (Compare.Int.min size1 size2) in
S.safe_int 50 + ((v0 lsr 3) + (v0 lsr 6))
model N_IAnd_nat
The difference with ` cost_N_IAnd_int_nat ` comes from Zarith , where the
complexity of ` Z.logand ` depends on the sign of the argument .
complexity of `Z.logand` depends on the sign of the argument. *)
let cost_N_IAnd_nat size1 size2 =
let open S_syntax in
let v0 = S.safe_int (Compare.Int.min size1 size2) in
S.safe_int 50 + ((v0 lsr 4) + (v0 lsr 7))
model
let cost_N_IApply = S.safe_int 160
Approximating 1.120804 x term
let cost_N_IBlake2b size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 430 + v0 + (v0 lsr 3)
let cost_N_IBytes_size = S.safe_int 15
model
let cost_N_ICar = S.safe_int 10
model N_ICdr
let cost_N_ICdr = S.safe_int 10
let cost_N_IChainId = S.safe_int 15
model
Approximating 1.123507 x term
let cost_N_ICheck_signature_ed25519 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 65_800 + (v0 + (v0 lsr 3))
Approximating 1.111539 x term
let cost_N_ICheck_signature_p256 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 990_000 + (v0 + (v0 lsr 3))
model
Approximating 1.125404 x term
let cost_N_ICheck_signature_secp256k1 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 51_600 + (v0 + (v0 lsr 3))
model N_IComb
Approximating 3.531001 x term
Note : size > = 2 , so the cost is never 0
let cost_N_IComb size =
let open S_syntax in
let v0 = S.safe_int size in
(S.safe_int 3 * v0) + (v0 lsr 1) + (v0 lsr 5)
let cost_N_IComb_get size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 30 + (v0 lsr 1) + (v0 lsr 4)
Approximating 1.287531 x term
let cost_N_IComb_set size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 40 + (v0 + (v0 lsr 2) + (v0 lsr 5))
Model N_ICompare
Approximating 0.024413 x term
let cost_N_ICompare size1 size2 =
let open S_syntax in
let v0 = S.safe_int (Compare.Int.min size1 size2) in
S.safe_int 35 + ((v0 lsr 6) + (v0 lsr 7))
model N_IConcat_bytes_pair
Approximating 0.065017 x term
let cost_N_IConcat_bytes_pair size1 size2 =
let open S_syntax in
let v0 = S.safe_int size1 + S.safe_int size2 in
S.safe_int 65 + (v0 lsr 4)
model N_IConcat_string_pair
let cost_N_IConcat_string_pair size1 size2 =
let open S_syntax in
let v0 = S.safe_int size1 + S.safe_int size2 in
S.safe_int 65 + (v0 lsr 4)
let cost_N_ICons_list = S.safe_int 15
model N_ICons_none
let cost_N_ICons_none = S.safe_int 15
model N_ICons_pair
let cost_N_ICons_pair = S.safe_int 15
model N_ICons_some
let cost_N_ICons_some = S.safe_int 15
model N_IConst
let cost_N_IConst = S.safe_int 10
model N_IContract
let cost_N_IContract = S.safe_int 30
let cost_N_ICreate_contract = S.safe_int 30
model N_IDiff_timestamps
let cost_N_IDiff_timestamps = cost_linear_op_int
Approximating 6.750442 x term
let cost_N_IDig size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + ((S.safe_int 6 * v0) + (v0 lsr 1) + (v0 lsr 2))
let cost_N_IDip = S.safe_int 15
model
Approximating 1.708122 x term
let cost_N_IDipN size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 45 + (v0 + (v0 lsr 1) + (v0 lsr 3))
model N_IView
let cost_N_IView = S.safe_int 1460
model N_IDrop
let cost_N_IDrop = S.safe_int 10
model N_IDropN
let cost_N_IDropN size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + (S.safe_int 2 * v0) + (v0 lsr 1) + (v0 lsr 3)
Approximating 6.718396 x term
let cost_N_IDug size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + ((S.safe_int 6 * v0) + (v0 lsr 1) + (v0 lsr 2))
model
let cost_N_IDup = S.safe_int 10
Approximating 1.129785 x term
let cost_N_IDupN size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 20 + v0 + (v0 lsr 3)
let cost_div_int size1 size2 =
let q = size1 - size2 in
if Compare.Int.(q < 0) then S.safe_int 140
else
let open S_syntax in
let v0 = S.safe_int q * S.safe_int size2 in
S.safe_int 140 + (v0 lsr 10) + (v0 lsr 11) + (v0 lsr 13)
Approximating 0.001591 x term
let cost_N_IEdiv_int = cost_div_int
Approximating 0.001605 x term
let cost_N_IEdiv_nat = cost_div_int
let cost_N_IEdiv_tez = S.safe_int 140
model N_IEdiv_teznat
let cost_N_IEdiv_teznat = S.safe_int 140
let cost_N_IEmpty_big_map = S.safe_int 15
model
let cost_N_IEmpty_map = S.safe_int 220
let cost_N_IEmpty_set = S.safe_int 220
let cost_N_IEq = S.safe_int 15
model N_IExec
let cost_N_IExec = S.safe_int 15
let = S.safe_int 105
model N_IGe
let cost_N_IGe = S.safe_int 15
model N_IGt
let cost_N_IGt = S.safe_int 15
let cost_N_IHalt = S.safe_int 15
let cost_N_IHash_key = S.safe_int 655
let cost_N_IIf = S.safe_int 10
let cost_N_IIf_cons = S.safe_int 10
let cost_N_IIf_left = S.safe_int 10
let cost_N_IIf_none = S.safe_int 10
let cost_opt_map = S.safe_int 15
let cost_N_IImplicit_account = S.safe_int 10
model N_IInt_bls12_381_z_fr
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IInt_bls12_381_z_fr = S.safe_int 125
model N_IInt_nat
let cost_N_IInt_nat = S.safe_int 15
model N_IIs_nat
let cost_N_IIs_nat = S.safe_int 15
Approximating 8.276352 x term
let cost_N_IKeccak size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 1350 + ((S.safe_int 8 * v0) + (v0 lsr 2))
let cost_N_ILambda = S.safe_int 10
let cost_N_ILe = S.safe_int 15
let cost_N_ILeft = S.safe_int 15
model N_ILevel
let cost_N_ILevel = S.safe_int 15
let cost_N_IList_iter _ = S.safe_int 25
let cost_N_IList_map _ = S.safe_int 25
model N_IList_size
let cost_N_IList_size = S.safe_int 15
let cost_N_ILoop = S.safe_int 10
model N_ILoop_left
let cost_N_ILoop_left = S.safe_int 10
model N_ILsl_nat
Approximating 0.115642 x term
let cost_N_ILsl_nat size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + ((v0 lsr 4) + (v0 lsr 5) + (v0 lsr 6))
model N_ILsr_nat
Approximating 0.115565 x term
let cost_N_ILsr_nat size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 60 + ((v0 lsr 4) + (v0 lsr 5) + (v0 lsr 6))
let cost_N_ILt = S.safe_int 15
model N_IMap_get
Approximating 0.048359 x term
let cost_N_IMap_get size1 size2 =
let open S_syntax in
let v0 = size1 * log2 size2 in
S.safe_int 110 + (v0 lsr 5) + (v0 lsr 6)
model N_IMap_get_and_update
Approximating 0.145661 x term
let cost_N_IMap_get_and_update size1 size2 =
let open S_syntax in
let v0 = size1 * log2 size2 in
S.safe_int 135 + (v0 lsr 3) + (v0 lsr 6)
model
let cost_N_IMap_iter size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 70 + (S.safe_int 7 * v0) + (v0 lsr 1) + (v0 lsr 3)
model N_IMap_map
Approximating 7.46280485884 x term
let cost_N_IMap_map size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 265 + ((S.safe_int 7 * v0) + (v0 lsr 1))
let cost_N_IMap_mem size1 size2 =
let open S_syntax in
let v0 = size1 * log2 size2 in
S.safe_int 110 + (v0 lsr 5) + (v0 lsr 6)
let cost_N_IMap_size = S.safe_int 15
model N_IMap_update
Approximating 0.097072 x term
let cost_N_IMap_update size1 size2 =
let open S_syntax in
let v0 = size1 * log2 size2 in
S.safe_int 130 + (v0 lsr 4) + (v0 lsr 5)
model N_IMul_bls12_381_fr
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_fr = S.safe_int 65
model
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_fr_z size1 =
let open S_syntax in
let v0 = S.safe_int size1 in
S.safe_int 330 + v0 + (v0 lsr 4)
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_g1 = S.safe_int 103_000
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_g2 = S.safe_int 220_000
model
Approximating 1.068674 x term
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IMul_bls12_381_z_fr size1 =
let open S_syntax in
let v0 = S.safe_int size1 in
S.safe_int 330 + v0 + (v0 lsr 4)
let cost_mul size1 size2 =
let open S_syntax in
let a = S.add (S.safe_int size1) (S.safe_int size2) in
let v0 = a * log2 a in
S.safe_int 100 + (v0 lsr 1) + (v0 lsr 2) + (v0 lsr 4)
model N_IMul_int
let cost_N_IMul_int = cost_mul
model N_IMul_nat
Approximating 0.861823 x term
let cost_N_IMul_nat = cost_mul
model
let cost_N_IMul_nattez = S.safe_int 50
model
let cost_N_IMul_teznat = S.safe_int 50
model N_INeg_bls12_381_fr
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_INeg_bls12_381_fr = S.safe_int 45
model
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_INeg_bls12_381_g1 = S.safe_int 60
model N_INeg_bls12_381_g2
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_INeg_bls12_381_g2 = S.safe_int 85
Approximating 0.066076 x term
let cost_N_INeg size =
let open S_syntax in
S.safe_int 40 + (S.safe_int size lsr 4)
model
let cost_N_INeq = S.safe_int 15
model N_INil
let cost_N_INil = S.safe_int 15
model N_INot
let cost_N_INot = S.safe_int 10
model N_INot_int
let cost_N_INot_int size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 50 + ((v0 lsr 4) + (v0 lsr 7))
let cost_N_INow = S.safe_int 15
612000 + chest * 19 + time * 19050
let cost_N_IOpen_chest ~chest ~time =
let open S_syntax in
let v0 = S.safe_int chest in
let v1 = S.safe_int time in
S.safe_int 612_000 + (S.safe_int 19 * v0) + (S.safe_int 19050 * v1)
let cost_N_IOr = S.safe_int 15
model N_IOr_nat
Approximating 0.075758 x term
let cost_N_IOr_nat = cost_linear_op_int
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_N_IPairing_check_bls12_381 size =
S.add (S.safe_int 450_000) (S.mul (S.safe_int 342_500) (S.safe_int size))
model
let cost_N_IRead_ticket = S.safe_int 15
model N_IRight
let cost_N_IRight = S.safe_int 15
model N_ISapling_empty_state
let cost_N_ISapling_empty_state = S.safe_int 15
model N_ISapling_verify_update
Approximating 38.72115 x term
let cost_N_ISapling_verify_update size1 size2 =
let open S_syntax in
let v1 = S.safe_int size1 in
let v0 = S.safe_int size2 in
S.safe_int 84_050 + (v1 + (v1 lsr 2)) + (S.safe_int 39 * v0)
let cost_N_ISelf_address = S.safe_int 15
let cost_N_ISelf = S.safe_int 15
let cost_N_ISender = S.safe_int 15
model N_ISet_delegate
let cost_N_ISet_delegate = S.safe_int 40
let cost_N_ISet_iter size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 70 + (S.safe_int 7 * v0) + (v0 lsr 1) + (v0 lsr 3)
model N_ISet_size
let cost_N_ISet_size = S.safe_int 15
Approximating 4.763264 x term
let cost_N_ISha256 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 600 + ((S.safe_int 4 * v0) + (v0 lsr 1) + (v0 lsr 2))
model N_ISha3
Approximating 8.362339 x term
let cost_N_ISha3 = cost_N_IKeccak
model N_ISha512
Approximating 3.074641 x term
let cost_N_ISha512 size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 680 + (S.safe_int 3 * v0)
let cost_N_ISlice_bytes size =
let open S_syntax in
S.safe_int 40 + (S.safe_int size lsr 4)
let cost_N_ISlice_string size =
let open S_syntax in
S.safe_int 40 + (S.safe_int size lsr 4)
model N_ISource
let cost_N_ISource = S.safe_int 15
let cost_N_ISplit_ticket size1 size2 =
let open S_syntax in
let v1 = S.safe_int (Compare.Int.max size1 size2) in
S.safe_int 55 + (v1 lsr 3)
let cost_N_IString_size = S.safe_int 15
let cost_N_ISub_int = cost_linear_op_int
model N_ISub_tez
let cost_N_ISub_tez = S.safe_int 20
let cost_N_ISub_tez_legacy = S.safe_int 20
Approximating 0.077794 x term
let cost_N_ISub_timestamp_seconds = cost_linear_op_int
let cost_N_ISwap = S.safe_int 10
model
let cost_N_ITicket = S.safe_int 15
model N_ITotal_voting_power
let cost_N_ITotal_voting_power = S.safe_int 370
let cost_N_ITransfer_tokens = S.safe_int 30
model
Approximating 3.944710 x term
let cost_N_IUncomb size =
let open S_syntax in
let v0 = S.safe_int size in
S.safe_int 25 + (S.safe_int 4 * v0)
let cost_N_IUnpair = S.safe_int 10
let cost_N_IVoting_power = S.safe_int 530
model
let cost_N_IXor = S.safe_int 20
model
Approximating 0.075601 x term
let cost_N_IXor_nat = cost_linear_op_int
model
let cost_N_KCons = S.safe_int 15
let cost_N_KIter = S.safe_int 20
let cost_N_KList_enter_body xs size_ys =
match xs with
| [] ->
let open S_syntax in
let v0 = S.safe_int size_ys in
S.safe_int 40 + (v0 + (v0 lsr 1) + (v0 lsr 3))
| _ :: _ -> S.safe_int 70
model N_KList_exit_body
let cost_N_KList_exit_body = S.safe_int 30
model N_KLoop_in
let cost_N_KLoop_in = S.safe_int 15
model
let cost_N_KLoop_in_left = S.safe_int 15
let cost_N_KMap_enter_body = S.safe_int 165
model
let cost_N_KNil = S.safe_int 20
let cost_N_KReturn = S.safe_int 15
let cost_N_KView_exit = S.safe_int 20
model
let const_N_KMap_head = S.safe_int 20
model N_KUndip
let cost_N_KUndip = S.safe_int 15
model DECODING_BLS_FR
when benchmarking , compile bls12 - 381 - unix without ADX , see
-bls12-381/-/blob/71d0b4d467fbfaa6452d702fcc408d7a70916a80/README.md#install
-bls12-381/-/blob/71d0b4d467fbfaa6452d702fcc408d7a70916a80/README.md#install
*)
let cost_DECODING_BLS_FR = S.safe_int 150
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_DECODING_BLS_G1 = S.safe_int 65_300
when benchmarking , compile bls12 - 381 - unix without ADX
let cost_DECODING_BLS_G2 = S.safe_int 73_300
model B58CHECK_DECODING_CHAIN_ID
let cost_B58CHECK_DECODING_CHAIN_ID = S.safe_int 1_600
model B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519
let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519 = S.safe_int 3_300
let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_p256 = S.safe_int 3_300
let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1 = S.safe_int 3_300
model
let cost_B58CHECK_DECODING_PUBLIC_KEY_ed25519 = S.safe_int 4_200
let cost_B58CHECK_DECODING_PUBLIC_KEY_p256 = S.safe_int 325_000
let cost_B58CHECK_DECODING_PUBLIC_KEY_secp256k1 = S.safe_int 9_000
let cost_B58CHECK_DECODING_SIGNATURE_ed25519 = S.safe_int 6_400
let cost_B58CHECK_DECODING_SIGNATURE_p256 = S.safe_int 6_400
model
let cost_B58CHECK_DECODING_SIGNATURE_secp256k1 = S.safe_int 6_400
model ENCODING_BLS_FR
let cost_ENCODING_BLS_FR = S.safe_int 80
model ENCODING_BLS_G1
let cost_ENCODING_BLS_G1 = S.safe_int 3200
model ENCODING_BLS_G2
let cost_ENCODING_BLS_G2 = S.safe_int 3900
model B58CHECK_ENCODING_CHAIN_ID
let cost_B58CHECK_ENCODING_CHAIN_ID = S.safe_int 1_800
let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519 = S.safe_int 3_200
let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256 = S.safe_int 3_200
let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1 = S.safe_int 3_200
model B58CHECK_ENCODING_PUBLIC_KEY_ed25519
let cost_B58CHECK_ENCODING_PUBLIC_KEY_ed25519 = S.safe_int 4_500
model
let cost_B58CHECK_ENCODING_PUBLIC_KEY_p256 = S.safe_int 4_550
let cost_B58CHECK_ENCODING_PUBLIC_KEY_secp256k1 = S.safe_int 4_950
model B58CHECK_ENCODING_SIGNATURE_ed25519
let cost_B58CHECK_ENCODING_SIGNATURE_ed25519 = S.safe_int 8_300
let cost_B58CHECK_ENCODING_SIGNATURE_p256 = S.safe_int 8_300
let cost_B58CHECK_ENCODING_SIGNATURE_secp256k1 = S.safe_int 8_300
model DECODING_CHAIN_ID
let cost_DECODING_CHAIN_ID = S.safe_int 50
model
let cost_DECODING_PUBLIC_KEY_HASH_ed25519 = S.safe_int 50
model DECODING_PUBLIC_KEY_HASH_p256
let cost_DECODING_PUBLIC_KEY_HASH_p256 = S.safe_int 50
model DECODING_PUBLIC_KEY_HASH_secp256k1
let cost_DECODING_PUBLIC_KEY_HASH_secp256k1 = S.safe_int 50
model
let cost_DECODING_PUBLIC_KEY_ed25519 = S.safe_int 60
model DECODING_PUBLIC_KEY_p256
let cost_DECODING_PUBLIC_KEY_p256 = S.safe_int 320_000
model DECODING_PUBLIC_KEY_secp256k1
let cost_DECODING_PUBLIC_KEY_secp256k1 = S.safe_int 4_900
model DECODING_SIGNATURE_ed25519
let cost_DECODING_SIGNATURE_ed25519 = S.safe_int 35
let cost_DECODING_SIGNATURE_p256 = S.safe_int 35
let cost_DECODING_SIGNATURE_secp256k1 = S.safe_int 35
model DECODING_Chest_key
let cost_DECODING_Chest_key = S.safe_int 5900
let cost_DECODING_Chest ~bytes =
let open S_syntax in
let v0 = S.safe_int bytes in
S.safe_int 7400 + (v0 lsr 5) + (v0 lsr 7)
model ENCODING_CHAIN_ID
let cost_ENCODING_CHAIN_ID = S.safe_int 50
let cost_ENCODING_PUBLIC_KEY_HASH_ed25519 = S.safe_int 70
let cost_ENCODING_PUBLIC_KEY_HASH_p256 = S.safe_int 70
model ENCODING_PUBLIC_KEY_HASH_secp256k1
let cost_ENCODING_PUBLIC_KEY_HASH_secp256k1 = S.safe_int 70
model
let cost_ENCODING_PUBLIC_KEY_ed25519 = S.safe_int 80
model ENCODING_PUBLIC_KEY_p256
let cost_ENCODING_PUBLIC_KEY_p256 = S.safe_int 90
let cost_ENCODING_PUBLIC_KEY_secp256k1 = S.safe_int 455
let cost_ENCODING_SIGNATURE_ed25519 = S.safe_int 45
let cost_ENCODING_SIGNATURE_p256 = S.safe_int 45
let cost_ENCODING_SIGNATURE_secp256k1 = S.safe_int 45
let cost_ENCODING_Chest_key = S.safe_int 13500
Approximating 0.120086 x term
let cost_ENCODING_Chest ~plaintext_size =
let open S_syntax in
let v0 = S.safe_int plaintext_size in
S.safe_int 16630 + (v0 lsr 3)
model TIMESTAMP_READABLE_DECODING
let cost_TIMESTAMP_READABLE_DECODING = S.safe_int 100
let cost_TIMESTAMP_READABLE_ENCODING = S.safe_int 820
model CHECK_PRINTABLE
let cost_CHECK_PRINTABLE size =
let open S_syntax in
S.safe_int 14 + (S.safe_int 10 * S.safe_int size)
TODO : /-/issues/2264
Rerun benchmarks due to faster gas monad .
With the the redesign of the gas - monad this needs to be benchmarked again .
Rerun benchmarks due to faster gas monad.
With the the redesign of the gas-monad this needs to be benchmarked again.
*)
model MERGE_TYPES
This is the estimated cost of one iteration of merge_types , extracted
and copied manually from the parameter fit for the MERGE_TYPES benchmark
( the model is parametric on the size of the type , which we do n't have
access to in O(1 ) ) .
This is the estimated cost of one iteration of merge_types, extracted
and copied manually from the parameter fit for the MERGE_TYPES benchmark
(the model is parametric on the size of the type, which we don't have
access to in O(1)). *)
let cost_MERGE_TYPES = S.safe_int 220
model TYPECHECKING_CODE
This is the cost of one iteration of parse_instr , extracted by hand from the
parameter fit for the TYPECHECKING_CODE benchmark .
This is the cost of one iteration of parse_instr, extracted by hand from the
parameter fit for the TYPECHECKING_CODE benchmark. *)
let cost_TYPECHECKING_CODE = S.safe_int 220
model UNPARSING_CODE
This is the cost of one iteration of unparse_instr , extracted by hand from the
parameter fit for the UNPARSING_CODE benchmark .
This is the cost of one iteration of unparse_instr, extracted by hand from the
parameter fit for the UNPARSING_CODE benchmark. *)
let cost_UNPARSING_CODE = S.safe_int 115
model TYPECHECKING_DATA
This is the cost of one iteration of parse_data , extracted by hand from the
parameter fit for the TYPECHECKING_DATA benchmark .
This is the cost of one iteration of parse_data, extracted by hand from the
parameter fit for the TYPECHECKING_DATA benchmark. *)
let cost_TYPECHECKING_DATA = S.safe_int 100
model UNPARSING_DATA
This is the cost of one iteration of unparse_data , extracted by hand from the
parameter fit for the UNPARSING_DATA benchmark .
This is the cost of one iteration of unparse_data, extracted by hand from the
parameter fit for the UNPARSING_DATA benchmark. *)
let cost_UNPARSING_DATA = S.safe_int 45
model PARSE_TYPE
This is the cost of one iteration of parse_ty , extracted by hand from the
parameter fit for the PARSE_TYPE benchmark .
This is the cost of one iteration of parse_ty, extracted by hand from the
parameter fit for the PARSE_TYPE benchmark. *)
let cost_PARSE_TYPE = S.safe_int 60
model UNPARSE_TYPE
This is the cost of one iteration of unparse_ty , extracted by hand from the
parameter fit for the UNPARSE_TYPE benchmark .
This is the cost of one iteration of unparse_ty, extracted by hand from the
parameter fit for the UNPARSE_TYPE benchmark. *)
let cost_UNPARSE_TYPE type_size = S.mul (S.safe_int 20) type_size
TODO : Add benchmarked value from [ Unparse_comparable_type_benchmark ] .
let cost_UNPARSE_COMPARABLE_TYPE type_size = S.mul (S.safe_int 20) type_size
let cost_COMPARABLE_TY_OF_TY = S.safe_int 120
let cost_SAPLING_TRANSACTION_ENCODING ~inputs ~outputs =
S.safe_int (1500 + (inputs * 160) + (outputs * 320))
let cost_SAPLING_DIFF_ENCODING ~nfs ~cms =
S.safe_int ((nfs * 22) + (cms * 215))
end
module Interpreter = struct
open Generated_costs
let drop = atomic_step_cost cost_N_IDrop
let dup = atomic_step_cost cost_N_IDup
let swap = atomic_step_cost cost_N_ISwap
let cons_some = atomic_step_cost cost_N_ICons_some
let cons_none = atomic_step_cost cost_N_ICons_none
let if_none = atomic_step_cost cost_N_IIf_none
let opt_map = atomic_step_cost cost_opt_map
let cons_pair = atomic_step_cost cost_N_ICons_pair
let unpair = atomic_step_cost cost_N_IUnpair
let car = atomic_step_cost cost_N_ICar
let cdr = atomic_step_cost cost_N_ICdr
let cons_left = atomic_step_cost cost_N_ILeft
let cons_right = atomic_step_cost cost_N_IRight
let if_left = atomic_step_cost cost_N_IIf_left
let cons_list = atomic_step_cost cost_N_ICons_list
let nil = atomic_step_cost cost_N_INil
let if_cons = atomic_step_cost cost_N_IIf_cons
let list_map : 'a Script_typed_ir.boxed_list -> Gas.cost =
fun {length; _} -> atomic_step_cost (cost_N_IList_map length)
let list_size = atomic_step_cost cost_N_IList_size
let list_iter : 'a Script_typed_ir.boxed_list -> Gas.cost =
fun {length; _} -> atomic_step_cost (cost_N_IList_iter length)
let empty_set = atomic_step_cost cost_N_IEmpty_set
let set_iter (type a) ((module Box) : a Script_typed_ir.set) =
atomic_step_cost (cost_N_ISet_iter Box.size)
let set_size = atomic_step_cost cost_N_ISet_size
let empty_map = atomic_step_cost cost_N_IEmpty_map
let map_map (type k v) ((module Box) : (k, v) Script_typed_ir.map) =
atomic_step_cost (cost_N_IMap_map Box.size)
let map_iter (type k v) ((module Box) : (k, v) Script_typed_ir.map) =
atomic_step_cost (cost_N_IMap_iter Box.size)
let map_size = atomic_step_cost cost_N_IMap_size
let big_map_elt_size = S.safe_int Script_expr_hash.size
let big_map_mem ({size; _} : _ Script_typed_ir.big_map_overlay) =
atomic_step_cost (cost_N_IMap_mem big_map_elt_size (S.safe_int size))
let big_map_get ({size; _} : _ Script_typed_ir.big_map_overlay) =
atomic_step_cost (cost_N_IMap_get big_map_elt_size (S.safe_int size))
let big_map_update ({size; _} : _ Script_typed_ir.big_map_overlay) =
atomic_step_cost (cost_N_IMap_update big_map_elt_size (S.safe_int size))
let big_map_get_and_update ({size; _} : _ Script_typed_ir.big_map_overlay) =
atomic_step_cost
(cost_N_IMap_get_and_update big_map_elt_size (S.safe_int size))
let add_seconds_timestamp :
'a Script_int.num -> Script_timestamp.t -> Gas.cost =
fun seconds timestamp ->
let seconds_bytes = int_bytes seconds in
let timestamp_bytes = z_bytes (Script_timestamp.to_zint timestamp) in
atomic_step_cost
(cost_N_IAdd_seconds_to_timestamp seconds_bytes timestamp_bytes)
let add_timestamp_seconds :
Script_timestamp.t -> 'a Script_int.num -> Gas.cost =
fun timestamp seconds ->
let seconds_bytes = int_bytes seconds in
let timestamp_bytes = z_bytes (Script_timestamp.to_zint timestamp) in
atomic_step_cost
(cost_N_IAdd_timestamp_to_seconds timestamp_bytes seconds_bytes)
let sub_timestamp_seconds :
Script_timestamp.t -> 'a Script_int.num -> Gas.cost =
fun timestamp seconds ->
let seconds_bytes = int_bytes seconds in
let timestamp_bytes = z_bytes (Script_timestamp.to_zint timestamp) in
atomic_step_cost
(cost_N_ISub_timestamp_seconds timestamp_bytes seconds_bytes)
let diff_timestamps t1 t2 =
let t1_bytes = z_bytes (Script_timestamp.to_zint t1) in
let t2_bytes = z_bytes (Script_timestamp.to_zint t2) in
atomic_step_cost (cost_N_IDiff_timestamps t1_bytes t2_bytes)
let concat_string_pair s1 s2 =
atomic_step_cost
(cost_N_IConcat_string_pair
(Script_string.length s1)
(Script_string.length s2))
let slice_string s =
atomic_step_cost (cost_N_ISlice_string (Script_string.length s))
let string_size = atomic_step_cost cost_N_IString_size
let concat_bytes_pair b1 b2 =
atomic_step_cost
(cost_N_IConcat_bytes_pair (Bytes.length b1) (Bytes.length b2))
let slice_bytes b = atomic_step_cost (cost_N_ISlice_bytes (Bytes.length b))
let bytes_size = atomic_step_cost cost_N_IBytes_size
let add_tez = atomic_step_cost cost_N_IAdd_tez
let sub_tez = atomic_step_cost cost_N_ISub_tez
let sub_tez_legacy = atomic_step_cost cost_N_ISub_tez_legacy
let mul_teznat = atomic_step_cost cost_N_IMul_teznat
let mul_nattez = atomic_step_cost cost_N_IMul_nattez
let bool_or = atomic_step_cost cost_N_IOr
let bool_and = atomic_step_cost cost_N_IAnd
let bool_xor = atomic_step_cost cost_N_IXor
let bool_not = atomic_step_cost cost_N_INot
let is_nat = atomic_step_cost cost_N_IIs_nat
let abs_int i = atomic_step_cost (cost_N_IAbs_int (int_bytes i))
let int_nat = atomic_step_cost cost_N_IInt_nat
let neg i = atomic_step_cost (cost_N_INeg (int_bytes i))
let add_int i1 i2 =
atomic_step_cost (cost_N_IAdd_int (int_bytes i1) (int_bytes i2))
let add_nat i1 i2 =
atomic_step_cost (cost_N_IAdd_nat (int_bytes i1) (int_bytes i2))
let sub_int i1 i2 =
atomic_step_cost (cost_N_ISub_int (int_bytes i1) (int_bytes i2))
let mul_int i1 i2 =
atomic_step_cost (cost_N_IMul_int (int_bytes i1) (int_bytes i2))
let mul_nat i1 i2 =
atomic_step_cost (cost_N_IMul_nat (int_bytes i1) (int_bytes i2))
let ediv_teznat _tez _n = atomic_step_cost cost_N_IEdiv_teznat
let ediv_tez = atomic_step_cost cost_N_IEdiv_tez
let ediv_int i1 i2 =
atomic_step_cost (cost_N_IEdiv_int (int_bytes i1) (int_bytes i2))
let ediv_nat i1 i2 =
atomic_step_cost (cost_N_IEdiv_nat (int_bytes i1) (int_bytes i2))
let eq = atomic_step_cost cost_N_IEq
let lsl_nat shifted = atomic_step_cost (cost_N_ILsl_nat (int_bytes shifted))
let lsr_nat shifted = atomic_step_cost (cost_N_ILsr_nat (int_bytes shifted))
let or_nat n1 n2 =
atomic_step_cost (cost_N_IOr_nat (int_bytes n1) (int_bytes n2))
let and_nat n1 n2 =
atomic_step_cost (cost_N_IAnd_nat (int_bytes n1) (int_bytes n2))
let and_int_nat n1 n2 =
atomic_step_cost (cost_N_IAnd_int_nat (int_bytes n1) (int_bytes n2))
let xor_nat n1 n2 =
atomic_step_cost (cost_N_IXor_nat (int_bytes n1) (int_bytes n2))
let not_int i = atomic_step_cost (cost_N_INot_int (int_bytes i))
let if_ = atomic_step_cost cost_N_IIf
let loop = atomic_step_cost cost_N_ILoop
let loop_left = atomic_step_cost cost_N_ILoop_left
let dip = atomic_step_cost cost_N_IDip
let view = atomic_step_cost cost_N_IView
let check_signature (pkey : Signature.public_key) b =
let cost =
match pkey with
| Ed25519 _ -> cost_N_ICheck_signature_ed25519 (Bytes.length b)
| Secp256k1 _ -> cost_N_ICheck_signature_secp256k1 (Bytes.length b)
| P256 _ -> cost_N_ICheck_signature_p256 (Bytes.length b)
in
atomic_step_cost cost
let blake2b b = atomic_step_cost (cost_N_IBlake2b (Bytes.length b))
let sha256 b = atomic_step_cost (cost_N_ISha256 (Bytes.length b))
let sha512 b = atomic_step_cost (cost_N_ISha512 (Bytes.length b))
let dign n = atomic_step_cost (cost_N_IDig n)
let dugn n = atomic_step_cost (cost_N_IDug n)
let dipn n = atomic_step_cost (cost_N_IDipN n)
let dropn n = atomic_step_cost (cost_N_IDropN n)
let voting_power = atomic_step_cost cost_N_IVoting_power
let total_voting_power = atomic_step_cost cost_N_ITotal_voting_power
let keccak b = atomic_step_cost (cost_N_IKeccak (Bytes.length b))
let sha3 b = atomic_step_cost (cost_N_ISha3 (Bytes.length b))
let add_bls12_381_g1 = atomic_step_cost cost_N_IAdd_bls12_381_g1
let add_bls12_381_g2 = atomic_step_cost cost_N_IAdd_bls12_381_g2
let add_bls12_381_fr = atomic_step_cost cost_N_IAdd_bls12_381_fr
let mul_bls12_381_g1 = atomic_step_cost cost_N_IMul_bls12_381_g1
let mul_bls12_381_g2 = atomic_step_cost cost_N_IMul_bls12_381_g2
let mul_bls12_381_fr = atomic_step_cost cost_N_IMul_bls12_381_fr
let mul_bls12_381_fr_z z =
atomic_step_cost (cost_N_IMul_bls12_381_fr_z (int_bytes z))
let mul_bls12_381_z_fr z =
atomic_step_cost (cost_N_IMul_bls12_381_z_fr (int_bytes z))
let int_bls12_381_fr = atomic_step_cost cost_N_IInt_bls12_381_z_fr
let neg_bls12_381_g1 = atomic_step_cost cost_N_INeg_bls12_381_g1
let neg_bls12_381_g2 = atomic_step_cost cost_N_INeg_bls12_381_g2
let neg_bls12_381_fr = atomic_step_cost cost_N_INeg_bls12_381_fr
let neq = atomic_step_cost cost_N_INeq
let pairing_check_bls12_381 (l : 'a Script_typed_ir.boxed_list) =
atomic_step_cost (cost_N_IPairing_check_bls12_381 l.length)
let comb n = atomic_step_cost (cost_N_IComb n)
let uncomb n = atomic_step_cost (cost_N_IUncomb n)
let comb_get n = atomic_step_cost (cost_N_IComb_get n)
let comb_set n = atomic_step_cost (cost_N_IComb_set n)
let dupn n = atomic_step_cost (cost_N_IDupN n)
let sapling_verify_update ~inputs ~outputs =
atomic_step_cost (cost_N_ISapling_verify_update inputs outputs)
let sapling_empty_state = atomic_step_cost cost_N_ISapling_empty_state
let halt = atomic_step_cost cost_N_IHalt
let const = atomic_step_cost cost_N_IConst
let empty_big_map = atomic_step_cost cost_N_IEmpty_big_map
let lt = atomic_step_cost cost_N_ILt
let le = atomic_step_cost cost_N_ILe
let gt = atomic_step_cost cost_N_IGt
let ge = atomic_step_cost cost_N_IGe
let exec = atomic_step_cost cost_N_IExec
let apply = atomic_step_cost cost_N_IApply
let lambda = atomic_step_cost cost_N_ILambda
let address = atomic_step_cost cost_N_IAddress
let contract = atomic_step_cost cost_N_IContract
let transfer_tokens = atomic_step_cost cost_N_ITransfer_tokens
let implicit_account = atomic_step_cost cost_N_IImplicit_account
let create_contract = atomic_step_cost cost_N_ICreate_contract
let set_delegate = atomic_step_cost cost_N_ISet_delegate
let level = atomic_step_cost cost_N_ILevel
let now = atomic_step_cost cost_N_INow
let source = atomic_step_cost cost_N_ISource
let sender = atomic_step_cost cost_N_ISender
let self = atomic_step_cost cost_N_ISelf
let self_address = atomic_step_cost cost_N_ISelf_address
let amount = atomic_step_cost cost_N_IAmount
let chain_id = atomic_step_cost cost_N_IChainId
let ticket = atomic_step_cost cost_N_ITicket
let read_ticket = atomic_step_cost cost_N_IRead_ticket
let hash_key _ = atomic_step_cost cost_N_IHash_key
let split_ticket _ amount_a amount_b =
atomic_step_cost
(cost_N_ISplit_ticket (int_bytes amount_a) (int_bytes amount_b))
let open_chest ~chest ~time =
let plaintext = Timelock.get_plaintext_size chest in
let log_time = Z.log2 Z.(add one time) in
atomic_step_cost (cost_N_IOpen_chest ~chest:plaintext ~time:log_time)
let compare_unit = atomic_step_cost (S.safe_int 10)
let compare_pair_tag = atomic_step_cost (S.safe_int 10)
let compare_union_tag = atomic_step_cost (S.safe_int 10)
let compare_option_tag = atomic_step_cost (S.safe_int 10)
let compare_bool = atomic_step_cost (cost_N_ICompare 1 1)
let compare_signature = atomic_step_cost (S.safe_int 92)
let compare_string s1 s2 =
atomic_step_cost
(cost_N_ICompare (Script_string.length s1) (Script_string.length s2))
let compare_bytes b1 b2 =
atomic_step_cost (cost_N_ICompare (Bytes.length b1) (Bytes.length b2))
let compare_mutez = atomic_step_cost (cost_N_ICompare 8 8)
let compare_int i1 i2 =
atomic_step_cost (cost_N_ICompare (int_bytes i1) (int_bytes i2))
let compare_nat n1 n2 =
atomic_step_cost (cost_N_ICompare (int_bytes n1) (int_bytes n2))
let compare_key_hash =
let sz = Signature.Public_key_hash.size in
atomic_step_cost (cost_N_ICompare sz sz)
let compare_key = atomic_step_cost (S.safe_int 92)
let compare_timestamp t1 t2 =
atomic_step_cost
(cost_N_ICompare
(z_bytes (Script_timestamp.to_zint t1))
(z_bytes (Script_timestamp.to_zint t2)))
let entrypoint_size = 31
let compare_address =
let sz = Signature.Public_key_hash.size + entrypoint_size in
atomic_step_cost (cost_N_ICompare sz sz)
let compare_chain_id = atomic_step_cost (S.safe_int 30)
type cont =
| Compare : 'a Script_typed_ir.comparable_ty * 'a * 'a * cont -> cont
| Return : cont
let compare : type a. a Script_typed_ir.comparable_ty -> a -> a -> cost =
fun ty x y ->
let rec compare :
type a.
a Script_typed_ir.comparable_ty -> a -> a -> cost -> cont -> cost =
fun ty x y acc k ->
match ty with
| Unit_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_unit) k
| Never_key _ -> ( match x with _ -> .)
| Bool_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_bool) k
| String_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_string x y) k
| Signature_key _ ->
(apply [@tailcall]) Gas.(acc +@ compare_signature) k
| Bytes_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_bytes x y) k
| Mutez_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_mutez) k
| Int_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_int x y) k
| Nat_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_nat x y) k
| Key_hash_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_key_hash) k
| Key_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_key) k
| Timestamp_key _ ->
(apply [@tailcall]) Gas.(acc +@ compare_timestamp x y) k
| Address_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_address) k
| Chain_id_key _ -> (apply [@tailcall]) Gas.(acc +@ compare_chain_id) k
| Pair_key ((tl, _), (tr, _), _) ->
let (xl, xr) = x in
let (yl, yr) = y in
(compare [@tailcall])
tl
xl
yl
Gas.(acc +@ compare_pair_tag)
(Compare (tr, xr, yr, k))
| Union_key ((tl, _), (tr, _), _) -> (
match (x, y) with
| (L x, L y) ->
(compare [@tailcall]) tl x y Gas.(acc +@ compare_union_tag) k
| (L _, R _) -> (apply [@tailcall]) Gas.(acc +@ compare_union_tag) k
| (R _, L _) -> (apply [@tailcall]) Gas.(acc +@ compare_union_tag) k
| (R x, R y) ->
(compare [@tailcall]) tr x y Gas.(acc +@ compare_union_tag) k)
| Option_key (t, _) -> (
match (x, y) with
| (None, None) ->
(apply [@tailcall]) Gas.(acc +@ compare_option_tag) k
| (None, Some _) ->
(apply [@tailcall]) Gas.(acc +@ compare_option_tag) k
| (Some _, None) ->
(apply [@tailcall]) Gas.(acc +@ compare_option_tag) k
| (Some x, Some y) ->
(compare [@tailcall]) t x y Gas.(acc +@ compare_option_tag) k)
and apply cost k =
match k with
| Compare (ty, x, y, k) -> (compare [@tailcall]) ty x y cost k
| Return -> cost
in
compare ty x y Gas.free Return
[@@coq_axiom_with_reason "non top-level mutually recursive function"]
let view_mem (elt : Script_string.t)
(m : Script_typed_ir.view Script_typed_ir.SMap.t) =
let open S_syntax in
let per_elt_cost =
compare (Script_typed_ir.string_key ~annot:None) elt elt
in
let size = S.safe_int (Script_typed_ir.SMap.cardinal m) in
let intercept = atomic_step_cost (S.safe_int 80) in
Gas.(intercept +@ (log2 size *@ per_elt_cost))
let view_get = view_mem
let view_update (elt : Script_string.t)
(m : Script_typed_ir.view Script_typed_ir.SMap.t) =
let open S_syntax in
let per_elt_cost =
compare (Script_typed_ir.string_key ~annot:None) elt elt
in
let size = S.safe_int (Script_typed_ir.SMap.cardinal m) in
let intercept = atomic_step_cost (S.safe_int 80) in
Gas.(intercept +@ (S.safe_int 2 * log2 size *@ per_elt_cost))
let set_mem (type a) (elt : a) ((module Box) : a Script_typed_ir.set) =
let open S_syntax in
let per_elt_cost = compare Box.elt_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 115) in
Gas.(intercept +@ (log2 size *@ per_elt_cost))
let set_update (type a) (elt : a) ((module Box) : a Script_typed_ir.set) =
let open S_syntax in
let per_elt_cost = compare Box.elt_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 130) in
The 2 factor reflects the update vs mem overhead as benchmarked
on non - structured data
on non-structured data *)
Gas.(intercept +@ (S.safe_int 2 * log2 size *@ per_elt_cost))
let map_mem (type k v) (elt : k) ((module Box) : (k, v) Script_typed_ir.map)
=
let open S_syntax in
let per_elt_cost = compare Box.key_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 80) in
Gas.(intercept +@ (log2 size *@ per_elt_cost))
let map_get = map_mem
let map_update (type k v) (elt : k)
((module Box) : (k, v) Script_typed_ir.map) =
let open S_syntax in
let per_elt_cost = compare Box.key_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 80) in
The 2 factor reflects the update vs mem overhead as benchmarked
on non - structured data
on non-structured data *)
Gas.(intercept +@ (S.safe_int 2 * log2 size *@ per_elt_cost))
let map_get_and_update (type k v) (elt : k)
((module Box) : (k, v) Script_typed_ir.map) =
let open S_syntax in
let per_elt_cost = compare Box.key_ty elt elt in
let size = S.safe_int Box.size in
let intercept = atomic_step_cost (S.safe_int 80) in
The 3 factor reflects the update vs mem overhead as benchmarked
on non - structured data
on non-structured data *)
Gas.(intercept +@ (S.safe_int 3 * log2 size *@ per_elt_cost))
let join_tickets :
'a Script_typed_ir.comparable_ty ->
'a Script_typed_ir.ticket ->
'a Script_typed_ir.ticket ->
Gas.cost =
fun ty ticket_a ticket_b ->
let contents_comparison =
compare ty ticket_a.contents ticket_b.contents
in
Gas.(
contents_comparison +@ compare_address
+@ add_nat ticket_a.amount ticket_b.amount)
module Control = struct
let nil = atomic_step_cost cost_N_KNil
let cons = atomic_step_cost cost_N_KCons
let return = atomic_step_cost cost_N_KReturn
let view_exit = atomic_step_cost cost_N_KView_exit
let map_head = atomic_step_cost const_N_KMap_head
let undip = atomic_step_cost cost_N_KUndip
let loop_in = atomic_step_cost cost_N_KLoop_in
let loop_in_left = atomic_step_cost cost_N_KLoop_in_left
let iter = atomic_step_cost cost_N_KIter
let list_enter_body xs ys_len =
atomic_step_cost (cost_N_KList_enter_body xs ys_len)
let list_exit_body = atomic_step_cost cost_N_KList_exit_body
let map_enter_body = atomic_step_cost cost_N_KMap_enter_body
let map_exit_body (type k v) (key : k) (map : (k, v) Script_typed_ir.map)
=
map_update key map
end
Cost for Concat_string is paid in two steps : when entering the interpreter ,
the user pays for the cost of computing the information necessary to compute
the actual gas ( so it 's meta - gas ): indeed , one needs to run through the
list of strings to compute the total allocated cost .
[ concat_string_precheck ] corresponds to the meta - gas cost of this computation .
the user pays for the cost of computing the information necessary to compute
the actual gas (so it's meta-gas): indeed, one needs to run through the
list of strings to compute the total allocated cost.
[concat_string_precheck] corresponds to the meta-gas cost of this computation.
*)
let concat_string_precheck (l : 'a Script_typed_ir.boxed_list) =
atomic_step_cost (S.mul (S.safe_int l.length) (S.safe_int 10))
let concat_string total_bytes =
atomic_step_cost
S.(add (S.safe_int 100) (S.ediv total_bytes (S.safe_int 10)))
Same story as Concat_string .
let concat_bytes total_bytes =
atomic_step_cost
S.(add (S.safe_int 100) (S.ediv total_bytes (S.safe_int 10)))
Cost of access taken care of in Contract_storage.get_balance_carbonated
let balance = Gas.free
Cost of Unpack pays two integer comparisons , and a Bytes slice
let unpack bytes =
let blen = Bytes.length bytes in
let open S_syntax in
atomic_step_cost (S.safe_int 260 + (S.safe_int blen lsr 3))
TODO benchmark
FIXME : imported from 006 , needs proper benchmarks
let unpack_failed bytes =
We can not instrument failed deserialization ,
so we take worst case fees : a set of size 1 bytes values .
so we take worst case fees: a set of size 1 bytes values. *)
let blen = String.length bytes in
let len = S.safe_int blen in
let d = Z.numbits (Z.of_int blen) in
(len *@ alloc_mbytes_cost 1)
+@ len
*@ (S.safe_int d *@ (alloc_cost (S.safe_int 3) +@ step_cost S.one))
end
module Typechecking = struct
open Generated_costs
let public_key_optimized =
atomic_step_cost
@@ S.(
max
cost_DECODING_PUBLIC_KEY_ed25519
(max
cost_DECODING_PUBLIC_KEY_secp256k1
cost_DECODING_PUBLIC_KEY_p256))
let public_key_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_DECODING_PUBLIC_KEY_ed25519
(max
cost_B58CHECK_DECODING_PUBLIC_KEY_secp256k1
cost_B58CHECK_DECODING_PUBLIC_KEY_p256))
let key_hash_optimized =
atomic_step_cost
@@ S.(
max
cost_DECODING_PUBLIC_KEY_HASH_ed25519
(max
cost_DECODING_PUBLIC_KEY_HASH_secp256k1
cost_DECODING_PUBLIC_KEY_HASH_p256))
let key_hash_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519
(max
cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1
cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_p256))
let signature_optimized =
atomic_step_cost
@@ S.(
max
cost_DECODING_SIGNATURE_ed25519
(max
cost_DECODING_SIGNATURE_secp256k1
cost_DECODING_SIGNATURE_p256))
let signature_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_DECODING_SIGNATURE_ed25519
(max
cost_B58CHECK_DECODING_SIGNATURE_secp256k1
cost_B58CHECK_DECODING_SIGNATURE_p256))
let chain_id_optimized = atomic_step_cost cost_DECODING_CHAIN_ID
let chain_id_readable = atomic_step_cost cost_B58CHECK_DECODING_CHAIN_ID
let address_optimized = key_hash_optimized
let contract_optimized = key_hash_optimized
let contract_readable = key_hash_readable
let bls12_381_g1 = atomic_step_cost cost_DECODING_BLS_G1
let bls12_381_g2 = atomic_step_cost cost_DECODING_BLS_G2
let bls12_381_fr = atomic_step_cost cost_DECODING_BLS_FR
let check_printable s =
atomic_step_cost (cost_CHECK_PRINTABLE (String.length s))
let merge_cycle = atomic_step_cost cost_MERGE_TYPES
let parse_type_cycle = atomic_step_cost cost_PARSE_TYPE
let parse_instr_cycle = atomic_step_cost cost_TYPECHECKING_CODE
let parse_data_cycle = atomic_step_cost cost_TYPECHECKING_DATA
let comparable_ty_of_ty_cycle = atomic_step_cost cost_COMPARABLE_TY_OF_TY
let check_dupable_cycle = atomic_step_cost cost_TYPECHECKING_DATA
let bool = free
let unit = free
let timestamp_readable = atomic_step_cost cost_TIMESTAMP_READABLE_DECODING
let contract = Gas.(S.safe_int 2 *@ public_key_readable)
Balance stored at /contracts / index / hash / balance , on 64 bits
let contract_exists =
Gas.cost_of_repr @@ Storage_costs.read_access ~path_length:4 ~read_bytes:8
let proof_argument n =
atomic_step_cost (S.mul (S.safe_int n) (S.safe_int 50))
let chest_key = atomic_step_cost cost_DECODING_Chest_key
let chest ~bytes = atomic_step_cost (cost_DECODING_Chest ~bytes)
end
module Unparsing = struct
open Generated_costs
let public_key_optimized =
atomic_step_cost
@@ S.(
max
cost_ENCODING_PUBLIC_KEY_ed25519
(max
cost_ENCODING_PUBLIC_KEY_secp256k1
cost_ENCODING_PUBLIC_KEY_p256))
let public_key_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_ENCODING_PUBLIC_KEY_ed25519
(max
cost_B58CHECK_ENCODING_PUBLIC_KEY_secp256k1
cost_B58CHECK_ENCODING_PUBLIC_KEY_p256))
let key_hash_optimized =
atomic_step_cost
@@ S.(
max
cost_ENCODING_PUBLIC_KEY_HASH_ed25519
(max
cost_ENCODING_PUBLIC_KEY_HASH_secp256k1
cost_ENCODING_PUBLIC_KEY_HASH_p256))
let key_hash_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519
(max
cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1
cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256))
let signature_optimized =
atomic_step_cost
@@ S.(
max
cost_ENCODING_SIGNATURE_ed25519
(max
cost_ENCODING_SIGNATURE_secp256k1
cost_ENCODING_SIGNATURE_p256))
let signature_readable =
atomic_step_cost
@@ S.(
max
cost_B58CHECK_ENCODING_SIGNATURE_ed25519
(max
cost_B58CHECK_ENCODING_SIGNATURE_secp256k1
cost_B58CHECK_ENCODING_SIGNATURE_p256))
let chain_id_optimized = atomic_step_cost cost_ENCODING_CHAIN_ID
let chain_id_readable = atomic_step_cost cost_B58CHECK_ENCODING_CHAIN_ID
let timestamp_readable = atomic_step_cost cost_TIMESTAMP_READABLE_ENCODING
let address_optimized = key_hash_optimized
let contract_optimized = key_hash_optimized
let contract_readable = key_hash_readable
let bls12_381_g1 = atomic_step_cost cost_ENCODING_BLS_G1
let bls12_381_g2 = atomic_step_cost cost_ENCODING_BLS_G2
let bls12_381_fr = atomic_step_cost cost_ENCODING_BLS_FR
let unparse_type ty =
atomic_step_cost
@@ cost_UNPARSE_TYPE Script_typed_ir.(ty_size ty |> Type_size.to_int)
let unparse_comparable_type comp_ty =
atomic_step_cost
@@ cost_UNPARSE_COMPARABLE_TYPE
Script_typed_ir.(comparable_ty_size comp_ty |> Type_size.to_int)
let unparse_instr_cycle = atomic_step_cost cost_UNPARSING_CODE
let unparse_data_cycle = atomic_step_cost cost_UNPARSING_DATA
let unit = Gas.free
let contract = Gas.(S.safe_int 2 *@ public_key_readable)
Reuse 006 costs .
let operation bytes = Script.bytes_node_cost bytes
let sapling_transaction (t : Sapling.transaction) =
let inputs = List.length t.inputs in
let outputs = List.length t.outputs in
atomic_step_cost (cost_SAPLING_TRANSACTION_ENCODING ~inputs ~outputs)
let sapling_diff (d : Sapling.diff) =
let nfs = List.length d.nullifiers in
let cms = List.length d.commitments_and_ciphertexts in
atomic_step_cost (cost_SAPLING_DIFF_ENCODING ~nfs ~cms)
let chest_key = atomic_step_cost cost_ENCODING_Chest_key
let chest ~plaintext_size =
atomic_step_cost (cost_ENCODING_Chest ~plaintext_size)
end
end
|
dae0a076bbb303b41c58bad035f44a88b6e100e00ca0670a871f46a10a2422c7 | y-taka-23/time-machine | Cockpit.hs | module Control.Monad.TimeMachine.Cockpit (
-- * Destinations
-- ** Absolute Destinations
the, future
-- ** Zoned Destinations
, Hour, Minute, DayOfMonth, Month, Year
, HalfDay, am, pm
, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
-- ** Reletive Destinations
, minutes, hours, days, weeks, months, years
, Direction, later, ago
, tomorrow, yesterday
-- * Acceleration
-- ** Absolute Acceleration
, at
, TimeScaleUnit, secondsPerSec, minutesPerSec, hoursPerSec, daysPerSec
-- ** Relative Acceleration
, x
) where
import Control.Monad.TimeMachine.Engine
import qualified Data.Time as T
import qualified Data.Time.Zones as TZ
| A piese of the DSL to construct ' Absolute ' destinations .
the :: T.UTCTime -> Destination
the = Absolute
| The point of time where arrived back from 1955 by DeLorean .
future :: T.UTCTime
future = T.localTimeToUTC zone lt
where
zone = T.TimeZone (-420) True "PDT"
lt = T.LocalTime d tod
d = T.fromGregorian 1985 10 26
tod = T.TimeOfDay 1 24 00
type Minute = Int
type Hour = Int
type DayOfMonth = Int
type Month = Int
type Year = Integer
mkZonedDestination :: Month -> DayOfMonth -> Year -> HalfDay -> Hour -> Minute
-> Destination
mkZonedDestination month day year hd hour min = Zoned $ T.LocalTime d tod
where
d = T.fromGregorian year month day
tod = T.TimeOfDay h m 0
h = case hd of
AM -> clip 0 11 hour
PM -> clip 0 11 hour + 12
m = clip 0 59 min
clip :: (Ord a) => a -> a -> a -> a
clip lo hi x
| x < lo = lo
| hi < x = hi
| otherwise = x
| A piese of the DSL to construct ' Zoned ' destinations .
If the arguments are in the invalid ranges like @jan 32 1970 am 12 60@ ,
they will be clipped as @jan 31 1970 am 11
jan :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
jan = mkZonedDestination 1
feb :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
feb = mkZonedDestination 2
mar :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
mar = mkZonedDestination 3
apr :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
apr = mkZonedDestination 4
may :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
may = mkZonedDestination 5
jun :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
jun = mkZonedDestination 6
jul :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
jul = mkZonedDestination 7
aug :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
aug = mkZonedDestination 8
sep :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
sep = mkZonedDestination 9
oct :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
oct = mkZonedDestination 10
nov :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
nov = mkZonedDestination 11
dec :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
dec = mkZonedDestination 12
| A piese of the DSL to construct ' Zoned ' destinations .
data HalfDay = AM | PM
deriving ( Eq, Show, Ord, Enum )
am :: HalfDay
am = AM
pm :: HalfDay
pm = PM
| A piese of the DSL to construct ' Relative ' destinations ,
-- which represents an unit of the interval.
minutes :: Integer -> Direction -> Destination
minutes n Forward = Relative $ Minutes n
minutes n Backward = Relative $ Minutes (-n)
hours :: Integer -> Direction -> Destination
hours n Forward = Relative $ Hours n
hours n Backward = Relative $ Hours (-n)
days :: Integer -> Direction -> Destination
days n Forward = Relative $ Days n
days n Backward = Relative $ Days (-n)
weeks :: Integer -> Direction -> Destination
weeks n Forward = Relative $ Weeks n
weeks n Backward = Relative $ Weeks (-n)
months :: Integer -> Direction -> Destination
months n Forward = Relative $ Months n
months n Backward = Relative $ Months (-n)
years :: Integer -> Direction -> Destination
years n Forward = Relative $ Years n
years n Backward = Relative $ Years (-n)
| A piese of the DSL to construct ' Relative ' destinations .
-- It represents the direction of a time travel,
-- namely which of going forward or back.
data Direction = Forward | Backward
deriving ( Eq, Show, Enum )
later :: Direction
later = Forward
ago :: Direction
ago = Backward
-- | An alias of @1 `days` later@.
tomorrow :: Destination
tomorrow = 1 `days` later
-- | An alias of @1 `days` ago@.
yesterday :: Destination
yesterday = 1 `days` ago
| A piese of the DSL to construct ' Velocity ' acceleration .
at :: T.NominalDiffTime -> TimeScaleUnit -> Acceleration
at v unit = Velocity . TimeScale $ v * (normarizeToSecondsPerSec unit)
| A piese of the DSL to construct ' Velocity ' acceleration .
It represents how long it spends within the real one seconds .
data TimeScaleUnit =
SecondsPerSec
| MinutesPerSec
| HoursPerSec
| DaysPerSec
deriving ( Show, Enum )
instance Eq TimeScaleUnit where
x == y = normarizeToSecondsPerSec x == normarizeToSecondsPerSec y
normarizeToSecondsPerSec :: TimeScaleUnit -> T.NominalDiffTime
normarizeToSecondsPerSec SecondsPerSec = 1
normarizeToSecondsPerSec MinutesPerSec = 60
normarizeToSecondsPerSec HoursPerSec = 60 * 60
normarizeToSecondsPerSec DaysPerSec = 60 * 60 * 24
secondsPerSec :: TimeScaleUnit
secondsPerSec = SecondsPerSec
minutesPerSec :: TimeScaleUnit
minutesPerSec = MinutesPerSec
hoursPerSec :: TimeScaleUnit
hoursPerSec = HoursPerSec
daysPerSec :: TimeScaleUnit
daysPerSec = DaysPerSec
| A piese of the DSL to construct ' Factor ' acceleration .
For example @x makes the current speed of time x60 faster .
x :: T.NominalDiffTime -> Acceleration
x = Factor . TimeScale
| null | https://raw.githubusercontent.com/y-taka-23/time-machine/c82f15d51d12b800438aa74401f42d39e0c472fe/src/Control/Monad/TimeMachine/Cockpit.hs | haskell | * Destinations
** Absolute Destinations
** Zoned Destinations
** Reletive Destinations
* Acceleration
** Absolute Acceleration
** Relative Acceleration
which represents an unit of the interval.
It represents the direction of a time travel,
namely which of going forward or back.
| An alias of @1 `days` later@.
| An alias of @1 `days` ago@. | module Control.Monad.TimeMachine.Cockpit (
the, future
, Hour, Minute, DayOfMonth, Month, Year
, HalfDay, am, pm
, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
, minutes, hours, days, weeks, months, years
, Direction, later, ago
, tomorrow, yesterday
, at
, TimeScaleUnit, secondsPerSec, minutesPerSec, hoursPerSec, daysPerSec
, x
) where
import Control.Monad.TimeMachine.Engine
import qualified Data.Time as T
import qualified Data.Time.Zones as TZ
| A piese of the DSL to construct ' Absolute ' destinations .
the :: T.UTCTime -> Destination
the = Absolute
| The point of time where arrived back from 1955 by DeLorean .
future :: T.UTCTime
future = T.localTimeToUTC zone lt
where
zone = T.TimeZone (-420) True "PDT"
lt = T.LocalTime d tod
d = T.fromGregorian 1985 10 26
tod = T.TimeOfDay 1 24 00
type Minute = Int
type Hour = Int
type DayOfMonth = Int
type Month = Int
type Year = Integer
mkZonedDestination :: Month -> DayOfMonth -> Year -> HalfDay -> Hour -> Minute
-> Destination
mkZonedDestination month day year hd hour min = Zoned $ T.LocalTime d tod
where
d = T.fromGregorian year month day
tod = T.TimeOfDay h m 0
h = case hd of
AM -> clip 0 11 hour
PM -> clip 0 11 hour + 12
m = clip 0 59 min
clip :: (Ord a) => a -> a -> a -> a
clip lo hi x
| x < lo = lo
| hi < x = hi
| otherwise = x
| A piese of the DSL to construct ' Zoned ' destinations .
If the arguments are in the invalid ranges like @jan 32 1970 am 12 60@ ,
they will be clipped as @jan 31 1970 am 11
jan :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
jan = mkZonedDestination 1
feb :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
feb = mkZonedDestination 2
mar :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
mar = mkZonedDestination 3
apr :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
apr = mkZonedDestination 4
may :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
may = mkZonedDestination 5
jun :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
jun = mkZonedDestination 6
jul :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
jul = mkZonedDestination 7
aug :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
aug = mkZonedDestination 8
sep :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
sep = mkZonedDestination 9
oct :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
oct = mkZonedDestination 10
nov :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
nov = mkZonedDestination 11
dec :: DayOfMonth -> Year -> HalfDay -> Hour -> Minute -> Destination
dec = mkZonedDestination 12
| A piese of the DSL to construct ' Zoned ' destinations .
data HalfDay = AM | PM
deriving ( Eq, Show, Ord, Enum )
am :: HalfDay
am = AM
pm :: HalfDay
pm = PM
| A piese of the DSL to construct ' Relative ' destinations ,
minutes :: Integer -> Direction -> Destination
minutes n Forward = Relative $ Minutes n
minutes n Backward = Relative $ Minutes (-n)
hours :: Integer -> Direction -> Destination
hours n Forward = Relative $ Hours n
hours n Backward = Relative $ Hours (-n)
days :: Integer -> Direction -> Destination
days n Forward = Relative $ Days n
days n Backward = Relative $ Days (-n)
weeks :: Integer -> Direction -> Destination
weeks n Forward = Relative $ Weeks n
weeks n Backward = Relative $ Weeks (-n)
months :: Integer -> Direction -> Destination
months n Forward = Relative $ Months n
months n Backward = Relative $ Months (-n)
years :: Integer -> Direction -> Destination
years n Forward = Relative $ Years n
years n Backward = Relative $ Years (-n)
| A piese of the DSL to construct ' Relative ' destinations .
data Direction = Forward | Backward
deriving ( Eq, Show, Enum )
later :: Direction
later = Forward
ago :: Direction
ago = Backward
tomorrow :: Destination
tomorrow = 1 `days` later
yesterday :: Destination
yesterday = 1 `days` ago
| A piese of the DSL to construct ' Velocity ' acceleration .
at :: T.NominalDiffTime -> TimeScaleUnit -> Acceleration
at v unit = Velocity . TimeScale $ v * (normarizeToSecondsPerSec unit)
| A piese of the DSL to construct ' Velocity ' acceleration .
It represents how long it spends within the real one seconds .
data TimeScaleUnit =
SecondsPerSec
| MinutesPerSec
| HoursPerSec
| DaysPerSec
deriving ( Show, Enum )
instance Eq TimeScaleUnit where
x == y = normarizeToSecondsPerSec x == normarizeToSecondsPerSec y
normarizeToSecondsPerSec :: TimeScaleUnit -> T.NominalDiffTime
normarizeToSecondsPerSec SecondsPerSec = 1
normarizeToSecondsPerSec MinutesPerSec = 60
normarizeToSecondsPerSec HoursPerSec = 60 * 60
normarizeToSecondsPerSec DaysPerSec = 60 * 60 * 24
secondsPerSec :: TimeScaleUnit
secondsPerSec = SecondsPerSec
minutesPerSec :: TimeScaleUnit
minutesPerSec = MinutesPerSec
hoursPerSec :: TimeScaleUnit
hoursPerSec = HoursPerSec
daysPerSec :: TimeScaleUnit
daysPerSec = DaysPerSec
| A piese of the DSL to construct ' Factor ' acceleration .
For example @x makes the current speed of time x60 faster .
x :: T.NominalDiffTime -> Acceleration
x = Factor . TimeScale
|
60ce3a739d703425896a07c24be0f87df43d4f010a829954dc052cdb56be4cef | fredrikt/yxa | local.erl | %%%-------------------------------------------------------------------
%%% File : local.erl
@author < >
%%% @doc Interface to local functions hooking into lots of
different parts of the various YXA applications .
%%%
@since 03 Jan 2006 by < >
%%% @end
%%%-------------------------------------------------------------------
-module(local).
%%--------------------------------------------------------------------
%% External exports
%%--------------------------------------------------------------------
-export([init/0
]).
%%--------------------------------------------------------------------
%% Hooks
%%--------------------------------------------------------------------
-export([
url2mnesia_userlist/1,
canonify_user/1,
canonify_addresses/1
]).
%% lookup
-export([
lookup_homedomain_request/2,
lookup_remote_request/2,
lookupregexproute/1,
lookupuser/1,
lookupuser_gruu/2,
lookupuser_locations/2,
lookup_url_to_locations/1,
lookup_url_to_addresses/2,
lookup_addresses_to_users/1,
lookup_address_to_users/1,
lookupappserver/1,
lookupdefault/1,
lookuppotn/1,
lookupnumber/1,
lookupenum/1,
lookuppstn/1,
isours/1,
format_number_for_remote_party_id/3,
get_remote_party_name/2,
get_remote_party_number/4,
rewrite_potn_to_e164/1,
is_request_to_this_proxy/1,
remove_unsuitable_locations/2
]).
%% siplocation
-export([
prioritize_locations/2,
homedomain/1,
get_locations_for_users/1,
get_user_with_contact/1,
get_locations_with_contact/1,
gruu_make_url/4,
is_gruu_url/1
]).
%% sipauth
-export([
get_user_verified/2,
get_user_verified_proxy/2,
can_use_address/2,
can_use_address_detail/2,
can_register/2,
is_allowed_pstn_dst/4,
canonify_authusername/2
]).
%% sipuserdb
-export([
get_addresses_for_user/1,
get_addresses_for_users/1,
get_users_for_address_of_record/1,
get_users_for_addresses_of_record/1,
get_users_for_url/1,
get_user_with_address/1,
get_classes_for_user/1,
get_password_for_user/1,
get_telephonenumber_for_user/1,
get_forwards_for_users/1,
sipuserdb_backend_override/3,
sipuserdb_mysql_make_sql_statement/2
]).
%% incomginproxy
-export([
incomingproxy_challenge_before_relay/3,
incomingproxy_request_homedomain_event/2
]).
%% pstnproxy
-export([
pstnproxy_route_pstn_not_e164/3,
pstnproxy_auth_and_tag/4,
pstnproxy_allowed_methods/2,
pstnproxy_allowed_proxy_request/2,
pstnproxy_verify_from/4,
pstnproxy_number_based_routing/4,
pstnproxy_lookup_action/2
]).
%% outgoingproxy
-export([
outgoingproxy_challenge_before_relay/3
]).
%% eventserver
-export([
get_event_package_module/3,
get_all_event_packages/0,
eventserver_locationdb_action/3
]).
%% sippipe
-export([
start_sippipe/4,
sippipe_received_response/3
]).
%% cpl_db
-export([
user_has_cpl_script/1,
user_has_cpl_script/2,
get_cpl_for_user/1
]).
%% transaction layer
-export([
start_client_transaction/4,
new_request/3,
new_response/3
]).
%% transport layer
-export([
is_acceptable_socket/7,
is_tls_equivalent/3,
get_valid_altnames/3,
lookup_sipsocket_blacklist/1
]).
%% custom log and mail cpl functions
-export([
cpl_mail/2,
cpl_log/4,
cpl_is_log_dest/1
]).
%% configuration
-export([
check_config_type/3,
config_is_soft_reloadable/2,
config_change_action/3
]).
%% sipdialog
-export([
create_dialog_state_uas/4
]).
%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("siprecords.hrl").
-include("sipsocket.hrl").
-include("pstnproxy.hrl").
%%--------------------------------------------------------------------
Macros
%%--------------------------------------------------------------------
-define(LOCAL_ETS_TABLE_NAME, yxa_hooks).
-define(CHECK_EXPORTED(LocalMacroKey, LocalMacroIfSo, LocalMacroOtherwise),
case ets:member(?LOCAL_ETS_TABLE_NAME, LocalMacroKey) of
true ->
LocalMacroIfSo;
false ->
LocalMacroOtherwise
end).
-define(SIPPIPE_TIMEOUT, 900).
%%====================================================================
%% External functions
%%====================================================================
%%--------------------------------------------------------------------
%% @spec () -> ok
%%
%% @doc Look at the list of exported functions from the module
%% specified as ?LOCAL_MODULE, and make a cache of which of
%% _this_ modules functions are overridden in the
%% ?LOCAL_MODULE module.
%% @hidden
%% @end
%%--------------------------------------------------------------------
init() ->
ets:new(?LOCAL_ETS_TABLE_NAME, [named_table, set]),
Exports = ?MODULE:module_info(exports),
MyLocalExports = ?LOCAL_MODULE:module_info(exports),
%% Check which of this ('local') modules exported functions are also exported
by the ? LOCAL_MODULE function . The LOCAL_MODULE define is provided at compile
%% time and can be affected by supplying a --with-local=modulename argument to
the YXA ' configure ' script .
Fun = fun({init, 0}) ->
?LOCAL_MODULE:init(),
[];
({module_info, _A}) ->
[];
({F, A}) ->
case lists:member({F, A}, Exports) of
true ->
ets:insert(?LOCAL_ETS_TABLE_NAME, {{F, A}, 1}),
F;
false ->
[]
end
end,
[Fun(V) || V <- MyLocalExports],
{ok, Count, Descr} = init_get_overridden(),
logger:log(debug, "Local: Found ~p overriding functions in module '~p' : ~s",
[Count, ?LOCAL_MODULE, Descr]),
ok.
init_get_overridden() ->
Overridden = ets:tab2list(?LOCAL_ETS_TABLE_NAME),
{ok, length(Overridden), format_overridden(Overridden, [])}.
format_overridden([{{F, A}, _Foo} | T], Res) ->
This = lists:concat([F, "/", A]),
format_overridden(T, [This | Res]);
format_overridden([], Res) ->
util:join(lists:reverse(Res), ", ").
%%====================================================================
%% Hooks
%%====================================================================
%%--------------------------------------------------------------------
%% @spec (URL) -> term()
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
url2mnesia_userlist(URL) when is_record(URL, sipurl) ->
?CHECK_EXPORTED({url2mnesia_userlist, 1},
?LOCAL_MODULE:url2mnesia_userlist(URL),
default_url2mnesia_userlist(URL)
).
%%--------------------------------------------------------------------
%% @spec (URL) -> term()
%%
URL = # sipurl { }
%%
@doc Return " user@host " from URL .
@private
%% @end
%%--------------------------------------------------------------------
default_url2mnesia_userlist(URL) when is_list(URL#sipurl.user) ->
[URL#sipurl.user ++ "@" ++ URL#sipurl.host];
default_url2mnesia_userlist(_URL) ->
[].
%%--------------------------------------------------------------------
%% @spec (User) -> string()
%%
%% User = string()
%%
%% @doc Turn a SIP username into an address which can be reached
from anywhere . Used for example from the
userdb - module . It should be possible to call users
%% based on their username, but the username might need sip:
%% prepended to it, or a default domain name appended to it.
%% @end
%%--------------------------------------------------------------------
canonify_user(User) when is_list(User) ->
?CHECK_EXPORTED({canonify_user, 1},
?LOCAL_MODULE:canonify_user(User),
default_canonify_user(User)
).
%%--------------------------------------------------------------------
%% @spec (User) -> string()
%%
%% User = string()
%%
%% @doc
@private
%% @end
%%--------------------------------------------------------------------
default_canonify_user("sip:" ++ User) ->
"sip:" ++ User;
default_canonify_user(Fulluser) ->
case string:tokens(Fulluser, "@") of
[_User, _Host] ->
"sip:" ++ Fulluser;
[User] ->
"sip:" ++ User ++ "@" ++ sipauth:realm()
end.
%%--------------------------------------------------------------------
%% @spec (In) -> [string()]
%%
%% In = [string()]
%%
%% @doc Canonify a list of addresses. Turn anything numeric into
it 's E.164 canonical representation . Used from some
%% userdb-modules which potentially get non-fully qualified
%% phone numbers (like local extension numbers) back from
%% the database.
%% @end
%%--------------------------------------------------------------------
canonify_addresses(In) when is_list(In) ->
?CHECK_EXPORTED({canonify_addresses, 1},
?LOCAL_MODULE:canonify_addresses(In),
default_canonify_addresses(In)
).
%%--------------------------------------------------------------------
%% @spec (In) -> [string()]
%%
%% In = [string()]
%%
%% @doc
@private
%% @end
%%--------------------------------------------------------------------
default_canonify_addresses(In) when is_list(In) ->
default_canonify_addresses2(In, []).
default_canonify_addresses2(["tel:+" ++ _ = H | T], Res) ->
default_canonify_addresses2(T, [H | Res]);
default_canonify_addresses2(["+" ++ Num = H | T], Res) ->
case util:isnumeric(Num) of
true ->
This = "tel:+" ++ Num,
default_canonify_addresses2(T, [This | Res]);
false ->
%% non-numeric part after '+' - leave unaltered
default_canonify_addresses2(T, [H | Res])
end;
default_canonify_addresses2([H | T], Res) ->
%% outgoingproxy don't have internal_to_e164 configuration parameter, so rewrite_potn_to_e164 might fail
case (catch rewrite_potn_to_e164(H)) of
"+" ++ _ = E164->
This = "tel:" ++ E164,
default_canonify_addresses2(T, [This | Res]);
_ ->
could not rewrite using rewrite_potn_to_e164/1 - leave unaltered
default_canonify_addresses2(T, [H | Res])
end;
default_canonify_addresses2([], Res) ->
lists:reverse(Res).
% Routing hooks
%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (Request, Origin) ->
%% {proxy, PDst} |
%% {relay, RDst} |
%% {error, S} |
%% {response, S, R} |
{ forward , Fwd } |
%% none
%%
%% Request = #request{}
%% Origin = #request{}
%%
PDst = # sipurl { } | [ # sipdst { } ] | route
RDst = # sipurl { } | [ # sipdst { } ] | route
%% S = integer() "SIP status code"
%% R = string() "SIP reason phrase"
%% Fwd = #sipurl{} "MUST have 'user' and 'pass' set to 'none'"
%%
%% @doc Determine where to route a request that arrived to the
%% 'incomingproxy' application, destined for a local domain
%% when it has been determined that the request was not
addressed to one of our users ( see local : lookupuser/1 ) .
%% Return 'none' for default routing.
%% @end
%%--------------------------------------------------------------------
lookup_homedomain_request(Request, Origin) when is_record(Request, request), is_record(Origin, siporigin) ->
?CHECK_EXPORTED({lookup_homedomain_request, 2},
?LOCAL_MODULE:lookup_homedomain_request(Request, Origin),
none
).
%%--------------------------------------------------------------------
%% @spec (Request, Origin) ->
%% {proxy, PDst} |
%% {relay, RDst} |
%% {error, S} |
%% {response, S, R} |
{ forward , Fwd } |
%% none
%%
%% Request = #request{}
%% Origin = #request{}
%%
PDst = # sipurl { } | [ # sipdst { } ] | route
RDst = # sipurl { } | [ # sipdst { } ] | route
%% S = integer() "SIP status code"
%% R = string() "SIP reason phrase"
%% Fwd = #sipurl{} "MUST have 'user' and 'pass' set to 'none'"
%%
%% @doc Determine where to route a request that arrived to the
%% 'incomingproxy' application, destined for a remote
%% domain. Return 'none' to perform default routing.
%% @end
%%--------------------------------------------------------------------
lookup_remote_request(Request, Origin) when is_record(Request, request), is_record(Origin, siporigin) ->
?CHECK_EXPORTED({lookup_remote_request, 2},
?LOCAL_MODULE:lookup_remote_request(Request, Origin),
none
).
%%--------------------------------------------------------------------
%% @spec (Request) -> true | false
%%
%% Request = #request{}
%%
%% @doc Determine if a request is meant for this proxy itself, as
%% opposed to say a user of the system.
%% @see lookup:is_request_to_this_proxy/1.
%% @end
%%--------------------------------------------------------------------
is_request_to_this_proxy(Request) when is_record(Request, request) ->
?CHECK_EXPORTED({is_request_to_this_proxy, 1},
?LOCAL_MODULE:is_request_to_this_proxy(Request),
lookup:is_request_to_this_proxy(Request)
).
% lookup.erl hooks
%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (User) -> term()
%%
%% @doc
@see lookup : lookupregexproute/1
%% @end
%%--------------------------------------------------------------------
lookupregexproute(User) ->
?CHECK_EXPORTED({lookupregexproute, 1},
?LOCAL_MODULE:lookupregexproute(User),
lookup:lookupregexproute(User)
).
%%--------------------------------------------------------------------
%% @spec (URL) ->
%% {proxy, URL} |
%% {relay, URL} |
%% {forward, URL} |
%% {response, Status, Reason} |
%% none |
%% nomatch
%%
URL = # sipurl { }
%%
@doc The main ' give me a set of locations for one of our users '
%% function that incomingproxy uses, when it determines that
a request is for one of it 's homedomains .
%% @see lookup:lookupuser/1.
%% @end
%%--------------------------------------------------------------------
lookupuser(URL) ->
?CHECK_EXPORTED({lookupuser, 1},
?LOCAL_MODULE:lookupuser(URL),
lookup:lookupuser(URL)
).
%%--------------------------------------------------------------------
%% @spec (URL, GRUU) ->
%% {proxy, URL} |
%% {relay, URL} |
%% {forward, URL} |
%% {response, Status, Reason} |
%% none |
%% nomatch
%%
URL = # sipurl { } " Request - URI "
%% GRUU = string()
%%
%% @doc Look up a GRUU. Used by incomingproxy and outgouingproxy.
%% @see lookup:lookupuser_gruu/2.
%% @end
%%--------------------------------------------------------------------
lookupuser_gruu(URL, GRUU) ->
?CHECK_EXPORTED({lookupuser_gruu, 2},
?LOCAL_MODULE:lookupuser_gruu(URL, GRUU),
lookup:lookupuser_gruu(URL, GRUU)
).
%%--------------------------------------------------------------------
%% @spec (Users, URL) ->
%% Locations
%%
%% Users = [string()] "SIP users to fetch locations of"
URL = # sipurl { } " the Request - URI "
%%
%% Locations = [#siplocationdb_e{}]
%%
%% @doc Return all locations for a list of users that is suitable
%% given a Request-URI. By suitable, we mean that we filter
out SIP locations if Request - URI was SIPS , unless this
%% proxy is configured not to.
%% @see lookup:lookupuser_locations/2.
%% @end
%%--------------------------------------------------------------------
lookupuser_locations(Users, URL) ->
?CHECK_EXPORTED({lookupuser_locations, 2},
?LOCAL_MODULE:lookupuser_locations(Users, URL),
lookup:lookupuser_locations(Users, URL)
).
%%--------------------------------------------------------------------
%% @spec (URL, Locations) -> [#sipurl{}]
%%
%% URL = #sipurl{} "Request-URI of request"
%% Location = [#sipurl{}]
%%
%% @doc Apply local policy for what locations are good to use for
%% a particular Request-URI.
%% @see lookup:remove_unsuitable_locations/2.
%% @end
%%--------------------------------------------------------------------
remove_unsuitable_locations(URL, Locations) when is_record(URL, sipurl), is_list(Locations) ->
?CHECK_EXPORTED({remove_unsuitable_locations, 2},
?LOCAL_MODULE:remove_unsuitable_locations(URL, Locations),
lookup:remove_unsuitable_locations(URL, Locations)
).
%%--------------------------------------------------------------------
%% @spec (URL) -> term()
%%
%% @doc
@see lookup : lookup_url_to_locations/1 .
%% @end
%%--------------------------------------------------------------------
lookup_url_to_locations(URL) ->
?CHECK_EXPORTED({lookup_url_to_locations, 1},
?LOCAL_MODULE:lookup_url_to_locations(URL),
lookup:lookup_url_to_locations(URL)
).
%%--------------------------------------------------------------------
%% @spec (Src, URL) -> term()
%%
%% @doc
%% @see lookup:lookup_url_to_addresses/2.
%% @end
%%--------------------------------------------------------------------
lookup_url_to_addresses(Src, URL) ->
?CHECK_EXPORTED({lookup_url_to_addresses, 2},
?LOCAL_MODULE:lookup_url_to_addresses(Src, URL),
lookup:lookup_url_to_addresses(Src, URL)
).
%%--------------------------------------------------------------------
%% @spec (Addresses) -> term()
%%
%% @doc
%% @see lookup:lookup_addresses_to_users/1
%% @end
%%--------------------------------------------------------------------
lookup_addresses_to_users(Addresses) ->
?CHECK_EXPORTED({lookup_addresses_to_users, 1},
?LOCAL_MODULE:lookup_addresses_to_users(Addresses),
lookup:lookup_addresses_to_users(Addresses)
).
%%--------------------------------------------------------------------
%% @spec (Address) -> term()
%%
%% @doc
%% @see lookup:lookup_address_to_users/1
%% @end
%%--------------------------------------------------------------------
lookup_address_to_users(Address) ->
?CHECK_EXPORTED({lookup_address_to_users, 1},
?LOCAL_MODULE:lookup_address_to_users(Address),
lookup:lookup_address_to_users(Address)
).
%%--------------------------------------------------------------------
%% @spec (Key) -> term()
%%
%% @doc
%% @see lookup:lookupappserver/1
%% @end
%%--------------------------------------------------------------------
lookupappserver(Key) ->
?CHECK_EXPORTED({lookupappserver, 1},
?LOCAL_MODULE:lookupappserver(Key),
lookup:lookupappserver(Key)
).
%%--------------------------------------------------------------------
%% @spec (Key, Locations) -> term()
%%
%% @doc
%% @see siplocation:prioritize_locations/1.
%% @end
%%--------------------------------------------------------------------
prioritize_locations(Key, Locations) ->
?CHECK_EXPORTED({prioritize_locations, 2},
?LOCAL_MODULE:prioritize_locations(Key, Locations),
siplocation:prioritize_locations(Locations)
).
%%--------------------------------------------------------------------
%% @spec (URL) -> term()
%%
%% @doc
%% @see lookup:lookupdefault/1.
%% @end
%%--------------------------------------------------------------------
lookupdefault(URL) ->
?CHECK_EXPORTED({lookupdefault, 1},
?LOCAL_MODULE:lookupdefault(URL),
lookup:lookupdefault(URL)
).
%%--------------------------------------------------------------------
%% @spec (Number) -> term()
%%
%% @doc
@see lookup : .
%% @end
%%--------------------------------------------------------------------
lookuppotn(Number) ->
?CHECK_EXPORTED({lookuppotn, 1},
?LOCAL_MODULE:lookuppotn(Number),
lookup:lookuppotn(Number)
).
%%--------------------------------------------------------------------
%% @spec (Number) -> term()
%%
%% @doc
%% @see lookup:lookupnumber/1.
%% @end
%%--------------------------------------------------------------------
lookupnumber(Number) ->
?CHECK_EXPORTED({lookupnumber, 1},
?LOCAL_MODULE:lookupnumber(Number),
lookup:lookupnumber(Number)
).
%%--------------------------------------------------------------------
%% @spec (Number) -> term()
%%
%% @doc
%% @see lookup:lookupenum/1.
%% @end
%%--------------------------------------------------------------------
lookupenum(Number) ->
?CHECK_EXPORTED({lookupenum, 1},
?LOCAL_MODULE:lookupenum(Number),
lookup:lookupenum(Number)
).
%%--------------------------------------------------------------------
%% @spec (Number) -> term()
%%
%% @doc
%% @see lookup:lookuppstn/1.
%% @end
%%--------------------------------------------------------------------
lookuppstn(Number) ->
?CHECK_EXPORTED({lookuppstn, 1},
?LOCAL_MODULE:lookuppstn(Number),
lookup:lookuppstn(Number)
).
%%--------------------------------------------------------------------
%% @spec (URL) -> term()
%%
%% @doc lookup:isours/1.
%% @see foo
%% @end
%%--------------------------------------------------------------------
isours(URL) ->
?CHECK_EXPORTED({isours, 1},
?LOCAL_MODULE:isours(URL),
lookup:isours(URL)
).
%%--------------------------------------------------------------------
%% @spec (Domain) -> true | false
%%
%% Domain = string()
%%
%% @doc Check if something is one of our 'homedomains' - a domain
%% we are the final destination for.
%% @see lookup:homedomain/1.
%% @end
%%--------------------------------------------------------------------
homedomain(Domain) ->
?CHECK_EXPORTED({homedomain, 1},
?LOCAL_MODULE:homedomain(Domain),
lookup:homedomain(Domain)
).
%%--------------------------------------------------------------------
%% @spec (User, Header, URI, DstHost) ->
%% {ok, Number} |
%% none
%%
%% User = string() "SIP authentication username"
%% Header = #keylist{}
URI = # sipurl { } " outgoing Request - URI "
%% DstHost = term() "chosen destination for request"
%%
%% Number = string()
%%
@doc This function is used by the pstnproxy to provide a PSTN
gateway with usefull caller - id information . PSTN networks
%% typically gets upset if the "A-number" (calling party) is
%% a SIP URL. Different gateways might want the number
%% formatted differently, thus the DstHost parameter (a TSP
gateway to PSTN might only handle E.164 numbers , while a
PBX might be expecting only a 4 - digit extension number ) .
@see lookup : get_remote_party_number/4 .
%% @end
%%--------------------------------------------------------------------
get_remote_party_number(User, Header, URI, DstHost) when is_list(User) ->
?CHECK_EXPORTED({get_remote_party_number, 4},
?LOCAL_MODULE:get_remote_party_number(User, Header, URI, DstHost),
lookup:get_remote_party_number(User, Header, URI, DstHost)
).
%%--------------------------------------------------------------------
%% @spec (Number, Header, DstHost) ->
%% {ok, Number}
%%
%% Number = string() "the number to format"
%% Header = #keylist{}
%% DstHost = term() "destination for request"
%%
%% Number = string()
%%
%% @doc Hook for the actual formatting once
has found a number to be
%% formatted.
%% @see lookup:format_number_for_remote_party_id/3.
%% @end
%%--------------------------------------------------------------------
format_number_for_remote_party_id(Number, Header, DstHost) when is_list(Number) ->
?CHECK_EXPORTED({format_number_for_remote_party_id, 3},
?LOCAL_MODULE:format_number_for_remote_party_id(Number, Header, DstHost),
lookup:format_number_for_remote_party_id(Number, Header, DstHost)
).
%%--------------------------------------------------------------------
%% @spec (Key, DstHost) ->
{ ok , } |
%% none
%%
%% Key = string() "number we should turn into a name"
%% DstHost = term() "destination for request"
%%
DisplayName = string ( )
%%
%% @doc When pstnproxy receives a request from a PSTN gateway,
%% this function is called to see if we can find a nice
%% Display Name for the calling party. By default, we only
do the actual lookup if we can rewrite Key into a E.164
%% number.
%% @see lookup:get_remote_party_name/2.
%% @end
%%--------------------------------------------------------------------
get_remote_party_name(Key, DstHost) ->
?CHECK_EXPORTED({get_remote_party_name, 2},
?LOCAL_MODULE:get_remote_party_name(Key, DstHost),
case rewrite_potn_to_e164(Key) of
"+" ++ E164 ->
lookup:get_remote_party_name("+" ++ E164, DstHost);
_ -> none
end
).
%%--------------------------------------------------------------------
%% @spec (Key) -> term()
%%
%% @doc
%% @see lookup:rewrite_potn_to_e164/1.
%% @end
%%--------------------------------------------------------------------
rewrite_potn_to_e164(Key) ->
?CHECK_EXPORTED({rewrite_potn_to_e164, 1},
?LOCAL_MODULE:rewrite_potn_to_e164(Key),
lookup:rewrite_potn_to_e164(Key)
).
% userdb hooks
%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (Address) -> term()
%%
%% @doc Looks up exactly one user with an Address. Used for
example in REGISTER . If there are multiple users with an
%% address, this function returns {error}.
%% @see sipuserdb:get_user_with_address/1.
%% @end
%%--------------------------------------------------------------------
get_user_with_address(Address) ->
?CHECK_EXPORTED({get_user_with_address, 1},
?LOCAL_MODULE:get_user_with_address(Address),
sipuserdb:get_user_with_address(Address)
).
%%--------------------------------------------------------------------
%% @spec (Address) -> term()
%%
%% @doc Looks up all users with a given address. Used to find out
%% to which users we should send a request.
%% @see sipuserdb:get_users_for_address_of_record/1.
%% @end
%%--------------------------------------------------------------------
get_users_for_address_of_record(Address) ->
?CHECK_EXPORTED({get_users_for_address_of_record, 1},
?LOCAL_MODULE:get_users_for_address_of_record(Address),
sipuserdb:get_users_for_address_of_record(Address)
).
%%--------------------------------------------------------------------
%% @spec (Addresses) -> term()
%%
%% @doc
@see sipuserdb : get_users_for_addresses_of_record/1 .
%% @end
%%--------------------------------------------------------------------
get_users_for_addresses_of_record(Addresses) ->
?CHECK_EXPORTED({get_users_for_addresses_of_record, 1},
?LOCAL_MODULE:get_users_for_addresses_of_record(Addresses),
sipuserdb:get_users_for_addresses_of_record(Addresses)
).
%%--------------------------------------------------------------------
%% @spec (User) -> term()
%%
%% @doc Gets all addresses for a user. Used for example to check
%% if a request from a user has an acceptable From: header.
%% @see sipuserdb:get_addresses_for_user/1.
%% @end
%%--------------------------------------------------------------------
get_addresses_for_user(User) ->
?CHECK_EXPORTED({get_addresses_for_user, 1},
?LOCAL_MODULE:get_addresses_for_user(User),
sipuserdb:get_addresses_for_user(User)
).
%%--------------------------------------------------------------------
%% @spec (Users) -> term()
%%
%% @doc
%% @see sipuserdb:get_addresses_for_users/1.
%% @end
%%--------------------------------------------------------------------
get_addresses_for_users(Users) ->
?CHECK_EXPORTED({get_addresses_for_users, 1},
?LOCAL_MODULE:get_addresses_for_users(Users),
sipuserdb:get_addresses_for_users(Users)
).
%%--------------------------------------------------------------------
%% @spec (URL) -> term()
%%
%% @doc
%% @see sipuserdb:get_users_for_url/1.
%% @end
%%--------------------------------------------------------------------
get_users_for_url(URL) ->
?CHECK_EXPORTED({get_users_for_url, 1},
?LOCAL_MODULE:get_users_for_url(URL),
sipuserdb:get_users_for_url(URL)
).
%%--------------------------------------------------------------------
%% @spec (User) -> term()
%%
%% @doc
%% @see sipuserdb:get_password_for_user/1.
%% @end
%%--------------------------------------------------------------------
get_password_for_user(User) ->
?CHECK_EXPORTED({get_password_for_user, 1},
?LOCAL_MODULE:get_password_for_user(User),
sipuserdb:get_password_for_user(User)
).
%%--------------------------------------------------------------------
%% @spec (User) -> term()
%%
%% @doc
@see sipuserdb : .
%% @end
%%--------------------------------------------------------------------
get_classes_for_user(User) ->
?CHECK_EXPORTED({get_classes_for_user, 1},
?LOCAL_MODULE:get_classes_for_user(User),
sipuserdb:get_classes_for_user(User)
).
%%--------------------------------------------------------------------
%% @spec (User) -> term()
%%
%% @doc
%% @see sipuserdb:get_telephonenumber_for_user/1.
%% @end
%%--------------------------------------------------------------------
get_telephonenumber_for_user(User) ->
?CHECK_EXPORTED({get_telephonenumber_for_user, 1},
?LOCAL_MODULE:get_telephonenumber_for_user(User),
sipuserdb:get_telephonenumber_for_user(User)
).
%%--------------------------------------------------------------------
%% @spec (Users) -> term()
%%
%% @doc
@see sipuserdb : get_forwards_for_users/1 .
%% @end
%%--------------------------------------------------------------------
get_forwards_for_users(Users) ->
?CHECK_EXPORTED({get_forwards_for_user, 1},
?LOCAL_MODULE:get_forwards_for_users(Users),
sipuserdb:get_forwards_for_users(Users)
).
%%--------------------------------------------------------------------
@spec ( Module , Function , ) - > { ok , Res } | undefined
%%
%% Module = atom() "sipuserdb module"
%% Function = atom() "function in Module"
= term ( ) " arguments to function "
%%
@doc to override a specific sipuserdb backend function . If
%% 'undefined' is returned, the real backend function will
%% be called
%% @end
%%--------------------------------------------------------------------
sipuserdb_backend_override(Module, Function, Args) ->
?CHECK_EXPORTED({sipuserdb_backend_override, 3},
?LOCAL_MODULE:sipuserdb_backend_override(Module, Function, Args),
undefined
).
%%--------------------------------------------------------------------
@spec ( CfgKey , ) - >
%% {ok, Res} | undefined
%%
%% CfgKey = sipuserdb_mysql_get_sipuser |
%% sipuserdb_mysql_get_user_for_address |
%% sipuserdb_mysql_get_addresses_for_user |
%% sipuserdb_mysql_get_classes_for_user |
%% sipuserdb_mysql_get_password_for_user |
%% sipuserdb_mysql_get_telephonenumber_for_user
= term ( ) " ) to use in SQL query "
%%
%% Res = string() "SQL query"
%%
%% @doc If you need to make SQL statements other than what is
%% possible using the template-based configuration parameter
%% possibilitys, do it here. Return 'undefined' to let
%% sipuserdb_mysql do it's default query construction. Note
: You have to mysql : quote ( ) everything you use from !
%% @end
%%--------------------------------------------------------------------
sipuserdb_mysql_make_sql_statement(CfgKey, Args) ->
?CHECK_EXPORTED({sipuserdb_mysql_make_sql_statement, 2},
?LOCAL_MODULE:sipuserdb_mysql_make_sql_statement(CfgKey, Args),
undefined
).
% Location lookup hooks
%%%%%%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (Users) -> term()
%%
%% @doc Looks up all contacts for a list of users. Used to find
%% out where a set of users are to see where we should route
%% a request.
%% @see siplocation:get_locations_for_users/1.
%% @end
%%--------------------------------------------------------------------
get_locations_for_users(Users) ->
?CHECK_EXPORTED({get_locations_for_users, 1},
?LOCAL_MODULE:get_locations_for_users(Users),
siplocation:get_locations_for_users(Users)
).
%%--------------------------------------------------------------------
%% @spec (URI) -> term()
%%
%% @doc Checks if any of our users are registered at the location
%% specified. Used to determine if we should proxy requests
%% to a URI without authorization.
%% @see siplocation:get_user_with_contact/1.
%% @end
%%--------------------------------------------------------------------
get_user_with_contact(URI) ->
?CHECK_EXPORTED({get_user_with_contact, 1},
?LOCAL_MODULE:get_user_with_contact(URI),
siplocation:get_user_with_contact(URI)
).
%%--------------------------------------------------------------------
%% @spec (URI) -> term()
%%
%% @doc like get_user_with_contact but returns a list of
%% siplocationdb_e records instead
%% @see siplocation:get_locations_with_contact/1.
%% @end
%%--------------------------------------------------------------------
%% like get_user_with_contact but returns a list of siplocationdb_e records instead
get_locations_with_contact(URI) ->
?CHECK_EXPORTED({get_locations_with_contact, 1},
?LOCAL_MODULE:get_locations_with_contact(URI),
siplocation:get_locations_with_contact(URI)
).
%%--------------------------------------------------------------------
@spec ( User , InstanceId , GRUU , To ) - >
%% URL | undefined
%%
URL = # sipurl { }
%%
%% @doc Make an URL out of a GRUU. Return 'undefined' for default
%% algorithm.
%% @see foo
%% @end
%%--------------------------------------------------------------------
gruu_make_url(User, InstanceId, GRUU, To) ->
?CHECK_EXPORTED({gruu_make_url, 4},
?LOCAL_MODULE:gruu_make_url(User, InstanceId, GRUU, To),
undefined
).
%%--------------------------------------------------------------------
%% @spec (URL) ->
%% {true, GRUU} | false
%%
%% GRUU = string()
%%
%% @doc Check if an URL possibly is a GRUU we've created.
@see gruu : is_gruu_url/1 .
%% @end
%%--------------------------------------------------------------------
is_gruu_url(URL) ->
?CHECK_EXPORTED({is_gruu_url, 1},
?LOCAL_MODULE:is_gruu_url(URL),
gruu:is_gruu_url(URL)
).
AAA hooks
%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (Header, Method) -> term()
%%
%% @doc
%% @see sipauth:get_user_verified/2.
%% @end
%%--------------------------------------------------------------------
get_user_verified(Header, Method) ->
?CHECK_EXPORTED({get_user_verified, 2},
?LOCAL_MODULE:get_user_verified(Header, Method),
sipauth:get_user_verified(Header, Method)
).
%%--------------------------------------------------------------------
%% @spec (Header, Method) -> term()
%%
%% @doc
%% @see sipauth:get_user_verified_proxy/2.
%% @end
%%--------------------------------------------------------------------
get_user_verified_proxy(Header, Method) ->
?CHECK_EXPORTED({get_user_verified_proxy, 2},
?LOCAL_MODULE:get_user_verified_proxy(Header, Method),
sipauth:get_user_verified_proxy(Header, Method)
).
%%--------------------------------------------------------------------
%% @spec (User, URL) -> true | false
%%
%% User = string() "SIP authentication username"
URL = # sipurl { }
%%
%% @doc Check if a user (authenticated elsewhere) may use an
%% address. See sipauth module for more information.
%% @see sipauth:can_use_address/2.
%% @end
%%--------------------------------------------------------------------
can_use_address(User, URL) when is_list(User), is_record(URL, sipurl) ->
?CHECK_EXPORTED({can_use_address, 2},
?LOCAL_MODULE:can_use_address(User, URL),
sipauth:can_use_address(User, URL)
).
%%--------------------------------------------------------------------
%% @spec (User, URL) ->
{ Verdict , Reason }
%%
%% User = string() "SIP authentication username"
URL = # sipurl { }
%%
%% Verdict = true | false
%% Reason = ok | eperm | nomatch | error
%%
%% @doc Check if a user (authenticated elsewhere) may use an
%% address. See sipauth module for more information.
%% @see sipauth:can_use_address_detail/2.
%% @end
%%--------------------------------------------------------------------
can_use_address_detail(User, URL) when is_list(User), is_record(URL, sipurl) ->
?CHECK_EXPORTED({can_use_address_detail, 2},
?LOCAL_MODULE:can_use_address_detail(User, URL),
sipauth:can_use_address_detail(User, URL)
).
%%--------------------------------------------------------------------
%% @spec (Header, ToURL) ->
{ { Verdict , Reason } , User } |
%% {stale, User} |
%% {false, none}
%%
%% Header = #keylist{}
# sipurl { }
%%
%% Verdict = true | false
%% Reason = ok | eperm | nomatch | error
%%
@doc Check if a REGISTER message authenticates OK etc . See
sipauth module for more information .
@see sipauth : .
%% @end
%%--------------------------------------------------------------------
can_register(Header, ToURL) when is_record(Header, keylist), is_record(ToURL, sipurl) ->
?CHECK_EXPORTED({can_register, 2},
?LOCAL_MODULE:can_register(Header, ToURL),
sipauth:can_register(Header, ToURL)
).
%%--------------------------------------------------------------------
@spec ( User , ToNumber , Header , Class ) - > bool ( )
%%
%% User = string() "authenticated SIP username"
%% ToNumber = string() "phone number - E.164 if conversion was possible, otherwise it is the number as entered by the caller"
%% Header = #keylist{} "SIP header of request"
%% Class = undefined | atom()
%%
%% @doc
@see sipauth : is_allowed_pstn_dst/4 .
%% @end
%%--------------------------------------------------------------------
is_allowed_pstn_dst(User, ToNumber, Header, Class) ->
?CHECK_EXPORTED({is_allowed_pstn_dst, 4},
?LOCAL_MODULE:is_allowed_pstn_dst(User, ToNumber, Header, Class),
sipauth:is_allowed_pstn_dst(User, ToNumber, Header, Class)
).
%%--------------------------------------------------------------------
%% @spec (Username, Header) ->
%% NewUsername |
%% undefined
%%
%% Username = string()
%% Header = #keylist{}
%%
%% NewUsername = string()
%%
%% @doc Possibly make us use another username for this request.
This is needed if your user database allows more than one
%% username per user, or if you have clients that does not
%% allow you to set authorization username explicitly and
%% the username they assume you have is incorrect.
%% @end
%%--------------------------------------------------------------------
canonify_authusername(Username, Header) when is_list(Username), is_record(Header, keylist) ->
?CHECK_EXPORTED({canonify_authusername, 2},
?LOCAL_MODULE:canonify_authusername(Username, Header),
undefined
).
% incomingproxy hooks
%%%%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (Origin, Request, Dst) -> term()
%%
%% @doc Check if 'incomingproxy' should challenge a request that
%% it has determined it should relay, or if it should proxy
%% the request without authorization instead.
%% @end
%%--------------------------------------------------------------------
incomingproxy_challenge_before_relay(Origin, Request, Dst) when is_record(Origin, siporigin),
is_record(Request, request) ->
?CHECK_EXPORTED({incomingproxy_challenge_before_relay, 3},
?LOCAL_MODULE:incomingproxy_challenge_before_relay(Origin, Request, Dst),
true
).
%%--------------------------------------------------------------------
%% @spec (Request, Origin) -> {forward, FwdURL} | false
%%
%% @doc This function is called when incomingproxy gets a PUBLISH
%% or SUBSCRIBE request to a homedomain. Return 'false' for
%% default processing, or {forward, FwdURL} if you want to
%% get the request routed somewhere special.
%% @end
%%--------------------------------------------------------------------
incomingproxy_request_homedomain_event(Request, Origin) when is_record(Request, request),
is_record(Origin, siporigin) ->
?CHECK_EXPORTED({incomingproxy_request_homedomain_event, 2},
?LOCAL_MODULE:incomingproxy_request_homedomain_event(Request, Origin),
undefined
).
%% pstnproxy hooks
%%%%%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
@spec ( DstNumber , Request , PstnCtx ) - >
undefined | nomatch | ignore | Relay
%%
%% DstNumber = string() "typically user-part of Request-URI"
%% Request = #request{}
%% Origin = #siporigin{}
%% THandler = term() "server transaction handler"
%%
%% Relay = {relay, DstURI}
%% Response = {response, Status, Reason, ExtraHeaders}
%%
@doc When a request destined for PSTN is received by the
%% pstnproxy, and no destination is found using
%% local:lookuppstn(), this function is called. The return
%% values have the following meaning :
%% undefined - proceed with default behavior nomatch - there
is no destination for DstNumber , reject request with a
%% '404 Not Found' ignore - pstnproxy should do nothing
%% further (this function must generate a final response)
%% Response - send a response Relay - send Request to DstURI
%%
%% @end
%%--------------------------------------------------------------------
pstnproxy_route_pstn_not_e164(DstNumber, Request, PstnCtx) ->
?CHECK_EXPORTED({pstnproxy_route_pstn_not_e164, 3},
?LOCAL_MODULE:pstnproxy_route_pstn_not_e164(DstNumber, Request, PstnCtx),
undefined
).
%%--------------------------------------------------------------------
@spec ( Request , Origin , THandler , PstnCtx ) - > term ( )
%%
%% Request = #request{}
Origin = # siporigin { }
%% THandler = term() "server transaction handle"
PstnCtx = # pstn_ctx { }
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
%% Returns: pstn_ctx record()
pstnproxy_auth_and_tag(Request, Origin, THandler, PstnCtx) when is_record(Request, request),
is_record(Origin, siporigin),
is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_auth_and_tag, 4},
?LOCAL_MODULE:pstnproxy_auth_and_tag(Request, Origin, THandler, PstnCtx),
PstnCtx
).
%%--------------------------------------------------------------------
@spec ( Request , PstnCtx ) - >
%% {ok, AllowedMethods}
%%
%% Request = #request{}
PstnCtx = # pstn_ctx { }
%%
%% AllowedMethods = [string()]
%%
%% @doc Return list of allowed SIP methods. Must be upper-cased.
%% @end
%%--------------------------------------------------------------------
pstnproxy_allowed_methods(Request, PstnCtx) when is_record(Request, request),
is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_allowed_methods, 2},
?LOCAL_MODULE:pstnproxy_allowed_methods(Request, PstnCtx),
yxa_config:get_env(allowed_request_methods)
).
%%--------------------------------------------------------------------
@spec ( Request , PstnCtx ) - > true | false | undefined
%%
%% Request = #request{}
PstnCtx = # pstn_ctx { }
%%
%% @doc Decide if pstnproxy should proxy a request, or reject it
%% with a '403 Forbidden'. Return 'undefined' for default
%% processing.
%% @end
%%--------------------------------------------------------------------
pstnproxy_allowed_proxy_request(Request, PstnCtx) when is_record(Request, request),
is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_allowed_proxy_request, 2},
?LOCAL_MODULE:pstnproxy_allowed_proxy_request(Request, PstnCtx),
undefined
).
%%--------------------------------------------------------------------
@spec ( Request , THandler , YXAPeerAuth , PstnCtx ) - > term ( )
%%
%% Request = #request{}
%% THandler = term() "server transaction handle"
%% YxaPeerAuth = true | false
PstnCtx = # pstn_ctx { }
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
pstnproxy_verify_from(Request, THandler, YXAPeerAuth, PstnCtx) when is_record(Request, request),
is_boolean(YXAPeerAuth),
is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_verify_from, 4},
?LOCAL_MODULE:pstnproxy_verify_from(Request, THandler, YXAPeerAuth, PstnCtx),
undefined
).
%%--------------------------------------------------------------------
@spec ( Request , THandler , LogTag , PstnCtx ) - > term ( )
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
pstnproxy_number_based_routing(Request, THandler, LogTag, PstnCtx) ->
?CHECK_EXPORTED({pstnproxy_number_based_routing, 4},
?LOCAL_MODULE:pstnproxy_number_based_routing(Request, THandler, LogTag, PstnCtx),
undefined
).
%%--------------------------------------------------------------------
@spec ( Request , PstnCtx ) - > term ( )
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
pstnproxy_lookup_action(Request, PstnCtx) when is_record(Request, request), is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_lookup_action, 2},
?LOCAL_MODULE:pstnproxy_lookup_action(Request, PstnCtx),
undefined
).
% outgoingproxy hooks
%%%%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (Origin, Request, Dst) -> term()
%%
%% @doc Check if 'outgoingproxy' should challenge a request that
%% it has determined it should relay, or if it should proxy
%% the request without authorization instead.
%% @end
%%--------------------------------------------------------------------
outgoingproxy_challenge_before_relay(Origin, Request, Dst) when is_record(Origin, siporigin),
is_record(Request, request) ->
?CHECK_EXPORTED({outgoingproxy_challenge_before_relay, 3},
?LOCAL_MODULE:outgoingproxy_challenge_before_relay(Origin, Request, Dst),
true
).
% eventserver hooks
%%%%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
@spec ( EventPackage , Request , ) - >
%% {ok, PackageModule} |
%% undefined
%%
EventPackage = string ( ) " \"presence\ " or \"ua - config\ " etc . "
%% Request = #request{}
%% YxaCtx = #yxa_ctx{}
%%
%% PackageModule = atom()
%%
%% @doc Decide which event package should handle a request
%% (SUBSCRIBE or PUBLISH) in the eventserver. You can use
%% this to make only certain SUBSCRIBE/PUBLISH requests go
%% to a custom event package. Remember to make
%% get_all_event_packages return any additions too.
%% @end
%%--------------------------------------------------------------------
get_event_package_module(EventPackage, Request, YxaCtx) when is_list(EventPackage), is_record(Request, request),
is_record(YxaCtx, yxa_ctx) ->
?CHECK_EXPORTED({get_event_package_module, 3},
?LOCAL_MODULE:get_event_package_module(EventPackage, Request, YxaCtx),
undefined
).
%%--------------------------------------------------------------------
%% @spec () ->
%% {ok, PackageDefs}
%%
%% PackageDefs = [{Package, Module}]
%% Package = string()
%% Module = atom()
%%
%% @doc Get list of all event packages. Duplicate Package is
%% allowed (and has a purpose, if you want to have more than
one possible Module for a Package ( decided using
%% get_event_package_module/3 above).
%% @end
%%--------------------------------------------------------------------
get_all_event_packages() ->
?CHECK_EXPORTED({get_all_event_packages, 0},
?LOCAL_MODULE:get_all_event_packages(),
yxa_config:get_env(eventserver_package_handlers)
).
%%--------------------------------------------------------------------
%% @spec (Type, User, Location) -> term()
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
eventserver_locationdb_action(Type, User, Location) when is_atom(Type), is_list(User) ->
?CHECK_EXPORTED({eventserver_locationdb_action, 3},
?LOCAL_MODULE:eventserver_locationdb_action(Type, User, Location),
undefined
).
% sippipe hooks
%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
@spec ( Request , , Dst , AppData ) - >
%% term() "result of sipppipe:start/5"
%%
%% Request = #request{}
YxaCtx = # yxa_ctx { }
Dst = # sipurl { } | route | [ # sipdst { } ]
%% AppData = [term()] "application specific data passed to the start_sippipe/4 function in your 'local' module."
%%
@doc Start a sippipe for one of the YXA applications
%% incomingproxy, outgoingproxy or pstnproxy. This is a very
%% suitable place to for example add/delete headers.
%% @see sippipe:start/5.
%% @end
%%--------------------------------------------------------------------
start_sippipe(Request, YxaCtx, Dst, AppData) when is_record(Request, request), is_record(YxaCtx, yxa_ctx),
is_list(AppData) ->
?CHECK_EXPORTED({start_sippipe, 4},
?LOCAL_MODULE:start_sippipe(Request, YxaCtx, Dst, AppData),
begin
THandler = YxaCtx#yxa_ctx.thandler,
ClientTransaction = none,
sippipe:start(THandler, ClientTransaction, Request, Dst, ?SIPPIPE_TIMEOUT)
end
).
%%--------------------------------------------------------------------
% action.
@spec ( Request , Response , DstList ) - >
%% undefined |
%% {huntstop, Status, Reason} |
{ next , NewDstList }
%%
%% Request = #request{}
%% Response = #response{} | {Status, Reason}
DstList = [ # sipdst { } ]
%%
%% Status = integer() "SIP status code"
%% Reason = string() "SIP reason phrase"
= [ # sipdst { } ]
%%
@doc When receives a final response , this function is
%% called. Depending on the return value of this function,
will behave differently . ' undefined ' means
will fall back to it 's default ' huntstop ' will
%% make sippipe stop processing and instruct the server
%% transaction to send a response (Status, Reason). 'next'
will tell to try the next destination in
NewDstList ( possibly altered version of DstList ) .
%% @end
%%--------------------------------------------------------------------
sippipe_received_response(Request, Response, DstList) when is_record(Request, request),
is_record(Response, response) ->
?CHECK_EXPORTED({sippipe_received_response, 3},
?LOCAL_MODULE:sippipe_received_response(Request, Response, DstList),
undefined
);
sippipe_received_response(Request, {Status, Reason}, DstList) when is_record(Request, request),
is_integer(Status), is_list(Reason) ->
?CHECK_EXPORTED({sippipe_received_response, 3},
?LOCAL_MODULE:sippipe_received_response(Request, {Status, Reason}, DstList),
undefined
).
% cpl_db hooks
%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (User) -> true | false
%%
%% User = string()
%%
%% @doc determine if a cpl script has been loaded for the user
%% User
%% @see cpl_db:user_has_cpl_script/1.
%% @end
%%--------------------------------------------------------------------
user_has_cpl_script(User) ->
?CHECK_EXPORTED({user_has_cpl_script, 1},
?LOCAL_MODULE:user_has_cpl_script(User),
cpl_db:user_has_cpl_script(User)
).
%%--------------------------------------------------------------------
%% @spec (User, Direction) -> true | false
%%
%% User = string()
%% Direction = incoming | outgoing
%%
%% @doc determine if a cpl script has been loaded for the user
%% User
%% @see cpl_db:user_has_cpl_script/1.
%% @end
%%--------------------------------------------------------------------
user_has_cpl_script(User, Direction) ->
?CHECK_EXPORTED({user_has_cpl_script, 2},
?LOCAL_MODULE:user_has_cpl_script(User, Direction),
cpl_db:user_has_cpl_script(User, Direction)
).
%%--------------------------------------------------------------------
%% @spec (User) ->
nomatch | { ok , CPLGraph }
%%
%% User = string()
%%
CPLGraph = term ( ) " a cpl graph for use in interpret_cpl : process_cpl_script ( ... ) "
%%
%% @doc get the cpl script graph for a certain user
@see cpl_db : get_cpl_for_user/1 .
%% @end
%%--------------------------------------------------------------------
get_cpl_for_user(User) ->
?CHECK_EXPORTED({get_cpl_for_user, 1},
?LOCAL_MODULE:get_cpl_for_user(User),
cpl_db:get_cpl_for_user(User)
).
%%--------------------------------------------------------------------
%% See cpl/README
%%--------------------------------------------------------------------
%%--------------------------------------------------------------------
%% @spec (LogName, Comment, User, Request) -> term()
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
cpl_log(LogName, Comment, User, Request) ->
?CHECK_EXPORTED({cpl_log, 4},
?LOCAL_MODULE:cpl_log(LogName, Comment, User, Request),
undefined
).
%%--------------------------------------------------------------------
%% @spec (LogName) -> term()
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
cpl_is_log_dest(LogName) ->
?CHECK_EXPORTED({cpl_is_log_dest, 1},
?LOCAL_MODULE:cpl_is_log_dest(LogName),
undefined
).
%%--------------------------------------------------------------------
%% @spec (Mail, User) -> term()
%%
%% @doc
%% @end
%%--------------------------------------------------------------------
cpl_mail(Mail, User) ->
?CHECK_EXPORTED({cpl_mail, 2},
?LOCAL_MODULE:cpl_mail(Mail, User),
undefined
).
%% transaction layer hooks
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
%% @spec (Request, Dst, Branch, Timeout) ->
%% Pid |
%% {error, Reason}
%%
%% Request = #request{}
Dst = # sipdst { } " the destination for this client transaction "
%% Branch = string()
Timeout = integer ( ) " timeout for INVITE transactions "
%%
%% Pid = pid() "started client transaction handler"
%% Reason = string()
%%
%% @doc Start a client transaction, possibly after altering the
%% request to be sent.
@see transactionlayer : .
%% @end
%%--------------------------------------------------------------------
start_client_transaction(Request, Dst, Branch, Timeout) when is_record(Request, request), is_record(Dst, sipdst),
is_list(Branch), is_integer(Timeout) ->
?CHECK_EXPORTED({start_client_transaction, 4},
?LOCAL_MODULE:start_client_transaction(Request, Dst, Branch, Timeout),
transactionlayer:start_client_transaction(Request, Dst, Branch, Timeout, self())
).
%%--------------------------------------------------------------------
@spec ( AppModule , Request , ) - >
%% undefined |
%% ignore |
{ modified , NewAppModule , NewRequest , NewOrigin , NewLogStr }
%%
AppModule = atom ( ) " YXA application module the transaction layer thought this request should be passed to "
%% Request = #request{}
%% YxaCtx = #yxa_ctx{}
%%
%% @doc This function gets called when the transaction layer has
%% decided that a new request has arrived, and figured it
should be passed to the YXA application ( proxy core/
%% transaction user). Depending on what this function
returns , the AppModule : request/2 function will either not
%% be called at all, called with the parameters unchanged or
%% called with a modified set of parameters. Note : DON'T
%% ALTER THE URI OF INVITE REQUESTS HERE! If you do, the
of non-2xx responses will be disqualified by the
server transaction since the URI of the ACK does n't match
the URI of the original INVITE ( since you changed it ) .
%% @end
%%--------------------------------------------------------------------
new_request(AppModule, Request, YxaCtx) ->
?CHECK_EXPORTED({new_request, 3},
?LOCAL_MODULE:new_request(AppModule, Request, YxaCtx),
undefined
).
%%--------------------------------------------------------------------
@spec ( AppModule , Response , ) - >
%% undefined |
%% ignore |
{ modified , NewAppModule , NewResponse , NewOrigin , NewLogStr }
%%
AppModule = atom ( ) " YXA application module the transaction layer thought this request should be passed to "
%% Response = #response{}
%% YxaCtx = #yxa_ctx{}
%%
%% @doc This function gets called when the transaction layer has
%% decided that a response not assoicated with a running
%% client transaction has arrived. Such responses should be
passed to the YXA application ( proxy core / transaction
%% user). Depending on what this function returns, the
AppModule : response/2 function will either not be called
%% at all, called with the parameters unchanged or called
%% with a modified set of parameters.
%% @end
%%--------------------------------------------------------------------
new_response(AppModule, Response, YxaCtx) ->
?CHECK_EXPORTED({new_response, 3},
?LOCAL_MODULE:new_response(AppModule, Response, YxaCtx),
undefined
).
%% transport layer hooks
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
@spec ( Socket , , Proto , Host , Port , Module , Subject ) - >
%% true | false | undefined
%%
%% Socket = term() "the socket"
%% Dir = in | out "direction of connection"
%% Proto = tcp | tcp6 | tls | tls6
%% Host = string() "IP address or hostname of remote end"
%% Port = integer()
Module = atom ( ) " SIP - socket module name ( sipsocket_tcp ) "
%% Subject = term() | undefined "SSL socket Subject information (if SSL socket)"
%%
%% @doc Verify a socket. Return 'true' for acceptable, 'false' for
%% NOT acceptable and 'undefined' to do default checks.
%% @end
%%--------------------------------------------------------------------
is_acceptable_socket(Socket, Dir, Proto, Host, Port, Module, Subject) ->
?CHECK_EXPORTED({is_acceptable_socket, 7},
?LOCAL_MODULE:is_acceptable_socket(Socket, Dir, Proto, Host, Port, Module, Subject),
undefined
).
%%--------------------------------------------------------------------
@spec ( Proto , Host , Port ) - > true | false | undefined
%%
%% Proto = tcp | tcp6 | udp | udp6
%%
%% @doc If a destination (proto:host:port) is not TLS it might
still be protected by an equivalence to TLS ( like IPsec ) .
%% When we require a TLS-protected destination, this hook
%% lets you indicate that a particular destination is to be
%% considered secure at the transport layer.
%% @end
%%--------------------------------------------------------------------
is_tls_equivalent(Proto, Host, Port) ->
?CHECK_EXPORTED({is_tls_equivalent, 3},
?LOCAL_MODULE:is_tls_equivalent(Proto, Host, Port),
undefined
).
%%--------------------------------------------------------------------
@spec ( Names , Subject , AltNames ) - >
NewAltNames
%%
%% Names = [string()] "list of names for the certificate that the upper layer is willing to accept"
Subject = term ( ) " ssl : ( ) subject data "
AltNames = [ string ( ) ] " subjectAltName : s in cert "
%%
NewAltNames = [ string ( ) ]
%%
@doc that lets you manipulate what names are considered
%% valid for a SSL certificate presented by a host. If, for
%% example, the host p1.example.org returns a certificate
%% with the subjectAltNames, Names might be ["example.org"]
since a user tried to reach sip: , and
AltNames might be [ " p1.example.org " ] . In this case , you
must add " example.org " to AltNames , to allow the
%% certificate.
%% @end
%%--------------------------------------------------------------------
get_valid_altnames(Names, Subject, AltNames) ->
?CHECK_EXPORTED({get_valid_altnames, 3},
?LOCAL_MODULE:get_valid_altnames(Names, Subject, AltNames),
AltNames
).
%%--------------------------------------------------------------------
%% @spec (Dst) ->
%% {ok, Entry} |
%% {ok, blacklisted} |
%% {ok, whitelisted} |
%% undefined
%%
Dst = { Proto , Addr , Port }
%% Proto = tcp | tcp6 | udp | udp6 | tls | tls6 | atom()
= string ( ) " typically IPv4 / IPv6 address "
%% Port = integer()
%%
%% Entry = #blacklist_entry{}
%%
%% @doc Check if a destination is blacklisted/whitelisted. Return
%% 'undefined' for default processing.
%% @see sipsocket_blacklist:lookup_sipsocket_blacklist/1.
%% @end
%%--------------------------------------------------------------------
lookup_sipsocket_blacklist(Dst) ->
?CHECK_EXPORTED({lookup_sipsocket_blacklist, 1},
?LOCAL_MODULE:lookup_sipsocket_blacklist(Dst),
sipsocket_blacklist:lookup_sipsocket_blacklist(Dst)
).
%% configuration hooks
%%%%%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
@spec ( Key , Value , ) - >
{ ok , } |
%% {error, Msg}
%%
%% Key = atom()
%% Value = term()
%% Src = atom() "config backend module that found this configuration parameter"
%%
= term ( )
%% Msg = string()
%%
%% @doc Check a local configuration parameter. Local parameters
%% are local_*.
%% @end
%%--------------------------------------------------------------------
check_config_type(Key, Value, Src) ->
%% We have to do this with try/catch instead of ?CHECK_EXPORTED since
%% this function is needed before 'local' has been initialized
try ?LOCAL_MODULE:check_config_type(Key, Value, Src) of
Res ->
Res
catch
error: undef ->
%% the local module did not export check_config_type/3
{ok, Value}
end.
%%--------------------------------------------------------------------
%% @spec (Key, Value) -> true | false
%%
%% Key = atom()
%% Value = term()
%%
%% @doc Check if it is possible to change a local configuration
%% parameter with a soft reconfiguration (true), or if a
%% complete restart of the application is necessary (false).
%% @end
%%--------------------------------------------------------------------
config_is_soft_reloadable(Key, Value) ->
?CHECK_EXPORTED({config_is_soft_reloadable, 2},
?LOCAL_MODULE:config_is_soft_reloadable(Key, Value),
true
).
%%--------------------------------------------------------------------
%% @spec (Key, Value, Mode) ->
%% ok | {error, Reason}
%%
%% Key = atom()
%% Value = term()
%% Mode = soft | hard
%%
%% Reason = string()
%%
%% @doc Perform any necessary actions when a configuration value
%% changes, like perhaps notifying a gen_server or similar.
%% @end
%%--------------------------------------------------------------------
config_change_action(Key, Value, Mode) ->
%% We have to do this with try/catch instead of ?CHECK_EXPORTED since
%% this function is needed before 'local' has been initialized
try ?LOCAL_MODULE:config_change_action(Key, Value, Mode) of
Res ->
Res
catch
error: undef ->
%% the local module did not export config_change_action/3
ok
end.
%% sipdialog hooks
%%%%%%%%%%%%%%%%%%%
%%--------------------------------------------------------------------
@spec ( Caller , Request , ToTag , Contact ) - >
%% {ok, Dialog}
%%
%% Caller = term() "who is calling us?"
%% Request = #request{} "received request that causes us to create a dialog"
%% ToTag = string() "the To-tag our server transaction for this request has generated"
%% Contact = string() "our Contact header value"
%%
%% Dialog = #dialog{}
%%
%% @doc Create a dialog record out of a received request and some
%% other parameters.
%% @see sipdialog:create_dialog_state_uas/3.
%% @end
%%--------------------------------------------------------------------
create_dialog_state_uas(Caller, Request, ToTag, Contact) ->
?CHECK_EXPORTED({create_dialog_state_uas, 4},
?LOCAL_MODULE:create_dialog_state_uas(Caller, Request, ToTag, Contact),
sipdialog:create_dialog_state_uas(Request, ToTag, Contact)
).
| null | https://raw.githubusercontent.com/fredrikt/yxa/85da46a999d083e6f00b5f156a634ca9be65645b/src/local.erl | erlang | -------------------------------------------------------------------
File : local.erl
@doc Interface to local functions hooking into lots of
@end
-------------------------------------------------------------------
--------------------------------------------------------------------
External exports
--------------------------------------------------------------------
--------------------------------------------------------------------
Hooks
--------------------------------------------------------------------
lookup
siplocation
sipauth
sipuserdb
incomginproxy
pstnproxy
outgoingproxy
eventserver
sippipe
cpl_db
transaction layer
transport layer
custom log and mail cpl functions
configuration
sipdialog
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
====================================================================
External functions
====================================================================
--------------------------------------------------------------------
@spec () -> ok
@doc Look at the list of exported functions from the module
specified as ?LOCAL_MODULE, and make a cache of which of
_this_ modules functions are overridden in the
?LOCAL_MODULE module.
@hidden
@end
--------------------------------------------------------------------
Check which of this ('local') modules exported functions are also exported
time and can be affected by supplying a --with-local=modulename argument to
====================================================================
Hooks
====================================================================
--------------------------------------------------------------------
@spec (URL) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL) -> term()
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User) -> string()
User = string()
@doc Turn a SIP username into an address which can be reached
based on their username, but the username might need sip:
prepended to it, or a default domain name appended to it.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User) -> string()
User = string()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (In) -> [string()]
In = [string()]
@doc Canonify a list of addresses. Turn anything numeric into
userdb-modules which potentially get non-fully qualified
phone numbers (like local extension numbers) back from
the database.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (In) -> [string()]
In = [string()]
@doc
@end
--------------------------------------------------------------------
non-numeric part after '+' - leave unaltered
outgoingproxy don't have internal_to_e164 configuration parameter, so rewrite_potn_to_e164 might fail
Routing hooks
--------------------------------------------------------------------
@spec (Request, Origin) ->
{proxy, PDst} |
{relay, RDst} |
{error, S} |
{response, S, R} |
none
Request = #request{}
Origin = #request{}
S = integer() "SIP status code"
R = string() "SIP reason phrase"
Fwd = #sipurl{} "MUST have 'user' and 'pass' set to 'none'"
@doc Determine where to route a request that arrived to the
'incomingproxy' application, destined for a local domain
when it has been determined that the request was not
Return 'none' for default routing.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Request, Origin) ->
{proxy, PDst} |
{relay, RDst} |
{error, S} |
{response, S, R} |
none
Request = #request{}
Origin = #request{}
S = integer() "SIP status code"
R = string() "SIP reason phrase"
Fwd = #sipurl{} "MUST have 'user' and 'pass' set to 'none'"
@doc Determine where to route a request that arrived to the
'incomingproxy' application, destined for a remote
domain. Return 'none' to perform default routing.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Request) -> true | false
Request = #request{}
@doc Determine if a request is meant for this proxy itself, as
opposed to say a user of the system.
@see lookup:is_request_to_this_proxy/1.
@end
--------------------------------------------------------------------
lookup.erl hooks
--------------------------------------------------------------------
@spec (User) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL) ->
{proxy, URL} |
{relay, URL} |
{forward, URL} |
{response, Status, Reason} |
none |
nomatch
function that incomingproxy uses, when it determines that
@see lookup:lookupuser/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL, GRUU) ->
{proxy, URL} |
{relay, URL} |
{forward, URL} |
{response, Status, Reason} |
none |
nomatch
GRUU = string()
@doc Look up a GRUU. Used by incomingproxy and outgouingproxy.
@see lookup:lookupuser_gruu/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Users, URL) ->
Locations
Users = [string()] "SIP users to fetch locations of"
Locations = [#siplocationdb_e{}]
@doc Return all locations for a list of users that is suitable
given a Request-URI. By suitable, we mean that we filter
proxy is configured not to.
@see lookup:lookupuser_locations/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL, Locations) -> [#sipurl{}]
URL = #sipurl{} "Request-URI of request"
Location = [#sipurl{}]
@doc Apply local policy for what locations are good to use for
a particular Request-URI.
@see lookup:remove_unsuitable_locations/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Src, URL) -> term()
@doc
@see lookup:lookup_url_to_addresses/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Addresses) -> term()
@doc
@see lookup:lookup_addresses_to_users/1
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Address) -> term()
@doc
@see lookup:lookup_address_to_users/1
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Key) -> term()
@doc
@see lookup:lookupappserver/1
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Key, Locations) -> term()
@doc
@see siplocation:prioritize_locations/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL) -> term()
@doc
@see lookup:lookupdefault/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Number) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Number) -> term()
@doc
@see lookup:lookupnumber/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Number) -> term()
@doc
@see lookup:lookupenum/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Number) -> term()
@doc
@see lookup:lookuppstn/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL) -> term()
@doc lookup:isours/1.
@see foo
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Domain) -> true | false
Domain = string()
@doc Check if something is one of our 'homedomains' - a domain
we are the final destination for.
@see lookup:homedomain/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User, Header, URI, DstHost) ->
{ok, Number} |
none
User = string() "SIP authentication username"
Header = #keylist{}
DstHost = term() "chosen destination for request"
Number = string()
typically gets upset if the "A-number" (calling party) is
a SIP URL. Different gateways might want the number
formatted differently, thus the DstHost parameter (a TSP
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Number, Header, DstHost) ->
{ok, Number}
Number = string() "the number to format"
Header = #keylist{}
DstHost = term() "destination for request"
Number = string()
@doc Hook for the actual formatting once
formatted.
@see lookup:format_number_for_remote_party_id/3.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Key, DstHost) ->
none
Key = string() "number we should turn into a name"
DstHost = term() "destination for request"
@doc When pstnproxy receives a request from a PSTN gateway,
this function is called to see if we can find a nice
Display Name for the calling party. By default, we only
number.
@see lookup:get_remote_party_name/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Key) -> term()
@doc
@see lookup:rewrite_potn_to_e164/1.
@end
--------------------------------------------------------------------
userdb hooks
--------------------------------------------------------------------
@spec (Address) -> term()
@doc Looks up exactly one user with an Address. Used for
address, this function returns {error}.
@see sipuserdb:get_user_with_address/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Address) -> term()
@doc Looks up all users with a given address. Used to find out
to which users we should send a request.
@see sipuserdb:get_users_for_address_of_record/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Addresses) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User) -> term()
@doc Gets all addresses for a user. Used for example to check
if a request from a user has an acceptable From: header.
@see sipuserdb:get_addresses_for_user/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Users) -> term()
@doc
@see sipuserdb:get_addresses_for_users/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL) -> term()
@doc
@see sipuserdb:get_users_for_url/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User) -> term()
@doc
@see sipuserdb:get_password_for_user/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User) -> term()
@doc
@see sipuserdb:get_telephonenumber_for_user/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Users) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Module = atom() "sipuserdb module"
Function = atom() "function in Module"
'undefined' is returned, the real backend function will
be called
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
{ok, Res} | undefined
CfgKey = sipuserdb_mysql_get_sipuser |
sipuserdb_mysql_get_user_for_address |
sipuserdb_mysql_get_addresses_for_user |
sipuserdb_mysql_get_classes_for_user |
sipuserdb_mysql_get_password_for_user |
sipuserdb_mysql_get_telephonenumber_for_user
Res = string() "SQL query"
@doc If you need to make SQL statements other than what is
possible using the template-based configuration parameter
possibilitys, do it here. Return 'undefined' to let
sipuserdb_mysql do it's default query construction. Note
@end
--------------------------------------------------------------------
Location lookup hooks
--------------------------------------------------------------------
@spec (Users) -> term()
@doc Looks up all contacts for a list of users. Used to find
out where a set of users are to see where we should route
a request.
@see siplocation:get_locations_for_users/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URI) -> term()
@doc Checks if any of our users are registered at the location
specified. Used to determine if we should proxy requests
to a URI without authorization.
@see siplocation:get_user_with_contact/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URI) -> term()
@doc like get_user_with_contact but returns a list of
siplocationdb_e records instead
@see siplocation:get_locations_with_contact/1.
@end
--------------------------------------------------------------------
like get_user_with_contact but returns a list of siplocationdb_e records instead
--------------------------------------------------------------------
URL | undefined
@doc Make an URL out of a GRUU. Return 'undefined' for default
algorithm.
@see foo
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (URL) ->
{true, GRUU} | false
GRUU = string()
@doc Check if an URL possibly is a GRUU we've created.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Header, Method) -> term()
@doc
@see sipauth:get_user_verified/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Header, Method) -> term()
@doc
@see sipauth:get_user_verified_proxy/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User, URL) -> true | false
User = string() "SIP authentication username"
@doc Check if a user (authenticated elsewhere) may use an
address. See sipauth module for more information.
@see sipauth:can_use_address/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User, URL) ->
User = string() "SIP authentication username"
Verdict = true | false
Reason = ok | eperm | nomatch | error
@doc Check if a user (authenticated elsewhere) may use an
address. See sipauth module for more information.
@see sipauth:can_use_address_detail/2.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Header, ToURL) ->
{stale, User} |
{false, none}
Header = #keylist{}
Verdict = true | false
Reason = ok | eperm | nomatch | error
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
User = string() "authenticated SIP username"
ToNumber = string() "phone number - E.164 if conversion was possible, otherwise it is the number as entered by the caller"
Header = #keylist{} "SIP header of request"
Class = undefined | atom()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Username, Header) ->
NewUsername |
undefined
Username = string()
Header = #keylist{}
NewUsername = string()
@doc Possibly make us use another username for this request.
username per user, or if you have clients that does not
allow you to set authorization username explicitly and
the username they assume you have is incorrect.
@end
--------------------------------------------------------------------
incomingproxy hooks
--------------------------------------------------------------------
@spec (Origin, Request, Dst) -> term()
@doc Check if 'incomingproxy' should challenge a request that
it has determined it should relay, or if it should proxy
the request without authorization instead.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Request, Origin) -> {forward, FwdURL} | false
@doc This function is called when incomingproxy gets a PUBLISH
or SUBSCRIBE request to a homedomain. Return 'false' for
default processing, or {forward, FwdURL} if you want to
get the request routed somewhere special.
@end
--------------------------------------------------------------------
pstnproxy hooks
--------------------------------------------------------------------
DstNumber = string() "typically user-part of Request-URI"
Request = #request{}
Origin = #siporigin{}
THandler = term() "server transaction handler"
Relay = {relay, DstURI}
Response = {response, Status, Reason, ExtraHeaders}
pstnproxy, and no destination is found using
local:lookuppstn(), this function is called. The return
values have the following meaning :
undefined - proceed with default behavior nomatch - there
'404 Not Found' ignore - pstnproxy should do nothing
further (this function must generate a final response)
Response - send a response Relay - send Request to DstURI
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Request = #request{}
THandler = term() "server transaction handle"
@doc
@end
--------------------------------------------------------------------
Returns: pstn_ctx record()
--------------------------------------------------------------------
{ok, AllowedMethods}
Request = #request{}
AllowedMethods = [string()]
@doc Return list of allowed SIP methods. Must be upper-cased.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Request = #request{}
@doc Decide if pstnproxy should proxy a request, or reject it
with a '403 Forbidden'. Return 'undefined' for default
processing.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Request = #request{}
THandler = term() "server transaction handle"
YxaPeerAuth = true | false
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
outgoingproxy hooks
--------------------------------------------------------------------
@spec (Origin, Request, Dst) -> term()
@doc Check if 'outgoingproxy' should challenge a request that
it has determined it should relay, or if it should proxy
the request without authorization instead.
@end
--------------------------------------------------------------------
eventserver hooks
--------------------------------------------------------------------
{ok, PackageModule} |
undefined
Request = #request{}
YxaCtx = #yxa_ctx{}
PackageModule = atom()
@doc Decide which event package should handle a request
(SUBSCRIBE or PUBLISH) in the eventserver. You can use
this to make only certain SUBSCRIBE/PUBLISH requests go
to a custom event package. Remember to make
get_all_event_packages return any additions too.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec () ->
{ok, PackageDefs}
PackageDefs = [{Package, Module}]
Package = string()
Module = atom()
@doc Get list of all event packages. Duplicate Package is
allowed (and has a purpose, if you want to have more than
get_event_package_module/3 above).
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Type, User, Location) -> term()
@doc
@end
--------------------------------------------------------------------
sippipe hooks
--------------------------------------------------------------------
term() "result of sipppipe:start/5"
Request = #request{}
AppData = [term()] "application specific data passed to the start_sippipe/4 function in your 'local' module."
incomingproxy, outgoingproxy or pstnproxy. This is a very
suitable place to for example add/delete headers.
@see sippipe:start/5.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
action.
undefined |
{huntstop, Status, Reason} |
Request = #request{}
Response = #response{} | {Status, Reason}
Status = integer() "SIP status code"
Reason = string() "SIP reason phrase"
called. Depending on the return value of this function,
make sippipe stop processing and instruct the server
transaction to send a response (Status, Reason). 'next'
@end
--------------------------------------------------------------------
cpl_db hooks
--------------------------------------------------------------------
@spec (User) -> true | false
User = string()
@doc determine if a cpl script has been loaded for the user
User
@see cpl_db:user_has_cpl_script/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User, Direction) -> true | false
User = string()
Direction = incoming | outgoing
@doc determine if a cpl script has been loaded for the user
User
@see cpl_db:user_has_cpl_script/1.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (User) ->
User = string()
@doc get the cpl script graph for a certain user
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
See cpl/README
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (LogName, Comment, User, Request) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (LogName) -> term()
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Mail, User) -> term()
@doc
@end
--------------------------------------------------------------------
transaction layer hooks
--------------------------------------------------------------------
@spec (Request, Dst, Branch, Timeout) ->
Pid |
{error, Reason}
Request = #request{}
Branch = string()
Pid = pid() "started client transaction handler"
Reason = string()
@doc Start a client transaction, possibly after altering the
request to be sent.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
undefined |
ignore |
Request = #request{}
YxaCtx = #yxa_ctx{}
@doc This function gets called when the transaction layer has
decided that a new request has arrived, and figured it
transaction user). Depending on what this function
be called at all, called with the parameters unchanged or
called with a modified set of parameters. Note : DON'T
ALTER THE URI OF INVITE REQUESTS HERE! If you do, the
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
undefined |
ignore |
Response = #response{}
YxaCtx = #yxa_ctx{}
@doc This function gets called when the transaction layer has
decided that a response not assoicated with a running
client transaction has arrived. Such responses should be
user). Depending on what this function returns, the
at all, called with the parameters unchanged or called
with a modified set of parameters.
@end
--------------------------------------------------------------------
transport layer hooks
--------------------------------------------------------------------
true | false | undefined
Socket = term() "the socket"
Dir = in | out "direction of connection"
Proto = tcp | tcp6 | tls | tls6
Host = string() "IP address or hostname of remote end"
Port = integer()
Subject = term() | undefined "SSL socket Subject information (if SSL socket)"
@doc Verify a socket. Return 'true' for acceptable, 'false' for
NOT acceptable and 'undefined' to do default checks.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Proto = tcp | tcp6 | udp | udp6
@doc If a destination (proto:host:port) is not TLS it might
When we require a TLS-protected destination, this hook
lets you indicate that a particular destination is to be
considered secure at the transport layer.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
Names = [string()] "list of names for the certificate that the upper layer is willing to accept"
valid for a SSL certificate presented by a host. If, for
example, the host p1.example.org returns a certificate
with the subjectAltNames, Names might be ["example.org"]
certificate.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Dst) ->
{ok, Entry} |
{ok, blacklisted} |
{ok, whitelisted} |
undefined
Proto = tcp | tcp6 | udp | udp6 | tls | tls6 | atom()
Port = integer()
Entry = #blacklist_entry{}
@doc Check if a destination is blacklisted/whitelisted. Return
'undefined' for default processing.
@see sipsocket_blacklist:lookup_sipsocket_blacklist/1.
@end
--------------------------------------------------------------------
configuration hooks
--------------------------------------------------------------------
{error, Msg}
Key = atom()
Value = term()
Src = atom() "config backend module that found this configuration parameter"
Msg = string()
@doc Check a local configuration parameter. Local parameters
are local_*.
@end
--------------------------------------------------------------------
We have to do this with try/catch instead of ?CHECK_EXPORTED since
this function is needed before 'local' has been initialized
the local module did not export check_config_type/3
--------------------------------------------------------------------
@spec (Key, Value) -> true | false
Key = atom()
Value = term()
@doc Check if it is possible to change a local configuration
parameter with a soft reconfiguration (true), or if a
complete restart of the application is necessary (false).
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@spec (Key, Value, Mode) ->
ok | {error, Reason}
Key = atom()
Value = term()
Mode = soft | hard
Reason = string()
@doc Perform any necessary actions when a configuration value
changes, like perhaps notifying a gen_server or similar.
@end
--------------------------------------------------------------------
We have to do this with try/catch instead of ?CHECK_EXPORTED since
this function is needed before 'local' has been initialized
the local module did not export config_change_action/3
sipdialog hooks
--------------------------------------------------------------------
{ok, Dialog}
Caller = term() "who is calling us?"
Request = #request{} "received request that causes us to create a dialog"
ToTag = string() "the To-tag our server transaction for this request has generated"
Contact = string() "our Contact header value"
Dialog = #dialog{}
@doc Create a dialog record out of a received request and some
other parameters.
@see sipdialog:create_dialog_state_uas/3.
@end
-------------------------------------------------------------------- | @author < >
different parts of the various YXA applications .
@since 03 Jan 2006 by < >
-module(local).
-export([init/0
]).
-export([
url2mnesia_userlist/1,
canonify_user/1,
canonify_addresses/1
]).
-export([
lookup_homedomain_request/2,
lookup_remote_request/2,
lookupregexproute/1,
lookupuser/1,
lookupuser_gruu/2,
lookupuser_locations/2,
lookup_url_to_locations/1,
lookup_url_to_addresses/2,
lookup_addresses_to_users/1,
lookup_address_to_users/1,
lookupappserver/1,
lookupdefault/1,
lookuppotn/1,
lookupnumber/1,
lookupenum/1,
lookuppstn/1,
isours/1,
format_number_for_remote_party_id/3,
get_remote_party_name/2,
get_remote_party_number/4,
rewrite_potn_to_e164/1,
is_request_to_this_proxy/1,
remove_unsuitable_locations/2
]).
-export([
prioritize_locations/2,
homedomain/1,
get_locations_for_users/1,
get_user_with_contact/1,
get_locations_with_contact/1,
gruu_make_url/4,
is_gruu_url/1
]).
-export([
get_user_verified/2,
get_user_verified_proxy/2,
can_use_address/2,
can_use_address_detail/2,
can_register/2,
is_allowed_pstn_dst/4,
canonify_authusername/2
]).
-export([
get_addresses_for_user/1,
get_addresses_for_users/1,
get_users_for_address_of_record/1,
get_users_for_addresses_of_record/1,
get_users_for_url/1,
get_user_with_address/1,
get_classes_for_user/1,
get_password_for_user/1,
get_telephonenumber_for_user/1,
get_forwards_for_users/1,
sipuserdb_backend_override/3,
sipuserdb_mysql_make_sql_statement/2
]).
-export([
incomingproxy_challenge_before_relay/3,
incomingproxy_request_homedomain_event/2
]).
-export([
pstnproxy_route_pstn_not_e164/3,
pstnproxy_auth_and_tag/4,
pstnproxy_allowed_methods/2,
pstnproxy_allowed_proxy_request/2,
pstnproxy_verify_from/4,
pstnproxy_number_based_routing/4,
pstnproxy_lookup_action/2
]).
-export([
outgoingproxy_challenge_before_relay/3
]).
-export([
get_event_package_module/3,
get_all_event_packages/0,
eventserver_locationdb_action/3
]).
-export([
start_sippipe/4,
sippipe_received_response/3
]).
-export([
user_has_cpl_script/1,
user_has_cpl_script/2,
get_cpl_for_user/1
]).
-export([
start_client_transaction/4,
new_request/3,
new_response/3
]).
-export([
is_acceptable_socket/7,
is_tls_equivalent/3,
get_valid_altnames/3,
lookup_sipsocket_blacklist/1
]).
-export([
cpl_mail/2,
cpl_log/4,
cpl_is_log_dest/1
]).
-export([
check_config_type/3,
config_is_soft_reloadable/2,
config_change_action/3
]).
-export([
create_dialog_state_uas/4
]).
-include("siprecords.hrl").
-include("sipsocket.hrl").
-include("pstnproxy.hrl").
Macros
-define(LOCAL_ETS_TABLE_NAME, yxa_hooks).
-define(CHECK_EXPORTED(LocalMacroKey, LocalMacroIfSo, LocalMacroOtherwise),
case ets:member(?LOCAL_ETS_TABLE_NAME, LocalMacroKey) of
true ->
LocalMacroIfSo;
false ->
LocalMacroOtherwise
end).
-define(SIPPIPE_TIMEOUT, 900).
init() ->
ets:new(?LOCAL_ETS_TABLE_NAME, [named_table, set]),
Exports = ?MODULE:module_info(exports),
MyLocalExports = ?LOCAL_MODULE:module_info(exports),
by the ? LOCAL_MODULE function . The LOCAL_MODULE define is provided at compile
the YXA ' configure ' script .
Fun = fun({init, 0}) ->
?LOCAL_MODULE:init(),
[];
({module_info, _A}) ->
[];
({F, A}) ->
case lists:member({F, A}, Exports) of
true ->
ets:insert(?LOCAL_ETS_TABLE_NAME, {{F, A}, 1}),
F;
false ->
[]
end
end,
[Fun(V) || V <- MyLocalExports],
{ok, Count, Descr} = init_get_overridden(),
logger:log(debug, "Local: Found ~p overriding functions in module '~p' : ~s",
[Count, ?LOCAL_MODULE, Descr]),
ok.
init_get_overridden() ->
Overridden = ets:tab2list(?LOCAL_ETS_TABLE_NAME),
{ok, length(Overridden), format_overridden(Overridden, [])}.
format_overridden([{{F, A}, _Foo} | T], Res) ->
This = lists:concat([F, "/", A]),
format_overridden(T, [This | Res]);
format_overridden([], Res) ->
util:join(lists:reverse(Res), ", ").
url2mnesia_userlist(URL) when is_record(URL, sipurl) ->
?CHECK_EXPORTED({url2mnesia_userlist, 1},
?LOCAL_MODULE:url2mnesia_userlist(URL),
default_url2mnesia_userlist(URL)
).
URL = # sipurl { }
@doc Return " user@host " from URL .
@private
default_url2mnesia_userlist(URL) when is_list(URL#sipurl.user) ->
[URL#sipurl.user ++ "@" ++ URL#sipurl.host];
default_url2mnesia_userlist(_URL) ->
[].
from anywhere . Used for example from the
userdb - module . It should be possible to call users
canonify_user(User) when is_list(User) ->
?CHECK_EXPORTED({canonify_user, 1},
?LOCAL_MODULE:canonify_user(User),
default_canonify_user(User)
).
@private
default_canonify_user("sip:" ++ User) ->
"sip:" ++ User;
default_canonify_user(Fulluser) ->
case string:tokens(Fulluser, "@") of
[_User, _Host] ->
"sip:" ++ Fulluser;
[User] ->
"sip:" ++ User ++ "@" ++ sipauth:realm()
end.
it 's E.164 canonical representation . Used from some
canonify_addresses(In) when is_list(In) ->
?CHECK_EXPORTED({canonify_addresses, 1},
?LOCAL_MODULE:canonify_addresses(In),
default_canonify_addresses(In)
).
@private
default_canonify_addresses(In) when is_list(In) ->
default_canonify_addresses2(In, []).
default_canonify_addresses2(["tel:+" ++ _ = H | T], Res) ->
default_canonify_addresses2(T, [H | Res]);
default_canonify_addresses2(["+" ++ Num = H | T], Res) ->
case util:isnumeric(Num) of
true ->
This = "tel:+" ++ Num,
default_canonify_addresses2(T, [This | Res]);
false ->
default_canonify_addresses2(T, [H | Res])
end;
default_canonify_addresses2([H | T], Res) ->
case (catch rewrite_potn_to_e164(H)) of
"+" ++ _ = E164->
This = "tel:" ++ E164,
default_canonify_addresses2(T, [This | Res]);
_ ->
could not rewrite using rewrite_potn_to_e164/1 - leave unaltered
default_canonify_addresses2(T, [H | Res])
end;
default_canonify_addresses2([], Res) ->
lists:reverse(Res).
{ forward , Fwd } |
PDst = # sipurl { } | [ # sipdst { } ] | route
RDst = # sipurl { } | [ # sipdst { } ] | route
addressed to one of our users ( see local : lookupuser/1 ) .
lookup_homedomain_request(Request, Origin) when is_record(Request, request), is_record(Origin, siporigin) ->
?CHECK_EXPORTED({lookup_homedomain_request, 2},
?LOCAL_MODULE:lookup_homedomain_request(Request, Origin),
none
).
{ forward , Fwd } |
PDst = # sipurl { } | [ # sipdst { } ] | route
RDst = # sipurl { } | [ # sipdst { } ] | route
lookup_remote_request(Request, Origin) when is_record(Request, request), is_record(Origin, siporigin) ->
?CHECK_EXPORTED({lookup_remote_request, 2},
?LOCAL_MODULE:lookup_remote_request(Request, Origin),
none
).
is_request_to_this_proxy(Request) when is_record(Request, request) ->
?CHECK_EXPORTED({is_request_to_this_proxy, 1},
?LOCAL_MODULE:is_request_to_this_proxy(Request),
lookup:is_request_to_this_proxy(Request)
).
@see lookup : lookupregexproute/1
lookupregexproute(User) ->
?CHECK_EXPORTED({lookupregexproute, 1},
?LOCAL_MODULE:lookupregexproute(User),
lookup:lookupregexproute(User)
).
URL = # sipurl { }
@doc The main ' give me a set of locations for one of our users '
a request is for one of it 's homedomains .
lookupuser(URL) ->
?CHECK_EXPORTED({lookupuser, 1},
?LOCAL_MODULE:lookupuser(URL),
lookup:lookupuser(URL)
).
URL = # sipurl { } " Request - URI "
lookupuser_gruu(URL, GRUU) ->
?CHECK_EXPORTED({lookupuser_gruu, 2},
?LOCAL_MODULE:lookupuser_gruu(URL, GRUU),
lookup:lookupuser_gruu(URL, GRUU)
).
URL = # sipurl { } " the Request - URI "
out SIP locations if Request - URI was SIPS , unless this
lookupuser_locations(Users, URL) ->
?CHECK_EXPORTED({lookupuser_locations, 2},
?LOCAL_MODULE:lookupuser_locations(Users, URL),
lookup:lookupuser_locations(Users, URL)
).
remove_unsuitable_locations(URL, Locations) when is_record(URL, sipurl), is_list(Locations) ->
?CHECK_EXPORTED({remove_unsuitable_locations, 2},
?LOCAL_MODULE:remove_unsuitable_locations(URL, Locations),
lookup:remove_unsuitable_locations(URL, Locations)
).
@see lookup : lookup_url_to_locations/1 .
lookup_url_to_locations(URL) ->
?CHECK_EXPORTED({lookup_url_to_locations, 1},
?LOCAL_MODULE:lookup_url_to_locations(URL),
lookup:lookup_url_to_locations(URL)
).
lookup_url_to_addresses(Src, URL) ->
?CHECK_EXPORTED({lookup_url_to_addresses, 2},
?LOCAL_MODULE:lookup_url_to_addresses(Src, URL),
lookup:lookup_url_to_addresses(Src, URL)
).
lookup_addresses_to_users(Addresses) ->
?CHECK_EXPORTED({lookup_addresses_to_users, 1},
?LOCAL_MODULE:lookup_addresses_to_users(Addresses),
lookup:lookup_addresses_to_users(Addresses)
).
lookup_address_to_users(Address) ->
?CHECK_EXPORTED({lookup_address_to_users, 1},
?LOCAL_MODULE:lookup_address_to_users(Address),
lookup:lookup_address_to_users(Address)
).
lookupappserver(Key) ->
?CHECK_EXPORTED({lookupappserver, 1},
?LOCAL_MODULE:lookupappserver(Key),
lookup:lookupappserver(Key)
).
prioritize_locations(Key, Locations) ->
?CHECK_EXPORTED({prioritize_locations, 2},
?LOCAL_MODULE:prioritize_locations(Key, Locations),
siplocation:prioritize_locations(Locations)
).
lookupdefault(URL) ->
?CHECK_EXPORTED({lookupdefault, 1},
?LOCAL_MODULE:lookupdefault(URL),
lookup:lookupdefault(URL)
).
@see lookup : .
lookuppotn(Number) ->
?CHECK_EXPORTED({lookuppotn, 1},
?LOCAL_MODULE:lookuppotn(Number),
lookup:lookuppotn(Number)
).
lookupnumber(Number) ->
?CHECK_EXPORTED({lookupnumber, 1},
?LOCAL_MODULE:lookupnumber(Number),
lookup:lookupnumber(Number)
).
lookupenum(Number) ->
?CHECK_EXPORTED({lookupenum, 1},
?LOCAL_MODULE:lookupenum(Number),
lookup:lookupenum(Number)
).
lookuppstn(Number) ->
?CHECK_EXPORTED({lookuppstn, 1},
?LOCAL_MODULE:lookuppstn(Number),
lookup:lookuppstn(Number)
).
isours(URL) ->
?CHECK_EXPORTED({isours, 1},
?LOCAL_MODULE:isours(URL),
lookup:isours(URL)
).
homedomain(Domain) ->
?CHECK_EXPORTED({homedomain, 1},
?LOCAL_MODULE:homedomain(Domain),
lookup:homedomain(Domain)
).
URI = # sipurl { } " outgoing Request - URI "
@doc This function is used by the pstnproxy to provide a PSTN
gateway with usefull caller - id information . PSTN networks
gateway to PSTN might only handle E.164 numbers , while a
PBX might be expecting only a 4 - digit extension number ) .
@see lookup : get_remote_party_number/4 .
get_remote_party_number(User, Header, URI, DstHost) when is_list(User) ->
?CHECK_EXPORTED({get_remote_party_number, 4},
?LOCAL_MODULE:get_remote_party_number(User, Header, URI, DstHost),
lookup:get_remote_party_number(User, Header, URI, DstHost)
).
has found a number to be
format_number_for_remote_party_id(Number, Header, DstHost) when is_list(Number) ->
?CHECK_EXPORTED({format_number_for_remote_party_id, 3},
?LOCAL_MODULE:format_number_for_remote_party_id(Number, Header, DstHost),
lookup:format_number_for_remote_party_id(Number, Header, DstHost)
).
{ ok , } |
DisplayName = string ( )
do the actual lookup if we can rewrite Key into a E.164
get_remote_party_name(Key, DstHost) ->
?CHECK_EXPORTED({get_remote_party_name, 2},
?LOCAL_MODULE:get_remote_party_name(Key, DstHost),
case rewrite_potn_to_e164(Key) of
"+" ++ E164 ->
lookup:get_remote_party_name("+" ++ E164, DstHost);
_ -> none
end
).
rewrite_potn_to_e164(Key) ->
?CHECK_EXPORTED({rewrite_potn_to_e164, 1},
?LOCAL_MODULE:rewrite_potn_to_e164(Key),
lookup:rewrite_potn_to_e164(Key)
).
example in REGISTER . If there are multiple users with an
get_user_with_address(Address) ->
?CHECK_EXPORTED({get_user_with_address, 1},
?LOCAL_MODULE:get_user_with_address(Address),
sipuserdb:get_user_with_address(Address)
).
get_users_for_address_of_record(Address) ->
?CHECK_EXPORTED({get_users_for_address_of_record, 1},
?LOCAL_MODULE:get_users_for_address_of_record(Address),
sipuserdb:get_users_for_address_of_record(Address)
).
@see sipuserdb : get_users_for_addresses_of_record/1 .
get_users_for_addresses_of_record(Addresses) ->
?CHECK_EXPORTED({get_users_for_addresses_of_record, 1},
?LOCAL_MODULE:get_users_for_addresses_of_record(Addresses),
sipuserdb:get_users_for_addresses_of_record(Addresses)
).
get_addresses_for_user(User) ->
?CHECK_EXPORTED({get_addresses_for_user, 1},
?LOCAL_MODULE:get_addresses_for_user(User),
sipuserdb:get_addresses_for_user(User)
).
get_addresses_for_users(Users) ->
?CHECK_EXPORTED({get_addresses_for_users, 1},
?LOCAL_MODULE:get_addresses_for_users(Users),
sipuserdb:get_addresses_for_users(Users)
).
get_users_for_url(URL) ->
?CHECK_EXPORTED({get_users_for_url, 1},
?LOCAL_MODULE:get_users_for_url(URL),
sipuserdb:get_users_for_url(URL)
).
get_password_for_user(User) ->
?CHECK_EXPORTED({get_password_for_user, 1},
?LOCAL_MODULE:get_password_for_user(User),
sipuserdb:get_password_for_user(User)
).
@see sipuserdb : .
get_classes_for_user(User) ->
?CHECK_EXPORTED({get_classes_for_user, 1},
?LOCAL_MODULE:get_classes_for_user(User),
sipuserdb:get_classes_for_user(User)
).
get_telephonenumber_for_user(User) ->
?CHECK_EXPORTED({get_telephonenumber_for_user, 1},
?LOCAL_MODULE:get_telephonenumber_for_user(User),
sipuserdb:get_telephonenumber_for_user(User)
).
@see sipuserdb : get_forwards_for_users/1 .
get_forwards_for_users(Users) ->
?CHECK_EXPORTED({get_forwards_for_user, 1},
?LOCAL_MODULE:get_forwards_for_users(Users),
sipuserdb:get_forwards_for_users(Users)
).
@spec ( Module , Function , ) - > { ok , Res } | undefined
= term ( ) " arguments to function "
@doc to override a specific sipuserdb backend function . If
sipuserdb_backend_override(Module, Function, Args) ->
?CHECK_EXPORTED({sipuserdb_backend_override, 3},
?LOCAL_MODULE:sipuserdb_backend_override(Module, Function, Args),
undefined
).
@spec ( CfgKey , ) - >
= term ( ) " ) to use in SQL query "
: You have to mysql : quote ( ) everything you use from !
sipuserdb_mysql_make_sql_statement(CfgKey, Args) ->
?CHECK_EXPORTED({sipuserdb_mysql_make_sql_statement, 2},
?LOCAL_MODULE:sipuserdb_mysql_make_sql_statement(CfgKey, Args),
undefined
).
get_locations_for_users(Users) ->
?CHECK_EXPORTED({get_locations_for_users, 1},
?LOCAL_MODULE:get_locations_for_users(Users),
siplocation:get_locations_for_users(Users)
).
get_user_with_contact(URI) ->
?CHECK_EXPORTED({get_user_with_contact, 1},
?LOCAL_MODULE:get_user_with_contact(URI),
siplocation:get_user_with_contact(URI)
).
get_locations_with_contact(URI) ->
?CHECK_EXPORTED({get_locations_with_contact, 1},
?LOCAL_MODULE:get_locations_with_contact(URI),
siplocation:get_locations_with_contact(URI)
).
@spec ( User , InstanceId , GRUU , To ) - >
URL = # sipurl { }
gruu_make_url(User, InstanceId, GRUU, To) ->
?CHECK_EXPORTED({gruu_make_url, 4},
?LOCAL_MODULE:gruu_make_url(User, InstanceId, GRUU, To),
undefined
).
@see gruu : is_gruu_url/1 .
is_gruu_url(URL) ->
?CHECK_EXPORTED({is_gruu_url, 1},
?LOCAL_MODULE:is_gruu_url(URL),
gruu:is_gruu_url(URL)
).
AAA hooks
get_user_verified(Header, Method) ->
?CHECK_EXPORTED({get_user_verified, 2},
?LOCAL_MODULE:get_user_verified(Header, Method),
sipauth:get_user_verified(Header, Method)
).
get_user_verified_proxy(Header, Method) ->
?CHECK_EXPORTED({get_user_verified_proxy, 2},
?LOCAL_MODULE:get_user_verified_proxy(Header, Method),
sipauth:get_user_verified_proxy(Header, Method)
).
URL = # sipurl { }
can_use_address(User, URL) when is_list(User), is_record(URL, sipurl) ->
?CHECK_EXPORTED({can_use_address, 2},
?LOCAL_MODULE:can_use_address(User, URL),
sipauth:can_use_address(User, URL)
).
{ Verdict , Reason }
URL = # sipurl { }
can_use_address_detail(User, URL) when is_list(User), is_record(URL, sipurl) ->
?CHECK_EXPORTED({can_use_address_detail, 2},
?LOCAL_MODULE:can_use_address_detail(User, URL),
sipauth:can_use_address_detail(User, URL)
).
{ { Verdict , Reason } , User } |
# sipurl { }
@doc Check if a REGISTER message authenticates OK etc . See
sipauth module for more information .
@see sipauth : .
can_register(Header, ToURL) when is_record(Header, keylist), is_record(ToURL, sipurl) ->
?CHECK_EXPORTED({can_register, 2},
?LOCAL_MODULE:can_register(Header, ToURL),
sipauth:can_register(Header, ToURL)
).
@spec ( User , ToNumber , Header , Class ) - > bool ( )
@see sipauth : is_allowed_pstn_dst/4 .
is_allowed_pstn_dst(User, ToNumber, Header, Class) ->
?CHECK_EXPORTED({is_allowed_pstn_dst, 4},
?LOCAL_MODULE:is_allowed_pstn_dst(User, ToNumber, Header, Class),
sipauth:is_allowed_pstn_dst(User, ToNumber, Header, Class)
).
This is needed if your user database allows more than one
canonify_authusername(Username, Header) when is_list(Username), is_record(Header, keylist) ->
?CHECK_EXPORTED({canonify_authusername, 2},
?LOCAL_MODULE:canonify_authusername(Username, Header),
undefined
).
incomingproxy_challenge_before_relay(Origin, Request, Dst) when is_record(Origin, siporigin),
is_record(Request, request) ->
?CHECK_EXPORTED({incomingproxy_challenge_before_relay, 3},
?LOCAL_MODULE:incomingproxy_challenge_before_relay(Origin, Request, Dst),
true
).
incomingproxy_request_homedomain_event(Request, Origin) when is_record(Request, request),
is_record(Origin, siporigin) ->
?CHECK_EXPORTED({incomingproxy_request_homedomain_event, 2},
?LOCAL_MODULE:incomingproxy_request_homedomain_event(Request, Origin),
undefined
).
@spec ( DstNumber , Request , PstnCtx ) - >
undefined | nomatch | ignore | Relay
@doc When a request destined for PSTN is received by the
is no destination for DstNumber , reject request with a
pstnproxy_route_pstn_not_e164(DstNumber, Request, PstnCtx) ->
?CHECK_EXPORTED({pstnproxy_route_pstn_not_e164, 3},
?LOCAL_MODULE:pstnproxy_route_pstn_not_e164(DstNumber, Request, PstnCtx),
undefined
).
@spec ( Request , Origin , THandler , PstnCtx ) - > term ( )
Origin = # siporigin { }
PstnCtx = # pstn_ctx { }
pstnproxy_auth_and_tag(Request, Origin, THandler, PstnCtx) when is_record(Request, request),
is_record(Origin, siporigin),
is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_auth_and_tag, 4},
?LOCAL_MODULE:pstnproxy_auth_and_tag(Request, Origin, THandler, PstnCtx),
PstnCtx
).
@spec ( Request , PstnCtx ) - >
PstnCtx = # pstn_ctx { }
pstnproxy_allowed_methods(Request, PstnCtx) when is_record(Request, request),
is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_allowed_methods, 2},
?LOCAL_MODULE:pstnproxy_allowed_methods(Request, PstnCtx),
yxa_config:get_env(allowed_request_methods)
).
@spec ( Request , PstnCtx ) - > true | false | undefined
PstnCtx = # pstn_ctx { }
pstnproxy_allowed_proxy_request(Request, PstnCtx) when is_record(Request, request),
is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_allowed_proxy_request, 2},
?LOCAL_MODULE:pstnproxy_allowed_proxy_request(Request, PstnCtx),
undefined
).
@spec ( Request , THandler , YXAPeerAuth , PstnCtx ) - > term ( )
PstnCtx = # pstn_ctx { }
pstnproxy_verify_from(Request, THandler, YXAPeerAuth, PstnCtx) when is_record(Request, request),
is_boolean(YXAPeerAuth),
is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_verify_from, 4},
?LOCAL_MODULE:pstnproxy_verify_from(Request, THandler, YXAPeerAuth, PstnCtx),
undefined
).
@spec ( Request , THandler , LogTag , PstnCtx ) - > term ( )
pstnproxy_number_based_routing(Request, THandler, LogTag, PstnCtx) ->
?CHECK_EXPORTED({pstnproxy_number_based_routing, 4},
?LOCAL_MODULE:pstnproxy_number_based_routing(Request, THandler, LogTag, PstnCtx),
undefined
).
@spec ( Request , PstnCtx ) - > term ( )
pstnproxy_lookup_action(Request, PstnCtx) when is_record(Request, request), is_record(PstnCtx, pstn_ctx) ->
?CHECK_EXPORTED({pstnproxy_lookup_action, 2},
?LOCAL_MODULE:pstnproxy_lookup_action(Request, PstnCtx),
undefined
).
outgoingproxy_challenge_before_relay(Origin, Request, Dst) when is_record(Origin, siporigin),
is_record(Request, request) ->
?CHECK_EXPORTED({outgoingproxy_challenge_before_relay, 3},
?LOCAL_MODULE:outgoingproxy_challenge_before_relay(Origin, Request, Dst),
true
).
@spec ( EventPackage , Request , ) - >
EventPackage = string ( ) " \"presence\ " or \"ua - config\ " etc . "
get_event_package_module(EventPackage, Request, YxaCtx) when is_list(EventPackage), is_record(Request, request),
is_record(YxaCtx, yxa_ctx) ->
?CHECK_EXPORTED({get_event_package_module, 3},
?LOCAL_MODULE:get_event_package_module(EventPackage, Request, YxaCtx),
undefined
).
one possible Module for a Package ( decided using
get_all_event_packages() ->
?CHECK_EXPORTED({get_all_event_packages, 0},
?LOCAL_MODULE:get_all_event_packages(),
yxa_config:get_env(eventserver_package_handlers)
).
eventserver_locationdb_action(Type, User, Location) when is_atom(Type), is_list(User) ->
?CHECK_EXPORTED({eventserver_locationdb_action, 3},
?LOCAL_MODULE:eventserver_locationdb_action(Type, User, Location),
undefined
).
@spec ( Request , , Dst , AppData ) - >
YxaCtx = # yxa_ctx { }
Dst = # sipurl { } | route | [ # sipdst { } ]
@doc Start a sippipe for one of the YXA applications
start_sippipe(Request, YxaCtx, Dst, AppData) when is_record(Request, request), is_record(YxaCtx, yxa_ctx),
is_list(AppData) ->
?CHECK_EXPORTED({start_sippipe, 4},
?LOCAL_MODULE:start_sippipe(Request, YxaCtx, Dst, AppData),
begin
THandler = YxaCtx#yxa_ctx.thandler,
ClientTransaction = none,
sippipe:start(THandler, ClientTransaction, Request, Dst, ?SIPPIPE_TIMEOUT)
end
).
@spec ( Request , Response , DstList ) - >
{ next , NewDstList }
DstList = [ # sipdst { } ]
= [ # sipdst { } ]
@doc When receives a final response , this function is
will behave differently . ' undefined ' means
will fall back to it 's default ' huntstop ' will
will tell to try the next destination in
NewDstList ( possibly altered version of DstList ) .
sippipe_received_response(Request, Response, DstList) when is_record(Request, request),
is_record(Response, response) ->
?CHECK_EXPORTED({sippipe_received_response, 3},
?LOCAL_MODULE:sippipe_received_response(Request, Response, DstList),
undefined
);
sippipe_received_response(Request, {Status, Reason}, DstList) when is_record(Request, request),
is_integer(Status), is_list(Reason) ->
?CHECK_EXPORTED({sippipe_received_response, 3},
?LOCAL_MODULE:sippipe_received_response(Request, {Status, Reason}, DstList),
undefined
).
user_has_cpl_script(User) ->
?CHECK_EXPORTED({user_has_cpl_script, 1},
?LOCAL_MODULE:user_has_cpl_script(User),
cpl_db:user_has_cpl_script(User)
).
user_has_cpl_script(User, Direction) ->
?CHECK_EXPORTED({user_has_cpl_script, 2},
?LOCAL_MODULE:user_has_cpl_script(User, Direction),
cpl_db:user_has_cpl_script(User, Direction)
).
nomatch | { ok , CPLGraph }
CPLGraph = term ( ) " a cpl graph for use in interpret_cpl : process_cpl_script ( ... ) "
@see cpl_db : get_cpl_for_user/1 .
get_cpl_for_user(User) ->
?CHECK_EXPORTED({get_cpl_for_user, 1},
?LOCAL_MODULE:get_cpl_for_user(User),
cpl_db:get_cpl_for_user(User)
).
cpl_log(LogName, Comment, User, Request) ->
?CHECK_EXPORTED({cpl_log, 4},
?LOCAL_MODULE:cpl_log(LogName, Comment, User, Request),
undefined
).
cpl_is_log_dest(LogName) ->
?CHECK_EXPORTED({cpl_is_log_dest, 1},
?LOCAL_MODULE:cpl_is_log_dest(LogName),
undefined
).
cpl_mail(Mail, User) ->
?CHECK_EXPORTED({cpl_mail, 2},
?LOCAL_MODULE:cpl_mail(Mail, User),
undefined
).
Dst = # sipdst { } " the destination for this client transaction "
Timeout = integer ( ) " timeout for INVITE transactions "
@see transactionlayer : .
start_client_transaction(Request, Dst, Branch, Timeout) when is_record(Request, request), is_record(Dst, sipdst),
is_list(Branch), is_integer(Timeout) ->
?CHECK_EXPORTED({start_client_transaction, 4},
?LOCAL_MODULE:start_client_transaction(Request, Dst, Branch, Timeout),
transactionlayer:start_client_transaction(Request, Dst, Branch, Timeout, self())
).
@spec ( AppModule , Request , ) - >
{ modified , NewAppModule , NewRequest , NewOrigin , NewLogStr }
AppModule = atom ( ) " YXA application module the transaction layer thought this request should be passed to "
should be passed to the YXA application ( proxy core/
returns , the AppModule : request/2 function will either not
of non-2xx responses will be disqualified by the
server transaction since the URI of the ACK does n't match
the URI of the original INVITE ( since you changed it ) .
new_request(AppModule, Request, YxaCtx) ->
?CHECK_EXPORTED({new_request, 3},
?LOCAL_MODULE:new_request(AppModule, Request, YxaCtx),
undefined
).
@spec ( AppModule , Response , ) - >
{ modified , NewAppModule , NewResponse , NewOrigin , NewLogStr }
AppModule = atom ( ) " YXA application module the transaction layer thought this request should be passed to "
passed to the YXA application ( proxy core / transaction
AppModule : response/2 function will either not be called
new_response(AppModule, Response, YxaCtx) ->
?CHECK_EXPORTED({new_response, 3},
?LOCAL_MODULE:new_response(AppModule, Response, YxaCtx),
undefined
).
@spec ( Socket , , Proto , Host , Port , Module , Subject ) - >
Module = atom ( ) " SIP - socket module name ( sipsocket_tcp ) "
is_acceptable_socket(Socket, Dir, Proto, Host, Port, Module, Subject) ->
?CHECK_EXPORTED({is_acceptable_socket, 7},
?LOCAL_MODULE:is_acceptable_socket(Socket, Dir, Proto, Host, Port, Module, Subject),
undefined
).
@spec ( Proto , Host , Port ) - > true | false | undefined
still be protected by an equivalence to TLS ( like IPsec ) .
is_tls_equivalent(Proto, Host, Port) ->
?CHECK_EXPORTED({is_tls_equivalent, 3},
?LOCAL_MODULE:is_tls_equivalent(Proto, Host, Port),
undefined
).
@spec ( Names , Subject , AltNames ) - >
NewAltNames
Subject = term ( ) " ssl : ( ) subject data "
AltNames = [ string ( ) ] " subjectAltName : s in cert "
NewAltNames = [ string ( ) ]
@doc that lets you manipulate what names are considered
since a user tried to reach sip: , and
AltNames might be [ " p1.example.org " ] . In this case , you
must add " example.org " to AltNames , to allow the
get_valid_altnames(Names, Subject, AltNames) ->
?CHECK_EXPORTED({get_valid_altnames, 3},
?LOCAL_MODULE:get_valid_altnames(Names, Subject, AltNames),
AltNames
).
Dst = { Proto , Addr , Port }
= string ( ) " typically IPv4 / IPv6 address "
lookup_sipsocket_blacklist(Dst) ->
?CHECK_EXPORTED({lookup_sipsocket_blacklist, 1},
?LOCAL_MODULE:lookup_sipsocket_blacklist(Dst),
sipsocket_blacklist:lookup_sipsocket_blacklist(Dst)
).
@spec ( Key , Value , ) - >
{ ok , } |
= term ( )
check_config_type(Key, Value, Src) ->
try ?LOCAL_MODULE:check_config_type(Key, Value, Src) of
Res ->
Res
catch
error: undef ->
{ok, Value}
end.
config_is_soft_reloadable(Key, Value) ->
?CHECK_EXPORTED({config_is_soft_reloadable, 2},
?LOCAL_MODULE:config_is_soft_reloadable(Key, Value),
true
).
config_change_action(Key, Value, Mode) ->
try ?LOCAL_MODULE:config_change_action(Key, Value, Mode) of
Res ->
Res
catch
error: undef ->
ok
end.
@spec ( Caller , Request , ToTag , Contact ) - >
create_dialog_state_uas(Caller, Request, ToTag, Contact) ->
?CHECK_EXPORTED({create_dialog_state_uas, 4},
?LOCAL_MODULE:create_dialog_state_uas(Caller, Request, ToTag, Contact),
sipdialog:create_dialog_state_uas(Request, ToTag, Contact)
).
|
6525e2781d3f487aea3a5870a3ce3c062ae3dc080823bc51301198152b357db0 | dustin/mqtt-hs | Topic.hs | |
Module : Network . .
Description : MQTT Topic types and utilities .
Copyright : ( c ) , 2019
License :
Stability : experimental
Topic and topic related utiilities .
Module : Network.MQTT.Topic.
Description : MQTT Topic types and utilities.
Copyright : (c) Dustin Sallings, 2019
License : BSD3
Maintainer :
Stability : experimental
Topic and topic related utiilities.
-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
module Network.MQTT.Topic (
Filter, unFilter, Topic, unTopic, match,
mkFilter, mkTopic, split, toFilter
) where
import Data.String (IsString (..))
import Data.Text (Text, isPrefixOf, splitOn)
class Splittable a where
-- | split separates a `Filter` or `Topic` into its `/`-separated components.
split :: a -> [a]
-- | An MQTT topic.
newtype Topic = Topic { unTopic :: Text } deriving (Show, Ord, Eq, IsString)
instance Splittable Topic where
split (Topic t) = Topic <$> splitOn "/" t
instance Semigroup Topic where
(Topic a) <> (Topic b) = Topic (a <> "/" <> b)
-- | mkTopic creates a topic from a text representation of a valid filter.
mkTopic :: Text -> Maybe Topic
mkTopic "" = Nothing
mkTopic t = Topic <$> validate (splitOn "/" t)
where
validate ("#":_) = Nothing
validate ("+":_) = Nothing
validate [] = Just t
validate (_:xs) = validate xs
-- | An MQTT topic filter.
newtype Filter = Filter { unFilter :: Text } deriving (Show, Ord, Eq, IsString)
instance Splittable Filter where
split (Filter f) = Filter <$> splitOn "/" f
instance Semigroup Filter where
(Filter a) <> (Filter b) = Filter (a <> "/" <> b)
-- | mkFilter creates a filter from a text representation of a valid filter.
mkFilter :: Text -> Maybe Filter
mkFilter "" = Nothing
mkFilter t = Filter <$> validate (splitOn "/" t)
where
validate ["#"] = Just t
validate ("#":_) = Nothing
validate [] = Just t
validate (_:xs) = validate xs
-- | match returns true iff the given pattern can be matched by the
-- specified Topic as defined in the
< -open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718107 MQTT 3.1.1 specification > .
match :: Filter -> Topic -> Bool
match (Filter pat) (Topic top) = cmp (splitOn "/" pat) (splitOn "/" top)
where
cmp [] [] = True
cmp [] _ = False
cmp ["#"] [] = True
cmp _ [] = False
cmp ["#"] (t:_) = not $ "$" `isPrefixOf` t
cmp (p:ps) (t:ts)
| p == t = cmp ps ts
| p == "+" && not ("$" `isPrefixOf` t) = cmp ps ts
| otherwise = False
-- | Convert a 'Topic' to a 'Filter' as all 'Topic's are valid 'Filter's
toFilter :: Topic -> Filter
toFilter (Topic t) = Filter t
| null | https://raw.githubusercontent.com/dustin/mqtt-hs/0ed3802c017487e63bde0a0512ee7b9f585414e3/src/Network/MQTT/Topic.hs | haskell | # LANGUAGE OverloadedStrings #
| split separates a `Filter` or `Topic` into its `/`-separated components.
| An MQTT topic.
| mkTopic creates a topic from a text representation of a valid filter.
| An MQTT topic filter.
| mkFilter creates a filter from a text representation of a valid filter.
| match returns true iff the given pattern can be matched by the
specified Topic as defined in the
| Convert a 'Topic' to a 'Filter' as all 'Topic's are valid 'Filter's | |
Module : Network . .
Description : MQTT Topic types and utilities .
Copyright : ( c ) , 2019
License :
Stability : experimental
Topic and topic related utiilities .
Module : Network.MQTT.Topic.
Description : MQTT Topic types and utilities.
Copyright : (c) Dustin Sallings, 2019
License : BSD3
Maintainer :
Stability : experimental
Topic and topic related utiilities.
-}
# LANGUAGE GeneralizedNewtypeDeriving #
module Network.MQTT.Topic (
Filter, unFilter, Topic, unTopic, match,
mkFilter, mkTopic, split, toFilter
) where
import Data.String (IsString (..))
import Data.Text (Text, isPrefixOf, splitOn)
class Splittable a where
split :: a -> [a]
newtype Topic = Topic { unTopic :: Text } deriving (Show, Ord, Eq, IsString)
instance Splittable Topic where
split (Topic t) = Topic <$> splitOn "/" t
instance Semigroup Topic where
(Topic a) <> (Topic b) = Topic (a <> "/" <> b)
mkTopic :: Text -> Maybe Topic
mkTopic "" = Nothing
mkTopic t = Topic <$> validate (splitOn "/" t)
where
validate ("#":_) = Nothing
validate ("+":_) = Nothing
validate [] = Just t
validate (_:xs) = validate xs
newtype Filter = Filter { unFilter :: Text } deriving (Show, Ord, Eq, IsString)
instance Splittable Filter where
split (Filter f) = Filter <$> splitOn "/" f
instance Semigroup Filter where
(Filter a) <> (Filter b) = Filter (a <> "/" <> b)
mkFilter :: Text -> Maybe Filter
mkFilter "" = Nothing
mkFilter t = Filter <$> validate (splitOn "/" t)
where
validate ["#"] = Just t
validate ("#":_) = Nothing
validate [] = Just t
validate (_:xs) = validate xs
< -open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718107 MQTT 3.1.1 specification > .
match :: Filter -> Topic -> Bool
match (Filter pat) (Topic top) = cmp (splitOn "/" pat) (splitOn "/" top)
where
cmp [] [] = True
cmp [] _ = False
cmp ["#"] [] = True
cmp _ [] = False
cmp ["#"] (t:_) = not $ "$" `isPrefixOf` t
cmp (p:ps) (t:ts)
| p == t = cmp ps ts
| p == "+" && not ("$" `isPrefixOf` t) = cmp ps ts
| otherwise = False
toFilter :: Topic -> Filter
toFilter (Topic t) = Filter t
|
f0db2446238ffc0bf4e9be736e27f45d029e8b5a9bcbc5bb6f52b23d683ee217 | libguestfs/virt-v2v | input_vddk.mli | virt - v2v
* Copyright ( C ) 2009 - 2021 Red Hat Inc.
*
* 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. ,
* 51 Franklin Street , Fifth Floor , Boston , USA .
* Copyright (C) 2009-2021 Red Hat Inc.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
(** Input from vCenter or ESXi over VDDK *)
module VDDK : Input.INPUT
| null | https://raw.githubusercontent.com/libguestfs/virt-v2v/7691f8e853d21980aac3008237a55f6bc291581c/input/input_vddk.mli | ocaml | * Input from vCenter or ESXi over VDDK | virt - v2v
* Copyright ( C ) 2009 - 2021 Red Hat Inc.
*
* 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. ,
* 51 Franklin Street , Fifth Floor , Boston , USA .
* Copyright (C) 2009-2021 Red Hat Inc.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
module VDDK : Input.INPUT
|
fc7c33a6b812a9205c2b878494360ffb77e32d4e54b9f1291335c73907ead5f6 | jrclogic/SMCDEL | RussianCards.hs | # LANGUAGE FlexibleInstances #
module SMCDEL.Examples.RussianCards where
import Control.Monad (replicateM)
import Data.HasCacBDD hiding (Top,Bot)
import Data.List ((\\),delete,intersect,nub,sort)
import Data.Map.Strict (fromList)
import SMCDEL.Internal.Help (powerset)
import SMCDEL.Language
import SMCDEL.Other.Planning
import SMCDEL.Symbolic.S5
import qualified SMCDEL.Symbolic.K as K
rcPlayers :: [Agent]
rcPlayers = [alice,bob,carol]
rcNumOf :: Agent -> Int
rcNumOf "Alice" = 0
rcNumOf "Bob" = 1
rcNumOf "Carol" = 2
rcNumOf _ = error "Unknown Agent"
rcCards :: [Int]
rcCards = [0..6]
rcProps :: [Prp]
rcProps = [ P k | k <-[0..((length rcPlayers * length rcCards)-1)] ]
hasCard :: Agent -> Int -> Form
hasCard i n = PrpF (P (3 * n + rcNumOf i))
hasHand :: Agent -> [Int] -> Form
hasHand i ns = Conj $ map (i `hasCard`) ns
rcExplain :: Prp -> String
rcExplain (P k) = (rcPlayers !! i) ++ " has card " ++ show n where (n,i) = divMod k 3
allCardsGiven, allCardsUnique :: Form
allCardsGiven = Conj [ Disj [ i `hasCard` n | i <- rcPlayers ] | n <- rcCards ]
allCardsUnique = Conj [ Neg $ isDouble n | n <- rcCards ] where
isDouble n = Disj [ Conj [ x `hasCard` n, y `hasCard` n ] | x <- rcPlayers, y <- rcPlayers, x < y ]
distribute331 :: Form
distribute331 = Conj [ aliceAtLeastThree, bobAtLeastThree, carolAtLeastOne ] where
triples = [ [x, y, z] | x <- rcCards, y <- delete x rcCards, z <- rcCards \\ [x,y] ]
aliceAtLeastThree = Disj [ Conj (map (alice `hasCard`) t) | t <- triples ]
bobAtLeastThree = Disj [ Conj (map (bob `hasCard`) t) | t <- triples ]
carolAtLeastOne = Disj [ carol `hasCard` k | k<-[0..6] ]
rusSCN :: KnowScene
rusKNS :: KnowStruct
rusSCN@(rusKNS,_) = (KnS rcProps law [ (i, obs i) | i <- rcPlayers ], defaultDeal) where
law = boolBddOf $ Conj [ allCardsGiven, allCardsUnique, distribute331 ]
obs i = [ P (3 * k + rcNumOf i) | k<-[0..6] ]
defaultDeal = [P 0,P 3,P 6,P 10,P 13,P 16,P 20]
aAnnounce :: Form
aAnnounce = K alice $ Disj [ Conj (map (alice `hasCard`) hand) |
hand <- [ [0,1,2], [0,3,4], [0,5,6], [1,3,5], [2,4,6] ] ]
bAnnounce :: Form
bAnnounce = K bob (carol `hasCard` 6)
aKnowsBs, bKnowsAs, cIgnorant :: Form
aKnowsBs = Conj [ alice `Kw` (bob `hasCard` k) | k<-rcCards ]
bKnowsAs = Conj [ bob `Kw` (alice `hasCard` k) | k<-rcCards ]
cIgnorant = Conj $ concat [ [ Neg $ K carol $ alice `hasCard` i
, Neg $ K carol $ bob `hasCard` i ] | i<-rcCards ]
rcCheck :: Int -> Form
rcCheck 0 = aAnnounce
rcCheck 1 = PubAnnounce aAnnounce bKnowsAs
rcCheck 2 = PubAnnounce aAnnounce (Ck [alice,bob] bKnowsAs)
rcCheck 3 = PubAnnounce aAnnounce (K bob (PrpF (P 20)))
rcCheck 4 = PubAnnounce aAnnounce (Ck [alice,bob,carol] cIgnorant)
rcCheck 5 = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck [alice,bob] aKnowsBs))
rcCheck 6 = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck [alice,bob] bKnowsAs))
rcCheck _ = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck rcPlayers cIgnorant))
rcAllChecks :: Bool
rcAllChecks = evalViaBdd rusSCN (Conj (map rcCheck [0..7]))
checkSet :: [[Int]] -> Bool
checkSet set = all (evalViaBdd rusSCN) fs where
aliceSays = K alice (Disj [ Conj $ map (alice `hasCard`) h | h <- set ])
bobSays = K bob (carol `hasCard` 6)
fs = [ aliceSays
, PubAnnounce aliceSays bKnowsAs
, PubAnnounce aliceSays (Ck [alice,bob] bKnowsAs)
, PubAnnounce aliceSays (Ck [alice,bob,carol] cIgnorant)
, PubAnnounce aliceSays (PubAnnounce bobSays (Ck [alice,bob] $ Conj [aKnowsBs, bKnowsAs]))
, PubAnnounce aliceSays (PubAnnounce bobSays (Ck rcPlayers cIgnorant)) ]
possibleHands :: [[Int]]
possibleHands = [ [x,y,z] | x <- rcCards, y <- filter (> x) rcCards, z <-filter (> y) rcCards ]
pickHandsNoCrossing :: [ [Int] ] -> Int -> [ [ [Int] ] ]
pickHandsNoCrossing _ 0 = [ [ [ ] ] ]
pickHandsNoCrossing unused 1 = [ [h] | h <- unused ]
pickHandsNoCrossing unused n = concat [ [ h:hs | hs <- pickHandsNoCrossing (myfilter h unused) (n-1) ] | h <- unused ] where
do not allow intersection > 2
allHandLists, safeHandLists :: [ [ [Int] ] ]
allHandLists = concatMap (pickHandsNoCrossing possibleHands) [5,6,7]
safeHandLists = sort (filter checkSet allHandLists)
alicesActions :: [Form]
alicesActions = [ Disj $ map (alice `hasHand`) ([0,1,2]:otherHands) | otherHands <- handLists ] where
handLists :: [ [ [Int] ] ]
handLists = pickHands (delete [0,1,2] possibleHands) 4
pickHands :: [ [Int] ] -> Int -> [ [ [Int] ] ]
pickHands _ 0 = [ [ [ ] ] ]
pickHands hands 1 = [ [ h ] | h <- hands ]
pickHands hands n = [ h:hs | h <- hands, hs <- pickHands (filter (h <) hands) (n-1) ]
bobsActions :: [Form]
bobsActions = [ carol `hasCard` n | n <- reverse [4..6] ]
rcSolutions :: [ [Form] ]
rcSolutions = [ [a, b] | a <- alicesActions, b <- bobsActions, testPlan a b ] where
testPlan :: Form -> Form -> Bool
testPlan aSays bSays = all (evalViaBdd rusSCN)
NOTE : increasing checks are faster than one big conjunction !
[ aSays
, PubAnnounce aSays bKnowsAs
, PubAnnounce aSays cIgnorant
, PubAnnounce aSays bSays
, PubAnnounce aSays (PubAnnounce bSays aKnowsBs)
, PubAnnounce aSays (PubAnnounce bSays (Ck [alice,bob] $ Conj [cIgnorant,aKnowsBs,bKnowsAs])) ]
rcPlan :: OfflinePlan
rcPlan = [ aAnnounce, bAnnounce ]
rcGoal :: Form
rcGoal = Conj [ aKnowsBs
, bKnowsAs
, Ck [alice,bob] (Conj [aKnowsBs, bKnowsAs])
, Ck [alice,bob,carol] cIgnorant ]
rcSolutionsViaPlanning :: [OfflinePlan]
rcSolutionsViaPlanning = offlineSearch maxSteps start actions constraints goal where
We need two steps !
start = rusSCNfor (3,3,1)
actions = alicesActions ++ bobsActions
constraints = [cIgnorant,bKnowsAs]
goal = Conj [aKnowsBs, bKnowsAs]
type RusCardProblem = (Int,Int,Int)
distribute :: RusCardProblem -> Form
distribute (na,nb,nc) = Conj [ alice `hasAtLeast` na
, bob `hasAtLeast` nb
, carol `hasAtLeast` nc ] where
n = na + nb + nc
hasAtLeast :: Agent -> Int -> Form
hasAtLeast _ 0 = Top
hasAtLeast i 1 = Disj [ i `hasCard` k | k <- nCards n ]
hasAtLeast i k = Disj [ Conj (map (i `hasCard`) (sort set))
| set <- powerset (nCards n), length set == k ]
nCards :: Int -> [Int]
nCards n = [0..(n-1)]
nCardsGiven, nCardsUnique :: Int -> Form
nCardsGiven n = Conj [ Disj [ i `hasCard` k | i <- rcPlayers ] | k <- nCards n ]
nCardsUnique n = Conj [ Neg $ isDouble k | k <- nCards n ] where
isDouble k = Disj [ Conj [ x `hasCard` k, y `hasCard` k ] | x <- rcPlayers, y <- rcPlayers, x/=y, x < y ]
rusSCNfor :: RusCardProblem -> KnowScene
rusSCNfor (na,nb,nc) = (KnS props law [ (i, obs i) | i <- rcPlayers ], defaultDeal) where
n = na + nb + nc
props = [ P k | k <-[0..((length rcPlayers * n)-1)] ]
law = boolBddOf $ Conj [ nCardsGiven n, nCardsUnique n, distribute (na,nb,nc) ]
obs i = [ P (3 * k + rcNumOf i) | k<-[0..6] ]
defaultDeal = [ let (PrpF p) = i `hasCard` k in p | i <- rcPlayers, k <- cardsFor i ]
cardsFor "Alice" = [0..(na-1)]
cardsFor "Bob" = [na..(na+nb-1)]
cardsFor "Carol" = [(na+nb)..(na+nb+nc-1)]
cardsFor _ = error "Who is that?"
possibleHandsN :: Int -> Int -> [[Int]]
possibleHandsN n na = filter alldiff $ nub $ map sort $ replicateM na (nCards n) where
alldiff [] = True
alldiff (x:xs) = x `notElem` xs && alldiff xs
allHandListsN :: Int -> Int -> [ [ [Int] ] ]
allHandListsN n na = concatMap (pickHandsNoCrossing (possibleHandsN n na)) [5,6,7] -- FIXME how to adapt the number of hands for larger n?
aKnowsBsN, bKnowsAsN, cIgnorantN :: Int -> Form
aKnowsBsN n = Conj [ alice `Kw` (bob `hasCard` k) | k <- nCards n ]
bKnowsAsN n = Conj [ bob `Kw` (alice `hasCard` k) | k <- nCards n ]
cIgnorantN n = Conj $ concat [ [ Neg $ K carol $ alice `hasCard` i
, Neg $ K carol $ bob `hasCard` i ] | i <- nCards n ]
checkSetFor :: RusCardProblem -> [[Int]] -> Bool
checkSetFor (na,nb,nc) set = reachesOn plan rcGoal (rusSCNfor (na,nb,nc)) where
n = na + nb + nc
aliceSays = K alice (Disj [ Conj $ map (alice `hasCard`) h | h <- set ])
bobSays = K bob (carol `hasCard` last (nCards n))
plan = [ aliceSays, bobSays ]
checkHandsFor :: RusCardProblem -> [ ( [[Int]], Bool) ]
checkHandsFor (na,nb,nc) = map (\hs -> (hs, checkSetFor (na,nb,nc) hs)) (allHandListsN n na) where
n = na + nb + nc
allCasesUpTo :: Int -> [RusCardProblem]
allCasesUpTo bound = [ (na,nb,nc) | na <- [1..bound]
, nb <- [1..(bound-na)]
, nc <- [1..(bound-(na+nb))]
-- these restrictions are only proven
for two announcement plans !
, nc < (na - 1)
, nc < nb ]
dontChange :: [Form] -> K.RelBDD
dontChange fs = conSet <$> sequence [ equ <$> K.mvBdd b <*> K.cpBdd b | b <- map boolBddOf fs ]
noDoubles :: Int -> Form
noDoubles n = Neg $ Disj [ notDouble k | k <- nCards n ] where
notDouble k = Conj [alice `hasCard` k, bob `hasCard` k]
rusBelScnfor :: RusCardProblem -> K.BelScene
rusBelScnfor (na,nb,nc) = (K.BlS props law (fromList [ (i, obsbdd i) | i <- rcPlayers ]), defaultDeal) where
n = na + nb + nc
props = [ P k | k <-[0..((2 * n)-1)] ]
law = boolBddOf $ Conj [ noDoubles n, distribute (na,nb,nc) ]
obsbdd "Alice" = dontChange [ PrpF (P $ 2*k) | k <- [0..(n-1)] ]
obsbdd "Bob" = dontChange [ PrpF (P $ (2*k) + 1) | k <- [0..(n-1)] ]
obsbdd "Carol" = dontChange [ Disj [PrpF (P $ 2*k), PrpF (P $ (2*k) + 1)] | k <- [0..(n-1)] ]
obsbdd _ = error "Unkown Agent"
defaultDeal = [ let (PrpF p) = i `hasCard` k in p | i <- [alice,bob], k <- cardsFor i ] where
cardsFor "Alice" = [0..(na-1)]
cardsFor "Bob" = [na..(na+nb-1)]
cardsFor "Carol" = [(na+nb)..(na+nb+nc-1)]
cardsFor _ = error "Unkown Agent"
| null | https://raw.githubusercontent.com/jrclogic/SMCDEL/10bd5ba2f1f3cc85e4b0f23d5eddbb26f05df5bf/src/SMCDEL/Examples/RussianCards.hs | haskell | FIXME how to adapt the number of hands for larger n?
these restrictions are only proven | # LANGUAGE FlexibleInstances #
module SMCDEL.Examples.RussianCards where
import Control.Monad (replicateM)
import Data.HasCacBDD hiding (Top,Bot)
import Data.List ((\\),delete,intersect,nub,sort)
import Data.Map.Strict (fromList)
import SMCDEL.Internal.Help (powerset)
import SMCDEL.Language
import SMCDEL.Other.Planning
import SMCDEL.Symbolic.S5
import qualified SMCDEL.Symbolic.K as K
rcPlayers :: [Agent]
rcPlayers = [alice,bob,carol]
rcNumOf :: Agent -> Int
rcNumOf "Alice" = 0
rcNumOf "Bob" = 1
rcNumOf "Carol" = 2
rcNumOf _ = error "Unknown Agent"
rcCards :: [Int]
rcCards = [0..6]
rcProps :: [Prp]
rcProps = [ P k | k <-[0..((length rcPlayers * length rcCards)-1)] ]
hasCard :: Agent -> Int -> Form
hasCard i n = PrpF (P (3 * n + rcNumOf i))
hasHand :: Agent -> [Int] -> Form
hasHand i ns = Conj $ map (i `hasCard`) ns
rcExplain :: Prp -> String
rcExplain (P k) = (rcPlayers !! i) ++ " has card " ++ show n where (n,i) = divMod k 3
allCardsGiven, allCardsUnique :: Form
allCardsGiven = Conj [ Disj [ i `hasCard` n | i <- rcPlayers ] | n <- rcCards ]
allCardsUnique = Conj [ Neg $ isDouble n | n <- rcCards ] where
isDouble n = Disj [ Conj [ x `hasCard` n, y `hasCard` n ] | x <- rcPlayers, y <- rcPlayers, x < y ]
distribute331 :: Form
distribute331 = Conj [ aliceAtLeastThree, bobAtLeastThree, carolAtLeastOne ] where
triples = [ [x, y, z] | x <- rcCards, y <- delete x rcCards, z <- rcCards \\ [x,y] ]
aliceAtLeastThree = Disj [ Conj (map (alice `hasCard`) t) | t <- triples ]
bobAtLeastThree = Disj [ Conj (map (bob `hasCard`) t) | t <- triples ]
carolAtLeastOne = Disj [ carol `hasCard` k | k<-[0..6] ]
rusSCN :: KnowScene
rusKNS :: KnowStruct
rusSCN@(rusKNS,_) = (KnS rcProps law [ (i, obs i) | i <- rcPlayers ], defaultDeal) where
law = boolBddOf $ Conj [ allCardsGiven, allCardsUnique, distribute331 ]
obs i = [ P (3 * k + rcNumOf i) | k<-[0..6] ]
defaultDeal = [P 0,P 3,P 6,P 10,P 13,P 16,P 20]
aAnnounce :: Form
aAnnounce = K alice $ Disj [ Conj (map (alice `hasCard`) hand) |
hand <- [ [0,1,2], [0,3,4], [0,5,6], [1,3,5], [2,4,6] ] ]
bAnnounce :: Form
bAnnounce = K bob (carol `hasCard` 6)
aKnowsBs, bKnowsAs, cIgnorant :: Form
aKnowsBs = Conj [ alice `Kw` (bob `hasCard` k) | k<-rcCards ]
bKnowsAs = Conj [ bob `Kw` (alice `hasCard` k) | k<-rcCards ]
cIgnorant = Conj $ concat [ [ Neg $ K carol $ alice `hasCard` i
, Neg $ K carol $ bob `hasCard` i ] | i<-rcCards ]
rcCheck :: Int -> Form
rcCheck 0 = aAnnounce
rcCheck 1 = PubAnnounce aAnnounce bKnowsAs
rcCheck 2 = PubAnnounce aAnnounce (Ck [alice,bob] bKnowsAs)
rcCheck 3 = PubAnnounce aAnnounce (K bob (PrpF (P 20)))
rcCheck 4 = PubAnnounce aAnnounce (Ck [alice,bob,carol] cIgnorant)
rcCheck 5 = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck [alice,bob] aKnowsBs))
rcCheck 6 = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck [alice,bob] bKnowsAs))
rcCheck _ = PubAnnounce aAnnounce (PubAnnounce bAnnounce (Ck rcPlayers cIgnorant))
rcAllChecks :: Bool
rcAllChecks = evalViaBdd rusSCN (Conj (map rcCheck [0..7]))
checkSet :: [[Int]] -> Bool
checkSet set = all (evalViaBdd rusSCN) fs where
aliceSays = K alice (Disj [ Conj $ map (alice `hasCard`) h | h <- set ])
bobSays = K bob (carol `hasCard` 6)
fs = [ aliceSays
, PubAnnounce aliceSays bKnowsAs
, PubAnnounce aliceSays (Ck [alice,bob] bKnowsAs)
, PubAnnounce aliceSays (Ck [alice,bob,carol] cIgnorant)
, PubAnnounce aliceSays (PubAnnounce bobSays (Ck [alice,bob] $ Conj [aKnowsBs, bKnowsAs]))
, PubAnnounce aliceSays (PubAnnounce bobSays (Ck rcPlayers cIgnorant)) ]
possibleHands :: [[Int]]
possibleHands = [ [x,y,z] | x <- rcCards, y <- filter (> x) rcCards, z <-filter (> y) rcCards ]
pickHandsNoCrossing :: [ [Int] ] -> Int -> [ [ [Int] ] ]
pickHandsNoCrossing _ 0 = [ [ [ ] ] ]
pickHandsNoCrossing unused 1 = [ [h] | h <- unused ]
pickHandsNoCrossing unused n = concat [ [ h:hs | hs <- pickHandsNoCrossing (myfilter h unused) (n-1) ] | h <- unused ] where
do not allow intersection > 2
allHandLists, safeHandLists :: [ [ [Int] ] ]
allHandLists = concatMap (pickHandsNoCrossing possibleHands) [5,6,7]
safeHandLists = sort (filter checkSet allHandLists)
alicesActions :: [Form]
alicesActions = [ Disj $ map (alice `hasHand`) ([0,1,2]:otherHands) | otherHands <- handLists ] where
handLists :: [ [ [Int] ] ]
handLists = pickHands (delete [0,1,2] possibleHands) 4
pickHands :: [ [Int] ] -> Int -> [ [ [Int] ] ]
pickHands _ 0 = [ [ [ ] ] ]
pickHands hands 1 = [ [ h ] | h <- hands ]
pickHands hands n = [ h:hs | h <- hands, hs <- pickHands (filter (h <) hands) (n-1) ]
bobsActions :: [Form]
bobsActions = [ carol `hasCard` n | n <- reverse [4..6] ]
rcSolutions :: [ [Form] ]
rcSolutions = [ [a, b] | a <- alicesActions, b <- bobsActions, testPlan a b ] where
testPlan :: Form -> Form -> Bool
testPlan aSays bSays = all (evalViaBdd rusSCN)
NOTE : increasing checks are faster than one big conjunction !
[ aSays
, PubAnnounce aSays bKnowsAs
, PubAnnounce aSays cIgnorant
, PubAnnounce aSays bSays
, PubAnnounce aSays (PubAnnounce bSays aKnowsBs)
, PubAnnounce aSays (PubAnnounce bSays (Ck [alice,bob] $ Conj [cIgnorant,aKnowsBs,bKnowsAs])) ]
rcPlan :: OfflinePlan
rcPlan = [ aAnnounce, bAnnounce ]
rcGoal :: Form
rcGoal = Conj [ aKnowsBs
, bKnowsAs
, Ck [alice,bob] (Conj [aKnowsBs, bKnowsAs])
, Ck [alice,bob,carol] cIgnorant ]
rcSolutionsViaPlanning :: [OfflinePlan]
rcSolutionsViaPlanning = offlineSearch maxSteps start actions constraints goal where
We need two steps !
start = rusSCNfor (3,3,1)
actions = alicesActions ++ bobsActions
constraints = [cIgnorant,bKnowsAs]
goal = Conj [aKnowsBs, bKnowsAs]
type RusCardProblem = (Int,Int,Int)
distribute :: RusCardProblem -> Form
distribute (na,nb,nc) = Conj [ alice `hasAtLeast` na
, bob `hasAtLeast` nb
, carol `hasAtLeast` nc ] where
n = na + nb + nc
hasAtLeast :: Agent -> Int -> Form
hasAtLeast _ 0 = Top
hasAtLeast i 1 = Disj [ i `hasCard` k | k <- nCards n ]
hasAtLeast i k = Disj [ Conj (map (i `hasCard`) (sort set))
| set <- powerset (nCards n), length set == k ]
nCards :: Int -> [Int]
nCards n = [0..(n-1)]
nCardsGiven, nCardsUnique :: Int -> Form
nCardsGiven n = Conj [ Disj [ i `hasCard` k | i <- rcPlayers ] | k <- nCards n ]
nCardsUnique n = Conj [ Neg $ isDouble k | k <- nCards n ] where
isDouble k = Disj [ Conj [ x `hasCard` k, y `hasCard` k ] | x <- rcPlayers, y <- rcPlayers, x/=y, x < y ]
rusSCNfor :: RusCardProblem -> KnowScene
rusSCNfor (na,nb,nc) = (KnS props law [ (i, obs i) | i <- rcPlayers ], defaultDeal) where
n = na + nb + nc
props = [ P k | k <-[0..((length rcPlayers * n)-1)] ]
law = boolBddOf $ Conj [ nCardsGiven n, nCardsUnique n, distribute (na,nb,nc) ]
obs i = [ P (3 * k + rcNumOf i) | k<-[0..6] ]
defaultDeal = [ let (PrpF p) = i `hasCard` k in p | i <- rcPlayers, k <- cardsFor i ]
cardsFor "Alice" = [0..(na-1)]
cardsFor "Bob" = [na..(na+nb-1)]
cardsFor "Carol" = [(na+nb)..(na+nb+nc-1)]
cardsFor _ = error "Who is that?"
possibleHandsN :: Int -> Int -> [[Int]]
possibleHandsN n na = filter alldiff $ nub $ map sort $ replicateM na (nCards n) where
alldiff [] = True
alldiff (x:xs) = x `notElem` xs && alldiff xs
allHandListsN :: Int -> Int -> [ [ [Int] ] ]
aKnowsBsN, bKnowsAsN, cIgnorantN :: Int -> Form
aKnowsBsN n = Conj [ alice `Kw` (bob `hasCard` k) | k <- nCards n ]
bKnowsAsN n = Conj [ bob `Kw` (alice `hasCard` k) | k <- nCards n ]
cIgnorantN n = Conj $ concat [ [ Neg $ K carol $ alice `hasCard` i
, Neg $ K carol $ bob `hasCard` i ] | i <- nCards n ]
checkSetFor :: RusCardProblem -> [[Int]] -> Bool
checkSetFor (na,nb,nc) set = reachesOn plan rcGoal (rusSCNfor (na,nb,nc)) where
n = na + nb + nc
aliceSays = K alice (Disj [ Conj $ map (alice `hasCard`) h | h <- set ])
bobSays = K bob (carol `hasCard` last (nCards n))
plan = [ aliceSays, bobSays ]
checkHandsFor :: RusCardProblem -> [ ( [[Int]], Bool) ]
checkHandsFor (na,nb,nc) = map (\hs -> (hs, checkSetFor (na,nb,nc) hs)) (allHandListsN n na) where
n = na + nb + nc
allCasesUpTo :: Int -> [RusCardProblem]
allCasesUpTo bound = [ (na,nb,nc) | na <- [1..bound]
, nb <- [1..(bound-na)]
, nc <- [1..(bound-(na+nb))]
for two announcement plans !
, nc < (na - 1)
, nc < nb ]
dontChange :: [Form] -> K.RelBDD
dontChange fs = conSet <$> sequence [ equ <$> K.mvBdd b <*> K.cpBdd b | b <- map boolBddOf fs ]
noDoubles :: Int -> Form
noDoubles n = Neg $ Disj [ notDouble k | k <- nCards n ] where
notDouble k = Conj [alice `hasCard` k, bob `hasCard` k]
rusBelScnfor :: RusCardProblem -> K.BelScene
rusBelScnfor (na,nb,nc) = (K.BlS props law (fromList [ (i, obsbdd i) | i <- rcPlayers ]), defaultDeal) where
n = na + nb + nc
props = [ P k | k <-[0..((2 * n)-1)] ]
law = boolBddOf $ Conj [ noDoubles n, distribute (na,nb,nc) ]
obsbdd "Alice" = dontChange [ PrpF (P $ 2*k) | k <- [0..(n-1)] ]
obsbdd "Bob" = dontChange [ PrpF (P $ (2*k) + 1) | k <- [0..(n-1)] ]
obsbdd "Carol" = dontChange [ Disj [PrpF (P $ 2*k), PrpF (P $ (2*k) + 1)] | k <- [0..(n-1)] ]
obsbdd _ = error "Unkown Agent"
defaultDeal = [ let (PrpF p) = i `hasCard` k in p | i <- [alice,bob], k <- cardsFor i ] where
cardsFor "Alice" = [0..(na-1)]
cardsFor "Bob" = [na..(na+nb-1)]
cardsFor "Carol" = [(na+nb)..(na+nb+nc-1)]
cardsFor _ = error "Unkown Agent"
|
cc5f6ef8eaa4ec989d97c8d61ee4b918f9285513f2a7c4c273a4504b0c7e40d6 | Fandoozle/AutoCAD | clearwipeouts.lsp | (vl-load-com)
(defun c:ClearWipeouts (/ b o)
;;--- Tharwat 26.June.2013 ---;;
(or doc
(setq doc (vla-get-ActiveDocument (vlax-get-acad-object)))
)
(vlax-for b
(vla-get-blocks
doc
)
(if
(and
(eq :vlax-false (vla-get-isLayout b))
(eq :vlax-false (vla-get-isXref b))
)
(vlax-for o b
(if (eq "AcDbWipeout" (vla-get-objectname o))
(vl-catch-all-apply 'vla-delete (list o))
)
)
)
)
(if (setq ss (ssget "_X" '((0 . "WIPEOUT")(410 . "Model"))))
(command "_.erase" ss "")
)
(vla-regen doc acAllViewports)
(princ)
) | null | https://raw.githubusercontent.com/Fandoozle/AutoCAD/18480cd17c9b46718762c3155f2bca1be2e2e5e2/clearwipeouts.lsp | lisp | --- Tharwat 26.June.2013 ---;;
| (vl-load-com)
(defun c:ClearWipeouts (/ b o)
(or doc
(setq doc (vla-get-ActiveDocument (vlax-get-acad-object)))
)
(vlax-for b
(vla-get-blocks
doc
)
(if
(and
(eq :vlax-false (vla-get-isLayout b))
(eq :vlax-false (vla-get-isXref b))
)
(vlax-for o b
(if (eq "AcDbWipeout" (vla-get-objectname o))
(vl-catch-all-apply 'vla-delete (list o))
)
)
)
)
(if (setq ss (ssget "_X" '((0 . "WIPEOUT")(410 . "Model"))))
(command "_.erase" ss "")
)
(vla-regen doc acAllViewports)
(princ)
) |
53621a9251eb3dfcffac96aeb26e65797669f63789b90bbffdfcc9c1cebfc393 | Clozure/ccl | interp.lisp | -*- Log : hemlock.log ; Package : Hemlock - Internals -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
;;;
#+CMU (ext:file-comment
"$Header$")
;;;
;;; **********************************************************************
;;;
Written by and .
;;;
;;; This file contains the routines which define hemlock commands and
;;; the command interpreter.
;;;
(in-package :hemlock-internals)
(defun %print-hcommand (obj stream depth)
(declare (ignore depth))
(write-string "#<Hemlock Command \"" stream)
(write-string (command-name obj) stream)
(write-string "\">" stream))
;;;; Key Tables:
;;;
;;; A key table provides a way to translate a sequence of characters to some
;;; lisp object. It is currently represented by a tree of hash-tables, where
;;; each level is a hashing from a key to either another hash-table or a value.
;;; GET-TABLE-ENTRY returns the value at the end of a series of hashings. For
;;; our purposes it is presently used to look up commands and key-translations.
;;;
(defun get-table-entry (table key &key (end (length key)))
(let ((foo nil))
(dotimes (i end foo)
(let ((key-event (aref key i)))
(setf foo (gethash key-event table))
(unless (hash-table-p foo) (return foo))
(setf table foo)))))
;;; SET-TABLE-ENTRY sets the entry for key in table to val, creating new
tables as needed . If val is nil , then use to remove this element
;;; from the hash-table.
;;;
(defun set-table-entry (table key val)
(dotimes (i (1- (length key)))
(let* ((key-event (aref key i))
(foo (gethash key-event table)))
(if (hash-table-p foo)
(setf table foo)
(let ((new-table (make-hash-table)))
(setf (gethash key-event table) new-table)
(setf table new-table)))))
(if (null val)
(remhash (aref key (1- (length key))) table)
(setf (gethash (aref key (1- (length key))) table) val)))
;;;; Key Translation:
;;;
;;; Key translations are maintained using a key table. If a value is an
;;; integer, then it is prefix bits to be OR'ed with the next character. If it
;;; is a key, then we translate to that key.
(defvar *key-translations* (make-hash-table))
TRANSLATE - KEY -- Internal
;;;
;;; This is used internally to do key translations when we want the
;;; canonical representation for Key. Result, if supplied, is an adjustable
;;; vector with a fill pointer. We compute the output in this vector. If the
;;; key ends in the prefix of a translation, we just return that part
untranslated and return the second value true .
;;;
(defun translate-key (key &optional (result (make-array (length key)
:fill-pointer 0
:adjustable t))
(temp (make-array 10 :fill-pointer 0 :adjustable t)))
(let ((key-len (length key))
(start 0)
(try-pos 0)
(prefix 0))
(setf (fill-pointer temp) 0)
(setf (fill-pointer result) 0)
(loop
(when (= try-pos key-len) (return))
(let ((key-event (aref key try-pos)))
(vector-push-extend
(make-key-event key-event (logior (key-event-bits key-event) prefix))
temp)
(setf prefix 0))
(let ((entry (get-table-entry *key-translations* temp)))
(cond ((hash-table-p entry)
(incf try-pos))
(t
(etypecase entry
(null
(vector-push-extend (aref temp 0) result)
(incf start))
(simple-vector
(dotimes (i (length entry))
(vector-push-extend (aref entry i) result))
(setf start (1+ try-pos)))
(integer
(setf start (1+ try-pos))
(when (= start key-len) (return))
(setf prefix (logior entry prefix))))
(setq try-pos start)
(setf (fill-pointer temp) 0)))))
(dotimes (i (length temp))
(vector-push-extend (aref temp i) result))
(values result (not (zerop (length temp))))))
;;; KEY-TRANSLATION -- Public.
;;;
(defun key-translation (key)
"Return the key translation for Key, or NIL if there is none. If Key is a
prefix of a translation, then :Prefix is returned. Whenever Key appears as a
subsequence of a key argument to the binding manipulation functions, that
portion will be replaced with the translation. A key translation may also be
a list (:Bits {Bit-Name}*). In this case, the named bits will be set in the
next character in the key being translated."
(let ((entry (get-table-entry *key-translations* (crunch-key key))))
(etypecase entry
(hash-table :prefix)
((or simple-vector null) entry)
(integer
(cons :bits (key-event-bits-modifiers entry))))))
% SET - KEY - TRANSLATION -- Internal
;;;
(defun %set-key-translation (key new-value)
(let ((entry (cond ((and (consp new-value) (eq (car new-value) :bits))
(apply #'make-key-event-bits (cdr new-value)))
(new-value (crunch-key new-value))
(t new-value))))
(set-table-entry *key-translations* (crunch-key key) entry)
new-value))
;;;
(defsetf key-translation %set-key-translation
"Set the key translation for a key. If set to null, deletes any
translation.")
;;;; Interface Utility Functions:
(defvar *global-command-table* (make-hash-table)
"The command table for global key bindings.")
GET - RIGHT - TABLE -- Internal
;;;
;;; Return a hash-table depending on "kind" and checking for errors.
;;;
(defun get-right-table (kind where)
(case kind
(:global
(when where
(error "Where argument ~S is meaningless for :global bindings."
where))
*global-command-table*)
(:mode (let ((mode (getstring where *mode-names*)))
(unless mode
(error "~S is not a defined mode." where))
(mode-object-bindings mode)))
(:buffer (unless (bufferp where)
(error "~S is not a buffer." where))
(buffer-bindings where))
(t (error "~S is not a valid binding type." kind))))
CRUNCH - KEY -- Internal .
;;;
;;; Take a key in one of the various specifications and turn it into the
;;; standard one: a simple-vector of characters.
;;;
(defun crunch-key (key)
(typecase key
(key-event (vector key))
((or list vector) ;List thrown in gratuitously.
(when (zerop (length key))
(error "A zero length key is illegal."))
(unless (every #'key-event-p key)
(error "A Key ~S must contain only key-events." key))
(coerce key 'simple-vector))
(t
(error "Key ~S is not a key-event or sequence of key-events." key))))
;;;; Exported Primitives:
(declaim (special *command-names*))
BIND - KEY -- Public .
;;;
(defun bind-key (name key &optional (kind :global) where)
"Bind a Hemlock command to some key somewhere. Name is the string name
of a Hemlock command, Key is either a key-event or a vector of key-events.
Kind is one of :Global, :Mode or :Buffer, and where is the mode name or
buffer concerned. Kind defaults to :Global."
;;(with-simple-restart (continue "Go on, ignoring binding attempt."))
(handler-bind ((error
#'(lambda (condition)
(format *error-output*
"~&Error while trying to bind key ~A: ~A~%"
key condition)
(message (format nil "~a" condition))
#-GZ (return-from bind-key nil)
)))
(let ((cmd (getstring name *command-names*))
(table (get-right-table kind where))
(key (copy-seq (translate-key (crunch-key key)))))
(cond (cmd
(set-table-entry table key cmd)
(push (list key kind where) (command-%bindings cmd))
cmd)
(t
(error "~S is not a defined command." name))))))
;;; DELETE-KEY-BINDING -- Public
;;;
Stick NIL in the key table specified .
;;;
(defun delete-key-binding (key &optional (kind :global) where)
"Remove a Hemlock key binding somewhere. Key is either a key-event or a
vector of key-events. Kind is one of :Global, :Mode or :Buffer, andl where
is the mode name or buffer concerned. Kind defaults to :Global."
(set-table-entry (get-right-table kind where)
(translate-key (crunch-key key))
nil))
GET - CURRENT - BINDING -- Internal
;;;
;;; Look up a key in the current environment.
;;;
(defun get-current-binding (key)
(let ((buffer (current-buffer))
(t-bindings nil) res t-res)
(multiple-value-setq (res t-res) (get-binding-in-buffer key buffer))
(when t-res (push t-res t-bindings))
(loop while (null res)
for mode in (buffer-minor-mode-objects buffer)
do (multiple-value-setq (res t-res) (get-binding-in-mode key mode))
do (when t-res (push t-res t-bindings)))
(when (null res)
(multiple-value-setq (res t-res)
(get-binding-in-mode key (buffer-major-mode-object buffer)))
(when t-res (push t-res t-bindings)))
(values (or res (get-table-entry *global-command-table* key))
(nreverse t-bindings))))
(defun get-binding-in-buffer (key buffer)
(let ((res (get-table-entry (buffer-bindings buffer) key)))
(when res
(if (and (commandp res) (command-transparent-p res))
(values nil res)
(values res nil)))))
(defun get-binding-in-mode (key mode)
(let* ((res (or (get-table-entry (mode-object-bindings mode) key)
(let ((default (mode-object-default-command mode)))
(and default (getstring default *command-names*))))))
(when res
(if (or (mode-object-transparent-p mode)
(and (commandp res) (command-transparent-p res)))
(values nil res)
(values res nil)))))
;;; GET-COMMAND -- Public.
;;;
(defun get-command (key &optional (kind :global) where)
"Return the command object for the command bound to key somewhere.
If key is not bound, return nil. Key is either a key-event or a vector of
key-events. If key is a prefix of a key-binding, then return :prefix.
Kind is one of :global, :mode or :buffer, and where is the mode name or
buffer concerned. Kind defaults to :Global."
(multiple-value-bind (key prefix-p)
(translate-key (crunch-key key))
(let ((entry (if (eq kind :current)
(get-current-binding key)
(get-table-entry (get-right-table kind where) key))))
(etypecase entry
(null (if prefix-p :prefix nil))
(command entry)
(hash-table :prefix)))))
(defvar *map-bindings-key* (make-array 5 :adjustable t :fill-pointer 0))
MAP - BINDINGS -- Public .
;;;
(defun map-bindings (function kind &optional where)
"Map function over the bindings in some place. The function is passed the
key and the command to which it is bound."
(labels ((mapping-fun (hash-key hash-value)
(vector-push-extend hash-key *map-bindings-key*)
(etypecase hash-value
(command (funcall function *map-bindings-key* hash-value))
(hash-table (maphash #'mapping-fun hash-value)))
(decf (fill-pointer *map-bindings-key*))))
(setf (fill-pointer *map-bindings-key*) 0)
(maphash #'mapping-fun (get-right-table kind where))))
;;; MAKE-COMMAND -- Public.
;;;
;;; If the command is already defined, then alter the command object;
;;; otherwise, make a new command object and enter it into the *command-names*.
;;;
(defun make-command (name documentation function &key transparent-p)
"Create a new Hemlock command with Name and Documentation which is
implemented by calling the function-value of the symbol Function"
(let ((entry (getstring name *command-names*)))
(cond
(entry
(setf (command-name entry) name)
(setf (command-documentation entry) documentation)
(setf (command-function entry) function)
(setf (command-transparent-p entry) transparent-p))
(t
(setf (getstring name *command-names*)
(internal-make-command name documentation function transparent-p))))))
;;; COMMAND-NAME, %SET-COMMAND-NAME -- Public.
;;;
(defun command-name (command)
"Returns the string which is the name of Command."
(command-%name command))
;;;
(defun %set-command-name (command new-name)
(check-type command command)
(check-type new-name string)
(setq new-name (coerce new-name 'simple-string))
(delete-string (command-%name command) *command-names*)
(setf (getstring new-name *command-names*) command)
(setf (command-%name command) new-name))
;;; COMMAND-BINDINGS -- Public.
;;;
;;; Check that all the supposed bindings really exists. Bindings which
;;; were once made may have been overwritten. It is easier to filter
;;; out bogus bindings here than to catch all the cases that can make a
;;; binding go away.
;;;
(defun command-bindings (command)
"Return a list of lists of the form (key kind where) describing
all the places where Command is bound."
(check-type command command)
(let (result)
(declare (list result))
(dolist (place (command-%bindings command))
(let ((table (case (cadr place)
(:global *global-command-table*)
(:mode
(let ((m (getstring (caddr place) *mode-names*)))
(when m (mode-object-bindings m))))
(t
(when (member (caddr place) *buffer-list*)
(buffer-bindings (caddr place)))))))
(when (and table
(eq (get-table-entry table (car place)) command)
(not (member place result :test #'equalp)))
(push place result))))
result))
;;; COMMANDS-AND-BINDINGS -- Public
;;;
;;; Return a list of (command . key-bindings), for use in help. Looks only at bindings
in modes in " Default Modes " variable , does n't require current buffer .
;;;
(defun commands-and-bindings (&optional (modes (value hemlock::default-modes)))
(when (some #'stringp modes)
(setq modes (mapcar (lambda (m) (if (stringp m) (get-mode-object m) m)) modes)))
(loop for cmd in (string-table-values *command-names*)
as bindings = (command-bindings cmd)
;; collect unshadowed bindings
as keys = (loop for (key-seq) in bindings
when (eq cmd (get-binding-with-modes key-seq modes))
collect key-seq)
unless (or (and bindings (not keys)) ;; ignore pseudo-commands like "I-Search whatever"
(command-transparent-p cmd) ;; ignore addons like exit search mode.
(eq cmd (get-default-command)) ;; ignore illegal
(eq cmd (get-self-insert-command));; and self insert
(> (length keys) 5)) ;; ignore commmands like "Digit"
collect (cons cmd keys)))
(defun get-binding-with-modes (key modes)
(or (loop for mode in modes ;; first find minor mode binding
do (when (stringp mode) (setq mode (get-mode-object mode)))
thereis (and (not (mode-object-major-p mode)) (get-binding-in-mode key mode)))
(loop for mode in modes ;; next try major mode
do (when (stringp mode) (setq mode (get-mode-object mode)))
thereis (and (mode-object-major-p mode) (get-binding-in-mode key mode)))
(get-table-entry *global-command-table* key)))
(defvar *key-event-history* (make-ring 60))
LAST - COMMAND - TYPE -- Public
;;;
;;;
(defun last-command-type ()
"Return the command-type of the last command invoked.
If no command-type has been set then return NIL. Setting this with
Setf sets the value for the next command."
*last-last-command-type*)
% SET - LAST - COMMAND - TYPE -- Internal
;;;
(defun %set-last-command-type (type)
(setf (hemlock-last-command-type *current-view*) type))
;;; PREFIX-ARGUMENT -- Public
;;;
;;;
(defun prefix-argument ()
"Return the current value of prefix argument."
*last-prefix-argument*)
(defun get-self-insert-command ()
;; Get the command used to implement normal character insertion in current buffer.
(getstring (value hemlock::self-insert-command-name) *command-names*))
(defun get-default-command ()
;; Get the command used when no binding is present in current buffer.
(getstring (value hemlock::default-command-name) *command-names*))
(defun get-system-default-behavior-command ()
Get the command used to invoke " System Default Behavior "
(getstring (value hemlock::system-default-behavior-command-name) *command-names*))
(defvar *native-key-events* (make-hash-table :test #'eq))
(defun native-key-event-p (key)
(check-type key key-event)
(gethash key *native-key-events*))
(defun (setf native-key-event-p) (flag key)
(check-type key key-event)
(if flag
(setf (gethash key *native-key-events*) flag)
(remhash key *native-key-events*)))
| null | https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/cocoa-ide/hemlock/src/interp.lisp | lisp | Package : Hemlock - Internals -*-
**********************************************************************
**********************************************************************
This file contains the routines which define hemlock commands and
the command interpreter.
Key Tables:
A key table provides a way to translate a sequence of characters to some
lisp object. It is currently represented by a tree of hash-tables, where
each level is a hashing from a key to either another hash-table or a value.
GET-TABLE-ENTRY returns the value at the end of a series of hashings. For
our purposes it is presently used to look up commands and key-translations.
SET-TABLE-ENTRY sets the entry for key in table to val, creating new
from the hash-table.
Key Translation:
Key translations are maintained using a key table. If a value is an
integer, then it is prefix bits to be OR'ed with the next character. If it
is a key, then we translate to that key.
This is used internally to do key translations when we want the
canonical representation for Key. Result, if supplied, is an adjustable
vector with a fill pointer. We compute the output in this vector. If the
key ends in the prefix of a translation, we just return that part
KEY-TRANSLATION -- Public.
Interface Utility Functions:
Return a hash-table depending on "kind" and checking for errors.
Take a key in one of the various specifications and turn it into the
standard one: a simple-vector of characters.
List thrown in gratuitously.
Exported Primitives:
(with-simple-restart (continue "Go on, ignoring binding attempt."))
DELETE-KEY-BINDING -- Public
Look up a key in the current environment.
GET-COMMAND -- Public.
MAKE-COMMAND -- Public.
If the command is already defined, then alter the command object;
otherwise, make a new command object and enter it into the *command-names*.
COMMAND-NAME, %SET-COMMAND-NAME -- Public.
COMMAND-BINDINGS -- Public.
Check that all the supposed bindings really exists. Bindings which
were once made may have been overwritten. It is easier to filter
out bogus bindings here than to catch all the cases that can make a
binding go away.
COMMANDS-AND-BINDINGS -- Public
Return a list of (command . key-bindings), for use in help. Looks only at bindings
collect unshadowed bindings
ignore pseudo-commands like "I-Search whatever"
ignore addons like exit search mode.
ignore illegal
and self insert
ignore commmands like "Digit"
first find minor mode binding
next try major mode
PREFIX-ARGUMENT -- Public
Get the command used to implement normal character insertion in current buffer.
Get the command used when no binding is present in current buffer. | This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
#+CMU (ext:file-comment
"$Header$")
Written by and .
(in-package :hemlock-internals)
(defun %print-hcommand (obj stream depth)
(declare (ignore depth))
(write-string "#<Hemlock Command \"" stream)
(write-string (command-name obj) stream)
(write-string "\">" stream))
(defun get-table-entry (table key &key (end (length key)))
(let ((foo nil))
(dotimes (i end foo)
(let ((key-event (aref key i)))
(setf foo (gethash key-event table))
(unless (hash-table-p foo) (return foo))
(setf table foo)))))
tables as needed . If val is nil , then use to remove this element
(defun set-table-entry (table key val)
(dotimes (i (1- (length key)))
(let* ((key-event (aref key i))
(foo (gethash key-event table)))
(if (hash-table-p foo)
(setf table foo)
(let ((new-table (make-hash-table)))
(setf (gethash key-event table) new-table)
(setf table new-table)))))
(if (null val)
(remhash (aref key (1- (length key))) table)
(setf (gethash (aref key (1- (length key))) table) val)))
(defvar *key-translations* (make-hash-table))
TRANSLATE - KEY -- Internal
untranslated and return the second value true .
(defun translate-key (key &optional (result (make-array (length key)
:fill-pointer 0
:adjustable t))
(temp (make-array 10 :fill-pointer 0 :adjustable t)))
(let ((key-len (length key))
(start 0)
(try-pos 0)
(prefix 0))
(setf (fill-pointer temp) 0)
(setf (fill-pointer result) 0)
(loop
(when (= try-pos key-len) (return))
(let ((key-event (aref key try-pos)))
(vector-push-extend
(make-key-event key-event (logior (key-event-bits key-event) prefix))
temp)
(setf prefix 0))
(let ((entry (get-table-entry *key-translations* temp)))
(cond ((hash-table-p entry)
(incf try-pos))
(t
(etypecase entry
(null
(vector-push-extend (aref temp 0) result)
(incf start))
(simple-vector
(dotimes (i (length entry))
(vector-push-extend (aref entry i) result))
(setf start (1+ try-pos)))
(integer
(setf start (1+ try-pos))
(when (= start key-len) (return))
(setf prefix (logior entry prefix))))
(setq try-pos start)
(setf (fill-pointer temp) 0)))))
(dotimes (i (length temp))
(vector-push-extend (aref temp i) result))
(values result (not (zerop (length temp))))))
(defun key-translation (key)
"Return the key translation for Key, or NIL if there is none. If Key is a
prefix of a translation, then :Prefix is returned. Whenever Key appears as a
subsequence of a key argument to the binding manipulation functions, that
portion will be replaced with the translation. A key translation may also be
a list (:Bits {Bit-Name}*). In this case, the named bits will be set in the
next character in the key being translated."
(let ((entry (get-table-entry *key-translations* (crunch-key key))))
(etypecase entry
(hash-table :prefix)
((or simple-vector null) entry)
(integer
(cons :bits (key-event-bits-modifiers entry))))))
% SET - KEY - TRANSLATION -- Internal
(defun %set-key-translation (key new-value)
(let ((entry (cond ((and (consp new-value) (eq (car new-value) :bits))
(apply #'make-key-event-bits (cdr new-value)))
(new-value (crunch-key new-value))
(t new-value))))
(set-table-entry *key-translations* (crunch-key key) entry)
new-value))
(defsetf key-translation %set-key-translation
"Set the key translation for a key. If set to null, deletes any
translation.")
(defvar *global-command-table* (make-hash-table)
"The command table for global key bindings.")
GET - RIGHT - TABLE -- Internal
(defun get-right-table (kind where)
(case kind
(:global
(when where
(error "Where argument ~S is meaningless for :global bindings."
where))
*global-command-table*)
(:mode (let ((mode (getstring where *mode-names*)))
(unless mode
(error "~S is not a defined mode." where))
(mode-object-bindings mode)))
(:buffer (unless (bufferp where)
(error "~S is not a buffer." where))
(buffer-bindings where))
(t (error "~S is not a valid binding type." kind))))
CRUNCH - KEY -- Internal .
(defun crunch-key (key)
(typecase key
(key-event (vector key))
(when (zerop (length key))
(error "A zero length key is illegal."))
(unless (every #'key-event-p key)
(error "A Key ~S must contain only key-events." key))
(coerce key 'simple-vector))
(t
(error "Key ~S is not a key-event or sequence of key-events." key))))
(declaim (special *command-names*))
BIND - KEY -- Public .
(defun bind-key (name key &optional (kind :global) where)
"Bind a Hemlock command to some key somewhere. Name is the string name
of a Hemlock command, Key is either a key-event or a vector of key-events.
Kind is one of :Global, :Mode or :Buffer, and where is the mode name or
buffer concerned. Kind defaults to :Global."
(handler-bind ((error
#'(lambda (condition)
(format *error-output*
"~&Error while trying to bind key ~A: ~A~%"
key condition)
(message (format nil "~a" condition))
#-GZ (return-from bind-key nil)
)))
(let ((cmd (getstring name *command-names*))
(table (get-right-table kind where))
(key (copy-seq (translate-key (crunch-key key)))))
(cond (cmd
(set-table-entry table key cmd)
(push (list key kind where) (command-%bindings cmd))
cmd)
(t
(error "~S is not a defined command." name))))))
Stick NIL in the key table specified .
(defun delete-key-binding (key &optional (kind :global) where)
"Remove a Hemlock key binding somewhere. Key is either a key-event or a
vector of key-events. Kind is one of :Global, :Mode or :Buffer, andl where
is the mode name or buffer concerned. Kind defaults to :Global."
(set-table-entry (get-right-table kind where)
(translate-key (crunch-key key))
nil))
GET - CURRENT - BINDING -- Internal
(defun get-current-binding (key)
(let ((buffer (current-buffer))
(t-bindings nil) res t-res)
(multiple-value-setq (res t-res) (get-binding-in-buffer key buffer))
(when t-res (push t-res t-bindings))
(loop while (null res)
for mode in (buffer-minor-mode-objects buffer)
do (multiple-value-setq (res t-res) (get-binding-in-mode key mode))
do (when t-res (push t-res t-bindings)))
(when (null res)
(multiple-value-setq (res t-res)
(get-binding-in-mode key (buffer-major-mode-object buffer)))
(when t-res (push t-res t-bindings)))
(values (or res (get-table-entry *global-command-table* key))
(nreverse t-bindings))))
(defun get-binding-in-buffer (key buffer)
(let ((res (get-table-entry (buffer-bindings buffer) key)))
(when res
(if (and (commandp res) (command-transparent-p res))
(values nil res)
(values res nil)))))
(defun get-binding-in-mode (key mode)
(let* ((res (or (get-table-entry (mode-object-bindings mode) key)
(let ((default (mode-object-default-command mode)))
(and default (getstring default *command-names*))))))
(when res
(if (or (mode-object-transparent-p mode)
(and (commandp res) (command-transparent-p res)))
(values nil res)
(values res nil)))))
(defun get-command (key &optional (kind :global) where)
"Return the command object for the command bound to key somewhere.
If key is not bound, return nil. Key is either a key-event or a vector of
key-events. If key is a prefix of a key-binding, then return :prefix.
Kind is one of :global, :mode or :buffer, and where is the mode name or
buffer concerned. Kind defaults to :Global."
(multiple-value-bind (key prefix-p)
(translate-key (crunch-key key))
(let ((entry (if (eq kind :current)
(get-current-binding key)
(get-table-entry (get-right-table kind where) key))))
(etypecase entry
(null (if prefix-p :prefix nil))
(command entry)
(hash-table :prefix)))))
(defvar *map-bindings-key* (make-array 5 :adjustable t :fill-pointer 0))
MAP - BINDINGS -- Public .
(defun map-bindings (function kind &optional where)
"Map function over the bindings in some place. The function is passed the
key and the command to which it is bound."
(labels ((mapping-fun (hash-key hash-value)
(vector-push-extend hash-key *map-bindings-key*)
(etypecase hash-value
(command (funcall function *map-bindings-key* hash-value))
(hash-table (maphash #'mapping-fun hash-value)))
(decf (fill-pointer *map-bindings-key*))))
(setf (fill-pointer *map-bindings-key*) 0)
(maphash #'mapping-fun (get-right-table kind where))))
(defun make-command (name documentation function &key transparent-p)
"Create a new Hemlock command with Name and Documentation which is
implemented by calling the function-value of the symbol Function"
(let ((entry (getstring name *command-names*)))
(cond
(entry
(setf (command-name entry) name)
(setf (command-documentation entry) documentation)
(setf (command-function entry) function)
(setf (command-transparent-p entry) transparent-p))
(t
(setf (getstring name *command-names*)
(internal-make-command name documentation function transparent-p))))))
(defun command-name (command)
"Returns the string which is the name of Command."
(command-%name command))
(defun %set-command-name (command new-name)
(check-type command command)
(check-type new-name string)
(setq new-name (coerce new-name 'simple-string))
(delete-string (command-%name command) *command-names*)
(setf (getstring new-name *command-names*) command)
(setf (command-%name command) new-name))
(defun command-bindings (command)
"Return a list of lists of the form (key kind where) describing
all the places where Command is bound."
(check-type command command)
(let (result)
(declare (list result))
(dolist (place (command-%bindings command))
(let ((table (case (cadr place)
(:global *global-command-table*)
(:mode
(let ((m (getstring (caddr place) *mode-names*)))
(when m (mode-object-bindings m))))
(t
(when (member (caddr place) *buffer-list*)
(buffer-bindings (caddr place)))))))
(when (and table
(eq (get-table-entry table (car place)) command)
(not (member place result :test #'equalp)))
(push place result))))
result))
in modes in " Default Modes " variable , does n't require current buffer .
(defun commands-and-bindings (&optional (modes (value hemlock::default-modes)))
(when (some #'stringp modes)
(setq modes (mapcar (lambda (m) (if (stringp m) (get-mode-object m) m)) modes)))
(loop for cmd in (string-table-values *command-names*)
as bindings = (command-bindings cmd)
as keys = (loop for (key-seq) in bindings
when (eq cmd (get-binding-with-modes key-seq modes))
collect key-seq)
collect (cons cmd keys)))
(defun get-binding-with-modes (key modes)
do (when (stringp mode) (setq mode (get-mode-object mode)))
thereis (and (not (mode-object-major-p mode)) (get-binding-in-mode key mode)))
do (when (stringp mode) (setq mode (get-mode-object mode)))
thereis (and (mode-object-major-p mode) (get-binding-in-mode key mode)))
(get-table-entry *global-command-table* key)))
(defvar *key-event-history* (make-ring 60))
LAST - COMMAND - TYPE -- Public
(defun last-command-type ()
"Return the command-type of the last command invoked.
If no command-type has been set then return NIL. Setting this with
Setf sets the value for the next command."
*last-last-command-type*)
% SET - LAST - COMMAND - TYPE -- Internal
(defun %set-last-command-type (type)
(setf (hemlock-last-command-type *current-view*) type))
(defun prefix-argument ()
"Return the current value of prefix argument."
*last-prefix-argument*)
(defun get-self-insert-command ()
(getstring (value hemlock::self-insert-command-name) *command-names*))
(defun get-default-command ()
(getstring (value hemlock::default-command-name) *command-names*))
(defun get-system-default-behavior-command ()
Get the command used to invoke " System Default Behavior "
(getstring (value hemlock::system-default-behavior-command-name) *command-names*))
(defvar *native-key-events* (make-hash-table :test #'eq))
(defun native-key-event-p (key)
(check-type key key-event)
(gethash key *native-key-events*))
(defun (setf native-key-event-p) (flag key)
(check-type key key-event)
(if flag
(setf (gethash key *native-key-events*) flag)
(remhash key *native-key-events*)))
|
921b7eecb74791904ee2853da773d2cbb9248cfffaeab514b6167e87f7e1aad1 | nasa/Common-Metadata-Repository | iso19115_2.clj | (ns cmr.umm-spec.umm-to-xml-mappings.iso19115-2
"Defines mappings from UMM records into ISO19115-2 XML."
(:require
[clojure.string :as string]
[cmr.common.date-time-parser :as p]
[cmr.common.util :as util]
[cmr.common.xml.gen :refer :all]
[cmr.umm-spec.date-util :as date-util]
[cmr.umm-spec.iso-keywords :as kws]
[cmr.umm-spec.iso19115-2-util :as iso]
[cmr.umm-spec.location-keywords :as lk]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.archive-and-dist-info :as archive-and-dist-info]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.collection-citation :as collection-citation]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.collection-progress :as collection-progress]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.distributions-related-url :as sdru]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.doi :as doi]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.iso-topic-categories :as iso-topic-categories]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.platform :as platform]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.processing-level :as proc-level]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.project-element :as project]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.use-constraints :as use-constraints]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.additional-attribute :as aa]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.data-contact :as data-contact]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.metadata-association :as ma]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.spatial :as spatial]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.tiling-system :as tiling]
[cmr.umm-spec.util :as su :refer [char-string]]))
(def iso19115-2-xml-namespaces
{:xmlns:eos ""
:xmlns:gco ""
:xmlns:gmd ""
:xmlns:gmi ""
:xmlns:gml ""
:xmlns:gmx ""
:xmlns:gsr ""
:xmlns:gss ""
:xmlns:gts ""
:xmlns:srv ""
:xmlns:xlink ""
:xmlns:xs ""
:xmlns:xsi "-instance"
:xsi:schemaLocation (str " "
" "
" "
" "
" "
" "
" "
" "
" "
" ")})
(def iso-topic-categories
#{"farming"
"biota"
"boundaries"
"climatologyMeteorologyAtmosphere"
"economy"
"elevation"
"environment"
"geoscientificInformation"
"health"
"imageryBaseMapsEarthCover"
"intelligenceMilitary"
"inlandWaters"
"location"
"oceans"
"planningCadastre"
"society"
"structure"
"transportation"
"utilitiesCommunication"})
(defn- generate-projects-keywords
"Returns the content generator instructions for descriptive keywords of the given projects."
[projects]
(let [project-keywords (map iso/generate-title projects)]
(kws/generate-iso19115-descriptive-keywords "project" project-keywords)))
(defn- generate-data-dates
"Returns ISO XML elements for the DataDates of given UMM collection."
[c]
;; Use a default value if none present in the UMM record
(let [dates (or (:DataDates c) [{:Type "CREATE" :Date date-util/default-date-value}])]
(for [date dates
:let [type-code (get iso/iso-date-type-codes (:Type date))
date-value (or (:Date date) date-util/default-date-value)]]
[:gmd:date
[:gmd:CI_Date
[:gmd:date
[:gco:DateTime date-value]]
[:gmd:dateType
[:gmd:CI_DateTypeCode {:codeList (str (:ngdc iso/code-lists) "#CI_DateTypeCode")
:codeListValue type-code} type-code]]]])))
(defn- generate-datestamp
"Return the ISO datestamp from metadata dates. Use update date if available, then creation date
if available, or a default if neither are populated."
[c]
(when-let [datestamp (or (date-util/metadata-update-date c)
(date-util/metadata-create-date c)
date-util/parsed-default-date)]
[:gmd:dateStamp
[:gco:DateTime (p/clj-time->date-time-str datestamp)]]))
(defn- generate-metadata-dates
"Returns ISO datestamp and XML elements for Metadata Dates of the given UMM collection.
ParentEntity, rule, and source are required under MD_ExtendedElementInformation, but are just
populated with empty since they are not needed for the Metadata Dates"
[c]
(for [date (:MetadataDates c)]
[:gmd:metadataExtensionInfo
[:gmd:MD_MetadataExtensionInformation
[:gmd:extendedElementInformation
[:gmd:MD_ExtendedElementInformation
[:gmd:name
[:gco:CharacterString (iso/get-iso-metadata-type-name (:Type date))]]
[:gmd:definition
[:gco:CharacterString (get iso/iso-metadata-type-definitions (:Type date))]]
[:gmd:dataType
[:gmd:MD_DatatypeCode
{:codeList ""
:codeListValue ""} "Date"]]
[:gmd:domainValue
[:gco:CharacterString (p/clj-time->date-time-str (:Date date))]]
[:gmd:parentEntity {:gco:nilReason "inapplicable"}]
[:gmd:rule {:gco:nilReason "inapplicable"}]
[:gmd:source {:gco:nilReason "inapplicable"}]]]]]))
(defn iso-topic-value->sanitized-iso-topic-category
"Ensures an uncontrolled IsoTopicCategory value is on the schema-defined list or substitues a
default value."
[category-value]
(get iso-topic-categories category-value "location"))
(defn- generate-doi-for-publication-reference
"Generates the DOI portion of a publication reference."
[pub-ref]
(let [doi (util/remove-nil-keys (:DOI pub-ref))]
(when (seq doi)
[:gmd:identifier
[:gmd:MD_Identifier
[:gmd:code (char-string (:DOI doi))]
[:gmd:description (char-string "DOI")]]])))
(defn- generate-publication-references
"Returns the publication references."
[pub-refs]
(for [pub-ref pub-refs
Title and PublicationDate are required fields in ISO
:when (and (:Title pub-ref) (:PublicationDate pub-ref))]
[:gmd:aggregationInfo
[:gmd:MD_AggregateInformation
[:gmd:aggregateDataSetName
[:gmd:CI_Citation
[:gmd:title (char-string (:Title pub-ref))]
(when (:PublicationDate pub-ref)
[:gmd:date
[:gmd:CI_Date
[:gmd:date
[:gco:Date (second (re-matches #"(\d\d\d\d-\d\d-\d\d)T.*" (str (:PublicationDate pub-ref))))]]
[:gmd:dateType
[:gmd:CI_DateTypeCode
{:codeList (str (:iso iso/code-lists) "#CI_DateTypeCode")
:codeListValue "publication"} "publication"]]]])
[:gmd:edition (char-string (:Edition pub-ref))]
(generate-doi-for-publication-reference pub-ref)
[:gmd:citedResponsibleParty
[:gmd:CI_ResponsibleParty
[:gmd:organisationName (char-string (:Author pub-ref))]
[:gmd:role
[:gmd:CI_RoleCode
{:codeList (str (:ngdc iso/code-lists) "#CI_RoleCode")
:codeListValue "author"} "author"]]]]
[:gmd:citedResponsibleParty
[:gmd:CI_ResponsibleParty
[:gmd:organisationName (char-string (:Publisher pub-ref))]
[:gmd:role
[:gmd:CI_RoleCode
{:codeList (str (:ngdc iso/code-lists) "#CI_RoleCode")
:codeListValue "publisher"} "publication"]]]]
(when-let [online-resource (:OnlineResource pub-ref)]
[:gmd:citedResponsibleParty
[:gmd:CI_ResponsibleParty
[:gmd:contactInfo
[:gmd:CI_Contact
[:gmd:onlineResource
[:gmd:CI_OnlineResource
[:gmd:linkage
[:gmd:URL (:Linkage online-resource)]]
[:gmd:protocol (char-string (:Protocol online-resource))]
[:gmd:applicationProfile (char-string (:ApplicationProfile online-resource))]
(when-let [name (:Name online-resource)]
[:gmd:name (char-string name)])
(when-let [description (:Description online-resource)]
[:gmd:description (char-string (str description " PublicationReference:"))])
[:gmd:function
[:gmd:CI_OnLineFunctionCode
{:codeList (str (:iso iso/code-lists) "#CI_OnLineFunctionCode")
:codeListValue ""} (:Function online-resource)]]]]]]
[:gmd:role
[:gmd:CI_RoleCode
{:codeList (str (:ngdc iso/code-lists) "#CI_RoleCode")
:codeListValue "resourceProvider"} "resourceProvider"]]]])
[:gmd:series
[:gmd:CI_Series
[:gmd:name (char-string (:Series pub-ref))]
[:gmd:issueIdentification (char-string (:Issue pub-ref))]
[:gmd:page (char-string (:Pages pub-ref))]]]
[:gmd:otherCitationDetails (char-string (:OtherReferenceDetails pub-ref))]
[:gmd:ISBN (char-string (:ISBN pub-ref))]]]
[:gmd:associationType
[:gmd:DS_AssociationTypeCode
{:codeList (str (:ngdc iso/code-lists) "#DS_AssociationTypeCode")
:codeListValue "crossReference"} "crossReference"]]]]))
(defn extent-description-string
"Returns the ISO extent description string (a \"key=value,key=value\" string) for the given UMM-C
collection record."
[c]
(let [temporal (first (:TemporalExtents c))
m {"SpatialCoverageType" (-> c :SpatialExtent :SpatialCoverageType)
"SpatialGranuleSpatialRepresentation" (-> c :SpatialExtent :GranuleSpatialRepresentation)
"CoordinateSystem" (-> c :SpatialExtent :HorizontalSpatialDomain :Geometry :CoordinateSystem)}]
(string/join "," (for [[k v] m
:when (some? v)]
(str k "=" (string/replace v #"[,=]" ""))))))
(defn umm-c-to-iso19115-2-xml
"Returns the generated ISO19115-2 xml from UMM collection record c."
[c]
(let [platforms (platform/platforms-with-id (:Platforms c))
{additional-attributes :AdditionalAttributes
abstract :Abstract
version-description :VersionDescription
processing-level :ProcessingLevel} c]
(xml
[:gmi:MI_Metadata
iso19115-2-xml-namespaces
[:gmd:fileIdentifier (char-string (:EntryTitle c))]
[:gmd:language (char-string "eng")]
[:gmd:characterSet
[:gmd:MD_CharacterSetCode {:codeList (str (:ngdc iso/code-lists) "#MD_CharacterSetCode")
:codeListValue "utf8"} "utf8"]]
[:gmd:hierarchyLevel
[:gmd:MD_ScopeCode {:codeList (str (:ngdc iso/code-lists) "#MD_ScopeCode")
:codeListValue "series"} "series"]]
(data-contact/generate-data-center-metadata-author-contact-persons (:DataCenters c))
(data-contact/generate-metadata-author-contact-persons (:ContactPersons c))
(if-let [archive-centers (data-contact/generate-archive-centers (:DataCenters c))]
archive-centers
[:gmd:contact {:gco:nilReason "missing"}])
(generate-datestamp c)
[:gmd:metadataStandardName (char-string "ISO 19115-2 Geographic Information - Metadata Part 2 Extensions for imagery and gridded data")]
[:gmd:metadataStandardVersion (char-string "ISO 19115-2:2009(E)")]
(spatial/generate-spatial-representation-infos c)
(spatial/coordinate-system-element c)
(generate-metadata-dates c)
[:gmd:identificationInfo
[:gmd:MD_DataIdentification
[:gmd:citation
[:gmd:CI_Citation
[:gmd:title (char-string (:EntryTitle c))]
(generate-data-dates c)
[:gmd:edition (char-string (:Version c))]
(collection-citation/convert-date c)
[:gmd:identifier
[:gmd:MD_Identifier
[:gmd:code (char-string (:ShortName c))]
[:gmd:codeSpace (char-string "gov.nasa.esdis.umm.shortname")]
[:gmd:description (char-string "Short Name")]]]
(doi/generate-doi c)
(when-let [collection-data-type (:CollectionDataType c)]
[:gmd:identifier
[:gmd:MD_Identifier
[:gmd:code [:gco:CharacterString collection-data-type]]
[:gmd:codeSpace [:gco:CharacterString "gov.nasa.esdis.umm.collectiondatatype"]]
[:gmd:description [:gco:CharacterString "Collection Data Type"]]]])
(let [standard-product (:StandardProduct c)]
(when (some? standard-product)
[:gmd:identifier
[:gmd:MD_Identifier
[:gmd:code [:gco:CharacterString standard-product]]
[:gmd:codeSpace [:gco:CharacterString "gov.nasa.esdis.umm.standardproduct"]]
[:gmd:description [:gco:CharacterString "Standard Product"]]]]))
(collection-citation/convert-creator c)
(collection-citation/convert-editor c)
(collection-citation/convert-publisher c)
(collection-citation/convert-release-place c)
(collection-citation/convert-online-resource c)
(collection-citation/convert-data-presentation-form c)
(collection-citation/convert-series-name-and-issue-id c)
(collection-citation/convert-other-citation-details c)]]
[:gmd:abstract (char-string (if (or abstract version-description)
(str abstract iso/version-description-separator version-description)
su/not-provided))]
[:gmd:purpose {:gco:nilReason "missing"} (char-string (:Purpose c))]
(collection-progress/generate-collection-progress c)
(data-contact/generate-data-centers (:DataCenters c))
(data-contact/generate-data-center-contact-persons (:DataCenters c))
(data-contact/generate-data-center-contact-groups (:DataCenters c))
(data-contact/generate-contact-persons (:ContactPersons c))
(data-contact/generate-contact-groups (:ContactGroups c))
(sdru/generate-browse-urls c)
(archive-and-dist-info/generate-file-archive-info c)
(generate-projects-keywords (:Projects c))
(kws/generate-iso19115-descriptive-keywords
kws/science-keyword-type (map kws/science-keyword->iso-keyword-string (:ScienceKeywords c)))
(kws/generate-iso19115-descriptive-keywords
kws/location-keyword-type (map kws/location-keyword->iso-keyword-string (:LocationKeywords c)))
(kws/generate-iso19115-descriptive-keywords "temporal" (:TemporalKeywords c))
(kws/generate-iso19115-descriptive-keywords nil (:AncillaryKeywords c))
(platform/generate-platform-keywords platforms)
(platform/generate-instrument-keywords platforms)
(use-constraints/generate-user-constraints c)
(ma/generate-non-source-metadata-associations c)
(generate-publication-references (:PublicationReferences c))
(sdru/generate-publication-related-urls c)
(doi/generate-associated-dois c)
[:gmd:language (char-string (or (:DataLanguage c) "eng"))]
(iso-topic-categories/generate-iso-topic-categories c)
(when (:TilingIdentificationSystems c)
[:gmd:extent
[:gmd:EX_Extent {:id "TilingIdentificationSystem"}
[:gmd:description
[:gco:CharacterString "Tiling Identitfication System"]]
(tiling/tiling-system-elements c)]])
[:gmd:extent
[:gmd:EX_Extent {:id "boundingExtent"}
[:gmd:description
[:gco:CharacterString (extent-description-string c)]]
(spatial/generate-zone-identifier c)
(spatial/spatial-extent-elements c)
(spatial/generate-resolution-and-coordinate-system-description c)
(spatial/generate-resolution-and-coordinate-system-geodetic-model c)
(spatial/generate-resolution-and-coordinate-system-local-coords c)
(spatial/generate-resolution-and-coordinate-system-horizontal-data-resolutions c)
(spatial/generate-vertical-domain c)
(spatial/generate-orbit-parameters c)
(spatial/generate-orbit-parameters-foot-prints c)
(for [temporal (:TemporalExtents c)
rdt (:RangeDateTimes temporal)]
[:gmd:temporalElement
[:gmd:EX_TemporalExtent
[:gmd:extent
[:gml:TimePeriod {:gml:id (su/generate-id)}
[:gml:beginPosition (:BeginningDateTime rdt)]
(if (:EndsAtPresentFlag temporal)
[:gml:endPosition {:indeterminatePosition "now"}]
[:gml:endPosition (su/nil-to-empty-string (:EndingDateTime rdt))])]]]])
(for [temporal (:TemporalExtents c)
date (:SingleDateTimes temporal)]
[:gmd:temporalElement
[:gmd:EX_TemporalExtent
[:gmd:extent
[:gml:TimeInstant {:gml:id (su/generate-id)}
[:gml:timePosition date]]]]])]]
(when processing-level
[:gmd:processingLevel
(proc-level/generate-iso-processing-level processing-level)])]]
(sdru/generate-service-related-url (:RelatedUrls c))
(aa/generate-content-info-additional-attributes additional-attributes)
(when processing-level
[:gmd:contentInfo
[:gmd:MD_ImageDescription
[:gmd:attributeDescription ""]
[:gmd:contentType ""]
[:gmd:processingLevelCode
(proc-level/generate-iso-processing-level processing-level)]]])
(let [related-url-distributions (sdru/generate-distributions c)
file-dist-info-formats (archive-and-dist-info/generate-file-dist-info-formats c)
file-dist-info-medias (archive-and-dist-info/generate-file-dist-info-medias c)
file-dist-info-total-coll-sizes (archive-and-dist-info/generate-file-dist-info-total-coll-sizes c)
file-dist-info-average-sizes (archive-and-dist-info/generate-file-dist-info-average-file-sizes c)
file-dist-info-distributors (archive-and-dist-info/generate-file-dist-info-distributors c)
direct-dist-info (archive-and-dist-info/generate-direct-dist-info-distributors c)]
(when (or file-dist-info-formats
related-url-distributions
file-dist-info-distributors
file-dist-info-medias
file-dist-info-total-coll-sizes
file-dist-info-average-sizes
direct-dist-info)
[:gmd:distributionInfo
[:gmd:MD_Distribution
file-dist-info-formats
related-url-distributions
file-dist-info-distributors
direct-dist-info
file-dist-info-medias
file-dist-info-total-coll-sizes
file-dist-info-average-sizes]]))
[:gmd:dataQualityInfo
[:gmd:DQ_DataQuality
[:gmd:scope
[:gmd:DQ_Scope
[:gmd:level
[:gmd:MD_ScopeCode
{:codeList (str (:ngdc iso/code-lists) "#MD_ScopeCode")
:codeListValue "series"}
"series"]]]]
[:gmd:report
[:gmd:DQ_AccuracyOfATimeMeasurement
[:gmd:measureIdentification
[:gmd:MD_Identifier
[:gmd:code
(char-string "PrecisionOfSeconds")]]]
[:gmd:result
[:gmd:DQ_QuantitativeResult
[:gmd:valueUnit ""]
[:gmd:value
[:gco:Record {:xsi:type "gco:Real_PropertyType"}
[:gco:Real (:PrecisionOfSeconds (first (:TemporalExtents c)))]]]]]]]
(when-let [quality (:Quality c)]
[:gmd:report
[:gmd:DQ_QuantitativeAttributeAccuracy
[:gmd:evaluationMethodDescription (char-string quality)]
[:gmd:result {:gco:nilReason "missing"}]]])
[:gmd:lineage
[:gmd:LI_Lineage
(aa/generate-data-quality-info-additional-attributes additional-attributes)
(when-let [processing-centers (data-contact/generate-processing-centers (:DataCenters c))]
[:gmd:processStep
[:gmd:LI_ProcessStep
[:gmd:description {:gco:nilReason "missing"}]
processing-centers]])
(ma/generate-source-metadata-associations c)]]]]
[:gmi:acquisitionInformation
[:gmi:MI_AcquisitionInformation
(platform/generate-instruments platforms)
(platform/generate-child-instruments platforms)
(project/generate-projects (:Projects c))
(platform/generate-platforms platforms)]]])))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/371be298e3eb9b80041d1ac661d7cde85978012e/umm-spec-lib/src/cmr/umm_spec/umm_to_xml_mappings/iso19115_2.clj | clojure | Use a default value if none present in the UMM record | (ns cmr.umm-spec.umm-to-xml-mappings.iso19115-2
"Defines mappings from UMM records into ISO19115-2 XML."
(:require
[clojure.string :as string]
[cmr.common.date-time-parser :as p]
[cmr.common.util :as util]
[cmr.common.xml.gen :refer :all]
[cmr.umm-spec.date-util :as date-util]
[cmr.umm-spec.iso-keywords :as kws]
[cmr.umm-spec.iso19115-2-util :as iso]
[cmr.umm-spec.location-keywords :as lk]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.archive-and-dist-info :as archive-and-dist-info]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.collection-citation :as collection-citation]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.collection-progress :as collection-progress]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.distributions-related-url :as sdru]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.doi :as doi]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.iso-topic-categories :as iso-topic-categories]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.platform :as platform]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.processing-level :as proc-level]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.project-element :as project]
[cmr.umm-spec.umm-to-xml-mappings.iso-shared.use-constraints :as use-constraints]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.additional-attribute :as aa]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.data-contact :as data-contact]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.metadata-association :as ma]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.spatial :as spatial]
[cmr.umm-spec.umm-to-xml-mappings.iso19115-2.tiling-system :as tiling]
[cmr.umm-spec.util :as su :refer [char-string]]))
(def iso19115-2-xml-namespaces
{:xmlns:eos ""
:xmlns:gco ""
:xmlns:gmd ""
:xmlns:gmi ""
:xmlns:gml ""
:xmlns:gmx ""
:xmlns:gsr ""
:xmlns:gss ""
:xmlns:gts ""
:xmlns:srv ""
:xmlns:xlink ""
:xmlns:xs ""
:xmlns:xsi "-instance"
:xsi:schemaLocation (str " "
" "
" "
" "
" "
" "
" "
" "
" "
" ")})
(def iso-topic-categories
#{"farming"
"biota"
"boundaries"
"climatologyMeteorologyAtmosphere"
"economy"
"elevation"
"environment"
"geoscientificInformation"
"health"
"imageryBaseMapsEarthCover"
"intelligenceMilitary"
"inlandWaters"
"location"
"oceans"
"planningCadastre"
"society"
"structure"
"transportation"
"utilitiesCommunication"})
(defn- generate-projects-keywords
"Returns the content generator instructions for descriptive keywords of the given projects."
[projects]
(let [project-keywords (map iso/generate-title projects)]
(kws/generate-iso19115-descriptive-keywords "project" project-keywords)))
(defn- generate-data-dates
"Returns ISO XML elements for the DataDates of given UMM collection."
[c]
(let [dates (or (:DataDates c) [{:Type "CREATE" :Date date-util/default-date-value}])]
(for [date dates
:let [type-code (get iso/iso-date-type-codes (:Type date))
date-value (or (:Date date) date-util/default-date-value)]]
[:gmd:date
[:gmd:CI_Date
[:gmd:date
[:gco:DateTime date-value]]
[:gmd:dateType
[:gmd:CI_DateTypeCode {:codeList (str (:ngdc iso/code-lists) "#CI_DateTypeCode")
:codeListValue type-code} type-code]]]])))
(defn- generate-datestamp
"Return the ISO datestamp from metadata dates. Use update date if available, then creation date
if available, or a default if neither are populated."
[c]
(when-let [datestamp (or (date-util/metadata-update-date c)
(date-util/metadata-create-date c)
date-util/parsed-default-date)]
[:gmd:dateStamp
[:gco:DateTime (p/clj-time->date-time-str datestamp)]]))
(defn- generate-metadata-dates
"Returns ISO datestamp and XML elements for Metadata Dates of the given UMM collection.
ParentEntity, rule, and source are required under MD_ExtendedElementInformation, but are just
populated with empty since they are not needed for the Metadata Dates"
[c]
(for [date (:MetadataDates c)]
[:gmd:metadataExtensionInfo
[:gmd:MD_MetadataExtensionInformation
[:gmd:extendedElementInformation
[:gmd:MD_ExtendedElementInformation
[:gmd:name
[:gco:CharacterString (iso/get-iso-metadata-type-name (:Type date))]]
[:gmd:definition
[:gco:CharacterString (get iso/iso-metadata-type-definitions (:Type date))]]
[:gmd:dataType
[:gmd:MD_DatatypeCode
{:codeList ""
:codeListValue ""} "Date"]]
[:gmd:domainValue
[:gco:CharacterString (p/clj-time->date-time-str (:Date date))]]
[:gmd:parentEntity {:gco:nilReason "inapplicable"}]
[:gmd:rule {:gco:nilReason "inapplicable"}]
[:gmd:source {:gco:nilReason "inapplicable"}]]]]]))
(defn iso-topic-value->sanitized-iso-topic-category
"Ensures an uncontrolled IsoTopicCategory value is on the schema-defined list or substitues a
default value."
[category-value]
(get iso-topic-categories category-value "location"))
(defn- generate-doi-for-publication-reference
"Generates the DOI portion of a publication reference."
[pub-ref]
(let [doi (util/remove-nil-keys (:DOI pub-ref))]
(when (seq doi)
[:gmd:identifier
[:gmd:MD_Identifier
[:gmd:code (char-string (:DOI doi))]
[:gmd:description (char-string "DOI")]]])))
(defn- generate-publication-references
"Returns the publication references."
[pub-refs]
(for [pub-ref pub-refs
Title and PublicationDate are required fields in ISO
:when (and (:Title pub-ref) (:PublicationDate pub-ref))]
[:gmd:aggregationInfo
[:gmd:MD_AggregateInformation
[:gmd:aggregateDataSetName
[:gmd:CI_Citation
[:gmd:title (char-string (:Title pub-ref))]
(when (:PublicationDate pub-ref)
[:gmd:date
[:gmd:CI_Date
[:gmd:date
[:gco:Date (second (re-matches #"(\d\d\d\d-\d\d-\d\d)T.*" (str (:PublicationDate pub-ref))))]]
[:gmd:dateType
[:gmd:CI_DateTypeCode
{:codeList (str (:iso iso/code-lists) "#CI_DateTypeCode")
:codeListValue "publication"} "publication"]]]])
[:gmd:edition (char-string (:Edition pub-ref))]
(generate-doi-for-publication-reference pub-ref)
[:gmd:citedResponsibleParty
[:gmd:CI_ResponsibleParty
[:gmd:organisationName (char-string (:Author pub-ref))]
[:gmd:role
[:gmd:CI_RoleCode
{:codeList (str (:ngdc iso/code-lists) "#CI_RoleCode")
:codeListValue "author"} "author"]]]]
[:gmd:citedResponsibleParty
[:gmd:CI_ResponsibleParty
[:gmd:organisationName (char-string (:Publisher pub-ref))]
[:gmd:role
[:gmd:CI_RoleCode
{:codeList (str (:ngdc iso/code-lists) "#CI_RoleCode")
:codeListValue "publisher"} "publication"]]]]
(when-let [online-resource (:OnlineResource pub-ref)]
[:gmd:citedResponsibleParty
[:gmd:CI_ResponsibleParty
[:gmd:contactInfo
[:gmd:CI_Contact
[:gmd:onlineResource
[:gmd:CI_OnlineResource
[:gmd:linkage
[:gmd:URL (:Linkage online-resource)]]
[:gmd:protocol (char-string (:Protocol online-resource))]
[:gmd:applicationProfile (char-string (:ApplicationProfile online-resource))]
(when-let [name (:Name online-resource)]
[:gmd:name (char-string name)])
(when-let [description (:Description online-resource)]
[:gmd:description (char-string (str description " PublicationReference:"))])
[:gmd:function
[:gmd:CI_OnLineFunctionCode
{:codeList (str (:iso iso/code-lists) "#CI_OnLineFunctionCode")
:codeListValue ""} (:Function online-resource)]]]]]]
[:gmd:role
[:gmd:CI_RoleCode
{:codeList (str (:ngdc iso/code-lists) "#CI_RoleCode")
:codeListValue "resourceProvider"} "resourceProvider"]]]])
[:gmd:series
[:gmd:CI_Series
[:gmd:name (char-string (:Series pub-ref))]
[:gmd:issueIdentification (char-string (:Issue pub-ref))]
[:gmd:page (char-string (:Pages pub-ref))]]]
[:gmd:otherCitationDetails (char-string (:OtherReferenceDetails pub-ref))]
[:gmd:ISBN (char-string (:ISBN pub-ref))]]]
[:gmd:associationType
[:gmd:DS_AssociationTypeCode
{:codeList (str (:ngdc iso/code-lists) "#DS_AssociationTypeCode")
:codeListValue "crossReference"} "crossReference"]]]]))
(defn extent-description-string
"Returns the ISO extent description string (a \"key=value,key=value\" string) for the given UMM-C
collection record."
[c]
(let [temporal (first (:TemporalExtents c))
m {"SpatialCoverageType" (-> c :SpatialExtent :SpatialCoverageType)
"SpatialGranuleSpatialRepresentation" (-> c :SpatialExtent :GranuleSpatialRepresentation)
"CoordinateSystem" (-> c :SpatialExtent :HorizontalSpatialDomain :Geometry :CoordinateSystem)}]
(string/join "," (for [[k v] m
:when (some? v)]
(str k "=" (string/replace v #"[,=]" ""))))))
(defn umm-c-to-iso19115-2-xml
"Returns the generated ISO19115-2 xml from UMM collection record c."
[c]
(let [platforms (platform/platforms-with-id (:Platforms c))
{additional-attributes :AdditionalAttributes
abstract :Abstract
version-description :VersionDescription
processing-level :ProcessingLevel} c]
(xml
[:gmi:MI_Metadata
iso19115-2-xml-namespaces
[:gmd:fileIdentifier (char-string (:EntryTitle c))]
[:gmd:language (char-string "eng")]
[:gmd:characterSet
[:gmd:MD_CharacterSetCode {:codeList (str (:ngdc iso/code-lists) "#MD_CharacterSetCode")
:codeListValue "utf8"} "utf8"]]
[:gmd:hierarchyLevel
[:gmd:MD_ScopeCode {:codeList (str (:ngdc iso/code-lists) "#MD_ScopeCode")
:codeListValue "series"} "series"]]
(data-contact/generate-data-center-metadata-author-contact-persons (:DataCenters c))
(data-contact/generate-metadata-author-contact-persons (:ContactPersons c))
(if-let [archive-centers (data-contact/generate-archive-centers (:DataCenters c))]
archive-centers
[:gmd:contact {:gco:nilReason "missing"}])
(generate-datestamp c)
[:gmd:metadataStandardName (char-string "ISO 19115-2 Geographic Information - Metadata Part 2 Extensions for imagery and gridded data")]
[:gmd:metadataStandardVersion (char-string "ISO 19115-2:2009(E)")]
(spatial/generate-spatial-representation-infos c)
(spatial/coordinate-system-element c)
(generate-metadata-dates c)
[:gmd:identificationInfo
[:gmd:MD_DataIdentification
[:gmd:citation
[:gmd:CI_Citation
[:gmd:title (char-string (:EntryTitle c))]
(generate-data-dates c)
[:gmd:edition (char-string (:Version c))]
(collection-citation/convert-date c)
[:gmd:identifier
[:gmd:MD_Identifier
[:gmd:code (char-string (:ShortName c))]
[:gmd:codeSpace (char-string "gov.nasa.esdis.umm.shortname")]
[:gmd:description (char-string "Short Name")]]]
(doi/generate-doi c)
(when-let [collection-data-type (:CollectionDataType c)]
[:gmd:identifier
[:gmd:MD_Identifier
[:gmd:code [:gco:CharacterString collection-data-type]]
[:gmd:codeSpace [:gco:CharacterString "gov.nasa.esdis.umm.collectiondatatype"]]
[:gmd:description [:gco:CharacterString "Collection Data Type"]]]])
(let [standard-product (:StandardProduct c)]
(when (some? standard-product)
[:gmd:identifier
[:gmd:MD_Identifier
[:gmd:code [:gco:CharacterString standard-product]]
[:gmd:codeSpace [:gco:CharacterString "gov.nasa.esdis.umm.standardproduct"]]
[:gmd:description [:gco:CharacterString "Standard Product"]]]]))
(collection-citation/convert-creator c)
(collection-citation/convert-editor c)
(collection-citation/convert-publisher c)
(collection-citation/convert-release-place c)
(collection-citation/convert-online-resource c)
(collection-citation/convert-data-presentation-form c)
(collection-citation/convert-series-name-and-issue-id c)
(collection-citation/convert-other-citation-details c)]]
[:gmd:abstract (char-string (if (or abstract version-description)
(str abstract iso/version-description-separator version-description)
su/not-provided))]
[:gmd:purpose {:gco:nilReason "missing"} (char-string (:Purpose c))]
(collection-progress/generate-collection-progress c)
(data-contact/generate-data-centers (:DataCenters c))
(data-contact/generate-data-center-contact-persons (:DataCenters c))
(data-contact/generate-data-center-contact-groups (:DataCenters c))
(data-contact/generate-contact-persons (:ContactPersons c))
(data-contact/generate-contact-groups (:ContactGroups c))
(sdru/generate-browse-urls c)
(archive-and-dist-info/generate-file-archive-info c)
(generate-projects-keywords (:Projects c))
(kws/generate-iso19115-descriptive-keywords
kws/science-keyword-type (map kws/science-keyword->iso-keyword-string (:ScienceKeywords c)))
(kws/generate-iso19115-descriptive-keywords
kws/location-keyword-type (map kws/location-keyword->iso-keyword-string (:LocationKeywords c)))
(kws/generate-iso19115-descriptive-keywords "temporal" (:TemporalKeywords c))
(kws/generate-iso19115-descriptive-keywords nil (:AncillaryKeywords c))
(platform/generate-platform-keywords platforms)
(platform/generate-instrument-keywords platforms)
(use-constraints/generate-user-constraints c)
(ma/generate-non-source-metadata-associations c)
(generate-publication-references (:PublicationReferences c))
(sdru/generate-publication-related-urls c)
(doi/generate-associated-dois c)
[:gmd:language (char-string (or (:DataLanguage c) "eng"))]
(iso-topic-categories/generate-iso-topic-categories c)
(when (:TilingIdentificationSystems c)
[:gmd:extent
[:gmd:EX_Extent {:id "TilingIdentificationSystem"}
[:gmd:description
[:gco:CharacterString "Tiling Identitfication System"]]
(tiling/tiling-system-elements c)]])
[:gmd:extent
[:gmd:EX_Extent {:id "boundingExtent"}
[:gmd:description
[:gco:CharacterString (extent-description-string c)]]
(spatial/generate-zone-identifier c)
(spatial/spatial-extent-elements c)
(spatial/generate-resolution-and-coordinate-system-description c)
(spatial/generate-resolution-and-coordinate-system-geodetic-model c)
(spatial/generate-resolution-and-coordinate-system-local-coords c)
(spatial/generate-resolution-and-coordinate-system-horizontal-data-resolutions c)
(spatial/generate-vertical-domain c)
(spatial/generate-orbit-parameters c)
(spatial/generate-orbit-parameters-foot-prints c)
(for [temporal (:TemporalExtents c)
rdt (:RangeDateTimes temporal)]
[:gmd:temporalElement
[:gmd:EX_TemporalExtent
[:gmd:extent
[:gml:TimePeriod {:gml:id (su/generate-id)}
[:gml:beginPosition (:BeginningDateTime rdt)]
(if (:EndsAtPresentFlag temporal)
[:gml:endPosition {:indeterminatePosition "now"}]
[:gml:endPosition (su/nil-to-empty-string (:EndingDateTime rdt))])]]]])
(for [temporal (:TemporalExtents c)
date (:SingleDateTimes temporal)]
[:gmd:temporalElement
[:gmd:EX_TemporalExtent
[:gmd:extent
[:gml:TimeInstant {:gml:id (su/generate-id)}
[:gml:timePosition date]]]]])]]
(when processing-level
[:gmd:processingLevel
(proc-level/generate-iso-processing-level processing-level)])]]
(sdru/generate-service-related-url (:RelatedUrls c))
(aa/generate-content-info-additional-attributes additional-attributes)
(when processing-level
[:gmd:contentInfo
[:gmd:MD_ImageDescription
[:gmd:attributeDescription ""]
[:gmd:contentType ""]
[:gmd:processingLevelCode
(proc-level/generate-iso-processing-level processing-level)]]])
(let [related-url-distributions (sdru/generate-distributions c)
file-dist-info-formats (archive-and-dist-info/generate-file-dist-info-formats c)
file-dist-info-medias (archive-and-dist-info/generate-file-dist-info-medias c)
file-dist-info-total-coll-sizes (archive-and-dist-info/generate-file-dist-info-total-coll-sizes c)
file-dist-info-average-sizes (archive-and-dist-info/generate-file-dist-info-average-file-sizes c)
file-dist-info-distributors (archive-and-dist-info/generate-file-dist-info-distributors c)
direct-dist-info (archive-and-dist-info/generate-direct-dist-info-distributors c)]
(when (or file-dist-info-formats
related-url-distributions
file-dist-info-distributors
file-dist-info-medias
file-dist-info-total-coll-sizes
file-dist-info-average-sizes
direct-dist-info)
[:gmd:distributionInfo
[:gmd:MD_Distribution
file-dist-info-formats
related-url-distributions
file-dist-info-distributors
direct-dist-info
file-dist-info-medias
file-dist-info-total-coll-sizes
file-dist-info-average-sizes]]))
[:gmd:dataQualityInfo
[:gmd:DQ_DataQuality
[:gmd:scope
[:gmd:DQ_Scope
[:gmd:level
[:gmd:MD_ScopeCode
{:codeList (str (:ngdc iso/code-lists) "#MD_ScopeCode")
:codeListValue "series"}
"series"]]]]
[:gmd:report
[:gmd:DQ_AccuracyOfATimeMeasurement
[:gmd:measureIdentification
[:gmd:MD_Identifier
[:gmd:code
(char-string "PrecisionOfSeconds")]]]
[:gmd:result
[:gmd:DQ_QuantitativeResult
[:gmd:valueUnit ""]
[:gmd:value
[:gco:Record {:xsi:type "gco:Real_PropertyType"}
[:gco:Real (:PrecisionOfSeconds (first (:TemporalExtents c)))]]]]]]]
(when-let [quality (:Quality c)]
[:gmd:report
[:gmd:DQ_QuantitativeAttributeAccuracy
[:gmd:evaluationMethodDescription (char-string quality)]
[:gmd:result {:gco:nilReason "missing"}]]])
[:gmd:lineage
[:gmd:LI_Lineage
(aa/generate-data-quality-info-additional-attributes additional-attributes)
(when-let [processing-centers (data-contact/generate-processing-centers (:DataCenters c))]
[:gmd:processStep
[:gmd:LI_ProcessStep
[:gmd:description {:gco:nilReason "missing"}]
processing-centers]])
(ma/generate-source-metadata-associations c)]]]]
[:gmi:acquisitionInformation
[:gmi:MI_AcquisitionInformation
(platform/generate-instruments platforms)
(platform/generate-child-instruments platforms)
(project/generate-projects (:Projects c))
(platform/generate-platforms platforms)]]])))
|
f4e911c51ed3dcf7eddd98d8f034f1268963d402a33f6fafd3e4a1235ad8ae9d | amnh/ocamion | bench.mli | (** {1 Bench}
Benchmark a function against optimization methods. Currently this supports
the multi-dimensional numerical optimization routines, thus this may change
to unify with combinatorial functions. *)
(** {2 Types} *)
(** Define the columns to report data. The default columns are the name of the
method, sample size [n], stddev and mean of both time and results.*)
type columns =
[ `N | `Name | `Result_Mean | `Result_StdDev | `Time_Mean | `Time_StdDev
| `Result_Skew | `Time_Skew | `Result_Kurt | `Time_Kurt | `Time_Var
| `Result_Var | `Time_Min | `Time_Max | `Result_Min | `Result_Max ]
* { 2 Benchmark Functions }
(** Benchmark the function [f] with all the numerical methods provided in
[MultiOptimize.all]. The [bench] function returns a list of triples of the
method name, a function timing summary, and a function result summary.
Timing an abstraction of computational time by the number of function calls.
This thus assumes that each call to [f] is approximately equal. The result
summary will show the distribution of results of each optimization round.
Many of the routines have extra data attached to the result of [f], here is
is not necessary, but to continue with that framework it is in the signature
here. Use [unit_wrapper] to fit a float result function. *)
val bench :
d:int -> range:float * float -> n:int -> f:(float array -> 'a * float) ->
(string * (Pareto.Sample.Summary.t * Pareto.Sample.Summary.t)) list
(** Generate a matrix of strings of the summaries against a list of columns to report. *)
val bench_table :
?columns:columns list ->
(string * (Pareto.Sample.Summary.t * Pareto.Sample.Summary.t)) list -> string array array
(** Output the benchmark table. *)
val output_bench : channel:out_channel -> string array array -> unit
(** Do a full set of operations to output benchmark details. Use default columns. *)
val report :
d:int -> range:float * float -> n:int -> f:(float array -> 'a * float) ->
channel:out_channel -> unit
| null | https://raw.githubusercontent.com/amnh/ocamion/699c2471b7fdac12f061cf24b588f9eef5bf5cb8/lib/bench.mli | ocaml | * {1 Bench}
Benchmark a function against optimization methods. Currently this supports
the multi-dimensional numerical optimization routines, thus this may change
to unify with combinatorial functions.
* {2 Types}
* Define the columns to report data. The default columns are the name of the
method, sample size [n], stddev and mean of both time and results.
* Benchmark the function [f] with all the numerical methods provided in
[MultiOptimize.all]. The [bench] function returns a list of triples of the
method name, a function timing summary, and a function result summary.
Timing an abstraction of computational time by the number of function calls.
This thus assumes that each call to [f] is approximately equal. The result
summary will show the distribution of results of each optimization round.
Many of the routines have extra data attached to the result of [f], here is
is not necessary, but to continue with that framework it is in the signature
here. Use [unit_wrapper] to fit a float result function.
* Generate a matrix of strings of the summaries against a list of columns to report.
* Output the benchmark table.
* Do a full set of operations to output benchmark details. Use default columns. |
type columns =
[ `N | `Name | `Result_Mean | `Result_StdDev | `Time_Mean | `Time_StdDev
| `Result_Skew | `Time_Skew | `Result_Kurt | `Time_Kurt | `Time_Var
| `Result_Var | `Time_Min | `Time_Max | `Result_Min | `Result_Max ]
* { 2 Benchmark Functions }
val bench :
d:int -> range:float * float -> n:int -> f:(float array -> 'a * float) ->
(string * (Pareto.Sample.Summary.t * Pareto.Sample.Summary.t)) list
val bench_table :
?columns:columns list ->
(string * (Pareto.Sample.Summary.t * Pareto.Sample.Summary.t)) list -> string array array
val output_bench : channel:out_channel -> string array array -> unit
val report :
d:int -> range:float * float -> n:int -> f:(float array -> 'a * float) ->
channel:out_channel -> unit
|
2ead18eca5c654b0f51e4747894314f81dc0a02a76e1441a1f0c0118d1625338 | konfig-xyz/rust-reason-parser | ConfigurationParser.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module ConfigurationParser (makeConfig) where
import Data.Bifunctor (first)
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Yaml.Config (Config, keys, load, lookup, lookupDefault,
subconfig)
import Helpers (parseTypeSplitBy)
import qualified Types as T
parseTypeMapConfiguration :: T.Text -> Maybe (T.Text, T.Text)
parseTypeMapConfiguration = parseTypeSplitBy "->"
toTypeMap :: [T.Text] -> T.Mapping
toTypeMap = M.fromList . mapMaybe parseTypeMapConfiguration
toQualified :: Config -> T.HiddenQualified
toQualified xs = M.fromList $ map (\k -> (k, S.fromList $ lookupDefault k [] xs)) (keys xs)
toPPXs :: [T.Text] -> [T.Text]
toPPXs = map (\x -> "[@" <> x <> "]\n")
makeConfig :: String -> IO T.Configuration
makeConfig path = do
config <- load path
types <- subconfig "types" config
hiding <- subconfig "hiding" config
annotations <- subconfig "annotations" config
qualified <- subconfig "qualified" hiding
pure $
T.Configuration
(toPPXs $ lookupDefault "alias-ppx" [] annotations)
(toPPXs $ lookupDefault "type-ppx" [] annotations)
(toPPXs $ lookupDefault "containerized-ppx" [] annotations)
(toTypeMap $ lookupDefault "aliases" [] types)
(toTypeMap $ lookupDefault "containerized" [] types)
(toTypeMap $ lookupDefault "base" [] types)
(toTypeMap $ lookupDefault "nested" [] types)
(toTypeMap $ lookupDefault "qualified" [] types)
(S.fromList $ lookupDefault "tables" [] hiding)
(S.fromList $ lookupDefault "keys" [] hiding)
(toQualified qualified)
| null | https://raw.githubusercontent.com/konfig-xyz/rust-reason-parser/71b7d79bca485e0c67835ec477dbf9760746385f/src/ConfigurationParser.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE ScopedTypeVariables #
module ConfigurationParser (makeConfig) where
import Data.Bifunctor (first)
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Yaml.Config (Config, keys, load, lookup, lookupDefault,
subconfig)
import Helpers (parseTypeSplitBy)
import qualified Types as T
parseTypeMapConfiguration :: T.Text -> Maybe (T.Text, T.Text)
parseTypeMapConfiguration = parseTypeSplitBy "->"
toTypeMap :: [T.Text] -> T.Mapping
toTypeMap = M.fromList . mapMaybe parseTypeMapConfiguration
toQualified :: Config -> T.HiddenQualified
toQualified xs = M.fromList $ map (\k -> (k, S.fromList $ lookupDefault k [] xs)) (keys xs)
toPPXs :: [T.Text] -> [T.Text]
toPPXs = map (\x -> "[@" <> x <> "]\n")
makeConfig :: String -> IO T.Configuration
makeConfig path = do
config <- load path
types <- subconfig "types" config
hiding <- subconfig "hiding" config
annotations <- subconfig "annotations" config
qualified <- subconfig "qualified" hiding
pure $
T.Configuration
(toPPXs $ lookupDefault "alias-ppx" [] annotations)
(toPPXs $ lookupDefault "type-ppx" [] annotations)
(toPPXs $ lookupDefault "containerized-ppx" [] annotations)
(toTypeMap $ lookupDefault "aliases" [] types)
(toTypeMap $ lookupDefault "containerized" [] types)
(toTypeMap $ lookupDefault "base" [] types)
(toTypeMap $ lookupDefault "nested" [] types)
(toTypeMap $ lookupDefault "qualified" [] types)
(S.fromList $ lookupDefault "tables" [] hiding)
(S.fromList $ lookupDefault "keys" [] hiding)
(toQualified qualified)
|
cc64b190a23ee353f1f4d4193410505952054f8ed9175705210459f29b738a1f | google/btls | DigestTests.hs | Copyright 2017 Google 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.
module Data.DigestTests (tests) where
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit ((@?), testCase)
import Data.Digest (md5, sha1, sha224, sha256, sha384, sha512)
import qualified Data.Digest.MD5Tests
import qualified Data.Digest.SHA1Tests
import qualified Data.Digest.SHA2Tests
tests :: TestTree
tests = testGroup "Data.Digest"
[ showTests
, Data.Digest.MD5Tests.tests
, Data.Digest.SHA1Tests.tests
, Data.Digest.SHA2Tests.tests ]
showTests = testGroup "show"
[ testNonEmpty "MD5" (show md5)
, testNonEmpty "SHA-1" (show sha1)
, testNonEmpty "SHA-224" (show sha224)
, testNonEmpty "SHA-256" (show sha256)
, testNonEmpty "SHA-384" (show sha384)
, testNonEmpty "SHA-512" (show sha512) ]
where
testNonEmpty description string = testCase description $
not (null string) @? "expected: nonempty string\n but got: " ++ show string
| null | https://raw.githubusercontent.com/google/btls/6de13194f15468b186fe62d089b3a7189795c704/tests/Data/DigestTests.hs | haskell |
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
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 2017 Google LLC
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
module Data.DigestTests (tests) where
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit ((@?), testCase)
import Data.Digest (md5, sha1, sha224, sha256, sha384, sha512)
import qualified Data.Digest.MD5Tests
import qualified Data.Digest.SHA1Tests
import qualified Data.Digest.SHA2Tests
tests :: TestTree
tests = testGroup "Data.Digest"
[ showTests
, Data.Digest.MD5Tests.tests
, Data.Digest.SHA1Tests.tests
, Data.Digest.SHA2Tests.tests ]
showTests = testGroup "show"
[ testNonEmpty "MD5" (show md5)
, testNonEmpty "SHA-1" (show sha1)
, testNonEmpty "SHA-224" (show sha224)
, testNonEmpty "SHA-256" (show sha256)
, testNonEmpty "SHA-384" (show sha384)
, testNonEmpty "SHA-512" (show sha512) ]
where
testNonEmpty description string = testCase description $
not (null string) @? "expected: nonempty string\n but got: " ++ show string
|
a8e686a10ddc8ecc38767951d0bbe96c6d76d9de7819f5de7cbc5520bf64acd1 | basho/machi | machi_proxy_flu1_client_test.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2007 - 2015 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(machi_proxy_flu1_client_test).
-compile(export_all).
-include("machi.hrl").
-include("machi_projection.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(MUT, machi_proxy_flu1_client).
-ifdef(TEST).
-ifndef(PULSE).
api_smoke_test() ->
RegName = api_smoke_flu,
TcpPort = 17124,
DataDir = "./data.api_smoke_flu",
W_props = [{active_mode, false},{initial_wedged, false}],
Prefix = <<"prefix">>,
NSInfo = undefined,
NoCSum = <<>>,
try
{[I], _, _} = machi_test_util:start_flu_package(
RegName, TcpPort, DataDir, W_props),
{ok, Prox1} = ?MUT:start_link(I),
try
FakeEpoch = ?DUMMY_PV1_EPOCH,
[{ok, {_,_,_}} = ?MUT:append_chunk(
Prox1, NSInfo, FakeEpoch,
Prefix, <<"data">>, NoCSum) ||
_ <- lists:seq(1,5)],
Stop the , what happens ?
machi_test_util:stop_flu_package(),
[{error,partition} = ?MUT:append_chunk(Prox1, NSInfo,
FakeEpoch, Prefix, <<"data-stopped1">>,
NoCSum) || _ <- lists:seq(1,3)],
Start the again , we should be able to do stuff immediately
machi_test_util:start_flu_package(RegName, TcpPort, DataDir,
[no_cleanup|W_props]),
MyChunk = <<"my chunk data">>,
{ok, {MyOff,MySize,MyFile}} =
?MUT:append_chunk(Prox1, NSInfo, FakeEpoch, Prefix, MyChunk,
NoCSum),
{ok, {[{_, MyOff, MyChunk, _MyChunkCSUM}], []}} =
?MUT:read_chunk(Prox1, NSInfo, FakeEpoch, MyFile, MyOff, MySize, undefined),
MyChunk2_parts = [<<"my chunk ">>, "data", <<", yeah, again">>],
MyChunk2 = iolist_to_binary(MyChunk2_parts),
Opts1 = #append_opts{chunk_extra=4242},
{ok, {MyOff2,MySize2,MyFile2}} =
?MUT:append_chunk(Prox1, NSInfo, FakeEpoch, Prefix,
MyChunk2_parts, NoCSum, Opts1, infinity),
[{ok, {[{_, MyOff2, MyChunk2, _}], []}} =
?MUT:read_chunk(Prox1, NSInfo, FakeEpoch, MyFile2, MyOff2, MySize2, DefaultOptions) ||
DefaultOptions <- [undefined, noopt, none, any_atom_at_all] ],
BadCSum = {?CSUM_TAG_CLIENT_SHA, crypto:hash(sha, "...................")},
{error, bad_checksum} = ?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
Prefix, MyChunk, BadCSum),
{error, bad_checksum} = ?MUT:write_chunk(Prox1, NSInfo, FakeEpoch,
MyFile2,
MyOff2 + size(MyChunk2),
MyChunk, BadCSum,
infinity),
%% Put kick_projection_reaction() in the middle of the test so
%% that any problems with its async nature will (hopefully)
%% cause problems later in the test.
ok = ?MUT:kick_projection_reaction(Prox1, []),
%% Alright, now for the rest of the API, whee
BadFile = <<"no-such-file">>,
{error, bad_arg} = ?MUT:checksum_list(Prox1, BadFile),
{ok, [_|_]} = ?MUT:list_files(Prox1, FakeEpoch),
{ok, {false, _,_,_}} = ?MUT:wedge_status(Prox1),
{ok, {0, _SomeCSum}} = ?MUT:get_latest_epochid(Prox1, public),
{ok, #projection_v1{epoch_number=0}} =
?MUT:read_latest_projection(Prox1, public),
{error, not_written} = ?MUT:read_projection(Prox1, public, 44),
P_a = #p_srvr{name=a, address="localhost", port=6622},
P1 = machi_projection:new(1, a, [P_a], [], [a], [], []),
ok = ?MUT:write_projection(Prox1, public, P1),
{ok, P1} = ?MUT:read_projection(Prox1, public, 1),
{ok, [#projection_v1{epoch_number=0},P1]} =
?MUT:get_all_projections(Prox1, public),
{ok, [0,1]} = ?MUT:list_all_projections(Prox1, public),
ok
after
_ = (catch ?MUT:quit(Prox1))
end
after
(catch machi_test_util:stop_flu_package())
end.
flu_restart_test_() ->
{timeout, 1*60, fun() -> flu_restart_test2() end}.
flu_restart_test2() ->
RegName = a,
TcpPort = 17125,
DataDir = "./data.api_smoke_flu2",
W_props = [{initial_wedged, false}, {active_mode, false}],
NSInfo = undefined,
NoCSum = <<>>,
try
{[I], _, _} = machi_test_util:start_flu_package(
RegName, TcpPort, DataDir, W_props),
{ok, Prox1} = ?MUT:start_link(I),
try
FakeEpoch = ?DUMMY_PV1_EPOCH,
Data = <<"data!">>,
Dataxx = <<"Fake!">>,
{ok, {Off1,Size1,File1}} = ?MUT:append_chunk(Prox1, NSInfo,
FakeEpoch, <<"prefix">>, Data, NoCSum),
P_a = #p_srvr{name=a, address="localhost", port=6622},
P1 = machi_projection:new(1, RegName, [P_a], [], [RegName], [], []),
P1xx = P1#projection_v1{dbg2=["dbg2 changes are ok"]},
P1yy = P1#projection_v1{dbg=["not exactly the same as P1!!!"]},
EpochID = {P1#projection_v1.epoch_number,
P1#projection_v1.epoch_csum},
ok = ?MUT:write_projection(Prox1, public, P1),
ok = ?MUT:write_projection(Prox1, private, P1),
{ok, EpochID} = ?MUT:get_epoch_id(Prox1),
{ok, EpochID} = ?MUT:get_latest_epochid(Prox1, public),
{ok, EpochID} = ?MUT:get_latest_epochid(Prox1, private),
ok = machi_test_util:stop_flu_package(), timer:sleep(50),
%% Now that the last proxy op was successful and only
after did we stop the FLU , let 's check that both the
1st & 2nd ops - via - proxy after FLU is restarted are
successful . And immediately after stopping the FLU ,
both 1st & 2nd ops - via - proxy should always fail .
%%
%% Some of the expectations have unbound variables, which
%% makes the code a bit convoluted. (No LFE or
%% Elixir macros here, alas, they'd be useful.)
AppendOpts1 = #append_opts{chunk_extra=42},
ExpectedOps =
[
fun(run) -> ?assertEqual({ok, EpochID}, ?MUT:get_epoch_id(Prox1)),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_epoch_id(Prox1) end,
fun(run) -> {ok, EpochID} =
?MUT:get_latest_epochid(Prox1, public),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_latest_epochid(Prox1, public)
end,
fun(run) -> {ok, EpochID} =
?MUT:get_latest_epochid(Prox1, private),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_latest_epochid(Prox1, private)
end,
fun(run) -> {ok, P1} =
?MUT:read_projection(Prox1, public, 1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:read_projection(Prox1, public, 1)
end,
fun(run) -> {ok, P1} =
?MUT:read_projection(Prox1, private, 1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:read_projection(Prox1, private, 1)
end,
fun(run) -> {error, not_written} =
?MUT:read_projection(Prox1, private, 7),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:read_projection(Prox1, private, 7)
end,
fun(run) -> ok =
?MUT:write_projection(Prox1, public, P1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, public, P1)
end,
fun(run) -> ok =
?MUT:write_projection(Prox1, private, P1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, private, P1)
end,
fun(run) -> {error, written} =
?MUT:write_projection(Prox1, public, P1xx),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, public, P1xx)
end,
P1xx is difference only in dbg2
?MUT:write_projection(Prox1, private, P1xx),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, private, P1xx)
end,
fun(run) -> {error, bad_arg} = % P1yy has got bad checksum
?MUT:write_projection(Prox1, private, P1yy),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, private, P1yy)
end,
fun(run) -> {ok, [#projection_v1{epoch_number=0}, #projection_v1{epoch_number=1}]} =
?MUT:get_all_projections(Prox1, public),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_all_projections(Prox1, public)
end,
fun(run) -> {ok, [#projection_v1{epoch_number=0}, #projection_v1{epoch_number=1}]} =
?MUT:get_all_projections(Prox1, private),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_all_projections(Prox1, private)
end,
fun(run) -> {ok, {_,_,_}} =
?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
<<"prefix">>, Data, NoCSum),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
<<"prefix">>, Data, NoCSum)
end,
fun(run) -> {ok, {_,_,_}} =
?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
<<"prefix">>, Data, NoCSum,
AppendOpts1, infinity),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
<<"prefix">>, Data, NoCSum,
AppendOpts1, infinity)
end,
fun(run) -> {ok, {[{_, Off1, Data, _}], []}} =
?MUT:read_chunk(Prox1, NSInfo, FakeEpoch,
File1, Off1, Size1, undefined),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:read_chunk(Prox1, NSInfo, FakeEpoch,
File1, Off1, Size1, undefined)
end,
fun(run) -> {ok, KludgeBin} =
?MUT:checksum_list(Prox1, File1),
true = is_binary(KludgeBin),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:checksum_list(Prox1, File1)
end,
fun(run) -> {ok, _} =
?MUT:list_files(Prox1, FakeEpoch),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:list_files(Prox1, FakeEpoch)
end,
fun(run) -> {ok, _} =
?MUT:wedge_status(Prox1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:wedge_status(Prox1)
end,
fun(run) ->
ok =
?MUT:write_chunk(Prox1, NSInfo, FakeEpoch, File1, Off1,
Data, NoCSum, infinity),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_chunk(Prox1, NSInfo, FakeEpoch, File1, Off1,
Data, NoCSum, infinity)
end,
fun(run) ->
{error, written} =
?MUT:write_chunk(Prox1, NSInfo, FakeEpoch, File1, Off1,
Dataxx, NoCSum, infinity),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_chunk(Prox1, NSInfo, FakeEpoch, File1, Off1,
Dataxx, NoCSum, infinity)
end
],
[begin
machi_test_util:start_flu_package(
RegName, TcpPort, DataDir,
[no_cleanup|W_props]),
_ = Fun(line),
ok = Fun(run),
ok = Fun(run),
ok = machi_test_util:stop_flu_package(),
{error, partition} = Fun(stop),
{error, partition} = Fun(stop),
ok
end || Fun <- ExpectedOps ],
ok
after
_ = (catch ?MUT:quit(Prox1))
end
after
(catch machi_test_util:stop_flu_package())
end.
-endif. % !PULSE
-endif. % TEST
| null | https://raw.githubusercontent.com/basho/machi/e87bd59a9777d805b00f9e9981467eb28e28390c/test/machi_proxy_flu1_client_test.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
Put kick_projection_reaction() in the middle of the test so
that any problems with its async nature will (hopefully)
cause problems later in the test.
Alright, now for the rest of the API, whee
Now that the last proxy op was successful and only
Some of the expectations have unbound variables, which
makes the code a bit convoluted. (No LFE or
Elixir macros here, alas, they'd be useful.)
P1yy has got bad checksum
!PULSE
TEST | Copyright ( c ) 2007 - 2015 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(machi_proxy_flu1_client_test).
-compile(export_all).
-include("machi.hrl").
-include("machi_projection.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(MUT, machi_proxy_flu1_client).
-ifdef(TEST).
-ifndef(PULSE).
api_smoke_test() ->
RegName = api_smoke_flu,
TcpPort = 17124,
DataDir = "./data.api_smoke_flu",
W_props = [{active_mode, false},{initial_wedged, false}],
Prefix = <<"prefix">>,
NSInfo = undefined,
NoCSum = <<>>,
try
{[I], _, _} = machi_test_util:start_flu_package(
RegName, TcpPort, DataDir, W_props),
{ok, Prox1} = ?MUT:start_link(I),
try
FakeEpoch = ?DUMMY_PV1_EPOCH,
[{ok, {_,_,_}} = ?MUT:append_chunk(
Prox1, NSInfo, FakeEpoch,
Prefix, <<"data">>, NoCSum) ||
_ <- lists:seq(1,5)],
Stop the , what happens ?
machi_test_util:stop_flu_package(),
[{error,partition} = ?MUT:append_chunk(Prox1, NSInfo,
FakeEpoch, Prefix, <<"data-stopped1">>,
NoCSum) || _ <- lists:seq(1,3)],
Start the again , we should be able to do stuff immediately
machi_test_util:start_flu_package(RegName, TcpPort, DataDir,
[no_cleanup|W_props]),
MyChunk = <<"my chunk data">>,
{ok, {MyOff,MySize,MyFile}} =
?MUT:append_chunk(Prox1, NSInfo, FakeEpoch, Prefix, MyChunk,
NoCSum),
{ok, {[{_, MyOff, MyChunk, _MyChunkCSUM}], []}} =
?MUT:read_chunk(Prox1, NSInfo, FakeEpoch, MyFile, MyOff, MySize, undefined),
MyChunk2_parts = [<<"my chunk ">>, "data", <<", yeah, again">>],
MyChunk2 = iolist_to_binary(MyChunk2_parts),
Opts1 = #append_opts{chunk_extra=4242},
{ok, {MyOff2,MySize2,MyFile2}} =
?MUT:append_chunk(Prox1, NSInfo, FakeEpoch, Prefix,
MyChunk2_parts, NoCSum, Opts1, infinity),
[{ok, {[{_, MyOff2, MyChunk2, _}], []}} =
?MUT:read_chunk(Prox1, NSInfo, FakeEpoch, MyFile2, MyOff2, MySize2, DefaultOptions) ||
DefaultOptions <- [undefined, noopt, none, any_atom_at_all] ],
BadCSum = {?CSUM_TAG_CLIENT_SHA, crypto:hash(sha, "...................")},
{error, bad_checksum} = ?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
Prefix, MyChunk, BadCSum),
{error, bad_checksum} = ?MUT:write_chunk(Prox1, NSInfo, FakeEpoch,
MyFile2,
MyOff2 + size(MyChunk2),
MyChunk, BadCSum,
infinity),
ok = ?MUT:kick_projection_reaction(Prox1, []),
BadFile = <<"no-such-file">>,
{error, bad_arg} = ?MUT:checksum_list(Prox1, BadFile),
{ok, [_|_]} = ?MUT:list_files(Prox1, FakeEpoch),
{ok, {false, _,_,_}} = ?MUT:wedge_status(Prox1),
{ok, {0, _SomeCSum}} = ?MUT:get_latest_epochid(Prox1, public),
{ok, #projection_v1{epoch_number=0}} =
?MUT:read_latest_projection(Prox1, public),
{error, not_written} = ?MUT:read_projection(Prox1, public, 44),
P_a = #p_srvr{name=a, address="localhost", port=6622},
P1 = machi_projection:new(1, a, [P_a], [], [a], [], []),
ok = ?MUT:write_projection(Prox1, public, P1),
{ok, P1} = ?MUT:read_projection(Prox1, public, 1),
{ok, [#projection_v1{epoch_number=0},P1]} =
?MUT:get_all_projections(Prox1, public),
{ok, [0,1]} = ?MUT:list_all_projections(Prox1, public),
ok
after
_ = (catch ?MUT:quit(Prox1))
end
after
(catch machi_test_util:stop_flu_package())
end.
flu_restart_test_() ->
{timeout, 1*60, fun() -> flu_restart_test2() end}.
flu_restart_test2() ->
RegName = a,
TcpPort = 17125,
DataDir = "./data.api_smoke_flu2",
W_props = [{initial_wedged, false}, {active_mode, false}],
NSInfo = undefined,
NoCSum = <<>>,
try
{[I], _, _} = machi_test_util:start_flu_package(
RegName, TcpPort, DataDir, W_props),
{ok, Prox1} = ?MUT:start_link(I),
try
FakeEpoch = ?DUMMY_PV1_EPOCH,
Data = <<"data!">>,
Dataxx = <<"Fake!">>,
{ok, {Off1,Size1,File1}} = ?MUT:append_chunk(Prox1, NSInfo,
FakeEpoch, <<"prefix">>, Data, NoCSum),
P_a = #p_srvr{name=a, address="localhost", port=6622},
P1 = machi_projection:new(1, RegName, [P_a], [], [RegName], [], []),
P1xx = P1#projection_v1{dbg2=["dbg2 changes are ok"]},
P1yy = P1#projection_v1{dbg=["not exactly the same as P1!!!"]},
EpochID = {P1#projection_v1.epoch_number,
P1#projection_v1.epoch_csum},
ok = ?MUT:write_projection(Prox1, public, P1),
ok = ?MUT:write_projection(Prox1, private, P1),
{ok, EpochID} = ?MUT:get_epoch_id(Prox1),
{ok, EpochID} = ?MUT:get_latest_epochid(Prox1, public),
{ok, EpochID} = ?MUT:get_latest_epochid(Prox1, private),
ok = machi_test_util:stop_flu_package(), timer:sleep(50),
after did we stop the FLU , let 's check that both the
1st & 2nd ops - via - proxy after FLU is restarted are
successful . And immediately after stopping the FLU ,
both 1st & 2nd ops - via - proxy should always fail .
AppendOpts1 = #append_opts{chunk_extra=42},
ExpectedOps =
[
fun(run) -> ?assertEqual({ok, EpochID}, ?MUT:get_epoch_id(Prox1)),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_epoch_id(Prox1) end,
fun(run) -> {ok, EpochID} =
?MUT:get_latest_epochid(Prox1, public),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_latest_epochid(Prox1, public)
end,
fun(run) -> {ok, EpochID} =
?MUT:get_latest_epochid(Prox1, private),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_latest_epochid(Prox1, private)
end,
fun(run) -> {ok, P1} =
?MUT:read_projection(Prox1, public, 1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:read_projection(Prox1, public, 1)
end,
fun(run) -> {ok, P1} =
?MUT:read_projection(Prox1, private, 1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:read_projection(Prox1, private, 1)
end,
fun(run) -> {error, not_written} =
?MUT:read_projection(Prox1, private, 7),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:read_projection(Prox1, private, 7)
end,
fun(run) -> ok =
?MUT:write_projection(Prox1, public, P1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, public, P1)
end,
fun(run) -> ok =
?MUT:write_projection(Prox1, private, P1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, private, P1)
end,
fun(run) -> {error, written} =
?MUT:write_projection(Prox1, public, P1xx),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, public, P1xx)
end,
P1xx is difference only in dbg2
?MUT:write_projection(Prox1, private, P1xx),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, private, P1xx)
end,
?MUT:write_projection(Prox1, private, P1yy),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_projection(Prox1, private, P1yy)
end,
fun(run) -> {ok, [#projection_v1{epoch_number=0}, #projection_v1{epoch_number=1}]} =
?MUT:get_all_projections(Prox1, public),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_all_projections(Prox1, public)
end,
fun(run) -> {ok, [#projection_v1{epoch_number=0}, #projection_v1{epoch_number=1}]} =
?MUT:get_all_projections(Prox1, private),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:get_all_projections(Prox1, private)
end,
fun(run) -> {ok, {_,_,_}} =
?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
<<"prefix">>, Data, NoCSum),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
<<"prefix">>, Data, NoCSum)
end,
fun(run) -> {ok, {_,_,_}} =
?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
<<"prefix">>, Data, NoCSum,
AppendOpts1, infinity),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:append_chunk(Prox1, NSInfo, FakeEpoch,
<<"prefix">>, Data, NoCSum,
AppendOpts1, infinity)
end,
fun(run) -> {ok, {[{_, Off1, Data, _}], []}} =
?MUT:read_chunk(Prox1, NSInfo, FakeEpoch,
File1, Off1, Size1, undefined),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:read_chunk(Prox1, NSInfo, FakeEpoch,
File1, Off1, Size1, undefined)
end,
fun(run) -> {ok, KludgeBin} =
?MUT:checksum_list(Prox1, File1),
true = is_binary(KludgeBin),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:checksum_list(Prox1, File1)
end,
fun(run) -> {ok, _} =
?MUT:list_files(Prox1, FakeEpoch),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:list_files(Prox1, FakeEpoch)
end,
fun(run) -> {ok, _} =
?MUT:wedge_status(Prox1),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:wedge_status(Prox1)
end,
fun(run) ->
ok =
?MUT:write_chunk(Prox1, NSInfo, FakeEpoch, File1, Off1,
Data, NoCSum, infinity),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_chunk(Prox1, NSInfo, FakeEpoch, File1, Off1,
Data, NoCSum, infinity)
end,
fun(run) ->
{error, written} =
?MUT:write_chunk(Prox1, NSInfo, FakeEpoch, File1, Off1,
Dataxx, NoCSum, infinity),
ok;
(line) -> io:format("line ~p, ", [?LINE]);
(stop) -> ?MUT:write_chunk(Prox1, NSInfo, FakeEpoch, File1, Off1,
Dataxx, NoCSum, infinity)
end
],
[begin
machi_test_util:start_flu_package(
RegName, TcpPort, DataDir,
[no_cleanup|W_props]),
_ = Fun(line),
ok = Fun(run),
ok = Fun(run),
ok = machi_test_util:stop_flu_package(),
{error, partition} = Fun(stop),
{error, partition} = Fun(stop),
ok
end || Fun <- ExpectedOps ],
ok
after
_ = (catch ?MUT:quit(Prox1))
end
after
(catch machi_test_util:stop_flu_package())
end.
|
2626552f4e5188c2a42638f5677d880073f9d8ae879727c5eb4b2a61f78617f2 | ucsd-progsys/liquidhaskell | NewTypes.hs | {-@ LIQUID "--expect-any-error" @-}
module NewTypes where
newtype Foo a = Bar Int
@ newtype Foo a = Bar { x : : } @
@ fromFoo : : Nat @
fromFoo :: Foo a -> Int
fromFoo (Bar n) = n
bar = Bar (-1)
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/datacon/neg/NewTypes.hs | haskell | @ LIQUID "--expect-any-error" @ | module NewTypes where
newtype Foo a = Bar Int
@ newtype Foo a = Bar { x : : } @
@ fromFoo : : Nat @
fromFoo :: Foo a -> Int
fromFoo (Bar n) = n
bar = Bar (-1)
|
778653b443233207ad417db35b14bee888a032a73adfc3de680be14e55290fbc | manuel-serrano/bigloo | compile.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / / comptime / SawC / compile.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Tue Feb 21 08:37:48 1995 * /
* Last change : Fri Jun 24 20:28:16 2022 ( serrano ) * /
* Copyright : 1995 - 2022 , see LICENSE file * /
;* ------------------------------------------------------------- */
;* The `C generation' pass. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module saw_c_compile
(include "Engine/pass.sch"
"Ast/unit.sch"
"Tools/trace.sch")
(import tools_shape
tools_error
engine_param
engine_configure
module_module
module_library
type_type
ast_var
ast_node
ast_occur
ast_build
ast_env
object_class
bdb_emit
prof_emit
backend_backend
backend_init
backend_cvm
backend_c_emit
backend_c_prototype
backend_c_main
backend_cplib
object_class
object_slots
saw_c_code))
;*---------------------------------------------------------------------*/
* backend - compile - functions : : ... * /
;*---------------------------------------------------------------------*/
(define-method (backend-compile-functions me::sawc)
(for-each-global! set-variable-name!)
(let ((globals (cvm-functions me)))
;; we now emit the code for all the Scheme functions
(saw-cheader)
(for-each (lambda (v) (saw-cgen me v)) globals)
(saw-cepilogue)))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/1ae5b060fcfd05ad33440765b45add3a26ced5b4/comptime/SawC/compile.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* The `C generation' pass. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
we now emit the code for all the Scheme functions | * serrano / prgm / project / bigloo / / comptime / SawC / compile.scm * /
* Author : * /
* Creation : Tue Feb 21 08:37:48 1995 * /
* Last change : Fri Jun 24 20:28:16 2022 ( serrano ) * /
* Copyright : 1995 - 2022 , see LICENSE file * /
(module saw_c_compile
(include "Engine/pass.sch"
"Ast/unit.sch"
"Tools/trace.sch")
(import tools_shape
tools_error
engine_param
engine_configure
module_module
module_library
type_type
ast_var
ast_node
ast_occur
ast_build
ast_env
object_class
bdb_emit
prof_emit
backend_backend
backend_init
backend_cvm
backend_c_emit
backend_c_prototype
backend_c_main
backend_cplib
object_class
object_slots
saw_c_code))
* backend - compile - functions : : ... * /
(define-method (backend-compile-functions me::sawc)
(for-each-global! set-variable-name!)
(let ((globals (cvm-functions me)))
(saw-cheader)
(for-each (lambda (v) (saw-cgen me v)) globals)
(saw-cepilogue)))
|
2f77a22a067fe3245e03d6c5cc90060ee428a17794bf5a740c3fc326b5c6561f | ngorogiannis/cyclist | predsym.ml | open Lib
open MParser
module T = Strng
module H = Hashcons.Make (T)
let predtbl = H.create 997
module HT = struct
type t = T.t Hashcons.hash_consed
let parse st = (parse_ident |>> H.hashcons predtbl) st
let of_string s = handle_reply (MParser.parse_string parse s ())
let to_string s = s.Hashcons.node
let pp fmt s = T.pp fmt (to_string s)
let compare s s' = Int.compare s.Hashcons.tag s'.Hashcons.tag
let equal s s' = s == s'
let hash s = s.Hashcons.hkey
end
include HT
module Set = Treeset.Make (HT)
module MSet = Multiset.Make (HT)
module Map = Treemap.Make (HT)
| null | https://raw.githubusercontent.com/ngorogiannis/cyclist/c93a168d586b308ab2a2c730cd1b2375ab263167/src/seplog/predsym.ml | ocaml | open Lib
open MParser
module T = Strng
module H = Hashcons.Make (T)
let predtbl = H.create 997
module HT = struct
type t = T.t Hashcons.hash_consed
let parse st = (parse_ident |>> H.hashcons predtbl) st
let of_string s = handle_reply (MParser.parse_string parse s ())
let to_string s = s.Hashcons.node
let pp fmt s = T.pp fmt (to_string s)
let compare s s' = Int.compare s.Hashcons.tag s'.Hashcons.tag
let equal s s' = s == s'
let hash s = s.Hashcons.hkey
end
include HT
module Set = Treeset.Make (HT)
module MSet = Multiset.Make (HT)
module Map = Treemap.Make (HT)
| |
8857c7f1cfa92290c30c28f62ad37e8676f0c7fe2276348a0f51c7a9fb359d2c | racket/htdp | stop-when-bad-draw.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-advanced-reader.ss" "lang")((modname stop-when-bad-draw) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f () #f)))
(require 2htdp/image)
(require 2htdp/universe)
(define (main x)
(big-bang x
[to-draw draw-circ]
[on-tick shrink-circ]
[stop-when stop-circ?]))
(define (draw-circ x) (circle x 'solid" 'red"))
(define (shrink-circ x) (- x 5))
(define (stop-circ? x) (<= x 0))
(check-expect (main 2) -3) | null | https://raw.githubusercontent.com/racket/htdp/aa78794fa1788358d6abd11dad54b3c9f4f5a80b/htdp-test/2htdp/tests/stop-when-bad-draw.rkt | racket | about the language level of this file in a form that our tools can easily process. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-advanced-reader.ss" "lang")((modname stop-when-bad-draw) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #t #t none #f () #f)))
(require 2htdp/image)
(require 2htdp/universe)
(define (main x)
(big-bang x
[to-draw draw-circ]
[on-tick shrink-circ]
[stop-when stop-circ?]))
(define (draw-circ x) (circle x 'solid" 'red"))
(define (shrink-circ x) (- x 5))
(define (stop-circ? x) (<= x 0))
(check-expect (main 2) -3) |
0bf47387dee9f38c07f346db3f3254bd153f0b591448011c8b281cfedb3c4766 | odis-labs/helix | View.ml | module Js = Helix_js
module Attr = Html.Attr
module Node = Stdweb.Dom.Node
module Element = Stdweb.Dom.Element
module Comment = Stdweb.Dom.Comment
module Document_fragment = Stdweb.Dom.Document_fragment
module Document = Stdweb.Dom.Document
module Html_element = Stdweb.Dom.Html_element
let option_get option =
match option with
| Some x -> x
| None -> invalid_arg "option is None"
(* Reactive rendering *)
let gen_show_id =
let i = ref (-1) in
fun () ->
incr i;
"show:" ^ string_of_int !i
let insert_after_anchor ~parent ~anchor node =
match Node.next_sibling anchor with
| Some anchor_sibling ->
Node.insert_before ~parent ~reference:anchor_sibling node
| None -> Node.append_child ~parent node
let show (to_html : 'a -> Html.html) signal : Html.html =
(* Anchor for the show node. *)
let anchor = Comment.to_node (Comment.make (gen_show_id ())) in
(* Create initial html. *)
let init = to_html (Signal.get signal) in
let init = Html.Elem.Internal.of_html init in
(* Store reference to prev html. *)
let prev = ref init in
(* Temporary fragment for next node. *)
let fragment = Document_fragment.(to_node (make ())) in
let mount parent =
(* Add anchor. *)
Node.append_child ~parent anchor;
(* Add initial html value. *)
init.mount parent;
(* Subscribe to updates. *)
Signal.sub
(fun x ->
(* Create next html. *)
let next = to_html x in
let next = Html.Elem.Internal.of_html next in
(* Remove prev node. *)
!prev.remove ();
(* Update prev. *)
prev := next;
(* Insert next to fragment and the fragment to parent. *)
next.mount fragment;
insert_after_anchor ~parent ~anchor fragment)
signal
in
let remove () = !prev.remove () in
Html.Elem.Internal.to_html { mount; remove }
let gen_conditional_id =
let i = ref (-1) in
fun () ->
incr i;
"conditional:" ^ string_of_int !i
let conditional ~on:active_sig : Attr.t =
Dedup the boolean signal .
let active_sig = Signal.uniq ~equal:( == ) active_sig in
(* Anchor for the conditional node. *)
let anchor = Comment.to_node (Comment.make (gen_conditional_id ())) in
(* Initial state. *)
let should_activate0 = Signal.get active_sig in
let set elem =
let node = Element.to_node elem in
let parent =
match Node.parent_node node with
| Some parent -> parent
| None ->
failwith "[BUG]: View.conditional: element does not have a parent"
in
(* The node is mounted initially. Do we unmount? *)
if not should_activate0 then
Node.replace_child ~parent ~reference:node anchor;
(* Subscribe to updates. *)
Signal.sub
(fun should_activate ->
if should_activate then
Node.replace_child ~parent ~reference:anchor node
else Node.replace_child ~parent ~reference:node anchor)
active_sig
in
let remove elem =
let node = Element.to_node elem in
let parent =
match Node.parent_node node with
| Some parent -> parent
| None ->
failwith "[BUG]: View.conditional: element does not have a parent"
in
(* Put to the original state. *)
if not should_activate0 then
Node.replace_child ~parent ~reference:anchor node
in
Attr.Internal.to_attr { set; remove }
let conditional_html : condition_s html = assert false
let anchor = Comment.to_node ( Comment.make ( ( ) ) ) in
let fragment = Document_fragment.(to_node ( make ( ) ) ) in
Node.append_child ~parent : fragment anchor ;
let prev_ref = ref None in
if Signal.get condition_s then begin
let node0 = Html . . Internal.of_html html in
Node.append_child ~parent : fragment node0 ;
prev_ref : = Some node0
end ;
Signal.sub
( fun condition - >
let parent =
match Node.parent_node anchor with
| Some parent - > parent
| None - > failwith " Html.show : can not update unmounted element "
in
if condition then (
let next = Html . . Internal.of_html html in
match ! prev_ref with
| None - >
insert_after_anchor ~parent ~anchor next ;
prev_ref : = Some next
| Some prev - >
Node.replace_child ~parent ~reference : prev next ;
prev_ref : = Some next )
else
match ! prev_ref with
| None - > ( )
| Some prev - >
Node.remove_child ~parent prev ;
prev_ref : = None )
condition_s ;
Html . Elem . Internal.to_html fragment
let fragment = Document_fragment.(to_node (make ())) in
Node.append_child ~parent:fragment anchor;
let prev_ref = ref None in
if Signal.get condition_s then begin
let node0 = Html.Elem.Internal.of_html html in
Node.append_child ~parent:fragment node0;
prev_ref := Some node0
end;
Signal.sub
(fun condition ->
let parent =
match Node.parent_node anchor with
| Some parent -> parent
| None -> failwith "Html.show: cannot update unmounted element"
in
if condition then (
let next = Html.Elem.Internal.of_html html in
match !prev_ref with
| None ->
insert_after_anchor ~parent ~anchor next;
prev_ref := Some next
| Some prev ->
Node.replace_child ~parent ~reference:prev next;
prev_ref := Some next)
else
match !prev_ref with
| None -> ()
| Some prev ->
Node.remove_child ~parent prev;
prev_ref := None)
condition_s;
Html.Elem.Internal.to_html fragment
*)
module Each = struct
let gen_id =
let i = ref (-1) in
fun () ->
incr i;
"each:" ^ string_of_int !i
module Cache : sig
type t
type slots
type key
val key : 'a -> key
val make : unit -> t
val set : t -> key:key -> slots -> unit
val get : t -> key:key -> slots option
val get_slot : slots -> int * Html.Elem.Internal.t
val add_slot : t -> key:key -> int -> Html.Elem.Internal.t -> unit
val del_slot : t -> key:key -> slots -> int -> unit
val clear : t -> unit
end = struct
module Map = Stdweb.Map
module Iterator = Stdweb.Iterator
module Dict = Stdweb.Dict
type key = string
type slots = Html.Elem.Internal.t Map.t
type t = slots Dict.t
let key x = string_of_int (Hashtbl.hash x)
let make () = Dict.empty ()
let make_slots = Map.make
let get_slot slots =
match Map.first_key slots with
| None -> failwith "BUG: get_slot: slots must not be empty"
| Some idx_js ->
let idx = Js.Decoder.int idx_js in
let html = Map.get slots idx_js in
(idx, html)
let set cache ~key slots = Dict.set cache key slots
let get cache ~key = Dict.get_opt cache key
let add_slot cache ~key idx html =
let slots =
match get cache ~key with
| None -> make_slots ()
| Some slots -> slots
in
Map.set slots (Js.Encoder.int idx) html;
set cache ~key slots
let del_slot cache ~key slots idx =
Map.delete slots (Js.Encoder.int idx);
if Map.size slots = 0 then Dict.del cache key
let clear cache =
Dict.iter cache (fun slots ->
let values = Map.values slots in
Iterator.iter
(fun (html : Html.Elem.Internal.t) -> html.remove ())
values;
Map.clear slots)
end
let make (render : 'a -> Html.html) items_signal : Html.html =
(* Create anchor. *)
let comment = Comment.to_node (Comment.make (gen_id ())) in
let anchor = ref comment in
Initialize cache with items0 .
let fragment = Document_fragment.(to_node (make ())) in
let items0 = Signal.get items_signal in
let old_cache = ref (Cache.make ()) in
List.iteri
(fun i item ->
let key = Cache.key item in
let html = Html.Elem.Internal.of_html (render item) in
html.mount fragment;
Cache.add_slot !old_cache ~key i html)
items0;
let mount parent =
(* Append anchor and initial fragment. *)
Node.append_child ~parent !anchor;
Node.append_child ~parent fragment;
(* Subscribe to changes. *)
Signal.sub
(fun new_items ->
let new_cache = Cache.make () in
List.iteri
(fun j item ->
let key = Cache.key item in
match Cache.get !old_cache ~key with
| None ->
(* New. *)
let html = Html.Elem.Internal.of_html (render item) in
html.mount fragment;
Cache.add_slot new_cache ~key j html
| Some old_slots ->
let i, i_html = Cache.get_slot old_slots in
if i = j then begin
(* Keep. *)
anchor := Node.next_sibling !anchor |> option_get;
Cache.del_slot !old_cache ~key old_slots j;
Cache.add_slot new_cache ~key j i_html
end
else begin
(* Swap. *)
i_html.mount fragment;
Cache.del_slot !old_cache ~key old_slots i;
Cache.add_slot new_cache ~key j i_html
end)
new_items;
Cache.clear !old_cache;
insert_after_anchor ~parent ~anchor:!anchor fragment;
old_cache := new_cache;
anchor := comment)
items_signal
in
let remove () = Cache.clear !old_cache in
Html.Elem.Internal.to_html { mount; remove }
end
let each = Each.make
(* Assign *)
let assign attr_sig : Attr.t =
let prev0 = Signal.get attr_sig in
let prev' : Attr.Internal.t ref = ref (Attr.Internal.of_attr prev0) in
let set elem =
!prev'.set elem;
Signal.use
(fun (next : Attr.t) ->
let next' = Attr.Internal.of_attr next in
!prev'.remove elem;
next'.set elem;
prev' := next')
attr_sig
in
let remove elem = !prev'.remove elem in
Attr.Internal.to_attr { set; remove }
let bind to_attr signal : Attr.t =
let prev0 = to_attr (Signal.get signal) in
let prev' : Attr.Internal.t ref = ref (Attr.Internal.of_attr prev0) in
let set elem =
!prev'.set elem;
Signal.use
(fun x ->
let next' = Attr.Internal.of_attr (to_attr x) in
!prev'.remove elem;
next'.set elem;
prev' := next')
signal
in
let remove elem = !prev'.remove elem in
Attr.Internal.to_attr { set; remove }
let toggle ~on:active_sig attr0 : Attr.t =
let active_sig = Signal.uniq ~equal:( = ) active_sig in
let internal = Attr.Internal.of_attr attr0 in
let should_activate0 = Signal.get active_sig in
let set elem =
if should_activate0 then internal.set elem;
Signal.use
(fun should_activate ->
if should_activate then internal.set elem else internal.remove elem)
active_sig
in
Attr.Internal.to_attr { internal with set }
let visible ~on:cond : Attr.t =
toggle ~on:(Signal.map not cond) (Html.style [ ("display", "none") ])
(* New experimental node api *)
let conditional_node ~on:active_sig : Attr.t =
Dedup the boolean signal .
let active_sig = Signal.uniq ~equal:( == ) active_sig in
(* Anchor for the conditional node. *)
let anchor = Comment.to_node (Comment.make (gen_conditional_id ())) in
(* Initial state. *)
let should_activate0 = Signal.get active_sig in
let set elem =
let node = Element.to_node elem in
(* The node is mounted initially. Do we unmount? *)
(* if not should_activate0 then *)
~parent ~reference : node anchor ;
(* Subscribe to updates. *)
Signal.sub
(fun should_activate ->
let parent =
match Node.parent_node node with
| Some parent -> parent
| None ->
failwith
"[BUG]: View.conditional_node: element does not have a parent"
in
if should_activate then
Node.replace_child ~parent ~reference:anchor node
else Node.replace_child ~parent ~reference:node anchor)
active_sig
in
let remove elem =
let node = Element.to_node elem in
let parent =
match Node.parent_node node with
| Some parent -> parent
| None ->
failwith "[BUG]: View.conditional: element does not have a parent"
in
(* Put to the original state. *)
if not should_activate0 then
Node.replace_child ~parent ~reference:anchor node
in
Attr.Internal.to_attr { set; remove }
| null | https://raw.githubusercontent.com/odis-labs/helix/7106652712626b9c7fd21660b4d53cca1e915224/src/helix/View.ml | ocaml | Reactive rendering
Anchor for the show node.
Create initial html.
Store reference to prev html.
Temporary fragment for next node.
Add anchor.
Add initial html value.
Subscribe to updates.
Create next html.
Remove prev node.
Update prev.
Insert next to fragment and the fragment to parent.
Anchor for the conditional node.
Initial state.
The node is mounted initially. Do we unmount?
Subscribe to updates.
Put to the original state.
Create anchor.
Append anchor and initial fragment.
Subscribe to changes.
New.
Keep.
Swap.
Assign
New experimental node api
Anchor for the conditional node.
Initial state.
The node is mounted initially. Do we unmount?
if not should_activate0 then
Subscribe to updates.
Put to the original state. | module Js = Helix_js
module Attr = Html.Attr
module Node = Stdweb.Dom.Node
module Element = Stdweb.Dom.Element
module Comment = Stdweb.Dom.Comment
module Document_fragment = Stdweb.Dom.Document_fragment
module Document = Stdweb.Dom.Document
module Html_element = Stdweb.Dom.Html_element
let option_get option =
match option with
| Some x -> x
| None -> invalid_arg "option is None"
let gen_show_id =
let i = ref (-1) in
fun () ->
incr i;
"show:" ^ string_of_int !i
let insert_after_anchor ~parent ~anchor node =
match Node.next_sibling anchor with
| Some anchor_sibling ->
Node.insert_before ~parent ~reference:anchor_sibling node
| None -> Node.append_child ~parent node
let show (to_html : 'a -> Html.html) signal : Html.html =
let anchor = Comment.to_node (Comment.make (gen_show_id ())) in
let init = to_html (Signal.get signal) in
let init = Html.Elem.Internal.of_html init in
let prev = ref init in
let fragment = Document_fragment.(to_node (make ())) in
let mount parent =
Node.append_child ~parent anchor;
init.mount parent;
Signal.sub
(fun x ->
let next = to_html x in
let next = Html.Elem.Internal.of_html next in
!prev.remove ();
prev := next;
next.mount fragment;
insert_after_anchor ~parent ~anchor fragment)
signal
in
let remove () = !prev.remove () in
Html.Elem.Internal.to_html { mount; remove }
let gen_conditional_id =
let i = ref (-1) in
fun () ->
incr i;
"conditional:" ^ string_of_int !i
let conditional ~on:active_sig : Attr.t =
Dedup the boolean signal .
let active_sig = Signal.uniq ~equal:( == ) active_sig in
let anchor = Comment.to_node (Comment.make (gen_conditional_id ())) in
let should_activate0 = Signal.get active_sig in
let set elem =
let node = Element.to_node elem in
let parent =
match Node.parent_node node with
| Some parent -> parent
| None ->
failwith "[BUG]: View.conditional: element does not have a parent"
in
if not should_activate0 then
Node.replace_child ~parent ~reference:node anchor;
Signal.sub
(fun should_activate ->
if should_activate then
Node.replace_child ~parent ~reference:anchor node
else Node.replace_child ~parent ~reference:node anchor)
active_sig
in
let remove elem =
let node = Element.to_node elem in
let parent =
match Node.parent_node node with
| Some parent -> parent
| None ->
failwith "[BUG]: View.conditional: element does not have a parent"
in
if not should_activate0 then
Node.replace_child ~parent ~reference:anchor node
in
Attr.Internal.to_attr { set; remove }
let conditional_html : condition_s html = assert false
let anchor = Comment.to_node ( Comment.make ( ( ) ) ) in
let fragment = Document_fragment.(to_node ( make ( ) ) ) in
Node.append_child ~parent : fragment anchor ;
let prev_ref = ref None in
if Signal.get condition_s then begin
let node0 = Html . . Internal.of_html html in
Node.append_child ~parent : fragment node0 ;
prev_ref : = Some node0
end ;
Signal.sub
( fun condition - >
let parent =
match Node.parent_node anchor with
| Some parent - > parent
| None - > failwith " Html.show : can not update unmounted element "
in
if condition then (
let next = Html . . Internal.of_html html in
match ! prev_ref with
| None - >
insert_after_anchor ~parent ~anchor next ;
prev_ref : = Some next
| Some prev - >
Node.replace_child ~parent ~reference : prev next ;
prev_ref : = Some next )
else
match ! prev_ref with
| None - > ( )
| Some prev - >
Node.remove_child ~parent prev ;
prev_ref : = None )
condition_s ;
Html . Elem . Internal.to_html fragment
let fragment = Document_fragment.(to_node (make ())) in
Node.append_child ~parent:fragment anchor;
let prev_ref = ref None in
if Signal.get condition_s then begin
let node0 = Html.Elem.Internal.of_html html in
Node.append_child ~parent:fragment node0;
prev_ref := Some node0
end;
Signal.sub
(fun condition ->
let parent =
match Node.parent_node anchor with
| Some parent -> parent
| None -> failwith "Html.show: cannot update unmounted element"
in
if condition then (
let next = Html.Elem.Internal.of_html html in
match !prev_ref with
| None ->
insert_after_anchor ~parent ~anchor next;
prev_ref := Some next
| Some prev ->
Node.replace_child ~parent ~reference:prev next;
prev_ref := Some next)
else
match !prev_ref with
| None -> ()
| Some prev ->
Node.remove_child ~parent prev;
prev_ref := None)
condition_s;
Html.Elem.Internal.to_html fragment
*)
module Each = struct
let gen_id =
let i = ref (-1) in
fun () ->
incr i;
"each:" ^ string_of_int !i
module Cache : sig
type t
type slots
type key
val key : 'a -> key
val make : unit -> t
val set : t -> key:key -> slots -> unit
val get : t -> key:key -> slots option
val get_slot : slots -> int * Html.Elem.Internal.t
val add_slot : t -> key:key -> int -> Html.Elem.Internal.t -> unit
val del_slot : t -> key:key -> slots -> int -> unit
val clear : t -> unit
end = struct
module Map = Stdweb.Map
module Iterator = Stdweb.Iterator
module Dict = Stdweb.Dict
type key = string
type slots = Html.Elem.Internal.t Map.t
type t = slots Dict.t
let key x = string_of_int (Hashtbl.hash x)
let make () = Dict.empty ()
let make_slots = Map.make
let get_slot slots =
match Map.first_key slots with
| None -> failwith "BUG: get_slot: slots must not be empty"
| Some idx_js ->
let idx = Js.Decoder.int idx_js in
let html = Map.get slots idx_js in
(idx, html)
let set cache ~key slots = Dict.set cache key slots
let get cache ~key = Dict.get_opt cache key
let add_slot cache ~key idx html =
let slots =
match get cache ~key with
| None -> make_slots ()
| Some slots -> slots
in
Map.set slots (Js.Encoder.int idx) html;
set cache ~key slots
let del_slot cache ~key slots idx =
Map.delete slots (Js.Encoder.int idx);
if Map.size slots = 0 then Dict.del cache key
let clear cache =
Dict.iter cache (fun slots ->
let values = Map.values slots in
Iterator.iter
(fun (html : Html.Elem.Internal.t) -> html.remove ())
values;
Map.clear slots)
end
let make (render : 'a -> Html.html) items_signal : Html.html =
let comment = Comment.to_node (Comment.make (gen_id ())) in
let anchor = ref comment in
Initialize cache with items0 .
let fragment = Document_fragment.(to_node (make ())) in
let items0 = Signal.get items_signal in
let old_cache = ref (Cache.make ()) in
List.iteri
(fun i item ->
let key = Cache.key item in
let html = Html.Elem.Internal.of_html (render item) in
html.mount fragment;
Cache.add_slot !old_cache ~key i html)
items0;
let mount parent =
Node.append_child ~parent !anchor;
Node.append_child ~parent fragment;
Signal.sub
(fun new_items ->
let new_cache = Cache.make () in
List.iteri
(fun j item ->
let key = Cache.key item in
match Cache.get !old_cache ~key with
| None ->
let html = Html.Elem.Internal.of_html (render item) in
html.mount fragment;
Cache.add_slot new_cache ~key j html
| Some old_slots ->
let i, i_html = Cache.get_slot old_slots in
if i = j then begin
anchor := Node.next_sibling !anchor |> option_get;
Cache.del_slot !old_cache ~key old_slots j;
Cache.add_slot new_cache ~key j i_html
end
else begin
i_html.mount fragment;
Cache.del_slot !old_cache ~key old_slots i;
Cache.add_slot new_cache ~key j i_html
end)
new_items;
Cache.clear !old_cache;
insert_after_anchor ~parent ~anchor:!anchor fragment;
old_cache := new_cache;
anchor := comment)
items_signal
in
let remove () = Cache.clear !old_cache in
Html.Elem.Internal.to_html { mount; remove }
end
let each = Each.make
let assign attr_sig : Attr.t =
let prev0 = Signal.get attr_sig in
let prev' : Attr.Internal.t ref = ref (Attr.Internal.of_attr prev0) in
let set elem =
!prev'.set elem;
Signal.use
(fun (next : Attr.t) ->
let next' = Attr.Internal.of_attr next in
!prev'.remove elem;
next'.set elem;
prev' := next')
attr_sig
in
let remove elem = !prev'.remove elem in
Attr.Internal.to_attr { set; remove }
let bind to_attr signal : Attr.t =
let prev0 = to_attr (Signal.get signal) in
let prev' : Attr.Internal.t ref = ref (Attr.Internal.of_attr prev0) in
let set elem =
!prev'.set elem;
Signal.use
(fun x ->
let next' = Attr.Internal.of_attr (to_attr x) in
!prev'.remove elem;
next'.set elem;
prev' := next')
signal
in
let remove elem = !prev'.remove elem in
Attr.Internal.to_attr { set; remove }
let toggle ~on:active_sig attr0 : Attr.t =
let active_sig = Signal.uniq ~equal:( = ) active_sig in
let internal = Attr.Internal.of_attr attr0 in
let should_activate0 = Signal.get active_sig in
let set elem =
if should_activate0 then internal.set elem;
Signal.use
(fun should_activate ->
if should_activate then internal.set elem else internal.remove elem)
active_sig
in
Attr.Internal.to_attr { internal with set }
let visible ~on:cond : Attr.t =
toggle ~on:(Signal.map not cond) (Html.style [ ("display", "none") ])
let conditional_node ~on:active_sig : Attr.t =
Dedup the boolean signal .
let active_sig = Signal.uniq ~equal:( == ) active_sig in
let anchor = Comment.to_node (Comment.make (gen_conditional_id ())) in
let should_activate0 = Signal.get active_sig in
let set elem =
let node = Element.to_node elem in
~parent ~reference : node anchor ;
Signal.sub
(fun should_activate ->
let parent =
match Node.parent_node node with
| Some parent -> parent
| None ->
failwith
"[BUG]: View.conditional_node: element does not have a parent"
in
if should_activate then
Node.replace_child ~parent ~reference:anchor node
else Node.replace_child ~parent ~reference:node anchor)
active_sig
in
let remove elem =
let node = Element.to_node elem in
let parent =
match Node.parent_node node with
| Some parent -> parent
| None ->
failwith "[BUG]: View.conditional: element does not have a parent"
in
if not should_activate0 then
Node.replace_child ~parent ~reference:anchor node
in
Attr.Internal.to_attr { set; remove }
|
3566969a1cec0dea6b1e5f61fd3b57dc53473628db79d58e4b018bff060f79fa | GNOME/aisleriot | thieves.scm | ; Aisleriot - Thieves
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-joker-deck)
(shuffle-deck)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-carriage-return-slot)
(add-carriage-return-slot)
(add-normal-slot DECK)
(add-normal-slot '())
(deal-cards-face-up 7 '(0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6 0
1 2 3 4 5 6 0 1 2 3 4 5 6 8))
(give-status-message)
(list 7 3))
(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 7)))))
(define (values-match? c1 c2)
(or (eq? (get-value c1) joker)
(eq? (get-value c2) joker)
(eq? (+ 1 (get-value c1)) (get-value c2))
(eq? (get-value c1) (+ 1 (get-value c2)))))
(define (score-for card)
(cond ((eq? card ace) 8)
((eq? card 2) 6)
((eq? card 3) 6)
((eq? card 4) 4)
((eq? card 5) 4)
((eq? card 6) 2)
((eq? card 7) 2)
((eq? card 8) 2)
((eq? card 9) 4)
((eq? card 10) 4)
((eq? card jack) 6)
((eq? card queen) 6)
((eq? card king) 8)
(#t 0)))
(define (can-move-from where)
(and (not (empty-slot? where))
(not (empty-slot? 8))
(values-match? (get-top-card where) (get-top-card 8))))
(define (move-possible)
(or (can-move-from 0)
(can-move-from 1)
(can-move-from 2)
(can-move-from 3)
(can-move-from 4)
(can-move-from 5)
(can-move-from 6)))
(define (button-pressed slot-id card-list)
(and (< slot-id 7)
(not (empty-slot? slot-id))
(= (length card-list) 1)))
(define (button-released start-slot card-list end-slot)
(and (= end-slot 8)
(values-match? (car card-list) (get-top-card 8))
(add-to-score! (score-for (get-value (car card-list))))
(move-n-cards! start-slot 8 card-list)))
(define (droppable? start-slot card-list end-slot)
(and (= end-slot 8)
(values-match? (car card-list) (get-top-card 8)) ) )
(define (button-clicked slot-id)
(if (eq? slot-id 7)
(and (not (empty-slot? slot-id))
(deal-cards-face-up 7 '(8)))
(and (< slot-id 7)
(not (empty-slot? slot-id))
(values-match? (get-top-card slot-id) (get-top-card 8))
(add-to-score! (score-for (get-value (get-top-card slot-id))))
(deal-cards slot-id '(8)))))
(define (button-double-clicked slot)
(button-clicked slot))
(define (game-won)
(and (empty-slot? 0)
(empty-slot? 1)
(empty-slot? 2)
(empty-slot? 3)
(empty-slot? 4)
(empty-slot? 5)
(empty-slot? 6)))
(define (game-over)
(give-status-message)
(if (game-won)
#f
(if (empty-slot? 7)
(move-possible)
#t)))
(define (hint-move-from where)
(if (or (empty-slot? where)
(empty-slot? where)
(not (values-match? (get-top-card where) (get-top-card 8))))
#f
(hint-move where 1 8)))
(define (get-hint)
(or (hint-move-from 0)
(hint-move-from 1)
(hint-move-from 2)
(hint-move-from 3)
(hint-move-from 4)
(hint-move-from 5)
(hint-move-from 6)
(list 0 (G_"Deal a card from the deck"))))
(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-over game-won get-hint get-options apply-options
timeout droppable?)
| null | https://raw.githubusercontent.com/GNOME/aisleriot/5b04e58ba5f8df8223a3830d2c61325527d52237/games/thieves.scm | scheme | Aisleriot - Thieves
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 </>. | 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-joker-deck)
(shuffle-deck)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-extended-slot '() down)
(add-carriage-return-slot)
(add-carriage-return-slot)
(add-normal-slot DECK)
(add-normal-slot '())
(deal-cards-face-up 7 '(0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6 0
1 2 3 4 5 6 0 1 2 3 4 5 6 8))
(give-status-message)
(list 7 3))
(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 7)))))
(define (values-match? c1 c2)
(or (eq? (get-value c1) joker)
(eq? (get-value c2) joker)
(eq? (+ 1 (get-value c1)) (get-value c2))
(eq? (get-value c1) (+ 1 (get-value c2)))))
(define (score-for card)
(cond ((eq? card ace) 8)
((eq? card 2) 6)
((eq? card 3) 6)
((eq? card 4) 4)
((eq? card 5) 4)
((eq? card 6) 2)
((eq? card 7) 2)
((eq? card 8) 2)
((eq? card 9) 4)
((eq? card 10) 4)
((eq? card jack) 6)
((eq? card queen) 6)
((eq? card king) 8)
(#t 0)))
(define (can-move-from where)
(and (not (empty-slot? where))
(not (empty-slot? 8))
(values-match? (get-top-card where) (get-top-card 8))))
(define (move-possible)
(or (can-move-from 0)
(can-move-from 1)
(can-move-from 2)
(can-move-from 3)
(can-move-from 4)
(can-move-from 5)
(can-move-from 6)))
(define (button-pressed slot-id card-list)
(and (< slot-id 7)
(not (empty-slot? slot-id))
(= (length card-list) 1)))
(define (button-released start-slot card-list end-slot)
(and (= end-slot 8)
(values-match? (car card-list) (get-top-card 8))
(add-to-score! (score-for (get-value (car card-list))))
(move-n-cards! start-slot 8 card-list)))
(define (droppable? start-slot card-list end-slot)
(and (= end-slot 8)
(values-match? (car card-list) (get-top-card 8)) ) )
(define (button-clicked slot-id)
(if (eq? slot-id 7)
(and (not (empty-slot? slot-id))
(deal-cards-face-up 7 '(8)))
(and (< slot-id 7)
(not (empty-slot? slot-id))
(values-match? (get-top-card slot-id) (get-top-card 8))
(add-to-score! (score-for (get-value (get-top-card slot-id))))
(deal-cards slot-id '(8)))))
(define (button-double-clicked slot)
(button-clicked slot))
(define (game-won)
(and (empty-slot? 0)
(empty-slot? 1)
(empty-slot? 2)
(empty-slot? 3)
(empty-slot? 4)
(empty-slot? 5)
(empty-slot? 6)))
(define (game-over)
(give-status-message)
(if (game-won)
#f
(if (empty-slot? 7)
(move-possible)
#t)))
(define (hint-move-from where)
(if (or (empty-slot? where)
(empty-slot? where)
(not (values-match? (get-top-card where) (get-top-card 8))))
#f
(hint-move where 1 8)))
(define (get-hint)
(or (hint-move-from 0)
(hint-move-from 1)
(hint-move-from 2)
(hint-move-from 3)
(hint-move-from 4)
(hint-move-from 5)
(hint-move-from 6)
(list 0 (G_"Deal a card from the deck"))))
(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-over game-won get-hint get-options apply-options
timeout droppable?)
|
2225aabb280ca57e38736e10a1d6a391fb8fc5ae8c5375cc7338c4ddce20a79e | GaloisInc/what4 | ProgramLoc.hs | -----------------------------------------------------------------------
-- |
Module :
Description : Datatype for handling program locations
Copyright : ( c ) Galois , Inc 2014 - 2020
-- License : BSD3
Maintainer : < >
-- Stability : provisional
--
-- This module primarily defines the `Position` datatype for
-- handling program location data. A program location may refer
-- either to a source file location (file name, line and column number),
-- a binary file location (file name and byte offset) or be a dummy
-- "internal" location assigned to generated program fragments.
------------------------------------------------------------------------
# LANGUAGE CPP #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
{-# LANGUAGE DeriveTraversable #-}
module What4.ProgramLoc
( Position(..)
, sourcePos
, startOfFile
, ppNoFileName
, Posd(..)
, ProgramLoc
, mkProgramLoc
, initializationLoc
, plFunction
, plSourceLoc
-- * Objects with a program location associated.
, HasProgramLoc(..)
) where
import Control.DeepSeq
import Control.Lens
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Word
import Numeric (showHex)
import qualified Prettyprinter as PP
import What4.FunctionName
------------------------------------------------------------------------
-- Position
data Position
-- | A source position containing filename, line, and column.
= SourcePos !Text !Int !Int
-- | A binary position containing a filename and address in memory.
| BinaryPos !Text !Word64
-- | Some unstructured position information that doesn't fit into the other categories.
| OtherPos !Text
-- | Generated internally by the simulator, or otherwise unknown.
| InternalPos
deriving (Eq, Ord)
instance Show Position where
show p = show (PP.pretty p)
instance NFData Position where
rnf (SourcePos t l c) = rnf (t,l,c)
rnf (BinaryPos t a) = rnf (t,a)
rnf (OtherPos t) = rnf t
rnf InternalPos = ()
sourcePos :: FilePath -> Int -> Int -> Position
sourcePos p l c = SourcePos (Text.pack p) l c
startOfFile :: FilePath -> Position
startOfFile path = sourcePos path 1 0
instance PP.Pretty Position where
pretty (SourcePos path l c) =
PP.pretty path
PP.<> PP.colon PP.<> PP.pretty l
PP.<> PP.colon PP.<> PP.pretty c
pretty (BinaryPos path addr) =
PP.pretty path PP.<> PP.colon PP.<>
PP.pretty "0x" PP.<> PP.pretty (showHex addr "")
pretty (OtherPos txt) = PP.pretty txt
pretty InternalPos = PP.pretty "internal"
ppNoFileName :: Position -> PP.Doc ann
ppNoFileName (SourcePos _ l c) =
PP.pretty l PP.<> PP.colon PP.<> PP.pretty c
ppNoFileName (BinaryPos _ addr) =
PP.pretty (showHex addr "")
ppNoFileName (OtherPos msg) =
PP.pretty msg
ppNoFileName InternalPos = PP.pretty "internal"
------------------------------------------------------------------------
-- Posd
-- | A value with a source position associated.
data Posd v = Posd { pos :: !Position
, pos_val :: !v
}
deriving (Functor, Foldable, Traversable, Show, Eq)
instance NFData v => NFData (Posd v) where
rnf p = rnf (pos p, pos_val p)
------------------------------------------------------------------------
-- ProgramLoc
-- | A very small type that contains a function and PC identifier.
data ProgramLoc
= ProgramLoc { plFunction :: {-# UNPACK #-} !FunctionName
, plSourceLoc :: !Position
}
deriving (Show, Eq, Ord)
-- | Location for initialization code
initializationLoc :: ProgramLoc
initializationLoc = ProgramLoc startFunctionName (startOfFile "")
| Make a program loc
mkProgramLoc :: FunctionName
-> Position
-> ProgramLoc
mkProgramLoc = ProgramLoc
------------------------------------------------------------------------
-- HasProgramLoc
class HasProgramLoc v where
programLoc :: Lens' v ProgramLoc
| null | https://raw.githubusercontent.com/GaloisInc/what4/91200aa39565c156226cec6a9409a692e4022501/what4/src/What4/ProgramLoc.hs | haskell | ---------------------------------------------------------------------
|
License : BSD3
Stability : provisional
This module primarily defines the `Position` datatype for
handling program location data. A program location may refer
either to a source file location (file name, line and column number),
a binary file location (file name and byte offset) or be a dummy
"internal" location assigned to generated program fragments.
----------------------------------------------------------------------
# LANGUAGE DeriveTraversable #
* Objects with a program location associated.
----------------------------------------------------------------------
Position
| A source position containing filename, line, and column.
| A binary position containing a filename and address in memory.
| Some unstructured position information that doesn't fit into the other categories.
| Generated internally by the simulator, or otherwise unknown.
----------------------------------------------------------------------
Posd
| A value with a source position associated.
----------------------------------------------------------------------
ProgramLoc
| A very small type that contains a function and PC identifier.
# UNPACK #
| Location for initialization code
----------------------------------------------------------------------
HasProgramLoc | Module :
Description : Datatype for handling program locations
Copyright : ( c ) Galois , Inc 2014 - 2020
Maintainer : < >
# LANGUAGE CPP #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
module What4.ProgramLoc
( Position(..)
, sourcePos
, startOfFile
, ppNoFileName
, Posd(..)
, ProgramLoc
, mkProgramLoc
, initializationLoc
, plFunction
, plSourceLoc
, HasProgramLoc(..)
) where
import Control.DeepSeq
import Control.Lens
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Word
import Numeric (showHex)
import qualified Prettyprinter as PP
import What4.FunctionName
data Position
= SourcePos !Text !Int !Int
| BinaryPos !Text !Word64
| OtherPos !Text
| InternalPos
deriving (Eq, Ord)
instance Show Position where
show p = show (PP.pretty p)
instance NFData Position where
rnf (SourcePos t l c) = rnf (t,l,c)
rnf (BinaryPos t a) = rnf (t,a)
rnf (OtherPos t) = rnf t
rnf InternalPos = ()
sourcePos :: FilePath -> Int -> Int -> Position
sourcePos p l c = SourcePos (Text.pack p) l c
startOfFile :: FilePath -> Position
startOfFile path = sourcePos path 1 0
instance PP.Pretty Position where
pretty (SourcePos path l c) =
PP.pretty path
PP.<> PP.colon PP.<> PP.pretty l
PP.<> PP.colon PP.<> PP.pretty c
pretty (BinaryPos path addr) =
PP.pretty path PP.<> PP.colon PP.<>
PP.pretty "0x" PP.<> PP.pretty (showHex addr "")
pretty (OtherPos txt) = PP.pretty txt
pretty InternalPos = PP.pretty "internal"
ppNoFileName :: Position -> PP.Doc ann
ppNoFileName (SourcePos _ l c) =
PP.pretty l PP.<> PP.colon PP.<> PP.pretty c
ppNoFileName (BinaryPos _ addr) =
PP.pretty (showHex addr "")
ppNoFileName (OtherPos msg) =
PP.pretty msg
ppNoFileName InternalPos = PP.pretty "internal"
data Posd v = Posd { pos :: !Position
, pos_val :: !v
}
deriving (Functor, Foldable, Traversable, Show, Eq)
instance NFData v => NFData (Posd v) where
rnf p = rnf (pos p, pos_val p)
data ProgramLoc
, plSourceLoc :: !Position
}
deriving (Show, Eq, Ord)
initializationLoc :: ProgramLoc
initializationLoc = ProgramLoc startFunctionName (startOfFile "")
| Make a program loc
mkProgramLoc :: FunctionName
-> Position
-> ProgramLoc
mkProgramLoc = ProgramLoc
class HasProgramLoc v where
programLoc :: Lens' v ProgramLoc
|
4fd933f2a3d79e64a5e66fd15a02c912a0b65b17cee29aa0382b838849478926 | junjihashimoto/hspec-server | Util.hs | module Test.Hspec.Server.Util where
import System.Exit
import Control.Monad
import Control.Monad.IO.Class
import Data.Monoid
import Text.Regex.Posix
import Test.Hspec.Server.Core
cmd :: ServerType dat => dat -> FilePath -> [String] -> String -> IO (ExitCode,String,String)
cmd = stCmd
type Patterns = [String]
type Arg = [String]
type Input = String
type TestType = String
--type TestedName = String
cmdAndChk :: (ServerType dat)
=> TestType
-> s
-> s
-> FilePath
-> Arg
-> Input
-> Patterns
-> ServerExample dat (Either String s)
cmdAndChk test testedval _failedval c arg i [] = do
dat <- getServerData
c'@(code,_out,_) <- liftIO $ cmd dat c arg i
if (code /= ExitSuccess)
then return $ Left $ test <> " error:" ++ show c'
else return $ Right testedval
cmdAndChk test testedval failedval c arg i patterns = do
dat <- getServerData
(code,out,_) <- liftIO $ cmd dat c arg i
if (code /= ExitSuccess)
then do
return $ Left $ test <> " error:" ++ show c
else do
if or (map (\v -> foldr (||) False
(map (\p -> v =~ p) patterns)
)
(lines out))
then return $ Right testedval
else return $ Right failedval
| null | https://raw.githubusercontent.com/junjihashimoto/hspec-server/473058fa4ca17abbe110d9f273d3c6726d5f1365/Test/Hspec/Server/Util.hs | haskell | type TestedName = String | module Test.Hspec.Server.Util where
import System.Exit
import Control.Monad
import Control.Monad.IO.Class
import Data.Monoid
import Text.Regex.Posix
import Test.Hspec.Server.Core
cmd :: ServerType dat => dat -> FilePath -> [String] -> String -> IO (ExitCode,String,String)
cmd = stCmd
type Patterns = [String]
type Arg = [String]
type Input = String
type TestType = String
cmdAndChk :: (ServerType dat)
=> TestType
-> s
-> s
-> FilePath
-> Arg
-> Input
-> Patterns
-> ServerExample dat (Either String s)
cmdAndChk test testedval _failedval c arg i [] = do
dat <- getServerData
c'@(code,_out,_) <- liftIO $ cmd dat c arg i
if (code /= ExitSuccess)
then return $ Left $ test <> " error:" ++ show c'
else return $ Right testedval
cmdAndChk test testedval failedval c arg i patterns = do
dat <- getServerData
(code,out,_) <- liftIO $ cmd dat c arg i
if (code /= ExitSuccess)
then do
return $ Left $ test <> " error:" ++ show c
else do
if or (map (\v -> foldr (||) False
(map (\p -> v =~ p) patterns)
)
(lines out))
then return $ Right testedval
else return $ Right failedval
|
30dc3c47895aec28573ee3078bf0fb5bf5834ef1c7e0318a4e8dca079df0e022 | zenspider/schemers | exercise.4.20.scm | #!/usr/bin/env csi -s
(require rackunit)
(require-library eval)
(import eval)
Exercise 4.20
;; Because internal definitions look sequential but
;; are actually simultaneous, some people prefer to avoid them
entirely , and use the special form ` letrec ' instead . ` Letrec '
;; looks like `let', so it is not surprising that the variables it
;; binds are bound simultaneously and have the same scope as each
;; other. The sample procedure `f' above can be written without
;; internal definitions, but with exactly the same meaning, as
;;
;; (define (f x)
;; (letrec ((even?
;; (lambda (n)
;; (if (= n 0)
;; true
;; (odd? (- n 1)))))
;; (odd?
;; (lambda (n)
;; (if (= n 0)
;; false
;; (even? (- n 1))))))
;; <REST OF BODY OF `F'>))
;;
;; `Letrec' expressions, which have the form
;;
( ( ( < > < EXP_1 > ) ... ( < VAR_N > < EXP_N > ) )
;; <BODY>)
;;
;; are a variation on `let' in which the expressions <EXP_K> that
;; provide the initial values for the variables <VAR_K> are evaluated
;; in an environment that includes all the `letrec' bindings. This
;; permits recursion in the bindings, such as the mutual recursion of
` even ? ' and ` odd ? ' in the example above , or the evaluation of 10
;; factorial with
;;
( ( ( fact
;; (lambda (n)
;; (if (= n 1)
1
;; (* n (fact (- n 1)))))))
( fact 10 ) )
;;
;; a. Implement `letrec' as a derived expression, by transforming a
;; `letrec' expression into a `let' expression as shown in the
text above or in * Note Exercise 4 - 18 : : . That is , the
;; `letrec' variables should be created with a `let' and then be
;; assigned their values with `set!'.
;;
b. is confused by all this fuss about internal
;; definitions. The way he sees it, if you don't like to use
;; `define' inside a procedure, you can just use `let'.
;; Illustrate what is loose about his reasoning by drawing an
;; environment diagram that shows the environment in which the
;; <REST OF BODY OF `F'> is evaluated during evaluation of the
;; expression `(f 5)', with `f' defined as in this exercise.
;; Draw an environment diagram for the same evaluation, but with
;; `let' in place of `letrec' in the definition of `f'.
| null | https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_4/exercise.4.20.scm | scheme | Because internal definitions look sequential but
are actually simultaneous, some people prefer to avoid them
looks like `let', so it is not surprising that the variables it
binds are bound simultaneously and have the same scope as each
other. The sample procedure `f' above can be written without
internal definitions, but with exactly the same meaning, as
(define (f x)
(letrec ((even?
(lambda (n)
(if (= n 0)
true
(odd? (- n 1)))))
(odd?
(lambda (n)
(if (= n 0)
false
(even? (- n 1))))))
<REST OF BODY OF `F'>))
`Letrec' expressions, which have the form
<BODY>)
are a variation on `let' in which the expressions <EXP_K> that
provide the initial values for the variables <VAR_K> are evaluated
in an environment that includes all the `letrec' bindings. This
permits recursion in the bindings, such as the mutual recursion of
factorial with
(lambda (n)
(if (= n 1)
(* n (fact (- n 1)))))))
a. Implement `letrec' as a derived expression, by transforming a
`letrec' expression into a `let' expression as shown in the
`letrec' variables should be created with a `let' and then be
assigned their values with `set!'.
definitions. The way he sees it, if you don't like to use
`define' inside a procedure, you can just use `let'.
Illustrate what is loose about his reasoning by drawing an
environment diagram that shows the environment in which the
<REST OF BODY OF `F'> is evaluated during evaluation of the
expression `(f 5)', with `f' defined as in this exercise.
Draw an environment diagram for the same evaluation, but with
`let' in place of `letrec' in the definition of `f'. | #!/usr/bin/env csi -s
(require rackunit)
(require-library eval)
(import eval)
Exercise 4.20
entirely , and use the special form ` letrec ' instead . ` Letrec '
( ( ( < > < EXP_1 > ) ... ( < VAR_N > < EXP_N > ) )
` even ? ' and ` odd ? ' in the example above , or the evaluation of 10
( ( ( fact
1
( fact 10 ) )
text above or in * Note Exercise 4 - 18 : : . That is , the
b. is confused by all this fuss about internal
|
22283dab489d3480ab4b2ec0b93ee3944100b1831d0d7f4ed7f4006abac469a3 | cicakhq/potato | misc-core.lisp | (in-package :potato.core)
(declaim #.potato.common::*compile-decl*)
(deftype byte-vector () '(vector (unsigned-byte 8) *))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Conditions. Perhaps these definitions belong in its own file.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-condition potato-error (error)
((message :type string
:initarg :message
:initform "Unknown message"
:reader potato-error/message))
(:report (lambda (condition stream)
(format stream "Potato error: ~a" (potato-error/message condition))))
(:documentation "Common superclass for errors thrown by web functions"))
(defgeneric potato-error/response-status (condition)
(:method ((condition t)) hunchentoot:+http-internal-server-error+)
(:documentation "The response status that this error should return to the HTTP client"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-condition permission-error (potato-error)
()
(:documentation "Error that is raised when permissions are violated"))
(defmethod potato-error/response-status ((condition permission-error))
hunchentoot:+http-forbidden+)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-condition not-logged-in-error (potato-error)
()
(:documentation "Error that is raised when an action which requres login in performed."))
(defmethod potato-error/response-status ((condition not-logged-in-error))
hunchentoot:+http-authorization-required+)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-condition custom-response-status-mixin (condition)
((status :type integer
:initarg :status
:reader custom-response-status-mixin/status
:initform hunchentoot:+http-internal-server-error+)))
(defmethod potato-error/response-status ((condition custom-response-status-mixin))
(custom-response-status-mixin/status condition))
(define-condition web-parameter-error (potato-error custom-response-status-mixin)
()
(:documentation "Error that is raised when the input parameters to a web function are incorrect"))
(define-condition uri-not-found-error (potato-error custom-response-status-mixin)
()
(:documentation "Error that is raised when http error should be set to not found"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun raise-permission-error (message &rest args)
(error 'permission-error :message (apply #'format nil message args)))
(defun raise-web-parameter-error (message &rest args)
(error 'web-parameter-error :status hunchentoot:+http-not-acceptable+ :message (apply #'format nil message args)))
(defun raise-not-found-error (message &rest args)
(error 'uri-not-found-error :status hunchentoot:+http-not-found+ :message (apply #'format nil message args)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Various random functions which have no better home
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro cd-row->list (row &rest fields)
(let ((row-sym (gensym "ROW-")))
`(let ((,row-sym ,row))
(list ,@(loop
for field in fields
unless (stringp field)
do (error "Fields need to be strings")
collect `(cons ,(intern (string-upcase (substitute #\- #\_ field)) "KEYWORD")
(getfield ,(intern field "KEYWORD") ,row-sym)))))))
(defun trim-string (string)
(string-trim +BLANK-CHARS+ string))
(defun parse-timestamp (s)
(local-time:parse-timestring s))
(defun format-timestamp (stream ts)
(local-time:format-timestring stream ts
:format (append local-time:+iso-8601-date-format+
'("T")
local-time:+iso-8601-time-format+
'("Z"))
:timezone local-time:+utc-zone+))
(defvar *inhibit-lparallel* nil
"If true, run futures in the same thread. Used for testcases.")
(defmacro run-future (&body body)
(alexandria:with-gensyms (body-fn)
`(flet ((,body-fn () ,@body))
(if *inhibit-lparallel*
(,body-fn)
(lparallel:future
(,body-fn))))))
(defun call-clouchdb-invoke-view* (id view &rest options &key key keys start-key
start-key-docid end-key end-key-docid limit stale
descending skip group group-level reduce
include-docs)
"Invoke a view by specifiying the document ID that contains the view
and the name of the contained view. The key parameter specifies an
optional value to match against the view's mapped field. The start-key
and end-key values specify the optional begin and end range of the
mapped field(s) of each document to return. If descending is t,
returns results in reverse order. If update is t, does not refresh
view for query, use for higher performance but possible data
inconsistency."
(declare (ignore key keys start-key start-key-docid end-key end-key-docid
limit stale descending skip group group-level
reduce include-docs))
(clouchdb::ensure-db
(clouchdb::db-request (clouchdb::cat (clouchdb::url-encode (clouchdb::db-name clouchdb:*couchdb*)) "/_design/"
(clouchdb::url-encode id) "/_view/" (clouchdb::url-encode view))
:method :get
:parameters (clouchdb::transform-params options clouchdb::*view-options*))))
(pushnew '(:keys . ((:name . "keys") (:fn . clouchdb:document-to-json)))
clouchdb::*view-options* :key #'car)
(defun copy-alist-with-replacement (src key replacement &key (test #'eql))
(loop
for row in src
for tag = (car row)
when (funcall test tag key)
collect (cons tag replacement)
else collect row))
(defun is-allowed-email-p (email)
(cl-ppcre:scan "^[^@]+@[^@]+$" email))
(defun make-potato-url (suffix-format &rest suffix-args)
(with-output-to-string (s)
(if *external-listen-address*
(progn
(princ *external-listen-address* s)
(unless (eql (aref *external-listen-address* (1- (length *external-listen-address*))) #\/)
(princ "/" s)))
;; ELSE: No external listen address set, use default
(princ ":8080/" s))
(apply #'format s suffix-format suffix-args)))
| null | https://raw.githubusercontent.com/cicakhq/potato/88b6c92dbbc80a6c9552435604f7b1ae6f2a4026/src/potato/misc-core.lisp | lisp |
Conditions. Perhaps these definitions belong in its own file.
Various random functions which have no better home
ELSE: No external listen address set, use default | (in-package :potato.core)
(declaim #.potato.common::*compile-decl*)
(deftype byte-vector () '(vector (unsigned-byte 8) *))
(define-condition potato-error (error)
((message :type string
:initarg :message
:initform "Unknown message"
:reader potato-error/message))
(:report (lambda (condition stream)
(format stream "Potato error: ~a" (potato-error/message condition))))
(:documentation "Common superclass for errors thrown by web functions"))
(defgeneric potato-error/response-status (condition)
(:method ((condition t)) hunchentoot:+http-internal-server-error+)
(:documentation "The response status that this error should return to the HTTP client"))
(define-condition permission-error (potato-error)
()
(:documentation "Error that is raised when permissions are violated"))
(defmethod potato-error/response-status ((condition permission-error))
hunchentoot:+http-forbidden+)
(define-condition not-logged-in-error (potato-error)
()
(:documentation "Error that is raised when an action which requres login in performed."))
(defmethod potato-error/response-status ((condition not-logged-in-error))
hunchentoot:+http-authorization-required+)
(define-condition custom-response-status-mixin (condition)
((status :type integer
:initarg :status
:reader custom-response-status-mixin/status
:initform hunchentoot:+http-internal-server-error+)))
(defmethod potato-error/response-status ((condition custom-response-status-mixin))
(custom-response-status-mixin/status condition))
(define-condition web-parameter-error (potato-error custom-response-status-mixin)
()
(:documentation "Error that is raised when the input parameters to a web function are incorrect"))
(define-condition uri-not-found-error (potato-error custom-response-status-mixin)
()
(:documentation "Error that is raised when http error should be set to not found"))
(defun raise-permission-error (message &rest args)
(error 'permission-error :message (apply #'format nil message args)))
(defun raise-web-parameter-error (message &rest args)
(error 'web-parameter-error :status hunchentoot:+http-not-acceptable+ :message (apply #'format nil message args)))
(defun raise-not-found-error (message &rest args)
(error 'uri-not-found-error :status hunchentoot:+http-not-found+ :message (apply #'format nil message args)))
(defmacro cd-row->list (row &rest fields)
(let ((row-sym (gensym "ROW-")))
`(let ((,row-sym ,row))
(list ,@(loop
for field in fields
unless (stringp field)
do (error "Fields need to be strings")
collect `(cons ,(intern (string-upcase (substitute #\- #\_ field)) "KEYWORD")
(getfield ,(intern field "KEYWORD") ,row-sym)))))))
(defun trim-string (string)
(string-trim +BLANK-CHARS+ string))
(defun parse-timestamp (s)
(local-time:parse-timestring s))
(defun format-timestamp (stream ts)
(local-time:format-timestring stream ts
:format (append local-time:+iso-8601-date-format+
'("T")
local-time:+iso-8601-time-format+
'("Z"))
:timezone local-time:+utc-zone+))
(defvar *inhibit-lparallel* nil
"If true, run futures in the same thread. Used for testcases.")
(defmacro run-future (&body body)
(alexandria:with-gensyms (body-fn)
`(flet ((,body-fn () ,@body))
(if *inhibit-lparallel*
(,body-fn)
(lparallel:future
(,body-fn))))))
(defun call-clouchdb-invoke-view* (id view &rest options &key key keys start-key
start-key-docid end-key end-key-docid limit stale
descending skip group group-level reduce
include-docs)
"Invoke a view by specifiying the document ID that contains the view
and the name of the contained view. The key parameter specifies an
optional value to match against the view's mapped field. The start-key
and end-key values specify the optional begin and end range of the
mapped field(s) of each document to return. If descending is t,
returns results in reverse order. If update is t, does not refresh
view for query, use for higher performance but possible data
inconsistency."
(declare (ignore key keys start-key start-key-docid end-key end-key-docid
limit stale descending skip group group-level
reduce include-docs))
(clouchdb::ensure-db
(clouchdb::db-request (clouchdb::cat (clouchdb::url-encode (clouchdb::db-name clouchdb:*couchdb*)) "/_design/"
(clouchdb::url-encode id) "/_view/" (clouchdb::url-encode view))
:method :get
:parameters (clouchdb::transform-params options clouchdb::*view-options*))))
(pushnew '(:keys . ((:name . "keys") (:fn . clouchdb:document-to-json)))
clouchdb::*view-options* :key #'car)
(defun copy-alist-with-replacement (src key replacement &key (test #'eql))
(loop
for row in src
for tag = (car row)
when (funcall test tag key)
collect (cons tag replacement)
else collect row))
(defun is-allowed-email-p (email)
(cl-ppcre:scan "^[^@]+@[^@]+$" email))
(defun make-potato-url (suffix-format &rest suffix-args)
(with-output-to-string (s)
(if *external-listen-address*
(progn
(princ *external-listen-address* s)
(unless (eql (aref *external-listen-address* (1- (length *external-listen-address*))) #\/)
(princ "/" s)))
(princ ":8080/" s))
(apply #'format s suffix-format suffix-args)))
|
9330035959db106d73120e47cfc3144b882a61f14e3c81d025ad67fa59254994 | mindpool/gambit-termite | match.scm | (define-macro (match/action on-success on-fail datum . clauses)
(let ((tmp (gensym))
(succ (gensym))
(fail (gensym)))
`(let ((,tmp ,datum)
(,succ (lambda () ,on-success)) ;; the thunk for success is lifted
(,fail (lambda () ,on-fail))) ;; the thunk for failure is lifted
,(compile-pattern-match `(,succ) `(,fail) clauses tmp))))
(define-macro (match datum . clauses)
(let ((tmp (gensym))
(fail (gensym)))
`(let* ((,tmp ,datum)
(,fail (lambda ()
(raise
(list bad-match: ,tmp)))))
,(compile-pattern-match
#f
`(,fail)
clauses
tmp))))
| null | https://raw.githubusercontent.com/mindpool/gambit-termite/391b75253cc3a5abd77dfc29392a72b2eca0d09e/match.scm | scheme | the thunk for success is lifted
the thunk for failure is lifted | (define-macro (match/action on-success on-fail datum . clauses)
(let ((tmp (gensym))
(succ (gensym))
(fail (gensym)))
`(let ((,tmp ,datum)
,(compile-pattern-match `(,succ) `(,fail) clauses tmp))))
(define-macro (match datum . clauses)
(let ((tmp (gensym))
(fail (gensym)))
`(let* ((,tmp ,datum)
(,fail (lambda ()
(raise
(list bad-match: ,tmp)))))
,(compile-pattern-match
#f
`(,fail)
clauses
tmp))))
|
c909fea9836d50af935ef1f26f754393eb97588ccd890525a0adf0963cef18c0 | chenyukang/eopl | tests.scm | (module tests mzscheme
(provide test-list)
;;;;;;;;;;;;;;;; tests ;;;;;;;;;;;;;;;;
(define test-list
'(
;; simple arithmetic
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "-(44,33)" 11)
;; nested arithmetic
(nested-arith-left "-(-(44,33),22)" -11)
(nested-arith-right "-(55, -(22,11))" 44)
;; simple variables
(test-var-1 "x" 10)
(test-var-2 "-(x,1)" 9)
(test-var-3 "-(1,x)" -9)
;; simple unbound variables
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "-(x,foo)" error)
;; simple conditionals
(if-true "if zero?(0) then 3 else 4" 3)
(if-false "if zero?(1) then 3 else 4" 4)
;; test dynamic typechecking
(no-bool-to-diff-1 "-(zero?(0),1)" error)
(no-bool-to-diff-2 "-(1,zero?(0))" error)
(no-int-to-if "if 1 then 2 else 3" error)
;; make sure that the test and both arms get evaluated
;; properly.
(if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3)
(if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4)
;; and make sure the other arm doesn't get evaluated.
(if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3)
(if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4)
;; simple let
(simple-let-1 "let x = 3 in x" 3)
make sure the body and rhs get evaluated
(eval-let-body "let x = 3 in -(x,1)" 2)
(eval-let-rhs "let x = -(4,1) in -(x,1)" 2)
;; check nested let and shadowing
(simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1)
(check-shadowing-in-body "let x = 3 in let x = 4 in x" 4)
(check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2)
;; simple applications
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)"
-1)
(y-combinator-1 "
let fix = proc (f)
let d = proc (x) proc (z) ((f (x x)) z)
in proc (n) ((f (d d)) n)
in let
t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4)
in let times4 = (fix t4m)
in (times4 3)" 12)
))
) | null | https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/base/chapter3/proc-lang/ds-rep/tests.scm | scheme | tests ;;;;;;;;;;;;;;;;
simple arithmetic
nested arithmetic
simple variables
simple unbound variables
simple conditionals
test dynamic typechecking
make sure that the test and both arms get evaluated
properly.
and make sure the other arm doesn't get evaluated.
simple let
check nested let and shadowing
simple applications
| (module tests mzscheme
(provide test-list)
(define test-list
'(
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "-(44,33)" 11)
(nested-arith-left "-(-(44,33),22)" -11)
(nested-arith-right "-(55, -(22,11))" 44)
(test-var-1 "x" 10)
(test-var-2 "-(x,1)" 9)
(test-var-3 "-(1,x)" -9)
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "-(x,foo)" error)
(if-true "if zero?(0) then 3 else 4" 3)
(if-false "if zero?(1) then 3 else 4" 4)
(no-bool-to-diff-1 "-(zero?(0),1)" error)
(no-bool-to-diff-2 "-(1,zero?(0))" error)
(no-int-to-if "if 1 then 2 else 3" error)
(if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3)
(if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4)
(if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3)
(if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4)
(simple-let-1 "let x = 3 in x" 3)
make sure the body and rhs get evaluated
(eval-let-body "let x = 3 in -(x,1)" 2)
(eval-let-rhs "let x = -(4,1) in -(x,1)" 2)
(simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1)
(check-shadowing-in-body "let x = 3 in let x = 4 in x" 4)
(check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2)
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)"
-1)
(y-combinator-1 "
let fix = proc (f)
let d = proc (x) proc (z) ((f (x x)) z)
in proc (n) ((f (d d)) n)
in let
t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4)
in let times4 = (fix t4m)
in (times4 3)" 12)
))
) |
827d6e7a6918a9a892aef14d5fe6ffc879934f6d98d2a617a8aa045292783a52 | NorfairKing/super-user-spark | Types.hs | # LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module SuperUserSpark.Diagnose.Types where
import Import hiding ((<>))
import Data.Aeson
import Data.Hashable
import Text.Printf
import SuperUserSpark.Bake.Types
import SuperUserSpark.Compiler.Types
#if __GLASGOW_HASKELL__ < 840
import Data.Semigroup (Semigroup, (<>))
#endif
data DiagnoseAssignment = DiagnoseAssignment
{ diagnoseCardReference :: BakeCardReference
, diagnoseSettings :: DiagnoseSettings
} deriving (Show, Eq, Generic)
instance Validity DiagnoseAssignment
newtype DiagnoseSettings = DiagnoseSettings
{ diagnoseBakeSettings :: BakeSettings
} deriving (Show, Eq, Generic)
instance Validity DiagnoseSettings
defaultDiagnoseSettings :: DiagnoseSettings
defaultDiagnoseSettings =
DiagnoseSettings {diagnoseBakeSettings = defaultBakeSettings}
type SparkDiagnoser = ExceptT DiagnoseError (ReaderT DiagnoseSettings IO)
data DiagnoseError
= DiagnoseBakeError BakeError
| DiagnoseError String
deriving (Show, Eq, Generic)
instance Validity DiagnoseError
newtype HashDigest =
HashDigest Int
deriving (Show, Eq, Generic)
instance Validity HashDigest
instance Semigroup HashDigest where
HashDigest h1 <> HashDigest h2 = HashDigest $ h1 * 31 + h2
instance Monoid HashDigest where
mempty = HashDigest (hash ())
mappend = (<>)
instance Hashable HashDigest
instance ToJSON HashDigest where
toJSON (HashDigest i) = toJSON (printf "%016x" i :: String)
data Diagnostics
= Nonexistent
| IsFile
| IsDirectory
| IsLinkTo AbsP -- Could point to directory too.
| IsWeird
deriving (Show, Eq, Generic)
instance Validity Diagnostics
instance ToJSON Diagnostics where
toJSON Nonexistent = String "nonexistent"
toJSON IsFile = String "file"
toJSON IsDirectory = String "directory"
toJSON (IsLinkTo ap) =
object ["kind" .= String "link", "link destination" .= ap]
toJSON IsWeird = String "weird"
data DiagnosedFp = D
{ diagnosedFilePath :: AbsP
, diagnosedDiagnostics :: Diagnostics
, diagnosedHashDigest :: HashDigest
} deriving (Show, Eq, Generic)
instance Validity DiagnosedFp
instance ToJSON DiagnosedFp where
toJSON D {..} =
object $
["path" .= diagnosedFilePath, "diagnostics" .= diagnosedDiagnostics] ++
if diagnosedHashDigest == mempty
then []
else ["hash" .= diagnosedHashDigest]
type DiagnosedDeployment = Deployment DiagnosedFp
| null | https://raw.githubusercontent.com/NorfairKing/super-user-spark/3c286a52a0b81e083c0e6d39f6f2b02aa9bb9231/src/SuperUserSpark/Diagnose/Types.hs | haskell | # LANGUAGE OverloadedStrings #
Could point to directory too. | # LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
# LANGUAGE RecordWildCards #
module SuperUserSpark.Diagnose.Types where
import Import hiding ((<>))
import Data.Aeson
import Data.Hashable
import Text.Printf
import SuperUserSpark.Bake.Types
import SuperUserSpark.Compiler.Types
#if __GLASGOW_HASKELL__ < 840
import Data.Semigroup (Semigroup, (<>))
#endif
data DiagnoseAssignment = DiagnoseAssignment
{ diagnoseCardReference :: BakeCardReference
, diagnoseSettings :: DiagnoseSettings
} deriving (Show, Eq, Generic)
instance Validity DiagnoseAssignment
newtype DiagnoseSettings = DiagnoseSettings
{ diagnoseBakeSettings :: BakeSettings
} deriving (Show, Eq, Generic)
instance Validity DiagnoseSettings
defaultDiagnoseSettings :: DiagnoseSettings
defaultDiagnoseSettings =
DiagnoseSettings {diagnoseBakeSettings = defaultBakeSettings}
type SparkDiagnoser = ExceptT DiagnoseError (ReaderT DiagnoseSettings IO)
data DiagnoseError
= DiagnoseBakeError BakeError
| DiagnoseError String
deriving (Show, Eq, Generic)
instance Validity DiagnoseError
newtype HashDigest =
HashDigest Int
deriving (Show, Eq, Generic)
instance Validity HashDigest
instance Semigroup HashDigest where
HashDigest h1 <> HashDigest h2 = HashDigest $ h1 * 31 + h2
instance Monoid HashDigest where
mempty = HashDigest (hash ())
mappend = (<>)
instance Hashable HashDigest
instance ToJSON HashDigest where
toJSON (HashDigest i) = toJSON (printf "%016x" i :: String)
data Diagnostics
= Nonexistent
| IsFile
| IsDirectory
| IsWeird
deriving (Show, Eq, Generic)
instance Validity Diagnostics
instance ToJSON Diagnostics where
toJSON Nonexistent = String "nonexistent"
toJSON IsFile = String "file"
toJSON IsDirectory = String "directory"
toJSON (IsLinkTo ap) =
object ["kind" .= String "link", "link destination" .= ap]
toJSON IsWeird = String "weird"
data DiagnosedFp = D
{ diagnosedFilePath :: AbsP
, diagnosedDiagnostics :: Diagnostics
, diagnosedHashDigest :: HashDigest
} deriving (Show, Eq, Generic)
instance Validity DiagnosedFp
instance ToJSON DiagnosedFp where
toJSON D {..} =
object $
["path" .= diagnosedFilePath, "diagnostics" .= diagnosedDiagnostics] ++
if diagnosedHashDigest == mempty
then []
else ["hash" .= diagnosedHashDigest]
type DiagnosedDeployment = Deployment DiagnosedFp
|
aaea17ee5dd43ccf4f4c9c3fab81b2cf2b63e90f8a8f762193986872f5bb9a54 | ChicagoBoss/tinymq | tinymq_test.erl | -module(tinymq_test).
-export([run_tests/0]).
run_tests() ->
application:start(tinymq),
Channel1 = "channel1",
Ts1 = tinymq:now(Channel1),
tinymq:push(Channel1, "Hello!"),
Ts2 = tinymq:now(Channel1),
{ok, _, ["Hello!"]} = tinymq:poll(Channel1, Ts1),
{ok, _, []} = tinymq:poll(Channel1, Ts2),
tinymq:push(Channel1, "Goodbye!"),
{ok, _, ["Goodbye!"]} = tinymq:poll(Channel1, Ts2),
{ok, _, ["Hello!", "Goodbye!"]} = tinymq:poll(Channel1, Ts1),
{ok, _} = tinymq:subscribe(Channel1, 'now', self()),
tinymq:push(Channel1, "Greetings!"),
ok = receive
{_, _, ["Greetings!"]} ->
ok
after
1000 ->
not_ok
end,
{ok, _} = tinymq:subscribe(Channel1, Ts2, self()),
ok = receive
{_, _, ["Goodbye!", "Greetings!"]} ->
ok
after
1000 ->
not_ok
end,
io:format("Passed all tests~n", []).
| null | https://raw.githubusercontent.com/ChicagoBoss/tinymq/12fc8472442a46bc7130847625a68be33f88f181/tests/tinymq_test.erl | erlang | -module(tinymq_test).
-export([run_tests/0]).
run_tests() ->
application:start(tinymq),
Channel1 = "channel1",
Ts1 = tinymq:now(Channel1),
tinymq:push(Channel1, "Hello!"),
Ts2 = tinymq:now(Channel1),
{ok, _, ["Hello!"]} = tinymq:poll(Channel1, Ts1),
{ok, _, []} = tinymq:poll(Channel1, Ts2),
tinymq:push(Channel1, "Goodbye!"),
{ok, _, ["Goodbye!"]} = tinymq:poll(Channel1, Ts2),
{ok, _, ["Hello!", "Goodbye!"]} = tinymq:poll(Channel1, Ts1),
{ok, _} = tinymq:subscribe(Channel1, 'now', self()),
tinymq:push(Channel1, "Greetings!"),
ok = receive
{_, _, ["Greetings!"]} ->
ok
after
1000 ->
not_ok
end,
{ok, _} = tinymq:subscribe(Channel1, Ts2, self()),
ok = receive
{_, _, ["Goodbye!", "Greetings!"]} ->
ok
after
1000 ->
not_ok
end,
io:format("Passed all tests~n", []).
| |
7def71217dcf73f690a493a898d09544aa3284bc31afda09ab82acacfd587aa4 | AndrasKovacs/ELTE-func-lang | Notes08.hs | # LANGUAGE DeriveFunctor , , DeriveTraversable , MonadComprehensions #
module Notes08 where
import Data.Char
import Data.List
import Control.Applicative
import Control.Monad
-------------------------------------------------------------------------------
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
instance Functor Parser where
fmap f (Parser p) = Parser $ \s -> case p s of
Just (x, s') -> Just (f x, s')
Nothing -> Nothing
instance Applicative Parser where pure = return; (<*>) = ap
instance Monad Parser where
return x = Parser $ \s -> Just (x, s)
Parser p >>= f = Parser $ \s -> case p s of
Just (x, s') -> runParser (f x) s'
Nothing -> Nothing
putP :: String -> Parser ()
putP s = Parser $ \_ -> Just ((), s)
getP :: Parser String
getP = Parser $ \s -> Just (s, s)
empty' :: Parser a
empty' = Parser $ \_ -> Nothing
guard' :: Bool -> Parser ()
guard' True = pure ()
guard' False = empty'
-------------------------------------------------------------------------------
The ` eof ` ( end of file ) parser .
-- succeeds if the input string is empty, fails otherwise.
eof :: Parser ()
eof = Parser $ \s -> case s of
[] -> Just ((), [])
_ -> Nothing
eof' :: Parser ()
eof' = do
input <- getP
guard' (null input)
-- The parser `satisfy p` succeeds if the input string starts with a character
-- that satisfies the predicate p (and consumes that character), and fails otherwise.
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser $ \s -> case s of
c:cs | p c -> Just (c, cs)
| otherwise -> Nothing
[] -> Nothing
satisfy' :: (Char -> Bool) -> Parser Char
satisfy' p = do
input <- getP
case input of
c:cs | p c -> do
putP cs
pure c
_ -> empty
-------------------------------------------------------------------------------
-- The parser `char c` should succeed if the input string start with the character c.
-- Examples:
-- runParser (char 'a') "" == Nothing
runParser ( char ' a ' ) " abc " = = Just ( ( ) , " bc " )
runParser ( char ' a ' ) " bcd " = = Nothing
char :: Char -> Parser ()
char c = satisfy (== c) *> pure ()
The parser anyChar should succeed if the input string is not empty , and return its first character .
-- Examples:
" " = = Nothing
" ( ) " = = Just ( ' ( ' , " ) " )
" abc " = = Just ( ' a ' , " bc " )
anyChar :: Parser Char
anyChar = satisfy (const True)
-- The parser `string s` should succeed if the input string starts with the string s.
( string " abc " ) " abdef " = = Nothing
( string " " ) " abcdef " = = Just ( ( ) , " abcdef " )
( string " abc " ) " abcdef " = = Just ( ( ) , " def " )
string :: String -> Parser ()
string s = forM_ s char
-------------------------------------------------------------------------------
-- class Applicative f => Alternative f where
-- empty :: f a
-- (<|>) :: f a -> f a -> f a
instance Alternative Parser where
-- The parser `empty` always fails.
empty = Parser $ \_ -> Nothing
-- The parser `p1 <|> p2` tries the parser p1.
-- If p1 succeeds, it returns the result of p1.
-- If p1 fails, then it tries the parser p2 instead.
(<|>) (Parser f) (Parser g) = Parser $ \s -> case f s of
Nothing -> g s
x -> x
-------------------------------------------------------------------------------
-- The parser `some p` and `many p` both try to use the parser p as many times as possible.
-- `many p` always succeeds.
` some p ` succeeds if the first run of p succeeded .
some' :: Parser a -> Parser [a]
many' :: Parser a -> Parser [a]
` some ' p ` uses p at least 1 times
= > ` some ' p ` uses p once , and then uses p again any number of times .
some' p = do
x <- p
xs <- many' p
pure $ (x : xs)
-- (:) <$> p <*> many p
` many ' p ` uses p any number of times
= > ` many ' p ` uses p either ( at least 1 times ) or does n't use p.
many' p = some p
<|> pure []
-- many p /= pure [] <|> some p
-- Examples:
( some ( char ' a ' ) ) " aaabbb " = Just ( " aaa " , " bbb " )
( some ( char ' a ' ) ) " bbb " = Nothing
( many ( char ' a ' ) ) " aaabbb " = Just ( " aaa " , " bbb " )
( many ( char ' a ' ) ) " bbb " = Just ( " " , " bbb " )
-------------------------------------------------------------------------------
The parser digit should parse a digit between 0 and 9 .
digit :: Parser Integer
-- digit = fromIntegral . digitToInt <$> satisfy isDigit
digit = do
c <- satisfy isDigit
pure (fromIntegral (digitToInt c))
-- <$> : same as fmap
-- The parser digit should parse a positive integer
posInt :: Parser Integer
posInt = foldl' (\x y -> 10*x+y) 0 <$> some digit
-- The parser int should parse a positive or negative integer
int :: Parser Integer
int = negInt <|> posInt
where negInt = char '-' *> (negate <$> posInt)
-- The parser `space` should parse a single whitespace character.
Hint : use ` isSpace : : Bool `
space :: Parser ()
space = satisfy isSpace *> pure ()
-- The parser `ws` should parse as many whitespace characters as possible.
ws :: Parser ()
ws = many space *> pure ()
--------------------------------------------------------------------------------
-- Parsing a simple configuration file.
-- A configuration file is a list of lines "key = value" where key is an
-- identifier and value is an integer.
pLine :: Parser (String, Integer)
pLine = do
ws
-- k <- some isAlpha
k <- some (satisfy isAlphaNum)
guard (isAlpha (head k))
-- k is any non-empty string of alphanumeric characters, starting from an alphabetic character.
ws
char '='
ws
v <- int
pure (k, v)
pFile :: Parser [(String, Integer)]
pFile = do
kvs <- many pLine
ws
eof
pure kvs
test1, test2, test3, test4 :: String
test1 = ""
test2 = "key = 10"
test3 = "key1 = 10 \nkey2 = 100"
test4 = " key = 10 \n key2 = 0 \n key3 = -10 "
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/88d41930999d6056bdd7bfaa85761a527cce4113/2020-21-1/gyak_3/Notes08.hs | haskell | -----------------------------------------------------------------------------
-----------------------------------------------------------------------------
succeeds if the input string is empty, fails otherwise.
The parser `satisfy p` succeeds if the input string starts with a character
that satisfies the predicate p (and consumes that character), and fails otherwise.
-----------------------------------------------------------------------------
The parser `char c` should succeed if the input string start with the character c.
Examples:
runParser (char 'a') "" == Nothing
Examples:
The parser `string s` should succeed if the input string starts with the string s.
-----------------------------------------------------------------------------
class Applicative f => Alternative f where
empty :: f a
(<|>) :: f a -> f a -> f a
The parser `empty` always fails.
The parser `p1 <|> p2` tries the parser p1.
If p1 succeeds, it returns the result of p1.
If p1 fails, then it tries the parser p2 instead.
-----------------------------------------------------------------------------
The parser `some p` and `many p` both try to use the parser p as many times as possible.
`many p` always succeeds.
(:) <$> p <*> many p
many p /= pure [] <|> some p
Examples:
-----------------------------------------------------------------------------
digit = fromIntegral . digitToInt <$> satisfy isDigit
<$> : same as fmap
The parser digit should parse a positive integer
The parser int should parse a positive or negative integer
The parser `space` should parse a single whitespace character.
The parser `ws` should parse as many whitespace characters as possible.
------------------------------------------------------------------------------
Parsing a simple configuration file.
A configuration file is a list of lines "key = value" where key is an
identifier and value is an integer.
k <- some isAlpha
k is any non-empty string of alphanumeric characters, starting from an alphabetic character.
------------------------------------------------------------------------------ | # LANGUAGE DeriveFunctor , , DeriveTraversable , MonadComprehensions #
module Notes08 where
import Data.Char
import Data.List
import Control.Applicative
import Control.Monad
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
instance Functor Parser where
fmap f (Parser p) = Parser $ \s -> case p s of
Just (x, s') -> Just (f x, s')
Nothing -> Nothing
instance Applicative Parser where pure = return; (<*>) = ap
instance Monad Parser where
return x = Parser $ \s -> Just (x, s)
Parser p >>= f = Parser $ \s -> case p s of
Just (x, s') -> runParser (f x) s'
Nothing -> Nothing
putP :: String -> Parser ()
putP s = Parser $ \_ -> Just ((), s)
getP :: Parser String
getP = Parser $ \s -> Just (s, s)
empty' :: Parser a
empty' = Parser $ \_ -> Nothing
guard' :: Bool -> Parser ()
guard' True = pure ()
guard' False = empty'
The ` eof ` ( end of file ) parser .
eof :: Parser ()
eof = Parser $ \s -> case s of
[] -> Just ((), [])
_ -> Nothing
eof' :: Parser ()
eof' = do
input <- getP
guard' (null input)
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser $ \s -> case s of
c:cs | p c -> Just (c, cs)
| otherwise -> Nothing
[] -> Nothing
satisfy' :: (Char -> Bool) -> Parser Char
satisfy' p = do
input <- getP
case input of
c:cs | p c -> do
putP cs
pure c
_ -> empty
runParser ( char ' a ' ) " abc " = = Just ( ( ) , " bc " )
runParser ( char ' a ' ) " bcd " = = Nothing
char :: Char -> Parser ()
char c = satisfy (== c) *> pure ()
The parser anyChar should succeed if the input string is not empty , and return its first character .
" " = = Nothing
" ( ) " = = Just ( ' ( ' , " ) " )
" abc " = = Just ( ' a ' , " bc " )
anyChar :: Parser Char
anyChar = satisfy (const True)
( string " abc " ) " abdef " = = Nothing
( string " " ) " abcdef " = = Just ( ( ) , " abcdef " )
( string " abc " ) " abcdef " = = Just ( ( ) , " def " )
string :: String -> Parser ()
string s = forM_ s char
instance Alternative Parser where
empty = Parser $ \_ -> Nothing
(<|>) (Parser f) (Parser g) = Parser $ \s -> case f s of
Nothing -> g s
x -> x
` some p ` succeeds if the first run of p succeeded .
some' :: Parser a -> Parser [a]
many' :: Parser a -> Parser [a]
` some ' p ` uses p at least 1 times
= > ` some ' p ` uses p once , and then uses p again any number of times .
some' p = do
x <- p
xs <- many' p
pure $ (x : xs)
` many ' p ` uses p any number of times
= > ` many ' p ` uses p either ( at least 1 times ) or does n't use p.
many' p = some p
<|> pure []
( some ( char ' a ' ) ) " aaabbb " = Just ( " aaa " , " bbb " )
( some ( char ' a ' ) ) " bbb " = Nothing
( many ( char ' a ' ) ) " aaabbb " = Just ( " aaa " , " bbb " )
( many ( char ' a ' ) ) " bbb " = Just ( " " , " bbb " )
The parser digit should parse a digit between 0 and 9 .
digit :: Parser Integer
digit = do
c <- satisfy isDigit
pure (fromIntegral (digitToInt c))
posInt :: Parser Integer
posInt = foldl' (\x y -> 10*x+y) 0 <$> some digit
int :: Parser Integer
int = negInt <|> posInt
where negInt = char '-' *> (negate <$> posInt)
Hint : use ` isSpace : : Bool `
space :: Parser ()
space = satisfy isSpace *> pure ()
ws :: Parser ()
ws = many space *> pure ()
pLine :: Parser (String, Integer)
pLine = do
ws
k <- some (satisfy isAlphaNum)
guard (isAlpha (head k))
ws
char '='
ws
v <- int
pure (k, v)
pFile :: Parser [(String, Integer)]
pFile = do
kvs <- many pLine
ws
eof
pure kvs
test1, test2, test3, test4 :: String
test1 = ""
test2 = "key = 10"
test3 = "key1 = 10 \nkey2 = 100"
test4 = " key = 10 \n key2 = 0 \n key3 = -10 "
|
7cf182cb4bdb00ac517bf491b451f6a303fe1fd29183a0acaf3b1eef0261e383 | cxphoe/SICP-solutions | 3.69.rkt | (load "pairs.rkt")
(define (triples S T U)
(let ((ps (pairs T U)))
(cons-stream
(cons (stream-car S) (stream-car ps))
(interleave
(stream-map (lambda (p) (cons (stream-car S) p))
(stream-cdr ps))
(triples (stream-cdr S) (stream-cdr T) (stream-cdr U))))))
(define (square-sum-equal? tris)
(define (square x) (* x x))
(= (+ (square (car tris)) (square (cadr tris)))
(square (caddr tris))))
(define pyth (stream-filter square-sum-equal?
(triples integars integars integars)))
(define (p n)
(display (stream-ref pyth (- n 1)))) | null | https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%203-Modeling%20with%20Mutable%20Data/5.Stream/3.69.rkt | racket | (load "pairs.rkt")
(define (triples S T U)
(let ((ps (pairs T U)))
(cons-stream
(cons (stream-car S) (stream-car ps))
(interleave
(stream-map (lambda (p) (cons (stream-car S) p))
(stream-cdr ps))
(triples (stream-cdr S) (stream-cdr T) (stream-cdr U))))))
(define (square-sum-equal? tris)
(define (square x) (* x x))
(= (+ (square (car tris)) (square (cadr tris)))
(square (caddr tris))))
(define pyth (stream-filter square-sum-equal?
(triples integars integars integars)))
(define (p n)
(display (stream-ref pyth (- n 1)))) | |
7aaabf53abe54ce240264d40f4b256c3ce9a2a1cb9d8fce654ad25f1ef8aabf1 | helvm/helma | AutoOptions.hs | module HelVM.HelMA.Automaton.API.AutoOptions where
import HelVM.HelMA.Automaton.Types.CellType
import HelVM.HelMA.Automaton.Types.IntCellType
import HelVM.HelMA.Automaton.Types.RAMType
import HelVM.HelMA.Automaton.Types.StackType
-- | Types
data AutoOptions = AutoOptions
{ ram :: !RAMType
, stack :: !StackType
, cell :: !CellType
, intCell :: !IntCellType
}
| null | https://raw.githubusercontent.com/helvm/helma/2ae31668ce11ded53daf01effe25047d5ce471cf/hs/src/HelVM/HelMA/Automaton/API/AutoOptions.hs | haskell | | Types | module HelVM.HelMA.Automaton.API.AutoOptions where
import HelVM.HelMA.Automaton.Types.CellType
import HelVM.HelMA.Automaton.Types.IntCellType
import HelVM.HelMA.Automaton.Types.RAMType
import HelVM.HelMA.Automaton.Types.StackType
data AutoOptions = AutoOptions
{ ram :: !RAMType
, stack :: !StackType
, cell :: !CellType
, intCell :: !IntCellType
}
|
8e2a0dc9df6dc69a60775322def861e616314f52e9bae8fb6cfa9d500e349a5d | anwarmamat/cmsc330fall20 | disc3.ml | (* Part 1: Type inference *)
let f1 a b = a + b;;
let f2 a b = if a then b else a;;
let f3 a b c = if (a +. b) == 0.0 then "Hi" else c;;
Part 2 : Type definition
let tf1 a = failwith "unimplemented"
let tf2 a b c = failwith "unimplemented"
let tf3 a b = failwith "unimplemented"
Part 3 : Functions
let concat str1 str2 = failwith "unimplemented";;
let add_to_float integer flt = failwith "unimplemented";;
let rec fib n = failwith "unimplemented";;
Part 4 : Lists
let rec add_three lst = failwith "unimplemented";;
let rec filter n lst = failwith "unimplemented";;
let rec double lst = failwith "unimplemented";;
| null | https://raw.githubusercontent.com/anwarmamat/cmsc330fall20/1f185a757ad86c37587ec15d580ea0ff728d9472/disc3/src/disc3.ml | ocaml | Part 1: Type inference |
let f1 a b = a + b;;
let f2 a b = if a then b else a;;
let f3 a b c = if (a +. b) == 0.0 then "Hi" else c;;
Part 2 : Type definition
let tf1 a = failwith "unimplemented"
let tf2 a b c = failwith "unimplemented"
let tf3 a b = failwith "unimplemented"
Part 3 : Functions
let concat str1 str2 = failwith "unimplemented";;
let add_to_float integer flt = failwith "unimplemented";;
let rec fib n = failwith "unimplemented";;
Part 4 : Lists
let rec add_three lst = failwith "unimplemented";;
let rec filter n lst = failwith "unimplemented";;
let rec double lst = failwith "unimplemented";;
|
05a1fb44ead250306f72dfc441ef0ef7b218141c301e2113ada3db940d24be9c | lndl/chesssimple | Color.hs | # LANGUAGE DeriveGeneric , DeriveAnyClass #
module Chesssimple.Color (Color(Black, White), switch) where
import Control.DeepSeq
import GHC.Generics (Generic)
data Color = White | Black deriving (Eq, Generic, NFData)
instance Show Color where
show Black = "-"
show White = "+"
switch :: Color -> Color
switch Black = White
switch White = Black
| null | https://raw.githubusercontent.com/lndl/chesssimple/dec08b72d72bc9dee62a11486c8d2b5126de612a/Chesssimple/Color.hs | haskell | # LANGUAGE DeriveGeneric , DeriveAnyClass #
module Chesssimple.Color (Color(Black, White), switch) where
import Control.DeepSeq
import GHC.Generics (Generic)
data Color = White | Black deriving (Eq, Generic, NFData)
instance Show Color where
show Black = "-"
show White = "+"
switch :: Color -> Color
switch Black = White
switch White = Black
| |
67e96363e7cbaf0404800483f62f0ee98ba11bc7e36bf159d9d7ee620fa5f79f | haskellari/edit-distance | SquareSTUArray.hs | # LANGUAGE PatternGuards , ScopedTypeVariables , BangPatterns , Trustworthy #
module Text.EditDistance.SquareSTUArray (
levenshteinDistance, levenshteinDistanceWithLengths, restrictedDamerauLevenshteinDistance, restrictedDamerauLevenshteinDistanceWithLengths
) where
import Text.EditDistance.EditCosts
import Text.EditDistance.MonadUtilities
import Text.EditDistance.ArrayUtilities
import Control.Monad hiding (foldM)
import Control.Monad.ST
import Data.Array.ST
levenshteinDistance :: EditCosts -> String -> String -> Int
levenshteinDistance !costs str1 str2 = levenshteinDistanceWithLengths costs str1_len str2_len str1 str2
where
str1_len = length str1
str2_len = length str2
levenshteinDistanceWithLengths :: EditCosts -> Int -> Int -> String -> String -> Int
levenshteinDistanceWithLengths !costs !str1_len !str2_len str1 str2 = runST (levenshteinDistanceST costs str1_len str2_len str1 str2)
levenshteinDistanceST :: EditCosts -> Int -> Int -> String -> String -> ST s Int
levenshteinDistanceST !costs !str1_len !str2_len str1 str2 = do
-- Create string arrays
str1_array <- stringToArray str1 str1_len
str2_array <- stringToArray str2 str2_len
-- Create array of costs. Say we index it by (i, j) where i is the column index and j the row index.
Rows correspond to characters of str2 and columns to characters of str1 .
cost_array <- newArray_ ((0, 0), (str1_len, str2_len)) :: ST s (STUArray s (Int, Int) Int)
read_str1 <- unsafeReadArray' str1_array
read_str2 <- unsafeReadArray' str2_array
read_cost <- unsafeReadArray' cost_array
write_cost <- unsafeWriteArray' cost_array
Fill out the first row ( j = 0 )
_ <- (\f -> foldM f (1, 0) str1) $ \(i, deletion_cost) col_char -> let deletion_cost' = deletion_cost + deletionCost costs col_char in write_cost (i, 0) deletion_cost' >> return (i + 1, deletion_cost')
Fill the remaining rows ( j > = 1 )
_ <- (\f -> foldM f 0 [1..str2_len]) $ \insertion_cost (!j) -> do
row_char <- read_str2 j
Initialize the first element of the row ( i = 0 )
let insertion_cost' = insertion_cost + insertionCost costs row_char
write_cost (0, j) insertion_cost'
Fill the remaining elements of the row ( i > = 1 )
loopM_ 1 str1_len $ \(!i) -> do
col_char <- read_str1 i
cost <- standardCosts costs read_cost row_char col_char (i, j)
write_cost (i, j) cost
return insertion_cost'
-- Return an actual answer
read_cost (str1_len, str2_len)
restrictedDamerauLevenshteinDistance :: EditCosts -> String -> String -> Int
restrictedDamerauLevenshteinDistance costs str1 str2 = restrictedDamerauLevenshteinDistanceWithLengths costs str1_len str2_len str1 str2
where
str1_len = length str1
str2_len = length str2
restrictedDamerauLevenshteinDistanceWithLengths :: EditCosts -> Int -> Int -> String -> String -> Int
restrictedDamerauLevenshteinDistanceWithLengths costs str1_len str2_len str1 str2 = runST (restrictedDamerauLevenshteinDistanceST costs str1_len str2_len str1 str2)
restrictedDamerauLevenshteinDistanceST :: EditCosts -> Int -> Int -> String -> String -> ST s Int
restrictedDamerauLevenshteinDistanceST !costs str1_len str2_len str1 str2 = do
-- Create string arrays
str1_array <- stringToArray str1 str1_len
str2_array <- stringToArray str2 str2_len
-- Create array of costs. Say we index it by (i, j) where i is the column index and j the row index.
Rows correspond to characters of str2 and columns to characters of str1 .
cost_array <- newArray_ ((0, 0), (str1_len, str2_len)) :: ST s (STUArray s (Int, Int) Int)
read_str1 <- unsafeReadArray' str1_array
read_str2 <- unsafeReadArray' str2_array
read_cost <- unsafeReadArray' cost_array
write_cost <- unsafeWriteArray' cost_array
Fill out the first row ( j = 0 )
_ <- (\f -> foldM f (1, 0) str1) $ \(i, deletion_cost) col_char -> let deletion_cost' = deletion_cost + deletionCost costs col_char in write_cost (i, 0) deletion_cost' >> return (i + 1, deletion_cost')
Fill out the second row ( j = 1 )
when (str2_len > 0) $ do
initial_row_char <- read_str2 1
Initialize the first element of the second row ( i = 0 )
write_cost (0, 1) (insertionCost costs initial_row_char)
Initialize the remaining elements of the row ( i > = 1 )
loopM_ 1 str1_len $ \(!i) -> do
col_char <- read_str1 i
cost <- standardCosts costs read_cost initial_row_char col_char (i, 1)
write_cost (i, 1) cost
Fill the remaining rows ( j > = 2 )
loopM_ 2 str2_len (\(!j) -> do
row_char <- read_str2 j
prev_row_char <- read_str2 (j - 1)
Initialize the first element of the row ( i = 0 )
write_cost (0, j) (insertionCost costs row_char * j)
Initialize the second element of the row ( i = 1 )
when (str1_len > 0) $ do
col_char <- read_str1 1
cost <- standardCosts costs read_cost row_char col_char (1, j)
write_cost (1, j) cost
Fill the remaining elements of the row ( i > = 2 )
loopM_ 2 str1_len (\(!i) -> do
col_char <- read_str1 i
prev_col_char <- read_str1 (i - 1)
standard_cost <- standardCosts costs read_cost row_char col_char (i, j)
cost <- if prev_row_char == col_char && prev_col_char == row_char
then do transpose_cost <- fmap (+ (transpositionCost costs col_char row_char)) $ read_cost (i - 2, j - 2)
return (standard_cost `min` transpose_cost)
else return standard_cost
write_cost (i, j) cost))
-- Return an actual answer
read_cost (str1_len, str2_len)
# INLINE standardCosts #
standardCosts :: EditCosts -> ((Int, Int) -> ST s Int) -> Char -> Char -> (Int, Int) -> ST s Int
standardCosts !costs read_cost !row_char !col_char (!i, !j) = do
deletion_cost <- fmap (+ (deletionCost costs col_char)) $ read_cost (i - 1, j)
insertion_cost <- fmap (+ (insertionCost costs row_char)) $ read_cost (i, j - 1)
subst_cost <- fmap (+ if row_char == col_char
then 0
else (substitutionCost costs col_char row_char))
(read_cost (i - 1, j - 1))
return $ deletion_cost `min` insertion_cost `min` subst_cost
| null | https://raw.githubusercontent.com/haskellari/edit-distance/5521afd4f4966a947499a16cfc7ce6d9e0a028ee/Text/EditDistance/SquareSTUArray.hs | haskell | Create string arrays
Create array of costs. Say we index it by (i, j) where i is the column index and j the row index.
Return an actual answer
Create string arrays
Create array of costs. Say we index it by (i, j) where i is the column index and j the row index.
Return an actual answer | # LANGUAGE PatternGuards , ScopedTypeVariables , BangPatterns , Trustworthy #
module Text.EditDistance.SquareSTUArray (
levenshteinDistance, levenshteinDistanceWithLengths, restrictedDamerauLevenshteinDistance, restrictedDamerauLevenshteinDistanceWithLengths
) where
import Text.EditDistance.EditCosts
import Text.EditDistance.MonadUtilities
import Text.EditDistance.ArrayUtilities
import Control.Monad hiding (foldM)
import Control.Monad.ST
import Data.Array.ST
levenshteinDistance :: EditCosts -> String -> String -> Int
levenshteinDistance !costs str1 str2 = levenshteinDistanceWithLengths costs str1_len str2_len str1 str2
where
str1_len = length str1
str2_len = length str2
levenshteinDistanceWithLengths :: EditCosts -> Int -> Int -> String -> String -> Int
levenshteinDistanceWithLengths !costs !str1_len !str2_len str1 str2 = runST (levenshteinDistanceST costs str1_len str2_len str1 str2)
levenshteinDistanceST :: EditCosts -> Int -> Int -> String -> String -> ST s Int
levenshteinDistanceST !costs !str1_len !str2_len str1 str2 = do
str1_array <- stringToArray str1 str1_len
str2_array <- stringToArray str2 str2_len
Rows correspond to characters of str2 and columns to characters of str1 .
cost_array <- newArray_ ((0, 0), (str1_len, str2_len)) :: ST s (STUArray s (Int, Int) Int)
read_str1 <- unsafeReadArray' str1_array
read_str2 <- unsafeReadArray' str2_array
read_cost <- unsafeReadArray' cost_array
write_cost <- unsafeWriteArray' cost_array
Fill out the first row ( j = 0 )
_ <- (\f -> foldM f (1, 0) str1) $ \(i, deletion_cost) col_char -> let deletion_cost' = deletion_cost + deletionCost costs col_char in write_cost (i, 0) deletion_cost' >> return (i + 1, deletion_cost')
Fill the remaining rows ( j > = 1 )
_ <- (\f -> foldM f 0 [1..str2_len]) $ \insertion_cost (!j) -> do
row_char <- read_str2 j
Initialize the first element of the row ( i = 0 )
let insertion_cost' = insertion_cost + insertionCost costs row_char
write_cost (0, j) insertion_cost'
Fill the remaining elements of the row ( i > = 1 )
loopM_ 1 str1_len $ \(!i) -> do
col_char <- read_str1 i
cost <- standardCosts costs read_cost row_char col_char (i, j)
write_cost (i, j) cost
return insertion_cost'
read_cost (str1_len, str2_len)
restrictedDamerauLevenshteinDistance :: EditCosts -> String -> String -> Int
restrictedDamerauLevenshteinDistance costs str1 str2 = restrictedDamerauLevenshteinDistanceWithLengths costs str1_len str2_len str1 str2
where
str1_len = length str1
str2_len = length str2
restrictedDamerauLevenshteinDistanceWithLengths :: EditCosts -> Int -> Int -> String -> String -> Int
restrictedDamerauLevenshteinDistanceWithLengths costs str1_len str2_len str1 str2 = runST (restrictedDamerauLevenshteinDistanceST costs str1_len str2_len str1 str2)
restrictedDamerauLevenshteinDistanceST :: EditCosts -> Int -> Int -> String -> String -> ST s Int
restrictedDamerauLevenshteinDistanceST !costs str1_len str2_len str1 str2 = do
str1_array <- stringToArray str1 str1_len
str2_array <- stringToArray str2 str2_len
Rows correspond to characters of str2 and columns to characters of str1 .
cost_array <- newArray_ ((0, 0), (str1_len, str2_len)) :: ST s (STUArray s (Int, Int) Int)
read_str1 <- unsafeReadArray' str1_array
read_str2 <- unsafeReadArray' str2_array
read_cost <- unsafeReadArray' cost_array
write_cost <- unsafeWriteArray' cost_array
Fill out the first row ( j = 0 )
_ <- (\f -> foldM f (1, 0) str1) $ \(i, deletion_cost) col_char -> let deletion_cost' = deletion_cost + deletionCost costs col_char in write_cost (i, 0) deletion_cost' >> return (i + 1, deletion_cost')
Fill out the second row ( j = 1 )
when (str2_len > 0) $ do
initial_row_char <- read_str2 1
Initialize the first element of the second row ( i = 0 )
write_cost (0, 1) (insertionCost costs initial_row_char)
Initialize the remaining elements of the row ( i > = 1 )
loopM_ 1 str1_len $ \(!i) -> do
col_char <- read_str1 i
cost <- standardCosts costs read_cost initial_row_char col_char (i, 1)
write_cost (i, 1) cost
Fill the remaining rows ( j > = 2 )
loopM_ 2 str2_len (\(!j) -> do
row_char <- read_str2 j
prev_row_char <- read_str2 (j - 1)
Initialize the first element of the row ( i = 0 )
write_cost (0, j) (insertionCost costs row_char * j)
Initialize the second element of the row ( i = 1 )
when (str1_len > 0) $ do
col_char <- read_str1 1
cost <- standardCosts costs read_cost row_char col_char (1, j)
write_cost (1, j) cost
Fill the remaining elements of the row ( i > = 2 )
loopM_ 2 str1_len (\(!i) -> do
col_char <- read_str1 i
prev_col_char <- read_str1 (i - 1)
standard_cost <- standardCosts costs read_cost row_char col_char (i, j)
cost <- if prev_row_char == col_char && prev_col_char == row_char
then do transpose_cost <- fmap (+ (transpositionCost costs col_char row_char)) $ read_cost (i - 2, j - 2)
return (standard_cost `min` transpose_cost)
else return standard_cost
write_cost (i, j) cost))
read_cost (str1_len, str2_len)
# INLINE standardCosts #
standardCosts :: EditCosts -> ((Int, Int) -> ST s Int) -> Char -> Char -> (Int, Int) -> ST s Int
standardCosts !costs read_cost !row_char !col_char (!i, !j) = do
deletion_cost <- fmap (+ (deletionCost costs col_char)) $ read_cost (i - 1, j)
insertion_cost <- fmap (+ (insertionCost costs row_char)) $ read_cost (i, j - 1)
subst_cost <- fmap (+ if row_char == col_char
then 0
else (substitutionCost costs col_char row_char))
(read_cost (i - 1, j - 1))
return $ deletion_cost `min` insertion_cost `min` subst_cost
|
aef66895fe2b177efbb54ea3395cfdf6eea594099df4a30e24775d1bf2d38e9b | BradWBeer/clinch | package.lisp | package.lisp
Please see the licence.txt for the CLinch
(defpackage #:clinch
(:use #:cl)
;;(:shadow )
(:import-from :rtg-math.vectors :v!)
(:export
#:*uncollected*
#:defevent
#:*controllers*
#:*haptic*
#:*texture*
#:*entity*
;; run in main (opengl) thread. Returns when done.
#:!
;; run in main (opengl) thread but returns immediately.
#:!!
;; Make a vector from the arguments
#:v!
;; shortcut to reset an object
#:!0
;; shortcuts to reset node translation, rotation and scaling respectively.
#:!t0 #:!r0 #:!s0
;; shortcuts to set or perform node translation, rotation and scaling respectively.
#:!t #:!r #:!s
shortcuts to pullg and respectively ( setf ( ! > obj ) value ) works too .
#:!> #:!<
#:pullg #:pushg
#:!reset #:!reset-translation #:!reset-rotation #:!reset-scaling
#:rotation
#:scaling
#:scale
#:translation
#:children
#:transform
#:translate
#:rotate
#:resize
#:n*
#:decompose-transform
#:init
#:uninit
#:*root*
#:*window*
#:*context*
#:*fbo*
#:*projection*
#:*ortho-projection*
#:*viewport*
#:*node*
#:*ticks* #:*delta-ticks*
#:*default-on-idle*
#:*next*
#:*on-window-size-changed*
#:*on-window-resized*
#:*on-window-hidden*
#:*on-window-exposed*
#:*on-window-moved*
#:*on-window-minimized*
#:*on-window-maximized*
#:*on-window-restored*
#:*on-window-enter*
#:*on-window-leave*
#:*on-window-focus-gained*
#:*on-window-focus-lost*
#:*on-window-close*
#:*on-key-down*
#:*on-key-up*
#:*on-mouse-move*
#:*on-mouse-down*
#:*on-mouse-up*
#:*on-mouse-click*
#:*on-mouse-double-click*
#:*on-mouse-wheel-move*
#:*on-controller-button-down*
#:*on-controller-button-up*
#:*on-controller-added*
#:*on-controller-removed*
#:*on-controller-remapped*
#:*on-controller-axis-move*
#:*on-idle*
#:*on-quit*
#:*on-text-editing*
#:*on-text-input*
#:unload-all-uncollected
#:shader-program #:name
#:get-generic-single-color-shader
#:get-generic-per-vertex-color-shader
#:get-generic-solid-phong-shader
#:get-generic-single-texture-shader
#:get-generic-single-diffuse-light-shader
#:get-generic-single-diffuse-light-animation-shader
#:get-generic-single-diffuse-light-per-vertex-color-shader
#:shader-source #:program #:shader-compile #:frag-shader #:vert-shader #:attributes #:with-attributes #:uniforms #:with-uniforms #:use-shader-program #:get-uniform-id #:get-attribute-id #:attach-uniform #:unload #:bind-static-values-to-attribute
#:buffer #:index-buffer #:id #:qtype #:usage #:stride #:vertex-count #:target #:loaded #:get-size #:size-in-bytes #:bind-buffer-to-vertex-array #:bind-buffer-to-attribute-array #:draw-with-index-buffer #:draw-with-ranged-index-buffer #:map-buffer #:unmap-buffer #:unload #:with-mapped-buffer #:get-buffer-data
#:texture #:tex-id #:width #:height #:data-format #:stride #:target #:bind #:map-buffer #:unmap-buffer #:bind-sampler #:unload #:bind-with-pbo #:unbind-with-pbo #:with-temporary-pbo #:set-texture-color #:get-default-texture #:get-identity-texture
#:transform #:make-vector #:transform-point #:transform-points #:ray-triangle-intersect? #:make-matrix #:degrees->radians #:radians->degrees #:d->r #:r->d #:qtype #:transform #:transform->list #:m* #:transpose #:determinate #:scale #:translate #:rotate #:make-orthogonal-transform #:make-frustum-transform #:make-perspective-transform #:unproject #:get-screen-direction #:data-from-pointer #:make-pbo-for-texture #:make-quad #:make-quad-for-texture #:make-quad-and-texture
#:+pi+
#:ensure-float
#:get-keyframe #:get-animation-time #:animation #:animator #:frames #:current-position #:repeat #:run-speed #:run-length
#:play #:paused #:pause #:stop #:skip
#:update
#:texture-animation #:get-current-frame
#:node #:children #:changed? #:render #:traverse-node #:with-node #:with-new-node
#:enabled
#:make-foreign-array #:make-identity-matrix #:list->matrix #:copy-foreign-array #:fill-foreign-array #:cached-matrix #:matrix #:get-current-matrix #:update-current-matrix #:read-gl-matrix #:get-current-gl-matrix #:use-matrix #:save-matrix #:print-node-data #:m*m #:mT #:det #:m-1
#:entity #:render-values #:indexes #:render #:make-render-func #:slow-render #:render-value #:ray-entity-intersect?
#:make-pipeline #:pipeline-get-loop #:pipeline-get-init #:pipeline-get-uninit #:run-loop #:run-init #:run-uninit
#:viewport #:x #:y #:width #:height #:add-child #:remove-child #:resize #:quick-set
#:print-text #:with-paragraph
#:clear-cairo-context
#:with-surface-for-texture
#:with-context-for-texture
#:frame-buffer #:unbind #:depth-buffer #:make-depth-texture #:color-attachment #:make-color-texture #:with-fbo
#:clear-color #:attribute #:uniform #:init #:clean-up #:enable #:disable #:window-width #:window-height #:*parent*
#:walk-node-tree
#:topological-sort
))
| null | https://raw.githubusercontent.com/BradWBeer/clinch/421de1e4844a5142e37cb06805bc2d9d13ba048f/package.lisp | lisp | (:shadow )
run in main (opengl) thread. Returns when done.
run in main (opengl) thread but returns immediately.
Make a vector from the arguments
shortcut to reset an object
shortcuts to reset node translation, rotation and scaling respectively.
shortcuts to set or perform node translation, rotation and scaling respectively. | package.lisp
Please see the licence.txt for the CLinch
(defpackage #:clinch
(:use #:cl)
(:import-from :rtg-math.vectors :v!)
(:export
#:*uncollected*
#:defevent
#:*controllers*
#:*haptic*
#:*texture*
#:*entity*
#:!
#:!!
#:v!
#:!0
#:!t0 #:!r0 #:!s0
#:!t #:!r #:!s
shortcuts to pullg and respectively ( setf ( ! > obj ) value ) works too .
#:!> #:!<
#:pullg #:pushg
#:!reset #:!reset-translation #:!reset-rotation #:!reset-scaling
#:rotation
#:scaling
#:scale
#:translation
#:children
#:transform
#:translate
#:rotate
#:resize
#:n*
#:decompose-transform
#:init
#:uninit
#:*root*
#:*window*
#:*context*
#:*fbo*
#:*projection*
#:*ortho-projection*
#:*viewport*
#:*node*
#:*ticks* #:*delta-ticks*
#:*default-on-idle*
#:*next*
#:*on-window-size-changed*
#:*on-window-resized*
#:*on-window-hidden*
#:*on-window-exposed*
#:*on-window-moved*
#:*on-window-minimized*
#:*on-window-maximized*
#:*on-window-restored*
#:*on-window-enter*
#:*on-window-leave*
#:*on-window-focus-gained*
#:*on-window-focus-lost*
#:*on-window-close*
#:*on-key-down*
#:*on-key-up*
#:*on-mouse-move*
#:*on-mouse-down*
#:*on-mouse-up*
#:*on-mouse-click*
#:*on-mouse-double-click*
#:*on-mouse-wheel-move*
#:*on-controller-button-down*
#:*on-controller-button-up*
#:*on-controller-added*
#:*on-controller-removed*
#:*on-controller-remapped*
#:*on-controller-axis-move*
#:*on-idle*
#:*on-quit*
#:*on-text-editing*
#:*on-text-input*
#:unload-all-uncollected
#:shader-program #:name
#:get-generic-single-color-shader
#:get-generic-per-vertex-color-shader
#:get-generic-solid-phong-shader
#:get-generic-single-texture-shader
#:get-generic-single-diffuse-light-shader
#:get-generic-single-diffuse-light-animation-shader
#:get-generic-single-diffuse-light-per-vertex-color-shader
#:shader-source #:program #:shader-compile #:frag-shader #:vert-shader #:attributes #:with-attributes #:uniforms #:with-uniforms #:use-shader-program #:get-uniform-id #:get-attribute-id #:attach-uniform #:unload #:bind-static-values-to-attribute
#:buffer #:index-buffer #:id #:qtype #:usage #:stride #:vertex-count #:target #:loaded #:get-size #:size-in-bytes #:bind-buffer-to-vertex-array #:bind-buffer-to-attribute-array #:draw-with-index-buffer #:draw-with-ranged-index-buffer #:map-buffer #:unmap-buffer #:unload #:with-mapped-buffer #:get-buffer-data
#:texture #:tex-id #:width #:height #:data-format #:stride #:target #:bind #:map-buffer #:unmap-buffer #:bind-sampler #:unload #:bind-with-pbo #:unbind-with-pbo #:with-temporary-pbo #:set-texture-color #:get-default-texture #:get-identity-texture
#:transform #:make-vector #:transform-point #:transform-points #:ray-triangle-intersect? #:make-matrix #:degrees->radians #:radians->degrees #:d->r #:r->d #:qtype #:transform #:transform->list #:m* #:transpose #:determinate #:scale #:translate #:rotate #:make-orthogonal-transform #:make-frustum-transform #:make-perspective-transform #:unproject #:get-screen-direction #:data-from-pointer #:make-pbo-for-texture #:make-quad #:make-quad-for-texture #:make-quad-and-texture
#:+pi+
#:ensure-float
#:get-keyframe #:get-animation-time #:animation #:animator #:frames #:current-position #:repeat #:run-speed #:run-length
#:play #:paused #:pause #:stop #:skip
#:update
#:texture-animation #:get-current-frame
#:node #:children #:changed? #:render #:traverse-node #:with-node #:with-new-node
#:enabled
#:make-foreign-array #:make-identity-matrix #:list->matrix #:copy-foreign-array #:fill-foreign-array #:cached-matrix #:matrix #:get-current-matrix #:update-current-matrix #:read-gl-matrix #:get-current-gl-matrix #:use-matrix #:save-matrix #:print-node-data #:m*m #:mT #:det #:m-1
#:entity #:render-values #:indexes #:render #:make-render-func #:slow-render #:render-value #:ray-entity-intersect?
#:make-pipeline #:pipeline-get-loop #:pipeline-get-init #:pipeline-get-uninit #:run-loop #:run-init #:run-uninit
#:viewport #:x #:y #:width #:height #:add-child #:remove-child #:resize #:quick-set
#:print-text #:with-paragraph
#:clear-cairo-context
#:with-surface-for-texture
#:with-context-for-texture
#:frame-buffer #:unbind #:depth-buffer #:make-depth-texture #:color-attachment #:make-color-texture #:with-fbo
#:clear-color #:attribute #:uniform #:init #:clean-up #:enable #:disable #:window-width #:window-height #:*parent*
#:walk-node-tree
#:topological-sort
))
|
90710261d42efda7976af2bb70d6f9358bfc24761e97535d4659e74018aadaba | cljfx/cljfx | chart.clj | (ns cljfx.fx.chart
"Part of a public API"
(:require [cljfx.composite :as composite]
[cljfx.coerce :as coerce]
[cljfx.lifecycle :as lifecycle]
[cljfx.fx.region :as fx.region])
(:import [javafx.scene.chart Chart]
[javafx.geometry Side]))
(set! *warn-on-reflection* true)
(def props
(merge
fx.region/props
(composite/props Chart
;; overrides
:style-class [:list lifecycle/scalar :coerce coerce/style-class :default "chart"]
;; definitions
:animated [:setter lifecycle/scalar :default true]
:legend-side [:setter lifecycle/scalar :coerce (coerce/enum Side) :default :bottom]
:legend-visible [:setter lifecycle/scalar :default true]
:title [:setter lifecycle/scalar]
:title-side [:setter lifecycle/scalar :coerce (coerce/enum Side) :default :top])))
| null | https://raw.githubusercontent.com/cljfx/cljfx/ec3c34e619b2408026b9f2e2ff8665bebf70bf56/src/cljfx/fx/chart.clj | clojure | overrides
definitions | (ns cljfx.fx.chart
"Part of a public API"
(:require [cljfx.composite :as composite]
[cljfx.coerce :as coerce]
[cljfx.lifecycle :as lifecycle]
[cljfx.fx.region :as fx.region])
(:import [javafx.scene.chart Chart]
[javafx.geometry Side]))
(set! *warn-on-reflection* true)
(def props
(merge
fx.region/props
(composite/props Chart
:style-class [:list lifecycle/scalar :coerce coerce/style-class :default "chart"]
:animated [:setter lifecycle/scalar :default true]
:legend-side [:setter lifecycle/scalar :coerce (coerce/enum Side) :default :bottom]
:legend-visible [:setter lifecycle/scalar :default true]
:title [:setter lifecycle/scalar]
:title-side [:setter lifecycle/scalar :coerce (coerce/enum Side) :default :top])))
|
f291c66832e87da73adc27b12b6f9ab7f5731da116956a5762c636b6b5ae387a | marigold-dev/deku | print.ml | let instr oc width e = Sexpr.output oc width (Arrange.instr e)
let func oc width f = Sexpr.output oc width (Arrange.func f)
let module_ oc width m = Sexpr.output oc width (Arrange.module_ m)
let script oc width mode s =
List.iter (Sexpr.output oc width) (Arrange.script mode s)
| null | https://raw.githubusercontent.com/marigold-dev/deku/a26f31e0560ad12fd86cf7fa4667bb147247c7ef/deku-c/interpreter/text/print.ml | ocaml | let instr oc width e = Sexpr.output oc width (Arrange.instr e)
let func oc width f = Sexpr.output oc width (Arrange.func f)
let module_ oc width m = Sexpr.output oc width (Arrange.module_ m)
let script oc width mode s =
List.iter (Sexpr.output oc width) (Arrange.script mode s)
| |
ecaaae756ab04f00c82991ef9a404e68cfe2c0efcf16336ac300ad9d02e3151d | careercup/CtCI-6th-Edition-Clojure | chapter_4_q7_test.clj | (ns ^{:author "Leeor Engel"}
chapter-4.chapter-4-q7-test
(:require [clojure.test :refer :all]
[chapter-4.chapter-4-q7 :refer :all]))
(deftest build-order-test
(let [projects [:a :b :c :d :e :f]
dependencies [[:d :a]
[:b :f]
[:d :b]
[:a :f]
[:c :d]]]
(is (= [:e :f :a :b :d :c] (build-order projects dependencies))))
(let [projects [:a :b :c :d :e :f]
dependencies [[:d :a]
[:b :f]
[:d :b]
[:a :d]
[:a :f]
[:c :d]]]
(is (thrown? Exception (build-order projects dependencies)))))
| null | https://raw.githubusercontent.com/careercup/CtCI-6th-Edition-Clojure/ef151b94978af82fb3e0b1b0cd084d910870c52a/test/chapter_4/chapter_4_q7_test.clj | clojure | (ns ^{:author "Leeor Engel"}
chapter-4.chapter-4-q7-test
(:require [clojure.test :refer :all]
[chapter-4.chapter-4-q7 :refer :all]))
(deftest build-order-test
(let [projects [:a :b :c :d :e :f]
dependencies [[:d :a]
[:b :f]
[:d :b]
[:a :f]
[:c :d]]]
(is (= [:e :f :a :b :d :c] (build-order projects dependencies))))
(let [projects [:a :b :c :d :e :f]
dependencies [[:d :a]
[:b :f]
[:d :b]
[:a :d]
[:a :f]
[:c :d]]]
(is (thrown? Exception (build-order projects dependencies)))))
| |
a9ed7799a855f53d24c68f52282b95ee3943e19f5b9cffc1e31b15e8add1dad1 | MassD/99 | p71_STAR.ml |
Determine the internal path length of a tree . ( easy )
We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree . By this definition , the tree t in the figure of the previous problem has an internal path length of 9 . Write a function ipl tree that returns the internal path length of tree .
Determine the internal path length of a tree. (easy)
We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree. By this definition, the tree t in the figure of the previous problem has an internal path length of 9. Write a function ipl tree that returns the internal path length of tree.
*)
type 'a mult_tree = T of 'a * 'a mult_tree list
let ipl mt =
let rec ipl_aux p (T(_,mtl)) =
List.fold_left (fun acc mt -> acc+(ipl_aux (p+1) mt)) p mtl
in
ipl_aux 0 mt
let mt = T('a', [T('f',[T('g',[])]); T('c',[]);T('b',[T('d',[]); T('e',[])])]);;
let mt1 = T(1,[T(2,[]);T(3,[]);T(4,[])])
| null | https://raw.githubusercontent.com/MassD/99/1d3019eb55b0d621ed1df4132315673dd812b1e1/70c-73-multiway-trees/p71_STAR.ml | ocaml |
Determine the internal path length of a tree . ( easy )
We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree . By this definition , the tree t in the figure of the previous problem has an internal path length of 9 . Write a function ipl tree that returns the internal path length of tree .
Determine the internal path length of a tree. (easy)
We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree. By this definition, the tree t in the figure of the previous problem has an internal path length of 9. Write a function ipl tree that returns the internal path length of tree.
*)
type 'a mult_tree = T of 'a * 'a mult_tree list
let ipl mt =
let rec ipl_aux p (T(_,mtl)) =
List.fold_left (fun acc mt -> acc+(ipl_aux (p+1) mt)) p mtl
in
ipl_aux 0 mt
let mt = T('a', [T('f',[T('g',[])]); T('c',[]);T('b',[T('d',[]); T('e',[])])]);;
let mt1 = T(1,[T(2,[]);T(3,[]);T(4,[])])
| |
c08bcabbfa70cec64ce061d2a3011dde7257ee89e87ee662f2c2061e3860d5b9 | conal/lub | AssocRepr.hs | # LANGUAGE TypeFamilies , FlexibleContexts #
# OPTIONS_GHC -Wall #
----------------------------------------------------------------------
-- |
-- Module : Data.AssocRepr
Copyright : ( c ) Conal Elliott 2008
-- License : BSD3
--
-- Maintainer :
-- Stability : experimental
--
Compute least upper bounds ( lub / join ) of two values
--
This version uses associated types for HasRepr
----------------------------------------------------------------------
module Data.AssocRepr (HasRepr(..), onRepr, onRepr2) where
-- Reprs. TODO: find & use a simple, standard generic programming framework.
class HasRepr t where
type Repr t
repr :: t -> Repr t
unrepr :: Repr t -> t
-- | Apply a binary function on a repr
onRepr :: (HasRepr a, HasRepr b) =>
(Repr a -> Repr b)
-> (a -> b)
onRepr h = unrepr . h . repr
-- | Apply a binary function on a repr
onRepr2 :: (HasRepr a, HasRepr b, HasRepr c) =>
(Repr a -> Repr b -> Repr c)
-> (a -> b -> c)
onRepr2 op a b = unrepr (repr a `op` repr b)
-- Repr instances
instance HasRepr (Maybe a) where
type Repr (Maybe a) = Either () a
repr Nothing = (Left ())
repr (Just a) = (Right a)
unrepr (Left ()) = Nothing
unrepr (Right a) = (Just a)
instance HasRepr [a] where
type Repr [a] = Either () (a,[a])
repr [] = (Left ())
repr (a:as) = (Right (a,as))
unrepr (Left ()) = []
unrepr (Right (a,as)) = (a:as)
-- ...
| null | https://raw.githubusercontent.com/conal/lub/3a146841d1502febf3951d31ec963a4334cd1751/src/Data/AssocRepr.hs | haskell | --------------------------------------------------------------------
|
Module : Data.AssocRepr
License : BSD3
Maintainer :
Stability : experimental
--------------------------------------------------------------------
Reprs. TODO: find & use a simple, standard generic programming framework.
| Apply a binary function on a repr
| Apply a binary function on a repr
Repr instances
... | # LANGUAGE TypeFamilies , FlexibleContexts #
# OPTIONS_GHC -Wall #
Copyright : ( c ) Conal Elliott 2008
Compute least upper bounds ( lub / join ) of two values
This version uses associated types for HasRepr
module Data.AssocRepr (HasRepr(..), onRepr, onRepr2) where
class HasRepr t where
type Repr t
repr :: t -> Repr t
unrepr :: Repr t -> t
onRepr :: (HasRepr a, HasRepr b) =>
(Repr a -> Repr b)
-> (a -> b)
onRepr h = unrepr . h . repr
onRepr2 :: (HasRepr a, HasRepr b, HasRepr c) =>
(Repr a -> Repr b -> Repr c)
-> (a -> b -> c)
onRepr2 op a b = unrepr (repr a `op` repr b)
instance HasRepr (Maybe a) where
type Repr (Maybe a) = Either () a
repr Nothing = (Left ())
repr (Just a) = (Right a)
unrepr (Left ()) = Nothing
unrepr (Right a) = (Just a)
instance HasRepr [a] where
type Repr [a] = Either () (a,[a])
repr [] = (Left ())
repr (a:as) = (Right (a,as))
unrepr (Left ()) = []
unrepr (Right (a,as)) = (a:as)
|
5045d433ad360f5d415c1c79a67acc4404c4dfa5115fbf7d1121afb5a18557f0 | cognitect-labs/onto | project.clj | (defproject com.cognitect/onto "0.1.2-SNAPSHOT"
:description "Ontological inferencing for Datomic"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:plugins [[codox "0.8.10"]]
:dependencies [[org.clojure/clojure "1.9.0"]
[com.datomic/datomic-free "0.9.5656"]]
:codox {:src-dir-uri "-labs/onto/blob/master/"
:src-linenum-anchor-prefix "L"
:defaults {:doc/format :markdown}}
:profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"]]
:aliases {"ci" ["do" "clean," "test," "doc," "jar"]}}})
| null | https://raw.githubusercontent.com/cognitect-labs/onto/56eee1833254b902ec7bcf6b82d36e611c1ae207/project.clj | clojure | (defproject com.cognitect/onto "0.1.2-SNAPSHOT"
:description "Ontological inferencing for Datomic"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:plugins [[codox "0.8.10"]]
:dependencies [[org.clojure/clojure "1.9.0"]
[com.datomic/datomic-free "0.9.5656"]]
:codox {:src-dir-uri "-labs/onto/blob/master/"
:src-linenum-anchor-prefix "L"
:defaults {:doc/format :markdown}}
:profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"]]
:aliases {"ci" ["do" "clean," "test," "doc," "jar"]}}})
| |
102be3bc40a751a9e8a2fdd2577f304757d34549371471664d4816189fcaedf2 | input-output-hk/cardano-ledger-byron | Buildable.hs | # LANGUAGE TemplateHaskell #
module Test.Cardano.Chain.Buildable
( tests
)
where
import Cardano.Prelude
import Test.Cardano.Prelude
import Formatting (Buildable, build, sformat)
import Cardano.Chain.Common
( Attributes(Attributes)
, UnparsedFields(UnparsedFields)
)
import Hedgehog (PropertyT, eval, property)
import qualified Test.Cardano.Chain.Block.Gen as Block
import Test.Cardano.Chain.Block.Gen
( genBlockSignature
, genBlockWithEpochSlots
, genHeader
)
import qualified Test.Cardano.Chain.Common.Gen as Common
import qualified Test.Cardano.Chain.Delegation.Gen as Delegation
import qualified Test.Cardano.Chain.Genesis.Gen as Genesis
import qualified Test.Cardano.Chain.Slotting.Gen as Slotting
import Test.Cardano.Chain.Slotting.Gen (feedPMEpochSlots)
import qualified Test.Cardano.Chain.Update.Gen as Update
import qualified Test.Cardano.Chain.UTxO.Gen as UTxO
import Test.Cardano.Crypto.Gen (feedPM)
import Test.Options (TSGroup, TSProperty, eachOfTS)
--------------------------------------------------------------------------------
-- Test helpers
--------------------------------------------------------------------------------
tests :: TSGroup
tests = $$discoverPropArg
-- | Check that the 'Buildable' instance for @a@ doesn't throw exceptions
isBuildable :: Buildable a => a -> PropertyT IO ()
isBuildable = void . eval . sformat build
--------------------------------------------------------------------------------
-- Block
--------------------------------------------------------------------------------
ts_prop_blockIsBuildable :: TSProperty
ts_prop_blockIsBuildable =
eachOfTS 100 (feedPM genBlockWithEpochSlots) isBuildable
ts_prop_blockProofIsBuildable :: TSProperty
ts_prop_blockProofIsBuildable = eachOfTS 100 (feedPM Block.genProof) isBuildable
ts_prop_headerIsBuildable :: TSProperty
ts_prop_headerIsBuildable =
eachOfTS
100
(feedPMEpochSlots (Slotting.genWithEpochSlots genHeader))
isBuildable
ts_prop_blockSignatureIsBuildable :: TSProperty
ts_prop_blockSignatureIsBuildable =
eachOfTS 100 (feedPMEpochSlots genBlockSignature) isBuildable
--------------------------------------------------------------------------------
-- Common
--------------------------------------------------------------------------------
ts_prop_addrAttributesIsBuildable :: TSProperty
ts_prop_addrAttributesIsBuildable =
eachOfTS 100 Common.genAddrAttributes isBuildable
ts_prop_addrSpendingData :: TSProperty
ts_prop_addrSpendingData = eachOfTS 100 Common.genAddrSpendingData isBuildable
ts_prop_addressIsBuildable :: TSProperty
ts_prop_addressIsBuildable = eachOfTS 100 Common.genAddress isBuildable
ts_prop_attributesUnitIsBuildable :: TSProperty
ts_prop_attributesUnitIsBuildable =
const . property $ isBuildable (Attributes () (UnparsedFields mempty))
ts_prop_blockCountIsBuildable :: TSProperty
ts_prop_blockCountIsBuildable = eachOfTS 100 Common.genBlockCount isBuildable
ts_prop_chainDifficultyIsBuildable :: TSProperty
ts_prop_chainDifficultyIsBuildable =
eachOfTS 100 Common.genChainDifficulty isBuildable
ts_prop_keyHashIsBuildable :: TSProperty
ts_prop_keyHashIsBuildable = eachOfTS 100 Common.genKeyHash isBuildable
ts_prop_lovelaceIsBuildable :: TSProperty
ts_prop_lovelaceIsBuildable = eachOfTS 100 Common.genLovelace isBuildable
ts_prop_lovelacePortionIsBuildable :: TSProperty
ts_prop_lovelacePortionIsBuildable =
eachOfTS 100 Common.genLovelacePortion isBuildable
ts_prop_merkleRootIsBuildable :: TSProperty
ts_prop_merkleRootIsBuildable =
eachOfTS 100 (Common.genMerkleRoot (pure ())) isBuildable
ts_prop_networkMagicIsBuildable :: TSProperty
ts_prop_networkMagicIsBuildable =
eachOfTS 100 Common.genNetworkMagic isBuildable
ts_prop_txFeePolicyIsBuildable :: TSProperty
ts_prop_txFeePolicyIsBuildable = eachOfTS 100 Common.genTxFeePolicy isBuildable
ts_prop_txSizeLinearIsBuildable :: TSProperty
ts_prop_txSizeLinearIsBuildable =
eachOfTS 100 Common.genTxSizeLinear isBuildable
--------------------------------------------------------------------------------
-- Delegation
--------------------------------------------------------------------------------
ts_prop_delegationCertificateIsBuildable :: TSProperty
ts_prop_delegationCertificateIsBuildable =
eachOfTS 100 (feedPM Delegation.genCertificate) isBuildable
ts_prop_delegationPayloadIsBuildable :: TSProperty
ts_prop_delegationPayloadIsBuildable =
eachOfTS 100 (feedPM Delegation.genPayload) isBuildable
--------------------------------------------------------------------------------
Genesis
--------------------------------------------------------------------------------
ts_prop_genesisKeyHashesIsBuildable :: TSProperty
ts_prop_genesisKeyHashesIsBuildable =
eachOfTS 100 Genesis.genGenesisKeyHashes isBuildable
ts_prop_genesisNonAvvmBalancesIsBuildable :: TSProperty
ts_prop_genesisNonAvvmBalancesIsBuildable =
eachOfTS 100 Genesis.genGenesisNonAvvmBalances isBuildable
--------------------------------------------------------------------------------
-- Slotting
--------------------------------------------------------------------------------
ts_prop_epochAndSlotCountIsBuildable :: TSProperty
ts_prop_epochAndSlotCountIsBuildable =
eachOfTS
100
(Slotting.genEpochSlots >>= Slotting.genEpochAndSlotCount)
isBuildable
ts_prop_epochNumberIsBuildable :: TSProperty
ts_prop_epochNumberIsBuildable =
eachOfTS 100 Slotting.genEpochNumber isBuildable
ts_prop_epochSlotsIsBuildable :: TSProperty
ts_prop_epochSlotsIsBuildable = eachOfTS 100 Slotting.genEpochSlots isBuildable
ts_prop_slotCountIsBuildable :: TSProperty
ts_prop_slotCountIsBuildable = eachOfTS 100 Slotting.genSlotCount isBuildable
ts_prop_slotNumberIsBuilable :: TSProperty
ts_prop_slotNumberIsBuilable = eachOfTS 100 Slotting.genSlotNumber isBuildable
--------------------------------------------------------------------------------
-- Update
--------------------------------------------------------------------------------
ts_prop_applicationNameIsBuildable :: TSProperty
ts_prop_applicationNameIsBuildable =
eachOfTS 100 Update.genApplicationName isBuildable
ts_prop_installerHashIsBuildable :: TSProperty
ts_prop_installerHashIsBuildable =
eachOfTS 100 Update.genInstallerHash isBuildable
ts_prop_updatePayloadIsBuildable :: TSProperty
ts_prop_updatePayloadIsBuildable =
eachOfTS 100 (feedPM Update.genPayload) isBuildable
ts_prop_proposalIsBuiladble :: TSProperty
ts_prop_proposalIsBuiladble =
eachOfTS 100 (feedPM Update.genProposal) isBuildable
ts_prop_protocolParametersIsBuildable :: TSProperty
ts_prop_protocolParametersIsBuildable =
eachOfTS 100 Update.genProtocolParameters isBuildable
ts_prop_protocolParametersUpdateIsBuildable :: TSProperty
ts_prop_protocolParametersUpdateIsBuildable =
eachOfTS 100 Update.genProtocolParametersUpdate isBuildable
ts_prop_protocolVersionIsBuildable :: TSProperty
ts_prop_protocolVersionIsBuildable =
eachOfTS 100 Update.genProtocolVersion isBuildable
ts_prop_softforkRuleIsBuildable :: TSProperty
ts_prop_softforkRuleIsBuildable =
eachOfTS 100 Update.genSoftforkRule isBuildable
ts_prop_softwareVersionIsBuildable :: TSProperty
ts_prop_softwareVersionIsBuildable =
eachOfTS 100 Update.genSoftforkRule isBuildable
ts_prop_systemTagIsBuildable :: TSProperty
ts_prop_systemTagIsBuildable = eachOfTS 100 Update.genSystemTag isBuildable
ts_prop_voteIsBuildable :: TSProperty
ts_prop_voteIsBuildable = eachOfTS 100 (feedPM Update.genVote) isBuildable
--------------------------------------------------------------------------------
-- Update
--------------------------------------------------------------------------------
ts_prop_txIsBuildable :: TSProperty
ts_prop_txIsBuildable = eachOfTS 100 UTxO.genTx isBuildable
ts_prop_txInIsBuildable :: TSProperty
ts_prop_txInIsBuildable = eachOfTS 100 UTxO.genTxIn isBuildable
ts_prop_txOutIsBuildable :: TSProperty
ts_prop_txOutIsBuildable = eachOfTS 100 UTxO.genTxOut isBuildable
ts_prop_txAuxIsBuildable :: TSProperty
ts_prop_txAuxIsBuildable = eachOfTS 100 (feedPM UTxO.genTxAux) isBuildable
ts_prop_txProofIsBuildable :: TSProperty
ts_prop_txProofIsBuildable = eachOfTS 100 (feedPM UTxO.genTxProof) isBuildable
ts_prop_txInWitnessIsBuildable :: TSProperty
ts_prop_txInWitnessIsBuildable =
eachOfTS 100 (feedPM UTxO.genTxInWitness) isBuildable
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger-byron/d309449e6c303a9f0dcc8dcf172df6f0b3195ed5/cardano-ledger/test/Test/Cardano/Chain/Buildable.hs | haskell | ------------------------------------------------------------------------------
Test helpers
------------------------------------------------------------------------------
| Check that the 'Buildable' instance for @a@ doesn't throw exceptions
------------------------------------------------------------------------------
Block
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Common
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Delegation
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Slotting
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Update
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Update
------------------------------------------------------------------------------ | # LANGUAGE TemplateHaskell #
module Test.Cardano.Chain.Buildable
( tests
)
where
import Cardano.Prelude
import Test.Cardano.Prelude
import Formatting (Buildable, build, sformat)
import Cardano.Chain.Common
( Attributes(Attributes)
, UnparsedFields(UnparsedFields)
)
import Hedgehog (PropertyT, eval, property)
import qualified Test.Cardano.Chain.Block.Gen as Block
import Test.Cardano.Chain.Block.Gen
( genBlockSignature
, genBlockWithEpochSlots
, genHeader
)
import qualified Test.Cardano.Chain.Common.Gen as Common
import qualified Test.Cardano.Chain.Delegation.Gen as Delegation
import qualified Test.Cardano.Chain.Genesis.Gen as Genesis
import qualified Test.Cardano.Chain.Slotting.Gen as Slotting
import Test.Cardano.Chain.Slotting.Gen (feedPMEpochSlots)
import qualified Test.Cardano.Chain.Update.Gen as Update
import qualified Test.Cardano.Chain.UTxO.Gen as UTxO
import Test.Cardano.Crypto.Gen (feedPM)
import Test.Options (TSGroup, TSProperty, eachOfTS)
tests :: TSGroup
tests = $$discoverPropArg
isBuildable :: Buildable a => a -> PropertyT IO ()
isBuildable = void . eval . sformat build
ts_prop_blockIsBuildable :: TSProperty
ts_prop_blockIsBuildable =
eachOfTS 100 (feedPM genBlockWithEpochSlots) isBuildable
ts_prop_blockProofIsBuildable :: TSProperty
ts_prop_blockProofIsBuildable = eachOfTS 100 (feedPM Block.genProof) isBuildable
ts_prop_headerIsBuildable :: TSProperty
ts_prop_headerIsBuildable =
eachOfTS
100
(feedPMEpochSlots (Slotting.genWithEpochSlots genHeader))
isBuildable
ts_prop_blockSignatureIsBuildable :: TSProperty
ts_prop_blockSignatureIsBuildable =
eachOfTS 100 (feedPMEpochSlots genBlockSignature) isBuildable
ts_prop_addrAttributesIsBuildable :: TSProperty
ts_prop_addrAttributesIsBuildable =
eachOfTS 100 Common.genAddrAttributes isBuildable
ts_prop_addrSpendingData :: TSProperty
ts_prop_addrSpendingData = eachOfTS 100 Common.genAddrSpendingData isBuildable
ts_prop_addressIsBuildable :: TSProperty
ts_prop_addressIsBuildable = eachOfTS 100 Common.genAddress isBuildable
ts_prop_attributesUnitIsBuildable :: TSProperty
ts_prop_attributesUnitIsBuildable =
const . property $ isBuildable (Attributes () (UnparsedFields mempty))
ts_prop_blockCountIsBuildable :: TSProperty
ts_prop_blockCountIsBuildable = eachOfTS 100 Common.genBlockCount isBuildable
ts_prop_chainDifficultyIsBuildable :: TSProperty
ts_prop_chainDifficultyIsBuildable =
eachOfTS 100 Common.genChainDifficulty isBuildable
ts_prop_keyHashIsBuildable :: TSProperty
ts_prop_keyHashIsBuildable = eachOfTS 100 Common.genKeyHash isBuildable
ts_prop_lovelaceIsBuildable :: TSProperty
ts_prop_lovelaceIsBuildable = eachOfTS 100 Common.genLovelace isBuildable
ts_prop_lovelacePortionIsBuildable :: TSProperty
ts_prop_lovelacePortionIsBuildable =
eachOfTS 100 Common.genLovelacePortion isBuildable
ts_prop_merkleRootIsBuildable :: TSProperty
ts_prop_merkleRootIsBuildable =
eachOfTS 100 (Common.genMerkleRoot (pure ())) isBuildable
ts_prop_networkMagicIsBuildable :: TSProperty
ts_prop_networkMagicIsBuildable =
eachOfTS 100 Common.genNetworkMagic isBuildable
ts_prop_txFeePolicyIsBuildable :: TSProperty
ts_prop_txFeePolicyIsBuildable = eachOfTS 100 Common.genTxFeePolicy isBuildable
ts_prop_txSizeLinearIsBuildable :: TSProperty
ts_prop_txSizeLinearIsBuildable =
eachOfTS 100 Common.genTxSizeLinear isBuildable
ts_prop_delegationCertificateIsBuildable :: TSProperty
ts_prop_delegationCertificateIsBuildable =
eachOfTS 100 (feedPM Delegation.genCertificate) isBuildable
ts_prop_delegationPayloadIsBuildable :: TSProperty
ts_prop_delegationPayloadIsBuildable =
eachOfTS 100 (feedPM Delegation.genPayload) isBuildable
Genesis
ts_prop_genesisKeyHashesIsBuildable :: TSProperty
ts_prop_genesisKeyHashesIsBuildable =
eachOfTS 100 Genesis.genGenesisKeyHashes isBuildable
ts_prop_genesisNonAvvmBalancesIsBuildable :: TSProperty
ts_prop_genesisNonAvvmBalancesIsBuildable =
eachOfTS 100 Genesis.genGenesisNonAvvmBalances isBuildable
ts_prop_epochAndSlotCountIsBuildable :: TSProperty
ts_prop_epochAndSlotCountIsBuildable =
eachOfTS
100
(Slotting.genEpochSlots >>= Slotting.genEpochAndSlotCount)
isBuildable
ts_prop_epochNumberIsBuildable :: TSProperty
ts_prop_epochNumberIsBuildable =
eachOfTS 100 Slotting.genEpochNumber isBuildable
ts_prop_epochSlotsIsBuildable :: TSProperty
ts_prop_epochSlotsIsBuildable = eachOfTS 100 Slotting.genEpochSlots isBuildable
ts_prop_slotCountIsBuildable :: TSProperty
ts_prop_slotCountIsBuildable = eachOfTS 100 Slotting.genSlotCount isBuildable
ts_prop_slotNumberIsBuilable :: TSProperty
ts_prop_slotNumberIsBuilable = eachOfTS 100 Slotting.genSlotNumber isBuildable
ts_prop_applicationNameIsBuildable :: TSProperty
ts_prop_applicationNameIsBuildable =
eachOfTS 100 Update.genApplicationName isBuildable
ts_prop_installerHashIsBuildable :: TSProperty
ts_prop_installerHashIsBuildable =
eachOfTS 100 Update.genInstallerHash isBuildable
ts_prop_updatePayloadIsBuildable :: TSProperty
ts_prop_updatePayloadIsBuildable =
eachOfTS 100 (feedPM Update.genPayload) isBuildable
ts_prop_proposalIsBuiladble :: TSProperty
ts_prop_proposalIsBuiladble =
eachOfTS 100 (feedPM Update.genProposal) isBuildable
ts_prop_protocolParametersIsBuildable :: TSProperty
ts_prop_protocolParametersIsBuildable =
eachOfTS 100 Update.genProtocolParameters isBuildable
ts_prop_protocolParametersUpdateIsBuildable :: TSProperty
ts_prop_protocolParametersUpdateIsBuildable =
eachOfTS 100 Update.genProtocolParametersUpdate isBuildable
ts_prop_protocolVersionIsBuildable :: TSProperty
ts_prop_protocolVersionIsBuildable =
eachOfTS 100 Update.genProtocolVersion isBuildable
ts_prop_softforkRuleIsBuildable :: TSProperty
ts_prop_softforkRuleIsBuildable =
eachOfTS 100 Update.genSoftforkRule isBuildable
ts_prop_softwareVersionIsBuildable :: TSProperty
ts_prop_softwareVersionIsBuildable =
eachOfTS 100 Update.genSoftforkRule isBuildable
ts_prop_systemTagIsBuildable :: TSProperty
ts_prop_systemTagIsBuildable = eachOfTS 100 Update.genSystemTag isBuildable
ts_prop_voteIsBuildable :: TSProperty
ts_prop_voteIsBuildable = eachOfTS 100 (feedPM Update.genVote) isBuildable
ts_prop_txIsBuildable :: TSProperty
ts_prop_txIsBuildable = eachOfTS 100 UTxO.genTx isBuildable
ts_prop_txInIsBuildable :: TSProperty
ts_prop_txInIsBuildable = eachOfTS 100 UTxO.genTxIn isBuildable
ts_prop_txOutIsBuildable :: TSProperty
ts_prop_txOutIsBuildable = eachOfTS 100 UTxO.genTxOut isBuildable
ts_prop_txAuxIsBuildable :: TSProperty
ts_prop_txAuxIsBuildable = eachOfTS 100 (feedPM UTxO.genTxAux) isBuildable
ts_prop_txProofIsBuildable :: TSProperty
ts_prop_txProofIsBuildable = eachOfTS 100 (feedPM UTxO.genTxProof) isBuildable
ts_prop_txInWitnessIsBuildable :: TSProperty
ts_prop_txInWitnessIsBuildable =
eachOfTS 100 (feedPM UTxO.genTxInWitness) isBuildable
|
4ffe963e17f2a6f4ccb8f8ac98e6107cb41e6269a85b85bc73783251e608446f | brick-lang/kekka | inferMonad.ml | open Core
open Common
open InferKind
type kst = KSub.t
type kenv = {
current_module : Name.t;
imports : ImportMap.t;
kgamma : KGamma.t;
infgamma : InfKGamma.t;
synonyms : Synonyms.t
}
type 'a kresult = {
result: 'a;
(* errors: (range * doc) list; *)
(* warnings: (range * doc) list; *)
st: kst;
}
(* kinfer *)
module Let_syntax = struct
type 'a t = kenv -> kst -> 'a kresult
let map (ki:'a t) ~(f:'a -> 'b) : 'b t = fun env st ->
let r = ki env st in
{r with result = f (r.result) }
let return (x:'a) : 'a t = fun env st -> {result=x; st}
let bind (ki:'a t) ~(f:'a -> 'b t) : 'b t = fun env st ->
errs1 ; warns1 ;
; warns2 ;
{result=y; (* errors=errs1^errs2; warnings=warns1^warns2; *) st=st2}
end
include Monadic.Make(Let_syntax)
let run_kind_infer module_name imports kgamma synonyms (ki:'a t) =
let imports' = Option.value ~default:imports @@
ImportMap.extend (Name.to_short_module_name module_name) module_name imports
in
(ki {current_module=module_name; imports=imports'; kgamma; infgamma=Name.Map.empty; synonyms}
KSub.empty).result
let get_kind_env : kenv t = fun env st -> {result=env; st}
let add_error range doc : unit t =
* add_range_info range Error(doc ) > >
* fun env st - > { ( ) ; errors=[(range , doc ) ] ; warnings= [ ] ; st }
*
* let add_warning range doc : unit t =
* add_range_info range Warning(doc ) > >
* fun env st - > { ( ) ; errors= [ ] ; warnings=[(range , doc ) ] ; st }
* add_range_info range Error(doc) >>
* fun env st -> {result=(); errors=[(range,doc)]; warnings=[]; st}
*
* let add_warning range doc : unit t =
* add_range_info range Warning(doc) >>
* fun env st -> {result=(); errors=[]; warnings=[(range,doc)]; st} *)
let get_ksub : KSub.t t = fun env st -> {result=st; st}
let extend_ksub (sub:KSub.t) : unit t =
fun env st -> {result=(); st=KSub.(sub @@@ st)}
(**********************************************************************
* Operations
**********************************************************************)
let fresh_kind =
return @@ InfKind.Var(Unique.unique_id "k")
let fresh_type_var tb flavour =
let open ConcreteSyntax.TypeBinder in
let id = Unique.unique_id (Name.show tb.name) in
return Heart.Type.TypeVar.{id; kind=tb.kind; flavour}
let subst x =
let%bind sub = get_ksub in
return InferKind.InfKind.(sub |=> x)
let get_kgamma =
let%bind env = get_kind_env in
return env.kgamma
let get_synonyms =
let%bind env = get_kind_env in
return env.synonyms
(** Extend the inference kind assumption; checks for shadowed definitions *)
let extend_inf_gamma tbinders (ki:'a t) : 'a t =
let open Common.ConcreteSyntax.TypeBinder in
let check (infgamma:InfKGamma.t) tb =
if Name.Map.mem infgamma tb.name then
add_error name_range @@ Printf.sprintf " Type % s is already defined " ( Name.show tb.name )
failwith (Printf.sprintf "Type %s is already defined" (Name.show tb.name))
return @@ Name.Map.set ~key : tb.name ~data : tb.kind ( * replaces
else
return @@ Name.Map.set infgamma ~key:tb.name ~data:tb.kind
in
let extend_unsafe tbinders ki =
let inf_gamma = Name.Map.of_alist_exn @@ List.map tbinders ~f:(fun {name; kind} -> (name,kind)) in
(* assumes left-biased union *)
fun env st -> ki {env with infgamma=Name.Map.union inf_gamma env.infgamma} st
in
let%bind env = get_kind_env in
foldM check env.infgamma tbinders >>
extend_unsafe tbinders ki
(** Extend the kind assumption; checks for shadowed definitions *)
let extend_kgamma (tdefs:Heart.Expr.TypeDef.group) (ki:'a t) : 'a t =
(* NOTE: duplication check already happens in extendInfGamma but
* there can still be a clash with a definition in another inference group *)
let name_kind = let open Heart.Expr.TypeDef in function
| Synonym{syn_info} -> Heart.Type.(syn_info.syn_info_name, syn_info.syn_info_kind)
| Data{data_info} -> Heart.Type.(data_info.data_info_name, data_info.data_info_kind)
in
let check (kgamma, tdefs) tdef =
if Heart.Expr.TypeDef.is_extension tdef then
return (kgamma, tdefs)
else
let (name,kind) = name_kind tdef in
match KGamma.lookup_q name kgamma with
| None -> return (KGamma.extend ~name ~data:kind kgamma, tdef::tdefs)
| Some _ ->
failwith (Printf.sprintf "Type %s is already defined" (Name.show name))
return ( , tdefs )
in
let extend_unsafe tdefs (ki:'a t) : 'a t =
let new_kgamma = KGamma.new_dedup (List.map ~f:name_kind tdefs) in
let ksyns = Synonyms.create (List.concat_map tdefs ~f:(function Heart.Expr.TypeDef.Synonym{syn_info} -> [syn_info] | _ -> [])) in
fun env st -> ki {env with kgamma = KGamma.union env.kgamma new_kgamma;
synonyms = Synonyms.compose env.synonyms ksyns} st
in
let%bind env = get_kind_env in
let%bind (_, tdefs') = foldM check (env.kgamma, []) tdefs in
extend_unsafe List.(rev tdefs') ki
let inf_qualified_name (name:Name.t) : Name.t t =
if not (Name.is_qualified name) then
return name
else
let%bind env = get_kind_env in
match ImportMap.expand name env.imports with
| Second (name', alias) when Name.case_equal (Name.qualifier name) alias ->
return name'
| Second (_, alias) ->
failwithf "module %s should be cased as %s" (Name.show name) (Name.show alias) ()
| First [] ->
failwithf "module %s is undefined" (Name.show name) ()
| First aliases ->
failwithf "module %s is ambiguous. It can refer to: %s" (Name.show name) (List.to_string aliases ~f:Name.show) ()
let find_inf_kind name0 =
let%bind env = get_kind_env in
let (name,mb_alias) = match ImportMap.expand name0 env.imports with
| Second (name', alias) -> (name', Some alias)
| _ -> (name0, None)
in
(* lookup locally
* NOTE: also lookup qualified since it might be recursive definition
* TODO: check for the locally inferred names for casing too. *)
match Name.Map.find env.infgamma name with
| Some infkind -> return (name, infkind)
| None -> match KGamma.lookup env.current_module name env.kgamma with
| Found(qname,kind) ->
let name' = if Name.is_qualified name then qname else (Name.unqualify qname) in
if not (Name.case_equal name' name) then
failwithf "type %s should be cased as %s." (Name.show @@ Name.unqualify name0) (Name.show @@ Name.unqualify name') ();
if (Option.is_some mb_alias) && not (String.equal name0.Name.name_module (Name.show @@ Option.value_exn mb_alias)) then
failwithf "module %s should be cased as %s." name0.Name.name_module (Name.show @@ Option.value_exn mb_alias) ();
return (qname, InfKind.Con(kind))
| NotFound ->
failwithf "Type %s is not defined.\n hint: bind the variable using 'forall<%s>'?" (Name.show name) (Name.show name) ()
| Ambiguous names ->
failwithf "Type %s is ambiguous. It can refer to: %s" (Name.show name) (List.to_string names ~f:Name.show) ()
let qualify_def name =
let%bind env = get_kind_env in
return (Name.qualify env.current_module name)
let find_kind name =
let%bind env = get_kind_env in
match KGamma.lookup env.current_module name env.kgamma with
| Found(qname,kind) -> return (qname, kind)
| _ -> failwithf "KindEngine.InferMonad.find_kind: unknown type constructor: %s" (Name.show name) ()
let lookup_syn_info name =
let%bind env = get_kind_env in
return (Synonyms.lookup name env.synonyms)
| null | https://raw.githubusercontent.com/brick-lang/kekka/7ede659ffb49959b140e6ab0a72d38ff6c63311b/kindEngine/inferMonad.ml | ocaml | errors: (range * doc) list;
warnings: (range * doc) list;
kinfer
errors=errs1^errs2; warnings=warns1^warns2;
*********************************************************************
* Operations
*********************************************************************
* Extend the inference kind assumption; checks for shadowed definitions
assumes left-biased union
* Extend the kind assumption; checks for shadowed definitions
NOTE: duplication check already happens in extendInfGamma but
* there can still be a clash with a definition in another inference group
lookup locally
* NOTE: also lookup qualified since it might be recursive definition
* TODO: check for the locally inferred names for casing too. | open Core
open Common
open InferKind
type kst = KSub.t
type kenv = {
current_module : Name.t;
imports : ImportMap.t;
kgamma : KGamma.t;
infgamma : InfKGamma.t;
synonyms : Synonyms.t
}
type 'a kresult = {
result: 'a;
st: kst;
}
module Let_syntax = struct
type 'a t = kenv -> kst -> 'a kresult
let map (ki:'a t) ~(f:'a -> 'b) : 'b t = fun env st ->
let r = ki env st in
{r with result = f (r.result) }
let return (x:'a) : 'a t = fun env st -> {result=x; st}
let bind (ki:'a t) ~(f:'a -> 'b t) : 'b t = fun env st ->
errs1 ; warns1 ;
; warns2 ;
end
include Monadic.Make(Let_syntax)
let run_kind_infer module_name imports kgamma synonyms (ki:'a t) =
let imports' = Option.value ~default:imports @@
ImportMap.extend (Name.to_short_module_name module_name) module_name imports
in
(ki {current_module=module_name; imports=imports'; kgamma; infgamma=Name.Map.empty; synonyms}
KSub.empty).result
let get_kind_env : kenv t = fun env st -> {result=env; st}
let add_error range doc : unit t =
* add_range_info range Error(doc ) > >
* fun env st - > { ( ) ; errors=[(range , doc ) ] ; warnings= [ ] ; st }
*
* let add_warning range doc : unit t =
* add_range_info range Warning(doc ) > >
* fun env st - > { ( ) ; errors= [ ] ; warnings=[(range , doc ) ] ; st }
* add_range_info range Error(doc) >>
* fun env st -> {result=(); errors=[(range,doc)]; warnings=[]; st}
*
* let add_warning range doc : unit t =
* add_range_info range Warning(doc) >>
* fun env st -> {result=(); errors=[]; warnings=[(range,doc)]; st} *)
let get_ksub : KSub.t t = fun env st -> {result=st; st}
let extend_ksub (sub:KSub.t) : unit t =
fun env st -> {result=(); st=KSub.(sub @@@ st)}
let fresh_kind =
return @@ InfKind.Var(Unique.unique_id "k")
let fresh_type_var tb flavour =
let open ConcreteSyntax.TypeBinder in
let id = Unique.unique_id (Name.show tb.name) in
return Heart.Type.TypeVar.{id; kind=tb.kind; flavour}
let subst x =
let%bind sub = get_ksub in
return InferKind.InfKind.(sub |=> x)
let get_kgamma =
let%bind env = get_kind_env in
return env.kgamma
let get_synonyms =
let%bind env = get_kind_env in
return env.synonyms
let extend_inf_gamma tbinders (ki:'a t) : 'a t =
let open Common.ConcreteSyntax.TypeBinder in
let check (infgamma:InfKGamma.t) tb =
if Name.Map.mem infgamma tb.name then
add_error name_range @@ Printf.sprintf " Type % s is already defined " ( Name.show tb.name )
failwith (Printf.sprintf "Type %s is already defined" (Name.show tb.name))
return @@ Name.Map.set ~key : tb.name ~data : tb.kind ( * replaces
else
return @@ Name.Map.set infgamma ~key:tb.name ~data:tb.kind
in
let extend_unsafe tbinders ki =
let inf_gamma = Name.Map.of_alist_exn @@ List.map tbinders ~f:(fun {name; kind} -> (name,kind)) in
fun env st -> ki {env with infgamma=Name.Map.union inf_gamma env.infgamma} st
in
let%bind env = get_kind_env in
foldM check env.infgamma tbinders >>
extend_unsafe tbinders ki
let extend_kgamma (tdefs:Heart.Expr.TypeDef.group) (ki:'a t) : 'a t =
let name_kind = let open Heart.Expr.TypeDef in function
| Synonym{syn_info} -> Heart.Type.(syn_info.syn_info_name, syn_info.syn_info_kind)
| Data{data_info} -> Heart.Type.(data_info.data_info_name, data_info.data_info_kind)
in
let check (kgamma, tdefs) tdef =
if Heart.Expr.TypeDef.is_extension tdef then
return (kgamma, tdefs)
else
let (name,kind) = name_kind tdef in
match KGamma.lookup_q name kgamma with
| None -> return (KGamma.extend ~name ~data:kind kgamma, tdef::tdefs)
| Some _ ->
failwith (Printf.sprintf "Type %s is already defined" (Name.show name))
return ( , tdefs )
in
let extend_unsafe tdefs (ki:'a t) : 'a t =
let new_kgamma = KGamma.new_dedup (List.map ~f:name_kind tdefs) in
let ksyns = Synonyms.create (List.concat_map tdefs ~f:(function Heart.Expr.TypeDef.Synonym{syn_info} -> [syn_info] | _ -> [])) in
fun env st -> ki {env with kgamma = KGamma.union env.kgamma new_kgamma;
synonyms = Synonyms.compose env.synonyms ksyns} st
in
let%bind env = get_kind_env in
let%bind (_, tdefs') = foldM check (env.kgamma, []) tdefs in
extend_unsafe List.(rev tdefs') ki
let inf_qualified_name (name:Name.t) : Name.t t =
if not (Name.is_qualified name) then
return name
else
let%bind env = get_kind_env in
match ImportMap.expand name env.imports with
| Second (name', alias) when Name.case_equal (Name.qualifier name) alias ->
return name'
| Second (_, alias) ->
failwithf "module %s should be cased as %s" (Name.show name) (Name.show alias) ()
| First [] ->
failwithf "module %s is undefined" (Name.show name) ()
| First aliases ->
failwithf "module %s is ambiguous. It can refer to: %s" (Name.show name) (List.to_string aliases ~f:Name.show) ()
let find_inf_kind name0 =
let%bind env = get_kind_env in
let (name,mb_alias) = match ImportMap.expand name0 env.imports with
| Second (name', alias) -> (name', Some alias)
| _ -> (name0, None)
in
match Name.Map.find env.infgamma name with
| Some infkind -> return (name, infkind)
| None -> match KGamma.lookup env.current_module name env.kgamma with
| Found(qname,kind) ->
let name' = if Name.is_qualified name then qname else (Name.unqualify qname) in
if not (Name.case_equal name' name) then
failwithf "type %s should be cased as %s." (Name.show @@ Name.unqualify name0) (Name.show @@ Name.unqualify name') ();
if (Option.is_some mb_alias) && not (String.equal name0.Name.name_module (Name.show @@ Option.value_exn mb_alias)) then
failwithf "module %s should be cased as %s." name0.Name.name_module (Name.show @@ Option.value_exn mb_alias) ();
return (qname, InfKind.Con(kind))
| NotFound ->
failwithf "Type %s is not defined.\n hint: bind the variable using 'forall<%s>'?" (Name.show name) (Name.show name) ()
| Ambiguous names ->
failwithf "Type %s is ambiguous. It can refer to: %s" (Name.show name) (List.to_string names ~f:Name.show) ()
let qualify_def name =
let%bind env = get_kind_env in
return (Name.qualify env.current_module name)
let find_kind name =
let%bind env = get_kind_env in
match KGamma.lookup env.current_module name env.kgamma with
| Found(qname,kind) -> return (qname, kind)
| _ -> failwithf "KindEngine.InferMonad.find_kind: unknown type constructor: %s" (Name.show name) ()
let lookup_syn_info name =
let%bind env = get_kind_env in
return (Synonyms.lookup name env.synonyms)
|
3ee7efae0c8f423e890c9444fe6dc68d0ea4d10001029d63611eec6c31ac66fe | karamellpelle/grid | Button.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see </>.
--
module Game.Run.Eggs.Button
(
EggButton (..),
) where
data EggButton =
ButtonLeft |
ButtonRight |
ButtonDown |
ButtonUp |
ButtonA |
ButtonB
deriving (Eq, Show)
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/source/Game/Run/Eggs/Button.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid 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 grid. If not, see </>.
| grid is a game written in Haskell
Copyright ( C ) 2018
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
module Game.Run.Eggs.Button
(
EggButton (..),
) where
data EggButton =
ButtonLeft |
ButtonRight |
ButtonDown |
ButtonUp |
ButtonA |
ButtonB
deriving (Eq, Show)
|
da289ab8285aef34eff69635872eefb85a81b5ec2b1341788abcba8e5ce0fc1d | elastic/eui-cljs | color_picker_swatch.cljs | (ns eui.color-picker-swatch
(:require ["@elastic/eui/lib/components/color_picker/color_picker_swatch.js" :as eui]))
(def EuiColorPickerSwatch eui/EuiColorPickerSwatch)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/color_picker_swatch.cljs | clojure | (ns eui.color-picker-swatch
(:require ["@elastic/eui/lib/components/color_picker/color_picker_swatch.js" :as eui]))
(def EuiColorPickerSwatch eui/EuiColorPickerSwatch)
| |
45a4387d3761c7c5ca115d2f771050f1ab83f65df3a83b6614eb3a130142f7bc | capnproto/capnp-ocaml | codecs.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* capnp - ocaml
*
* Copyright ( c ) 2013 - 2014 ,
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
*
* 2 . 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 HOLDER OR
* LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
* CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
* INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , 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 .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* capnp-ocaml
*
* Copyright (c) 2013-2014, Paul Pelzl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************)
type compression_t = [ `None | `Packing ]
module FramingError = struct
type t =
| Incomplete (** less than a full frame is available *)
| Unsupported (** frame header describes a segment count or segment size that
is too large for the implementation *)
end
module UncompStream = struct
type incomplete_frame_t = {
frame_header : string;
complete_segments : string Res.Array.t;
}
type decoder_state_t =
| IncompleteHeader
| IncompleteFrame of incomplete_frame_t
type t = {
(** Primary storage for incoming stream segments. *)
fragment_buffer : FragmentBuffer.t;
(** Partially-decoded frame information *)
mutable decoder_state : decoder_state_t;
}
let empty () = {
fragment_buffer = FragmentBuffer.empty ();
decoder_state = IncompleteHeader;
}
let add_fragment stream fragment =
FragmentBuffer.add_fragment stream.fragment_buffer fragment
let bytes_available stream =
match stream.decoder_state with
| IncompleteHeader ->
FragmentBuffer.byte_count stream.fragment_buffer
| IncompleteFrame partial_frame ->
(String.length partial_frame.frame_header) +
(Res.Array.fold_left (fun acc x -> acc + (String.length x))
0
partial_frame.complete_segments) +
(FragmentBuffer.byte_count stream.fragment_buffer)
let is_empty stream =
match stream.decoder_state with
| IncompleteHeader ->
FragmentBuffer.byte_count stream.fragment_buffer = 0
| _ ->
false
let rec get_next_frame stream =
match stream.decoder_state with
| IncompleteHeader -> unpack_header stream
| IncompleteFrame incomplete_frame ->
unpack_frame stream incomplete_frame
and unpack_header stream =
First four bytes of the header contain a segment count , which tells
you how long the full header is
you how long the full header is *)
match FragmentBuffer.peek_exact stream.fragment_buffer 4 with
| Some partial_header ->
begin try
let segment_count =
let bytes_header = Bytes.unsafe_of_string partial_header in
Util.int_of_uint32_exn (BytesStorage.get_uint32 bytes_header 0)
in
let () =
if segment_count > (max_int / 4) - 2 then
Util.out_of_int_range "Uint32.to_int"
in
let segment_count = segment_count + 1 in
let frame_header_size =
let word_size = 8 in
(Util.ceil_ratio (4 * (segment_count + 1)) word_size) * word_size
in
(* Now we know the full header size, so try to get the whole thing *)
begin match FragmentBuffer.remove_exact stream.fragment_buffer
frame_header_size with
| Some frame_header ->
let () = stream.decoder_state <- IncompleteFrame {
frame_header;
complete_segments = Res.Array.empty ();
}
in
get_next_frame stream
| None ->
Result.Error FramingError.Incomplete
end
with Util.Out_of_int_range _ ->
Result.Error FramingError.Unsupported
end
| None ->
Result.Error FramingError.Incomplete
and unpack_frame stream incomplete_frame =
let frame_header_bytes =
Bytes.unsafe_of_string incomplete_frame.frame_header
in
let segment_count_u32 = BytesStorage.get_uint32 frame_header_bytes 0 in
let segment_count = 1 + (Util.int_of_uint32_exn segment_count_u32) in
let segments_decoded = Res.Array.length incomplete_frame.complete_segments in
if segments_decoded = segment_count then
let () = stream.decoder_state <- IncompleteHeader in
let string_segments = Res.Array.to_list incomplete_frame.complete_segments in
let bytes_segments = ListLabels.map string_segments ~f:Bytes.unsafe_of_string in
Result.Ok (Message.BytesMessage.Message.of_storage bytes_segments)
else
let () = assert (segments_decoded < segment_count) in
let segment_size_words_u32 = BytesStorage.get_uint32
frame_header_bytes (4 + (4 * segments_decoded))
in
begin try
let segment_size = 8 * (Util.int_of_uint32_exn segment_size_words_u32) in
begin match FragmentBuffer.remove_exact stream.fragment_buffer
segment_size with
| Some segment ->
let () = Res.Array.add_one incomplete_frame.complete_segments segment in
unpack_frame stream incomplete_frame
| None ->
Result.Error FramingError.Incomplete
end
with Invalid_argument _ ->
Result.Error FramingError.Unsupported
end
end
module PackedStream = struct
type t = {
(** Packed fragments waiting to be unpacked *)
packed : FragmentBuffer.t;
(** Unpacked fragments waiting to be decoded as messages *)
unpacked : UncompStream.t;
}
let empty () = {
packed = FragmentBuffer.empty ();
unpacked = UncompStream.empty ();
}
let add_fragment stream fragment =
FragmentBuffer.add_fragment stream.packed fragment
let bytes_available stream =
(* This isn't a very meaningful number, except maybe for the
purpose of bounding the amount of memory in use... *)
(FragmentBuffer.byte_count stream.packed) +
(UncompStream.bytes_available stream.unpacked)
let is_empty stream =
(FragmentBuffer.byte_count stream.packed = 0) &&
(UncompStream.is_empty stream.unpacked)
let get_next_frame stream =
let () = Packing.unpack ~packed:stream.packed
~unpacked:stream.unpacked.UncompStream.fragment_buffer
in
UncompStream.get_next_frame stream.unpacked
end
module FramedStream = struct
(* Using runtime dispatch here... makes the API much easier to use
relative to exposing different types for compressed and
uncompressed streams. *)
type t =
| NoPack of UncompStream.t
| Pack of PackedStream.t
let empty compression =
match compression with
| `None -> NoPack (UncompStream.empty ())
| `Packing -> Pack (PackedStream.empty ())
let of_string ~compression s =
match compression with
| `None ->
let stream = UncompStream.empty () in
let () = UncompStream.add_fragment stream s in
NoPack stream
| `Packing ->
let stream = PackedStream.empty () in
let () = PackedStream.add_fragment stream s in
Pack stream
let add_fragment stream fragment =
match stream with
| NoPack stream' -> UncompStream.add_fragment stream' fragment
| Pack stream' -> PackedStream.add_fragment stream' fragment
let bytes_available stream =
match stream with
| NoPack stream' -> UncompStream.bytes_available stream'
| Pack stream' -> PackedStream.bytes_available stream'
let is_empty stream =
match stream with
| NoPack stream' -> UncompStream.is_empty stream'
| Pack stream' -> PackedStream.is_empty stream'
let get_next_frame stream =
match stream with
| NoPack stream' -> UncompStream.get_next_frame stream'
| Pack stream' -> PackedStream.get_next_frame stream'
end
let make_header segment_descrs : string =
let buf = Buffer.create 8 in
let () = ListLabels.iter segment_descrs ~f:(fun descr ->
let size_buf = Bytes.create 4 in
let seg_len = descr.Message.BytesMessage.Message.bytes_consumed in
let () = assert ((seg_len mod 8) = 0) in
let seg_word_count = seg_len / 8 in
let () = BytesStorage.set_uint32 size_buf 0
(Util.uint32_of_int_exn seg_word_count)
in
Buffer.add_string buf (Bytes.unsafe_to_string size_buf))
in
let segment_sizes = Buffer.contents buf in
let segment_count = (String.length segment_sizes) / 4 in
if segment_count = 0 then
invalid_arg "make_header requires nonempty message"
else
let count_buf = Bytes.create 4 in
let () = BytesStorage.set_uint32 count_buf 0
(Util.uint32_of_int_exn (segment_count - 1))
in
(* pad out to a word boundary *)
let count_buf = Bytes.unsafe_to_string count_buf in
if segment_count mod 2 = 0 then
count_buf ^ segment_sizes ^ (String.make 4 '\x00')
else
count_buf ^ segment_sizes
let rec serialize_fold message ~compression ~init ~f =
let segment_descrs = Message.BytesMessage.Message.to_storage message in
match compression with
| `None ->
let header = make_header segment_descrs in
ListLabels.fold_left segment_descrs ~init:(f init header) ~f:(fun acc descr ->
let open Message.BytesMessage in
let seg =
if descr.Message.bytes_consumed = Bytes.length descr.Message.segment then
descr.Message.segment
else
Bytes.sub descr.Message.segment 0 descr.Message.bytes_consumed
in
f acc (Bytes.unsafe_to_string seg))
| `Packing ->
serialize_fold message ~compression:`None ~init
~f:(fun acc unpacked_fragment ->
f acc (Packing.pack_string unpacked_fragment))
let serialize_iter message ~compression ~f =
serialize_fold message ~compression ~init:() ~f:(fun () s -> f s)
let serialize_fold_copyless message ~compression ~init ~f =
let segment_descrs = Message.BytesMessage.Message.to_storage message in
match compression with
| `None ->
let header = make_header segment_descrs in
ListLabels.fold_left segment_descrs ~init:(f init header (String.length header)) ~f:(fun acc descr ->
let open Message.BytesMessage in
f acc (Bytes.unsafe_to_string descr.Message.segment) descr.Message.bytes_consumed)
| `Packing ->
serialize_fold message ~compression:`None ~init
~f:(fun acc unpacked_fragment ->
let packed_string = Packing.pack_string unpacked_fragment in
f acc packed_string (String.length packed_string))
let serialize_iter_copyless message ~compression ~f =
serialize_fold_copyless message ~compression ~init:() ~f:(fun () s -> f s)
let rec serialize ~compression message =
match compression with
| `None ->
let segment_descrs = Message.BytesMessage.Message.to_storage message in
let header = make_header segment_descrs in
let header_size = String.length header in
let segments_size = Message.BytesMessage.Message.total_size message in
let total_size = header_size + segments_size in
let buf = Bytes.create total_size in
Bytes.blit
(Bytes.unsafe_of_string header) 0
buf 0
header_size;
let (_ : int) = ListLabels.fold_left segment_descrs ~init:header_size
~f:(fun pos descr ->
let open Message.BytesMessage in
Bytes.blit
descr.Message.segment 0
buf pos
descr.Message.bytes_consumed;
pos + descr.Message.bytes_consumed)
in
Bytes.unsafe_to_string buf
| `Packing ->
Packing.pack_string (serialize ~compression:`None message)
| null | https://raw.githubusercontent.com/capnproto/capnp-ocaml/cadb5f8d9138f51d2dd3a7867dabc0c17b7d4ba2/src/runtime/codecs.ml | ocaml | * less than a full frame is available
* frame header describes a segment count or segment size that
is too large for the implementation
* Primary storage for incoming stream segments.
* Partially-decoded frame information
Now we know the full header size, so try to get the whole thing
* Packed fragments waiting to be unpacked
* Unpacked fragments waiting to be decoded as messages
This isn't a very meaningful number, except maybe for the
purpose of bounding the amount of memory in use...
Using runtime dispatch here... makes the API much easier to use
relative to exposing different types for compressed and
uncompressed streams.
pad out to a word boundary | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* capnp - ocaml
*
* Copyright ( c ) 2013 - 2014 ,
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
*
* 2 . 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 HOLDER OR
* LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
* CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS
* INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , 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 .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* capnp-ocaml
*
* Copyright (c) 2013-2014, Paul Pelzl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************)
type compression_t = [ `None | `Packing ]
module FramingError = struct
type t =
end
module UncompStream = struct
type incomplete_frame_t = {
frame_header : string;
complete_segments : string Res.Array.t;
}
type decoder_state_t =
| IncompleteHeader
| IncompleteFrame of incomplete_frame_t
type t = {
fragment_buffer : FragmentBuffer.t;
mutable decoder_state : decoder_state_t;
}
let empty () = {
fragment_buffer = FragmentBuffer.empty ();
decoder_state = IncompleteHeader;
}
let add_fragment stream fragment =
FragmentBuffer.add_fragment stream.fragment_buffer fragment
let bytes_available stream =
match stream.decoder_state with
| IncompleteHeader ->
FragmentBuffer.byte_count stream.fragment_buffer
| IncompleteFrame partial_frame ->
(String.length partial_frame.frame_header) +
(Res.Array.fold_left (fun acc x -> acc + (String.length x))
0
partial_frame.complete_segments) +
(FragmentBuffer.byte_count stream.fragment_buffer)
let is_empty stream =
match stream.decoder_state with
| IncompleteHeader ->
FragmentBuffer.byte_count stream.fragment_buffer = 0
| _ ->
false
let rec get_next_frame stream =
match stream.decoder_state with
| IncompleteHeader -> unpack_header stream
| IncompleteFrame incomplete_frame ->
unpack_frame stream incomplete_frame
and unpack_header stream =
First four bytes of the header contain a segment count , which tells
you how long the full header is
you how long the full header is *)
match FragmentBuffer.peek_exact stream.fragment_buffer 4 with
| Some partial_header ->
begin try
let segment_count =
let bytes_header = Bytes.unsafe_of_string partial_header in
Util.int_of_uint32_exn (BytesStorage.get_uint32 bytes_header 0)
in
let () =
if segment_count > (max_int / 4) - 2 then
Util.out_of_int_range "Uint32.to_int"
in
let segment_count = segment_count + 1 in
let frame_header_size =
let word_size = 8 in
(Util.ceil_ratio (4 * (segment_count + 1)) word_size) * word_size
in
begin match FragmentBuffer.remove_exact stream.fragment_buffer
frame_header_size with
| Some frame_header ->
let () = stream.decoder_state <- IncompleteFrame {
frame_header;
complete_segments = Res.Array.empty ();
}
in
get_next_frame stream
| None ->
Result.Error FramingError.Incomplete
end
with Util.Out_of_int_range _ ->
Result.Error FramingError.Unsupported
end
| None ->
Result.Error FramingError.Incomplete
and unpack_frame stream incomplete_frame =
let frame_header_bytes =
Bytes.unsafe_of_string incomplete_frame.frame_header
in
let segment_count_u32 = BytesStorage.get_uint32 frame_header_bytes 0 in
let segment_count = 1 + (Util.int_of_uint32_exn segment_count_u32) in
let segments_decoded = Res.Array.length incomplete_frame.complete_segments in
if segments_decoded = segment_count then
let () = stream.decoder_state <- IncompleteHeader in
let string_segments = Res.Array.to_list incomplete_frame.complete_segments in
let bytes_segments = ListLabels.map string_segments ~f:Bytes.unsafe_of_string in
Result.Ok (Message.BytesMessage.Message.of_storage bytes_segments)
else
let () = assert (segments_decoded < segment_count) in
let segment_size_words_u32 = BytesStorage.get_uint32
frame_header_bytes (4 + (4 * segments_decoded))
in
begin try
let segment_size = 8 * (Util.int_of_uint32_exn segment_size_words_u32) in
begin match FragmentBuffer.remove_exact stream.fragment_buffer
segment_size with
| Some segment ->
let () = Res.Array.add_one incomplete_frame.complete_segments segment in
unpack_frame stream incomplete_frame
| None ->
Result.Error FramingError.Incomplete
end
with Invalid_argument _ ->
Result.Error FramingError.Unsupported
end
end
module PackedStream = struct
type t = {
packed : FragmentBuffer.t;
unpacked : UncompStream.t;
}
let empty () = {
packed = FragmentBuffer.empty ();
unpacked = UncompStream.empty ();
}
let add_fragment stream fragment =
FragmentBuffer.add_fragment stream.packed fragment
let bytes_available stream =
(FragmentBuffer.byte_count stream.packed) +
(UncompStream.bytes_available stream.unpacked)
let is_empty stream =
(FragmentBuffer.byte_count stream.packed = 0) &&
(UncompStream.is_empty stream.unpacked)
let get_next_frame stream =
let () = Packing.unpack ~packed:stream.packed
~unpacked:stream.unpacked.UncompStream.fragment_buffer
in
UncompStream.get_next_frame stream.unpacked
end
module FramedStream = struct
type t =
| NoPack of UncompStream.t
| Pack of PackedStream.t
let empty compression =
match compression with
| `None -> NoPack (UncompStream.empty ())
| `Packing -> Pack (PackedStream.empty ())
let of_string ~compression s =
match compression with
| `None ->
let stream = UncompStream.empty () in
let () = UncompStream.add_fragment stream s in
NoPack stream
| `Packing ->
let stream = PackedStream.empty () in
let () = PackedStream.add_fragment stream s in
Pack stream
let add_fragment stream fragment =
match stream with
| NoPack stream' -> UncompStream.add_fragment stream' fragment
| Pack stream' -> PackedStream.add_fragment stream' fragment
let bytes_available stream =
match stream with
| NoPack stream' -> UncompStream.bytes_available stream'
| Pack stream' -> PackedStream.bytes_available stream'
let is_empty stream =
match stream with
| NoPack stream' -> UncompStream.is_empty stream'
| Pack stream' -> PackedStream.is_empty stream'
let get_next_frame stream =
match stream with
| NoPack stream' -> UncompStream.get_next_frame stream'
| Pack stream' -> PackedStream.get_next_frame stream'
end
let make_header segment_descrs : string =
let buf = Buffer.create 8 in
let () = ListLabels.iter segment_descrs ~f:(fun descr ->
let size_buf = Bytes.create 4 in
let seg_len = descr.Message.BytesMessage.Message.bytes_consumed in
let () = assert ((seg_len mod 8) = 0) in
let seg_word_count = seg_len / 8 in
let () = BytesStorage.set_uint32 size_buf 0
(Util.uint32_of_int_exn seg_word_count)
in
Buffer.add_string buf (Bytes.unsafe_to_string size_buf))
in
let segment_sizes = Buffer.contents buf in
let segment_count = (String.length segment_sizes) / 4 in
if segment_count = 0 then
invalid_arg "make_header requires nonempty message"
else
let count_buf = Bytes.create 4 in
let () = BytesStorage.set_uint32 count_buf 0
(Util.uint32_of_int_exn (segment_count - 1))
in
let count_buf = Bytes.unsafe_to_string count_buf in
if segment_count mod 2 = 0 then
count_buf ^ segment_sizes ^ (String.make 4 '\x00')
else
count_buf ^ segment_sizes
let rec serialize_fold message ~compression ~init ~f =
let segment_descrs = Message.BytesMessage.Message.to_storage message in
match compression with
| `None ->
let header = make_header segment_descrs in
ListLabels.fold_left segment_descrs ~init:(f init header) ~f:(fun acc descr ->
let open Message.BytesMessage in
let seg =
if descr.Message.bytes_consumed = Bytes.length descr.Message.segment then
descr.Message.segment
else
Bytes.sub descr.Message.segment 0 descr.Message.bytes_consumed
in
f acc (Bytes.unsafe_to_string seg))
| `Packing ->
serialize_fold message ~compression:`None ~init
~f:(fun acc unpacked_fragment ->
f acc (Packing.pack_string unpacked_fragment))
let serialize_iter message ~compression ~f =
serialize_fold message ~compression ~init:() ~f:(fun () s -> f s)
let serialize_fold_copyless message ~compression ~init ~f =
let segment_descrs = Message.BytesMessage.Message.to_storage message in
match compression with
| `None ->
let header = make_header segment_descrs in
ListLabels.fold_left segment_descrs ~init:(f init header (String.length header)) ~f:(fun acc descr ->
let open Message.BytesMessage in
f acc (Bytes.unsafe_to_string descr.Message.segment) descr.Message.bytes_consumed)
| `Packing ->
serialize_fold message ~compression:`None ~init
~f:(fun acc unpacked_fragment ->
let packed_string = Packing.pack_string unpacked_fragment in
f acc packed_string (String.length packed_string))
let serialize_iter_copyless message ~compression ~f =
serialize_fold_copyless message ~compression ~init:() ~f:(fun () s -> f s)
let rec serialize ~compression message =
match compression with
| `None ->
let segment_descrs = Message.BytesMessage.Message.to_storage message in
let header = make_header segment_descrs in
let header_size = String.length header in
let segments_size = Message.BytesMessage.Message.total_size message in
let total_size = header_size + segments_size in
let buf = Bytes.create total_size in
Bytes.blit
(Bytes.unsafe_of_string header) 0
buf 0
header_size;
let (_ : int) = ListLabels.fold_left segment_descrs ~init:header_size
~f:(fun pos descr ->
let open Message.BytesMessage in
Bytes.blit
descr.Message.segment 0
buf pos
descr.Message.bytes_consumed;
pos + descr.Message.bytes_consumed)
in
Bytes.unsafe_to_string buf
| `Packing ->
Packing.pack_string (serialize ~compression:`None message)
|
417b6d6de5a593c2bece06edb1f25c3c649fa223491a32186549ed1814cde142 | shirok/Gauche | mime-port.scm | ;;;
;;; mime-port.scm - submodule to read from mime part body
;;;
Copyright ( c ) 2000 - 2022 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. 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.
;;;
;;; 3. Neither the name of the authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this
;;; software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
;; This module is autoloaded from rfc.mime. You don't need to "use" this
;; directly.
(define-module rfc.mime-port
(use gauche.uvector)
(use gauche.vport)
(use data.queue)
(use util.match)
(export make-mime-port))
(select-module rfc.mime-port)
;;===============================================================
;; Virtual port to recognize mime boundary
;;
(define-class <mime-port> (<buffered-input-port>)
((state :init-form 'prologue)
;; prologue -> boundary <-> body -> eof
))
;; Creates a procedural port, which reads from SRCPORT until it reaches
either EOF or MIME boundary . Basically it runs a DFA .
(define (make-mime-port boundary srcport)
(define q (make-queue))
(define --boundary (string->u8vector #"--~boundary"))
(define port (make <mime-port>))
(define eof (read-from-string ""))
(define (deq! q)
(if (queue-empty? q) eof (dequeue! q)))
(define (fifo! q b)
(enqueue! q b) (dequeue! q))
(define (getb)
(if (queue-empty? q)
(case (ref port 'state)
[(prologue) (skip-prologue)]
[(boundary eof) eof]
[else (newb)])
(dequeue! q)))
(define (newb)
(match (read-byte srcport)
[(and #x0d b) ;; CR, check to see LF
(let1 b2 (peek-byte srcport)
(if (eqv? b2 #x0a)
(begin
(read-byte srcport)
(enqueue! q b #x0a)
(check-boundary))
b))]
LF , check boundary
(enqueue! q b) (check-boundary)]
[(? eof-object?) (set! (ref port 'state) 'eof) eof]
[b b]))
(define (check-boundary)
(let loop ((b (peek-byte srcport))
(ind 0)
(max (u8vector-length --boundary)))
(cond [(eof-object? b) (deq! q)]
[(= ind max)
(cond [(memv b '(#x0d #x0a)) ;;found boundary
consume LF or CRLF
(when (and (eqv? #x0d b)
(eqv? #x0a (peek-byte srcport)))
(read-byte srcport))
(dequeue-all! q)
(set! (ref port 'state) 'boundary)
eof]
[(eqv? b #x2d) ;; maybe end boundary
(enqueue! q (read-byte srcport))
(cond [(eqv? (peek-byte srcport) #x2d);; yes, end boundary
(read-byte srcport)
(dequeue-all! q)
(skip-epilogue)]
[else (deq! q)])]
[else (deq! q)])]
[(= b (u8vector-ref --boundary ind))
(enqueue! q (read-byte srcport))
(loop (peek-byte srcport) (+ ind 1) max)]
[(queue-empty? q) (newb)]
[else (dequeue! q)])))
Reads past the first boundary . The first boundary may appear
;; at the beginning of the message (instead of after CRLF), so
we need slightly different handling than the normal getb .
(define (skip-prologue)
(let loop ((b (check-boundary)))
(cond
[(eof-object? b)
(cond [(eq? (ref port 'state) 'boundary) ; we've found the boundary
(set! (ref port 'state) 'body) (getb)]
[else ; no boundary found
(set! (ref port 'state) 'eof) eof])]
[(queue-empty? q) (loop (newb))]
[else (dequeue-all! q) (loop (newb))])))
(define (skip-epilogue)
(let loop ((b (read-byte srcport)))
(if (eof-object? b)
(begin (set! (ref port 'state) 'eof) b)
(loop (read-byte srcport)))))
;; fills vector, until it sees either
( 1 ) vec got full
( 2 ) srcport reaches EOF
( 3 ) mime - boundary is read
(define (fill vec)
(let1 len (u8vector-length vec)
(let loop ((ind 0))
(if (= ind len)
len
(let1 b (getb)
(if (eof-object? b)
ind
(begin (u8vector-set! vec ind b)
(loop (+ ind 1)))))))))
(set! (ref port 'fill) fill)
port)
| null | https://raw.githubusercontent.com/shirok/Gauche/b773899dbe0b2955e1c4f1daa066da874070c1e4/lib/rfc/mime-port.scm | scheme |
mime-port.scm - submodule to read from mime part body
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the authors nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This module is autoloaded from rfc.mime. You don't need to "use" this
directly.
===============================================================
Virtual port to recognize mime boundary
prologue -> boundary <-> body -> eof
Creates a procedural port, which reads from SRCPORT until it reaches
CR, check to see LF
found boundary
maybe end boundary
yes, end boundary
at the beginning of the message (instead of after CRLF), so
we've found the boundary
no boundary found
fills vector, until it sees either | Copyright ( c ) 2000 - 2022 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(define-module rfc.mime-port
(use gauche.uvector)
(use gauche.vport)
(use data.queue)
(use util.match)
(export make-mime-port))
(select-module rfc.mime-port)
(define-class <mime-port> (<buffered-input-port>)
((state :init-form 'prologue)
))
either EOF or MIME boundary . Basically it runs a DFA .
(define (make-mime-port boundary srcport)
(define q (make-queue))
(define --boundary (string->u8vector #"--~boundary"))
(define port (make <mime-port>))
(define eof (read-from-string ""))
(define (deq! q)
(if (queue-empty? q) eof (dequeue! q)))
(define (fifo! q b)
(enqueue! q b) (dequeue! q))
(define (getb)
(if (queue-empty? q)
(case (ref port 'state)
[(prologue) (skip-prologue)]
[(boundary eof) eof]
[else (newb)])
(dequeue! q)))
(define (newb)
(match (read-byte srcport)
(let1 b2 (peek-byte srcport)
(if (eqv? b2 #x0a)
(begin
(read-byte srcport)
(enqueue! q b #x0a)
(check-boundary))
b))]
LF , check boundary
(enqueue! q b) (check-boundary)]
[(? eof-object?) (set! (ref port 'state) 'eof) eof]
[b b]))
(define (check-boundary)
(let loop ((b (peek-byte srcport))
(ind 0)
(max (u8vector-length --boundary)))
(cond [(eof-object? b) (deq! q)]
[(= ind max)
consume LF or CRLF
(when (and (eqv? #x0d b)
(eqv? #x0a (peek-byte srcport)))
(read-byte srcport))
(dequeue-all! q)
(set! (ref port 'state) 'boundary)
eof]
(enqueue! q (read-byte srcport))
(read-byte srcport)
(dequeue-all! q)
(skip-epilogue)]
[else (deq! q)])]
[else (deq! q)])]
[(= b (u8vector-ref --boundary ind))
(enqueue! q (read-byte srcport))
(loop (peek-byte srcport) (+ ind 1) max)]
[(queue-empty? q) (newb)]
[else (dequeue! q)])))
Reads past the first boundary . The first boundary may appear
we need slightly different handling than the normal getb .
(define (skip-prologue)
(let loop ((b (check-boundary)))
(cond
[(eof-object? b)
(set! (ref port 'state) 'body) (getb)]
(set! (ref port 'state) 'eof) eof])]
[(queue-empty? q) (loop (newb))]
[else (dequeue-all! q) (loop (newb))])))
(define (skip-epilogue)
(let loop ((b (read-byte srcport)))
(if (eof-object? b)
(begin (set! (ref port 'state) 'eof) b)
(loop (read-byte srcport)))))
( 1 ) vec got full
( 2 ) srcport reaches EOF
( 3 ) mime - boundary is read
(define (fill vec)
(let1 len (u8vector-length vec)
(let loop ((ind 0))
(if (= ind len)
len
(let1 b (getb)
(if (eof-object? b)
ind
(begin (u8vector-set! vec ind b)
(loop (+ ind 1)))))))))
(set! (ref port 'fill) fill)
port)
|
4e9e91795bb0fc21a0cde31d27e95fa5aa4f90f379fed4d7a6523969579b10cb | alejandrogallo/keyboard-lab | Cutting.hs | module Cutting where
import Diagrams.Prelude
cutting = green
engraving = orange
| null | https://raw.githubusercontent.com/alejandrogallo/keyboard-lab/e261933a5c4ff3733ccbd951b8830b9dc66bbd32/Cutting.hs | haskell | module Cutting where
import Diagrams.Prelude
cutting = green
engraving = orange
| |
b7ff0265f8a960d1a592a5a1ab9cdf3b7abb7a9983669b65d4606bedd774a63e | taktoa/hsdm | Main.hs | module Main where
import qualified System.HSDM
main :: IO ()
main = System.HSDM.main
| null | https://raw.githubusercontent.com/taktoa/hsdm/e088ddbd20da76ac40450ae4cca9b1f87d042c58/haskell/src/Main.hs | haskell | module Main where
import qualified System.HSDM
main :: IO ()
main = System.HSDM.main
| |
be591f2c66082fcff9069b49d463573cc5a72d595bff76219324ebb817498476 | joeyadams/haskell-iocp | Clock.hs | module IOCP.Clock (
Clock,
Seconds,
getTime,
getClock,
-- * Specific implementations
queryPerformanceCounter,
getTickCount64,
getTickCount,
) where
import qualified IOCP.FFI as FFI
import Control.Monad (liftM)
import Data.IORef
import Data.Int (Int32)
import Data.Word (Word32, Word64)
| Monotonic clock
newtype Clock = Clock (IO Seconds)
type Seconds = Double
| Get the current time , in seconds since some fixed time in the past .
getTime :: Clock -> IO Seconds
getTime (Clock io) = io
-- | Figure out what time API to use, and return a 'Clock' for accessing it.
getClock :: IO Clock
getClock = tryInOrder
[ queryPerformanceCounter
, getTickCount64
, fmap Just getTickCount
]
tryInOrder :: Monad m => [m (Maybe a)] -> m a
tryInOrder (x:xs) = x >>= maybe (tryInOrder xs) return
tryInOrder [] = undefined
mapJust :: Monad m => m (Maybe a) -> (a -> b) -> m (Maybe b)
mapJust m f = liftM (fmap f) m
queryPerformanceCounter :: IO (Maybe Clock)
queryPerformanceCounter =
FFI.queryPerformanceFrequency `mapJust` \freq ->
Clock $ do
count <- FFI.queryPerformanceCounter
return $! fromIntegral count / fromIntegral freq
getTickCount64 :: IO (Maybe Clock)
getTickCount64 =
FFI.loadGetTickCount64 `mapJust` \gtc64 ->
Clock $ do
msec <- gtc64
return $! fromIntegral msec / 1000
getTickCount :: IO Clock
getTickCount = do
Work around GetTickCount 's 49.7 - day wraparound by maintaining a 64 - bit
-- counter and updating it every time the clock is used.
Only works if getTickCount is called at least once every 24.8 days .
count64 <- FFI.getTickCount >>= newIORef . fromIntegral :: IO (IORef Word64)
return $ Clock $ do
msec <- FFI.getTickCount >>= atomicModifyIORef count64 . step
return $! fromIntegral msec / 1000
where
step :: Word32 -> Word64 -> (Word64, Word64)
step now before = (now64, now64)
where
Compute the amount of time that has passed since getTickCount was
called last . Subtract times modulo 2 ^ 32 , to handle wraparound
-- properly. However, convert the offset from unsigned to signed,
-- to avoid a bogus result if now is earlier than before
-- (which should never happen).
offset = fromIntegral (now - fromIntegral before :: Word32) :: Int32
-- Add the offset to the previous time.
now64 = before + fromIntegral offset
| null | https://raw.githubusercontent.com/joeyadams/haskell-iocp/67b65759b3d1473770533f782ca7a42131ae2ca7/IOCP/Clock.hs | haskell | * Specific implementations
| Figure out what time API to use, and return a 'Clock' for accessing it.
counter and updating it every time the clock is used.
properly. However, convert the offset from unsigned to signed,
to avoid a bogus result if now is earlier than before
(which should never happen).
Add the offset to the previous time. | module IOCP.Clock (
Clock,
Seconds,
getTime,
getClock,
queryPerformanceCounter,
getTickCount64,
getTickCount,
) where
import qualified IOCP.FFI as FFI
import Control.Monad (liftM)
import Data.IORef
import Data.Int (Int32)
import Data.Word (Word32, Word64)
| Monotonic clock
newtype Clock = Clock (IO Seconds)
type Seconds = Double
| Get the current time , in seconds since some fixed time in the past .
getTime :: Clock -> IO Seconds
getTime (Clock io) = io
getClock :: IO Clock
getClock = tryInOrder
[ queryPerformanceCounter
, getTickCount64
, fmap Just getTickCount
]
tryInOrder :: Monad m => [m (Maybe a)] -> m a
tryInOrder (x:xs) = x >>= maybe (tryInOrder xs) return
tryInOrder [] = undefined
mapJust :: Monad m => m (Maybe a) -> (a -> b) -> m (Maybe b)
mapJust m f = liftM (fmap f) m
queryPerformanceCounter :: IO (Maybe Clock)
queryPerformanceCounter =
FFI.queryPerformanceFrequency `mapJust` \freq ->
Clock $ do
count <- FFI.queryPerformanceCounter
return $! fromIntegral count / fromIntegral freq
getTickCount64 :: IO (Maybe Clock)
getTickCount64 =
FFI.loadGetTickCount64 `mapJust` \gtc64 ->
Clock $ do
msec <- gtc64
return $! fromIntegral msec / 1000
getTickCount :: IO Clock
getTickCount = do
Work around GetTickCount 's 49.7 - day wraparound by maintaining a 64 - bit
Only works if getTickCount is called at least once every 24.8 days .
count64 <- FFI.getTickCount >>= newIORef . fromIntegral :: IO (IORef Word64)
return $ Clock $ do
msec <- FFI.getTickCount >>= atomicModifyIORef count64 . step
return $! fromIntegral msec / 1000
where
step :: Word32 -> Word64 -> (Word64, Word64)
step now before = (now64, now64)
where
Compute the amount of time that has passed since getTickCount was
called last . Subtract times modulo 2 ^ 32 , to handle wraparound
offset = fromIntegral (now - fromIntegral before :: Word32) :: Int32
now64 = before + fromIntegral offset
|
beefe3a78d3b992a25bea7fe3900200764d440a61a2766033eb486ea31038866 | xh4/web-toolkit | package.lisp | (in-package :cl-user)
(defpackage :utility
(:nicknames :wt.utility)
(:use :cl :alexandria)
(:export
;; tree
:walk-tree
:map-tree
;; string
:string-prefix-p
:string-suffix-p
;; function
:function-lambda-list
;; class
:replace-class-option
:rewrite-class-option
;; parser
:parser
:define-parser
:define-traced-parser
:parse
:*parser-stack*
:with-parser-stack
:parser-match-all-p
:parser-value
:.element :.satisfies :.or :.test :.eq :.seq :.seq/s
:.any :.any/s :.and :.maybe :.some :.some/s :.end :.not
:.n :.n/s :.m :.m/s :.s
:.alpha :alpha-p :.digit :digit-p :.hexdig))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/utility/package.lisp | lisp | tree
string
function
class
parser | (in-package :cl-user)
(defpackage :utility
(:nicknames :wt.utility)
(:use :cl :alexandria)
(:export
:walk-tree
:map-tree
:string-prefix-p
:string-suffix-p
:function-lambda-list
:replace-class-option
:rewrite-class-option
:parser
:define-parser
:define-traced-parser
:parse
:*parser-stack*
:with-parser-stack
:parser-match-all-p
:parser-value
:.element :.satisfies :.or :.test :.eq :.seq :.seq/s
:.any :.any/s :.and :.maybe :.some :.some/s :.end :.not
:.n :.n/s :.m :.m/s :.s
:.alpha :alpha-p :.digit :digit-p :.hexdig))
|
3963ed49cb489079e3e920cae2c247c1acd9c2752272b0c5524cf373c2f3854a | rotatef/json-streams | fail33.lisp | ()
(:begin-array
"mismatch"
:error)
| null | https://raw.githubusercontent.com/rotatef/json-streams/5da012e8133affbf75024e7500feb37394690752/tests/json.org/fail33.lisp | lisp | ()
(:begin-array
"mismatch"
:error)
| |
e3e975c04e37ddc56ff18de5fe9f183a35e3df9c29e13e9ab8b66ee50e1f5ed6 | albertoruiz/easyVision | play6.hs | import Vision.GUI
import Image.Processing
import System.Random(randomIO)
import Util.Misc(splitEvery)
import Util.Statistics(mean)
import Control.Concurrent(threadDelay)
main = runT_ rnd $ see "x" >>> freqMonitor
>>> arrL f >>> see "mean" >>> freqMonitor
see name = observe name (text (Point 0.9 0) . show)
rnd = return (threadDelay 1000 >> fmap (Just . flip mod 10) randomIO)
avg = map (mean . map fromIntegral) . splitEvery 100
f :: [Int] -> [(Int,Double)]
f = zip [1..100] . avg
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/tour/play6.hs | haskell | import Vision.GUI
import Image.Processing
import System.Random(randomIO)
import Util.Misc(splitEvery)
import Util.Statistics(mean)
import Control.Concurrent(threadDelay)
main = runT_ rnd $ see "x" >>> freqMonitor
>>> arrL f >>> see "mean" >>> freqMonitor
see name = observe name (text (Point 0.9 0) . show)
rnd = return (threadDelay 1000 >> fmap (Just . flip mod 10) randomIO)
avg = map (mean . map fromIntegral) . splitEvery 100
f :: [Int] -> [(Int,Double)]
f = zip [1..100] . avg
| |
4dadfaba42e52ffdd611d6171dae85f329161dda91569428b198faadd5fb7291 | cram2/cram | matrix-minmax-index.lisp | Regression test MATRIX - MINMAX - INDEX for GSLL , automatically generated
;;
Copyright 2009 , 2011
Distributed under the terms of the GNU General Public License
;;
;; 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 </>.
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST MATRIX-MINMAX-INDEX
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0 0 2 0)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'SINGLE-FLOAT
:INITIAL-CONTENTS
'((-34.5f0 8.24f0 3.29f0)
(-8.93f0 34.12f0 -6.15f0)
(49.27f0 -13.49f0 32.5f0)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 0 2 0)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'DOUBLE-FLOAT
:INITIAL-CONTENTS
'((-34.5d0
8.24d0
3.29d0)
(-8.93d0
34.12d0
-6.15d0)
(49.27d0
-13.49d0
32.5d0)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1 0 2 2)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE
8)
:INITIAL-CONTENTS
'((-64 -68
71)
(-91 52
-10)
(73 -5
123)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 1 2 1)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE
8)
:INITIAL-CONTENTS
'((67 44
189)
(116 163
140)
(161 215
98)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1 0 2 2)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE
16)
:INITIAL-CONTENTS
'((-64 -68
71)
(-91 52
-10)
(73 -5
123)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 1 2 1)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE
16)
:INITIAL-CONTENTS
'((67 44
189)
(116 163
140)
(161 215
98)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1 0 2 2)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE
32)
:INITIAL-CONTENTS
'((-64 -68
71)
(-91 52
-10)
(73 -5
123)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 1 2 1)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE
32)
:INITIAL-CONTENTS
'((67 44
189)
(116 163
140)
(161 215
98)))))
(MINMAX-INDEX
M1))))
#+int64
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1 0 2 2)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE
64)
:INITIAL-CONTENTS
'((-64 -68
71)
(-91 52
-10)
(73 -5
123)))))
(MINMAX-INDEX
M1))))
#+int64
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 1 2 1)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE
64)
:INITIAL-CONTENTS
'((67 44
189)
(116 163
140)
(161 215
98)))))
(MINMAX-INDEX
M1)))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/tests/matrix-minmax-index.lisp | lisp |
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 </>. | Regression test MATRIX - MINMAX - INDEX for GSLL , automatically generated
Copyright 2009 , 2011
Distributed under the terms of the GNU General Public License
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
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST MATRIX-MINMAX-INDEX
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 0 0 2 0)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'SINGLE-FLOAT
:INITIAL-CONTENTS
'((-34.5f0 8.24f0 3.29f0)
(-8.93f0 34.12f0 -6.15f0)
(49.27f0 -13.49f0 32.5f0)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 0 2 0)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'DOUBLE-FLOAT
:INITIAL-CONTENTS
'((-34.5d0
8.24d0
3.29d0)
(-8.93d0
34.12d0
-6.15d0)
(49.27d0
-13.49d0
32.5d0)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1 0 2 2)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE
8)
:INITIAL-CONTENTS
'((-64 -68
71)
(-91 52
-10)
(73 -5
123)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 1 2 1)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE
8)
:INITIAL-CONTENTS
'((67 44
189)
(116 163
140)
(161 215
98)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1 0 2 2)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE
16)
:INITIAL-CONTENTS
'((-64 -68
71)
(-91 52
-10)
(73 -5
123)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 1 2 1)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE
16)
:INITIAL-CONTENTS
'((67 44
189)
(116 163
140)
(161 215
98)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1 0 2 2)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE
32)
:INITIAL-CONTENTS
'((-64 -68
71)
(-91 52
-10)
(73 -5
123)))))
(MINMAX-INDEX
M1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 1 2 1)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE
32)
:INITIAL-CONTENTS
'((67 44
189)
(116 163
140)
(161 215
98)))))
(MINMAX-INDEX
M1))))
#+int64
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 1 0 2 2)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE
64)
:INITIAL-CONTENTS
'((-64 -68
71)
(-91 52
-10)
(73 -5
123)))))
(MINMAX-INDEX
M1))))
#+int64
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 0 1 2 1)
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE
64)
:INITIAL-CONTENTS
'((67 44
189)
(116 163
140)
(161 215
98)))))
(MINMAX-INDEX
M1)))))
|
28a3eb2e49e5bf5f68681ffd5dfa1bc6d825f9f44b95a1139ec735ded8518fed | input-output-hk/ouroboros-network | Driver.hs |
| Drivers for running ' Peer 's with a ' Codec ' and a ' Channel ' .
--
module Ouroboros.Network.Driver
( -- * Normal peers
runPeer
, runPeerWithLimits
, TraceSendRecv (..)
* peers
, runPipelinedPeer
, runPipelinedPeerWithLimits
) where
import Ouroboros.Network.Driver.Limits
import Ouroboros.Network.Driver.Simple
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/6c15a8093bac34091ad96af2b8b0d1f7fe54b732/ouroboros-network-framework/src/Ouroboros/Network/Driver.hs | haskell |
* Normal peers |
| Drivers for running ' Peer 's with a ' Codec ' and a ' Channel ' .
module Ouroboros.Network.Driver
runPeer
, runPeerWithLimits
, TraceSendRecv (..)
* peers
, runPipelinedPeer
, runPipelinedPeerWithLimits
) where
import Ouroboros.Network.Driver.Limits
import Ouroboros.Network.Driver.Simple
|
322eb85fdae7d73a58c94bda065284a235de23adcdb65c07ef96fa45bf5ce6d2 | ygrek/mldonkey | filename2.mli | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey 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 .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey 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.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val slash : char
(** character used as a directory separator in file paths *)
val dirname : string -> string
d [ filename ] returns the dirname of [ filename ] after normalization
val normalize : string -> string
(*d [normalize filename] returns a normalized name for [filename], where no
"//", "<name>/.." or "/./" are present. *)
val extension : string -> string
d [ extension filename ] returns the longest extension of [ filename ] ,
which is the substring after the first " . " in [ filename ] ( including
the " . " )
which is the substring after the first "." in [filename] (including
the ".") *)
val last_extension : string -> string
(*d [last_extension filename] returns the last extension of [filename],
which is the substring after the last "." in [filename]
(including the "."). If no extension is present, returns "". *)
val last_extension2 : string -> string
(*d [last_extension filename] returns the last extension of [filename],
which is the substring after the last "." in [filename]
(without the "."). If no extension is present, returns "". *)
val extensions : string -> string list
(*d [extensions filename] returns the list of extensions (without the dot)
found at the end of filename. *)
val register_conversions: (string -> string) -> (string -> string) -> unit
d [ register_conversions from_string to_string ] registers two conversion
functions for filenames . The first [ from_string ] one converts strings
( from the user ) to
filenames ( for system use ) , whereas the second [ to_string ]
converts filenames to strings .
functions for filenames. The first [from_string] one converts strings
(from the user) to
filenames (for system use) , whereas the second [to_string]
converts filenames to strings.
*)
val from_string : string -> string
(*d [from_string str] converts the [str] string to a filename using reistered
conversion functions. *)
val to_string : string -> string
(*d [to_string filename] converts [filename] to a string using registered
conversion functions. *)
transform a filename in a list of
val path_of_filename : string -> string list
val basename : string -> string
(* remove invalid chars in a filename, depending on the filesystem,
trim filename length to allowed limit on filesystem *)
val filesystem_compliant : string -> Unix32.fstype -> int -> string
* [ temp_file prefix suffix ] returns the name of a
fresh temporary file in the temporary directory .
The base name of the temporary file is formed by concatenating
[ prefix ] , then a suitably chosen integer number , then [ suffix ] .
The temporary file is created empty , with permissions [ 0o600 ]
( readable and writable only by the file owner ) . The file is
guaranteed to be different from any other file that existed when
[ temp_file ] was called .
fresh temporary file in the temporary directory.
The base name of the temporary file is formed by concatenating
[prefix], then a suitably chosen integer number, then [suffix].
The temporary file is created empty, with permissions [0o600]
(readable and writable only by the file owner). The file is
guaranteed to be different from any other file that existed when
[temp_file] was called.
*)
val temp_file : string -> string -> string
(** The name of the temporary directory:
The value of the [MLDONKEY_TEMP] environment variable is used,
or "mlnet_tmp" if the variable is not set.
*)
val temp_dir_name : unit -> string
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/utils/cdk/filename2.mli | ocaml | * character used as a directory separator in file paths
d [normalize filename] returns a normalized name for [filename], where no
"//", "<name>/.." or "/./" are present.
d [last_extension filename] returns the last extension of [filename],
which is the substring after the last "." in [filename]
(including the "."). If no extension is present, returns "".
d [last_extension filename] returns the last extension of [filename],
which is the substring after the last "." in [filename]
(without the "."). If no extension is present, returns "".
d [extensions filename] returns the list of extensions (without the dot)
found at the end of filename.
d [from_string str] converts the [str] string to a filename using reistered
conversion functions.
d [to_string filename] converts [filename] to a string using registered
conversion functions.
remove invalid chars in a filename, depending on the filesystem,
trim filename length to allowed limit on filesystem
* The name of the temporary directory:
The value of the [MLDONKEY_TEMP] environment variable is used,
or "mlnet_tmp" if the variable is not set.
| Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This file is part of mldonkey .
mldonkey 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 .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This file is part of mldonkey.
mldonkey 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.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
val slash : char
val dirname : string -> string
d [ filename ] returns the dirname of [ filename ] after normalization
val normalize : string -> string
val extension : string -> string
d [ extension filename ] returns the longest extension of [ filename ] ,
which is the substring after the first " . " in [ filename ] ( including
the " . " )
which is the substring after the first "." in [filename] (including
the ".") *)
val last_extension : string -> string
val last_extension2 : string -> string
val extensions : string -> string list
val register_conversions: (string -> string) -> (string -> string) -> unit
d [ register_conversions from_string to_string ] registers two conversion
functions for filenames . The first [ from_string ] one converts strings
( from the user ) to
filenames ( for system use ) , whereas the second [ to_string ]
converts filenames to strings .
functions for filenames. The first [from_string] one converts strings
(from the user) to
filenames (for system use) , whereas the second [to_string]
converts filenames to strings.
*)
val from_string : string -> string
val to_string : string -> string
transform a filename in a list of
val path_of_filename : string -> string list
val basename : string -> string
val filesystem_compliant : string -> Unix32.fstype -> int -> string
* [ temp_file prefix suffix ] returns the name of a
fresh temporary file in the temporary directory .
The base name of the temporary file is formed by concatenating
[ prefix ] , then a suitably chosen integer number , then [ suffix ] .
The temporary file is created empty , with permissions [ 0o600 ]
( readable and writable only by the file owner ) . The file is
guaranteed to be different from any other file that existed when
[ temp_file ] was called .
fresh temporary file in the temporary directory.
The base name of the temporary file is formed by concatenating
[prefix], then a suitably chosen integer number, then [suffix].
The temporary file is created empty, with permissions [0o600]
(readable and writable only by the file owner). The file is
guaranteed to be different from any other file that existed when
[temp_file] was called.
*)
val temp_file : string -> string -> string
val temp_dir_name : unit -> string
|
d2989b420ac3667de105b005dc7f0db3e5729ff6f0d033398474ec793c09759a | elaforge/karya | Library.hs | Copyright 2014
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
{-# LANGUAGE RankNTypes #-}
| Utilities for the Library type .
module Derive.Library (
-- * make
Library, library, generators, transformers, vals, pattern
, ToLibrary, Entry(..)
, Calls(..), both
, poly_generators, poly_transformers
-- * compile
, Shadowed, compile, compile_log
) where
import qualified Data.Either as Either
import qualified Data.Map.Strict as Map
import qualified Util.Log as Log
import qualified Util.Logger as Logger
import qualified Util.Maps as Maps
import qualified Util.Seq as Seq
import qualified Derive.Call.Module as Module
import qualified Derive.Derive as Derive
import qualified Derive.Expr as Expr
import Global
-- | The holds the libary of statically-declared calls. It gets compiled to
-- 'Derive.Builtins' by 'compile'.
type Library = Derive.ScopesT
(Derive.Scope
[Entry (Derive.Generator Derive.Note)]
[Entry (Derive.Generator Derive.Control)]
[Entry (Derive.Generator Derive.Pitch)])
(Derive.Scope
[Entry (Derive.Transformer Derive.Note)]
[Entry (Derive.Transformer Derive.Control)]
[Entry (Derive.Transformer Derive.Pitch)])
(Derive.Scope
[Entry (Derive.TrackCall Derive.Note)]
[Entry (Derive.TrackCall Derive.Control)]
[Entry (Derive.TrackCall Derive.Pitch)])
[Entry Derive.ValCall]
data Entry call =
Single !Expr.Symbol !call
| Pattern !(Derive.PatternCall call)
instance Show Library where show _ = "((Library))"
instance Pretty (Entry call) where
pretty (Single sym _) = Expr.unsym sym
pretty (Pattern pattern) = "pattern:" <> Derive.pat_description pattern
-- * make
library :: ToLibrary call => [(Expr.Symbol, call)] -> Library
library [] = mempty
library calls = to_library (map (uncurry Single) calls) mempty
-- | This is just a specialization of 'library', just for documentation.
generators :: ToLibrary (Derive.Generator call) =>
[(Expr.Symbol, Derive.Generator call)] -> Library
generators = library
-- | This is just a specialization of 'library', just for documentation.
transformers :: ToLibrary (Derive.Transformer call) =>
[(Expr.Symbol, Derive.Transformer call)] -> Library
transformers = library
-- | This is just a specialization of 'library', just for documentation.
vals :: [(Expr.Symbol, Derive.ValCall)] -> Library
vals = library
pattern :: ToLibrary call => Derive.PatternCall call -> Library
pattern c = to_library [Pattern c] mempty
-- | Bundle a generator and transformer together, so I can define them
together . Functions to create these are in " Derive . Call . Make " .
data Calls d = Calls {
generator :: !(Derive.Generator d)
, transformer :: !(Derive.Transformer d)
}
both :: (ToLibrary (Derive.Generator d), ToLibrary (Derive.Transformer d)) =>
[(Expr.Symbol, Calls d)] -> Library
both sym_calls =
generators (zip syms (map generator calls))
<> transformers (zip syms (map transformer calls))
where (syms, calls) = unzip sym_calls
-- | Add a polymorphic generator to all call types.
--
The Callable constraint is not needed here , but callers will have it , and
-- for some reason you can't coerce a parametric variable into a constrained
-- one.
poly_generators ::
(forall d. Derive.CallableExpr d => [(Expr.Symbol, Derive.Generator d)])
-> Library
poly_generators calls = mconcat
[ generators (calls :: [(Expr.Symbol, Derive.Generator Derive.Note)])
, generators (calls :: [(Expr.Symbol, Derive.Generator Derive.Control)])
, generators (calls :: [(Expr.Symbol, Derive.Generator Derive.Pitch)])
]
poly_transformers ::
(forall d. Derive.CallableExpr d => [(Expr.Symbol, Derive.Transformer d)])
-> Library
poly_transformers calls = mconcat
[ transformers (calls :: [(Expr.Symbol, Derive.Transformer Derive.Note)])
, transformers (calls :: [(Expr.Symbol, Derive.Transformer Derive.Control)])
, transformers (calls :: [(Expr.Symbol, Derive.Transformer Derive.Pitch)])
]
* *
class ToLibrary call where
to_library :: [Entry call] -> Library -> Library
instance ToLibrary (Derive.Generator Derive.Note) where
to_library = (Derive.s_generator#Derive.s_note #=)
instance ToLibrary (Derive.Generator Derive.Control) where
to_library = (Derive.s_generator#Derive.s_control #=)
instance ToLibrary (Derive.Generator Derive.Pitch) where
to_library = (Derive.s_generator#Derive.s_pitch #=)
instance ToLibrary (Derive.Transformer Derive.Note) where
to_library = (Derive.s_transformer#Derive.s_note #=)
instance ToLibrary (Derive.Transformer Derive.Control) where
to_library = (Derive.s_transformer#Derive.s_control #=)
instance ToLibrary (Derive.Transformer Derive.Pitch) where
to_library = (Derive.s_transformer#Derive.s_pitch #=)
instance ToLibrary (Derive.TrackCall Derive.Note) where
to_library = (Derive.s_track#Derive.s_note #=)
instance ToLibrary (Derive.TrackCall Derive.Control) where
to_library = (Derive.s_track#Derive.s_control #=)
instance ToLibrary (Derive.TrackCall Derive.Pitch) where
to_library = (Derive.s_track#Derive.s_pitch #=)
instance ToLibrary Derive.ValCall where
to_library = (Derive.s_val #=)
-- * compile
-- | Warnings for shadowed symbols. ((call_type, module), symbols)
type Shadowed = ((Text, Module.Module), [Expr.Symbol])
-- | Convert Library to Builtins. This indexes by module and also gives me
-- a place to emit warnings about duplicate symbol names.
compile :: Library -> (Derive.Builtins, [Shadowed])
compile (Derive.Scopes lgen ltrans ltrack lval) = Logger.runId $ Derive.Scopes
<$> compile_scope Derive.call_doc Derive.call_doc Derive.call_doc lgen
<*> compile_scope Derive.call_doc Derive.call_doc Derive.call_doc ltrans
<*> compile_scope Derive.tcall_doc Derive.tcall_doc Derive.tcall_doc ltrack
<*> compile_entries "val" Derive.vcall_doc lval
where
compile_scope doc1 doc2 doc3 (Derive.Scope note control pitch) =
Derive.Scope
<$> compile_entries "note" doc1 note
<*> compile_entries "control" doc2 control
<*> compile_entries "pitch" doc3 pitch
compile_entries kind get_doc = fmap Map.fromAscList
. traverse (compile1 kind)
. Seq.keyed_group_sort (Derive.cdoc_module . entry_doc)
where
entry_doc (Single _ call) = get_doc call
entry_doc (Pattern pattern) = Derive.pat_call_doc pattern
compile1 kind (module_, entries) = do
let (singles, patterns) = partition entries
let (cmap, dups) = Maps.unique singles
unless (null dups) $
Logger.log ((kind, module_), map fst dups)
return $ (module_,) $ Derive.CallMap
{ call_map = cmap
, call_patterns = patterns
}
partition = Either.partitionEithers . map partition1
partition1 (Single sym call) = Left (sym, call)
partition1 (Pattern pattern) = Right pattern
compile_log :: Log.LogMonad m => Library -> m Derive.Builtins
compile_log lib = do
let (builtins, shadows) = compile lib
forM_ shadows $ \((call_type, _module), calls) ->
Log.warn $ call_type <> " shadowed: " <> pretty calls
return builtins
| null | https://raw.githubusercontent.com/elaforge/karya/471a2131f5a68b3b10b1a138e6f9ed1282980a18/Derive/Library.hs | haskell | This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt
# LANGUAGE RankNTypes #
* make
* compile
| The holds the libary of statically-declared calls. It gets compiled to
'Derive.Builtins' by 'compile'.
* make
| This is just a specialization of 'library', just for documentation.
| This is just a specialization of 'library', just for documentation.
| This is just a specialization of 'library', just for documentation.
| Bundle a generator and transformer together, so I can define them
| Add a polymorphic generator to all call types.
for some reason you can't coerce a parametric variable into a constrained
one.
* compile
| Warnings for shadowed symbols. ((call_type, module), symbols)
| Convert Library to Builtins. This indexes by module and also gives me
a place to emit warnings about duplicate symbol names. | Copyright 2014
| Utilities for the Library type .
module Derive.Library (
Library, library, generators, transformers, vals, pattern
, ToLibrary, Entry(..)
, Calls(..), both
, poly_generators, poly_transformers
, Shadowed, compile, compile_log
) where
import qualified Data.Either as Either
import qualified Data.Map.Strict as Map
import qualified Util.Log as Log
import qualified Util.Logger as Logger
import qualified Util.Maps as Maps
import qualified Util.Seq as Seq
import qualified Derive.Call.Module as Module
import qualified Derive.Derive as Derive
import qualified Derive.Expr as Expr
import Global
type Library = Derive.ScopesT
(Derive.Scope
[Entry (Derive.Generator Derive.Note)]
[Entry (Derive.Generator Derive.Control)]
[Entry (Derive.Generator Derive.Pitch)])
(Derive.Scope
[Entry (Derive.Transformer Derive.Note)]
[Entry (Derive.Transformer Derive.Control)]
[Entry (Derive.Transformer Derive.Pitch)])
(Derive.Scope
[Entry (Derive.TrackCall Derive.Note)]
[Entry (Derive.TrackCall Derive.Control)]
[Entry (Derive.TrackCall Derive.Pitch)])
[Entry Derive.ValCall]
data Entry call =
Single !Expr.Symbol !call
| Pattern !(Derive.PatternCall call)
instance Show Library where show _ = "((Library))"
instance Pretty (Entry call) where
pretty (Single sym _) = Expr.unsym sym
pretty (Pattern pattern) = "pattern:" <> Derive.pat_description pattern
library :: ToLibrary call => [(Expr.Symbol, call)] -> Library
library [] = mempty
library calls = to_library (map (uncurry Single) calls) mempty
generators :: ToLibrary (Derive.Generator call) =>
[(Expr.Symbol, Derive.Generator call)] -> Library
generators = library
transformers :: ToLibrary (Derive.Transformer call) =>
[(Expr.Symbol, Derive.Transformer call)] -> Library
transformers = library
vals :: [(Expr.Symbol, Derive.ValCall)] -> Library
vals = library
pattern :: ToLibrary call => Derive.PatternCall call -> Library
pattern c = to_library [Pattern c] mempty
together . Functions to create these are in " Derive . Call . Make " .
data Calls d = Calls {
generator :: !(Derive.Generator d)
, transformer :: !(Derive.Transformer d)
}
both :: (ToLibrary (Derive.Generator d), ToLibrary (Derive.Transformer d)) =>
[(Expr.Symbol, Calls d)] -> Library
both sym_calls =
generators (zip syms (map generator calls))
<> transformers (zip syms (map transformer calls))
where (syms, calls) = unzip sym_calls
The Callable constraint is not needed here , but callers will have it , and
poly_generators ::
(forall d. Derive.CallableExpr d => [(Expr.Symbol, Derive.Generator d)])
-> Library
poly_generators calls = mconcat
[ generators (calls :: [(Expr.Symbol, Derive.Generator Derive.Note)])
, generators (calls :: [(Expr.Symbol, Derive.Generator Derive.Control)])
, generators (calls :: [(Expr.Symbol, Derive.Generator Derive.Pitch)])
]
poly_transformers ::
(forall d. Derive.CallableExpr d => [(Expr.Symbol, Derive.Transformer d)])
-> Library
poly_transformers calls = mconcat
[ transformers (calls :: [(Expr.Symbol, Derive.Transformer Derive.Note)])
, transformers (calls :: [(Expr.Symbol, Derive.Transformer Derive.Control)])
, transformers (calls :: [(Expr.Symbol, Derive.Transformer Derive.Pitch)])
]
* *
class ToLibrary call where
to_library :: [Entry call] -> Library -> Library
instance ToLibrary (Derive.Generator Derive.Note) where
to_library = (Derive.s_generator#Derive.s_note #=)
instance ToLibrary (Derive.Generator Derive.Control) where
to_library = (Derive.s_generator#Derive.s_control #=)
instance ToLibrary (Derive.Generator Derive.Pitch) where
to_library = (Derive.s_generator#Derive.s_pitch #=)
instance ToLibrary (Derive.Transformer Derive.Note) where
to_library = (Derive.s_transformer#Derive.s_note #=)
instance ToLibrary (Derive.Transformer Derive.Control) where
to_library = (Derive.s_transformer#Derive.s_control #=)
instance ToLibrary (Derive.Transformer Derive.Pitch) where
to_library = (Derive.s_transformer#Derive.s_pitch #=)
instance ToLibrary (Derive.TrackCall Derive.Note) where
to_library = (Derive.s_track#Derive.s_note #=)
instance ToLibrary (Derive.TrackCall Derive.Control) where
to_library = (Derive.s_track#Derive.s_control #=)
instance ToLibrary (Derive.TrackCall Derive.Pitch) where
to_library = (Derive.s_track#Derive.s_pitch #=)
instance ToLibrary Derive.ValCall where
to_library = (Derive.s_val #=)
type Shadowed = ((Text, Module.Module), [Expr.Symbol])
compile :: Library -> (Derive.Builtins, [Shadowed])
compile (Derive.Scopes lgen ltrans ltrack lval) = Logger.runId $ Derive.Scopes
<$> compile_scope Derive.call_doc Derive.call_doc Derive.call_doc lgen
<*> compile_scope Derive.call_doc Derive.call_doc Derive.call_doc ltrans
<*> compile_scope Derive.tcall_doc Derive.tcall_doc Derive.tcall_doc ltrack
<*> compile_entries "val" Derive.vcall_doc lval
where
compile_scope doc1 doc2 doc3 (Derive.Scope note control pitch) =
Derive.Scope
<$> compile_entries "note" doc1 note
<*> compile_entries "control" doc2 control
<*> compile_entries "pitch" doc3 pitch
compile_entries kind get_doc = fmap Map.fromAscList
. traverse (compile1 kind)
. Seq.keyed_group_sort (Derive.cdoc_module . entry_doc)
where
entry_doc (Single _ call) = get_doc call
entry_doc (Pattern pattern) = Derive.pat_call_doc pattern
compile1 kind (module_, entries) = do
let (singles, patterns) = partition entries
let (cmap, dups) = Maps.unique singles
unless (null dups) $
Logger.log ((kind, module_), map fst dups)
return $ (module_,) $ Derive.CallMap
{ call_map = cmap
, call_patterns = patterns
}
partition = Either.partitionEithers . map partition1
partition1 (Single sym call) = Left (sym, call)
partition1 (Pattern pattern) = Right pattern
compile_log :: Log.LogMonad m => Library -> m Derive.Builtins
compile_log lib = do
let (builtins, shadows) = compile lib
forM_ shadows $ \((call_type, _module), calls) ->
Log.warn $ call_type <> " shadowed: " <> pretty calls
return builtins
|
c0d7a931462bcb8f785327289028f10c3159b7bf2929a9268994577d5cebeb78 | chvanikoff/cowboy_session | cowboy_session_storage.erl | -module(cowboy_session_storage).
-author('chvanikoff <>').
-type error() :: {already_started, pid()} | term().
-callback start_link() -> {ok, pid()} | ignore | {error, error()}.
-callback new(SID) -> ok when
SID :: bitstring().
-callback set(SID, Key, Value) -> ok when
SID :: bitstring(),
Key :: term(),
Value :: term().
-callback get(SID, Key, Default) -> term() when
SID :: bitstring(),
Key :: term(),
Default :: term().
-callback delete(SID) -> ok when
SID :: bitstring().
-callback stop(New_storage) -> ok when
New_storage :: pid().
| null | https://raw.githubusercontent.com/chvanikoff/cowboy_session/11950a69686c10c7dad5c5fe2f21f7af0d8cf816/src/cowboy_session_storage.erl | erlang | -module(cowboy_session_storage).
-author('chvanikoff <>').
-type error() :: {already_started, pid()} | term().
-callback start_link() -> {ok, pid()} | ignore | {error, error()}.
-callback new(SID) -> ok when
SID :: bitstring().
-callback set(SID, Key, Value) -> ok when
SID :: bitstring(),
Key :: term(),
Value :: term().
-callback get(SID, Key, Default) -> term() when
SID :: bitstring(),
Key :: term(),
Default :: term().
-callback delete(SID) -> ok when
SID :: bitstring().
-callback stop(New_storage) -> ok when
New_storage :: pid().
| |
836fe8e7e04156b906f1c75bf7f40dc2228534731cc9f2fb599a58537243a5bc | imandra-ai/imandra-ros | bond_to_json.ml | open Json_utils;;
open Basic_types_to_json;;
open Ros_messages.Bond;;
let status_to_json x = [
( "header" , x.header |> Std_msgs_to_json.header_to_json );
( "id" , x.id |> string_to_json );
( "instance_id" , x.instance_id |> string_to_json );
( "active" , x.active |> bool_to_json );
( "heartbeat_timeout" , x.heartbeat_timeout |> float32_to_json );
( "heartbeat_period" , x.heartbeat_period |> float32_to_json );
] |> assoc_filter_nulls
let constants_to_json x = `Assoc []
| null | https://raw.githubusercontent.com/imandra-ai/imandra-ros/e1380c267ee319dd4f86c4b54e0b270bc0738796/imandra_model/src-messages-pp/bond_to_json.ml | ocaml | open Json_utils;;
open Basic_types_to_json;;
open Ros_messages.Bond;;
let status_to_json x = [
( "header" , x.header |> Std_msgs_to_json.header_to_json );
( "id" , x.id |> string_to_json );
( "instance_id" , x.instance_id |> string_to_json );
( "active" , x.active |> bool_to_json );
( "heartbeat_timeout" , x.heartbeat_timeout |> float32_to_json );
( "heartbeat_period" , x.heartbeat_period |> float32_to_json );
] |> assoc_filter_nulls
let constants_to_json x = `Assoc []
| |
e898cf29d991b2c0c2b0857f08379203c9f62e84d985d629dc6583e1c8fe8f11 | camllight/camllight | prop.mli | type proposition =
Vrai
| Faux
| Non of proposition
| Et of proposition * proposition
| Ou of proposition * proposition
| Implique of proposition * proposition
| Équivalent of proposition * proposition
| Variable of string;;
exception Réfutation of (string * bool) list;;
value vérifie_tautologie: proposition -> string list -> unit
and variables_libres: proposition -> string list;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/examples/demonstr/prop.mli | ocaml | type proposition =
Vrai
| Faux
| Non of proposition
| Et of proposition * proposition
| Ou of proposition * proposition
| Implique of proposition * proposition
| Équivalent of proposition * proposition
| Variable of string;;
exception Réfutation of (string * bool) list;;
value vérifie_tautologie: proposition -> string list -> unit
and variables_libres: proposition -> string list;;
| |
da6464765ee8e04b9c45a34fdd565087c9428ea4e976491d5c7d39c31fbad3d6 | fluree/db | retraction_test.clj | (ns fluree.db.transact.retraction-test
(:require [clojure.test :refer :all]
[fluree.db.test-utils :as test-utils]
[fluree.db.json-ld.api :as fluree]))
(deftest ^:integration retracting-data
(testing "Retractions of individual properties and entire subjects."
(let [conn (test-utils/create-conn)
ledger @(fluree/create conn "tx/retract")
db @(fluree/stage
(fluree/db ledger)
{:context {:ex "/"}
:graph [{:id :ex/alice,
:type :ex/User,
:schema/name "Alice"
:schema/age 42}
{:id :ex/bob,
:type :ex/User,
:schema/name "Bob"
:schema/age 22}
{:id :ex/jane,
:type :ex/User,
:schema/name "Jane"
:schema/age 30}]})
retract 's age attribute by using nil
db-age-retract @(fluree/stage
db
{:context {:ex "/"}
:id :ex/alice,
:schema/age nil})]
(is (= @(fluree/query db-age-retract
'{:context {:ex "/"},
:select {?s [:*]},
:where [[?s :id :ex/alice]]})
[{:id :ex/alice,
:rdf/type [:ex/User],
:schema/name "Alice"}])
"Alice should no longer have an age property"))))
| null | https://raw.githubusercontent.com/fluree/db/ef55f39b24f2c9d0770e6cfd096c8337e0040439/test/fluree/db/transact/retraction_test.clj | clojure | (ns fluree.db.transact.retraction-test
(:require [clojure.test :refer :all]
[fluree.db.test-utils :as test-utils]
[fluree.db.json-ld.api :as fluree]))
(deftest ^:integration retracting-data
(testing "Retractions of individual properties and entire subjects."
(let [conn (test-utils/create-conn)
ledger @(fluree/create conn "tx/retract")
db @(fluree/stage
(fluree/db ledger)
{:context {:ex "/"}
:graph [{:id :ex/alice,
:type :ex/User,
:schema/name "Alice"
:schema/age 42}
{:id :ex/bob,
:type :ex/User,
:schema/name "Bob"
:schema/age 22}
{:id :ex/jane,
:type :ex/User,
:schema/name "Jane"
:schema/age 30}]})
retract 's age attribute by using nil
db-age-retract @(fluree/stage
db
{:context {:ex "/"}
:id :ex/alice,
:schema/age nil})]
(is (= @(fluree/query db-age-retract
'{:context {:ex "/"},
:select {?s [:*]},
:where [[?s :id :ex/alice]]})
[{:id :ex/alice,
:rdf/type [:ex/User],
:schema/name "Alice"}])
"Alice should no longer have an age property"))))
| |
8af840a9299f4a2dd95d75e579031083f8bc9c17d0ebd4ee8d5aab01d370d22c | zotonic/ringbuffer | ringbuffer_app.erl | @author < >
2021
@doc RingBuffer application
Copyright 2021
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
-module(ringbuffer_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%% ===================================================================
%% Application callbacks
%% ===================================================================
@doc Application callback , start the supervisor .
start(_StartType, _StartArgs) ->
ringbuffer_sup:start_link().
%% @doc Application callback, called when stopping the application.
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/zotonic/ringbuffer/5c27f3dcadb20eefa30f165f0836781236bfa289/src/ringbuffer_app.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Application callbacks
===================================================================
Application callbacks
===================================================================
@doc Application callback, called when stopping the application. | @author < >
2021
@doc RingBuffer application
Copyright 2021
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(ringbuffer_app).
-behaviour(application).
-export([start/2, stop/1]).
@doc Application callback , start the supervisor .
start(_StartType, _StartArgs) ->
ringbuffer_sup:start_link().
stop(_State) ->
ok.
|
cd3a3f33ed8f28980b065aa1c4177dc14ca4cf033560c85c947058bd524e4816 | stumpwm/stumpwm-contrib | stump-nm.lisp | (in-package #:stump-nm)
(stumpwm:defcommand nm-list-wireless-networks () ()
(with-open-bus (bus (system-server-addresses))
(let* ((root (make-root bus))
(primary-connection (primary-connection root))
(is-connected (= (getprop root "State") 70))
(is-wireless (search "wireless" (getprop primary-connection "Type")))
(device (first (connection-devices primary-connection))))
(when (and is-connected (not is-wireless))
(error "Wired connection is established"))
(let ((selected
(stumpwm:select-from-menu
(stumpwm:current-screen)
(mapcar (lambda (ap) (list (render-ap ap primary-connection) ap))
(device-access-points device)))))
(when selected
(let ((ap (second selected)))
(dbus-call root "DeactivateConnection" (path primary-connection))
(unless (active ap)
(dbus-call root "ActivateConnection" "/" (path device) (path ap))))))))
nil)
(stumpwm:defcommand nm-list-vpn-connections () ()
(with-open-bus (bus (system-server-addresses))
(let* ((root (make-root bus))
(settings (get-settings root))
(all-connections (get-connection-settings settings))
(vpn-connections (remove-if-not #'is-vpn-connection all-connections))
(active-connections (get-active-connections root))
(active-connections-uuids (mapcar #'uuid active-connections))
(selected (stumpwm:select-from-menu
(stumpwm:current-screen)
(mapcar (lambda (connection)
(let ((is-active
(member (uuid connection)
active-connections-uuids
:test #'string=)))
(list
(render-vpn-connection
connection
(when is-active
(find-active-connection-by-uuid
active-connections
(uuid connection))))
connection
is-active)))
vpn-connections))))
(when selected
(let ((connection (second selected))
(was-active (third selected)))
(if was-active
(let ((active-connection (find-active-connection-by-uuid
active-connections
(uuid connection))))
(dbus-call root "DeactivateConnection" (path active-connection)))
(dbus-call root "ActivateConnection"
(path (connection connection)) "/" "/"))))))
nil)
(defun find-active-connection-by-uuid (active-connections uuid)
(find-if (lambda (active-connection)
(string= (uuid active-connection) uuid))
active-connections))
(defun is-vpn-connection (c)
(string= (cs-type c) "vpn"))
(defun render-vpn-connection (connection active-connection)
(format nil "~A ~A"
(if active-connection
(active-connection-state-indicator (state active-connection))
" ")
(id connection)))
(defun render-ap (ap connection)
(format nil "~A ~A (~AMHz) ~A%"
(if (active ap)
(active-connection-state-indicator (state connection))
" ")
(ssid ap) (frequency ap) (strength ap)))
(defun active-connection-state-indicator (state)
(ecase state
(0 "?")
(1 "?")
(2 "*")
(3 " ")
(4 " ")))
| null | https://raw.githubusercontent.com/stumpwm/stumpwm-contrib/a7dc1c663d04e6c73a4772c8a6ad56a34381096a/util/stump-nm/stump-nm.lisp | lisp | (in-package #:stump-nm)
(stumpwm:defcommand nm-list-wireless-networks () ()
(with-open-bus (bus (system-server-addresses))
(let* ((root (make-root bus))
(primary-connection (primary-connection root))
(is-connected (= (getprop root "State") 70))
(is-wireless (search "wireless" (getprop primary-connection "Type")))
(device (first (connection-devices primary-connection))))
(when (and is-connected (not is-wireless))
(error "Wired connection is established"))
(let ((selected
(stumpwm:select-from-menu
(stumpwm:current-screen)
(mapcar (lambda (ap) (list (render-ap ap primary-connection) ap))
(device-access-points device)))))
(when selected
(let ((ap (second selected)))
(dbus-call root "DeactivateConnection" (path primary-connection))
(unless (active ap)
(dbus-call root "ActivateConnection" "/" (path device) (path ap))))))))
nil)
(stumpwm:defcommand nm-list-vpn-connections () ()
(with-open-bus (bus (system-server-addresses))
(let* ((root (make-root bus))
(settings (get-settings root))
(all-connections (get-connection-settings settings))
(vpn-connections (remove-if-not #'is-vpn-connection all-connections))
(active-connections (get-active-connections root))
(active-connections-uuids (mapcar #'uuid active-connections))
(selected (stumpwm:select-from-menu
(stumpwm:current-screen)
(mapcar (lambda (connection)
(let ((is-active
(member (uuid connection)
active-connections-uuids
:test #'string=)))
(list
(render-vpn-connection
connection
(when is-active
(find-active-connection-by-uuid
active-connections
(uuid connection))))
connection
is-active)))
vpn-connections))))
(when selected
(let ((connection (second selected))
(was-active (third selected)))
(if was-active
(let ((active-connection (find-active-connection-by-uuid
active-connections
(uuid connection))))
(dbus-call root "DeactivateConnection" (path active-connection)))
(dbus-call root "ActivateConnection"
(path (connection connection)) "/" "/"))))))
nil)
(defun find-active-connection-by-uuid (active-connections uuid)
(find-if (lambda (active-connection)
(string= (uuid active-connection) uuid))
active-connections))
(defun is-vpn-connection (c)
(string= (cs-type c) "vpn"))
(defun render-vpn-connection (connection active-connection)
(format nil "~A ~A"
(if active-connection
(active-connection-state-indicator (state active-connection))
" ")
(id connection)))
(defun render-ap (ap connection)
(format nil "~A ~A (~AMHz) ~A%"
(if (active ap)
(active-connection-state-indicator (state connection))
" ")
(ssid ap) (frequency ap) (strength ap)))
(defun active-connection-state-indicator (state)
(ecase state
(0 "?")
(1 "?")
(2 "*")
(3 " ")
(4 " ")))
| |
dc5a5791c36b1bfd842e4f529e2df6542f69dbbb7009a3ad78bba150ffccd391 | DianaPajon/tiger | TigerSeman.hs | # LANGUAGE TupleSections #
module TigerSeman where
import TigerAbs
import TigerErrores as E
import TigerSres
import TigerSymbol
import TigerTips
import TigerUnique
Segunda parte imports :
import TigerTemp
import TigerTrans
import TigerFrame (Frag)
-- Monads
import qualified Control.Conditional as C
import Control.Monad
import Control.Monad.State
import Control.Monad.Trans.Except
-- Data
import Data.List as List
import Data.Map as M
import Data.Ord as Ord
Le doy nombre .
import Prelude as P
-- Debugging. 'trace :: String -> a -> a'
imprime en pantalla la string ejecuta .
import Debug.Trace (trace)
* , aka Inferidor de Tipos
-- ** Notas :
[ 1 ] No deberían fallar variables . Recuerden que
el calculo de variables las variables
-- no definidas.
[ 2 ] En la siguiente a ir generando el código intermedio
mezclado con esta etapa por lo que es muy posible
este modulo . Mi consejo posible/ teniendo en cuenta
-- que van a tener que reescribir bastante.
class (Demon w, Monad w, MemM w) => Manticore w where
-- | Inserta una Variable al entorno
insertValV :: Symbol -> ValEntry -> w a -> w a
| Inserta una entorno
insertFunV :: Symbol -> FunEntry -> w a -> w a
| Inserta una Variable de sólo lectura
insertVRO :: Symbol -> w a -> w a
| Inserta una variable entorno
insertTipoT :: Symbol -> Tipo -> w a -> w a
| Busca una función en
getTipoFunV :: Symbol -> w FunEntry
| Busca una variable en el entorno . Ver [ 1 ]
getTipoValV :: Symbol -> w ValEntry
| Busca un tipo en el entorno
getTipoT :: Symbol -> w Tipo
-- | Funciones de Debugging!
showVEnv :: w a -> w a
showTEnv :: w a -> w a
--
| son .
El catch está en especie de referencia entre los
nombres de los tipos , ya que
en los linearizamos con el
-- sort topológico.
tiposIguales :: Tipo -> Tipo -> w Bool
tiposIguales (RefRecord s) l@(TRecord _ u) = do
st <- getTipoT s
case st of
TRecord _ u1 -> return (u1 == u)
ls@RefRecord{} -> tiposIguales ls l
_ -> E.internal $ pack "No son tipos iguales... 123+1"
tiposIguales l@(TRecord _ u) (RefRecord s) = do
st <- getTipoT s
case st of
TRecord _ u1 -> return (u1 == u)
ls@RefRecord{} -> tiposIguales l ls
_ -> E.internal $ pack "No son tipos iguales... 123+2"
tiposIguales (RefRecord s) (RefRecord s') = do
s1 <- getTipoT s
s2 <- getTipoT s'
tiposIguales s1 s2
tiposIguales TNil (RefRecord _) = return True
tiposIguales (RefRecord _) TNil = return True
tiposIguales (RefRecord _) _ = E.internal $ pack "No son tipos iguales... 123+3"
tiposIguales e (RefRecord s) = E.internal $ pack $ "No son tipos iguales... 123+4" ++ (show e ++ show s)
tiposIguales a b = return (equivTipo a b)
--
-- | Generador de uniques.
--
ugen :: w Unique
| Definimos algunos helpers
| ` addpos ` nos permite agregar información al error .
addpos :: (Demon w, Show b) => w a -> b -> w a
addpos t p = E.adder t (pack $ show p)
-- | Patrón de errores...
errorTiposMsg :: (Demon w, Show p)
=> p -> String -> Tipo -> Tipo -> w a
errorTiposMsg p msg t1 t2 = flip addpos p
$ flip adder (pack msg)
$ errorTipos t1 t2
depend :: Ty -> [Symbol]
depend (NameTy s) = [s]
depend (ArrayTy s) = [s]
depend (RecordTy ts) = concatMap (depend . snd) ts
| son
-- comparables.
Por ejemplo , ` if nil = nil then ... ` es una expresión ilegal
ya que no se puede determinar el tipo de cada uno de los nils .
: [ A.3.Expressions . Nil ]
tiposComparables :: Tipo -> Tipo -> Oper -> Bool
tiposComparables TNil TNil EqOp = False
tiposComparables TUnit _ EqOp = False
tiposComparables _ _ EqOp = True
tiposComparables TNil TNil NeqOp = False
tiposComparables TUnit _ NeqOp = False
tiposComparables _ _ NeqOp = True
tiposComparables _ _ _ = True
| indica que operadores son de comparación
comparacion :: Oper -> Bool
comparacion PlusOp = False
comparacion MinusOp = False
comparacion TimesOp = False
comparacion DivideOp = False
comparacion _ = True
| indica que operadores son
igualdad :: Oper -> Bool
igualdad NeqOp = True
igualdad EqOp = True
igualdad _ = False
diferentes :: (Eq a) => [a] -> Bool
diferentes [] = True
diferentes (a:xs) = not (elem a xs) && diferentes xs
| Función que chequea que campos
-- Ver 'transExp (RecordExp ...)'
Ver ' transExp ( CallExp ... ) '
cmpZip [] [] = return ()
cmpZip [] _ = derror $ pack "Diferencia en la cantidad. 1"
cmpZip _ [] = derror $ pack "Diferencia en la cantidad. 2"
cmpZip ((sl,tl):xs) ((sr,tr,p):ys) =
if (equivTipo tl tr && sl == sr)
then cmpZip xs ys
else errorTipos tl tr
buscarM :: Symbol -> [(Symbol, Tipo, Int)] -> Maybe (Symbol, Tipo, Int)
buscarM s [] = Nothing
buscarM s ((s',t,i):xs) | s == s' = Just (s',t,i)
| otherwise = buscarM s xs
| _ _ _ _ ' transVar ' .
El objetivo de esta función es obtener
-- de la variable a la que se está __accediendo__.
* * transVar : : ( MemM w , Manticore w ) = > Var - > w ( BExp , )
transVar :: (MemM w, Manticore w) => Var -> w ( BExp , Tipo)
Nota [ 1 ]
var <- simpleVar a l
return (var, t)
transVar (FieldVar v s) = do (var, tBase) <- transVar v
case tBase of
TRecord fs u ->
case buscarM s fs of
Just (s,t,i) -> do
campo <- fieldVar var i
return (campo, t)
Nothing -> derror $ pack "No se encontró el campo."
_ -> derror $ pack "No es un record"
transVar (SubscriptVar v e) = do (var, tBase) <- transVar v
case tBase of
TArray t u -> do
(indice, tipo) <- transExp e
case tipo of
TInt _ -> do
campo <- subscriptVar var indice
return (campo, t)
_ -> errorTipos tipo $ TInt RW
_ -> derror $ pack "No es un array"
| _ _ _ _ ' TransTy '
El objetivo de esta función es dado
que proviene de la gramatica , representación
de tipo interna del compilador
| Nota para cuando se generte
que ' TransTy ' no necesita ni ' MemM ' ni devuelve ' '
porque no se genera en .
transTy :: (Manticore w) => Ty -> w Tipo
transTy (ArrayTy s) =
do
unique <- ugen
tipo <- getTipoT s
return $ TArray tipo unique
transTy (RecordTy flds) =
do
let simbolos = P.map fst flds
tipos <- mapM (transTy) (P.map snd flds)
unique <- ugen
let componentes = triZip simbolos tipos (repeat 0)
return $ TRecord componentes unique
transTy (NameTy s) = --Es importante diferenciar las
getTipoT s
Esta funcion se encarga de detectar los bucles ilegales en la lista
hayCiclos :: [(Symbol, Tipo)] -> Bool
hayCiclos tips = P.foldr (\bl bb -> bl || bb) False listaCiclos
where
nameTys = P.filter (\(s,t) -> esNameTy t) tips
esNameTy t = case t of
TTipo _ -> True
_ -> False
listaCiclos = P.map (\(a,TTipo b) -> hayCiclo (hacerHead a nameTys) []) nameTys
hayCiclo :: [(Symbol,Tipo)] -> [Symbol] -> Bool
hayCiclo ((a, TTipo b):ts) ls = P.elem b ls || hayCiclo (hacerHead b ts) (a:ls)
hayCiclo [] ls = False
hacerHead :: Symbol -> [(Symbol, Tipo)] -> [(Symbol, Tipo)]
hacerHead b ((c,t):ts) = if b == c then (c,t):ts else (hacerHead b ts ++ [(c,t)])
hacerHead b [] = []
Esta función se
las definiciones de tipo a la gramatica interna del compilador .
Los tipos estan referidos ,
preTy :: (Manticore w) => (Symbol, Ty, Pos) -> w (Symbol, Tipo)
preTy (sim,(NameTy s),p) = addpos (return (sim, TTipo s)) p
preTy (sim,(RecordTy flds),p) =
flip addpos p (
do
unique <- ugen
return (sim, TRecord (P.map (\(sim,NameTy s) -> (sim, RefRecord s, posicion sim flds)) flds) unique)
) where
posicion s ((s', t):xs) = if s == s' then 0 else 1 + posicion s xs
preTy (sim,(ArrayTy s),p) =
flip addpos p (
do
unique <- ugen
return (sim, TArray (TTipo s) unique)
)
Dada una lista función anterior , detecta que tipos se refieren entre si
y .
cleanTy :: (Manticore w) => [Symbol] -> Tipo -> w Tipo
cleanTy sims (RefRecord s) =
if elem s sims
then return $ RefRecord s
else getTipoT s
cleanTy sims (TTipo s) =
if elem s sims
then return $ TTipo s
else getTipoT s
cleanTy sims (TArray t u) =
do ct <- cleanTy sims t
return (TArray ct u)
cleanTy sims (TRecord ts u) =
do let tiposRecord = P.map (\(a,b,c) -> b) ts
ctipos <- mapM (cleanTy sims) tiposRecord
let nuevosTiposRecord = zipWith (\(a,b,c) t -> (a,t,c)) ts ctipos
return $ TRecord nuevosTiposRecord u
cleanTy sims lala = return lala
| Dada una lista función anterior , detecta que tipos se refieren entre si
y .
cleanTys :: (Manticore w) => [Symbol] -> [(Symbol, Tipo)] -> w [(Symbol, Tipo)]
cleanTys ssims [] = return []
cleanTys sims ((s,t) : sts) =
do tip <- cleanTy sims t
tipos <- cleanTys sims sts
return ((s,tip):tipos)
elemTupla :: Eq a => a -> [(a, b)] -> b
elemTupla s ((ss,t):ts) = if s == ss then t else elemTupla s ts
| Esta función , dada la definicón anterior , genera los tipos REALES del compilador
como valores lazy en un mapa .
arreglarLazy :: Tipo -> [(Symbol, Tipo)] -> Tipo
arreglarLazy (RefRecord s) tipos = arreglarLazy (elemTupla s tipos) tipos
arreglarLazy (TTipo s) tipos = arreglarLazy (elemTupla s tipos) tipos
arreglarLazy (TRecord ts u) tipos = TRecord (P.map (\(s,t,i) -> (s, arreglarLazy t tipos,i)) ts) u
arreglarLazy (TArray t u) tipos = TArray (arreglarLazy t tipos) u
arreglarLazy lala tipos = lala
triZip :: [a] -> [b] -> [c] -> [(a,b,c)]
triZip as bs cs = P.map (\((a,b),c) -> (a,b,c)) (zip (zip as bs) cs)
fromTy :: (Manticore w) => Ty -> w Tipo
fromTy (NameTy s) = getTipoT s
fromTy _ = P.error "no debería haber una definición de tipos en los args..."
| Tip : Capaz que se debería restringir transDecs ' .
Tip2 : que . ( LetExp ... )
* * transDecs : : ( MemM w , Manticore w ) = > [ Dec ] - > w a - > w a
transDecs' :: (MemM w, Manticore w) => [Dec] -> w (BExp,Tipo) -> w ((BExp,Tipo),[BExp])
transDecs' ((VarDec nm escap t init p): xs) exp = flip addpos p (do
nil <- nilExp
acceso <- allocLocal (escap == Escapa)
nivel <- getActualLevel
variable <- varDec acceso
(inicializacion, tipoExp) <- transExp init
let tipoInit = if tipoExp == TInt RO then TInt RW else tipoExp
asignacion <- assignExp variable inicializacion
tipoDeclarado <- case t of
Just s -> getTipoT s
Nothing -> return tipoInit
iguales <- tiposIguales tipoExp tipoDeclarado
case (iguales, tipoDeclarado == TNil) of
(True, False) -> do
(cuerpo, inits) <- insertValV nm (tipoDeclarado, acceso, fromIntegral nivel) (transDecs' xs exp)
return (cuerpo, asignacion : inits)
(True, True) -> derror $ pack "Se debe declarar el tipo para poder asignar nil"
(False, _) -> derror $ pack "El tipo declarado no conicide con el de la expresión dada" )
transDecs' ((TypeDec xs): xss) exp = do
tys <- mapM preTy xs
let sims = P.map fst tys
clean <- cleanTys sims tys
let noRepiten = diferentes sims
if ((not $ hayCiclos clean) && noRepiten)
then do let decs = P.map (\(s,t) ->(s,arreglarLazy t clean)) clean
P.foldr (\(s,t) e -> insertTipoT s t e) (transDecs' xss exp) decs
else do let (_,_,p) = head xs
addpos (derror $ pack "Bloque de tipos mal declarados") p
transDecs' ((FunctionDec fs) : xs) exp = do
let noRepiten = diferentes $ P.map (\(s,_,_,_,_) -> s) fs
if(noRepiten)
then do
funEntries <- mapM mkFunEntry fs
Ignoro .
P.foldr (\(s,fentry) e -> insertFunV s fentry e) (transDecs' xs exp) (actualizar funEntries funs)
else let (_,_, _, _, p) = head fs
in addpos (derror $ pack "Hay varias funciones con el mismo nombre declaradas en un solo bloque.") p
where actualizar [] xs = []
actualizar ((s,(l,a,b,c,d)):es) ((ci,t,l'):ts) = (s,(l',a,b,c,d)) : actualizar es ts
transDecs' [] exp = do
cuerpo <- exp
return (cuerpo, [])
transDecs :: (MemM w, Manticore w) => [Dec] -> w (BExp,Tipo) -> w (BExp,Tipo)
transDecs decs cuerpo = do
((cuerpo,tipo), asignaciones) <- transDecs' decs cuerpo
cuerpoLet <- letExp asignaciones cuerpo
return (cuerpoLet, tipo)
type FunDec = (Symbol ,[(Symbol, Escapa, Ty)], Maybe Symbol, Exp, Pos)
transFun :: (MemM w, Manticore w) => [(Symbol, FunEntry)] -> FunDec -> w (BExp, Tipo, Level)
transFun fs (nombre, args, mt, body, p) =
flip addpos p (
do
let nivelFun = nivelFuncion fs nombre
pushLevel nivelFun
nLevel <- getActualLevel
args <- mapM (\arg -> mkArgEntry arg nLevel) args
let expresionConArgs = P.foldr (\(s,argentry) e -> insertValV s argentry e) (transExp body) args
(cuerpo , tipo) <- P.foldr (\(s,fentry) e -> insertFunV s fentry e) expresionConArgs fs
let isproc = if mt == Nothing then IsProc else IsFun
levelConArgs <- topLevel
intermedio <- envFunctionDec nivelFun (functionDec cuerpo levelConArgs isproc)
popLevel
case mt of
Nothing -> do esProc <- tiposIguales TUnit tipo
if esProc then return (intermedio,TUnit,levelConArgs) else derror $ pack "Un procedimiento retorna un valor"
Just t -> do tipoEsperado <- getTipoT t
iguales <- tiposIguales tipoEsperado tipo
if iguales
then return (intermedio, tipo, levelConArgs)
else derror $ pack "La función no tipa"
)
where
nivelFuncion ((nombre, (level,_,_,_,_)):funs) s = if s == nombre then level else nivelFuncion funs s
mkArgEntry :: (MemM w, Manticore w) => (Symbol,Escapa,Ty) -> Int -> w (Symbol, ValEntry)
mkArgEntry (s,e,t) level = do
acceso <- allocArg (e == Escapa)
tipo <- fromTy t
return (s,(tipo, acceso, level))
mkFunEntry :: (MemM w, Manticore w) => FunDec -> w (Symbol, FunEntry)
mkFunEntry (nombre,args,mtipo,cuerpo,pos) = do
nivelPadre <- topLevel
let formals = (P.map (\(a,b,c) -> b == Escapa) args)
tipos <- mapM transTy (P.map (\(a,b,c) -> c) args)
label <- newLabel
let funLabel = pack (unpack label ++ "_" ++ unpack nombre)
tipo <- case mtipo of
Nothing -> return TUnit
Just s -> getTipoT s
let nivelFuncion = newLevel nivelPadre funLabel formals
return (nombre,(nivelFuncion, funLabel, tipos, tipo, Propia))
getTipoEntry :: (Unique, Label, [Tipo], Tipo, Externa) -> Tipo
getTipoEntry (u,l,ts,t,e) = t
normalizarRecord :: (Manticore w ) => Exp -> w Exp
normalizarRecord (RecordExp flds rt p) = do
(TRecord fldsTy _) <- getTipoT rt --TODO: Bad fail alert.
let ordFldsTy = sortBy (\(a,b,c) (a',b',c') -> compare c c') fldsTy
let ordFldsRec = sortBy (\(a,b) (a',b') -> compare (posicion a fldsTy) (posicion a' fldsTy)) flds
return $ RecordExp ordFldsRec rt p
where posicion elem ((a,b,c):es) = if a == elem then 0 else 1 + posicion elem es
* * transExp : : ( MemM w , Manticore w ) = > Exp - > w ( BExp , )
transExp :: (MemM w, Manticore w) => Exp -> w (BExp , Tipo)
transExp (VarExp v p) = addpos (transVar v) p
transExp UnitExp{} = fmap (,TUnit) unitExp
transExp NilExp{} = fmap (,TNil) nilExp
transExp (IntExp i _) = fmap (,TInt RW) (intExp i)
transExp (StringExp s _) = fmap (,TString) (stringExp (pack s))
transExp (CallExp nm args p) = flip addpos p (do
transArgs <- mapM transExp args
let tiposArgs = P.map snd transArgs
let argumentos = P.map fst transArgs
(level, label, parametros, tipo, externa) <- getTipoFunV nm
iguales <- mapM (\(t1,t2) -> tiposIguales t1 t2) $ zip tiposArgs parametros
let tipa = P.foldr (\a b -> a && b) True iguales
let isProc = if tipo == TUnit then IsProc else IsFun
if tipa && P.length parametros == P.length argumentos
then do llamada <- callExp label externa isProc level argumentos
return (llamada, tipo)
else derror $ pack "La llamada a funcion no tipa."
)
Esta va /gratis/
(leftExp, el) <- transExp el'
(rightExp, er) <- transExp er'
intermedio <- case (el, er) of
(TInt _, TInt _) ->
if comparacion oper
then binOpIntRelExp leftExp oper rightExp
else binOpIntExp leftExp oper rightExp
(TString , TString) ->
if comparacion oper
then binOpStrExp leftExp oper rightExp
else derror $ pack "Operacion inválida"
(TArray _ u1, TArray _ u2) ->
case (u1 == u2, igualdad oper) of
(True, True) -> binOpIntRelExp leftExp oper rightExp --Es comparacion de instancias
_ -> derror $ pack "Operacion inválida"
(TRecord _ u1, tu2) ->
case tu2 of
TNil -> if igualdad oper then binOpIntRelExp leftExp oper rightExp else derror $ pack "Operacion inválida"
TRecord _ u2 -> if u1 == u2 && igualdad oper then binOpIntRelExp leftExp oper rightExp else derror $ pack "Operacion inválida"
_ -> derror $ pack "Operacion inválida"
(TNil, tu2) ->
case tu2 of
TRecord _ u2 -> if igualdad oper then binOpIntRelExp leftExp oper rightExp else derror $ pack "Operacion inválida"
_ -> derror $ pack "Operacion inválida"
_ -> derror $ pack "Operacion inválida"
return (intermedio, TInt RW)
)
-- | Recordemos que 'RecordExp :: [(Symbol, Exp)] -> Symbol -> Pos -> Exp'
Donde el primer argumento son , y el segundo es
el texto plano de un tipo ( que ya debería estar ) . Una expresión
-- de este tipo está creando un nuevo record.
transExp(RecordExp flds rt p) =
addpos (getTipoT rt) p >>= (
Buscamos en la tabla rt ' , .
' : : TRecord [ ( Symbol , , Int ) ] Unique '
do
-- Especial atención acá.
Tenemos una lista de expresiones con efectos
y en orden ! ' mapM ' viene a mano .
(RecordExp fldsCanon _ _ ) <- normalizarRecord (RecordExp flds rt p)
fldsTys <- mapM (\(nm, cod) -> (nm,) <$> transExp cod) fldsCanon
flip addpos p $ cmpZip ( (\(s,(c,t)) -> (s,t)) <$> fldsTys) fldsTy -- Demon corta la ejecución.
--let camposRecord = P.map (\(s, (exp, t)) -> (exp, pos s fldsTy)) fldsTys
let camposRecord = P.map (\(s, (exp, t)) -> (exp, pos s fldsTy)) fldsTys
--record <- return recordExp
record <- recordExp camposRecord
.
_ -> flip addpos p $ derror (pack "Error de tipos en la definición del record.")
)
where pos s ((s',t,p):ts) = if s == s' then p else pos s ts
transExp(SeqExp es p) = do
es' <- mapM transExp es
seq <- seqExp $ P.map fst es'
return ( seq , snd $ last es')
transExp(AssignExp var val p) = flip addpos p (do
(variable, tipoVar) <- transVar var
(valor, tipoExp) <- transExp val
let asignable = tipoVar /= TInt RO
iguales <- tiposIguales tipoVar tipoExp
case (asignable,iguales) of
(False,_) -> derror $ pack ("La variable " ++ show var ++ " es de solo lectura")
(True, False) -> derror $ pack ("Los tipos no coinciden en la asignaciòn" )
(True, True) -> do
asignacion <- assignExp variable valor
return (asignacion, TUnit)
)
transExp(IfExp co th Nothing p) = do
* * ( ccond , co ' ) < - transExp co
-- Analizamos el tipo de la condición
(condicion , co') <- transExp co
chequeamos que sea un entero .
acá error .
-- ** (cth , th') <- transExp th
Analizamos el tipo del branch .
(cuerpo , th') <- transExp th
chequeamos que sea de tipo Unit .
unless (equivTipo th' TUnit) $ errorTiposMsg p "En el branch del if->" th' TUnit
, devolvemos que if ' es de tipo Unit .
ifthen <- ifThenExp condicion cuerpo
return (ifthen , TUnit)
transExp(IfExp co th (Just el) p) = do
(condicion , condType) <- transExp co
unless (equivTipo condType TBool) $ errorTiposMsg p "En la condición del if ->" condType TBool
(cuerpoThen, ttType) <- transExp th
(cuerpoElse, ffType) <- transExp el
C.unlessM (tiposIguales ttType ffType) $ errorTiposMsg p "En los branches." ttType ffType
branches .
ifthenelse <- ifThenElseExp condicion cuerpoThen cuerpoElse
return (ifthenelse, ttType)
transExp(WhileExp co body p) = do
(condicion , coTy) <- transExp co
unless (equivTipo coTy TBool) $ errorTiposMsg p "Error en la condición del While" coTy TBool
preWhileforExp
(cuerpo , boTy) <- transExp body
unless (equivTipo boTy TUnit) $ errorTiposMsg p "Error en el cuerpo del While" boTy TUnit
while <- whileExp condicion cuerpo
posWhileforExp
return (while, TUnit)
transExp(ForExp nv mb lo hi bo p) =
do
--Genero la varEntry que necesito.
acceso <- allocLocal (mb == Escapa)
level <-getActualLevel
insertValV nv (TInt RO, acceso, level) ( do
(variable, tVariable) <- transExp (VarExp ( SimpleVar nv) (Simple 0 0))
(minimo, tMinimo) <- transExp lo
unless (equivTipo tMinimo (TInt RW)) $ errorTiposMsg p "El minimo del for no es un entero" tMinimo (TInt RW)
(maximo, tMaximo) <- transExp hi
unless (equivTipo tMaximo (TInt RW)) $ errorTiposMsg p "El maximo del for no es un entero" tMaximo (TInt RW)
preWhileforExp
(cuerpo, tCuerpo) <- transExp bo
unless (equivTipo tCuerpo TUnit) $ errorTiposMsg p "Error en el cuerpo del For" tCuerpo TUnit
for <- forExp minimo maximo variable cuerpo
posWhileforExp
return (for, TUnit)
)
transExp(LetExp dcs body p) = transDecs dcs (transExp body)
transExp(BreakExp p) =
do break <- breakExp
return (break, TUnit)
transExp(ArrayExp sn cant init p) = do
tipoUsado <- getTipoT sn
case tipoUsado of
TArray t u -> do
(cantidad, tipoCant) <- transExp cant
(init, tipoInit) <- transExp init
cantEntera <- tiposIguales tipoCant (TInt RO)
tipoValido <- tiposIguales tipoInit t
if (cantEntera && tipoValido)
then do
array <- arrayExp cantidad init
return (array,TArray t u)
else derror $ pack ("Arreglo mal declarado, linea " ++ show p)
_ -> derror $ pack "Se declara un array de un tipo no array"
transProg :: (MemM w, Manticore w) => Exp -> w [Frag]
transProg programa = do
(programBody,tipoPrograma) <- transExp programa
level <- topLevel
proc <- functionDec programBody level IsProc
frags <- getFrags
return frags
runSeman = undefined | null | https://raw.githubusercontent.com/DianaPajon/tiger/30d360f02f5fc57883f988a1cbb581208ecd2744/src/TigerSeman.hs | haskell | Monads
Data
Debugging. 'trace :: String -> a -> a'
** Notas :
no definidas.
que van a tener que reescribir bastante.
| Inserta una Variable al entorno
| Funciones de Debugging!
sort topológico.
| Generador de uniques.
| Patrón de errores...
comparables.
Ver 'transExp (RecordExp ...)'
de la variable a la que se está __accediendo__.
Es importante diferenciar las
TODO: Bad fail alert.
Es comparacion de instancias
| Recordemos que 'RecordExp :: [(Symbol, Exp)] -> Symbol -> Pos -> Exp'
de este tipo está creando un nuevo record.
Especial atención acá.
Demon corta la ejecución.
let camposRecord = P.map (\(s, (exp, t)) -> (exp, pos s fldsTy)) fldsTys
record <- return recordExp
Analizamos el tipo de la condición
** (cth , th') <- transExp th
Genero la varEntry que necesito. | # LANGUAGE TupleSections #
module TigerSeman where
import TigerAbs
import TigerErrores as E
import TigerSres
import TigerSymbol
import TigerTips
import TigerUnique
Segunda parte imports :
import TigerTemp
import TigerTrans
import TigerFrame (Frag)
import qualified Control.Conditional as C
import Control.Monad
import Control.Monad.State
import Control.Monad.Trans.Except
import Data.List as List
import Data.Map as M
import Data.Ord as Ord
Le doy nombre .
import Prelude as P
imprime en pantalla la string ejecuta .
import Debug.Trace (trace)
* , aka Inferidor de Tipos
[ 1 ] No deberían fallar variables . Recuerden que
el calculo de variables las variables
[ 2 ] En la siguiente a ir generando el código intermedio
mezclado con esta etapa por lo que es muy posible
este modulo . Mi consejo posible/ teniendo en cuenta
class (Demon w, Monad w, MemM w) => Manticore w where
insertValV :: Symbol -> ValEntry -> w a -> w a
| Inserta una entorno
insertFunV :: Symbol -> FunEntry -> w a -> w a
| Inserta una Variable de sólo lectura
insertVRO :: Symbol -> w a -> w a
| Inserta una variable entorno
insertTipoT :: Symbol -> Tipo -> w a -> w a
| Busca una función en
getTipoFunV :: Symbol -> w FunEntry
| Busca una variable en el entorno . Ver [ 1 ]
getTipoValV :: Symbol -> w ValEntry
| Busca un tipo en el entorno
getTipoT :: Symbol -> w Tipo
showVEnv :: w a -> w a
showTEnv :: w a -> w a
| son .
El catch está en especie de referencia entre los
nombres de los tipos , ya que
en los linearizamos con el
tiposIguales :: Tipo -> Tipo -> w Bool
tiposIguales (RefRecord s) l@(TRecord _ u) = do
st <- getTipoT s
case st of
TRecord _ u1 -> return (u1 == u)
ls@RefRecord{} -> tiposIguales ls l
_ -> E.internal $ pack "No son tipos iguales... 123+1"
tiposIguales l@(TRecord _ u) (RefRecord s) = do
st <- getTipoT s
case st of
TRecord _ u1 -> return (u1 == u)
ls@RefRecord{} -> tiposIguales l ls
_ -> E.internal $ pack "No son tipos iguales... 123+2"
tiposIguales (RefRecord s) (RefRecord s') = do
s1 <- getTipoT s
s2 <- getTipoT s'
tiposIguales s1 s2
tiposIguales TNil (RefRecord _) = return True
tiposIguales (RefRecord _) TNil = return True
tiposIguales (RefRecord _) _ = E.internal $ pack "No son tipos iguales... 123+3"
tiposIguales e (RefRecord s) = E.internal $ pack $ "No son tipos iguales... 123+4" ++ (show e ++ show s)
tiposIguales a b = return (equivTipo a b)
ugen :: w Unique
| Definimos algunos helpers
| ` addpos ` nos permite agregar información al error .
addpos :: (Demon w, Show b) => w a -> b -> w a
addpos t p = E.adder t (pack $ show p)
errorTiposMsg :: (Demon w, Show p)
=> p -> String -> Tipo -> Tipo -> w a
errorTiposMsg p msg t1 t2 = flip addpos p
$ flip adder (pack msg)
$ errorTipos t1 t2
depend :: Ty -> [Symbol]
depend (NameTy s) = [s]
depend (ArrayTy s) = [s]
depend (RecordTy ts) = concatMap (depend . snd) ts
| son
Por ejemplo , ` if nil = nil then ... ` es una expresión ilegal
ya que no se puede determinar el tipo de cada uno de los nils .
: [ A.3.Expressions . Nil ]
tiposComparables :: Tipo -> Tipo -> Oper -> Bool
tiposComparables TNil TNil EqOp = False
tiposComparables TUnit _ EqOp = False
tiposComparables _ _ EqOp = True
tiposComparables TNil TNil NeqOp = False
tiposComparables TUnit _ NeqOp = False
tiposComparables _ _ NeqOp = True
tiposComparables _ _ _ = True
| indica que operadores son de comparación
comparacion :: Oper -> Bool
comparacion PlusOp = False
comparacion MinusOp = False
comparacion TimesOp = False
comparacion DivideOp = False
comparacion _ = True
| indica que operadores son
igualdad :: Oper -> Bool
igualdad NeqOp = True
igualdad EqOp = True
igualdad _ = False
diferentes :: (Eq a) => [a] -> Bool
diferentes [] = True
diferentes (a:xs) = not (elem a xs) && diferentes xs
| Función que chequea que campos
Ver ' transExp ( CallExp ... ) '
cmpZip [] [] = return ()
cmpZip [] _ = derror $ pack "Diferencia en la cantidad. 1"
cmpZip _ [] = derror $ pack "Diferencia en la cantidad. 2"
cmpZip ((sl,tl):xs) ((sr,tr,p):ys) =
if (equivTipo tl tr && sl == sr)
then cmpZip xs ys
else errorTipos tl tr
buscarM :: Symbol -> [(Symbol, Tipo, Int)] -> Maybe (Symbol, Tipo, Int)
buscarM s [] = Nothing
buscarM s ((s',t,i):xs) | s == s' = Just (s',t,i)
| otherwise = buscarM s xs
| _ _ _ _ ' transVar ' .
El objetivo de esta función es obtener
* * transVar : : ( MemM w , Manticore w ) = > Var - > w ( BExp , )
transVar :: (MemM w, Manticore w) => Var -> w ( BExp , Tipo)
Nota [ 1 ]
var <- simpleVar a l
return (var, t)
transVar (FieldVar v s) = do (var, tBase) <- transVar v
case tBase of
TRecord fs u ->
case buscarM s fs of
Just (s,t,i) -> do
campo <- fieldVar var i
return (campo, t)
Nothing -> derror $ pack "No se encontró el campo."
_ -> derror $ pack "No es un record"
transVar (SubscriptVar v e) = do (var, tBase) <- transVar v
case tBase of
TArray t u -> do
(indice, tipo) <- transExp e
case tipo of
TInt _ -> do
campo <- subscriptVar var indice
return (campo, t)
_ -> errorTipos tipo $ TInt RW
_ -> derror $ pack "No es un array"
| _ _ _ _ ' TransTy '
El objetivo de esta función es dado
que proviene de la gramatica , representación
de tipo interna del compilador
| Nota para cuando se generte
que ' TransTy ' no necesita ni ' MemM ' ni devuelve ' '
porque no se genera en .
transTy :: (Manticore w) => Ty -> w Tipo
transTy (ArrayTy s) =
do
unique <- ugen
tipo <- getTipoT s
return $ TArray tipo unique
transTy (RecordTy flds) =
do
let simbolos = P.map fst flds
tipos <- mapM (transTy) (P.map snd flds)
unique <- ugen
let componentes = triZip simbolos tipos (repeat 0)
return $ TRecord componentes unique
getTipoT s
Esta funcion se encarga de detectar los bucles ilegales en la lista
hayCiclos :: [(Symbol, Tipo)] -> Bool
hayCiclos tips = P.foldr (\bl bb -> bl || bb) False listaCiclos
where
nameTys = P.filter (\(s,t) -> esNameTy t) tips
esNameTy t = case t of
TTipo _ -> True
_ -> False
listaCiclos = P.map (\(a,TTipo b) -> hayCiclo (hacerHead a nameTys) []) nameTys
hayCiclo :: [(Symbol,Tipo)] -> [Symbol] -> Bool
hayCiclo ((a, TTipo b):ts) ls = P.elem b ls || hayCiclo (hacerHead b ts) (a:ls)
hayCiclo [] ls = False
hacerHead :: Symbol -> [(Symbol, Tipo)] -> [(Symbol, Tipo)]
hacerHead b ((c,t):ts) = if b == c then (c,t):ts else (hacerHead b ts ++ [(c,t)])
hacerHead b [] = []
Esta función se
las definiciones de tipo a la gramatica interna del compilador .
Los tipos estan referidos ,
preTy :: (Manticore w) => (Symbol, Ty, Pos) -> w (Symbol, Tipo)
preTy (sim,(NameTy s),p) = addpos (return (sim, TTipo s)) p
preTy (sim,(RecordTy flds),p) =
flip addpos p (
do
unique <- ugen
return (sim, TRecord (P.map (\(sim,NameTy s) -> (sim, RefRecord s, posicion sim flds)) flds) unique)
) where
posicion s ((s', t):xs) = if s == s' then 0 else 1 + posicion s xs
preTy (sim,(ArrayTy s),p) =
flip addpos p (
do
unique <- ugen
return (sim, TArray (TTipo s) unique)
)
Dada una lista función anterior , detecta que tipos se refieren entre si
y .
cleanTy :: (Manticore w) => [Symbol] -> Tipo -> w Tipo
cleanTy sims (RefRecord s) =
if elem s sims
then return $ RefRecord s
else getTipoT s
cleanTy sims (TTipo s) =
if elem s sims
then return $ TTipo s
else getTipoT s
cleanTy sims (TArray t u) =
do ct <- cleanTy sims t
return (TArray ct u)
cleanTy sims (TRecord ts u) =
do let tiposRecord = P.map (\(a,b,c) -> b) ts
ctipos <- mapM (cleanTy sims) tiposRecord
let nuevosTiposRecord = zipWith (\(a,b,c) t -> (a,t,c)) ts ctipos
return $ TRecord nuevosTiposRecord u
cleanTy sims lala = return lala
| Dada una lista función anterior , detecta que tipos se refieren entre si
y .
cleanTys :: (Manticore w) => [Symbol] -> [(Symbol, Tipo)] -> w [(Symbol, Tipo)]
cleanTys ssims [] = return []
cleanTys sims ((s,t) : sts) =
do tip <- cleanTy sims t
tipos <- cleanTys sims sts
return ((s,tip):tipos)
elemTupla :: Eq a => a -> [(a, b)] -> b
elemTupla s ((ss,t):ts) = if s == ss then t else elemTupla s ts
| Esta función , dada la definicón anterior , genera los tipos REALES del compilador
como valores lazy en un mapa .
arreglarLazy :: Tipo -> [(Symbol, Tipo)] -> Tipo
arreglarLazy (RefRecord s) tipos = arreglarLazy (elemTupla s tipos) tipos
arreglarLazy (TTipo s) tipos = arreglarLazy (elemTupla s tipos) tipos
arreglarLazy (TRecord ts u) tipos = TRecord (P.map (\(s,t,i) -> (s, arreglarLazy t tipos,i)) ts) u
arreglarLazy (TArray t u) tipos = TArray (arreglarLazy t tipos) u
arreglarLazy lala tipos = lala
triZip :: [a] -> [b] -> [c] -> [(a,b,c)]
triZip as bs cs = P.map (\((a,b),c) -> (a,b,c)) (zip (zip as bs) cs)
fromTy :: (Manticore w) => Ty -> w Tipo
fromTy (NameTy s) = getTipoT s
fromTy _ = P.error "no debería haber una definición de tipos en los args..."
| Tip : Capaz que se debería restringir transDecs ' .
Tip2 : que . ( LetExp ... )
* * transDecs : : ( MemM w , Manticore w ) = > [ Dec ] - > w a - > w a
transDecs' :: (MemM w, Manticore w) => [Dec] -> w (BExp,Tipo) -> w ((BExp,Tipo),[BExp])
transDecs' ((VarDec nm escap t init p): xs) exp = flip addpos p (do
nil <- nilExp
acceso <- allocLocal (escap == Escapa)
nivel <- getActualLevel
variable <- varDec acceso
(inicializacion, tipoExp) <- transExp init
let tipoInit = if tipoExp == TInt RO then TInt RW else tipoExp
asignacion <- assignExp variable inicializacion
tipoDeclarado <- case t of
Just s -> getTipoT s
Nothing -> return tipoInit
iguales <- tiposIguales tipoExp tipoDeclarado
case (iguales, tipoDeclarado == TNil) of
(True, False) -> do
(cuerpo, inits) <- insertValV nm (tipoDeclarado, acceso, fromIntegral nivel) (transDecs' xs exp)
return (cuerpo, asignacion : inits)
(True, True) -> derror $ pack "Se debe declarar el tipo para poder asignar nil"
(False, _) -> derror $ pack "El tipo declarado no conicide con el de la expresión dada" )
transDecs' ((TypeDec xs): xss) exp = do
tys <- mapM preTy xs
let sims = P.map fst tys
clean <- cleanTys sims tys
let noRepiten = diferentes sims
if ((not $ hayCiclos clean) && noRepiten)
then do let decs = P.map (\(s,t) ->(s,arreglarLazy t clean)) clean
P.foldr (\(s,t) e -> insertTipoT s t e) (transDecs' xss exp) decs
else do let (_,_,p) = head xs
addpos (derror $ pack "Bloque de tipos mal declarados") p
transDecs' ((FunctionDec fs) : xs) exp = do
let noRepiten = diferentes $ P.map (\(s,_,_,_,_) -> s) fs
if(noRepiten)
then do
funEntries <- mapM mkFunEntry fs
Ignoro .
P.foldr (\(s,fentry) e -> insertFunV s fentry e) (transDecs' xs exp) (actualizar funEntries funs)
else let (_,_, _, _, p) = head fs
in addpos (derror $ pack "Hay varias funciones con el mismo nombre declaradas en un solo bloque.") p
where actualizar [] xs = []
actualizar ((s,(l,a,b,c,d)):es) ((ci,t,l'):ts) = (s,(l',a,b,c,d)) : actualizar es ts
transDecs' [] exp = do
cuerpo <- exp
return (cuerpo, [])
transDecs :: (MemM w, Manticore w) => [Dec] -> w (BExp,Tipo) -> w (BExp,Tipo)
transDecs decs cuerpo = do
((cuerpo,tipo), asignaciones) <- transDecs' decs cuerpo
cuerpoLet <- letExp asignaciones cuerpo
return (cuerpoLet, tipo)
type FunDec = (Symbol ,[(Symbol, Escapa, Ty)], Maybe Symbol, Exp, Pos)
transFun :: (MemM w, Manticore w) => [(Symbol, FunEntry)] -> FunDec -> w (BExp, Tipo, Level)
transFun fs (nombre, args, mt, body, p) =
flip addpos p (
do
let nivelFun = nivelFuncion fs nombre
pushLevel nivelFun
nLevel <- getActualLevel
args <- mapM (\arg -> mkArgEntry arg nLevel) args
let expresionConArgs = P.foldr (\(s,argentry) e -> insertValV s argentry e) (transExp body) args
(cuerpo , tipo) <- P.foldr (\(s,fentry) e -> insertFunV s fentry e) expresionConArgs fs
let isproc = if mt == Nothing then IsProc else IsFun
levelConArgs <- topLevel
intermedio <- envFunctionDec nivelFun (functionDec cuerpo levelConArgs isproc)
popLevel
case mt of
Nothing -> do esProc <- tiposIguales TUnit tipo
if esProc then return (intermedio,TUnit,levelConArgs) else derror $ pack "Un procedimiento retorna un valor"
Just t -> do tipoEsperado <- getTipoT t
iguales <- tiposIguales tipoEsperado tipo
if iguales
then return (intermedio, tipo, levelConArgs)
else derror $ pack "La función no tipa"
)
where
nivelFuncion ((nombre, (level,_,_,_,_)):funs) s = if s == nombre then level else nivelFuncion funs s
mkArgEntry :: (MemM w, Manticore w) => (Symbol,Escapa,Ty) -> Int -> w (Symbol, ValEntry)
mkArgEntry (s,e,t) level = do
acceso <- allocArg (e == Escapa)
tipo <- fromTy t
return (s,(tipo, acceso, level))
mkFunEntry :: (MemM w, Manticore w) => FunDec -> w (Symbol, FunEntry)
mkFunEntry (nombre,args,mtipo,cuerpo,pos) = do
nivelPadre <- topLevel
let formals = (P.map (\(a,b,c) -> b == Escapa) args)
tipos <- mapM transTy (P.map (\(a,b,c) -> c) args)
label <- newLabel
let funLabel = pack (unpack label ++ "_" ++ unpack nombre)
tipo <- case mtipo of
Nothing -> return TUnit
Just s -> getTipoT s
let nivelFuncion = newLevel nivelPadre funLabel formals
return (nombre,(nivelFuncion, funLabel, tipos, tipo, Propia))
getTipoEntry :: (Unique, Label, [Tipo], Tipo, Externa) -> Tipo
getTipoEntry (u,l,ts,t,e) = t
normalizarRecord :: (Manticore w ) => Exp -> w Exp
normalizarRecord (RecordExp flds rt p) = do
let ordFldsTy = sortBy (\(a,b,c) (a',b',c') -> compare c c') fldsTy
let ordFldsRec = sortBy (\(a,b) (a',b') -> compare (posicion a fldsTy) (posicion a' fldsTy)) flds
return $ RecordExp ordFldsRec rt p
where posicion elem ((a,b,c):es) = if a == elem then 0 else 1 + posicion elem es
* * transExp : : ( MemM w , Manticore w ) = > Exp - > w ( BExp , )
transExp :: (MemM w, Manticore w) => Exp -> w (BExp , Tipo)
transExp (VarExp v p) = addpos (transVar v) p
transExp UnitExp{} = fmap (,TUnit) unitExp
transExp NilExp{} = fmap (,TNil) nilExp
transExp (IntExp i _) = fmap (,TInt RW) (intExp i)
transExp (StringExp s _) = fmap (,TString) (stringExp (pack s))
transExp (CallExp nm args p) = flip addpos p (do
transArgs <- mapM transExp args
let tiposArgs = P.map snd transArgs
let argumentos = P.map fst transArgs
(level, label, parametros, tipo, externa) <- getTipoFunV nm
iguales <- mapM (\(t1,t2) -> tiposIguales t1 t2) $ zip tiposArgs parametros
let tipa = P.foldr (\a b -> a && b) True iguales
let isProc = if tipo == TUnit then IsProc else IsFun
if tipa && P.length parametros == P.length argumentos
then do llamada <- callExp label externa isProc level argumentos
return (llamada, tipo)
else derror $ pack "La llamada a funcion no tipa."
)
Esta va /gratis/
(leftExp, el) <- transExp el'
(rightExp, er) <- transExp er'
intermedio <- case (el, er) of
(TInt _, TInt _) ->
if comparacion oper
then binOpIntRelExp leftExp oper rightExp
else binOpIntExp leftExp oper rightExp
(TString , TString) ->
if comparacion oper
then binOpStrExp leftExp oper rightExp
else derror $ pack "Operacion inválida"
(TArray _ u1, TArray _ u2) ->
case (u1 == u2, igualdad oper) of
_ -> derror $ pack "Operacion inválida"
(TRecord _ u1, tu2) ->
case tu2 of
TNil -> if igualdad oper then binOpIntRelExp leftExp oper rightExp else derror $ pack "Operacion inválida"
TRecord _ u2 -> if u1 == u2 && igualdad oper then binOpIntRelExp leftExp oper rightExp else derror $ pack "Operacion inválida"
_ -> derror $ pack "Operacion inválida"
(TNil, tu2) ->
case tu2 of
TRecord _ u2 -> if igualdad oper then binOpIntRelExp leftExp oper rightExp else derror $ pack "Operacion inválida"
_ -> derror $ pack "Operacion inválida"
_ -> derror $ pack "Operacion inválida"
return (intermedio, TInt RW)
)
Donde el primer argumento son , y el segundo es
el texto plano de un tipo ( que ya debería estar ) . Una expresión
transExp(RecordExp flds rt p) =
addpos (getTipoT rt) p >>= (
Buscamos en la tabla rt ' , .
' : : TRecord [ ( Symbol , , Int ) ] Unique '
do
Tenemos una lista de expresiones con efectos
y en orden ! ' mapM ' viene a mano .
(RecordExp fldsCanon _ _ ) <- normalizarRecord (RecordExp flds rt p)
fldsTys <- mapM (\(nm, cod) -> (nm,) <$> transExp cod) fldsCanon
let camposRecord = P.map (\(s, (exp, t)) -> (exp, pos s fldsTy)) fldsTys
record <- recordExp camposRecord
.
_ -> flip addpos p $ derror (pack "Error de tipos en la definición del record.")
)
where pos s ((s',t,p):ts) = if s == s' then p else pos s ts
transExp(SeqExp es p) = do
es' <- mapM transExp es
seq <- seqExp $ P.map fst es'
return ( seq , snd $ last es')
transExp(AssignExp var val p) = flip addpos p (do
(variable, tipoVar) <- transVar var
(valor, tipoExp) <- transExp val
let asignable = tipoVar /= TInt RO
iguales <- tiposIguales tipoVar tipoExp
case (asignable,iguales) of
(False,_) -> derror $ pack ("La variable " ++ show var ++ " es de solo lectura")
(True, False) -> derror $ pack ("Los tipos no coinciden en la asignaciòn" )
(True, True) -> do
asignacion <- assignExp variable valor
return (asignacion, TUnit)
)
transExp(IfExp co th Nothing p) = do
* * ( ccond , co ' ) < - transExp co
(condicion , co') <- transExp co
chequeamos que sea un entero .
acá error .
Analizamos el tipo del branch .
(cuerpo , th') <- transExp th
chequeamos que sea de tipo Unit .
unless (equivTipo th' TUnit) $ errorTiposMsg p "En el branch del if->" th' TUnit
, devolvemos que if ' es de tipo Unit .
ifthen <- ifThenExp condicion cuerpo
return (ifthen , TUnit)
transExp(IfExp co th (Just el) p) = do
(condicion , condType) <- transExp co
unless (equivTipo condType TBool) $ errorTiposMsg p "En la condición del if ->" condType TBool
(cuerpoThen, ttType) <- transExp th
(cuerpoElse, ffType) <- transExp el
C.unlessM (tiposIguales ttType ffType) $ errorTiposMsg p "En los branches." ttType ffType
branches .
ifthenelse <- ifThenElseExp condicion cuerpoThen cuerpoElse
return (ifthenelse, ttType)
transExp(WhileExp co body p) = do
(condicion , coTy) <- transExp co
unless (equivTipo coTy TBool) $ errorTiposMsg p "Error en la condición del While" coTy TBool
preWhileforExp
(cuerpo , boTy) <- transExp body
unless (equivTipo boTy TUnit) $ errorTiposMsg p "Error en el cuerpo del While" boTy TUnit
while <- whileExp condicion cuerpo
posWhileforExp
return (while, TUnit)
transExp(ForExp nv mb lo hi bo p) =
do
acceso <- allocLocal (mb == Escapa)
level <-getActualLevel
insertValV nv (TInt RO, acceso, level) ( do
(variable, tVariable) <- transExp (VarExp ( SimpleVar nv) (Simple 0 0))
(minimo, tMinimo) <- transExp lo
unless (equivTipo tMinimo (TInt RW)) $ errorTiposMsg p "El minimo del for no es un entero" tMinimo (TInt RW)
(maximo, tMaximo) <- transExp hi
unless (equivTipo tMaximo (TInt RW)) $ errorTiposMsg p "El maximo del for no es un entero" tMaximo (TInt RW)
preWhileforExp
(cuerpo, tCuerpo) <- transExp bo
unless (equivTipo tCuerpo TUnit) $ errorTiposMsg p "Error en el cuerpo del For" tCuerpo TUnit
for <- forExp minimo maximo variable cuerpo
posWhileforExp
return (for, TUnit)
)
transExp(LetExp dcs body p) = transDecs dcs (transExp body)
transExp(BreakExp p) =
do break <- breakExp
return (break, TUnit)
transExp(ArrayExp sn cant init p) = do
tipoUsado <- getTipoT sn
case tipoUsado of
TArray t u -> do
(cantidad, tipoCant) <- transExp cant
(init, tipoInit) <- transExp init
cantEntera <- tiposIguales tipoCant (TInt RO)
tipoValido <- tiposIguales tipoInit t
if (cantEntera && tipoValido)
then do
array <- arrayExp cantidad init
return (array,TArray t u)
else derror $ pack ("Arreglo mal declarado, linea " ++ show p)
_ -> derror $ pack "Se declara un array de un tipo no array"
transProg :: (MemM w, Manticore w) => Exp -> w [Frag]
transProg programa = do
(programBody,tipoPrograma) <- transExp programa
level <- topLevel
proc <- functionDec programBody level IsProc
frags <- getFrags
return frags
runSeman = undefined |
c2723720641b9ccbf60a3ecd27275aa7e5efe763e41a962e34771ce71a36cd8f | e-bigmoon/haskell-blog | Email.hs | #!/usr/bin/env stack
{- stack repl --resolver lts-15.4
--package blaze-html
--package http-conduit
--package mime-mail
--package monad-logger
--package persistent-sqlite
--package persistent-template
--package shakespeare
--package text
--package yesod
--package yesod-auth
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DerivingStrategies #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
# LANGUAGE StandaloneDeriving #
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE UndecidableInstances #-}
import Control.Monad (join)
import Control.Monad.Logger (runNoLoggingT)
import Data.Maybe (isJust)
import Data.Text (Text, unpack)
import qualified Data.Text.Lazy.Encoding
import Data.Typeable (Typeable)
import Database.Persist.Sqlite
import Database.Persist.TH
import Network.Mail.Mime
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Text.Hamlet (shamlet)
import Text.Shakespeare.Text (stext)
import Yesod
import Yesod.Auth
import Yesod.Auth.Email
share [mkPersist sqlSettings { mpsGeneric = False }, mkMigrate "migrateAll"] [persistLowerCase|
User
email Text
password Text Maybe -- Password may not be set yet
verkey Text Maybe -- Used for resetting passwords
verified Bool
UniqueUser email
deriving Typeable
|]
newtype App = App SqlBackend
mkYesod "App" [parseRoutes|
/ HomeR GET
/auth AuthR Auth getAuth
|]
instance Yesod App where
-- Emails will include links, so be sure to include an approot so that
-- the links are valid!
approot = ApprootStatic ":3000"
yesodMiddleware = defaultCsrfMiddleware . defaultYesodMiddleware
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- Set up Persistent
instance YesodPersist App where
type YesodPersistBackend App = SqlBackend
runDB f = do
App conn <- getYesod
runSqlConn f conn
instance YesodAuth App where
type AuthId App = UserId
loginDest _ = HomeR
logoutDest _ = HomeR
authPlugins _ = [authEmail]
-- Need to find the UserId for the given email address.
authenticate creds = liftHandler $ runDB $ do
x <- insertBy $ User (credsIdent creds) Nothing Nothing False
return $ Authenticated $
case x of
Left (Entity userid _) -> userid -- newly added user
Right userid -> userid -- existing user
instance YesodAuthPersist App
-- Here's all of the email-specific code
instance YesodAuthEmail App where
type AuthEmailId App = UserId
afterPasswordRoute _ = HomeR
addUnverified email verkey =
liftHandler $ runDB $ insert $ User email Nothing (Just verkey) False
sendVerifyEmail email _ verurl = do
-- Print out to the console the verification email, for easier
-- debugging.
liftIO $ putStrLn $ "Copy/ Paste this URL in your browser:" ++ unpack verurl
-- Send email.
liftIO $ renderSendMail (emptyMail $ Address Nothing "noreply")
{ mailTo = [Address Nothing email]
, mailHeaders =
[ ("Subject", "Verify your email address")
]
, mailParts = [[textPart, htmlPart]]
}
where
textPart = Part
{ partType = "text/plain; charset=utf-8"
, partEncoding = None
, partDisposition = DefaultDisposition
, partContent = PartContent $ Data.Text.Lazy.Encoding.encodeUtf8
[stext|
Please confirm your email address by clicking on the link below.
#{verurl}
Thank you
|]
, partHeaders = []
}
htmlPart = Part
{ partType = "text/html; charset=utf-8"
, partEncoding = None
, partDisposition = DefaultDisposition
, partContent = PartContent $ renderHtml
[shamlet|
<p>Please confirm your email address by clicking on the link below.
<p>
<a href=#{verurl}>#{verurl}
<p>Thank you
|]
, partHeaders = []
}
getVerifyKey = liftHandler . runDB . fmap (userVerkey =<<) . get
setVerifyKey uid key = liftHandler $ runDB $ update uid [UserVerkey =. Just key]
verifyAccount uid = liftHandler $ runDB $ do
mu <- get uid
case mu of
Nothing -> return Nothing
Just u -> do
update uid [UserVerified =. True]
return $ Just uid
getPassword = liftHandler . runDB . fmap (userVerkey =<<) . get
setPassword uid pass = liftHandler . runDB $ update uid [UserPassword =. Just pass]
getEmailCreds email = liftHandler $ runDB $ do
mu <- getBy $ UniqueUser email
case mu of
Nothing -> return Nothing
Just (Entity uid u) -> return $ Just EmailCreds
{ emailCredsId = uid
, emailCredsAuthId = Just uid
, emailCredsStatus = isJust $ userPassword u
, emailCredsVerkey = userVerkey u
, emailCredsEmail = email
}
getEmail = liftHandler . runDB . fmap (fmap userEmail) . get
getHomeR :: Handler Html
getHomeR = do
maid <- maybeAuthId
defaultLayout
[whamlet|
<p>Your current auth ID: #{show maid}
$maybe _ <- maid
<p>
<a href=@{AuthR LogoutR}>Logout
$nothing
<p>
<a href=@{AuthR LoginR}>Go to the login page
|]
main :: IO ()
main = runNoLoggingT $ withSqliteConn "email.db3" $ \conn -> liftIO $ do
runSqlConn (runMigration migrateAll) conn
warp 3000 $ App conn
| null | https://raw.githubusercontent.com/e-bigmoon/haskell-blog/5c9e7c25f31ea6856c5d333e8e991dbceab21c56/sample-code/yesod/ch14/Email.hs | haskell | stack repl --resolver lts-15.4
--package blaze-html
--package http-conduit
--package mime-mail
--package monad-logger
--package persistent-sqlite
--package persistent-template
--package shakespeare
--package text
--package yesod
--package yesod-auth
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DerivingStrategies #
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell #
# LANGUAGE UndecidableInstances #
Password may not be set yet
Used for resetting passwords
Emails will include links, so be sure to include an approot so that
the links are valid!
Set up Persistent
Need to find the UserId for the given email address.
newly added user
existing user
Here's all of the email-specific code
Print out to the console the verification email, for easier
debugging.
Send email. | #!/usr/bin/env stack
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
import Control.Monad (join)
import Control.Monad.Logger (runNoLoggingT)
import Data.Maybe (isJust)
import Data.Text (Text, unpack)
import qualified Data.Text.Lazy.Encoding
import Data.Typeable (Typeable)
import Database.Persist.Sqlite
import Database.Persist.TH
import Network.Mail.Mime
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Text.Hamlet (shamlet)
import Text.Shakespeare.Text (stext)
import Yesod
import Yesod.Auth
import Yesod.Auth.Email
share [mkPersist sqlSettings { mpsGeneric = False }, mkMigrate "migrateAll"] [persistLowerCase|
User
email Text
verified Bool
UniqueUser email
deriving Typeable
|]
newtype App = App SqlBackend
mkYesod "App" [parseRoutes|
/ HomeR GET
/auth AuthR Auth getAuth
|]
instance Yesod App where
approot = ApprootStatic ":3000"
yesodMiddleware = defaultCsrfMiddleware . defaultYesodMiddleware
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
instance YesodPersist App where
type YesodPersistBackend App = SqlBackend
runDB f = do
App conn <- getYesod
runSqlConn f conn
instance YesodAuth App where
type AuthId App = UserId
loginDest _ = HomeR
logoutDest _ = HomeR
authPlugins _ = [authEmail]
authenticate creds = liftHandler $ runDB $ do
x <- insertBy $ User (credsIdent creds) Nothing Nothing False
return $ Authenticated $
case x of
instance YesodAuthPersist App
instance YesodAuthEmail App where
type AuthEmailId App = UserId
afterPasswordRoute _ = HomeR
addUnverified email verkey =
liftHandler $ runDB $ insert $ User email Nothing (Just verkey) False
sendVerifyEmail email _ verurl = do
liftIO $ putStrLn $ "Copy/ Paste this URL in your browser:" ++ unpack verurl
liftIO $ renderSendMail (emptyMail $ Address Nothing "noreply")
{ mailTo = [Address Nothing email]
, mailHeaders =
[ ("Subject", "Verify your email address")
]
, mailParts = [[textPart, htmlPart]]
}
where
textPart = Part
{ partType = "text/plain; charset=utf-8"
, partEncoding = None
, partDisposition = DefaultDisposition
, partContent = PartContent $ Data.Text.Lazy.Encoding.encodeUtf8
[stext|
Please confirm your email address by clicking on the link below.
#{verurl}
Thank you
|]
, partHeaders = []
}
htmlPart = Part
{ partType = "text/html; charset=utf-8"
, partEncoding = None
, partDisposition = DefaultDisposition
, partContent = PartContent $ renderHtml
[shamlet|
<p>Please confirm your email address by clicking on the link below.
<p>
<a href=#{verurl}>#{verurl}
<p>Thank you
|]
, partHeaders = []
}
getVerifyKey = liftHandler . runDB . fmap (userVerkey =<<) . get
setVerifyKey uid key = liftHandler $ runDB $ update uid [UserVerkey =. Just key]
verifyAccount uid = liftHandler $ runDB $ do
mu <- get uid
case mu of
Nothing -> return Nothing
Just u -> do
update uid [UserVerified =. True]
return $ Just uid
getPassword = liftHandler . runDB . fmap (userVerkey =<<) . get
setPassword uid pass = liftHandler . runDB $ update uid [UserPassword =. Just pass]
getEmailCreds email = liftHandler $ runDB $ do
mu <- getBy $ UniqueUser email
case mu of
Nothing -> return Nothing
Just (Entity uid u) -> return $ Just EmailCreds
{ emailCredsId = uid
, emailCredsAuthId = Just uid
, emailCredsStatus = isJust $ userPassword u
, emailCredsVerkey = userVerkey u
, emailCredsEmail = email
}
getEmail = liftHandler . runDB . fmap (fmap userEmail) . get
getHomeR :: Handler Html
getHomeR = do
maid <- maybeAuthId
defaultLayout
[whamlet|
<p>Your current auth ID: #{show maid}
$maybe _ <- maid
<p>
<a href=@{AuthR LogoutR}>Logout
$nothing
<p>
<a href=@{AuthR LoginR}>Go to the login page
|]
main :: IO ()
main = runNoLoggingT $ withSqliteConn "email.db3" $ \conn -> liftIO $ do
runSqlConn (runMigration migrateAll) conn
warp 3000 $ App conn
|
0cb4632ba5e3232105df88a463c34af8a0967a934b4939bd57ec59b0720e71c5 | masateruk/micro-caml | sum.ml | let () =
let rec sum x =
if x <= 0 then 0 else
sum (x - 1) + x in
print_int (sum 1000)
| null | https://raw.githubusercontent.com/masateruk/micro-caml/0c0bd066b87cf54ce33709355c422993a85a86a1/test/sum.ml | ocaml | let () =
let rec sum x =
if x <= 0 then 0 else
sum (x - 1) + x in
print_int (sum 1000)
| |
8d49120a9bfe040641c8c21a4985157e38c5208e1486d8a6687f14e7faedbbb9 | mhuebert/inside-out | macros.cljc | (ns inside-out.macros
(:refer-clojure :exclude [meta])
(:require [clojure.string :as str]
[clojure.zip :as z]
[inside-out.util :as util]
[re-db.hooks :as hooks]
[re-db.reactive :as r])
#?(:cljs (:require-macros inside-out.macros)))
(defn replace-toplevel [pmap forms]
(map (fn [x]
(if (list? x)
(list* (pmap (first x) (first x)) (rest x))
(pmap x x))) forms))
(defmacro support-clj-protocols
"Given a cljs deftype/defrecord, replace cljs-specific protocols/methods with clj variants
when expansion target is clj.
NOTE: only works for the subset of protocols/methods listed below."
[form]
target is cljs
form
(replace-toplevel '{ILookup clojure.lang.ILookup
-lookup valAt
ISeqable clojure.lang.Seqable
-seq seq
IDeref clojure.lang.IDeref
-deref deref
IReset clojure.lang.IAtom
-reset! reset
ISwap clojure.lang.IAtom
-swap! swap
IMeta clojure.lang.IMeta
-meta meta
IWithMeta clojure.lang.IObj
-with-meta withMeta
IFn clojure.lang.IFn
-invoke invoke} form)))
from -to-implement-walk-postwalk-traversal-using-clojure-zip
(defn prewalk [f loc]
(let [loc (z/replace loc (f (z/node loc) loc))]
(if-some [loc (z/down loc)]
(loop [loc loc]
(let [loc (prewalk f loc)]
(if-some [loc (z/right loc)]
(recur loc)
(z/up loc))))
loc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; utility macros
(defmacro if-found [[sym lookup] then else]
`(let [v# ~(concat lookup [::not-found])]
(if (= ::not-found v#)
~else
(let [~sym v#]
~then))))
(defmacro some-or [& forms]
(loop [forms (reverse forms)
out nil]
(if (empty? forms)
out
(recur (rest forms)
`(if-some [v# ~(first forms)]
v#
~out)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; helper functions
(defn remove-empty [m] (into {} (remove (comp nil? second)) m))
(defn code-zipper
"Zipper for representing arbitrary code supporting traversal into maps, sets, and any sequential collection"
[form]
(z/zipper
(fn branch? [x]
(or (sequential? x)
(map? x)
(set? x)))
seq
(fn make-node [node children]
(cond (map? node) (with-meta (into (empty node) children) (clojure.core/meta node))
(map-entry? node) #?(:clj (clojure.lang.MapEntry. (first children) (second children))
:cljs (cljs.core/MapEntry. (first children) (second children) nil))
(vector? node) (with-meta (vec children) (clojure.core/meta node))
(set? node) (with-meta (set children) (clojure.core/meta node))
:else children))
form))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; working with field variables
(defn field? [x]
(util/field-sym? (cond-> x (list? x) first)))
;; unwraps fields wrapped in lists
(defn quoted? [x] (and (list? x) (= 'quote (first x))))
(defn quote-it [x] `(quote ~x))
(defn unquote-it [x] (cond-> x (quoted? x) second))
(defn field-sym [x]
(cond-> x
(and (field? x)
(list? x)) first))
(defn quote-field-sym [form]
(cond-> form
(field? form)
(-> field-sym quote-it)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; handling ?field metadata
(defn inline-meta [field]
(when (list? field)
(apply hash-map (rest field))))
;; metadata inference: you can pass your own `:infer-meta` function as an option to `with-form*`
;; if these are not sufficient for your use-case
(defn infer-from-map-value [m loc]
(when (some-> loc z/left z/up z/node map-entry?)
{:attribute (z/node (z/left loc))
:id (:db/id (-> loc z/up z/up z/node))}))
(defn infer-from-tx-value [m loc]
(let [parent (some-> loc z/up z/node)]
(when (and (vector? parent)
(= :db/add (first parent))
(= 3 (count (z/lefts loc))))
{:attribute (nth parent 2)
:id (nth parent 1)})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; core analysis/macro
(def default-infer [infer-from-map-value
infer-from-tx-value])
(defn ns-ify
"For a keyword :a.b.c, turns first segment into namespace."
[kw]
(let [kw-name (name kw)
parts (str/split kw-name #"\.")]
(if (> (count parts) 1)
(keyword (first parts) (str/join "." (rest parts)))
(keyword kw-name))))
(defn lift-ns [m ns]
(let [ns-name (name ns)]
(reduce-kv (fn [out k v]
(cond-> out
(= ns-name (namespace k))
(assoc (ns-ify (name k)) v))) {} m)))
(comment
(lift-ns {:form/a.b 1 :form/b.c 2 :other 3} :form))
(defn dissoc-ns [m ns]
(let [ns-name (name ns)]
(reduce (fn [out k]
(cond-> out
(= ns-name (namespace k))
(dissoc k))) m (keys m))))
(defn analyze-form
([form] (analyze-form form {}))
([form options]
(let [analyze-many (fn [{:as field :keys [many]}]
(cond-> field
many
(assoc :many
(let [{:form/keys [fields compute]} (analyze-form many options)]
{:many/fields (update-keys fields quote-it)
:many/compute compute}))))
[return fields] (let [!fields (atom {})]
[(->> (code-zipper form)
(prewalk (fn [x loc]
(when (field? x)
(swap! !fields update (field-sym x) merge
;; fields know their own symbol
{:sym (quote-field-sym x)}
;; infer metadata from position within form
(->> (:infer-meta options default-infer)
(reduce (fn [meta f] (merge meta (remove-empty (f meta loc))))
{})
(#(update-vals % quote-field-sym)))
;; merge inline-meta last, overrides inferred metadata
(-> (inline-meta x) ;; (?field :attr v)
analyze-many))) ;; handle many-children
(field-sym x)))
z/node)
@!fields])
;; the core function where we bring bindings into scope and evaluate the form
compute (let [bindings (gensym "bindings")]
`(fn [~bindings]
(let [~@(mapcat (fn [sym] [(unquote-it sym) `(get ~bindings '~sym)]) (keys fields))]
~return)))
;; all other fields are assumed to be <key> {?field <value>}
fields (reduce-kv
(fn [fields meta-k values]
(cond (map? values)
(reduce-kv (fn [fields sym value]
(cond-> fields
(fields sym)
(assoc-in [sym meta-k] value))) fields values)
(vector? values)
(reduce (fn [fields sym]
(cond-> fields
(fields sym)
(assoc-in [sym meta-k] true))) fields values)))
fields
(-> options
(dissoc :meta)
(dissoc-ns :form)))
;; handle form metadata
form-meta (merge {:meta (cond-> (:meta options)
(map? (:meta options))
(update-keys quote-field-sym))}
(lift-ns options :form))]
{:form/fields fields
:form/return return
:form/compute compute
:form/meta form-meta})))
(comment
;; check that all the ?vars are found
(->> (analyze-form '[[:db/add 1 :name/first ?first]
{:name/last ?last}
[:db/add 2 :pet/name ?pet-name]])
:form/fields
keys
set
(= '#{?first ?last ?pet-name}))
;; verify that all fields are found and replaced
(->> '[[:db/add ?id :name/first ?owner-name]
[:db/add 2 :pet/owner (?id :default 99)]
[:db/add 2 :pet/name ?pet-name]
#{?set-member}]
analyze-form
((juxt :form/return (comp set keys :form/fields)))
(= '[[[:db/add ?id :name/first ?owner-name]
[:db/add 2 :pet/owner ?id]
[:db/add 2 :pet/name ?pet-name]
#{?set-member}]
#{?id ?owner-name ?pet-name ?set-member}]))
;; metadata overrides
(-> '[[:db/add 1 :name/first (?first :attribute :first-name)]]
analyze-form
(get-in [:form/fields '?first :attribute])
(= :first-name)))
(defn with-form*
"Implements with-form. Can pass :infer-meta function for additional metadata inference."
[_form _env analyzer-options bindings body]
(let [[root-sym expr] bindings
options (apply hash-map (drop 2 bindings))
_ (assert (every? keyword? (keys options)) (str "Invalid options (not a keyword: " (remove keyword? (keys options)) ")"))
{:form/keys [fields compute meta]} (analyze-form expr (merge analyzer-options options))]
`(hooks/with-let [~root-sym (~'inside-out.forms/root ~compute ~meta ~(vec (vals fields)))
~@(->> fields
(mapcat (fn [[sym {:keys [many]}]]
[(cond-> sym
many
(with-meta {:many/bindings (->> many :many/fields keys vec)}))
`(get ~root-sym '~sym)])))]
~@body)))
(defn form* [_form _env expr options]
(let [{:form/keys [fields compute meta]} (analyze-form expr options)]
`(~'inside-out.forms/root ~compute ~(or meta {}) ~(vec (vals fields)))))
;; just for dev/notebook
(defn timeout* [_ _ ms body]
`(~'js/setTimeout (fn [] ~@body) ~ms))
(defmacro timeout [ms & body]
(timeout* nil nil ms body))
(defmacro swap-> [ref & forms]
`(swap! ~ref (fn [val#] (-> val# ~@forms))))
| null | https://raw.githubusercontent.com/mhuebert/inside-out/f38b49e8b8f8242d2c0112932e11300ddb2bc47a/src/inside_out/macros.cljc | clojure |
utility macros
helper functions
working with field variables
unwraps fields wrapped in lists
handling ?field metadata
metadata inference: you can pass your own `:infer-meta` function as an option to `with-form*`
if these are not sufficient for your use-case
core analysis/macro
fields know their own symbol
infer metadata from position within form
merge inline-meta last, overrides inferred metadata
(?field :attr v)
handle many-children
the core function where we bring bindings into scope and evaluate the form
all other fields are assumed to be <key> {?field <value>}
handle form metadata
check that all the ?vars are found
verify that all fields are found and replaced
metadata overrides
just for dev/notebook | (ns inside-out.macros
(:refer-clojure :exclude [meta])
(:require [clojure.string :as str]
[clojure.zip :as z]
[inside-out.util :as util]
[re-db.hooks :as hooks]
[re-db.reactive :as r])
#?(:cljs (:require-macros inside-out.macros)))
(defn replace-toplevel [pmap forms]
(map (fn [x]
(if (list? x)
(list* (pmap (first x) (first x)) (rest x))
(pmap x x))) forms))
(defmacro support-clj-protocols
"Given a cljs deftype/defrecord, replace cljs-specific protocols/methods with clj variants
when expansion target is clj.
NOTE: only works for the subset of protocols/methods listed below."
[form]
target is cljs
form
(replace-toplevel '{ILookup clojure.lang.ILookup
-lookup valAt
ISeqable clojure.lang.Seqable
-seq seq
IDeref clojure.lang.IDeref
-deref deref
IReset clojure.lang.IAtom
-reset! reset
ISwap clojure.lang.IAtom
-swap! swap
IMeta clojure.lang.IMeta
-meta meta
IWithMeta clojure.lang.IObj
-with-meta withMeta
IFn clojure.lang.IFn
-invoke invoke} form)))
from -to-implement-walk-postwalk-traversal-using-clojure-zip
(defn prewalk [f loc]
(let [loc (z/replace loc (f (z/node loc) loc))]
(if-some [loc (z/down loc)]
(loop [loc loc]
(let [loc (prewalk f loc)]
(if-some [loc (z/right loc)]
(recur loc)
(z/up loc))))
loc)))
(defmacro if-found [[sym lookup] then else]
`(let [v# ~(concat lookup [::not-found])]
(if (= ::not-found v#)
~else
(let [~sym v#]
~then))))
(defmacro some-or [& forms]
(loop [forms (reverse forms)
out nil]
(if (empty? forms)
out
(recur (rest forms)
`(if-some [v# ~(first forms)]
v#
~out)))))
(defn remove-empty [m] (into {} (remove (comp nil? second)) m))
(defn code-zipper
"Zipper for representing arbitrary code supporting traversal into maps, sets, and any sequential collection"
[form]
(z/zipper
(fn branch? [x]
(or (sequential? x)
(map? x)
(set? x)))
seq
(fn make-node [node children]
(cond (map? node) (with-meta (into (empty node) children) (clojure.core/meta node))
(map-entry? node) #?(:clj (clojure.lang.MapEntry. (first children) (second children))
:cljs (cljs.core/MapEntry. (first children) (second children) nil))
(vector? node) (with-meta (vec children) (clojure.core/meta node))
(set? node) (with-meta (set children) (clojure.core/meta node))
:else children))
form))
(defn field? [x]
(util/field-sym? (cond-> x (list? x) first)))
(defn quoted? [x] (and (list? x) (= 'quote (first x))))
(defn quote-it [x] `(quote ~x))
(defn unquote-it [x] (cond-> x (quoted? x) second))
(defn field-sym [x]
(cond-> x
(and (field? x)
(list? x)) first))
(defn quote-field-sym [form]
(cond-> form
(field? form)
(-> field-sym quote-it)))
(defn inline-meta [field]
(when (list? field)
(apply hash-map (rest field))))
(defn infer-from-map-value [m loc]
(when (some-> loc z/left z/up z/node map-entry?)
{:attribute (z/node (z/left loc))
:id (:db/id (-> loc z/up z/up z/node))}))
(defn infer-from-tx-value [m loc]
(let [parent (some-> loc z/up z/node)]
(when (and (vector? parent)
(= :db/add (first parent))
(= 3 (count (z/lefts loc))))
{:attribute (nth parent 2)
:id (nth parent 1)})))
(def default-infer [infer-from-map-value
infer-from-tx-value])
(defn ns-ify
"For a keyword :a.b.c, turns first segment into namespace."
[kw]
(let [kw-name (name kw)
parts (str/split kw-name #"\.")]
(if (> (count parts) 1)
(keyword (first parts) (str/join "." (rest parts)))
(keyword kw-name))))
(defn lift-ns [m ns]
(let [ns-name (name ns)]
(reduce-kv (fn [out k v]
(cond-> out
(= ns-name (namespace k))
(assoc (ns-ify (name k)) v))) {} m)))
(comment
(lift-ns {:form/a.b 1 :form/b.c 2 :other 3} :form))
(defn dissoc-ns [m ns]
(let [ns-name (name ns)]
(reduce (fn [out k]
(cond-> out
(= ns-name (namespace k))
(dissoc k))) m (keys m))))
(defn analyze-form
([form] (analyze-form form {}))
([form options]
(let [analyze-many (fn [{:as field :keys [many]}]
(cond-> field
many
(assoc :many
(let [{:form/keys [fields compute]} (analyze-form many options)]
{:many/fields (update-keys fields quote-it)
:many/compute compute}))))
[return fields] (let [!fields (atom {})]
[(->> (code-zipper form)
(prewalk (fn [x loc]
(when (field? x)
(swap! !fields update (field-sym x) merge
{:sym (quote-field-sym x)}
(->> (:infer-meta options default-infer)
(reduce (fn [meta f] (merge meta (remove-empty (f meta loc))))
{})
(#(update-vals % quote-field-sym)))
(field-sym x)))
z/node)
@!fields])
compute (let [bindings (gensym "bindings")]
`(fn [~bindings]
(let [~@(mapcat (fn [sym] [(unquote-it sym) `(get ~bindings '~sym)]) (keys fields))]
~return)))
fields (reduce-kv
(fn [fields meta-k values]
(cond (map? values)
(reduce-kv (fn [fields sym value]
(cond-> fields
(fields sym)
(assoc-in [sym meta-k] value))) fields values)
(vector? values)
(reduce (fn [fields sym]
(cond-> fields
(fields sym)
(assoc-in [sym meta-k] true))) fields values)))
fields
(-> options
(dissoc :meta)
(dissoc-ns :form)))
form-meta (merge {:meta (cond-> (:meta options)
(map? (:meta options))
(update-keys quote-field-sym))}
(lift-ns options :form))]
{:form/fields fields
:form/return return
:form/compute compute
:form/meta form-meta})))
(comment
(->> (analyze-form '[[:db/add 1 :name/first ?first]
{:name/last ?last}
[:db/add 2 :pet/name ?pet-name]])
:form/fields
keys
set
(= '#{?first ?last ?pet-name}))
(->> '[[:db/add ?id :name/first ?owner-name]
[:db/add 2 :pet/owner (?id :default 99)]
[:db/add 2 :pet/name ?pet-name]
#{?set-member}]
analyze-form
((juxt :form/return (comp set keys :form/fields)))
(= '[[[:db/add ?id :name/first ?owner-name]
[:db/add 2 :pet/owner ?id]
[:db/add 2 :pet/name ?pet-name]
#{?set-member}]
#{?id ?owner-name ?pet-name ?set-member}]))
(-> '[[:db/add 1 :name/first (?first :attribute :first-name)]]
analyze-form
(get-in [:form/fields '?first :attribute])
(= :first-name)))
(defn with-form*
"Implements with-form. Can pass :infer-meta function for additional metadata inference."
[_form _env analyzer-options bindings body]
(let [[root-sym expr] bindings
options (apply hash-map (drop 2 bindings))
_ (assert (every? keyword? (keys options)) (str "Invalid options (not a keyword: " (remove keyword? (keys options)) ")"))
{:form/keys [fields compute meta]} (analyze-form expr (merge analyzer-options options))]
`(hooks/with-let [~root-sym (~'inside-out.forms/root ~compute ~meta ~(vec (vals fields)))
~@(->> fields
(mapcat (fn [[sym {:keys [many]}]]
[(cond-> sym
many
(with-meta {:many/bindings (->> many :many/fields keys vec)}))
`(get ~root-sym '~sym)])))]
~@body)))
(defn form* [_form _env expr options]
(let [{:form/keys [fields compute meta]} (analyze-form expr options)]
`(~'inside-out.forms/root ~compute ~(or meta {}) ~(vec (vals fields)))))
(defn timeout* [_ _ ms body]
`(~'js/setTimeout (fn [] ~@body) ~ms))
(defmacro timeout [ms & body]
(timeout* nil nil ms body))
(defmacro swap-> [ref & forms]
`(swap! ~ref (fn [val#] (-> val# ~@forms))))
|
d3a0bb7a077277c01d6dfbd3341e2ceb2615b6e9d644c7c697ed8480adcf9728 | letmaik/monadiccp | Alpha.hs | # LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
A kid goes into a grocery store and buys four items . The cashier charges $ 7.11 .
-- The kid pays and is about to leave when the cashier calls the kid back, and says
" Hold on , I multiplied the four items instead of adding them ; I 'll try again ...
Gosh , with adding them the price still comes to $ 7.11 " ! What were the prices of
the four items ?
import Data.Char (ord)
import Control.CP.FD.Example
import Control.CP.FD.Interface
import Control.CP.FD.Model
import Control.CP.SearchTree
import Control.CP.Solver
(@==) :: (MonadTree m, TreeSolver m ~ s, Constraint s ~ Either Model q) => ModelInt -> ModelInt -> m ()
(@==) = (@=)
word :: ModelCol -> String -> ModelInt
word lst = foldr (\x -> (lst!(cte $ ord x - ord 'a')+)) (cte 0)
model :: ExampleModel ()
model _ = exists $ \col -> do
size col @= cte 26
allDiff col
col `allin` (cte 1,cte 26)
word col "ballet" @== 45
word col "cello" @== 43
word col "concert" @== 74
word col "flute" @== 30
word col "fugue" @== 50
word col "glee" @== 66
word col "jazz" @== 58
word col "lyre" @== 47
word col "oboe" @== 53
word col "opera" @== 65
word col "polka" @== 59
word col "quartet" @== 50
word col "saxophone" @== 134
word col "scale" @== 51
word col "solo" @== 37
word col "song" @== 61
word col "soprano" @== 82
word col "theme" @== 72
word col "violin" @== 100
word col "waltz" @== 34
return col
main = example_sat_main_void model
| null | https://raw.githubusercontent.com/letmaik/monadiccp/fe4498e46a7b9d9e387fd5e4ed5d0749a89d0188/examples/Alpha.hs | haskell | The kid pays and is about to leave when the cashier calls the kid back, and says | # LANGUAGE TypeFamilies #
# LANGUAGE FlexibleContexts #
A kid goes into a grocery store and buys four items . The cashier charges $ 7.11 .
" Hold on , I multiplied the four items instead of adding them ; I 'll try again ...
Gosh , with adding them the price still comes to $ 7.11 " ! What were the prices of
the four items ?
import Data.Char (ord)
import Control.CP.FD.Example
import Control.CP.FD.Interface
import Control.CP.FD.Model
import Control.CP.SearchTree
import Control.CP.Solver
(@==) :: (MonadTree m, TreeSolver m ~ s, Constraint s ~ Either Model q) => ModelInt -> ModelInt -> m ()
(@==) = (@=)
word :: ModelCol -> String -> ModelInt
word lst = foldr (\x -> (lst!(cte $ ord x - ord 'a')+)) (cte 0)
model :: ExampleModel ()
model _ = exists $ \col -> do
size col @= cte 26
allDiff col
col `allin` (cte 1,cte 26)
word col "ballet" @== 45
word col "cello" @== 43
word col "concert" @== 74
word col "flute" @== 30
word col "fugue" @== 50
word col "glee" @== 66
word col "jazz" @== 58
word col "lyre" @== 47
word col "oboe" @== 53
word col "opera" @== 65
word col "polka" @== 59
word col "quartet" @== 50
word col "saxophone" @== 134
word col "scale" @== 51
word col "solo" @== 37
word col "song" @== 61
word col "soprano" @== 82
word col "theme" @== 72
word col "violin" @== 100
word col "waltz" @== 34
return col
main = example_sat_main_void model
|
747f8b0d9a2f864eb36f767733e076edbccf1448dd6fbcc24223258f70d6edff | K2InformaticsGmbH/dderl | dderl_dal.erl | -module(dderl_dal).
-behavior(gen_server).
-include("dderl.hrl").
-export([init/1
,start_link/0
,handle_call/3
,handle_cast/2
,handle_info/2
,terminate/2
,code_change/3
,format_status/2
]).
-export([get_adapters/1
,add_adapter/2
,add_command/7
,update_command/6
,update_command/7
,add_view/5
,update_view/4
,rename_view/3
,delete_view/2
,add_connect/2
,get_connects/2
,del_conn/3
,get_command/2
,get_view/4
,get_view/2
,is_local_query/1
,can_connect_locally/1
,save_dashboard/5
,rename_dashboard/3
,delete_dashboard/2
,get_dashboards/2
,add_adapter_to_cmd/3
,user_name/1
,get_restartable_apps/0
,process_login/3
,rows_from/3
,expand_rows/4
,add_d3_templates_path/2
,get_d3_templates/0
,get_d3_templates_path/1
,get_host_app/0
,is_proxy/2
]).
-record(state, { schema :: term()
, sess :: {atom(), pid()}
, d3_templates :: list()
, host_app :: binary()
}).
%% Privileges
-define(MANAGE_CONNS, {dderl, conn, manage}).
-define(CREATE_CONNS, {dderl, conn, create}).
-define(USE_SYS_CONNS, {dderl, conn, {owner, system}, use}).
-define(USE_CONN(__ConnId), {dderl, conn, {conn, __ConnId}, use}).
-define(USE_LOCAL_CONN, {dderl, conn, local, use}).
Validate this permission .
-define(USE_ADAPTER, {dderl, adapter, {id, __AdaptId}, use}).
-spec add_adapter(atom(), binary()) -> ok.
add_adapter(Id, FullName) -> gen_server:cast(?MODULE, {add_adapter, Id, FullName}).
-spec add_connect({atom(), pid()} | undefined, #ddConn{}) -> integer() | {error, binary()}.
add_connect(undefined, #ddConn{} = Conn) -> gen_server:call(?MODULE, {add_connect, Conn});
add_connect(Sess, #ddConn{} = Conn) -> gen_server:call(?MODULE, {add_connect, Sess, Conn}).
-spec del_conn({atom(), pid()}, ddEntityId(), integer()) -> ok | no_permission.
del_conn(Sess, UserId, ConId) ->
HasAll = (Sess:run_cmd(have_permission, [[?MANAGE_CONNS]]) == true),
if HasAll ->
ok = Sess:run_cmd(delete, [ddConn, ConId]),
?Info("user ~p deleted connection ~p", [UserId, ConId]),
ok;
true ->
case Sess:run_cmd(select, [ddConn, [{#ddConn{id=ConId,owner=UserId,_='_'},[],['$_']}]]) of
{[_|_], true} ->
ok = Sess:run_cmd(delete, [ddConn, ConId]),
?Info("user ~p deleted connection ~p", [UserId, ConId]),
ok;
_ ->
?Error("user ~p doesn't have permission to delete connection ~p", [UserId, ConId]),
no_permission
end
end.
-spec get_connects({atom(), pid()}, ddEntityId()) -> [#ddConn{}] | {error, binary()}.
get_connects(Sess, UserId) -> gen_server:call(?MODULE, {get_connects, Sess, UserId}).
-spec add_command({atom(), pid()} | undefined, ddEntityId(), atom(), binary(), binary(), list() | undefined, term()) -> ddEntityId().
add_command(undefined, Owner, Adapter, Name, Cmd, Conn, Opts) ->
gen_server:call(?MODULE, {add_command, Owner, Adapter, Name, Cmd, Conn, Opts});
add_command(Sess, Owner, Adapter, Name, Cmd, undefined, Opts) ->
case is_local_query(Cmd) of
true -> Conn = local;
false -> Conn = []
end,
add_command(Sess, Owner, Adapter, Name, Cmd, Conn, Opts);
add_command(Sess, Owner, Adapter, Name, Cmd, Conn, Opts) ->
Id = erlang:phash2(make_ref()),
?Debug("add_command ~p new id ~p", [Name, Id]),
NewCmd = #ddCmd { id = Id
, name = Name
, owner = Owner
, adapters = [Adapter]
, command = Cmd
, conns = Conn
, opts = Opts},
Sess:run_cmd(insert, [ddCmd, NewCmd]),
?Debug("add_command inserted ~p", [NewCmd]),
Id.
-spec update_command({atom(), pid()} | undefined, ddEntityId(), ddEntityId(), binary(), binary(), term()) -> ddEntityId().
update_command(undefined, Id, Owner, Name, Sql, Opts) -> gen_server:call(?MODULE, {update_command, Id, Owner, Name, Sql, Opts});
update_command(Sess, Id, Owner, Name, Sql, Opts) ->
?Debug("update command ~p replacing id ~p", [Name, Id]),
{[Cmd], true} = Sess:run_cmd(select, [ddCmd, [{#ddCmd{id = Id, _='_'}, [], ['$_']}]]),
NewCmd = #ddCmd { id = Id
, name = Name
, owner = Owner
, adapters = Cmd#ddCmd.adapters
, command = Sql
, conns = Cmd#ddCmd.conns
, opts = Opts},
Sess:run_cmd(write, [ddCmd, NewCmd]),
Id.
-spec update_command({atom(), pid()} | undefined, ddEntityId(), ddEntityId(), binary(), binary(), list(), term()) -> ddEntityId().
update_command(undefined, Id, Owner, Name, Sql, Conns, Opts) -> gen_server:call(?MODULE, {update_command, Id, Owner, Name, Sql, Conns, Opts});
update_command(Sess, Id, Owner, Name, Sql, Conns, Opts) ->
?Debug("update command ~p replacing id ~p", [Name, Id]),
{[Cmd], true} = Sess:run_cmd(select, [ddCmd, [{#ddCmd{id = Id, _='_'}, [], ['$_']}]]),
NewCmd = #ddCmd { id = Id
, name = Name
, owner = Owner
, adapters = Cmd#ddCmd.adapters
, command = Sql
, conns = Conns
, opts = Opts},
Sess:run_cmd(write, [ddCmd, NewCmd]),
Id.
-spec user_name(atom() | integer() | binary()) -> binary().
user_name(system) -> <<"system">>;
user_name(Name) when is_binary(Name) -> Name;
user_name(Id) when is_integer(Id) ->
{[Name],true} = imem_meta:select(ddAccount, [{#ddAccount{id=Id,name='$1',_='_'},[],['$1']}]),
Name.
-spec add_view({atom(), pid()} | undefined, ddEntityId(), binary(), ddEntityId(), #viewstate{}) -> ddEntityId().
add_view(undefined, Owner, Name, CmdId, ViewsState) ->
gen_server:call(?MODULE, {add_view, Owner, Name, CmdId, ViewsState});
add_view(Sess, Owner, Name, CmdId, ViewsState) ->
Id = case Sess:run_cmd(select, [ddView, [{#ddView{name=Name, cmd = CmdId, id='$1', owner=Owner, _='_'}
, []
, ['$1']}]]) of
{[Id0|_], true} ->
?Debug("add_view ~p replacing id ~p ~p~n", [Name, Id0, Owner]),
Id0;
_ ->
Id1 = erlang:phash2(make_ref()),
?Debug("add_view ~p new id ~p", [Name, Id1]),
Id1
end,
NewView = #ddView { id = Id
, name = Name
, owner = Owner
, cmd = CmdId
, state = ViewsState},
Sess:run_cmd(write, [ddView, NewView]), %% TODO: Validate result...
?Debug("add_view written ~p", [NewView]),
Id.
-spec update_view({atom(), pid()}, integer(), #viewstate{}, binary()) -> integer() | {error, binary()}.
update_view(Sess, ViewId, ViewsState, Qry) when is_integer(ViewId) ->
%% TODO: At the moment the command and the view always have the same owner.
%% Check for authorization.
case Sess:run_cmd(select, [ddView, [{#ddView{id=ViewId, _='_'}, [], ['$_']}]]) of
{[OldView], true} ->
?Debug("The oldView ~p and the session ~p", [OldView, Sess]),
Cmd = get_command(Sess, OldView#ddView.cmd),
?Debug("The old cmd ~p", [Cmd]),
%% TODO: Handle multiple adapters.
update_command(Sess, Cmd#ddCmd.id, Cmd#ddCmd.owner, Cmd#ddCmd.name, Qry, Cmd#ddCmd.opts),
case ViewsState of
#viewstate{table_layout=[], column_layout=[]} ->
NewView = OldView;
#viewstate{table_layout=[]} ->
#viewstate{table_layout=OldTableLay} = OldView#ddView.state,
NewState = ViewsState#viewstate{table_layout=OldTableLay},
NewView = OldView#ddView{state=NewState};
#viewstate{column_layout=[]} ->
#viewstate{column_layout=OldColumLay} = OldView#ddView.state,
NewState = ViewsState#viewstate{column_layout=OldColumLay},
NewView = OldView#ddView{state=NewState};
#viewstate{} ->
NewView = OldView#ddView{state=ViewsState}
end,
Sess:run_cmd(write, [ddView, NewView]),
?Debug("update_view written ~p", [NewView]),
ViewId;
_ ->
?Error("Unable to get the view to update ~p", [ViewId]),
{error, <<"Unable to get the view to update">>}
end.
-spec rename_view({atom(), pid()}, integer(), binary()) -> ok | {error, binary()}.
rename_view(Sess, ViewId, ViewName) ->
%% TODO: At the moment the command and the view always have the same owner.
%% Check for authorization.
case Sess:run_cmd(select, [ddView, [{#ddView{id=ViewId, _='_'}, [], ['$_']}]]) of
{[OldView], true} ->
case Sess:run_cmd(select, [ddCmd, [{#ddCmd{id=OldView#ddView.cmd, _='_'}, [], ['$_']}]]) of
{[OldCmd], true} ->
Sess:run_cmd(write, [ddCmd, OldCmd#ddCmd{name = ViewName}]),
Sess:run_cmd(write, [ddView, OldView#ddView{name = ViewName}]),
ok;
_ ->
?Error("Unable to get the command to rename ~p", [OldView#ddView.cmd]),
{error, <<"Unable to find the command to rename">>}
end;
_ ->
?Error("Unable to get the view to rename ~p", [ViewId]),
{error, <<"Unable to find the view to rename">>}
end.
-spec delete_view({atom(), pid()}, integer()) -> integer() | {error, binary()}.
delete_view(Sess, ViewId) ->
%% TODO: At the moment the command and the view always have the same owner.
%% Check for authorization.
case Sess:run_cmd(select, [ddView, [{#ddView{id=ViewId, _='_'}, [], ['$_']}]]) of
{[OldView], true} ->
case Sess:run_cmd(select, [ddView, [{#ddView{cmd=OldView#ddView.cmd, _='_'}, [], ['$_']}]]) of
{[OldView], true} ->
% Only one view with the command, so the command is also deleted
case Sess:run_cmd(select, [ddCmd, [{#ddCmd{id=OldView#ddView.cmd, _='_'}, [], ['$_']}]]) of
{[OldCmd], true} ->
ok = Sess:run_cmd(delete, [ddCmd, OldCmd#ddCmd.id]);
_ -> ?Info("No command found to delete ~p", [OldView#ddView.cmd])
end;
_ -> ok
end,
ok = Sess:run_cmd(delete, [ddView, OldView#ddView.id]),
ok;
_ ->
?Error("Unable to get the view to delete ~p", [ViewId]),
{error, <<"Unable to find the view to delete">>}
end.
-spec get_adapters({atom(), pid()}) -> {error, binary()} | [#ddAdapter{}].
get_adapters(Sess) ->
?Debug("get_adapters"),
check_cmd_select(Sess, [ddAdapter, [{'$1', [], ['$_']}]]).
-spec get_command({atom(), pid()}, ddEntityId() | binary()) -> #ddCmd{} | {error, binary()}.
get_command(Sess, IdOrName) ->
?Debug("get_command for id ~p", [IdOrName]),
CmdsResult =
case IdOrName of
Id when is_integer(Id) ->
check_cmd_select(Sess, [ddCmd, [{#ddCmd{id=Id, _='_'}, [], ['$_']}]]);
Name ->
check_cmd_select(Sess, [ddCmd, [{#ddCmd{name=Name, _='_'}, [], ['$_']}]])
end,
case CmdsResult of
{error, _} = Error -> Error;
[Cmd | _Ignored] -> Cmd;
[] -> #ddCmd{opts=[]}
end.
-spec get_view({atom(), pid()}, ddEntityId()) -> {error, binary()} | #ddView{} | undefined .
get_view(undefined, ViewId) -> gen_server:call(?MODULE, {get_view, ViewId});
get_view(Sess, ViewId) ->
?Debug("get ddView by id ~p", [ViewId]),
case check_cmd_select(Sess, [ddView, [{#ddView{id = ViewId, _ = '_'}, [], ['$_']}]]) of
{error, _} = Error -> Error;
[View] -> View;
Result ->
?Error("ddView with the id ~p was not found, select result: ~n~p", [ViewId, Result]),
undefined
end.
-spec get_view({atom(), pid()} | undefined, binary(), atom(), ddEntityId() | '_') -> #ddView{} | undefined.
get_view(undefined, Name, Adapter, Owner) -> gen_server:call(?MODULE, {get_view, Name, Adapter, Owner});
get_view(Sess, Name, Adapter, Owner) ->
?Debug("get_view ~p", [Name]),
case check_cmd_select(Sess, [ddView,[{#ddView{name=Name, owner=Owner, _='_'}, [], ['$_']}]]) of
{error, _} = Error -> Error;
Views ->
case filter_view_result(Views, Sess, Adapter) of
{error, _} = Error -> Error;
View -> View
end
end.
-spec save_dashboard({atom(), pid()}, ddEntityId(), integer(), binary(), list()) -> integer() | {error, binary()}.
save_dashboard(Sess, Owner, -1, Name, Views) ->
NewId = erlang:phash2(make_ref()),
case Sess:run_cmd(select, [ddDash, [{#ddDash{id=NewId, name='$1', _='_'}, [], ['$1']}]]) of
{[DashName], true} ->
?Debug("Save dashboard colision saving the dashboard ~p with id ~p", [DashName, NewId]),
save_dashboard(Sess, Owner, -1, Name, Views);
_ ->
save_dashboard(Sess, Owner, NewId, Name, Views)
end;
save_dashboard(Sess, Owner, DashId, Name, Views) ->
NewDash = #ddDash{id = DashId, name = Name, owner = Owner, views = Views},
Sess:run_cmd(write, [ddDash, NewDash]),
?Debug("dashboard saved ~p", [NewDash]),
DashId.
-spec rename_dashboard({atom(), pid()}, integer(), binary()) -> binary() | {error, binary()}.
rename_dashboard(Sess, Id, Name) ->
case check_cmd_select(Sess, [ddDash, [{#ddDash{id=Id, _='_'}, [], ['$_']}]]) of
{error, _} = Error -> Error;
[] -> {error, <<"Dashboard not found">>};
[OldDash = #ddDash{}] ->
Sess:run_cmd(write, [ddDash, OldDash#ddDash{name=Name}]),
Name
end.
-spec delete_dashboard({atom(), pid()}, integer()) -> integer() | {error, binary()}.
delete_dashboard(Sess, Id) ->
case check_cmd_select(Sess, [ddDash, [{#ddDash{id=Id, _='_'}, [], ['$_']}]]) of
{error, _} = Error -> Error;
[] -> {error, <<"Dashboard not found">>};
[#ddDash{id = Id}] ->
ok = Sess:run_cmd(delete, [ddDash, Id]),
Id
end.
-spec get_dashboards({atom(), pid()}, ddEntityId()) -> {error, binary()} | [#ddDash{}].
get_dashboards(Sess, Owner) ->
check_cmd_select(Sess, [ddDash, [{#ddDash{owner = Owner, _='_'}, [], ['$_']}]]).
-spec get_name({atom(), pid()}, ddEntityId()) -> ddIdentity().
get_name(Sess, UserId) ->
case Sess:run_cmd(select, [ddAccount, [{#ddAccount{id=UserId, name='$1', _='_'}, [], ['$1']}]]) of
{[Username], true} -> Username;
_ -> <<"">>
end.
-spec add_adapter_to_cmd({atom(), pid()} | undefined, ddEntityId(), atom()) -> ok | {error, binary()}.
add_adapter_to_cmd(undefined, CmdId, Adapter) ->
gen_server:call(?MODULE, {add_adapter_to_cmd, CmdId, Adapter});
add_adapter_to_cmd(Sess, CmdId, Adapter) ->
{[Cmd], true} = Sess:run_cmd(select, [ddCmd, [{#ddCmd{id = CmdId, _='_'}, [], ['$_']}]]),
case lists:member(Adapter, Cmd#ddCmd.adapters) of
false ->
NewAdapters = [Adapter|Cmd#ddCmd.adapters];
true ->
NewAdapters = Cmd#ddCmd.adapters
end,
Sess:run_cmd(write, [ddCmd, Cmd#ddCmd{adapters = NewAdapters}]),
CmdId.
-spec add_d3_templates_path(atom(), string()) -> ok.
add_d3_templates_path(Application, Path) ->
gen_server:call(?MODULE, {add_d3_templates_path, {Application, Path}}).
-spec get_d3_templates() -> [{atom(), string()}].
get_d3_templates() ->
gen_server:call(?MODULE, get_d3_templates).
-spec get_d3_templates_path(atom()) -> string().
get_d3_templates_path(Application) ->
gen_server:call(?MODULE, {get_d3_templates_path, Application}).
-spec get_host_app() -> binary().
get_host_app() ->
gen_server:call(?MODULE, get_host_app).
-spec start_link() -> {ok, pid()} | ignore | {error, term()}.
start_link() ->
?Info("~p starting...~n", [?MODULE]),
case gen_server:start_link({local, ?MODULE}, ?MODULE, [], []) of
{ok, _} = Success ->
?Info("~p started!~n", [?MODULE]),
Success;
Error ->
?Error("~p failed to start ~p~n", [?MODULE, Error]),
Error
end.
init([]) ->
SchemaName = imem_meta:schema(),
case erlimem:open(local, SchemaName) of
{ok, Sess} ->
{ok, Vsn} = application:get_key(dderl,vsn),
case code:lib_dir(dderl) of
{error,bad_name} -> ?Info("Application not running from installation", []);
LibDir ->
ConfigPath = filename:join([LibDir,"..","..","releases",Vsn]),
case filelib:is_dir(ConfigPath) of
true ->
?Info("Adding system schema: ~p", [ConfigPath]),
Sess:run_cmd(create_sys_conf, [ConfigPath]);
false ->
?Info("Application not running from installation", [])
end
end,
TablesToBuild = [
{ddAdapter, record_info(fields, ddAdapter), ?ddAdapter, #ddAdapter{}}
, {ddInterface, record_info(fields, ddInterface), ?ddInterface, #ddInterface{}}
, {ddConn, record_info(fields, ddConn), ?ddConn, #ddConn{}}
, {ddCmd, record_info(fields, ddCmd), ?ddCmd, #ddCmd{}}
, {ddView, record_info(fields, ddView), ?ddView, #ddView{}}
, {ddDash, record_info(fields, ddDash), ?ddDash, #ddDash{}}
],
?Debug("tables to build: ~p", [TablesToBuild]),
build_tables_on_boot(Sess, TablesToBuild),
Sess:run_cmd(write, [ddInterface, #ddInterface{id = ddjson, fullName = <<"DDerl">>}]),
% Initializing adapters (all the *_adapter modules compiled with dderl)
% doesn't include dynamically built adapters
{ok, AdaptMods} = application:get_key(dderl, modules),
Adapters = [A || A <- AdaptMods, re:run(erlang:atom_to_binary(A, utf8), ".*_adapter$") =/= nomatch],
[gen_server:cast(?MODULE, {init_adapter, Adapter}) || Adapter <- Adapters],
?Info("Available adapters ~p", [Adapters]),
D3Templates = [{dderl, filename:join(dderl:priv_dir(), "d3_templates")}],
?Info("Default d3 templates directory ~p", [D3Templates]),
{ok, #state{sess=Sess, schema=SchemaName, d3_templates=D3Templates}};
{error, Reason} ->
?Error("Failed to start : ~p", [Reason]),
{stop, Reason};
Else ->
?Error("Failed to start : ~p", [Else]),
{stop, Else}
end.
-spec build_tables_on_boot({atom(), pid()}, [tuple()]) -> ok.
build_tables_on_boot(_, []) -> ok;
build_tables_on_boot(Sess, [{N, Cols, Types, Default}|R]) ->
Sess:run_cmd(init_create_check_table, [N, {Cols, Types, Default}, []]),
build_tables_on_boot(Sess, R).
handle_call({add_connect, Conn}, _From, #state{sess=Sess} = State) ->
{reply, add_connect_internal(Sess, Sess, Conn), State};
handle_call({add_connect, UserSess, Conn}, _From, #state{sess=DalSess} = State) ->
{reply, add_connect_internal(UserSess, DalSess, Conn), State};
handle_call({get_connects, UserSess, UserId}, _From, #state{sess = DalSess} = State) ->
case check_cmd_select(UserSess, [ddConn, [{'$1', [], ['$_']}]]) of
{error, _} = Error ->
{reply, Error, State};
AllCons ->
case UserSess:run_cmd(have_permission, [[?MANAGE_CONNS]]) of
true -> Cons = [C#ddConn{owner = get_name(DalSess, C#ddConn.owner)} || C <- AllCons];
_ ->
Cons = [C#ddConn{owner = get_name(DalSess, C#ddConn.owner)}
|| C <- AllCons, conn_permission(UserSess, UserId, C)]
end,
{reply, Cons, State}
end;
handle_call({update_command, Id, Owner, Name, Sql, Opts}, _From, #state{sess=Sess} = State) ->
{reply, update_command(Sess, Id, Owner, Name, Sql, Opts), State};
handle_call({update_command, Id, Owner, Name, Sql, Conns, Opts}, _From, #state{sess=Sess} = State) ->
{reply, update_command(Sess, Id, Owner, Name, Sql, Conns, Opts), State};
handle_call({add_command, Owner, Adapter, Name, Cmd, Conn, Opts}, _From, #state{sess=Sess} = State) ->
{reply, add_command(Sess, Owner, Adapter, Name, Cmd, Conn, Opts), State};
handle_call({add_adapter_to_cmd, CmdId, Adapter}, _From, #state{sess=Sess} = State) ->
{reply, add_adapter_to_cmd(Sess, CmdId, Adapter), State};
handle_call({add_view, Owner, Name, CmdId, ViewsState}, _From, #state{sess=Sess} = State) ->
{reply, add_view(Sess, Owner, Name, CmdId, ViewsState), State};
handle_call({get_view, ViewId}, _From, #state{sess = Sess} = State) ->
{reply, get_view(Sess, ViewId), State};
handle_call({get_view, Name, Adapter, Owner}, _From, #state{sess=Sess} = State) ->
{reply, get_view(Sess, Name, Adapter, Owner), State};
handle_call({add_d3_templates_path, Entry}, _From, #state{d3_templates=D3Templates} = State) ->
{reply, ok, State#state{d3_templates=[Entry | D3Templates]}};
handle_call(get_d3_templates, _From, #state{d3_templates=D3Templates} = State) ->
{reply, D3Templates, State};
handle_call({get_d3_templates_path, Application}, _From, #state{d3_templates=D3Templates} = State) ->
Entry = proplists:get_value(Application, D3Templates),
{reply, Entry, State};
handle_call(get_host_app, _From, #state{host_app = undefined} = State) ->
HostApp =
lists:foldl(
fun({App,_,_}, <<>>) ->
{ok, Apps} = application:get_key(App, applications),
case lists:member(dderl, Apps) of
true -> atom_to_binary(App, utf8);
_ -> <<>>
end;
(_, App) -> App
end, <<>>, application:which_applications()),
{reply, HostApp, State#state{host_app = HostApp}};
handle_call(get_host_app, _From, #state{host_app = HostApp} = State) ->
{reply, HostApp, State};
handle_call(Req,From,State) ->
?Info("unknown call req ~p from ~p~n", [Req, From]),
{reply, ok, State}.
handle_cast({add_adapter, Id, FullName}, #state{sess=Sess} = State) ->
Adp = #ddAdapter{id=Id,fullName=FullName},
Sess:run_cmd(write, [ddAdapter, Adp]),
?Debug("add_adapter written ~p", [Adp]),
{noreply, State};
handle_cast({init_adapter, Adapter}, State) ->
spawn(fun() ->
Deps = Adapter:get_deps(),
?Info("checking for ~p dependencies: ~p", [Adapter, Deps]),
case check_dependencies(Deps) of
true ->
?Info("Dependencies found, initializing adapter ~p", [Adapter]),
Adapter:init();
false ->
?Info("Some dependencies of ~p missing, it will be excluded", [Adapter])
end
end),
{noreply, State};
handle_cast(Req,State) ->
?Debug("unknown cast ~p", [Req]),
{noreply, State}.
handle_info(Req,State) ->
?Debug("unknown info ~p", [Req]),
{noreply, State}.
terminate(Reason, #state{sess = Sess}) ->
?Debug("terminating, reason ~p", [Reason]),
Sess:close(),
ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
format_status(_Opt, [_PDict, _State]) -> ok.
%% Helper functions %%
-spec is_local_query(binary()) -> boolean().
is_local_query(Qry) ->
SysTabs = [erlang:atom_to_binary(Dt, utf8) || Dt <- [ddAdapter,ddInterface,ddConn,ddCmd,ddView,ddDash]],
% Example estructure for a query with joins and alias
SELECT * from tab1 a INNER JOIN tab2 on a = b INNER JOIN tab3 on c = d , tab4 f , tab2 , tab3 b INNER JOIN tab2 on a1 = b4 , tab5 INNER JOIN tab2 on a1 = b4
% {select,[{hints,<<>>},
% {opt,<<>>},
% {fields,[<<"*">>]},
% {into,[]},
% {from,[{{as,<<"tab1">>,<<"a">>},
[ { " > > } } } ,
% {join_inner,<<"tab3">>,{on,{'=',<<"c">>,<<"d">>}}}]},
% {as,<<"tab4">>,<<"f">>},
% <<"tab2">>,
% {{as,<<"tab3">>,<<"b">>},
[ { " > > } } } ] } ,
% {<<"tab5">>,
[ { " > > } } } ] } ] } ,
% {where,{}},
% {'group by',[]},
% {having,{}},
% {'order by',[]}]}
case sqlparse:parsetree(Qry) of
{ok, [{{select,QOpts},_}|_]} ->
case lists:keyfind(from, 1, QOpts) of
{from, Tables} ->
lists:foldl(fun(T,_) ->
Tab = case T of
{{_,T1,_}, _} when is_binary(T1) -> T1;
{T1, _} when is_binary(T1) -> T1;
{_,T1,_} when is_binary(T1) -> T1;
T when is_binary(T) -> T;
_ -> T
end,
lists:member(Tab, SysTabs)
end,
true,
Tables);
_ -> false
end;
{lex_error, Error} ->
?Error("SQL lexer error ~p", [Error]),
false;
{parse_error, Error} ->
?Error("SQL parser error ~p", [Error]),
false;
_ ->
false
end.
-spec can_connect_locally({atom(), pid()}) -> boolean().
can_connect_locally(Sess) ->
Sess:run_cmd(have_permission, [[?USE_LOCAL_CONN]]) == true.
-spec conn_permission({atom(), pid()}, ddEntityId(), #ddConn{}) -> boolean().
conn_permission(_Sess, UserId, #ddConn{owner=UserId}) -> true; %% If it is the owner always allow usage.
conn_permission(Sess, _UserId, #ddConn{id=ConnId, owner=system}) ->
Sess:run_cmd(have_permission, [?USE_SYS_CONNS]) orelse %% If it can use system connections.
Sess:run_cmd(have_permission, [?USE_CONN(ConnId)]); %% or maybe only this particular connection.
conn_permission(Sess, _UserId, #ddConn{id=ConnId}) ->
Sess:run_cmd(have_permission, [?USE_CONN(ConnId)]). %% Access to a connection by id.
-spec add_connect_internal({atom(), pid()}, {atom(), pid()}, #ddConn{}) -> #ddConn{} | {error, binary()}.
add_connect_internal(UserSess, DalSess, #ddConn{schm = undefined} = Conn) ->
{ok, SchemaName} = application:get_env(imem, mnesia_schema_name),
add_connect_internal(UserSess, DalSess, Conn#ddConn{schm = atom_to_binary(SchemaName, utf8)});
add_connect_internal(UserSess, DalSess, #ddConn{id = null, owner = Owner} = Conn) ->
case UserSess:run_cmd(select, [ddConn, [{#ddConn{name='$1', owner='$2', id='$3', _='_'}
, [{'=:=','$1',Conn#ddConn.name},{'=:=','$2',Owner}]
, ['$_']}]]) of
{[#ddConn{id = Id} = OldCon | _], true} ->
%% User is updating is own connection no need for privileges
NewCon = Conn#ddConn{id=Id},
if OldCon == NewCon -> %% Connection not changed
Conn#ddConn{owner = get_name(DalSess, Conn#ddConn.owner)};
true ->
?Info("replacing connection ~p, owner ~p", [NewCon, Owner]),
check_save_conn(UserSess, DalSess, update, {OldCon, NewCon})
end;
_ ->
HavePermission = (UserSess =:= DalSess) orelse
UserSess:run_cmd(have_permission, [[manage_system, ?MANAGE_CONNS, ?CREATE_CONNS]]),
case HavePermission of
true ->
Id = erlang:phash2(crypto:strong_rand_bytes(16)),
NewCon = Conn#ddConn{id=Id},
?Info("adding new connection ~p", [NewCon]),
check_save_conn(UserSess, DalSess, insert, NewCon);
_ -> {error, <<"Create connections unauthorized">>}
end
end;
add_connect_internal(UserSess, DalSess, #ddConn{id = OldId, owner = Owner} = Conn)
when is_integer(OldId) ->
case UserSess:run_cmd(select, [ddConn, [{#ddConn{id=OldId, _='_'}, [], ['$_']}]]) of
{[#ddConn{owner = OldOwner} = OldCon], true} ->
%% Save the conn only if there is some difference.
case is_same_conn(OldCon, Conn) of
true ->
%% If the connection is not changed then do not save a copy.
OldCon#ddConn{owner = get_name(DalSess, OldCon#ddConn.owner)};
false ->
if
Owner =:= OldOwner -> %% Same owner update the connection.
check_save_conn(UserSess, DalSess, update, {OldCon, Conn});
true -> %% Different owner, create a copy.
add_connect_internal(UserSess, DalSess, Conn#ddConn{id = null})
end
end;
{[], true} ->
%% Connection with id not found, adding a new one.
add_connect_internal(UserSess, DalSess, Conn#ddConn{id = null});
Result ->
?Error("Error getting connection with id ~p, Result:~n~p", [OldId, Result]),
{error, <<"Error saving the connection">>}
end.
is_same_conn(#ddConn{access = Access1} = Conn1, Conn2) when not is_map(Access1) ->
is_same_conn(Conn1#ddConn{access = maps:from_list(Access1)}, Conn2);
is_same_conn(Conn1, #ddConn{access = Access2} = Conn2) when not is_map(Access2) ->
is_same_conn(Conn1, Conn2#ddConn{access = maps:from_list(Access2)});
is_same_conn(Conn1, Conn2) ->
Conn1#ddConn{access = maps:remove(<<"user">>,maps:remove(user,Conn1#ddConn.access))} ==
Conn2#ddConn{owner = Conn1#ddConn.owner,
access = maps:remove(<<"user">>,maps:remove(user, Conn2#ddConn.access))}.
-spec check_save_conn({atom(), pid()}, {atom(), pid()}, atom(), #ddConn{}) -> #ddConn{} | {error, binary()}.
check_save_conn(UserSess, DalSess, Op, Conn0) ->
Conn = case Conn0 of
Conn0 when is_record(Conn0, ddConn) ->
Conn0#ddConn{access = maps:remove(password, pl2m(Conn0#ddConn.access))};
{C1, C2} when is_record(C1, ddConn), is_record(C2, ddConn) ->
{C1, C2#ddConn{access = maps:remove(password, pl2m(C2#ddConn.access))}}
end,
case UserSess:run_cmd(Op, [ddConn, Conn]) of
{error, {{Exception, M}, _Stacktrace} = Error} ->
?Error("failed to ~p connection with ~p : ~n~p", [Op, Conn, Error]),
Msg = list_to_binary(atom_to_list(Exception) ++ ": " ++
lists:flatten(io_lib:format("~p", [M]))),
{error, Msg};
{error, Error} ->
?Error("~p connection failed: ~p", [Op, Error]),
Msg = list_to_binary(lists:flatten(io_lib:format("~p", [Error]))),
{error, Msg};
#ddConn{} = SavedConn ->
SavedConn#ddConn{owner = get_name(DalSess, SavedConn#ddConn.owner)};
InvalidReturn ->
?Error("Invalid return on ~p connection ~p: The result:~n~p", [Op, Conn, InvalidReturn]),
{error, <<"Error saving the connection (Invalid value returned from DB)">>}
end.
-spec pl2m([tuple()] | map()) -> map().
pl2m(Map) when is_map(Map) -> Map;
pl2m([{_,_}|_] = PL) -> maps:from_list(PL).
-spec check_cmd_select({atom(), pid()}, list()) -> {error, binary()} | list().
check_cmd_select(UserSess, Args) ->
case UserSess:run_cmd(select, Args) of
{error, {{Exception, M}, _Stacktrace} = Error} ->
?Error("select failed : ~n~p", [Error]),
Msg = list_to_binary(atom_to_list(Exception) ++ ": " ++
lists:flatten(io_lib:format("~p", [M]))),
{error, Msg};
{error, Error} ->
?Error("select failed: ~p", [Error]),
Msg = list_to_binary(lists:flatten(io_lib:format("~p", [Error]))),
{error, Msg};
{Result, true} ->
Result;
InvalidReturn ->
?Error("Invalid return on select, args ~p: The result:~n~p", [Args, InvalidReturn]),
{error, <<"Error on select (Invalid value returned from DB)">>}
end.
-spec check_dependencies([atom()]) -> boolean().
check_dependencies([]) -> true;
check_dependencies([Dep | Rest]) ->
case code:priv_dir(Dep) of
{error, bad_name} -> false;
_ -> check_dependencies(Rest)
end.
-spec filter_view_result([#ddView{}], {atom(), pid()}, atom()) -> #ddView{} | {error, binary()}.
filter_view_result([], _, _) -> undefined;
filter_view_result([V | Views], Sess, Adapter) ->
case check_cmd_select(Sess, [ddCmd, [{#ddCmd{id=V#ddView.cmd, adapters='$1', _='_'}, [], ['$1']}]]) of
{error, _} = Error ->
Error;
[C] ->
case lists:member(Adapter, C) of
true -> V;
false -> filter_view_result(Views, Sess, Adapter)
end;
_ ->
?Error("Command id ~p not found for view ~p, with id ~p", [V#ddView.cmd, V#ddView.name, V#ddView.id]),
{error, iolist_to_binary(["Command not found for view ", V#ddView.name])}
end.
-spec get_restartable_apps() -> [atom()].
get_restartable_apps() ->
{ok, CurrApp} = application:get_application(?MODULE),
?RESTARTAPPS(CurrApp).
-spec process_login(map(), any(),
#{auth => fun((any()) -> ok | {any(), list()}),
connInfo => map(),
stateUpdateUsr => fun((any(), any()) -> any()),
stateUpdateSKey => fun((any(), any()) -> any()),
relayState => fun((any(), any()) -> any()),
urlPrefix => list()}) -> ok | map().
process_login(#{<<"smsott">> := Token} = Body, State,
#{auth := AuthFun} = Ctx) ->
process_login_reply(AuthFun({smsott,Token}), Body, Ctx, State);
process_login(#{<<"user">>:=User, <<"password">>:=Password} = Body, State,
#{stateUpdateUsr := StateUpdateFun, auth := AuthFun} = Ctx) ->
process_login_reply(AuthFun({pwdmd5,
{User, list_to_binary(Password)}}),
Body, Ctx, StateUpdateFun(State, User));
process_login(#{<<"samluser">>:=User} = Body, State,
#{stateUpdateUsr := StateUpdateFun, auth := AuthFun} = Ctx)
when is_function(StateUpdateFun, 2), is_function(AuthFun, 1) ->
process_login_reply(AuthFun({saml, User}), Body, Ctx,
StateUpdateFun(State, User));
process_login(Body, State, #{connInfo := ConnInfo, auth := AuthFun} = Ctx)
when is_map(ConnInfo), is_function(AuthFun, 1) ->
process_login_reply(AuthFun({access, ConnInfo}), Body, Ctx, State).
process_login_reply(ok, _Body, _Ctx, State) -> {ok, State};
process_login_reply({ok, []}, _Body, _Ctx, State) -> {ok, State};
process_login_reply({SKey, []}, _Body, #{stateUpdateSKey := StateUpdateFun},
State) when is_function(StateUpdateFun, 2) ->
{ok, StateUpdateFun(State, SKey)};
process_login_reply({ok, [{pwdmd5, Data}|_]}, _Body, _Ctx, State) ->
{#{pwdmd5=>fix_login_data(Data)}, State};
process_login_reply({SKey, [{pwdmd5, Data}|_]}, _Body,
#{stateUpdateSKey := StateUpdateFun}, State)
when is_function(StateUpdateFun, 2) ->
{#{pwdmd5=>fix_login_data(Data)}, StateUpdateFun(State, SKey)};
process_login_reply({ok, [{smsott, Data}|_]}, _Body, _Ctx, State) ->
{#{smsott=>fix_login_data(Data)}, State};
process_login_reply({SKey, [{smsott, Data}|_]}, _Body,
#{stateUpdateSKey := StateUpdateFun}, State)
when is_function(StateUpdateFun, 2) ->
{#{smsott=>fix_login_data(Data)}, StateUpdateFun(State, SKey)};
process_login_reply({SKey, [{saml, _Data}|_]}, Body,
#{urlPrefix := UrlPrefix,
stateUpdateSKey := StateUpdateFun,
relayState := RelayStateFun}, State)
when is_function(RelayStateFun, 2), is_function(StateUpdateFun, 2) ->
#{<<"host_url">> := HostUrlBin} = Body,
HostUrl = binary_to_list(HostUrlBin),
{#{saml =>
fix_login_data(
#{form =>
dderl_saml_handler:fwdUrl(
HostUrl, HostUrl ++ UrlPrefix ++ dderl:get_sp_url_suffix(),
RelayStateFun)})},
if SKey == ok -> State;
true -> StateUpdateFun(State, SKey)
end}.
fix_login_data(#{accountName:=undefined}=Data) ->
fix_login_data(Data#{accountName=><<"">>});
fix_login_data(Data) -> Data.
Functions used to extract rows from fsm using ets directly .
%% Used by data_sender and csv_export_buffer.
-spec rows_from(ets:tab(), term(), pos_integer()) -> [term()].
rows_from(TableId, Key, Limit) ->
ets:select(TableId, [{'$1', [{'>=',{element,1,'$1'}, {const, Key}}],['$_']}], Limit).
-spec expand_rows([term()], ets:tab(), fun(), [integer()]) -> [[binary()]].
expand_rows([], _TableId, _RowFun, _ColumnPos) -> [];
expand_rows([{_, Id} | RestRows], TableId, RowFun, ColumnPos) ->
Row = lists:nth(1, ets:lookup(TableId, Id)),
expand_rows([Row | RestRows], TableId, RowFun, ColumnPos);
expand_rows([{_I,_Op, RK} | RestRows], TableId, RowFun, ColumnPos) ->
ExpandedRow = list_to_tuple(RowFun(RK)), %% As tuple for faster access.
SelectedColumns = [element(Col, ExpandedRow) || Col <- ColumnPos],
[SelectedColumns | expand_rows(RestRows, TableId, RowFun, ColumnPos)];
expand_rows([FullRowTuple | RestRows], TableId, RowFun, ColumnPos) ->
SelectedColumns = [element(3+Col, FullRowTuple) || Col <- ColumnPos],
[SelectedColumns | expand_rows(RestRows, TableId, RowFun, ColumnPos)].
-spec is_proxy(list(), map()) -> boolean().
is_proxy(AppId, NetCtx) ->
ProxyCheckFun = ?GET_CONFIG(isProxyCheckFun, [AppId], <<"fun(NetCtx) -> false end">>, "Function checks if user is coming through a proxy or not"),
CacheKey = {?MODULE, isProxyCheckFun, ProxyCheckFun},
case imem_cache:read(CacheKey) of
[] ->
case imem_datatype:io_to_fun(ProxyCheckFun) of
PF when is_function(PF, 1) ->
imem_cache:write(CacheKey, PF),
exec_is_proxy_fun(PF, NetCtx);
_ ->
?Error("Not a valid is proxy fun configured"),
false
end;
[PF] when is_function(PF, 1) -> exec_is_proxy_fun(PF, NetCtx);
_ -> false
end.
-spec exec_is_proxy_fun(reference(), map()) -> boolean().
exec_is_proxy_fun(Fun, NetCtx) ->
case catch Fun(NetCtx) of
false -> false;
true -> true;
Error ->
?Error("proxy check fail : ~p", [Error]),
false
end.
| null | https://raw.githubusercontent.com/K2InformaticsGmbH/dderl/84697547fe8009db7964baa4eceb876fd78512a0/src/dderl_dal.erl | erlang | Privileges
TODO: Validate result...
TODO: At the moment the command and the view always have the same owner.
Check for authorization.
TODO: Handle multiple adapters.
TODO: At the moment the command and the view always have the same owner.
Check for authorization.
TODO: At the moment the command and the view always have the same owner.
Check for authorization.
Only one view with the command, so the command is also deleted
Initializing adapters (all the *_adapter modules compiled with dderl)
doesn't include dynamically built adapters
Helper functions %%
Example estructure for a query with joins and alias
{select,[{hints,<<>>},
{opt,<<>>},
{fields,[<<"*">>]},
{into,[]},
{from,[{{as,<<"tab1">>,<<"a">>},
{join_inner,<<"tab3">>,{on,{'=',<<"c">>,<<"d">>}}}]},
{as,<<"tab4">>,<<"f">>},
<<"tab2">>,
{{as,<<"tab3">>,<<"b">>},
{<<"tab5">>,
{where,{}},
{'group by',[]},
{having,{}},
{'order by',[]}]}
If it is the owner always allow usage.
If it can use system connections.
or maybe only this particular connection.
Access to a connection by id.
User is updating is own connection no need for privileges
Connection not changed
Save the conn only if there is some difference.
If the connection is not changed then do not save a copy.
Same owner update the connection.
Different owner, create a copy.
Connection with id not found, adding a new one.
Used by data_sender and csv_export_buffer.
As tuple for faster access. | -module(dderl_dal).
-behavior(gen_server).
-include("dderl.hrl").
-export([init/1
,start_link/0
,handle_call/3
,handle_cast/2
,handle_info/2
,terminate/2
,code_change/3
,format_status/2
]).
-export([get_adapters/1
,add_adapter/2
,add_command/7
,update_command/6
,update_command/7
,add_view/5
,update_view/4
,rename_view/3
,delete_view/2
,add_connect/2
,get_connects/2
,del_conn/3
,get_command/2
,get_view/4
,get_view/2
,is_local_query/1
,can_connect_locally/1
,save_dashboard/5
,rename_dashboard/3
,delete_dashboard/2
,get_dashboards/2
,add_adapter_to_cmd/3
,user_name/1
,get_restartable_apps/0
,process_login/3
,rows_from/3
,expand_rows/4
,add_d3_templates_path/2
,get_d3_templates/0
,get_d3_templates_path/1
,get_host_app/0
,is_proxy/2
]).
-record(state, { schema :: term()
, sess :: {atom(), pid()}
, d3_templates :: list()
, host_app :: binary()
}).
-define(MANAGE_CONNS, {dderl, conn, manage}).
-define(CREATE_CONNS, {dderl, conn, create}).
-define(USE_SYS_CONNS, {dderl, conn, {owner, system}, use}).
-define(USE_CONN(__ConnId), {dderl, conn, {conn, __ConnId}, use}).
-define(USE_LOCAL_CONN, {dderl, conn, local, use}).
Validate this permission .
-define(USE_ADAPTER, {dderl, adapter, {id, __AdaptId}, use}).
-spec add_adapter(atom(), binary()) -> ok.
add_adapter(Id, FullName) -> gen_server:cast(?MODULE, {add_adapter, Id, FullName}).
-spec add_connect({atom(), pid()} | undefined, #ddConn{}) -> integer() | {error, binary()}.
add_connect(undefined, #ddConn{} = Conn) -> gen_server:call(?MODULE, {add_connect, Conn});
add_connect(Sess, #ddConn{} = Conn) -> gen_server:call(?MODULE, {add_connect, Sess, Conn}).
-spec del_conn({atom(), pid()}, ddEntityId(), integer()) -> ok | no_permission.
del_conn(Sess, UserId, ConId) ->
HasAll = (Sess:run_cmd(have_permission, [[?MANAGE_CONNS]]) == true),
if HasAll ->
ok = Sess:run_cmd(delete, [ddConn, ConId]),
?Info("user ~p deleted connection ~p", [UserId, ConId]),
ok;
true ->
case Sess:run_cmd(select, [ddConn, [{#ddConn{id=ConId,owner=UserId,_='_'},[],['$_']}]]) of
{[_|_], true} ->
ok = Sess:run_cmd(delete, [ddConn, ConId]),
?Info("user ~p deleted connection ~p", [UserId, ConId]),
ok;
_ ->
?Error("user ~p doesn't have permission to delete connection ~p", [UserId, ConId]),
no_permission
end
end.
-spec get_connects({atom(), pid()}, ddEntityId()) -> [#ddConn{}] | {error, binary()}.
get_connects(Sess, UserId) -> gen_server:call(?MODULE, {get_connects, Sess, UserId}).
-spec add_command({atom(), pid()} | undefined, ddEntityId(), atom(), binary(), binary(), list() | undefined, term()) -> ddEntityId().
add_command(undefined, Owner, Adapter, Name, Cmd, Conn, Opts) ->
gen_server:call(?MODULE, {add_command, Owner, Adapter, Name, Cmd, Conn, Opts});
add_command(Sess, Owner, Adapter, Name, Cmd, undefined, Opts) ->
case is_local_query(Cmd) of
true -> Conn = local;
false -> Conn = []
end,
add_command(Sess, Owner, Adapter, Name, Cmd, Conn, Opts);
add_command(Sess, Owner, Adapter, Name, Cmd, Conn, Opts) ->
Id = erlang:phash2(make_ref()),
?Debug("add_command ~p new id ~p", [Name, Id]),
NewCmd = #ddCmd { id = Id
, name = Name
, owner = Owner
, adapters = [Adapter]
, command = Cmd
, conns = Conn
, opts = Opts},
Sess:run_cmd(insert, [ddCmd, NewCmd]),
?Debug("add_command inserted ~p", [NewCmd]),
Id.
-spec update_command({atom(), pid()} | undefined, ddEntityId(), ddEntityId(), binary(), binary(), term()) -> ddEntityId().
update_command(undefined, Id, Owner, Name, Sql, Opts) -> gen_server:call(?MODULE, {update_command, Id, Owner, Name, Sql, Opts});
update_command(Sess, Id, Owner, Name, Sql, Opts) ->
?Debug("update command ~p replacing id ~p", [Name, Id]),
{[Cmd], true} = Sess:run_cmd(select, [ddCmd, [{#ddCmd{id = Id, _='_'}, [], ['$_']}]]),
NewCmd = #ddCmd { id = Id
, name = Name
, owner = Owner
, adapters = Cmd#ddCmd.adapters
, command = Sql
, conns = Cmd#ddCmd.conns
, opts = Opts},
Sess:run_cmd(write, [ddCmd, NewCmd]),
Id.
-spec update_command({atom(), pid()} | undefined, ddEntityId(), ddEntityId(), binary(), binary(), list(), term()) -> ddEntityId().
update_command(undefined, Id, Owner, Name, Sql, Conns, Opts) -> gen_server:call(?MODULE, {update_command, Id, Owner, Name, Sql, Conns, Opts});
update_command(Sess, Id, Owner, Name, Sql, Conns, Opts) ->
?Debug("update command ~p replacing id ~p", [Name, Id]),
{[Cmd], true} = Sess:run_cmd(select, [ddCmd, [{#ddCmd{id = Id, _='_'}, [], ['$_']}]]),
NewCmd = #ddCmd { id = Id
, name = Name
, owner = Owner
, adapters = Cmd#ddCmd.adapters
, command = Sql
, conns = Conns
, opts = Opts},
Sess:run_cmd(write, [ddCmd, NewCmd]),
Id.
-spec user_name(atom() | integer() | binary()) -> binary().
user_name(system) -> <<"system">>;
user_name(Name) when is_binary(Name) -> Name;
user_name(Id) when is_integer(Id) ->
{[Name],true} = imem_meta:select(ddAccount, [{#ddAccount{id=Id,name='$1',_='_'},[],['$1']}]),
Name.
-spec add_view({atom(), pid()} | undefined, ddEntityId(), binary(), ddEntityId(), #viewstate{}) -> ddEntityId().
add_view(undefined, Owner, Name, CmdId, ViewsState) ->
gen_server:call(?MODULE, {add_view, Owner, Name, CmdId, ViewsState});
add_view(Sess, Owner, Name, CmdId, ViewsState) ->
Id = case Sess:run_cmd(select, [ddView, [{#ddView{name=Name, cmd = CmdId, id='$1', owner=Owner, _='_'}
, []
, ['$1']}]]) of
{[Id0|_], true} ->
?Debug("add_view ~p replacing id ~p ~p~n", [Name, Id0, Owner]),
Id0;
_ ->
Id1 = erlang:phash2(make_ref()),
?Debug("add_view ~p new id ~p", [Name, Id1]),
Id1
end,
NewView = #ddView { id = Id
, name = Name
, owner = Owner
, cmd = CmdId
, state = ViewsState},
?Debug("add_view written ~p", [NewView]),
Id.
-spec update_view({atom(), pid()}, integer(), #viewstate{}, binary()) -> integer() | {error, binary()}.
update_view(Sess, ViewId, ViewsState, Qry) when is_integer(ViewId) ->
case Sess:run_cmd(select, [ddView, [{#ddView{id=ViewId, _='_'}, [], ['$_']}]]) of
{[OldView], true} ->
?Debug("The oldView ~p and the session ~p", [OldView, Sess]),
Cmd = get_command(Sess, OldView#ddView.cmd),
?Debug("The old cmd ~p", [Cmd]),
update_command(Sess, Cmd#ddCmd.id, Cmd#ddCmd.owner, Cmd#ddCmd.name, Qry, Cmd#ddCmd.opts),
case ViewsState of
#viewstate{table_layout=[], column_layout=[]} ->
NewView = OldView;
#viewstate{table_layout=[]} ->
#viewstate{table_layout=OldTableLay} = OldView#ddView.state,
NewState = ViewsState#viewstate{table_layout=OldTableLay},
NewView = OldView#ddView{state=NewState};
#viewstate{column_layout=[]} ->
#viewstate{column_layout=OldColumLay} = OldView#ddView.state,
NewState = ViewsState#viewstate{column_layout=OldColumLay},
NewView = OldView#ddView{state=NewState};
#viewstate{} ->
NewView = OldView#ddView{state=ViewsState}
end,
Sess:run_cmd(write, [ddView, NewView]),
?Debug("update_view written ~p", [NewView]),
ViewId;
_ ->
?Error("Unable to get the view to update ~p", [ViewId]),
{error, <<"Unable to get the view to update">>}
end.
-spec rename_view({atom(), pid()}, integer(), binary()) -> ok | {error, binary()}.
rename_view(Sess, ViewId, ViewName) ->
case Sess:run_cmd(select, [ddView, [{#ddView{id=ViewId, _='_'}, [], ['$_']}]]) of
{[OldView], true} ->
case Sess:run_cmd(select, [ddCmd, [{#ddCmd{id=OldView#ddView.cmd, _='_'}, [], ['$_']}]]) of
{[OldCmd], true} ->
Sess:run_cmd(write, [ddCmd, OldCmd#ddCmd{name = ViewName}]),
Sess:run_cmd(write, [ddView, OldView#ddView{name = ViewName}]),
ok;
_ ->
?Error("Unable to get the command to rename ~p", [OldView#ddView.cmd]),
{error, <<"Unable to find the command to rename">>}
end;
_ ->
?Error("Unable to get the view to rename ~p", [ViewId]),
{error, <<"Unable to find the view to rename">>}
end.
-spec delete_view({atom(), pid()}, integer()) -> integer() | {error, binary()}.
delete_view(Sess, ViewId) ->
case Sess:run_cmd(select, [ddView, [{#ddView{id=ViewId, _='_'}, [], ['$_']}]]) of
{[OldView], true} ->
case Sess:run_cmd(select, [ddView, [{#ddView{cmd=OldView#ddView.cmd, _='_'}, [], ['$_']}]]) of
{[OldView], true} ->
case Sess:run_cmd(select, [ddCmd, [{#ddCmd{id=OldView#ddView.cmd, _='_'}, [], ['$_']}]]) of
{[OldCmd], true} ->
ok = Sess:run_cmd(delete, [ddCmd, OldCmd#ddCmd.id]);
_ -> ?Info("No command found to delete ~p", [OldView#ddView.cmd])
end;
_ -> ok
end,
ok = Sess:run_cmd(delete, [ddView, OldView#ddView.id]),
ok;
_ ->
?Error("Unable to get the view to delete ~p", [ViewId]),
{error, <<"Unable to find the view to delete">>}
end.
-spec get_adapters({atom(), pid()}) -> {error, binary()} | [#ddAdapter{}].
get_adapters(Sess) ->
?Debug("get_adapters"),
check_cmd_select(Sess, [ddAdapter, [{'$1', [], ['$_']}]]).
-spec get_command({atom(), pid()}, ddEntityId() | binary()) -> #ddCmd{} | {error, binary()}.
get_command(Sess, IdOrName) ->
?Debug("get_command for id ~p", [IdOrName]),
CmdsResult =
case IdOrName of
Id when is_integer(Id) ->
check_cmd_select(Sess, [ddCmd, [{#ddCmd{id=Id, _='_'}, [], ['$_']}]]);
Name ->
check_cmd_select(Sess, [ddCmd, [{#ddCmd{name=Name, _='_'}, [], ['$_']}]])
end,
case CmdsResult of
{error, _} = Error -> Error;
[Cmd | _Ignored] -> Cmd;
[] -> #ddCmd{opts=[]}
end.
-spec get_view({atom(), pid()}, ddEntityId()) -> {error, binary()} | #ddView{} | undefined .
get_view(undefined, ViewId) -> gen_server:call(?MODULE, {get_view, ViewId});
get_view(Sess, ViewId) ->
?Debug("get ddView by id ~p", [ViewId]),
case check_cmd_select(Sess, [ddView, [{#ddView{id = ViewId, _ = '_'}, [], ['$_']}]]) of
{error, _} = Error -> Error;
[View] -> View;
Result ->
?Error("ddView with the id ~p was not found, select result: ~n~p", [ViewId, Result]),
undefined
end.
-spec get_view({atom(), pid()} | undefined, binary(), atom(), ddEntityId() | '_') -> #ddView{} | undefined.
get_view(undefined, Name, Adapter, Owner) -> gen_server:call(?MODULE, {get_view, Name, Adapter, Owner});
get_view(Sess, Name, Adapter, Owner) ->
?Debug("get_view ~p", [Name]),
case check_cmd_select(Sess, [ddView,[{#ddView{name=Name, owner=Owner, _='_'}, [], ['$_']}]]) of
{error, _} = Error -> Error;
Views ->
case filter_view_result(Views, Sess, Adapter) of
{error, _} = Error -> Error;
View -> View
end
end.
-spec save_dashboard({atom(), pid()}, ddEntityId(), integer(), binary(), list()) -> integer() | {error, binary()}.
save_dashboard(Sess, Owner, -1, Name, Views) ->
NewId = erlang:phash2(make_ref()),
case Sess:run_cmd(select, [ddDash, [{#ddDash{id=NewId, name='$1', _='_'}, [], ['$1']}]]) of
{[DashName], true} ->
?Debug("Save dashboard colision saving the dashboard ~p with id ~p", [DashName, NewId]),
save_dashboard(Sess, Owner, -1, Name, Views);
_ ->
save_dashboard(Sess, Owner, NewId, Name, Views)
end;
save_dashboard(Sess, Owner, DashId, Name, Views) ->
NewDash = #ddDash{id = DashId, name = Name, owner = Owner, views = Views},
Sess:run_cmd(write, [ddDash, NewDash]),
?Debug("dashboard saved ~p", [NewDash]),
DashId.
-spec rename_dashboard({atom(), pid()}, integer(), binary()) -> binary() | {error, binary()}.
rename_dashboard(Sess, Id, Name) ->
case check_cmd_select(Sess, [ddDash, [{#ddDash{id=Id, _='_'}, [], ['$_']}]]) of
{error, _} = Error -> Error;
[] -> {error, <<"Dashboard not found">>};
[OldDash = #ddDash{}] ->
Sess:run_cmd(write, [ddDash, OldDash#ddDash{name=Name}]),
Name
end.
-spec delete_dashboard({atom(), pid()}, integer()) -> integer() | {error, binary()}.
delete_dashboard(Sess, Id) ->
case check_cmd_select(Sess, [ddDash, [{#ddDash{id=Id, _='_'}, [], ['$_']}]]) of
{error, _} = Error -> Error;
[] -> {error, <<"Dashboard not found">>};
[#ddDash{id = Id}] ->
ok = Sess:run_cmd(delete, [ddDash, Id]),
Id
end.
-spec get_dashboards({atom(), pid()}, ddEntityId()) -> {error, binary()} | [#ddDash{}].
get_dashboards(Sess, Owner) ->
check_cmd_select(Sess, [ddDash, [{#ddDash{owner = Owner, _='_'}, [], ['$_']}]]).
-spec get_name({atom(), pid()}, ddEntityId()) -> ddIdentity().
get_name(Sess, UserId) ->
case Sess:run_cmd(select, [ddAccount, [{#ddAccount{id=UserId, name='$1', _='_'}, [], ['$1']}]]) of
{[Username], true} -> Username;
_ -> <<"">>
end.
-spec add_adapter_to_cmd({atom(), pid()} | undefined, ddEntityId(), atom()) -> ok | {error, binary()}.
add_adapter_to_cmd(undefined, CmdId, Adapter) ->
gen_server:call(?MODULE, {add_adapter_to_cmd, CmdId, Adapter});
add_adapter_to_cmd(Sess, CmdId, Adapter) ->
{[Cmd], true} = Sess:run_cmd(select, [ddCmd, [{#ddCmd{id = CmdId, _='_'}, [], ['$_']}]]),
case lists:member(Adapter, Cmd#ddCmd.adapters) of
false ->
NewAdapters = [Adapter|Cmd#ddCmd.adapters];
true ->
NewAdapters = Cmd#ddCmd.adapters
end,
Sess:run_cmd(write, [ddCmd, Cmd#ddCmd{adapters = NewAdapters}]),
CmdId.
-spec add_d3_templates_path(atom(), string()) -> ok.
add_d3_templates_path(Application, Path) ->
gen_server:call(?MODULE, {add_d3_templates_path, {Application, Path}}).
-spec get_d3_templates() -> [{atom(), string()}].
get_d3_templates() ->
gen_server:call(?MODULE, get_d3_templates).
-spec get_d3_templates_path(atom()) -> string().
get_d3_templates_path(Application) ->
gen_server:call(?MODULE, {get_d3_templates_path, Application}).
-spec get_host_app() -> binary().
get_host_app() ->
gen_server:call(?MODULE, get_host_app).
-spec start_link() -> {ok, pid()} | ignore | {error, term()}.
start_link() ->
?Info("~p starting...~n", [?MODULE]),
case gen_server:start_link({local, ?MODULE}, ?MODULE, [], []) of
{ok, _} = Success ->
?Info("~p started!~n", [?MODULE]),
Success;
Error ->
?Error("~p failed to start ~p~n", [?MODULE, Error]),
Error
end.
init([]) ->
SchemaName = imem_meta:schema(),
case erlimem:open(local, SchemaName) of
{ok, Sess} ->
{ok, Vsn} = application:get_key(dderl,vsn),
case code:lib_dir(dderl) of
{error,bad_name} -> ?Info("Application not running from installation", []);
LibDir ->
ConfigPath = filename:join([LibDir,"..","..","releases",Vsn]),
case filelib:is_dir(ConfigPath) of
true ->
?Info("Adding system schema: ~p", [ConfigPath]),
Sess:run_cmd(create_sys_conf, [ConfigPath]);
false ->
?Info("Application not running from installation", [])
end
end,
TablesToBuild = [
{ddAdapter, record_info(fields, ddAdapter), ?ddAdapter, #ddAdapter{}}
, {ddInterface, record_info(fields, ddInterface), ?ddInterface, #ddInterface{}}
, {ddConn, record_info(fields, ddConn), ?ddConn, #ddConn{}}
, {ddCmd, record_info(fields, ddCmd), ?ddCmd, #ddCmd{}}
, {ddView, record_info(fields, ddView), ?ddView, #ddView{}}
, {ddDash, record_info(fields, ddDash), ?ddDash, #ddDash{}}
],
?Debug("tables to build: ~p", [TablesToBuild]),
build_tables_on_boot(Sess, TablesToBuild),
Sess:run_cmd(write, [ddInterface, #ddInterface{id = ddjson, fullName = <<"DDerl">>}]),
{ok, AdaptMods} = application:get_key(dderl, modules),
Adapters = [A || A <- AdaptMods, re:run(erlang:atom_to_binary(A, utf8), ".*_adapter$") =/= nomatch],
[gen_server:cast(?MODULE, {init_adapter, Adapter}) || Adapter <- Adapters],
?Info("Available adapters ~p", [Adapters]),
D3Templates = [{dderl, filename:join(dderl:priv_dir(), "d3_templates")}],
?Info("Default d3 templates directory ~p", [D3Templates]),
{ok, #state{sess=Sess, schema=SchemaName, d3_templates=D3Templates}};
{error, Reason} ->
?Error("Failed to start : ~p", [Reason]),
{stop, Reason};
Else ->
?Error("Failed to start : ~p", [Else]),
{stop, Else}
end.
-spec build_tables_on_boot({atom(), pid()}, [tuple()]) -> ok.
build_tables_on_boot(_, []) -> ok;
build_tables_on_boot(Sess, [{N, Cols, Types, Default}|R]) ->
Sess:run_cmd(init_create_check_table, [N, {Cols, Types, Default}, []]),
build_tables_on_boot(Sess, R).
handle_call({add_connect, Conn}, _From, #state{sess=Sess} = State) ->
{reply, add_connect_internal(Sess, Sess, Conn), State};
handle_call({add_connect, UserSess, Conn}, _From, #state{sess=DalSess} = State) ->
{reply, add_connect_internal(UserSess, DalSess, Conn), State};
handle_call({get_connects, UserSess, UserId}, _From, #state{sess = DalSess} = State) ->
case check_cmd_select(UserSess, [ddConn, [{'$1', [], ['$_']}]]) of
{error, _} = Error ->
{reply, Error, State};
AllCons ->
case UserSess:run_cmd(have_permission, [[?MANAGE_CONNS]]) of
true -> Cons = [C#ddConn{owner = get_name(DalSess, C#ddConn.owner)} || C <- AllCons];
_ ->
Cons = [C#ddConn{owner = get_name(DalSess, C#ddConn.owner)}
|| C <- AllCons, conn_permission(UserSess, UserId, C)]
end,
{reply, Cons, State}
end;
handle_call({update_command, Id, Owner, Name, Sql, Opts}, _From, #state{sess=Sess} = State) ->
{reply, update_command(Sess, Id, Owner, Name, Sql, Opts), State};
handle_call({update_command, Id, Owner, Name, Sql, Conns, Opts}, _From, #state{sess=Sess} = State) ->
{reply, update_command(Sess, Id, Owner, Name, Sql, Conns, Opts), State};
handle_call({add_command, Owner, Adapter, Name, Cmd, Conn, Opts}, _From, #state{sess=Sess} = State) ->
{reply, add_command(Sess, Owner, Adapter, Name, Cmd, Conn, Opts), State};
handle_call({add_adapter_to_cmd, CmdId, Adapter}, _From, #state{sess=Sess} = State) ->
{reply, add_adapter_to_cmd(Sess, CmdId, Adapter), State};
handle_call({add_view, Owner, Name, CmdId, ViewsState}, _From, #state{sess=Sess} = State) ->
{reply, add_view(Sess, Owner, Name, CmdId, ViewsState), State};
handle_call({get_view, ViewId}, _From, #state{sess = Sess} = State) ->
{reply, get_view(Sess, ViewId), State};
handle_call({get_view, Name, Adapter, Owner}, _From, #state{sess=Sess} = State) ->
{reply, get_view(Sess, Name, Adapter, Owner), State};
handle_call({add_d3_templates_path, Entry}, _From, #state{d3_templates=D3Templates} = State) ->
{reply, ok, State#state{d3_templates=[Entry | D3Templates]}};
handle_call(get_d3_templates, _From, #state{d3_templates=D3Templates} = State) ->
{reply, D3Templates, State};
handle_call({get_d3_templates_path, Application}, _From, #state{d3_templates=D3Templates} = State) ->
Entry = proplists:get_value(Application, D3Templates),
{reply, Entry, State};
handle_call(get_host_app, _From, #state{host_app = undefined} = State) ->
HostApp =
lists:foldl(
fun({App,_,_}, <<>>) ->
{ok, Apps} = application:get_key(App, applications),
case lists:member(dderl, Apps) of
true -> atom_to_binary(App, utf8);
_ -> <<>>
end;
(_, App) -> App
end, <<>>, application:which_applications()),
{reply, HostApp, State#state{host_app = HostApp}};
handle_call(get_host_app, _From, #state{host_app = HostApp} = State) ->
{reply, HostApp, State};
handle_call(Req,From,State) ->
?Info("unknown call req ~p from ~p~n", [Req, From]),
{reply, ok, State}.
handle_cast({add_adapter, Id, FullName}, #state{sess=Sess} = State) ->
Adp = #ddAdapter{id=Id,fullName=FullName},
Sess:run_cmd(write, [ddAdapter, Adp]),
?Debug("add_adapter written ~p", [Adp]),
{noreply, State};
handle_cast({init_adapter, Adapter}, State) ->
spawn(fun() ->
Deps = Adapter:get_deps(),
?Info("checking for ~p dependencies: ~p", [Adapter, Deps]),
case check_dependencies(Deps) of
true ->
?Info("Dependencies found, initializing adapter ~p", [Adapter]),
Adapter:init();
false ->
?Info("Some dependencies of ~p missing, it will be excluded", [Adapter])
end
end),
{noreply, State};
handle_cast(Req,State) ->
?Debug("unknown cast ~p", [Req]),
{noreply, State}.
handle_info(Req,State) ->
?Debug("unknown info ~p", [Req]),
{noreply, State}.
terminate(Reason, #state{sess = Sess}) ->
?Debug("terminating, reason ~p", [Reason]),
Sess:close(),
ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
format_status(_Opt, [_PDict, _State]) -> ok.
-spec is_local_query(binary()) -> boolean().
is_local_query(Qry) ->
SysTabs = [erlang:atom_to_binary(Dt, utf8) || Dt <- [ddAdapter,ddInterface,ddConn,ddCmd,ddView,ddDash]],
SELECT * from tab1 a INNER JOIN tab2 on a = b INNER JOIN tab3 on c = d , tab4 f , tab2 , tab3 b INNER JOIN tab2 on a1 = b4 , tab5 INNER JOIN tab2 on a1 = b4
[ { " > > } } } ,
[ { " > > } } } ] } ,
[ { " > > } } } ] } ] } ,
case sqlparse:parsetree(Qry) of
{ok, [{{select,QOpts},_}|_]} ->
case lists:keyfind(from, 1, QOpts) of
{from, Tables} ->
lists:foldl(fun(T,_) ->
Tab = case T of
{{_,T1,_}, _} when is_binary(T1) -> T1;
{T1, _} when is_binary(T1) -> T1;
{_,T1,_} when is_binary(T1) -> T1;
T when is_binary(T) -> T;
_ -> T
end,
lists:member(Tab, SysTabs)
end,
true,
Tables);
_ -> false
end;
{lex_error, Error} ->
?Error("SQL lexer error ~p", [Error]),
false;
{parse_error, Error} ->
?Error("SQL parser error ~p", [Error]),
false;
_ ->
false
end.
-spec can_connect_locally({atom(), pid()}) -> boolean().
can_connect_locally(Sess) ->
Sess:run_cmd(have_permission, [[?USE_LOCAL_CONN]]) == true.
-spec conn_permission({atom(), pid()}, ddEntityId(), #ddConn{}) -> boolean().
conn_permission(Sess, _UserId, #ddConn{id=ConnId, owner=system}) ->
conn_permission(Sess, _UserId, #ddConn{id=ConnId}) ->
-spec add_connect_internal({atom(), pid()}, {atom(), pid()}, #ddConn{}) -> #ddConn{} | {error, binary()}.
add_connect_internal(UserSess, DalSess, #ddConn{schm = undefined} = Conn) ->
{ok, SchemaName} = application:get_env(imem, mnesia_schema_name),
add_connect_internal(UserSess, DalSess, Conn#ddConn{schm = atom_to_binary(SchemaName, utf8)});
add_connect_internal(UserSess, DalSess, #ddConn{id = null, owner = Owner} = Conn) ->
case UserSess:run_cmd(select, [ddConn, [{#ddConn{name='$1', owner='$2', id='$3', _='_'}
, [{'=:=','$1',Conn#ddConn.name},{'=:=','$2',Owner}]
, ['$_']}]]) of
{[#ddConn{id = Id} = OldCon | _], true} ->
NewCon = Conn#ddConn{id=Id},
Conn#ddConn{owner = get_name(DalSess, Conn#ddConn.owner)};
true ->
?Info("replacing connection ~p, owner ~p", [NewCon, Owner]),
check_save_conn(UserSess, DalSess, update, {OldCon, NewCon})
end;
_ ->
HavePermission = (UserSess =:= DalSess) orelse
UserSess:run_cmd(have_permission, [[manage_system, ?MANAGE_CONNS, ?CREATE_CONNS]]),
case HavePermission of
true ->
Id = erlang:phash2(crypto:strong_rand_bytes(16)),
NewCon = Conn#ddConn{id=Id},
?Info("adding new connection ~p", [NewCon]),
check_save_conn(UserSess, DalSess, insert, NewCon);
_ -> {error, <<"Create connections unauthorized">>}
end
end;
add_connect_internal(UserSess, DalSess, #ddConn{id = OldId, owner = Owner} = Conn)
when is_integer(OldId) ->
case UserSess:run_cmd(select, [ddConn, [{#ddConn{id=OldId, _='_'}, [], ['$_']}]]) of
{[#ddConn{owner = OldOwner} = OldCon], true} ->
case is_same_conn(OldCon, Conn) of
true ->
OldCon#ddConn{owner = get_name(DalSess, OldCon#ddConn.owner)};
false ->
if
check_save_conn(UserSess, DalSess, update, {OldCon, Conn});
add_connect_internal(UserSess, DalSess, Conn#ddConn{id = null})
end
end;
{[], true} ->
add_connect_internal(UserSess, DalSess, Conn#ddConn{id = null});
Result ->
?Error("Error getting connection with id ~p, Result:~n~p", [OldId, Result]),
{error, <<"Error saving the connection">>}
end.
is_same_conn(#ddConn{access = Access1} = Conn1, Conn2) when not is_map(Access1) ->
is_same_conn(Conn1#ddConn{access = maps:from_list(Access1)}, Conn2);
is_same_conn(Conn1, #ddConn{access = Access2} = Conn2) when not is_map(Access2) ->
is_same_conn(Conn1, Conn2#ddConn{access = maps:from_list(Access2)});
is_same_conn(Conn1, Conn2) ->
Conn1#ddConn{access = maps:remove(<<"user">>,maps:remove(user,Conn1#ddConn.access))} ==
Conn2#ddConn{owner = Conn1#ddConn.owner,
access = maps:remove(<<"user">>,maps:remove(user, Conn2#ddConn.access))}.
-spec check_save_conn({atom(), pid()}, {atom(), pid()}, atom(), #ddConn{}) -> #ddConn{} | {error, binary()}.
check_save_conn(UserSess, DalSess, Op, Conn0) ->
Conn = case Conn0 of
Conn0 when is_record(Conn0, ddConn) ->
Conn0#ddConn{access = maps:remove(password, pl2m(Conn0#ddConn.access))};
{C1, C2} when is_record(C1, ddConn), is_record(C2, ddConn) ->
{C1, C2#ddConn{access = maps:remove(password, pl2m(C2#ddConn.access))}}
end,
case UserSess:run_cmd(Op, [ddConn, Conn]) of
{error, {{Exception, M}, _Stacktrace} = Error} ->
?Error("failed to ~p connection with ~p : ~n~p", [Op, Conn, Error]),
Msg = list_to_binary(atom_to_list(Exception) ++ ": " ++
lists:flatten(io_lib:format("~p", [M]))),
{error, Msg};
{error, Error} ->
?Error("~p connection failed: ~p", [Op, Error]),
Msg = list_to_binary(lists:flatten(io_lib:format("~p", [Error]))),
{error, Msg};
#ddConn{} = SavedConn ->
SavedConn#ddConn{owner = get_name(DalSess, SavedConn#ddConn.owner)};
InvalidReturn ->
?Error("Invalid return on ~p connection ~p: The result:~n~p", [Op, Conn, InvalidReturn]),
{error, <<"Error saving the connection (Invalid value returned from DB)">>}
end.
-spec pl2m([tuple()] | map()) -> map().
pl2m(Map) when is_map(Map) -> Map;
pl2m([{_,_}|_] = PL) -> maps:from_list(PL).
-spec check_cmd_select({atom(), pid()}, list()) -> {error, binary()} | list().
check_cmd_select(UserSess, Args) ->
case UserSess:run_cmd(select, Args) of
{error, {{Exception, M}, _Stacktrace} = Error} ->
?Error("select failed : ~n~p", [Error]),
Msg = list_to_binary(atom_to_list(Exception) ++ ": " ++
lists:flatten(io_lib:format("~p", [M]))),
{error, Msg};
{error, Error} ->
?Error("select failed: ~p", [Error]),
Msg = list_to_binary(lists:flatten(io_lib:format("~p", [Error]))),
{error, Msg};
{Result, true} ->
Result;
InvalidReturn ->
?Error("Invalid return on select, args ~p: The result:~n~p", [Args, InvalidReturn]),
{error, <<"Error on select (Invalid value returned from DB)">>}
end.
-spec check_dependencies([atom()]) -> boolean().
check_dependencies([]) -> true;
check_dependencies([Dep | Rest]) ->
case code:priv_dir(Dep) of
{error, bad_name} -> false;
_ -> check_dependencies(Rest)
end.
-spec filter_view_result([#ddView{}], {atom(), pid()}, atom()) -> #ddView{} | {error, binary()}.
filter_view_result([], _, _) -> undefined;
filter_view_result([V | Views], Sess, Adapter) ->
case check_cmd_select(Sess, [ddCmd, [{#ddCmd{id=V#ddView.cmd, adapters='$1', _='_'}, [], ['$1']}]]) of
{error, _} = Error ->
Error;
[C] ->
case lists:member(Adapter, C) of
true -> V;
false -> filter_view_result(Views, Sess, Adapter)
end;
_ ->
?Error("Command id ~p not found for view ~p, with id ~p", [V#ddView.cmd, V#ddView.name, V#ddView.id]),
{error, iolist_to_binary(["Command not found for view ", V#ddView.name])}
end.
-spec get_restartable_apps() -> [atom()].
get_restartable_apps() ->
{ok, CurrApp} = application:get_application(?MODULE),
?RESTARTAPPS(CurrApp).
-spec process_login(map(), any(),
#{auth => fun((any()) -> ok | {any(), list()}),
connInfo => map(),
stateUpdateUsr => fun((any(), any()) -> any()),
stateUpdateSKey => fun((any(), any()) -> any()),
relayState => fun((any(), any()) -> any()),
urlPrefix => list()}) -> ok | map().
process_login(#{<<"smsott">> := Token} = Body, State,
#{auth := AuthFun} = Ctx) ->
process_login_reply(AuthFun({smsott,Token}), Body, Ctx, State);
process_login(#{<<"user">>:=User, <<"password">>:=Password} = Body, State,
#{stateUpdateUsr := StateUpdateFun, auth := AuthFun} = Ctx) ->
process_login_reply(AuthFun({pwdmd5,
{User, list_to_binary(Password)}}),
Body, Ctx, StateUpdateFun(State, User));
process_login(#{<<"samluser">>:=User} = Body, State,
#{stateUpdateUsr := StateUpdateFun, auth := AuthFun} = Ctx)
when is_function(StateUpdateFun, 2), is_function(AuthFun, 1) ->
process_login_reply(AuthFun({saml, User}), Body, Ctx,
StateUpdateFun(State, User));
process_login(Body, State, #{connInfo := ConnInfo, auth := AuthFun} = Ctx)
when is_map(ConnInfo), is_function(AuthFun, 1) ->
process_login_reply(AuthFun({access, ConnInfo}), Body, Ctx, State).
process_login_reply(ok, _Body, _Ctx, State) -> {ok, State};
process_login_reply({ok, []}, _Body, _Ctx, State) -> {ok, State};
process_login_reply({SKey, []}, _Body, #{stateUpdateSKey := StateUpdateFun},
State) when is_function(StateUpdateFun, 2) ->
{ok, StateUpdateFun(State, SKey)};
process_login_reply({ok, [{pwdmd5, Data}|_]}, _Body, _Ctx, State) ->
{#{pwdmd5=>fix_login_data(Data)}, State};
process_login_reply({SKey, [{pwdmd5, Data}|_]}, _Body,
#{stateUpdateSKey := StateUpdateFun}, State)
when is_function(StateUpdateFun, 2) ->
{#{pwdmd5=>fix_login_data(Data)}, StateUpdateFun(State, SKey)};
process_login_reply({ok, [{smsott, Data}|_]}, _Body, _Ctx, State) ->
{#{smsott=>fix_login_data(Data)}, State};
process_login_reply({SKey, [{smsott, Data}|_]}, _Body,
#{stateUpdateSKey := StateUpdateFun}, State)
when is_function(StateUpdateFun, 2) ->
{#{smsott=>fix_login_data(Data)}, StateUpdateFun(State, SKey)};
process_login_reply({SKey, [{saml, _Data}|_]}, Body,
#{urlPrefix := UrlPrefix,
stateUpdateSKey := StateUpdateFun,
relayState := RelayStateFun}, State)
when is_function(RelayStateFun, 2), is_function(StateUpdateFun, 2) ->
#{<<"host_url">> := HostUrlBin} = Body,
HostUrl = binary_to_list(HostUrlBin),
{#{saml =>
fix_login_data(
#{form =>
dderl_saml_handler:fwdUrl(
HostUrl, HostUrl ++ UrlPrefix ++ dderl:get_sp_url_suffix(),
RelayStateFun)})},
if SKey == ok -> State;
true -> StateUpdateFun(State, SKey)
end}.
fix_login_data(#{accountName:=undefined}=Data) ->
fix_login_data(Data#{accountName=><<"">>});
fix_login_data(Data) -> Data.
Functions used to extract rows from fsm using ets directly .
-spec rows_from(ets:tab(), term(), pos_integer()) -> [term()].
rows_from(TableId, Key, Limit) ->
ets:select(TableId, [{'$1', [{'>=',{element,1,'$1'}, {const, Key}}],['$_']}], Limit).
-spec expand_rows([term()], ets:tab(), fun(), [integer()]) -> [[binary()]].
expand_rows([], _TableId, _RowFun, _ColumnPos) -> [];
expand_rows([{_, Id} | RestRows], TableId, RowFun, ColumnPos) ->
Row = lists:nth(1, ets:lookup(TableId, Id)),
expand_rows([Row | RestRows], TableId, RowFun, ColumnPos);
expand_rows([{_I,_Op, RK} | RestRows], TableId, RowFun, ColumnPos) ->
SelectedColumns = [element(Col, ExpandedRow) || Col <- ColumnPos],
[SelectedColumns | expand_rows(RestRows, TableId, RowFun, ColumnPos)];
expand_rows([FullRowTuple | RestRows], TableId, RowFun, ColumnPos) ->
SelectedColumns = [element(3+Col, FullRowTuple) || Col <- ColumnPos],
[SelectedColumns | expand_rows(RestRows, TableId, RowFun, ColumnPos)].
-spec is_proxy(list(), map()) -> boolean().
is_proxy(AppId, NetCtx) ->
ProxyCheckFun = ?GET_CONFIG(isProxyCheckFun, [AppId], <<"fun(NetCtx) -> false end">>, "Function checks if user is coming through a proxy or not"),
CacheKey = {?MODULE, isProxyCheckFun, ProxyCheckFun},
case imem_cache:read(CacheKey) of
[] ->
case imem_datatype:io_to_fun(ProxyCheckFun) of
PF when is_function(PF, 1) ->
imem_cache:write(CacheKey, PF),
exec_is_proxy_fun(PF, NetCtx);
_ ->
?Error("Not a valid is proxy fun configured"),
false
end;
[PF] when is_function(PF, 1) -> exec_is_proxy_fun(PF, NetCtx);
_ -> false
end.
-spec exec_is_proxy_fun(reference(), map()) -> boolean().
exec_is_proxy_fun(Fun, NetCtx) ->
case catch Fun(NetCtx) of
false -> false;
true -> true;
Error ->
?Error("proxy check fail : ~p", [Error]),
false
end.
|
25e048731d1b58583a9408eb9a71e896983894ac970a2888c82beffe27bf7f34 | google/ormolu | proc-cases-out.hs | {-# LANGUAGE Arrows #-}
foo f = proc a -> case a of Left b -> f -< b
bar f g h j =
proc a -> case a of
Left
( (a, b)
, (c, d)
) -> f (a <> c) -< b <> d
Right
(Left a) ->
h -< a
Right
(Right b) ->
j -< b
| null | https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/data/examples/declaration/value/function/arrow/proc-cases-out.hs | haskell | # LANGUAGE Arrows # |
foo f = proc a -> case a of Left b -> f -< b
bar f g h j =
proc a -> case a of
Left
( (a, b)
, (c, d)
) -> f (a <> c) -< b <> d
Right
(Left a) ->
h -< a
Right
(Right b) ->
j -< b
|
349ff5f3f8e0e17db2f904da97d70a0504f48b9214f1ee17f4b0729abb83a448 | release-project/benchmarks | util.erl | -module(util).
-compile(export_all).
-spec quit(string(),list()) -> ok.
quit(Fmt,Args) ->
io:format(Fmt,Args),
init:stop().
% This isn't ideal. I think it only stops the current process, and there may
% be other processes running. Specifically, if you put a non-existent node
% in the nodes file, we get an error message but the start_aco function carries
% on and attempts to start a process on that node anyway.
-spec int_of_string(string()) -> integer().
int_of_string(S) ->
try
list_to_integer(S)
catch
error: _ ->
quit ("Error: bad integer ~p~n", [S])
end.
-spec float_of_string(string()) -> float().
float_of_string(S) ->
try
case string:chr (S, $.) of
0 -> list_to_integer(S);
_ -> list_to_float([$0|S]) % list_to_float doesn't like ".9"
end
catch
error: _ -> quit ("Error: bad float ~p~n", [S])
end.
-spec check_positive({atom(), number()}) -> ok.
check_positive({S,N}) ->
if N > 0 ->
ok;
true -> quit ("Error: require ~p > 0, but found ~p.~n", [S,N])
end.
-include_lib ("kernel/include/file.hrl"). % For file_info type
-spec check_file (string()) -> ok.
check_file(Fname) ->
case file:read_file_info(Fname) of
{ok, Info} ->
#file_info{access=Access, type=Type} = Info,
if Access =:= read orelse Access =:= read_write
-> case Type of
regular -> ok;
_ -> quit ("Error reading ~p: found ~p~n", [Fname, Type])
end;
true -> quit ("Error: file ~p not readable~n", [Fname])
end;
{error, Reason} ->
case Reason of
enoent -> quit ("Error: can't open file ~p~n", [Fname]);
_ -> quit ("Error opening file ~p: ~p~n", [Fname, Reason])
end
end.
-spec check_node (atom()) -> ok.
check_node(N) ->
case net_adm:ping(N) of
pong -> ok;
pang -> quit ("Error: can't find node ~p~n", [N])
end.
-spec make_tuple(non_neg_integer(), any()) -> tuple().
make_tuple(N,T) -> list_to_tuple (lists:duplicate(N,T)).
| null | https://raw.githubusercontent.com/release-project/benchmarks/55f042dca3a2c680e2967c59edc9636456047bd5/ACO/SMP-ACO/util.erl | erlang | This isn't ideal. I think it only stops the current process, and there may
be other processes running. Specifically, if you put a non-existent node
in the nodes file, we get an error message but the start_aco function carries
on and attempts to start a process on that node anyway.
list_to_float doesn't like ".9"
For file_info type | -module(util).
-compile(export_all).
-spec quit(string(),list()) -> ok.
quit(Fmt,Args) ->
io:format(Fmt,Args),
init:stop().
-spec int_of_string(string()) -> integer().
int_of_string(S) ->
try
list_to_integer(S)
catch
error: _ ->
quit ("Error: bad integer ~p~n", [S])
end.
-spec float_of_string(string()) -> float().
float_of_string(S) ->
try
case string:chr (S, $.) of
0 -> list_to_integer(S);
end
catch
error: _ -> quit ("Error: bad float ~p~n", [S])
end.
-spec check_positive({atom(), number()}) -> ok.
check_positive({S,N}) ->
if N > 0 ->
ok;
true -> quit ("Error: require ~p > 0, but found ~p.~n", [S,N])
end.
-spec check_file (string()) -> ok.
check_file(Fname) ->
case file:read_file_info(Fname) of
{ok, Info} ->
#file_info{access=Access, type=Type} = Info,
if Access =:= read orelse Access =:= read_write
-> case Type of
regular -> ok;
_ -> quit ("Error reading ~p: found ~p~n", [Fname, Type])
end;
true -> quit ("Error: file ~p not readable~n", [Fname])
end;
{error, Reason} ->
case Reason of
enoent -> quit ("Error: can't open file ~p~n", [Fname]);
_ -> quit ("Error opening file ~p: ~p~n", [Fname, Reason])
end
end.
-spec check_node (atom()) -> ok.
check_node(N) ->
case net_adm:ping(N) of
pong -> ok;
pang -> quit ("Error: can't find node ~p~n", [N])
end.
-spec make_tuple(non_neg_integer(), any()) -> tuple().
make_tuple(N,T) -> list_to_tuple (lists:duplicate(N,T)).
|
6261f244b6bd33aa248ad5d6b73b9ed587d1cd2e1e017234f25b48f3bb2f9b50 | input-output-hk/voting-tools | Extended.hs |
module Test.Cardano.API.Extended
( tests
)
where
import qualified Data.Aeson as Aeson
import Hedgehog (Property, forAll, property, tripping)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.Hedgehog (testProperty)
import qualified Cardano.Catalyst.Test.DSL.Gen as Gen
tests :: TestTree
tests = testGroup "Test.Cardano.API.Extended"
[ testProperty "JSON roundtrip VotingKeyPublic" prop_votingKeyPublic_json_roundtrip
]
prop_votingKeyPublic_json_roundtrip :: Property
prop_votingKeyPublic_json_roundtrip = property $ do
votepub <- forAll Gen.genVotingKeyPublic
tripping votepub Aeson.encode Aeson.eitherDecode'
| null | https://raw.githubusercontent.com/input-output-hk/voting-tools/d14c5a456dc440b1dfe7901b6f19e53e8aadea12/test/Test/Cardano/API/Extended.hs | haskell |
module Test.Cardano.API.Extended
( tests
)
where
import qualified Data.Aeson as Aeson
import Hedgehog (Property, forAll, property, tripping)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.Hedgehog (testProperty)
import qualified Cardano.Catalyst.Test.DSL.Gen as Gen
tests :: TestTree
tests = testGroup "Test.Cardano.API.Extended"
[ testProperty "JSON roundtrip VotingKeyPublic" prop_votingKeyPublic_json_roundtrip
]
prop_votingKeyPublic_json_roundtrip :: Property
prop_votingKeyPublic_json_roundtrip = property $ do
votepub <- forAll Gen.genVotingKeyPublic
tripping votepub Aeson.encode Aeson.eitherDecode'
| |
cbf3cc6d8128a4d37216eea204ea0d98a7a8a755b19f1224286bc7e5a57a6d4c | haskell/containers | Set.hs | {-# LANGUAGE BangPatterns #-}
module Main where
import Control.DeepSeq (rnf)
import Control.Exception (evaluate)
import Test.Tasty.Bench (bench, defaultMain, whnf)
import Data.List (foldl')
import qualified Data.Set as S
main = do
let s = S.fromAscList elems :: S.Set Int
s_even = S.fromAscList elems_even :: S.Set Int
s_odd = S.fromAscList elems_odd :: S.Set Int
strings_s = S.fromList strings
evaluate $ rnf [s, s_even, s_odd]
defaultMain
[ bench "member" $ whnf (member elems) s
, bench "insert" $ whnf (ins elems) S.empty
, bench "map" $ whnf (S.map (+ 1)) s
, bench "filter" $ whnf (S.filter ((== 0) . (`mod` 2))) s
, bench "partition" $ whnf (S.partition ((== 0) . (`mod` 2))) s
, bench "fold" $ whnf (S.fold (:) []) s
, bench "delete" $ whnf (del elems) s
, bench "findMin" $ whnf S.findMin s
, bench "findMax" $ whnf S.findMax s
, bench "deleteMin" $ whnf S.deleteMin s
, bench "deleteMax" $ whnf S.deleteMax s
, bench "unions" $ whnf S.unions [s_even, s_odd]
, bench "union" $ whnf (S.union s_even) s_odd
, bench "difference" $ whnf (S.difference s) s_even
, bench "intersection" $ whnf (S.intersection s) s_even
, bench "fromList" $ whnf S.fromList elems
, bench "fromList-desc" $ whnf S.fromList (reverse elems)
, bench "fromAscList" $ whnf S.fromAscList elems
, bench "fromDistinctAscList" $ whnf S.fromDistinctAscList elems
, bench "disjoint:false" $ whnf (S.disjoint s) s_even
, bench "disjoint:true" $ whnf (S.disjoint s_odd) s_even
, bench "null.intersection:false" $ whnf (S.null. S.intersection s) s_even
, bench "null.intersection:true" $ whnf (S.null. S.intersection s_odd) s_even
, bench "alterF:member" $ whnf (alterF_member elems) s
, bench "alterF:insert" $ whnf (alterF_ins elems) S.empty
, bench "alterF:delete" $ whnf (alterF_del elems) s
, bench "alterF:four" $ whnf (alterF_four elems) s
, bench "alterF:four:strings" $ whnf (alterF_four strings) strings_s
, bench "alterF_naive:four" $ whnf (alterF_naive_four elems) s
, bench "alterF_naive:four:strings" $ whnf (alterF_naive_four strings) strings_s
, bench "powerSet (19)" $ whnf S.powerSet (S.fromList[1..19])
, bench "powerSet (20)" $ whnf S.powerSet (S.fromList[1..20])
, bench "powerSet (21)" $ whnf S.powerSet (S.fromList[1..21])
, bench "member.powerSet (16)" $ whnf (\ s -> all (flip S.member s) s) (S.powerSet (S.fromList [1..16]))
, bench "member.powerSet (17)" $ whnf (\ s -> all (flip S.member s) s) (S.powerSet (S.fromList [1..17]))
, bench "member.powerSet (18)" $ whnf (\ s -> all (flip S.member s) s) (S.powerSet (S.fromList [1..18]))
]
where
elems = [1..2^12]
elems_even = [2,4..2^12]
elems_odd = [1,3..2^12]
strings = map show elems
member :: [Int] -> S.Set Int -> Int
member xs s = foldl' (\n x -> if S.member x s then n + 1 else n) 0 xs
ins :: [Int] -> S.Set Int -> S.Set Int
ins xs s0 = foldl' (\s a -> S.insert a s) s0 xs
del :: [Int] -> S.Set Int -> S.Set Int
del xs s0 = foldl' (\s k -> S.delete k s) s0 xs
alterF_member :: [Int] -> S.Set Int -> Int
alterF_member xs s = foldl' (\n x -> if member' x s then n + 1 else n) 0 xs
where
member' k s = getConsty (S.alterF (\b -> Consty b) k s)
alterF_ins :: [Int] -> S.Set Int -> S.Set Int
alterF_ins xs s0 = foldl' (\s a -> insert' a s) s0 xs
where
insert' k s = runIdent (S.alterF (const (Ident True)) k s)
alterF_del :: [Int] -> S.Set Int -> S.Set Int
alterF_del xs s0 = foldl' (\s k -> delete' k s) s0 xs
where
delete' k s = runIdent (S.alterF (const (Ident False)) k s)
alterF_four :: Ord a => [a] -> S.Set a -> S.Set a
alterF_four xs s0 = foldl' (\s k -> S.alterF four k s `seq` s) s0 xs
alterF_naive_four :: Ord a => [a] -> S.Set a -> S.Set a
alterF_naive_four xs s0 = foldl' (\s k -> alterF_naive four k s `seq` s) s0 xs
alterF_naive :: (Ord a, Functor f) => (Bool -> f Bool) -> a -> S.Set a -> f (S.Set a)
alterF_naive f k s = fmap g (f (k `S.member` s))
where
g True = S.insert k s
g False = S.delete k s
four :: Bool -> Four Bool
-- insert delete reinsert toggle
four True = Four True False True False
four False = Four True False False True
newtype Consty a b = Consty { getConsty :: a}
instance Functor (Consty a) where
fmap _ (Consty a) = Consty a
newtype Ident a = Ident { runIdent :: a }
instance Functor Ident where
fmap f (Ident a) = Ident (f a)
data Four a = Four !a !a !a !a
instance Functor Four where
fmap f (Four a b c d) = Four (f a) (f b) (f c) (f d)
| null | https://raw.githubusercontent.com/haskell/containers/0f4f7be103f4197272e48baaf9de809987b8dc9f/containers-tests/benchmarks/Set.hs | haskell | # LANGUAGE BangPatterns #
insert delete reinsert toggle |
module Main where
import Control.DeepSeq (rnf)
import Control.Exception (evaluate)
import Test.Tasty.Bench (bench, defaultMain, whnf)
import Data.List (foldl')
import qualified Data.Set as S
main = do
let s = S.fromAscList elems :: S.Set Int
s_even = S.fromAscList elems_even :: S.Set Int
s_odd = S.fromAscList elems_odd :: S.Set Int
strings_s = S.fromList strings
evaluate $ rnf [s, s_even, s_odd]
defaultMain
[ bench "member" $ whnf (member elems) s
, bench "insert" $ whnf (ins elems) S.empty
, bench "map" $ whnf (S.map (+ 1)) s
, bench "filter" $ whnf (S.filter ((== 0) . (`mod` 2))) s
, bench "partition" $ whnf (S.partition ((== 0) . (`mod` 2))) s
, bench "fold" $ whnf (S.fold (:) []) s
, bench "delete" $ whnf (del elems) s
, bench "findMin" $ whnf S.findMin s
, bench "findMax" $ whnf S.findMax s
, bench "deleteMin" $ whnf S.deleteMin s
, bench "deleteMax" $ whnf S.deleteMax s
, bench "unions" $ whnf S.unions [s_even, s_odd]
, bench "union" $ whnf (S.union s_even) s_odd
, bench "difference" $ whnf (S.difference s) s_even
, bench "intersection" $ whnf (S.intersection s) s_even
, bench "fromList" $ whnf S.fromList elems
, bench "fromList-desc" $ whnf S.fromList (reverse elems)
, bench "fromAscList" $ whnf S.fromAscList elems
, bench "fromDistinctAscList" $ whnf S.fromDistinctAscList elems
, bench "disjoint:false" $ whnf (S.disjoint s) s_even
, bench "disjoint:true" $ whnf (S.disjoint s_odd) s_even
, bench "null.intersection:false" $ whnf (S.null. S.intersection s) s_even
, bench "null.intersection:true" $ whnf (S.null. S.intersection s_odd) s_even
, bench "alterF:member" $ whnf (alterF_member elems) s
, bench "alterF:insert" $ whnf (alterF_ins elems) S.empty
, bench "alterF:delete" $ whnf (alterF_del elems) s
, bench "alterF:four" $ whnf (alterF_four elems) s
, bench "alterF:four:strings" $ whnf (alterF_four strings) strings_s
, bench "alterF_naive:four" $ whnf (alterF_naive_four elems) s
, bench "alterF_naive:four:strings" $ whnf (alterF_naive_four strings) strings_s
, bench "powerSet (19)" $ whnf S.powerSet (S.fromList[1..19])
, bench "powerSet (20)" $ whnf S.powerSet (S.fromList[1..20])
, bench "powerSet (21)" $ whnf S.powerSet (S.fromList[1..21])
, bench "member.powerSet (16)" $ whnf (\ s -> all (flip S.member s) s) (S.powerSet (S.fromList [1..16]))
, bench "member.powerSet (17)" $ whnf (\ s -> all (flip S.member s) s) (S.powerSet (S.fromList [1..17]))
, bench "member.powerSet (18)" $ whnf (\ s -> all (flip S.member s) s) (S.powerSet (S.fromList [1..18]))
]
where
elems = [1..2^12]
elems_even = [2,4..2^12]
elems_odd = [1,3..2^12]
strings = map show elems
member :: [Int] -> S.Set Int -> Int
member xs s = foldl' (\n x -> if S.member x s then n + 1 else n) 0 xs
ins :: [Int] -> S.Set Int -> S.Set Int
ins xs s0 = foldl' (\s a -> S.insert a s) s0 xs
del :: [Int] -> S.Set Int -> S.Set Int
del xs s0 = foldl' (\s k -> S.delete k s) s0 xs
alterF_member :: [Int] -> S.Set Int -> Int
alterF_member xs s = foldl' (\n x -> if member' x s then n + 1 else n) 0 xs
where
member' k s = getConsty (S.alterF (\b -> Consty b) k s)
alterF_ins :: [Int] -> S.Set Int -> S.Set Int
alterF_ins xs s0 = foldl' (\s a -> insert' a s) s0 xs
where
insert' k s = runIdent (S.alterF (const (Ident True)) k s)
alterF_del :: [Int] -> S.Set Int -> S.Set Int
alterF_del xs s0 = foldl' (\s k -> delete' k s) s0 xs
where
delete' k s = runIdent (S.alterF (const (Ident False)) k s)
alterF_four :: Ord a => [a] -> S.Set a -> S.Set a
alterF_four xs s0 = foldl' (\s k -> S.alterF four k s `seq` s) s0 xs
alterF_naive_four :: Ord a => [a] -> S.Set a -> S.Set a
alterF_naive_four xs s0 = foldl' (\s k -> alterF_naive four k s `seq` s) s0 xs
alterF_naive :: (Ord a, Functor f) => (Bool -> f Bool) -> a -> S.Set a -> f (S.Set a)
alterF_naive f k s = fmap g (f (k `S.member` s))
where
g True = S.insert k s
g False = S.delete k s
four :: Bool -> Four Bool
four True = Four True False True False
four False = Four True False False True
newtype Consty a b = Consty { getConsty :: a}
instance Functor (Consty a) where
fmap _ (Consty a) = Consty a
newtype Ident a = Ident { runIdent :: a }
instance Functor Ident where
fmap f (Ident a) = Ident (f a)
data Four a = Four !a !a !a !a
instance Functor Four where
fmap f (Four a b c d) = Four (f a) (f b) (f c) (f d)
|
1167a0efff0d6a55aca5b193985193050a33d55b8713a780a1c8423080c5a3c9 | osa1/sc-plugin | Renaming.hs | {-# LANGUAGE Rank2Types #-}
# OPTIONS_GHC -fno - warn - missing - signatures #
module Supercompile.Core.Renaming (
|
Renaming, emptyRenaming,
mkInScopeIdentityRenaming, mkIdentityRenaming, mkTyVarRenaming, mkRenaming,
InScopeSet, emptyInScopeSet, mkInScopeSet,
| PreRenamings
PreRenaming, invertRenaming, composeRenamings,
restrictRenaming,
-- | Extending the renaming
insertVarRenaming,
insertIdRenaming, insertIdRenamings,
insertTypeSubst, insertTypeSubsts,
insertCoercionSubst, insertCoercionSubsts,
-- | Querying the renaming
renameId, lookupTyVarSubst, lookupCoVarSubst,
-- | Things with associated renamings
In, Out,
-- | Renaming variables occurrences and binding sites
inFreeVars, renameFreeVars, renameIn,
renameType, renameCoercion,
renameBinders, renameNonRecBinder, renameNonRecBinders,
renameBounds, renameNonRecBound,
-- | Renaming actual bits of syntax
renameValueG, renameAltCon,
renameTerm, renameAlts, renameValue, renameValue',
renameFVedTerm, renameFVedAlts, renameFVedValue, renameFVedValue',
renameTaggedTerm, renameTaggedAlts, renameTaggedValue, renameTaggedValue',
renameTaggedSizedFVedTerm, renameTaggedSizedFVedAlts, renameTaggedSizedFVedValue, renameTaggedSizedFVedValue'
) where
import Supercompile.Core.FreeVars
import Supercompile.Core.Syntax
import Supercompile.Utilities
import CoreSubst
import OptCoercion (optCoercion)
import Coercion (CvSubst(..), CvSubstEnv, isCoVar, mkCoVarCo, getCoVar_maybe)
import qualified CoreSyn as CoreSyn (CoreExpr, Expr(Var))
import Type (mkTyVarTy, getTyVar_maybe)
import Id (mkSysLocal)
import Var (Id, TyVar, CoVar, isTyVar, mkTyVar, varType, isGlobalId, varUnique)
import OccName (occNameFS)
import Name (getOccName, mkSysTvName)
import FastString (FastString)
import UniqFM (ufmToList)
import VarEnv
import Control.Monad.Fix (mfix)
import qualified Data.Map as M
We are going to use GHC 's substitution type in a rather stylised way , and only
-- ever substitute variables for variables. The reasons for this are twofold:
--
1 . Particularly since we are in ANF , doing any other sort of substitution is unnecessary
--
2 . We have our own syntax data type , and we do n't want to build a GHC syntax tree just
for insertion into the Subst if we can help it !
--
-- Unfortunately, in order to make this work with the coercionful operational semantics
-- we will sometimes need to substitute coerced variables for variables. An example would be
-- when reducing:
--
( \x . e ) | > gam y
--
-- Where
--
gam = ( F Int - > F Int ~ Bool - > Bool )
--
-- We need to reduce to something like:
--
e[(y | > sym ( nth 1 gam))/x ] | > ( nth 2 gam )
--
-- We deal with this problem in the evaluator by introducing an intermediate let binding for
-- such redexes.
type Renaming = (IdSubstEnv, TvSubstEnv, CvSubstEnv)
joinSubst :: InScopeSet -> Renaming -> Subst
joinSubst iss (id_subst, tv_subst, co_subst) = mkSubst iss tv_subst co_subst id_subst
GHC 's binder - renaming stuff does this awful thing where a var->var renaming
will always be added to the InScopeSet ( which is really an InScopeMap ) but
-- will only be added to the IdSubstEnv *if the unique changes*.
--
-- This is a problem for us because we only store the Renaming with each In thing,
not the full Subst . So we might lose some renamings recorded only in the InScopeSet .
--
-- The solution is either:
1 ) Rewrite the rest of the supercompiler so it stores a Subst with each binding .
Given the behaviour of GHCs binder - renamer , this is probably cleaner ( and matches
what the GHC does ) , but I 'm not really interested in doing that work right now .
--
-- It also means you have te be very careful to join together InScopeSets if you
pull one of those Subst - paired things down into a strictly deeper context . This
-- is easy to get wrong.
--
2 ) Ensure that we always extend the IdSubstEnv , regardless of whether the unique changed .
This is the solution I 've adopted , and it is implemented here in splitSubst :
splitSubst :: Subst -> [(Var, Var)] -> (InScopeSet, Renaming)
splitSubst (Subst iss id_subst tv_subst co_subst) extend
= (iss, foldVarlikes (\f -> foldr (\x_x' -> f (fst x_x') x_x')) extend
(\(x, x') -> first3 (\id_subst -> extendVarEnv id_subst x (mkIdExpr x')))
(\(a, a') -> second3 (\tv_subst -> extendVarEnv tv_subst a (mkTyVarTy a')))
(\(q, q') -> third3 (\co_subst -> extendVarEnv co_subst q (mkCoVarCo q')))
(id_subst, tv_subst, co_subst))
NB : this used to return a triple of lists , but I introduced this version due to profiling
results that indicated a caller ( renameFreeVars ) was causing 2 % of all allocations . It turns
-- out that I managed to achieve deforestation in all of the callers by rewriting them to use this
-- version instead.
# INLINE foldVarlikes #
foldVarlikes :: ((Var -> a -> b -> b) -> b -> f_a -> b)
-> f_a
-> (a -> b -> b) -- Id continuation
TyVar continuation
-> (a -> b -> b) -- CoVar continuation
-> b -> b
foldVarlikes fold as id tv co acc = fold go acc as
where go x a res | isTyVar x = tv a res
| isCoVar x = co a res
| otherwise = id a res
emptyRenaming :: Renaming
emptyRenaming = (emptyVarEnv, emptyVarEnv, emptyVarEnv)
mkIdentityRenaming :: FreeVars -> Renaming
mkIdentityRenaming fvs = foldVarlikes (\f -> foldVarSet (\x -> f x x)) fvs
(\x -> first3 (\id_subst -> extendVarEnv id_subst x (mkIdExpr x)))
(\a -> second3 (\tv_subst -> extendVarEnv tv_subst a (mkTyVarTy a)))
(\q -> third3 (\co_subst -> extendVarEnv co_subst q (mkCoVarCo q)))
(emptyVarEnv, emptyVarEnv, emptyVarEnv)
mkInScopeIdentityRenaming :: InScopeSet -> Renaming
mkInScopeIdentityRenaming = mkIdentityRenaming . getInScopeVars
mkTyVarRenaming :: [(TyVar, Type)] -> Renaming
mkTyVarRenaming aas = (emptyVarEnv, mkVarEnv aas, emptyVarEnv)
mkRenaming :: M.Map Var Var -> Renaming
mkRenaming rn = foldVarlikes (\f -> M.foldWithKey (\x x' -> f x (x, x'))) rn
(\(x, x') -> first3 (\id_subst -> extendVarEnv id_subst x (mkIdExpr x')))
(\(a, a') -> second3 (\tv_subst -> extendVarEnv tv_subst a (mkTyVarTy a')))
(\(q, q') -> third3 (\co_subst -> extendVarEnv co_subst q (mkCoVarCo q')))
(emptyVarEnv, emptyVarEnv, emptyVarEnv)
type PreRenaming = (VarEnv Id, VarEnv TyVar, VarEnv CoVar)
NB : the output Vars in the range of the mappings are dodgy and should really only be used for
their Uniques . I turn them into full Ids mostly for convenience .
--
NB : the InScopeSet should be that of the * domain * of the renaming ( I think ! )
--
NB : I used to return a real * Renaming * as the result , but that was n't very convenient for the MSG caller :
1 . It hides the fact that looking up a CoVar / TyVar always yields a variable
2 . It does n't let us easily test if a variable is actually present in the domain of the inverted renaming
invertRenaming :: InScopeSet -> Renaming -> Maybe PreRenaming
invertRenaming ids (id_subst, tv_subst, co_subst)
= mfix $ \rn -> let -- FIXME: this inversion relies on something of a hack because the domain of the mapping is not stored (only its Unique)
-- Furthermore, we want to carefully rename the *types* (and extra info, if we actually preserved any) as well when doing
-- this inversion so that the renaming {a |-> b, y |-> x :: b} is inverted to {b |-> a, x |-> y :: a}
invertVarEnv :: (FastString -> Unique -> Type -> Var)
-> VarEnv Var -> Maybe (VarEnv Var)
invertVarEnv mk env
| distinct (varEnvElts env) = Just (mkVarEnv [ (x, if isGlobalId x && u == varUnique x
then x -- So we don't replace global Ids with new local Ids!
else mk (occNameFS (getOccName x)) u (renameType ids (mkRenaming' rn) (varType x)))
| (u, x) <- ufmToList env])
| otherwise = Nothing
in liftM3 (,,) (traverse getId_maybe id_subst >>= invertVarEnv mkSysLocal)
(traverse getTyVar_maybe tv_subst >>= invertVarEnv (\fs uniq -> mkTyVar (mkSysTvName uniq fs)))
(traverse getCoVar_maybe co_subst >>= invertVarEnv mkSysLocal)
where
mkRenaming' :: PreRenaming -> Renaming
mkRenaming' (xxs, aas, qqs) = (mapVarEnv mkIdExpr xxs,
mapVarEnv mkTyVarTy aas,
mapVarEnv mkCoVarCo qqs)
composeRenamings :: PreRenaming -> Renaming -> Renaming
composeRenamings (id_subst1, tv_subst1, co_subst1) rn2
= (mapVarEnv (mkIdExpr . renameId rn2) id_subst1,
mapVarEnv (lookupTyVarSubst rn2) tv_subst1,
mapVarEnv (lookupCoVarSubst rn2) co_subst1)
restrictRenaming :: Renaming -> VarSet -> Renaming
restrictRenaming (id_subst, tv_subst, co_subst) fvs = (id_subst `restrictVarEnv` fvs, tv_subst `restrictVarEnv` fvs, co_subst `restrictVarEnv` fvs)
mkIdExpr :: Id -> CoreSyn.CoreExpr
mkIdExpr = CoreSyn.Var
getId_maybe :: CoreSyn.CoreExpr -> Maybe Id
getId_maybe (CoreSyn.Var x') = Just x'
getId_maybe _ = Nothing
coreSynToVar :: CoreSyn.CoreExpr -> Var
coreSynToVar = fromMaybe (panic "renameId" empty) . getId_maybe
insertVarRenaming :: Renaming -> Var -> Out Var -> Renaming
insertVarRenaming rn x y
| isTyVar x = insertTypeSubst rn x (mkTyVarTy y)
| isCoVar x = insertCoercionSubst rn x (mkCoVarCo y)
| otherwise = insertIdRenaming rn x y
insertIdRenaming :: Renaming -> Id -> Out Id -> Renaming
insertIdRenaming (id_subst, tv_subst, co_subst) x x'
= (extendVarEnv id_subst x (mkIdExpr x'), tv_subst, co_subst)
insertIdRenamings :: Renaming -> [(Id, Out Id)] -> Renaming
insertIdRenamings = foldr (\(x, x') rn -> insertIdRenaming rn x x')
insertTypeSubst :: Renaming -> TyVar -> Out Type -> Renaming
insertTypeSubst (id_subst, tv_subst, co_subst) x ty' = (id_subst, extendVarEnv tv_subst x ty', co_subst)
insertTypeSubsts :: Renaming -> [(TyVar, Out Type)] -> Renaming
insertTypeSubsts (id_subst, tv_subst, co_subst) xtys = (id_subst, extendVarEnvList tv_subst xtys, co_subst)
insertCoercionSubst :: Renaming -> CoVar -> Out Coercion -> Renaming
insertCoercionSubst (id_subst, tv_subst, co_subst) x co' = (id_subst, tv_subst, extendVarEnv co_subst x co')
insertCoercionSubsts :: Renaming -> [(CoVar, Out Coercion)] -> Renaming
insertCoercionSubsts (id_subst, tv_subst, co_subst) xcos = (id_subst, tv_subst, extendVarEnvList co_subst xcos)
NB : these three function can supply emptyInScopeSet because of what I do in splitSubst
renameId :: Renaming -> Id -> Out Id
renameId rn = coreSynToVar . lookupIdSubst (text "renameId") (joinSubst emptyInScopeSet rn)
lookupTyVarSubst :: Renaming -> TyVar -> Out Type
lookupTyVarSubst rn = lookupTvSubst (joinSubst emptyInScopeSet rn)
lookupCoVarSubst :: Renaming -> CoVar -> Out Coercion
lookupCoVarSubst rn = lookupCvSubst (joinSubst emptyInScopeSet rn)
type In a = (Renaming, a)
type Out a = a
inFreeVars :: (a -> FreeVars) -> In a -> FreeVars
inFreeVars thing_fvs (rn, thing) = renameFreeVars rn (thing_fvs thing)
renameFreeVars :: Renaming -> FreeVars -> FreeVars
renameFreeVars rn fvs = foldVarlikes (\f -> foldVarSet (\x -> f x x)) fvs
(\x -> flip extendVarSet (renameId rn x))
(\a -> unionVarSet (tyVarsOfType (lookupTyVarSubst rn a)))
(\q -> unionVarSet (tyCoVarsOfCo (lookupCoVarSubst rn q)))
emptyVarSet
renameType :: InScopeSet -> Renaming -> Type -> Type
renameType iss rn = substTy (joinSubst iss rn)
renameCoercion :: InScopeSet -> Renaming -> Coercion -> NormalCo
renameCoercion iss (_, tv_subst, co_subst) = optCoercion (CvSubst iss tv_subst co_subst)
renameIn :: (Renaming -> a -> a) -> In a -> a
renameIn f (rn, x) = f rn x
renameBinders :: InScopeSet -> Renaming -> [Var] -> (InScopeSet, Renaming, [Var])
renameBinders iss rn xs = (iss', rn', xs')
where (subst', xs') = substRecBndrs (joinSubst iss rn) xs
(iss', rn') = splitSubst subst' (xs `zip` xs')
renameNonRecBinder :: InScopeSet -> Renaming -> Var -> (InScopeSet, Renaming, Var)
renameNonRecBinder iss rn x = (iss', rn', x')
where (subst', x') = substBndr (joinSubst iss rn) x
(iss', rn') = splitSubst subst' [(x, x')]
renameNonRecBinders :: InScopeSet -> Renaming -> [Var] -> (InScopeSet, Renaming, [Var])
renameNonRecBinders iss rn xs = (iss', rn', xs')
where (subst', xs') = substBndrs (joinSubst iss rn) xs
(iss', rn') = splitSubst subst' (xs `zip` xs')
renameBounds :: InScopeSet -> Renaming -> [(Var, a)] -> (InScopeSet, Renaming, [(Var, In a)])
renameBounds iss rn xes = (iss', rn', xs' `zip` map ((,) rn') es)
where (xs, es) = unzip xes
(iss', rn', xs') = renameBinders iss rn xs
renameNonRecBound :: InScopeSet -> Renaming -> (Var, a) -> (InScopeSet, Renaming, (Var, In a))
renameNonRecBound iss rn (x, e) = (iss', rn', (x', (rn, e)))
where (iss', rn', x') = renameNonRecBinder iss rn x
(renameTerm, renameAlts, renameValue, renameValue') = mkRename (\f rn (I e) -> I (f rn e))
(renameFVedTerm, renameFVedAlts, renameFVedValue, renameFVedValue') = mkRename (\f rn (FVed fvs e) -> FVed (renameFreeVars rn fvs) (f rn e))
(renameTaggedTerm, renameTaggedAlts, renameTaggedValue, renameTaggedValue') = mkRename (\f rn (Tagged tg e) -> Tagged tg (f rn e))
(renameTaggedSizedFVedTerm, renameTaggedSizedFVedAlts, renameTaggedSizedFVedValue, renameTaggedSizedFVedValue') = mkRename (\f rn (Comp (Tagged tg (Comp (Sized sz (FVed fvs e))))) -> Comp (Tagged tg (Comp (Sized sz (FVed (renameFreeVars rn fvs) (f rn e))))))
# INLINE mkRename #
mkRename :: (forall a. (Renaming -> a -> a) -> Renaming -> ann a -> ann a)
-> (InScopeSet -> Renaming -> ann (TermF ann) -> ann (TermF ann),
InScopeSet -> Renaming -> [AltF ann] -> [AltF ann],
InScopeSet -> Renaming -> ann (ValueF ann) -> ann (ValueF ann),
InScopeSet -> Renaming -> ValueF ann -> ValueF ann)
mkRename rec = (term, alternatives, value, value')
where
term ids rn = rec (term' ids) rn
term' ids rn e = case e of
Var x -> Var (renameId rn x)
Value v -> Value (value' ids rn v)
TyApp e ty -> TyApp (term ids rn e) (renameType ids rn ty)
CoApp e co -> CoApp (term ids rn e) (renameCoercion ids rn co)
App e x -> App (term ids rn e) (renameId rn x)
PrimOp pop tys es -> PrimOp pop (map (renameType ids rn) tys) (map (term ids rn) es)
Case e x ty alts -> Case (term ids rn e) x' (renameType ids rn ty) (alternatives ids' rn' alts)
where (ids', rn', x') = renameNonRecBinder ids rn x
Let x e1 e2 -> Let x' (renameIn (term ids) in_e1) (term ids' rn' e2)
where (ids', rn', (x', in_e1)) = renameNonRecBound ids rn (x, e1)
LetRec xes e -> LetRec (map (second (renameIn (term ids'))) xes') (term ids' rn' e)
where (ids', rn', xes') = renameBounds ids rn xes
Cast e co -> Cast (term ids rn e) (renameCoercion ids rn co)
value ids rn = rec (value' ids) rn
value' ids rn v = renameValueG term ids rn v
alternatives ids rn = map (alternative ids rn)
alternative ids rn (alt_con, alt_e) = (alt_con', term ids' rn' alt_e)
where (ids', rn', alt_con') = renameAltCon ids rn alt_con
renameValueG :: (InScopeSet -> Renaming -> a -> b)
-> InScopeSet -> Renaming -> ValueG a -> ValueG b
renameValueG term ids rn v = case v of
TyLambda x e -> TyLambda x' (term ids' rn' e)
where (ids', rn', x') = renameNonRecBinder ids rn x
Lambda x e -> Lambda x' (term ids' rn' e)
where (ids', rn', x') = renameNonRecBinder ids rn x
Data dc tys cos xs -> Data dc (map (renameType ids rn) tys) (map (renameCoercion ids rn) cos) (map (renameId rn) xs)
Literal l -> Literal l
Coercion co -> Coercion (renameCoercion ids rn co)
renameAltCon :: InScopeSet -> Renaming -> AltCon -> (InScopeSet, Renaming, AltCon)
renameAltCon ids rn_alt alt_con = case alt_con of
DataAlt alt_dc alt_as alt_qs alt_xs -> third3 (DataAlt alt_dc alt_as' alt_qs') $ renameNonRecBinders ids1 rn_alt1 alt_xs
where (ids0, rn_alt0, alt_as') = renameNonRecBinders ids rn_alt alt_as
(ids1, rn_alt1, alt_qs') = renameNonRecBinders ids0 rn_alt0 alt_qs
LiteralAlt _ -> (ids, rn_alt, alt_con)
DefaultAlt -> (ids, rn_alt, alt_con)
| null | https://raw.githubusercontent.com/osa1/sc-plugin/1969ad81f16ca8ed8110ca8dadfccf6f3d463635/src/Supercompile/Core/Renaming.hs | haskell | # LANGUAGE Rank2Types #
| Extending the renaming
| Querying the renaming
| Things with associated renamings
| Renaming variables occurrences and binding sites
| Renaming actual bits of syntax
ever substitute variables for variables. The reasons for this are twofold:
Unfortunately, in order to make this work with the coercionful operational semantics
we will sometimes need to substitute coerced variables for variables. An example would be
when reducing:
Where
We need to reduce to something like:
We deal with this problem in the evaluator by introducing an intermediate let binding for
such redexes.
will only be added to the IdSubstEnv *if the unique changes*.
This is a problem for us because we only store the Renaming with each In thing,
The solution is either:
It also means you have te be very careful to join together InScopeSets if you
is easy to get wrong.
out that I managed to achieve deforestation in all of the callers by rewriting them to use this
version instead.
Id continuation
CoVar continuation
FIXME: this inversion relies on something of a hack because the domain of the mapping is not stored (only its Unique)
Furthermore, we want to carefully rename the *types* (and extra info, if we actually preserved any) as well when doing
this inversion so that the renaming {a |-> b, y |-> x :: b} is inverted to {b |-> a, x |-> y :: a}
So we don't replace global Ids with new local Ids! | # OPTIONS_GHC -fno - warn - missing - signatures #
module Supercompile.Core.Renaming (
|
Renaming, emptyRenaming,
mkInScopeIdentityRenaming, mkIdentityRenaming, mkTyVarRenaming, mkRenaming,
InScopeSet, emptyInScopeSet, mkInScopeSet,
| PreRenamings
PreRenaming, invertRenaming, composeRenamings,
restrictRenaming,
insertVarRenaming,
insertIdRenaming, insertIdRenamings,
insertTypeSubst, insertTypeSubsts,
insertCoercionSubst, insertCoercionSubsts,
renameId, lookupTyVarSubst, lookupCoVarSubst,
In, Out,
inFreeVars, renameFreeVars, renameIn,
renameType, renameCoercion,
renameBinders, renameNonRecBinder, renameNonRecBinders,
renameBounds, renameNonRecBound,
renameValueG, renameAltCon,
renameTerm, renameAlts, renameValue, renameValue',
renameFVedTerm, renameFVedAlts, renameFVedValue, renameFVedValue',
renameTaggedTerm, renameTaggedAlts, renameTaggedValue, renameTaggedValue',
renameTaggedSizedFVedTerm, renameTaggedSizedFVedAlts, renameTaggedSizedFVedValue, renameTaggedSizedFVedValue'
) where
import Supercompile.Core.FreeVars
import Supercompile.Core.Syntax
import Supercompile.Utilities
import CoreSubst
import OptCoercion (optCoercion)
import Coercion (CvSubst(..), CvSubstEnv, isCoVar, mkCoVarCo, getCoVar_maybe)
import qualified CoreSyn as CoreSyn (CoreExpr, Expr(Var))
import Type (mkTyVarTy, getTyVar_maybe)
import Id (mkSysLocal)
import Var (Id, TyVar, CoVar, isTyVar, mkTyVar, varType, isGlobalId, varUnique)
import OccName (occNameFS)
import Name (getOccName, mkSysTvName)
import FastString (FastString)
import UniqFM (ufmToList)
import VarEnv
import Control.Monad.Fix (mfix)
import qualified Data.Map as M
We are going to use GHC 's substitution type in a rather stylised way , and only
1 . Particularly since we are in ANF , doing any other sort of substitution is unnecessary
2 . We have our own syntax data type , and we do n't want to build a GHC syntax tree just
for insertion into the Subst if we can help it !
( \x . e ) | > gam y
gam = ( F Int - > F Int ~ Bool - > Bool )
e[(y | > sym ( nth 1 gam))/x ] | > ( nth 2 gam )
type Renaming = (IdSubstEnv, TvSubstEnv, CvSubstEnv)
joinSubst :: InScopeSet -> Renaming -> Subst
joinSubst iss (id_subst, tv_subst, co_subst) = mkSubst iss tv_subst co_subst id_subst
GHC 's binder - renaming stuff does this awful thing where a var->var renaming
will always be added to the InScopeSet ( which is really an InScopeMap ) but
not the full Subst . So we might lose some renamings recorded only in the InScopeSet .
1 ) Rewrite the rest of the supercompiler so it stores a Subst with each binding .
Given the behaviour of GHCs binder - renamer , this is probably cleaner ( and matches
what the GHC does ) , but I 'm not really interested in doing that work right now .
pull one of those Subst - paired things down into a strictly deeper context . This
2 ) Ensure that we always extend the IdSubstEnv , regardless of whether the unique changed .
This is the solution I 've adopted , and it is implemented here in splitSubst :
splitSubst :: Subst -> [(Var, Var)] -> (InScopeSet, Renaming)
splitSubst (Subst iss id_subst tv_subst co_subst) extend
= (iss, foldVarlikes (\f -> foldr (\x_x' -> f (fst x_x') x_x')) extend
(\(x, x') -> first3 (\id_subst -> extendVarEnv id_subst x (mkIdExpr x')))
(\(a, a') -> second3 (\tv_subst -> extendVarEnv tv_subst a (mkTyVarTy a')))
(\(q, q') -> third3 (\co_subst -> extendVarEnv co_subst q (mkCoVarCo q')))
(id_subst, tv_subst, co_subst))
NB : this used to return a triple of lists , but I introduced this version due to profiling
results that indicated a caller ( renameFreeVars ) was causing 2 % of all allocations . It turns
# INLINE foldVarlikes #
foldVarlikes :: ((Var -> a -> b -> b) -> b -> f_a -> b)
-> f_a
TyVar continuation
-> b -> b
foldVarlikes fold as id tv co acc = fold go acc as
where go x a res | isTyVar x = tv a res
| isCoVar x = co a res
| otherwise = id a res
emptyRenaming :: Renaming
emptyRenaming = (emptyVarEnv, emptyVarEnv, emptyVarEnv)
mkIdentityRenaming :: FreeVars -> Renaming
mkIdentityRenaming fvs = foldVarlikes (\f -> foldVarSet (\x -> f x x)) fvs
(\x -> first3 (\id_subst -> extendVarEnv id_subst x (mkIdExpr x)))
(\a -> second3 (\tv_subst -> extendVarEnv tv_subst a (mkTyVarTy a)))
(\q -> third3 (\co_subst -> extendVarEnv co_subst q (mkCoVarCo q)))
(emptyVarEnv, emptyVarEnv, emptyVarEnv)
mkInScopeIdentityRenaming :: InScopeSet -> Renaming
mkInScopeIdentityRenaming = mkIdentityRenaming . getInScopeVars
mkTyVarRenaming :: [(TyVar, Type)] -> Renaming
mkTyVarRenaming aas = (emptyVarEnv, mkVarEnv aas, emptyVarEnv)
mkRenaming :: M.Map Var Var -> Renaming
mkRenaming rn = foldVarlikes (\f -> M.foldWithKey (\x x' -> f x (x, x'))) rn
(\(x, x') -> first3 (\id_subst -> extendVarEnv id_subst x (mkIdExpr x')))
(\(a, a') -> second3 (\tv_subst -> extendVarEnv tv_subst a (mkTyVarTy a')))
(\(q, q') -> third3 (\co_subst -> extendVarEnv co_subst q (mkCoVarCo q')))
(emptyVarEnv, emptyVarEnv, emptyVarEnv)
type PreRenaming = (VarEnv Id, VarEnv TyVar, VarEnv CoVar)
NB : the output Vars in the range of the mappings are dodgy and should really only be used for
their Uniques . I turn them into full Ids mostly for convenience .
NB : the InScopeSet should be that of the * domain * of the renaming ( I think ! )
NB : I used to return a real * Renaming * as the result , but that was n't very convenient for the MSG caller :
1 . It hides the fact that looking up a CoVar / TyVar always yields a variable
2 . It does n't let us easily test if a variable is actually present in the domain of the inverted renaming
invertRenaming :: InScopeSet -> Renaming -> Maybe PreRenaming
invertRenaming ids (id_subst, tv_subst, co_subst)
invertVarEnv :: (FastString -> Unique -> Type -> Var)
-> VarEnv Var -> Maybe (VarEnv Var)
invertVarEnv mk env
| distinct (varEnvElts env) = Just (mkVarEnv [ (x, if isGlobalId x && u == varUnique x
else mk (occNameFS (getOccName x)) u (renameType ids (mkRenaming' rn) (varType x)))
| (u, x) <- ufmToList env])
| otherwise = Nothing
in liftM3 (,,) (traverse getId_maybe id_subst >>= invertVarEnv mkSysLocal)
(traverse getTyVar_maybe tv_subst >>= invertVarEnv (\fs uniq -> mkTyVar (mkSysTvName uniq fs)))
(traverse getCoVar_maybe co_subst >>= invertVarEnv mkSysLocal)
where
mkRenaming' :: PreRenaming -> Renaming
mkRenaming' (xxs, aas, qqs) = (mapVarEnv mkIdExpr xxs,
mapVarEnv mkTyVarTy aas,
mapVarEnv mkCoVarCo qqs)
composeRenamings :: PreRenaming -> Renaming -> Renaming
composeRenamings (id_subst1, tv_subst1, co_subst1) rn2
= (mapVarEnv (mkIdExpr . renameId rn2) id_subst1,
mapVarEnv (lookupTyVarSubst rn2) tv_subst1,
mapVarEnv (lookupCoVarSubst rn2) co_subst1)
restrictRenaming :: Renaming -> VarSet -> Renaming
restrictRenaming (id_subst, tv_subst, co_subst) fvs = (id_subst `restrictVarEnv` fvs, tv_subst `restrictVarEnv` fvs, co_subst `restrictVarEnv` fvs)
mkIdExpr :: Id -> CoreSyn.CoreExpr
mkIdExpr = CoreSyn.Var
getId_maybe :: CoreSyn.CoreExpr -> Maybe Id
getId_maybe (CoreSyn.Var x') = Just x'
getId_maybe _ = Nothing
coreSynToVar :: CoreSyn.CoreExpr -> Var
coreSynToVar = fromMaybe (panic "renameId" empty) . getId_maybe
insertVarRenaming :: Renaming -> Var -> Out Var -> Renaming
insertVarRenaming rn x y
| isTyVar x = insertTypeSubst rn x (mkTyVarTy y)
| isCoVar x = insertCoercionSubst rn x (mkCoVarCo y)
| otherwise = insertIdRenaming rn x y
insertIdRenaming :: Renaming -> Id -> Out Id -> Renaming
insertIdRenaming (id_subst, tv_subst, co_subst) x x'
= (extendVarEnv id_subst x (mkIdExpr x'), tv_subst, co_subst)
insertIdRenamings :: Renaming -> [(Id, Out Id)] -> Renaming
insertIdRenamings = foldr (\(x, x') rn -> insertIdRenaming rn x x')
insertTypeSubst :: Renaming -> TyVar -> Out Type -> Renaming
insertTypeSubst (id_subst, tv_subst, co_subst) x ty' = (id_subst, extendVarEnv tv_subst x ty', co_subst)
insertTypeSubsts :: Renaming -> [(TyVar, Out Type)] -> Renaming
insertTypeSubsts (id_subst, tv_subst, co_subst) xtys = (id_subst, extendVarEnvList tv_subst xtys, co_subst)
insertCoercionSubst :: Renaming -> CoVar -> Out Coercion -> Renaming
insertCoercionSubst (id_subst, tv_subst, co_subst) x co' = (id_subst, tv_subst, extendVarEnv co_subst x co')
insertCoercionSubsts :: Renaming -> [(CoVar, Out Coercion)] -> Renaming
insertCoercionSubsts (id_subst, tv_subst, co_subst) xcos = (id_subst, tv_subst, extendVarEnvList co_subst xcos)
NB : these three function can supply emptyInScopeSet because of what I do in splitSubst
renameId :: Renaming -> Id -> Out Id
renameId rn = coreSynToVar . lookupIdSubst (text "renameId") (joinSubst emptyInScopeSet rn)
lookupTyVarSubst :: Renaming -> TyVar -> Out Type
lookupTyVarSubst rn = lookupTvSubst (joinSubst emptyInScopeSet rn)
lookupCoVarSubst :: Renaming -> CoVar -> Out Coercion
lookupCoVarSubst rn = lookupCvSubst (joinSubst emptyInScopeSet rn)
type In a = (Renaming, a)
type Out a = a
inFreeVars :: (a -> FreeVars) -> In a -> FreeVars
inFreeVars thing_fvs (rn, thing) = renameFreeVars rn (thing_fvs thing)
renameFreeVars :: Renaming -> FreeVars -> FreeVars
renameFreeVars rn fvs = foldVarlikes (\f -> foldVarSet (\x -> f x x)) fvs
(\x -> flip extendVarSet (renameId rn x))
(\a -> unionVarSet (tyVarsOfType (lookupTyVarSubst rn a)))
(\q -> unionVarSet (tyCoVarsOfCo (lookupCoVarSubst rn q)))
emptyVarSet
renameType :: InScopeSet -> Renaming -> Type -> Type
renameType iss rn = substTy (joinSubst iss rn)
renameCoercion :: InScopeSet -> Renaming -> Coercion -> NormalCo
renameCoercion iss (_, tv_subst, co_subst) = optCoercion (CvSubst iss tv_subst co_subst)
renameIn :: (Renaming -> a -> a) -> In a -> a
renameIn f (rn, x) = f rn x
renameBinders :: InScopeSet -> Renaming -> [Var] -> (InScopeSet, Renaming, [Var])
renameBinders iss rn xs = (iss', rn', xs')
where (subst', xs') = substRecBndrs (joinSubst iss rn) xs
(iss', rn') = splitSubst subst' (xs `zip` xs')
renameNonRecBinder :: InScopeSet -> Renaming -> Var -> (InScopeSet, Renaming, Var)
renameNonRecBinder iss rn x = (iss', rn', x')
where (subst', x') = substBndr (joinSubst iss rn) x
(iss', rn') = splitSubst subst' [(x, x')]
renameNonRecBinders :: InScopeSet -> Renaming -> [Var] -> (InScopeSet, Renaming, [Var])
renameNonRecBinders iss rn xs = (iss', rn', xs')
where (subst', xs') = substBndrs (joinSubst iss rn) xs
(iss', rn') = splitSubst subst' (xs `zip` xs')
renameBounds :: InScopeSet -> Renaming -> [(Var, a)] -> (InScopeSet, Renaming, [(Var, In a)])
renameBounds iss rn xes = (iss', rn', xs' `zip` map ((,) rn') es)
where (xs, es) = unzip xes
(iss', rn', xs') = renameBinders iss rn xs
renameNonRecBound :: InScopeSet -> Renaming -> (Var, a) -> (InScopeSet, Renaming, (Var, In a))
renameNonRecBound iss rn (x, e) = (iss', rn', (x', (rn, e)))
where (iss', rn', x') = renameNonRecBinder iss rn x
(renameTerm, renameAlts, renameValue, renameValue') = mkRename (\f rn (I e) -> I (f rn e))
(renameFVedTerm, renameFVedAlts, renameFVedValue, renameFVedValue') = mkRename (\f rn (FVed fvs e) -> FVed (renameFreeVars rn fvs) (f rn e))
(renameTaggedTerm, renameTaggedAlts, renameTaggedValue, renameTaggedValue') = mkRename (\f rn (Tagged tg e) -> Tagged tg (f rn e))
(renameTaggedSizedFVedTerm, renameTaggedSizedFVedAlts, renameTaggedSizedFVedValue, renameTaggedSizedFVedValue') = mkRename (\f rn (Comp (Tagged tg (Comp (Sized sz (FVed fvs e))))) -> Comp (Tagged tg (Comp (Sized sz (FVed (renameFreeVars rn fvs) (f rn e))))))
# INLINE mkRename #
mkRename :: (forall a. (Renaming -> a -> a) -> Renaming -> ann a -> ann a)
-> (InScopeSet -> Renaming -> ann (TermF ann) -> ann (TermF ann),
InScopeSet -> Renaming -> [AltF ann] -> [AltF ann],
InScopeSet -> Renaming -> ann (ValueF ann) -> ann (ValueF ann),
InScopeSet -> Renaming -> ValueF ann -> ValueF ann)
mkRename rec = (term, alternatives, value, value')
where
term ids rn = rec (term' ids) rn
term' ids rn e = case e of
Var x -> Var (renameId rn x)
Value v -> Value (value' ids rn v)
TyApp e ty -> TyApp (term ids rn e) (renameType ids rn ty)
CoApp e co -> CoApp (term ids rn e) (renameCoercion ids rn co)
App e x -> App (term ids rn e) (renameId rn x)
PrimOp pop tys es -> PrimOp pop (map (renameType ids rn) tys) (map (term ids rn) es)
Case e x ty alts -> Case (term ids rn e) x' (renameType ids rn ty) (alternatives ids' rn' alts)
where (ids', rn', x') = renameNonRecBinder ids rn x
Let x e1 e2 -> Let x' (renameIn (term ids) in_e1) (term ids' rn' e2)
where (ids', rn', (x', in_e1)) = renameNonRecBound ids rn (x, e1)
LetRec xes e -> LetRec (map (second (renameIn (term ids'))) xes') (term ids' rn' e)
where (ids', rn', xes') = renameBounds ids rn xes
Cast e co -> Cast (term ids rn e) (renameCoercion ids rn co)
value ids rn = rec (value' ids) rn
value' ids rn v = renameValueG term ids rn v
alternatives ids rn = map (alternative ids rn)
alternative ids rn (alt_con, alt_e) = (alt_con', term ids' rn' alt_e)
where (ids', rn', alt_con') = renameAltCon ids rn alt_con
renameValueG :: (InScopeSet -> Renaming -> a -> b)
-> InScopeSet -> Renaming -> ValueG a -> ValueG b
renameValueG term ids rn v = case v of
TyLambda x e -> TyLambda x' (term ids' rn' e)
where (ids', rn', x') = renameNonRecBinder ids rn x
Lambda x e -> Lambda x' (term ids' rn' e)
where (ids', rn', x') = renameNonRecBinder ids rn x
Data dc tys cos xs -> Data dc (map (renameType ids rn) tys) (map (renameCoercion ids rn) cos) (map (renameId rn) xs)
Literal l -> Literal l
Coercion co -> Coercion (renameCoercion ids rn co)
renameAltCon :: InScopeSet -> Renaming -> AltCon -> (InScopeSet, Renaming, AltCon)
renameAltCon ids rn_alt alt_con = case alt_con of
DataAlt alt_dc alt_as alt_qs alt_xs -> third3 (DataAlt alt_dc alt_as' alt_qs') $ renameNonRecBinders ids1 rn_alt1 alt_xs
where (ids0, rn_alt0, alt_as') = renameNonRecBinders ids rn_alt alt_as
(ids1, rn_alt1, alt_qs') = renameNonRecBinders ids0 rn_alt0 alt_qs
LiteralAlt _ -> (ids, rn_alt, alt_con)
DefaultAlt -> (ids, rn_alt, alt_con)
|
6ee75e148a8176ccdac32c37f1e93996180ac97097086fc63c5f52749a82a941 | rain-1/single_cream | rle.scm | ;(define (run-length-decode v)
; (apply string-append (map (lambda (p) (make-string (car p) (cdr p))) v)))
(define (run-length-encode s)
((lambda (n)
(run-length-encode/loop s (- n 2) (string-ref s (- n 1)) 1 '()))
(string-length s)))
(define (run-length-encode/loop s i c k v)
(if (negative? i)
(cons (cons k c) v)
((lambda (x)
(if (char=? c x)
(run-length-encode/loop s (- i 1) c (+ k 1) v)
(run-length-encode/loop s (- i 1) x 1 (cons (cons k c) v))))
(string-ref s i))))
(run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")
( ( 12 . # \W ) ( 1 . # \B ) ( 12 . # \W ) ( 3 . # \B ) ( 24 . # \W ) ( 1 . # \B ) ( 14 . # \W ) )
| null | https://raw.githubusercontent.com/rain-1/single_cream/f8989fde4bfcffe0af7f6ed5916885446bf40124/t/rosetta/rle.scm | scheme | (define (run-length-decode v)
(apply string-append (map (lambda (p) (make-string (car p) (cdr p))) v))) |
(define (run-length-encode s)
((lambda (n)
(run-length-encode/loop s (- n 2) (string-ref s (- n 1)) 1 '()))
(string-length s)))
(define (run-length-encode/loop s i c k v)
(if (negative? i)
(cons (cons k c) v)
((lambda (x)
(if (char=? c x)
(run-length-encode/loop s (- i 1) c (+ k 1) v)
(run-length-encode/loop s (- i 1) x 1 (cons (cons k c) v))))
(string-ref s i))))
(run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")
( ( 12 . # \W ) ( 1 . # \B ) ( 12 . # \W ) ( 3 . # \B ) ( 24 . # \W ) ( 1 . # \B ) ( 14 . # \W ) )
|
3925255e37f44f239348cb796ac658e04b4c9fe8ce9928cbf6161b7d3397e490 | uim/uim | generic-predict.scm | ;;; generic-predict.scm: generic prediction base class
;;;
Copyright ( c ) 2009 - 2013 uim Project
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . 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.
3 . Neither the name of authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
;;; SUCH DAMAGE.
;;;;
(require-extension (srfi 1 48))
(require "util.scm")
(require "wlos.scm")
(require "light-record.scm")
(require-custom "predict-custom.scm")
(define-list-record predict-result
'((word "")
(cands ()) ;; list of string
(appendix ()))) ;; list of string
(define-class predict object
'((limit 10)
(internal-charset "UTF-8")
(external-charset "UTF-8"))
'(open
close
search
commit
convert-charset
>internal-charset
>external-charset))
(class-set-method! predict open
(lambda (self im-name)
#t))
(class-set-method! predict close
(lambda (self)
#t))
(class-set-method! predict search
(lambda (self str)
(make-predict-result str str '())))
(class-set-method! predict commit
(lambda (self word cand appendix)
#t))
(class-set-method! predict convert-charset
(lambda (self str tocode fromcode)
(iconv-convert tocode fromcode str)))
(class-set-method! predict >internal-charset
(lambda (self str)
(predict-convert-charset
self
str
(predict-internal-charset self)
(predict-external-charset self))))
(class-set-method! predict >external-charset
(lambda (self str)
(predict-convert-charset
self
str
(predict-external-charset self)
(predict-internal-charset self))))
(for-each try-load
'("predict-look.scm"
"predict-look-skk.scm"
"predict-sqlite3.scm"
"predict-google-suggest.scm"))
;;
;; uim-custom specific settings
;;
(define-macro (make-predict-make-meta-search methods)
`(if predict-custom-enable?
(map-in-order (lambda (m)
(let ((method (find (lambda (x)
(eq? m x))
,methods)))
(if method
(string->symbol
(format "make-predict-~a-with-custom" method))
(error (N_ "unknown prediction method")))))
predict-custom-methods)
'()))
(define (predict-make-meta-search)
(map-in-order (lambda (m)
(eval (list m) (interaction-environment)))
(make-predict-make-meta-search '(look look-skk sqlite3 google-suggest))))
(define (predict-meta-open methods im-name)
(for-each (lambda (obj)
(predict-open obj im-name))
methods))
(define (predict-meta-search methods str)
(map-in-order (lambda (obj)
(predict-search obj str))
methods))
(define (predict-meta-select-result results thunk)
(apply append
(filter (lambda (x)
(not (null? x)))
(map thunk results))))
(define (predict-meta-word? results)
(predict-meta-select-result results predict-result-word))
(define (predict-meta-candidates? results)
(predict-meta-select-result results predict-result-cands))
(define (predict-meta-appendix? results)
(predict-meta-select-result results predict-result-appendix))
(define (predict-meta-set-external-charset! methods external-charset)
(for-each (lambda (obj)
(predict-set-external-charset! obj external-charset))
methods))
(define (predict-meta-set-internal-charset! methods external-charset)
(for-each (lambda (obj)
(predict-set-internal-charset! obj external-charset))
methods))
(define (predict-meta-commit methods word cands appendix)
(for-each (lambda (obj)
(predict-commit obj word cands appendix))
methods))
| null | https://raw.githubusercontent.com/uim/uim/d1ac9d9315ff8c57c713b502544fef9b3a83b3e5/scm/generic-predict.scm | scheme | generic-predict.scm: generic prediction base class
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
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.
list of string
list of string
uim-custom specific settings
| Copyright ( c ) 2009 - 2013 uim Project
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(require-extension (srfi 1 48))
(require "util.scm")
(require "wlos.scm")
(require "light-record.scm")
(require-custom "predict-custom.scm")
(define-list-record predict-result
'((word "")
(define-class predict object
'((limit 10)
(internal-charset "UTF-8")
(external-charset "UTF-8"))
'(open
close
search
commit
convert-charset
>internal-charset
>external-charset))
(class-set-method! predict open
(lambda (self im-name)
#t))
(class-set-method! predict close
(lambda (self)
#t))
(class-set-method! predict search
(lambda (self str)
(make-predict-result str str '())))
(class-set-method! predict commit
(lambda (self word cand appendix)
#t))
(class-set-method! predict convert-charset
(lambda (self str tocode fromcode)
(iconv-convert tocode fromcode str)))
(class-set-method! predict >internal-charset
(lambda (self str)
(predict-convert-charset
self
str
(predict-internal-charset self)
(predict-external-charset self))))
(class-set-method! predict >external-charset
(lambda (self str)
(predict-convert-charset
self
str
(predict-external-charset self)
(predict-internal-charset self))))
(for-each try-load
'("predict-look.scm"
"predict-look-skk.scm"
"predict-sqlite3.scm"
"predict-google-suggest.scm"))
(define-macro (make-predict-make-meta-search methods)
`(if predict-custom-enable?
(map-in-order (lambda (m)
(let ((method (find (lambda (x)
(eq? m x))
,methods)))
(if method
(string->symbol
(format "make-predict-~a-with-custom" method))
(error (N_ "unknown prediction method")))))
predict-custom-methods)
'()))
(define (predict-make-meta-search)
(map-in-order (lambda (m)
(eval (list m) (interaction-environment)))
(make-predict-make-meta-search '(look look-skk sqlite3 google-suggest))))
(define (predict-meta-open methods im-name)
(for-each (lambda (obj)
(predict-open obj im-name))
methods))
(define (predict-meta-search methods str)
(map-in-order (lambda (obj)
(predict-search obj str))
methods))
(define (predict-meta-select-result results thunk)
(apply append
(filter (lambda (x)
(not (null? x)))
(map thunk results))))
(define (predict-meta-word? results)
(predict-meta-select-result results predict-result-word))
(define (predict-meta-candidates? results)
(predict-meta-select-result results predict-result-cands))
(define (predict-meta-appendix? results)
(predict-meta-select-result results predict-result-appendix))
(define (predict-meta-set-external-charset! methods external-charset)
(for-each (lambda (obj)
(predict-set-external-charset! obj external-charset))
methods))
(define (predict-meta-set-internal-charset! methods external-charset)
(for-each (lambda (obj)
(predict-set-internal-charset! obj external-charset))
methods))
(define (predict-meta-commit methods word cands appendix)
(for-each (lambda (obj)
(predict-commit obj word cands appendix))
methods))
|
169908a04b88c2ee75988fac6d2d2a88759c257dab75b87b0e8db3f847b2b2d4 | racket/games | moves.rkt | #lang racket
(require "board.rkt")
;; a move is either:
;; - (make-enter-piece pawn)
;; - (make-move-piece-main pawn start distance)
;; - (make-move-piece-home pawn start distance)
(define-struct move () #:inspector (make-inspector))
(define-struct (enter-piece move) (pawn) #:inspector (make-inspector))
(define-struct (move-piece-main move) (pawn start distance) #:inspector (make-inspector))
(define-struct (move-piece-home move) (pawn start distance) #:inspector (make-inspector))
(provide/contract
(struct enter-piece ((pawn pawn?)))
(struct move-piece-main ([pawn pawn?] [start number?] [distance number?]))
(struct move-piece-home ([pawn pawn?] [start number?] [distance number?])))
(provide take-turn
bad-move
make-moves
move?
board-enter-piece
board-move-piece-main
board-move-piece-home
blockade-moved?
find-end-spot
board-doubles-penalty
make-one-move
get-move-id
get-move-color
has-entering-roll?
entering-blockade?
exn:bad-move?
exn:bad-move-with-info?
exn:bad-move-with-info-color
exn:bad-move-with-info-board
exn:bad-move-with-info-dice
exn:bad-move-with-info-moves
board-all-in?
<=/m
possible-to-move)
(define bop-bonus 20)
(define home-bonus 10)
moves - dice : moves - > ( listof number )
;; does not return the die moves that correspond to entering pawns
(define (moves-dice moves)
(let loop ([moves moves]
[dice null])
(cond
[(null? moves) dice]
[else
(let ([move (car moves)])
(cond
[(move-piece-main? move)
(loop (cdr moves) (cons (move-piece-main-distance move) dice))]
[(move-piece-home? move)
(loop (cdr moves) (cons (move-piece-home-distance move) dice))]
[else (loop (cdr moves) dice)]))])))
;; board-doubles-penalty : board color -> board
(define (board-doubles-penalty board color)
(let home-row-loop ([i board-home-row-size])
(cond
[(zero? i)
(let main-board-loop ([i (get-enter-pos color)]
[first-time? #t])
(cond
[(and (not first-time?) (= i (get-enter-pos color)))
board]
[else
(let* ([next-i (modulo (- i 1) board-main-size)]
[ent (board-main-i board next-i)])
(if (and (pair? ent)
(eq? (pawn-color (car ent)) color))
(move-piece board (car ent) 'start)
(main-board-loop next-i #f)))]))]
[else
(let ([ent (board-home-row-i board color (- i 1))])
(if (null? ent)
(home-row-loop (- i 1))
(move-piece board (car ent) 'start)))])))
take - turn : color board ( listof number ) ( listof move ) - > board
;; raises an exception if the turn is illegal
(define (take-turn color original-board original-dice original-moves)
(parameterize ([current-color/board/dice/moves
(list color original-board original-dice original-moves)])
(unless (andmap (lambda (x) (eq? color (get-move-color x))) original-moves)
(bad-move "attempted to move two different colors"))
(let loop ([moves original-moves]
[board original-board]
[dice original-dice])
(cond
[(null? moves)
(when (and (has-entering-roll? dice)
(memf (lambda (pawn) (eq? (pawn-color pawn) color))
(board-start board)) ;; has pieces in start
(not (entering-blockade? board color)))
(bad-move "can still enter a pawn"))
(let ([used-dice (moves-dice original-moves)])
(for-each (lambda (die)
(let ([potential-board (possible-to-move color board die)])
(when potential-board
(unless (blockade-moved? original-board potential-board color)
(bad-move "die roll ~a can still be used" die)))))
dice)
(when (blockade-moved? original-board board color)
(bad-move "cannot move blockade together")))
board]
[else
(let ([move (car moves)])
(let-values ([(new-board bonus new-dice)
(make-move/dice board move dice)])
(let ([new-new-dice (if bonus
(cons bonus new-dice)
new-dice)])
(loop (cdr moves)
new-board
new-new-dice))))]))))
;; get-move-color : move -> symbol
;; extracts the moved color from the move
(define (get-move-color move) (pawn-color (get-move-pawn move)))
;; get-move-id : move -> number
(define (get-move-id move) (pawn-id (get-move-pawn move)))
(define (get-move-pawn move)
(cond
[(enter-piece? move) (enter-piece-pawn move)]
[(move-piece-main? move) (move-piece-main-pawn move)]
[(move-piece-home? move) (move-piece-home-pawn move)]))
;; blocakde-moved? : board board color -> boolean
(define (blockade-moved? original-board new-board color)
(let ([original-blockades (find-blockades/color original-board color)]
[new-blockades (find-blockades/color new-board color)])
(ormap (lambda (new-blockade) (memf (same-blockade-different-place? new-blockade) original-blockades))
new-blockades)))
(define ((same-blockade-different-place? b1) b2)
(and (equal? (blockade-p1 b1) (blockade-p1 b2))
(equal? (blockade-p2 b1) (blockade-p2 b2))
(not (equal? (blockade-loc b1) (blockade-loc b2)))))
make - move / dice : board move ( listof number ) number - > ( values board bonus ( listof number ) )
;; makes the given move, removing the used dice from the dice list.
;; raises an error if the move isn't legal.
check for : using a five to move when there are pieces to come in
;; moving without the matching roll
(define (make-move/dice board move dice)
(cond
[(enter-piece? move)
(let ([new-dice (cond
[(memq 5 dice) (remq 5 dice)]
[(and (memq 1 dice) (memq 4 dice))
(remq 1 (remq 4 dice))]
[(and (memq 2 dice) (memq 3 dice))
(remq 2 (remq 3 dice))]
[else (bad-move "entered without having a 5")])])
(let-values ([(board bonus) (board-enter-piece board (enter-piece-pawn move))])
(values board bonus new-dice)))]
[(move-piece-main? move)
(do-move/dice/moving board dice
(move-piece-main-distance move)
(move-piece-main-pawn move)
(move-piece-main-start move)
board-move-piece-main)]
[(move-piece-home? move)
(do-move/dice/moving board dice
(move-piece-home-distance move)
(move-piece-home-pawn move)
(move-piece-home-start move)
board-move-piece-home)]))
helper function to collapse last two cases of make - move / dice
(define (do-move/dice/moving board dice die pawn start board-move-piece)
(let ([new-dice (remq die dice)])
(unless (memq die dice)
(bad-move "tried to move ~a squares but dice read ~a" die dice))
(let-values ([(new-board bonus)
(board-move-piece board pawn start die)])
(values new-board bonus new-dice))))
;; entering-blocade? : board symbol -> boolean
(define (entering-blockade? board color)
(let ([ent (board-main-i board (get-enter-pos color))])
(and (pair? ent) (pair? (cdr ent)))))
(define (no-blockades board start end)
(let ([ind (find-blockade/between board start end)])
(cond
[(not ind) (void)]
[(number? ind)
(bad-move "there is a blockade at ~a in the main ring" ind)]
[(home-row-loc? ind)
(bad-move "there is a blockade at ~a in the ~a home row"
(home-row-loc-num ind)
(home-row-loc-color ind))]
[else (bad-move "blockade in the way")])))
has - entering - roll ? : ( listof number ) - > boolean
(define (has-entering-roll? dice)
(or (memq 5 dice)
(and (memq 1 dice) (memq 4 dice))
(and (memq 2 dice) (memq 3 dice))))
;; possible-to-move : symbol board number -> (union #f board)
;; indicates if there are any moves that could happen with the
;; given die, for the given color in the given board.
;; doesn't consider entering moves
(define (possible-to-move color board die)
(let/ec k
(for-each-pawn/loc
board
(lambda (pawn loc)
(when (and (eq? color (pawn-color pawn))
(not (symbol? loc)))
(with-handlers ([exn:bad-move? (lambda (x) #f)])
(cond
[(number? loc)
(let-values ([(board bonus) (board-move-piece-main board pawn loc die)])
(k board))]
[(home-row-loc? loc)
(let-values ([(board bonus) (board-move-piece-home board pawn (home-row-loc-num loc) die)])
(k board))])))))
#f))
make - moves : board ( listof move ) - > board ( listof number )
;; only checks that each move, in isloation, would be possible
(define (make-moves board moves)
(let loop ([board board]
[bonus '()]
[moves moves])
(cond
[(null? moves) (values board bonus)]
[else
(let-values ([(new-board new-bonus) (make-one-move board (car moves))])
(loop new-board
(if new-bonus (cons new-bonus bonus) bonus)
(cdr moves)))])))
make - one - move : board move - > board
(define (make-one-move board move)
(cond
[(enter-piece? move) (board-enter-piece board (enter-piece-pawn move))]
[(move-piece-main? move) (board-move-piece-main board
(move-piece-main-pawn move)
(move-piece-main-start move)
(move-piece-main-distance move))]
[(move-piece-home? move) (board-move-piece-home board
(move-piece-home-pawn move)
(move-piece-home-start move)
(move-piece-home-distance move))]))
(define (board-all-in? board color)
(not (memf (lambda (pawn) (eq? (pawn-color pawn) color))
(board-start board))))
;; enter-piece : board pawn -> (values board (union #f number))
(define (board-enter-piece orig-board pawn)
(unless (member pawn (board-start orig-board))
(bad-move "~a's pawn ~a is already on the board" (pawn-color pawn) (pawn-id pawn)))
;; move the color out of the starting area
(let* ([pos (get-enter-pos (pawn-color pawn))]
[old-ent (board-main-i orig-board pos)])
(when (= 2 (length old-ent))
(bad-move "cannot move out into a blockade"))
(cond
;; no bop
[(or (null? old-ent)
(eq? (pawn-color (car old-ent)) (pawn-color pawn)))
(values (move-piece orig-board pawn pos)
#f)]
;; bop
[else
(values (move-piece2
orig-board
pawn
pos
(car old-ent)
'start)
bop-bonus)])))
;; board-move-piece-home : board pawn number number -> (values board (union #f number))
;; result of #f indicates no bop; result of a color indicates who got bopped
(define (board-move-piece-home board pawn start distance)
(let* ([color (pawn-color pawn)]
[old (board-home-row-i board color start)])
(unless (member pawn old)
(bad-move "color ~a is not in the home row on ~a" (pawn-color pawn) start))
(unless (and (<= 0 start) (< start board-home-row-size))
(error 'boad-move-piece-home "bad start argument ~e" start))
(unless (<= 0 start (+ start distance) (+ board-home-row-size 1))
(bad-move "moved too far, off the end of the board"))
(let ([finish (+ start distance)])
(cond
[(= finish board-home-row-size)
(when (< start (- finish 1))
if only moving one square , then we do n't need to check blockades
;; this lets us satisfy the inputs to no-blockades
(no-blockades board
(make-home-row-loc (+ start 1) color)
(make-home-row-loc (- finish 1) color)))
(values (move-piece board pawn 'home)
home-bonus)]
[(< finish board-home-row-size)
(no-blockades board
(make-home-row-loc (+ start 1) color)
(make-home-row-loc finish color))
(let ([old-ent (board-home-row-i board color finish)])
(cond
[(or (null? old-ent)
(null? (cdr old-ent)))
(values (move-piece board
pawn
(make-home-row-loc finish color))
#f)]
[else
(bad-move "moved onto a blockade in the home row")]))]
[else
(bad-move "moved off of the end of the board")]))))
;; board-move-piece-main : board pawn number number -> (values board (union #f number))
;; result of #f indicates no bop; result of a color indicates who got bopped
(define (board-move-piece-main board pawn start distance)
(unless (member pawn (board-main-i board start))
(bad-move "color ~a (piece #~a) is not on square ~a"
(pawn-color pawn)
(pawn-id pawn)
start))
(let* ([color (pawn-color pawn)]
[landed (find-end-spot color start distance)]
[exit (get-exit-pos color)])
(cond
[(eq? landed 'too-far) (bad-move "moved off of the board")]
[(eq? landed 'home)
(no-blockades board
(modulo (+ start 1) board-main-size)
(make-home-row-loc (- board-home-row-size 1) color))
(values (move-piece board
pawn
'home)
10)]
[(eq? (car landed) 'home-row)
;; turned onto the exit ramp
(let* ([final-spot (cdr landed)])
(no-blockades board
(next-pos color start)
(make-home-row-loc final-spot color))
(let ([old (board-home-row-i board color final-spot)])
(when (and (pair? old)
(pair? (cdr old)))
(bad-move "cannot move onto a blockade"))
(values (move-piece board pawn (make-home-row-loc final-spot color))
#f)))]
[else
;; stayed on the main board
(let ([end (cdr landed)])
(let ([start+1 (modulo (+ start 1) board-main-size)])
(unless (= start+1 end)
(no-blockades board start+1 end)))
(let ([old-contents (board-main-i board end)])
(cond
;; no one there
[(null? old-contents)
(values (move-piece board pawn end)
#f)]
[(and (pair? old-contents)
(pair? (cdr old-contents)))
(bad-move "cannot move directly onto a blockade")]
already one of the same color on that spot
[(eq? (pawn-color (car old-contents)) color)
(values (move-piece board
pawn
end)
#f)]
;; attempt to bop on a safety -- illegal
[(safety? end)
(bad-move "cannot move onto a safety if someone else is already there")]
;; successful bop
[else
(values
(move-piece2 board
pawn
end
(car old-contents)
'start)
bop-bonus)])))])))
;; next-pos : color number -> (union number home-row-loc)
;; given a position on the main ring, it finds the next position
;; for the given color on the board.
(define (next-pos color pos)
(cond
[(= pos (get-exit-pos color))
(make-home-row-loc 0 color)]
[else
(modulo (+ pos 1) board-main-size)]))
;; find-end-spot : color number number -> (union 'too-far 'home (cons 'home-row number) (cons 'main number)))
(define (find-end-spot color start distance)
(let ([exit (get-exit-pos color)]
[end (modulo (+ start distance) board-main-size)])
(cond
[(and (<=/m start exit end)
(not (= exit end)))
(let* ([distance-to-exit (modulo (- exit start) board-main-size)]
[final-spot (- distance distance-to-exit 1)])
(cond
[(final-spot . = . board-home-row-size)
'home]
[(final-spot . < . board-home-row-size)
(cons 'home-row final-spot)]
[else
'too-far]))]
[else
(cons 'main end)])))
(define (<=/m one two three)
(or (<= one two three)
(<= two three one)
(<= three one two)))
(define-struct (exn:bad-move exn) ())
(define-struct (exn:bad-move-with-info exn:bad-move) (color board dice moves))
(define current-color/board/dice/moves (make-parameter #f))
(define (bad-move _str . args)
(define str (if (null? args) _str (apply format _str args)))
(raise
(cond
[(current-color/board/dice/moves)
(define-values (color board dice moves) (apply values (current-color/board/dice/moves)))
(make-exn:bad-move-with-info str (current-continuation-marks) color board dice moves)]
[else
(make-exn:bad-move str (current-continuation-marks))])))
| null | https://raw.githubusercontent.com/racket/games/e57376f067be51257ed12cdf3e4509a00ffd533d/parcheesi/moves.rkt | racket | a move is either:
- (make-enter-piece pawn)
- (make-move-piece-main pawn start distance)
- (make-move-piece-home pawn start distance)
does not return the die moves that correspond to entering pawns
board-doubles-penalty : board color -> board
raises an exception if the turn is illegal
has pieces in start
get-move-color : move -> symbol
extracts the moved color from the move
get-move-id : move -> number
blocakde-moved? : board board color -> boolean
makes the given move, removing the used dice from the dice list.
raises an error if the move isn't legal.
moving without the matching roll
entering-blocade? : board symbol -> boolean
possible-to-move : symbol board number -> (union #f board)
indicates if there are any moves that could happen with the
given die, for the given color in the given board.
doesn't consider entering moves
only checks that each move, in isloation, would be possible
enter-piece : board pawn -> (values board (union #f number))
move the color out of the starting area
no bop
bop
board-move-piece-home : board pawn number number -> (values board (union #f number))
result of #f indicates no bop; result of a color indicates who got bopped
this lets us satisfy the inputs to no-blockades
board-move-piece-main : board pawn number number -> (values board (union #f number))
result of #f indicates no bop; result of a color indicates who got bopped
turned onto the exit ramp
stayed on the main board
no one there
attempt to bop on a safety -- illegal
successful bop
next-pos : color number -> (union number home-row-loc)
given a position on the main ring, it finds the next position
for the given color on the board.
find-end-spot : color number number -> (union 'too-far 'home (cons 'home-row number) (cons 'main number))) | #lang racket
(require "board.rkt")
(define-struct move () #:inspector (make-inspector))
(define-struct (enter-piece move) (pawn) #:inspector (make-inspector))
(define-struct (move-piece-main move) (pawn start distance) #:inspector (make-inspector))
(define-struct (move-piece-home move) (pawn start distance) #:inspector (make-inspector))
(provide/contract
(struct enter-piece ((pawn pawn?)))
(struct move-piece-main ([pawn pawn?] [start number?] [distance number?]))
(struct move-piece-home ([pawn pawn?] [start number?] [distance number?])))
(provide take-turn
bad-move
make-moves
move?
board-enter-piece
board-move-piece-main
board-move-piece-home
blockade-moved?
find-end-spot
board-doubles-penalty
make-one-move
get-move-id
get-move-color
has-entering-roll?
entering-blockade?
exn:bad-move?
exn:bad-move-with-info?
exn:bad-move-with-info-color
exn:bad-move-with-info-board
exn:bad-move-with-info-dice
exn:bad-move-with-info-moves
board-all-in?
<=/m
possible-to-move)
(define bop-bonus 20)
(define home-bonus 10)
moves - dice : moves - > ( listof number )
(define (moves-dice moves)
(let loop ([moves moves]
[dice null])
(cond
[(null? moves) dice]
[else
(let ([move (car moves)])
(cond
[(move-piece-main? move)
(loop (cdr moves) (cons (move-piece-main-distance move) dice))]
[(move-piece-home? move)
(loop (cdr moves) (cons (move-piece-home-distance move) dice))]
[else (loop (cdr moves) dice)]))])))
(define (board-doubles-penalty board color)
(let home-row-loop ([i board-home-row-size])
(cond
[(zero? i)
(let main-board-loop ([i (get-enter-pos color)]
[first-time? #t])
(cond
[(and (not first-time?) (= i (get-enter-pos color)))
board]
[else
(let* ([next-i (modulo (- i 1) board-main-size)]
[ent (board-main-i board next-i)])
(if (and (pair? ent)
(eq? (pawn-color (car ent)) color))
(move-piece board (car ent) 'start)
(main-board-loop next-i #f)))]))]
[else
(let ([ent (board-home-row-i board color (- i 1))])
(if (null? ent)
(home-row-loop (- i 1))
(move-piece board (car ent) 'start)))])))
take - turn : color board ( listof number ) ( listof move ) - > board
(define (take-turn color original-board original-dice original-moves)
(parameterize ([current-color/board/dice/moves
(list color original-board original-dice original-moves)])
(unless (andmap (lambda (x) (eq? color (get-move-color x))) original-moves)
(bad-move "attempted to move two different colors"))
(let loop ([moves original-moves]
[board original-board]
[dice original-dice])
(cond
[(null? moves)
(when (and (has-entering-roll? dice)
(memf (lambda (pawn) (eq? (pawn-color pawn) color))
(not (entering-blockade? board color)))
(bad-move "can still enter a pawn"))
(let ([used-dice (moves-dice original-moves)])
(for-each (lambda (die)
(let ([potential-board (possible-to-move color board die)])
(when potential-board
(unless (blockade-moved? original-board potential-board color)
(bad-move "die roll ~a can still be used" die)))))
dice)
(when (blockade-moved? original-board board color)
(bad-move "cannot move blockade together")))
board]
[else
(let ([move (car moves)])
(let-values ([(new-board bonus new-dice)
(make-move/dice board move dice)])
(let ([new-new-dice (if bonus
(cons bonus new-dice)
new-dice)])
(loop (cdr moves)
new-board
new-new-dice))))]))))
(define (get-move-color move) (pawn-color (get-move-pawn move)))
(define (get-move-id move) (pawn-id (get-move-pawn move)))
(define (get-move-pawn move)
(cond
[(enter-piece? move) (enter-piece-pawn move)]
[(move-piece-main? move) (move-piece-main-pawn move)]
[(move-piece-home? move) (move-piece-home-pawn move)]))
(define (blockade-moved? original-board new-board color)
(let ([original-blockades (find-blockades/color original-board color)]
[new-blockades (find-blockades/color new-board color)])
(ormap (lambda (new-blockade) (memf (same-blockade-different-place? new-blockade) original-blockades))
new-blockades)))
(define ((same-blockade-different-place? b1) b2)
(and (equal? (blockade-p1 b1) (blockade-p1 b2))
(equal? (blockade-p2 b1) (blockade-p2 b2))
(not (equal? (blockade-loc b1) (blockade-loc b2)))))
make - move / dice : board move ( listof number ) number - > ( values board bonus ( listof number ) )
check for : using a five to move when there are pieces to come in
(define (make-move/dice board move dice)
(cond
[(enter-piece? move)
(let ([new-dice (cond
[(memq 5 dice) (remq 5 dice)]
[(and (memq 1 dice) (memq 4 dice))
(remq 1 (remq 4 dice))]
[(and (memq 2 dice) (memq 3 dice))
(remq 2 (remq 3 dice))]
[else (bad-move "entered without having a 5")])])
(let-values ([(board bonus) (board-enter-piece board (enter-piece-pawn move))])
(values board bonus new-dice)))]
[(move-piece-main? move)
(do-move/dice/moving board dice
(move-piece-main-distance move)
(move-piece-main-pawn move)
(move-piece-main-start move)
board-move-piece-main)]
[(move-piece-home? move)
(do-move/dice/moving board dice
(move-piece-home-distance move)
(move-piece-home-pawn move)
(move-piece-home-start move)
board-move-piece-home)]))
helper function to collapse last two cases of make - move / dice
(define (do-move/dice/moving board dice die pawn start board-move-piece)
(let ([new-dice (remq die dice)])
(unless (memq die dice)
(bad-move "tried to move ~a squares but dice read ~a" die dice))
(let-values ([(new-board bonus)
(board-move-piece board pawn start die)])
(values new-board bonus new-dice))))
(define (entering-blockade? board color)
(let ([ent (board-main-i board (get-enter-pos color))])
(and (pair? ent) (pair? (cdr ent)))))
(define (no-blockades board start end)
(let ([ind (find-blockade/between board start end)])
(cond
[(not ind) (void)]
[(number? ind)
(bad-move "there is a blockade at ~a in the main ring" ind)]
[(home-row-loc? ind)
(bad-move "there is a blockade at ~a in the ~a home row"
(home-row-loc-num ind)
(home-row-loc-color ind))]
[else (bad-move "blockade in the way")])))
has - entering - roll ? : ( listof number ) - > boolean
(define (has-entering-roll? dice)
(or (memq 5 dice)
(and (memq 1 dice) (memq 4 dice))
(and (memq 2 dice) (memq 3 dice))))
(define (possible-to-move color board die)
(let/ec k
(for-each-pawn/loc
board
(lambda (pawn loc)
(when (and (eq? color (pawn-color pawn))
(not (symbol? loc)))
(with-handlers ([exn:bad-move? (lambda (x) #f)])
(cond
[(number? loc)
(let-values ([(board bonus) (board-move-piece-main board pawn loc die)])
(k board))]
[(home-row-loc? loc)
(let-values ([(board bonus) (board-move-piece-home board pawn (home-row-loc-num loc) die)])
(k board))])))))
#f))
make - moves : board ( listof move ) - > board ( listof number )
(define (make-moves board moves)
(let loop ([board board]
[bonus '()]
[moves moves])
(cond
[(null? moves) (values board bonus)]
[else
(let-values ([(new-board new-bonus) (make-one-move board (car moves))])
(loop new-board
(if new-bonus (cons new-bonus bonus) bonus)
(cdr moves)))])))
make - one - move : board move - > board
(define (make-one-move board move)
(cond
[(enter-piece? move) (board-enter-piece board (enter-piece-pawn move))]
[(move-piece-main? move) (board-move-piece-main board
(move-piece-main-pawn move)
(move-piece-main-start move)
(move-piece-main-distance move))]
[(move-piece-home? move) (board-move-piece-home board
(move-piece-home-pawn move)
(move-piece-home-start move)
(move-piece-home-distance move))]))
(define (board-all-in? board color)
(not (memf (lambda (pawn) (eq? (pawn-color pawn) color))
(board-start board))))
(define (board-enter-piece orig-board pawn)
(unless (member pawn (board-start orig-board))
(bad-move "~a's pawn ~a is already on the board" (pawn-color pawn) (pawn-id pawn)))
(let* ([pos (get-enter-pos (pawn-color pawn))]
[old-ent (board-main-i orig-board pos)])
(when (= 2 (length old-ent))
(bad-move "cannot move out into a blockade"))
(cond
[(or (null? old-ent)
(eq? (pawn-color (car old-ent)) (pawn-color pawn)))
(values (move-piece orig-board pawn pos)
#f)]
[else
(values (move-piece2
orig-board
pawn
pos
(car old-ent)
'start)
bop-bonus)])))
(define (board-move-piece-home board pawn start distance)
(let* ([color (pawn-color pawn)]
[old (board-home-row-i board color start)])
(unless (member pawn old)
(bad-move "color ~a is not in the home row on ~a" (pawn-color pawn) start))
(unless (and (<= 0 start) (< start board-home-row-size))
(error 'boad-move-piece-home "bad start argument ~e" start))
(unless (<= 0 start (+ start distance) (+ board-home-row-size 1))
(bad-move "moved too far, off the end of the board"))
(let ([finish (+ start distance)])
(cond
[(= finish board-home-row-size)
(when (< start (- finish 1))
if only moving one square , then we do n't need to check blockades
(no-blockades board
(make-home-row-loc (+ start 1) color)
(make-home-row-loc (- finish 1) color)))
(values (move-piece board pawn 'home)
home-bonus)]
[(< finish board-home-row-size)
(no-blockades board
(make-home-row-loc (+ start 1) color)
(make-home-row-loc finish color))
(let ([old-ent (board-home-row-i board color finish)])
(cond
[(or (null? old-ent)
(null? (cdr old-ent)))
(values (move-piece board
pawn
(make-home-row-loc finish color))
#f)]
[else
(bad-move "moved onto a blockade in the home row")]))]
[else
(bad-move "moved off of the end of the board")]))))
(define (board-move-piece-main board pawn start distance)
(unless (member pawn (board-main-i board start))
(bad-move "color ~a (piece #~a) is not on square ~a"
(pawn-color pawn)
(pawn-id pawn)
start))
(let* ([color (pawn-color pawn)]
[landed (find-end-spot color start distance)]
[exit (get-exit-pos color)])
(cond
[(eq? landed 'too-far) (bad-move "moved off of the board")]
[(eq? landed 'home)
(no-blockades board
(modulo (+ start 1) board-main-size)
(make-home-row-loc (- board-home-row-size 1) color))
(values (move-piece board
pawn
'home)
10)]
[(eq? (car landed) 'home-row)
(let* ([final-spot (cdr landed)])
(no-blockades board
(next-pos color start)
(make-home-row-loc final-spot color))
(let ([old (board-home-row-i board color final-spot)])
(when (and (pair? old)
(pair? (cdr old)))
(bad-move "cannot move onto a blockade"))
(values (move-piece board pawn (make-home-row-loc final-spot color))
#f)))]
[else
(let ([end (cdr landed)])
(let ([start+1 (modulo (+ start 1) board-main-size)])
(unless (= start+1 end)
(no-blockades board start+1 end)))
(let ([old-contents (board-main-i board end)])
(cond
[(null? old-contents)
(values (move-piece board pawn end)
#f)]
[(and (pair? old-contents)
(pair? (cdr old-contents)))
(bad-move "cannot move directly onto a blockade")]
already one of the same color on that spot
[(eq? (pawn-color (car old-contents)) color)
(values (move-piece board
pawn
end)
#f)]
[(safety? end)
(bad-move "cannot move onto a safety if someone else is already there")]
[else
(values
(move-piece2 board
pawn
end
(car old-contents)
'start)
bop-bonus)])))])))
(define (next-pos color pos)
(cond
[(= pos (get-exit-pos color))
(make-home-row-loc 0 color)]
[else
(modulo (+ pos 1) board-main-size)]))
(define (find-end-spot color start distance)
(let ([exit (get-exit-pos color)]
[end (modulo (+ start distance) board-main-size)])
(cond
[(and (<=/m start exit end)
(not (= exit end)))
(let* ([distance-to-exit (modulo (- exit start) board-main-size)]
[final-spot (- distance distance-to-exit 1)])
(cond
[(final-spot . = . board-home-row-size)
'home]
[(final-spot . < . board-home-row-size)
(cons 'home-row final-spot)]
[else
'too-far]))]
[else
(cons 'main end)])))
(define (<=/m one two three)
(or (<= one two three)
(<= two three one)
(<= three one two)))
(define-struct (exn:bad-move exn) ())
(define-struct (exn:bad-move-with-info exn:bad-move) (color board dice moves))
(define current-color/board/dice/moves (make-parameter #f))
(define (bad-move _str . args)
(define str (if (null? args) _str (apply format _str args)))
(raise
(cond
[(current-color/board/dice/moves)
(define-values (color board dice moves) (apply values (current-color/board/dice/moves)))
(make-exn:bad-move-with-info str (current-continuation-marks) color board dice moves)]
[else
(make-exn:bad-move str (current-continuation-marks))])))
|
d5efcd2369c55d81397dbe219eb2f4c0ca97039acbae36bc2eea10f2e53c4867 | vonzhou/LearnYouHaskellForGreatGood | random_str3.hs | import System.Random
main = do
gen <- getStdGen
putStrLn $ take 20 (randomRs ('a', 'z') gen)
gen2 <- newStdGen
putStrLn $ take 20 (randomRs ('a', 'z') gen2)
| null | https://raw.githubusercontent.com/vonzhou/LearnYouHaskellForGreatGood/439d848deac53ef6da6df433078b7f1dcf54d18d/chapter9/random_str3.hs | haskell | import System.Random
main = do
gen <- getStdGen
putStrLn $ take 20 (randomRs ('a', 'z') gen)
gen2 <- newStdGen
putStrLn $ take 20 (randomRs ('a', 'z') gen2)
| |
1305b03062a31656d8259e649c254f9d267769bb0845e854611f6fc37511b394 | oriansj/mes-m2 | charalpha.scm | GNU --- Maxwell Equations of Software
Copyright ( C ) 2008 Kragen
;;;
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 < / >
;; Setup output file
(set-current-output-port (open-output-file "test/results/test058.answer"))
(define (newline) (display #\newline))
;;; Tests for char-alphabetic?
(define (x a b)
(if (= a b) (newline)
(begin (display (if (char-alphabetic? (integer->char a)) "!" "."))
(x (+ 1 a) b))))
(x 0 32)
(x 32 64)
(x 64 96)
(x 96 128)
; stick to ASCII!
( x 128 160 )
( x 160 192 )
( x 192 224 )
( x 224 256 )
(exit 0)
| null | https://raw.githubusercontent.com/oriansj/mes-m2/b44fbc976ae334252de4eb82a57c361a195f2194/test/test058/charalpha.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.
Setup output file
Tests for char-alphabetic?
stick to ASCII! | GNU --- Maxwell Equations of Software
Copyright ( C ) 2008 Kragen
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 < / >
(set-current-output-port (open-output-file "test/results/test058.answer"))
(define (newline) (display #\newline))
(define (x a b)
(if (= a b) (newline)
(begin (display (if (char-alphabetic? (integer->char a)) "!" "."))
(x (+ 1 a) b))))
(x 0 32)
(x 32 64)
(x 64 96)
(x 96 128)
( x 128 160 )
( x 160 192 )
( x 192 224 )
( x 224 256 )
(exit 0)
|
3e7355ae8060915784755b581f8d89aa0b6f211f6f1bd2cfdfce7577f585a2d6 | onedata/op-worker | lfm_multipart_upload.erl | %%%-------------------------------------------------------------------
@author
( C ) 2022 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc
%%% This module performs multipart upload operations of lfm_submodules.
%%% @end
%%%-------------------------------------------------------------------
-module(lfm_multipart_upload).
-include("global_definitions.hrl").
-include("modules/logical_file_manager/lfm.hrl").
-include("proto/oneclient/fuse_messages.hrl").
-include("proto/oneprovider/provider_messages.hrl").
%% API
-export([
create/3, abort/2, complete/2, list/4,
upload_part/3, list_parts/4
]).
%%%===================================================================
%%% API
%%%===================================================================
-spec create(session:id(), od_space:id(), file_meta:path()) ->
{ok, multipart_upload:id()} | {error, term()}.
create(SessId, SpaceId, Path) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#create_multipart_upload{space_id = SpaceId, path = Path},
fun(#multipart_upload{multipart_upload_id = UploadId}) ->
{ok, UploadId}
end
).
-spec abort(session:id(), multipart_upload:id()) -> ok | {error, term()}.
abort(SessId, UploadId) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#abort_multipart_upload{multipart_upload_id = UploadId},
fun(_) -> ok end
).
-spec complete(session:id(), multipart_upload:id()) -> ok | {error, term()}.
complete(SessId, UploadId) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#complete_multipart_upload{multipart_upload_id = UploadId},
fun(_) -> ok end
).
-spec list(session:id(), od_space:id(), non_neg_integer(), multipart_upload:pagination_token() | undefined) ->
{ok, [multipart_upload:record()], multipart_upload:pagination_token() | undefined, boolean()} | {error, term()}.
list(SessId, SpaceId, Limit, Token) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#list_multipart_uploads{
space_id = SpaceId,
limit = Limit,
index_token = Token
},
fun(#multipart_uploads{uploads = Uploads, next_page_token = NextPageToken,is_last = IsLast}) ->
{ok, Uploads, NextPageToken, IsLast}
end
).
-spec upload_part(session:id(), multipart_upload:id(), multipart_upload_part:record()) ->
ok | {error, term()}.
upload_part(SessId, UploadId, Part) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#upload_multipart_part{multipart_upload_id = UploadId, part = Part},
fun(_) -> ok end
).
-spec list_parts(session:id(), multipart_upload:id(), non_neg_integer(), multipart_upload_part:part_number()) ->
{ok, [multipart_upload_part:record()], boolean()} | {error, term()}.
list_parts(SessId, UploadId, Limit, StartAfter) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#list_multipart_parts{
multipart_upload_id = UploadId,
limit = Limit,
part_marker = StartAfter
},
fun(#multipart_parts{parts = Parts, is_last = IsLast}) ->
{ok, Parts, IsLast}
end
).
| null | https://raw.githubusercontent.com/onedata/op-worker/71d2ac527f4d20ca40b8f5ae28b8107b68ca90e9/src/modules/logical_file_manager/lfm_submodules/lfm_multipart_upload.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc
This module performs multipart upload operations of lfm_submodules.
@end
-------------------------------------------------------------------
API
===================================================================
API
=================================================================== | @author
( C ) 2022 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(lfm_multipart_upload).
-include("global_definitions.hrl").
-include("modules/logical_file_manager/lfm.hrl").
-include("proto/oneclient/fuse_messages.hrl").
-include("proto/oneprovider/provider_messages.hrl").
-export([
create/3, abort/2, complete/2, list/4,
upload_part/3, list_parts/4
]).
-spec create(session:id(), od_space:id(), file_meta:path()) ->
{ok, multipart_upload:id()} | {error, term()}.
create(SessId, SpaceId, Path) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#create_multipart_upload{space_id = SpaceId, path = Path},
fun(#multipart_upload{multipart_upload_id = UploadId}) ->
{ok, UploadId}
end
).
-spec abort(session:id(), multipart_upload:id()) -> ok | {error, term()}.
abort(SessId, UploadId) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#abort_multipart_upload{multipart_upload_id = UploadId},
fun(_) -> ok end
).
-spec complete(session:id(), multipart_upload:id()) -> ok | {error, term()}.
complete(SessId, UploadId) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#complete_multipart_upload{multipart_upload_id = UploadId},
fun(_) -> ok end
).
-spec list(session:id(), od_space:id(), non_neg_integer(), multipart_upload:pagination_token() | undefined) ->
{ok, [multipart_upload:record()], multipart_upload:pagination_token() | undefined, boolean()} | {error, term()}.
list(SessId, SpaceId, Limit, Token) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#list_multipart_uploads{
space_id = SpaceId,
limit = Limit,
index_token = Token
},
fun(#multipart_uploads{uploads = Uploads, next_page_token = NextPageToken,is_last = IsLast}) ->
{ok, Uploads, NextPageToken, IsLast}
end
).
-spec upload_part(session:id(), multipart_upload:id(), multipart_upload_part:record()) ->
ok | {error, term()}.
upload_part(SessId, UploadId, Part) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#upload_multipart_part{multipart_upload_id = UploadId, part = Part},
fun(_) -> ok end
).
-spec list_parts(session:id(), multipart_upload:id(), non_neg_integer(), multipart_upload_part:part_number()) ->
{ok, [multipart_upload_part:record()], boolean()} | {error, term()}.
list_parts(SessId, UploadId, Limit, StartAfter) ->
remote_utils:call_fslogic(
SessId,
multipart_upload_request,
#list_multipart_parts{
multipart_upload_id = UploadId,
limit = Limit,
part_marker = StartAfter
},
fun(#multipart_parts{parts = Parts, is_last = IsLast}) ->
{ok, Parts, IsLast}
end
).
|
1754392040777381801df98a0ccfe8e6a214b3af75ae1f625aa0f500beaa14bf | jixiuf/helloerlang | cluster.erl | -module(cluster).
-export([slaves/1]).
%% Argument:
%% Hosts: List of hostname (string)
cluster : slaves(["gateway " , " yaws1 " , " yaws2 " , " " , " " , " eddieware " ] ) .
slaves([]) ->
ok;
slaves([Host|Hosts]) ->
Args = erl_system_args(),
NodeName = "cluster",
{ok, Node} = slave:start_link(Host, NodeName, Args),
io:format("Erlang node started = [~p]~n", [Node]),
slaves(Hosts).
erl_system_args()->
Shared = case init:get_argument(shared) of
error -> " ";
{ok,[[]]} -> " -shared "
end,
lists:append(["-rsh ssh -setcookie ",
atom_to_list(erlang:get_cookie()),
Shared, " +Mea r10b "]).
Do not forget to start erlang with a command like :
%% erl -rsh ssh -sname clustmaster
%% slave:start_link("jf.org","c2","-rsh ssh -setcookie DJQWUOCYZCIZNETCXWES +Mea r10b ")
| null | https://raw.githubusercontent.com/jixiuf/helloerlang/3960eb4237b026f98edf35d6064539259a816d58/emysql-test/src/cluster.erl | erlang | Argument:
Hosts: List of hostname (string)
erl -rsh ssh -sname clustmaster
slave:start_link("jf.org","c2","-rsh ssh -setcookie DJQWUOCYZCIZNETCXWES +Mea r10b ") | -module(cluster).
-export([slaves/1]).
cluster : slaves(["gateway " , " yaws1 " , " yaws2 " , " " , " " , " eddieware " ] ) .
slaves([]) ->
ok;
slaves([Host|Hosts]) ->
Args = erl_system_args(),
NodeName = "cluster",
{ok, Node} = slave:start_link(Host, NodeName, Args),
io:format("Erlang node started = [~p]~n", [Node]),
slaves(Hosts).
erl_system_args()->
Shared = case init:get_argument(shared) of
error -> " ";
{ok,[[]]} -> " -shared "
end,
lists:append(["-rsh ssh -setcookie ",
atom_to_list(erlang:get_cookie()),
Shared, " +Mea r10b "]).
Do not forget to start erlang with a command like :
|
c558eaeb645362406a5a7581e4aaed524de3e0b6046af8b003b43504c3784608 | tschady/advent-of-code | d23_test.clj | (ns aoc.2018.d23-test
(:require [aoc.2018.d23 :as sut]
[clojure.test :refer :all]))
(def test-input1 ["pos=<0,0,0>, r=4"
"pos=<1,0,0>, r=1"
"pos=<4,0,0>, r=3"
"pos=<0,2,0>, r=1"
"pos=<0,5,0>, r=3"
"pos=<0,0,3>, r=1"
"pos=<1,1,1>, r=1"
"pos=<1,1,2>, r=1"
"pos=<1,3,1>, r=1"])
(def test-input2 ["pos=<10,12,12>, r=2"
"pos=<12,14,12>, r=2"
"pos=<16,12,12>, r=4"
"pos=<14,14,14>, r=6"
"pos=<50,50,50>, r=200"
"pos=<10,10,10>, r=5"])
(deftest part1-examples
(is (= 7 (sut/part-1 test-input1))))
#_(deftest part2-examples
(is (= 36 (sut/part-2 test-input2))))
(deftest challenge
(is (= 410 (sut/part-1 sut/input)))
#_(is (= false (sut/part-2 sut/input))))
| null | https://raw.githubusercontent.com/tschady/advent-of-code/1e4a95ef580c3bf635837eff52aa998b0acfc666/test/aoc/2018/d23_test.clj | clojure | (ns aoc.2018.d23-test
(:require [aoc.2018.d23 :as sut]
[clojure.test :refer :all]))
(def test-input1 ["pos=<0,0,0>, r=4"
"pos=<1,0,0>, r=1"
"pos=<4,0,0>, r=3"
"pos=<0,2,0>, r=1"
"pos=<0,5,0>, r=3"
"pos=<0,0,3>, r=1"
"pos=<1,1,1>, r=1"
"pos=<1,1,2>, r=1"
"pos=<1,3,1>, r=1"])
(def test-input2 ["pos=<10,12,12>, r=2"
"pos=<12,14,12>, r=2"
"pos=<16,12,12>, r=4"
"pos=<14,14,14>, r=6"
"pos=<50,50,50>, r=200"
"pos=<10,10,10>, r=5"])
(deftest part1-examples
(is (= 7 (sut/part-1 test-input1))))
#_(deftest part2-examples
(is (= 36 (sut/part-2 test-input2))))
(deftest challenge
(is (= 410 (sut/part-1 sut/input)))
#_(is (= false (sut/part-2 sut/input))))
| |
1c0145154b58ac31d0b5c5d804ac086860198897de2035c258d3cb9fa649ac9c | xavierleroy/camlidl | fixlabels.ml | (***********************************************************************)
(* *)
(* CamlIDL *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
(* under the terms of the GNU Lesser General Public License LGPL v2.1 *)
(* *)
(***********************************************************************)
$ I d : fixlabels.ml , v 1.4 2001 - 06 - 17 10:50:24 xleroy Exp $
(* Prefix record labels with struct/typedef name if required or requested *)
open Printf
open Utils
open Idltypes
open Typedef
open Funct
open Intf
open File
Determine if an mlname was provided by the user in the IDL file
let no_ml_name f = f.field_mlname == f.field_name
We use physical equality instead of string equality
so that an explicit [ ) ] can override the prefixing
so that an explicit [mlname(samename)] can override the prefixing *)
(* Collect all label names and those that appear at least twice *)
module LabelSet = Set.Make(struct type t = string let compare = compare end)
let all_labels = ref LabelSet.empty
let repeated_labels = ref LabelSet.empty
let add_label s =
if LabelSet.mem s !all_labels then
repeated_labels := LabelSet.add s !repeated_labels
else
all_labels := LabelSet.add s !all_labels
let rec collect_type = function
Type_pointer(_, ty) -> collect_type ty
| Type_array(_, ty) -> collect_type ty
| Type_bigarray(_, ty) -> collect_type ty
| Type_struct sd -> List.iter collect_field sd.sd_fields
| Type_union(ud, _) -> List.iter collect_case ud.ud_cases
| Type_const ty -> collect_type ty
| _ -> ()
and collect_field f =
if no_ml_name f then add_label f.field_name;
collect_type f.field_typ
and collect_case c =
match c.case_field with None -> () | Some f -> collect_field f
let collect_component = function
Comp_typedecl td -> collect_type td.td_type
| Comp_structdecl sd -> List.iter collect_field sd.sd_fields
| Comp_uniondecl ud -> List.iter collect_case ud.ud_cases
| Comp_fundecl fd -> collect_type fd.fun_res
| Comp_interface intf ->
List.iter (fun fd -> collect_type fd.fun_res) intf.intf_methods
| _ -> ()
(* A struct definition needs prefixing if some of its labels occur
several times in the file *)
let need_prefixing sd =
List.exists
(fun f -> no_ml_name f && LabelSet.mem f.field_name !repeated_labels)
sd.sd_fields
(* Prefix label names with struct or typedef name, if required or requested *)
let choose_prefix oldpref newpref =
if newpref <> "" then newpref else oldpref
let rec prefix_type pref = function
Type_struct sd -> Type_struct(prefix_struct pref sd)
| Type_union(ud, attr) -> Type_union(prefix_union pref ud, attr)
| Type_pointer(kind, ty) -> Type_pointer(kind, prefix_type pref ty)
| Type_array(attr, ty) -> Type_array(attr, prefix_type pref ty)
| Type_const ty -> Type_const(prefix_type pref ty)
| ty -> ty
and prefix_struct pref sd =
let prefix = choose_prefix pref sd.sd_name in
let add_prefix =
if !Clflags.prefix_all_labels || need_prefixing sd then begin
if prefix = "" then begin
eprintf "Warning: couldn't find prefix for anonymous struct\n";
false
end else
true
end else
false in
{sd with sd_fields = List.map (prefix_field add_prefix prefix) sd.sd_fields}
and prefix_field add_prefix pref f =
let new_mlname =
if add_prefix && no_ml_name f
then pref ^ "_" ^ f.field_name
else f.field_mlname in
{f with field_mlname = new_mlname;
field_typ = prefix_type pref f.field_typ}
and prefix_union pref ud =
let prefix = choose_prefix pref ud.ud_name in
{ud with ud_cases = List.map (prefix_case prefix) ud.ud_cases}
and prefix_case pref cs =
match cs.case_field with
None -> cs
| Some ty -> {cs with case_field = Some(prefix_field false pref ty)}
let prefix_typedecl td =
{td with td_type = prefix_type td.td_name td.td_type}
let prefix_fundecl fd =
{fd with fun_res = prefix_type "" fd.fun_res}
(* no struct decl in function arguments *)
let prefix_interface intf =
{intf with intf_methods = List.map prefix_fundecl intf.intf_methods}
let prefix_component = function
Comp_typedecl td -> Comp_typedecl(prefix_typedecl td)
| Comp_structdecl sd -> Comp_structdecl(prefix_struct "" sd)
| Comp_uniondecl ud -> Comp_uniondecl(prefix_union "" ud)
| Comp_fundecl fd -> Comp_fundecl(prefix_fundecl fd)
| Comp_interface intf -> Comp_interface(prefix_interface intf)
| cmp -> cmp
let prefix_file f =
if !Clflags.keep_labels then f else begin
all_labels := LabelSet.empty;
repeated_labels := LabelSet.empty;
List.iter collect_component f;
let res = List.map prefix_component f in
all_labels := LabelSet.empty;
repeated_labels := LabelSet.empty;
res
end
| null | https://raw.githubusercontent.com/xavierleroy/camlidl/b192760875fe6e97b13004bd289720618e12ee22/compiler/fixlabels.ml | ocaml | *********************************************************************
CamlIDL
under the terms of the GNU Lesser General Public License LGPL v2.1
*********************************************************************
Prefix record labels with struct/typedef name if required or requested
Collect all label names and those that appear at least twice
A struct definition needs prefixing if some of its labels occur
several times in the file
Prefix label names with struct or typedef name, if required or requested
no struct decl in function arguments | , projet Cristal , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
$ I d : fixlabels.ml , v 1.4 2001 - 06 - 17 10:50:24 xleroy Exp $
open Printf
open Utils
open Idltypes
open Typedef
open Funct
open Intf
open File
Determine if an mlname was provided by the user in the IDL file
let no_ml_name f = f.field_mlname == f.field_name
We use physical equality instead of string equality
so that an explicit [ ) ] can override the prefixing
so that an explicit [mlname(samename)] can override the prefixing *)
module LabelSet = Set.Make(struct type t = string let compare = compare end)
let all_labels = ref LabelSet.empty
let repeated_labels = ref LabelSet.empty
let add_label s =
if LabelSet.mem s !all_labels then
repeated_labels := LabelSet.add s !repeated_labels
else
all_labels := LabelSet.add s !all_labels
let rec collect_type = function
Type_pointer(_, ty) -> collect_type ty
| Type_array(_, ty) -> collect_type ty
| Type_bigarray(_, ty) -> collect_type ty
| Type_struct sd -> List.iter collect_field sd.sd_fields
| Type_union(ud, _) -> List.iter collect_case ud.ud_cases
| Type_const ty -> collect_type ty
| _ -> ()
and collect_field f =
if no_ml_name f then add_label f.field_name;
collect_type f.field_typ
and collect_case c =
match c.case_field with None -> () | Some f -> collect_field f
let collect_component = function
Comp_typedecl td -> collect_type td.td_type
| Comp_structdecl sd -> List.iter collect_field sd.sd_fields
| Comp_uniondecl ud -> List.iter collect_case ud.ud_cases
| Comp_fundecl fd -> collect_type fd.fun_res
| Comp_interface intf ->
List.iter (fun fd -> collect_type fd.fun_res) intf.intf_methods
| _ -> ()
let need_prefixing sd =
List.exists
(fun f -> no_ml_name f && LabelSet.mem f.field_name !repeated_labels)
sd.sd_fields
let choose_prefix oldpref newpref =
if newpref <> "" then newpref else oldpref
let rec prefix_type pref = function
Type_struct sd -> Type_struct(prefix_struct pref sd)
| Type_union(ud, attr) -> Type_union(prefix_union pref ud, attr)
| Type_pointer(kind, ty) -> Type_pointer(kind, prefix_type pref ty)
| Type_array(attr, ty) -> Type_array(attr, prefix_type pref ty)
| Type_const ty -> Type_const(prefix_type pref ty)
| ty -> ty
and prefix_struct pref sd =
let prefix = choose_prefix pref sd.sd_name in
let add_prefix =
if !Clflags.prefix_all_labels || need_prefixing sd then begin
if prefix = "" then begin
eprintf "Warning: couldn't find prefix for anonymous struct\n";
false
end else
true
end else
false in
{sd with sd_fields = List.map (prefix_field add_prefix prefix) sd.sd_fields}
and prefix_field add_prefix pref f =
let new_mlname =
if add_prefix && no_ml_name f
then pref ^ "_" ^ f.field_name
else f.field_mlname in
{f with field_mlname = new_mlname;
field_typ = prefix_type pref f.field_typ}
and prefix_union pref ud =
let prefix = choose_prefix pref ud.ud_name in
{ud with ud_cases = List.map (prefix_case prefix) ud.ud_cases}
and prefix_case pref cs =
match cs.case_field with
None -> cs
| Some ty -> {cs with case_field = Some(prefix_field false pref ty)}
let prefix_typedecl td =
{td with td_type = prefix_type td.td_name td.td_type}
let prefix_fundecl fd =
{fd with fun_res = prefix_type "" fd.fun_res}
let prefix_interface intf =
{intf with intf_methods = List.map prefix_fundecl intf.intf_methods}
let prefix_component = function
Comp_typedecl td -> Comp_typedecl(prefix_typedecl td)
| Comp_structdecl sd -> Comp_structdecl(prefix_struct "" sd)
| Comp_uniondecl ud -> Comp_uniondecl(prefix_union "" ud)
| Comp_fundecl fd -> Comp_fundecl(prefix_fundecl fd)
| Comp_interface intf -> Comp_interface(prefix_interface intf)
| cmp -> cmp
let prefix_file f =
if !Clflags.keep_labels then f else begin
all_labels := LabelSet.empty;
repeated_labels := LabelSet.empty;
List.iter collect_component f;
let res = List.map prefix_component f in
all_labels := LabelSet.empty;
repeated_labels := LabelSet.empty;
res
end
|
5e6660fbee1999c2a586c3a00da5dccb02b1fffb9bb5826675df3986d9d130e9 | pirapira/coq2rust | vm_printers.ml | open Format
open Term
open Names
open Cbytecodes
open Cemitcodes
open Vm
let ppripos (ri,pos) =
(match ri with
| Reloc_annot a ->
let sp,i = a.ci.ci_ind in
print_string
("annot : MutInd("^(string_of_mind sp)^","^(string_of_int i)^")\n")
| Reloc_const _ ->
print_string "structured constant\n"
| Reloc_getglobal kn ->
print_string ("getglob "^(string_of_con kn)^"\n"));
print_flush ()
let print_vfix () = print_string "vfix"
let print_vfix_app () = print_string "vfix_app"
let print_vswith () = print_string "switch"
let ppsort = function
| Prop(Pos) -> print_string "Set"
| Prop(Null) -> print_string "Prop"
| Type u -> print_string "Type"
let print_idkey idk =
match idk with
| ConstKey sp ->
print_string "Cons(";
print_string (string_of_con sp);
print_string ")"
| VarKey id -> print_string (Id.to_string id)
| RelKey i -> print_string "~";print_int i
let rec ppzipper z =
match z with
| Zapp args ->
let n = nargs args in
open_hbox ();
for i = 0 to n-2 do
ppvalues (arg args i);print_string ";";print_space()
done;
if n-1 >= 0 then ppvalues (arg args (n-1));
close_box()
| Zfix _ -> print_string "Zfix"
| Zswitch _ -> print_string "Zswitch"
and ppstack s =
open_hovbox 0;
print_string "[";
List.iter (fun z -> ppzipper z;print_string " | ") s;
print_string "]";
close_box()
and ppatom a =
match a with
| Aid idk -> print_idkey idk
| Aiddef(idk,_) -> print_string "&";print_idkey idk
| Aind(sp,i) -> print_string "Ind(";
print_string (string_of_mind sp);
print_string ","; print_int i;
print_string ")"
and ppwhd whd =
match whd with
| Vsort s -> ppsort s
| Vprod _ -> print_string "product"
| Vfun _ -> print_string "function"
| Vfix _ -> print_vfix()
| Vcofix _ -> print_string "cofix"
| Vconstr_const i -> print_string "C(";print_int i;print_string")"
| Vconstr_block b -> ppvblock b
| Vatom_stk(a,s) ->
open_hbox();ppatom a;close_box();
print_string"@";ppstack s
and ppvblock b =
open_hbox();
print_string "Cb(";print_int (btag b);
let n = bsize b in
for i = 0 to n -1 do
print_string ",";ppvalues (bfield b i)
done;
print_string")";
close_box()
and ppvalues v =
open_hovbox 0;ppwhd (whd_val v);close_box();
print_flush()
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/dev/vm_printers.ml | ocaml | open Format
open Term
open Names
open Cbytecodes
open Cemitcodes
open Vm
let ppripos (ri,pos) =
(match ri with
| Reloc_annot a ->
let sp,i = a.ci.ci_ind in
print_string
("annot : MutInd("^(string_of_mind sp)^","^(string_of_int i)^")\n")
| Reloc_const _ ->
print_string "structured constant\n"
| Reloc_getglobal kn ->
print_string ("getglob "^(string_of_con kn)^"\n"));
print_flush ()
let print_vfix () = print_string "vfix"
let print_vfix_app () = print_string "vfix_app"
let print_vswith () = print_string "switch"
let ppsort = function
| Prop(Pos) -> print_string "Set"
| Prop(Null) -> print_string "Prop"
| Type u -> print_string "Type"
let print_idkey idk =
match idk with
| ConstKey sp ->
print_string "Cons(";
print_string (string_of_con sp);
print_string ")"
| VarKey id -> print_string (Id.to_string id)
| RelKey i -> print_string "~";print_int i
let rec ppzipper z =
match z with
| Zapp args ->
let n = nargs args in
open_hbox ();
for i = 0 to n-2 do
ppvalues (arg args i);print_string ";";print_space()
done;
if n-1 >= 0 then ppvalues (arg args (n-1));
close_box()
| Zfix _ -> print_string "Zfix"
| Zswitch _ -> print_string "Zswitch"
and ppstack s =
open_hovbox 0;
print_string "[";
List.iter (fun z -> ppzipper z;print_string " | ") s;
print_string "]";
close_box()
and ppatom a =
match a with
| Aid idk -> print_idkey idk
| Aiddef(idk,_) -> print_string "&";print_idkey idk
| Aind(sp,i) -> print_string "Ind(";
print_string (string_of_mind sp);
print_string ","; print_int i;
print_string ")"
and ppwhd whd =
match whd with
| Vsort s -> ppsort s
| Vprod _ -> print_string "product"
| Vfun _ -> print_string "function"
| Vfix _ -> print_vfix()
| Vcofix _ -> print_string "cofix"
| Vconstr_const i -> print_string "C(";print_int i;print_string")"
| Vconstr_block b -> ppvblock b
| Vatom_stk(a,s) ->
open_hbox();ppatom a;close_box();
print_string"@";ppstack s
and ppvblock b =
open_hbox();
print_string "Cb(";print_int (btag b);
let n = bsize b in
for i = 0 to n -1 do
print_string ",";ppvalues (bfield b i)
done;
print_string")";
close_box()
and ppvalues v =
open_hovbox 0;ppwhd (whd_val v);close_box();
print_flush()
| |
f8c6e27762bd666ea567d3b8763acfaba216b3c15c49bfe560b2149d2cd2e476 | mars0i/pasta | core.clj | This software is copyright 2016 , 2017 , 2018 , 2019 by ,
and is distributed under the Gnu General Public License version 3.0
;; as specified in the the file LICENSE.
;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Clojure main function , and other central utility functions
(ns pasta.core
(:require [pasta.Sim :as sim]
[pasta.GUI :as gui]
[clojure.pprint]) ; for *print-right-margin*
(:gen-class))
;; Always handy at the repl
(defn set-pprint-width
"Sets width for pretty-printing with pprint and pp."
[cols]
(alter-var-root
#'clojure.pprint/*print-right-margin*
(constantly cols)))
(defn -main
"This function, core/main, examines the use-gui command line option, if
it exists, to decide whether to run the main in Sim.clj or the main in
GUI.clj (which will eventually run code in Sim)."
[& args]
The is n't available yet , so store commandline args for later access by start ( ):
(sim/record-commandline-args! args) ; defined by defsim: records args in commandline$, defined above
(if (and args (not (:use-gui (:options @sim/commandline$)))) ; if commandline options, default to no-gui unless use-gui is true
(sim/mein args) ; a wrapper around sim/main
otherwise default to
| null | https://raw.githubusercontent.com/mars0i/pasta/e835317c932611bfc09cc5a7cdeb4ccc7b6e1339/src/clj/pasta/core.clj | clojure | as specified in the the file LICENSE.
(set! *warn-on-reflection* true)
for *print-right-margin*
Always handy at the repl
defined by defsim: records args in commandline$, defined above
if commandline options, default to no-gui unless use-gui is true
a wrapper around sim/main | This software is copyright 2016 , 2017 , 2018 , 2019 by ,
and is distributed under the Gnu General Public License version 3.0
Clojure main function , and other central utility functions
(ns pasta.core
(:require [pasta.Sim :as sim]
[pasta.GUI :as gui]
(:gen-class))
(defn set-pprint-width
"Sets width for pretty-printing with pprint and pp."
[cols]
(alter-var-root
#'clojure.pprint/*print-right-margin*
(constantly cols)))
(defn -main
"This function, core/main, examines the use-gui command line option, if
it exists, to decide whether to run the main in Sim.clj or the main in
GUI.clj (which will eventually run code in Sim)."
[& args]
The is n't available yet , so store commandline args for later access by start ( ):
otherwise default to
|
a83e7eee3d34b3d6da56674bf726d45a16c419542e070fd9dcd5685cf6d8ebba | mentat-collective/fdg-book | utils.scm | Utilities I want to share between exercises .
;; Printing
(load "exdisplay.scm")
(define (replace-all haystack needle replacement)
(let ((haystack (string->list haystack))
(replacement (reverse
(string->list replacement)))
(needle-len (string-length needle)))
(let loop ((haystack haystack) (acc '()))
(cond ((null? haystack)
(list->string (reverse acc)))
((string-prefix? needle (list->string haystack))
(loop (list-tail haystack needle-len)
(append replacement acc)))
(else
(loop (cdr haystack) (cons (car haystack) acc)))))))
Generates a properly formatted string of LaTeX.
(define (->tex* expr)
(let* ((tex-string (expression->tex-string
((prepare-for-printing expr simplify))))
(len (string-length tex-string)))
(substring tex-string 10 (- len 3))))
Prints the string as a LaTeX code block .
(define (->write-tex tex-string)
(write-string
(string-append "\\[ " tex-string " \\]")))
Prints the TeX representation of the supplied expression to the screen .
(define (->tex expr)
(->write-tex (->tex* expr)))
Prints an equation code block containing the expression as LaTeX.
(define (->tex-equation* expr #!optional label)
(string-append
"\\begin{equation}\n"
(->tex* expr)
(if (default-object? label)
""
(string-append "\n\\label{" label "}"))
"\n\\end{equation}"))
(define (->tex-equation expr #!optional label)
(write-string (->tex-equation* expr label)))
| null | https://raw.githubusercontent.com/mentat-collective/fdg-book/be6e03e4f917006fa46df956b448e922dd1dc853/scheme/org/utils.scm | scheme | Printing | Utilities I want to share between exercises .
(load "exdisplay.scm")
(define (replace-all haystack needle replacement)
(let ((haystack (string->list haystack))
(replacement (reverse
(string->list replacement)))
(needle-len (string-length needle)))
(let loop ((haystack haystack) (acc '()))
(cond ((null? haystack)
(list->string (reverse acc)))
((string-prefix? needle (list->string haystack))
(loop (list-tail haystack needle-len)
(append replacement acc)))
(else
(loop (cdr haystack) (cons (car haystack) acc)))))))
Generates a properly formatted string of LaTeX.
(define (->tex* expr)
(let* ((tex-string (expression->tex-string
((prepare-for-printing expr simplify))))
(len (string-length tex-string)))
(substring tex-string 10 (- len 3))))
Prints the string as a LaTeX code block .
(define (->write-tex tex-string)
(write-string
(string-append "\\[ " tex-string " \\]")))
Prints the TeX representation of the supplied expression to the screen .
(define (->tex expr)
(->write-tex (->tex* expr)))
Prints an equation code block containing the expression as LaTeX.
(define (->tex-equation* expr #!optional label)
(string-append
"\\begin{equation}\n"
(->tex* expr)
(if (default-object? label)
""
(string-append "\n\\label{" label "}"))
"\n\\end{equation}"))
(define (->tex-equation expr #!optional label)
(write-string (->tex-equation* expr label)))
|
eb2e86d02ed887ced76181ab60822b3f332343cf299c7fb01ea81ee6336a157a | racket/plot | snip2d.rkt | #lang racket/base
(require racket/gui/base racket/class racket/contract racket/match racket/list racket/math
plot/private/common/math
plot/private/common/format
plot/private/common/ticks
plot/private/common/parameters
plot/private/common/parameter-groups
plot/private/common/parameter-group
plot/private/common/draw-attribs
plot/private/common/color-map
plot/private/plot2d/plot-area
plot/private/plot2d/renderer
plot/private/no-gui/plot2d-utils
plot/private/common/contract
(submod plot/private/common/plotmetrics untyped)
"worker-thread.rkt"
"snip.rkt")
(define plot-mouse-event-callback/c
(-> (is-a?/c snip%) (is-a?/c mouse-event%) (or/c real? #f) (or/c real? #f) any/c))
(define 2d-plot-snip%/c
(class/c
(set-mouse-event-callback (->m (or/c plot-mouse-event-callback/c #f) any/c))
(set-overlay-renderers (->m (or/c (treeof renderer2d?) #f) any/c))))
(provide
(contract-out
[make-2d-plot-snip (unconstrained-domain-> (instanceof/c 2d-plot-snip%/c))]
[2d-plot-snip% 2d-plot-snip%/c])
plot-mouse-event-callback/c)
(define update-delay 16)
(define show-zoom-message? #t)
(struct draw-command (animating? plot-bounds-rect width height) #:transparent)
(define 2d-plot-snip%
(class* plot-snip% (plot-metrics<%>)
(init init-bm saved-plot-parameters)
(init-field make-bm plot-bounds-rect area width height)
(inherit set-bitmap get-bitmap
get-saved-plot-parameters
refresh
stop-message set-message reset-message-timeout
update-thread-running? set-update
get-left-down-here?)
(super-make-object init-bm saved-plot-parameters)
(define (set-message-center)
(match-define (vector x-mid y-mid) (rect-center (send area get-area-bounds-rect)))
(send this set-message-center x-mid y-mid))
(set-message-center)
(define/override (copy)
(define c
(make-object this%
(get-bitmap) (get-saved-plot-parameters)
make-bm plot-bounds-rect area width height))
(when mouse-event-callback
(send c set-mouse-event-callback mouse-event-callback))
c)
(define left-click-x 0)
(define left-click-y 0)
(define left-drag-x 0)
(define left-drag-y 0)
(define plot-bounds-rects empty)
(define (area-bounds->plot-bounds rect)
;; assumes: (rect-known? rect)
(match-define (vector (ivl area-x-min area-x-max) (ivl area-y-min area-y-max)) rect)
(match-define (vector x-min y-min) (send area dc->plot (vector area-x-min area-y-min)))
(match-define (vector x-max y-max) (send area dc->plot (vector area-x-max area-y-max)))
(vector (ivl x-min x-max) (ivl y-min y-max)))
(define (plot-bounds->area-bounds rect)
;; assumes (rect-known? rect)
(match-define (vector (ivl plot-x-min plot-x-max) (ivl plot-y-min plot-y-max)) rect)
(match-define (vector x-min y-min) (send area plot->dc (vector plot-x-min plot-y-min)))
(match-define (vector x-max y-max) (send area plot->dc (vector plot-x-max plot-y-max)))
(vector (ivl x-min x-max) (ivl y-min y-max)))
(define (get-new-area-bounds-rect)
(rect-meet (send area get-area-bounds-rect)
(rect-inexact->exact
(vector (ivl left-click-x left-drag-x) (ivl left-click-y left-drag-y)))))
(define dragging? #f)
(define zoom-timer #f)
(define (set-zoom-timer)
(when (not zoom-timer)
(set! zoom-timer (make-object timer%
(λ ()
(set! zoom-timer #f)
(refresh))
update-delay #t))))
(define (set-click-message)
(when show-zoom-message?
(set-message "Click and drag to zoom\n Click to unzoom once")))
(define (zoom-or-unzoom)
(cond [dragging?
(set! dragging? #f)
(define new-rect
(let ([bounds (get-new-area-bounds-rect)])
BOUNDS might be + nan.0 for an empty selection
(and (rect-rational? bounds)
(area-bounds->plot-bounds bounds))))
(cond [(and new-rect
(rect-rational? new-rect)
(not (rect-zero-area? new-rect)))
#;(printf "~a: new-plot-bounds-rect = ~v~n"
(current-milliseconds) new-rect)
(set! plot-bounds-rects (cons plot-bounds-rect plot-bounds-rects))
(set! plot-bounds-rect new-rect)
(update-plot)]
[else
(refresh)])]
[(not (empty? plot-bounds-rects))
(set! plot-bounds-rect (first plot-bounds-rects))
(set! plot-bounds-rects (rest plot-bounds-rects))
(set! show-zoom-message? #f)
(update-plot)]))
(define (start-update-thread animating?)
(send this start-update-thread
(λ () (make-worker-thread
(match-lambda
[(draw-command animating? plot-bounds-rect width height)
(make-bm animating? plot-bounds-rect width height)])))
(λ (animating?) (draw-command animating? plot-bounds-rect width height))
(λ (rth)
(define-values (new-bm new-area)
(worker-thread-try-get rth (λ () (values #f #f))))
(cond [(is-a? new-bm bitmap%)
(set! area new-area)
(set! plot-metrics-ok? #f)
(set-bitmap new-bm)
(set-message-center)
#t]
[else #f]))
animating?))
(define (update-plot)
(start-update-thread #f)
(set-update #t))
(define (zoom-or-unzoom-mouse-event-handler dc x y editorx editory evt)
(define evt-type (send evt get-event-type))
(define mouse-x (- (send evt get-x) x))
(define mouse-y (- (send evt get-y) y))
(case evt-type
[(left-down) (set! left-click-x mouse-x)
(set! left-click-y mouse-y)
(set! left-drag-x mouse-x)
(set! left-drag-y mouse-y)
(set! dragging? #f)
(set-message #f)
(set-zoom-timer)]
[(left-up) (set! left-drag-x mouse-x)
(set! left-drag-y mouse-y)
(zoom-or-unzoom)]
[(motion) (cond [(get-left-down-here?) ; only #t if clicked on snip
(when (not (and (= left-drag-x mouse-x)
(= left-drag-y mouse-y)))
(set! left-drag-x mouse-x)
(set! left-drag-y mouse-y)
(set! dragging? #t)
(set-zoom-timer))]
[(and (not (send evt get-left-down))
(<= 0 mouse-x (send (get-bitmap) get-width))
(<= 0 mouse-y (send (get-bitmap) get-height)))
(set-click-message)])]))
(define mouse-event-callback #f)
(define mouse-event-handler zoom-or-unzoom-mouse-event-handler)
(define (user-mouse-event-handler dc x y editorx editory evt)
(define mouse-x (- (send evt get-x) x))
(define mouse-y (- (send evt get-y) y))
(if (rect-contains? (send area get-area-bounds-rect) (vector mouse-x mouse-y))
(match-let (((vector px py) (send area dc->plot (vector mouse-x mouse-y))))
(mouse-event-callback this evt px py))
(mouse-event-callback this evt #f #f)))
(define/public (set-mouse-event-callback callback)
(set! mouse-event-callback callback)
(set! mouse-event-handler
(if mouse-event-callback
user-mouse-event-handler
zoom-or-unzoom-mouse-event-handler)))
(define the-overlay-renderers #f)
(define/public (set-overlay-renderers renderers)
(set! the-overlay-renderers (and renderers (flatten renderers)))
(refresh))
(define (draw-overlay-renderers dc x y left top right bottom)
(when the-overlay-renderers
;; Implementation notes:
;;
;; * the `plot-area` routine used to draw plots, expects the origin of
the DC to be set to the origin or ( 0 , 0 ) of the plot , see
;; `set-origin` call.
;;
* Since the DC origin has been adjusted to start at X , Y , the LEFT ,
;; TOP, RIGHT and BOTTOM values have to be adjusted accordingly.
;;
;; * plot Y axis grows upwards (lower values are at the bottom, higher
;; values are at the top), draw context Y axis grows downwards (lower
;; values are at the top, higher values are at the bottom). This
;; results in some non-obvious `plot->dc` and `dc->plot` calls.
;;
;; * The area bounded by LEFT, TOP, RIGHT and BOTTOM might cover an
;; area outside the plot area (e.g. where axis are drawn). We need to
;; intersect the current plot bounds with this area to obtain the
;; final overlay redraw area.
;;
;; * If the redraw area is at the edge of the visible part of the plot
snip , we seem to have an off - by - one error and pixels are " left
over " at the edge . This is adjusted using the ` add1 ` , ` sub1 ` calls
;; below.
(match-define (vector (ivl cleft cright) (ivl ctop cbottom))
(plot-bounds->area-bounds plot-bounds-rect))
(define dc-x-min (max cleft (add1 (- left x))))
(define dc-x-max (min cright (sub1 (- right x))))
(define dc-y-min (max ctop (add1 (- top y))))
(define dc-y-max (min cbottom (sub1 (- bottom y))))
(when (and (> dc-x-max dc-x-min) (> dc-y-max dc-y-min))
(define overlay-plot-bounds
(area-bounds->plot-bounds (vector (ivl dc-x-min dc-x-max) (ivl dc-y-min dc-y-max))))
(define-values (scale-x scale-y) (send dc get-scale))
(define-values (origin-x origin-y) (send dc get-origin))
(send dc set-origin (+ origin-x (* scale-x x)) (+ origin-y (* scale-y y)))
;; Use the same plot parameters as the main plot -- this ensures
;; that any axis transforms (e.g. logarithmic, stretch, etc) are
;; applied to the overlays as well. We than omit the decorations
;; and specify a transparent background so the main plot underneath
;; is visible.
(parameterize/group ([plot-parameters (get-saved-plot-parameters)])
(parameterize ([plot-decorations? #f]
[plot-background-alpha 0])
;; The new overlay area has to be constructed inside the
;; parameterize call, as it picks up the value of the
;; plot-decorations? parameter.
(define overlay-area
(make-object 2d-plot-area%
overlay-plot-bounds
'() '() '() '() '()
dc
dc-x-min dc-y-min
(- dc-x-max dc-x-min) (- dc-y-max dc-y-min)
(send area get-aspect-ratio)))
(plot-area overlay-area the-overlay-renderers)))
(send dc set-origin origin-x origin-y))))
(define/override (on-event dc x y editorx editory evt)
(apply mouse-event-handler dc x y editorx editory evt '())
(super on-event dc x y editorx editory evt))
(define (draw-selection dc dc-x-min dc-y-min rect)
(with-handlers ([exn? (λ (e) (printf "draw-selection: ~v~n" e))])
(when (and (rect-rational? rect) (not (rect-zero-area? rect)))
(define width (send (get-bitmap) get-width))
(define height (send (get-bitmap) get-height))
(define-values (scale-x scale-y) (send dc get-scale))
(define-values (origin-x origin-y) (send dc get-origin))
(define smoothing (send dc get-smoothing))
(define text-mode (send dc get-text-mode))
(define font (send dc get-font))
(define pen (send dc get-pen))
(define brush (send dc get-brush))
(define alpha (send dc get-alpha))
(define text-foreground (send dc get-text-foreground))
(send dc set-origin
(+ origin-x (* scale-x dc-x-min))
(+ origin-y (* scale-y dc-y-min)))
(send dc set-smoothing 'smoothed)
(send dc set-text-mode 'transparent)
(send dc set-font (send the-font-list find-or-create-font
(real->font-size (plot-font-size))
(plot-font-face)
(plot-font-family)
'normal
'normal))
(match-define (vector (ivl sel-x-min sel-x-max) (ivl sel-y-min sel-y-max)) rect)
(define sel-x-size (- sel-x-max sel-x-min))
(define sel-y-size (- sel-y-max sel-y-min))
(define select-color (get-highlight-background-color))
(define pen-color (color->color% (->pen-color (plot-foreground))))
(define brush-color (color->color% (->brush-color (plot-background))))
;; inside selection
(send dc set-pen select-color 1 'transparent)
(send dc set-brush select-color 'solid)
(send dc set-alpha 1/4)
(send dc draw-rectangle sel-x-min sel-y-min sel-x-size sel-y-size)
;; selection border
(send dc set-pen select-color (* 1/2 (plot-line-width)) 'solid)
(send dc set-brush select-color 'transparent)
(send dc set-alpha 3/4)
(send dc draw-rectangle sel-x-min sel-y-min sel-x-size sel-y-size)
;; format side labels
(match-define (vector (ivl x-min x-max) (ivl y-min y-max)) plot-bounds-rect)
(match-define (vector (ivl new-x-min new-x-max) (ivl new-y-min new-y-max))
(area-bounds->plot-bounds rect))
(match-define (list new-x-min-str new-x-max-str)
(format-tick-labels (plot-x-ticks) x-min x-max (list new-x-min new-x-max)))
(match-define (list new-y-min-str new-y-max-str)
(format-tick-labels (plot-y-ticks) y-min y-max (list new-y-min new-y-max)))
;; draw side labels
(match-define (vector (ivl new-area-x-min new-area-x-max)
(ivl new-area-y-min new-area-y-max))
rect)
(define new-area-x-mid (* 1/2 (+ new-area-x-min new-area-x-max)))
(define new-area-y-mid (* 1/2 (+ new-area-y-min new-area-y-max)))
(send dc set-alpha 1)
(send this draw-text dc new-x-min-str new-area-x-min new-area-y-mid
pen-color brush-color 'center (* 1/2 pi) 0)
(send this draw-text dc new-x-max-str new-area-x-max new-area-y-mid
pen-color brush-color 'center (* 1/2 pi) 0)
(send this draw-text dc new-y-min-str new-area-x-mid new-area-y-max
pen-color brush-color 'center 0 0)
(send this draw-text dc new-y-max-str new-area-x-mid new-area-y-min
pen-color brush-color 'center 0 0)
(send dc set-origin origin-x origin-y)
(send dc set-smoothing smoothing)
(send dc set-text-mode text-mode)
(send dc set-font font)
(send dc set-pen pen)
(send dc set-brush brush)
(send dc set-alpha alpha)
(send dc set-text-foreground text-foreground))))
(define/override (draw dc x y left top right bottom dx dy draw-caret)
;(printf "~a: drawing~n" (current-milliseconds))
(super draw dc x y left top right bottom dx dy draw-caret)
(when dragging?
(parameterize/group ([plot-parameters (get-saved-plot-parameters)])
(draw-selection dc x y (get-new-area-bounds-rect))))
(draw-overlay-renderers dc x y left top right bottom))
(define/override (resize w h)
(when (not (and (= w width) (= h height)))
(set! width w)
(set! height h)
(stop-message)
(start-update-thread #f)
(set-update #t))
(super resize w h))
(define plot-metrics-ok? #f)
(match-define (list bounds ->dc ->plot plane)
(send area get-plot-metrics-functions))
(define (update-metrics)
(match-define (list new-bounds new-->dc new-->plot new-plane)
(send area get-plot-metrics-functions))
(set! bounds new-bounds)
(set! ->dc new-->dc)
(set! ->plot new-->plot)
(set! plane new-plane)
(set! plot-metrics-ok? #t))
(define/public (get-plot-bounds) (unless plot-metrics-ok? (update-metrics)) (bounds))
(define/public (plot->dc coords) (unless plot-metrics-ok? (update-metrics)) (->dc coords))
(define/public (dc->plot coords) (unless plot-metrics-ok? (update-metrics)) (->plot coords))
(define/public (plane-vector) (unless plot-metrics-ok? (update-metrics)) (plane))
(define/public (get-plot-metrics-functions) (unless plot-metrics-ok? (update-metrics)) (list bounds ->dc ->plot plane))
))
(define (make-2d-plot-snip
init-bm saved-plot-parameters
make-bm plot-bounds-rect area width height)
(make-object 2d-plot-snip%
init-bm saved-plot-parameters
make-bm plot-bounds-rect area width height))
| null | https://raw.githubusercontent.com/racket/plot/c4126001f2c609e36c3aa12f300e9c673ab1a806/plot-gui-lib/plot/private/gui/snip2d.rkt | racket | assumes: (rect-known? rect)
assumes (rect-known? rect)
(printf "~a: new-plot-bounds-rect = ~v~n"
only #t if clicked on snip
Implementation notes:
* the `plot-area` routine used to draw plots, expects the origin of
`set-origin` call.
TOP, RIGHT and BOTTOM values have to be adjusted accordingly.
* plot Y axis grows upwards (lower values are at the bottom, higher
values are at the top), draw context Y axis grows downwards (lower
values are at the top, higher values are at the bottom). This
results in some non-obvious `plot->dc` and `dc->plot` calls.
* The area bounded by LEFT, TOP, RIGHT and BOTTOM might cover an
area outside the plot area (e.g. where axis are drawn). We need to
intersect the current plot bounds with this area to obtain the
final overlay redraw area.
* If the redraw area is at the edge of the visible part of the plot
below.
Use the same plot parameters as the main plot -- this ensures
that any axis transforms (e.g. logarithmic, stretch, etc) are
applied to the overlays as well. We than omit the decorations
and specify a transparent background so the main plot underneath
is visible.
The new overlay area has to be constructed inside the
parameterize call, as it picks up the value of the
plot-decorations? parameter.
inside selection
selection border
format side labels
draw side labels
(printf "~a: drawing~n" (current-milliseconds)) | #lang racket/base
(require racket/gui/base racket/class racket/contract racket/match racket/list racket/math
plot/private/common/math
plot/private/common/format
plot/private/common/ticks
plot/private/common/parameters
plot/private/common/parameter-groups
plot/private/common/parameter-group
plot/private/common/draw-attribs
plot/private/common/color-map
plot/private/plot2d/plot-area
plot/private/plot2d/renderer
plot/private/no-gui/plot2d-utils
plot/private/common/contract
(submod plot/private/common/plotmetrics untyped)
"worker-thread.rkt"
"snip.rkt")
(define plot-mouse-event-callback/c
(-> (is-a?/c snip%) (is-a?/c mouse-event%) (or/c real? #f) (or/c real? #f) any/c))
(define 2d-plot-snip%/c
(class/c
(set-mouse-event-callback (->m (or/c plot-mouse-event-callback/c #f) any/c))
(set-overlay-renderers (->m (or/c (treeof renderer2d?) #f) any/c))))
(provide
(contract-out
[make-2d-plot-snip (unconstrained-domain-> (instanceof/c 2d-plot-snip%/c))]
[2d-plot-snip% 2d-plot-snip%/c])
plot-mouse-event-callback/c)
(define update-delay 16)
(define show-zoom-message? #t)
(struct draw-command (animating? plot-bounds-rect width height) #:transparent)
(define 2d-plot-snip%
(class* plot-snip% (plot-metrics<%>)
(init init-bm saved-plot-parameters)
(init-field make-bm plot-bounds-rect area width height)
(inherit set-bitmap get-bitmap
get-saved-plot-parameters
refresh
stop-message set-message reset-message-timeout
update-thread-running? set-update
get-left-down-here?)
(super-make-object init-bm saved-plot-parameters)
(define (set-message-center)
(match-define (vector x-mid y-mid) (rect-center (send area get-area-bounds-rect)))
(send this set-message-center x-mid y-mid))
(set-message-center)
(define/override (copy)
(define c
(make-object this%
(get-bitmap) (get-saved-plot-parameters)
make-bm plot-bounds-rect area width height))
(when mouse-event-callback
(send c set-mouse-event-callback mouse-event-callback))
c)
(define left-click-x 0)
(define left-click-y 0)
(define left-drag-x 0)
(define left-drag-y 0)
(define plot-bounds-rects empty)
(define (area-bounds->plot-bounds rect)
(match-define (vector (ivl area-x-min area-x-max) (ivl area-y-min area-y-max)) rect)
(match-define (vector x-min y-min) (send area dc->plot (vector area-x-min area-y-min)))
(match-define (vector x-max y-max) (send area dc->plot (vector area-x-max area-y-max)))
(vector (ivl x-min x-max) (ivl y-min y-max)))
(define (plot-bounds->area-bounds rect)
(match-define (vector (ivl plot-x-min plot-x-max) (ivl plot-y-min plot-y-max)) rect)
(match-define (vector x-min y-min) (send area plot->dc (vector plot-x-min plot-y-min)))
(match-define (vector x-max y-max) (send area plot->dc (vector plot-x-max plot-y-max)))
(vector (ivl x-min x-max) (ivl y-min y-max)))
(define (get-new-area-bounds-rect)
(rect-meet (send area get-area-bounds-rect)
(rect-inexact->exact
(vector (ivl left-click-x left-drag-x) (ivl left-click-y left-drag-y)))))
(define dragging? #f)
(define zoom-timer #f)
(define (set-zoom-timer)
(when (not zoom-timer)
(set! zoom-timer (make-object timer%
(λ ()
(set! zoom-timer #f)
(refresh))
update-delay #t))))
(define (set-click-message)
(when show-zoom-message?
(set-message "Click and drag to zoom\n Click to unzoom once")))
(define (zoom-or-unzoom)
(cond [dragging?
(set! dragging? #f)
(define new-rect
(let ([bounds (get-new-area-bounds-rect)])
BOUNDS might be + nan.0 for an empty selection
(and (rect-rational? bounds)
(area-bounds->plot-bounds bounds))))
(cond [(and new-rect
(rect-rational? new-rect)
(not (rect-zero-area? new-rect)))
(current-milliseconds) new-rect)
(set! plot-bounds-rects (cons plot-bounds-rect plot-bounds-rects))
(set! plot-bounds-rect new-rect)
(update-plot)]
[else
(refresh)])]
[(not (empty? plot-bounds-rects))
(set! plot-bounds-rect (first plot-bounds-rects))
(set! plot-bounds-rects (rest plot-bounds-rects))
(set! show-zoom-message? #f)
(update-plot)]))
(define (start-update-thread animating?)
(send this start-update-thread
(λ () (make-worker-thread
(match-lambda
[(draw-command animating? plot-bounds-rect width height)
(make-bm animating? plot-bounds-rect width height)])))
(λ (animating?) (draw-command animating? plot-bounds-rect width height))
(λ (rth)
(define-values (new-bm new-area)
(worker-thread-try-get rth (λ () (values #f #f))))
(cond [(is-a? new-bm bitmap%)
(set! area new-area)
(set! plot-metrics-ok? #f)
(set-bitmap new-bm)
(set-message-center)
#t]
[else #f]))
animating?))
(define (update-plot)
(start-update-thread #f)
(set-update #t))
(define (zoom-or-unzoom-mouse-event-handler dc x y editorx editory evt)
(define evt-type (send evt get-event-type))
(define mouse-x (- (send evt get-x) x))
(define mouse-y (- (send evt get-y) y))
(case evt-type
[(left-down) (set! left-click-x mouse-x)
(set! left-click-y mouse-y)
(set! left-drag-x mouse-x)
(set! left-drag-y mouse-y)
(set! dragging? #f)
(set-message #f)
(set-zoom-timer)]
[(left-up) (set! left-drag-x mouse-x)
(set! left-drag-y mouse-y)
(zoom-or-unzoom)]
(when (not (and (= left-drag-x mouse-x)
(= left-drag-y mouse-y)))
(set! left-drag-x mouse-x)
(set! left-drag-y mouse-y)
(set! dragging? #t)
(set-zoom-timer))]
[(and (not (send evt get-left-down))
(<= 0 mouse-x (send (get-bitmap) get-width))
(<= 0 mouse-y (send (get-bitmap) get-height)))
(set-click-message)])]))
(define mouse-event-callback #f)
(define mouse-event-handler zoom-or-unzoom-mouse-event-handler)
(define (user-mouse-event-handler dc x y editorx editory evt)
(define mouse-x (- (send evt get-x) x))
(define mouse-y (- (send evt get-y) y))
(if (rect-contains? (send area get-area-bounds-rect) (vector mouse-x mouse-y))
(match-let (((vector px py) (send area dc->plot (vector mouse-x mouse-y))))
(mouse-event-callback this evt px py))
(mouse-event-callback this evt #f #f)))
(define/public (set-mouse-event-callback callback)
(set! mouse-event-callback callback)
(set! mouse-event-handler
(if mouse-event-callback
user-mouse-event-handler
zoom-or-unzoom-mouse-event-handler)))
(define the-overlay-renderers #f)
(define/public (set-overlay-renderers renderers)
(set! the-overlay-renderers (and renderers (flatten renderers)))
(refresh))
(define (draw-overlay-renderers dc x y left top right bottom)
(when the-overlay-renderers
the DC to be set to the origin or ( 0 , 0 ) of the plot , see
* Since the DC origin has been adjusted to start at X , Y , the LEFT ,
snip , we seem to have an off - by - one error and pixels are " left
over " at the edge . This is adjusted using the ` add1 ` , ` sub1 ` calls
(match-define (vector (ivl cleft cright) (ivl ctop cbottom))
(plot-bounds->area-bounds plot-bounds-rect))
(define dc-x-min (max cleft (add1 (- left x))))
(define dc-x-max (min cright (sub1 (- right x))))
(define dc-y-min (max ctop (add1 (- top y))))
(define dc-y-max (min cbottom (sub1 (- bottom y))))
(when (and (> dc-x-max dc-x-min) (> dc-y-max dc-y-min))
(define overlay-plot-bounds
(area-bounds->plot-bounds (vector (ivl dc-x-min dc-x-max) (ivl dc-y-min dc-y-max))))
(define-values (scale-x scale-y) (send dc get-scale))
(define-values (origin-x origin-y) (send dc get-origin))
(send dc set-origin (+ origin-x (* scale-x x)) (+ origin-y (* scale-y y)))
(parameterize/group ([plot-parameters (get-saved-plot-parameters)])
(parameterize ([plot-decorations? #f]
[plot-background-alpha 0])
(define overlay-area
(make-object 2d-plot-area%
overlay-plot-bounds
'() '() '() '() '()
dc
dc-x-min dc-y-min
(- dc-x-max dc-x-min) (- dc-y-max dc-y-min)
(send area get-aspect-ratio)))
(plot-area overlay-area the-overlay-renderers)))
(send dc set-origin origin-x origin-y))))
(define/override (on-event dc x y editorx editory evt)
(apply mouse-event-handler dc x y editorx editory evt '())
(super on-event dc x y editorx editory evt))
(define (draw-selection dc dc-x-min dc-y-min rect)
(with-handlers ([exn? (λ (e) (printf "draw-selection: ~v~n" e))])
(when (and (rect-rational? rect) (not (rect-zero-area? rect)))
(define width (send (get-bitmap) get-width))
(define height (send (get-bitmap) get-height))
(define-values (scale-x scale-y) (send dc get-scale))
(define-values (origin-x origin-y) (send dc get-origin))
(define smoothing (send dc get-smoothing))
(define text-mode (send dc get-text-mode))
(define font (send dc get-font))
(define pen (send dc get-pen))
(define brush (send dc get-brush))
(define alpha (send dc get-alpha))
(define text-foreground (send dc get-text-foreground))
(send dc set-origin
(+ origin-x (* scale-x dc-x-min))
(+ origin-y (* scale-y dc-y-min)))
(send dc set-smoothing 'smoothed)
(send dc set-text-mode 'transparent)
(send dc set-font (send the-font-list find-or-create-font
(real->font-size (plot-font-size))
(plot-font-face)
(plot-font-family)
'normal
'normal))
(match-define (vector (ivl sel-x-min sel-x-max) (ivl sel-y-min sel-y-max)) rect)
(define sel-x-size (- sel-x-max sel-x-min))
(define sel-y-size (- sel-y-max sel-y-min))
(define select-color (get-highlight-background-color))
(define pen-color (color->color% (->pen-color (plot-foreground))))
(define brush-color (color->color% (->brush-color (plot-background))))
(send dc set-pen select-color 1 'transparent)
(send dc set-brush select-color 'solid)
(send dc set-alpha 1/4)
(send dc draw-rectangle sel-x-min sel-y-min sel-x-size sel-y-size)
(send dc set-pen select-color (* 1/2 (plot-line-width)) 'solid)
(send dc set-brush select-color 'transparent)
(send dc set-alpha 3/4)
(send dc draw-rectangle sel-x-min sel-y-min sel-x-size sel-y-size)
(match-define (vector (ivl x-min x-max) (ivl y-min y-max)) plot-bounds-rect)
(match-define (vector (ivl new-x-min new-x-max) (ivl new-y-min new-y-max))
(area-bounds->plot-bounds rect))
(match-define (list new-x-min-str new-x-max-str)
(format-tick-labels (plot-x-ticks) x-min x-max (list new-x-min new-x-max)))
(match-define (list new-y-min-str new-y-max-str)
(format-tick-labels (plot-y-ticks) y-min y-max (list new-y-min new-y-max)))
(match-define (vector (ivl new-area-x-min new-area-x-max)
(ivl new-area-y-min new-area-y-max))
rect)
(define new-area-x-mid (* 1/2 (+ new-area-x-min new-area-x-max)))
(define new-area-y-mid (* 1/2 (+ new-area-y-min new-area-y-max)))
(send dc set-alpha 1)
(send this draw-text dc new-x-min-str new-area-x-min new-area-y-mid
pen-color brush-color 'center (* 1/2 pi) 0)
(send this draw-text dc new-x-max-str new-area-x-max new-area-y-mid
pen-color brush-color 'center (* 1/2 pi) 0)
(send this draw-text dc new-y-min-str new-area-x-mid new-area-y-max
pen-color brush-color 'center 0 0)
(send this draw-text dc new-y-max-str new-area-x-mid new-area-y-min
pen-color brush-color 'center 0 0)
(send dc set-origin origin-x origin-y)
(send dc set-smoothing smoothing)
(send dc set-text-mode text-mode)
(send dc set-font font)
(send dc set-pen pen)
(send dc set-brush brush)
(send dc set-alpha alpha)
(send dc set-text-foreground text-foreground))))
(define/override (draw dc x y left top right bottom dx dy draw-caret)
(super draw dc x y left top right bottom dx dy draw-caret)
(when dragging?
(parameterize/group ([plot-parameters (get-saved-plot-parameters)])
(draw-selection dc x y (get-new-area-bounds-rect))))
(draw-overlay-renderers dc x y left top right bottom))
(define/override (resize w h)
(when (not (and (= w width) (= h height)))
(set! width w)
(set! height h)
(stop-message)
(start-update-thread #f)
(set-update #t))
(super resize w h))
(define plot-metrics-ok? #f)
(match-define (list bounds ->dc ->plot plane)
(send area get-plot-metrics-functions))
(define (update-metrics)
(match-define (list new-bounds new-->dc new-->plot new-plane)
(send area get-plot-metrics-functions))
(set! bounds new-bounds)
(set! ->dc new-->dc)
(set! ->plot new-->plot)
(set! plane new-plane)
(set! plot-metrics-ok? #t))
(define/public (get-plot-bounds) (unless plot-metrics-ok? (update-metrics)) (bounds))
(define/public (plot->dc coords) (unless plot-metrics-ok? (update-metrics)) (->dc coords))
(define/public (dc->plot coords) (unless plot-metrics-ok? (update-metrics)) (->plot coords))
(define/public (plane-vector) (unless plot-metrics-ok? (update-metrics)) (plane))
(define/public (get-plot-metrics-functions) (unless plot-metrics-ok? (update-metrics)) (list bounds ->dc ->plot plane))
))
(define (make-2d-plot-snip
init-bm saved-plot-parameters
make-bm plot-bounds-rect area width height)
(make-object 2d-plot-snip%
init-bm saved-plot-parameters
make-bm plot-bounds-rect area width height))
|
d3ffaa72910dbec2e948a93d834e93c50608a38dc4599730271678c382cae33b | ragkousism/Guix-on-Hurd | markdown.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 >
Copyright © 2015 < >
Copyright © 2016 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages markdown)
#:use-module (guix licenses)
#:use-module (guix download)
#:use-module (guix packages)
#:use-module (guix build-system gnu)
#:use-module (guix build-system trivial)
#:use-module (guix build-system cmake)
#:use-module (gnu packages perl)
#:use-module (gnu packages python)
#:use-module (gnu packages web)
#:use-module (gnu packages zip))
(define-public hoedown
(package
(name "hoedown")
(version "3.0.7")
(source (origin
(method url-fetch)
(uri (string-append "/"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"0859dc2xjasd6kgkshi8mb20kbyw5sql1ln0hw3bfaf33qdh5dh1"))))
(build-system gnu-build-system)
(arguments
'(#:make-flags (list "CC=gcc" (string-append "PREFIX=" %output))
#:phases (modify-phases %standard-phases
(delete 'configure)) ; no configure script
#:test-target "test"))
(native-inputs
`(("python" ,python-2)
("tidy" ,tidy)))
(synopsis "Markdown processing library")
(description "Hoedown is a standards compliant, fast, secure markdown
processing library written in C.")
(home-page "")
(license expat)))
(define-public markdown
(package
(name "markdown")
(version "1.0.1")
(source
(origin
(method url-fetch)
(uri (string-append
"/"
(string-capitalize name) "_" version ".zip"))
(sha256
(base32 "0dq1pj91pvlwkv0jwcgdfpv6gvnxzrk3s8mnh7imamcclnvfj835"))))
(build-system trivial-build-system)
(arguments
'(#:modules ((guix build utils))
#:builder
(begin
(use-modules (guix build utils))
(let ((source (assoc-ref %build-inputs "source"))
(out (assoc-ref %outputs "out"))
(perlbd (string-append (assoc-ref %build-inputs "perl") "/bin"))
(unzip (string-append (assoc-ref %build-inputs "unzip")
"/bin/unzip")))
(mkdir-p out)
(with-directory-excursion out
(system* unzip source)
(mkdir "bin")
(mkdir-p "share/doc")
(rename-file "Markdown_1.0.1/Markdown.pl" "bin/markdown")
(rename-file "Markdown_1.0.1/Markdown Readme.text"
"share/doc/README")
(patch-shebang "bin/markdown" (list perlbd))
(delete-file-recursively "Markdown_1.0.1"))))))
(native-inputs `(("unzip" ,unzip)))
(inputs `(("perl" ,perl)))
(home-page "")
(synopsis "Text-to-HTML conversion tool")
(description
"Markdown is a text-to-HTML conversion tool for web writers. It allows
you to write using an easy-to-read, easy-to-write plain text format, then
convert it to structurally valid XHTML (or HTML).")
(license (non-copyleft "file"
"See License.text in the distribution."))))
(define-public cmark
(package
(name "cmark")
(version "0.26.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"1mpmcy4bbmc8m058zqs9dwx49lcfi7bdnfszsr9y66cwgylia1mm"))))
(build-system cmake-build-system)
(arguments
'(#:test-target "test"))
(native-inputs `(("python" ,python)))
(synopsis "CommonMark Markdown reference implementation")
(description "CommonMark is a strongly defined, highly compatible
specification of Markdown. cmark is the C reference implementation of
CommonMark. It provides @code{libcmark} shared library for parsing
CommonMark to an abstract syntax tree (AST) and rendering the document
as HTML, groff man, LaTeX, CommonMark, or an XML representation of the
AST. The package also provides the command-line program @command{cmark}
for parsing and rendering CommonMark.")
(home-page "")
cmark is distributed with a BSD-2 license , but some components are Expat
licensed . The CommonMark specification is Creative Commons CC - BY - SA 4.0
;; licensed. See 'COPYING' in the source distribution for more information.
(license (list bsd-2 expat cc-by-sa4.0))))
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/markdown.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
no configure script
licensed. See 'COPYING' in the source distribution for more information. | Copyright © 2015 >
Copyright © 2015 < >
Copyright © 2016 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages markdown)
#:use-module (guix licenses)
#:use-module (guix download)
#:use-module (guix packages)
#:use-module (guix build-system gnu)
#:use-module (guix build-system trivial)
#:use-module (guix build-system cmake)
#:use-module (gnu packages perl)
#:use-module (gnu packages python)
#:use-module (gnu packages web)
#:use-module (gnu packages zip))
(define-public hoedown
(package
(name "hoedown")
(version "3.0.7")
(source (origin
(method url-fetch)
(uri (string-append "/"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"0859dc2xjasd6kgkshi8mb20kbyw5sql1ln0hw3bfaf33qdh5dh1"))))
(build-system gnu-build-system)
(arguments
'(#:make-flags (list "CC=gcc" (string-append "PREFIX=" %output))
#:phases (modify-phases %standard-phases
#:test-target "test"))
(native-inputs
`(("python" ,python-2)
("tidy" ,tidy)))
(synopsis "Markdown processing library")
(description "Hoedown is a standards compliant, fast, secure markdown
processing library written in C.")
(home-page "")
(license expat)))
(define-public markdown
(package
(name "markdown")
(version "1.0.1")
(source
(origin
(method url-fetch)
(uri (string-append
"/"
(string-capitalize name) "_" version ".zip"))
(sha256
(base32 "0dq1pj91pvlwkv0jwcgdfpv6gvnxzrk3s8mnh7imamcclnvfj835"))))
(build-system trivial-build-system)
(arguments
'(#:modules ((guix build utils))
#:builder
(begin
(use-modules (guix build utils))
(let ((source (assoc-ref %build-inputs "source"))
(out (assoc-ref %outputs "out"))
(perlbd (string-append (assoc-ref %build-inputs "perl") "/bin"))
(unzip (string-append (assoc-ref %build-inputs "unzip")
"/bin/unzip")))
(mkdir-p out)
(with-directory-excursion out
(system* unzip source)
(mkdir "bin")
(mkdir-p "share/doc")
(rename-file "Markdown_1.0.1/Markdown.pl" "bin/markdown")
(rename-file "Markdown_1.0.1/Markdown Readme.text"
"share/doc/README")
(patch-shebang "bin/markdown" (list perlbd))
(delete-file-recursively "Markdown_1.0.1"))))))
(native-inputs `(("unzip" ,unzip)))
(inputs `(("perl" ,perl)))
(home-page "")
(synopsis "Text-to-HTML conversion tool")
(description
"Markdown is a text-to-HTML conversion tool for web writers. It allows
you to write using an easy-to-read, easy-to-write plain text format, then
convert it to structurally valid XHTML (or HTML).")
(license (non-copyleft "file"
"See License.text in the distribution."))))
(define-public cmark
(package
(name "cmark")
(version "0.26.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
version ".tar.gz"))
(file-name (string-append name "-" version ".tar.gz"))
(sha256
(base32
"1mpmcy4bbmc8m058zqs9dwx49lcfi7bdnfszsr9y66cwgylia1mm"))))
(build-system cmake-build-system)
(arguments
'(#:test-target "test"))
(native-inputs `(("python" ,python)))
(synopsis "CommonMark Markdown reference implementation")
(description "CommonMark is a strongly defined, highly compatible
specification of Markdown. cmark is the C reference implementation of
CommonMark. It provides @code{libcmark} shared library for parsing
CommonMark to an abstract syntax tree (AST) and rendering the document
as HTML, groff man, LaTeX, CommonMark, or an XML representation of the
AST. The package also provides the command-line program @command{cmark}
for parsing and rendering CommonMark.")
(home-page "")
cmark is distributed with a BSD-2 license , but some components are Expat
licensed . The CommonMark specification is Creative Commons CC - BY - SA 4.0
(license (list bsd-2 expat cc-by-sa4.0))))
|
70b9e1aeb8f844cf189b220d378fb257ee6a4319654d3304216d8405beb184c9 | LeventErkok/sbvPlugin | T26.hs | {-# OPTIONS_GHC -fplugin=Data.SBV.Plugin #-}
module T26 where
import Data.SBV.Plugin
{-# ANN f theorem #-}
f :: Bool
f = False
| null | https://raw.githubusercontent.com/LeventErkok/sbvPlugin/b6a6e94cd237a4f64f985783931bd7656e7a6a69/tests/T26.hs | haskell | # OPTIONS_GHC -fplugin=Data.SBV.Plugin #
# ANN f theorem # |
module T26 where
import Data.SBV.Plugin
f :: Bool
f = False
|
45b77afe4c0a316cf3e0db8d4d075c36bf8e7dd22a4304beb99880a45d37c1df | russ/openpoker | game_start.erl | Copyright ( C ) 2005 - 2008 Wager Labs , SA
%%%%
%%%% THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS
CREATIVE COMMONS PUBLIC LICENSE ( " CCPL " OR " LICENSE " ) . THE WORK IS
%%%% PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF
%%%% THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT
%%%% LAW IS PROHIBITED.
%%%%
%%%% BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT
%%%% AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT
%%%% THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS
%%%% YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE
%%%% OF SUCH TERMS AND CONDITIONS.
%%%%
%%%% Please see LICENSE for full legal details and the following URL
%%%% for a human-readable explanation:
%%%%
-nc-sa/3.0/us/
%%%%
-module(game_start).
-export([start/3, game_start/3]).
-include("common.hrl").
-include("game.hrl").
-include("texas.hrl").
-include("pp.hrl").
-define(DELAY, 15000).
start(Game, Ctx, [Barrier]) ->
process_flag(trap_exit, true),
link(Barrier),
Game1 = Game#game{ barrier = Barrier },
Game2 = g:restart_timer(Game1, ?DELAY),
%% reset call amount
Ctx1 = Ctx#texas{ call = 0 },
{next, game_start, Game2, Ctx1}.
game_start(Game, Ctx, {timeout, _, _}) ->
Ready = g:get_seats(Game, ?PS_READY),
ReqCount = Game#game.required_player_count,
Barrier = Game#game.barrier,
Start = (length(Ready) >= ReqCount),
Game1 = if
Start ->
barrier:bump(Barrier),
g:cancel_timer(Game);
true ->
g:notify_cancel_game(Game),
g:restart_timer(Game, ?DELAY)
end,
{continue, Game1, Ctx};
game_start(Game, Ctx, {'EXIT', Barrier, _})
when Barrier == Game#game.barrier ->
g:notify_start_game(Game),
{stop, Game, Ctx};
game_start(Game, Ctx, R = #join{}) ->
Game1 = g:join(Game, R#join { state = ?PS_PLAY }),
{continue, Game1, Ctx};
game_start(Game, Ctx, R = #leave{}) ->
Game1 = g:leave(Game, R#leave { state = ?PS_ANY }),
{continue, Game1, Ctx};
game_start(Game, Ctx, _) ->
{skip, Game, Ctx}.
| null | https://raw.githubusercontent.com/russ/openpoker/62edd72a35b9ef52f55da9303cf1e06142e95895/src/game_start.erl | erlang |
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS
PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF
THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT
LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT
AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT
THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS
YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE
OF SUCH TERMS AND CONDITIONS.
Please see LICENSE for full legal details and the following URL
for a human-readable explanation:
reset call amount | Copyright ( C ) 2005 - 2008 Wager Labs , SA
CREATIVE COMMONS PUBLIC LICENSE ( " CCPL " OR " LICENSE " ) . THE WORK IS
-nc-sa/3.0/us/
-module(game_start).
-export([start/3, game_start/3]).
-include("common.hrl").
-include("game.hrl").
-include("texas.hrl").
-include("pp.hrl").
-define(DELAY, 15000).
start(Game, Ctx, [Barrier]) ->
process_flag(trap_exit, true),
link(Barrier),
Game1 = Game#game{ barrier = Barrier },
Game2 = g:restart_timer(Game1, ?DELAY),
Ctx1 = Ctx#texas{ call = 0 },
{next, game_start, Game2, Ctx1}.
game_start(Game, Ctx, {timeout, _, _}) ->
Ready = g:get_seats(Game, ?PS_READY),
ReqCount = Game#game.required_player_count,
Barrier = Game#game.barrier,
Start = (length(Ready) >= ReqCount),
Game1 = if
Start ->
barrier:bump(Barrier),
g:cancel_timer(Game);
true ->
g:notify_cancel_game(Game),
g:restart_timer(Game, ?DELAY)
end,
{continue, Game1, Ctx};
game_start(Game, Ctx, {'EXIT', Barrier, _})
when Barrier == Game#game.barrier ->
g:notify_start_game(Game),
{stop, Game, Ctx};
game_start(Game, Ctx, R = #join{}) ->
Game1 = g:join(Game, R#join { state = ?PS_PLAY }),
{continue, Game1, Ctx};
game_start(Game, Ctx, R = #leave{}) ->
Game1 = g:leave(Game, R#leave { state = ?PS_ANY }),
{continue, Game1, Ctx};
game_start(Game, Ctx, _) ->
{skip, Game, Ctx}.
|
14b1a44cf02e3b709bba98b255b99650ebccbb716d32376967e9c9258287cfda | oasis-open/openc2-lycan-beam | scan_SUITE.erl | @author
( C ) 2018 , sFractal Consulting LLC
%%%
-module(scan_SUITE).
-author("Duncan Sparrell").
-license("MIT").
-copyright("2018, Duncan Sparrell sFractal Consulting LLC").
%%%-------------------------------------------------------------------
Copyright ( c ) 2018 , , sFractal Consulting
MIT License
%%% 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.
%%%-------------------------------------------------------------------
%% for test export all functions
-export( [ all/0
, suite/0
, init_per_suite/1
, end_per_suite/1
, test_scan_memory/1
]).
%% required for common_test to work
-include_lib("common_test/include/ct.hrl").
%% tests to run
all() ->
[ test_scan_memory
].
timeout if no reply in a minute
suite() ->
[{timetrap, {minutes, 2}}].
%% setup config parameters
init_per_suite(Config) ->
{ok, _AppList} = application:ensure_all_started(lager),
%%lager:info("AppList: ~p~n", [AppList]),
{ok, _AppList2} = application:ensure_all_started(gun),
%%lager:info("AppList2: ~p~n", [AppList2]),
%% since ct doesn't read sys.config, set configs here
application:set_env(haga, port, 8080),
application:set_env(haga, listener_count, 5),
%% start application
{ok, _AppList3} = application:ensure_all_started(haga),
%%lager:info("AppList3: ~p~n", [AppList3]),
lager_common_test_backend:bounce(debug),
Config.
end_per_suite(Config) ->
Config.
test_scan_memory(Config) ->
%% test json file with scan memory
JsonSendFileName = "scan.memory.json",
%% expect results files
JsonResponseFileName = "scan.memory.reply.json",
expect status = OK ie 200
StatusCode = 200,
%% send command and check results
ok = helper:post_oc2_body( JsonSendFileName
, StatusCode
, JsonResponseFileName
, Config
),
ok.
| null | https://raw.githubusercontent.com/oasis-open/openc2-lycan-beam/c8a580eb79a46cb3fa7db0d6576bfa23eb78c943/haga/erlang/haga/apps/haga/test/scan_SUITE.erl | erlang |
-------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
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.
-------------------------------------------------------------------
for test export all functions
required for common_test to work
tests to run
setup config parameters
lager:info("AppList: ~p~n", [AppList]),
lager:info("AppList2: ~p~n", [AppList2]),
since ct doesn't read sys.config, set configs here
start application
lager:info("AppList3: ~p~n", [AppList3]),
test json file with scan memory
expect results files
send command and check results | @author
( C ) 2018 , sFractal Consulting LLC
-module(scan_SUITE).
-author("Duncan Sparrell").
-license("MIT").
-copyright("2018, Duncan Sparrell sFractal Consulting LLC").
Copyright ( c ) 2018 , , sFractal Consulting
MIT License
( the " Software " ) , to deal in the Software without restriction ,
sell copies of the Software , and to permit persons to whom the
shall be included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
AND NONINFRINGEMENT . IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-export( [ all/0
, suite/0
, init_per_suite/1
, end_per_suite/1
, test_scan_memory/1
]).
-include_lib("common_test/include/ct.hrl").
all() ->
[ test_scan_memory
].
timeout if no reply in a minute
suite() ->
[{timetrap, {minutes, 2}}].
init_per_suite(Config) ->
{ok, _AppList} = application:ensure_all_started(lager),
{ok, _AppList2} = application:ensure_all_started(gun),
application:set_env(haga, port, 8080),
application:set_env(haga, listener_count, 5),
{ok, _AppList3} = application:ensure_all_started(haga),
lager_common_test_backend:bounce(debug),
Config.
end_per_suite(Config) ->
Config.
test_scan_memory(Config) ->
JsonSendFileName = "scan.memory.json",
JsonResponseFileName = "scan.memory.reply.json",
expect status = OK ie 200
StatusCode = 200,
ok = helper:post_oc2_body( JsonSendFileName
, StatusCode
, JsonResponseFileName
, Config
),
ok.
|
dd6ff4d71d87228d687a650e6d2612c35075aba4a759cfb863b50cb122101f91 | carl-eastlund/mischief | main.rkt | #lang racket/base
(require mischief/require)
(module+ test
(require rackunit/docs-complete))
(module+ reflection
(require scribble/manual)
(provide phase-1-exports phase-0-exports)
(define phase-1-exports empty)
(define phase-0-exports empty))
(define-syntax-rule (require/provide-phase-1 mod-path ...)
(begin
(require/provide
(only-meta-in 1
(for-syntax mod-path ...)))
(module+ reflection
(set! phase-1-exports
(list* 'mod-path ... phase-1-exports)))))
(define-syntax-rule (require/provide-phase-0 mod-path ...)
(begin
(require/provide
(only-meta-in 0
mod-path ...))
(module+ reflection
(set! phase-0-exports
(list* 'mod-path ... phase-0-exports)))))
(define-syntax-rule (require/provide/check-docs-phase-0 mod-path ...)
(begin
(require/provide-phase-0 mod-path ...)
(module+ test (check-docs (quote mod-path)) ...)
(module+ reflection
(set! phase-0-exports
(list* 'mod-path ... phase-0-exports)))))
(require/provide-phase-1
racket)
(require/provide-phase-0
racket
racket/block
racket/generic
racket/pretty
racket/syntax
racket/splicing
racket/generator
racket/runtime-path
racket/date
data/queue
syntax/parse
syntax/parse/define
syntax/parse/experimental/specialize
syntax/parse/experimental/template
syntax/id-table
syntax/kerncase
syntax/srcloc
syntax/location
syntax/strip-context)
(require/provide/check-docs-phase-0
mischief/define
mischief/values
mischief/error
mischief/dict
mischief/for
mischief/list
mischief/contract
mischief/match
mischief/function
mischief/boolean
mischief/maybe
mischief/symbol
mischief/keyword
mischief/quotation
mischief/phrase
mischief/stylish
mischief/string
mischief/struct
mischief/visitor
mischief/memoize
mischief/require
mischief/module
mischief/sort
mischief/scope
mischief/parse
mischief/dye-pack
mischief/transform
mischief/shorthand
mischief/fold
mischief/id-table
mischief/stream)
| null | https://raw.githubusercontent.com/carl-eastlund/mischief/ce58c3170240f12297e2f98475f53c9514225825/mischief/main.rkt | racket | #lang racket/base
(require mischief/require)
(module+ test
(require rackunit/docs-complete))
(module+ reflection
(require scribble/manual)
(provide phase-1-exports phase-0-exports)
(define phase-1-exports empty)
(define phase-0-exports empty))
(define-syntax-rule (require/provide-phase-1 mod-path ...)
(begin
(require/provide
(only-meta-in 1
(for-syntax mod-path ...)))
(module+ reflection
(set! phase-1-exports
(list* 'mod-path ... phase-1-exports)))))
(define-syntax-rule (require/provide-phase-0 mod-path ...)
(begin
(require/provide
(only-meta-in 0
mod-path ...))
(module+ reflection
(set! phase-0-exports
(list* 'mod-path ... phase-0-exports)))))
(define-syntax-rule (require/provide/check-docs-phase-0 mod-path ...)
(begin
(require/provide-phase-0 mod-path ...)
(module+ test (check-docs (quote mod-path)) ...)
(module+ reflection
(set! phase-0-exports
(list* 'mod-path ... phase-0-exports)))))
(require/provide-phase-1
racket)
(require/provide-phase-0
racket
racket/block
racket/generic
racket/pretty
racket/syntax
racket/splicing
racket/generator
racket/runtime-path
racket/date
data/queue
syntax/parse
syntax/parse/define
syntax/parse/experimental/specialize
syntax/parse/experimental/template
syntax/id-table
syntax/kerncase
syntax/srcloc
syntax/location
syntax/strip-context)
(require/provide/check-docs-phase-0
mischief/define
mischief/values
mischief/error
mischief/dict
mischief/for
mischief/list
mischief/contract
mischief/match
mischief/function
mischief/boolean
mischief/maybe
mischief/symbol
mischief/keyword
mischief/quotation
mischief/phrase
mischief/stylish
mischief/string
mischief/struct
mischief/visitor
mischief/memoize
mischief/require
mischief/module
mischief/sort
mischief/scope
mischief/parse
mischief/dye-pack
mischief/transform
mischief/shorthand
mischief/fold
mischief/id-table
mischief/stream)
| |
5d01fa107834cf9e73bebaed6bdf005aae42263bb9272320e4618bafa9604697 | haskell-webgear/webgear | QueryParam.hs | # OPTIONS_GHC -Wno - orphans #
| OpenApi implementation of ' QueryParam ' trait .
module WebGear.OpenApi.Trait.QueryParam where
import Data.OpenApi (
Param (..),
ParamLocation (ParamQuery),
Referenced (Inline),
ToSchema,
toSchema,
)
import Data.Proxy (Proxy (Proxy))
import Data.String (fromString)
import GHC.TypeLits (KnownSymbol, symbolVal)
import WebGear.Core.Modifiers
import WebGear.Core.Request (Request)
import WebGear.Core.Trait (Get (..), TraitAbsence)
import WebGear.Core.Trait.QueryParam (QueryParam (..))
import WebGear.OpenApi.Handler (DocNode (DocQueryParam), OpenApiHandler (..), singletonNode)
instance (KnownSymbol name, ToSchema val, TraitAbsence (QueryParam Required ps name val) Request) => Get (OpenApiHandler m) (QueryParam Required ps name val) Request where
# INLINE getTrait #
getTrait _ =
let param =
(mempty :: Param)
{ _paramName = fromString $ symbolVal $ Proxy @name
, _paramIn = ParamQuery
, _paramRequired = Just True
, _paramSchema = Just $ Inline $ toSchema $ Proxy @val
}
in OpenApiHandler $ singletonNode (DocQueryParam param)
instance (KnownSymbol name, ToSchema val, TraitAbsence (QueryParam Optional ps name val) Request) => Get (OpenApiHandler m) (QueryParam Optional ps name val) Request where
# INLINE getTrait #
getTrait _ =
let param =
(mempty :: Param)
{ _paramName = fromString $ symbolVal $ Proxy @name
, _paramIn = ParamQuery
, _paramRequired = Just False
, _paramSchema = Just $ Inline $ toSchema $ Proxy @val
}
in OpenApiHandler $ singletonNode (DocQueryParam param)
| null | https://raw.githubusercontent.com/haskell-webgear/webgear/52e90e28d81e4ce6d7c8e63b3f9769f6629b031f/webgear-openapi/src/WebGear/OpenApi/Trait/QueryParam.hs | haskell | # OPTIONS_GHC -Wno - orphans #
| OpenApi implementation of ' QueryParam ' trait .
module WebGear.OpenApi.Trait.QueryParam where
import Data.OpenApi (
Param (..),
ParamLocation (ParamQuery),
Referenced (Inline),
ToSchema,
toSchema,
)
import Data.Proxy (Proxy (Proxy))
import Data.String (fromString)
import GHC.TypeLits (KnownSymbol, symbolVal)
import WebGear.Core.Modifiers
import WebGear.Core.Request (Request)
import WebGear.Core.Trait (Get (..), TraitAbsence)
import WebGear.Core.Trait.QueryParam (QueryParam (..))
import WebGear.OpenApi.Handler (DocNode (DocQueryParam), OpenApiHandler (..), singletonNode)
instance (KnownSymbol name, ToSchema val, TraitAbsence (QueryParam Required ps name val) Request) => Get (OpenApiHandler m) (QueryParam Required ps name val) Request where
# INLINE getTrait #
getTrait _ =
let param =
(mempty :: Param)
{ _paramName = fromString $ symbolVal $ Proxy @name
, _paramIn = ParamQuery
, _paramRequired = Just True
, _paramSchema = Just $ Inline $ toSchema $ Proxy @val
}
in OpenApiHandler $ singletonNode (DocQueryParam param)
instance (KnownSymbol name, ToSchema val, TraitAbsence (QueryParam Optional ps name val) Request) => Get (OpenApiHandler m) (QueryParam Optional ps name val) Request where
# INLINE getTrait #
getTrait _ =
let param =
(mempty :: Param)
{ _paramName = fromString $ symbolVal $ Proxy @name
, _paramIn = ParamQuery
, _paramRequired = Just False
, _paramSchema = Just $ Inline $ toSchema $ Proxy @val
}
in OpenApiHandler $ singletonNode (DocQueryParam param)
| |
f988edaf151d04d088f1f162f4a97c3843e8357334b1a59e96df079842283cfd | fpco/ide-backend | CopyFile.hs | # LANGUAGE CPP #
{-# OPTIONS_HADDOCK hide #-}
module Distribution.Compat.CopyFile (
copyFile,
copyFileChanged,
filesEqual,
copyOrdinaryFile,
copyExecutableFile,
setFileOrdinary,
setFileExecutable,
setDirOrdinary,
) where
import Control.Monad
( when, unless )
import Control.Exception
( bracket, bracketOnError, throwIO )
import qualified Data.ByteString.Lazy as BSL
import Distribution.Compat.Exception
( catchIO )
import System.IO.Error
( ioeSetLocation )
import System.Directory
( doesFileExist, renameFile, removeFile )
import Distribution.Compat.TempFile
( openBinaryTempFile )
import System.FilePath
( takeDirectory )
import System.IO
( openBinaryFile, IOMode(ReadMode), hClose, hGetBuf, hPutBuf
, withBinaryFile )
import Foreign
( allocaBytes )
#ifndef mingw32_HOST_OS
import System.Posix.Internals (withFilePath)
import System.Posix.Types
( FileMode )
import System.Posix.Internals
( c_chmod )
import Foreign.C
( throwErrnoPathIfMinus1_ )
#endif /* mingw32_HOST_OS */
copyOrdinaryFile, copyExecutableFile :: FilePath -> FilePath -> IO ()
copyOrdinaryFile src dest = copyFile src dest >> setFileOrdinary dest
copyExecutableFile src dest = copyFile src dest >> setFileExecutable dest
setFileOrdinary, setFileExecutable, setDirOrdinary :: FilePath -> IO ()
#ifndef mingw32_HOST_OS
setFileOrdinary path = setFileMode path 0o644 -- file perms -rw-r--r--
setFileExecutable path = setFileMode path 0o755 -- file perms -rwxr-xr-x
setFileMode :: FilePath -> FileMode -> IO ()
setFileMode name m =
withFilePath name $ \s -> do
throwErrnoPathIfMinus1_ "setFileMode" name (c_chmod s m)
#else
setFileOrdinary _ = return ()
setFileExecutable _ = return ()
#endif
This happens to be true on Unix and currently on Windows too :
setDirOrdinary = setFileExecutable
-- | Copies a file to a new destination.
-- Often you should use `copyFileChanged` instead.
copyFile :: FilePath -> FilePath -> IO ()
copyFile fromFPath toFPath =
copy
`catchIO` (\ioe -> throwIO (ioeSetLocation ioe "copyFile"))
where copy = bracket (openBinaryFile fromFPath ReadMode) hClose $ \hFrom ->
bracketOnError openTmp cleanTmp $ \(tmpFPath, hTmp) ->
do allocaBytes bufferSize $ copyContents hFrom hTmp
hClose hTmp
renameFile tmpFPath toFPath
openTmp = openBinaryTempFile (takeDirectory toFPath) ".copyFile.tmp"
cleanTmp (tmpFPath, hTmp) = do
hClose hTmp `catchIO` \_ -> return ()
removeFile tmpFPath `catchIO` \_ -> return ()
bufferSize = 4096
copyContents hFrom hTo buffer = do
count <- hGetBuf hFrom buffer bufferSize
when (count > 0) $ do
hPutBuf hTo buffer count
copyContents hFrom hTo buffer
-- | Like `copyFile`, but does not touch the target if source and destination
-- are already byte-identical. This is recommended as it is useful for
-- time-stamp based recompilation avoidance.
copyFileChanged :: FilePath -> FilePath -> IO ()
copyFileChanged src dest = do
equal <- filesEqual src dest
unless equal $ copyFile src dest
| Checks if two files are byte - identical .
-- Returns False if either of the files do not exist.
filesEqual :: FilePath -> FilePath -> IO Bool
filesEqual f1 f2 = do
ex1 <- doesFileExist f1
ex2 <- doesFileExist f2
if not (ex1 && ex2) then return False else do
withBinaryFile f1 ReadMode $ \h1 ->
withBinaryFile f2 ReadMode $ \h2 -> do
c1 <- BSL.hGetContents h1
c2 <- BSL.hGetContents h2
return $! c1 == c2
| null | https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/TestSuite/inputs/Cabal-1.22.0.0/Distribution/Compat/CopyFile.hs | haskell | # OPTIONS_HADDOCK hide #
file perms -rw-r--r--
file perms -rwxr-xr-x
| Copies a file to a new destination.
Often you should use `copyFileChanged` instead.
| Like `copyFile`, but does not touch the target if source and destination
are already byte-identical. This is recommended as it is useful for
time-stamp based recompilation avoidance.
Returns False if either of the files do not exist. | # LANGUAGE CPP #
module Distribution.Compat.CopyFile (
copyFile,
copyFileChanged,
filesEqual,
copyOrdinaryFile,
copyExecutableFile,
setFileOrdinary,
setFileExecutable,
setDirOrdinary,
) where
import Control.Monad
( when, unless )
import Control.Exception
( bracket, bracketOnError, throwIO )
import qualified Data.ByteString.Lazy as BSL
import Distribution.Compat.Exception
( catchIO )
import System.IO.Error
( ioeSetLocation )
import System.Directory
( doesFileExist, renameFile, removeFile )
import Distribution.Compat.TempFile
( openBinaryTempFile )
import System.FilePath
( takeDirectory )
import System.IO
( openBinaryFile, IOMode(ReadMode), hClose, hGetBuf, hPutBuf
, withBinaryFile )
import Foreign
( allocaBytes )
#ifndef mingw32_HOST_OS
import System.Posix.Internals (withFilePath)
import System.Posix.Types
( FileMode )
import System.Posix.Internals
( c_chmod )
import Foreign.C
( throwErrnoPathIfMinus1_ )
#endif /* mingw32_HOST_OS */
copyOrdinaryFile, copyExecutableFile :: FilePath -> FilePath -> IO ()
copyOrdinaryFile src dest = copyFile src dest >> setFileOrdinary dest
copyExecutableFile src dest = copyFile src dest >> setFileExecutable dest
setFileOrdinary, setFileExecutable, setDirOrdinary :: FilePath -> IO ()
#ifndef mingw32_HOST_OS
setFileMode :: FilePath -> FileMode -> IO ()
setFileMode name m =
withFilePath name $ \s -> do
throwErrnoPathIfMinus1_ "setFileMode" name (c_chmod s m)
#else
setFileOrdinary _ = return ()
setFileExecutable _ = return ()
#endif
This happens to be true on Unix and currently on Windows too :
setDirOrdinary = setFileExecutable
copyFile :: FilePath -> FilePath -> IO ()
copyFile fromFPath toFPath =
copy
`catchIO` (\ioe -> throwIO (ioeSetLocation ioe "copyFile"))
where copy = bracket (openBinaryFile fromFPath ReadMode) hClose $ \hFrom ->
bracketOnError openTmp cleanTmp $ \(tmpFPath, hTmp) ->
do allocaBytes bufferSize $ copyContents hFrom hTmp
hClose hTmp
renameFile tmpFPath toFPath
openTmp = openBinaryTempFile (takeDirectory toFPath) ".copyFile.tmp"
cleanTmp (tmpFPath, hTmp) = do
hClose hTmp `catchIO` \_ -> return ()
removeFile tmpFPath `catchIO` \_ -> return ()
bufferSize = 4096
copyContents hFrom hTo buffer = do
count <- hGetBuf hFrom buffer bufferSize
when (count > 0) $ do
hPutBuf hTo buffer count
copyContents hFrom hTo buffer
copyFileChanged :: FilePath -> FilePath -> IO ()
copyFileChanged src dest = do
equal <- filesEqual src dest
unless equal $ copyFile src dest
| Checks if two files are byte - identical .
filesEqual :: FilePath -> FilePath -> IO Bool
filesEqual f1 f2 = do
ex1 <- doesFileExist f1
ex2 <- doesFileExist f2
if not (ex1 && ex2) then return False else do
withBinaryFile f1 ReadMode $ \h1 ->
withBinaryFile f2 ReadMode $ \h2 -> do
c1 <- BSL.hGetContents h1
c2 <- BSL.hGetContents h2
return $! c1 == c2
|
dd6dd1878afeab7dd236becd6d604364da61b3f6d2dd7f35f27fd14aa9826b02 | mathematical-systems/clml | packages.lisp | (in-package :cl)
(defpackage :ffi-utils
(:use :cl :alexandria)
(:export #:complex-float
#:complex-double
#:defffun
#:with-safe-foreign-function-call-settings
#:make-static-array
#:with-arrays-as-foreign-arrays
))
(defpackage :mkl.blas-lapack-common
(:use :cl :alexandria :ffi-utils)
(:export #:blas-int
#:+precision-definitions+
#:+matrix-type-definitions+
#:defblas
#:deflapack
))
(defpackage :mkl.blas
(:use :cl :alexandria :ffi-utils :mkl.blas-lapack-common))
(defpackage :mkl.lapack
(:use :cl :alexandria :ffi-utils :mkl.blas-lapack-common))
| null | https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/addons/blas-lapack-ffi/src/packages.lisp | lisp | (in-package :cl)
(defpackage :ffi-utils
(:use :cl :alexandria)
(:export #:complex-float
#:complex-double
#:defffun
#:with-safe-foreign-function-call-settings
#:make-static-array
#:with-arrays-as-foreign-arrays
))
(defpackage :mkl.blas-lapack-common
(:use :cl :alexandria :ffi-utils)
(:export #:blas-int
#:+precision-definitions+
#:+matrix-type-definitions+
#:defblas
#:deflapack
))
(defpackage :mkl.blas
(:use :cl :alexandria :ffi-utils :mkl.blas-lapack-common))
(defpackage :mkl.lapack
(:use :cl :alexandria :ffi-utils :mkl.blas-lapack-common))
| |
d9d5de44172d84cbb2706873b1385cae963ee7667138f329ae2260503c2347c2 | janestreet/base | test_container.ml | open! Base
open! Container
module Test_generic (Elt : sig
type 'a t
val of_int : int -> int t
val to_int : int t -> int
end) (Container : sig
type 'a t [@@deriving sexp]
include Generic with type ('a, _) t := 'a t with type 'a elt := 'a Elt.t
val mem : 'a t -> 'a Elt.t -> equal:(('a Elt.t -> 'a Elt.t -> bool)[@local]) -> bool
val of_list : 'a Elt.t list -> [ `Ok of 'a t | `Skip_test ]
end) : sig
type 'a t [@@deriving sexp]
include Generic with type ('a, _) t := 'a t
val mem : 'a t -> 'a Elt.t -> equal:(('a Elt.t -> 'a Elt.t -> bool)[@local]) -> bool
end
with type 'a t := 'a Container.t
with type 'a elt := 'a Elt.t =
(* This signature constraint reminds us to add unit tests when functions are added to
[Generic]. *)
struct
open Container
let find = find
let find_map = find_map
let fold = fold
let is_empty = is_empty
let iter = iter
let length = length
let mem = mem
let sexp_of_t = sexp_of_t
let t_of_sexp = t_of_sexp
let to_array = to_array
let to_list = to_list
let fold_result = fold_result
let fold_until = fold_until
let%test_unit _ =
let ( = ) = Poly.equal in
let compare = Poly.compare in
List.iter [ 0; 1; 2; 3; 4; 8; 128 ] ~f:(fun n ->
let list = List.init n ~f:Elt.of_int in
match Container.of_list list with
| `Skip_test -> ()
| `Ok c ->
let sort l = List.sort l ~compare in
let sorts_are_equal l1 l2 = sort l1 = sort l2 in
assert (n = Container.length c);
assert (n = 0 = Container.is_empty c);
assert (
sorts_are_equal list (Container.fold c ~init:[] ~f:(fun ac e -> e :: ac)));
assert (sorts_are_equal list (Container.to_list c));
assert (sorts_are_equal list (Array.to_list (Container.to_array c)));
assert (n > 0 = Option.is_some (Container.find c ~f:(fun e -> Elt.to_int e = 0)));
assert (
n > 0 = Option.is_some (Container.find c ~f:(fun e -> Elt.to_int e = n - 1)));
assert (Option.is_none (Container.find c ~f:(fun e -> Elt.to_int e = n)));
assert (n > 0 = Container.mem c (Elt.of_int 0) ~equal:( = ));
if n > 0 then assert (Container.mem c (Elt.of_int (n - 1)) ~equal:( = ));
assert (not (Container.mem c (Elt.of_int n) ~equal:( = )));
assert (
n
> 0
= Option.is_some
(Container.find_map c ~f:(fun e ->
if Elt.to_int e = 0 then Some () else None)));
assert (
n
> 0
= Option.is_some
(Container.find_map c ~f:(fun e ->
if Elt.to_int e = n - 1 then Some () else None)));
assert (
Option.is_none
(Container.find_map c ~f:(fun e ->
if Elt.to_int e = n then Some () else None)));
let r = ref 0 in
Container.iter c ~f:(fun e -> r := !r + Elt.to_int e);
assert (!r = List.fold list ~init:0 ~f:(fun n e -> n + Elt.to_int e));
assert (!r = sum (module Int) c ~f:Elt.to_int);
let c2 = [%of_sexp: int Container.t] ([%sexp_of: int Container.t] c) in
assert (sorts_are_equal list (Container.to_list c2));
let compare_elt a b = Int.compare (Elt.to_int a) (Elt.to_int b) in
if n = 0
then (
assert (!r = 0);
assert (min_elt ~compare:compare_elt c = None);
assert (max_elt ~compare:compare_elt c = None))
else (
assert (!r = n * (n - 1) / 2);
assert (Option.map ~f:Elt.to_int (min_elt ~compare:compare_elt c) = Some 0);
assert (
Option.map ~f:Elt.to_int (max_elt ~compare:compare_elt c)
= Some (Int.pred n)));
let mid = Container.length c / 2 in
(match
Container.fold_result c ~init:0 ~f:(fun count _elt ->
if count = mid then Error count else Ok (count + 1))
with
| Ok 0 -> assert (Container.length c = 0)
| Ok _ -> failwith "Expected fold to stop early"
| Error x -> assert (mid = x)))
;;
let min_elt = min_elt
let max_elt = max_elt
let count = count
let sum = sum
let exists = exists
let for_all = for_all
let%test_unit _ =
List.iter
[ []
; [ true ]
; [ false ]
; [ false; false ]
; [ true; false ]
; [ false; true ]
; [ true; true ]
]
~f:(fun bools ->
let count_should_be =
List.fold bools ~init:0 ~f:(fun n b -> if b then n + 1 else n)
in
let forall_should_be = List.fold bools ~init:true ~f:(fun ac b -> b && ac) in
let exists_should_be = List.fold bools ~init:false ~f:(fun ac b -> b || ac) in
match
Container.of_list (List.map bools ~f:(fun b -> Elt.of_int (if b then 1 else 0)))
with
| `Skip_test -> ()
| `Ok container ->
let is_one e = Elt.to_int e = 1 in
let ( = ) = Poly.equal in
assert (forall_should_be = Container.for_all container ~f:is_one);
assert (exists_should_be = Container.exists container ~f:is_one);
assert (count_should_be = Container.count container ~f:is_one))
;;
end
module Test_S1_allow_skipping_tests (Container : sig
type 'a t [@@deriving sexp]
include Container.S1 with type 'a t := 'a t
val of_list : 'a list -> [ `Ok of 'a t | `Skip_test ]
end) =
struct
include
Test_generic
(struct
type 'a t = 'a
let of_int = Fn.id
let to_int = Fn.id
end)
(Container)
end
module Test_S1 (Container : sig
type 'a t [@@deriving sexp]
include Container.S1 with type 'a t := 'a t
val of_list : 'a list -> 'a t
end) =
Test_S1_allow_skipping_tests (struct
include Container
let of_list l = `Ok (of_list l)
end)
module Test_S0 (Container : sig
module Elt : sig
type t [@@deriving sexp]
val of_int : int -> t
val to_int : t -> int
end
type t [@@deriving sexp]
include Container.S0 with type t := t and type elt := Elt.t
val of_list : Elt.t list -> t
end) =
struct
include
Test_generic
(struct
include Container.Elt
type 'a t = Container.Elt.t
end)
(struct
include Container
type 'a t = Container.t [@@deriving sexp]
let of_list l = `Ok (of_list l)
let mem t x ~equal:_ = Container.mem t x
end)
[ mem ] in the second functor argument above ignores its [ ~equal ] , so this [ ~equal ]
should never be called .
should never be called. *)
let mem t x = mem t x ~equal:(fun _ _ -> assert false)
end
| null | https://raw.githubusercontent.com/janestreet/base/1462b7d5458e96569275a1c673df968ecbf3342f/test/helpers/test_container.ml | ocaml | This signature constraint reminds us to add unit tests when functions are added to
[Generic]. | open! Base
open! Container
module Test_generic (Elt : sig
type 'a t
val of_int : int -> int t
val to_int : int t -> int
end) (Container : sig
type 'a t [@@deriving sexp]
include Generic with type ('a, _) t := 'a t with type 'a elt := 'a Elt.t
val mem : 'a t -> 'a Elt.t -> equal:(('a Elt.t -> 'a Elt.t -> bool)[@local]) -> bool
val of_list : 'a Elt.t list -> [ `Ok of 'a t | `Skip_test ]
end) : sig
type 'a t [@@deriving sexp]
include Generic with type ('a, _) t := 'a t
val mem : 'a t -> 'a Elt.t -> equal:(('a Elt.t -> 'a Elt.t -> bool)[@local]) -> bool
end
with type 'a t := 'a Container.t
with type 'a elt := 'a Elt.t =
struct
open Container
let find = find
let find_map = find_map
let fold = fold
let is_empty = is_empty
let iter = iter
let length = length
let mem = mem
let sexp_of_t = sexp_of_t
let t_of_sexp = t_of_sexp
let to_array = to_array
let to_list = to_list
let fold_result = fold_result
let fold_until = fold_until
let%test_unit _ =
let ( = ) = Poly.equal in
let compare = Poly.compare in
List.iter [ 0; 1; 2; 3; 4; 8; 128 ] ~f:(fun n ->
let list = List.init n ~f:Elt.of_int in
match Container.of_list list with
| `Skip_test -> ()
| `Ok c ->
let sort l = List.sort l ~compare in
let sorts_are_equal l1 l2 = sort l1 = sort l2 in
assert (n = Container.length c);
assert (n = 0 = Container.is_empty c);
assert (
sorts_are_equal list (Container.fold c ~init:[] ~f:(fun ac e -> e :: ac)));
assert (sorts_are_equal list (Container.to_list c));
assert (sorts_are_equal list (Array.to_list (Container.to_array c)));
assert (n > 0 = Option.is_some (Container.find c ~f:(fun e -> Elt.to_int e = 0)));
assert (
n > 0 = Option.is_some (Container.find c ~f:(fun e -> Elt.to_int e = n - 1)));
assert (Option.is_none (Container.find c ~f:(fun e -> Elt.to_int e = n)));
assert (n > 0 = Container.mem c (Elt.of_int 0) ~equal:( = ));
if n > 0 then assert (Container.mem c (Elt.of_int (n - 1)) ~equal:( = ));
assert (not (Container.mem c (Elt.of_int n) ~equal:( = )));
assert (
n
> 0
= Option.is_some
(Container.find_map c ~f:(fun e ->
if Elt.to_int e = 0 then Some () else None)));
assert (
n
> 0
= Option.is_some
(Container.find_map c ~f:(fun e ->
if Elt.to_int e = n - 1 then Some () else None)));
assert (
Option.is_none
(Container.find_map c ~f:(fun e ->
if Elt.to_int e = n then Some () else None)));
let r = ref 0 in
Container.iter c ~f:(fun e -> r := !r + Elt.to_int e);
assert (!r = List.fold list ~init:0 ~f:(fun n e -> n + Elt.to_int e));
assert (!r = sum (module Int) c ~f:Elt.to_int);
let c2 = [%of_sexp: int Container.t] ([%sexp_of: int Container.t] c) in
assert (sorts_are_equal list (Container.to_list c2));
let compare_elt a b = Int.compare (Elt.to_int a) (Elt.to_int b) in
if n = 0
then (
assert (!r = 0);
assert (min_elt ~compare:compare_elt c = None);
assert (max_elt ~compare:compare_elt c = None))
else (
assert (!r = n * (n - 1) / 2);
assert (Option.map ~f:Elt.to_int (min_elt ~compare:compare_elt c) = Some 0);
assert (
Option.map ~f:Elt.to_int (max_elt ~compare:compare_elt c)
= Some (Int.pred n)));
let mid = Container.length c / 2 in
(match
Container.fold_result c ~init:0 ~f:(fun count _elt ->
if count = mid then Error count else Ok (count + 1))
with
| Ok 0 -> assert (Container.length c = 0)
| Ok _ -> failwith "Expected fold to stop early"
| Error x -> assert (mid = x)))
;;
let min_elt = min_elt
let max_elt = max_elt
let count = count
let sum = sum
let exists = exists
let for_all = for_all
let%test_unit _ =
List.iter
[ []
; [ true ]
; [ false ]
; [ false; false ]
; [ true; false ]
; [ false; true ]
; [ true; true ]
]
~f:(fun bools ->
let count_should_be =
List.fold bools ~init:0 ~f:(fun n b -> if b then n + 1 else n)
in
let forall_should_be = List.fold bools ~init:true ~f:(fun ac b -> b && ac) in
let exists_should_be = List.fold bools ~init:false ~f:(fun ac b -> b || ac) in
match
Container.of_list (List.map bools ~f:(fun b -> Elt.of_int (if b then 1 else 0)))
with
| `Skip_test -> ()
| `Ok container ->
let is_one e = Elt.to_int e = 1 in
let ( = ) = Poly.equal in
assert (forall_should_be = Container.for_all container ~f:is_one);
assert (exists_should_be = Container.exists container ~f:is_one);
assert (count_should_be = Container.count container ~f:is_one))
;;
end
module Test_S1_allow_skipping_tests (Container : sig
type 'a t [@@deriving sexp]
include Container.S1 with type 'a t := 'a t
val of_list : 'a list -> [ `Ok of 'a t | `Skip_test ]
end) =
struct
include
Test_generic
(struct
type 'a t = 'a
let of_int = Fn.id
let to_int = Fn.id
end)
(Container)
end
module Test_S1 (Container : sig
type 'a t [@@deriving sexp]
include Container.S1 with type 'a t := 'a t
val of_list : 'a list -> 'a t
end) =
Test_S1_allow_skipping_tests (struct
include Container
let of_list l = `Ok (of_list l)
end)
module Test_S0 (Container : sig
module Elt : sig
type t [@@deriving sexp]
val of_int : int -> t
val to_int : t -> int
end
type t [@@deriving sexp]
include Container.S0 with type t := t and type elt := Elt.t
val of_list : Elt.t list -> t
end) =
struct
include
Test_generic
(struct
include Container.Elt
type 'a t = Container.Elt.t
end)
(struct
include Container
type 'a t = Container.t [@@deriving sexp]
let of_list l = `Ok (of_list l)
let mem t x ~equal:_ = Container.mem t x
end)
[ mem ] in the second functor argument above ignores its [ ~equal ] , so this [ ~equal ]
should never be called .
should never be called. *)
let mem t x = mem t x ~equal:(fun _ _ -> assert false)
end
|
d12393d67b49d823b0a2cf129b60509dce589ca4f27af3891aa5c444fadd6fe3 | racket/games | gen-tiles.rkt |
(module gen-tiles racket
(require racket/gui
racket/math)
(module test racket/base)
(define SIZE 24)
(define bm (make-object bitmap% SIZE SIZE))
(define dc (make-object bitmap-dc% bm))
(define dir (build-path (collection-path "games" "mines")
"images"))
;; Bomb ----------------------------------------
(define (draw-bomb color fuse?)
(send dc set-smoothing 'smoothed)
(send dc set-pen (make-object pen% color 1 'solid))
(send dc set-brush (make-object brush% color 'solid))
(send dc draw-ellipse 5 7 14 14)
(when fuse?
(send dc set-pen (make-object pen% (make-object color% 100 100 100) 1 'solid))
(send dc set-brush (make-object brush% "BLACK" 'transparent))
(send dc draw-arc 12 2 24 14 (* 2/3 pi) pi)))
(send dc clear)
(draw-bomb "BLACK" #t)
(send dc set-pen (make-object pen% "RED" 1 'solid))
(send dc set-smoothing 'aligned)
(send dc draw-line 14 0 16 2)
(send dc draw-line 18 4 20 6)
(send dc draw-line 18 2 20 0)
(send bm save-file (build-path dir "bomb.png") 'png)
(let ([path (make-object dc-path%)])
(send path move-to 4 0)
(send path line-to 12 4)
(send path line-to 22 0)
(send path line-to 20 12)
(send path line-to 24 20)
(send path line-to 20 20)
(send path line-to 20 24)
(send path line-to 12 20)
(send path line-to 0 24)
(send path line-to 4 18)
(send path line-to 0 10)
(send path line-to 6 6)
(send path close)
(send path translate -12 -12)
(send dc clear)
(send dc set-pen (make-object pen% "RED" 1 'solid))
(send dc set-brush (make-object brush% "RED" 'solid))
(send dc draw-path path 12 12)
(send path scale 2/3 2/3)
(send dc set-pen (make-object pen% "ORANGE" 1 'solid))
(send dc set-brush (make-object brush% "ORANGE" 'solid))
(send dc draw-path path 12 12)
(send path scale 1/2 1/2)
(send dc set-pen (make-object pen% "YELLOW" 1 'solid))
(send dc set-brush (make-object brush% "YELLOW" 'solid))
(send dc draw-path path 12 12)
(void))
(send bm save-file (build-path dir "explode.png") 'png)
;; Tiles ----------------------------------------
(define bg (make-object bitmap% (build-path dir "bg.png")))
(define (lighter n q)
(- 255 (floor (* (if (zero? q) 3/4 4/5) (- 255 n)))))
(define (darker n q)
(floor (* (if (zero? q) 1/2 4/5) n)))
(send dc draw-bitmap bg 0 0)
(let ([c (make-object color%)])
(let loop ([q 0])
(unless (= q 2)
(let loop ([i 0])
(unless (= i SIZE)
(let ([adjust
(lambda (adj x y)
(send dc get-pixel x y c)
(send c set
(adj (send c red) q)
(adj (send c green) q)
(adj (send c blue) q))
(send dc set-pixel x y c))])
(when (<= q i (- SIZE q))
(adjust lighter q i)
(unless (zero? i)
(adjust lighter i q))
(adjust darker (- SIZE 1 q) i)
(unless (= i (- SIZE q))
(adjust darker i (- SIZE 1 q)))))
(loop (add1 i))))
(loop (add1 q)))))
(send bm save-file (build-path dir "tile.png") 'png)
(define (bright r g b)
(min
(inexact->exact
(floor
(sqrt (+ (sqr r) (sqr g) (sqr g)))))
255))
(define (xform red green blue)
(let ([c (make-object color%)])
(let loop ([i 0])
(unless (= i SIZE)
(let loop ([j 0])
(unless (= j SIZE)
(send dc get-pixel i j c)
(let ([r (send c red)]
[g (send c green)]
[b (send c blue)])
(send c set
(red r g b)
(green r g b)
(blue r g b))
(send dc set-pixel i j c)
(loop (add1 j)))))
(loop (add1 i))))))
(xform (lambda (r g b) r) (lambda (r g b) g) bright)
(define tile-bm (make-object bitmap% (build-path dir "tile.png")))
(send bm save-file (build-path dir "lclick-tile.png") 'png)
(send dc draw-bitmap tile-bm 0 0)
(xform bright (lambda (r g b) g) (lambda (r g b) b))
(send bm save-file (build-path dir "rclick-tile.png") 'png)
(define (semi-bright r g b)
(floor (- 255 (* 2/3 (- 255 r)))))
(send dc draw-bitmap tile-bm 0 0)
(xform semi-bright semi-bright semi-bright)
(send bm save-file (build-path dir "local-tile.png") 'png)
(define (semi-dim r g b)
(floor (* 4/5 r)))
(send dc draw-bitmap tile-bm 0 0)
(xform semi-dim semi-dim semi-dim)
(send bm save-file (build-path dir "near-tile.png") 'png)
;; Flag -----------------------------------------
(define (draw-flag dc color field?)
(send dc clear)
(send dc set-smoothing 'aligned)
(send dc set-pen (make-object pen% "BLACK" 1 'solid))
(send dc set-brush (make-object brush% "BLACK" 'solid))
(send dc draw-rectangle 5 9 2 12)
(send dc set-pen (make-object pen% color 1 'solid))
(send dc set-brush (make-object brush% color 'solid))
(send dc draw-polygon
(list (make-object point% 5 4)
(make-object point% 19 9)
(make-object point% 5 14)))
(when field?
(send dc draw-rectangle 7 3 12 7)))
(let* ([bm2 (make-object bitmap% SIZE SIZE)]
[dc2 (make-object bitmap-dc% bm2)])
(draw-flag dc2 "BLACK" #f)
(send dc2 set-bitmap #f)
(send bm set-loaded-mask bm2))
(draw-flag dc "RED" #t)
(send bm save-file (build-path dir "flag.png") 'png)
)
| null | https://raw.githubusercontent.com/racket/games/e57376f067be51257ed12cdf3e4509a00ffd533d/mines/gen-tiles.rkt | racket | Bomb ----------------------------------------
Tiles ----------------------------------------
Flag ----------------------------------------- |
(module gen-tiles racket
(require racket/gui
racket/math)
(module test racket/base)
(define SIZE 24)
(define bm (make-object bitmap% SIZE SIZE))
(define dc (make-object bitmap-dc% bm))
(define dir (build-path (collection-path "games" "mines")
"images"))
(define (draw-bomb color fuse?)
(send dc set-smoothing 'smoothed)
(send dc set-pen (make-object pen% color 1 'solid))
(send dc set-brush (make-object brush% color 'solid))
(send dc draw-ellipse 5 7 14 14)
(when fuse?
(send dc set-pen (make-object pen% (make-object color% 100 100 100) 1 'solid))
(send dc set-brush (make-object brush% "BLACK" 'transparent))
(send dc draw-arc 12 2 24 14 (* 2/3 pi) pi)))
(send dc clear)
(draw-bomb "BLACK" #t)
(send dc set-pen (make-object pen% "RED" 1 'solid))
(send dc set-smoothing 'aligned)
(send dc draw-line 14 0 16 2)
(send dc draw-line 18 4 20 6)
(send dc draw-line 18 2 20 0)
(send bm save-file (build-path dir "bomb.png") 'png)
(let ([path (make-object dc-path%)])
(send path move-to 4 0)
(send path line-to 12 4)
(send path line-to 22 0)
(send path line-to 20 12)
(send path line-to 24 20)
(send path line-to 20 20)
(send path line-to 20 24)
(send path line-to 12 20)
(send path line-to 0 24)
(send path line-to 4 18)
(send path line-to 0 10)
(send path line-to 6 6)
(send path close)
(send path translate -12 -12)
(send dc clear)
(send dc set-pen (make-object pen% "RED" 1 'solid))
(send dc set-brush (make-object brush% "RED" 'solid))
(send dc draw-path path 12 12)
(send path scale 2/3 2/3)
(send dc set-pen (make-object pen% "ORANGE" 1 'solid))
(send dc set-brush (make-object brush% "ORANGE" 'solid))
(send dc draw-path path 12 12)
(send path scale 1/2 1/2)
(send dc set-pen (make-object pen% "YELLOW" 1 'solid))
(send dc set-brush (make-object brush% "YELLOW" 'solid))
(send dc draw-path path 12 12)
(void))
(send bm save-file (build-path dir "explode.png") 'png)
(define bg (make-object bitmap% (build-path dir "bg.png")))
(define (lighter n q)
(- 255 (floor (* (if (zero? q) 3/4 4/5) (- 255 n)))))
(define (darker n q)
(floor (* (if (zero? q) 1/2 4/5) n)))
(send dc draw-bitmap bg 0 0)
(let ([c (make-object color%)])
(let loop ([q 0])
(unless (= q 2)
(let loop ([i 0])
(unless (= i SIZE)
(let ([adjust
(lambda (adj x y)
(send dc get-pixel x y c)
(send c set
(adj (send c red) q)
(adj (send c green) q)
(adj (send c blue) q))
(send dc set-pixel x y c))])
(when (<= q i (- SIZE q))
(adjust lighter q i)
(unless (zero? i)
(adjust lighter i q))
(adjust darker (- SIZE 1 q) i)
(unless (= i (- SIZE q))
(adjust darker i (- SIZE 1 q)))))
(loop (add1 i))))
(loop (add1 q)))))
(send bm save-file (build-path dir "tile.png") 'png)
(define (bright r g b)
(min
(inexact->exact
(floor
(sqrt (+ (sqr r) (sqr g) (sqr g)))))
255))
(define (xform red green blue)
(let ([c (make-object color%)])
(let loop ([i 0])
(unless (= i SIZE)
(let loop ([j 0])
(unless (= j SIZE)
(send dc get-pixel i j c)
(let ([r (send c red)]
[g (send c green)]
[b (send c blue)])
(send c set
(red r g b)
(green r g b)
(blue r g b))
(send dc set-pixel i j c)
(loop (add1 j)))))
(loop (add1 i))))))
(xform (lambda (r g b) r) (lambda (r g b) g) bright)
(define tile-bm (make-object bitmap% (build-path dir "tile.png")))
(send bm save-file (build-path dir "lclick-tile.png") 'png)
(send dc draw-bitmap tile-bm 0 0)
(xform bright (lambda (r g b) g) (lambda (r g b) b))
(send bm save-file (build-path dir "rclick-tile.png") 'png)
(define (semi-bright r g b)
(floor (- 255 (* 2/3 (- 255 r)))))
(send dc draw-bitmap tile-bm 0 0)
(xform semi-bright semi-bright semi-bright)
(send bm save-file (build-path dir "local-tile.png") 'png)
(define (semi-dim r g b)
(floor (* 4/5 r)))
(send dc draw-bitmap tile-bm 0 0)
(xform semi-dim semi-dim semi-dim)
(send bm save-file (build-path dir "near-tile.png") 'png)
(define (draw-flag dc color field?)
(send dc clear)
(send dc set-smoothing 'aligned)
(send dc set-pen (make-object pen% "BLACK" 1 'solid))
(send dc set-brush (make-object brush% "BLACK" 'solid))
(send dc draw-rectangle 5 9 2 12)
(send dc set-pen (make-object pen% color 1 'solid))
(send dc set-brush (make-object brush% color 'solid))
(send dc draw-polygon
(list (make-object point% 5 4)
(make-object point% 19 9)
(make-object point% 5 14)))
(when field?
(send dc draw-rectangle 7 3 12 7)))
(let* ([bm2 (make-object bitmap% SIZE SIZE)]
[dc2 (make-object bitmap-dc% bm2)])
(draw-flag dc2 "BLACK" #f)
(send dc2 set-bitmap #f)
(send bm set-loaded-mask bm2))
(draw-flag dc "RED" #t)
(send bm save-file (build-path dir "flag.png") 'png)
)
|
1fe35f039418269834ef1c199c60136f57fbcb43464bf3338e5201980ed82899 | CompSciCabal/SMRTYPRTY | trees.rkt | #lang racket
(provide (all-defined-out))
(require "sets-lists-fn.rkt")
;; This module provides the functions which will convert a list of vertices
;; and a list of edges into the data type which the graph algorithm
;; operates on. The code is not very pretty :(
I did not adhere to the 79 character line limit .
(define (other-vertex vertex edge)
(cond
[(equal? vertex (first edge)) (second edge)]
[else (first edge)]))
(define (already-in-tree? vertex tree)
(cond
[(empty? tree) #f]
[(equal? vertex (first (first tree))) #t]
[else (already-in-tree? vertex (rest tree))]))
this order ( I hope )
(define (add-to-tree neighbor tree)
(define first-tree (first tree))
(define rest-tree (rest tree))
(define first-first-tree (first first-tree))
(define rest-first-tree (second first-tree))
;; the reconstructed tree:
(cons (list first-first-tree (cons neighbor rest-first-tree)) rest-tree))
(define (find-neighbours vertex tree)
(cond
[(empty? tree) null]
[(equal? vertex (first (first tree))) (second (first tree))]
[else (find-neighbours vertex (rest tree))]))
(define (tree-maker vertices edges)
(make-tree vertices edges edges null))
;; This needs to be re-factored ...
(define (make-tree vertices edges static-edges tree)
(cond
[(empty? vertices) tree]
;; non-empty vertices, but out of edges, but tree is empty
[(and (empty? tree) (empty? edges))
(make-tree (rest vertices) static-edges static-edges (list (list (first vertices) null)))]
;; non-empty vertices, out of edges, but you are already in the tree!
[(and (and (not (empty? tree)) (empty? edges)) (already-in-tree? (first vertices) tree))
(make-tree (rest vertices) static-edges static-edges tree)]
;; non-empty vertices, out of edges, but the tree is not empty
[(and (and (not (empty? tree)) (empty? edges)) (not (already-in-tree? (first vertices) tree)))
(make-tree (rest vertices) static-edges static-edges (cons (list (first vertices) null) tree))]
;; non-empty vertices, has edges, but not a member
[(and (and (not (empty? vertices)) (not (empty? edges))) (not (member? (first vertices) (first edges))))
(make-tree vertices (rest edges) static-edges tree)]
now , we go through vertices ( and edges is non - empty ) ( and we are operating on ( first vertices ) )
;; it's a member! so we add it to its edge set ... but the tree is currently empty
[(and (empty? tree) (member? (first vertices) (first edges)))
(make-tree vertices (rest edges) static-edges (cons (list (first vertices) (list (other-vertex (first vertices) (first edges)))) tree))]
;; it's a member! but the tree is *not* empty ... but is it already in the *ordered* tree?
[(and (member? (first vertices) (first edges)) (already-in-tree? (first vertices) tree))
(make-tree vertices (rest edges) static-edges (add-to-tree (other-vertex (first vertices) (first edges)) tree))]
;; it's a member, but it's not already in the tree!
[(member? (first vertices) (first edges))
(make-tree vertices (rest edges) static-edges (cons (list (first vertices) (list (other-vertex (first vertices) (first edges)))) tree))]))
;; Tests
;;(equal? (make-tree '(a b) (list '(a b)) (list '(a b)) null) (list (list 'a '(b)) (list 'b '(a))))
;;(equal? (add-to-tree 'b (list (list 'a '(c g)))) (list (list 'a '(b c g))))
;;(equal? (add-to-tree 'b (list (list 'a '(c g)) (list 'z '(c o)))) (list (list 'a '(b c g)) (list 'z '(c o))))
;;(equal? (add-to-tree 'b (list (list 'a '(c g)) (list 'z '(c o)) (list 'p '(w q))))
;; (list (list 'a '(b c g)) (list 'z '(c o)) (list 'p '(w q))))
;;(equal? (make-tree '(a b c) null null null) '((c ()) (b ()) (a ())))
;;(equal? (make-tree '(a b c) (list '(a b) '(b c) '(c a)) (list '(a b) '(b c) '(c a)) null) '((c (a b)) (b (c a)) (a (c b))))
| null | https://raw.githubusercontent.com/CompSciCabal/SMRTYPRTY/4a5550789c997c20fb7256b81469de1f1fce3514/experiments/ynasser/bipartite/trees.rkt | racket | This module provides the functions which will convert a list of vertices
and a list of edges into the data type which the graph algorithm
operates on. The code is not very pretty :(
the reconstructed tree:
This needs to be re-factored ...
non-empty vertices, but out of edges, but tree is empty
non-empty vertices, out of edges, but you are already in the tree!
non-empty vertices, out of edges, but the tree is not empty
non-empty vertices, has edges, but not a member
it's a member! so we add it to its edge set ... but the tree is currently empty
it's a member! but the tree is *not* empty ... but is it already in the *ordered* tree?
it's a member, but it's not already in the tree!
Tests
(equal? (make-tree '(a b) (list '(a b)) (list '(a b)) null) (list (list 'a '(b)) (list 'b '(a))))
(equal? (add-to-tree 'b (list (list 'a '(c g)))) (list (list 'a '(b c g))))
(equal? (add-to-tree 'b (list (list 'a '(c g)) (list 'z '(c o)))) (list (list 'a '(b c g)) (list 'z '(c o))))
(equal? (add-to-tree 'b (list (list 'a '(c g)) (list 'z '(c o)) (list 'p '(w q))))
(list (list 'a '(b c g)) (list 'z '(c o)) (list 'p '(w q))))
(equal? (make-tree '(a b c) null null null) '((c ()) (b ()) (a ())))
(equal? (make-tree '(a b c) (list '(a b) '(b c) '(c a)) (list '(a b) '(b c) '(c a)) null) '((c (a b)) (b (c a)) (a (c b)))) | #lang racket
(provide (all-defined-out))
(require "sets-lists-fn.rkt")
I did not adhere to the 79 character line limit .
(define (other-vertex vertex edge)
(cond
[(equal? vertex (first edge)) (second edge)]
[else (first edge)]))
(define (already-in-tree? vertex tree)
(cond
[(empty? tree) #f]
[(equal? vertex (first (first tree))) #t]
[else (already-in-tree? vertex (rest tree))]))
this order ( I hope )
(define (add-to-tree neighbor tree)
(define first-tree (first tree))
(define rest-tree (rest tree))
(define first-first-tree (first first-tree))
(define rest-first-tree (second first-tree))
(cons (list first-first-tree (cons neighbor rest-first-tree)) rest-tree))
(define (find-neighbours vertex tree)
(cond
[(empty? tree) null]
[(equal? vertex (first (first tree))) (second (first tree))]
[else (find-neighbours vertex (rest tree))]))
(define (tree-maker vertices edges)
(make-tree vertices edges edges null))
(define (make-tree vertices edges static-edges tree)
(cond
[(empty? vertices) tree]
[(and (empty? tree) (empty? edges))
(make-tree (rest vertices) static-edges static-edges (list (list (first vertices) null)))]
[(and (and (not (empty? tree)) (empty? edges)) (already-in-tree? (first vertices) tree))
(make-tree (rest vertices) static-edges static-edges tree)]
[(and (and (not (empty? tree)) (empty? edges)) (not (already-in-tree? (first vertices) tree)))
(make-tree (rest vertices) static-edges static-edges (cons (list (first vertices) null) tree))]
[(and (and (not (empty? vertices)) (not (empty? edges))) (not (member? (first vertices) (first edges))))
(make-tree vertices (rest edges) static-edges tree)]
now , we go through vertices ( and edges is non - empty ) ( and we are operating on ( first vertices ) )
[(and (empty? tree) (member? (first vertices) (first edges)))
(make-tree vertices (rest edges) static-edges (cons (list (first vertices) (list (other-vertex (first vertices) (first edges)))) tree))]
[(and (member? (first vertices) (first edges)) (already-in-tree? (first vertices) tree))
(make-tree vertices (rest edges) static-edges (add-to-tree (other-vertex (first vertices) (first edges)) tree))]
[(member? (first vertices) (first edges))
(make-tree vertices (rest edges) static-edges (cons (list (first vertices) (list (other-vertex (first vertices) (first edges)))) tree))]))
|
61a6f8687bb465cc39973eee54738a772f8863281f1a5ec25515e7f0a96b3f92 | silky/myth | rope.ml | open Core
type 'a t =
| Concat of 'a t * 'a t
| OfList of 'a list
let rec map (r : 'a t) ~f : 'b t =
match r with
| Concat(lr, rr) ->
let ml = map lr f in
let mr = map rr f in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> OfList (List.map l ~f)
let rec iter (r : 'a t) ~f : unit =
match r with
| Concat(lr, rr) -> iter lr f; iter rr f
| OfList l -> List.iter l ~f
let rec to_list (r : 'a t) : 'a list =
match r with
| Concat(lr, rr) -> (to_list lr) @ (to_list rr)
| OfList l -> l
(* TODO: Factor these implementations to share common code *)
let rec concat_map (r : 'a t) ~f : 'b t =
match r with
| Concat(lr, rr) ->
let ml = concat_map ~f lr in
let mr = concat_map ~f rr in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> List.fold_left ~f:(fun acc x -> Concat((f x), acc)) ~init:(OfList []) l
let rec filter (r : 'a t) ~f : 'b t =
match r with
| Concat(lr, rr) ->
let ml = filter ~f lr in
let mr = filter ~f rr in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> OfList (List.filter ~f l)
let rec filter_map (r : 'a t) ~f : 'b t =
match r with
| Concat(lr, rr) ->
let ml = filter_map ~f lr in
let mr = filter_map ~f rr in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> OfList (List.filter_map ~f l)
let rec dedup (r:'a t) ~compare:(cc:'a -> 'a -> int) : 'a t =
match r with
| Concat (lr, rr) ->
let ml = dedup ~compare:cc lr in
let mr = dedup ~compare:cc rr in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> OfList (List.dedup_and_sort ~compare:cc l)
let rec cons x r =
match r with
| Concat(rr, rl) -> Concat(cons x rr, rl)
| OfList l -> OfList(x::l)
let empty = OfList []
let of_list l = OfList l
let concat r1 r2 = Concat(r1, r2)
let rec length r =
match r with
| Concat(lr, rr) -> (length lr) + (length rr)
| OfList l -> List.length l
let rec is_empty r =
match r with
| Concat(lr, rr) -> (is_empty lr) && (is_empty rr)
| OfList [] -> true
| OfList _ -> false
Morally :
Given a list of lists , [ [ x1;x2;x3];[y1;y2;y3; ... ]; ... ;[z1;z2;z3 ] ]
form all possible combinations by drawing one element from each list .
[ [ x1;y1; ... ;z1];[x1;y1; ... ;z2]; ... ;[x3;ym; ... ;z3 ] ]
The length of the resulting list is the product of the lengths of the
input lists .
Given a list of lists, [[x1;x2;x3];[y1;y2;y3;...];...;[z1;z2;z3]]
form all possible combinations by drawing one element from each list.
[[x1;y1;...;z1];[x1;y1;...;z2];...;[x3;ym;...;z3]]
The length of the resulting list is the product of the lengths of the
input lists.
*)
let cartesian_product (ls:'a t list) : 'a list t =
let ll = List.map ~f:to_list ls in
let rec list_cartesian_product (ls : 'a list list) : 'a list list =
begin match ls with
| [] -> [[]]
| xs::rest ->
let r = list_cartesian_product rest in
List.concat_map ~f:(fun x -> List.map ~f:(fun l -> (x::l)) r) xs
end
in
of_list (list_cartesian_product ll)
The following slowed down the cartesian product !
if ls = [ ] then [ [ ] ]
else
let rec to_lists ls acc =
begin match ls with
| [ ] - > Some acc
| r::rest - >
let lr = to_list r in
if lr = [ ] then None
else to_lists rest ( )
end
in
match to_lists ls [ ] with
| None - > Empty
| Some ll - >
let rec list_cartesian_product ( ls : ' a list list ) : ' a list list =
begin match ls with
| [ ] - > [ [ ] ]
| xs::rest - >
let r = list_cartesian_product rest in
List.concat_map ~f:(fun x - > List.map ~f:(fun l - > ( x::l ) ) r ) xs
end
in
of_list ( list_cartesian_product ll )
The following slowed down the cartesian product!
if ls = [] then OfList [[]]
else
let rec to_lists ls acc =
begin match ls with
| [] -> Some acc
| r::rest ->
let lr = to_list r in
if lr = [] then None
else to_lists rest (lr::acc)
end
in
match to_lists ls [] with
| None -> Empty
| Some ll ->
let rec list_cartesian_product (ls : 'a list list) : 'a list list =
begin match ls with
| [] -> [[]]
| xs::rest ->
let r = list_cartesian_product rest in
List.concat_map ~f:(fun x -> List.map ~f:(fun l -> (x::l)) r) xs
end
in
of_list (list_cartesian_product ll)
*)
| null | https://raw.githubusercontent.com/silky/myth/b631edefb2a27a1d731daa6654517d91ca660b95/src/rope.ml | ocaml | TODO: Factor these implementations to share common code | open Core
type 'a t =
| Concat of 'a t * 'a t
| OfList of 'a list
let rec map (r : 'a t) ~f : 'b t =
match r with
| Concat(lr, rr) ->
let ml = map lr f in
let mr = map rr f in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> OfList (List.map l ~f)
let rec iter (r : 'a t) ~f : unit =
match r with
| Concat(lr, rr) -> iter lr f; iter rr f
| OfList l -> List.iter l ~f
let rec to_list (r : 'a t) : 'a list =
match r with
| Concat(lr, rr) -> (to_list lr) @ (to_list rr)
| OfList l -> l
let rec concat_map (r : 'a t) ~f : 'b t =
match r with
| Concat(lr, rr) ->
let ml = concat_map ~f lr in
let mr = concat_map ~f rr in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> List.fold_left ~f:(fun acc x -> Concat((f x), acc)) ~init:(OfList []) l
let rec filter (r : 'a t) ~f : 'b t =
match r with
| Concat(lr, rr) ->
let ml = filter ~f lr in
let mr = filter ~f rr in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> OfList (List.filter ~f l)
let rec filter_map (r : 'a t) ~f : 'b t =
match r with
| Concat(lr, rr) ->
let ml = filter_map ~f lr in
let mr = filter_map ~f rr in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> OfList (List.filter_map ~f l)
let rec dedup (r:'a t) ~compare:(cc:'a -> 'a -> int) : 'a t =
match r with
| Concat (lr, rr) ->
let ml = dedup ~compare:cc lr in
let mr = dedup ~compare:cc rr in
begin match (ml, mr) with
| OfList [], OfList [] -> OfList []
| OfList [], _ -> mr
| _, OfList [] -> ml
| _, _ -> Concat(ml, mr)
end
| OfList l -> OfList (List.dedup_and_sort ~compare:cc l)
let rec cons x r =
match r with
| Concat(rr, rl) -> Concat(cons x rr, rl)
| OfList l -> OfList(x::l)
let empty = OfList []
let of_list l = OfList l
let concat r1 r2 = Concat(r1, r2)
let rec length r =
match r with
| Concat(lr, rr) -> (length lr) + (length rr)
| OfList l -> List.length l
let rec is_empty r =
match r with
| Concat(lr, rr) -> (is_empty lr) && (is_empty rr)
| OfList [] -> true
| OfList _ -> false
Morally :
Given a list of lists , [ [ x1;x2;x3];[y1;y2;y3; ... ]; ... ;[z1;z2;z3 ] ]
form all possible combinations by drawing one element from each list .
[ [ x1;y1; ... ;z1];[x1;y1; ... ;z2]; ... ;[x3;ym; ... ;z3 ] ]
The length of the resulting list is the product of the lengths of the
input lists .
Given a list of lists, [[x1;x2;x3];[y1;y2;y3;...];...;[z1;z2;z3]]
form all possible combinations by drawing one element from each list.
[[x1;y1;...;z1];[x1;y1;...;z2];...;[x3;ym;...;z3]]
The length of the resulting list is the product of the lengths of the
input lists.
*)
let cartesian_product (ls:'a t list) : 'a list t =
let ll = List.map ~f:to_list ls in
let rec list_cartesian_product (ls : 'a list list) : 'a list list =
begin match ls with
| [] -> [[]]
| xs::rest ->
let r = list_cartesian_product rest in
List.concat_map ~f:(fun x -> List.map ~f:(fun l -> (x::l)) r) xs
end
in
of_list (list_cartesian_product ll)
The following slowed down the cartesian product !
if ls = [ ] then [ [ ] ]
else
let rec to_lists ls acc =
begin match ls with
| [ ] - > Some acc
| r::rest - >
let lr = to_list r in
if lr = [ ] then None
else to_lists rest ( )
end
in
match to_lists ls [ ] with
| None - > Empty
| Some ll - >
let rec list_cartesian_product ( ls : ' a list list ) : ' a list list =
begin match ls with
| [ ] - > [ [ ] ]
| xs::rest - >
let r = list_cartesian_product rest in
List.concat_map ~f:(fun x - > List.map ~f:(fun l - > ( x::l ) ) r ) xs
end
in
of_list ( list_cartesian_product ll )
The following slowed down the cartesian product!
if ls = [] then OfList [[]]
else
let rec to_lists ls acc =
begin match ls with
| [] -> Some acc
| r::rest ->
let lr = to_list r in
if lr = [] then None
else to_lists rest (lr::acc)
end
in
match to_lists ls [] with
| None -> Empty
| Some ll ->
let rec list_cartesian_product (ls : 'a list list) : 'a list list =
begin match ls with
| [] -> [[]]
| xs::rest ->
let r = list_cartesian_product rest in
List.concat_map ~f:(fun x -> List.map ~f:(fun l -> (x::l)) r) xs
end
in
of_list (list_cartesian_product ll)
*)
|
0bbdab313830adf43da2789cf323e08a6070c46f36d2f277ed309dbd0b0b805b | input-output-hk/plutus-apps | Chain.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeOperators #-}
module Cardano.Node.Emulator.Chain where
import Cardano.Api qualified as C
import Cardano.Node.Emulator.Params (Params (..))
import Cardano.Node.Emulator.Validation qualified as Validation
import Control.Lens hiding (index)
import Control.Monad.Freer
import Control.Monad.Freer.Extras.Log (LogMsg, logDebug, logInfo, logWarn)
import Control.Monad.Freer.State (State, gets, modify)
import Control.Monad.State qualified as S
import Data.Aeson (FromJSON, ToJSON)
import Data.Either (fromRight)
import Data.Foldable (traverse_)
import Data.List ((\\))
import Data.Map qualified as Map
import Data.Maybe (mapMaybe)
import Data.Monoid (Ap (Ap))
import Data.Text (Text)
import Data.Traversable (for)
import GHC.Generics (Generic)
import Ledger (Block, Blockchain, CardanoTx (..), OnChainTx (..), Slot (..), TxId, TxIn (txInRef),
getCardanoTxCollateralInputs, getCardanoTxFee, getCardanoTxId, getCardanoTxTotalCollateral,
getCardanoTxValidityRange, txOutValue, unOnChain)
import Ledger.Index qualified as Index
import Ledger.Interval qualified as Interval
import Ledger.Tx.CardanoAPI (fromPlutusIndex)
import Ledger.Value.CardanoAPI (lovelaceToValue)
import Plutus.V1.Ledger.Scripts qualified as Scripts
import Prettyprinter
-- | Events produced by the blockchain emulator.
data ChainEvent =
TxnValidate TxId CardanoTx [Text]
-- ^ A transaction has been validated and added to the blockchain.
| TxnValidationFail Index.ValidationPhase TxId CardanoTx Index.ValidationError C.Value [Text]
-- ^ A transaction failed to validate. The @Value@ indicates the amount of collateral stored in the transaction.
| SlotAdd Slot
deriving stock (Eq, Show, Generic)
deriving anyclass (FromJSON, ToJSON)
instance Pretty ChainEvent where
pretty = \case
TxnValidate i _ logs -> "TxnValidate" <+> pretty i <+> pretty logs
TxnValidationFail p i _ e _ logs -> "TxnValidationFail" <+> pretty p <+> pretty i <> colon <+> pretty e <+> pretty logs
SlotAdd sl -> "SlotAdd" <+> pretty sl
-- | A pool of transactions which have yet to be validated.
type TxPool = [CardanoTx]
data ChainState = ChainState {
^ The current chain , with the newest transactions first in the list .
_txPool :: TxPool, -- ^ The pool of pending transactions.
^ The index , used for validation .
_chainCurrentSlot :: Slot -- ^ The current slot number
} deriving (Show, Generic)
emptyChainState :: ChainState
emptyChainState = ChainState [] [] mempty 0
makeLenses ''ChainState
data ChainControlEffect r where
ProcessBlock :: ChainControlEffect Block
ModifySlot :: (Slot -> Slot) -> ChainControlEffect Slot
data ChainEffect r where
QueueTx :: CardanoTx -> ChainEffect ()
GetCurrentSlot :: ChainEffect Slot
GetParams :: ChainEffect Params
-- | Make a new block
processBlock :: Member ChainControlEffect effs => Eff effs Block
processBlock = send ProcessBlock
-- | Adjust the current slot number, returning the new slot.
modifySlot :: Member ChainControlEffect effs => (Slot -> Slot) -> Eff effs Slot
modifySlot = send . ModifySlot
queueTx :: Member ChainEffect effs => CardanoTx -> Eff effs ()
queueTx tx = send (QueueTx tx)
getParams :: Member ChainEffect effs => Eff effs Params
getParams = send GetParams
getCurrentSlot :: Member ChainEffect effs => Eff effs Slot
getCurrentSlot = send GetCurrentSlot
type ChainEffs = '[State ChainState, LogMsg ChainEvent]
handleControlChain :: Members ChainEffs effs => Params -> ChainControlEffect ~> Eff effs
handleControlChain params = \case
ProcessBlock -> do
pool <- gets $ view txPool
slot <- gets $ view chainCurrentSlot
idx <- gets $ view index
let ValidatedBlock block events idx' =
validateBlock params slot idx pool
modify $ txPool .~ []
modify $ index .~ idx'
modify $ addBlock block
traverse_ logEvent events
pure block
ModifySlot f -> modify @ChainState (over chainCurrentSlot f) >> gets (view chainCurrentSlot)
logEvent :: Member (LogMsg ChainEvent) effs => ChainEvent -> Eff effs ()
logEvent e = case e of
SlotAdd{} -> logDebug e
TxnValidationFail{} -> logWarn e
TxnValidate{} -> logInfo e
handleChain :: (Members ChainEffs effs) => Params -> ChainEffect ~> Eff effs
handleChain params = \case
QueueTx tx -> modify $ over txPool (addTxToPool tx)
GetCurrentSlot -> gets _chainCurrentSlot
GetParams -> pure params
-- | The result of validating a block.
data ValidatedBlock = ValidatedBlock
{ vlbValid :: Block
-- ^ The transactions that have been validated in this block.
, vlbEvents :: [ChainEvent]
-- ^ Transaction validation events for the transactions in this block.
, vlbIndex :: Index.UtxoIndex
^ The updated UTxO index after processing the block
}
data ValidationCtx = ValidationCtx { vctxIndex :: Index.UtxoIndex, vctxParams :: Params }
| Validate a block given the current slot and UTxO index , returning the valid
transactions , success / failure events and the updated set .
validateBlock :: Params -> Slot -> Index.UtxoIndex -> TxPool -> ValidatedBlock
validateBlock params slot@(Slot s) idx txns =
let
Validate transactions , updating the UTXO index each time
(processed, ValidationCtx idx' _) =
flip S.runState (ValidationCtx idx params) $ for txns $ \tx -> do
result <- validateEm slot tx
pure (tx, result)
-- The new block contains all transaction that were validated
-- successfully
block = mapMaybe toOnChain processed
where
toOnChain (_ , Left (Index.Phase1, _)) = Nothing
toOnChain (tx, Left (Index.Phase2, _)) = Just (Invalid tx)
toOnChain (tx, Right _ ) = Just (Valid tx)
Also return an ` EmulatorEvent ` for each transaction that was
-- processed
nextSlot = Slot (s + 1)
events = (uncurry (mkValidationEvent idx) <$> processed) ++ [SlotAdd nextSlot]
in ValidatedBlock block events idx'
getCollateral :: Index.UtxoIndex -> CardanoTx -> C.Value
getCollateral idx tx = case getCardanoTxTotalCollateral tx of
Just v -> lovelaceToValue v
Nothing -> fromRight (lovelaceToValue $ getCardanoTxFee tx) $
alaf Ap foldMap (fmap txOutValue . (`Index.lookup` idx) . txInRef) (getCardanoTxCollateralInputs tx)
-- | Check whether the given transaction can be validated in the given slot.
canValidateNow :: Slot -> CardanoTx -> Bool
canValidateNow slot = Interval.member slot . getCardanoTxValidityRange
mkValidationEvent :: Index.UtxoIndex -> CardanoTx -> Either Index.ValidationErrorInPhase Index.ValidationSuccess -> ChainEvent
mkValidationEvent idx t result =
case result of
Right r -> TxnValidate (getCardanoTxId t) t logs
where logs = concatMap (fst . snd) $ Map.toList r
Left (phase, err) -> TxnValidationFail phase (getCardanoTxId t) t err (getCollateral idx t) logs
where
logs = case err of
Index.ScriptFailure (Scripts.EvaluationError msgs _) -> msgs
_ -> []
-- | Validate a transaction in the current emulator state.
validateEm
:: S.MonadState ValidationCtx m
=> Slot
-> CardanoTx
-> m (Either Index.ValidationErrorInPhase Index.ValidationSuccess)
validateEm h txn = do
ctx@(ValidationCtx idx params) <- S.get
let
cUtxoIndex = either (error . show) id $ fromPlutusIndex idx
e = Validation.validateCardanoTx params h cUtxoIndex txn
idx' = case e of
Left (Index.Phase1, _) -> idx
Left (Index.Phase2, _) -> Index.insertCollateral txn idx
Right _ -> Index.insert txn idx
_ <- S.put ctx{ vctxIndex = idx' }
pure e
| Adds a block to ChainState , without validation .
addBlock :: Block -> ChainState -> ChainState
addBlock blk st =
st & chainNewestFirst %~ (blk :)
-- The block update may contain txs that are not in this client's
` txPool ` which will get ignored
& txPool %~ (\\ map unOnChain blk)
addTxToPool :: CardanoTx -> TxPool -> TxPool
addTxToPool = (:)
makePrisms ''ChainEvent
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/e8688b8f86a92b285e7d93eb418ccc314ad41bf9/cardano-node-emulator/src/Cardano/Node/Emulator/Chain.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RankNTypes #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators #
| Events produced by the blockchain emulator.
^ A transaction has been validated and added to the blockchain.
^ A transaction failed to validate. The @Value@ indicates the amount of collateral stored in the transaction.
| A pool of transactions which have yet to be validated.
^ The pool of pending transactions.
^ The current slot number
| Make a new block
| Adjust the current slot number, returning the new slot.
| The result of validating a block.
^ The transactions that have been validated in this block.
^ Transaction validation events for the transactions in this block.
The new block contains all transaction that were validated
successfully
processed
| Check whether the given transaction can be validated in the given slot.
| Validate a transaction in the current emulator state.
The block update may contain txs that are not in this client's | # LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
module Cardano.Node.Emulator.Chain where
import Cardano.Api qualified as C
import Cardano.Node.Emulator.Params (Params (..))
import Cardano.Node.Emulator.Validation qualified as Validation
import Control.Lens hiding (index)
import Control.Monad.Freer
import Control.Monad.Freer.Extras.Log (LogMsg, logDebug, logInfo, logWarn)
import Control.Monad.Freer.State (State, gets, modify)
import Control.Monad.State qualified as S
import Data.Aeson (FromJSON, ToJSON)
import Data.Either (fromRight)
import Data.Foldable (traverse_)
import Data.List ((\\))
import Data.Map qualified as Map
import Data.Maybe (mapMaybe)
import Data.Monoid (Ap (Ap))
import Data.Text (Text)
import Data.Traversable (for)
import GHC.Generics (Generic)
import Ledger (Block, Blockchain, CardanoTx (..), OnChainTx (..), Slot (..), TxId, TxIn (txInRef),
getCardanoTxCollateralInputs, getCardanoTxFee, getCardanoTxId, getCardanoTxTotalCollateral,
getCardanoTxValidityRange, txOutValue, unOnChain)
import Ledger.Index qualified as Index
import Ledger.Interval qualified as Interval
import Ledger.Tx.CardanoAPI (fromPlutusIndex)
import Ledger.Value.CardanoAPI (lovelaceToValue)
import Plutus.V1.Ledger.Scripts qualified as Scripts
import Prettyprinter
data ChainEvent =
TxnValidate TxId CardanoTx [Text]
| TxnValidationFail Index.ValidationPhase TxId CardanoTx Index.ValidationError C.Value [Text]
| SlotAdd Slot
deriving stock (Eq, Show, Generic)
deriving anyclass (FromJSON, ToJSON)
instance Pretty ChainEvent where
pretty = \case
TxnValidate i _ logs -> "TxnValidate" <+> pretty i <+> pretty logs
TxnValidationFail p i _ e _ logs -> "TxnValidationFail" <+> pretty p <+> pretty i <> colon <+> pretty e <+> pretty logs
SlotAdd sl -> "SlotAdd" <+> pretty sl
type TxPool = [CardanoTx]
data ChainState = ChainState {
^ The current chain , with the newest transactions first in the list .
^ The index , used for validation .
} deriving (Show, Generic)
emptyChainState :: ChainState
emptyChainState = ChainState [] [] mempty 0
makeLenses ''ChainState
data ChainControlEffect r where
ProcessBlock :: ChainControlEffect Block
ModifySlot :: (Slot -> Slot) -> ChainControlEffect Slot
data ChainEffect r where
QueueTx :: CardanoTx -> ChainEffect ()
GetCurrentSlot :: ChainEffect Slot
GetParams :: ChainEffect Params
processBlock :: Member ChainControlEffect effs => Eff effs Block
processBlock = send ProcessBlock
modifySlot :: Member ChainControlEffect effs => (Slot -> Slot) -> Eff effs Slot
modifySlot = send . ModifySlot
queueTx :: Member ChainEffect effs => CardanoTx -> Eff effs ()
queueTx tx = send (QueueTx tx)
getParams :: Member ChainEffect effs => Eff effs Params
getParams = send GetParams
getCurrentSlot :: Member ChainEffect effs => Eff effs Slot
getCurrentSlot = send GetCurrentSlot
type ChainEffs = '[State ChainState, LogMsg ChainEvent]
handleControlChain :: Members ChainEffs effs => Params -> ChainControlEffect ~> Eff effs
handleControlChain params = \case
ProcessBlock -> do
pool <- gets $ view txPool
slot <- gets $ view chainCurrentSlot
idx <- gets $ view index
let ValidatedBlock block events idx' =
validateBlock params slot idx pool
modify $ txPool .~ []
modify $ index .~ idx'
modify $ addBlock block
traverse_ logEvent events
pure block
ModifySlot f -> modify @ChainState (over chainCurrentSlot f) >> gets (view chainCurrentSlot)
logEvent :: Member (LogMsg ChainEvent) effs => ChainEvent -> Eff effs ()
logEvent e = case e of
SlotAdd{} -> logDebug e
TxnValidationFail{} -> logWarn e
TxnValidate{} -> logInfo e
handleChain :: (Members ChainEffs effs) => Params -> ChainEffect ~> Eff effs
handleChain params = \case
QueueTx tx -> modify $ over txPool (addTxToPool tx)
GetCurrentSlot -> gets _chainCurrentSlot
GetParams -> pure params
data ValidatedBlock = ValidatedBlock
{ vlbValid :: Block
, vlbEvents :: [ChainEvent]
, vlbIndex :: Index.UtxoIndex
^ The updated UTxO index after processing the block
}
data ValidationCtx = ValidationCtx { vctxIndex :: Index.UtxoIndex, vctxParams :: Params }
| Validate a block given the current slot and UTxO index , returning the valid
transactions , success / failure events and the updated set .
validateBlock :: Params -> Slot -> Index.UtxoIndex -> TxPool -> ValidatedBlock
validateBlock params slot@(Slot s) idx txns =
let
Validate transactions , updating the UTXO index each time
(processed, ValidationCtx idx' _) =
flip S.runState (ValidationCtx idx params) $ for txns $ \tx -> do
result <- validateEm slot tx
pure (tx, result)
block = mapMaybe toOnChain processed
where
toOnChain (_ , Left (Index.Phase1, _)) = Nothing
toOnChain (tx, Left (Index.Phase2, _)) = Just (Invalid tx)
toOnChain (tx, Right _ ) = Just (Valid tx)
Also return an ` EmulatorEvent ` for each transaction that was
nextSlot = Slot (s + 1)
events = (uncurry (mkValidationEvent idx) <$> processed) ++ [SlotAdd nextSlot]
in ValidatedBlock block events idx'
getCollateral :: Index.UtxoIndex -> CardanoTx -> C.Value
getCollateral idx tx = case getCardanoTxTotalCollateral tx of
Just v -> lovelaceToValue v
Nothing -> fromRight (lovelaceToValue $ getCardanoTxFee tx) $
alaf Ap foldMap (fmap txOutValue . (`Index.lookup` idx) . txInRef) (getCardanoTxCollateralInputs tx)
canValidateNow :: Slot -> CardanoTx -> Bool
canValidateNow slot = Interval.member slot . getCardanoTxValidityRange
mkValidationEvent :: Index.UtxoIndex -> CardanoTx -> Either Index.ValidationErrorInPhase Index.ValidationSuccess -> ChainEvent
mkValidationEvent idx t result =
case result of
Right r -> TxnValidate (getCardanoTxId t) t logs
where logs = concatMap (fst . snd) $ Map.toList r
Left (phase, err) -> TxnValidationFail phase (getCardanoTxId t) t err (getCollateral idx t) logs
where
logs = case err of
Index.ScriptFailure (Scripts.EvaluationError msgs _) -> msgs
_ -> []
validateEm
:: S.MonadState ValidationCtx m
=> Slot
-> CardanoTx
-> m (Either Index.ValidationErrorInPhase Index.ValidationSuccess)
validateEm h txn = do
ctx@(ValidationCtx idx params) <- S.get
let
cUtxoIndex = either (error . show) id $ fromPlutusIndex idx
e = Validation.validateCardanoTx params h cUtxoIndex txn
idx' = case e of
Left (Index.Phase1, _) -> idx
Left (Index.Phase2, _) -> Index.insertCollateral txn idx
Right _ -> Index.insert txn idx
_ <- S.put ctx{ vctxIndex = idx' }
pure e
| Adds a block to ChainState , without validation .
addBlock :: Block -> ChainState -> ChainState
addBlock blk st =
st & chainNewestFirst %~ (blk :)
` txPool ` which will get ignored
& txPool %~ (\\ map unOnChain blk)
addTxToPool :: CardanoTx -> TxPool -> TxPool
addTxToPool = (:)
makePrisms ''ChainEvent
|
1e80385c44da23ab19734a115a71211ccacbdb0774879d3e87fca8b183ab7bfd | frenetic-lang/ocaml-openflow | Arbitrary_OpenFlow0x04.ml | open OpenFlow0x04
open OpenFlow0x04_Core
open Arbitrary_Base
open QuickCheck
module Gen = QuickCheck_gen
let sum (lst : int list) = List.fold_left (fun x y -> x + y) 0 lst
let arbitrary_32mask =
let open Gen in
(choose_int (1, 32)) >>= fun a ->
ret_gen (Int32.of_int a)
let arbitrary_128mask =
let open Gen in
(choose_int (1,64)) >>= fun a ->
(choose_int (0,64)) >>= fun b ->
ret_gen (Int64.of_int b,Int64.of_int a)
let arbitrary_64mask =
let open Gen in
(choose_int (1,64)) >>= fun a ->
ret_gen (Int64.of_int a)
let arbitrary_48mask =
let open Gen in
(choose_int (1,48)) >>= fun a ->
ret_gen (Int64.of_int a)
let arbitrary_12mask =
let open Gen in
(choose_int (1,12)) >>= fun a ->
ret_gen a
let arbitrary_16mask =
let open Gen in
(choose_int (1,16)) >>= fun a ->
ret_gen a
let arbitrary_masked arb arb_mask =
let open OpenFlow0x04_Core in
let open Gen in
frequency [
(1, arb >>= fun v -> ret_gen {OpenFlow0x04_Core.m_value = v; m_mask = None});
(3, arb >>= fun v ->
arb_mask >>= fun m -> ret_gen {OpenFlow0x04_Core.m_value = v; m_mask = Some m}) ]
let arbitrary_timeout =
let open OpenFlow0x04_Core in
let open Gen in
oneof [
ret_gen Permanent;
arbitrary_uint16 >>= (fun n -> ret_gen (ExpiresAfter n))
]
let fill_with_0 n=
String.make n '\000'
let arbitrary_stringl n=
let open Gen in
(choose_int (0,n)) >>= fun a ->
arbitrary_stringN a >>= fun str ->
ret_gen (str ^ (fill_with_0 (n-a)))
module type OpenFlow0x04_Arbitrary = sig
type t
type s
val arbitrary : t arbitrary
val to_string : t -> string
val parse : s -> t
val marshal : t -> s
end
module type OpenFlow0x04_ArbitraryCstruct = sig
type t
val arbitrary : t arbitrary
val to_string : t -> string
val parse : Cstruct.t -> t
val marshal : Cstruct.t -> t -> int
val size_of : t -> int
end
module OpenFlow0x04_Unsize(ArbC : OpenFlow0x04_ArbitraryCstruct) = struct
type t = ArbC.t
type s = Cstruct.t
let arbitrary = ArbC.arbitrary
let to_string = ArbC.to_string
let parse = ArbC.parse
let marshal m =
let bytes = Cstruct.of_bigarray Bigarray.(Array1.create char c_layout (ArbC.size_of m))
in ignore (ArbC.marshal bytes m); bytes
end
module PortDesc = struct
module PortFeatures = struct
type t = OpenFlow0x04_Core.portFeatures
type s = Int32.t
let arbitrary =
let open Gen in
let open PortFeatures in
arbitrary_bool >>= fun rate_10mb_hd ->
arbitrary_bool >>= fun rate_10mb_fd ->
arbitrary_bool >>= fun rate_100mb_hd ->
arbitrary_bool >>= fun rate_100mb_fd ->
arbitrary_bool >>= fun rate_1gb_hd ->
arbitrary_bool >>= fun rate_1gb_fd ->
arbitrary_bool >>= fun rate_10gb_fd ->
arbitrary_bool >>= fun rate_40gb_fd ->
arbitrary_bool >>= fun rate_100gb_fd ->
arbitrary_bool >>= fun rate_1tb_fd ->
arbitrary_bool >>= fun other ->
arbitrary_bool >>= fun copper ->
arbitrary_bool >>= fun fiber ->
arbitrary_bool >>= fun autoneg ->
arbitrary_bool >>= fun pause ->
arbitrary_bool >>= fun pause_asym ->
ret_gen {
rate_10mb_hd; rate_10mb_fd;
rate_100mb_hd; rate_100mb_fd;
rate_1gb_hd; rate_1gb_fd;
rate_10gb_fd; rate_40gb_fd;
rate_100gb_fd; rate_1tb_fd;
other; copper; fiber;
autoneg; pause; pause_asym
}
let to_string = PortFeatures.to_string
let marshal = PortFeatures.marshal
let parse = PortFeatures.parse
end
module PortState = struct
type t = OpenFlow0x04_Core.portState
type s = Int32.t
let arbitrary =
let open Gen in
let open PortState in
arbitrary_bool >>= fun link_down ->
arbitrary_bool >>= fun blocked ->
arbitrary_bool >>= fun live ->
ret_gen {
link_down;
blocked;
live
}
let to_string = PortState.to_string
let marshal = PortState.marshal
let parse = PortState.parse
end
module PortConfig = struct
type t = OpenFlow0x04_Core.portConfig
type s = Int32.t
let arbitrary =
let open Gen in
let open PortConfig in
arbitrary_bool >>= fun port_down ->
arbitrary_bool >>= fun no_recv ->
arbitrary_bool >>= fun no_fwd ->
arbitrary_bool >>= fun no_packet_in ->
ret_gen {
port_down;
no_recv;
no_fwd;
no_packet_in
}
let to_string = PortConfig.to_string
let marshal = PortConfig.marshal
let parse = PortConfig.parse
end
type t = OpenFlow0x04_Core.portDesc
let arbitrary =
let open Gen in
let open PortDesc in
arbitrary_uint32 >>= fun port_no ->
arbitrary_uint48 >>= fun hw_addr ->
arbitrary_stringN 16 >>= fun name ->
PortConfig.arbitrary >>= fun config ->
PortState.arbitrary >>= fun state ->
PortFeatures.arbitrary >>= fun curr ->
PortFeatures.arbitrary >>= fun advertised ->
PortFeatures.arbitrary >>= fun supported ->
PortFeatures.arbitrary >>= fun peer ->
arbitrary_uint32 >>= fun curr_speed ->
arbitrary_uint32 >>= fun max_speed ->
ret_gen {
port_no;
hw_addr;
name;
config;
state;
curr;
advertised;
supported;
peer;
curr_speed;
max_speed
}
let to_string = PortDesc.to_string
let parse = PortDesc.parse
let marshal = PortDesc.marshal
let size_of = PortDesc.sizeof
end
module PortStatus = struct
open Gen
type t = OpenFlow0x04_Core.portStatus
let arbitrary_reason =
oneof [
ret_gen PortAdd;
ret_gen PortDelete;
ret_gen PortModify
]
let arbitrary : t arbitrary =
let open PortStatus in
arbitrary_reason >>= fun reason ->
PortDesc.arbitrary >>= fun desc ->
ret_gen {
reason = reason;
desc = desc}
let to_string = PortStatus.to_string
let parse = PortStatus.parse
let marshal = PortStatus.marshal
let size_of = PortStatus.sizeof
end
module PseudoPort = struct
type s = int * (int option)
type t = PseudoPort.t
let arbitrary =
let open Gen in
let open OpenFlow0x04_Core in
oneof [
arbitrary_uint32 >>= (fun p -> ret_gen (PhysicalPort p));
ret_gen InPort;
ret_gen Table;
ret_gen Normal;
ret_gen Flood;
ret_gen AllPorts;
arbitrary_uint >>= (fun l -> ret_gen (Controller l));
ret_gen Local;
ret_gen Any
]
(* Use in cases where a `Controller` port is invalid input *)
let arbitrary_nc =
let open Gen in
let open OpenFlow0x04_Core in
oneof [
arbitrary_uint32 >>= (fun p -> ret_gen (PhysicalPort p));
ret_gen InPort;
ret_gen Table;
ret_gen Normal;
ret_gen Flood;
ret_gen AllPorts;
ret_gen Local;
ret_gen Any
]
let to_string = PseudoPort.to_string
let parse (p, l) =
let l' = match l with
| None -> 0
| Some i -> i
in PseudoPort.make p l'
let marshal p =
let open OpenFlow0x04_Core in
let l = match p with
| Controller i -> Some i
| _ -> None
in (PseudoPort.marshal p, l)
let size_of = PseudoPort.size_of
end
module OfpMatch = struct
open Gen
type t = OpenFlow0x04_Core.oxmMatch
module Oxm = struct
type t = Oxm.t
let arbitrary =
let open Gen in
let open Oxm in
let arbitrary_dscp =
(choose_int (0,64)) >>= fun a ->
ret_gen a in
let arbitrary_ecn =
(choose_int (0,3)) >>= fun a ->
ret_gen a in
let arbitrary_24mask =
let open Gen in
(choose_int (1,24)) >>= fun a ->
ret_gen (Int32.of_int a) in
let arbitrary_uint24 =
arbitrary_uint16 >>= fun a ->
arbitrary_uint8 >>= fun b ->
let open Int32 in
let hi = shift_left (of_int a) 8 in
let lo = of_int b in
ret_gen (logor hi lo) in
let arbitrary_ipv6hdr =
arbitrary_bool >>= fun noext ->
arbitrary_bool >>= fun esp ->
arbitrary_bool >>= fun auth ->
arbitrary_bool >>= fun dest ->
arbitrary_bool >>= fun frac ->
arbitrary_bool >>= fun router ->
arbitrary_bool >>= fun hop ->
arbitrary_bool >>= fun unrep ->
arbitrary_bool >>= fun unseq ->
ret_gen {noext; esp; auth; dest; frac; router; hop; unrep; unseq } in
arbitrary_uint32 >>= fun portId ->
arbitrary_uint32 >>= fun portPhyId ->
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun oxmMetadata ->
arbitrary_uint16 >>= fun oxmEthType ->
arbitrary_masked arbitrary_uint48 arbitrary_48mask >>= fun oxmEthDst ->
arbitrary_masked arbitrary_uint48 arbitrary_48mask >>= fun oxmEthSrc ->
arbitrary_masked arbitrary_uint12 arbitrary_12mask >>= fun oxmVlanVId ->
arbitrary_uint8 >>= fun oxmVlanPcp ->
arbitrary_uint8 >>= fun oxmIPProto ->
arbitrary_dscp >>= fun oxmIPDscp ->
arbitrary_ecn >>= fun oxmIPEcn ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmIP4Src ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmIP4Dst ->
arbitrary_uint16 >>= fun oxmTCPSrc ->
arbitrary_uint16 >>= fun oxmTCPDst ->
arbitrary_uint16 >>= fun oxmARPOp ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmARPSpa ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmARPTpa ->
arbitrary_masked arbitrary_uint48 arbitrary_48mask >>= fun oxmARPSha ->
arbitrary_masked arbitrary_uint48 arbitrary_48mask >>= fun oxmARPTha ->
arbitrary_uint8 >>= fun oxmICMPType ->
arbitrary_uint8 >>= fun oxmICMPCode ->
arbitrary_uint32 >>= fun oxmMPLSLabel ->
arbitrary_uint8 >>= fun oxmMPLSTc ->
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun oxmTunnelId ->
arbitrary_masked arbitrary_uint128 arbitrary_128mask >>= fun oxmIPv6Src ->
arbitrary_masked arbitrary_uint128 arbitrary_128mask >>= fun oxmIPv6Dst ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmIPv6FLabel ->
arbitrary_masked arbitrary_uint128 arbitrary_128mask >>= fun oxmIPv6NDTarget ->
arbitrary_masked arbitrary_uint24 arbitrary_24mask >>= fun oxmPBBIsid ->
arbitrary_masked arbitrary_ipv6hdr arbitrary_ipv6hdr >>= fun oxmIPv6ExtHdr ->
arbitrary_bool >>= fun oxmMPLSBos ->
arbitrary_uint16 >>= fun oxmUDPSrc ->
arbitrary_uint16 >>= fun oxmUDPDst ->
arbitrary_uint16 >>= fun oxmSCTPSrc ->
arbitrary_uint16 >>= fun oxmSCTPDst ->
arbitrary_uint8 >>= fun oxmICMPv6Type ->
arbitrary_uint8 >>= fun oxmICMPv6Code ->
arbitrary_uint48 >>= fun oxmIPv6NDSll ->
arbitrary_uint48 >>= fun oxmIPv6NDTll ->
oneof [
ret_gen (OxmInPort portId);
ret_gen (OxmInPhyPort portPhyId);
ret_gen (OxmMetadata oxmMetadata);
ret_gen (OxmEthType oxmEthType);
ret_gen (OxmEthDst oxmEthDst);
ret_gen (OxmEthSrc oxmEthSrc);
ret_gen (OxmVlanVId oxmVlanVId);
ret_gen (OxmVlanPcp oxmVlanPcp);
ret_gen (OxmIPProto oxmIPProto);
ret_gen (OxmIPDscp oxmIPDscp);
ret_gen (OxmIPEcn oxmIPEcn);
ret_gen (OxmIP4Src oxmIP4Src);
ret_gen (OxmIP4Dst oxmIP4Dst);
ret_gen (OxmTCPSrc oxmTCPSrc);
ret_gen (OxmTCPDst oxmTCPDst);
ret_gen (OxmARPOp oxmARPOp);
ret_gen (OxmARPSpa oxmARPSpa);
ret_gen (OxmARPTpa oxmARPTpa);
ret_gen (OxmARPSha oxmARPSha);
ret_gen (OxmARPTha oxmARPTha);
ret_gen (OxmICMPType oxmICMPType);
ret_gen (OxmICMPCode oxmICMPCode);
ret_gen (OxmMPLSLabel oxmMPLSLabel);
ret_gen (OxmMPLSTc oxmMPLSTc);
ret_gen (OxmTunnelId oxmTunnelId);
ret_gen (OxmUDPSrc oxmUDPSrc);
ret_gen (OxmUDPDst oxmUDPDst);
ret_gen (OxmSCTPSrc oxmSCTPSrc);
ret_gen (OxmSCTPDst oxmSCTPDst);
ret_gen (OxmIPv6Src oxmIPv6Src);
ret_gen (OxmIPv6Dst oxmIPv6Dst);
ret_gen (OxmIPv6FLabel oxmIPv6FLabel);
ret_gen (OxmICMPv6Type oxmICMPv6Type);
ret_gen (OxmICMPv6Code oxmICMPv6Code);
ret_gen (OxmIPv6NDTarget oxmIPv6NDTarget);
ret_gen (OxmIPv6NDSll oxmIPv6NDSll);
ret_gen (OxmIPv6NDTll oxmIPv6NDTll);
ret_gen (OxmMPLSBos oxmMPLSBos);
ret_gen (OxmPBBIsid oxmPBBIsid);
ret_gen (OxmIPv6ExtHdr oxmIPv6ExtHdr);
]
let marshal = Oxm.marshal
let to_string = Oxm.to_string
let size_of = Oxm.sizeof
let parse bits =
let p,_ = Oxm.parse bits in
p
end
module OxmHeader = struct
type t = OpenFlow0x04_Core.oxm
module Oxm = OpenFlow0x04.Oxm
let arbitrary =
let open Gen in
let open Oxm in
let ipv6hdr_nul = {noext = false; esp = false; auth = false; dest = false; frac = false; router = false; hop = false; unrep = false; unseq = false } in
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmMetadata ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmEthDst ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmEthSrc ->
arbitrary_masked (ret_gen 0) (ret_gen 0) >>= fun oxmVlanVId ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmIP4Src ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmIP4Dst ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmARPSpa ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmARPTpa ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmARPSha ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmARPTha ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmTunnelId ->
arbitrary_masked (ret_gen (0L,0L)) (ret_gen (0L,0L)) >>= fun oxmIPv6Src ->
arbitrary_masked (ret_gen (0L,0L)) (ret_gen (0L,0L)) >>= fun oxmIPv6Dst ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmIPv6FLabel ->
arbitrary_masked (ret_gen (0L,0L)) (ret_gen (0L,0L)) >>= fun oxmIPv6NDTarget ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmPBBIsid ->
arbitrary_masked (ret_gen ipv6hdr_nul) (ret_gen ipv6hdr_nul) >>= fun oxmIPv6ExtHdr ->
oneof [
ret_gen (OxmInPort 0l);
ret_gen (OxmInPhyPort 0l);
ret_gen (OxmMetadata oxmMetadata);
ret_gen (OxmEthType 0);
ret_gen (OxmEthDst oxmEthDst);
ret_gen (OxmEthSrc oxmEthSrc);
ret_gen (OxmVlanVId oxmVlanVId);
ret_gen (OxmVlanPcp 0);
ret_gen (OxmIPProto 0);
ret_gen (OxmIPDscp 0);
ret_gen (OxmIPEcn 0);
ret_gen (OxmIP4Src oxmIP4Src);
ret_gen (OxmIP4Dst oxmIP4Dst);
ret_gen (OxmTCPSrc 0);
ret_gen (OxmTCPDst 0);
ret_gen (OxmARPOp 0);
ret_gen (OxmARPSpa oxmARPSpa);
ret_gen (OxmARPTpa oxmARPTpa);
ret_gen (OxmARPSha oxmARPSha);
ret_gen (OxmARPTha oxmARPTha);
ret_gen (OxmICMPType 0);
ret_gen (OxmICMPCode 0);
ret_gen (OxmMPLSLabel 0l);
ret_gen (OxmMPLSTc 0);
ret_gen (OxmTunnelId oxmTunnelId);
ret_gen (OxmUDPSrc 0);
ret_gen (OxmUDPDst 0);
ret_gen (OxmSCTPSrc 0);
ret_gen (OxmSCTPDst 0);
ret_gen (OxmIPv6Src oxmIPv6Src);
ret_gen (OxmIPv6Dst oxmIPv6Dst);
ret_gen (OxmIPv6FLabel oxmIPv6FLabel);
ret_gen (OxmICMPv6Type 0);
ret_gen (OxmICMPv6Code 0);
ret_gen (OxmIPv6NDTarget oxmIPv6NDTarget);
ret_gen (OxmIPv6NDSll 0L);
ret_gen (OxmIPv6NDTll 0L);
ret_gen (OxmMPLSBos false);
ret_gen (OxmPBBIsid oxmPBBIsid);
ret_gen (OxmIPv6ExtHdr oxmIPv6ExtHdr);
]
let marshal = Oxm.marshal_header
let to_string = Oxm.field_name
let size_of = Oxm.sizeof
let parse bits =
let p,_ = Oxm.parse_header bits in
p
end
let arbitrary =
let open Gen in
let open OfpMatch in
arbitrary_list Oxm.arbitrary >>= fun ofpMatch ->
ret_gen ofpMatch
let marshal = OfpMatch.marshal
let parse bits=
let ofpMatch,_ = OfpMatch.parse bits in
ofpMatch
let to_string = OfpMatch.to_string
let size_of = OfpMatch.sizeof
end
module MeterBand = struct
type t = OpenFlow0x04_Core.meterBand
let arbitrary =
let open Gen in
let open OpenFlow0x04_Core in
arbitrary_uint32 >>= fun rate ->
arbitrary_uint32 >>= fun burst ->
oneof [
ret_gen (Drop (rate, burst));
arbitrary_uint8 >>= (fun p -> ret_gen (DscpRemark (rate,burst,p)));
arbitrary_uint32 >>= (fun p -> ret_gen (ExpMeter (rate,burst,p)))
]
let to_string = MeterBand.to_string
let marshal = MeterBand.marshal
let parse = MeterBand.parse
let size_of = MeterBand.sizeof
end
module Action = struct
type t = OpenFlow0x04_Core.action
let arbitrary =
let open Gen in
let open OpenFlow0x04_Core in
oneof [
PseudoPort.arbitrary >>= (fun p -> ret_gen (Output p));
arbitrary_uint32 >>= (fun p -> ret_gen (Group p));
ret_gen PopVlan;
ret_gen PushVlan;
ret_gen PopMpls;
ret_gen PushMpls;
ret_gen CopyTtlOut;
ret_gen CopyTtlIn;
ret_gen DecNwTtl;
ret_gen PushPbb;
ret_gen PopPbb;
ret_gen DecMplsTtl;
arbitrary_uint8 >>= (fun p -> ret_gen (SetNwTtl p));
arbitrary_uint8 >>= (fun p -> ret_gen (SetMplsTtl p));
arbitrary_uint32 >>= (fun p -> ret_gen (SetQueue p));
OfpMatch.Oxm.arbitrary >>= (fun p -> ret_gen (SetField p))
]
let to_string = Action.to_string
let marshal = Action.marshal
let parse = Action.parse
let size_of = Action.sizeof
end
module Instructions = struct
open Gen
type t = OpenFlow0x04_Core.instruction list
module Instruction = struct
type t = OpenFlow0x04_Core.instruction
let arbitrary =
let open Gen in
let open Instruction in
arbitrary_uint8 >>= fun tableid ->
arbitrary_uint32 >>= fun meter ->
arbitrary_uint32 >>= fun exp ->
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun wrMeta ->
arbitrary_list Action.arbitrary >>= fun wrAction ->
arbitrary_list Action.arbitrary >>= fun appAction ->
oneof [
ret_gen (GotoTable tableid);
ret_gen (WriteMetadata wrMeta);
ret_gen (WriteActions wrAction);
ret_gen (ApplyActions appAction);
ret_gen Clear;
ret_gen (Meter meter);
ret_gen (Experimenter exp);
]
let marshal = Instruction.marshal
let parse = Instruction.parse
let to_string = Instruction.to_string
let size_of = Instruction.sizeof
end
let arbitrary =
let open Gen in
let open Instructions in
arbitrary_list Instruction.arbitrary >>= fun ins ->
ret_gen ins
let marshal = Instructions.marshal
let parse = Instructions.parse
let to_string = Instructions.to_string
let size_of = Instructions.sizeof
end
module FlowMod = struct
open Gen
module FlowModCommand = struct
type t = OpenFlow0x04_Core.flowModCommand
let arbitrary =
let open Gen in
let open FlowModCommand in
oneof [
ret_gen AddFlow;
ret_gen ModFlow;
ret_gen ModStrictFlow;
ret_gen DeleteFlow;
ret_gen DeleteStrictFlow;
]
let to_string = FlowModCommand.to_string
let marshal = FlowModCommand.marshal
let parse = FlowModCommand.parse
end
type t = OpenFlow0x04_Core.flowMod
let arbitrary_flags =
arbitrary_bool >>= fun fmf_send_flow_rem ->
arbitrary_bool >>= fun fmf_check_overlap ->
arbitrary_bool >>= fun fmf_reset_counts ->
arbitrary_bool >>= fun fmf_no_pkt_counts ->
arbitrary_bool >>= fun fmf_no_byt_counts ->
ret_gen {
fmf_send_flow_rem;
fmf_check_overlap;
fmf_reset_counts;
fmf_no_pkt_counts;
fmf_no_byt_counts
}
let arbitrary_buffer_id =
arbitrary_uint32 >>= fun bid ->
oneof [
ret_gen None;
ret_gen (Some bid)
]
let arbitrary =
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun mfCookie ->
arbitrary_uint8 >>= fun mfTable_id ->
arbitrary_timeout >>= fun mfIdle_timeout ->
arbitrary_timeout >>= fun mfHard_timeout ->
arbitrary_uint16 >>= fun mfPriority ->
arbitrary_flags >>= fun mfFlags ->
arbitrary_buffer_id >>= fun mfBuffer_id ->
FlowModCommand.arbitrary >>= fun mfCommand ->
PseudoPort.arbitrary_nc >>= fun mfPort ->
oneof [ ret_gen None; ret_gen (Some mfPort)] >>= fun mfOut_port ->
arbitrary_uint32 >>= fun mfGroup ->
oneof [ ret_gen None; ret_gen (Some mfGroup)] >>= fun mfOut_group ->
OfpMatch.arbitrary >>= fun mfOfp_match ->
Instructions.arbitrary >>= fun mfInstructions ->
ret_gen {
mfCookie; mfTable_id;
mfCommand; mfIdle_timeout;
mfHard_timeout; mfPriority;
mfBuffer_id;
mfOut_port;
mfOut_group; mfFlags;
mfOfp_match; mfInstructions}
let marshal = FlowMod.marshal
let parse = FlowMod.parse
let to_string = FlowMod.to_string
let size_of = FlowMod.sizeof
end
module Bucket = struct
open Gen
open OpenFlow0x04_Core
type t = OpenFlow0x04_Core.bucket
let arbitrary_option =
frequency [
(1, ret_gen None);
(5, arbitrary_uint32 >>= (fun v -> ret_gen (Some v)))
]
let no_output act =
match act with
| Output _ -> false
| _ -> true
let arbitrary =
arbitrary_uint16 >>= fun bu_weight ->
arbitrary_option >>= fun bu_watch_port ->
arbitrary_option >>= fun bu_watch_group ->
list1 (such_that no_output Action.arbitrary) >>= fun bu_actions ->
ret_gen {
bu_weight;
bu_watch_port;
bu_watch_group;
bu_actions
}
let marshal = Bucket.marshal
let parse = Bucket.parse
let to_string = Bucket.to_string
let size_of = Bucket.sizeof
end
module GroupMod = struct
open Gen
open OpenFlow0x04_Core
type t = GroupMod.t
let arbitrary_typ =
oneof [
ret_gen All;
ret_gen Select;
ret_gen Indirect;
ret_gen FF
]
let arbitrary =
arbitrary_typ >>= fun typ ->
arbitrary_uint32 >>= fun gid ->
arbitrary_list Bucket.arbitrary >>= fun buckets ->
oneof [
ret_gen (AddGroup (typ, gid, buckets));
ret_gen (DeleteGroup (typ, gid));
ret_gen (ModifyGroup (typ, gid, buckets))
]
let marshal = GroupMod.marshal
let parse = GroupMod.parse
let to_string = GroupMod.to_string
let size_of = GroupMod.sizeof
end
module MultipartReq = struct
open Gen
open OpenFlow0x04_Core
module TableFeature = struct
module TableFeatureProp = struct
type t = TableFeatureProp.t
let arbitrary_ins =
oneof [
ret_gen GotoTableHdr;
ret_gen ApplyActionsHdr;
ret_gen WriteActionsHdr;
ret_gen WriteMetadataHdr;
ret_gen ClearHdr;
ret_gen MeterHdr;
arbitrary_uint32 >>= (fun n -> ret_gen (ExperimenterHdr n))
]
let arbitrary_act =
oneof [
ret_gen OutputHdr;
ret_gen GroupHdr;
ret_gen PopVlanHdr;
ret_gen PushVlanHdr;
ret_gen PopMplsHdr;
ret_gen PushMplsHdr;
ret_gen SetFieldHdr;
ret_gen CopyTtlOutHdr;
ret_gen CopyTtlInHdr;
ret_gen SetNwTtlHdr;
ret_gen DecNwTtlHdr;
ret_gen PushPbbHdr;
ret_gen PopPbbHdr;
ret_gen SetMplsTtlHdr;
ret_gen DecMplsTtlHdr;
ret_gen SetQueueHdr;
arbitrary_uint32 >>= (fun n -> ret_gen (ExperimenterAHdr n))
]
let arbitrary =
oneof [
list1 arbitrary_ins >>= (fun n -> ret_gen (TfpInstruction n));
list1 arbitrary_ins >>= (fun n -> ret_gen (TfpInstructionMiss n));
arbitrary_list arbitrary_act >>= (fun n -> ret_gen (TfpWriteAction n));
arbitrary_list arbitrary_act >>= (fun n -> ret_gen (TfpWriteActionMiss n));
arbitrary_list arbitrary_act >>= (fun n -> ret_gen (TfpApplyAction n));
arbitrary_list arbitrary_act >>= (fun n -> ret_gen (TfpApplyActionMiss n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpMatch n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpWildcard n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpWriteSetField n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpWriteSetFieldMiss n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpApplySetField n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpApplySetFieldMiss n))
]
let marshal = TableFeatureProp.marshal
let parse = TableFeatureProp.parse
let to_string = TableFeatureProp.to_string
let size_of = TableFeatureProp.sizeof
end
type t = TableFeature.t
let arbitrary_config =
ret_gen Deprecated
let calc_length tfp =
sizeof_ofp_table_feature = 64
ret_gen (64+sum (List.map TableFeatureProp.size_of tfp))
let arbitrary =
arbitrary_uint8 >>= fun table_id ->
arbitrary_stringN 32 >>= fun name ->
arbitrary_uint64 >>= fun metadata_match ->
arbitrary_uint64 >>= fun metadata_write ->
arbitrary_config >>= fun config ->
arbitrary_uint32 >>= fun max_entries ->
list1 TableFeatureProp.arbitrary >>= fun feature_prop ->
calc_length feature_prop>>= fun length ->
ret_gen {
length;
table_id;
name;
metadata_match;
metadata_write;
config;
max_entries;
feature_prop
}
let marshal = TableFeature.marshal
let parse = TableFeature.parse
let to_string = TableFeature.to_string
let size_of = TableFeature.sizeof
end
module FlowRequest = struct
type t = FlowRequest.t
let arbitrary =
arbitrary_uint8 >>= fun fr_table_id ->
arbitrary_uint32 >>= fun fr_out_port ->
arbitrary_uint32 >>= fun fr_out_group ->
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun fr_cookie ->
OfpMatch.arbitrary >>= fun fr_match ->
ret_gen {
fr_table_id;
fr_out_port;
fr_out_group;
fr_cookie;
fr_match
}
let marshal = FlowRequest.marshal
let parse = FlowRequest.parse
let to_string = FlowRequest.to_string
let size_of = FlowRequest.sizeof
end
module QueueRequest = struct
type t = QueueRequest.t
let arbitrary =
arbitrary_uint32 >>= fun port_number ->
arbitrary_uint32 >>= fun queue_id ->
ret_gen {
port_number;
queue_id
}
let marshal = QueueRequest.marshal
let parse = QueueRequest.parse
let to_string = QueueRequest.to_string
let size_of = QueueRequest.sizeof
end
type t = MultipartReq.t
let arbitrary_option =
frequency [
(1, ret_gen None);
(3, list1 TableFeature.arbitrary >>= (fun v -> ret_gen (Some v)))
]
let arbitrary_type =
oneof [
ret_gen SwitchDescReq;
ret_gen PortsDescReq;
FlowRequest.arbitrary >>= (fun n -> ret_gen (FlowStatsReq n));
FlowRequest.arbitrary >>= (fun n -> ret_gen (AggregFlowStatsReq n));
ret_gen TableStatsReq;
arbitrary_uint32 >>= (fun n -> ret_gen (PortStatsReq n));
QueueRequest.arbitrary >>= (fun n -> ret_gen (QueueStatsReq n));
arbitrary_uint32 >>= (fun n -> ret_gen (GroupStatsReq n));
ret_gen GroupDescReq;
ret_gen GroupFeatReq;
arbitrary_uint32 >>= (fun n -> ret_gen (MeterStatsReq n));
arbitrary_uint32 >>= (fun n -> ret_gen (MeterConfReq n));
ret_gen MeterFeatReq;
arbitrary_option >>= (fun n -> ret_gen (TableFeatReq n));
]
let arbitrary =
arbitrary_bool >>= fun mpr_flags ->
arbitrary_type >>= fun mpr_type ->
ret_gen {
mpr_type;
mpr_flags
}
let marshal = MultipartReq.marshal
let parse = MultipartReq.parse
let to_string = MultipartReq.to_string
let size_of = MultipartReq.sizeof
end
module MultipartReply = struct
open Gen
open OpenFlow0x04_Core
module FlowStats = struct
type t = FlowStats.t
let arbitrary_flags =
arbitrary_bool >>= fun fmf_send_flow_rem ->
arbitrary_bool >>= fun fmf_check_overlap ->
arbitrary_bool >>= fun fmf_reset_counts ->
arbitrary_bool >>= fun fmf_no_pkt_counts ->
arbitrary_bool >>= fun fmf_no_byt_counts ->
ret_gen {
fmf_send_flow_rem;
fmf_check_overlap;
fmf_reset_counts;
fmf_no_pkt_counts;
fmf_no_byt_counts
}
let arbitrary =
Instructions.arbitrary >>= fun instructions ->
arbitrary_uint8 >>= fun table_id ->
list1 OfpMatch.Oxm.arbitrary >>= fun ofp_match ->
arbitrary_uint64 >>= fun byte_count ->
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun cookie ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
arbitrary_uint16 >>= fun priority ->
arbitrary_timeout >>= fun idle_timeout ->
arbitrary_timeout >>= fun hard_timeout ->
arbitrary_flags >>= fun flags ->
ret_gen { table_id
; duration_sec
; duration_nsec
; priority
; idle_timeout
; hard_timeout
; flags
; cookie
; packet_count
; byte_count
; ofp_match
; instructions}
let marshal = FlowStats.marshal
let parse = FlowStats.parse
let to_string = FlowStats.to_string
let size_of = FlowStats.sizeof
end
module AggregateStats = struct
type t = AggregateStats.t
let arbitrary =
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun byte_count ->
arbitrary_uint32 >>= fun flow_count ->
ret_gen {
packet_count;
byte_count;
flow_count
}
let marshal = AggregateStats.marshal
let parse = AggregateStats.parse
let to_string = AggregateStats.to_string
let size_of = AggregateStats.sizeof
end
module TableStats = struct
type t = TableStats.t
let arbitrary =
arbitrary_uint8 >>= fun table_id ->
arbitrary_uint32 >>= fun active_count ->
arbitrary_uint64 >>= fun lookup_count ->
arbitrary_uint64 >>= fun matched_count ->
ret_gen {
table_id;
active_count;
lookup_count;
matched_count
}
let marshal = TableStats.marshal
let parse = TableStats.parse
let to_string = TableStats.to_string
let size_of = TableStats.sizeof
end
module PortStats = struct
type t = PortStats.t
let arbitrary =
arbitrary_uint32 >>= fun psPort_no ->
arbitrary_uint64 >>= fun rx_packets ->
arbitrary_uint64 >>= fun tx_packets ->
arbitrary_uint64 >>= fun rx_bytes ->
arbitrary_uint64 >>= fun tx_bytes ->
arbitrary_uint64 >>= fun rx_dropped ->
arbitrary_uint64 >>= fun tx_dropped ->
arbitrary_uint64 >>= fun rx_errors ->
arbitrary_uint64 >>= fun tx_errors ->
arbitrary_uint64 >>= fun rx_frame_err ->
arbitrary_uint64 >>= fun rx_over_err ->
arbitrary_uint64 >>= fun rx_crc_err ->
arbitrary_uint64 >>= fun collisions ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
ret_gen {
psPort_no;
rx_packets;
tx_packets;
rx_bytes;
tx_bytes;
rx_dropped;
tx_dropped;
rx_errors;
tx_errors;
rx_frame_err;
rx_over_err;
rx_crc_err;
collisions;
duration_sec;
duration_nsec
}
let marshal = PortStats.marshal
let parse = PortStats.parse
let to_string = PortStats.to_string
let size_of = PortStats.sizeof
end
module SwitchDescriptionReply = struct
type t = SwitchDescriptionReply.t
let arbitrary =
arbitrary_stringl 256 >>= fun mfr_desc ->
arbitrary_stringl 256 >>= fun hw_desc ->
arbitrary_stringl 256 >>= fun sw_desc ->
arbitrary_stringl 32 >>= fun serial_num ->
ret_gen {
mfr_desc;
hw_desc;
sw_desc;
serial_num
}
let marshal = SwitchDescriptionReply.marshal
let parse = SwitchDescriptionReply.parse
let to_string = SwitchDescriptionReply.to_string
let size_of = SwitchDescriptionReply.sizeof
end
module QueueStats = struct
type t = QueueStats.t
let arbitrary =
arbitrary_uint32 >>= fun qsPort_no ->
arbitrary_uint32 >>= fun queue_id ->
arbitrary_uint64 >>= fun tx_bytes ->
arbitrary_uint64 >>= fun tx_packets ->
arbitrary_uint64 >>= fun tx_errors ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
ret_gen {
qsPort_no;
queue_id;
tx_bytes;
tx_packets;
tx_errors;
duration_sec;
duration_nsec
}
let marshal = QueueStats.marshal
let parse = QueueStats.parse
let to_string = QueueStats.to_string
let size_of = QueueStats.sizeof
end
module GroupStats = struct
module BucketStats = struct
type t = GroupStats.BucketStats.t
let arbitrary =
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun byte_count ->
ret_gen {packet_count; byte_count}
let marshal = GroupStats.BucketStats.marshal
let parse = GroupStats.BucketStats.parse
let to_string = GroupStats.BucketStats.to_string
let size_of = GroupStats.BucketStats.sizeof
end
type t = GroupStats.t
let calc_length bs =
sizeof_ofp_group_stats = 40
ret_gen (40+(sum (List.map BucketStats.size_of bs)))
let arbitrary =
arbitrary_uint32 >>= fun group_id ->
arbitrary_uint32 >>= fun ref_count ->
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun byte_count ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
list1 BucketStats.arbitrary >>= fun bucket_stats ->
calc_length bucket_stats >>= fun length ->
ret_gen {
length;
group_id;
ref_count;
packet_count;
byte_count;
duration_sec;
duration_nsec;
bucket_stats}
let marshal = GroupStats.marshal
let parse = GroupStats.parse
let to_string = GroupStats.to_string
let size_of = GroupStats.sizeof
end
module GroupDesc = struct
type t = GroupDesc.t
let arbitrary_groupTyp =
oneof [
ret_gen All;
ret_gen Select;
ret_gen Indirect;
ret_gen FF]
let calc_length bucket =
ofp_group_desc = 8
ret_gen (8+ sum (List.map Bucket.size_of bucket))
let arbitrary =
arbitrary_uint32 >>= fun group_id ->
arbitrary_groupTyp >>= fun typ ->
list1 Bucket.arbitrary >>= fun bucket ->
calc_length bucket>>= fun length ->
ret_gen {
length;
typ;
group_id;
bucket
}
let marshal = GroupDesc.marshal
let parse = GroupDesc.parse
let to_string = GroupDesc.to_string
let size_of = GroupDesc.sizeof
end
module GroupFeatures = struct
type t = GroupFeatures.t
let arbitrary_groupTypeMap =
arbitrary_bool >>= fun all ->
arbitrary_bool >>= fun select ->
arbitrary_bool >>= fun indirect ->
arbitrary_bool >>= fun ff ->
ret_gen {
all;
select;
indirect;
ff
}
let arbitrary_groupCapabilities =
arbitrary_bool >>= fun select_weight ->
arbitrary_bool >>= fun select_liveness ->
arbitrary_bool >>= fun chaining ->
arbitrary_bool >>= fun chaining_checks ->
ret_gen {
select_weight;
select_liveness;
chaining;
chaining_checks
}
let arbitrary_actionTypeMap =
arbitrary_bool >>= fun output ->
arbitrary_bool >>= fun copy_ttl_out ->
arbitrary_bool >>= fun copy_ttl_in ->
arbitrary_bool >>= fun set_mpls_ttl ->
arbitrary_bool >>= fun dec_mpls_ttl ->
arbitrary_bool >>= fun push_vlan ->
arbitrary_bool >>= fun pop_vlan ->
arbitrary_bool >>= fun push_mpls ->
arbitrary_bool >>= fun pop_mpls ->
arbitrary_bool >>= fun set_queue ->
arbitrary_bool >>= fun group ->
arbitrary_bool >>= fun set_nw_ttl ->
arbitrary_bool >>= fun dec_nw_ttl ->
arbitrary_bool >>= fun set_field ->
arbitrary_bool >>= fun push_pbb ->
arbitrary_bool >>= fun pop_pbb ->
ret_gen {
output;
copy_ttl_out;
copy_ttl_in;
set_mpls_ttl;
dec_mpls_ttl;
push_vlan;
pop_vlan;
push_mpls;
pop_mpls;
set_queue;
group;
set_nw_ttl;
dec_nw_ttl;
set_field;
push_pbb;
pop_pbb
}
let arbitrary =
arbitrary_groupTypeMap >>= fun typ ->
arbitrary_groupCapabilities >>= fun capabilities ->
arbitrary_uint32 >>= fun max_groups_all ->
arbitrary_uint32 >>= fun max_groups_select ->
arbitrary_uint32 >>= fun max_groups_indirect ->
arbitrary_uint32 >>= fun max_groups_ff ->
arbitrary_actionTypeMap >>= fun actions_all ->
arbitrary_actionTypeMap >>= fun actions_select ->
arbitrary_actionTypeMap >>= fun actions_indirect ->
arbitrary_actionTypeMap >>= fun actions_ff ->
ret_gen {
typ;
capabilities;
max_groups_all;
max_groups_select;
max_groups_indirect;
max_groups_ff;
actions_all;
actions_select;
actions_indirect;
actions_ff
}
let marshal = GroupFeatures.marshal
let parse = GroupFeatures.parse
let to_string = GroupFeatures.to_string
let size_of = GroupFeatures.sizeof
end
module MeterStats = struct
type t = MeterStats.t
let calc_length band =
sizeof_ofp_meter_stats = 40
ret_gen (40+(List.length band)*16)
let arbitrary_meterBandStats =
arbitrary_uint64 >>= fun packet_band_count ->
arbitrary_uint64 >>= fun byte_band_count ->
ret_gen { packet_band_count; byte_band_count }
let arbitrary =
arbitrary_uint32 >>= fun meter_id ->
arbitrary_uint32 >>= fun flow_count ->
arbitrary_uint64 >>= fun packet_in_count ->
arbitrary_uint64 >>= fun byte_in_count ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
list1 arbitrary_meterBandStats >>= fun band ->
calc_length band >>= fun len ->
ret_gen {
meter_id;
len;
flow_count;
packet_in_count;
byte_in_count;
duration_sec;
duration_nsec;
band
}
let marshal = MeterStats.marshal
let parse = MeterStats.parse
let to_string = MeterStats.to_string
let size_of = MeterStats.sizeof
end
module MeterConfig = struct
type t = MeterConfig.t
let arbitrary_meterFlagsMap =
arbitrary_bool >>= fun kbps ->
arbitrary_bool >>= fun pktps ->
arbitrary_bool >>= fun burst ->
arbitrary_bool >>= fun stats ->
ret_gen {
kbps;
pktps;
burst;
stats
}
let calc_length bands =
sizeof_ofp_meter_config = 8
ret_gen (8 + sum (List.map MeterBand.size_of bands))
let arbitrary =
arbitrary_meterFlagsMap >>= fun flags ->
arbitrary_uint32 >>= fun meter_id ->
list1 MeterBand.arbitrary >>= fun bands ->
calc_length bands >>= fun length ->
ret_gen {
length;
flags;
meter_id;
bands
}
let marshal = MeterConfig.marshal
let parse = MeterConfig.parse
let to_string = MeterConfig.to_string
let size_of = MeterConfig.sizeof
end
module MeterFeatures = struct
type t = MeterFeatures.t
let arbitrary_meterBandMaps =
arbitrary_bool >>= fun drop ->
arbitrary_bool >>= fun dscpRemark ->
ret_gen {
drop;
dscpRemark }
let arbitrary_meterFlagsMap =
arbitrary_bool >>= fun kbps ->
arbitrary_bool >>= fun pktps ->
arbitrary_bool >>= fun burst ->
arbitrary_bool >>= fun stats ->
ret_gen {
kbps;
pktps;
burst;
stats
}
let arbitrary =
arbitrary_uint32 >>= fun max_meter ->
arbitrary_meterBandMaps >>= fun band_typ ->
arbitrary_meterFlagsMap >>= fun capabilities ->
arbitrary_uint8 >>= fun max_band ->
arbitrary_uint8 >>= fun max_color ->
ret_gen {
max_meter;
band_typ;
capabilities;
max_band;
max_color
}
let marshal = MeterFeatures.marshal
let parse = MeterFeatures.parse
let to_string = MeterFeatures.to_string
let size_of = MeterFeatures.sizeof
end
type t = MultipartReply.t
let arbitrary =
arbitrary_bool >>= fun flags ->
oneof [
list1 PortDesc.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (PortsDescReply n); mpreply_flags = flags});
SwitchDescriptionReply.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (SwitchDescReply n); mpreply_flags = flags});
list1 FlowStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (FlowStatsReply n); mpreply_flags = flags});
AggregateStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (AggregateReply n); mpreply_flags = flags});
list1 TableStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (TableReply n); mpreply_flags = flags});
list1 PortStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (PortStatsReply n); mpreply_flags = flags});
list1 QueueStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (QueueStatsReply n); mpreply_flags = flags});
list1 GroupStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (GroupStatsReply n); mpreply_flags = flags});
GroupFeatures.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (GroupFeaturesReply n); mpreply_flags = flags});
list1 GroupDesc.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (GroupDescReply n); mpreply_flags = flags});
list1 MeterStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (MeterReply n); mpreply_flags = flags});
list1 MeterConfig.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (MeterConfig n); mpreply_flags = flags});
MeterFeatures.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (MeterFeaturesReply n); mpreply_flags = flags});
]
let marshal = MultipartReply.marshal
let parse = MultipartReply.parse
let to_string = MultipartReply.to_string
let size_of = MultipartReply.sizeof
end
module PacketOut = struct
open Gen
open OpenFlow0x04_Core
type t = PacketOut.t
let arbitrary_len =
(choose_int (24, 1500)) >>= fun a ->
ret_gen a
let arbitrary_byte n =
(* construct an arbitrary byte of length n*)
arbitrary_stringN n >>= fun a ->
let byte = Cstruct.create n in
Cstruct.blit_from_string a 0 byte 0 n;
ret_gen (byte)
let arbitrary_pay byte =
frequency [
(1, ret_gen (NotBuffered byte));
(3, arbitrary_uint32 >>= fun bid ->
arbitrary_byte 0 >>= fun byte -> (* buffered packet out don't have payload *)
ret_gen (Buffered (bid,byte)))
]
let arbitrary_port_id =
frequency [
(1, ret_gen None);
(9, arbitrary_uint32 >>= fun port_id ->
ret_gen (Some port_id))
]
let arbitrary =
arbitrary_list Action.arbitrary >>= fun po_actions ->
arbitrary_len >>= fun len ->
arbitrary_byte len >>= fun byte ->
arbitrary_pay byte >>= fun po_payload ->
arbitrary_port_id >>= fun po_port_id ->
ret_gen {
po_payload;
po_port_id;
po_actions
}
let parse = PacketOut.parse
let marshal = PacketOut.marshal
let to_string = PacketOut.to_string
let size_of = PacketOut.sizeof
end
module PacketIn = struct
open Gen
open OpenFlow0x04_Core
type t = OpenFlow0x04_Core.packetIn
let arbitrary_len =
(choose_int (24, 1500)) >>= fun a ->
ret_gen a
let arbitrary_byte n =
(* construct an arbitrary byte of length n*)
arbitrary_stringN n >>= fun a ->
let byte = Cstruct.create n in
Cstruct.blit_from_string a 0 byte 0 n;
ret_gen (byte)
let arbitrary_reason =
oneof [
ret_gen (OpenFlow0x04_Core.NoMatch);
ret_gen (OpenFlow0x04_Core.ExplicitSend);
ret_gen (OpenFlow0x04_Core.InvalidTTL)
]
let arbitrary_pay byte =
frequency [
(1, ret_gen (NotBuffered byte));
(3, arbitrary_uint32 >>= fun bid ->
ret_gen (Buffered (bid,byte)))
]
let arbitrary =
arbitrary_len >>= fun pi_total_len ->
arbitrary_reason >>= fun pi_reason ->
arbitrary_uint8 >>= fun pi_table_id ->
arbitrary_uint64 >>= fun pi_cookie ->
OfpMatch.arbitrary >>= fun pi_ofp_match ->
arbitrary_byte pi_total_len >>= fun byte ->
arbitrary_pay byte >>= fun pi_payload ->
ret_gen {
pi_total_len;
pi_reason;
pi_table_id;
pi_cookie;
pi_ofp_match;
pi_payload
}
let marshal = PacketIn.marshal
let parse = PacketIn.parse
let to_string = PacketIn.to_string
let size_of = PacketIn.sizeof
end
module RoleRequest = struct
open Gen
open OpenFlow0x04_Core
type t = OpenFlow0x04_Core.roleRequest
let arbitrary_role =
oneof [
ret_gen NoChangeRole;
ret_gen EqualRole;
ret_gen MasterRole;
ret_gen SlaveRole
]
let arbitrary =
arbitrary_role >>= fun role ->
arbitrary_uint64 >>= fun generation_id ->
ret_gen { role; generation_id }
let marshal = RoleRequest.marshal
let parse = RoleRequest.parse
let to_string = RoleRequest.to_string
let size_of = RoleRequest.sizeof
end
module QueueDesc = struct
open Gen
open OpenFlow0x04_Core
module QueueProp = struct
open Gen
open OpenFlow0x04_Core
type t = QueueDesc.QueueProp.t
let arbitrary_rate =
frequency [
(1, ret_gen Disabled);
(10, choose_int (0,1000) >>= fun a ->
ret_gen (Rate a))
]
let arbitrary =
arbitrary_rate >>= fun min_rate ->
arbitrary_rate >>= fun max_rate ->
arbitrary_uint32 >>= fun exp_id ->
oneof [
ret_gen (MinRateProp min_rate);
ret_gen (MaxRateProp max_rate);
ret_gen (ExperimenterProp exp_id)
]
let marshal = QueueDesc.QueueProp.marshal
let parse = QueueDesc.QueueProp.parse
let to_string = QueueDesc.QueueProp.to_string
let size_of = QueueDesc.QueueProp.sizeof
end
type t = QueueDesc.t
let calc_length prop =
sizeof_ofp_packet_queue = 16
ret_gen (16+sum (List.map QueueProp.size_of prop))
let arbitrary =
arbitrary_uint32 >>= fun queue_id ->
arbitrary_uint32 >>= fun port ->
arbitrary_list QueueProp.arbitrary >>= fun properties ->
calc_length properties >>= fun len ->
ret_gen { queue_id; port; len; properties}
let marshal = QueueDesc.marshal
let parse = QueueDesc.parse
let to_string = QueueDesc.to_string
let size_of = QueueDesc.sizeof
end
module QueueConfReq = struct
open Gen
open OpenFlow0x04_Core
type t = QueueConfReq.t
let arbitrary =
arbitrary_uint32 >>= fun port ->
ret_gen {port}
let marshal = QueueConfReq.marshal
let parse = QueueConfReq.parse
let to_string = QueueConfReq.to_string
let size_of = QueueConfReq.sizeof
end
module QueueConfReply = struct
open Gen
open OpenFlow0x04_Core
type t = QueueConfReply.t
let arbitrary =
arbitrary_uint32 >>= fun port ->
arbitrary_list QueueDesc.arbitrary >>= fun queues ->
ret_gen {port; queues}
let marshal = QueueConfReply.marshal
let parse = QueueConfReply.parse
let to_string = QueueConfReply.to_string
let size_of = QueueConfReply.sizeof
end
module SwitchConfig = struct
open Gen
open OpenFlow0x04_Core
type t = SwitchConfig.t
let arbitrary_flags =
oneof [
ret_gen NormalFrag;
ret_gen DropFrag;
ret_gen ReasmFrag;
ret_gen MaskFrag
]
let arbitrary =
arbitrary_flags >>= fun flags ->
arbitrary_uint16 >>= fun miss_send_len ->
ret_gen { flags; miss_send_len}
let marshal = SwitchConfig.marshal
let parse = SwitchConfig.parse
let to_string = SwitchConfig.to_string
let size_of = SwitchConfig.sizeof
end
module TableMod = struct
open Gen
open OpenFlow0x04_Core
type t = TableMod.t
let arbitrary_config =
ret_gen Deprecated
let arbitrary =
arbitrary_uint8 >>= fun table_id ->
arbitrary_config >>= fun config ->
ret_gen { table_id; config }
let marshal = TableMod.marshal
let parse = TableMod.parse
let to_string = TableMod.to_string
let size_of = TableMod.sizeof
end
module PortMod = struct
open Gen
open OpenFlow0x04_Core
type t = PortMod.t
let arbitrary =
arbitrary_uint32 >>= fun mpPortNo ->
arbitrary_uint48 >>= fun mpHw_addr ->
PortDesc.PortConfig.arbitrary >>= fun mpConfig ->
PortDesc.PortConfig.arbitrary >>= fun mpMask ->
PortDesc.PortState.arbitrary >>= fun mpAdvertise ->
ret_gen { mpPortNo; mpHw_addr; mpConfig; mpMask; mpAdvertise}
let marshal = PortMod.marshal
let parse = PortMod.parse
let to_string = PortMod.to_string
let size_of = PortMod.sizeof
end
module MeterMod = struct
open Gen
open OpenFlow0x04_Core
type t = MeterMod.t
let arbitrary_command =
oneof [
ret_gen AddMeter;
ret_gen ModifyMeter;
ret_gen DeleteMeter
]
let arbitrary_meterFlagsMap =
arbitrary_bool >>= fun kbps ->
arbitrary_bool >>= fun pktps ->
arbitrary_bool >>= fun burst ->
arbitrary_bool >>= fun stats ->
ret_gen {
kbps;
pktps;
burst;
stats
}
let arbitrary =
arbitrary_command >>= fun command ->
arbitrary_meterFlagsMap >>= fun flags ->
arbitrary_uint32 >>= fun meter_id ->
list1 MeterBand.arbitrary >>= fun bands ->
ret_gen {
command;
flags;
meter_id;
bands
}
let marshal = MeterMod.marshal
let parse = MeterMod.parse
let to_string = MeterMod.to_string
let size_of = MeterMod.sizeof
end
module Hello = struct
open Gen
open OpenFlow0x04_Core
module Element = struct
open Gen
open OpenFlow0x04_Core
module VersionBitMap = struct
open Gen
open OpenFlow0x04_Core
type t = Hello.Element.VersionBitMap.t
let maxi = 300
let choose_int2 b =
choose_int (b,maxi)
let rec arbitrary_sorted n l acc=
match n with
| 0 -> (choose_int2 l >>= fun a ->
ret_gen( a::acc))
| n -> choose_int2 l >>= fun li ->
if li = maxi then
ret_gen (li::acc)
else
arbitrary_sorted (n-1) (li+1) (li::acc)
let arbitrary =
choose_int(1,30) >>= fun n ->
arbitrary_sorted n 0 [] >>= fun l ->
ret_gen l
let marshal = Hello.Element.VersionBitMap.marshal
let parse = Hello.Element.VersionBitMap.parse
let to_string = Hello.Element.VersionBitMap.to_string
let size_of = Hello.Element.VersionBitMap.sizeof
end
type t = Hello.Element.t
let arbitrary =
VersionBitMap.arbitrary >>= fun version ->
ret_gen (VersionBitMap version)
let marshal = Hello.Element.marshal
let parse = Hello.Element.parse
let to_string = Hello.Element.to_string
let size_of = Hello.Element.sizeof
end
type t = Hello.t
let arbitrary =
arbitrary_list Element.arbitrary >>= fun element ->
ret_gen element
let marshal = Hello.marshal
let parse = Hello.parse
let to_string = Hello.to_string
let size_of = Hello.sizeof
end
module FlowRemoved = struct
open Gen
open OpenFlow0x04_Core
type t = FlowRemoved.t
let arbitrary_reason =
oneof [
ret_gen FlowIdleTimeout;
ret_gen FlowHardTiemout;
ret_gen FlowDelete;
ret_gen FlowGroupDelete]
let arbitrary =
arbitrary_uint64 >>= fun cookie ->
arbitrary_uint16 >>= fun priority ->
arbitrary_reason >>= fun reason ->
arbitrary_uint8 >>= fun table_id ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
arbitrary_timeout >>= fun idle_timeout ->
arbitrary_timeout >>= fun hard_timeout ->
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun byte_count ->
OfpMatch.arbitrary >>= fun oxm ->
ret_gen { cookie; priority; reason; table_id; duration_sec; duration_nsec;
idle_timeout; hard_timeout; packet_count; byte_count; oxm }
let marshal = FlowRemoved.marshal
let parse = FlowRemoved.parse
let to_string = FlowRemoved.to_string
let size_of = FlowRemoved.sizeof
end
module AsyncConfig = struct
open Gen
open OpenFlow0x04_Core
type t = AsyncConfig.t
let arbitrary_packetInReasonMap =
arbitrary_bool >>= fun table_miss ->
arbitrary_bool >>= fun apply_action ->
arbitrary_bool >>= fun invalid_ttl ->
ret_gen { table_miss; apply_action; invalid_ttl }
let arbitrary_portStatusReasonMap =
arbitrary_bool >>= fun add ->
arbitrary_bool >>= fun delete ->
arbitrary_bool >>= fun modify ->
ret_gen { add; delete; modify }
let arbitrary_flowRemovedReasonMap =
arbitrary_bool >>= fun idle_timeout ->
arbitrary_bool >>= fun hard_timeout ->
arbitrary_bool >>= fun delete ->
arbitrary_bool >>= fun group_delete ->
ret_gen { idle_timeout; hard_timeout; delete; group_delete }
let arbitrary_mask arb =
arb >>= fun m_master ->
arb >>= fun m_slave ->
ret_gen { m_master; m_slave }
let arbitrary =
arbitrary_mask arbitrary_packetInReasonMap >>= fun packet_in ->
arbitrary_mask arbitrary_portStatusReasonMap >>= fun port_status ->
arbitrary_mask arbitrary_flowRemovedReasonMap >>= fun flow_removed ->
ret_gen { packet_in; port_status; flow_removed }
let marshal = AsyncConfig.marshal
let parse = AsyncConfig.parse
let to_string = AsyncConfig.to_string
let size_of = AsyncConfig.sizeof
end
module Error = struct
open Gen
open OpenFlow0x04_Core
type t = Error.t
let arbitrary_helloFailed =
oneof [
ret_gen HelloIncompatible;
ret_gen HelloPermError
]
let arbitrary_badRequest =
oneof [
ret_gen ReqBadVersion;
ret_gen ReqBadType;
ret_gen ReqBadMultipart;
ret_gen ReqBadExp;
ret_gen ReqBadExpType;
ret_gen ReqPermError;
ret_gen ReqBadLen;
ret_gen ReqBufferEmpty;
ret_gen ReqBufferUnknown;
ret_gen ReqBadTableId;
ret_gen ReqIsSlave;
ret_gen ReqBadPort;
ret_gen ReqBadPacket;
ret_gen ReqMultipartBufOverflow
]
let arbitrary_badAction =
oneof [
ret_gen ActBadType;
ret_gen ActBadLen;
ret_gen ActBadExp;
ret_gen ActBadExpType;
ret_gen ActBadOutPort;
ret_gen ActBadArg;
ret_gen ActPermError;
ret_gen ActTooMany;
ret_gen ActBadQueue;
ret_gen ActBadOutGroup;
ret_gen ActMatchInconsistent;
ret_gen ActUnsupportedOrder;
ret_gen ActBadTag;
ret_gen ActBadSetTyp;
ret_gen ActBadSetLen;
ret_gen ActBadSetArg
]
let arbitrary_badInstruction =
oneof [
ret_gen InstUnknownInst;
ret_gen InstBadTableId;
ret_gen InstUnsupInst;
ret_gen InstUnsupMeta;
ret_gen InstUnsupMetaMask;
ret_gen InstBadExp;
ret_gen InstBadExpTyp;
ret_gen InstBadLen;
ret_gen InstPermError
]
let arbitrary_badMatch =
oneof [
ret_gen MatBadTyp;
ret_gen MatBadLen;
ret_gen MatBadTag;
ret_gen MatBadDlAddrMask;
ret_gen MatBadNwAddrMask;
ret_gen MatBadWildcards;
ret_gen MatBadField;
ret_gen MatBadValue;
ret_gen MatBadMask;
ret_gen MatBadPrereq;
ret_gen MatDupField;
ret_gen MatPermError
]
let arbitrary_flowModFailed =
oneof [
ret_gen FlUnknown;
ret_gen FlTableFull;
ret_gen FlBadTableId;
ret_gen FlOverlap;
ret_gen FlPermError;
ret_gen FlBadTimeout;
ret_gen FlBadCommand;
ret_gen FlBadFlags
]
let arbitrary_groupModFailed =
oneof [
ret_gen GrGroupExists;
ret_gen GrInvalidGroup;
ret_gen GrWeightUnsupported;
ret_gen GrOutOfGroups;
ret_gen GrOutOfBuckets;
ret_gen GrChainingUnsupported;
ret_gen GrWatcHUnsupported;
ret_gen GrLoop;
ret_gen GrUnknownGroup;
ret_gen GrChainedGroup;
ret_gen GrBadTyp;
ret_gen GrBadCommand;
ret_gen GrBadBucket;
ret_gen GrBadWatch;
ret_gen GrPermError
]
let arbitrary_portModFailed =
oneof [
ret_gen PoBadPort;
ret_gen PoBadHwAddr;
ret_gen PoBadConfig;
ret_gen PoBadAdvertise;
ret_gen PoPermError
]
let arbitrary_tableModFailed =
oneof [
ret_gen TaBadTable;
ret_gen TaBadConfig;
ret_gen TaPermError
]
let arbitrary_queueOpFailed =
oneof [
ret_gen QuBadPort;
ret_gen QuBadQUeue;
ret_gen QuPermError
]
let arbitrary_switchConfigFailed =
oneof [
ret_gen ScBadFlags;
ret_gen ScBadLen;
ret_gen ScPermError
]
let arbitrary_roleReqFailed =
oneof [
ret_gen RoStale;
ret_gen RoUnsup;
ret_gen RoBadRole;
]
let arbitrary_meterModFailed =
oneof [
ret_gen MeUnknown;
ret_gen MeMeterExists;
ret_gen MeInvalidMeter;
ret_gen MeUnknownMeter;
ret_gen MeBadCommand;
ret_gen MeBadFlags;
ret_gen MeBadRate;
ret_gen MeBadBurst;
ret_gen MeBadBand;
ret_gen MeBadBandValue;
ret_gen MeOutOfMeters;
ret_gen MeOutOfBands
]
let arbitrary_tableFeatFailed =
oneof [
ret_gen TfBadTable;
ret_gen TfBadMeta;
ret_gen TfBadType;
ret_gen TfBadLen;
ret_gen TfBadArg;
ret_gen TfPermError
]
let arbitrary_exp =
arbitrary_uint16 >>= fun exp_typ ->
arbitrary_uint32 >>= fun exp_id ->
ret_gen {exp_typ; exp_id}
let arbitrary_err =
oneof [
arbitrary_helloFailed >>= (fun n -> ret_gen (HelloFailed n));
arbitrary_badRequest >>= (fun n -> ret_gen (BadRequest n));
arbitrary_badAction >>= (fun n -> ret_gen (BadAction n));
arbitrary_badInstruction >>= (fun n -> ret_gen (BadInstruction n));
arbitrary_badMatch >>= (fun n -> ret_gen (BadMatch n));
arbitrary_flowModFailed >>= (fun n -> ret_gen (FlowModFailed n));
arbitrary_groupModFailed >>= (fun n -> ret_gen (GroupModFailed n));
arbitrary_portModFailed >>= (fun n -> ret_gen (PortModFailed n));
arbitrary_tableModFailed >>= (fun n -> ret_gen (TableModFailed n));
arbitrary_queueOpFailed >>= (fun n -> ret_gen (QueueOpFailed n));
arbitrary_switchConfigFailed >>= (fun n -> ret_gen (SwitchConfigFailed n));
arbitrary_roleReqFailed >>= (fun n -> ret_gen (RoleReqFailed n));
arbitrary_meterModFailed >>= (fun n -> ret_gen (MeterModFailed n));
arbitrary_tableFeatFailed >>= (fun n -> ret_gen (TableFeatFailed n));
arbitrary_exp >>= (fun n -> ret_gen (ExperimenterFailed n));
]
let arbitrary_len =
(choose_int (64, 150)) >>= fun a ->
ret_gen a
let arbitrary_byte n =
(* construct an arbitrary byte of length n*)
arbitrary_stringN n >>= fun a ->
let byte = Cstruct.create n in
Cstruct.blit_from_string a 0 byte 0 n;
ret_gen (byte)
let arbitrary =
arbitrary_len >>= fun len ->
arbitrary_byte len >>= fun data ->
arbitrary_err >>= fun err ->
ret_gen {
Error.err = err;
Error.data = data}
let marshal = Error.marshal
let parse = Error.parse
let to_string = Error.to_string
let size_of = Error.sizeof
end
| null | https://raw.githubusercontent.com/frenetic-lang/ocaml-openflow/289ffb8a692cf32b8413cc58044aae9c151ddd44/quickcheck/Arbitrary_OpenFlow0x04.ml | ocaml | Use in cases where a `Controller` port is invalid input
construct an arbitrary byte of length n
buffered packet out don't have payload
construct an arbitrary byte of length n
construct an arbitrary byte of length n | open OpenFlow0x04
open OpenFlow0x04_Core
open Arbitrary_Base
open QuickCheck
module Gen = QuickCheck_gen
let sum (lst : int list) = List.fold_left (fun x y -> x + y) 0 lst
let arbitrary_32mask =
let open Gen in
(choose_int (1, 32)) >>= fun a ->
ret_gen (Int32.of_int a)
let arbitrary_128mask =
let open Gen in
(choose_int (1,64)) >>= fun a ->
(choose_int (0,64)) >>= fun b ->
ret_gen (Int64.of_int b,Int64.of_int a)
let arbitrary_64mask =
let open Gen in
(choose_int (1,64)) >>= fun a ->
ret_gen (Int64.of_int a)
let arbitrary_48mask =
let open Gen in
(choose_int (1,48)) >>= fun a ->
ret_gen (Int64.of_int a)
let arbitrary_12mask =
let open Gen in
(choose_int (1,12)) >>= fun a ->
ret_gen a
let arbitrary_16mask =
let open Gen in
(choose_int (1,16)) >>= fun a ->
ret_gen a
let arbitrary_masked arb arb_mask =
let open OpenFlow0x04_Core in
let open Gen in
frequency [
(1, arb >>= fun v -> ret_gen {OpenFlow0x04_Core.m_value = v; m_mask = None});
(3, arb >>= fun v ->
arb_mask >>= fun m -> ret_gen {OpenFlow0x04_Core.m_value = v; m_mask = Some m}) ]
let arbitrary_timeout =
let open OpenFlow0x04_Core in
let open Gen in
oneof [
ret_gen Permanent;
arbitrary_uint16 >>= (fun n -> ret_gen (ExpiresAfter n))
]
let fill_with_0 n=
String.make n '\000'
let arbitrary_stringl n=
let open Gen in
(choose_int (0,n)) >>= fun a ->
arbitrary_stringN a >>= fun str ->
ret_gen (str ^ (fill_with_0 (n-a)))
module type OpenFlow0x04_Arbitrary = sig
type t
type s
val arbitrary : t arbitrary
val to_string : t -> string
val parse : s -> t
val marshal : t -> s
end
module type OpenFlow0x04_ArbitraryCstruct = sig
type t
val arbitrary : t arbitrary
val to_string : t -> string
val parse : Cstruct.t -> t
val marshal : Cstruct.t -> t -> int
val size_of : t -> int
end
module OpenFlow0x04_Unsize(ArbC : OpenFlow0x04_ArbitraryCstruct) = struct
type t = ArbC.t
type s = Cstruct.t
let arbitrary = ArbC.arbitrary
let to_string = ArbC.to_string
let parse = ArbC.parse
let marshal m =
let bytes = Cstruct.of_bigarray Bigarray.(Array1.create char c_layout (ArbC.size_of m))
in ignore (ArbC.marshal bytes m); bytes
end
module PortDesc = struct
module PortFeatures = struct
type t = OpenFlow0x04_Core.portFeatures
type s = Int32.t
let arbitrary =
let open Gen in
let open PortFeatures in
arbitrary_bool >>= fun rate_10mb_hd ->
arbitrary_bool >>= fun rate_10mb_fd ->
arbitrary_bool >>= fun rate_100mb_hd ->
arbitrary_bool >>= fun rate_100mb_fd ->
arbitrary_bool >>= fun rate_1gb_hd ->
arbitrary_bool >>= fun rate_1gb_fd ->
arbitrary_bool >>= fun rate_10gb_fd ->
arbitrary_bool >>= fun rate_40gb_fd ->
arbitrary_bool >>= fun rate_100gb_fd ->
arbitrary_bool >>= fun rate_1tb_fd ->
arbitrary_bool >>= fun other ->
arbitrary_bool >>= fun copper ->
arbitrary_bool >>= fun fiber ->
arbitrary_bool >>= fun autoneg ->
arbitrary_bool >>= fun pause ->
arbitrary_bool >>= fun pause_asym ->
ret_gen {
rate_10mb_hd; rate_10mb_fd;
rate_100mb_hd; rate_100mb_fd;
rate_1gb_hd; rate_1gb_fd;
rate_10gb_fd; rate_40gb_fd;
rate_100gb_fd; rate_1tb_fd;
other; copper; fiber;
autoneg; pause; pause_asym
}
let to_string = PortFeatures.to_string
let marshal = PortFeatures.marshal
let parse = PortFeatures.parse
end
module PortState = struct
type t = OpenFlow0x04_Core.portState
type s = Int32.t
let arbitrary =
let open Gen in
let open PortState in
arbitrary_bool >>= fun link_down ->
arbitrary_bool >>= fun blocked ->
arbitrary_bool >>= fun live ->
ret_gen {
link_down;
blocked;
live
}
let to_string = PortState.to_string
let marshal = PortState.marshal
let parse = PortState.parse
end
module PortConfig = struct
type t = OpenFlow0x04_Core.portConfig
type s = Int32.t
let arbitrary =
let open Gen in
let open PortConfig in
arbitrary_bool >>= fun port_down ->
arbitrary_bool >>= fun no_recv ->
arbitrary_bool >>= fun no_fwd ->
arbitrary_bool >>= fun no_packet_in ->
ret_gen {
port_down;
no_recv;
no_fwd;
no_packet_in
}
let to_string = PortConfig.to_string
let marshal = PortConfig.marshal
let parse = PortConfig.parse
end
type t = OpenFlow0x04_Core.portDesc
let arbitrary =
let open Gen in
let open PortDesc in
arbitrary_uint32 >>= fun port_no ->
arbitrary_uint48 >>= fun hw_addr ->
arbitrary_stringN 16 >>= fun name ->
PortConfig.arbitrary >>= fun config ->
PortState.arbitrary >>= fun state ->
PortFeatures.arbitrary >>= fun curr ->
PortFeatures.arbitrary >>= fun advertised ->
PortFeatures.arbitrary >>= fun supported ->
PortFeatures.arbitrary >>= fun peer ->
arbitrary_uint32 >>= fun curr_speed ->
arbitrary_uint32 >>= fun max_speed ->
ret_gen {
port_no;
hw_addr;
name;
config;
state;
curr;
advertised;
supported;
peer;
curr_speed;
max_speed
}
let to_string = PortDesc.to_string
let parse = PortDesc.parse
let marshal = PortDesc.marshal
let size_of = PortDesc.sizeof
end
module PortStatus = struct
open Gen
type t = OpenFlow0x04_Core.portStatus
let arbitrary_reason =
oneof [
ret_gen PortAdd;
ret_gen PortDelete;
ret_gen PortModify
]
let arbitrary : t arbitrary =
let open PortStatus in
arbitrary_reason >>= fun reason ->
PortDesc.arbitrary >>= fun desc ->
ret_gen {
reason = reason;
desc = desc}
let to_string = PortStatus.to_string
let parse = PortStatus.parse
let marshal = PortStatus.marshal
let size_of = PortStatus.sizeof
end
module PseudoPort = struct
type s = int * (int option)
type t = PseudoPort.t
let arbitrary =
let open Gen in
let open OpenFlow0x04_Core in
oneof [
arbitrary_uint32 >>= (fun p -> ret_gen (PhysicalPort p));
ret_gen InPort;
ret_gen Table;
ret_gen Normal;
ret_gen Flood;
ret_gen AllPorts;
arbitrary_uint >>= (fun l -> ret_gen (Controller l));
ret_gen Local;
ret_gen Any
]
let arbitrary_nc =
let open Gen in
let open OpenFlow0x04_Core in
oneof [
arbitrary_uint32 >>= (fun p -> ret_gen (PhysicalPort p));
ret_gen InPort;
ret_gen Table;
ret_gen Normal;
ret_gen Flood;
ret_gen AllPorts;
ret_gen Local;
ret_gen Any
]
let to_string = PseudoPort.to_string
let parse (p, l) =
let l' = match l with
| None -> 0
| Some i -> i
in PseudoPort.make p l'
let marshal p =
let open OpenFlow0x04_Core in
let l = match p with
| Controller i -> Some i
| _ -> None
in (PseudoPort.marshal p, l)
let size_of = PseudoPort.size_of
end
module OfpMatch = struct
open Gen
type t = OpenFlow0x04_Core.oxmMatch
module Oxm = struct
type t = Oxm.t
let arbitrary =
let open Gen in
let open Oxm in
let arbitrary_dscp =
(choose_int (0,64)) >>= fun a ->
ret_gen a in
let arbitrary_ecn =
(choose_int (0,3)) >>= fun a ->
ret_gen a in
let arbitrary_24mask =
let open Gen in
(choose_int (1,24)) >>= fun a ->
ret_gen (Int32.of_int a) in
let arbitrary_uint24 =
arbitrary_uint16 >>= fun a ->
arbitrary_uint8 >>= fun b ->
let open Int32 in
let hi = shift_left (of_int a) 8 in
let lo = of_int b in
ret_gen (logor hi lo) in
let arbitrary_ipv6hdr =
arbitrary_bool >>= fun noext ->
arbitrary_bool >>= fun esp ->
arbitrary_bool >>= fun auth ->
arbitrary_bool >>= fun dest ->
arbitrary_bool >>= fun frac ->
arbitrary_bool >>= fun router ->
arbitrary_bool >>= fun hop ->
arbitrary_bool >>= fun unrep ->
arbitrary_bool >>= fun unseq ->
ret_gen {noext; esp; auth; dest; frac; router; hop; unrep; unseq } in
arbitrary_uint32 >>= fun portId ->
arbitrary_uint32 >>= fun portPhyId ->
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun oxmMetadata ->
arbitrary_uint16 >>= fun oxmEthType ->
arbitrary_masked arbitrary_uint48 arbitrary_48mask >>= fun oxmEthDst ->
arbitrary_masked arbitrary_uint48 arbitrary_48mask >>= fun oxmEthSrc ->
arbitrary_masked arbitrary_uint12 arbitrary_12mask >>= fun oxmVlanVId ->
arbitrary_uint8 >>= fun oxmVlanPcp ->
arbitrary_uint8 >>= fun oxmIPProto ->
arbitrary_dscp >>= fun oxmIPDscp ->
arbitrary_ecn >>= fun oxmIPEcn ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmIP4Src ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmIP4Dst ->
arbitrary_uint16 >>= fun oxmTCPSrc ->
arbitrary_uint16 >>= fun oxmTCPDst ->
arbitrary_uint16 >>= fun oxmARPOp ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmARPSpa ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmARPTpa ->
arbitrary_masked arbitrary_uint48 arbitrary_48mask >>= fun oxmARPSha ->
arbitrary_masked arbitrary_uint48 arbitrary_48mask >>= fun oxmARPTha ->
arbitrary_uint8 >>= fun oxmICMPType ->
arbitrary_uint8 >>= fun oxmICMPCode ->
arbitrary_uint32 >>= fun oxmMPLSLabel ->
arbitrary_uint8 >>= fun oxmMPLSTc ->
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun oxmTunnelId ->
arbitrary_masked arbitrary_uint128 arbitrary_128mask >>= fun oxmIPv6Src ->
arbitrary_masked arbitrary_uint128 arbitrary_128mask >>= fun oxmIPv6Dst ->
arbitrary_masked arbitrary_uint32 arbitrary_32mask >>= fun oxmIPv6FLabel ->
arbitrary_masked arbitrary_uint128 arbitrary_128mask >>= fun oxmIPv6NDTarget ->
arbitrary_masked arbitrary_uint24 arbitrary_24mask >>= fun oxmPBBIsid ->
arbitrary_masked arbitrary_ipv6hdr arbitrary_ipv6hdr >>= fun oxmIPv6ExtHdr ->
arbitrary_bool >>= fun oxmMPLSBos ->
arbitrary_uint16 >>= fun oxmUDPSrc ->
arbitrary_uint16 >>= fun oxmUDPDst ->
arbitrary_uint16 >>= fun oxmSCTPSrc ->
arbitrary_uint16 >>= fun oxmSCTPDst ->
arbitrary_uint8 >>= fun oxmICMPv6Type ->
arbitrary_uint8 >>= fun oxmICMPv6Code ->
arbitrary_uint48 >>= fun oxmIPv6NDSll ->
arbitrary_uint48 >>= fun oxmIPv6NDTll ->
oneof [
ret_gen (OxmInPort portId);
ret_gen (OxmInPhyPort portPhyId);
ret_gen (OxmMetadata oxmMetadata);
ret_gen (OxmEthType oxmEthType);
ret_gen (OxmEthDst oxmEthDst);
ret_gen (OxmEthSrc oxmEthSrc);
ret_gen (OxmVlanVId oxmVlanVId);
ret_gen (OxmVlanPcp oxmVlanPcp);
ret_gen (OxmIPProto oxmIPProto);
ret_gen (OxmIPDscp oxmIPDscp);
ret_gen (OxmIPEcn oxmIPEcn);
ret_gen (OxmIP4Src oxmIP4Src);
ret_gen (OxmIP4Dst oxmIP4Dst);
ret_gen (OxmTCPSrc oxmTCPSrc);
ret_gen (OxmTCPDst oxmTCPDst);
ret_gen (OxmARPOp oxmARPOp);
ret_gen (OxmARPSpa oxmARPSpa);
ret_gen (OxmARPTpa oxmARPTpa);
ret_gen (OxmARPSha oxmARPSha);
ret_gen (OxmARPTha oxmARPTha);
ret_gen (OxmICMPType oxmICMPType);
ret_gen (OxmICMPCode oxmICMPCode);
ret_gen (OxmMPLSLabel oxmMPLSLabel);
ret_gen (OxmMPLSTc oxmMPLSTc);
ret_gen (OxmTunnelId oxmTunnelId);
ret_gen (OxmUDPSrc oxmUDPSrc);
ret_gen (OxmUDPDst oxmUDPDst);
ret_gen (OxmSCTPSrc oxmSCTPSrc);
ret_gen (OxmSCTPDst oxmSCTPDst);
ret_gen (OxmIPv6Src oxmIPv6Src);
ret_gen (OxmIPv6Dst oxmIPv6Dst);
ret_gen (OxmIPv6FLabel oxmIPv6FLabel);
ret_gen (OxmICMPv6Type oxmICMPv6Type);
ret_gen (OxmICMPv6Code oxmICMPv6Code);
ret_gen (OxmIPv6NDTarget oxmIPv6NDTarget);
ret_gen (OxmIPv6NDSll oxmIPv6NDSll);
ret_gen (OxmIPv6NDTll oxmIPv6NDTll);
ret_gen (OxmMPLSBos oxmMPLSBos);
ret_gen (OxmPBBIsid oxmPBBIsid);
ret_gen (OxmIPv6ExtHdr oxmIPv6ExtHdr);
]
let marshal = Oxm.marshal
let to_string = Oxm.to_string
let size_of = Oxm.sizeof
let parse bits =
let p,_ = Oxm.parse bits in
p
end
module OxmHeader = struct
type t = OpenFlow0x04_Core.oxm
module Oxm = OpenFlow0x04.Oxm
let arbitrary =
let open Gen in
let open Oxm in
let ipv6hdr_nul = {noext = false; esp = false; auth = false; dest = false; frac = false; router = false; hop = false; unrep = false; unseq = false } in
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmMetadata ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmEthDst ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmEthSrc ->
arbitrary_masked (ret_gen 0) (ret_gen 0) >>= fun oxmVlanVId ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmIP4Src ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmIP4Dst ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmARPSpa ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmARPTpa ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmARPSha ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmARPTha ->
arbitrary_masked (ret_gen 0L) (ret_gen 0L) >>= fun oxmTunnelId ->
arbitrary_masked (ret_gen (0L,0L)) (ret_gen (0L,0L)) >>= fun oxmIPv6Src ->
arbitrary_masked (ret_gen (0L,0L)) (ret_gen (0L,0L)) >>= fun oxmIPv6Dst ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmIPv6FLabel ->
arbitrary_masked (ret_gen (0L,0L)) (ret_gen (0L,0L)) >>= fun oxmIPv6NDTarget ->
arbitrary_masked (ret_gen 0l) (ret_gen 0l) >>= fun oxmPBBIsid ->
arbitrary_masked (ret_gen ipv6hdr_nul) (ret_gen ipv6hdr_nul) >>= fun oxmIPv6ExtHdr ->
oneof [
ret_gen (OxmInPort 0l);
ret_gen (OxmInPhyPort 0l);
ret_gen (OxmMetadata oxmMetadata);
ret_gen (OxmEthType 0);
ret_gen (OxmEthDst oxmEthDst);
ret_gen (OxmEthSrc oxmEthSrc);
ret_gen (OxmVlanVId oxmVlanVId);
ret_gen (OxmVlanPcp 0);
ret_gen (OxmIPProto 0);
ret_gen (OxmIPDscp 0);
ret_gen (OxmIPEcn 0);
ret_gen (OxmIP4Src oxmIP4Src);
ret_gen (OxmIP4Dst oxmIP4Dst);
ret_gen (OxmTCPSrc 0);
ret_gen (OxmTCPDst 0);
ret_gen (OxmARPOp 0);
ret_gen (OxmARPSpa oxmARPSpa);
ret_gen (OxmARPTpa oxmARPTpa);
ret_gen (OxmARPSha oxmARPSha);
ret_gen (OxmARPTha oxmARPTha);
ret_gen (OxmICMPType 0);
ret_gen (OxmICMPCode 0);
ret_gen (OxmMPLSLabel 0l);
ret_gen (OxmMPLSTc 0);
ret_gen (OxmTunnelId oxmTunnelId);
ret_gen (OxmUDPSrc 0);
ret_gen (OxmUDPDst 0);
ret_gen (OxmSCTPSrc 0);
ret_gen (OxmSCTPDst 0);
ret_gen (OxmIPv6Src oxmIPv6Src);
ret_gen (OxmIPv6Dst oxmIPv6Dst);
ret_gen (OxmIPv6FLabel oxmIPv6FLabel);
ret_gen (OxmICMPv6Type 0);
ret_gen (OxmICMPv6Code 0);
ret_gen (OxmIPv6NDTarget oxmIPv6NDTarget);
ret_gen (OxmIPv6NDSll 0L);
ret_gen (OxmIPv6NDTll 0L);
ret_gen (OxmMPLSBos false);
ret_gen (OxmPBBIsid oxmPBBIsid);
ret_gen (OxmIPv6ExtHdr oxmIPv6ExtHdr);
]
let marshal = Oxm.marshal_header
let to_string = Oxm.field_name
let size_of = Oxm.sizeof
let parse bits =
let p,_ = Oxm.parse_header bits in
p
end
let arbitrary =
let open Gen in
let open OfpMatch in
arbitrary_list Oxm.arbitrary >>= fun ofpMatch ->
ret_gen ofpMatch
let marshal = OfpMatch.marshal
let parse bits=
let ofpMatch,_ = OfpMatch.parse bits in
ofpMatch
let to_string = OfpMatch.to_string
let size_of = OfpMatch.sizeof
end
module MeterBand = struct
type t = OpenFlow0x04_Core.meterBand
let arbitrary =
let open Gen in
let open OpenFlow0x04_Core in
arbitrary_uint32 >>= fun rate ->
arbitrary_uint32 >>= fun burst ->
oneof [
ret_gen (Drop (rate, burst));
arbitrary_uint8 >>= (fun p -> ret_gen (DscpRemark (rate,burst,p)));
arbitrary_uint32 >>= (fun p -> ret_gen (ExpMeter (rate,burst,p)))
]
let to_string = MeterBand.to_string
let marshal = MeterBand.marshal
let parse = MeterBand.parse
let size_of = MeterBand.sizeof
end
module Action = struct
type t = OpenFlow0x04_Core.action
let arbitrary =
let open Gen in
let open OpenFlow0x04_Core in
oneof [
PseudoPort.arbitrary >>= (fun p -> ret_gen (Output p));
arbitrary_uint32 >>= (fun p -> ret_gen (Group p));
ret_gen PopVlan;
ret_gen PushVlan;
ret_gen PopMpls;
ret_gen PushMpls;
ret_gen CopyTtlOut;
ret_gen CopyTtlIn;
ret_gen DecNwTtl;
ret_gen PushPbb;
ret_gen PopPbb;
ret_gen DecMplsTtl;
arbitrary_uint8 >>= (fun p -> ret_gen (SetNwTtl p));
arbitrary_uint8 >>= (fun p -> ret_gen (SetMplsTtl p));
arbitrary_uint32 >>= (fun p -> ret_gen (SetQueue p));
OfpMatch.Oxm.arbitrary >>= (fun p -> ret_gen (SetField p))
]
let to_string = Action.to_string
let marshal = Action.marshal
let parse = Action.parse
let size_of = Action.sizeof
end
module Instructions = struct
open Gen
type t = OpenFlow0x04_Core.instruction list
module Instruction = struct
type t = OpenFlow0x04_Core.instruction
let arbitrary =
let open Gen in
let open Instruction in
arbitrary_uint8 >>= fun tableid ->
arbitrary_uint32 >>= fun meter ->
arbitrary_uint32 >>= fun exp ->
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun wrMeta ->
arbitrary_list Action.arbitrary >>= fun wrAction ->
arbitrary_list Action.arbitrary >>= fun appAction ->
oneof [
ret_gen (GotoTable tableid);
ret_gen (WriteMetadata wrMeta);
ret_gen (WriteActions wrAction);
ret_gen (ApplyActions appAction);
ret_gen Clear;
ret_gen (Meter meter);
ret_gen (Experimenter exp);
]
let marshal = Instruction.marshal
let parse = Instruction.parse
let to_string = Instruction.to_string
let size_of = Instruction.sizeof
end
let arbitrary =
let open Gen in
let open Instructions in
arbitrary_list Instruction.arbitrary >>= fun ins ->
ret_gen ins
let marshal = Instructions.marshal
let parse = Instructions.parse
let to_string = Instructions.to_string
let size_of = Instructions.sizeof
end
module FlowMod = struct
open Gen
module FlowModCommand = struct
type t = OpenFlow0x04_Core.flowModCommand
let arbitrary =
let open Gen in
let open FlowModCommand in
oneof [
ret_gen AddFlow;
ret_gen ModFlow;
ret_gen ModStrictFlow;
ret_gen DeleteFlow;
ret_gen DeleteStrictFlow;
]
let to_string = FlowModCommand.to_string
let marshal = FlowModCommand.marshal
let parse = FlowModCommand.parse
end
type t = OpenFlow0x04_Core.flowMod
let arbitrary_flags =
arbitrary_bool >>= fun fmf_send_flow_rem ->
arbitrary_bool >>= fun fmf_check_overlap ->
arbitrary_bool >>= fun fmf_reset_counts ->
arbitrary_bool >>= fun fmf_no_pkt_counts ->
arbitrary_bool >>= fun fmf_no_byt_counts ->
ret_gen {
fmf_send_flow_rem;
fmf_check_overlap;
fmf_reset_counts;
fmf_no_pkt_counts;
fmf_no_byt_counts
}
let arbitrary_buffer_id =
arbitrary_uint32 >>= fun bid ->
oneof [
ret_gen None;
ret_gen (Some bid)
]
let arbitrary =
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun mfCookie ->
arbitrary_uint8 >>= fun mfTable_id ->
arbitrary_timeout >>= fun mfIdle_timeout ->
arbitrary_timeout >>= fun mfHard_timeout ->
arbitrary_uint16 >>= fun mfPriority ->
arbitrary_flags >>= fun mfFlags ->
arbitrary_buffer_id >>= fun mfBuffer_id ->
FlowModCommand.arbitrary >>= fun mfCommand ->
PseudoPort.arbitrary_nc >>= fun mfPort ->
oneof [ ret_gen None; ret_gen (Some mfPort)] >>= fun mfOut_port ->
arbitrary_uint32 >>= fun mfGroup ->
oneof [ ret_gen None; ret_gen (Some mfGroup)] >>= fun mfOut_group ->
OfpMatch.arbitrary >>= fun mfOfp_match ->
Instructions.arbitrary >>= fun mfInstructions ->
ret_gen {
mfCookie; mfTable_id;
mfCommand; mfIdle_timeout;
mfHard_timeout; mfPriority;
mfBuffer_id;
mfOut_port;
mfOut_group; mfFlags;
mfOfp_match; mfInstructions}
let marshal = FlowMod.marshal
let parse = FlowMod.parse
let to_string = FlowMod.to_string
let size_of = FlowMod.sizeof
end
module Bucket = struct
open Gen
open OpenFlow0x04_Core
type t = OpenFlow0x04_Core.bucket
let arbitrary_option =
frequency [
(1, ret_gen None);
(5, arbitrary_uint32 >>= (fun v -> ret_gen (Some v)))
]
let no_output act =
match act with
| Output _ -> false
| _ -> true
let arbitrary =
arbitrary_uint16 >>= fun bu_weight ->
arbitrary_option >>= fun bu_watch_port ->
arbitrary_option >>= fun bu_watch_group ->
list1 (such_that no_output Action.arbitrary) >>= fun bu_actions ->
ret_gen {
bu_weight;
bu_watch_port;
bu_watch_group;
bu_actions
}
let marshal = Bucket.marshal
let parse = Bucket.parse
let to_string = Bucket.to_string
let size_of = Bucket.sizeof
end
module GroupMod = struct
open Gen
open OpenFlow0x04_Core
type t = GroupMod.t
let arbitrary_typ =
oneof [
ret_gen All;
ret_gen Select;
ret_gen Indirect;
ret_gen FF
]
let arbitrary =
arbitrary_typ >>= fun typ ->
arbitrary_uint32 >>= fun gid ->
arbitrary_list Bucket.arbitrary >>= fun buckets ->
oneof [
ret_gen (AddGroup (typ, gid, buckets));
ret_gen (DeleteGroup (typ, gid));
ret_gen (ModifyGroup (typ, gid, buckets))
]
let marshal = GroupMod.marshal
let parse = GroupMod.parse
let to_string = GroupMod.to_string
let size_of = GroupMod.sizeof
end
module MultipartReq = struct
open Gen
open OpenFlow0x04_Core
module TableFeature = struct
module TableFeatureProp = struct
type t = TableFeatureProp.t
let arbitrary_ins =
oneof [
ret_gen GotoTableHdr;
ret_gen ApplyActionsHdr;
ret_gen WriteActionsHdr;
ret_gen WriteMetadataHdr;
ret_gen ClearHdr;
ret_gen MeterHdr;
arbitrary_uint32 >>= (fun n -> ret_gen (ExperimenterHdr n))
]
let arbitrary_act =
oneof [
ret_gen OutputHdr;
ret_gen GroupHdr;
ret_gen PopVlanHdr;
ret_gen PushVlanHdr;
ret_gen PopMplsHdr;
ret_gen PushMplsHdr;
ret_gen SetFieldHdr;
ret_gen CopyTtlOutHdr;
ret_gen CopyTtlInHdr;
ret_gen SetNwTtlHdr;
ret_gen DecNwTtlHdr;
ret_gen PushPbbHdr;
ret_gen PopPbbHdr;
ret_gen SetMplsTtlHdr;
ret_gen DecMplsTtlHdr;
ret_gen SetQueueHdr;
arbitrary_uint32 >>= (fun n -> ret_gen (ExperimenterAHdr n))
]
let arbitrary =
oneof [
list1 arbitrary_ins >>= (fun n -> ret_gen (TfpInstruction n));
list1 arbitrary_ins >>= (fun n -> ret_gen (TfpInstructionMiss n));
arbitrary_list arbitrary_act >>= (fun n -> ret_gen (TfpWriteAction n));
arbitrary_list arbitrary_act >>= (fun n -> ret_gen (TfpWriteActionMiss n));
arbitrary_list arbitrary_act >>= (fun n -> ret_gen (TfpApplyAction n));
arbitrary_list arbitrary_act >>= (fun n -> ret_gen (TfpApplyActionMiss n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpMatch n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpWildcard n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpWriteSetField n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpWriteSetFieldMiss n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpApplySetField n));
arbitrary_list OfpMatch.OxmHeader.arbitrary >>= (fun n -> ret_gen (TfpApplySetFieldMiss n))
]
let marshal = TableFeatureProp.marshal
let parse = TableFeatureProp.parse
let to_string = TableFeatureProp.to_string
let size_of = TableFeatureProp.sizeof
end
type t = TableFeature.t
let arbitrary_config =
ret_gen Deprecated
let calc_length tfp =
sizeof_ofp_table_feature = 64
ret_gen (64+sum (List.map TableFeatureProp.size_of tfp))
let arbitrary =
arbitrary_uint8 >>= fun table_id ->
arbitrary_stringN 32 >>= fun name ->
arbitrary_uint64 >>= fun metadata_match ->
arbitrary_uint64 >>= fun metadata_write ->
arbitrary_config >>= fun config ->
arbitrary_uint32 >>= fun max_entries ->
list1 TableFeatureProp.arbitrary >>= fun feature_prop ->
calc_length feature_prop>>= fun length ->
ret_gen {
length;
table_id;
name;
metadata_match;
metadata_write;
config;
max_entries;
feature_prop
}
let marshal = TableFeature.marshal
let parse = TableFeature.parse
let to_string = TableFeature.to_string
let size_of = TableFeature.sizeof
end
module FlowRequest = struct
type t = FlowRequest.t
let arbitrary =
arbitrary_uint8 >>= fun fr_table_id ->
arbitrary_uint32 >>= fun fr_out_port ->
arbitrary_uint32 >>= fun fr_out_group ->
arbitrary_masked arbitrary_uint64 arbitrary_64mask >>= fun fr_cookie ->
OfpMatch.arbitrary >>= fun fr_match ->
ret_gen {
fr_table_id;
fr_out_port;
fr_out_group;
fr_cookie;
fr_match
}
let marshal = FlowRequest.marshal
let parse = FlowRequest.parse
let to_string = FlowRequest.to_string
let size_of = FlowRequest.sizeof
end
module QueueRequest = struct
type t = QueueRequest.t
let arbitrary =
arbitrary_uint32 >>= fun port_number ->
arbitrary_uint32 >>= fun queue_id ->
ret_gen {
port_number;
queue_id
}
let marshal = QueueRequest.marshal
let parse = QueueRequest.parse
let to_string = QueueRequest.to_string
let size_of = QueueRequest.sizeof
end
type t = MultipartReq.t
let arbitrary_option =
frequency [
(1, ret_gen None);
(3, list1 TableFeature.arbitrary >>= (fun v -> ret_gen (Some v)))
]
let arbitrary_type =
oneof [
ret_gen SwitchDescReq;
ret_gen PortsDescReq;
FlowRequest.arbitrary >>= (fun n -> ret_gen (FlowStatsReq n));
FlowRequest.arbitrary >>= (fun n -> ret_gen (AggregFlowStatsReq n));
ret_gen TableStatsReq;
arbitrary_uint32 >>= (fun n -> ret_gen (PortStatsReq n));
QueueRequest.arbitrary >>= (fun n -> ret_gen (QueueStatsReq n));
arbitrary_uint32 >>= (fun n -> ret_gen (GroupStatsReq n));
ret_gen GroupDescReq;
ret_gen GroupFeatReq;
arbitrary_uint32 >>= (fun n -> ret_gen (MeterStatsReq n));
arbitrary_uint32 >>= (fun n -> ret_gen (MeterConfReq n));
ret_gen MeterFeatReq;
arbitrary_option >>= (fun n -> ret_gen (TableFeatReq n));
]
let arbitrary =
arbitrary_bool >>= fun mpr_flags ->
arbitrary_type >>= fun mpr_type ->
ret_gen {
mpr_type;
mpr_flags
}
let marshal = MultipartReq.marshal
let parse = MultipartReq.parse
let to_string = MultipartReq.to_string
let size_of = MultipartReq.sizeof
end
module MultipartReply = struct
open Gen
open OpenFlow0x04_Core
module FlowStats = struct
type t = FlowStats.t
let arbitrary_flags =
arbitrary_bool >>= fun fmf_send_flow_rem ->
arbitrary_bool >>= fun fmf_check_overlap ->
arbitrary_bool >>= fun fmf_reset_counts ->
arbitrary_bool >>= fun fmf_no_pkt_counts ->
arbitrary_bool >>= fun fmf_no_byt_counts ->
ret_gen {
fmf_send_flow_rem;
fmf_check_overlap;
fmf_reset_counts;
fmf_no_pkt_counts;
fmf_no_byt_counts
}
let arbitrary =
Instructions.arbitrary >>= fun instructions ->
arbitrary_uint8 >>= fun table_id ->
list1 OfpMatch.Oxm.arbitrary >>= fun ofp_match ->
arbitrary_uint64 >>= fun byte_count ->
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun cookie ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
arbitrary_uint16 >>= fun priority ->
arbitrary_timeout >>= fun idle_timeout ->
arbitrary_timeout >>= fun hard_timeout ->
arbitrary_flags >>= fun flags ->
ret_gen { table_id
; duration_sec
; duration_nsec
; priority
; idle_timeout
; hard_timeout
; flags
; cookie
; packet_count
; byte_count
; ofp_match
; instructions}
let marshal = FlowStats.marshal
let parse = FlowStats.parse
let to_string = FlowStats.to_string
let size_of = FlowStats.sizeof
end
module AggregateStats = struct
type t = AggregateStats.t
let arbitrary =
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun byte_count ->
arbitrary_uint32 >>= fun flow_count ->
ret_gen {
packet_count;
byte_count;
flow_count
}
let marshal = AggregateStats.marshal
let parse = AggregateStats.parse
let to_string = AggregateStats.to_string
let size_of = AggregateStats.sizeof
end
module TableStats = struct
type t = TableStats.t
let arbitrary =
arbitrary_uint8 >>= fun table_id ->
arbitrary_uint32 >>= fun active_count ->
arbitrary_uint64 >>= fun lookup_count ->
arbitrary_uint64 >>= fun matched_count ->
ret_gen {
table_id;
active_count;
lookup_count;
matched_count
}
let marshal = TableStats.marshal
let parse = TableStats.parse
let to_string = TableStats.to_string
let size_of = TableStats.sizeof
end
module PortStats = struct
type t = PortStats.t
let arbitrary =
arbitrary_uint32 >>= fun psPort_no ->
arbitrary_uint64 >>= fun rx_packets ->
arbitrary_uint64 >>= fun tx_packets ->
arbitrary_uint64 >>= fun rx_bytes ->
arbitrary_uint64 >>= fun tx_bytes ->
arbitrary_uint64 >>= fun rx_dropped ->
arbitrary_uint64 >>= fun tx_dropped ->
arbitrary_uint64 >>= fun rx_errors ->
arbitrary_uint64 >>= fun tx_errors ->
arbitrary_uint64 >>= fun rx_frame_err ->
arbitrary_uint64 >>= fun rx_over_err ->
arbitrary_uint64 >>= fun rx_crc_err ->
arbitrary_uint64 >>= fun collisions ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
ret_gen {
psPort_no;
rx_packets;
tx_packets;
rx_bytes;
tx_bytes;
rx_dropped;
tx_dropped;
rx_errors;
tx_errors;
rx_frame_err;
rx_over_err;
rx_crc_err;
collisions;
duration_sec;
duration_nsec
}
let marshal = PortStats.marshal
let parse = PortStats.parse
let to_string = PortStats.to_string
let size_of = PortStats.sizeof
end
module SwitchDescriptionReply = struct
type t = SwitchDescriptionReply.t
let arbitrary =
arbitrary_stringl 256 >>= fun mfr_desc ->
arbitrary_stringl 256 >>= fun hw_desc ->
arbitrary_stringl 256 >>= fun sw_desc ->
arbitrary_stringl 32 >>= fun serial_num ->
ret_gen {
mfr_desc;
hw_desc;
sw_desc;
serial_num
}
let marshal = SwitchDescriptionReply.marshal
let parse = SwitchDescriptionReply.parse
let to_string = SwitchDescriptionReply.to_string
let size_of = SwitchDescriptionReply.sizeof
end
module QueueStats = struct
type t = QueueStats.t
let arbitrary =
arbitrary_uint32 >>= fun qsPort_no ->
arbitrary_uint32 >>= fun queue_id ->
arbitrary_uint64 >>= fun tx_bytes ->
arbitrary_uint64 >>= fun tx_packets ->
arbitrary_uint64 >>= fun tx_errors ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
ret_gen {
qsPort_no;
queue_id;
tx_bytes;
tx_packets;
tx_errors;
duration_sec;
duration_nsec
}
let marshal = QueueStats.marshal
let parse = QueueStats.parse
let to_string = QueueStats.to_string
let size_of = QueueStats.sizeof
end
module GroupStats = struct
module BucketStats = struct
type t = GroupStats.BucketStats.t
let arbitrary =
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun byte_count ->
ret_gen {packet_count; byte_count}
let marshal = GroupStats.BucketStats.marshal
let parse = GroupStats.BucketStats.parse
let to_string = GroupStats.BucketStats.to_string
let size_of = GroupStats.BucketStats.sizeof
end
type t = GroupStats.t
let calc_length bs =
sizeof_ofp_group_stats = 40
ret_gen (40+(sum (List.map BucketStats.size_of bs)))
let arbitrary =
arbitrary_uint32 >>= fun group_id ->
arbitrary_uint32 >>= fun ref_count ->
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun byte_count ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
list1 BucketStats.arbitrary >>= fun bucket_stats ->
calc_length bucket_stats >>= fun length ->
ret_gen {
length;
group_id;
ref_count;
packet_count;
byte_count;
duration_sec;
duration_nsec;
bucket_stats}
let marshal = GroupStats.marshal
let parse = GroupStats.parse
let to_string = GroupStats.to_string
let size_of = GroupStats.sizeof
end
module GroupDesc = struct
type t = GroupDesc.t
let arbitrary_groupTyp =
oneof [
ret_gen All;
ret_gen Select;
ret_gen Indirect;
ret_gen FF]
let calc_length bucket =
ofp_group_desc = 8
ret_gen (8+ sum (List.map Bucket.size_of bucket))
let arbitrary =
arbitrary_uint32 >>= fun group_id ->
arbitrary_groupTyp >>= fun typ ->
list1 Bucket.arbitrary >>= fun bucket ->
calc_length bucket>>= fun length ->
ret_gen {
length;
typ;
group_id;
bucket
}
let marshal = GroupDesc.marshal
let parse = GroupDesc.parse
let to_string = GroupDesc.to_string
let size_of = GroupDesc.sizeof
end
module GroupFeatures = struct
type t = GroupFeatures.t
let arbitrary_groupTypeMap =
arbitrary_bool >>= fun all ->
arbitrary_bool >>= fun select ->
arbitrary_bool >>= fun indirect ->
arbitrary_bool >>= fun ff ->
ret_gen {
all;
select;
indirect;
ff
}
let arbitrary_groupCapabilities =
arbitrary_bool >>= fun select_weight ->
arbitrary_bool >>= fun select_liveness ->
arbitrary_bool >>= fun chaining ->
arbitrary_bool >>= fun chaining_checks ->
ret_gen {
select_weight;
select_liveness;
chaining;
chaining_checks
}
let arbitrary_actionTypeMap =
arbitrary_bool >>= fun output ->
arbitrary_bool >>= fun copy_ttl_out ->
arbitrary_bool >>= fun copy_ttl_in ->
arbitrary_bool >>= fun set_mpls_ttl ->
arbitrary_bool >>= fun dec_mpls_ttl ->
arbitrary_bool >>= fun push_vlan ->
arbitrary_bool >>= fun pop_vlan ->
arbitrary_bool >>= fun push_mpls ->
arbitrary_bool >>= fun pop_mpls ->
arbitrary_bool >>= fun set_queue ->
arbitrary_bool >>= fun group ->
arbitrary_bool >>= fun set_nw_ttl ->
arbitrary_bool >>= fun dec_nw_ttl ->
arbitrary_bool >>= fun set_field ->
arbitrary_bool >>= fun push_pbb ->
arbitrary_bool >>= fun pop_pbb ->
ret_gen {
output;
copy_ttl_out;
copy_ttl_in;
set_mpls_ttl;
dec_mpls_ttl;
push_vlan;
pop_vlan;
push_mpls;
pop_mpls;
set_queue;
group;
set_nw_ttl;
dec_nw_ttl;
set_field;
push_pbb;
pop_pbb
}
let arbitrary =
arbitrary_groupTypeMap >>= fun typ ->
arbitrary_groupCapabilities >>= fun capabilities ->
arbitrary_uint32 >>= fun max_groups_all ->
arbitrary_uint32 >>= fun max_groups_select ->
arbitrary_uint32 >>= fun max_groups_indirect ->
arbitrary_uint32 >>= fun max_groups_ff ->
arbitrary_actionTypeMap >>= fun actions_all ->
arbitrary_actionTypeMap >>= fun actions_select ->
arbitrary_actionTypeMap >>= fun actions_indirect ->
arbitrary_actionTypeMap >>= fun actions_ff ->
ret_gen {
typ;
capabilities;
max_groups_all;
max_groups_select;
max_groups_indirect;
max_groups_ff;
actions_all;
actions_select;
actions_indirect;
actions_ff
}
let marshal = GroupFeatures.marshal
let parse = GroupFeatures.parse
let to_string = GroupFeatures.to_string
let size_of = GroupFeatures.sizeof
end
module MeterStats = struct
type t = MeterStats.t
let calc_length band =
sizeof_ofp_meter_stats = 40
ret_gen (40+(List.length band)*16)
let arbitrary_meterBandStats =
arbitrary_uint64 >>= fun packet_band_count ->
arbitrary_uint64 >>= fun byte_band_count ->
ret_gen { packet_band_count; byte_band_count }
let arbitrary =
arbitrary_uint32 >>= fun meter_id ->
arbitrary_uint32 >>= fun flow_count ->
arbitrary_uint64 >>= fun packet_in_count ->
arbitrary_uint64 >>= fun byte_in_count ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
list1 arbitrary_meterBandStats >>= fun band ->
calc_length band >>= fun len ->
ret_gen {
meter_id;
len;
flow_count;
packet_in_count;
byte_in_count;
duration_sec;
duration_nsec;
band
}
let marshal = MeterStats.marshal
let parse = MeterStats.parse
let to_string = MeterStats.to_string
let size_of = MeterStats.sizeof
end
module MeterConfig = struct
type t = MeterConfig.t
let arbitrary_meterFlagsMap =
arbitrary_bool >>= fun kbps ->
arbitrary_bool >>= fun pktps ->
arbitrary_bool >>= fun burst ->
arbitrary_bool >>= fun stats ->
ret_gen {
kbps;
pktps;
burst;
stats
}
let calc_length bands =
sizeof_ofp_meter_config = 8
ret_gen (8 + sum (List.map MeterBand.size_of bands))
let arbitrary =
arbitrary_meterFlagsMap >>= fun flags ->
arbitrary_uint32 >>= fun meter_id ->
list1 MeterBand.arbitrary >>= fun bands ->
calc_length bands >>= fun length ->
ret_gen {
length;
flags;
meter_id;
bands
}
let marshal = MeterConfig.marshal
let parse = MeterConfig.parse
let to_string = MeterConfig.to_string
let size_of = MeterConfig.sizeof
end
module MeterFeatures = struct
type t = MeterFeatures.t
let arbitrary_meterBandMaps =
arbitrary_bool >>= fun drop ->
arbitrary_bool >>= fun dscpRemark ->
ret_gen {
drop;
dscpRemark }
let arbitrary_meterFlagsMap =
arbitrary_bool >>= fun kbps ->
arbitrary_bool >>= fun pktps ->
arbitrary_bool >>= fun burst ->
arbitrary_bool >>= fun stats ->
ret_gen {
kbps;
pktps;
burst;
stats
}
let arbitrary =
arbitrary_uint32 >>= fun max_meter ->
arbitrary_meterBandMaps >>= fun band_typ ->
arbitrary_meterFlagsMap >>= fun capabilities ->
arbitrary_uint8 >>= fun max_band ->
arbitrary_uint8 >>= fun max_color ->
ret_gen {
max_meter;
band_typ;
capabilities;
max_band;
max_color
}
let marshal = MeterFeatures.marshal
let parse = MeterFeatures.parse
let to_string = MeterFeatures.to_string
let size_of = MeterFeatures.sizeof
end
type t = MultipartReply.t
let arbitrary =
arbitrary_bool >>= fun flags ->
oneof [
list1 PortDesc.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (PortsDescReply n); mpreply_flags = flags});
SwitchDescriptionReply.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (SwitchDescReply n); mpreply_flags = flags});
list1 FlowStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (FlowStatsReply n); mpreply_flags = flags});
AggregateStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (AggregateReply n); mpreply_flags = flags});
list1 TableStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (TableReply n); mpreply_flags = flags});
list1 PortStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (PortStatsReply n); mpreply_flags = flags});
list1 QueueStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (QueueStatsReply n); mpreply_flags = flags});
list1 GroupStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (GroupStatsReply n); mpreply_flags = flags});
GroupFeatures.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (GroupFeaturesReply n); mpreply_flags = flags});
list1 GroupDesc.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (GroupDescReply n); mpreply_flags = flags});
list1 MeterStats.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (MeterReply n); mpreply_flags = flags});
list1 MeterConfig.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (MeterConfig n); mpreply_flags = flags});
MeterFeatures.arbitrary >>= (fun n -> ret_gen {mpreply_typ = (MeterFeaturesReply n); mpreply_flags = flags});
]
let marshal = MultipartReply.marshal
let parse = MultipartReply.parse
let to_string = MultipartReply.to_string
let size_of = MultipartReply.sizeof
end
module PacketOut = struct
open Gen
open OpenFlow0x04_Core
type t = PacketOut.t
let arbitrary_len =
(choose_int (24, 1500)) >>= fun a ->
ret_gen a
let arbitrary_byte n =
arbitrary_stringN n >>= fun a ->
let byte = Cstruct.create n in
Cstruct.blit_from_string a 0 byte 0 n;
ret_gen (byte)
let arbitrary_pay byte =
frequency [
(1, ret_gen (NotBuffered byte));
(3, arbitrary_uint32 >>= fun bid ->
ret_gen (Buffered (bid,byte)))
]
let arbitrary_port_id =
frequency [
(1, ret_gen None);
(9, arbitrary_uint32 >>= fun port_id ->
ret_gen (Some port_id))
]
let arbitrary =
arbitrary_list Action.arbitrary >>= fun po_actions ->
arbitrary_len >>= fun len ->
arbitrary_byte len >>= fun byte ->
arbitrary_pay byte >>= fun po_payload ->
arbitrary_port_id >>= fun po_port_id ->
ret_gen {
po_payload;
po_port_id;
po_actions
}
let parse = PacketOut.parse
let marshal = PacketOut.marshal
let to_string = PacketOut.to_string
let size_of = PacketOut.sizeof
end
module PacketIn = struct
open Gen
open OpenFlow0x04_Core
type t = OpenFlow0x04_Core.packetIn
let arbitrary_len =
(choose_int (24, 1500)) >>= fun a ->
ret_gen a
let arbitrary_byte n =
arbitrary_stringN n >>= fun a ->
let byte = Cstruct.create n in
Cstruct.blit_from_string a 0 byte 0 n;
ret_gen (byte)
let arbitrary_reason =
oneof [
ret_gen (OpenFlow0x04_Core.NoMatch);
ret_gen (OpenFlow0x04_Core.ExplicitSend);
ret_gen (OpenFlow0x04_Core.InvalidTTL)
]
let arbitrary_pay byte =
frequency [
(1, ret_gen (NotBuffered byte));
(3, arbitrary_uint32 >>= fun bid ->
ret_gen (Buffered (bid,byte)))
]
let arbitrary =
arbitrary_len >>= fun pi_total_len ->
arbitrary_reason >>= fun pi_reason ->
arbitrary_uint8 >>= fun pi_table_id ->
arbitrary_uint64 >>= fun pi_cookie ->
OfpMatch.arbitrary >>= fun pi_ofp_match ->
arbitrary_byte pi_total_len >>= fun byte ->
arbitrary_pay byte >>= fun pi_payload ->
ret_gen {
pi_total_len;
pi_reason;
pi_table_id;
pi_cookie;
pi_ofp_match;
pi_payload
}
let marshal = PacketIn.marshal
let parse = PacketIn.parse
let to_string = PacketIn.to_string
let size_of = PacketIn.sizeof
end
module RoleRequest = struct
open Gen
open OpenFlow0x04_Core
type t = OpenFlow0x04_Core.roleRequest
let arbitrary_role =
oneof [
ret_gen NoChangeRole;
ret_gen EqualRole;
ret_gen MasterRole;
ret_gen SlaveRole
]
let arbitrary =
arbitrary_role >>= fun role ->
arbitrary_uint64 >>= fun generation_id ->
ret_gen { role; generation_id }
let marshal = RoleRequest.marshal
let parse = RoleRequest.parse
let to_string = RoleRequest.to_string
let size_of = RoleRequest.sizeof
end
module QueueDesc = struct
open Gen
open OpenFlow0x04_Core
module QueueProp = struct
open Gen
open OpenFlow0x04_Core
type t = QueueDesc.QueueProp.t
let arbitrary_rate =
frequency [
(1, ret_gen Disabled);
(10, choose_int (0,1000) >>= fun a ->
ret_gen (Rate a))
]
let arbitrary =
arbitrary_rate >>= fun min_rate ->
arbitrary_rate >>= fun max_rate ->
arbitrary_uint32 >>= fun exp_id ->
oneof [
ret_gen (MinRateProp min_rate);
ret_gen (MaxRateProp max_rate);
ret_gen (ExperimenterProp exp_id)
]
let marshal = QueueDesc.QueueProp.marshal
let parse = QueueDesc.QueueProp.parse
let to_string = QueueDesc.QueueProp.to_string
let size_of = QueueDesc.QueueProp.sizeof
end
type t = QueueDesc.t
let calc_length prop =
sizeof_ofp_packet_queue = 16
ret_gen (16+sum (List.map QueueProp.size_of prop))
let arbitrary =
arbitrary_uint32 >>= fun queue_id ->
arbitrary_uint32 >>= fun port ->
arbitrary_list QueueProp.arbitrary >>= fun properties ->
calc_length properties >>= fun len ->
ret_gen { queue_id; port; len; properties}
let marshal = QueueDesc.marshal
let parse = QueueDesc.parse
let to_string = QueueDesc.to_string
let size_of = QueueDesc.sizeof
end
module QueueConfReq = struct
open Gen
open OpenFlow0x04_Core
type t = QueueConfReq.t
let arbitrary =
arbitrary_uint32 >>= fun port ->
ret_gen {port}
let marshal = QueueConfReq.marshal
let parse = QueueConfReq.parse
let to_string = QueueConfReq.to_string
let size_of = QueueConfReq.sizeof
end
module QueueConfReply = struct
open Gen
open OpenFlow0x04_Core
type t = QueueConfReply.t
let arbitrary =
arbitrary_uint32 >>= fun port ->
arbitrary_list QueueDesc.arbitrary >>= fun queues ->
ret_gen {port; queues}
let marshal = QueueConfReply.marshal
let parse = QueueConfReply.parse
let to_string = QueueConfReply.to_string
let size_of = QueueConfReply.sizeof
end
module SwitchConfig = struct
open Gen
open OpenFlow0x04_Core
type t = SwitchConfig.t
let arbitrary_flags =
oneof [
ret_gen NormalFrag;
ret_gen DropFrag;
ret_gen ReasmFrag;
ret_gen MaskFrag
]
let arbitrary =
arbitrary_flags >>= fun flags ->
arbitrary_uint16 >>= fun miss_send_len ->
ret_gen { flags; miss_send_len}
let marshal = SwitchConfig.marshal
let parse = SwitchConfig.parse
let to_string = SwitchConfig.to_string
let size_of = SwitchConfig.sizeof
end
module TableMod = struct
open Gen
open OpenFlow0x04_Core
type t = TableMod.t
let arbitrary_config =
ret_gen Deprecated
let arbitrary =
arbitrary_uint8 >>= fun table_id ->
arbitrary_config >>= fun config ->
ret_gen { table_id; config }
let marshal = TableMod.marshal
let parse = TableMod.parse
let to_string = TableMod.to_string
let size_of = TableMod.sizeof
end
module PortMod = struct
open Gen
open OpenFlow0x04_Core
type t = PortMod.t
let arbitrary =
arbitrary_uint32 >>= fun mpPortNo ->
arbitrary_uint48 >>= fun mpHw_addr ->
PortDesc.PortConfig.arbitrary >>= fun mpConfig ->
PortDesc.PortConfig.arbitrary >>= fun mpMask ->
PortDesc.PortState.arbitrary >>= fun mpAdvertise ->
ret_gen { mpPortNo; mpHw_addr; mpConfig; mpMask; mpAdvertise}
let marshal = PortMod.marshal
let parse = PortMod.parse
let to_string = PortMod.to_string
let size_of = PortMod.sizeof
end
module MeterMod = struct
open Gen
open OpenFlow0x04_Core
type t = MeterMod.t
let arbitrary_command =
oneof [
ret_gen AddMeter;
ret_gen ModifyMeter;
ret_gen DeleteMeter
]
let arbitrary_meterFlagsMap =
arbitrary_bool >>= fun kbps ->
arbitrary_bool >>= fun pktps ->
arbitrary_bool >>= fun burst ->
arbitrary_bool >>= fun stats ->
ret_gen {
kbps;
pktps;
burst;
stats
}
let arbitrary =
arbitrary_command >>= fun command ->
arbitrary_meterFlagsMap >>= fun flags ->
arbitrary_uint32 >>= fun meter_id ->
list1 MeterBand.arbitrary >>= fun bands ->
ret_gen {
command;
flags;
meter_id;
bands
}
let marshal = MeterMod.marshal
let parse = MeterMod.parse
let to_string = MeterMod.to_string
let size_of = MeterMod.sizeof
end
module Hello = struct
open Gen
open OpenFlow0x04_Core
module Element = struct
open Gen
open OpenFlow0x04_Core
module VersionBitMap = struct
open Gen
open OpenFlow0x04_Core
type t = Hello.Element.VersionBitMap.t
let maxi = 300
let choose_int2 b =
choose_int (b,maxi)
let rec arbitrary_sorted n l acc=
match n with
| 0 -> (choose_int2 l >>= fun a ->
ret_gen( a::acc))
| n -> choose_int2 l >>= fun li ->
if li = maxi then
ret_gen (li::acc)
else
arbitrary_sorted (n-1) (li+1) (li::acc)
let arbitrary =
choose_int(1,30) >>= fun n ->
arbitrary_sorted n 0 [] >>= fun l ->
ret_gen l
let marshal = Hello.Element.VersionBitMap.marshal
let parse = Hello.Element.VersionBitMap.parse
let to_string = Hello.Element.VersionBitMap.to_string
let size_of = Hello.Element.VersionBitMap.sizeof
end
type t = Hello.Element.t
let arbitrary =
VersionBitMap.arbitrary >>= fun version ->
ret_gen (VersionBitMap version)
let marshal = Hello.Element.marshal
let parse = Hello.Element.parse
let to_string = Hello.Element.to_string
let size_of = Hello.Element.sizeof
end
type t = Hello.t
let arbitrary =
arbitrary_list Element.arbitrary >>= fun element ->
ret_gen element
let marshal = Hello.marshal
let parse = Hello.parse
let to_string = Hello.to_string
let size_of = Hello.sizeof
end
module FlowRemoved = struct
open Gen
open OpenFlow0x04_Core
type t = FlowRemoved.t
let arbitrary_reason =
oneof [
ret_gen FlowIdleTimeout;
ret_gen FlowHardTiemout;
ret_gen FlowDelete;
ret_gen FlowGroupDelete]
let arbitrary =
arbitrary_uint64 >>= fun cookie ->
arbitrary_uint16 >>= fun priority ->
arbitrary_reason >>= fun reason ->
arbitrary_uint8 >>= fun table_id ->
arbitrary_uint32 >>= fun duration_sec ->
arbitrary_uint32 >>= fun duration_nsec ->
arbitrary_timeout >>= fun idle_timeout ->
arbitrary_timeout >>= fun hard_timeout ->
arbitrary_uint64 >>= fun packet_count ->
arbitrary_uint64 >>= fun byte_count ->
OfpMatch.arbitrary >>= fun oxm ->
ret_gen { cookie; priority; reason; table_id; duration_sec; duration_nsec;
idle_timeout; hard_timeout; packet_count; byte_count; oxm }
let marshal = FlowRemoved.marshal
let parse = FlowRemoved.parse
let to_string = FlowRemoved.to_string
let size_of = FlowRemoved.sizeof
end
module AsyncConfig = struct
open Gen
open OpenFlow0x04_Core
type t = AsyncConfig.t
let arbitrary_packetInReasonMap =
arbitrary_bool >>= fun table_miss ->
arbitrary_bool >>= fun apply_action ->
arbitrary_bool >>= fun invalid_ttl ->
ret_gen { table_miss; apply_action; invalid_ttl }
let arbitrary_portStatusReasonMap =
arbitrary_bool >>= fun add ->
arbitrary_bool >>= fun delete ->
arbitrary_bool >>= fun modify ->
ret_gen { add; delete; modify }
let arbitrary_flowRemovedReasonMap =
arbitrary_bool >>= fun idle_timeout ->
arbitrary_bool >>= fun hard_timeout ->
arbitrary_bool >>= fun delete ->
arbitrary_bool >>= fun group_delete ->
ret_gen { idle_timeout; hard_timeout; delete; group_delete }
let arbitrary_mask arb =
arb >>= fun m_master ->
arb >>= fun m_slave ->
ret_gen { m_master; m_slave }
let arbitrary =
arbitrary_mask arbitrary_packetInReasonMap >>= fun packet_in ->
arbitrary_mask arbitrary_portStatusReasonMap >>= fun port_status ->
arbitrary_mask arbitrary_flowRemovedReasonMap >>= fun flow_removed ->
ret_gen { packet_in; port_status; flow_removed }
let marshal = AsyncConfig.marshal
let parse = AsyncConfig.parse
let to_string = AsyncConfig.to_string
let size_of = AsyncConfig.sizeof
end
module Error = struct
open Gen
open OpenFlow0x04_Core
type t = Error.t
let arbitrary_helloFailed =
oneof [
ret_gen HelloIncompatible;
ret_gen HelloPermError
]
let arbitrary_badRequest =
oneof [
ret_gen ReqBadVersion;
ret_gen ReqBadType;
ret_gen ReqBadMultipart;
ret_gen ReqBadExp;
ret_gen ReqBadExpType;
ret_gen ReqPermError;
ret_gen ReqBadLen;
ret_gen ReqBufferEmpty;
ret_gen ReqBufferUnknown;
ret_gen ReqBadTableId;
ret_gen ReqIsSlave;
ret_gen ReqBadPort;
ret_gen ReqBadPacket;
ret_gen ReqMultipartBufOverflow
]
let arbitrary_badAction =
oneof [
ret_gen ActBadType;
ret_gen ActBadLen;
ret_gen ActBadExp;
ret_gen ActBadExpType;
ret_gen ActBadOutPort;
ret_gen ActBadArg;
ret_gen ActPermError;
ret_gen ActTooMany;
ret_gen ActBadQueue;
ret_gen ActBadOutGroup;
ret_gen ActMatchInconsistent;
ret_gen ActUnsupportedOrder;
ret_gen ActBadTag;
ret_gen ActBadSetTyp;
ret_gen ActBadSetLen;
ret_gen ActBadSetArg
]
let arbitrary_badInstruction =
oneof [
ret_gen InstUnknownInst;
ret_gen InstBadTableId;
ret_gen InstUnsupInst;
ret_gen InstUnsupMeta;
ret_gen InstUnsupMetaMask;
ret_gen InstBadExp;
ret_gen InstBadExpTyp;
ret_gen InstBadLen;
ret_gen InstPermError
]
let arbitrary_badMatch =
oneof [
ret_gen MatBadTyp;
ret_gen MatBadLen;
ret_gen MatBadTag;
ret_gen MatBadDlAddrMask;
ret_gen MatBadNwAddrMask;
ret_gen MatBadWildcards;
ret_gen MatBadField;
ret_gen MatBadValue;
ret_gen MatBadMask;
ret_gen MatBadPrereq;
ret_gen MatDupField;
ret_gen MatPermError
]
let arbitrary_flowModFailed =
oneof [
ret_gen FlUnknown;
ret_gen FlTableFull;
ret_gen FlBadTableId;
ret_gen FlOverlap;
ret_gen FlPermError;
ret_gen FlBadTimeout;
ret_gen FlBadCommand;
ret_gen FlBadFlags
]
let arbitrary_groupModFailed =
oneof [
ret_gen GrGroupExists;
ret_gen GrInvalidGroup;
ret_gen GrWeightUnsupported;
ret_gen GrOutOfGroups;
ret_gen GrOutOfBuckets;
ret_gen GrChainingUnsupported;
ret_gen GrWatcHUnsupported;
ret_gen GrLoop;
ret_gen GrUnknownGroup;
ret_gen GrChainedGroup;
ret_gen GrBadTyp;
ret_gen GrBadCommand;
ret_gen GrBadBucket;
ret_gen GrBadWatch;
ret_gen GrPermError
]
let arbitrary_portModFailed =
oneof [
ret_gen PoBadPort;
ret_gen PoBadHwAddr;
ret_gen PoBadConfig;
ret_gen PoBadAdvertise;
ret_gen PoPermError
]
let arbitrary_tableModFailed =
oneof [
ret_gen TaBadTable;
ret_gen TaBadConfig;
ret_gen TaPermError
]
let arbitrary_queueOpFailed =
oneof [
ret_gen QuBadPort;
ret_gen QuBadQUeue;
ret_gen QuPermError
]
let arbitrary_switchConfigFailed =
oneof [
ret_gen ScBadFlags;
ret_gen ScBadLen;
ret_gen ScPermError
]
let arbitrary_roleReqFailed =
oneof [
ret_gen RoStale;
ret_gen RoUnsup;
ret_gen RoBadRole;
]
let arbitrary_meterModFailed =
oneof [
ret_gen MeUnknown;
ret_gen MeMeterExists;
ret_gen MeInvalidMeter;
ret_gen MeUnknownMeter;
ret_gen MeBadCommand;
ret_gen MeBadFlags;
ret_gen MeBadRate;
ret_gen MeBadBurst;
ret_gen MeBadBand;
ret_gen MeBadBandValue;
ret_gen MeOutOfMeters;
ret_gen MeOutOfBands
]
let arbitrary_tableFeatFailed =
oneof [
ret_gen TfBadTable;
ret_gen TfBadMeta;
ret_gen TfBadType;
ret_gen TfBadLen;
ret_gen TfBadArg;
ret_gen TfPermError
]
let arbitrary_exp =
arbitrary_uint16 >>= fun exp_typ ->
arbitrary_uint32 >>= fun exp_id ->
ret_gen {exp_typ; exp_id}
let arbitrary_err =
oneof [
arbitrary_helloFailed >>= (fun n -> ret_gen (HelloFailed n));
arbitrary_badRequest >>= (fun n -> ret_gen (BadRequest n));
arbitrary_badAction >>= (fun n -> ret_gen (BadAction n));
arbitrary_badInstruction >>= (fun n -> ret_gen (BadInstruction n));
arbitrary_badMatch >>= (fun n -> ret_gen (BadMatch n));
arbitrary_flowModFailed >>= (fun n -> ret_gen (FlowModFailed n));
arbitrary_groupModFailed >>= (fun n -> ret_gen (GroupModFailed n));
arbitrary_portModFailed >>= (fun n -> ret_gen (PortModFailed n));
arbitrary_tableModFailed >>= (fun n -> ret_gen (TableModFailed n));
arbitrary_queueOpFailed >>= (fun n -> ret_gen (QueueOpFailed n));
arbitrary_switchConfigFailed >>= (fun n -> ret_gen (SwitchConfigFailed n));
arbitrary_roleReqFailed >>= (fun n -> ret_gen (RoleReqFailed n));
arbitrary_meterModFailed >>= (fun n -> ret_gen (MeterModFailed n));
arbitrary_tableFeatFailed >>= (fun n -> ret_gen (TableFeatFailed n));
arbitrary_exp >>= (fun n -> ret_gen (ExperimenterFailed n));
]
let arbitrary_len =
(choose_int (64, 150)) >>= fun a ->
ret_gen a
let arbitrary_byte n =
arbitrary_stringN n >>= fun a ->
let byte = Cstruct.create n in
Cstruct.blit_from_string a 0 byte 0 n;
ret_gen (byte)
let arbitrary =
arbitrary_len >>= fun len ->
arbitrary_byte len >>= fun data ->
arbitrary_err >>= fun err ->
ret_gen {
Error.err = err;
Error.data = data}
let marshal = Error.marshal
let parse = Error.parse
let to_string = Error.to_string
let size_of = Error.sizeof
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.