filename
stringlengths
3
67
data
stringlengths
0
58.3M
license
stringlengths
0
19.5k
michelson_v1_primitives.ml
open Micheline type error += Unknown_primitive_name of string type error += Invalid_case of string type error += | Invalid_primitive_name of string Micheline.canonical * Micheline.canonical_location type prim = | K_parameter | K_storage | K_code | K_view | D_False | D_Elt | D_Left | D_None | D_Pair | D_Right | D_Some | D_True | D_Unit | D_Lambda_rec | I_PACK | I_UNPACK | I_BLAKE2B | I_SHA256 | I_SHA512 | I_ABS | I_ADD | I_AMOUNT | I_AND | I_BALANCE | I_CAR | I_CDR | I_CHAIN_ID | I_CHECK_SIGNATURE | I_COMPARE | I_CONCAT | I_CONS | I_CREATE_ACCOUNT | I_CREATE_CONTRACT | I_IMPLICIT_ACCOUNT | I_DIP | I_DROP | I_DUP | I_VIEW | I_EDIV | I_EMPTY_BIG_MAP | I_EMPTY_MAP | I_EMPTY_SET | I_EQ | I_EXEC | I_APPLY | I_FAILWITH | I_GE | I_GET | I_GET_AND_UPDATE | I_GT | I_HASH_KEY | I_IF | I_IF_CONS | I_IF_LEFT | I_IF_NONE | I_INT | I_LAMBDA | I_LAMBDA_REC | I_LE | I_LEFT | I_LEVEL | I_LOOP | I_LSL | I_LSR | I_LT | I_MAP | I_MEM | I_MUL | I_NEG | I_NEQ | I_NIL | I_NONE | I_NOT | I_NOW | I_MIN_BLOCK_TIME | I_OR | I_PAIR | I_UNPAIR | I_PUSH | I_RIGHT | I_SIZE | I_SOME | I_SOURCE | I_SENDER | I_SELF | I_SELF_ADDRESS | I_SLICE | I_STEPS_TO_QUOTA | I_SUB | I_SUB_MUTEZ | I_SWAP | I_TRANSFER_TOKENS | I_SET_DELEGATE | I_UNIT | I_UPDATE | I_XOR | I_ITER | I_LOOP_LEFT | I_ADDRESS | I_CONTRACT | I_ISNAT | I_CAST | I_RENAME | I_SAPLING_EMPTY_STATE | I_SAPLING_VERIFY_UPDATE | I_DIG | I_DUG | I_NEVER | I_VOTING_POWER | I_TOTAL_VOTING_POWER | I_KECCAK | I_SHA3 | I_PAIRING_CHECK | I_TICKET | I_TICKET_DEPRECATED | I_READ_TICKET | I_SPLIT_TICKET | I_JOIN_TICKETS | I_OPEN_CHEST | I_EMIT | T_bool | T_contract | T_int | T_key | T_key_hash | T_lambda | T_list | T_map | T_big_map | T_nat | T_option | T_or | T_pair | T_set | T_signature | T_string | T_bytes | T_mutez | T_timestamp | T_unit | T_operation | T_address | T_tx_rollup_l2_address | T_sapling_transaction | T_sapling_transaction_deprecated | T_sapling_state | T_chain_id | T_never | T_bls12_381_g1 | T_bls12_381_g2 | T_bls12_381_fr | T_ticket | T_chest_key | T_chest | H_constant (* Auxiliary types for error documentation. All the prim constructor prefixes must match their namespace. *) type namespace = | (* prefix "T" *) Type_namespace | (* prefix "D" *) Constant_namespace | (* prefix "I" *) Instr_namespace | (* prefix "K" *) Keyword_namespace | (* prefix "H" *) Constant_hash_namespace let namespace = function | K_code | K_view | K_parameter | K_storage -> Keyword_namespace | D_Elt | D_False | D_Left | D_None | D_Pair | D_Right | D_Some | D_True | D_Unit | D_Lambda_rec -> Constant_namespace | I_ABS | I_ADD | I_ADDRESS | I_AMOUNT | I_AND | I_APPLY | I_BALANCE | I_BLAKE2B | I_CAR | I_CAST | I_CDR | I_CHAIN_ID | I_CHECK_SIGNATURE | I_COMPARE | I_CONCAT | I_CONS | I_CONTRACT | I_CREATE_ACCOUNT | I_CREATE_CONTRACT | I_DIG | I_DIP | I_DROP | I_DUG | I_DUP | I_VIEW | I_EDIV | I_EMPTY_BIG_MAP | I_EMPTY_MAP | I_EMPTY_SET | I_EQ | I_EXEC | I_FAILWITH | I_GE | I_GET | I_GET_AND_UPDATE | I_GT | I_HASH_KEY | I_IF | I_IF_CONS | I_IF_LEFT | I_IF_NONE | I_IMPLICIT_ACCOUNT | I_INT | I_ISNAT | I_ITER | I_JOIN_TICKETS | I_KECCAK | I_LAMBDA | I_LAMBDA_REC | I_LE | I_LEFT | I_LEVEL | I_LOOP | I_LOOP_LEFT | I_LSL | I_LSR | I_LT | I_MAP | I_MEM | I_MUL | I_NEG | I_NEQ | I_NEVER | I_NIL | I_NONE | I_NOT | I_NOW | I_MIN_BLOCK_TIME | I_OR | I_PACK | I_PAIR | I_PAIRING_CHECK | I_PUSH | I_READ_TICKET | I_RENAME | I_RIGHT | I_SAPLING_EMPTY_STATE | I_SAPLING_VERIFY_UPDATE | I_SELF | I_SELF_ADDRESS | I_SENDER | I_SET_DELEGATE | I_SHA256 | I_SHA512 | I_SHA3 | I_SIZE | I_SLICE | I_SOME | I_SOURCE | I_SPLIT_TICKET | I_STEPS_TO_QUOTA | I_SUB | I_SUB_MUTEZ | I_SWAP | I_TICKET | I_TICKET_DEPRECATED | I_TOTAL_VOTING_POWER | I_TRANSFER_TOKENS | I_UNIT | I_UNPACK | I_UNPAIR | I_UPDATE | I_VOTING_POWER | I_XOR | I_OPEN_CHEST | I_EMIT -> Instr_namespace | T_address | T_tx_rollup_l2_address | T_big_map | T_bool | T_bytes | T_chain_id | T_contract | T_int | T_key | T_key_hash | T_lambda | T_list | T_map | T_mutez | T_nat | T_never | T_operation | T_option | T_or | T_pair | T_sapling_state | T_sapling_transaction | T_sapling_transaction_deprecated | T_set | T_signature | T_string | T_timestamp | T_unit | T_bls12_381_fr | T_bls12_381_g1 | T_bls12_381_g2 | T_ticket | T_chest_key | T_chest -> Type_namespace | H_constant -> Constant_hash_namespace let valid_case name = let is_lower = function '_' | 'a' .. 'z' -> true | _ -> false in let is_upper = function '_' | 'A' .. 'Z' -> true | _ -> false in let rec for_all a b f = Compare.Int.(a > b) || (f a && for_all (a + 1) b f) in let len = String.length name in Compare.Int.(len <> 0) && Compare.Char.(name.[0] <> '_') && ((is_upper name.[0] && for_all 1 (len - 1) (fun i -> is_upper name.[i])) || (is_upper name.[0] && for_all 1 (len - 1) (fun i -> is_lower name.[i])) || (is_lower name.[0] && for_all 1 (len - 1) (fun i -> is_lower name.[i])) ) let string_of_prim = function | K_parameter -> "parameter" | K_storage -> "storage" | K_code -> "code" | K_view -> "view" | D_False -> "False" | D_Elt -> "Elt" | D_Left -> "Left" | D_None -> "None" | D_Pair -> "Pair" | D_Right -> "Right" | D_Some -> "Some" | D_True -> "True" | D_Unit -> "Unit" | D_Lambda_rec -> "Lambda_rec" | I_PACK -> "PACK" | I_UNPACK -> "UNPACK" | I_BLAKE2B -> "BLAKE2B" | I_SHA256 -> "SHA256" | I_SHA512 -> "SHA512" | I_ABS -> "ABS" | I_ADD -> "ADD" | I_AMOUNT -> "AMOUNT" | I_AND -> "AND" | I_BALANCE -> "BALANCE" | I_CAR -> "CAR" | I_CDR -> "CDR" | I_CHAIN_ID -> "CHAIN_ID" | I_CHECK_SIGNATURE -> "CHECK_SIGNATURE" | I_COMPARE -> "COMPARE" | I_CONCAT -> "CONCAT" | I_CONS -> "CONS" | I_CREATE_ACCOUNT -> "CREATE_ACCOUNT" | I_CREATE_CONTRACT -> "CREATE_CONTRACT" | I_IMPLICIT_ACCOUNT -> "IMPLICIT_ACCOUNT" | I_DIP -> "DIP" | I_DROP -> "DROP" | I_DUP -> "DUP" | I_EDIV -> "EDIV" | I_EMPTY_BIG_MAP -> "EMPTY_BIG_MAP" | I_EMPTY_MAP -> "EMPTY_MAP" | I_EMPTY_SET -> "EMPTY_SET" | I_EQ -> "EQ" | I_EXEC -> "EXEC" | I_APPLY -> "APPLY" | I_FAILWITH -> "FAILWITH" | I_GE -> "GE" | I_GET -> "GET" | I_GET_AND_UPDATE -> "GET_AND_UPDATE" | I_GT -> "GT" | I_HASH_KEY -> "HASH_KEY" | I_IF -> "IF" | I_IF_CONS -> "IF_CONS" | I_IF_LEFT -> "IF_LEFT" | I_IF_NONE -> "IF_NONE" | I_INT -> "INT" | I_LAMBDA -> "LAMBDA" | I_LAMBDA_REC -> "LAMBDA_REC" | I_LE -> "LE" | I_LEFT -> "LEFT" | I_LEVEL -> "LEVEL" | I_LOOP -> "LOOP" | I_LSL -> "LSL" | I_LSR -> "LSR" | I_LT -> "LT" | I_MAP -> "MAP" | I_MEM -> "MEM" | I_MUL -> "MUL" | I_NEG -> "NEG" | I_NEQ -> "NEQ" | I_NIL -> "NIL" | I_NONE -> "NONE" | I_NOT -> "NOT" | I_NOW -> "NOW" | I_MIN_BLOCK_TIME -> "MIN_BLOCK_TIME" | I_OR -> "OR" | I_PAIR -> "PAIR" | I_PUSH -> "PUSH" | I_RIGHT -> "RIGHT" | I_SIZE -> "SIZE" | I_SOME -> "SOME" | I_SOURCE -> "SOURCE" | I_SENDER -> "SENDER" | I_SELF -> "SELF" | I_SELF_ADDRESS -> "SELF_ADDRESS" | I_SLICE -> "SLICE" | I_STEPS_TO_QUOTA -> "STEPS_TO_QUOTA" | I_SUB -> "SUB" | I_SUB_MUTEZ -> "SUB_MUTEZ" | I_SWAP -> "SWAP" | I_TRANSFER_TOKENS -> "TRANSFER_TOKENS" | I_SET_DELEGATE -> "SET_DELEGATE" | I_UNIT -> "UNIT" | I_UNPAIR -> "UNPAIR" | I_UPDATE -> "UPDATE" | I_XOR -> "XOR" | I_ITER -> "ITER" | I_LOOP_LEFT -> "LOOP_LEFT" | I_ADDRESS -> "ADDRESS" | I_CONTRACT -> "CONTRACT" | I_ISNAT -> "ISNAT" | I_CAST -> "CAST" | I_RENAME -> "RENAME" | I_SAPLING_EMPTY_STATE -> "SAPLING_EMPTY_STATE" | I_SAPLING_VERIFY_UPDATE -> "SAPLING_VERIFY_UPDATE" | I_DIG -> "DIG" | I_DUG -> "DUG" | I_NEVER -> "NEVER" | I_VOTING_POWER -> "VOTING_POWER" | I_TOTAL_VOTING_POWER -> "TOTAL_VOTING_POWER" | I_KECCAK -> "KECCAK" | I_SHA3 -> "SHA3" | I_PAIRING_CHECK -> "PAIRING_CHECK" | I_TICKET -> "TICKET" | I_TICKET_DEPRECATED -> "TICKET_DEPRECATED" | I_READ_TICKET -> "READ_TICKET" | I_SPLIT_TICKET -> "SPLIT_TICKET" | I_JOIN_TICKETS -> "JOIN_TICKETS" | I_OPEN_CHEST -> "OPEN_CHEST" | I_EMIT -> "EMIT" | I_VIEW -> "VIEW" | T_bool -> "bool" | T_contract -> "contract" | T_int -> "int" | T_key -> "key" | T_key_hash -> "key_hash" | T_lambda -> "lambda" | T_list -> "list" | T_map -> "map" | T_big_map -> "big_map" | T_nat -> "nat" | T_option -> "option" | T_or -> "or" | T_pair -> "pair" | T_set -> "set" | T_signature -> "signature" | T_string -> "string" | T_bytes -> "bytes" | T_mutez -> "mutez" | T_timestamp -> "timestamp" | T_unit -> "unit" | T_operation -> "operation" | T_address -> "address" | T_tx_rollup_l2_address -> "tx_rollup_l2_address" | T_sapling_state -> "sapling_state" | T_sapling_transaction -> "sapling_transaction" | T_sapling_transaction_deprecated -> "sapling_transaction_deprecated" | T_chain_id -> "chain_id" | T_never -> "never" | T_bls12_381_g1 -> "bls12_381_g1" | T_bls12_381_g2 -> "bls12_381_g2" | T_bls12_381_fr -> "bls12_381_fr" | T_ticket -> "ticket" | T_chest_key -> "chest_key" | T_chest -> "chest" | H_constant -> "constant" let prim_of_string = function | "parameter" -> ok K_parameter | "storage" -> ok K_storage | "code" -> ok K_code | "view" -> ok K_view | "False" -> ok D_False | "Elt" -> ok D_Elt | "Left" -> ok D_Left | "None" -> ok D_None | "Pair" -> ok D_Pair | "Right" -> ok D_Right | "Some" -> ok D_Some | "True" -> ok D_True | "Unit" -> ok D_Unit | "Lambda_rec" -> ok D_Lambda_rec | "PACK" -> ok I_PACK | "UNPACK" -> ok I_UNPACK | "BLAKE2B" -> ok I_BLAKE2B | "SHA256" -> ok I_SHA256 | "SHA512" -> ok I_SHA512 | "ABS" -> ok I_ABS | "ADD" -> ok I_ADD | "AMOUNT" -> ok I_AMOUNT | "AND" -> ok I_AND | "BALANCE" -> ok I_BALANCE | "CAR" -> ok I_CAR | "CDR" -> ok I_CDR | "CHAIN_ID" -> ok I_CHAIN_ID | "CHECK_SIGNATURE" -> ok I_CHECK_SIGNATURE | "COMPARE" -> ok I_COMPARE | "CONCAT" -> ok I_CONCAT | "CONS" -> ok I_CONS | "CREATE_ACCOUNT" -> ok I_CREATE_ACCOUNT | "CREATE_CONTRACT" -> ok I_CREATE_CONTRACT | "IMPLICIT_ACCOUNT" -> ok I_IMPLICIT_ACCOUNT | "DIP" -> ok I_DIP | "DROP" -> ok I_DROP | "DUP" -> ok I_DUP | "VIEW" -> ok I_VIEW | "EDIV" -> ok I_EDIV | "EMPTY_BIG_MAP" -> ok I_EMPTY_BIG_MAP | "EMPTY_MAP" -> ok I_EMPTY_MAP | "EMPTY_SET" -> ok I_EMPTY_SET | "EQ" -> ok I_EQ | "EXEC" -> ok I_EXEC | "APPLY" -> ok I_APPLY | "FAILWITH" -> ok I_FAILWITH | "GE" -> ok I_GE | "GET" -> ok I_GET | "GET_AND_UPDATE" -> ok I_GET_AND_UPDATE | "GT" -> ok I_GT | "HASH_KEY" -> ok I_HASH_KEY | "IF" -> ok I_IF | "IF_CONS" -> ok I_IF_CONS | "IF_LEFT" -> ok I_IF_LEFT | "IF_NONE" -> ok I_IF_NONE | "INT" -> ok I_INT | "KECCAK" -> ok I_KECCAK | "LAMBDA" -> ok I_LAMBDA | "LAMBDA_REC" -> ok I_LAMBDA_REC | "LE" -> ok I_LE | "LEFT" -> ok I_LEFT | "LEVEL" -> ok I_LEVEL | "LOOP" -> ok I_LOOP | "LSL" -> ok I_LSL | "LSR" -> ok I_LSR | "LT" -> ok I_LT | "MAP" -> ok I_MAP | "MEM" -> ok I_MEM | "MUL" -> ok I_MUL | "NEG" -> ok I_NEG | "NEQ" -> ok I_NEQ | "NIL" -> ok I_NIL | "NONE" -> ok I_NONE | "NOT" -> ok I_NOT | "NOW" -> ok I_NOW | "MIN_BLOCK_TIME" -> ok I_MIN_BLOCK_TIME | "OR" -> ok I_OR | "PAIR" -> ok I_PAIR | "UNPAIR" -> ok I_UNPAIR | "PAIRING_CHECK" -> ok I_PAIRING_CHECK | "PUSH" -> ok I_PUSH | "RIGHT" -> ok I_RIGHT | "SHA3" -> ok I_SHA3 | "SIZE" -> ok I_SIZE | "SOME" -> ok I_SOME | "SOURCE" -> ok I_SOURCE | "SENDER" -> ok I_SENDER | "SELF" -> ok I_SELF | "SELF_ADDRESS" -> ok I_SELF_ADDRESS | "SLICE" -> ok I_SLICE | "STEPS_TO_QUOTA" -> ok I_STEPS_TO_QUOTA | "SUB" -> ok I_SUB | "SUB_MUTEZ" -> ok I_SUB_MUTEZ | "SWAP" -> ok I_SWAP | "TRANSFER_TOKENS" -> ok I_TRANSFER_TOKENS | "SET_DELEGATE" -> ok I_SET_DELEGATE | "UNIT" -> ok I_UNIT | "UPDATE" -> ok I_UPDATE | "XOR" -> ok I_XOR | "ITER" -> ok I_ITER | "LOOP_LEFT" -> ok I_LOOP_LEFT | "ADDRESS" -> ok I_ADDRESS | "CONTRACT" -> ok I_CONTRACT | "ISNAT" -> ok I_ISNAT | "CAST" -> ok I_CAST | "RENAME" -> ok I_RENAME | "SAPLING_EMPTY_STATE" -> ok I_SAPLING_EMPTY_STATE | "SAPLING_VERIFY_UPDATE" -> ok I_SAPLING_VERIFY_UPDATE | "DIG" -> ok I_DIG | "DUG" -> ok I_DUG | "NEVER" -> ok I_NEVER | "VOTING_POWER" -> ok I_VOTING_POWER | "TOTAL_VOTING_POWER" -> ok I_TOTAL_VOTING_POWER | "TICKET" -> ok I_TICKET | "TICKET_DEPRECATED" -> ok I_TICKET_DEPRECATED | "READ_TICKET" -> ok I_READ_TICKET | "SPLIT_TICKET" -> ok I_SPLIT_TICKET | "JOIN_TICKETS" -> ok I_JOIN_TICKETS | "OPEN_CHEST" -> ok I_OPEN_CHEST | "EMIT" -> ok I_EMIT | "bool" -> ok T_bool | "contract" -> ok T_contract | "int" -> ok T_int | "key" -> ok T_key | "key_hash" -> ok T_key_hash | "lambda" -> ok T_lambda | "list" -> ok T_list | "map" -> ok T_map | "big_map" -> ok T_big_map | "nat" -> ok T_nat | "option" -> ok T_option | "or" -> ok T_or | "pair" -> ok T_pair | "set" -> ok T_set | "signature" -> ok T_signature | "string" -> ok T_string | "bytes" -> ok T_bytes | "mutez" -> ok T_mutez | "timestamp" -> ok T_timestamp | "unit" -> ok T_unit | "operation" -> ok T_operation | "address" -> ok T_address | "tx_rollup_l2_address" -> ok T_tx_rollup_l2_address | "sapling_state" -> ok T_sapling_state | "sapling_transaction" -> ok T_sapling_transaction | "sapling_transaction_deprecated" -> ok T_sapling_transaction_deprecated | "chain_id" -> ok T_chain_id | "never" -> ok T_never | "bls12_381_g1" -> ok T_bls12_381_g1 | "bls12_381_g2" -> ok T_bls12_381_g2 | "bls12_381_fr" -> ok T_bls12_381_fr | "ticket" -> ok T_ticket | "chest_key" -> ok T_chest_key | "chest" -> ok T_chest | "constant" -> ok H_constant | n -> if valid_case n then error (Unknown_primitive_name n) else error (Invalid_case n) let prims_of_strings expr = let rec convert = function | (Int _ | String _ | Bytes _) as expr -> ok expr | Prim (loc, prim, args, annot) -> Error_monad.record_trace (Invalid_primitive_name (expr, loc)) (prim_of_string prim) >>? fun prim -> List.map_e convert args >|? fun args -> Prim (loc, prim, args, annot) | Seq (loc, args) -> List.map_e convert args >|? fun args -> Seq (loc, args) in convert (root expr) >|? fun expr -> strip_locations expr let strings_of_prims expr = let rec convert = function | (Int _ | String _ | Bytes _) as expr -> expr | Prim (loc, prim, args, annot) -> let prim = string_of_prim prim in let args = List.map convert args in Prim (loc, prim, args, annot) | Seq (loc, args) -> let args = List.map convert args in Seq (loc, args) in strip_locations (convert (root expr)) let prim_encoding = let open Data_encoding in def "michelson.v1.primitives" @@ string_enum (* Add the comment below every 10 lines *) [ (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("parameter", K_parameter); ("storage", K_storage); ("code", K_code); ("False", D_False); ("Elt", D_Elt); ("Left", D_Left); ("None", D_None); ("Pair", D_Pair); ("Right", D_Right); ("Some", D_Some); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("True", D_True); ("Unit", D_Unit); ("PACK", I_PACK); ("UNPACK", I_UNPACK); ("BLAKE2B", I_BLAKE2B); ("SHA256", I_SHA256); ("SHA512", I_SHA512); ("ABS", I_ABS); ("ADD", I_ADD); ("AMOUNT", I_AMOUNT); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("AND", I_AND); ("BALANCE", I_BALANCE); ("CAR", I_CAR); ("CDR", I_CDR); ("CHECK_SIGNATURE", I_CHECK_SIGNATURE); ("COMPARE", I_COMPARE); ("CONCAT", I_CONCAT); ("CONS", I_CONS); ("CREATE_ACCOUNT", I_CREATE_ACCOUNT); ("CREATE_CONTRACT", I_CREATE_CONTRACT); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("IMPLICIT_ACCOUNT", I_IMPLICIT_ACCOUNT); ("DIP", I_DIP); ("DROP", I_DROP); ("DUP", I_DUP); ("EDIV", I_EDIV); ("EMPTY_MAP", I_EMPTY_MAP); ("EMPTY_SET", I_EMPTY_SET); ("EQ", I_EQ); ("EXEC", I_EXEC); ("FAILWITH", I_FAILWITH); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("GE", I_GE); ("GET", I_GET); ("GT", I_GT); ("HASH_KEY", I_HASH_KEY); ("IF", I_IF); ("IF_CONS", I_IF_CONS); ("IF_LEFT", I_IF_LEFT); ("IF_NONE", I_IF_NONE); ("INT", I_INT); ("LAMBDA", I_LAMBDA); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("LE", I_LE); ("LEFT", I_LEFT); ("LOOP", I_LOOP); ("LSL", I_LSL); ("LSR", I_LSR); ("LT", I_LT); ("MAP", I_MAP); ("MEM", I_MEM); ("MUL", I_MUL); ("NEG", I_NEG); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("NEQ", I_NEQ); ("NIL", I_NIL); ("NONE", I_NONE); ("NOT", I_NOT); ("NOW", I_NOW); ("OR", I_OR); ("PAIR", I_PAIR); ("PUSH", I_PUSH); ("RIGHT", I_RIGHT); ("SIZE", I_SIZE); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("SOME", I_SOME); ("SOURCE", I_SOURCE); ("SENDER", I_SENDER); ("SELF", I_SELF); ("STEPS_TO_QUOTA", I_STEPS_TO_QUOTA); ("SUB", I_SUB); ("SWAP", I_SWAP); ("TRANSFER_TOKENS", I_TRANSFER_TOKENS); ("SET_DELEGATE", I_SET_DELEGATE); ("UNIT", I_UNIT); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("UPDATE", I_UPDATE); ("XOR", I_XOR); ("ITER", I_ITER); ("LOOP_LEFT", I_LOOP_LEFT); ("ADDRESS", I_ADDRESS); ("CONTRACT", I_CONTRACT); ("ISNAT", I_ISNAT); ("CAST", I_CAST); ("RENAME", I_RENAME); ("bool", T_bool); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("contract", T_contract); ("int", T_int); ("key", T_key); ("key_hash", T_key_hash); ("lambda", T_lambda); ("list", T_list); ("map", T_map); ("big_map", T_big_map); ("nat", T_nat); ("option", T_option); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("or", T_or); ("pair", T_pair); ("set", T_set); ("signature", T_signature); ("string", T_string); ("bytes", T_bytes); ("mutez", T_mutez); ("timestamp", T_timestamp); ("unit", T_unit); ("operation", T_operation); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("address", T_address); (* Alpha_002 addition *) ("SLICE", I_SLICE); (* Alpha_005 addition *) ("DIG", I_DIG); ("DUG", I_DUG); ("EMPTY_BIG_MAP", I_EMPTY_BIG_MAP); ("APPLY", I_APPLY); ("chain_id", T_chain_id); ("CHAIN_ID", I_CHAIN_ID); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) (* Alpha_008 addition *) ("LEVEL", I_LEVEL); ("SELF_ADDRESS", I_SELF_ADDRESS); ("never", T_never); ("NEVER", I_NEVER); ("UNPAIR", I_UNPAIR); ("VOTING_POWER", I_VOTING_POWER); ("TOTAL_VOTING_POWER", I_TOTAL_VOTING_POWER); ("KECCAK", I_KECCAK); ("SHA3", I_SHA3); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) (* Alpha_008 addition *) ("PAIRING_CHECK", I_PAIRING_CHECK); ("bls12_381_g1", T_bls12_381_g1); ("bls12_381_g2", T_bls12_381_g2); ("bls12_381_fr", T_bls12_381_fr); ("sapling_state", T_sapling_state); ("sapling_transaction_deprecated", T_sapling_transaction_deprecated); ("SAPLING_EMPTY_STATE", I_SAPLING_EMPTY_STATE); ("SAPLING_VERIFY_UPDATE", I_SAPLING_VERIFY_UPDATE); ("ticket", T_ticket); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) (* Alpha_008 addition *) ("TICKET_DEPRECATED", I_TICKET_DEPRECATED); ("READ_TICKET", I_READ_TICKET); ("SPLIT_TICKET", I_SPLIT_TICKET); ("JOIN_TICKETS", I_JOIN_TICKETS); ("GET_AND_UPDATE", I_GET_AND_UPDATE); (* Alpha_011 addition *) ("chest", T_chest); ("chest_key", T_chest_key); ("OPEN_CHEST", I_OPEN_CHEST); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("VIEW", I_VIEW); ("view", K_view); ("constant", H_constant); (* Alpha_012 addition *) ("SUB_MUTEZ", I_SUB_MUTEZ); (* Alpha_013 addition *) ("tx_rollup_l2_address", T_tx_rollup_l2_address); ("MIN_BLOCK_TIME", I_MIN_BLOCK_TIME); ("sapling_transaction", T_sapling_transaction); (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) (* Alpha_014 addition *) ("EMIT", I_EMIT); (* Alpha_015 addition *) ("Lambda_rec", D_Lambda_rec); ("LAMBDA_REC", I_LAMBDA_REC); ("TICKET", I_TICKET) (* New instructions must be added here, for backward compatibility of the encoding. *) (* Keep the comment above at the end of the list *); ] let () = register_error_kind `Permanent ~id:"michelson_v1.unknown_primitive_name" ~title:"Unknown primitive name" ~description:"In a script or data expression, a primitive was unknown." ~pp:(fun ppf n -> Format.fprintf ppf "Unknown primitive %s." n) Data_encoding.(obj1 (req "wrong_primitive_name" string)) (function Unknown_primitive_name got -> Some got | _ -> None) (fun got -> Unknown_primitive_name got) ; register_error_kind `Permanent ~id:"michelson_v1.invalid_primitive_name_case" ~title:"Invalid primitive name case" ~description: "In a script or data expression, a primitive name is neither uppercase, \ lowercase or capitalized." ~pp:(fun ppf n -> Format.fprintf ppf "Primitive %s has invalid case." n) Data_encoding.(obj1 (req "wrong_primitive_name" string)) (function Invalid_case name -> Some name | _ -> None) (fun name -> Invalid_case name) ; register_error_kind `Permanent ~id:"michelson_v1.invalid_primitive_name" ~title:"Invalid primitive name" ~description: "In a script or data expression, a primitive name is unknown or has a \ wrong case." ~pp:(fun ppf _ -> Format.fprintf ppf "Invalid primitive.") Data_encoding.( obj2 (req "expression" (Micheline.canonical_encoding ~variant:"generic" string)) (req "location" Micheline.canonical_location_encoding)) (function | Invalid_primitive_name (expr, loc) -> Some (expr, loc) | _ -> None) (fun (expr, loc) -> Invalid_primitive_name (expr, loc)) let string_of_namespace = function | Type_namespace -> "T" | Constant_namespace -> "D" | Instr_namespace -> "I" | Keyword_namespace -> "K" | Constant_hash_namespace -> "H"
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *) (* *) (* 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. *) (* *) (*****************************************************************************)
merkle_proof_encoding.ml
(* Using vanilla Data_encoding. Easier to parse but less efficient *) module Make_V1 (Conf : sig val entries : int end) = struct open Tezos_context_sigs.Context.Proof_types open Data_encoding let entries = Conf.entries (* The code only supports branching factors 2 and 32 *) let () = assert (entries = 2 || entries = 32) let value_encoding : value Data_encoding.t = bytes let length_field = req "length" (conv Int64.of_int Int64.to_int int64) let step_encoding : step Data_encoding.t = (* Context path name. [bytes] must be used for JSON since we have no charset specificaiton. *) conv Bytes.unsafe_of_string Bytes.unsafe_to_string (Bounded.bytes 255 (* 1 byte for the length *)) let hash_encoding = Context_hash.encoding let index_encoding = uint8 (* This works for entries <= 32 but specialized for entries = 32 *) let segment_encoding_32 = (* The segment int is in 5bits. *) (* Format * Required bytes = (n * 5 + 8) / 8 * Maximum length allowed: 406 * 10* is filled at the end of the bytes ex: Encoding of [aaaaa; bbbbb; ccccc; ddddd; eeeee; ..; zzzzz] |76543210|76543210|7654.. .. |76543210| |aaaaabbb|bbcccccd|ddde.. .. zzzzz100| |76543210|76543210|7654.. .. 43210|76543210| |aaaaabbb|bbcccccd|ddde.. .. yzzzz|z1000000| |76543210|76543210|7654.. .. 543210|76543210| |aaaaabbb|bbcccccd|ddde.. .. yzzzzz|10000000| *) let encode is = let buf = Buffer.create 0 in let push c = Buffer.add_char buf @@ Char.chr c in let close c bit = push (c lor (1 lsl (7 - bit))) in let write c bit i = if bit < 3 then (c lor (i lsl (3 - bit)), bit + 5) else let i = i lsl (11 - bit) in push (c lor (i / 256)) ; (i land 255, bit - 3) in let rec f c bit = function | [] -> close c bit | i :: is -> let c, bit = write c bit i in f c bit is in f 0 0 is ; Buffer.to_bytes buf in let decode b = let open Result_syntax in let error = Error "invalid 5bit list" in let* l = let sl = Bytes.length b in if sl = 0 then error else let c = Char.code @@ Bytes.get b (sl - 1) in let* last_bit = if c = 0 then error else let rec aux i = if c land (1 lsl i) = 0 then aux (i + 1) else i + 1 in Ok (aux 0) in let bits = (sl * 8) - last_bit in if bits mod 5 = 0 then Ok (bits / 5) else error in let s = Bytes.to_seq b in let head s = (* This assertion won't fail even with malformed input. *) match s () with | Seq.Nil -> assert false | Seq.Cons (c, s) -> (Char.code c, s) in let rec read c rembit l s = if l = 0 then [] else let c, s, rembit = if rembit >= 5 then (c, s, rembit) else let c', s = head s in ((c * 256) + c', s, rembit + 8) in let rembit = rembit - 5 in let i = c lsr rembit in let c = c land ((1 lsl rembit) - 1) in i :: read c rembit (l - 1) s in Ok (read 0 0 l s) in conv_with_guard encode decode (Bounded.bytes 255) (* This works only for entries = 2 *) let segment_encoding_2 = (* Format * Required bytes = (n + 8) / 8 * Maximum length allowed: 2032 * 10* is filled at the end of the bytes *) let encode is = let buf = Buffer.create 0 in let push c = Buffer.add_char buf @@ Char.chr c in let close c bit = push (c lor (1 lsl (7 - bit))) in let write c bit i = if bit < 7 then (c lor (i lsl (7 - bit)), bit + 1) else let i = i lsl (15 - bit) in push (c lor (i / 256)) ; (i land 255, bit - 7) in let rec f c bit = function | [] -> close c bit | i :: is -> let c, bit = write c bit i in f c bit is in f 0 0 is ; Buffer.to_bytes buf in let decode b = let open Result_syntax in let error = Error "invalid binary list" in let* l = let sl = Bytes.length b in if sl = 0 then error else let c = Char.code @@ Bytes.get b (sl - 1) in let* last_bit = if c = 0 then error else let rec aux i = if c land (1 lsl i) = 0 then aux (i + 1) else i + 1 in Ok (aux 0) in let bits = (sl * 8) - last_bit in Ok bits in let s = Bytes.to_seq b in let head s = (* This assertion won't fail even with malformed input. *) match s () with | Seq.Nil -> assert false | Seq.Cons (c, s) -> (Char.code c, s) in let rec read c rembit l s = if l = 0 then [] else let c, s, rembit = if rembit >= 1 then (c, s, rembit) else let c', s = head s in ((c * 256) + c', s, rembit + 8) in let rembit = rembit - 1 in let i = c lsr rembit in let c = c land ((1 lsl rembit) - 1) in i :: read c rembit (l - 1) s in Ok (read 0 0 l s) in conv_with_guard encode decode (Bounded.bytes 255) let segment_encoding = match entries with | 32 -> segment_encoding_32 | 2 -> segment_encoding_2 | _ -> (* Unsupported *) assert false let inode_proofs_encoding_2 a = conv_with_guard (function | [(0, x); (1, y)] -> (Some x, Some y) | [(0, x)] -> (Some x, None) | [(1, y)] -> (None, Some y) | [] -> invalid_arg "cannot encode ill-formed Merkle proof" | _ -> invalid_arg "cannot encode non binary proof tree") (function | Some x, Some y -> Ok [(0, x); (1, y)] | Some x, None -> Ok [(0, x)] | None, Some y -> Ok [(1, y)] | None, None -> Error "cannot decode ill-formed Merkle proof") (tup2 a a) let inode_proofs_encoding_gen a = (* When the number of proofs is large enough (>= Context.Conf.entries / 2), proofs are encoded as `array` instead of `list` for compactness. *) (* This encode assumes that proofs are ordered by its index. *) let encode_type v = if Compare.List_length_with.(v >= entries / 2) then `Array else `List in union ~tag_size:`Uint8 [ case ~title:"sparse_proof" (Tag 0) (obj1 (req "sparse_proof" (conv_with_guard (fun v -> List.map (fun (i, d) -> (i, Some d)) v) (fun v -> List.fold_right_e (fun (i, d) acc -> match d with | None -> Error "cannot decode ill-formed Merkle proof" | Some d -> Ok ((i, d) :: acc)) v []) (list (tup2 index_encoding a))))) (fun v -> if encode_type v = `List then Some v else None) (fun v -> v); case ~title:"dense_proof" (Tag 1) (obj1 (req "dense_proof" (Fixed.array entries a))) (fun v -> if encode_type v = `Array then ( let arr = Array.make entries None in (* The `a` passed to this encoding will be `option_inode_tree_encoding` and `option_inode_tree_encoding`, both encode `option` tags with its variant tag, thus this `option` wrapping won't increase the encoding size. *) List.iter (fun (i, d) -> arr.(i) <- Some d) v ; Some arr) else None) (fun v -> let res = ref [] in for i = Array.length v - 1 downto 0 do match v.(i) with None -> () | Some d -> res := (i, d) :: !res done ; !res); ] let inode_proofs_encoding = match entries with | 2 -> inode_proofs_encoding_2 | _ -> inode_proofs_encoding_gen let inode_encoding a = conv (fun {length; proofs} -> (length, proofs)) (fun (length, proofs) -> {length; proofs}) @@ obj2 length_field (req "proofs" (inode_proofs_encoding a)) let inode_extender_encoding a = conv (fun {length; segment; proof} -> (length, segment, proof)) (fun (length, segment, proof) -> {length; segment; proof}) @@ obj3 length_field (req "segment" segment_encoding) (req "proof" a) (* data-encoding.0.4/test/mu.ml for building mutually recursive data_encodings *) let _inode_tree_encoding, tree_encoding = let unoptionize enc = conv_with_guard (fun v -> Some v) (function | Some v -> Ok v | None -> Error "cannot decode ill-formed Merkle proof") enc in let mu_option_inode_tree_encoding tree_encoding = mu "inode_tree" (fun option_inode_tree_encoding -> let inode_tree_encoding = unoptionize option_inode_tree_encoding in union [ case ~title:"Blinded_inode" (Tag 0) (obj1 (req "blinded_inode" hash_encoding)) (function Some (Blinded_inode h) -> Some h | _ -> None) (fun h -> Some (Blinded_inode h)); case ~title:"Inode_values" (Tag 1) (obj1 (req "inode_values" (list (tup2 step_encoding tree_encoding)))) (function Some (Inode_values xs) -> Some xs | _ -> None) (fun xs -> Some (Inode_values xs)); case ~title:"Inode_tree" (Tag 2) (obj1 (req "inode_tree" (inode_encoding option_inode_tree_encoding))) (function Some (Inode_tree i) -> Some i | _ -> None) (fun i -> Some (Inode_tree i)); case ~title:"Inode_extender" (Tag 3) (obj1 (req "inode_extender" (inode_extender_encoding inode_tree_encoding))) (function | Some (Inode_extender i : inode_tree) -> Some i | _ -> None) (fun i : inode_tree option -> Some (Inode_extender i)); case ~title:"None" (Tag 4) (obj1 (req "none" null)) (function None -> Some () | Some _ -> None) (fun () -> None); ]) in let mu_option_tree_encoding : tree option encoding = mu "tree_encoding" (fun option_tree_encoding -> let tree_encoding = unoptionize option_tree_encoding in let option_inode_tree_encoding = mu_option_inode_tree_encoding tree_encoding in let inode_tree_encoding = unoptionize option_inode_tree_encoding in union [ case ~title:"Value" (Tag 0) (obj1 (req "value" value_encoding)) (function Some (Value v : tree) -> Some v | _ -> None) (fun v -> Some (Value v)); case ~title:"Blinded_value" (Tag 1) (obj1 (req "blinded_value" hash_encoding)) (function Some (Blinded_value hash) -> Some hash | _ -> None) (fun hash -> Some (Blinded_value hash)); case ~title:"Node" (Tag 2) (obj1 (req "node" (list (tup2 step_encoding tree_encoding)))) (function Some (Node sts : tree) -> Some sts | _ -> None) (fun sts -> Some (Node sts)); case ~title:"Blinded_node" (Tag 3) (obj1 (req "blinded_node" hash_encoding)) (function Some (Blinded_node hash) -> Some hash | _ -> None) (fun hash -> Some (Blinded_node hash)); case ~title:"Inode" (Tag 4) (obj1 (req "inode" (inode_encoding option_inode_tree_encoding))) (function Some (Inode i : tree) -> Some i | _ -> None) (fun i -> Some (Inode i)); case ~title:"Extender" (Tag 5) (obj1 (req "extender" (inode_extender_encoding inode_tree_encoding))) (function Some (Extender i) -> Some i | _ -> None) (fun i -> Some (Extender i)); case ~title:"None" (Tag 6) (obj1 (req "none" null)) (function None -> Some () | Some _ -> None) (fun () -> None); ]) in let tree_encoding = unoptionize mu_option_tree_encoding in let inode_tree_encoding = unoptionize @@ mu_option_inode_tree_encoding tree_encoding in (inode_tree_encoding, tree_encoding) let kinded_hash_encoding = union [ case ~title:"Value" (Tag 0) (obj1 (req "value" hash_encoding)) (function `Value ch -> Some ch | _ -> None) (fun ch -> `Value ch); case ~title:"Node" (Tag 1) (obj1 (req "node" hash_encoding)) (function `Node ch -> Some ch | _ -> None) (fun ch -> `Node ch); ] let elt_encoding = let open Stream in union [ case ~title:"Value" (Tag 0) (obj1 (req "value" value_encoding)) (function Value v -> Some v | _ -> None) (fun v -> Value v); case ~title:"Node" (Tag 1) (obj1 (req "node" (list (tup2 step_encoding kinded_hash_encoding)))) (function Node sks -> Some sks | _ -> None) (fun sks -> Node sks); case ~title:"Inode" (Tag 2) (* This option wrapping increases the encoding size. But stream encoding is basically larger than proof encoding, so I temporarily won't mind this increment. *) (obj1 (req "inode" (inode_encoding (option hash_encoding)))) (function Inode hinode -> Some hinode | _ -> None) (fun hinode -> Inode hinode); case ~title:"Inode_extender" (Tag 3) (obj1 (req "inode_extender" (inode_extender_encoding hash_encoding))) (function Inode_extender e -> Some e | _ -> None) (fun e -> Inode_extender e); ] let stream_encoding = conv List.of_seq List.to_seq (list elt_encoding) let encoding a = conv (fun {version; before; after; state} -> (version, before, after, state)) (fun (version, before, after, state) -> {version; before; after; state}) @@ obj4 (req "version" int16) (req "before" kinded_hash_encoding) (req "after" kinded_hash_encoding) (req "state" a) let tree_proof_encoding = encoding tree_encoding let stream_proof_encoding = encoding stream_encoding end (* Using `Data_encoding.Compact`. Harder to parse but more efficient *) module Make_V2 (Conf : sig val entries : int end) = struct open Tezos_context_sigs.Context.Proof_types module V1 = Make_V1 (Conf) open Data_encoding let entries = Conf.entries (* The code only supports branching factors 2 and 32 *) let () = assert (entries = 2 || entries = 32) let value_encoding : value Compact.t = let open Compact in let bytes_case name a b = let check_length s = let l = Bytes.length s in a <= l && l < b in case ~title:name (payload @@ Bounded.bytes (b - 1)) (fun s -> if check_length s then Some s else None) (fun s -> if check_length s then s else invalid_arg "cannot decode ill-formed Merkle proof") in union ~union_tag_bits:2 ~cases_tag_bits:0 [ bytes_case "short_bytes" 0 256; bytes_case "medium_bytes" 256 (256 * 256); (* The following case will be introduced when uint24 field is implemented in Data_enopding. *) (* bytes_case "long_bytes" (256 * 256 * 256); *) void_case ~title:"long_bytes"; (let check_length s = 256 * 256 <= Bytes.length s in case ~title:"unlimited_bytes" (payload bytes) (fun s -> if check_length s then Some s else None) (fun s -> if check_length s then s else invalid_arg "cannot decode ill-formed Merkle proof")); ] let length_field : int Compact.field = let open Compact in req "length" @@ conv Int64.of_int Int64.to_int int64 let step_encoding : step Data_encoding.t = V1.step_encoding let hash_encoding = Compact.payload V1.hash_encoding let segment_encoding = Compact.payload V1.segment_encoding let inode_proofs_encoding_2 a = let open Compact in conv (function | [(0, x); (1, y)] -> (Some x, Some y) | [(0, x)] -> (Some x, None) | [(1, y)] -> (None, Some y) | [] -> invalid_arg "cannot encode ill-formed Merkle proof" | _ -> invalid_arg "cannot encode non binary proof tree") (function | Some x, Some y -> [(0, x); (1, y)] | Some x, None -> [(0, x)] | None, Some y -> [(1, y)] | None, None -> invalid_arg "cannot decode ill-formed Merkle proof") (tup2 a a) let inode_proofs_encoding_32 a = (* When the number of proofs is large enough (>= Context.Conf.entries / 2), proofs are encoded as `array` instead of `list` for compactness. *) (* Due to the limitation of tag bits, we encode lists whose length is 15 as an array. *) (* This encode assumes that proofs are ordered by its index. *) let encode_type v = if Compare.List_length_with.(v < 15) then `List else `Array in let open Compact in (* When mu is introduced to `Data_encoding.Compact`, we may better use 5bit union as index_encoding. *) let index_encoding = uint8 in let a = make ~tag_size:(if tag_bit_count a = 0 then `Uint0 else `Uint8) a in union ~union_tag_bits:1 ~cases_tag_bits:4 [ case ~title:"sparse_proof" (obj1 (req "sparse_proof" (conv (fun v -> List.map (fun (i, d) -> (i, Some d)) v) (fun v -> List.fold_right (fun (i, d) acc -> match d with | None -> invalid_arg "cannot decode ill-formed Merkle proof" | Some d -> (i, d) :: acc) v []) (* 4bit share tag is required to store the length of sparse proof (0..14) *) (list ~bits:4 Data_encoding.(tup2 index_encoding a))))) (fun v -> if encode_type v = `List then Some v else None) (fun v -> v); case ~title:"dense_proof" (obj1 (req "dense_proof" (payload @@ Fixed.array entries a))) (fun v -> if encode_type v = `Array then ( let arr = Array.make entries None in (* The `a` passed to this encoding will be `option_inode_tree_encoding` and `option_inode_tree_encoding`, both encode `option` tags with its variant tag, thus this `option` wrapping won't increase the encoding size. *) List.iter (fun (i, d) -> arr.(i) <- Some d) v ; Some arr) else None) (fun v -> let res = ref [] in for i = Array.length v - 1 downto 0 do match v.(i) with None -> () | Some d -> res := (i, d) :: !res done ; !res); ] let inode_proofs_encoding = match entries with | 2 -> inode_proofs_encoding_2 | 32 -> inode_proofs_encoding_32 | _ -> (* Unsupported *) assert false let inode_encoding a = let open Compact in conv (fun {length; proofs} -> (length, proofs)) (fun (length, proofs) -> {length; proofs}) @@ obj2 length_field (req "proofs" (inode_proofs_encoding a)) let inode_extender_encoding a = let open Compact in conv (fun {length; segment; proof} -> (length, segment, proof)) (fun (length, segment, proof) -> {length; segment; proof}) @@ obj3 length_field (req "segment" segment_encoding) (req "proof" a) let bits_of_node_list = match entries with | 32 -> 6 (* 6bit :: 0 - 62 *) | 2 -> 2 (* 2bit :: 0 - 2 *) | _ -> (* Unsupported *) assert false (* data-encoding.0.4/test/mu.ml for building mutually recursive data_encodings *) let _inode_tree_encoding, tree_encoding = let unoptionize enc = conv_with_guard (fun v -> Some v) (function | Some v -> Ok v | None -> Error "cannot decode ill-formed Merkle proof") enc in let mu_option_inode_tree_encoding tree_encoding = mu "inode_tree" (fun option_inode_tree_encoding -> let inode_tree_encoding = unoptionize option_inode_tree_encoding in let open Compact in (* Variant layouts and required shared tag bits. 0xxxxxxx :: Inode_tree (requires 7bits) 10xxxxxx :: Inode_values (requires 6bits) 1100xxxx :: Blinded_inode (requires 0bits) 1101xxxx :: Inode_extender (requires 2bits) 1110xxxx :: None (requires 0bits) *) make ~tag_size:`Uint8 @@ union ~union_tag_bits:1 ~cases_tag_bits:7 [ case ~title:"Inode_tree" (obj1 (req "inode_tree" (inode_encoding (payload option_inode_tree_encoding)))) (function Some (Inode_tree i) -> Some i | _ -> None) (fun i -> Some (Inode_tree i)); case ~title:"other_inode_trees" (obj1 (req "other_inode_trees" (union ~union_tag_bits:1 ~cases_tag_bits:6 [ case ~title:"Inode_values" (obj1 (req "inode_values" (list ~bits:bits_of_node_list Data_encoding.( tup2 step_encoding tree_encoding)))) (function | Some (Inode_values xs) -> Some xs | _ -> None) (fun xs -> Some (Inode_values xs)); case ~title:"other_inode_trees" (obj1 (req "other_inode_trees" (union ~union_tag_bits:2 ~cases_tag_bits:4 [ case ~title:"Blinded_inode" (obj1 (req "blinded_inode" hash_encoding)) (function | Some (Blinded_inode h) -> Some h | _ -> None) (fun h -> Some (Blinded_inode h)); case ~title:"Inode_extender" (obj1 (req "inode_extender" (inode_extender_encoding (payload inode_tree_encoding)))) (function | Some (Inode_extender i : inode_tree) -> Some i | _ -> None) (fun i : inode_tree option -> Some (Inode_extender i)); case (obj1 (req "none" unit)) ~title:"None" (function | None -> Some () | Some _ -> None) (fun () -> None); ]))) (function | Some (Inode_values _) -> None | v -> Some v) (fun v -> v); ]))) (function Some (Inode_tree _) -> None | v -> Some v) (fun v -> v); ]) in let mu_option_tree_encoding : tree option encoding = mu "tree_encoding" (fun option_tree_encoding -> let tree_encoding = unoptionize option_tree_encoding in let option_inode_tree_encoding = mu_option_inode_tree_encoding tree_encoding in let inode_tree_encoding = unoptionize option_inode_tree_encoding in let open Compact in (* Variant layouts and required shared tag bits. 0xxxxxxx :: Inode (requires 7bits) 10xxxxxx :: Node (requires 6bits) 11000xxx :: Value (requires 2bits) 11001xxx :: Blinded_value (requires 0bits) 11010xxx :: Blinded_node (requires 0bits) 11011xxx :: Extender (requires 2bits) 11100xxx :: None (requires 0bits) *) make ~tag_size:`Uint8 @@ union ~union_tag_bits:1 ~cases_tag_bits:7 [ case ~title:"Inode" (obj1 (req "inode" (inode_encoding (payload option_inode_tree_encoding)))) (function Some (Inode i : tree) -> Some i | _ -> None) (fun i -> Some (Inode i)); case ~title:"other_trees" (obj1 (req "other_trees" (union ~union_tag_bits:1 ~cases_tag_bits:6 [ case ~title:"Node" (obj1 (req "node" (list ~bits:bits_of_node_list Data_encoding.( tup2 step_encoding tree_encoding)))) (function | Some (Node sts : tree) -> Some sts | _ -> None) (fun sts -> Some (Node sts)); case ~title:"other_trees" (obj1 (req "other_trees" (union ~union_tag_bits:3 ~cases_tag_bits:3 [ case ~title:"Value" (obj1 (req "value" value_encoding)) (function | Some (Value v : tree) -> Some v | _ -> None) (fun v -> Some (Value v)); case ~title:"Blinded_value" (obj1 (req "blinded_value" hash_encoding)) (function | Some (Blinded_value hash) -> Some hash | _ -> None) (fun hash -> Some (Blinded_value hash)); case ~title:"Blinded_node" (obj1 (req "blinded_node" hash_encoding)) (function | Some (Blinded_node hash) -> Some hash | _ -> None) (fun hash -> Some (Blinded_node hash)); case ~title:"Extender" (obj1 (req "extender" (inode_extender_encoding (payload inode_tree_encoding)))) (function | Some (Extender i) -> Some i | _ -> None) (fun i -> Some (Extender i)); case (obj1 (req "none" unit)) ~title:"None" (function | None -> Some () | Some _ -> None) (fun () -> None); ]))) (function Some (Node _) -> None | v -> Some v) (fun v -> v); ]))) (function Some (Inode _) -> None | v -> Some v) (fun v -> v); ]) in let tree_encoding = unoptionize mu_option_tree_encoding in let inode_tree_encoding = unoptionize @@ mu_option_inode_tree_encoding tree_encoding in (inode_tree_encoding, tree_encoding) let kinded_hash_encoding = let open Compact in union ~union_tag_bits:1 ~cases_tag_bits:0 [ case ~title:"Value" (obj1 (req "value" hash_encoding)) (function `Value ch -> Some ch | _ -> None) (fun ch -> `Value ch); case ~title:"Node" (obj1 (req "node" hash_encoding)) (function `Node ch -> Some ch | _ -> None) (fun ch -> `Node ch); ] let elt_encoding = let open Stream in let open Compact in (* Variant layouts and required shared tag bits. 0xxxxxxx :: Inode (requires 7bits) 10xxxxxx :: Node (requires 6bits) 11000xxx :: Value (requires 2bits) 11011xxx :: Inode_extender (requires 2bits) *) union ~union_tag_bits:1 ~cases_tag_bits:7 [ case ~title:"Inode" (obj1 (req "inode" (inode_encoding (option hash_encoding)))) (function Inode hinode -> Some hinode | _ -> None) (fun hinode -> Inode hinode) (* This option wrapping increases the encoding size when `entries = 32`. But stream encoding is basically larger than proof encoding, so I temporarily won't mind this increment. *); case ~title:"other_elts" (obj1 (req "other_elts" (union ~union_tag_bits:1 ~cases_tag_bits:6 [ case ~title:"Node" (obj1 (req "node" (list ~bits:bits_of_node_list Data_encoding.( tup2 step_encoding (make ~tag_size:`Uint8 kinded_hash_encoding))))) (function Node sks -> Some sks | _ -> None) (fun sks -> Node sks); case ~title:"other_elts" (obj1 (req "other_elts" (union ~union_tag_bits:1 ~cases_tag_bits:5 [ case ~title:"Value" (obj1 (req "value" value_encoding)) (function Value v -> Some v | _ -> None) (fun v -> Value v); case ~title:"Inode_extender" (obj1 (req "inode_extender" (inode_extender_encoding hash_encoding))) (function | Inode_extender e -> Some e | _ -> None) (fun e -> Inode_extender e); ]))) (function Node _ -> None | e -> Some e) (fun e -> e); ]))) (function Inode _ -> None | e -> Some e) (fun e -> e); ] let stream_encoding = (* Encoding method should be revisited after the actual stream length is determined. *) conv List.of_seq List.to_seq (list @@ Compact.make ~tag_size:`Uint8 elt_encoding) let encoding a = let open Compact in conv (fun {version; before; after; state} -> (version, before, after, state)) (fun (version, before, after, state) -> {version; before; after; state}) @@ obj4 (req "version" (payload int16)) (req "before" kinded_hash_encoding) (req "after" kinded_hash_encoding) (req "state" a) let tree_proof_encoding = let open Compact in make ~tag_size:`Uint8 @@ encoding (payload tree_encoding) let stream_proof_encoding = let open Compact in make ~tag_size:`Uint8 @@ encoding (payload stream_encoding) end module V1 = struct module Tree32 = Make_V1 (struct let entries = 32 end) module Tree2 = Make_V1 (struct let entries = 2 end) end module V2 = struct module Tree32 = Make_V2 (struct let entries = 32 end) module Tree2 = Make_V2 (struct let entries = 2 end) end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 DaiLambda, Inc. <contact@dailambda.jp> *) (* *) (* 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. *) (* *) (*****************************************************************************)
commitment_repr.ml
type t = { blinded_public_key_hash : Blinded_public_key_hash.t; amount : Tez_repr.t; } let encoding = let open Data_encoding in conv (fun {blinded_public_key_hash; amount} -> (blinded_public_key_hash, amount)) (fun (blinded_public_key_hash, amount) -> {blinded_public_key_hash; amount}) (tup2 Blinded_public_key_hash.encoding Tez_repr.encoding)
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
compose_fmpq_mpoly_gen.c
#include "fmpq_mpoly.h" /* evaluate B(x_1,...,x_n) at x_i = y_c[i], y_j are vars of ctxAC */ void fmpq_mpoly_compose_fmpq_mpoly_gen(fmpq_mpoly_t A, const fmpq_mpoly_t B, const slong * c, const fmpq_mpoly_ctx_t ctxB, const fmpq_mpoly_ctx_t ctxAC) { fmpq_set(A->content, B->content); fmpz_mpoly_compose_fmpz_mpoly_gen(A->zpoly, B->zpoly, c, ctxB->zctx, ctxAC->zctx); fmpq_mpoly_reduce(A, ctxAC); return; }
/* Copyright (C) 2020 Daniel Schultz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
test_fast.ml
open Tztest module Preimage_map = Map.Make (String) open Wasm_utils let apply_fast ?(images = Preimage_map.empty) counter tree = let open Lwt.Syntax in let run_counter = ref 0l in let reveal_builtins = Some Tezos_scoru_wasm.Builtins. { reveal_preimage = (fun hash -> match Preimage_map.find hash images with | None -> Stdlib.failwith "Failed to find preimage" | Some preimage -> Lwt.return preimage); reveal_metadata = (fun () -> Stdlib.failwith "reveal_preimage is not available"); } in let+ tree = Wasm_utils.eval_until_input_requested ~reveal_builtins (* We override the builtins to provide our own [reveal_preimage] implementation. This allows us to run Fast Exec with kernels that want to reveal stuff. *) ~after_fast_exec:(fun () -> run_counter := Int32.succ !run_counter) ~fast_exec:true ~max_steps:Int64.max_int tree in if counter > 0l then (* Assert that the FE actual ran. We must consider that before the first message is inserted, FE is unlikely to run. *) if !run_counter <> 1l then Stdlib.failwith "Fast Execution was expected to run!" ; tree let rec apply_slow ?images tree = let open Lwt.Syntax in let* tree = Wasm_utils.eval_until_input_or_reveal_requested ~fast_exec:false ~max_steps:Int64.max_int tree in (* Sometimes the evaluation will stop when a revelation is required. We don't want to expose this intermediate state because the Fast Execution doesn't either. The following step takes care of that by trying to satisfy the revelation request. *) (check_reveal [@tailcall]) ?images tree and check_reveal ?(images = Preimage_map.empty) tree = let open Lwt.Syntax in let* info = Wasm_utils.Wasm.get_info tree in match info.input_request with | Reveal_required (Reveal_raw_data hash) -> ( match Preimage_map.find hash images with | None -> Lwt.return tree | Some preimage -> let* tree = Wasm_utils.Wasm.reveal_step (Bytes.of_string preimage) tree in (apply_slow [@tailcall]) ~images tree) | _ -> Lwt.return tree let test_against_both ?images ~from_binary ~kernel ~messages () = let open Lwt.Syntax in let make_folder apply (tree, counter, hashes) message = let* tree = apply counter tree in let hash1 = Tezos_context_memory.Context_binary.Tree.hash tree in let* stuck = Wasm_utils.Wasm.Internal_for_tests.is_stuck tree in assert (Option.is_none stuck) ; let* info = Wasm_utils.Wasm.get_info tree in assert (info.input_request = Input_required) ; let+ tree = Wasm_utils.set_full_input_step [message] counter tree in let hash2 = Tezos_context_memory.Context_binary.Tree.hash tree in (tree, Int32.succ counter, hash1 :: hash2 :: hashes) in let* initial_tree = Wasm_utils.initial_tree ~max_tick:Int64.max_int ~from_binary kernel in let run_with apply = let* tree, counter, hashes = List.fold_left_s (make_folder apply) (initial_tree, 0l, []) messages in let+ tree = apply counter tree in let hash = Tezos_context_memory.Context_binary.Tree.hash tree in hash :: hashes in let* fast_hashes = run_with (apply_fast ?images) in let* slow_hashes = run_with (fun _ -> apply_slow ?images) in assert (List.equal Context_hash.equal slow_hashes fast_hashes) ; Lwt_result_syntax.return_unit let test_computation = Wasm_utils.test_with_kernel "computation" (fun kernel -> (* Providing 4 empty messages basically means calling the kernel entrypoint 4 times. *) test_against_both ~from_binary:true ~kernel ~messages:[""; ""; ""; ""] ()) let test_store_read_write = let kernel = {| (module (import "smart_rollup_core" "write_debug" (func $write_debug (param i32 i32)) ) (import "smart_rollup_core" "store_write" (func $store_write (param i32 i32 i32 i32 i32) (result i32)) ) (import "smart_rollup_core" "store_read" (func $store_read (param i32 i32 i32 i32 i32) (result i32)) ) (memory 1) (export "memory" (memory 0)) (data (i32.const 0) "Hello World") (data (i32.const 100) "/foo") (func (export "kernel_run") (local $n i64) (call $write_debug ;; Memory address and length of the string to log ;; Should be "Hello" as defined above (i32.const 0) (i32.const 5) ) (call $write_debug ;; Memory address and length of the string to log ;; Should be "World" as defined above (i32.const 6) (i32.const 5) ) (call $write_debug ;; Memory address and length of the string to log ;; Should be "Hello World" as defined above (i32.const 0) (i32.const 11) ) ;; Write the initial value to the durable store (call $store_write ;; Memory address and length of the store path (i32.const 100) (i32.const 4) ;; Offset into the store value (i32.const 0) ;; Memory address and length of the payload to write (i32.const 1000) (i32.const 4) ) (drop) ;; Set the loop counter (local.set $n (i64.const 100)) (loop ;; Read from store to memory (call $store_read ;; Memory address and length of the store path (i32.const 100) (i32.const 4) ;; Offset into the store value (i32.const 0) ;; Memory address and length of the read buffer (i32.const 1000) (i32.const 4) ;; Bytes to write ) (drop) ;; Increment the value in memory (i32.store (i32.const 1000) (i32.add (i32.load (i32.const 1000)) (i32.const 1))) ;; Write value from memory to durable store (call $store_write ;; Memory address and length of the store path (i32.const 100) (i32.const 4) ;; Offset into the store value (i32.const 0) ;; Memory address and length of the payload to write (i32.const 1000) (i32.const 4) ) (drop) ;; Decrement loop counter (local.set $n (i64.sub (local.get $n) (i64.const 1))) ;; Check if we ought to loop again (i32.eq (i32.const 0) (i64.eq (local.get $n) (i64.const 0))) (br_if 0) ) ) ) |} in test_against_both ~from_binary:false ~kernel ~messages:(List.repeat 100 "") let test_read_input = let kernel = {| (module (import "smart_rollup_core" "read_input" (func $read_input (param i32 i32 i32) (result i32)) ) (import "smart_rollup_core" "write_output" (func $write_output (param i32 i32) (result i32)) ) (import "smart_rollup_core" "write_debug" (func $write_debug (param i32 i32)) ) (memory 1) (export "memory" (memory 0)) (data (i32.const 1000) "kernel_run called") (func (export "kernel_run") (call $write_debug (i32.const 1000) ;; Memory address (i32.const 17) ;; length of the string to log ) ;; Should print "kernel_run called" (call $read_input (i32.const 100) ;; address to write the level (4b) (i32.const 104) ;; address to write the message counter (8b) (i32.const 112) ;; address to write the read input (i32.const 4) ;; length of the input ) ;; should fill the bytes 100-116 with level, msg counter and the data "abcd" (drop) ;; we don't care about the result (call $write_output (i32.const 100) ;; source address (i32.const 16) ;; number of bytes ) ;; writes the read level, msg counter and the data "abcd" (drop) ;; we don't care about the result of write_output (drop) ;; we don't care about the result of write_output ) ) |} in let msg = "abcd" in (* We want to produce more than 255 levels such that, when the level is written in the memory, its multi-byte representation is tested for correctness. If the number were a single byte the test would have been less relevant*) let no_of_levels = 257 in test_against_both ~from_binary:false ~kernel ~messages:(List.repeat no_of_levels msg) let test_big_address = let kernel = {| (module (type $read_t (func (param i32 i32 i32) (result i32))) (import "smart_rollup_core" "read_input" (func $read_input (type $read_t))) (memory 65536) (export "mem" (memory 0)) (func (export "kernel_run") (call $read_input (i32.const 4_294_967_100) ;; addr_info (i32.const 4_294_967_196) ;; (-100) (i32.const 4)) (drop) ) ) |} in let msg = "abcd" in test_against_both ~from_binary:false ~kernel ~messages:[msg] let test_reveal_preimage = let example_hash = "this represents the 33-byte hash " in let example_preimage = "This is the expected preimage" in let images = Preimage_map.singleton example_hash example_preimage in let kernel = Format.asprintf {| (module (import "smart_rollup_core" "store_write" (func $store_write (param i32 i32 i32 i32 i32) (result i32)) ) (import "smart_rollup_core" "reveal_preimage" (func $reveal_preimage (param i32 i32 i32 i32) (result i32)) ) (memory 1) (export "memory" (memory 0)) (data (i32.const 0) "%s") ;; The hash we want to reveal (data (i32.const 100) "/foo") (func (export "kernel_run") (local $len i32) ;; Reveal something (call $reveal_preimage ;; Address of the hash (i32.const 0) ;; size of the hash (i32.const 33) ;; Destination address and length (i32.const 1000) (i32.const 1000) ) (local.set $len) ;; Write the preimage to the output buffer (call $store_write ;; Key address and length (i32.const 100) (i32.const 4) ;; Offset into the target value (i32.const 0) ;; Memory address and length of the payload to write (i32.const 1000) (local.get $len) ) (drop) ) ) |} example_hash in test_against_both ~images ~from_binary:false ~kernel ~messages:[""; ""] let test_tx = let open Lwt.Syntax in Wasm_utils.test_with_kernel "tx-kernel-no-verif" (fun kernel -> let* messages = Wasm_utils.read_test_messages ["deposit.out"; "withdrawal.out"] in test_against_both ~from_binary:true ~kernel ~messages ()) let test_compute_step_many_pauses_at_snapshot_when_flag_set = Wasm_utils.test_with_kernel "computation" (fun kernel -> let open Lwt_result_syntax in let reveal_builtins = Tezos_scoru_wasm.Builtins. { reveal_preimage = (fun _ -> Stdlib.failwith "reveal_preimage is not available"); reveal_metadata = (fun () -> Stdlib.failwith "reveal_metadata is not available"); } in let*! initial_tree = Wasm_utils.initial_tree ~max_tick:Int64.max_int ~from_binary:true kernel in (* Supply input messages manually in order to have full control over tick_state we are in *) let*! tree = Wasm_utils.set_sol_input 0l initial_tree in let*! tree = Wasm_utils.set_internal_message 0l Z.one "message" tree in let*! tree = Wasm_utils.set_eol_input 0l (Z.of_int 2) tree in let*! tick_state = Wasm.Internal_for_tests.get_tick_state tree in (* Check precondition that we are not in Snapshot *) assert (tick_state == Padding) ; let*! fast_tree, _ = Wasm_utils.Wasm_fast.compute_step_many ~reveal_builtins ~write_debug:Noop ~stop_at_snapshot:true ~max_steps:Int64.max_int tree in let*! slow_tree, _ = Wasm_utils.Wasm.compute_step_many ~reveal_builtins ~stop_at_snapshot:true ~max_steps:Int64.max_int tree in let hash_fast = Tezos_context_memory.Context_binary.Tree.hash fast_tree in let hash_slow = Tezos_context_memory.Context_binary.Tree.hash slow_tree in assert (Context_hash.equal hash_fast hash_slow) ; return ()) let tests = [ tztest "Big addresses are working correctly" `Quick test_big_address; tztest "Computation kernel" `Quick test_computation; tztest "Store read/write kernel" `Quick test_store_read_write; tztest "read_input" `Quick test_read_input; tztest "Reveal_preimage kernel" `Quick test_reveal_preimage; (* TODO: https://gitlab.com/tezos/tezos/-/issues/3729 Enable back this test when the transaction kernel has been updated. *) (* tztest "TX kernel" `Quick test_tx; *) tztest "compute_step_many pauses at snapshot" `Quick test_compute_step_many_pauses_at_snapshot_when_flag_set; ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 TriliTech <contact@trili.tech> *) (* *) (* 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. *) (* *) (*****************************************************************************)
native_generic.ml
open Types module Make (M : Owl_types_ndarray_algodiff.Sig with type elt = float) = struct module C = Common.Make (M) type f_t = M.arr -> float -> M.arr module M = struct include M (* TODO: implement this in owl *) let ( $* ) = M.scalar_mul let ( *$ ) = M.mul_scalar let ( /$ ) = M.div_scalar let ( + ) = M.add end let prepare step f y0 tspec () = let tspan, dt = match tspec with | T1 { t0; duration; dt } -> (t0, t0 +. duration), dt | T2 { tspan; dt } -> tspan, dt | T3 _ -> raise Owl_exception.(NOT_IMPLEMENTED "T3 not implemented") in let step = step f ~dt in C.integrate ~step ~tspan ~dt y0 let adaptive_prepare step f y0 tspec () = let (t0, t1), _dt = match tspec with | T1 { t0; duration; dt } -> (t0, t0 +. duration), dt | T2 { tspan; dt } -> tspan, dt | T3 _ -> raise Owl_exception.(NOT_IMPLEMENTED "T3 not implemented") in let dtmax = (t1 -. t0) /. 128.0 in let step = step ~dtmax f in C.adaptive_integrate ~step ~tspan:(t0, t1) ~dtmax y0 let euler_s (f : f_t) ~dt y0 t0 = let y = M.(y0 + (f y0 t0 *$ dt)) in let t = t0 +. dt in y, t let euler = (module struct type state = M.arr type f = M.arr -> float -> M.arr type step_output = M.arr * float type solve_output = M.arr * M.arr let step = euler_s let solve = prepare step end : Solver with type state = M.arr and type f = M.arr -> float -> M.arr and type step_output = M.arr * float and type solve_output = M.arr * M.arr) let midpoint_s (f : f_t) ~dt y0 t0 = let k1 = M.(dt $* f y0 t0) in let k2 = M.(dt $* f (y0 + (k1 *$ 0.5)) (t0 +. (0.5 *. dt))) in let y = M.(y0 + k2) in let t = t0 +. dt in y, t let midpoint = (module struct type state = M.arr type f = M.arr -> float -> M.arr type step_output = M.arr * float type solve_output = M.arr * M.arr let step = midpoint_s let solve = prepare step end : Solver with type state = M.arr and type f = M.arr -> float -> M.arr and type step_output = M.arr * float and type solve_output = M.arr * M.arr) let rk4_s (f : f_t) ~dt y0 t0 = let k1 = M.(dt $* f y0 t0) in let k2 = M.(dt $* f (y0 + (k1 *$ 0.5)) (t0 +. (0.5 *. dt))) in let k3 = M.(dt $* f (y0 + (k2 *$ 0.5)) (t0 +. (0.5 *. dt))) in let k4 = M.(dt $* f (y0 + k3) (t0 +. dt)) in let dy = M.((k1 + (2. $* k2) + (2. $* k3) + k4) /$ 6.) in let y = M.(y0 + dy) in let t = t0 +. dt in y, t let rk4 = (module struct type state = M.arr type f = M.arr -> float -> M.arr type step_output = M.arr * float type solve_output = M.arr * M.arr let step = rk4_s let solve = prepare step end : Solver with type state = M.arr and type f = M.arr -> float -> M.arr and type step_output = M.arr * float and type solve_output = M.arr * M.arr) let rk23_s ~tol ~dtmax f = (* Bogacki-Shampine parameters *) let a = [| 0.0; 0.5; 0.75 |] in let b = [| [||]; [| 0.5 |]; [| 0.0; 3.0 /. 4.0 |] |] in let c = [| 2.0 /. 9.0; 1.0 /. 3.0; 4.0 /. 9.0 |] in let dc = [| c.(0) -. (7.0 /. 24.0) ; c.(1) -. (1.0 /. 4.0) ; c.(2) -. (1.0 /. 3.0) ; -1.0 /. 8.0 |] in fun ~dt y0 t0 -> (* Compute k_i function values. *) let k1 = f y0 t0 in let k2 = M.(f (y0 + (k1 *$ (dt *. b.(1).(0)))) (t0 +. (a.(1) *. dt))) in let k3 = M.(f (y0 + (k2 *$ (dt *. b.(2).(1)))) (t0 +. (a.(2) *. dt))) in let t = t0 +. dt in let y = M.(y0 + (k1 *$ (dt *. c.(0))) + (k2 *$ (dt *. c.(1))) + (k3 *$ (dt *. c.(2)))) in let k4 = f y t in (* Estimate current error and current maximum error.*) let err = M.l1norm' M.(dt $* (k1 *$ dc.(0)) + (k2 *$ dc.(1)) + (k3 *$ dc.(2)) + (k4 *$ dc.(3))) in let err_max = tol *. max (M.l1norm' y0) 1.0 in (* Update step size *) let dt = if err > 0. then min dtmax (0.85 *. dt *. ((err_max /. err) ** 0.2)) else dt in y, t, dt, err <= err_max let rk23 ~tol ~dtmax = (module struct type state = M.arr type f = M.arr -> float -> M.arr type step_output = M.arr * float * float * bool type solve_output = M.arr * M.arr let step = rk23_s ~tol ~dtmax let solve = adaptive_prepare (rk23_s ~tol) end : Solver with type state = M.arr and type f = M.arr -> float -> M.arr and type step_output = M.arr * float * float * bool and type solve_output = M.arr * M.arr) let rk45_s ~tol ~dtmax f = (* Cash-Karp parameters *) let a = [| 0.0; 0.2; 0.3; 0.6; 1.0; 0.875 |] in let b = [| [||] ; [| 0.2 |] ; [| 3.0 /. 40.0; 9.0 /. 40.0 |] ; [| 0.3; -0.9; 1.2 |] ; [| -11.0 /. 54.0; 2.5; -70.0 /. 27.0; 35.0 /. 27.0 |] ; [| 1631.0 /. 55296.0 ; 175.0 /. 512.0 ; 575.0 /. 13824.0 ; 44275.0 /. 110592.0 ; 253.0 /. 4096.0 |] |] in let c = [| 37.0 /. 378.0; 0.0; 250.0 /. 621.0; 125.0 /. 594.0; 0.0; 512.0 /. 1771.0 |] in let dc = [| c.(0) -. (2825.0 /. 27648.0) ; c.(1) -. 0.0 ; c.(2) -. (18575.0 /. 48384.0) ; c.(3) -. (13525.0 /. 55296.0) ; c.(4) -. (277.00 /. 14336.0) ; c.(5) -. 0.25 |] in fun ~dt y0 t0 -> (* Compute k_i function values. *) let k1 = f y0 t0 in let k2 = M.(f (y0 + (k1 *$ (dt *. b.(1).(0)))) (t0 +. (a.(1) *. dt))) in let k3 = M.( f (y0 + (k1 *$ (dt *. b.(2).(0))) + (k2 *$ (dt *. b.(2).(1)))) (t0 +. (a.(2) *. dt))) in let k4 = M.( f (y0 + (k1 *$ (dt *. b.(3).(0))) + (k2 *$ (dt *. b.(3).(1))) + (k3 *$ (dt *. b.(3).(2)))) (t0 +. (a.(3) *. dt))) in let k5 = M.( f (y0 + (k1 *$ (dt *. b.(4).(0))) + (k2 *$ (dt *. b.(4).(1))) + (k3 *$ (dt *. b.(4).(2))) + (k4 *$ (dt *. b.(4).(3)))) (t0 +. (a.(4) *. dt))) in let k6 = M.( f (y0 + (k1 *$ (dt *. b.(5).(0))) + (k2 *$ (dt *. b.(5).(1))) + (k3 *$ (dt *. b.(5).(2))) + (k4 *$ (dt *. b.(5).(3))) + (k5 *$ (dt *. b.(5).(4)))) (t0 +. (a.(5) *. dt))) in (* Estimate current error and current maximum error.*) let err = M.l1norm' M.( dt $* (k1 *$ dc.(0)) + (k2 *$ dc.(1)) + (k3 *$ dc.(2)) + (k4 *$ dc.(3)) + (k5 *$ dc.(4)) + (k6 *$ dc.(5))) in let err_max = tol *. max (M.l1norm' y0) 1.0 in (* Update step size *) let dt = if err > 0. then min dtmax (0.85 *. dt *. ((err_max /. err) ** 0.2)) else dt in let t = t0 +. dt in let y = M.( y0 + (k1 *$ (dt *. c.(0))) + (k2 *$ (dt *. c.(1))) + (k3 *$ (dt *. c.(2))) + (k4 *$ (dt *. c.(3))) + (k5 *$ (dt *. c.(4))) + (k6 *$ (dt *. c.(5)))) in y, t, dt, err <= err_max let rk45 ~tol ~dtmax = (module struct type state = M.arr type f = M.arr -> float -> M.arr type step_output = M.arr * float * float * bool type solve_output = M.arr * M.arr let step = rk45_s ~tol ~dtmax let solve = adaptive_prepare (rk45_s ~tol) end : Solver with type state = M.arr and type f = M.arr -> float -> M.arr and type step_output = M.arr * float * float * bool and type solve_output = M.arr * M.arr) (* ----- helper functions ----- *) let to_state_array ?(axis = 0) (dim1, dim2) ys = let unpack = if axis = 0 then M.to_rows (* TODO: add to_cols to types_ndarray_basic *) else if axis = 1 then M.to_cols else raise Owl_exception.INDEX_OUT_OF_BOUND in let ys = unpack ys in if M.numel ys.(0) <> dim1 * dim2 then raise Owl_exception.(DIFFERENT_SHAPE ([| M.numel ys.(0) |], [| dim1 * dim2 |])); Array.map (fun y -> M.reshape y [| dim1; dim2 |]) ys end
(* * OWL - OCaml Scientific and Engineering Computing * OWL-ODE - Ordinary Differential Equation Solvers * * Copyright (c) 2019 Ta-Chu Kao <tck29@cam.ac.uk> * Copyright (c) 2019 Marcello Seri <m.seri@rug.nl> *)
test_mappable.ml
open OUnit (* The purpose of this test file is to test properties that should be verified by all instances of a given interface, here BatInterfaces.Mappable. It is very minimal for now : it only check for one property, and only a few of the Mappable modules (it is actually a regression test for a very specific bug). New properties will be added, and hopefully they will be verified against all Mappable modules. *) module TestMappable (M : sig include BatEnum.Enumerable include BatInterfaces.Mappable with type 'a mappable = 'a enumerable end) = struct (* The property we test is that the order in which the [map] function traverse the structure (applying a given function on each element) is the same as the order of the [enum] function of the module (the order in which the elements are produced in the enumeration). *) let test_map_evaluation_order printer t = let elems_in_enum_order = BatList.of_enum (M.enum t) in let elems_in_map_order = let li = ref [] in ignore (M.map (fun x -> li := x :: !li) t); List.rev !li in assert_equal ~printer:(BatIO.to_string (BatList.print printer)) elems_in_enum_order elems_in_map_order end let test_list_mappable () = let module T = TestMappable(BatList) in T.test_map_evaluation_order BatInt.print [1; 2; 3] let test_array_mappable () = let module T = TestMappable(BatArray) in T.test_map_evaluation_order BatInt.print [|1; 2; 3|] (* let test_pair_mappable () = let module T = TestMappable(BatTuple.Tuple2) in T.test_map_evaluation_order BatInt.print (1, 2) *) let tests = "Mappable" >::: [ "Array" >:: test_array_mappable; "List" >:: test_list_mappable; (* "Pair" >:: test_pair_mappable;*) ]
client_commands.mli
open Client_context type command = full Clic.command type network = [`Mainnet | `Alphanet | `Zeronet | `Sandbox] exception Version_not_found val register : Protocol_hash.t -> (network option -> command list) -> unit val commands_for_version : Protocol_hash.t -> network option -> command list val get_versions : unit -> (Protocol_hash.t * (network option -> command list)) list
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
Nanotest.ml
let fmt = Format.asprintf module C = struct let color_pp color = fmt "\027[%dm%s\027[0m" (match color with | `Black -> 30 | `Red -> 31 | `Green -> 32 | `Yellow -> 33 | `Blue -> 34 | `Magenta -> 35 | `Cyan -> 36 | `White -> 37) let blue = color_pp `Blue let red = color_pp `Red let yellow = color_pp `Yellow let magenta = color_pp `Magenta let cyan = color_pp `Cyan let white = color_pp `White let green = color_pp `Green let bright_white x = fmt "\027[1;37m%s\027[0m" x let bright_blue x = fmt "\027[1;34m%s\027[0m" x let bright_magenta x = fmt "\027[1;35m%s\027[0m" x let violet x = fmt "\027[0;34m%s\027[0m" x let bright_red x = fmt "\027[1;31m%s\027[0m" x let bright_green x = fmt "\027[1;32m%s\027[0m" x let start_bright_white = fmt "\027[1;37m" let start_white = fmt "\027[37m" let end_color = "\027[0m" let italic x = "\027[3m" ^ x ^ "\027[0m" let underline x = "\027[4m" ^ x ^ "\027[0m" let blink x = "\027[5m" ^ x ^ "\027[0m" end module type Testable = sig type t val equal : t -> t -> bool val pp : Format.formatter -> t -> unit end type 'a testable = (module Testable with type t = 'a) module Testable = struct let pp (type a) (t: a testable) = let (module T) = t in T.pp let equal (type a) (t: a testable) = let (module T) = t in T.equal end let time ?fmt f x = let t0 = Unix.gettimeofday () in let fx = f x in let t1 = Unix.gettimeofday () -. t0 in let () = match fmt with | Some fmt -> Printf.eprintf "%s\n" (fmt fx t1) | None -> Printf.eprintf "Elapsed time: %f sec\n" t1 in fx let test ?(verbose = true) ty msg ~actual ~expected () = let ok = Testable.equal ty actual expected in begin if not ok then begin Fmt.pr " %s %s@." (C.bright_red "✗") (C.bright_white msg); Fmt.pr " - %a@." (Testable.pp ty) expected; Fmt.pr " + %a@." (Testable.pp ty) actual end else if verbose then Fmt.pr " %s %s@." (C.bright_green "✓") (C.bright_white msg) end; ok let raises ?(verbose = true) msg ~exn f () = let state = try let _ = f () in `No_exn with e -> if e = exn then `Ok else `Other e in match state with | `No_exn -> Fmt.pr " %s %s@." (C.bright_red "✗") (C.bright_white msg); Fmt.pr " * did not raise %s@." (Printexc.to_string exn); false | `Other actual -> Fmt.pr " %s %s@." (C.bright_red "✗") (C.bright_white msg); Fmt.pr " - %s@." (Printexc.to_string exn); Fmt.pr " + %s@." (Printexc.to_string actual); false | `Ok -> if verbose then Fmt.pr " %s %s@." (C.bright_green "✓") (C.bright_white msg); true let testable (type a) ?(equal: a -> a -> bool = (=)) (pp: a Fmt.t) : a testable = let module M = struct type t = a let pp = pp let equal = equal end in (module M) let group name tests = Fmt.pr "━━━ %s ━━━@." (C.bright_blue name); let t0 = Unix.gettimeofday () in let s, f = List.fold_left begin fun (s, f) test -> if test () then (s + 1, f) else (s, f + 1) end (0, 0) tests in let t = Unix.gettimeofday () -. t0 in let msg = match s, f with | 1, 0 -> "Test passed" | s, 0 -> fmt "%d tests passed" s | 0, 1 -> "Test failed" | 0, f -> fmt "%d tests failed" f | s, f -> fmt "%d tests passed, %d tests failed" s f in Fmt.pr " %s %s in %0.2fms@." (C.bright_magenta "•") msg (t *. 1000.0) let int : 'a testable = testable Fmt.int let float : 'a testable = testable Fmt.float let char : 'a testable = testable Fmt.char let bool : 'a testable = testable Fmt.bool let unit : 'a testable = testable (Fmt.unit "()") let int32 : 'a testable = testable ~equal:Int32.equal Fmt.int32 let int64 : 'a testable = testable ~equal:Int64.equal Fmt.int64 let string : 'a testable = testable ~equal:String.equal Fmt.string let list e = let rec equal l1 l2 = match (l1, l2) with | (x::xs, y::ys) -> Testable.equal e x y && equal xs ys | ([], []) -> true | _ -> false in testable (Fmt.Dump.list (Testable.pp e)) ~equal let sorted_list (type a) (a : a testable) compare = let l = list a in let equal l1 l2 = Testable.equal l (List.sort compare l1) (List.sort compare l2) in testable (Testable.pp l) ~equal let array e = let equal a1 a2 = let (m, n) = Array.(length a1, length a2) in let rec go i = i = m || (Testable.equal e a1.(i) a2.(i) && go (i + 1)) in m = n && go 0 in testable (Fmt.Dump.array (Testable.pp e)) ~equal let pair a b = let equal (a1, b1) (a2, b2) = Testable.equal a a1 a2 && Testable.equal b b1 b2 in testable (Fmt.Dump.pair (Testable.pp a) (Testable.pp b)) ~equal let option e = let equal x y = match (x, y) with | (Some a, Some b) -> Testable.equal e a b | (None, None) -> true | _ -> false in testable (Fmt.Dump.option (Testable.pp e)) ~equal let result a e = let equal x y = match (x, y) with | (Ok x, Ok y) -> Testable.equal a x y | (Error x, Error y) -> Testable.equal e x y | _ -> false in testable (Fmt.Dump.result ~ok:(Testable.pp a) ~error:(Testable.pp e)) ~equal
tx_rollup_prefixes.ml
type t = { b58check_prefix : string; prefix : string; hash_size : int; b58check_size : int; } let rollup_address = { b58check_prefix = "\001\128\120\031"; prefix = "txr1"; hash_size = 20; b58check_size = 37; } let inbox_hash = { b58check_prefix = "\079\148\196"; prefix = "txi"; hash_size = 32; b58check_size = 53; } let inbox_list_hash = inbox_hash let message_hash = { b58check_prefix = "\079\149\030"; prefix = "txm"; hash_size = 32; b58check_size = 53; } let commitment_hash = { b58check_prefix = "\079\148\017"; prefix = "txc"; hash_size = 32; b58check_size = 53; } let message_result_hash = { b58check_prefix = "\018\007\206\087"; prefix = "txmr"; hash_size = 32; b58check_size = 54; } let message_result_list_hash = { b58check_prefix = "\079\146\082"; prefix = "txM"; hash_size = 32; b58check_size = 53; } let withdraw_list_hash = { b58check_prefix = "\079\150\072"; prefix = "txw"; hash_size = 32; b58check_size = 53; } let check_encoding {prefix; b58check_size; _} encoding = Base58.check_encoded_prefix encoding prefix b58check_size
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
dune
(executable (name test_lwt) (libraries lwt.unix markup-lwt.unix ounit2 test_support)) (rule (alias runtest) (package markup-lwt) (action (run %{exe:test_lwt.exe} -runner sequential)))
dune
(executable (name main) (libraries tezos-stdlib tezos-alpha-test-helpers tezos-micheline tezos-protocol-alpha tezt-tezos ptime) (flags (:standard -open Tezt -open Tezt_tezos -open Tezt.Base -open Tezos_stdlib)))
pervasives.mli
(** The OCaml Standard library. This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by [Stdlib]. It particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the {{!modules}standard library modules}. *) (** {1 Exceptions} *) external raise : exn -> 'a = "%raise" (** Raise the given exception value *) external raise_notrace : exn -> 'a = "%raise_notrace" (** A faster version [raise] which does not record the backtrace. @since 4.02.0 *) val invalid_arg : string -> 'a (** Raise exception [Invalid_argument] with the given string. *) val failwith : string -> 'a (** Raise exception [Failure] with the given string. *) exception Exit (** The [Exit] exception is not raised by any library function. It is provided for use in your programs. *) (** {1 Boolean operations} *) external not : bool -> bool = "%boolnot" (** The boolean negation. *) external ( && ) : bool -> bool -> bool = "%sequand" (** The boolean 'and'. Evaluation is sequential, left-to-right: in [e1 && e2], [e1] is evaluated first, and if it returns [false], [e2] is not evaluated at all. Right-associative operator, see {!Ocaml_operators} for more information. *) external ( || ) : bool -> bool -> bool = "%sequor" (** The boolean 'or'. Evaluation is sequential, left-to-right: in [e1 || e2], [e1] is evaluated first, and if it returns [true], [e2] is not evaluated at all. Right-associative operator, see {!Ocaml_operators} for more information. *) (** {1 Debugging} *) external __LOC__ : string = "%loc_LOC" (** [__LOC__] returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". @since 4.02.0 *) external __FILE__ : string = "%loc_FILE" (** [__FILE__] returns the name of the file currently being parsed by the compiler. @since 4.02.0 *) external __LINE__ : int = "%loc_LINE" (** [__LINE__] returns the line number at which this expression appears in the file currently being parsed by the compiler. @since 4.02.0 *) external __MODULE__ : string = "%loc_MODULE" (** [__MODULE__] returns the module name of the file being parsed by the compiler. @since 4.02.0 *) external __POS__ : string * int * int * int = "%loc_POS" (** [__POS__] returns a tuple [(file,lnum,cnum,enum)], corresponding to the location at which this expression appears in the file currently being parsed by the compiler. [file] is the current filename, [lnum] the line number, [cnum] the character position in the line and [enum] the last character position in the line. @since 4.02.0 *) external __LOC_OF__ : 'a -> string * 'a = "%loc_LOC" (** [__LOC_OF__ expr] returns a pair [(loc, expr)] where [loc] is the location of [expr] in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". @since 4.02.0 *) external __LINE_OF__ : 'a -> int * 'a = "%loc_LINE" (** [__LINE_OF__ expr] returns a pair [(line, expr)], where [line] is the line number at which the expression [expr] appears in the file currently being parsed by the compiler. @since 4.02.0 *) external __POS_OF__ : 'a -> (string * int * int * int) * 'a = "%loc_POS" (** [__POS_OF__ expr] returns a pair [(loc,expr)], where [loc] is a tuple [(file,lnum,cnum,enum)] corresponding to the location at which the expression [expr] appears in the file currently being parsed by the compiler. [file] is the current filename, [lnum] the line number, [cnum] the character position in the line and [enum] the last character position in the line. @since 4.02.0 *) (** {1 Composition operators} *) external ( |> ) : 'a -> ('a -> 'b) -> 'b = "%revapply" (** Reverse-application operator: [x |> f |> g] is exactly equivalent to [g (f (x))]. Left-associative operator, see {!Ocaml_operators} for more information. @since 4.01 *) external ( @@ ) : ('a -> 'b) -> 'a -> 'b = "%apply" (** Application operator: [g @@ f @@ x] is exactly equivalent to [g (f (x))]. Right-associative operator, see {!Ocaml_operators} for more information. @since 4.01 *) (** {1 Integer arithmetic} *) (** Integers are [Sys.int_size] bits wide. All operations are taken modulo 2{^[Sys.int_size]}. They do not fail on overflow. *) external ( ~- ) : int -> int = "%negint" (** Unary negation. You can also write [- e] instead of [~- e]. Unary operator, see {!Ocaml_operators} for more information. *) external ( ~+ ) : int -> int = "%identity" (** Unary addition. You can also write [+ e] instead of [~+ e]. Unary operator, see {!Ocaml_operators} for more information. @since 3.12.0 *) external succ : int -> int = "%succint" (** [succ x] is [x + 1]. *) external pred : int -> int = "%predint" (** [pred x] is [x - 1]. *) external ( + ) : int -> int -> int = "%addint" (** Integer addition. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( - ) : int -> int -> int = "%subint" (** Integer subtraction. Left-associative operator, , see {!Ocaml_operators} for more information. *) external ( * ) : int -> int -> int = "%mulint" (** Integer multiplication. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( / ) : int -> int -> int = "%divint" (** Integer division. Raise [Division_by_zero] if the second argument is 0. Integer division rounds the real quotient of its arguments towards zero. More precisely, if [x >= 0] and [y > 0], [x / y] is the greatest integer less than or equal to the real quotient of [x] by [y]. Moreover, [(- x) / y = x / (- y) = - (x / y)]. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( mod ) : int -> int -> int = "%modint" (** Integer remainder. If [y] is not zero, the result of [x mod y] satisfies the following properties: [x = (x / y) * y + x mod y] and [abs(x mod y) <= abs(y) - 1]. If [y = 0], [x mod y] raises [Division_by_zero]. Note that [x mod y] is negative only if [x < 0]. Raise [Division_by_zero] if [y] is zero. Left-associative operator, see {!Ocaml_operators} for more information. *) val abs : int -> int (** Return the absolute value of the argument. Note that this may be negative if the argument is [min_int]. *) val max_int : int (** The greatest representable integer. *) val min_int : int (** The smallest representable integer. *) (** {2 Bitwise operations} *) external ( land ) : int -> int -> int = "%andint" (** Bitwise logical and. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( lor ) : int -> int -> int = "%orint" (** Bitwise logical or. Left-associative operator, see {!Ocaml_operators} for more information. *) external ( lxor ) : int -> int -> int = "%xorint" (** Bitwise logical exclusive or. Left-associative operator, see {!Ocaml_operators} for more information. *) val lnot : int -> int (** Bitwise logical negation. *) external ( lsl ) : int -> int -> int = "%lslint" (** [n lsl m] shifts [n] to the left by [m] bits. The result is unspecified if [m < 0] or [m > Sys.int_size]. Right-associative operator, see {!Ocaml_operators} for more information. *) external ( lsr ) : int -> int -> int = "%lsrint" (** [n lsr m] shifts [n] to the right by [m] bits. This is a logical shift: zeroes are inserted regardless of the sign of [n]. The result is unspecified if [m < 0] or [m > Sys.int_size]. Right-associative operator, see {!Ocaml_operators} for more information. *) external ( asr ) : int -> int -> int = "%asrint" (** [n asr m] shifts [n] to the right by [m] bits. This is an arithmetic shift: the sign bit of [n] is replicated. The result is unspecified if [m < 0] or [m > Sys.int_size]. Right-associative operator, see {!Ocaml_operators} for more information. *) (** {1 String operations} More string operations are provided in module {!String}. *) val ( ^ ) : string -> string -> string (** String concatenation. Right-associative operator, see {!Ocaml_operators} for more information. *) (** {1 Character operations} More character operations are provided in module {!Char}. *) external int_of_char : char -> int = "%identity" (** Return the ASCII code of the argument. *) val char_of_int : int -> char (** Return the character with the given ASCII code. Raise [Invalid_argument "char_of_int"] if the argument is outside the range 0--255. *) (** {1 Unit operations} *) external ignore : 'a -> unit = "%ignore" (** Discard the value of its argument and return [()]. For instance, [ignore(f x)] discards the result of the side-effecting function [f]. It is equivalent to [f x; ()], except that the latter may generate a compiler warning; writing [ignore(f x)] instead avoids the warning. *) (** {1 String conversion functions} *) val string_of_bool : bool -> string (** Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly. *) val bool_of_string_opt: string -> bool option (** Convert the given string to a boolean. Return [None] if the string is not ["true"] or ["false"]. @since 4.05 *) val string_of_int : int -> string (** Return the string representation of an integer, in decimal. *) val int_of_string_opt: string -> int option (** Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with [0u]), in hexadecimal (if it begins with [0x] or [0X]), in octal (if it begins with [0o] or [0O]), or in binary (if it begins with [0b] or [0B]). The [0u] prefix reads the input as an unsigned integer in the range [[0, 2*max_int+1]]. If the input exceeds {!max_int} it is converted to the signed integer [min_int + input - max_int - 1]. The [_] (underscore) character can appear anywhere in the string and is ignored. Return [None] if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type [int]. @since 4.05 *) (** {1 Pair operations} *) external fst : 'a * 'b -> 'a = "%field0" (** Return the first component of a pair. *) external snd : 'a * 'b -> 'b = "%field1" (** Return the second component of a pair. *) (** {1 List operations} More list operations are provided in module {!List}. *) val ( @ ) : 'a list -> 'a list -> 'a list (** List concatenation. Not tail-recursive (length of the first argument). Right-associative operator, see {!Ocaml_operators} for more information. *) (** {1 References} *) type 'a ref = { mutable contents : 'a } (** The type of references (mutable indirection cells) containing a value of type ['a]. *) external ref : 'a -> 'a ref = "%makemutable" (** Return a fresh reference containing the given value. *) external ( ! ) : 'a ref -> 'a = "%field0" (** [!r] returns the current contents of reference [r]. Equivalent to [fun r -> r.contents]. Unary operator, see {!Ocaml_operators} for more information. *) external ( := ) : 'a ref -> 'a -> unit = "%setfield0" (** [r := a] stores the value of [a] in reference [r]. Equivalent to [fun r v -> r.contents <- v]. Right-associative operator, see {!Ocaml_operators} for more information. *) external incr : int ref -> unit = "%incr" (** Increment the integer contained in the given reference. Equivalent to [fun r -> r := succ !r]. *) external decr : int ref -> unit = "%decr" (** Decrement the integer contained in the given reference. Equivalent to [fun r -> r := pred !r]. *) (** {1 Result type} *) (** @since 4.03.0 *) type ('a,'b) result = Ok of 'a | Error of 'b (** {1 Operations on format strings} *) (** Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module {!Scanf} and to print data with formatted output functions from modules {!Printf} and {!Format}. Format strings are made of three kinds of entities: - {e conversions specifications}, introduced by the special character ['%'] followed by one or more characters specifying what kind of argument to read or print, - {e formatting indications}, introduced by the special character ['@'] followed by one or more characters specifying how to read or print the argument, - {e plain characters} that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output. There is an additional lexical rule to escape the special characters ['%'] and ['@'] in format strings: if a special character follows a ['%'] character, it is treated as a plain character. In other words, ["%%"] is considered as a plain ['%'] and ["%@"] as a plain ['@']. For more information about conversion specifications and formatting indications available, read the documentation of modules {!Scanf}, {!Printf} and {!Format}. *) (** Format strings have a general and highly polymorphic type [('a, 'b, 'c, 'd, 'e, 'f) format6]. The two simplified types, [format] and [format4] below are included for backward compatibility with earlier releases of OCaml. The meaning of format string type parameters is as follows: - ['a] is the type of the parameters of the format for formatted output functions ([printf]-style functions); ['a] is the type of the values read by the format for formatted input functions ([scanf]-style functions). - ['b] is the type of input source for formatted input functions and the type of output target for formatted output functions. For [printf]-style functions from module {!Printf}, ['b] is typically [out_channel]; for [printf]-style functions from module {!Format}, ['b] is typically {!Format.formatter}; for [scanf]-style functions from module {!Scanf}, ['b] is typically {!Scanf.Scanning.in_channel}. Type argument ['b] is also the type of the first argument given to user's defined printing functions for [%a] and [%t] conversions, and user's defined reading functions for [%r] conversion. - ['c] is the type of the result of the [%a] and [%t] printing functions, and also the type of the argument transmitted to the first argument of [kprintf]-style functions or to the [kscanf]-style functions. - ['d] is the type of parameters for the [scanf]-style functions. - ['e] is the type of the receiver function for the [scanf]-style functions. - ['f] is the final result type of a formatted input/output function invocation: for the [printf]-style functions, it is typically [unit]; for the [scanf]-style functions, it is typically the result type of the receiver function. *) type ('a, 'b, 'c, 'd, 'e, 'f) format6 = ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6 type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6 type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string (** Converts a format string into a string. *) external format_of_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity" (** [format_of_string s] returns a format string read from the string literal [s]. Note: [format_of_string] can not convert a string argument that is not a literal. If you need this functionality, use the more general {!Scanf.format_from_string} function. *) val ( ^^ ) : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('f, 'b, 'c, 'e, 'g, 'h) format6 -> ('a, 'b, 'c, 'd, 'g, 'h) format6 (** [f1 ^^ f2] catenates format strings [f1] and [f2]. The result is a format string that behaves as the concatenation of format strings [f1] and [f2]: in case of formatted output, it accepts arguments from [f1], then arguments from [f2]; in case of formatted input, it returns results from [f1], then results from [f2]. Right-associative operator, see {!Ocaml_operators} for more information. *)
(**************************************************************************) (* *) (* OCaml *) (* *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
foo.ml
open Dune_action_plugin.V1 module Glob = Dune_glob.V1 let action = let open Dune_action_plugin.V1.O in let+ listing = read_directory_with_glob ~glob:Glob.universal ~path:(Path.of_string "some_dir") in String.concat "; " listing |> Printf.printf "Directory listing: [%s]" let () = run action
raw_level_repr.mli
(** The shell's notion of a level: an integer indicating the number of blocks since genesis: genesis is 0, all other blocks have increasing levels from there. *) type t type raw_level = t val encoding : raw_level Data_encoding.t val rpc_arg : raw_level RPC_arg.arg val pp : Format.formatter -> raw_level -> unit include Compare.S with type t := raw_level val to_int32 : raw_level -> int32 val of_int32_exn : int32 -> raw_level val of_int32 : int32 -> raw_level tzresult val diff : raw_level -> raw_level -> int32 val root : raw_level val succ : raw_level -> raw_level val pred : raw_level -> raw_level option module Index : Storage_description.INDEX with type t = raw_level
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
limit.ml
type 'a t = 'a option let unknown = None let known x = Some x let of_option = Fun.id let is_unknown = Option.is_none let join (type a) ~where eq (l1 : a t) (l2 : a t) = match (l1, l2) with | (None, None) -> Result.return_none | (Some x, None) | (None, Some x) -> Result.return_some x | (Some x, Some y) -> if eq x y then Result.return_some x else error_with "Limit.join: error (%s)" where let%test "join" = let check res y = match res with Ok x -> Option.equal Bool.equal x y | Error _ -> false in check (join ~where:__LOC__ Bool.equal (Some true) (Some true)) (Some true) && check (join ~where:__LOC__ Bool.equal None None) None && check (join ~where:__LOC__ Bool.equal None (Some true)) (Some true) && check (join ~where:__LOC__ Bool.equal (Some true) None) (Some true) && not (Result.is_ok (join ~where:__LOC__ Bool.equal (Some true) (Some false))) let get ~when_unknown = function | None -> error_with "Limit.get: %s" when_unknown | Some x -> ok x let%test "get" = match get ~when_unknown:"" (Some true) with Ok true -> true | _ -> false let fold ~unknown ~known x = match x with None -> unknown | Some x -> known x let value ~when_unknown = function None -> when_unknown | Some x -> x
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Nomadic Labs, <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
test_ratios.ml
open Test;; open Nat;; open Big_int;; open Ratio;; open Arith_status;; set_error_when_null_denominator false ;; let infinite_failure = "infinite or undefined rational number";; testing_function "create_ratio" ;; let r = create_ratio (big_int_of_int 1) (big_int_of_int (-2)) in test 1 eq_big_int (numerator_ratio r, big_int_of_int (-1)) && test 2 eq_big_int (denominator_ratio r, big_int_of_int 2) ;; let r = create_ratio (big_int_of_int 2) (big_int_of_int 3) in test 3 eq_big_int (numerator_ratio r, big_int_of_int 2) && test 4 eq_big_int (denominator_ratio r, big_int_of_int 3) ;; set_normalize_ratio true ;; let r = create_ratio (big_int_of_int 12) (big_int_of_int (-16)) in test 5 eq_big_int (numerator_ratio r, big_int_of_int (-3)) && test 6 eq_big_int (denominator_ratio r, big_int_of_int 4) ;; set_normalize_ratio false ;; let r = create_ratio (big_int_of_int 0) (big_int_of_int 0) in test 7 eq_big_int (numerator_ratio r, big_int_of_int 0) && test 8 eq_big_int (denominator_ratio r, big_int_of_int 0) ;; testing_function "create_normalized_ratio" ;; let r = create_normalized_ratio (big_int_of_int 1) (big_int_of_int (-2)) in test 1 eq_big_int (numerator_ratio r, big_int_of_int (-1)) && test 2 eq_big_int (denominator_ratio r, big_int_of_int 2) ;; let r = create_normalized_ratio (big_int_of_int 2) (big_int_of_int 3) in test 3 eq_big_int (numerator_ratio r, big_int_of_int 2) && test 4 eq_big_int (denominator_ratio r, big_int_of_int 3) ;; set_normalize_ratio true ;; let r = create_normalized_ratio (big_int_of_int 12) (big_int_of_int (-16)) in test 5 eq_big_int (numerator_ratio r, big_int_of_int (-12)) && test 6 eq_big_int (denominator_ratio r, big_int_of_int 16) ;; set_normalize_ratio false ;; let r = create_normalized_ratio (big_int_of_int 1) (big_int_of_int 0) in test 7 eq_big_int (numerator_ratio r, big_int_of_int 1) && test 8 eq_big_int (denominator_ratio r, big_int_of_int 0) ;; let r = create_normalized_ratio (big_int_of_int 0) (big_int_of_int 0) in test 9 eq_big_int (numerator_ratio r, big_int_of_int 0) && test 10 eq_big_int (denominator_ratio r, big_int_of_int 0) ;; testing_function "null_denominator" ;; test 1 eq (null_denominator (create_ratio (big_int_of_int 1) (big_int_of_int (-2))), false) ;; test 2 eq (null_denominator (create_ratio (big_int_of_int 1) zero_big_int),true) ;; (***** testing_function "verify_null_denominator" ;; test 1 eq (verify_null_denominator (ratio_of_string "0/1"), false) ;; test 2 eq (verify_null_denominator (ratio_of_string "0/0"), true) ;; *****) testing_function "sign_ratio" ;; test 1 eq_int (sign_ratio (create_ratio (big_int_of_int (-2)) (big_int_of_int (-3))), 1) ;; test 2 eq_int (sign_ratio (create_ratio (big_int_of_int 2) (big_int_of_int (-3))), (-1)) ;; test 3 eq_int (sign_ratio (create_ratio zero_big_int (big_int_of_int (-3))), 0) ;; testing_function "normalize_ratio" ;; let r = create_ratio (big_int_of_int 12) (big_int_of_int (-16)) in ignore (normalize_ratio r); test 1 eq_big_int (numerator_ratio r, big_int_of_int (-3)) && test 2 eq_big_int (denominator_ratio r, big_int_of_int 4) ;; let r = create_ratio (big_int_of_int (-1)) zero_big_int in ignore (normalize_ratio r); test 3 eq_big_int (numerator_ratio r, big_int_of_int (-1)) && test 4 eq_big_int (denominator_ratio r, zero_big_int) ;; testing_function "report_sign_ratio" ;; test 1 eq_big_int (report_sign_ratio (create_ratio (big_int_of_int 2) (big_int_of_int (-3))) (big_int_of_int 1), big_int_of_int (-1)) ;; test 2 eq_big_int (report_sign_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (big_int_of_int 1), big_int_of_int 1) ;; testing_function "is_integer_ratio" ;; test 1 eq (is_integer_ratio (create_ratio (big_int_of_int 2) (big_int_of_int (-1))), true) ;; test 2 eq (is_integer_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)), false) ;; testing_function "add_ratio" ;; let r = add_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 2)) (create_ratio (big_int_of_int 2) (big_int_of_int 3)) in test 1 eq_big_int (numerator_ratio r, big_int_of_int 7) && test 2 eq_big_int (denominator_ratio r, big_int_of_int 6) ;; let r = add_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in test 3 eq_big_int (numerator_ratio r, big_int_of_int 1) && test 4 eq_big_int (denominator_ratio r, big_int_of_int 6) ;; let r = add_ratio (create_ratio (big_int_of_int 2) zero_big_int) (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in test 5 eq_big_int (numerator_ratio r, big_int_of_int 4) && test 6 eq_big_int (denominator_ratio r, zero_big_int) ;; let r = add_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (create_ratio (big_int_of_int 1) zero_big_int) in test 7 eq_big_int (numerator_ratio r, big_int_of_int 3) && test 8 eq_big_int (denominator_ratio r, zero_big_int) ;; let r = add_ratio (create_ratio (big_int_of_int 2) zero_big_int) (create_ratio (big_int_of_int 1) zero_big_int) in test 9 eq_big_int (numerator_ratio r, zero_big_int) && test 10 eq_big_int (denominator_ratio r, zero_big_int) ;; let r = add_ratio (create_ratio (big_int_of_string "12724951") (big_int_of_string "26542080")) (create_ratio (big_int_of_string "-1") (big_int_of_string "81749606400")) in test 11 eq_big_int (numerator_ratio r, big_int_of_string "1040259735682744320") && test 12 eq_big_int (denominator_ratio r, big_int_of_string "2169804593037312000") ;; let r1,r2 = (create_ratio (big_int_of_string "12724951") (big_int_of_string "26542080"), create_ratio (big_int_of_string "-1") (big_int_of_string "81749606400")) in let bi1 = mult_big_int (numerator_ratio r1) (denominator_ratio r2) and bi2 = mult_big_int (numerator_ratio r2) (denominator_ratio r1) in test 1 eq_big_int (bi1, big_int_of_string "1040259735709286400") && test 2 eq_big_int (bi2, big_int_of_string "-26542080") && test 3 eq_big_int (mult_big_int (denominator_ratio r1) (denominator_ratio r2), big_int_of_string "2169804593037312000") && test 4 eq_big_int (add_big_int bi1 bi2, big_int_of_string "1040259735682744320") ;; testing_function "sub_ratio" ;; let r = sub_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (create_ratio (big_int_of_int 1) (big_int_of_int 2)) in test 1 eq_big_int (numerator_ratio r, big_int_of_int 1) && test 2 eq_big_int (denominator_ratio r, big_int_of_int 6) ;; let r = sub_ratio (create_ratio (big_int_of_int 2) zero_big_int) (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in test 3 eq_big_int (numerator_ratio r, big_int_of_int 4) && test 4 eq_big_int (denominator_ratio r, zero_big_int) ;; let r = sub_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (create_ratio (big_int_of_int 1) zero_big_int) in test 5 eq_big_int (numerator_ratio r, big_int_of_int (-3)) && test 6 eq_big_int (denominator_ratio r, zero_big_int) ;; let r = sub_ratio (create_ratio (big_int_of_int 2) zero_big_int) (create_ratio (big_int_of_int 1) zero_big_int) in test 7 eq_big_int (numerator_ratio r, zero_big_int) && test 8 eq_big_int (denominator_ratio r, zero_big_int) ;; testing_function "mult_ratio" ;; let r = mult_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (create_ratio (big_int_of_int 7) (big_int_of_int 5)) in test 1 eq_big_int (numerator_ratio r, big_int_of_int 14) && test 2 eq_big_int (denominator_ratio r, big_int_of_int 15) ;; let r = mult_ratio (create_ratio (big_int_of_int 2) zero_big_int) (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in test 3 eq_big_int (numerator_ratio r, big_int_of_int (-2)) && test 4 eq_big_int (denominator_ratio r, zero_big_int) ;; let r = mult_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (create_ratio (big_int_of_int 1) zero_big_int) in test 5 eq_big_int (numerator_ratio r, big_int_of_int 2) && test 6 eq_big_int (denominator_ratio r, zero_big_int) ;; let r = mult_ratio (create_ratio (big_int_of_int 2) zero_big_int) (create_ratio (big_int_of_int 1) zero_big_int) in test 7 eq_big_int (numerator_ratio r, big_int_of_int 2) && test 8 eq_big_int (denominator_ratio r, zero_big_int) ;; testing_function "div_ratio" ;; let r = div_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (create_ratio (big_int_of_int 5) (big_int_of_int 7)) in test 1 eq_big_int (numerator_ratio r, big_int_of_int 14) && test 2 eq_big_int (denominator_ratio r, big_int_of_int 15) ;; let r = div_ratio (create_ratio (big_int_of_int 2) zero_big_int) (create_ratio (big_int_of_int 1) (big_int_of_int (-2))) in test 3 eq_big_int (numerator_ratio r, big_int_of_int (-4)) && test 4 eq_big_int (denominator_ratio r, zero_big_int) ;; let r = div_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 3)) (create_ratio (big_int_of_int 1) zero_big_int) in test 5 eq_big_int (numerator_ratio r, zero_big_int) && test 6 eq_big_int (denominator_ratio r, big_int_of_int 3) ;; let r = div_ratio (create_ratio (big_int_of_int 2) zero_big_int) (create_ratio (big_int_of_int 1) zero_big_int) in test 7 eq_big_int (numerator_ratio r, zero_big_int) && test 8 eq_big_int (denominator_ratio r, zero_big_int) ;; testing_function "integer_ratio" ;; test 1 eq_big_int (integer_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)), big_int_of_int 1) ;; test 2 eq_big_int (integer_ratio (create_ratio (big_int_of_int 5) (big_int_of_int (-3))), big_int_of_int (-1)) ;; test 3 eq_big_int (integer_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2)), big_int_of_int 1) ;; test 4 eq_big_int (integer_ratio (create_ratio (big_int_of_int 3) (big_int_of_int (-2))), big_int_of_int (-1)) ;; failwith_test 5 integer_ratio (create_ratio (big_int_of_int 3) zero_big_int) (Failure("integer_ratio "^infinite_failure)) ;; testing_function "floor_ratio" ;; test 1 eq_big_int (floor_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)), big_int_of_int 1) ;; test 2 eq_big_int (floor_ratio (create_ratio (big_int_of_int 5) (big_int_of_int (-3))), big_int_of_int (-2)) ;; test 3 eq_big_int (floor_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2)), big_int_of_int 1) ;; test 4 eq_big_int (floor_ratio (create_ratio (big_int_of_int 3) (big_int_of_int (-2))), big_int_of_int (-2)) ;; failwith_test 5 floor_ratio (create_ratio (big_int_of_int 3) zero_big_int) Division_by_zero ;; testing_function "round_ratio" ;; test 1 eq_big_int (round_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)), big_int_of_int 2) ;; test 2 eq_big_int (round_ratio (create_ratio (big_int_of_int 5) (big_int_of_int (-3))), big_int_of_int (-2)) ;; test 3 eq_big_int (round_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2)), big_int_of_int 2) ;; test 4 eq_big_int (round_ratio (create_ratio (big_int_of_int 3) (big_int_of_int (-2))), big_int_of_int (-2)) ;; failwith_test 5 round_ratio (create_ratio (big_int_of_int 3) zero_big_int) Division_by_zero ;; testing_function "ceiling_ratio" ;; test 1 eq_big_int (ceiling_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)), big_int_of_int 2) ;; test 2 eq_big_int (ceiling_ratio (create_ratio (big_int_of_int 5) (big_int_of_int (-3))), big_int_of_int (-1)) ;; test 3 eq_big_int (ceiling_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2)), big_int_of_int 2) ;; test 4 eq_big_int (ceiling_ratio (create_ratio (big_int_of_int 3) (big_int_of_int (-2))), big_int_of_int (-1)) ;; test 5 eq_big_int (ceiling_ratio (create_ratio (big_int_of_int 4) (big_int_of_int 2)), big_int_of_int 2) ;; failwith_test 6 ceiling_ratio (create_ratio (big_int_of_int 3) zero_big_int) Division_by_zero ;; testing_function "eq_ratio" ;; test 1 eq_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3), create_ratio (big_int_of_int (-20)) (big_int_of_int (-12))) ;; test 2 eq_ratio (create_ratio (big_int_of_int 1) zero_big_int, create_ratio (big_int_of_int 2) zero_big_int) ;; let neq_ratio x y = not (eq_ratio x y);; test 3 neq_ratio (create_ratio (big_int_of_int 1) zero_big_int, create_ratio (big_int_of_int (-1)) zero_big_int) ;; test 4 neq_ratio (create_ratio (big_int_of_int 1) zero_big_int, create_ratio zero_big_int zero_big_int) ;; test 5 eq_ratio (create_ratio zero_big_int zero_big_int, create_ratio zero_big_int zero_big_int) ;; testing_function "compare_ratio" ;; test 1 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0)) (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0) ;; test 2 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0)) (create_ratio (big_int_of_int 1) (big_int_of_int 0)), 0) ;; test 3 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0)) (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)), 0) ;; test 4 eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0) ;; test 5 eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)) (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0) ;; test 6 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0)) (create_ratio (big_int_of_int 5) (big_int_of_int 3)), 0) ;; test 7 eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)) (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0) ;; test 8 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0)) (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)), 0) ;; test 9 eq_int (compare_ratio (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)) (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0) ;; test 10 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0)) (create_ratio (big_int_of_int 0) (big_int_of_int 1)), 0) ;; test 11 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 1)) (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0) ;; test 12 eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (create_ratio (big_int_of_int 1) (big_int_of_int 0)), 0) ;; test 13 eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (create_ratio (big_int_of_int 2) (big_int_of_int 0)), 0) ;; test 14 eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)), 1) ;; test 15 eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)) (create_ratio (big_int_of_int 1) (big_int_of_int 0)), (-1)) ;; test 16 eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)) (create_ratio (big_int_of_int 1) (big_int_of_int 0)), (-1)) ;; test 17 eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (create_ratio (big_int_of_int 5) (big_int_of_int 3)), 1) ;; test 18 eq_int (compare_ratio (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)) (create_ratio (big_int_of_int 1) (big_int_of_int 0)), (-1)) ;; test 19 eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)), 1) ;; test 20 eq_int (compare_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (create_ratio (big_int_of_int 0) (big_int_of_int 3)), 1) ;; test 21 eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)) (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)), 0) ;; test 22 eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)) (create_ratio (big_int_of_int (-2)) (big_int_of_int 0)), 0) ;; test 23 eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)) (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)), 1) ;; test 24 eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)) (create_ratio (big_int_of_int 5) (big_int_of_int 3)), (-1)) ;; test 25 eq_int (compare_ratio (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)) (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)), 1) ;; test 26 eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)) (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)), (-1)) ;; test 27 eq_int (compare_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)) (create_ratio (big_int_of_int 0) (big_int_of_int 3)), (-1)) ;; test 28 eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)) (create_ratio (big_int_of_int 3) (big_int_of_int 2)), 1) ;; test 29 eq_int (compare_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2)) (create_ratio (big_int_of_int 5) (big_int_of_int 3)), (-1)) ;; test 30 eq_int (compare_ratio (create_ratio (big_int_of_int 5) (big_int_of_int 3)) (create_ratio (big_int_of_int (-3)) (big_int_of_int 2)), 1) ;; test 31 eq_int (compare_ratio (create_ratio (big_int_of_int (-3)) (big_int_of_int 2)) (create_ratio (big_int_of_int 5) (big_int_of_int 3)), (-1)) ;; test 32 eq_int (compare_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2)) (create_ratio (big_int_of_int 0) (big_int_of_int 3)), 1) ;; test 33 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 2)) (create_ratio (big_int_of_int 5) (big_int_of_int 3)), (-1)) ;; test 34 eq_int (compare_ratio (create_ratio (big_int_of_int (-3)) (big_int_of_int 2)) (create_ratio (big_int_of_int 0) (big_int_of_int 3)), (-1)) ;; test 35 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 2)) (create_ratio (big_int_of_int (-5)) (big_int_of_int 3)), 1) ;; test 36 eq_int (compare_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 2)) (create_ratio (big_int_of_int 0) (big_int_of_int 3)), 0) ;; testing_function "eq_big_int_ratio" ;; test 1 eq_big_int_ratio (big_int_of_int 3, (create_ratio (big_int_of_int 3) (big_int_of_int 1))) ;; test 2 eq (not (eq_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int 3) (big_int_of_int 1))), true) ;; test 3 eq (not (eq_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int 3) (big_int_of_int 2))), true) ;; test 4 eq (not (eq_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int 3) (big_int_of_int 0))), true) ;; test 5 eq (not (eq_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int (-3)) (big_int_of_int 2))), true) ;; testing_function "compare_big_int_ratio" ;; test 1 eq_int (compare_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int 3) (big_int_of_int 0)), (-1)) ;; test 2 eq_int (compare_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0) ;; test 3 eq_int (compare_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int (-3)) (big_int_of_int 0)), 1) ;; test 4 eq_int (compare_big_int_ratio (big_int_of_int (-1)) (create_ratio (big_int_of_int 3) (big_int_of_int 0)), (-1)) ;; test 5 eq_int (compare_big_int_ratio (big_int_of_int (-1)) (create_ratio (big_int_of_int 0) (big_int_of_int 0)), 0) ;; test 6 eq_int (compare_big_int_ratio (big_int_of_int (-1)) (create_ratio (big_int_of_int (-3)) (big_int_of_int 0)), 1) ;; test 7 eq_int (compare_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int 1) (big_int_of_int 1)), 0) ;; test 8 eq_int (compare_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int 3) (big_int_of_int 2)), (-1)) ;; test 9 eq_int (compare_big_int_ratio (big_int_of_int 1) (create_ratio (big_int_of_int 2) (big_int_of_int 3)), 1) ;; testing_function "int_of_ratio" ;; test 1 eq_int (int_of_ratio (create_ratio (big_int_of_int 4) (big_int_of_int 2)), 2) ;; test 2 eq_int (int_of_ratio (create_ratio (big_int_of_int biggest_int) (big_int_of_int 1)), biggest_int) ;; failwith_test 3 int_of_ratio (create_ratio (big_int_of_int 4) (big_int_of_int 0)) (Failure "integer argument required") ;; failwith_test 4 int_of_ratio (create_ratio (succ_big_int (big_int_of_int biggest_int)) (big_int_of_int 1)) (Failure "integer argument required") ;; failwith_test 5 int_of_ratio (create_ratio (big_int_of_int 4) (big_int_of_int 3)) (Failure "integer argument required") ;; testing_function "ratio_of_int" ;; test 1 eq_ratio (ratio_of_int 3, create_ratio (big_int_of_int 3) (big_int_of_int 1)) ;; test 2 eq_ratio (ratio_of_nat (nat_of_int 2), create_ratio (big_int_of_int 2) (big_int_of_int 1)) ;; testing_function "nat_of_ratio" ;; let nat1 = nat_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 1)) and nat2 = nat_of_int 3 in test 1 eq (eq_nat nat1 0 (length_nat nat1) nat2 0 (length_nat nat2), true) ;; failwith_test 2 nat_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 0)) (Failure "nat_of_ratio") ;; failwith_test 3 nat_of_ratio (create_ratio (big_int_of_int (-3)) (big_int_of_int 1)) (Failure "nat_of_ratio") ;; failwith_test 4 nat_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 2)) (Failure "nat_of_ratio") ;; testing_function "ratio_of_big_int" ;; test 1 eq_ratio (ratio_of_big_int (big_int_of_int 3), create_ratio (big_int_of_int 3) (big_int_of_int 1)) ;; testing_function "big_int_of_ratio" ;; test 1 eq_big_int (big_int_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 1)), big_int_of_int 3) ;; test 2 eq_big_int (big_int_of_ratio (create_ratio (big_int_of_int (-3)) (big_int_of_int 1)), big_int_of_int (-3)) ;; failwith_test 3 big_int_of_ratio (create_ratio (big_int_of_int 3) (big_int_of_int 0)) (Failure "big_int_of_ratio") ;; testing_function "string_of_ratio" ;; test 1 eq_string (string_of_ratio (create_ratio (big_int_of_int 43) (big_int_of_int 35)), "43/35") ;; test 2 eq_string (string_of_ratio (create_ratio (big_int_of_int 42) (big_int_of_int 0)), "1/0") ;; set_normalize_ratio_when_printing false ;; test 3 eq_string (string_of_ratio (create_ratio (big_int_of_int 42) (big_int_of_int 35)), "42/35") ;; set_normalize_ratio_when_printing true ;; test 4 eq_string (string_of_ratio (create_ratio (big_int_of_int 42) (big_int_of_int 35)), "6/5") ;; testing_function "ratio_of_string" ;; test 1 eq_ratio (ratio_of_string ("123/3456"), create_ratio (big_int_of_int 123) (big_int_of_int 3456)) ;; (*********** test 2 eq_ratio (ratio_of_string ("12.3/34.56"), create_ratio (big_int_of_int 1230) (big_int_of_int 3456)) ;; test 3 eq_ratio (ratio_of_string ("1.23/325.6"), create_ratio (big_int_of_int 123) (big_int_of_int 32560)) ;; test 4 eq_ratio (ratio_of_string ("12.3/345.6"), create_ratio (big_int_of_int 123) (big_int_of_int 3456)) ;; test 5 eq_ratio (ratio_of_string ("12.3/0.0"), create_ratio (big_int_of_int 123) (big_int_of_int 0)) ;; ***********) test 6 eq_ratio (ratio_of_string ("0/0"), create_ratio (big_int_of_int 0) (big_int_of_int 0)) ;; test 7 eq_ratio (ratio_of_string "1234567890", create_ratio (big_int_of_string "1234567890") unit_big_int) ;; failwith_test 8 ratio_of_string "frlshjkurty" (Failure "invalid digit");; (*********** testing_function "msd_ratio" ;; test 1 eq_int (msd_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 1)), 0) ;; test 2 eq_int (msd_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 12)), (-2)) ;; test 3 eq_int (msd_ratio (create_ratio (big_int_of_int 12) (big_int_of_int 1)), 1) ;; test 4 eq_int (msd_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 2)), (-1)) ;; test 5 eq_int (msd_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 1)), 0) ;; test 6 eq_int (msd_ratio (create_ratio (big_int_of_int 25) (big_int_of_int 21)), 0) ;; test 7 eq_int (msd_ratio (create_ratio (big_int_of_int 35) (big_int_of_int 21)), 0) ;; test 8 eq_int (msd_ratio (create_ratio (big_int_of_int 215) (big_int_of_int 31)), 0) ;; test 9 eq_int (msd_ratio (create_ratio (big_int_of_int 2) (big_int_of_int 30)), (-2)) ;; test 10 eq_int (msd_ratio (create_ratio (big_int_of_int 2345) (big_int_of_int 23456)), (-2)) ;; test 11 eq_int (msd_ratio (create_ratio (big_int_of_int 2345) (big_int_of_int 2346)), (-1)) ;; test 12 eq_int (msd_ratio (create_ratio (big_int_of_int 2345) (big_int_of_int 2344)), 0) ;; test 13 eq_int (msd_ratio (create_ratio (big_int_of_int 23456) (big_int_of_int 2345)), 1) ;; test 14 eq_int (msd_ratio (create_ratio (big_int_of_int 23467) (big_int_of_int 2345)), 1) ;; failwith_test 15 msd_ratio (create_ratio (big_int_of_int 1) (big_int_of_int 0)) ("msd_ratio "^infinite_failure) ;; failwith_test 16 msd_ratio (create_ratio (big_int_of_int (-1)) (big_int_of_int 0)) ("msd_ratio "^infinite_failure) ;; failwith_test 17 msd_ratio (create_ratio (big_int_of_int 0) (big_int_of_int 0)) ("msd_ratio "^infinite_failure) ;; *************************) testing_function "round_futur_last_digit" ;; let s = Bytes.of_string "+123456" in test 1 eq (round_futur_last_digit s 1 (pred (Bytes.length s)), false) && test 2 eq_bytes_string (s, "+123466") ;; let s = Bytes.of_string "123456" in test 3 eq (round_futur_last_digit s 0 (Bytes.length s), false) && test 4 eq_bytes_string (s, "123466") ;; let s = Bytes.of_string "-123456" in test 5 eq (round_futur_last_digit s 1 (pred (Bytes.length s)), false) && test 6 eq_bytes_string (s, "-123466") ;; let s = Bytes.of_string "+123496" in test 7 eq (round_futur_last_digit s 1 (pred (Bytes.length s)), false) && test 8 eq_bytes_string (s, "+123506") ;; let s = Bytes.of_string "123496" in test 9 eq (round_futur_last_digit s 0 (Bytes.length s), false) && test 10 eq_bytes_string (s, "123506") ;; let s = Bytes.of_string "-123496" in test 11 eq (round_futur_last_digit s 1 (pred (Bytes.length s)), false) && test 12 eq_bytes_string (s, "-123506") ;; let s = Bytes.of_string "+996" in test 13 eq (round_futur_last_digit s 1 (pred (Bytes.length s)), true) && test 14 eq_bytes_string (s, "+006") ;; let s = Bytes.of_string "996" in test 15 eq (round_futur_last_digit s 0 (Bytes.length s), true) && test 16 eq_bytes_string (s, "006") ;; let s = Bytes.of_string "-996" in test 17 eq (round_futur_last_digit s 1 (pred (Bytes.length s)), true) && test 18 eq_bytes_string (s, "-006") ;; let s = Bytes.of_string "+6666666" in test 19 eq (round_futur_last_digit s 1 (pred (Bytes.length s)), false) && test 20 eq_bytes_string (s, "+6666676") ;; let s = Bytes.of_string "6666666" in test 21 eq (round_futur_last_digit s 0 (Bytes.length s), false) && test 22 eq_bytes_string (s, "6666676") ;; let s = Bytes.of_string "-6666666" in test 23 eq (round_futur_last_digit s 1 (pred (Bytes.length s)), false) && test 24 eq_bytes_string (s, "-6666676") ;; testing_function "approx_ratio_fix" ;; let s = approx_ratio_fix 5 (create_ratio (big_int_of_int 2) (big_int_of_int 3)) in test 1 eq_string (s, "+0.66667") ;; test 2 eq_string (approx_ratio_fix 5 (create_ratio (big_int_of_int 20) (big_int_of_int 3)), "+6.66667") ;; test 3 eq_string (approx_ratio_fix 5 (create_ratio (big_int_of_int 2) (big_int_of_int 30)), "+0.06667") ;; test 4 eq_string (approx_ratio_fix 5 (create_ratio (big_int_of_string "999996") (big_int_of_string "1000000")), "+1.00000") ;; test 5 eq_string (approx_ratio_fix 5 (create_ratio (big_int_of_string "299996") (big_int_of_string "100000")), "+2.99996") ;; test 6 eq_string (approx_ratio_fix 5 (create_ratio (big_int_of_string "2999996") (big_int_of_string "1000000")), "+3.00000") ;; test 7 eq_string (approx_ratio_fix 4 (create_ratio (big_int_of_string "299996") (big_int_of_string "100000")), "+3.0000") ;; test 8 eq_string (approx_ratio_fix 5 (create_ratio (big_int_of_int 29996) (big_int_of_string "100000")), "+0.29996") ;; test 9 eq_string (approx_ratio_fix 5 (create_ratio (big_int_of_int 0) (big_int_of_int 1)), "+0") ;; failwith_test 10 (approx_ratio_fix 5) (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (Failure "approx_ratio_fix infinite or undefined rational number") ;; failwith_test 11 (approx_ratio_fix 5) (create_ratio (big_int_of_int 0) (big_int_of_int 0)) (Failure "approx_ratio_fix infinite or undefined rational number") ;; (* PR#4566 *) test 12 eq_string (approx_ratio_fix 8 (create_ratio (big_int_of_int 9603) (big_int_of_string "100000000000")), "+0.00000010") ;; test 13 eq_string (approx_ratio_fix 1 (create_ratio (big_int_of_int 94) (big_int_of_int 1000)), "+0.1") ;; test 14 eq_string (approx_ratio_fix 1 (create_ratio (big_int_of_int 49) (big_int_of_int 1000)), "+0.0") ;; testing_function "approx_ratio_exp" ;; test 1 eq_string (approx_ratio_exp 5 (create_ratio (big_int_of_int 2) (big_int_of_int 3)), "+0.66667e0") ;; test 2 eq_string (approx_ratio_exp 5 (create_ratio (big_int_of_int 20) (big_int_of_int 3)), "+0.66667e1") ;; test 3 eq_string (approx_ratio_exp 5 (create_ratio (big_int_of_int 2) (big_int_of_int 30)), "+0.66667e-1") ;; test 4 eq_string (approx_ratio_exp 5 (create_ratio (big_int_of_string "999996") (big_int_of_string "1000000")), "+1.00000e0") ;; test 5 eq_string (approx_ratio_exp 5 (create_ratio (big_int_of_string "299996") (big_int_of_string "100000")), "+0.30000e1") ;; test 6 eq_string (approx_ratio_exp 5 (create_ratio (big_int_of_int 29996) (big_int_of_string "100000")), "+0.29996e0") ;; test 7 eq_string (approx_ratio_exp 5 (create_ratio (big_int_of_int 0) (big_int_of_int 1)), "+0.00000e0") ;; failwith_test 8 (approx_ratio_exp 5) (create_ratio (big_int_of_int 1) (big_int_of_int 0)) (Failure "approx_ratio_exp infinite or undefined rational number") ;; failwith_test 9 (approx_ratio_exp 5) (create_ratio (big_int_of_int 0) (big_int_of_int 0)) (Failure "approx_ratio_exp infinite or undefined rational number") ;; testing_function "float_of_ratio";; let ok = ref true in for _ = 1 to 100 do let p = Random.int64 0x20000000000000L and pexp = Random.int 100 and q = Random.int64 0x20000000000000L and qexp = Random.int 100 in if not (eq_float (float_of_ratio (create_ratio (shift_left_big_int (big_int_of_int64 p) pexp) (shift_left_big_int (big_int_of_int64 q) qexp))) (ldexp (Int64.to_float p) pexp /. ldexp (Int64.to_float q) qexp)) then ok := false done; test 1 eq (!ok, true) ;;
Analyze_pattern.mli
val extract_specific_strings : ?lang:Lang.t -> Pattern.t -> string list (* Extract strings and metavariables that occur in the source code. *) val extract_strings_and_mvars : ?lang:Lang.t -> Pattern.t -> string list * Metavariable.mvar list
builtin_attributes.ml
open Asttypes open Parsetree let string_of_cst = function | Pconst_string(s, _, _) -> Some s | _ -> None let string_of_payload = function | PStr[{pstr_desc=Pstr_eval({pexp_desc=Pexp_constant c},_)}] -> string_of_cst c | _ -> None let string_of_opt_payload p = match string_of_payload p with | Some s -> s | None -> "" let error_of_extension ext = let submessage_from main_loc main_txt = function | {pstr_desc=Pstr_extension (({txt = ("ocaml.error"|"error"); loc}, p), _)} -> begin match p with | PStr([{pstr_desc=Pstr_eval ({pexp_desc=Pexp_constant(Pconst_string(msg,_,_))}, _)} ]) -> { Location.loc; txt = fun ppf -> Format.pp_print_text ppf msg } | _ -> { Location.loc; txt = fun ppf -> Format.fprintf ppf "Invalid syntax for sub-message of extension '%s'." main_txt } end | {pstr_desc=Pstr_extension (({txt; loc}, _), _)} -> { Location.loc; txt = fun ppf -> Format.fprintf ppf "Uninterpreted extension '%s'." txt } | _ -> { Location.loc = main_loc; txt = fun ppf -> Format.fprintf ppf "Invalid syntax for sub-message of extension '%s'." main_txt } in match ext with | ({txt = ("ocaml.error"|"error") as txt; loc}, p) -> begin match p with | PStr [] -> raise Location.Already_displayed_error | PStr({pstr_desc=Pstr_eval ({pexp_desc=Pexp_constant(Pconst_string(msg,_,_))}, _)}:: inner) -> let sub = List.map (submessage_from loc txt) inner in Location.error_of_printer ~loc ~sub Format.pp_print_text msg | _ -> Location.errorf ~loc "Invalid syntax for extension '%s'." txt end | ({txt; loc}, _) -> Location.errorf ~loc "Uninterpreted extension '%s'." txt let kind_and_message = function | PStr[ {pstr_desc= Pstr_eval ({pexp_desc=Pexp_apply ({pexp_desc=Pexp_ident{txt=Longident.Lident id}}, [Nolabel,{pexp_desc=Pexp_constant (Pconst_string(s,_,_))}]) },_)}] -> Some (id, s) | PStr[ {pstr_desc= Pstr_eval ({pexp_desc=Pexp_ident{txt=Longident.Lident id}},_)}] -> Some (id, "") | _ -> None let cat s1 s2 = if s2 = "" then s1 else s1 ^ "\n" ^ s2 let alert_attr x = match x.attr_name.txt with | "ocaml.deprecated"|"deprecated" -> Some (x, "deprecated", string_of_opt_payload x.attr_payload) | "ocaml.alert"|"alert" -> begin match kind_and_message x.attr_payload with | Some (kind, message) -> Some (x, kind, message) | None -> None (* note: bad payloads detected by warning_attribute *) end | _ -> None let alert_attrs l = List.filter_map alert_attr l let alerts_of_attrs l = List.fold_left (fun acc (_, kind, message) -> let upd = function | None | Some "" -> Some message | Some s -> Some (cat s message) in Misc.String.Map.update kind upd acc ) Misc.String.Map.empty (alert_attrs l) let check_alerts loc attrs s = Misc.String.Map.iter (fun kind message -> Location.alert loc ~kind (cat s message)) (alerts_of_attrs attrs) let check_alerts_inclusion ~def ~use loc attrs1 attrs2 s = let m2 = alerts_of_attrs attrs2 in Misc.String.Map.iter (fun kind msg -> if not (Misc.String.Map.mem kind m2) then Location.alert ~def ~use ~kind loc (cat s msg) ) (alerts_of_attrs attrs1) let rec deprecated_mutable_of_attrs = function | [] -> None | {attr_name = {txt = "ocaml.deprecated_mutable"|"deprecated_mutable"; _}; attr_payload = p} :: _ -> Some (string_of_opt_payload p) | _ :: tl -> deprecated_mutable_of_attrs tl let check_deprecated_mutable loc attrs s = match deprecated_mutable_of_attrs attrs with | None -> () | Some txt -> Location.deprecated loc (Printf.sprintf "mutating field %s" (cat s txt)) let check_deprecated_mutable_inclusion ~def ~use loc attrs1 attrs2 s = match deprecated_mutable_of_attrs attrs1, deprecated_mutable_of_attrs attrs2 with | None, _ | Some _, Some _ -> () | Some txt, None -> Location.deprecated ~def ~use loc (Printf.sprintf "mutating field %s" (cat s txt)) let rec attrs_of_sig = function | {psig_desc = Psig_attribute a} :: tl -> a :: attrs_of_sig tl | _ -> [] let alerts_of_sig sg = alerts_of_attrs (attrs_of_sig sg) let rec attrs_of_str = function | {pstr_desc = Pstr_attribute a} :: tl -> a :: attrs_of_str tl | _ -> [] let alerts_of_str str = alerts_of_attrs (attrs_of_str str) let check_no_alert attrs = List.iter (fun (a, _, _) -> Location.prerr_warning a.attr_loc (Warnings.Misplaced_attribute a.attr_name.txt) ) (alert_attrs attrs) let warn_payload loc txt msg = Location.prerr_warning loc (Warnings.Attribute_payload (txt, msg)) let warning_attribute ?(ppwarning = true) = let process loc txt errflag payload = match string_of_payload payload with | Some s -> begin try Option.iter (Location.prerr_alert loc) (Warnings.parse_options errflag s) with Arg.Bad msg -> warn_payload loc txt msg end | None -> warn_payload loc txt "A single string literal is expected" in let process_alert loc txt = function | PStr[{pstr_desc= Pstr_eval( {pexp_desc=Pexp_constant(Pconst_string(s,_,_))}, _) }] -> begin try Warnings.parse_alert_option s with Arg.Bad msg -> warn_payload loc txt msg end | k -> match kind_and_message k with | Some ("all", _) -> warn_payload loc txt "The alert name 'all' is reserved" | Some _ -> () | None -> warn_payload loc txt "Invalid payload" in function | {attr_name = {txt = ("ocaml.warning"|"warning") as txt; _}; attr_loc; attr_payload; } -> process attr_loc txt false attr_payload | {attr_name = {txt = ("ocaml.warnerror"|"warnerror") as txt; _}; attr_loc; attr_payload } -> process attr_loc txt true attr_payload | {attr_name = {txt="ocaml.ppwarning"|"ppwarning"; _}; attr_loc = _; attr_payload = PStr [ { pstr_desc= Pstr_eval({pexp_desc=Pexp_constant (Pconst_string (s, _, _))},_); pstr_loc } ]; } when ppwarning -> Location.prerr_warning pstr_loc (Warnings.Preprocessor s) | {attr_name = {txt = ("ocaml.alert"|"alert") as txt; _}; attr_loc; attr_payload; } -> process_alert attr_loc txt attr_payload | _ -> () let warning_scope ?ppwarning attrs f = let prev = Warnings.backup () in try List.iter (warning_attribute ?ppwarning) (List.rev attrs); let ret = f () in Warnings.restore prev; ret with exn -> Warnings.restore prev; raise exn let warn_on_literal_pattern = List.exists (fun a -> match a.attr_name.txt with | "ocaml.warn_on_literal_pattern"|"warn_on_literal_pattern" -> true | _ -> false ) let explicit_arity = List.exists (fun a -> match a.attr_name.txt with | "ocaml.explicit_arity"|"explicit_arity" -> true | _ -> false ) let immediate = List.exists (fun a -> match a.attr_name.txt with | "ocaml.immediate"|"immediate" -> true | _ -> false ) let immediate64 = List.exists (fun a -> match a.attr_name.txt with | "ocaml.immediate64"|"immediate64" -> true | _ -> false ) (* The "ocaml.boxed (default)" and "ocaml.unboxed (default)" attributes cannot be input by the user, they are added by the compiler when applying the default setting. This is done to record in the .cmi the default used by the compiler when compiling the source file because the default can change between compiler invocations. *) let check l a = List.mem a.attr_name.txt l let has_unboxed attr = List.exists (check ["ocaml.unboxed"; "unboxed"]) attr let has_boxed attr = List.exists (check ["ocaml.boxed"; "boxed"]) attr
(**************************************************************************) (* *) (* OCaml *) (* *) (* Alain Frisch, LexiFi *) (* *) (* Copyright 2012 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
efsolver.c
/* * SUPPORT FOR EXISTS/FORALL SOLVING */ #if defined(CYGWIN) || defined(MINGW) #ifndef __YICES_DLLSPEC__ #define __YICES_DLLSPEC__ __declspec(dllexport) #endif #endif #include <inttypes.h> #include "context/context.h" #include "exists_forall/efsolver.h" #include "model/literal_collector.h" //get_implicant (pre qf normalization) #include "model/projection.h" //project_literals (quantifier elimination) #include "terms/term_substitution.h" #include "utils/index_vectors.h" #include "yices.h" #define EF_VERBOSE 0 /* * PRINT STUFF */ /* * Print solution found by the ef solver */ void print_ef_solution(FILE *f, ef_solver_t *solver) { ef_prob_t *prob; uint32_t i, n; prob = solver->prob; n = ef_prob_num_evars(prob); for (i=0; i<n; i++) { fprintf(f, "%s := ", yices_get_term_name(prob->all_evars[i])); yices_pp_term(f, solver->evalue[i], 100, 1, 10); } } /* * Show witness found for constraint i */ void print_forall_witness(FILE *f, ef_solver_t *solver, uint32_t i) { ef_prob_t *prob; ef_cnstr_t *cnstr; uint32_t j, n; prob = solver->prob; assert(i < ef_prob_num_constraints(prob)); cnstr = prob->cnstr + i; n = ef_constraint_num_uvars(cnstr); for (j=0; j<n; j++) { fprintf(f, "%s := ", yices_get_term_name(cnstr->uvars[j])); yices_pp_term(f, solver->uvalue_aux.data[j], 100, 1, 10); } } /* * Print the full map: * - the variables are in solver->all_vars * - their values are in solver->all_values */ void print_full_map(FILE *f, ef_solver_t *solver) { uint32_t i, n; n = solver->all_vars.size; assert(n == solver->all_values.size); for (i=0; i<n; i++) { fprintf(f, "%s := ", yices_get_term_name(solver->all_vars.data[i])); yices_pp_term(f, solver->all_values.data[i], 100, 1, 10); } fprintf(f, "(%"PRIu32" variables)\n", n); } /* * GLOBAL PROCEDURES */ /* * Initialize solver: * - prob = problem descriptor * - logic/arch/parameters = for context initialization and check */ void init_ef_solver(ef_solver_t *solver, ef_prob_t *prob, smt_logic_t logic, context_arch_t arch) { uint32_t n; solver->prob = prob; solver->logic = logic; solver->arch = arch; solver->status = EF_STATUS_IDLE; solver->error_code = 0; solver->parameters = NULL; solver->option = EF_GEN_BY_SUBST_OPTION; solver->max_samples = 0; solver->max_iters = 0; solver->scan_idx = 0; solver->exists_context = NULL; solver->forall_context = NULL; solver->exists_model = NULL; n = ef_prob_num_evars(prob); assert(n <= UINT32_MAX/sizeof(term_t)); solver->evalue = (term_t *) safe_malloc(n * sizeof(term_t)); n = ef_prob_num_uvars(prob); assert(n <= UINT32_MAX/sizeof(term_t)); solver->uvalue = (term_t *) safe_malloc(n * sizeof(term_t)); solver->full_model = NULL; init_ivector(&solver->implicant, 20); init_ivector(&solver->projection, 20); init_ivector(&solver->evalue_aux, 64); init_ivector(&solver->uvalue_aux, 64); init_ivector(&solver->all_vars, 64); init_ivector(&solver->all_values, 64); solver->trace = NULL; } /* * Delete the whole thing */ void delete_ef_solver(ef_solver_t *solver) { if (solver->exists_context != NULL) { delete_context(solver->exists_context); safe_free(solver->exists_context); solver->exists_context = NULL; } if (solver->forall_context != NULL) { delete_context(solver->forall_context); safe_free(solver->forall_context); solver->forall_context = NULL; } if (solver->exists_model != NULL) { yices_free_model(solver->exists_model); solver->exists_model = NULL; } safe_free(solver->evalue); safe_free(solver->uvalue); solver->evalue = NULL; solver->uvalue = NULL; if (solver->full_model != NULL) { yices_free_model(solver->full_model); solver->full_model = NULL; } delete_ivector(&solver->implicant); delete_ivector(&solver->projection); delete_ivector(&solver->evalue_aux); delete_ivector(&solver->uvalue_aux); delete_ivector(&solver->all_vars); delete_ivector(&solver->all_values); } /* * Set the trace: * - the current tracer must be NULL. */ void ef_solver_set_trace(ef_solver_t *solver, tracer_t *trace) { assert(solver->trace == NULL); solver->trace = trace; } /* * OPERATIONS ON THE EXISTS CONTEXT */ /* * Allocate and initialize the exists context */ static void init_exists_context(ef_solver_t *solver) { context_t *ctx; assert(solver->exists_context == NULL); ctx = (context_t *) safe_malloc(sizeof(context_t)); init_context(ctx, solver->prob->terms, solver->logic, CTX_MODE_MULTICHECKS, solver->arch, false); // qflag is false solver->exists_context = ctx; if (solver->trace != NULL) { context_set_trace(ctx, solver->trace); } } /* * Assert all the conditions from prob into ctx * - return the internalization code */ static int32_t exists_context_assert_conditions(ef_solver_t *solver) { context_t *ctx; uint32_t n; ctx = solver->exists_context; assert(ctx != NULL && context_status(ctx) == STATUS_IDLE); n = ef_prob_num_conditions(solver->prob); return assert_formulas(ctx, n, solver->prob->conditions); } /* * Add assertion f to the exists context * - return the internalization code * - the exists context must not be UNSAT */ static int32_t update_exists_context(ef_solver_t *solver, term_t f) { context_t *ctx; smt_status_t status; int32_t code; ctx = solver->exists_context; assert(ctx != NULL && is_boolean_term(ctx->terms, f)); status = context_status(ctx); switch (status) { case STATUS_SAT: case STATUS_UNKNOWN: context_clear(ctx); assert(context_status(ctx) == STATUS_IDLE); case STATUS_IDLE: code = assert_formula(ctx, f); break; default: code = INTERNAL_ERROR; // should not happen break; } return code; } /* * SUBSTITUTION */ /* * Apply the substitution defined by var and value to term t * - n = size of arrays var and value * - return code < 0 means that an error occurred during the substitution * (cf. apply_term_subst in term_substitution.h). */ static term_t ef_substitution(ef_prob_t *prob, term_t *var, term_t *value, uint32_t n, term_t t) { term_subst_t subst; term_t g; init_term_subst(&subst, prob->manager, n, var, value); g = apply_term_subst(&subst, t); delete_term_subst(&subst); return g; } /* * FORALL CONTEXT */ /* * Allocate and initialize it (prior to sampling) */ static void init_forall_context(ef_solver_t *solver) { context_t *ctx; assert(solver->forall_context == NULL); ctx = (context_t *) safe_malloc(sizeof(context_t)); init_context(ctx, solver->prob->terms, solver->logic, CTX_MODE_MULTICHECKS, solver->arch, false); solver->forall_context = ctx; if (solver->trace != NULL) { context_set_trace(ctx, solver->trace); } } /* * Assert (B and not C) in ctx * - return the assertion code */ static int32_t forall_context_assert(ef_solver_t *solver, term_t b, term_t c) { context_t *ctx; term_t assertions[2]; ctx = solver->forall_context; assert(ctx != NULL && context_status(ctx) == STATUS_IDLE); assert(is_boolean_term(ctx->terms, b) && is_boolean_term(ctx->terms, c)); assertions[0] = b; assertions[1] = opposite_term(c); return assert_formulas(ctx, 2, assertions); } /* * Free or reset the forall_context: * - if flag del is true: delete * - otherwise, just reset */ static void clear_forall_context(ef_solver_t *solver, bool del) { assert(solver->forall_context != NULL); if (del) { delete_context(solver->forall_context); safe_free(solver->forall_context); solver->forall_context = NULL; } else { reset_context(solver->forall_context); } } /* * Get the forall_context: return it if it's not NULL * allocate and initialize it otherwise. */ static context_t *get_forall_context(ef_solver_t *solver) { if (solver->forall_context == NULL) { init_forall_context(solver); } return solver->forall_context; } /* * SAT SOLVING */ /* * Check satisfiability and get a model * - ctx = the context * - parameters = heuristic settings (if parameters is NULL, the defaults are used) * - var = array of n uninterpreted terms * - n = size of array evar and value * Output parameters; * - value = array of n terms (to receive the value of each var) * - model = to export the model (if model is NULL, nothing is exported) * * The return code is as in check_context: * 1) if code = STATUS_SAT then the context is satisfiable * and a model is stored in value[0 ... n-1] * - value[i] = a constant term mapped to evar[i] in the model * 2) code = STATUS_UNSAT: not satisfiable * * 3) other codes report an error of some kind or STATUS_INTERRUPTED */ static smt_status_t satisfy_context(context_t *ctx, const param_t *parameters, term_t *var, uint32_t n, term_t *value, model_t **model) { smt_status_t stat; model_t *mdl; int32_t code; assert(context_status(ctx) == STATUS_IDLE); stat = check_context(ctx, parameters); switch (stat) { case STATUS_SAT: case STATUS_UNKNOWN: mdl = yices_get_model(ctx, true); code = yices_term_array_value(mdl, n, var, value); if (model != NULL) { *model = mdl; } else { yices_free_model(mdl); } if (code < 0) { // can't convert the model to constant terms stat = STATUS_ERROR; } break; default: // can't build a model break; } return stat; } /* * Check satisfiability of the exists_context * - first free the exists_model if non-NULL * - if SAT build a model (in solver->evalue) and store the exists_model */ static smt_status_t ef_solver_check_exists(ef_solver_t *solver) { term_t *evar; uint32_t n; if (solver->exists_model != NULL) { yices_free_model(solver->exists_model); solver->exists_model = NULL; } evar = solver->prob->all_evars; n = iv_len(evar); return satisfy_context(solver->exists_context, solver->parameters, evar, n, solver->evalue, &solver->exists_model); } /* * Test the current exists model using universal constraint i * - i must be a valid index (i.e., 0 <= i < solver->prob->num_cnstr) * - this checks the assertion B_i and not C_i after replacing existential * variables by their values (stored in evalue) * - return code: * if STATUS_SAT (or STATUS_UNKNOWN): a model of (B_i and not C_i) * is found and stored in uvalue_aux * if STATUS_UNSAT: no model found (current exists model is good as * far as constraint i is concerned) * anything else: an error or interruption * * - if we get an error or interruption, solver->status is updated * otherwise, it is kept as is (should be EF_STATUS_SEARCHING) */ static smt_status_t ef_solver_test_exists_model(ef_solver_t *solver, uint32_t i) { context_t *forall_ctx; ef_cnstr_t *cnstr; term_t *value; term_t g; uint32_t n; int32_t code; smt_status_t status; assert(i < ef_prob_num_constraints(solver->prob)); cnstr = solver->prob->cnstr + i; n = ef_prob_num_evars(solver->prob); g = ef_substitution(solver->prob, solver->prob->all_evars, solver->evalue, n, cnstr->guarantee); if (g < 0) { // error in substitution solver->status = EF_STATUS_SUBST_ERROR; solver->error_code = g; return STATUS_ERROR; } /* * make uvalue_aux large enough */ n = ef_constraint_num_uvars(cnstr); resize_ivector(&solver->uvalue_aux, n); solver->uvalue_aux.size = n; value = solver->uvalue_aux.data; forall_ctx = get_forall_context(solver); code = forall_context_assert(solver, cnstr->assumption, g); // assert B_i(Y_i) and not g(Y_i) if (code == CTX_NO_ERROR) { status = satisfy_context(forall_ctx, solver->parameters, cnstr->uvars, n, value, NULL); switch (status) { case STATUS_SAT: case STATUS_UNKNOWN: case STATUS_UNSAT: break; case STATUS_INTERRUPTED: solver->status = EF_STATUS_INTERRUPTED; break; default: solver->status = EF_STATUS_CHECK_ERROR; solver->error_code = status; break; } } else if (code == TRIVIALLY_UNSAT) { assert(context_status(forall_ctx) == STATUS_UNSAT); status = STATUS_UNSAT; } else { // error in assertion solver->status = EF_STATUS_ASSERT_ERROR; solver->error_code = code; status = STATUS_ERROR; } clear_forall_context(solver, true); return status; } /* * PROJECTION */ /* * Search for x in sorted array v */ static int32_t find_elem(int32_t *v, int32_t x) { uint32_t i, j, k; i = 0; j = iv_len(v); while (i < j) { k = (i + j) >> 1; assert(i <= k && k < j); if (v[k] == x) return k; if (v[k] < x) { i = k+1; } else { j = k; } } return -1; // not found } /* * Restrict a model defined by var and value to subvar * - the result is stored in subvalue * - n = size of arrays subvar and subvalue * - preconditions: * var is a sorted index vector * every element of subvar occurs in var * value has the same size as var */ static void project_model(int32_t *var, term_t *value, term_t *subvar, term_t *subvalue, uint32_t n) { uint32_t i; int32_t k; for (i=0; i<n; i++) { k = find_elem(var, subvar[i]); assert(k >= 0 && subvar[i] == var[k]); subvalue[i] = value[k]; } } /* * Project model onto a subset of the existential variables * - value[i] = exist model = array of constant values * - evar = an array of n existential variables: every element of evar occurs in ef->all_evars * - then this function builds the model restricted to evar into array eval * * Assumption: * - value[i] = value mapped to ef->all_evars[i] for i=0 ... num_evars-1 * - every x in sub_var occurs somewhere in ef->all_evars * - then if evar[i] = x and x is equal to all_evar[k] the function copies * value[k] into eval[i] */ static void ef_project_exists_model(ef_prob_t *prob, term_t *value, term_t *evar, term_t *eval, uint32_t n) { project_model(prob->all_evars, value, evar, eval, n); } /* * PRE SAMPLING */ /* * Sampling for the i-th constraint in solver->prob * - search for at most max_samples y's that satisfy the assumption of constraint i in prob * - for each such y, add a new constraint to the exist context ctx * - max_samples = bound on the number of samples to take (must be positive) * * Constraint i is of the form * (FORALL Y_i: B_i(Y_i) => C(X_i, Y_i)) * - every sample is a model y_i that satisfies B_i. * - for each sample, we learn that any good candidate X_i must satisfy C(X_i, y_i). * So we add the constraint C(X_i, y_i) to ctx. * * Update the solver->status to * - EF_STATUS_UNSAT if the exits context is trivially unsat * - EF_STATUS_..._ERROR if something goes wrong * - EF_STATUS_INTERRUPTED if a call to check/recheck context is interrupted * keep it unchanged otherwise (should be EF_STATUS_SEARCHING). */ static void ef_sample_constraint(ef_solver_t *solver, uint32_t i) { context_t *sampling_ctx; ef_cnstr_t *cnstr; term_t *value; uint32_t nvars, samples; int32_t ucode, ecode; smt_status_t status; term_t cnd; assert(i < ef_prob_num_constraints(solver->prob) && solver->max_samples > 0); cnstr = solver->prob->cnstr + i; /* * make uvalue_aux large enough * its size = number of universal variables in constraint i */ nvars = ef_constraint_num_uvars(cnstr); resize_ivector(&solver->uvalue_aux, nvars); solver->uvalue_aux.size = nvars; value = solver->uvalue_aux.data; samples = solver->max_samples; /* * assert the assumption in the forall context */ sampling_ctx = get_forall_context(solver); ucode = assert_formula(sampling_ctx, cnstr->assumption); while (ucode == CTX_NO_ERROR) { tprintf(solver->trace, 4, "(EF: start: sampling universal variables)\n"); status = satisfy_context(sampling_ctx, solver->parameters, cnstr->uvars, nvars, value, NULL); switch (status) { case STATUS_SAT: case STATUS_UNKNOWN: // learned condition on X: cnd = ef_substitution(solver->prob, cnstr->uvars, value, nvars, cnstr->guarantee); if (cnd < 0) { solver->status = EF_STATUS_SUBST_ERROR; solver->error_code = cnd; goto done; } ecode = update_exists_context(solver, cnd); if (ecode < 0) { solver->status = EF_STATUS_ASSERT_ERROR; solver->error_code = ecode; goto done; } if (ecode == TRIVIALLY_UNSAT) { solver->status = EF_STATUS_UNSAT; goto done; } break; case STATUS_UNSAT: // no more samples for this constraints goto done; case STATUS_INTERRUPTED: solver->status = EF_STATUS_INTERRUPTED; goto done; default: solver->status = EF_STATUS_CHECK_ERROR; solver->error_code = status; goto done; } samples --; if (samples == 0) goto done; ucode = assert_blocking_clause(sampling_ctx); } /* * if ucode < 0, something went wrong in assert_formula * or in assert_blocking_clause */ if (ucode < 0) { solver->status = EF_STATUS_ASSERT_ERROR; solver->error_code = ucode; } done: clear_forall_context(solver, true); } /* * FIRST EXISTS MODELS */ /* * Initialize the exists context * - asserts all conditions from solver->prob * - if max_samples is positive, also apply pre-sampling to all the universal constraints * * - solver->status is set as follows * EF_STATUS_SEARCHING: means not solved yet * EF_STATUS_UNSAT: if the exists context is trivially UNSAT * EF_STATUS_..._ERROR: if something goes wrong * EF_STATUS_INTERRUPTED if the pre-sampling is interrupted */ static void ef_solver_start(ef_solver_t *solver) { int32_t code; uint32_t i, n; assert(solver->status == EF_STATUS_IDLE); solver->status = EF_STATUS_SEARCHING; init_exists_context(solver); code = exists_context_assert_conditions(solver); // add all conditions if (code < 0) { // assertion error solver->status = EF_STATUS_ASSERT_ERROR; solver->error_code = code; } else if (code == TRIVIALLY_UNSAT) { solver->status = EF_STATUS_UNSAT; } else if (solver->max_samples > 0) { /* * run the pre-sampling stuff */ n = ef_prob_num_constraints(solver->prob); for (i=0; i<n; i++) { ef_sample_constraint(solver, i); if (solver->status != EF_STATUS_SEARCHING) break; } } } /* * IMPLICANT CONSTRUCTION */ /* * Merge the exists and forall variables of constraint i * - store the variables in solver->all_vars * - store their values in solver->all_values */ static void ef_build_full_map(ef_solver_t *solver, uint32_t i) { ef_cnstr_t *cnstr; ivector_t *v; uint32_t n; assert(i < ef_prob_num_constraints(solver->prob)); cnstr = solver->prob->cnstr + i; // collect all variables of cnstr in solver->all_vars v = &solver->all_vars; ivector_reset(v); n = ef_constraint_num_evars(cnstr); ivector_add(v, cnstr->evars, n); n = ef_constraint_num_uvars(cnstr); ivector_add(v, cnstr->uvars, n); // project the evalues onto the exists variable of constraint i // store the results in all_values v = &solver->all_values; n = ef_constraint_num_evars(cnstr); resize_ivector(v, n); v->size = n; ef_project_exists_model(solver->prob, solver->evalue, cnstr->evars, v->data, n); // copy the uvalues for constraint i (from uvalue_aux to v) n = ef_constraint_num_uvars(cnstr); assert(n == solver->uvalue_aux.size); ivector_add(v, solver->uvalue_aux.data, n); #if EF_VERBOSE printf("Full map\n"); print_full_map(stdout, solver); fflush(stdout); #endif } /* * GENERALIZATION FROM UNIVERSAL MODELS */ /* * Option 1: don't generalize: * - build the formula (or (/= var[0] value[0]) ... (/= var[n-1] value[n-1])) */ static term_t ef_generalize1(ef_prob_t *prob, term_t *var, term_t *value, uint32_t n) { return mk_array_neq(prob->manager, n, var, value); } /* * Option 2: generalize by substitution * - return (prob->cnstr[i].guarantee with y := value) */ static term_t ef_generalize2(ef_prob_t *prob, uint32_t i, term_t *value) { ef_cnstr_t *cnstr; uint32_t n; term_t g; assert(i < ef_prob_num_constraints(prob)); cnstr = prob->cnstr + i; n = ef_constraint_num_uvars(cnstr); g = ef_substitution(prob, cnstr->uvars, value, n, cnstr->guarantee); return g; } /* * Option 3: generalize by computing an implicant then * applying projection. */ static term_t ef_generalize3(ef_solver_t *solver, uint32_t i) { model_t *mdl; ef_cnstr_t *cnstr; ivector_t *v, *w; term_t a[2]; uint32_t n; int32_t code; proj_flag_t pflag; term_t result; assert(i < ef_prob_num_constraints(solver->prob)); // free the current full model if any if (solver->full_model != NULL) { yices_free_model(solver->full_model); solver->full_model = NULL; } // build the full_map and the corresponding model. ef_build_full_map(solver, i); n = solver->all_vars.size; assert(n == solver->all_values.size); mdl = yices_model_from_map(n, solver->all_vars.data, solver->all_values.data); if (mdl == NULL) { // error in the model construction solver->status = EF_STATUS_MDL_ERROR; solver->error_code = yices_error_code(); return NULL_TERM; } solver->full_model = mdl; // Constraint cnstr = solver->prob->cnstr + i; a[0] = cnstr->assumption; // B(y) a[1] = opposite_term(cnstr->guarantee); // not C(x, y) #if EF_VERBOSE printf("Constraint:\n"); yices_pp_term_array(stdout, 2, a, 120, UINT32_MAX, 0, 0); printf("(%"PRIu32" literals)\n", 2); #endif // Compute the implicant v = &solver->implicant; ivector_reset(v); code = get_implicant(mdl, solver->prob->manager, LIT_COLLECTOR_ALL_OPTIONS, 2, a, v); if (code < 0) { solver->status = EF_STATUS_IMPLICANT_ERROR; solver->error_code = code; return NULL_TERM; } #if EF_VERBOSE printf("Implicant:\n"); yices_pp_term_array(stdout, v->size, v->data, 120, UINT32_MAX, 0, 0); printf("(%"PRIu32" literals)\n", v->size); #endif // Projection w = &solver->projection; ivector_reset(w); n = ef_constraint_num_uvars(cnstr); #if EF_VERBOSE printf("(%"PRIu32" universals)\n", n); yices_pp_term_array(stdout, n, cnstr->uvars, 120, UINT32_MAX, 0, 0); #endif pflag = project_literals(mdl, solver->prob->manager, v->size, v->data, n, cnstr->uvars, w); if (pflag != PROJ_NO_ERROR) { solver->status = EF_STATUS_PROJECTION_ERROR; solver->error_code = pflag; return NULL_TERM; } #if EF_VERBOSE printf("Projection:\n"); yices_pp_term_array(stdout, w->size, w->data, 120, UINT32_MAX, 0, 0); printf("(%"PRIu32" literals)\n", w->size); #endif switch (w->size) { case 0: result = true_term; break; case 1: result = w->data[0]; break; default: result = mk_and(solver->prob->manager, w->size, w->data); break; } return opposite_term(result); } /* * Learn a constraint for the exists variable based on the * existing forall witness for constraint i: * - the witness is defined by the uvars of constraint i * and the values stored in uvalue_aux. * * This function adds a constraint to the exists_context that will remove the * current exists model: * - if solver->option is EF_NOGEN_OPTION, the new constraint is * of the form (or (/= var[0] eval[k0]) ... (/= var[k-1] eval[k-1])) * where var[0 ... k-1] are the exist variables of constraint i * - if solver->option is EF_GEN_BY_SUBST_OPTION, we build a new * constraint by substitution (option 2) * * If something goes wrong, then solver->status is updated to EF_STATUS_ERROR. * If the new learned assertion makes the exist context trivially unsat * then context->status is set to EF_STATUS_UNSAT. * Otherwise context->status is kept as is. */ static void ef_solver_learn(ef_solver_t *solver, uint32_t i) { ef_cnstr_t *cnstr; term_t *val; term_t new_constraint; uint32_t n; int32_t code; assert(i < ef_prob_num_constraints(solver->prob)); cnstr = solver->prob->cnstr + i; switch (solver->option) { case EF_NOGEN_OPTION: /* * project solver->evalues on the existential * variables that occur in constraint i. * then build (or (/= evar[0] val[0]) ... (/= evar[n-1] val[n-1])) */ n = ef_constraint_num_evars(cnstr); resize_ivector(&solver->evalue_aux, n); solver->evalue_aux.size = n; val = solver->evalue_aux.data; ef_project_exists_model(solver->prob, solver->evalue, cnstr->evars, val, n); new_constraint = ef_generalize1(solver->prob, cnstr->evars, val, n); break; case EF_GEN_BY_SUBST_OPTION: val = solver->uvalue_aux.data; new_constraint = ef_generalize2(solver->prob, i, val); if (new_constraint < 0) { // error in substitution solver->status = EF_STATUS_SUBST_ERROR; solver->error_code = new_constraint; return; } break; case EF_GEN_BY_PROJ_OPTION: default: // added this to prevent bogus GCC warning new_constraint = ef_generalize3(solver, i); if (new_constraint < 0) { return; } break; } // add the new constraint to the exists context code = update_exists_context(solver, new_constraint); if (code == TRIVIALLY_UNSAT) { solver->status = EF_STATUS_UNSAT; } else if (code < 0) { solver->status = EF_STATUS_ASSERT_ERROR; solver->error_code = code; } } /* * EF SOLVER: INNER LOOP */ /* * Trace: result of testing candidate * - i = constraint id */ static void trace_candidate_check(ef_solver_t *solver, uint32_t i, smt_status_t status) { switch (status) { case STATUS_SAT: case STATUS_UNKNOWN: tprintf(solver->trace, 4, "(EF: candidate rejected: failed constraint %"PRIu32")\n", i); break; case STATUS_UNSAT: tprintf(solver->trace, 4, "(EF: candidate passed constraint %"PRIu32")\n", i); break; case STATUS_INTERRUPTED: tprintf(solver->trace, 4, "(EF: candidate check was interrupted)\n"); break; default: tprintf(solver->trace, 4, "(EF: error in candidate check for constraint %"PRIu32")\n", i); break; } } /* * Check whether the current exists_model can be falsified by one * of the universal constraints. * - scan the universal constraints starting from solver->scan_idx * - the current exists model is defined by * the mapping from solver->prob->evars to solver->evalues * * Update the solver->status as follows: * - if no constraint falsifies the model, solver->status = EF_STATUS_SAT * - if some constraint falsifies the model, then solver->status may be * updated to EF_STATUS_UNSAT (trivially unsat after learning) * - if something goes wrong, solver->status = EF_STATUS_ERROR * * If constraint i falsifies the model then solver->scan_idx is * set to (i+1) modulo num_constraints. */ static void ef_solver_check_exists_model(ef_solver_t *solver) { smt_status_t status; uint32_t i, n; n = ef_prob_num_constraints(solver->prob); /* * Special case: if there are no universal constraints * we return SAT immediately. */ if (n == 0) { solver->status = EF_STATUS_SAT; return; } i = solver->scan_idx; do { tprintf(solver->trace, 4, "(EF: testing candidate against constraint %"PRIu32")\n", i); status = ef_solver_test_exists_model(solver, i); trace_candidate_check(solver, i, status); switch (status) { case STATUS_SAT: case STATUS_UNKNOWN: #if EF_VERBOSE printf("Counterexample for constraint[%"PRIu32"]\n", i); print_forall_witness(stdout, solver, i); printf("\n"); fflush(stdout); #endif ef_solver_learn(solver, i); default: i ++; if (i == n) { i = 0; } break; } } while (status == STATUS_UNSAT && i != solver->scan_idx); solver->scan_idx = i; // prepare for the next call if (status == STATUS_UNSAT) { // done a full scan solver->status = EF_STATUS_SAT; } } /* * EF SOLVER: OUTER LOOP */ /* * Sample exists models * - stop when we find one that's not refuted by the forall constraints * - or when we reach the iteration bound * * Result: * - solver->status = EF_STATUS_ERROR if something goes wrong * - solver->status = EF_STATUS_INTERRUPTED if one of the calls to * check_context is interrupted * - solver->status = EF_STATUS_UNSAT if all efmodels have been tried and none * of them worked * - solver->status = EF_STATUS_UNKNOWN if the iteration limit is reached * - solver->status = EF_STATUS_SAT if a good model is found * * In the later case, * - the model is stored in solver->exists_model * - also it's available as a mapping form solver->prob->evars to solver->evalues * * Also solver->iters stores the number of iterations used. */ static void ef_solver_search(ef_solver_t *solver) { smt_status_t stat; uint32_t i, max; max = solver->max_iters; i = 0; assert(max > 0); tprintf(solver->trace, 2, "(EF search: %"PRIu32" constraints, %"PRIu32" exists vars, %"PRIu32" forall vars)\n", ef_prob_num_constraints(solver->prob), ef_prob_num_evars(solver->prob), ef_prob_num_uvars(solver->prob)); #if EF_VERBOSE printf("\nConditions on the exists variables:\n"); yices_pp_term_array(stdout, ef_prob_num_conditions(solver->prob), solver->prob->conditions, 120, UINT32_MAX, 0, 0); #endif ef_solver_start(solver); while (solver->status == EF_STATUS_SEARCHING && i < max) { tprintf(solver->trace, 3, "(EF Iteration %"PRIu32", scan_idx = %"PRIu32")\n", i, solver->scan_idx); stat = ef_solver_check_exists(solver); switch (stat) { case STATUS_SAT: case STATUS_UNKNOWN: // we have a candidate exists model // check it and learn what we can #if EF_VERBOSE // FOR DEBUGGING printf("Candidate exists model:\n"); print_ef_solution(stdout, solver); printf("\n"); #endif tputs(solver->trace, 4, "(EF: Found candidate model)\n"); ef_solver_check_exists_model(solver); break; case STATUS_UNSAT: tputs(solver->trace, 4, "(EF: No candidate model)\n"); solver->status = EF_STATUS_UNSAT; break; case STATUS_INTERRUPTED: tputs(solver->trace, 4, "(EF: Interrupted)\n"); solver->status = EF_STATUS_INTERRUPTED; break; default: solver->status = EF_STATUS_CHECK_ERROR; solver->error_code = stat; break; } i ++; } /* * Cleanup and set status if i == max */ if (solver->status != EF_STATUS_SAT && solver->exists_model != NULL) { yices_free_model(solver->exists_model); solver->exists_model = NULL; if (solver->status == EF_STATUS_SEARCHING) { assert(i == max); solver->status = EF_STATUS_UNKNOWN; } } solver->iters = i; tputs(solver->trace, 3, "(EF: done)\n\n"); } /* * Check satisfiability: the result is stored in solver->status * - if solver->status is EF_STATUS_SAT then the model is in solver->exists_model * (as in ef_solver_search). */ void ef_solver_check(ef_solver_t *solver, const param_t *parameters, ef_gen_option_t gen_mode, uint32_t max_samples, uint32_t max_iters) { solver->parameters = parameters; solver->option = gen_mode; solver->max_samples = max_samples; solver->max_iters = max_iters; solver->scan_idx = 0; // adjust mode if (gen_mode == EF_GEN_AUTO_OPTION) { solver->option = EF_GEN_BY_SUBST_OPTION; if (ef_prob_has_arithmetic_uvars(solver->prob)) { solver->option = EF_GEN_BY_PROJ_OPTION; } } assert(solver->exists_context == NULL && solver->forall_context == NULL && solver->exists_model == NULL); ef_solver_search(solver); }
/* * The Yices SMT Solver. Copyright 2014 SRI International. * * This program may only be used subject to the noncommercial end user * license agreement which is downloadable along with this program. */
test.ml
let () = Alcotest.run "irmin-bench" (Ema.test_cases @ Misc.test_cases @ Replay.test_cases)
(* * Copyright (c) 2018-2022 Tarides <contact@tarides.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
dependent_bool.ml
type no = private DNo type yes = private DYes type _ dbool = No : no dbool | Yes : yes dbool type ('a, 'b, 'r) dand = | NoNo : (no, no, no) dand | NoYes : (no, yes, no) dand | YesNo : (yes, no, no) dand | YesYes : (yes, yes, yes) dand type ('a, 'b) ex_dand = Ex_dand : ('a, 'b, _) dand -> ('a, 'b) ex_dand [@@unboxed] let dand : type a b. a dbool -> b dbool -> (a, b) ex_dand = fun a b -> match (a, b) with | (No, No) -> Ex_dand NoNo | (No, Yes) -> Ex_dand NoYes | (Yes, No) -> Ex_dand YesNo | (Yes, Yes) -> Ex_dand YesYes let dbool_of_dand : type a b r. (a, b, r) dand -> r dbool = function | NoNo -> No | NoYes -> No | YesNo -> No | YesYes -> Yes type (_, _) eq = Eq : ('a, 'a) eq let merge_dand : type a b c1 c2. (a, b, c1) dand -> (a, b, c2) dand -> (c1, c2) eq = fun w1 w2 -> match (w1, w2) with | (NoNo, NoNo) -> Eq | (NoYes, NoYes) -> Eq | (YesNo, YesNo) -> Eq | (YesYes, YesYes) -> Eq
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
vec_init.c
#include "arb.h" arb_ptr _arb_vec_init(slong n) { slong i; arb_ptr v = (arb_ptr) flint_malloc(sizeof(arb_struct) * n); for (i = 0; i < n; i++) arb_init(v + i); return v; }
/* Copyright (C) 2014 Fredrik Johansson This file is part of Arb. Arb is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */
test001.ml
open OCanren open Tester let rec zed f x = f (zed f) x module _ = struct [%%distrib type nonrec 'a t = | Z | S of 'a [@@deriving gt ~options:{ gmap; show }] type ground = ground t] let run_peano_exn n = run_r prj_exn (GT.show ground) n let run_peano n = run_r reify (GT.show logic) n let () = run_peano 1 q qh (REPR (fun q -> q === z ())); run_peano 1 q qh (REPR (fun q -> q === s (z ()))) ;; end module _ = struct [%%distrib type nonrec 'a t = | None | Some of 'a [@@deriving gt ~options:{ gmap; show }] type nonrec 'a ground = 'a t] let run_option n = run_r [%reify: GT.int ground] (GT.show logic (GT.show OCanren.logic (GT.show GT.int))) n ;; let () = run_option 1 q qh (REPR (fun q -> q === none ())); run_option 1 q qh (REPR (fun q -> fresh x (q === some x))); run_option 1 q qh (REPR (fun q -> fresh x (q === some !!42))) ;; end module _ = struct [%%distrib type nonrec ('a, 'b) t = | [] [@name "nil"] | ( :: ) of 'a * 'b [@name "cons"] [@@deriving gt ~options:{ gmap; show }] type 'a ground = ('a, 'a ground) t] let __ : ('a -> string) -> ('a logic as 'b) -> string = GT.show logic let __ : int OCanren.logic logic -> string = GT.show logic (GT.show OCanren.logic (GT.show GT.int)) ;; let __ : ((('b ilogic, 'a) t ilogic as 'a), (('b, 'c) t as 'c)) OCanren__Logic.Reifier.t = prj_exn OCanren.prj_exn ;; let __ = reify OCanren.reify let run_list n = run_r [%reify: GT.int t] (GT.show logic (GT.show OCanren.logic (GT.show GT.int))) n ;; let () = run_list 1 q qh (REPR (fun q -> q === nil ())); run_list 1 q qh (REPR (fun q -> fresh x (q === cons x (nil ())))) ;; end module Moves = struct [%%distrib type nonrec 'nat t = | Forward of 'nat | Backward of 'nat | Unload of 'nat | Fill of 'nat [@@deriving gt ~options:{ gmap; show }] type nonrec ground = GT.int t] end
mBytes.mli
type t val create : int -> t val length : t -> int val copy : t -> t (** [sub src ofs len] extract a sub-array of [src] starting at [ofs] and of length [len]. No copying of elements is involved: the sub-array and the original array share the same storage space. *) val sub : t -> int -> int -> t (** [blit src ofs_src dst ofs_dst len] copy [len] bytes from [src] starting at [ofs_src] into [dst] starting at [ofs_dst]. *) val blit : t -> int -> t -> int -> int -> unit (** See [blit] *) val blit_of_string : string -> int -> t -> int -> int -> unit (** See [blit] *) val blit_to_bytes : t -> int -> bytes -> int -> int -> unit (** [of_string s] create an byte array filled with the same content than [s]. *) val of_string : string -> t (** [to_string b] dump the array content in a [string]. *) val to_string : t -> string (** [sub_string b ofs len] is equivalent to [to_string (sub b ofs len)]. *) val sub_string : t -> int -> int -> string (** Functions reading and writing bytes *) (** [get_char buff i] reads 1 byte at offset i as a char *) val get_char : t -> int -> char (** [get_uint8 buff i] reads 1 byte at offset i as an unsigned int of 8 bits. i.e. It returns a value between 0 and 2^8-1 *) val get_uint8 : t -> int -> int (** [get_int8 buff i] reads 1 byte at offset i as a signed int of 8 bits. i.e. It returns a value between -2^7 and 2^7-1 *) val get_int8 : t -> int -> int (** [set_char buff i v] writes [v] to [buff] at offset [i] *) val set_char : t -> int -> char -> unit (** [set_int8 buff i v] writes the least significant 8 bits of [v] to [buff] at offset [i] *) val set_int8 : t -> int -> int -> unit (** Functions reading according to Big Endian byte order *) (** [get_uint16 buff i] reads 2 bytes at offset i as an unsigned int of 16 bits. i.e. It returns a value between 0 and 2^16-1 *) val get_uint16 : t -> int -> int (** [get_int16 buff i] reads 2 byte at offset i as a signed int of 16 bits. i.e. It returns a value between -2^15 and 2^15-1 *) val get_int16 : t -> int -> int (** [get_int32 buff i] reads 4 bytes at offset i as an int32. *) val get_int32 : t -> int -> int32 (** [get_int64 buff i] reads 8 bytes at offset i as an int64. *) val get_int64 : t -> int -> int64 (** [set_int16 buff i v] writes the least significant 16 bits of [v] to [buff] at offset [i] *) val set_int16 : t -> int -> int -> unit (** [set_int32 buff i v] writes [v] to [buff] at offset [i] *) val set_int32 : t -> int -> int32 -> unit (** [set_int64 buff i v] writes [v] to [buff] at offset [i] *) val set_int64 : t -> int -> int64 -> unit module LE : sig (** Functions reading according to Little Endian byte order *) (** [get_uint16 buff i] reads 2 bytes at offset i as an unsigned int of 16 bits. i.e. It returns a value between 0 and 2^16-1 *) val get_uint16 : t -> int -> int (** [get_int16 buff i] reads 2 byte at offset i as a signed int of 16 bits. i.e. It returns a value between -2^15 and 2^15-1 *) val get_int16 : t -> int -> int (** [get_int32 buff i] reads 4 bytes at offset i as an int32. *) val get_int32 : t -> int -> int32 (** [get_int64 buff i] reads 8 bytes at offset i as an int64. *) val get_int64 : t -> int -> int64 (** [set_int16 buff i v] writes the least significant 16 bits of [v] to [buff] at offset [i] *) val set_int16 : t -> int -> int -> unit (** [set_int32 buff i v] writes [v] to [buff] at offset [i] *) val set_int32 : t -> int -> int32 -> unit (** [set_int64 buff i v] writes [v] to [buff] at offset [i] *) val set_int64 : t -> int -> int64 -> unit end val ( = ) : t -> t -> bool val ( <> ) : t -> t -> bool val ( < ) : t -> t -> bool val ( <= ) : t -> t -> bool val ( >= ) : t -> t -> bool val ( > ) : t -> t -> bool val compare : t -> t -> int val concat : string -> t list -> t val to_hex : t -> [`Hex of string] val of_hex : [`Hex of string] -> t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
t-gcd_euclidean.c
#include "fq_poly.h" #ifdef T #undef T #endif #define T fq #define CAP_T FQ #include "fq_poly_templates/test/t-gcd_euclidean.c" #undef CAP_T #undef T
/* Copyright (C) 2011 William Hart Copyright (C) 2012 Andres Goens Copyright (C) 2013 Mike Hansen This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
dune
(cram (applies_to src-documentation module-doc) (enabled_if (<> %{architecture} i386)))
measurement.mli
(** A module internal to [Core_bench]. Please look at {!Bench}. Contains the measurements of several runs of one benchmark. *) open! Core type t [@@deriving sexp] val name : t -> string val test_name : t -> string val file_name : t -> string val module_name : t -> string val largest_run : t -> int val sample_count : t -> int val samples : t -> Measurement_sample.t array (** [samples] should have length at least [sample_count]. Extra entries are ignored in calculations. *) val create : name:string -> test_name:string -> file_name:string -> module_name:string -> largest_run:int -> sample_count:int -> samples:Measurement_sample.t array -> t val save : t -> filename:string -> unit val load : filename:string -> t
(** A module internal to [Core_bench]. Please look at {!Bench}. Contains the measurements of several runs of one benchmark. *)
a.mli
(** Text attached to references are written as single words to have a more readable output. References from the first comment (which is the doc of the entire module): {{!B.C}Doc-relative} {{!A.B.C}Doc-absolute} *) (** References from inside the module's signature: {{!B.C}Defined-below} {{!A.B.C}Defined-below-but-absolute} *) module B : sig module C : sig end end module D : sig open B (** {{!C}Through-open} *) end
(** Text attached to references are written as single words to have a more readable output. References from the first comment (which is the doc of the entire module): {{!B.C}Doc-relative} {{!A.B.C}Doc-absolute} *)
b.ml
module C = struct module F() = struct end end
contract_hash.mli
include S.HASH
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2020-2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
lib_parsing_lisp.mli
val find_source_files_of_dir_or_files : Common.path list -> Common.filename list
log_accurate.c
/* * Correctly rounded logarithm * * Author : David Defour * * This file is part of the crlibm library developed by the Arenaire * project at Ecole Normale Superieure de Lyon * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; 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 Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h> #include "log_accurate.h" /* * 1) First reduction: exponent extraction * E * x = 2^ .(1+f) with 0 <= f < 1 * * log(x) = E.log(2) + log(1+f) where: * - log(2) is tabulated * - log(1+f) need to be evaluated * * * 2) Avoiding accuracy problem when E=-1 by testing * * if (1+f >= sqrt(2)) then * 1+f = (1+f)/2; E = E+1; * and, * log(x) = (E+1).log(2) + log((1+f)/2) * * so now: sqrt(2)/2 <= (1+f) < sqrt(2) * * * 3) Second reduction: tabular reduction * -4 * wi = 1 + i. 2^ * 1 * log(1+f) = log(wi) + log ( 1 + --- . (1 + f - wi) ) * wi * * then |(1+f-wi)/wi| <= 2^-5 if we use rounded to nearest. * * 4) Computation: * a) Table lookup of: * - ti = log(wi) * - inv_wi = 1/(wi) * b) Polynomial evaluation of: * - P(R) ~ log(1 + R), where R = (1+f-wi) * inv_wi * * -5 * with |R| < 2^ * * * 5) Reconstruction: * log(x) = E.log(2) + t_i + P(R) * */ void scs_log(scs_ptr res, db_number y, int E){ scs_t R, sc_ln2_times_E, res1, addi; scs_ptr ti, inv_wi; db_number z, wi; int i; #if EVAL_PERF crlibm_second_step_taken++; #endif /* to normalize y.d and round to nearest */ /* + (1-trunc(sqrt(2.)/2 * 2^(4))*2^(-4) )+2.^(-(4+1))*/ z.d = y.d + norm_number.d; i = (z.i[HI] & 0x000fffff); i = i >> 16; /* 0<= i <=11 */ wi.d = ((double)(11+i))*0.0625; /* (1+f-w_i) */ y.d -= wi.d; /* Table reduction */ ti = table_ti_ptr[i]; inv_wi = table_inv_wi_ptr[i]; /* R = (1+f-w_i)/w_i */ scs_set_d(R, y.d); scs_mul(R, R, inv_wi); /* * Polynomial evaluation of log(1 + R) with an error less than 2^(-130) */ scs_mul(res1, constant_poly_ptr[0], R); for(i=1; i<20; i++){ scs_add(addi, constant_poly_ptr[i], res1); scs_mul(res1, addi, R); } if(E==0){ scs_add(res, res1, ti); }else{ /* sc_ln2_times_E = E*log(2) */ scs_set(sc_ln2_times_E, sc_ln2_ptr); if (E >= 0){ scs_mul_ui(sc_ln2_times_E, (unsigned int) E); }else{ scs_mul_ui(sc_ln2_times_E, (unsigned int) -E); sc_ln2_times_E->sign = -1; } scs_add(addi, res1, ti); scs_add(res, addi, sc_ln2_times_E); } }
/* * Correctly rounded logarithm * * Author : David Defour * * This file is part of the crlibm library developed by the Arenaire * project at Ecole Normale Superieure de Lyon * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; 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 Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
node.ml
type history_mode = Archive | Full of int option | Rolling of int option type media_type = Json | Binary | Any let string_of_media_type = function | Any -> "any" | Binary -> "binary" | Json -> "json" type argument = | Network of string | History_mode of history_mode | Expected_pow of int | Singleprocess | Bootstrap_threshold of int | Synchronisation_threshold of int | Connections of int | Private_mode | Peer of string | No_bootstrap_peers | Disable_operations_precheck | Media_type of media_type | Metadata_size_limit of int option | Metrics_addr of string let make_argument = function | Network x -> ["--network"; x] | History_mode Archive -> ["--history-mode"; "archive"] | History_mode (Full None) -> ["--history-mode"; "full"] | History_mode (Full (Some i)) -> ["--history-mode"; "full:" ^ string_of_int i] | History_mode (Rolling None) -> ["--history-mode"; "rolling"] | History_mode (Rolling (Some i)) -> ["--history-mode"; "rolling:" ^ string_of_int i] | Expected_pow x -> ["--expected-pow"; string_of_int x] | Singleprocess -> ["--singleprocess"] | Bootstrap_threshold x -> ["--bootstrap-threshold"; string_of_int x] | Synchronisation_threshold x -> ["--synchronisation-threshold"; string_of_int x] | Connections x -> ["--connections"; string_of_int x] | Private_mode -> ["--private-mode"] | Peer x -> ["--peer"; x] | No_bootstrap_peers -> ["--no-bootstrap-peers"] | Disable_operations_precheck -> ["--disable-mempool-precheck"] | Media_type media_type -> ["--media-type"; string_of_media_type media_type] | Metadata_size_limit None -> ["--metadata-size-limit"; "unlimited"] | Metadata_size_limit (Some i) -> ["--metadata-size-limit"; string_of_int i] | Metrics_addr metrics_addr -> ["--metrics-addr"; metrics_addr] let make_arguments arguments = List.flatten (List.map make_argument arguments) type 'a known = Unknown | Known of 'a module Parameters = struct type persistent_state = { data_dir : string; mutable net_port : int; advertised_net_port : int option; rpc_host : string; rpc_port : int; default_expected_pow : int; mutable arguments : argument list; mutable pending_ready : unit option Lwt.u list; mutable pending_level : (int * int option Lwt.u) list; mutable pending_identity : string option Lwt.u list; runner : Runner.t option; } type session_state = { mutable ready : bool; mutable level : int known; mutable identity : string known; } let base_default_name = "node" let default_colors = Log.Color.[|FG.cyan; FG.magenta; FG.yellow; FG.green|] end open Parameters include Daemon.Make (Parameters) let check_error ?exit_code ?msg node = match node.status with | Not_running -> Test.fail "node %s is not running, it has no stderr" (name node) | Running {process; _} -> Process.check_error ?exit_code ?msg process let wait node = match node.status with | Not_running -> Test.fail "node %s is not running, cannot wait for it to terminate" (name node) | Running {process; _} -> Process.wait process let name node = node.name let net_port node = node.persistent_state.net_port let advertised_net_port node = node.persistent_state.advertised_net_port let rpc_host node = node.persistent_state.rpc_host let rpc_port node = node.persistent_state.rpc_port let data_dir node = node.persistent_state.data_dir let runner node = node.persistent_state.runner let spawn_command node = Process.spawn ?runner:node.persistent_state.runner ~name:node.name ~color:node.color node.path let spawn_identity_generate ?expected_pow node = spawn_command node [ "identity"; "generate"; "--data-dir"; node.persistent_state.data_dir; string_of_int (Option.value expected_pow ~default:node.persistent_state.default_expected_pow); ] let identity_generate ?expected_pow node = spawn_identity_generate ?expected_pow node |> Process.check let show_history_mode = function | Archive -> "archive" | Full None -> "full" | Full (Some i) -> "full_" ^ string_of_int i | Rolling None -> "rolling" | Rolling (Some i) -> "rolling_" ^ string_of_int i let spawn_config_init node arguments = let arguments = node.persistent_state.arguments @ arguments in (* Since arguments will be in the configuration file, we will not need them after this. *) node.persistent_state.arguments <- [] ; let arguments = (* Give a default value of "sandbox" to --network. *) if List.exists (function Network _ -> true | _ -> false) arguments then arguments else Network "sandbox" :: arguments in spawn_command node ("config" :: "init" :: "--data-dir" :: node.persistent_state.data_dir :: make_arguments arguments) let config_init node arguments = spawn_config_init node arguments |> Process.check module Config_file = struct let filename node = sf "%s/config.json" @@ data_dir node let read node = JSON.parse_file (filename node) let write node config = JSON.encode_to_file (filename node) config let update node update = read node |> update |> write node let set_prevalidator ?(operations_request_timeout = 10.) ?(max_refused_operations = 1000) ?(operations_batch_size = 50) ?(disable_operations_precheck = false) old_config = let prevalidator = `O [ ("operations_request_timeout", `Float operations_request_timeout); ( "max_refused_operations", `Float (float_of_int max_refused_operations) ); ("operations_batch_size", `Float (float_of_int operations_batch_size)); ("disable_precheck", `Bool disable_operations_precheck); ] |> JSON.annotate ~origin:"set_prevalidator" in JSON.update "shell" (fun config -> JSON.put ("prevalidator", prevalidator) config) old_config let set_peer_validator ?(new_head_request_timeout = 60.) old_config = let peer_validator = `O [ ( "peer_validator", `O [("new_head_request_timeout", `Float new_head_request_timeout)] ); ] |> JSON.annotate ~origin:"set_peer_validator" in JSON.put ("shell", peer_validator) old_config let sandbox_network_config = `O [ ( "genesis", `O [ ("timestamp", `String "2018-06-30T16:07:32Z"); ( "block", `String "BLockGenesisGenesisGenesisGenesisGenesisf79b5d1CoW2" ); ("protocol", `String Protocol.genesis_hash); ] ); ( "genesis_parameters", `O [ ( "values", `O [("genesis_pubkey", `String Constant.activator.public_key)] ); ] ); ("chain_name", `String "TEZOS"); ("sandboxed_chain_name", `String "SANDBOXED_TEZOS"); ] let set_sandbox_network_with_user_activated_upgrades upgrade_points old_config = let network = sandbox_network_config |> JSON.annotate ~origin:"set_sandbox_network_with_user_activated_upgrades" |> JSON.put ( "user_activated_upgrades", JSON.annotate ~origin:"user_activated_upgrades" @@ `A (List.map (fun (level, protocol) -> `O [ ("level", `Float (float level)); ( "replacement_protocol", `String (Protocol.hash protocol) ); ]) upgrade_points) ) in JSON.put ("network", network) old_config let set_sandbox_network_with_user_activated_overrides overrides old_config = let network = sandbox_network_config |> JSON.annotate ~origin:"set_sandbox_network_with_user_activated_overrides" |> JSON.put ( "user_activated_protocol_overrides", JSON.annotate ~origin:"user_activated_overrides" @@ `A (List.map (fun (replaced_protocol, replacement_protocol) -> `O [ ("replaced_protocol", `String replaced_protocol); ("replacement_protocol", `String replacement_protocol); ]) overrides) ) in JSON.put ("network", network) old_config end let trigger_ready node value = let pending = node.persistent_state.pending_ready in node.persistent_state.pending_ready <- [] ; List.iter (fun pending -> Lwt.wakeup_later pending value) pending let set_ready node = (match node.status with | Not_running -> () | Running status -> status.session_state.ready <- true) ; trigger_ready node (Some ()) let update_level node current_level = (match node.status with | Not_running -> () | Running status -> ( match status.session_state.level with | Unknown -> status.session_state.level <- Known current_level | Known old_level -> status.session_state.level <- Known (max old_level current_level))) ; let pending = node.persistent_state.pending_level in node.persistent_state.pending_level <- [] ; List.iter (fun ((level, resolver) as pending) -> if current_level >= level then Lwt.wakeup_later resolver (Some current_level) else node.persistent_state.pending_level <- pending :: node.persistent_state.pending_level) pending let update_identity node identity = match node.status with | Not_running -> () | Running status -> (match status.session_state.identity with | Unknown -> status.session_state.identity <- Known identity | Known identity' -> if identity' <> identity then Test.fail "node identity changed") ; let pending = node.persistent_state.pending_identity in node.persistent_state.pending_identity <- [] ; List.iter (fun resolver -> Lwt.wakeup_later resolver (Some identity)) pending let handle_event node {name; value} = match name with | "node_is_ready.v0" -> set_ready node | "node_chain_validator.v0" -> ( match JSON.as_list_opt value with | Some [_timestamp; details] -> ( match JSON.( details |-> "event" |-> "processed_block" |-> "level" |> as_int_opt) with | None -> (* There are several kinds of [node_chain_validator.v0] events and maybe this one is not the one with the level: ignore it. *) () | Some level -> update_level node level) | _ -> (* Other kind of node_chain_validator event that we don't care about. *) ()) | "read_identity.v0" -> update_identity node (JSON.as_string value) | _ -> () let check_event ?where node name promise = let* result = promise in match result with | None -> raise (Terminated_before_event {daemon = node.name; event = name; where}) | Some x -> return x let wait_for_ready node = match node.status with | Running {session_state = {ready = true; _}; _} -> unit | Not_running | Running {session_state = {ready = false; _}; _} -> let (promise, resolver) = Lwt.task () in node.persistent_state.pending_ready <- resolver :: node.persistent_state.pending_ready ; check_event node "node_is_ready.v0" promise let wait_for_level node level = match node.status with | Running {session_state = {level = Known current_level; _}; _} when current_level >= level -> return current_level | Not_running | Running _ -> let (promise, resolver) = Lwt.task () in node.persistent_state.pending_level <- (level, resolver) :: node.persistent_state.pending_level ; check_event node "node_chain_validator.v0" ~where:("level >= " ^ string_of_int level) promise let get_level node = match node.status with | Running {session_state = {level = Known level; _}; _} -> level | Not_running | Running _ -> 0 let wait_for_identity node = match node.status with | Running {session_state = {identity = Known identity; _}; _} -> return identity | Not_running | Running _ -> let (promise, resolver) = Lwt.task () in node.persistent_state.pending_identity <- resolver :: node.persistent_state.pending_identity ; check_event node "read_identity.v0" promise let wait_for_request ~request node = let event_name = match request with | `Flush | `Inject -> "request_completed_notice.v0" | `Notify | `Arrived -> "request_completed_debug.v0" in let request_str = match request with | `Flush -> "flush" | `Inject -> "inject" | `Notify -> "notify" | `Arrived -> "arrived" in let filter json = match JSON.(json |-> "view" |-> "request" |> as_string_opt) with | Some s when String.equal s request_str -> Some () | Some _ | None -> None in wait_for node event_name filter let create ?runner ?(path = Constant.tezos_node) ?name ?color ?data_dir ?event_pipe ?net_port ?advertised_net_port ?(rpc_host = "localhost") ?rpc_port arguments = let name = match name with None -> fresh_name () | Some name -> name in let data_dir = match data_dir with None -> Temp.dir ?runner name | Some dir -> dir in let net_port = match net_port with None -> Port.fresh () | Some port -> port in let rpc_port = match rpc_port with None -> Port.fresh () | Some port -> port in let arguments = (* Give a default value of 0 to --expected-pow. *) if List.exists (function Expected_pow _ -> true | _ -> false) arguments then arguments else Expected_pow 0 :: arguments in let default_expected_pow = list_find_map (function Expected_pow x -> Some x | _ -> None) arguments |> Option.value ~default:0 in let node = create ?runner ~path ~name ?color ?event_pipe { data_dir; net_port; advertised_net_port; rpc_host; rpc_port; arguments; default_expected_pow; runner; pending_ready = []; pending_level = []; pending_identity = []; } in on_event node (handle_event node) ; node let add_argument node argument = node.persistent_state.arguments <- argument :: node.persistent_state.arguments let add_peer node peer = let address = Runner.address ?from:node.persistent_state.runner peer.persistent_state.runner ^ ":" in add_argument node (Peer (address ^ string_of_int (net_port peer))) let point_and_id ?from node = let from = match from with None -> None | Some peer -> peer.persistent_state.runner in let address = Runner.address ?from node.persistent_state.runner ^ ":" in let* id = wait_for_identity node in Lwt.return (address ^ string_of_int (net_port node) ^ "#" ^ id) let add_peer_with_id node peer = let* peer = point_and_id ~from:node peer in add_argument node (Peer peer) ; Lwt.return_unit let get_peers node = List.filter_map (fun arg -> match arg with Peer s -> Some s | _ -> None) node.persistent_state.arguments (** [runlike_command_arguments node command arguments] evaluates in a list of strings containing all command line arguments needed to spawn a [command] like [run] or [replay] for the given [node] and extra [arguments]. *) let runlike_command_arguments node command arguments = let (net_addr, rpc_addr) = match node.persistent_state.runner with | None -> ("127.0.0.1:", node.persistent_state.rpc_host ^ ":") | Some _ -> (* FIXME spawn an ssh tunnel in case of remote host *) ("0.0.0.0:", "0.0.0.0:") in let arguments = node.persistent_state.arguments @ arguments in let command_args = make_arguments arguments in let command_args = match node.persistent_state.advertised_net_port with | None -> command_args | Some port -> "--advertised-net-port" :: string_of_int port :: command_args in command :: "--data-dir" :: node.persistent_state.data_dir :: "--net-addr" :: (net_addr ^ string_of_int node.persistent_state.net_port) :: "--rpc-addr" :: (rpc_addr ^ string_of_int node.persistent_state.rpc_port) :: command_args let do_runlike_command ?(on_terminate = fun _ -> ()) ?event_level ?event_sections_levels node arguments = (match node.status with | Not_running -> () | Running _ -> Test.fail "node %s is already running" node.name) ; let on_terminate status = on_terminate status ; (* Cancel all [Ready] event listeners. *) trigger_ready node None ; (* Cancel all [Level_at_least] event listeners. *) let pending = node.persistent_state.pending_level in node.persistent_state.pending_level <- [] ; List.iter (fun (_, pending) -> Lwt.wakeup_later pending None) pending ; (* Cancel all [Read_identity] event listeners. *) let pending = node.persistent_state.pending_identity in node.persistent_state.pending_identity <- [] ; List.iter (fun pending -> Lwt.wakeup_later pending None) pending ; unit in run ?runner:node.persistent_state.runner ?event_level ?event_sections_levels node {ready = false; level = Unknown; identity = Unknown} arguments ~on_terminate let run ?on_terminate ?event_level ?event_sections_levels node arguments = let arguments = runlike_command_arguments node "run" arguments in do_runlike_command ?on_terminate ?event_level ?event_sections_levels node arguments let replay ?on_terminate ?event_level ?event_sections_levels ?(blocks = ["head"]) node arguments = let arguments = runlike_command_arguments node "replay" arguments @ blocks in do_runlike_command ?on_terminate ?event_level ?event_sections_levels node arguments let init ?runner ?path ?name ?color ?data_dir ?event_pipe ?net_port ?advertised_net_port ?rpc_host ?rpc_port ?event_level ?event_sections_levels arguments = let node = create ?runner ?path ?name ?color ?data_dir ?event_pipe ?net_port ?advertised_net_port ?rpc_host ?rpc_port arguments in let* () = identity_generate node in let* () = config_init node [] in let* () = run ?event_level ?event_sections_levels node [] in let* () = wait_for_ready node in return node let send_raw_data node ~data = (* Extracted from Lwt_utils_unix. *) let write_string ?(pos = 0) ?len descr buf = let len = match len with None -> String.length buf - pos | Some l -> l in let rec inner pos len = if len = 0 then Lwt.return_unit else Lwt.bind (Lwt_unix.write_string descr buf pos len) (function | 0 -> Lwt.fail End_of_file (* other endpoint cleanly closed its connection *) | nb_written -> inner (pos + nb_written) (len - nb_written)) in inner pos len in Log.debug "Write raw data to node %s" node.name ; let socket = Lwt_unix.socket PF_INET SOCK_STREAM 0 in Lwt_unix.set_close_on_exec socket ; let uaddr = Lwt_unix.ADDR_INET (Unix.inet_addr_loopback, net_port node) in let* () = Lwt_unix.connect socket uaddr in write_string socket data
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
expr.ml
type name = string type typexp = | TVar of name | TFun of typexp * typexp type param = | PVar of name * typexp type exp = | ELam of param * exp | EApp of exp * exp | EVar of name type command = | Decl of name * typexp * exp | Eval of exp * typexp let rec lam params exp = match params with | [] -> exp | x :: xs -> ELam (x, lam xs exp) let rec app f = function | [] -> f | x :: xs -> app (EApp (f, x)) xs let rec t_to_s (t : typexp): name :> string = match t with | TVar n -> n | TFun (t1, t2) -> Printf.sprintf "(%s→%s)" (t_to_s t1) (t_to_s t2) let p_to_s (p : param): name :> string = match p with | PVar (n, t) -> Printf.sprintf "(%s: %s)" n (t_to_s t) let rec e_to_s (exp: exp): name :> string = match exp with | ELam (p, e) -> Printf.sprintf "(λ%s,%s)" (p_to_s p) (e_to_s e) | EApp (e1, e2) -> Printf.sprintf "(%s %s)" (e_to_s e1) (e_to_s e2) | EVar v -> v
is_approx_zero.c
#include "d_vec.h" int _d_vec_is_approx_zero(const double *vec, slong len, double eps) { slong i; for (i = 0; i < len; i++) if (fabs(vec[i]) > eps) return 0; return 1; }
/* Copyright (C) 2010 Sebastian Pancratz Copyright (C) 2014 Abhinav Baid This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
mul.c
#include "fq_nmod_poly.h" void _fq_nmod_poly_mul(fq_nmod_struct * rop, const fq_nmod_struct * op1, slong len1, const fq_nmod_struct * op2, slong len2, const fq_nmod_ctx_t ctx) { if (len1 <= 1 || len2 <= 1 || (fq_nmod_ctx_degree(ctx) == 2 && FLINT_MAX(len1, len2) <= 2) || FLINT_BIT_COUNT(fmpz_get_ui(fq_nmod_ctx_prime(ctx)))* fq_nmod_ctx_degree(ctx)* FLINT_MAX(len1, len2) <= 8) _fq_nmod_poly_mul_classical(rop, op1, len1, op2, len2, ctx); else _fq_nmod_poly_mul_univariate(rop, op1, len1, op2, len2, ctx); } void fq_nmod_poly_mul(fq_nmod_poly_t rop, const fq_nmod_poly_t op1, const fq_nmod_poly_t op2, const fq_nmod_ctx_t ctx) { slong len1 = fq_nmod_poly_length(op1, ctx); slong len2 = fq_nmod_poly_length(op2, ctx); if (len1 <= 1 || len2 <= 1 || (fq_nmod_ctx_degree(ctx) == 2 && FLINT_MAX(len1, len2) <= 2) || FLINT_BIT_COUNT(fmpz_get_ui(fq_nmod_ctx_prime(ctx)))* fq_nmod_ctx_degree(ctx)* FLINT_MAX(len1, len2) <= 8) fq_nmod_poly_mul_classical(rop, op1, op2, ctx); else fq_nmod_poly_mul_univariate(rop, op1, op2, ctx); }
/* Copyright (C) 2012 Sebastian Pancratz Copyright (C) 2013 Mike Hansen This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */
shared.ml
open Core (* the maximum read/write I managed to get off of a socket or disk was 65k *) let buffer_size = 10 * 65 * 1024 type ('a, 'b) reader = ?strip:bool -> ?skip_lines:int -> ?on_parse_error: [ `Raise | `Handle of string Queue.t -> exn -> [ `Continue | `Finish ] ] -> header:'a -> 'b let strip_buffer buf = let len = Buffer.length buf in let rec first_non_space n = if n >= len then None else if Char.is_whitespace (Buffer.nth buf n) then first_non_space (n + 1) else Some n in let rec last_non_space n = if n < 0 then None else if Char.is_whitespace (Buffer.nth buf n) then last_non_space (n - 1) else Some n in match first_non_space 0 with | None -> "" | Some s -> (match last_non_space (len - 1) with | None -> assert false | Some e -> Buffer.To_string.sub buf ~pos:s ~len:(e - s + 1)) ;; let make_emit_field ~strip current_row field = stage (fun () -> Queue.enqueue current_row (if strip then strip_buffer field else Buffer.contents field); Buffer.clear field) ;; let set_headers header_index headers = List.iteri headers ~f:(fun i h -> Option.iter h ~f:(fun h -> match Hashtbl.find header_index h with | None -> Hashtbl.set header_index ~key:h ~data:i | Some other_i -> failwithf "header %s duplicated at position %i and %i" h other_i i ())) ;; let make_emit_row current_row row_queue header ~lineno = let module Table = String.Table in let header_index = match (header : Header.t) with | `No | `Yes | `Require _ | `Transform _ | `Filter_map _ -> Table.create () ~size:1 | `Replace headers | `Add headers -> Table.of_alist_exn (List.mapi headers ~f:(fun i s -> s, i)) in let header_processed = ref (match header with | `No | `Add _ -> true | `Require _ | `Replace _ | `Transform _ | `Filter_map _ | `Yes -> false) in ( `on_eof (fun () -> if not !header_processed then failwith "Header line was not found") , fun () -> if not !header_processed then ( header_processed := true; match header with | `No | `Add _ -> assert false | `Require at_least -> let headers = Queue.to_list current_row in List.iter at_least ~f:(fun must_exist -> match List.findi headers ~f:(fun _ h -> String.equal h must_exist) with | None -> failwithf "The required header '%s' was not found in '%s' (lineno=%d)" must_exist (String.concat ~sep:"," headers) !lineno () | Some (i, _) -> Hashtbl.set header_index ~key:must_exist ~data:i) | `Replace _new_headers -> () (* already set above *) | `Transform f -> Queue.to_list current_row |> f |> List.map ~f:Option.some |> set_headers header_index | `Filter_map f -> Queue.to_list current_row |> f |> set_headers header_index | `Yes -> Queue.to_list current_row |> List.map ~f:Option.some |> set_headers header_index) else Queue.enqueue row_queue (Row.create header_index (Queue.to_array current_row)); lineno := !lineno + 1; Queue.clear current_row ) ;;
client_baking_endorsement.mli
open Protocol open Alpha_context (** [forge_endorsement cctxt blk ~src_sk src_pk] emits an endorsement operation for the block [blk] *) val forge_endorsement : #Protocol_client_context.full -> ?async:bool -> chain:Chain_services.chain -> block:Block_services.block -> src_sk:Client_keys.sk_uri -> public_key -> Operation_hash.t tzresult Lwt.t val create : #Protocol_client_context.full -> ?max_past:int64 (* number of seconds *) -> delay:int -> public_key_hash list -> Client_baking_blocks.block_info tzresult Lwt_stream.t -> unit tzresult Lwt.t
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2018 Nomadic Labs, <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
dyn.ml
module Array = Stdlib.ArrayLabels module List = Stdlib.ListLabels module String = Stdlib.StringLabels module Bytes = Stdlib.Bytes type t = | Opaque | Unit | Int of int | Int32 of int32 | Int64 of int64 | Nativeint of nativeint | Bool of bool | String of string | Bytes of bytes | Char of char | Float of float | Option of t option | List of t list | Array of t array | Tuple of t list | Record of (string * t) list | Variant of string * t list | Map of (t * t) list | Set of t list let unsnoc l = match List.rev l with | last :: before_last -> Some (List.rev before_last, last) | [] -> None let string_in_ocaml_syntax str = let is_space = function | ' ' -> (* don't need to handle tabs because those are already escaped *) true | _ -> false in let escape_protect_first_space s = let first_char = if String.length s > 0 && is_space s.[0] then "\\" else " " in first_char ^ String.escaped s in (* CR-someday aalekseyev: should use the method from [Dune_lang.prepare_formatter] so that the formatter can fit multiple lines on one line. *) match String.split_on_char ~sep:'\n' str with | [] -> assert false | first :: rest -> ( match unsnoc rest with | None -> Pp.verbatim (Printf.sprintf "%S" first) | Some (middle, last) -> Pp.vbox (Pp.concat ~sep:Pp.newline (List.map ~f:Pp.verbatim (("\"" ^ String.escaped first ^ "\\n\\") :: List.map middle ~f:(fun s -> escape_protect_first_space s ^ "\\n\\") @ [ escape_protect_first_space last ^ "\"" ])))) let pp_sequence start stop x ~f = let open Pp.O in match x with | [] -> Pp.verbatim start ++ Pp.verbatim stop | _ -> let sep = ";" ^ String.make (String.length start) ' ' in Pp.hvbox (Pp.concat_mapi ~sep:Pp.cut x ~f:(fun i x -> Pp.box ((if i = 0 then Pp.verbatim (start ^ " ") else Pp.verbatim sep) ++ f x)) ++ Pp.space ++ Pp.verbatim stop) let rec pp = let open Pp.O in function | Opaque -> Pp.verbatim "<opaque>" | Unit -> Pp.verbatim "()" | Int i -> Pp.verbatim (string_of_int i) | Int32 i -> Pp.verbatim (Int32.to_string i) | Int64 i -> Pp.verbatim (Int64.to_string i) | Nativeint i -> Pp.verbatim (Nativeint.to_string i) | Bool b -> Pp.verbatim (string_of_bool b) | String s -> string_in_ocaml_syntax s | Bytes b -> string_in_ocaml_syntax (Bytes.to_string b) | Char c -> Pp.char c | Float f -> Pp.verbatim (string_of_float f) | Option None -> pp (Variant ("None", [])) | Option (Some x) -> pp (Variant ("Some", [ x ])) | List xs -> pp_sequence "[" "]" xs ~f:pp | Array xs -> pp_sequence "[|" "|]" (Array.to_list xs) ~f:pp | Set xs -> Pp.box ~indent:2 (Pp.verbatim "set" ++ Pp.space ++ pp_sequence "{" "}" xs ~f:pp) | Map xs -> Pp.box ~indent:2 (Pp.verbatim "map" ++ Pp.space ++ pp_sequence "{" "}" xs ~f:(fun (k, v) -> Pp.box ~indent:2 (pp k ++ Pp.space ++ Pp.char ':' ++ Pp.space ++ pp v))) | Tuple x -> Pp.box (Pp.char '(' ++ Pp.concat_map ~sep:(Pp.seq (Pp.char ',') Pp.space) x ~f:pp ++ Pp.char ')') | Record fields -> pp_sequence "{" "}" fields ~f:(fun (f, v) -> Pp.box ~indent:2 (Pp.verbatim f ++ Pp.space ++ Pp.char '=' ++ Pp.space ++ pp v)) | Variant (v, []) -> Pp.verbatim v | Variant (v, xs) -> Pp.hvbox ~indent:2 (Pp.concat [ Pp.verbatim v; Pp.space; Pp.concat_map ~sep:(Pp.char ',') xs ~f:pp ]) let to_string t = Format.asprintf "%a" Pp.to_fmt (pp t) type 'a builder = 'a -> t let unit () = Unit let char x = Char x let string x = String x let int x = Int x let int32 x = Int32 x let int64 x = Int64 x let nativeint x = Nativeint x let float x = Float x let bool x = Bool x let pair f g (x, y) = Tuple [ f x; g y ] let triple f g h (x, y, z) = Tuple [ f x; g y; h z ] let list f l = List (List.map ~f l) let array f a = Array (Array.map ~f a) let option f x = Option (match x with | None -> None | Some x -> Some (f x)) let record r = Record r let opaque _ = Opaque let variant s args = Variant (s, args) let hash = Stdlib.Hashtbl.hash let compare x y = Ordering.of_int (compare x y) let equal x y = x = y
bar.ml
let bar () = print_endline "bar from vlib"
nonce_storage.mli
type error += | Too_late_revelation | Too_early_revelation | Previously_revealed_nonce | Unexpected_nonce type t = Seed_repr.nonce type nonce = t val encoding: nonce Data_encoding.t type unrevealed = Storage.Seed.unrevealed_nonce = { nonce_hash: Nonce_hash.t ; delegate: Signature.Public_key_hash.t ; rewards: Tez_repr.t ; fees: Tez_repr.t ; } type status = | Unrevealed of unrevealed | Revealed of Seed_repr.nonce val get: Raw_context.t -> Level_repr.t -> status tzresult Lwt.t val record_hash: Raw_context.t -> unrevealed -> Raw_context.t tzresult Lwt.t val reveal: Raw_context.t -> Level_repr.t -> nonce -> Raw_context.t tzresult Lwt.t val of_bytes: MBytes.t -> nonce tzresult val hash: nonce -> Nonce_hash.t val check_hash: nonce -> Nonce_hash.t -> bool
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
dune
(test (name test_zed) (libraries zed))
svg_sigs.mli
(** SVG signatures for the functorial interface. *) (** Signature of typesafe constructors for SVG documents. *) module type T = sig (** SVG elements. Element constructors are in section {!elements}. Most elements constructors are either {{!nullary}nullary}, {{!unary}unary} or {{!star}star}, depending on the number of children they accept. Children are usually given as a list of elements. {{!txt}txt} is used for text. The type variable ['a] is used to track the element's type. This allows the OCaml typechecker to check SVG validity. Note that the concrete implementation of this type can vary. See {!Xml} for details. *) type +'a elt (** A complete SVG document. *) type doc = [ `Svg ] elt (** SVG attributes Attribute constructors are in section {!attributes} and their name starts with [a_]. Attributes are given to elements with the [~a] optional argument. Similarly to {{!elt}elt}, attributes use the OCaml type system to enforce Html validity. In some cases, attributes have to be disambiguated. The [max] attribute has two version, {!a_fill} and {!a_animation_fill}, depending on the element. Such disambiguated attribute will contain the name of the associated element. *) type +'a attrib (** Underlying XML data-structure The type variables in {!elt} and {!attrib} are know as {i phantom types}. The implementation, defined here, is actually monomorphic. In particular, tyxml doesn't impose any overhead over the underlying representation. The {!tot} and {!toelt} functions allows to convert between the typed and the untyped representation without any cost. Note that some implementation may not be iterable or printable, such as the Dom representation exposed by js_of_ocaml. *) module Xml : Xml_sigs.T (** [wrap] is a container for elements and values. In most cases, ['a wrap = 'a]. For [R] modules (in eliom or js_of_ocaml), It will be {!React.S.t}. *) type 'a wrap = 'a Xml.W.t (** [list_wrap] is a containre for list of elements. In most cases, ['a list_wrap = 'a list]. For [R] modules (in eliom or js_of_ocaml), It will be {!ReactiveData.RList.t}. *) type 'a list_wrap = 'a Xml.W.tlist (** A nullary element is an element that doesn't have any children. *) type ('a, 'b) nullary = ?a: (('a attrib) list) -> unit -> 'b elt (** A unary element is an element that have exactly one children. *) type ('a, 'b, 'c) unary = ?a: (('a attrib) list) -> 'b elt wrap -> 'c elt (** A star element is an element that has any number of children, including zero. *) type ('a, 'b, 'c) star = ?a: (('a attrib) list) -> ('b elt) list_wrap -> 'c elt (** Various information about SVG, such as the doctype, ... *) module Info : Xml_sigs.Info (** {3 Uri} *) type uri = Xml.uri val string_of_uri : (uri, string) Xml.W.ft val uri_of_string : (string, uri) Xml.W.ft open Svg_types (** {2:attributes Attributes } *) val a_version : string wrap -> [> | `Version ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_baseProfile : string wrap -> [> | `BaseProfile ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_x : coord wrap -> [> | `X ] attrib val a_y : coord wrap -> [> | `Y ] attrib val a_width : Unit.length wrap -> [> | `Width ] attrib val a_height : Unit.length wrap -> [> | `Height ] attrib val a_preserveAspectRatio : string wrap -> [> | `PreserveAspectRatio ] attrib val a_contentScriptType : string wrap -> [> | `ContentScriptType ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_contentStyleType : string wrap -> [> | `ContentStyleType ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_zoomAndPan : [< | `Disable | `Magnify ] wrap -> [> | `ZoomAndSpan ] attrib val a_href : iri wrap -> [> | `Xlink_href ] attrib val a_xlink_href : iri wrap -> [> | `Xlink_href ] attrib [@@ocaml.deprecated "Use a_href"] (** @deprecated Use a_href *) val a_requiredFeatures : spacestrings wrap -> [> | `RequiredFeatures ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_requiredExtensions : spacestrings wrap -> [> | `RequiredExtension ] attrib val a_systemLanguage : commastrings wrap -> [> | `SystemLanguage ] attrib val a_externalRessourcesRequired : bool wrap -> [> | `ExternalRessourcesRequired ] attrib val a_id : string wrap -> [> | `Id ] attrib val a_user_data : string -> string wrap -> [> | `User_data] attrib val a_xml_base : iri wrap -> [> | `Xml_Base ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_xml_lang : iri wrap -> [> | `Xml_Lang ] attrib val a_xml_space : [< `Default | `Preserve ] wrap -> [> | `Xml_Space ] attrib [@@ocaml.deprecated "Use CSS white-space"] (** @deprecated Use CSS white-space *) val a_type : string wrap -> [> | `Type ] attrib val a_media : commastrings wrap -> [> | `Media ] attrib val a_xlink_title : string wrap -> [> | `Title ] attrib [@@ocaml.deprecated "Use a child title element"] (** @deprecated Use a child title element *) val a_class : spacestrings wrap -> [> | `Class ] attrib val a_style : string wrap -> [> | `Style ] attrib val a_transform : transforms wrap -> [> | `Transform ] attrib val a_viewBox : fourfloats wrap -> [> | `ViewBox ] attrib val a_d : string wrap -> [> | `D ] attrib val a_pathLength : float wrap -> [> | `PathLength ] attrib (* XXX: better language support *) val a_rx : Unit.length wrap -> [> | `Rx ] attrib val a_ry : Unit.length wrap -> [> | `Ry ] attrib val a_cx : Unit.length wrap -> [> | `Cx ] attrib val a_cy : Unit.length wrap -> [> | `Cy ] attrib val a_r : Unit.length wrap -> [> | `R ] attrib val a_x1 : coord wrap -> [> | `X1 ] attrib val a_y1 : coord wrap -> [> | `Y1 ] attrib val a_x2 : coord wrap -> [> | `X2 ] attrib val a_y2 : coord wrap -> [> | `Y2 ] attrib val a_points : coords wrap -> [> | `Points ] attrib val a_x_list : lengths wrap -> [> | `X_list ] attrib [@@reflect.attribute "x" ["text"; "tspan"; "tref"; "altGlyph"]] val a_y_list : lengths wrap -> [> | `Y_list ] attrib [@@reflect.attribute "y" ["text"; "tspan"; "tref"; "altGlyph"]] val a_dx : number wrap -> [> | `Dx ] attrib val a_dy : number wrap -> [> | `Dy ] attrib val a_dx_list : lengths wrap -> [> | `Dx_list ] attrib [@@reflect.attribute "dx" ["text"; "tspan"; "tref"; "altGlyph"]] val a_dy_list : lengths wrap -> [> | `Dy_list ] attrib [@@reflect.attribute "dy" ["text"; "tspan"; "tref"; "altGlyph"]] val a_lengthAdjust : [< `Spacing | `SpacingAndGlyphs ] wrap -> [> | `LengthAdjust ] attrib val a_textLength : Unit.length wrap -> [> | `TextLength ] attrib val a_text_anchor : [< `Start | `Middle | `End | `Inherit ] wrap -> [> | `Text_Anchor ] attrib val a_text_decoration : [< `None | `Underline | `Overline | `Line_through | `Blink | `Inherit ] wrap -> [> | `Text_Decoration ] attrib val a_text_rendering : [< `Auto | `OptimizeSpeed | `OptimizeLegibility | `GeometricPrecision | `Inherit ] wrap -> [> | `Text_Rendering ] attrib val a_rotate : numbers wrap -> [> | `Rotate ] attrib val a_startOffset : Unit.length wrap -> [> | `StartOffset ] attrib val a_method : [< `Align | `Stretch ] wrap -> [> | `Method ] attrib val a_spacing : [< `Auto | `Exact ] wrap -> [> | `Spacing ] attrib val a_glyphRef : string wrap -> [> | `GlyphRef ] attrib val a_format : string wrap -> [> | `Format ] attrib val a_markerUnits : [< `StrokeWidth | `UserSpaceOnUse ] wrap -> [> | `MarkerUnits ] attrib val a_refX : coord wrap -> [> | `RefX ] attrib val a_refY : coord wrap -> [> | `RefY ] attrib val a_markerWidth : Unit.length wrap -> [> | `MarkerWidth ] attrib val a_markerHeight : Unit.length wrap -> [> | `MarkerHeight ] attrib val a_orient : Unit.angle option wrap -> [> | `Orient ] attrib val a_local : string wrap -> [> | `Local ] attrib val a_rendering_intent : [< | `Auto | `Perceptual | `Relative_colorimetric | `Saturation | `Absolute_colorimetric ] wrap -> [> | `Rendering_Indent ] attrib val a_gradientUnits : [< `UserSpaceOnUse | `ObjectBoundingBox ] wrap -> [ | `GradientUnits ] attrib val a_gradientTransform : transforms wrap -> [> | `Gradient_Transform ] attrib val a_spreadMethod : [< `Pad | `Reflect | `Repeat ] wrap -> [> | `SpreadMethod ] attrib val a_fx : coord wrap -> [> | `Fx ] attrib val a_fy : coord wrap -> [> | `Fy ] attrib val a_offset : [< `Number of number | `Percentage of percentage ] wrap -> [> | `Offset ] attrib val a_patternUnits : [< `UserSpaceOnUse | `ObjectBoundingBox ] wrap -> [> | `PatternUnits ] attrib val a_patternContentUnits : [< `UserSpaceOnUse | `ObjectBoundingBox ] wrap -> [> | `PatternContentUnits ] attrib val a_patternTransform : transforms wrap -> [> | `PatternTransform ] attrib val a_clipPathUnits : [< `UserSpaceOnUse | `ObjectBoundingBox ] wrap -> [> | `ClipPathUnits ] attrib val a_maskUnits : [< | `UserSpaceOnUse | `ObjectBoundingBox ] wrap -> [> | `MaskUnits ] attrib val a_maskContentUnits : [< | `UserSpaceOnUse | `ObjectBoundingBox ] wrap -> [> | `MaskContentUnits ] attrib val a_primitiveUnits : [< | `UserSpaceOnUse | `ObjectBoundingBox ] wrap -> [> | `PrimitiveUnits ] attrib val a_filterRes : number_optional_number wrap -> [> | `FilterResUnits ] attrib val a_result : string wrap -> [> | `Result ] attrib val a_in : [< | `SourceGraphic | `SourceAlpha | `BackgroundImage | `BackgroundAlpha | `FillPaint | `StrokePaint | `Ref of string ] wrap -> [> | `In ] attrib val a_in2 : [< | `SourceGraphic | `SourceAlpha | `BackgroundImage | `BackgroundAlpha | `FillPaint | `StrokePaint | `Ref of string ] wrap -> [> | `In2 ] attrib val a_azimuth : float wrap -> [> | `Azimuth ] attrib val a_elevation : float wrap -> [> | `Elevation ] attrib val a_pointsAtX : float wrap -> [> | `PointsAtX ] attrib val a_pointsAtY : float wrap -> [> | `PointsAtY ] attrib val a_pointsAtZ : float wrap -> [> | `PointsAtZ ] attrib val a_specularExponent : float wrap -> [> | `SpecularExponent ] attrib val a_specularConstant : float wrap -> [> | `SpecularConstant ] attrib val a_limitingConeAngle : float wrap -> [> | `LimitingConeAngle ] attrib val a_mode : [< | `Normal | `Multiply | `Screen | `Darken | `Lighten ] wrap -> [> | `Mode ] attrib val a_feColorMatrix_type : [< | `Matrix | `Saturate | `HueRotate | `LuminanceToAlpha ] wrap -> [> | `Typefecolor ] attrib [@@reflect.attribute "type" ["feColorMatrix"]] val a_values : numbers wrap -> [> | `Values ] attrib val a_transfer_type : [< | `Identity | `Table | `Discrete | `Linear | `Gamma ] wrap -> [> | `Type_transfert ] attrib [@@reflect.attribute "type" ["feFuncR"; "feFuncG"; "feFuncB"; "feFuncA"]] val a_tableValues : numbers wrap -> [> | `TableValues ] attrib val a_intercept : number wrap -> [> | `Intercept ] attrib val a_amplitude : number wrap -> [> | `Amplitude ] attrib val a_exponent : number wrap -> [> | `Exponent ] attrib val a_transfer_offset : number wrap -> [> | `Offset_transfer ] attrib [@@reflect.attribute "offset" ["feFuncR"; "feFuncG"; "feFuncB"; "feFuncA"]] val a_feComposite_operator : [< | `Over | `In | `Out | `Atop | `Xor | `Arithmetic ] wrap -> [> | `OperatorComposite ] attrib [@@reflect.attribute "operator" ["feComposite"]] val a_k1 : number wrap -> [> | `K1 ] attrib val a_k2 : number wrap -> [> | `K2 ] attrib val a_k3 : number wrap -> [> | `K3 ] attrib val a_k4 : number wrap -> [> | `K4 ] attrib val a_order : number_optional_number wrap -> [> | `Order ] attrib val a_kernelMatrix : numbers wrap -> [> | `KernelMatrix ] attrib val a_divisor : number wrap -> [> | `Divisor ] attrib val a_bias : number wrap -> [> | `Bias ] attrib val a_kernelUnitLength : number_optional_number wrap -> [> | `KernelUnitLength ] attrib val a_targetX : int wrap -> [> | `TargetX ] attrib val a_targetY : int wrap -> [> | `TargetY ] attrib val a_edgeMode : [< | `Duplicate | `Wrap | `None ] wrap -> [> | `TargetY ] attrib val a_preserveAlpha : bool wrap -> [> | `TargetY ] attrib val a_surfaceScale : number wrap -> [> | `SurfaceScale ] attrib val a_diffuseConstant : number wrap -> [> | `DiffuseConstant ] attrib val a_scale : number wrap -> [> | `Scale ] attrib val a_xChannelSelector : [< | `R | `G | `B | `A ] wrap -> [> | `XChannelSelector ] attrib val a_yChannelSelector : [< | `R | `G | `B | `A ] wrap -> [> | `YChannelSelector ] attrib val a_stdDeviation : number_optional_number wrap -> [> | `StdDeviation ] attrib val a_feMorphology_operator : [< | `Erode | `Dilate ] wrap -> [> | `OperatorMorphology ] attrib [@@reflect.attribute "operator" ["feMorphology"]] val a_radius : number_optional_number wrap -> [> | `Radius ] attrib val a_baseFrenquency : number_optional_number wrap -> [> | `BaseFrequency ] attrib val a_numOctaves : int wrap -> [> | `NumOctaves ] attrib val a_seed : number wrap -> [> | `Seed ] attrib val a_stitchTiles : [< | `Stitch | `NoStitch ] wrap -> [> | `StitchTiles ] attrib val a_feTurbulence_type : [< | `FractalNoise | `Turbulence ] wrap -> [> | `TypeStitch ] attrib [@@reflect.attribute "type" ["feTurbulence"]] val a_xlink_show : [< | `New | `Replace ] wrap -> [> | `Xlink_show ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_xlink_actuate : [< | `OnRequest | `OnLoad | `Other | `None ] wrap -> [> | `Xlink_actuate ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_target : string wrap -> [> | `Xlink_target ] attrib val a_viewTarget : string wrap -> [> | `ViewTarget ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_attributeName : string wrap -> [> | `AttributeName ] attrib val a_attributeType : [< | `CSS | `XML | `Auto ] wrap -> [> | `AttributeType ] attrib val a_begin : string wrap -> [> | `Begin ] attrib val a_dur : string wrap -> [> | `Dur ] attrib val a_min : string wrap -> [> | `Min ] attrib val a_max : string wrap -> [> | `Max ] attrib val a_restart : [< | `Always | `WhenNotActive | `Never ] wrap -> [> | `Restart ] attrib val a_repeatCount : string wrap -> [> | `RepeatCount ] attrib val a_repeatDur : string wrap -> [> | `RepeatDur ] attrib val a_fill : paint wrap -> [> | `Fill ] attrib val a_animation_fill : [< | `Freeze | `Remove ] wrap -> [> | `Fill_Animation ] attrib [@@reflect.attribute "fill" ["animation"]] val a_calcMode : [< | `Discrete | `Linear | `Paced | `Spline ] wrap -> [> | `CalcMode ] attrib val a_animation_values : strings wrap -> [> | `Valuesanim ] attrib [@@reflect.attribute "values" ["animation"]] val a_keyTimes : strings wrap -> [> | `KeyTimes ] attrib val a_keySplines : strings wrap -> [> | `KeySplines ] attrib val a_from : string wrap -> [> | `From ] attrib val a_to : string wrap -> [> | `To ] attrib val a_by : string wrap -> [> | `By ] attrib val a_additive : [< | `Replace | `Sum ] wrap -> [> | `Additive ] attrib val a_accumulate : [< | `None | `Sum ] wrap -> [> | `Accumulate ] attrib val a_keyPoints : numbers_semicolon wrap -> [> | `KeyPoints ] attrib val a_path : string wrap -> [> | `Path ] attrib val a_animateTransform_type : [ | `Translate | `Scale | `Rotate | `SkewX | `SkewY ] wrap -> [ | `Typeanimatetransform ] attrib [@@reflect.attribute "type" ["animateTransform"]] val a_horiz_origin_x : number wrap -> [> | `HorizOriginX ] attrib val a_horiz_origin_y : number wrap -> [> | `HorizOriginY ] attrib val a_horiz_adv_x : number wrap -> [> | `HorizAdvX ] attrib val a_vert_origin_x : number wrap -> [> | `VertOriginX ] attrib val a_vert_origin_y : number wrap -> [> | `VertOriginY ] attrib val a_vert_adv_y : number wrap -> [> | `VertAdvY ] attrib val a_unicode : string wrap -> [> | `Unicode ] attrib val a_glyph_name : string wrap -> [> | `glyphname ] attrib val a_orientation : [< | `H | `V ] wrap -> [> | `Orientation ] attrib val a_arabic_form : [< | `Initial | `Medial | `Terminal | `Isolated ] wrap -> [> | `Arabicform ] attrib val a_lang : string wrap -> [> | `Lang ] attrib val a_u1 : string wrap -> [> | `U1 ] attrib val a_u2 : string wrap -> [> | `U2 ] attrib val a_g1 : string wrap -> [> | `G1 ] attrib val a_g2 : string wrap -> [> | `G2 ] attrib val a_k : string wrap -> [> | `K ] attrib val a_font_family : string wrap -> [> | `Font_Family ] attrib val a_font_style : string wrap -> [> | `Font_Style ] attrib val a_font_variant : string wrap -> [> | `Font_Variant ] attrib val a_font_weight : string wrap -> [> | `Font_Weight ] attrib val a_font_stretch : string wrap -> [> | `Font_Stretch ] attrib val a_font_size : string wrap -> [> | `Font_Size ] attrib val a_unicode_range : string wrap -> [> | `UnicodeRange ] attrib val a_units_per_em : string wrap -> [> | `UnitsPerEm ] attrib val a_stemv : number wrap -> [> | `Stemv ] attrib val a_stemh : number wrap -> [> | `Stemh ] attrib val a_slope : number wrap -> [> | `Slope ] attrib val a_cap_height : number wrap -> [> | `CapHeight ] attrib val a_x_height : number wrap -> [> | `XHeight ] attrib val a_accent_height : number wrap -> [> | `AccentHeight ] attrib val a_ascent : number wrap -> [> | `Ascent ] attrib val a_widths : string wrap -> [> | `Widths ] attrib val a_bbox : string wrap -> [> | `Bbox ] attrib val a_ideographic : number wrap -> [> | `Ideographic ] attrib val a_alphabetic : number wrap -> [> | `Alphabetic ] attrib val a_mathematical : number wrap -> [> | `Mathematical ] attrib val a_hanging : number wrap -> [> | `Hanging ] attrib val a_videographic : number wrap -> [> | `VIdeographic ] attrib val a_v_alphabetic : number wrap -> [> | `VAlphabetic ] attrib val a_v_mathematical : number wrap -> [> | `VMathematical ] attrib val a_v_hanging : number wrap -> [> | `VHanging ] attrib val a_underline_position : number wrap -> [> | `UnderlinePosition ] attrib val a_underline_thickness : number wrap -> [> | `UnderlineThickness ] attrib val a_strikethrough_position : number wrap -> [> | `StrikethroughPosition ] attrib val a_strikethrough_thickness : number wrap -> [> | `StrikethroughThickness ] attrib val a_overline_position : number wrap -> [> | `OverlinePosition ] attrib val a_overline_thickness : number wrap -> [> | `OverlineThickness ] attrib val a_string : string wrap -> [> | `String ] attrib val a_name : string wrap -> [> | `Name ] attrib val a_alignment_baseline : [< | `Auto | `Baseline | `Before_edge | `Text_before_edge | `Middle | `Central | `After_edge | `Text_after_edge | `Ideographic | `Alphabetic | `Hanging | `Mathematical | `Inherit ] wrap -> [> | `Alignment_Baseline ] attrib val a_dominant_baseline : [< | `Auto | `Use_script | `No_change | `Reset_size | `Ideographic | `Alphabetic | `Hanging | `Mathematical | `Central | `Middle | `Text_after_edge | `Text_before_edge | `Inherit ] wrap -> [> | `Dominant_Baseline ] attrib val a_stop_color : color wrap -> [> | `Stop_Color ] attrib val a_stop_opacity : number wrap -> [> | `Stop_Opacity ] attrib val a_stroke : paint wrap -> [> | `Stroke ] attrib val a_stroke_width : Unit.length wrap -> [> | `Stroke_Width ] attrib val a_stroke_linecap : [< `Butt | `Round | `Square ] wrap -> [> | `Stroke_Linecap ] attrib val a_stroke_linejoin : [< `Miter | `Round | `Bever ] wrap -> [> `Stroke_Linejoin ] attrib val a_stroke_miterlimit : float wrap -> [> `Stroke_Miterlimit ] attrib val a_stroke_dasharray : Unit.length list wrap -> [> `Stroke_Dasharray ] attrib val a_stroke_dashoffset : Unit.length wrap -> [> `Stroke_Dashoffset ] attrib val a_stroke_opacity : float wrap -> [> `Stroke_Opacity ] attrib (** {2 Events} {3 Javascript events} *) val a_onabort : Xml.event_handler -> [> | `OnAbort ] attrib val a_onactivate : Xml.event_handler -> [> | `OnActivate ] attrib val a_onbegin : Xml.event_handler -> [> | `OnBegin ] attrib val a_onend : Xml.event_handler -> [> | `OnEnd ] attrib val a_onerror : Xml.event_handler -> [> | `OnError ] attrib val a_onfocusin : Xml.event_handler -> [> | `OnFocusIn ] attrib val a_onfocusout : Xml.event_handler -> [> | `OnFocusOut ] attrib val a_onload : Xml.event_handler -> [> | `OnLoad ] attrib [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val a_onrepeat : Xml.event_handler -> [> | `OnRepeat ] attrib val a_onresize : Xml.event_handler -> [> | `OnResize ] attrib val a_onscroll : Xml.event_handler -> [> | `OnScroll ] attrib val a_onunload : Xml.event_handler -> [> | `OnUnload ] attrib val a_onzoom : Xml.event_handler -> [> | `OnZoom ] attrib (** {3 Javascript mouse events} *) val a_onclick : Xml.mouse_event_handler -> [> | `OnClick ] attrib val a_onmousedown : Xml.mouse_event_handler -> [> | `OnMouseDown ] attrib val a_onmouseup : Xml.mouse_event_handler -> [> | `OnMouseUp ] attrib val a_onmouseover : Xml.mouse_event_handler -> [> | `OnMouseOver ] attrib val a_onmouseout : Xml.mouse_event_handler -> [> | `OnMouseOut ] attrib val a_onmousemove : Xml.mouse_event_handler -> [> | `OnMouseMove ] attrib (** {3 Javascript touch events} *) val a_ontouchstart : Xml.touch_event_handler -> [> | `OnTouchStart] attrib val a_ontouchend : Xml.touch_event_handler -> [> | `OnTouchEnd] attrib val a_ontouchmove : Xml.touch_event_handler -> [> | `OnTouchMove] attrib val a_ontouchcancel : Xml.touch_event_handler -> [> | `OnTouchCancel] attrib (** {2:elements Elements} *) val txt : string wrap -> [> | txt] elt val svg : ([< | svg_attr], [< | svg_content], [> | svg]) star val g : ([< | g_attr], [< | g_content], [> | g]) star val defs : ([< | defs_attr], [< | defs_content], [> | defs]) star val desc : ([< | desc_attr], [< | desc_content], [> | desc]) unary val title : ([< | title_attr], [< | title_content], [> | title]) unary val symbol : ([< | symbol_attr], [< | symbol_content], [> | symbol]) star val use : ([< | use_attr], [< | use_content], [> | use]) star val image : ([< | image_attr], [< | image_content], [> | image]) star val switch : ([< | switch_attr], [< | switch_content], [> | switch]) star val style : ([< | style_attr], [< | style_content], [> | style]) unary val path : ([< | path_attr], [< | path_content], [> | path]) star val rect : ([< | rect_attr], [< | rect_content], [> | rect]) star val circle : ([< | circle_attr], [< | circle_content], [> | circle]) star val ellipse : ([< | ellipse_attr], [< | ellipse_content], [> | ellipse]) star val line : ([< | line_attr], [< | line_content], [> | line]) star val polyline : ([< | polyline_attr], [< | polyline_content], [> | polyline]) star val polygon : ([< | polygon_attr], [< | polygon_content], [> | polygon]) star val text : ([< | text_attr], [< | text_content], [> | text]) star val tspan : ([< | tspan_attr], [< | tspan_content], [> | tspan]) star val tref : ([< | tref_attr], [< | tref_content], [> | tref]) star [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val textPath : ([< | textpath_attr], [< | textpath_content], [> | textpath]) star val altGlyph : ([< | altglyph_attr], [< | altglyph_content], [> | altglyph]) unary [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) type altglyphdef_content = [ | `Ref of (glyphref elt) list | `Item of (altglyphitem elt) list ] val altGlyphDef : ([< | altglyphdef_attr], [< | altglyphdef_content], [> | altglyphdef]) unary [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val altGlyphItem : ([< | altglyphitem_attr], [< | altglyphitem_content], [> | altglyphitem ]) star [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val glyphRef : ([< | glyphref_attr], [> | glyphref]) nullary [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val marker : ([< | marker_attr], [< | marker_content], [> | marker]) star val color_profile : ([< | colorprofile_attr], [< | colorprofile_content], [> | colorprofile ]) star [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val linearGradient : ([< | lineargradient_attr], [< | lineargradient_content], [> | lineargradient]) star val radialGradient : ([< | radialgradient_attr], [< | radialgradient_content], [> | radialgradient]) star val stop : ([< | stop_attr], [< | stop_content], [> | stop ]) star val pattern : ([< | pattern_attr], [< | pattern_content], [> | pattern]) star val clipPath : ([< | clippath_attr], [< | clippath_content], [> | clippath]) star val filter : ([< | filter_attr], [< | filter_content], [> | filter]) star val feDistantLight : ([< | fedistantlight_attr], [< | fedistantlight_content], [> | fedistantlight]) star val fePointLight : ([< | fepointlight_attr], [< | fepointlight_content], [> | fepointlight ]) star val feSpotLight : ([< | fespotlight_attr], [< | fespotlight_content], [> | fespotlight]) star val feBlend : ([< | feblend_attr], [< | feblend_content], [> | feblend]) star val feColorMatrix : ([< | fecolormatrix_attr], [< | fecolormatrix_content], [> | fecolormatrix]) star val feComponentTransfer : ([< | fecomponenttransfer_attr], [< | fecomponenttransfer_content], [> | fecomponenttransfer]) star val feFuncA : ([< | fefunca_attr], [< | fefunca_content], [> | fefunca]) star val feFuncG : ([< | fefuncg_attr], [< | fefuncg_content], [> | fefuncg]) star val feFuncB : ([< | fefuncb_attr], [< | fefuncb_content], [> | fefuncb]) star val feFuncR : ([< | fefuncr_attr], [< | fefuncr_content], [> | fefuncr]) star val feComposite : ([< | fecomposite_attr], [< | fecomposite_content], [> | fecomposite]) star val feConvolveMatrix : ([< | feconvolvematrix_attr], [< | feconvolvematrix_content], [> | feconvolvematrix]) star val feDiffuseLighting : ([< | fediffuselighting_attr], [< | fediffuselighting_content], [> | fediffuselighting]) star val feDisplacementMap : ([< | fedisplacementmap_attr], [< | fedisplacementmap_content], [> | fedisplacementmap]) star val feFlood : ([< | feflood_attr], [< | feflood_content], [> | feflood]) star val feGaussianBlur : ([< | fegaussianblur_attr], [< | fegaussianblur_content], [> | fegaussianblur]) star val feImage : ([< | feimage_attr], [< | feimage_content], [> | feimage]) star val feMerge : ([< | femerge_attr], [< | femerge_content], [> | femerge]) star val feMorphology : ([< | femorphology_attr], [< | femorphology_content], [> | femorphology ]) star val feOffset : ([< | feoffset_attr], [< | feoffset_content], [> | feoffset]) star val feSpecularLighting : ([< | fespecularlighting_attr], [< | fespecularlighting_content], [> | fespecularlighting]) star val feTile : ([< | fetile_attr], [< | fetile_content], [> | fetile]) star val feTurbulence : ([< | feturbulence_attr], [< | feturbulence_content], [> | feturbulence ]) star val cursor : ([< | cursor_attr], [< | cursor_content], [> | cursor]) star val a : ([< | a_attr], [< | a_content], [> | a]) star val view : ([< | view_attr], [< | view_content], [> | view]) star val script : ([< | script_attr], [< | script_content], [> | script]) unary val animation : ([< | animation_attr], [< | animation_content], [> | animation]) star val set : ([< | set_attr], [< | set_content], [> | set]) star val animateMotion : ([< | animatemotion_attr], [< | animatemotion_content], [> | animatemotion]) star val mpath : ([< | mpath_attr], [< | mpath_content], [> | mpath]) star val animateColor : ([< | animatecolor_attr], [< | animatecolor_content], [> | animatecolor ]) star val animateTransform : ([< | animatetransform_attr], [< | animatetransform_content], [> | animatetransform]) star val font : ([< | font_attr], [< | font_content], [> | font]) star [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val glyph : ([< | glyph_attr], [< | glyph_content], [> | glyph]) star [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val missing_glyph : ([< | missingglyph_attr], [< | missingglyph_content], [> | missingglyph ]) star [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val hkern : ([< | hkern_attr], [> | hkern]) nullary [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val vkern : ([< | vkern_attr], [> | vkern]) nullary [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val font_face : ([< | font_face_attr], [> | font_face]) nullary [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val font_face_src : ([< | font_face_src_attr], [< | font_face_src_content], [> | font_face_src]) star [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val font_face_uri : ([< | font_face_uri_attr], [< | font_face_uri_content], [> | font_face_uri]) star [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val font_face_format : ([< | font_face_format_attr], [> | font_face_format]) nullary [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val font_face_name : ([< | font_face_name_attr], [> | font_face_name]) nullary [@@ocaml.deprecated "Removed in SVG2"] (** @deprecated Removed in SVG2 *) val metadata : ?a: ((metadata_attr attrib) list) -> Xml.elt list_wrap -> [> | metadata] elt val foreignObject : ?a: ((foreignobject_attr attrib) list) -> Xml.elt list_wrap -> [> | foreignobject] elt (** {3 Deprecated} *) val pcdata : string wrap -> [> txt] elt [@@ocaml.deprecated "Use txt instead"] (** @deprecated Use txt instead *) (** {2 Conversion with untyped representation} WARNING: These functions do not ensure HTML or SVG validity! You should always explicitly given an appropriate type to the output. *) (** [import signal] converts the given XML signal into Tyxml elements. It can be used with HTML and SVG parsing libraries, such as Markup. @raise Xml_stream.Malformed_stream if the stream is malformed. *) val of_seq : Xml_stream.signal Seq.t -> 'a elt list_wrap val tot : Xml.elt -> 'a elt val totl : Xml.elt list_wrap -> ('a elt) list_wrap val toelt : 'a elt -> Xml.elt val toeltl : ('a elt) list_wrap -> Xml.elt list_wrap val doc_toelt : doc -> Xml.elt val to_xmlattribs : ('a attrib) list -> Xml.attrib list val to_attrib : Xml.attrib -> 'a attrib (** Unsafe features. Using this module can break SVG validity and may introduce security problems like code injection. Use it with care. *) module Unsafe : sig (** Insert raw text without any encoding *) val data : string wrap -> 'a elt (** Insert an XML node that is not implemented in this module. If it is a standard SVG node which is missing, please report to the Ocsigen team. *) val node : string -> ?a:'a attrib list -> 'b elt list_wrap -> 'c elt (** Insert an XML node without children that is not implemented in this module. If it is a standard SVG node which is missing, please report to the Ocsigen team. *) val leaf : string -> ?a:'a attrib list -> unit -> 'b elt (** Remove phantom type annotation on an element, to make it usable everywhere. *) val coerce_elt : 'a elt -> 'b elt (** Insert an attribute that is not implemented in this module. If it is a standard SVG attribute which is missing, please report to the Ocsigen team. *) val string_attrib : string -> string wrap -> 'a attrib (** Same, for float attribute *) val float_attrib : string -> float wrap -> 'a attrib (** Same, for int attribute *) val int_attrib : string -> int wrap -> 'a attrib (** Same, for URI attribute *) val uri_attrib : string -> uri wrap -> 'a attrib (** Same, for a space separated list of values *) val space_sep_attrib : string -> string list wrap -> 'a attrib (** Same, for a comma separated list of values *) val comma_sep_attrib : string -> string list wrap -> 'a attrib end end (** Equivalent to {!T}, but without wrapping. *) module type NoWrap = T with module Xml.W = Xml_wrap.NoWrap (** {2 Signature functors} See {% <<a_manual chapter="functors"|the manual of the functorial interface>> %}. *) (** Signature functor for {!Svg_f.Make}. *) module Make (Xml : Xml_sigs.T) : sig (** See {!module-type:Svg_sigs.T}. *) module type T = T with type 'a Xml.W.t = 'a Xml.W.t and type 'a Xml.W.tlist = 'a Xml.W.tlist and type ('a,'b) Xml.W.ft = ('a,'b) Xml.W.ft and type Xml.uri = Xml.uri and type Xml.event_handler = Xml.event_handler and type Xml.mouse_event_handler = Xml.mouse_event_handler and type Xml.keyboard_event_handler = Xml.keyboard_event_handler and type Xml.touch_event_handler = Xml.touch_event_handler and type Xml.attrib = Xml.attrib and type Xml.elt = Xml.elt end (** Wrapped functions, to be used with {!Svg_f.Make_with_wrapped_functions}. *) module type Wrapped_functions = sig module Xml : Xml_sigs.T val string_of_alignment_baseline : ([< Svg_types.alignment_baseline], string) Xml.W.ft val string_of_bool : (bool, string) Xml.W.ft val string_of_big_variant : ([< Svg_types.big_variant], string) Xml.W.ft val string_of_coords : (Svg_types.coords, string) Xml.W.ft val string_of_dominant_baseline : ([< Svg_types.dominant_baseline], string) Xml.W.ft val string_of_fourfloats : (float * float * float * float, string) Xml.W.ft val string_of_in_value : ([< Svg_types.in_value], string) Xml.W.ft val string_of_int : (int, string) Xml.W.ft val string_of_length : (Svg_types.Unit.length, string) Xml.W.ft val string_of_lengths : (Svg_types.lengths, string) Xml.W.ft val string_of_number : (float, string) Xml.W.ft val string_of_number_optional_number : (float * float option, string) Xml.W.ft val string_of_numbers : (float list, string) Xml.W.ft val string_of_numbers_semicolon : (float list, string) Xml.W.ft val string_of_offset : ([< Svg_types.offset], string) Xml.W.ft val string_of_orient : (Svg_types.Unit.angle option, string) Xml.W.ft val string_of_paint : ([< Svg_types.paint], string) Xml.W.ft val string_of_strokedasharray : (Svg_types.lengths, string) Xml.W.ft val string_of_transform : (Svg_types.transform, string) Xml.W.ft val string_of_transforms : (Svg_types.transforms, string) Xml.W.ft end
(* TyXML * http://www.ocsigen.org/tyxml * Copyright (C) 2011 Pierre Chambart, Grégoire Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1301, USA. *)
michelson_v1_primitives.ml
open Micheline type error += Unknown_primitive_name of string type error += Invalid_case of string type error += Invalid_primitive_name of string Micheline.canonical * Micheline.canonical_location type prim = | K_parameter | K_storage | K_code | D_False | D_Elt | D_Left | D_None | D_Pair | D_Right | D_Some | D_True | D_Unit | I_PACK | I_UNPACK | I_BLAKE2B | I_SHA256 | I_SHA512 | I_ABS | I_ADD | I_AMOUNT | I_AND | I_BALANCE | I_CAR | I_CDR | I_CHAIN_ID | I_CHECK_SIGNATURE | I_COMPARE | I_CONCAT | I_CONS | I_CREATE_ACCOUNT | I_CREATE_CONTRACT | I_IMPLICIT_ACCOUNT | I_DIP | I_DROP | I_DUP | I_EDIV | I_EMPTY_BIG_MAP | I_EMPTY_MAP | I_EMPTY_SET | I_EQ | I_EXEC | I_APPLY | I_FAILWITH | I_GE | I_GET | I_GT | I_HASH_KEY | I_IF | I_IF_CONS | I_IF_LEFT | I_IF_NONE | I_INT | I_LAMBDA | I_LE | I_LEFT | I_LOOP | I_LSL | I_LSR | I_LT | I_MAP | I_MEM | I_MUL | I_NEG | I_NEQ | I_NIL | I_NONE | I_NOT | I_NOW | I_OR | I_PAIR | I_PUSH | I_RIGHT | I_SIZE | I_SOME | I_SOURCE | I_SENDER | I_SELF | I_SLICE | I_STEPS_TO_QUOTA | I_SUB | I_SWAP | I_TRANSFER_TOKENS | I_SET_DELEGATE | I_UNIT | I_UPDATE | I_XOR | I_ITER | I_LOOP_LEFT | I_ADDRESS | I_CONTRACT | I_ISNAT | I_CAST | I_RENAME | I_DIG | I_DUG | T_bool | T_contract | T_int | T_key | T_key_hash | T_lambda | T_list | T_map | T_big_map | T_nat | T_option | T_or | T_pair | T_set | T_signature | T_string | T_bytes | T_mutez | T_timestamp | T_unit | T_operation | T_address | T_chain_id let valid_case name = let is_lower = function '_' | 'a'..'z' -> true | _ -> false in let is_upper = function '_' | 'A'..'Z' -> true | _ -> false in let rec for_all a b f = Compare.Int.(a > b) || f a && for_all (a + 1) b f in let len = String.length name in Compare.Int.(len <> 0) && Compare.Char.(String.get name 0 <> '_') && ((is_upper (String.get name 0) && for_all 1 (len - 1) (fun i -> is_upper (String.get name i))) || (is_upper (String.get name 0) && for_all 1 (len - 1) (fun i -> is_lower (String.get name i))) || (is_lower (String.get name 0) && for_all 1 (len - 1) (fun i -> is_lower (String.get name i)))) let string_of_prim = function | K_parameter -> "parameter" | K_storage -> "storage" | K_code -> "code" | D_False -> "False" | D_Elt -> "Elt" | D_Left -> "Left" | D_None -> "None" | D_Pair -> "Pair" | D_Right -> "Right" | D_Some -> "Some" | D_True -> "True" | D_Unit -> "Unit" | I_PACK -> "PACK" | I_UNPACK -> "UNPACK" | I_BLAKE2B -> "BLAKE2B" | I_SHA256 -> "SHA256" | I_SHA512 -> "SHA512" | I_ABS -> "ABS" | I_ADD -> "ADD" | I_AMOUNT -> "AMOUNT" | I_AND -> "AND" | I_BALANCE -> "BALANCE" | I_CAR -> "CAR" | I_CDR -> "CDR" | I_CHAIN_ID -> "CHAIN_ID" | I_CHECK_SIGNATURE -> "CHECK_SIGNATURE" | I_COMPARE -> "COMPARE" | I_CONCAT -> "CONCAT" | I_CONS -> "CONS" | I_CREATE_ACCOUNT -> "CREATE_ACCOUNT" | I_CREATE_CONTRACT -> "CREATE_CONTRACT" | I_IMPLICIT_ACCOUNT -> "IMPLICIT_ACCOUNT" | I_DIP -> "DIP" | I_DROP -> "DROP" | I_DUP -> "DUP" | I_EDIV -> "EDIV" | I_EMPTY_BIG_MAP -> "EMPTY_BIG_MAP" | I_EMPTY_MAP -> "EMPTY_MAP" | I_EMPTY_SET -> "EMPTY_SET" | I_EQ -> "EQ" | I_EXEC -> "EXEC" | I_APPLY -> "APPLY" | I_FAILWITH -> "FAILWITH" | I_GE -> "GE" | I_GET -> "GET" | I_GT -> "GT" | I_HASH_KEY -> "HASH_KEY" | I_IF -> "IF" | I_IF_CONS -> "IF_CONS" | I_IF_LEFT -> "IF_LEFT" | I_IF_NONE -> "IF_NONE" | I_INT -> "INT" | I_LAMBDA -> "LAMBDA" | I_LE -> "LE" | I_LEFT -> "LEFT" | I_LOOP -> "LOOP" | I_LSL -> "LSL" | I_LSR -> "LSR" | I_LT -> "LT" | I_MAP -> "MAP" | I_MEM -> "MEM" | I_MUL -> "MUL" | I_NEG -> "NEG" | I_NEQ -> "NEQ" | I_NIL -> "NIL" | I_NONE -> "NONE" | I_NOT -> "NOT" | I_NOW -> "NOW" | I_OR -> "OR" | I_PAIR -> "PAIR" | I_PUSH -> "PUSH" | I_RIGHT -> "RIGHT" | I_SIZE -> "SIZE" | I_SOME -> "SOME" | I_SOURCE -> "SOURCE" | I_SENDER -> "SENDER" | I_SELF -> "SELF" | I_SLICE -> "SLICE" | I_STEPS_TO_QUOTA -> "STEPS_TO_QUOTA" | I_SUB -> "SUB" | I_SWAP -> "SWAP" | I_TRANSFER_TOKENS -> "TRANSFER_TOKENS" | I_SET_DELEGATE -> "SET_DELEGATE" | I_UNIT -> "UNIT" | I_UPDATE -> "UPDATE" | I_XOR -> "XOR" | I_ITER -> "ITER" | I_LOOP_LEFT -> "LOOP_LEFT" | I_ADDRESS -> "ADDRESS" | I_CONTRACT -> "CONTRACT" | I_ISNAT -> "ISNAT" | I_CAST -> "CAST" | I_RENAME -> "RENAME" | I_DIG -> "DIG" | I_DUG -> "DUG" | T_bool -> "bool" | T_contract -> "contract" | T_int -> "int" | T_key -> "key" | T_key_hash -> "key_hash" | T_lambda -> "lambda" | T_list -> "list" | T_map -> "map" | T_big_map -> "big_map" | T_nat -> "nat" | T_option -> "option" | T_or -> "or" | T_pair -> "pair" | T_set -> "set" | T_signature -> "signature" | T_string -> "string" | T_bytes -> "bytes" | T_mutez -> "mutez" | T_timestamp -> "timestamp" | T_unit -> "unit" | T_operation -> "operation" | T_address -> "address" | T_chain_id -> "chain_id" let prim_of_string = function | "parameter" -> ok K_parameter | "storage" -> ok K_storage | "code" -> ok K_code | "False" -> ok D_False | "Elt" -> ok D_Elt | "Left" -> ok D_Left | "None" -> ok D_None | "Pair" -> ok D_Pair | "Right" -> ok D_Right | "Some" -> ok D_Some | "True" -> ok D_True | "Unit" -> ok D_Unit | "PACK" -> ok I_PACK | "UNPACK" -> ok I_UNPACK | "BLAKE2B" -> ok I_BLAKE2B | "SHA256" -> ok I_SHA256 | "SHA512" -> ok I_SHA512 | "ABS" -> ok I_ABS | "ADD" -> ok I_ADD | "AMOUNT" -> ok I_AMOUNT | "AND" -> ok I_AND | "BALANCE" -> ok I_BALANCE | "CAR" -> ok I_CAR | "CDR" -> ok I_CDR | "CHAIN_ID" -> ok I_CHAIN_ID | "CHECK_SIGNATURE" -> ok I_CHECK_SIGNATURE | "COMPARE" -> ok I_COMPARE | "CONCAT" -> ok I_CONCAT | "CONS" -> ok I_CONS | "CREATE_ACCOUNT" -> ok I_CREATE_ACCOUNT | "CREATE_CONTRACT" -> ok I_CREATE_CONTRACT | "IMPLICIT_ACCOUNT" -> ok I_IMPLICIT_ACCOUNT | "DIP" -> ok I_DIP | "DROP" -> ok I_DROP | "DUP" -> ok I_DUP | "EDIV" -> ok I_EDIV | "EMPTY_BIG_MAP" -> ok I_EMPTY_BIG_MAP | "EMPTY_MAP" -> ok I_EMPTY_MAP | "EMPTY_SET" -> ok I_EMPTY_SET | "EQ" -> ok I_EQ | "EXEC" -> ok I_EXEC | "APPLY" -> ok I_APPLY | "FAILWITH" -> ok I_FAILWITH | "GE" -> ok I_GE | "GET" -> ok I_GET | "GT" -> ok I_GT | "HASH_KEY" -> ok I_HASH_KEY | "IF" -> ok I_IF | "IF_CONS" -> ok I_IF_CONS | "IF_LEFT" -> ok I_IF_LEFT | "IF_NONE" -> ok I_IF_NONE | "INT" -> ok I_INT | "LAMBDA" -> ok I_LAMBDA | "LE" -> ok I_LE | "LEFT" -> ok I_LEFT | "LOOP" -> ok I_LOOP | "LSL" -> ok I_LSL | "LSR" -> ok I_LSR | "LT" -> ok I_LT | "MAP" -> ok I_MAP | "MEM" -> ok I_MEM | "MUL" -> ok I_MUL | "NEG" -> ok I_NEG | "NEQ" -> ok I_NEQ | "NIL" -> ok I_NIL | "NONE" -> ok I_NONE | "NOT" -> ok I_NOT | "NOW" -> ok I_NOW | "OR" -> ok I_OR | "PAIR" -> ok I_PAIR | "PUSH" -> ok I_PUSH | "RIGHT" -> ok I_RIGHT | "SIZE" -> ok I_SIZE | "SOME" -> ok I_SOME | "SOURCE" -> ok I_SOURCE | "SENDER" -> ok I_SENDER | "SELF" -> ok I_SELF | "SLICE" -> ok I_SLICE | "STEPS_TO_QUOTA" -> ok I_STEPS_TO_QUOTA | "SUB" -> ok I_SUB | "SWAP" -> ok I_SWAP | "TRANSFER_TOKENS" -> ok I_TRANSFER_TOKENS | "SET_DELEGATE" -> ok I_SET_DELEGATE | "UNIT" -> ok I_UNIT | "UPDATE" -> ok I_UPDATE | "XOR" -> ok I_XOR | "ITER" -> ok I_ITER | "LOOP_LEFT" -> ok I_LOOP_LEFT | "ADDRESS" -> ok I_ADDRESS | "CONTRACT" -> ok I_CONTRACT | "ISNAT" -> ok I_ISNAT | "CAST" -> ok I_CAST | "RENAME" -> ok I_RENAME | "DIG" -> ok I_DIG | "DUG" -> ok I_DUG | "bool" -> ok T_bool | "contract" -> ok T_contract | "int" -> ok T_int | "key" -> ok T_key | "key_hash" -> ok T_key_hash | "lambda" -> ok T_lambda | "list" -> ok T_list | "map" -> ok T_map | "big_map" -> ok T_big_map | "nat" -> ok T_nat | "option" -> ok T_option | "or" -> ok T_or | "pair" -> ok T_pair | "set" -> ok T_set | "signature" -> ok T_signature | "string" -> ok T_string | "bytes" -> ok T_bytes | "mutez" -> ok T_mutez | "timestamp" -> ok T_timestamp | "unit" -> ok T_unit | "operation" -> ok T_operation | "address" -> ok T_address | "chain_id" -> ok T_chain_id | n -> if valid_case n then error (Unknown_primitive_name n) else error (Invalid_case n) let prims_of_strings expr = let rec convert = function | Int _ | String _ | Bytes _ as expr -> ok expr | Prim (loc, prim, args, annot) -> Error_monad.record_trace (Invalid_primitive_name (expr, loc)) (prim_of_string prim) >>? fun prim -> List.fold_left (fun acc arg -> acc >>? fun args -> convert arg >>? fun arg -> ok (arg :: args)) (ok []) args >>? fun args -> ok (Prim (0, prim, List.rev args, annot)) | Seq (_, args) -> List.fold_left (fun acc arg -> acc >>? fun args -> convert arg >>? fun arg -> ok (arg :: args)) (ok []) args >>? fun args -> ok (Seq (0, List.rev args)) in convert (root expr) >>? fun expr -> ok (strip_locations expr) let strings_of_prims expr = let rec convert = function | Int _ | String _ | Bytes _ as expr -> expr | Prim (_, prim, args, annot) -> let prim = string_of_prim prim in let args = List.map convert args in Prim (0, prim, args, annot) | Seq (_, args) -> let args = List.map convert args in Seq (0, args) in strip_locations (convert (root expr)) let prim_encoding = let open Data_encoding in def "michelson.v1.primitives" @@ string_enum [ (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("parameter", K_parameter) ; ("storage", K_storage) ; ("code", K_code) ; ("False", D_False) ; ("Elt", D_Elt) ; ("Left", D_Left) ; ("None", D_None) ; ("Pair", D_Pair) ; ("Right", D_Right) ; ("Some", D_Some) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("True", D_True) ; ("Unit", D_Unit) ; ("PACK", I_PACK) ; ("UNPACK", I_UNPACK) ; ("BLAKE2B", I_BLAKE2B) ; ("SHA256", I_SHA256) ; ("SHA512", I_SHA512) ; ("ABS", I_ABS) ; ("ADD", I_ADD) ; ("AMOUNT", I_AMOUNT) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("AND", I_AND) ; ("BALANCE", I_BALANCE) ; ("CAR", I_CAR) ; ("CDR", I_CDR) ; ("CHECK_SIGNATURE", I_CHECK_SIGNATURE) ; ("COMPARE", I_COMPARE) ; ("CONCAT", I_CONCAT) ; ("CONS", I_CONS) ; ("CREATE_ACCOUNT", I_CREATE_ACCOUNT) ; ("CREATE_CONTRACT", I_CREATE_CONTRACT) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("IMPLICIT_ACCOUNT", I_IMPLICIT_ACCOUNT) ; ("DIP", I_DIP) ; ("DROP", I_DROP) ; ("DUP", I_DUP) ; ("EDIV", I_EDIV) ; ("EMPTY_MAP", I_EMPTY_MAP) ; ("EMPTY_SET", I_EMPTY_SET) ; ("EQ", I_EQ) ; ("EXEC", I_EXEC) ; ("FAILWITH", I_FAILWITH) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("GE", I_GE) ; ("GET", I_GET) ; ("GT", I_GT) ; ("HASH_KEY", I_HASH_KEY) ; ("IF", I_IF) ; ("IF_CONS", I_IF_CONS) ; ("IF_LEFT", I_IF_LEFT) ; ("IF_NONE", I_IF_NONE) ; ("INT", I_INT) ; ("LAMBDA", I_LAMBDA) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("LE", I_LE) ; ("LEFT", I_LEFT) ; ("LOOP", I_LOOP) ; ("LSL", I_LSL) ; ("LSR", I_LSR) ; ("LT", I_LT) ; ("MAP", I_MAP) ; ("MEM", I_MEM) ; ("MUL", I_MUL) ; ("NEG", I_NEG) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("NEQ", I_NEQ) ; ("NIL", I_NIL) ; ("NONE", I_NONE) ; ("NOT", I_NOT) ; ("NOW", I_NOW) ; ("OR", I_OR) ; ("PAIR", I_PAIR) ; ("PUSH", I_PUSH) ; ("RIGHT", I_RIGHT) ; ("SIZE", I_SIZE) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("SOME", I_SOME) ; ("SOURCE", I_SOURCE) ; ("SENDER", I_SENDER) ; ("SELF", I_SELF) ; ("STEPS_TO_QUOTA", I_STEPS_TO_QUOTA) ; ("SUB", I_SUB) ; ("SWAP", I_SWAP) ; ("TRANSFER_TOKENS", I_TRANSFER_TOKENS) ; ("SET_DELEGATE", I_SET_DELEGATE) ; ("UNIT", I_UNIT) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("UPDATE", I_UPDATE) ; ("XOR", I_XOR) ; ("ITER", I_ITER) ; ("LOOP_LEFT", I_LOOP_LEFT) ; ("ADDRESS", I_ADDRESS) ; ("CONTRACT", I_CONTRACT) ; ("ISNAT", I_ISNAT) ; ("CAST", I_CAST) ; ("RENAME", I_RENAME) ; ("bool", T_bool) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("contract", T_contract) ; ("int", T_int) ; ("key", T_key) ; ("key_hash", T_key_hash) ; ("lambda", T_lambda) ; ("list", T_list) ; ("map", T_map) ; ("big_map", T_big_map) ; ("nat", T_nat) ; ("option", T_option) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("or", T_or) ; ("pair", T_pair) ; ("set", T_set) ; ("signature", T_signature) ; ("string", T_string) ; ("bytes", T_bytes) ; ("mutez", T_mutez) ; ("timestamp", T_timestamp) ; ("unit", T_unit) ; ("operation", T_operation) ; (* /!\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *) ("address", T_address) ; (* Alpha_002 addition *) ("SLICE", I_SLICE) ; (* Alpha_005 addition *) ("DIG", I_DIG) ; ("DUG", I_DUG) ; ("EMPTY_BIG_MAP", I_EMPTY_BIG_MAP) ; ("APPLY", I_APPLY) ; ("chain_id", T_chain_id) ; ("CHAIN_ID", I_CHAIN_ID) (* New instructions must be added here, for backward compatibility of the encoding. *) ] let () = register_error_kind `Permanent ~id:"michelson_v1.unknown_primitive_name" ~title: "Unknown primitive name" ~description: "In a script or data expression, a primitive was unknown." ~pp:(fun ppf n -> Format.fprintf ppf "Unknown primitive %s." n) Data_encoding.(obj1 (req "wrong_primitive_name" string)) (function | Unknown_primitive_name got -> Some got | _ -> None) (fun got -> Unknown_primitive_name got) ; register_error_kind `Permanent ~id:"michelson_v1.invalid_primitive_name_case" ~title: "Invalid primitive name case" ~description: "In a script or data expression, a primitive name is \ neither uppercase, lowercase or capitalized." ~pp:(fun ppf n -> Format.fprintf ppf "Primitive %s has invalid case." n) Data_encoding.(obj1 (req "wrong_primitive_name" string)) (function | Invalid_case name -> Some name | _ -> None) (fun name -> Invalid_case name) ; register_error_kind `Permanent ~id:"michelson_v1.invalid_primitive_name" ~title: "Invalid primitive name" ~description: "In a script or data expression, a primitive name is \ unknown or has a wrong case." ~pp:(fun ppf _ -> Format.fprintf ppf "Invalid primitive.") Data_encoding.(obj2 (req "expression" (Micheline.canonical_encoding ~variant:"generic" string)) (req "location" Micheline.canonical_location_encoding)) (function | Invalid_primitive_name (expr, loc) -> Some (expr, loc) | _ -> None) (fun (expr, loc) -> Invalid_primitive_name (expr, loc))
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
tx_rollup_services.ml
let custom_root = (RPC_path.(open_root / "context" / "tx_rollup") : RPC_context.t RPC_path.context) module S = struct let state = RPC_service.get_service ~description:"Access the state of a rollup." ~query:RPC_query.empty ~output:Tx_rollup_state.encoding RPC_path.(custom_root /: Tx_rollup.rpc_arg / "state") let inbox = RPC_service.get_service ~description:"Get the inbox of a transaction rollup" ~query:RPC_query.empty ~output:Data_encoding.(option Tx_rollup_inbox.encoding) RPC_path.( custom_root /: Tx_rollup.rpc_arg / "inbox" /: Tx_rollup_level.rpc_arg) let commitment = RPC_service.get_service ~description:"Return the commitment for a level, if any" ~query:RPC_query.empty ~output: Data_encoding.( option Tx_rollup_commitment.Submitted_commitment.encoding) RPC_path.( custom_root /: Tx_rollup.rpc_arg / "commitment" /: Tx_rollup_level.rpc_arg) let pending_bonded_commitments = RPC_service.get_service ~description: "Get the number of pending bonded commitments for a pkh on a rollup" ~query:RPC_query.empty ~output:Data_encoding.int32 RPC_path.( custom_root /: Tx_rollup.rpc_arg / "pending_bonded_commitments" /: Signature.Public_key_hash.rpc_arg) end let register () = let open Services_registration in opt_register1 ~chunked:false S.state (fun ctxt tx_rollup () () -> Tx_rollup_state.find ctxt tx_rollup >|=? snd) ; register2 ~chunked:false S.inbox (fun ctxt tx_rollup level () () -> Tx_rollup_inbox.find ctxt level tx_rollup >|=? snd) ; register2 ~chunked:false S.commitment (fun ctxt tx_rollup level () () -> Tx_rollup_state.get ctxt tx_rollup >>=? fun (ctxt, state) -> Tx_rollup_commitment.find ctxt tx_rollup state level >|=? fun (_, commitment) -> commitment) ; register2 ~chunked:false S.pending_bonded_commitments (fun ctxt tx_rollup pkh () () -> Tx_rollup_commitment.pending_bonded_commitments ctxt tx_rollup pkh >|=? fun (_, count) -> Int32.of_int count) let state ctxt block tx_rollup = RPC_context.make_call1 S.state ctxt block tx_rollup () () let inbox ctxt block tx_rollup level = RPC_context.make_call2 S.inbox ctxt block tx_rollup level () () let commitment ctxt block tx_rollup level = RPC_context.make_call2 S.commitment ctxt block tx_rollup level () ()
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Marigold <contact@marigold.dev> *) (* Copyright (c) 2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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
token.ml
(**The Token Module*) (**Type of tokens*) type token_type = | LEFT_PARENTHESIS | RIGHT_PARENTHESIS | KEYWORD of string | QUOTE | SEMI_COLON | INT_TOKEN of int | FLOAT_TOKEN of float | NULL_TOKEN | STRING_TOKEN of string | BOOL_TOKEN of bool | ARRAY_BEGIN | PARAM_BEGIN | ARRAY_END | PARAM_END | COMMENT | COMMA (**Parses a string into a token*) let string_to_token str = match String.trim str with | "CHOUQUETTE" -> LEFT_PARENTHESIS | "CLAFOUTIS" -> RIGHT_PARENTHESIS | "PARISBREST" -> QUOTE | "BAGUETTE" -> SEMI_COLON | "CUPCAKE" -> BOOL_TOKEN true | "POPCAKE" -> BOOL_TOKEN false | "MUFFIN" -> KEYWORD "BEGIN" | "COOKIES" -> KEYWORD "END" | "ICECREAM" -> KEYWORD "LABEL" | "PAINVIENNOIS" -> KEYWORD "GOTO" | "SABLE" -> KEYWORD "IF" | "FRAMBOISIER" -> KEYWORD "THEN" | "LOAD" -> KEYWORD "LOAD" | "BABAAURHUM" -> ARRAY_BEGIN | "CHARLOTTEAUXFRAISES" -> ARRAY_END | "SCHNECKENKUCHEN" -> PARAM_END | "CRUMBLE" -> PARAM_BEGIN | "//" -> COMMENT | "," -> COMMA | str -> ( try INT_TOKEN (int_of_string str) with | Failure _ -> ( try FLOAT_TOKEN (float_of_string str) with Failure _ -> NULL_TOKEN) | _ -> NULL_TOKEN) (**A list of token recognized by the lexer*) let recognized_token = [ ","; "CHOUQUETTE"; "CLAFOUTIS"; "PARISBREST"; "BAGUETTE"; "CUPCAKE"; "SCHNECKENKUCHEN"; "CRUMBLE"; "POPCAKE"; "MUFFIN"; "COOKIES"; "ICECREAM"; "PAINVIENNOIS"; "SABLE"; "FRAMBOISIER"; "BABAAURHUM"; "//"; "LOAD"; ] (**Transforms a token into a string*) let token_to_string = function | LEFT_PARENTHESIS -> "{(}" | RIGHT_PARENTHESIS -> "{)}" | QUOTE -> "{\"}" | SEMI_COLON -> "{;}" | INT_TOKEN i -> "{Int " ^ string_of_int i ^ "}" | FLOAT_TOKEN i -> "{Float " ^ string_of_float i ^ "}" | STRING_TOKEN s -> "{String \"" ^ s ^ "\"}" | BOOL_TOKEN f -> "{Bool: " ^ string_of_bool f ^ "}" | KEYWORD k -> "{KEYWORD: " ^ k ^ "}" | ARRAY_BEGIN -> "{[}" | ARRAY_END -> "{]}" | PARAM_BEGIN -> "{ { }" | PARAM_END -> "{ } }" | COMMENT -> "{//}" | COMMA -> "{,}" | NULL_TOKEN -> "NULL" (**Transforms the value of a token into a string*) let token_to_litteral_string = function | LEFT_PARENTHESIS -> "(" | RIGHT_PARENTHESIS -> ")" | SEMI_COLON -> ";" | INT_TOKEN i -> string_of_int i ^ " " | STRING_TOKEN s -> s | FLOAT_TOKEN d -> string_of_float d ^ " " | BOOL_TOKEN f -> string_of_bool f ^ " " | KEYWORD k -> k ^ " " | ARRAY_BEGIN -> "[" | ARRAY_END -> "]" | PARAM_BEGIN -> "{" | PARAM_END -> "}" | COMMENT -> "//" | COMMA -> "," | _ -> "" (**Pretty print a token*) let pretty_print ppf tok = Fmt.pf ppf "Token %s" (token_to_string tok) (**Prints a list of token*) let print_token_list list = let rec str acc list = match list with | [] -> acc | t :: q -> str (acc ^ token_to_string t ^ " ") q in let s = str "[" list in print_string (s ^ "]")
(**The Token Module*)
generate.ml
open Structures open Util open Migrate_parsetree open Ast_404 let is_list ~shapes ~shp = try match (StringTable.find shp shapes).Shape.content with | Shape.List _ -> true | _ -> false with Not_found -> false let is_flat_list ~shapes ~shp = try match (StringTable.find shp shapes).Shape.content with | Shape.List (_,_,true) -> true | _ -> false with Not_found -> false let toposort (shapes : Shape.t StringTable.t) = let open Graph in let module G = Imperative.Digraph.ConcreteBidirectional(struct type t = Shape.t let compare a b = compare a.Shape.name b.Shape.name let hash a = Hashtbl.hash a.Shape.name let equal a b = a.Shape.name = b.Shape.name end) in let graph = G.create () in let add_edge from to_ = try G.add_edge graph from (StringTable.find to_ shapes) with Not_found -> () in StringTable.iter (fun _key data -> G.add_vertex graph data; match data.Shape.content with | Shape.Structure members -> List.iter (fun mem -> add_edge data mem.Structure.shape) members | Shape.List (s,_,_) -> add_edge data s | Shape.Map ((ks,_), (vs,_)) -> add_edge data ks; add_edge data vs | Shape.Enum _ -> ()) shapes; let module T = Topological.Make(G) in let out = ref [] in T.iter (fun shape -> out := shape :: !out) graph; !out let types is_ec2 shapes = let option_type shp = function |true -> Syntax.ty0 shp |false -> Syntax.ty1 "option" shp in let build_module v = let mkrecty fs = Syntax.tyreclet "t" (List.map (fun (nm,shp,req) -> (nm, option_type shp req)) fs) in let ty = match v.Shape.content with | Shape.Structure [ ] -> (* Hack for a unit type since empty records aren't yet valid *) Syntax.tyunit "t" | Shape.Structure members -> mkrecty (List.map (fun m -> (m.Structure.field_name, (String.capitalize_ascii m.Structure.shape) ^ ".t", m.Structure.required || is_list ~shapes ~shp:m.Structure.shape)) members) | Shape.List (shp, _, _flatten) -> Syntax.tylet "t" (Syntax.ty1 "list" (shp ^ ".t")) | Shape.Map ((kshp, _loc), (vshp, _)) -> Syntax.tylet "t" (Syntax.ty2 "Hashtbl.t" (kshp ^ ".t") (vshp ^ ".t")) | Shape.Enum opts -> Syntax.tyvariantlet "t" (List.map (fun t -> (Util.to_variant_name t, [])) opts) in let make = match v.Shape.content with | Shape.Structure [ ] -> let body = Syntax.(fununit (unit ())) in Syntax.let_ "make" body | Shape.Structure members -> let rec mkfun (args : Structure.member list) body = match args with | [ ] -> body | (x::xs) -> let fn = if x.Structure.required then Syntax.funlab else if is_list ~shapes ~shp:x.Structure.shape then Syntax.(funopt_def (list [])) else Syntax.funopt in fn x.Structure.field_name (mkfun xs body) in let body = Syntax.(fununit (record (List.map (fun a -> (a.Structure.field_name, ident a.Structure.field_name)) members))) in Syntax.let_ "make" (mkfun members body) | Shape.List _ -> [%stri let make elems () = elems] | Shape.Enum _ -> [%stri let make v () = v] (* TODO: maybe accept a list of tuples and create a Hashtbl *) | Shape.Map _ -> [%stri let make elems () = elems] in let extra = let open Syntax in match v.Shape.content with | Shape.Enum opts -> [let_ "str_to_t" (list (List.map (fun o -> pair (str o) (ident (Util.to_variant_name o))) opts)); let_ "t_to_str" (list (List.map (fun o -> pair (ident (Util.to_variant_name o)) (str o)) opts)); let_ "to_string" (fun_ "e" (app1 "Util.of_option_exn" (app2 "Util.list_find" (ident "t_to_str") (ident "e")))); let_ "of_string" (fun_ "s" (app1 "Util.of_option_exn" (app2 "Util.list_find" (ident "str_to_t") (ident "s")))) ] | _ -> [] in let parse = match v.Shape.content with | Shape.Structure [ ] -> Syntax.(let_ "parse" (fun_ "xml" (app1 "Some" (unit ())))) | Shape.Structure s -> let fields = List.map (fun (mem : Structure.member) -> let loc_name = match mem.Structure.loc_name with | Some name -> name | None -> mem.Structure.name in let b = if is_flat_list ~shapes ~shp:mem.Structure.shape then Syntax.( (app1 (String.capitalize_ascii mem.Structure.shape ^ ".parse") (ident "xml")) ) else Syntax.(app2 "Util.option_bind" (app2 "Xml.member" (str loc_name) (ident "xml")) (ident (String.capitalize_ascii mem.Structure.shape ^ ".parse"))) in let op = if mem.Structure.required then Syntax.(app2 "Xml.required" (str loc_name) b) else if is_list ~shapes ~shp:mem.Structure.shape then Syntax.(app2 "Util.of_option" (list []) b) else b in (mem.Structure.field_name, op)) s in Syntax.(let_ "parse" (fun_ "xml" (app1 "Some" (record fields)))) | Shape.Map ((_shp, _loc_name), _) -> Syntax.(let_ "parse" (fun_ "xml" (ident "None"))) | Shape.List (shp, loc_name, _flatten) -> let item_name = match loc_name with | None -> "member" | Some nm -> nm in Syntax.(let_ "parse" (fun_ "xml" (app1 "Util.option_all" (app2 "List.map" (ident (shp ^ ".parse")) (app2 "Xml.members" (str item_name) (ident "xml")))))) | Shape.Enum _opts -> Syntax.(let_ "parse" (fun_ "xml" (app2 "Util.option_bind" (app1 "String.parse" (ident "xml")) (fun_ "s" (app2 "Util.list_find" (ident "str_to_t") (ident "s")))))) in let to_query = Syntax.( let_ "to_query" (fun_ "v" (match v.Shape.content with | Shape.Structure s -> (app1 "Query.List" (app1 "Util.list_filter_opt" (list (List.map (fun mem -> let location = match mem.Structure.loc_name with | Some name -> name | None -> mem.Structure.name ^ if not is_ec2 && is_list ~shapes ~shp:mem.Structure.shape then ".member" else "" in let location = if is_ec2 then String.capitalize_ascii location else location in let q arg = app1 "Query.Pair" (pair (str location) (app1 (String.capitalize_ascii mem.Structure.shape ^ ".to_query") arg)) in (if mem.Structure.required || is_list ~shapes ~shp:mem.Structure.shape then app1 "Some" (q (ident ("v." ^ mem.Structure.field_name))) else app2 "Util.option_map" (ident ("v." ^ mem.Structure.field_name)) (fun_ "f" (q (ident "f"))))) s)))) | Shape.List (shp,_,_flatten) -> (app2 "Query.to_query_list" (ident (shp ^ ".to_query")) (ident "v")) | Shape.Map ((key_shp,_),(val_shp,_)) -> (app3 "Query.to_query_hashtbl" (ident (key_shp ^ ".to_string")) (ident (val_shp ^ ".to_query")) (ident "v")) | Shape.Enum _ -> (app1 "Query.Value" (app1 "Some" (app1 "Util.of_option_exn" (app2 "Util.list_find" (ident "t_to_str") (ident "v")))))))) in let to_json = Syntax.( let_ "to_json" (fun_ "v" (match v.Shape.content with | Shape.Structure s -> (variant1 "Assoc" (app1 "Util.list_filter_opt" (list (List.map (fun mem -> let q arg = (pair (str mem.Structure.field_name) (app1 (String.capitalize_ascii mem.Structure.shape ^ ".to_json") arg)) in if mem.Structure.required || is_list ~shapes ~shp:mem.Structure.shape then app1 "Some" (q (ident ("v." ^ mem.Structure.field_name))) else app2 "Util.option_map" (ident ("v." ^ mem.Structure.field_name)) (fun_ "f" (q (ident "f"))) ) s)))) | Shape.List (shp,_,_flatten) -> (variant1 "List" (app2 "List.map" (ident (shp ^ ".to_json")) (ident "v"))) | Shape.Map ((key_shp,_),(val_shp,_)) -> (variant1 "Assoc" (app3 "Hashtbl.fold" (fun3 "k" "v" "acc" (list_expr (pair (app1 (key_shp ^ ".to_string") (ident "k")) (app1 (val_shp ^ ".to_json") (ident "v"))) (ident "acc"))) (ident "v") (list []))) | Shape.Enum _ -> app1 "String.to_json" (app1 "Util.of_option_exn" (app2 "Util.list_find" (ident "t_to_str") (ident "v"))) ))) in let of_json = Syntax.( let_ "of_json" (fun_ "j" (match v.Shape.content with | Shape.Structure [ ] -> (* Hack for a unit type since empty records aren't yet valid *) Syntax.unit () | Shape.Structure s -> record (List.map (fun mem -> (mem.Structure.field_name, (if mem.Structure.required || is_list ~shapes ~shp:mem.Structure.shape then fun v -> app1 (String.capitalize_ascii mem.Structure.shape ^ ".of_json") (app1 "Util.of_option_exn" v) else fun v -> app2 "Util.option_map" v (ident (mem.Structure.shape ^ ".of_json"))) (app2 "Json.lookup" (ident "j") (str mem.Structure.field_name)))) s) | Shape.List (shp,_,_flatten) -> app2 "Json.to_list" (ident (shp ^ ".of_json")) (ident "j") | Shape.Map ((key_shp,_),(val_shp,_)) -> app3 "Json.to_hashtbl" (ident (key_shp ^ ".of_string")) (ident (val_shp ^ ".of_json")) (ident "j") | Shape.Enum _ -> (app1 "Util.of_option_exn" (app2 "Util.list_find" (ident "str_to_t") (app1 "String.of_json" (ident "j")))) ))) in Syntax.module_ (String.capitalize_ascii v.Shape.name) ([ty] @ extra @ [make; parse; to_query; to_json; of_json]) in let modules = List.map build_module (toposort shapes) in let imports = [Syntax.open_ "Aws"; Syntax.open_ "Aws.BaseTypes"; Syntax.open_ "CalendarLib"; Syntax.(tylet "calendar" (ty0 "Calendar.t")); ] in imports @ modules let op service version _shapes op signature_version = let open Syntax in let mkty = function | None -> ty0 "unit" | Some shp -> ty0 (shp ^ ".t") in let defaults = (list [ pair (str "Action") (list [str op.Operation.name]) ; pair (str "Version") (list [str version]) ]) in let to_body = letin "uri" (app2 "Uri.add_query_params" (app1 "Uri.of_string" (app1 "Aws.Util.of_option_exn" (app2 "Endpoints.url_of" (ident "service") (ident "region")))) (match op.Operation.input_shape with | None -> defaults | Some input_shape -> (app2 "List.append" defaults (app1 "Util.drop_empty" (app1 "Uri.query_of_encoded" (app1 "Query.render" (app1 (input_shape ^ ".to_query") (ident "req")))))))) (tuple [variant op.Operation.http_meth; ident "uri"; list []]) in let of_body = match op.Operation.output_shape with | None -> variant1 "Ok" (ident "()") | Some shp -> tryfail (letin "xml" (app1 "Ezxmlm.from_string" (ident "body")) (letin "resp" (let r = app2 "Xml.member" (str (op.Operation.name ^ "Response")) (app1 "snd" (ident "xml")) in match op.Operation.output_wrapper with | None -> r | Some w -> app2 "Util.option_bind" r (app1 "Xml.member" (str w))) (try_msg "Xml.RequiredFieldMissing" (app2 "Util.or_error" (app2 "Util.option_bind" (ident "resp") (ident (shp ^ ".parse"))) (letom "Error" (app1 "BadResponse" (record [("body", ident "body"); ("message", str ("Could not find well formed " ^ shp ^ "."))])))) (letom "Error" (variant1 "Error" (app1 "BadResponse" (record [("body", ident "body"); ("message", app2 "^" (str ("Error parsing " ^ shp ^ " - missing field in body or children: ")) (ident "msg"))]))))) )) (variant1 "Error" (letom "Error" (app1 "BadResponse" (record [("body", ident "body"); ("message", app2 "^" (str "Error parsing xml: ") (ident "msg") )])))) in let op_error_parse = letin "errors" (app2 "@" (list (List.map (fun name -> ident ("Errors_internal." ^ (Util.to_variant_name name))) op.Operation.errors)) (ident "Errors_internal.common")) (matchoption (app1 "Errors_internal.of_string" (ident "err")) (ifthen (app2 "&&" (app2 "List.mem" (ident "var") (ident "errors")) (matchoption (app1 "Errors_internal.to_http_code" (ident "var")) (app2 "=" (ident "var") (ident "code")) (ident "true"))) (app1 "Some" (ident "var")) (ident "None")) (ident "None")) in (** Tuple corresponding to (mli, ml) *) ([ sopen_ "Types" ; stylet "input" (mkty op.Operation.input_shape) ; stylet "output" (mkty op.Operation.output_shape) ; stylet "error" (ty0 "Errors_internal.t") ; sinclude_ "Aws.Call" [withty "input" "input" ; withty "output" "output" ; withty "error" "error"] ], [ open_ "Types" ; open_ "Aws" ; tylet "input" (mkty op.Operation.input_shape) ; tylet "output" (mkty op.Operation.output_shape) ; tylet "error" (ty0 "Errors_internal.t") ; let_ "service" (str service) ; let_ "signature_version" (ident ("Request." ^ String.capitalize_ascii signature_version)) ; let_ "to_http" (fun3 "service" "region" "req" to_body) ; let_ "of_http" (fun_ "body" of_body) ; let_ "parse_error" (fun2 "code" "err" op_error_parse) ]) let errors errs common_errors = let errs = errs @ [Error.({shape_name = "UninhabitedError"; variant_name = "Uninhabited"; string_name = "Uninhabited"; http_code = None})] in let open Syntax in [ tyvariantlet "t" (List.map (fun e -> (e.Error.variant_name, [])) errs) ; let_ "common" (list (List.map (fun e -> ident e.Error.variant_name) common_errors)) ; let_ "to_http_code" (fun_ "e" (matchvar (ident "e") (List.map (fun e -> (e.Error.variant_name, match e.Error.http_code with | Some n -> app1 "Some" (int n) | None -> ident "None")) errs))) ; let_ "to_string" (fun_ "e" (matchvar (ident "e") (List.map (fun e -> (e.Error.variant_name, str e.Error.string_name)) errs))) ; let_ "of_string" (fun_ "e" (matchstrs (ident "e") (List.map (fun e -> (e.Error.string_name, app1 "Some" (ident e.Error.variant_name))) errs) (ident "None") )) ]
(*---------------------------------------------------------------------------- Copyright (c) 2016 Inhabited Type LLC. 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 the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS 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. ----------------------------------------------------------------------------*)
bindings.c
/* Generated by ocaml-tree-sitter for go. */ #include <string.h> #include <tree_sitter/api.h> #include <caml/alloc.h> #include <caml/bigarray.h> #include <caml/callback.h> #include <caml/custom.h> #include <caml/memory.h> #include <caml/mlvalues.h> #include <caml/threads.h> // Implemented by parser.c TSLanguage *tree_sitter_go(); typedef struct _parser { TSParser *parser; } parser_W; static void finalize_parser(value v) { parser_W *p; p = (parser_W *)Data_custom_val(v); ts_parser_delete(p->parser); } static struct custom_operations parser_custom_ops = { .identifier = "parser handling", .finalize = finalize_parser, .compare = custom_compare_default, .hash = custom_hash_default, .serialize = custom_serialize_default, .deserialize = custom_deserialize_default }; // OCaml function CAMLprim value octs_create_parser_go(value unit) { CAMLparam0(); CAMLlocal1(v); parser_W parserWrapper; TSParser *parser = ts_parser_new(); parserWrapper.parser = parser; v = caml_alloc_custom(&parser_custom_ops, sizeof(parser_W), 0, 1); memcpy(Data_custom_val(v), &parserWrapper, sizeof(parser_W)); ts_parser_set_language(parser, tree_sitter_go()); CAMLreturn(v); };
/* Generated by ocaml-tree-sitter for go. */
Constants.mli
(** Get an attribute of this module as a Py.Object.t. This is useful to pass a Python function to another function. *) val get_py : string -> Py.Object.t module ConstantWarning : sig type tag = [`ConstantWarning] type t = [`BaseException | `ConstantWarning | `Object] Obj.t val of_pyobject : Py.Object.t -> t val to_pyobject : [> tag] Obj.t -> Py.Object.t val as_exception : t -> [`BaseException] Obj.t val with_traceback : tb:Py.Object.t -> [> tag] Obj.t -> Py.Object.t (** Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self. *) (** Print the object to a human-readable representation. *) val to_string : t -> string (** Print the object to a human-readable representation. *) val show : t -> string (** Pretty-print the object to a formatter. *) val pp : Format.formatter -> t -> unit [@@ocaml.toplevel_printer] end module Codata : sig (** Get an attribute of this module as a Py.Object.t. This is useful to pass a Python function to another function. *) val get_py : string -> Py.Object.t val find : ?sub:string -> ?disp:bool -> unit -> [`ArrayLike|`Ndarray|`Object] Np.Obj.t option (** Return list of physical_constant keys containing a given string. Parameters ---------- sub : str, unicode Sub-string to search keys for. By default, return all keys. disp : bool If True, print the keys that are found and return None. Otherwise, return the list of keys without printing anything. Returns ------- keys : list or None If `disp` is False, the list of keys is returned. Otherwise, None is returned. Examples -------- >>> from scipy.constants import find, physical_constants Which keys in the ``physical_constants`` dictionary contain 'boltzmann'? >>> find('boltzmann') ['Boltzmann constant', 'Boltzmann constant in Hz/K', 'Boltzmann constant in eV/K', 'Boltzmann constant in inverse meter per kelvin', 'Stefan-Boltzmann constant'] Get the constant called 'Boltzmann constant in Hz/K': >>> physical_constants['Boltzmann constant in Hz/K'] (20836619120.0, 'Hz K^-1', 0.0) Find constants with 'radius' in the key: >>> find('radius') ['Bohr radius', 'classical electron radius', 'deuteron rms charge radius', 'proton rms charge radius'] >>> physical_constants['classical electron radius'] (2.8179403262e-15, 'm', 1.3e-24) *) val parse_constants_2002to2014 : Py.Object.t -> Py.Object.t (** None *) val parse_constants_2018toXXXX : Py.Object.t -> Py.Object.t (** None *) val precision : [`Python_string of Py.Object.t | `S of string] -> float (** Relative precision in physical_constants indexed by key Parameters ---------- key : Python string or unicode Key in dictionary `physical_constants` Returns ------- prec : float Relative precision in `physical_constants` corresponding to `key` Examples -------- >>> from scipy import constants >>> constants.precision(u'proton mass') 5.1e-37 *) val sqrt : Py.Object.t -> Py.Object.t (** Return the square root of x. *) val unit : [`Python_string of Py.Object.t | `S of string] -> Py.Object.t (** Unit in physical_constants indexed by key Parameters ---------- key : Python string or unicode Key in dictionary `physical_constants` Returns ------- unit : Python string Unit in `physical_constants` corresponding to `key` Examples -------- >>> from scipy import constants >>> constants.unit(u'proton mass') 'kg' *) val value : [`Python_string of Py.Object.t | `S of string] -> float (** Value in physical_constants indexed by key Parameters ---------- key : Python string or unicode Key in dictionary `physical_constants` Returns ------- value : float Value in `physical_constants` corresponding to `key` Examples -------- >>> from scipy import constants >>> constants.value(u'elementary charge') 1.602176634e-19 *) end module Constants : sig (** Get an attribute of this module as a Py.Object.t. This is useful to pass a Python function to another function. *) val get_py : string -> Py.Object.t val convert_temperature : val_:[>`Ndarray] Np.Obj.t -> old_scale:string -> new_scale:string -> unit -> Py.Object.t (** Convert from a temperature scale to another one among Celsius, Kelvin, Fahrenheit, and Rankine scales. Parameters ---------- val : array_like Value(s) of the temperature(s) to be converted expressed in the original scale. old_scale: str Specifies as a string the original scale from which the temperature value(s) will be converted. Supported scales are Celsius ('Celsius', 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'), Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine ('Rankine', 'rankine', 'R', 'r'). new_scale: str Specifies as a string the new scale to which the temperature value(s) will be converted. Supported scales are Celsius ('Celsius', 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'), Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine ('Rankine', 'rankine', 'R', 'r'). Returns ------- res : float or array of floats Value(s) of the converted temperature(s) expressed in the new scale. Notes ----- .. versionadded:: 0.18.0 Examples -------- >>> from scipy.constants import convert_temperature >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin') array([ 233.15, 313.15]) *) val lambda2nu : [>`Ndarray] Np.Obj.t -> Py.Object.t (** Convert wavelength to optical frequency Parameters ---------- lambda_ : array_like Wavelength(s) to be converted. Returns ------- nu : float or array of floats Equivalent optical frequency. Notes ----- Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the (vacuum) speed of light in meters/second. Examples -------- >>> from scipy.constants import lambda2nu, speed_of_light >>> lambda2nu(np.array((1, speed_of_light))) array([ 2.99792458e+08, 1.00000000e+00]) *) val nu2lambda : [>`Ndarray] Np.Obj.t -> Py.Object.t (** Convert optical frequency to wavelength. Parameters ---------- nu : array_like Optical frequency to be converted. Returns ------- lambda : float or array of floats Equivalent wavelength(s). Notes ----- Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the (vacuum) speed of light in meters/second. Examples -------- >>> from scipy.constants import nu2lambda, speed_of_light >>> nu2lambda(np.array((1, speed_of_light))) array([ 2.99792458e+08, 1.00000000e+00]) *) end val convert_temperature : val_:[>`Ndarray] Np.Obj.t -> old_scale:string -> new_scale:string -> unit -> Py.Object.t (** Convert from a temperature scale to another one among Celsius, Kelvin, Fahrenheit, and Rankine scales. Parameters ---------- val : array_like Value(s) of the temperature(s) to be converted expressed in the original scale. old_scale: str Specifies as a string the original scale from which the temperature value(s) will be converted. Supported scales are Celsius ('Celsius', 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'), Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine ('Rankine', 'rankine', 'R', 'r'). new_scale: str Specifies as a string the new scale to which the temperature value(s) will be converted. Supported scales are Celsius ('Celsius', 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'), Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine ('Rankine', 'rankine', 'R', 'r'). Returns ------- res : float or array of floats Value(s) of the converted temperature(s) expressed in the new scale. Notes ----- .. versionadded:: 0.18.0 Examples -------- >>> from scipy.constants import convert_temperature >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin') array([ 233.15, 313.15]) *) val find : ?sub:string -> ?disp:bool -> unit -> [`ArrayLike|`Ndarray|`Object] Np.Obj.t option (** Return list of physical_constant keys containing a given string. Parameters ---------- sub : str, unicode Sub-string to search keys for. By default, return all keys. disp : bool If True, print the keys that are found and return None. Otherwise, return the list of keys without printing anything. Returns ------- keys : list or None If `disp` is False, the list of keys is returned. Otherwise, None is returned. Examples -------- >>> from scipy.constants import find, physical_constants Which keys in the ``physical_constants`` dictionary contain 'boltzmann'? >>> find('boltzmann') ['Boltzmann constant', 'Boltzmann constant in Hz/K', 'Boltzmann constant in eV/K', 'Boltzmann constant in inverse meter per kelvin', 'Stefan-Boltzmann constant'] Get the constant called 'Boltzmann constant in Hz/K': >>> physical_constants['Boltzmann constant in Hz/K'] (20836619120.0, 'Hz K^-1', 0.0) Find constants with 'radius' in the key: >>> find('radius') ['Bohr radius', 'classical electron radius', 'deuteron rms charge radius', 'proton rms charge radius'] >>> physical_constants['classical electron radius'] (2.8179403262e-15, 'm', 1.3e-24) *) val lambda2nu : [>`Ndarray] Np.Obj.t -> Py.Object.t (** Convert wavelength to optical frequency Parameters ---------- lambda_ : array_like Wavelength(s) to be converted. Returns ------- nu : float or array of floats Equivalent optical frequency. Notes ----- Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the (vacuum) speed of light in meters/second. Examples -------- >>> from scipy.constants import lambda2nu, speed_of_light >>> lambda2nu(np.array((1, speed_of_light))) array([ 2.99792458e+08, 1.00000000e+00]) *) val nu2lambda : [>`Ndarray] Np.Obj.t -> Py.Object.t (** Convert optical frequency to wavelength. Parameters ---------- nu : array_like Optical frequency to be converted. Returns ------- lambda : float or array of floats Equivalent wavelength(s). Notes ----- Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the (vacuum) speed of light in meters/second. Examples -------- >>> from scipy.constants import nu2lambda, speed_of_light >>> nu2lambda(np.array((1, speed_of_light))) array([ 2.99792458e+08, 1.00000000e+00]) *) val precision : [`Python_string of Py.Object.t | `S of string] -> float (** Relative precision in physical_constants indexed by key Parameters ---------- key : Python string or unicode Key in dictionary `physical_constants` Returns ------- prec : float Relative precision in `physical_constants` corresponding to `key` Examples -------- >>> from scipy import constants >>> constants.precision(u'proton mass') 5.1e-37 *) val unit : [`Python_string of Py.Object.t | `S of string] -> Py.Object.t (** Unit in physical_constants indexed by key Parameters ---------- key : Python string or unicode Key in dictionary `physical_constants` Returns ------- unit : Python string Unit in `physical_constants` corresponding to `key` Examples -------- >>> from scipy import constants >>> constants.unit(u'proton mass') 'kg' *) val value : [`Python_string of Py.Object.t | `S of string] -> float (** Value in physical_constants indexed by key Parameters ---------- key : Python string or unicode Key in dictionary `physical_constants` Returns ------- value : float Value in `physical_constants` corresponding to `key` Examples -------- >>> from scipy import constants >>> constants.value(u'elementary charge') 1.602176634e-19 *)
(** Get an attribute of this module as a Py.Object.t. This is useful to pass a Python function to another function. *)
Xlang.mli
(* eXtended languages: everything from Lang.t + spacegrep (generic) and regex. *) type t = (* For "real" semgrep. The first language is used to parse the pattern and targets. The other languages are extra target languages that can use the same pattern. *) | L of Lang.t * Lang.t list (* for pattern-regex (referred as 'regex' or 'none' in languages:) *) | LRegex (* for spacegrep *) | LGeneric [@@deriving show, eq] exception InternalInvalidLanguage of string (* rule id *) * string (* msg *) val of_lang : Lang.t -> t (* raises an exception with error message *) val to_lang_exn : t -> Lang.t (* Does not raise, but returns empty list for all but the L variant *) val to_langs : t -> Lang.t list (* raises an exception with error message *) val lang_of_opt_xlang_exn : t option -> Lang.t (* Convert an object that represent a pattern's multiple languages into the list of target languages of the form 'L (lang, [])'. *) val flatten : t -> t list (* map from valid extended language names to unique xlang ID *) val assoc : (string * t) list (* efficient map from valid extended language names to unique xlang ID *) val map : (string, t) Hashtbl.t (* list of valid names for extended languages, sorted alphabetically *) val keys : string list (* comma-separated list of the supported languages *) val supported_xlangs : string (* Convert from a string or raise an exception with an error message. TODO: explain the 'id' option *) val of_string : ?id:string option -> string -> t val to_string : t -> string
(* eXtended languages: everything from Lang.t + spacegrep (generic) and regex. *)
server_connection.ml
module IOVec = Httpaf.IOVec module Server_handshake = Gluten.Server type state = | Handshake of Server_handshake.t | Websocket of Websocket_connection.t type input_handlers = Websocket_connection.input_handlers = { frame : opcode:Websocket.Opcode.t -> is_fin:bool -> len:int -> Payload.t -> unit ; eof : unit -> unit } type error = Websocket_connection.error type error_handler = Websocket_connection.error_handler type t = { mutable state: state ; websocket_handler: Wsd.t -> input_handlers } let is_closed t = match t.state with | Handshake handshake -> Server_handshake.is_closed handshake | Websocket websocket -> Websocket_connection.is_closed websocket let create ~sha1 ?error_handler websocket_handler = let rec upgrade_handler upgrade () = let t = Lazy.force t in let ws_connection = Websocket_connection.create ~mode:`Server ?error_handler websocket_handler in t.state <- Websocket ws_connection; upgrade (Gluten.make (module Websocket_connection) ws_connection); and request_handler { Gluten.reqd; upgrade } = let error msg = let response = Httpaf.(Response.create ~headers:(Headers.of_list ["Connection", "close"]) `Bad_request) in Httpaf.Reqd.respond_with_string reqd response msg in let ret = Httpaf.Reqd.try_with reqd (fun () -> match Handshake.respond_with_upgrade ~sha1 reqd (upgrade_handler upgrade) with | Ok () -> () | Error msg -> error msg) in match ret with | Ok () -> () | Error exn -> error (Printexc.to_string exn) and t = lazy { state = Handshake (Server_handshake.create_upgradable ~protocol:(module Httpaf.Server_connection) ~create: (Httpaf.Server_connection.create ?config:None ?error_handler:None) request_handler) ; websocket_handler } in Lazy.force t let create_websocket ?error_handler websocket_handler = { state = Websocket (Websocket_connection.create ~mode:`Server ?error_handler websocket_handler) ; websocket_handler } let shutdown t = match t.state with | Handshake handshake -> Server_handshake.shutdown handshake | Websocket websocket -> Websocket_connection.shutdown websocket ;; let report_exn t exn = match t.state with | Handshake _ -> (* TODO: we need to handle this properly. There was an error in the upgrade *) assert false | Websocket websocket -> Websocket_connection.report_exn websocket exn let next_read_operation t = match t.state with | Handshake handshake -> Server_handshake.next_read_operation handshake | Websocket websocket -> Websocket_connection.next_read_operation websocket ;; let read t bs ~off ~len = match t.state with | Handshake handshake -> Server_handshake.read handshake bs ~off ~len | Websocket websocket -> Websocket_connection.read websocket bs ~off ~len ;; let read_eof t bs ~off ~len = match t.state with | Handshake handshake -> Server_handshake.read_eof handshake bs ~off ~len | Websocket websocket -> Websocket_connection.read_eof websocket bs ~off ~len ;; let yield_reader t f = match t.state with | Handshake handshake -> Server_handshake.yield_reader handshake f | Websocket _ -> assert false let next_write_operation t = match t.state with | Handshake handshake -> Server_handshake.next_write_operation handshake | Websocket websocket -> Websocket_connection.next_write_operation websocket ;; let report_write_result t result = match t.state with | Handshake handshake -> Server_handshake.report_write_result handshake result | Websocket websocket -> Websocket_connection.report_write_result websocket result ;; let yield_writer t f = match t.state with | Handshake handshake -> Server_handshake.yield_writer handshake f | Websocket websocket -> Websocket_connection.yield_writer websocket f ;;
common.mli
module StrSet : Set.S with type elt = string module State : sig type t val loadpath : t -> Loadpath.State.t end (** [init args] Init coqdep, setting arguments from [args]. *) val init : make_separator_hack:bool -> Args.t -> State.t (** [treat_file_command_line file] Add an input file to be considered *) val treat_file_command_line : string -> unit val sort : State.t -> unit val compute_deps : State.t -> Dep_info.t list
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) (* v * Copyright INRIA, CNRS and contributors *) (* <O___,, * (see version control and CREDITS file for authors & dates) *) (* \VV/ **************************************************************) (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (* * (see LICENSE file for the text of the license) *) (************************************************************************)
vacopy.c
#include <stdarg.h> #include <string.h> void _vacopy(va_list *pap, va_list ap) { *pap = ap; }
t-get_str.c
#include <string.h> #include "ca.h" int main() { slong iter; flint_rand_t state; flint_printf("get_str..."); fflush(stdout); flint_randinit(state); for (iter = 0; iter < 1000 * calcium_test_multiplier(); iter++) { ca_ctx_t ctx; ca_t x; char * s; slong slen; ca_ctx_init(ctx); ca_init(x, ctx); /* just check that it doesn't crash */ ca_randtest_special(x, state, 10, 100, ctx); s = ca_get_str(x, ctx); slen = strlen(s); slen = slen; flint_free(s); ca_clear(x, ctx); ca_ctx_clear(ctx); } flint_randclear(state); flint_cleanup(); flint_printf("PASS\n"); return EXIT_SUCCESS; }
/* Copyright (C) 2020 Fredrik Johansson This file is part of Calcium. Calcium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */
arg_helper.ml
let fatal err = prerr_endline err; exit 2 module Make (S : sig module Key : sig type t val of_string : string -> t module Map : Map.S with type key = t end module Value : sig type t val of_string : string -> t end end) = struct type parsed = { base_default : S.Value.t; base_override : S.Value.t S.Key.Map.t; user_default : S.Value.t option; user_override : S.Value.t S.Key.Map.t; } let default v = { base_default = v; base_override = S.Key.Map.empty; user_default = None; user_override = S.Key.Map.empty; } let set_base_default value t = { t with base_default = value } let add_base_override key value t = { t with base_override = S.Key.Map.add key value t.base_override } let reset_base_overrides t = { t with base_override = S.Key.Map.empty } let set_user_default value t = { t with user_default = Some value } let add_user_override key value t = { t with user_override = S.Key.Map.add key value t.user_override } exception Parse_failure of exn let parse_exn str ~update = (* Is the removal of empty chunks really relevant here? *) (* (It has been added to mimic the old Misc.String.split.) *) let values = String.split_on_char ',' str |> List.filter ((<>) "") in let parsed = List.fold_left (fun acc value -> match String.index value '=' with | exception Not_found -> begin match S.Value.of_string value with | value -> set_user_default value acc | exception exn -> raise (Parse_failure exn) end | equals -> let key_value_pair = value in let length = String.length key_value_pair in assert (equals >= 0 && equals < length); if equals = 0 then begin raise (Parse_failure ( Failure "Missing key in argument specification")) end; let key = let key = String.sub key_value_pair 0 equals in try S.Key.of_string key with exn -> raise (Parse_failure exn) in let value = let value = String.sub key_value_pair (equals + 1) (length - equals - 1) in try S.Value.of_string value with exn -> raise (Parse_failure exn) in add_user_override key value acc) !update values in update := parsed let parse str help_text update = match parse_exn str ~update with | () -> () | exception (Parse_failure exn) -> fatal (Printf.sprintf "%s: %s" (Printexc.to_string exn) help_text) type parse_result = | Ok | Parse_failed of exn let parse_no_error str update = match parse_exn str ~update with | () -> Ok | exception (Parse_failure exn) -> Parse_failed exn let get ~key parsed = match S.Key.Map.find key parsed.user_override with | value -> value | exception Not_found -> match parsed.user_default with | Some value -> value | None -> match S.Key.Map.find key parsed.base_override with | value -> value | exception Not_found -> parsed.base_default end
(**************************************************************************) (* *) (* OCaml *) (* *) (* Pierre Chambart, OCamlPro *) (* Mark Shinwell and Leo White, Jane Street Europe *) (* *) (* Copyright 2015--2016 OCamlPro SAS *) (* Copyright 2015--2016 Jane Street Group LLC *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
dune
(library (public_name cplugin.ml_plugin_b) (name ml_plugin_b) (flags :standard -rectypes) (libraries ml_plugin_a))
ppextend.mli
open Constrexpr (** {6 Pretty-print. } *) type ppbox = | PpHB | PpHOVB of int | PpHVB of int | PpVB of int type ppcut = | PpBrk of int * int | PpFnl val ppcmd_of_box : ppbox -> Pp.t -> Pp.t val ppcmd_of_cut : ppcut -> Pp.t (** {6 Printing rules for notations} *) type pattern_quote_style = QuotedPattern | NotQuotedPattern (** Declare and look for the printing rule for symbolic notations *) type unparsing = | UnpMetaVar of entry_relative_level * Extend.side option | UnpBinderMetaVar of entry_relative_level * pattern_quote_style | UnpListMetaVar of entry_relative_level * unparsing list * Extend.side option | UnpBinderListMetaVar of bool * unparsing list | UnpTerminal of string | UnpBox of ppbox * unparsing Loc.located list | UnpCut of ppcut type unparsing_rule = unparsing list val unparsing_eq : unparsing -> unparsing -> bool type notation_printing_rules = { notation_printing_unparsing : unparsing_rule; notation_printing_level : entry_level; } type generic_notation_printing_rules = { notation_printing_reserved : bool; notation_printing_rules : notation_printing_rules; } val declare_generic_notation_printing_rules : notation -> generic_notation_printing_rules -> unit val declare_specific_notation_printing_rules : specific_notation -> notation_printing_rules -> unit val has_generic_notation_printing_rule : notation -> bool val find_generic_notation_printing_rule : notation -> generic_notation_printing_rules val find_specific_notation_printing_rule : specific_notation -> notation_printing_rules val find_notation_printing_rule : notation_with_optional_scope option -> notation -> notation_printing_rules
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) (* v * Copyright INRIA, CNRS and contributors *) (* <O___,, * (see version control and CREDITS file for authors & dates) *) (* \VV/ **************************************************************) (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (* * (see LICENSE file for the text of the license) *) (************************************************************************)
uucp_cmap.ml
(* Binary tree uchar maps. *) type 'a tree = | Empty | C of int * 'a | Cn of 'a tree * 'a tree * int * 'a type 'a t = { default : 'a; tree : 'a tree } let get m cp = let rec loop cp = function | Cn (l, r, i, v) -> if cp < i then loop cp l else if cp > i then loop cp r else v | C (i, v) -> if cp = i then v else m.default | Empty -> m.default in loop cp m.tree let of_sorted_list default l = (* perfect balance. *) let rec loop len l = if len = 1 then match l with | `C (i, v) :: r -> C (i, v), r | _ -> assert false else let len_ll = len / 2 in let len_rl = len - len_ll in let ltree, rlist = loop len_ll l in match rlist with | [] -> ltree, [] | `C (i, v) :: r -> if len_rl = 1 then Cn (ltree, Empty, i, v), r else let rtree, rlist = loop (len_rl - 1) r in Cn (ltree, rtree, i, v), rlist in let keep acc (`C (_, v) as p) = if v <> default then p :: acc else acc in let l = List.rev (List.fold_left keep [] l) in let len = List.length l in let tree = if len = 0 then Empty else fst (loop len l) in { default; tree } let height m = let rec loop = function | Empty -> 0 | C _ -> 1 | Cn (l, r, _, _) -> 1 + max (loop l) (loop r) in loop m.tree let word_size v_size m = (* value sharing not taken into account. *) let rec loop = function | Empty -> 0 | C (_, v) -> 3 + v_size v | Cn (l, r, _, v) -> 5 + loop l + loop r + v_size v in loop m.tree let rec dump pp_v ppf m = let open Uucp_fmt in let rec dump_tree ppf = function | Cn (l, r, i, v) -> pf ppf "@[<4>Cn(%a,@,%a,@,0x%04X,@,%a)@]" dump_tree l dump_tree r i pp_v v | C (i, v) -> pf ppf "@[<3>C(0x%04X,@,%a)@]" i pp_v v | Empty -> pf ppf "Empty" in record ["default", pp_v; "tree", dump_tree] ppf m.default m.tree (*--------------------------------------------------------------------------- Copyright (c) 2014 The uucp programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
(*--------------------------------------------------------------------------- Copyright (c) 2014 The uucp programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. ---------------------------------------------------------------------------*)
dune
(mdx (files README.md) (deps (package pkg2)) (packages pkg))
vec_SDCZ.h
#include <math.h> #include "lacaml_macros.h" /* fill_vec */ CAMLprim value LFUN(fill_vec_stub)( intnat vN, intnat vOFSX, intnat vINCX, value vX, vNUMBER vA) { CAMLparam1(vX); integer GET_INT(N), GET_INT(INCX); NUMBER A; VEC_PARAMS(X); NUMBER *start, *last; INIT_NUMBER(A); caml_enter_blocking_section(); /* Allow other threads */ if (INCX == 1) /* NOTE: may improve SIMD optimization */ for (int i = 0; i < N; i++) X_data[i] = A; else { if (INCX > 0) { start = X_data; last = start + N*INCX; } else { start = X_data - (N - 1)*INCX; last = X_data + INCX; }; while (start != last) { *start = A; start += INCX; } } caml_leave_blocking_section(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value LFUN(fill_vec_stub_bc)( value vN, value vOFSX, value vINCX, value vX, value vA) { return LFUN(fill_vec_stub)( Int_val(vN), Int_val(vOFSX), Int_val(vINCX), vX, NUMBER_val(vA)); } /* add_const_vec */ CAMLprim value LFUN(add_const_vec_stub)( vNUMBER vC, intnat vN, intnat vOFSY, intnat vINCY, value vY, intnat vOFSX, intnat vINCX, value vX) { CAMLparam2(vX, vY); NUMBER C; integer GET_INT(N), GET_INT(INCX), GET_INT(INCY); VEC_PARAMS(X); VEC_PARAMS(Y); NUMBER *start_src, *last_src, *dst; INIT_NUMBER(C); caml_enter_blocking_section(); /* Allow other threads */ if (INCX == 1 && INCY == 1) /* NOTE: may improve SIMD optimization */ for (int i = 0; i < N; i++) { NUMBER src = X_data[i]; Y_data[i] = ADD_NUMBER(src, C); } else { if (INCX > 0) { start_src = X_data; last_src = start_src + N*INCX; } else { start_src = X_data - (N - 1)*INCX; last_src = X_data + INCX; }; if (INCY > 0) dst = Y_data; else dst = Y_data - (N - 1)*INCY; while (start_src != last_src) { NUMBER src = *start_src; *dst = ADD_NUMBER(src, C); start_src += INCX; dst += INCY; } } caml_leave_blocking_section(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value LFUN(add_const_vec_stub_bc)(value *argv, int __unused argn) { return LFUN(add_const_vec_stub)( NUMBER_val(argv[0]), Int_val(argv[1]), Int_val(argv[2]), Int_val(argv[3]), argv[4], Int_val(argv[5]), Int_val(argv[6]), argv[7]); }
/* File: vec_SDCZ.h Copyright (C) 2013- Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
stop_after_parsing_intf.mli
(* TEST * setup-ocamlc.byte-build-env ** ocamlc.byte flags = "-stop-after parsing -dparsetree" ocamlc_byte_exit_status = "0" *** check-ocamlc.byte-output *) (* we intentionally write ill-typed output; if `-stop-after parsing` was not supported properly, the test would fail with an error *) val x : Module_that_does_not_exists.type_that_does_not_exists
(* TEST * setup-ocamlc.byte-build-env ** ocamlc.byte flags = "-stop-after parsing -dparsetree" ocamlc_byte_exit_status = "0" *** check-ocamlc.byte-output *)
protocol_client_context.ml
module Lifted_protocol = struct include Protocol.Environment.Lift (Protocol) let hash = Protocol.hash end module Alpha_block_services = Block_services.Make (Lifted_protocol) (Lifted_protocol) (** Client RPC context *) class type rpc_context = object inherit RPC_context.json inherit [Shell_services.chain * Shell_services.block] Protocol.Environment .RPC_context .simple end class wrap_rpc_context (t : RPC_context.json) : rpc_context = object method base : Uri.t = t#base method generic_json_call = t#generic_json_call method call_service : 'm 'p 'q 'i 'o. (([< Resto.meth] as 'm), unit, 'p, 'q, 'i, 'o) RPC_service.t -> 'p -> 'q -> 'i -> 'o tzresult Lwt.t = t#call_service method call_streamed_service : 'm 'p 'q 'i 'o. (([< Resto.meth] as 'm), unit, 'p, 'q, 'i, 'o) RPC_service.t -> on_chunk:('o -> unit) -> on_close:(unit -> unit) -> 'p -> 'q -> 'i -> (unit -> unit) tzresult Lwt.t = t#call_streamed_service inherit [Shell_services.chain, Shell_services.block] Protocol.Environment .proto_rpc_context (t :> RPC_context.t) Shell_services.Blocks.path end class type full = object inherit Client_context.full inherit [Shell_services.chain * Shell_services.block] Protocol.Environment .RPC_context .simple inherit [Shell_services.chain, Shell_services.block] Protocol.Environment .proto_rpc_context end class wrap_full (t : Client_context.full) : full = object inherit Client_context.proxy_context t inherit [Shell_services.chain, Shell_services.block] Protocol.Environment .proto_rpc_context (t :> RPC_context.t) Shell_services.Blocks.path end let register_error_kind category ~id ~title ~description ?pp encoding from_error to_error = let id = "client." ^ Protocol.name ^ "." ^ id in register_error_kind category ~id ~title ~description ?pp encoding from_error to_error let () = let open Data_encoding.Registration in let open Data_encoding in let stamp_proto id ids = String.concat "." (Protocol.name :: id :: ids) in register @@ def (stamp_proto "parameters" []) Protocol.Parameters_repr.encoding ; register ~pp:Protocol.Alpha_context.Tez.pp @@ def (stamp_proto "tez" []) Protocol.Alpha_context.Tez.encoding ; register @@ def (stamp_proto "roll" []) Protocol.Alpha_context.Roll.encoding ; register ~pp:Protocol.Alpha_context.Fitness.pp @@ def (stamp_proto "fitness" []) Protocol.Alpha_context.Fitness.encoding ; register ~pp:Protocol.Alpha_context.Timestamp.pp @@ def (stamp_proto "timestamp" []) Protocol.Alpha_context.Timestamp.encoding ; register ~pp:Protocol.Alpha_context.Raw_level.pp @@ def (stamp_proto "raw_level" []) Protocol.Alpha_context.Raw_level.encoding ; register @@ def (stamp_proto "vote" ["ballot"]) Protocol.Alpha_context.Vote.ballot_encoding ; register @@ def (stamp_proto "vote" ["ballots"]) Protocol.Alpha_context.Vote.ballots_encoding ; register @@ def (stamp_proto "vote" ["listings"]) Protocol.Alpha_context.Vote.listings_encoding ; register @@ def (stamp_proto "seed" []) Protocol.Alpha_context.Seed.seed_encoding ; register ~pp:Protocol.Alpha_context.Gas.pp @@ def (stamp_proto "gas" []) Protocol.Alpha_context.Gas.encoding ; register ~pp:Protocol.Alpha_context.Gas.pp_cost @@ def (stamp_proto "gas" ["cost"]) Protocol.Alpha_context.Gas.cost_encoding ; register @@ def (stamp_proto "script" []) Protocol.Alpha_context.Script.encoding ; register @@ def (stamp_proto "script" ["expr"]) Protocol.Alpha_context.Script.expr_encoding ; register @@ def (stamp_proto "script" ["prim"]) Protocol.Alpha_context.Script.prim_encoding ; register @@ def (stamp_proto "script" ["lazy_expr"]) Protocol.Alpha_context.Script.lazy_expr_encoding ; register @@ def (stamp_proto "script" ["loc"]) Protocol.Alpha_context.Script.location_encoding ; register ~pp:Protocol.Alpha_context.Contract.pp @@ def (stamp_proto "contract" []) Protocol.Alpha_context.Contract.encoding ; register @@ def (stamp_proto "contract" ["big_map_diff"]) Protocol.Alpha_context.Contract.big_map_diff_encoding ; register @@ def (stamp_proto "delegate" ["frozen_balance"]) Protocol.Alpha_context.Delegate.frozen_balance_encoding ; register @@ def (stamp_proto "delegate" ["balance_updates"]) Protocol.Alpha_context.Delegate.balance_updates_encoding ; register @@ def (stamp_proto "delegate" ["frozen_balance_by_cycles"]) Protocol.Alpha_context.Delegate.frozen_balance_by_cycle_encoding ; register ~pp:Protocol.Alpha_context.Level.pp_full @@ def (stamp_proto "level" []) Protocol.Alpha_context.Level.encoding ; register @@ def (stamp_proto "operation" []) Protocol.Alpha_context.Operation.encoding ; register @@ def (stamp_proto "operation" ["contents"]) Protocol.Alpha_context.Operation.contents_encoding ; register @@ def (stamp_proto "operation" ["contents_list"]) Protocol.Alpha_context.Operation.contents_list_encoding ; register @@ def (stamp_proto "operation" ["protocol_data"]) Protocol.Alpha_context.Operation.protocol_data_encoding ; register @@ def (stamp_proto "operation" ["raw"]) Protocol.Alpha_context.Operation.raw_encoding ; register @@ def (stamp_proto "operation" ["internal"]) Protocol.Alpha_context.Operation.internal_operation_encoding ; register @@ def (stamp_proto "operation" ["unsigned"]) Protocol.Alpha_context.Operation.unsigned_encoding ; register ~pp:Protocol.Alpha_context.Period.pp @@ def (stamp_proto "period" []) Protocol.Alpha_context.Period.encoding ; register ~pp:Protocol.Alpha_context.Cycle.pp @@ def (stamp_proto "cycle" []) Protocol.Alpha_context.Cycle.encoding ; register @@ def (stamp_proto "constants" []) Protocol.Alpha_context.Constants.encoding ; register @@ def (stamp_proto "constants" ["fixed"]) Protocol.Alpha_context.Constants.fixed_encoding ; register @@ def (stamp_proto "constants" ["parametric"]) Protocol.Alpha_context.Constants.parametric_encoding ; register @@ def (stamp_proto "nonce" []) Protocol.Alpha_context.Nonce.encoding ; register @@ def (stamp_proto "block_header" []) Protocol.Alpha_context.Block_header.encoding ; register @@ def (stamp_proto "block_header" ["unsigned"]) Protocol.Alpha_context.Block_header.unsigned_encoding ; register @@ def (stamp_proto "block_header" ["raw"]) Protocol.Alpha_context.Block_header.raw_encoding ; register @@ def (stamp_proto "block_header" ["contents"]) Protocol.Alpha_context.Block_header.contents_encoding ; register @@ def (stamp_proto "block_header" ["shell_header"]) Protocol.Alpha_context.Block_header.shell_header_encoding ; register @@ def (stamp_proto "block_header" ["protocol_data"]) Protocol.Alpha_context.Block_header.protocol_data_encoding ; register ~pp:Protocol.Alpha_context.Voting_period.pp @@ def (stamp_proto "voting_period" []) Protocol.Alpha_context.Voting_period.encoding ; register @@ def (stamp_proto "voting_period" ["kind"]) Protocol.Alpha_context.Voting_period.kind_encoding ; register @@ Data_encoding.def (stamp_proto "errors" []) ~description: "The full list of RPC errors would be too long to include.It is\n\ available through the RPC `/errors` (GET)." error_encoding
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
broken_invariants.ml
(* TEST files="illegal_ppx.ml" * setup-ocamlc.byte-build-env ** ocamlc.byte with ocamlcommon all_modules="illegal_ppx.ml" program="ppx.exe" *** toplevel all_modules="broken_invariants.ml" flags="-ppx '${ocamlrun} ${test_build_directory_prefix}/ocamlc.byte/ppx.exe'" *) let empty_tuple = [%tuple];; let empty_record = [%record];; let empty_apply = [%no_args f];; let f = function [%record_with_functor_fields] -> ();; [%%empty_let];; [%%empty_type];;
(* TEST files="illegal_ppx.ml" * setup-ocamlc.byte-build-env ** ocamlc.byte with ocamlcommon all_modules="illegal_ppx.ml" program="ppx.exe" *** toplevel all_modules="broken_invariants.ml" flags="-ppx '${ocamlrun} ${test_build_directory_prefix}/ocamlc.byte/ppx.exe'" *)
round_repr.ml
type round = int32 type t = round module Map = Map.Make (Int32) include (Compare.Int32 : Compare.S with type t := t) let zero = 0l let succ n = if Compare.Int32.equal n Int32.max_int then invalid_arg "round_repr.succ: cannot apply succ to maximum round value" else Int32.succ n let pp fmt i = Format.fprintf fmt "%ld" i type error += Negative_round of int type error += Round_overflow of int let () = let open Data_encoding in register_error_kind `Permanent ~id:"negative_round" ~title:"Negative round" ~description:"Round cannot be built out of negative integers." ~pp:(fun ppf i -> Format.fprintf ppf "Negative round cannot be built out of negative integers (%Ld)" i) (obj1 (req "Negative_round" int64)) (function Negative_round i -> Some (Int64.of_int i) | _ -> None) (fun i -> Negative_round (Int64.to_int i)) ; register_error_kind `Permanent ~id:"round_overflow" ~title:"Round overflow" ~description: "Round cannot be built out of integer greater than maximum int32 value." ~pp:(fun ppf i -> Format.fprintf ppf "Round cannot be built out of integer greater than maximum int32 value \ (%Ld)" i) (obj1 (req "Negative_round" int64)) (function Round_overflow i -> Some (Int64.of_int i) | _ -> None) (fun i -> Round_overflow (Int64.to_int i)) let of_int32 i = if i >= 0l then Ok i else error (Negative_round (Int32.to_int i)) [@@inline] let pred r = let p = Int32.pred r in of_int32 p let of_int i = if Compare.Int.(i < 0) then error (Negative_round i) else (* i is positive *) let i32 = Int32.of_int i in if Compare.Int.(Int32.to_int i32 = i) then Ok i32 else error (Round_overflow i) let to_int i32 = let i = Int32.to_int i32 in if Int32.(equal (of_int i) i32) then ok i else error (Round_overflow i) let to_int32 t = t [@@inline] let to_slot round ~committee_size = to_int round >>? fun r -> let slot = r mod committee_size in Slot_repr.of_int slot let encoding = Data_encoding.conv_with_guard (fun i -> i) (fun i -> match of_int32 i with | Ok _ as res -> res | Error _ -> Error "Round_repr.encoding: negative round") Data_encoding.int32 module Durations = struct type t = { first_round_duration : Period_repr.t; delay_increment_per_round : Period_repr.t; } type error += | Non_increasing_rounds of {increment : Period_repr.t} | Round_durations_must_be_at_least_one_second of {round : Period_repr.t} let () = register_error_kind `Permanent ~id:"durations.non_increasing_rounds" ~title:"Non increasing round" ~description:"The provided rounds are not increasing." ~pp:(fun ppf increment -> Format.fprintf ppf "The provided rounds are not increasing (increment: %a)" Period_repr.pp increment) Data_encoding.(obj1 (req "increment" Period_repr.encoding)) (function | Non_increasing_rounds {increment} -> Some increment | _ -> None) (fun increment -> Non_increasing_rounds {increment}) let pp fmt t = Format.fprintf fmt "%a,@ +%a" Period_repr.pp t.first_round_duration Period_repr.pp t.delay_increment_per_round let create ~first_round_duration ~delay_increment_per_round = error_when Compare.Int64.(Period_repr.to_seconds first_round_duration < 1L) (Round_durations_must_be_at_least_one_second {round = first_round_duration}) >>? fun () -> error_when Compare.Int64.(Period_repr.to_seconds delay_increment_per_round < 1L) (Non_increasing_rounds {increment = delay_increment_per_round}) >>? fun () -> ok {first_round_duration; delay_increment_per_round} let create_opt ~first_round_duration ~delay_increment_per_round = match create ~first_round_duration ~delay_increment_per_round with | Ok v -> Some v | Error _ -> None let encoding = let open Data_encoding in conv_with_guard (fun {first_round_duration; delay_increment_per_round} -> (first_round_duration, delay_increment_per_round)) (fun (first_round_duration, delay_increment_per_round) -> match create_opt ~first_round_duration ~delay_increment_per_round with | None -> Error "Either round durations are non-increasing or minimal block \ delay < 1" | Some rounds -> Ok rounds) (obj2 (req "first_round_duration" Period_repr.encoding) (req "delay_increment_per_round" Period_repr.encoding)) let round_duration {first_round_duration; delay_increment_per_round} round = if Compare.Int32.(round < 0l) then invalid_arg "round must be a non-negative integer" else let first_round_duration_s = Period_repr.to_seconds first_round_duration and delay_increment_per_round_s = Period_repr.to_seconds delay_increment_per_round in Period_repr.of_seconds_exn Int64.( add first_round_duration_s (mul (of_int32 round) delay_increment_per_round_s)) end type error += Round_too_high of int32 let () = let open Data_encoding in register_error_kind `Permanent ~id:"round_too_high" ~title:"round too high" ~description:"block round too high." ~pp:(fun ppf round -> Format.fprintf ppf "Block round is too high: %ld" round) (obj1 (req "level_offset_too_high" int32)) (function Round_too_high round -> Some round | _ -> None) (fun round -> Round_too_high round) (* The duration of round n follows the arithmetic sequence: round_duration(0) = first_round_duration round_duration(r+1) = round_duration(r) + delay_increment_per_round Hence, this sequence can be explicited into: round_duration(r) = first_round_duration + r * delay_increment_per_round The level offset of round r is the sum of the durations of the rounds up until round r - 1. In other words, when r > 0 raw_level_offset_of_round(0) = 0 raw_level_offset_of_round(r+1) = raw_level_offset_of_round(r) + round_duration(r) Hence raw_level_offset_of_round(r) = Σ_{k=0}^{r-1} (round_duration(k)) After unfolding the series, the same function can be finally explicited into raw_level_offset_of_round(0) = 0 raw_level_offset_of_round(r) = r * first_round_duration + 1/2 * r * (r - 1) * delay_increment_per_round *) let raw_level_offset_of_round round_durations ~round = if Compare.Int32.(round = zero) then ok Int64.zero else let sum_durations = let Durations.{first_round_duration; delay_increment_per_round} = round_durations in let roundz = Int64.of_int32 round in let m = Z.of_int64 Int64.(div (mul roundz (pred roundz)) (of_int 2)) in Z.( add (mul m (Z.of_int64 @@ Period_repr.to_seconds delay_increment_per_round)) (mul (Z.of_int32 round) (Z.of_int64 @@ Period_repr.to_seconds first_round_duration))) in if Compare.Z.(sum_durations > Z.of_int64 Int64.max_int) then error (Round_too_high round) else ok (Z.to_int64 sum_durations) type error += Level_offset_too_high of Period_repr.t let () = let open Data_encoding in register_error_kind `Permanent ~id:"level_offset_too_high" ~title:"level offset too high" ~description:"The block's level offset is too high." ~pp:(fun ppf offset -> Format.fprintf ppf "The block's level offset is too high: %a" Period_repr.pp offset) (obj1 (req "level_offset_too_high" Period_repr.encoding)) (function Level_offset_too_high offset -> Some offset | _ -> None) (fun offset -> Level_offset_too_high offset) type round_and_offset = {round : int32; offset : Period_repr.t} (** Complexity: O(log level_offset). *) let round_and_offset round_durations ~level_offset = let level_offset_in_seconds = Period_repr.to_seconds level_offset in (* We set the bound as 2^53 to prevent overflows when computing the variable [discr] for reasonable values of [first_round_duration] and [delay_increment_per_round]. This bound is derived by a rough approximation from the inequation [discr] < Int64.max_int. *) let overflow_bound = Int64.shift_right Int64.max_int 10 in if Compare.Int64.(overflow_bound < level_offset_in_seconds) then error (Level_offset_too_high level_offset) else let Durations.{first_round_duration; delay_increment_per_round} = round_durations in let first_round_duration = Period_repr.to_seconds first_round_duration in let delay_increment_per_round = Period_repr.to_seconds delay_increment_per_round in (* If [level_offset] is lower than the first round duration, then the solution straightforward. *) if Compare.Int64.(level_offset_in_seconds < first_round_duration) then ok {round = 0l; offset = level_offset} else let round = if Compare.Int64.(delay_increment_per_round = Int64.zero) then (* Case when delay_increment_per_round is zero and a simple linear solution exists. *) Int64.div level_offset_in_seconds first_round_duration else (* Case when the increment is non-negative and we look for the quadratic solution. *) let pow_2 n = Int64.mul n n in let double n = Int64.shift_left n 1 in let times_8 n = Int64.shift_left n 3 in let half n = Int64.shift_right n 1 in (* The integer square root is implemented using the Newton-Raphson method. For any integer N, the convergence within the neighborhood of √N is ensured within log2 (N) steps. *) let sqrt (n : int64) = let x0 = ref (half n) in if Compare.Int64.(!x0 > 1L) then ( let x1 = ref (half (Int64.add !x0 (Int64.div n !x0))) in while Compare.Int64.(!x1 < !x0) do x0 := !x1 ; x1 := half (Int64.add !x0 (Int64.div n !x0)) done ; !x0) else n in (* The idea is to solve the following equation in [round] and use its integer value: Σ_{k=0}^{round-1} round_duration(k) = level_offset After unfolding the sum and expanding terms, we obtain a quadratic equation: delay_increment_per_round × round² + (2 first_round_duration - delay_increment_per_round) × round - 2 level_offset = 0 From there, we compute the discriminant and the solution of the equation. Refer to https://gitlab.com/tezos/tezos/-/merge_requests/4009 for more explanations. *) let discr = Int64.add (pow_2 (Int64.sub (double first_round_duration) delay_increment_per_round)) (times_8 (Int64.mul delay_increment_per_round level_offset_in_seconds)) in Int64.div (Int64.add (Int64.sub delay_increment_per_round (double first_round_duration)) (sqrt discr)) (double delay_increment_per_round) in raw_level_offset_of_round round_durations ~round:(Int64.to_int32 round) >>? fun current_level_offset -> ok { round = Int64.to_int32 round; offset = Period_repr.of_seconds_exn (Int64.sub (Period_repr.to_seconds level_offset) current_level_offset); } (** Complexity: O(|round_durations|). *) let timestamp_of_round round_durations ~predecessor_timestamp ~predecessor_round ~round = let pred_round_duration = Durations.round_duration round_durations predecessor_round in (* First, the function computes when the current level l is supposed to start. This is given by adding to the timestamp of the round of predecessor level l-1 [predecessor_timestamp], the duration of its last round [predecessor_round]. *) Time_repr.(predecessor_timestamp +? pred_round_duration) >>? fun start_of_current_level -> (* Finally, we sum the durations of the rounds at the current level l until reaching current [round]. *) raw_level_offset_of_round round_durations ~round >>? fun level_offset -> let level_offset = Period_repr.of_seconds_exn level_offset in Time_repr.(start_of_current_level +? level_offset) (** Unlike [timestamp_of_round], this function gets the starting time of a given round, given the timestamp and the round of a proposal at the same level. We compute the starting time of [considered_round] from a given [round_durations] description, some [current_round], and its starting time [current_timestamp]. Complexity: O(|round_durations|). *) let timestamp_of_another_round_same_level round_durations ~current_timestamp ~current_round ~considered_round = raw_level_offset_of_round round_durations ~round:considered_round >>? fun target_offset -> raw_level_offset_of_round round_durations ~round:current_round >>? fun current_offset -> ok @@ Time_repr.of_seconds Int64.( add (sub (Time_repr.to_seconds current_timestamp) current_offset) target_offset) type error += | Round_of_past_timestamp of { provided_timestamp : Time.t; predecessor_timestamp : Time.t; predecessor_round : t; } let () = let open Data_encoding in register_error_kind `Permanent ~id:"round_of_past_timestamp" ~title:"Round_of_timestamp for past timestamp" ~description:"Provided timestamp is before the expected level start." ~pp:(fun ppf (provided_ts, predecessor_ts, round) -> Format.fprintf ppf "Provided timestamp (%a) is before the expected level start (computed \ based on predecessor_ts %a at round %a)." Time.pp_hum provided_ts Time.pp_hum predecessor_ts pp round) (obj3 (req "provided_timestamp" Time.encoding) (req "predecessor_timestamp" Time.encoding) (req "predecessor_round" encoding)) (function | Round_of_past_timestamp {provided_timestamp; predecessor_timestamp; predecessor_round} -> Some (provided_timestamp, predecessor_timestamp, predecessor_round) | _ -> None) (fun (provided_timestamp, predecessor_timestamp, predecessor_round) -> Round_of_past_timestamp {provided_timestamp; predecessor_timestamp; predecessor_round}) let round_of_timestamp round_durations ~predecessor_timestamp ~predecessor_round ~timestamp = let round_duration = Durations.round_duration round_durations predecessor_round in Time_repr.(predecessor_timestamp +? round_duration) >>? fun start_of_current_level -> Period_repr.of_seconds (Time_repr.diff timestamp start_of_current_level) |> Error_monad.record_trace (Round_of_past_timestamp { predecessor_timestamp; provided_timestamp = timestamp; predecessor_round; }) >>? fun diff -> round_and_offset round_durations ~level_offset:diff >>? fun round_and_offset -> ok round_and_offset.round let level_offset_of_round round_durations ~round = raw_level_offset_of_round round_durations ~round >>? fun offset -> ok (Period_repr.of_seconds_exn offset) module Internals_for_test = struct type round_and_offset_raw = {round : round; offset : Period_repr.t} let round_and_offset round_durations ~level_offset = round_and_offset round_durations ~level_offset >|? fun v -> {round = v.round; offset = v.offset} end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
program.mli
open Definitions (** {2 Transformations} *) val map_exprs : f:('expr1 -> 'expr2 boxed) -> varf:('expr1 Var.t -> 'expr2 Var.t) -> 'expr1 program -> 'expr2 program Bindlib.box val get_scope_body : (([< dcalc | lcalc ], _) gexpr as 'e) program -> ScopeName.t -> 'e scope_body val untype : (([< dcalc | lcalc ] as 'a), 'm mark) gexpr program -> ('a, untyped mark) gexpr program val to_expr : (([< dcalc | lcalc ], _) gexpr as 'e) program -> ScopeName.t -> 'e boxed (** Usage: [build_whole_program_expr program main_scope] builds an expression corresponding to the main program and returning the main scope as a function. *)
(* This file is part of the Catala compiler, a specification language for tax and social benefits computation rules. Copyright (C) 2020-2022 Inria, contributor: Denis Merigoux <denis.merigoux@inria.fr>, Alain Delaët-Tixeuil <alain.delaet--tixeuil@inria.fr>, Louis Gesbert <louis.gesbert@inria.fr> 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 http://www.apache.org/licenses/LICENSE-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. *)
hash.ml
(** Secure hashes. *) class type digest_context = object method update : string -> unit (** Return the final digest as an ASCII string. The context cannot be used after this. *) method to_hex : string (** Return the final digest as a binary string. The context cannot be used after this. *) method to_bin : string end (* Implementation using the "sha" package *) module type DIGEST = sig type ctx type t val init: unit -> ctx val update_string : ctx -> string -> unit val finalize : ctx -> t val to_bin : t -> string val to_hex : t -> string end let make_context (module D : DIGEST) = let ctx = D.init () in object method update data = D.update_string ctx data method to_bin = D.finalize ctx |> D.to_bin method to_hex = D.finalize ctx |> D.to_hex end let create = function | "sha1" -> make_context (module Sha1) | "sha256" -> make_context (module Sha256) | x -> Safe_exn.failf "Unknown digest type '%s'" x let hex_digest ctx = ctx#to_hex let update ctx = ctx#update let base32_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" (** Return the digest as a base-32-encoded ASCII string (with no padding characters) *) let b32_digest ctx = let raw_digest = ctx#to_bin in let str_digest = Bytes.create ((String.length raw_digest * 8 + 4) / 5) in let in_byte = ref 0 in let in_bit = ref 3 in for i = 0 to Bytes.length str_digest - 1 do (* Read next five bits from raw_digest *) let vl = if !in_byte = String.length raw_digest then 0 else Char.code raw_digest.[!in_byte] lsr !in_bit in let vh = if !in_bit > 3 then ( Char.code raw_digest.[!in_byte - 1] lsl (8 - !in_bit) ) else 0 in Bytes.set str_digest i (base32_chars.[(vl lor vh) land 31]); if !in_bit >= 5 then in_bit := !in_bit - 5 else ( in_bit := !in_bit + 3; incr in_byte ) done; Bytes.unsafe_to_string str_digest (** Read until the end of the channel, adding each byte to the digest. *) let update_from_channel ctx ch = let buf = Bytes.create 4096 in let rec read () = match input ch buf 0 (Bytes.length buf) with | 0 -> () | n -> let data = Bytes.sub buf 0 n |> Bytes.unsafe_to_string in ctx#update data; read () in read ()
(* Copyright (C) 2013, Thomas Leonard * See the README file for details, or visit http://0install.net. *)
lwt_backend.ml
module Scheduler = Hkt.Make_sched (struct type +'a t = 'a Lwt.t end) let lwt = let open Scheduler in let open Lwt.Infix in Sigs. { bind = (fun x f -> inj (prj x >>= fun x -> prj (f x))); return = (fun x -> inj (Lwt.return x)); } module Flow = Unixiz.Make (Mimic) let lwt_io = let open Scheduler in Sigs. { recv = (fun flow raw -> inj (Flow.recv flow raw)); send = (fun flow raw -> inj (Flow.send flow raw)); pp_error = Flow.pp_error; } let lwt_fail exn = Scheduler.inj (Lwt.fail exn)
dune
(executable (libraries graphql-lwt alcotest lwt.unix yojson) (name lwt_test)) (alias (name runtest) (package graphql-lwt) (deps (:test lwt_test.exe)) (action (run %{test})))
digestif_native.ml
module By = Digestif_by module Bi = Digestif_bi type off = int type size = int type ba = Bi.t type st = By.t type ctx = By.t let dup : ctx -> ctx = By.copy module MD5 = struct type kind = [ `MD5 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_md5_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_md5_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_md5_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_md5_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_md5_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_md5_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_md5_ctx_size" [@@noalloc] end module SHA1 = struct type kind = [ `SHA1 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha1_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha1_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha1_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha1_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha1_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha1_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha1_ctx_size" [@@noalloc] end module SHA224 = struct type kind = [ `SHA224 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha224_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha224_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha224_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha224_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha224_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha224_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha224_ctx_size" [@@noalloc] end module SHA256 = struct type kind = [ `SHA256 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha256_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha256_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha256_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha256_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha256_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha256_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha256_ctx_size" [@@noalloc] end module SHA384 = struct type kind = [ `SHA384 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha384_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha384_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha384_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha384_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha384_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha384_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha384_ctx_size" [@@noalloc] end module SHA512 = struct type kind = [ `SHA512 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha512_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha512_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha512_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha512_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha512_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha512_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha512_ctx_size" [@@noalloc] end module SHA3_224 = struct type kind = [ `SHA3_224 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha3_224_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha3_224_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha3_224_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha3_224_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha3_224_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha3_224_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha3_224_ctx_size" [@@noalloc] end module SHA3_256 = struct type kind = [ `SHA3_256 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha3_256_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha3_256_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha3_256_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha3_256_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha3_256_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha3_256_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha3_256_ctx_size" [@@noalloc] end module KECCAK_256 = struct type kind = [ `KECCAK_256 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha3_256_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha3_256_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_keccak_256_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha3_256_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha3_256_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_keccak_256_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha3_256_ctx_size" [@@noalloc] end module SHA3_384 = struct type kind = [ `SHA3_384 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha3_384_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha3_384_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha3_384_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha3_384_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha3_384_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha3_384_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha3_384_ctx_size" [@@noalloc] end module SHA3_512 = struct type kind = [ `SHA3_512 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_sha3_512_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_sha3_512_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_sha3_512_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_sha3_512_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_sha3_512_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_sha3_512_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_sha3_512_ctx_size" [@@noalloc] end module WHIRLPOOL = struct type kind = [ `WHIRLPOOL ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_whirlpool_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_whirlpool_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_whirlpool_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_whirlpool_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_whirlpool_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_whirlpool_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_whirlpool_ctx_size" [@@noalloc] end module BLAKE2B = struct type kind = [ `BLAKE2B ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_blake2b_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_blake2b_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_blake2b_ba_finalize" [@@noalloc] external with_outlen_and_key : ctx -> size -> ba -> off -> size -> unit = "caml_digestif_blake2b_ba_init_with_outlen_and_key" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_blake2b_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_blake2b_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_blake2b_st_finalize" [@@noalloc] external with_outlen_and_key : ctx -> size -> st -> off -> size -> unit = "caml_digestif_blake2b_st_init_with_outlen_and_key" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_blake2b_ctx_size" [@@noalloc] external key_size : unit -> int = "caml_digestif_blake2b_key_size" [@@noalloc] external max_outlen : unit -> int = "caml_digestif_blake2b_max_outlen" [@@noalloc] external digest_size : ctx -> int = "caml_digestif_blake2b_digest_size" [@@noalloc] end module BLAKE2S = struct type kind = [ `BLAKE2S ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_blake2s_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_blake2s_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_blake2s_ba_finalize" [@@noalloc] external with_outlen_and_key : ctx -> size -> ba -> off -> size -> unit = "caml_digestif_blake2s_ba_init_with_outlen_and_key" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_blake2s_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_blake2s_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_blake2s_st_finalize" [@@noalloc] external with_outlen_and_key : ctx -> size -> st -> off -> size -> unit = "caml_digestif_blake2s_st_init_with_outlen_and_key" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_blake2s_ctx_size" [@@noalloc] external key_size : unit -> int = "caml_digestif_blake2s_key_size" [@@noalloc] external max_outlen : unit -> int = "caml_digestif_blake2s_max_outlen" [@@noalloc] external digest_size : ctx -> int = "caml_digestif_blake2s_digest_size" [@@noalloc] end module RMD160 = struct type kind = [ `RMD160 ] module Bigstring = struct external init : ctx -> unit = "caml_digestif_rmd160_ba_init" [@@noalloc] external update : ctx -> ba -> off -> size -> unit = "caml_digestif_rmd160_ba_update" external finalize : ctx -> ba -> off -> unit = "caml_digestif_rmd160_ba_finalize" [@@noalloc] end module Bytes = struct external init : ctx -> unit = "caml_digestif_rmd160_st_init" [@@noalloc] external update : ctx -> st -> off -> size -> unit = "caml_digestif_rmd160_st_update" [@@noalloc] external finalize : ctx -> st -> off -> unit = "caml_digestif_rmd160_st_finalize" [@@noalloc] end external ctx_size : unit -> int = "caml_digestif_rmd160_ctx_size" [@@noalloc] end let imin (a : int) (b : int) = if a < b then a else b module XOR = struct module Bigstring = struct external xor_into : ba -> off -> ba -> off -> size -> unit = "caml_digestif_ba_xor_into" [@@noalloc] let xor_into a b n = if n > imin (Bi.length a) (Bi.length b) then raise (Invalid_argument "Native.Bigstring.xor_into: buffers to small") else xor_into a 0 b 0 n let xor a b = let l = imin (Bi.length a) (Bi.length b) in let r = Bi.copy (Bi.sub b 0 l) in xor_into a r l ; r end module Bytes = struct external xor_into : st -> off -> st -> off -> size -> unit = "caml_digestif_st_xor_into" [@@noalloc] let xor_into a b n = if n > imin (By.length a) (By.length b) then raise (Invalid_argument "Native.Bigstring.xor_into: buffers to small") else xor_into a 0 b 0 n let xor a b = let l = imin (By.length a) (By.length b) in let r = By.copy (By.sub b 0 l) in xor_into a r l ; r end end
(* Copyright (c) 2014-2016 David Kaloper Meršinjak Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
test_level_module.ml
(** Testing ------- Component: Protocol (baking) Invocation: dune exec src/proto_alpha/lib_protocol/test/unit/main.exe \ -- test "^\[Unit\] level module$" Subject: some functions in the Level module *) open Protocol let test_create_cycle_eras () = let empty_cycle_eras = Level_repr.create_cycle_eras [] |> Environment.wrap_tzresult in Assert.proto_error_with_info ~loc:__LOC__ empty_cycle_eras "Invalid cycle eras" >>=? fun () -> let increasing_first_levels = [ Level_repr. { first_level = Raw_level_repr.of_int32_exn 1l; first_cycle = Cycle_repr.succ Cycle_repr.root; blocks_per_cycle = 8l; blocks_per_commitment = 2l; }; { first_level = Raw_level_repr.of_int32_exn 9l; first_cycle = Cycle_repr.root; blocks_per_cycle = 8l; blocks_per_commitment = 2l; }; ] |> Level_repr.create_cycle_eras |> Environment.wrap_tzresult in Assert.proto_error_with_info ~loc:__LOC__ increasing_first_levels "Invalid cycle eras" >>=? fun () -> let increasing_first_cycles = [ Level_repr. { first_level = Raw_level_repr.of_int32_exn 9l; first_cycle = Cycle_repr.root; blocks_per_cycle = 8l; blocks_per_commitment = 2l; }; { first_level = Raw_level_repr.of_int32_exn 1l; first_cycle = Cycle_repr.succ Cycle_repr.root; blocks_per_cycle = 8l; blocks_per_commitment = 2l; }; ] |> Level_repr.create_cycle_eras |> Environment.wrap_tzresult in Assert.proto_error_with_info ~loc:__LOC__ increasing_first_cycles "Invalid cycle eras" let test_case_1 = ( [ Level_repr. { first_level = Raw_level_repr.of_int32_exn 1l; first_cycle = Cycle_repr.root; blocks_per_cycle = 8l; blocks_per_commitment = 2l; }; ], [ (1, (1, 0, 0, 0, false)); (2, (2, 1, 0, 1, true)); (3, (3, 2, 0, 2, false)); (8, (8, 7, 0, 7, true)); (9, (9, 8, 1, 0, false)); (16, (16, 15, 1, 7, true)); (17, (17, 16, 2, 0, false)); (64, (64, 63, 7, 7, true)); (65, (65, 64, 8, 0, false)); ] ) let test_case_2 = ( List.rev [ Level_repr. { first_level = Raw_level_repr.of_int32_exn 1l; first_cycle = Cycle_repr.root; blocks_per_cycle = 8l; blocks_per_commitment = 2l; }; { first_level = Raw_level_repr.of_int32_exn 17l; first_cycle = Cycle_repr.of_int32_exn 2l; blocks_per_cycle = 16l; blocks_per_commitment = 4l; }; ], [ (1, (1, 0, 0, 0, false)); (2, (2, 1, 0, 1, true)); (3, (3, 2, 0, 2, false)); (8, (8, 7, 0, 7, true)); (9, (9, 8, 1, 0, false)); (16, (16, 15, 1, 7, true)); (17, (17, 16, 2, 0, false)); (32, (32, 31, 2, 15, true)); (33, (33, 32, 3, 0, false)); (64, (64, 63, 4, 15, true)); (65, (65, 64, 5, 0, false)); ] ) let test_case_3 = ( List.rev [ Level_repr. { first_level = Raw_level_repr.of_int32_exn 1l; first_cycle = Cycle_repr.root; blocks_per_cycle = 8l; blocks_per_commitment = 2l; }; { first_level = Raw_level_repr.of_int32_exn 17l; first_cycle = Cycle_repr.of_int32_exn 2l; blocks_per_cycle = 16l; blocks_per_commitment = 4l; }; { first_level = Raw_level_repr.of_int32_exn 49l; first_cycle = Cycle_repr.of_int32_exn 4l; blocks_per_cycle = 6l; blocks_per_commitment = 3l; }; ], [ (1, (1, 0, 0, 0, false)); (2, (2, 1, 0, 1, true)); (3, (3, 2, 0, 2, false)); (8, (8, 7, 0, 7, true)); (9, (9, 8, 1, 0, false)); (16, (16, 15, 1, 7, true)); (17, (17, 16, 2, 0, false)); (32, (32, 31, 2, 15, true)); (33, (33, 32, 3, 0, false)); (48, (48, 47, 3, 15, true)); (49, (49, 48, 4, 0, false)); (64, (64, 63, 6, 3, false)); (65, (65, 64, 6, 4, false)); (66, (66, 65, 6, 5, true)); (67, (67, 66, 7, 0, false)); ] ) let test_level_from_raw () = List.iter_es (fun (cycle_eras, test_cases) -> List.iter_es (fun ( input_level, ( level, level_position, cycle, cycle_position, expected_commitment ) ) -> let raw_level = Raw_level_repr.of_int32_exn (Int32.of_int input_level) in Level_repr.create_cycle_eras cycle_eras |> Environment.wrap_tzresult >>?= fun cycle_eras -> let level_from_raw = Protocol.Level_repr.level_from_raw ~cycle_eras raw_level in Assert.equal_int ~loc:__LOC__ (Int32.to_int (Raw_level_repr.to_int32 level_from_raw.level)) level >>=? fun () -> Assert.equal_int ~loc:__LOC__ (Int32.to_int level_from_raw.level_position) level_position >>=? fun () -> Assert.equal_int ~loc:__LOC__ (Int32.to_int (Cycle_repr.to_int32 level_from_raw.cycle)) cycle >>=? fun () -> Assert.equal_int ~loc:__LOC__ (Int32.to_int level_from_raw.cycle_position) cycle_position >>=? fun () -> Assert.equal_bool ~loc:__LOC__ level_from_raw.expected_commitment expected_commitment >>=? fun () -> let offset = Int32.neg (Int32.add Int32.one (Int32.of_int input_level)) in let res = Level_repr.level_from_raw_with_offset ~cycle_eras ~offset raw_level in Assert.proto_error ~loc:__LOC__ (Environment.wrap_tzresult res) (fun err -> let error_info = Error_monad.find_info_of_error (Environment.wrap_tzerror err) in error_info.title = "Negative sum of level and offset")) test_cases) [test_case_1; test_case_2; test_case_3] let test_first_level_in_cycle () = let cycle_eras = fst test_case_3 in let test_cases = (* cycle, level *) [ (0l, 1); (1l, 9); (2l, 17); (3l, 33); (4l, 49); (5l, 55); (6l, 61); (7l, 67); ] in let f (input_cycle, level) = Level_repr.create_cycle_eras cycle_eras |> Environment.wrap_tzresult >>?= fun cycle_eras -> let input_cycle = Cycle_repr.of_int32_exn input_cycle in let level_res = Level_repr.first_level_in_cycle_from_eras ~cycle_eras input_cycle in Assert.equal_int ~loc:__LOC__ (Int32.to_int (Raw_level_repr.to_int32 level_res.level)) level in List.iter_es f test_cases let tests = [ Tztest.tztest "create_cycle_eras" `Quick test_create_cycle_eras; Tztest.tztest "level_from_raw" `Quick test_level_from_raw; Tztest.tztest "first_level_in_cycle" `Quick test_first_level_in_cycle; ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
lmdb.mli
(** High level bindings for LMDB. *) (** The {{:http://www.lmdb.tech/doc/}LMDB} database is a fast in-file key-value store that supports ACID transactions. These bindings attempt to expose a typesafe yet low-overhead API. First, an environment must be opened using {!Env.create}: {[let env = Env.(create Rw ~flags:Flags.no_subdir "mydb") ]} Now the data file [mydb] and lock file [mydb-lock] have been created in the current directory. One environment may contain multiple named and one unnamed key-value stores. They are called {e databases} in the {{:http://www.lmdb.tech/doc/starting.html}LMDB documentation}, but called {e maps} in these OCaml bindings. A single [('key, 'value, [< `Read | `Write], [< `Dup | `Uni ])] {!type: Map.t} is a key-value store mapping OCaml values of type ['key] to values of type ['value]. Multiple values per key are supported on request. Using {!Map}, we can open the unnamed map and add our first value: {[ let map = Map.open_existing Nodup ~key:Conv.string ~value:Conv.string env in Map.add map "Bactrian camel" "Elegant and beautiful animal with two humps." ]} {{!Txn}Transactions} and {{!Cursor}Iterators} are also available. *) (** {2 Raw bindings} *) module Mdb = Lmdb_bindings (** {2 Permissions} *) (** This library uses [[< `Read | `Write ]] phantom types to encode the read/write permissions of transactions and cursors. The following values are used to request read-only or read-write permissions on environments, transactions and cursors. *) type 'a perm = | Ro : [ `Read ] perm | Rw : [ `Read | `Write ] perm (** {2 Database} *) (** Collection of maps stored in a single memory-mapped file. *) module Env : sig type t module Flags = Mdb.EnvFlags (** [create perm path] creates an environment with {!Ro} or {!Rw} permissions with {e data} and {e lock} files in the already existing directory [path]. If no separate directory is desired, {!Flags.no_subdir} can be passed. The returned handle is not garbage collected and should be closed explicitely to free locks and prevent corruption on async environments. @param map_size Size of the memory map. Limited by the virtual address space. @param max_readers Maximum number of threads/reader slots. @param max_maps Maximum number of named maps. @param mode The UNIX permissions to set on created files and semaphores. Default is [0o644]. *) val create : _ perm -> ?max_readers:int -> ?map_size:int -> ?max_maps:int -> ?flags:Flags.t -> ?mode:int -> string -> t val sync : ?force:bool -> t -> unit val close: t -> unit val copy : ?compact:bool -> t -> string -> unit val copyfd : ?compact:bool -> t -> Unix.file_descr -> unit val set_flags : t -> Flags.t -> bool -> unit val flags : t -> Flags.t val set_map_size : t -> int -> unit val path : t -> string val fd : t -> Unix.file_descr val stat : t -> Mdb.stat val info : t -> Mdb.envinfo val max_readers : t -> int val max_keysize : t -> int val reader_list : t -> string list val reader_check : t -> int end (** Series of operations on an environment performed atomically. *) module Txn : sig (** A transaction handle. A transaction may be read-only or read-write. *) type -'perm t constraint 'perm = [< `Read | `Write ] (** [go perm env f] runs a transaction with [perm] read/write permissions in [env]. The function [f txn] will receive the transaction handle. All changes to the environment [env] done using the transaction handle will be persisted to the environment only when [f] returns. After [f] returned, the transaction handle is invalid and should therefore not be leaked outside [f]. @return [None] if the transaction was aborted with [abort], and [Some _] otherwise. @param txn Create a child transaction to [txn]. This is not supported on an [env] with {!Env.Flags.write_map}. Here is an example incrementing a value atomically: {[ go rw env begin fun txn -> let v = Map.get ~txn k in Map.add ~txn k (v+1) ; v end ]} *) val go : 'perm perm -> ?txn:'perm t -> Env.t -> ('perm t -> 'a) -> 'a option (** [abort txn] aborts transaction [txn] and the current [go] function, which will return [None]. *) val abort : _ t -> _ val env : 'perm t -> Env.t (** [env txn] returns the environment of [txn] *) end (** Converters to and from the internal representation of keys and values. A converter contains serialising and deserialising functions as well as the flags applied when the converter is used in a map. *) module Conv : sig (** {2 Types } *) type 'a t type bigstring = (char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t (** Bigstrings are used to transfer the raw serialised data into and out of the database. They may point directly to a memory-mapped region of the database file. *) (** Flags describing the (sorting) properties of keys and values of a map. See the LMDB documentation for the meaning of these flags. You probably won't need those flags since the converters provided in {!Conv} will already make appropriate use of these flags. *) module Flags = Lmdb_bindings.DbiFlags (** {2 Constructor and accessors} *) val make : ?flags:Flags.t -> serialise:((int -> bigstring) -> 'a -> bigstring) -> deserialise:(bigstring -> 'a) -> unit -> 'a t (** [make ~serialise ~deserialise] creates a converter from a serialising and a deserialising function @param serialise [serialise alloc x] {e may} call [alloc len] {e once} to allocate a [bigstring] of size [len]. It then {e must} fill the serialised data of [x] into this [bigstring] and return {e exactly this} bigstring. If [serialise] didn't call [alloc] it may return any [bigstring]. [alloc] may return uninitialised memory. It is therefore recommended that [serialise] overwrites all allocated memory to avoid leaking possibly sensitive memory content into the database. If [serialise] calls [alloc] the library may utilise the [MDB_RESERVE] interface when appropriate to avoid calls to [malloc] and [memcpy]. @param deserialise The passed {!bigstring} is only valid as long as the current transaction. It is therefore strongly recommended not to leak it out of [deserialise]. @param flags Flags to be set on a map using this converter. Depending on the use of a converter as {e key} or {e value} {!Map.create} and {!Map.open_existing} will select the correct set of flags: [_key] flags will be used for keys and [_dup] flags will be used for values on maps supporting duplicates. *) val serialise : 'a t -> (int -> bigstring) -> 'a -> bigstring val deserialise : 'a t -> bigstring -> 'a val flags : _ t -> Flags.t (** {2 Predefined converters } *) (** {3 Strings } *) val bigstring :bigstring t (** The [bigstring] converter returns bigstrings as returned by the lmdb backend. These bigstrings point into the environment memory-map and are therefore only guaranteed to be valid until the transaction ends. If you need longer-lived values then use the [string] converter, make a copy or write a custom converter. *) val string :string t (** The [string] converter simply copies the raw database content from / to OCaml strings. *) (** {3 Integers } *) (** The integer converters will make use of {! Flags.t} as appropriate so that integers are sorted in ascending order irrespective of machine endianness. *) val int32_be :Int32.t t val int64_be :Int64.t t val int32_le :Int32.t t val int64_le :Int64.t t (** For convenience, the [_as_int] converters convert the internal integer representation to and from [int]. @raise Invalid_argument [Invalid_argument "Lmdb: Integer out of bounds"] *) val int32_be_as_int :int t val int64_be_as_int :int t val int32_le_as_int :int t val int64_le_as_int :int t end (** Key-value maps. *) module Map : sig (** A handle for a map from keys of type ['key] to values of type ['value]. The map may support only a single value per key ([[ `Dup ]]) or multiple values per key ([[ `Dup | `Uni ]]). *) type ('key, 'value, -'dup) t constraint 'perm = [< `Read | `Write ] constraint 'dup = [< `Dup | `Uni ] type 'a card = | Nodup : [ `Uni ] card | Dup : [ `Dup | `Uni ] card (** [create dup ~key ~value env] open (and possibly create) a map in the environment [env]. [dup] may be {!Dup} or {!Nodup}, specifying whether the map supports multiple values per key. Only a single transaction may call this function at a time. This transaction needs to finish before any other transaction may call this function. @param name if omitted the unnamed map will be opened. Otherwise make sure that {! Env.create} was called with a large enough [~max_maps]. @param key Converter for keys @param value Converter for values @raise Invalid_argument if an existing map doesn't support duplicates, but duplicates where requested. *) val create : ([< `Dup | `Uni ] as 'dup) card -> key :'key Conv.t -> value :'value Conv.t -> ?txn :[> `Read | `Write ] Txn.t -> ?name :string -> Env.t -> ('key, 'value, 'dup) t (** [open_existing env] is like [create], but only opens already existing maps. @raise Not_found if the map doesn't exist. *) val open_existing : ([< `Dup | `Uni ] as 'dup) card -> key :'key Conv.t -> value :'value Conv.t -> ?txn :[> `Read ] Txn.t -> ?name :string -> Env.t -> ('key, 'value, 'dup) t (** [env map] returns the environment of [map]. *) val env : _ t -> Env.t (** [get map key] returns the first value associated to [key]. @raise Not_found if the key is not in the map. *) val get : ('key, 'value, _) t -> ?txn:[> `Read ] Txn.t -> 'key -> 'value module Flags = Lmdb_bindings.PutFlags (** [add map key value] adds [value] to [key]. For a map not supporting duplicates an existing value is overwritten. For a map supporting duplicates the value is added to the key. This is the same as [overwrite] for duplicate maps, but [overwrite ~flags:Flags.no_overwrite] for non-duplicate maps. @param flags {!Flags} @raise Exists on maps not supporting duplicates if the key already exists. @raise Exists if key is already bound to [value] and {! Map.Flags.no_dup_data} was passed. *) val add : ('key, 'value, _) t -> ?txn:[> `Write ] Txn.t -> ?flags:Flags.t -> 'key -> 'value -> unit (** [set map key value] sets binding of [key] to [value]. Values of an already existing key are silently overwritten. @param flags {!Flags} *) val set : ('key, 'value, _) t -> ?txn:[> `Write ] Txn.t -> ?flags:Flags.t -> 'key -> 'value -> unit (** [remove map key] removes [key] from [map]. @param value Only the specified value is removed. If not provided, all the values of [key] and [key] itself are removed. @raise Not_found if the key is not in the map. *) val remove : ('key, 'value, _) t -> ?txn:[> `Write ] Txn.t -> ?value:'value -> 'key -> unit (** {2 Misc} *) val stat : ?txn: [> `Read ] Txn.t -> ('key, 'value, _) t -> Mdb.stat (** [drop ?delete map] Empties [map]. @param delete If [true] [map] is also deleted from the environment and the handle [map] invalidated. *) val drop : ?txn: [> `Write ] Txn.t -> ?delete:bool -> ('key, 'value, _) t -> unit (** [compare_key map ?txn a b] Compares [a] and [b] as if they were keys in [map]. *) val compare_key : ('key, 'value, _) t -> ?txn:[> `Read ] Txn.t -> 'key -> 'key -> int (** [compare map ?txn a b] Same as [compare_key]. *) val compare : ('key, 'value, _) t -> ?txn:[> `Read ] Txn.t -> 'key -> 'key -> int (** [compare_val map ?txn a b] Compares [a] and [b] as if they were values in a [dup_sort] [map]. *) val compare_val : ('key, 'value, [> `Dup ]) t -> ?txn:[> `Read ] Txn.t -> 'value -> 'value -> int end (** Iterators over maps. *) module Cursor : sig (** A cursor allows to iterate manually on the map. Every cursor implicitely uses a transaction. *) (** A cursor inherits two phantom types: the [[< `Read | `Write ]] permissions from the transaction and the [[< `Dup | `Uni ]] support from the map. *) type ('key, 'value, -'perm, -'dup) t constraint 'perm = [< `Read | `Write ] constraint 'dup = [< `Dup | `Uni ] (** [go perm map ?txn f] makes a cursor in the transaction [txn] using the function [f cursor]. The function [f] will receive the [cursor]. A cursor can only be created and used inside a transaction. The cursor inherits the permissions of the transaction. The cursor should not be leaked outside of [f]. Here is an example that returns the first 5 elements of a [map]: {[ go ro map begin fun c -> let h = first c in let rec aux i = if i < 5 then next c :: aux (i+1) else [] in h :: aux 1 end ]} @param txn if omitted a transient transaction will implicitely be created before calling [f] and be committed after [f] returns. *) val go : 'perm perm -> ?txn:'perm Txn.t -> ('key, 'value, 'dup) Map.t -> (('key, 'value, 'perm, 'dup) t -> 'a) -> 'a (** {2 Modification} *) module Flags = Lmdb_bindings.PutFlags (** [add cursor key value] adds [value] to [key] and moves the cursor to its position. For a map not supporting duplicates an existing value is overwritten. For a map supporting duplicates the value is added to the key. This is the same as [overwrite] for duplicate maps, but [overwrite ~flags:Flags.no_overwrite] for non-duplicate maps. @param flags {!Flags} @raise Exists on maps not supporting duplicates if the key already exists. @raise Exists if [key] is already bound to [value] and {! Cursor.Flags.no_dup_data} was passed. *) val add : ('key, 'value, [> `Read | `Write ], _) t -> ?flags:Flags.t -> 'key -> 'value -> unit (** [set cursor key value] sets binding of [key] to [value]. and moves the cursor to its position. Values of an already existing key are silently overwritten. @param flags {!Flags} *) val set : ('key, 'value, _, _) t -> ?flags:Flags.t -> 'key -> 'value -> unit (** [replace cursor value] replace the current value by [value]. *) val replace : ('key, 'value, [> `Read | `Write ], _) t -> 'value -> unit (** [remove cursor] removes the current binding. @param all If [true] removes all values associated to the current key. Default is [false]. *) val remove : ?all:bool -> ('key, 'value, [> `Read | `Write ], _) t -> unit (** {2 Reading} *) (** [current cursor] returns key and value at the position of the cursor. *) val current : ('key, 'value, [> `Read ], _) t -> 'key * 'value (** [current_all cursor] moves the cursor to the {e last} value of the {e current} key. Returns key and all values of the current key. *) val current_all : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key * 'value array (** [count cursor] returns the number of values bound to the current key. *) val count : ('key, 'value, [> `Read ], [> `Dup ]) t -> int (** {3 Seeking} *) (** [get cursor key] moves the cursor to the {e first} value of [key]. *) val get : ('key, 'value, [> `Read ], _) t -> 'key -> 'value (** [get_all cursor key] moves the cursor to the {e last} value of [key]. Returns all values of [key]. *) val get_all : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key -> 'value array (** [seek cursor key] moves the cursor to the first value of [key]. *) val seek : ('key, 'value, [> `Read ], _) t -> 'key -> 'key * 'value (** [seek_all cursor key] moves the cursor to the {e last} value of [key]. Returns all values of [key]. *) val seek_all : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key -> 'key * 'value array (** [seek_range cursor key] moves the cursor to the {e first} value of the first key greater than or equal to [key]. *) val seek_range : ('key, 'value, [> `Read ], _) t -> 'key -> 'key * 'value (** [seek_range_all cursor key] moves the cursor to the {e last} value of the first key greater than or equal to [key]. Returns all values of this key. *) val seek_range_all : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key -> 'key * 'value array (** [seek_dup cursor key value] moves the cursor to [value] of [key]. *) val seek_dup : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key -> 'value -> unit (** [seek_range_dup cursor key value] moves the cursor to the first value greater than or equal to [value] of the first key greater than or equal to [key]. *) val seek_range_dup : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key -> 'value -> ('key * 'value) (** {3 Moving} *) (** {4 Moving over all key-value pairs } *) (** [first cursor] moves the cursor to the {e first} value of the first key. *) val first : ('key, 'value, [> `Read ], _) t -> 'key * 'value (** [last cursor] moves the cursor to the {e last} value of the last key. *) val last : ('key, 'value, [> `Read ], _) t -> 'key * 'value (** [next cursor] moves the cursor to the next key-value pair. This may be the {e next value} of the {e current key} or the {e first value} of the {e next key}. *) val next : ('key, 'value, [> `Read ], _) t -> 'key * 'value (** [prev cursor] moves the cursor to the previous key-value pair. This may be the {e previous value} of the {e current key} or the {e last value} of the {e previous key}. *) val prev : ('key, 'value, [> `Read ], _) t -> 'key * 'value (** {4 Moving to neighboring keys } *) (** [next_nodup cursor] moves the cursor to the {e first} value of the next key. *) val next_nodup : ('key, 'value, [> `Read ], _) t -> 'key * 'value (** [prev_nodup cursor] moves the cursor to the {e last} value of the previous key. *) val prev_nodup : ('key, 'value, [> `Read ], _) t -> 'key * 'value (** {4 Moving over duplicates of a single key } *) (** [first_dup cursor] moves the cursor to the first {e value} of the current key. *) val first_dup : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'value (** [last_dup cursor] moves the cursor to the last {e value} of the current key. *) val last_dup : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'value (** [next_dup cursor] moves the cursor to the next value of the current key. @raise Not_found if the cursor is already on the last value of the current key. *) val next_dup : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'value (** [prev_dup cursor] moves the cursor to the previous value of the current key. @raise Not_found if the cursor is already on the first value of the current key. *) val prev_dup : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'value (** {4 Moving over keys getting all duplicates } *) (** [first_all cursor] moves the cursor to the {e last} value of the first key. Returns all values of the first key. *) val first_all : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key * 'value array (** [last_all cursor] moves the cursor to the {e first} value of the last key. Returns all values of the {e last} key. *) val last_all : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key * 'value array (** [next_all cursor] moves the cursor to the {e last} value of the next key. Returns all values of the next key. *) val next_all : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key * 'value array (** [prev_all cursor] moves the cursor to the {e first} value of the previous key. Returns all values of the previous key. *) val prev_all : ('key, 'value, [> `Read ], [> `Dup ]) t -> 'key * 'value array (** {2 Convenient Iterators} *) (** Call [f] once for each key-value pair. Will call [f] multiple times with the same key for duplicates *) val iter : ?cursor:('key, 'value, [> `Read ], 'dup) t -> f:('key -> 'value -> unit) -> ('key, 'value, 'dup) Map.t -> unit val iter_rev : ?cursor:('key, 'value, [> `Read ] as 'perm, 'dup) t -> f:('key -> 'value -> unit) -> ('key, 'value, 'dup) Map.t -> unit val fold_left : ?cursor:('key, 'value, [> `Read ], 'dup) t -> f:('a -> 'key -> 'value -> 'a) -> 'a -> ('key, 'value, 'dup) Map.t -> 'a val fold_right : ?cursor:('key, 'value, [> `Read ], 'dup) t -> f:('key -> 'value -> 'a -> 'a) -> ('key, 'value, 'dup) Map.t -> 'a -> 'a (** Call [f] once for each key passing the key and {e all} associated values. *) val iter_all : ?cursor:('key, 'value, [> `Read ], 'dup) t -> f:('key -> 'value array -> unit) -> ('key, 'value, [> `Dup ] as 'dup) Map.t -> unit val iter_rev_all : ?cursor:('key, 'value, [> `Read ] as 'perm, 'dup) t -> f:('key -> 'value array -> unit) -> ('key, 'value, [> `Dup ] as 'dup) Map.t -> unit val fold_left_all : ?cursor:('key, 'value, [> `Read ], 'dup) t -> f:('a -> 'key -> 'value array -> 'a) -> 'a -> ('key, 'value, [> `Dup ] as 'dup) Map.t -> 'a val fold_right_all : ?cursor:('key, 'value, [> `Read ], 'dup) t -> f:('key -> 'value array -> 'a -> 'a) -> ('key, 'value, [> `Dup ] as 'dup) Map.t -> 'a -> 'a end (** {2 Error reporting} *) exception Exists (** Raised when adding an already existing key to a [`Uni] map or adding an an already existing value with {! Map.Flags.no_dup_data} to a key of a [`Dup] map. Also raised when trying to [add ~flags:Flags.append(_dup)] non-sorted data. *) exception Not_found (** Raised when searching for non-existing key *) exception Map_full (** Raised when memory map is full *) exception Error of int (** Other errors are reported with [Invalid_arg s] or [Error n]. *) val pp_error : Format.formatter -> int -> unit (** [pp_error Format.std_formatter e] prepares a human-readable description of the given error code [n] raised via [Error n]. *) val version : string * int * int * int (** [(name, major, minor, patch)] *)
(** High level bindings for LMDB. *)
statistics.ml
(* * More info about small world networks * http://en.wikipedia.org/wiki/Small-world_network *) (** Small World analisys *) open Graph open ExtLib open Dose_common include Util.Logging (struct let label = "dose_algo.statistics" end) module Make (G : Sig.I) = struct module VS = Set.Make (G.V) module UndG = Imperative.Graph.Concrete (G.V) let undirect g = let g2 = UndG.create () in G.iter_vertex (fun v -> UndG.add_vertex g2 v ; G.iter_succ (fun v' -> UndG.add_edge g2 v v') g v ; G.iter_pred (fun v' -> UndG.add_edge g2 v' v) g v) g ; g2 (* www.cs.cornell.edu/home/kleinber/...book/networks-book-ch20.pdf *) let clustering_coefficient graph vertex = let neighbours = G.succ graph vertex in let n = List.length neighbours in if n = 0 then 0.0 else if n = 1 then 1.0 else let n_edges = List.fold_left (fun old_sum v -> old_sum + List.fold_left (fun old_sum' v' -> if G.mem_edge graph v v' && v <> v' then old_sum' + 1 else old_sum') 0 neighbours) 0 neighbours and max_edges = if G.is_directed then n * (n - 1) else n * (n - 1) / 2 in float_of_int n_edges /. float_of_int max_edges let average_distance graph vertex = let rec add_successors distance visited vertices = (* Add successors breadth-first, we want the shortest path we can find *) let succs = ref [] in let (n, sum) = List.fold_left (fun (old_n, old_sum) v -> if not (VS.mem v !visited) then ( visited := VS.add v !visited ; succs := G.succ graph v :: !succs ; (old_n + 1, old_sum + distance)) else (old_n, old_sum)) (0, 0) vertices in let sf = List.flatten !succs in if sf <> [] then let (n', sum') = add_successors (distance + 1) visited sf in (n + n', sum + sum') else (n, sum) in let visited = ref (VS.singleton vertex) in let (n, sum) = add_successors 1 visited (G.succ graph vertex) in if sum = 0 then 0.0 else float_of_int sum /. float_of_int n module MSin = Map.Make (struct type t = G.V.t * G.t ref let compare (v1, _) (v2, g) = G.in_degree !g v1 - G.in_degree !g v2 end) module MSout = Map.Make (struct type t = G.V.t * G.t ref let compare (v1, _) (v2, g) = G.out_degree !g v1 - G.out_degree !g v2 end) let _avgdegree = ref None let _outdata = ref None let _indata = ref None let _outdatadegree = ref MSout.empty let _indatadegree = ref MSin.empty let degree graph = let nv = G.nb_vertex graph in let outmax = ref 0 in let inmax = ref 0 in let outh = Hashtbl.create 1031 in let inh = Hashtbl.create 1031 in (* how many vertices have degree X *) let add h d = if d = 0 then () else try Hashtbl.replace h d (Hashtbl.find h d + 1) with Not_found -> Hashtbl.add h d 1 in let total = G.fold_vertex (fun v sum -> let outdeg = G.out_degree graph v in let indeg = G.in_degree graph v in add outh outdeg ; add inh indeg ; _indatadegree := MSin.add (v, ref graph) indeg !_indatadegree ; _outdatadegree := MSout.add (v, ref graph) outdeg !_outdatadegree ; sum + indeg) graph 0 in (float_of_int total /. float_of_int nv, !outmax, !inmax, outh, inh) let computeDegree graph = if Option.is_some !_avgdegree then () else let (avdeg, _maxout, _maxin, outdata, indata) = degree graph in _avgdegree := Some avdeg ; _outdata := Some outdata ; _indata := Some indata let maxOutDegree graph = computeDegree graph ; snd (MSout.max_binding !_outdatadegree) let maxInDegree graph = computeDegree graph ; snd (MSin.max_binding !_indatadegree) let averageDegree graph = computeDegree graph ; Option.get !_avgdegree let zdp graph = G.fold_vertex (fun v sum -> if G.in_degree graph v = 0 && G.out_degree graph v = 0 then sum + 1 else sum) graph 0 let scatteredPlotIn graph = computeDegree graph ; Option.get !_indata let scatteredPlotOut graph = computeDegree graph ; Option.get !_outdata let scatteredPlotBoth graph = let add h i o = try Hashtbl.replace h (i, o) (Hashtbl.find h (i, o) + 1) with Not_found -> Hashtbl.add h (i, o) 1 in let h = Hashtbl.create 1031 in G.iter_vertex (fun v -> add h (G.in_degree graph v) (G.out_degree graph v)) graph ; h (* http://en.wikipedia.org/wiki/Centrality *) let centralityDegree graph fd = let n = float_of_int (G.nb_vertex graph) in let cd v = float_of_int v /. (n -. 1.0) in let m = G.fold_vertex (fun v max -> let s = List.length (fd graph v) in let m = cd s in if m > max then m else max) graph 0.0 in let c = G.fold_vertex (fun v sum -> let s = List.length (fd graph v) in sum +. (m -. cd s)) graph 0.0 in c /. (n -. 2.0) let centralityOutDegree graph = centralityDegree graph G.succ let centralityInDegree graph = centralityDegree graph G.pred let clustering graph = let n = float_of_int (G.nb_vertex graph) in let c = G.fold_vertex (fun v acc -> acc +. clustering_coefficient graph v) graph 0.0 in c /. n let averageShortestPathLength graph = let n = float_of_int (G.nb_vertex graph) in let c = G.fold_vertex (fun v acc -> acc +. average_distance graph v) graph 0.0 in c /. n (* strongly directed components *) (* weakly directed compoenents = strongly directed compoenents if the graph * is not direct !!! *) let components graph = let module C = Components.Make (G) in C.scc_array graph let weaklycomponents graph = let module C = Components.Make (UndG) in C.scc_array (undirect graph) let numberComponents c = Array.length c let averageComponents c = let sum = Array.fold_left (fun acc i -> acc + List.length i) 0 c in float_of_int sum /. float_of_int (Array.length c) let largestComponent c = Array.sort (fun x y -> compare (List.length x) (List.length y)) c ; List.length c.(Array.length c - 1) let density graph = let n = float_of_int (G.nb_vertex graph) in let ps_edg = n *. (n -. 1.0) in float_of_int (G.nb_edges graph) /. ps_edg let averageTwoStepReach graph = let module S = Set.Make (struct type t = G.vertex let compare = compare end) in let n = float_of_int (G.nb_vertex graph) in let t = G.fold_vertex (fun i0 total -> let s = G.fold_succ (fun i1 set1 -> G.fold_succ (fun i2 set2 -> S.add i2 set2) graph i1 set1) graph i0 S.empty in total +. float_of_int (S.cardinal s)) graph 0.0 in t /. n let removezdp graph = let g = G.copy graph in G.iter_vertex (fun v -> if G.in_degree graph v = 0 && G.out_degree graph v = 0 then G.remove_vertex g v) graph ; g (* (* bullshit *) let brokerage graph = let n = float_of_int (G.nb_vertex graph) in let ps_edg = n *. (n -. 1.0) in let total = ref 0 in G.iter_vertex (fun i0 -> G.iter_vertex (fun i1 -> if not (G.mem_edge graph i0 i1) then incr total ) graph ) graph; ((float_of_int !total) /. ps_edg) let shorter_path_length gr v = let module Bfs = Graph.Traverse.Bfs(G) in let seen = Hashtbl.create 1031 in let level = ref 0 in Bfs.prefix_component (fun v -> incr level ; Hashtbl.add see v !level ) gr v seen ;; let eccentricity gr = let vv = Hashtbl.create 1031 in G.iter_vertex (fun v -> let h = shorted_path_length gr v in Hashtbl.add vv v (Hashtbl.fold (fun k v acc -> max v acc) h 0) ) gr *) end
(**************************************************************************************) (* Copyright (C) 2008 Stefano Zacchiroli <zack@debian.org> and *) (* Jaap Boender <boender@pps.jussieu.fr> and *) (* Pietro Abate <pietro.abate@pps.jussieu.fr> *) (* *) (* This library is free software: you can redistribute it and/or modify *) (* it under the terms of the GNU Lesser General Public License as *) (* published by the Free Software Foundation, either version 3 of the *) (* License, or (at your option) any later version. A special linking *) (* exception to the GNU Lesser General Public License applies to this *) (* library, see the COPYING file for more information. *) (**************************************************************************************)
Dataflow_var_env.mli
(** Dataflow environments where the key is a simple variable name (a string) *) (* The comparison function uses only the name of a variable (a string), so * two variables at different positions in the code will be agglomerated * correctly in the Set or Map. *) type var = string module VarMap : Map.S with type key = String.t module VarSet : Set.S with type elt = String.t type 'a t = 'a VarMap.t type 'a env = 'a t type 'a inout = 'a env Dataflow_core.inout type 'a mapping = 'a env Dataflow_core.mapping type 'a transfn = 'a mapping -> Dataflow_core.nodei -> 'a inout val empty_env : unit -> 'a env val empty_inout : unit -> 'a inout val eq_env : ('a -> 'a -> bool) -> 'a env -> 'a env -> bool val varmap_union : ('a -> 'a -> 'a) -> 'a env -> 'a env -> 'a env val varmap_diff : ('a -> 'a -> 'a) -> ('a -> bool) -> 'a env -> 'a env -> 'a env val env_to_str : ('a -> string) -> 'a env -> string (** {2 Variable to [Dataflow_core.NodeiSet] environments} *) val add_var_and_nodei_to_env : var -> Dataflow_core.nodei -> Dataflow_core.NodeiSet.t env -> Dataflow_core.NodeiSet.t env val add_vars_and_nodei_to_env : VarSet.t -> Dataflow_core.nodei -> Dataflow_core.NodeiSet.t env -> Dataflow_core.NodeiSet.t env val union_env : Dataflow_core.NodeiSet.t env -> Dataflow_core.NodeiSet.t env -> Dataflow_core.NodeiSet.t env val diff_env : Dataflow_core.NodeiSet.t env -> Dataflow_core.NodeiSet.t env -> Dataflow_core.NodeiSet.t env
(** Dataflow environments where the key is a simple variable name (a string) *)
dune
(library (name ltac2_plugin) (public_name coq-core.plugins.ltac2) (synopsis "Ltac2 plugin") (modules_without_implementation tac2expr tac2qexpr tac2types) (libraries coq-core.plugins.ltac)) (coq.pp (modules g_ltac2))
web_authorization.ml
let user ~login_path_f = let filter handler req = let user = Web_user.find_opt req in match user with | Some _ -> handler req | None -> let login_path = login_path_f () in Opium.Response.redirect_to login_path |> Lwt.return in Rock.Middleware.create ~name:"authorization.user" ~filter ;; let admin ~login_path_f is_admin = let filter handler req = let user = Web_user.find_opt req in match user with | Some user -> if is_admin user then handler req else ( let login_path = login_path_f () in Opium.Response.redirect_to login_path |> Lwt.return) | None -> let login_path = login_path_f () in Opium.Response.redirect_to login_path |> Lwt.return in Rock.Middleware.create ~name:"authorization.admin" ~filter ;;
addTags.mli
open Types type input = AddTagsRequest.t type output = unit type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
pread_pwrite_ba.c
#define EXTUNIX_WANT_PREAD #define EXTUNIX_WANT_PWRITE #include "config.h" enum mode_bits { BIT_ONCE = 1 << 0, BIT_NOERROR = 1 << 1, BIT_NOINTR = 1 << 2 }; #if defined(EXTUNIX_HAVE_PREAD) /* Copyright © 2012 Goswin von Brederlow <goswin-v-b@web.de> */ CAMLprim value caml_extunixba_pread_common(value v_fd, off_t off, value v_buf, int mode) { CAMLparam2(v_fd, v_buf); ssize_t ret; size_t fd = Int_val(v_fd); size_t len = caml_ba_byte_size(Caml_ba_array_val(v_buf)); size_t processed = 0; char *buf = (char*)Caml_ba_data_val(v_buf); while(len > 0) { caml_enter_blocking_section(); ret = pread(fd, buf, len, off); caml_leave_blocking_section(); if (ret == 0) break; if (ret == -1) { if (errno == EINTR && (mode & BIT_NOINTR)) continue; if (processed > 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & BIT_NOERROR) break; } uerror("pread", Nothing); } processed += ret; buf += ret; off += ret; len -= ret; if (mode & BIT_ONCE) break; } CAMLreturn(Val_long(processed)); } value caml_extunixba_all_pread(value v_fd, value v_off, value v_buf) { off_t off = Long_val(v_off); return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOINTR); } value caml_extunixba_single_pread(value v_fd, value v_off, value v_buf) { off_t off = Long_val(v_off); return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_ONCE); } value caml_extunixba_pread(value v_fd, value v_off, value v_buf) { off_t off = Long_val(v_off); return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOINTR | BIT_NOERROR); } value caml_extunixba_intr_pread(value v_fd, value v_off, value v_buf) { off_t off = Long_val(v_off); return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOERROR); } value caml_extunixba_all_pread64(value v_fd, value v_off, value v_buf) { off_t off = Int64_val(v_off); return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOINTR); } value caml_extunixba_single_pread64(value v_fd, value v_off, value v_buf) { off_t off = Int64_val(v_off); return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_ONCE); } value caml_extunixba_pread64(value v_fd, value v_off, value v_buf) { off_t off = Int64_val(v_off); return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOINTR | BIT_NOERROR); } value caml_extunixba_intr_pread64(value v_fd, value v_off, value v_buf) { off_t off = Int64_val(v_off); return caml_extunixba_pread_common(v_fd, off, v_buf, BIT_NOERROR); } #endif #if defined(EXTUNIX_HAVE_PWRITE) /* Copyright © 2012 Goswin von Brederlow <goswin-v-b@web.de> */ CAMLprim value caml_extunixba_pwrite_common(value v_fd, off_t off, value v_buf, int mode) { CAMLparam2(v_fd, v_buf); ssize_t ret; size_t fd = Int_val(v_fd); size_t len = caml_ba_byte_size(Caml_ba_array_val(v_buf)); size_t processed = 0; char *buf = (char*)Caml_ba_data_val(v_buf); while(len > 0) { caml_enter_blocking_section(); ret = pwrite(fd, buf, len, off); caml_leave_blocking_section(); if (ret == 0) break; if (ret == -1) { if (errno == EINTR && (mode & BIT_NOINTR)) continue; if (processed > 0){ if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & BIT_NOERROR) break; } uerror("pwrite", Nothing); } processed += ret; buf += ret; off += ret; len -= ret; if (mode & BIT_ONCE) break; } CAMLreturn(Val_long(processed)); } value caml_extunixba_all_pwrite(value v_fd, value v_off, value v_buf) { off_t off = Long_val(v_off); return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOINTR); } value caml_extunixba_single_pwrite(value v_fd, value v_off, value v_buf) { off_t off = Long_val(v_off); return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_ONCE); } value caml_extunixba_pwrite(value v_fd, value v_off, value v_buf) { off_t off = Long_val(v_off); return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOINTR | BIT_NOERROR); } value caml_extunixba_intr_pwrite(value v_fd, value v_off, value v_buf) { off_t off = Long_val(v_off); return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOERROR); } value caml_extunixba_all_pwrite64(value v_fd, value v_off, value v_buf) { off_t off = Int64_val(v_off); return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOINTR); } value caml_extunixba_single_pwrite64(value v_fd, value v_off, value v_buf) { off_t off = Int64_val(v_off); return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_ONCE); } value caml_extunixba_pwrite64(value v_fd, value v_off, value v_buf) { off_t off = Int64_val(v_off); return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOINTR | BIT_NOERROR); } value caml_extunixba_intr_pwrite64(value v_fd, value v_off, value v_buf) { off_t off = Int64_val(v_off); return caml_extunixba_pwrite_common(v_fd, off, v_buf, BIT_NOERROR); } #endif #if defined(EXTUNIX_HAVE_READ) /* Copyright © 2012 Goswin von Brederlow <goswin-v-b@web.de> */ CAMLprim value caml_extunixba_read_common(value v_fd, value v_buf, int mode) { CAMLparam2(v_fd, v_buf); ssize_t ret; size_t fd = Int_val(v_fd); size_t len = caml_ba_byte_size(Caml_ba_array_val(v_buf)); size_t processed = 0; char *buf = (char*)Caml_ba_data_val(v_buf); while(len > 0) { caml_enter_blocking_section(); ret = read(fd, buf, len); caml_leave_blocking_section(); if (ret == 0) break; if (ret == -1) { if (errno == EINTR && (mode & BIT_NOINTR)) continue; if (processed > 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & BIT_NOERROR) break; } uerror("read", Nothing); } processed += ret; buf += ret; len -= ret; if (mode & BIT_ONCE) break; } CAMLreturn(Val_long(processed)); } value caml_extunixba_all_read(value v_fd, value v_buf) { return caml_extunixba_read_common(v_fd, v_buf, BIT_NOINTR); } value caml_extunixba_single_read(value v_fd, value v_buf) { return caml_extunixba_read_common(v_fd, v_buf, BIT_ONCE); } value caml_extunixba_read(value v_fd, value v_buf) { return caml_extunixba_read_common(v_fd, v_buf, BIT_NOINTR | BIT_NOERROR); } value caml_extunixba_intr_read(value v_fd, value v_buf) { return caml_extunixba_read_common(v_fd, v_buf, BIT_NOERROR); } #endif #if defined(EXTUNIX_HAVE_WRITE) /* Copyright © 2012 Goswin von Brederlow <goswin-v-b@web.de> */ CAMLprim value caml_extunixba_write_common(value v_fd, value v_buf, int mode) { CAMLparam2(v_fd, v_buf); ssize_t ret; size_t fd = Int_val(v_fd); size_t len = caml_ba_byte_size(Caml_ba_array_val(v_buf)); size_t processed = 0; char *buf = (char*)Caml_ba_data_val(v_buf); while(len > 0) { caml_enter_blocking_section(); ret = write(fd, buf, len); caml_leave_blocking_section(); if (ret == 0) break; if (ret == -1) { if (errno == EINTR && (mode & BIT_NOINTR)) continue; if (processed > 0){ if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (mode & BIT_NOERROR) break; } uerror("write", Nothing); } processed += ret; buf += ret; len -= ret; if (mode & BIT_ONCE) break; } CAMLreturn(Val_long(processed)); } value caml_extunixba_all_write(value v_fd, value v_buf) { return caml_extunixba_write_common(v_fd, v_buf, BIT_NOINTR); } value caml_extunixba_single_write(value v_fd, value v_buf) { return caml_extunixba_write_common(v_fd, v_buf, BIT_ONCE); } value caml_extunixba_write(value v_fd, value v_buf) { return caml_extunixba_write_common(v_fd, v_buf, BIT_NOINTR | BIT_NOERROR); } value caml_extunixba_intr_write(value v_fd, value v_buf) { return caml_extunixba_write_common(v_fd, v_buf, BIT_NOERROR); } #endif
owl_aeos_tuner_map_stub.c
#include "owl_aeos_macros.h" #define FUN4 #define BASE_FUN4 bl_float32_reci #define OMP_FUN4 omp_float32_reci #define NUMBER float #define NUMBER1 float #define MAPFN(X) (1. / X) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_abs #define OMP_FUN4 omp_float32_abs #define NUMBER float #define NUMBER1 float #define MAPFN(X) (fabsf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_abs2 #define OMP_FUN4 omp_float32_abs2 #define NUMBER float #define NUMBER1 float #define MAPFN(X) (X * X) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_signum #define OMP_FUN4 omp_float32_signum #define NUMBER float #define NUMBER1 float #define MAPFN(X) ((X > 0.0) ? 1.0 : (X < 0.0) ? -1.0 : X) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_sqr #define OMP_FUN4 omp_float32_sqr #define NUMBER float #define NUMBER1 float #define MAPFN(X) (X * X) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_sqrt #define OMP_FUN4 omp_float32_sqrt #define NUMBER float #define NUMBER1 float #define MAPFN(X) (sqrtf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_cbrt #define OMP_FUN4 omp_float32_cbrt #define NUMBER float #define NUMBER1 float #define MAPFN(X) (cbrtf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_exp #define OMP_FUN4 omp_float32_exp #define NUMBER float #define NUMBER1 float #define MAPFN(X) (expf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_expm1 #define OMP_FUN4 omp_float32_expm1 #define NUMBER float #define NUMBER1 float #define MAPFN(X) (expm1f(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_log #define OMP_FUN4 omp_float32_log #define NUMBER float #define NUMBER1 float #define MAPFN(X) (logf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_log1p #define OMP_FUN4 omp_float32_log1p #define NUMBER float #define NUMBER1 float #define MAPFN(X) (log1pf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_sin #define OMP_FUN4 omp_float32_sin #define NUMBER float #define NUMBER1 float #define MAPFN(X) (sinf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_cos #define OMP_FUN4 omp_float32_cos #define NUMBER float #define NUMBER1 float #define MAPFN(X) (cosf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_tan #define OMP_FUN4 omp_float32_tan #define NUMBER float #define NUMBER1 float #define MAPFN(X) (tanf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_asin #define OMP_FUN4 omp_float32_asin #define NUMBER float #define NUMBER1 float #define MAPFN(X) (asinf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_acos #define OMP_FUN4 omp_float32_acos #define NUMBER float #define NUMBER1 float #define MAPFN(X) (acosf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_atan #define OMP_FUN4 omp_float32_atan #define NUMBER float #define NUMBER1 float #define MAPFN(X) (atanf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_sinh #define OMP_FUN4 omp_float32_sinh #define NUMBER float #define NUMBER1 float #define MAPFN(X) (sinhf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_cosh #define OMP_FUN4 omp_float32_cosh #define NUMBER float #define NUMBER1 float #define MAPFN(X) (coshf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_tanh #define OMP_FUN4 omp_float32_tanh #define NUMBER float #define NUMBER1 float #define MAPFN(X) (tanhf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_asinh #define OMP_FUN4 omp_float32_asinh #define NUMBER float #define NUMBER1 float #define MAPFN(X) (asinhf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_acosh #define OMP_FUN4 omp_float32_acosh #define NUMBER float #define NUMBER1 float #define MAPFN(X) (acoshf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_atanh #define OMP_FUN4 omp_float32_atanh #define NUMBER float #define NUMBER1 float #define MAPFN(X) (atanhf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_erf #define OMP_FUN4 omp_float32_erf #define NUMBER float #define NUMBER1 float #define MAPFN(X) (erff(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_erfc #define OMP_FUN4 omp_float32_erfc #define NUMBER float #define NUMBER1 float #define MAPFN(X) (erfcf(X)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_logistic #define OMP_FUN4 omp_float32_logistic #define NUMBER float #define NUMBER1 float #define MAPFN(X) (1 / (1 + expf(-X))) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_relu #define OMP_FUN4 omp_float32_relu #define NUMBER float #define NUMBER1 float #define MAPFN(X) (fmaxf(X,0)) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_softplus #define OMP_FUN4 omp_float32_softplus #define NUMBER float #define NUMBER1 float #define MAPFN(X) (log1pf(expf(X))) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_softsign #define OMP_FUN4 omp_float32_softsign #define NUMBER float #define NUMBER1 float #define MAPFN(X) (X / (1 + fabsf(X))) #include "owl_aeos_tuner_map_impl.h" #define FUN4 #define BASE_FUN4 bl_float32_sigmoid #define OMP_FUN4 omp_float32_sigmoid #define NUMBER float #define NUMBER1 float #define MAPFN(X) (1 / (1 + expf(-X))) #include "owl_aeos_tuner_map_impl.h" /* BASE_FUN15 */ // share with: approx_elt_equal, elt_not_equal, elt_less, elt_greater, // elt_less_equal, elt_greater_equal #define FUN15 #define BASE_FUN15 bl_float32_elt_equal #define OMP_FUN15 omp_float32_elt_equal #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = (*X == *Y) #include "owl_aeos_tuner_map_impl.h" // share with sub #define FUN15 #define BASE_FUN15 bl_float32_add #define OMP_FUN15 omp_float32_add #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = *X + *Y #include "owl_aeos_tuner_map_impl.h" #define FUN15 #define BASE_FUN15 bl_float32_mul #define OMP_FUN15 omp_float32_mul #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = *X * *Y #include "owl_aeos_tuner_map_impl.h" #define FUN15 #define BASE_FUN15 bl_float32_div #define OMP_FUN15 omp_float32_div #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = *X / *Y #include "owl_aeos_tuner_map_impl.h" #define FUN15 #define BASE_FUN15 bl_float32_pow #define OMP_FUN15 omp_float32_pow #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = powf(*X,*Y) #include "owl_aeos_tuner_map_impl.h" #define FUN15 #define BASE_FUN15 bl_float32_hypot #define OMP_FUN15 omp_float32_hypot #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = hypotf(*X,*Y) #include "owl_aeos_tuner_map_impl.h" #define FUN15 #define BASE_FUN15 bl_float32_atan2 #define OMP_FUN15 omp_float32_atan2 #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = atan2f(*X,*Y) #include "owl_aeos_tuner_map_impl.h" // share with min2 #define FUN15 #define BASE_FUN15 bl_float32_max2 #define OMP_FUN15 omp_float32_max2 #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = fminf(*X,*Y) #include "owl_aeos_tuner_map_impl.h" // share with fmod_scalar #define FUN15 #define BASE_FUN15 bl_float32_fmod #define OMP_FUN15 omp_float32_fmod #define NUMBER float #define NUMBER1 float #define NUMBER2 float #define MAPFN(X,Y,Z) *Z = fmodf(*X, *Y) #include "owl_aeos_tuner_map_impl.h"
/* * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <liang.wang@cl.cam.ac.uk> */
string_generator.h
// Copyright 2008 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // String generator: generates all possible strings of up to // maxlen letters using the set of letters in alpha. // Fetch strings using a Java-like Next()/HasNext() interface. #ifndef RE2_TESTING_STRING_GENERATOR_H__ #define RE2_TESTING_STRING_GENERATOR_H__ #include <string> #include <vector> #include "util/util.h" #include "util/random.h" #include "re2/stringpiece.h" namespace re2 { class StringGenerator { public: StringGenerator(int maxlen, const vector<string>& alphabet); ~StringGenerator(); const StringPiece& Next(); bool HasNext() { return hasnext_; } // Resets generator to start sequence over. void Reset(); // Causes generator to emit random strings for next n calls to Next(). void Random(int32 seed, int n); // Causes generator to emit a NULL as the next call. void GenerateNULL(); private: bool IncrementDigits(); bool RandomDigits(); // Global state. int maxlen_; // Maximum length string to generate. vector<string> alphabet_; // Alphabet, one string per letter. // Iteration state. StringPiece sp_; // Last StringPiece returned by Next(). string s_; // String data in last StringPiece returned by Next(). bool hasnext_; // Whether Next() can be called again. vector<int> digits_; // Alphabet indices for next string. bool generate_null_; // Whether to generate a NULL StringPiece next. bool random_; // Whether generated strings are random. int nrandom_; // Number of random strings left to generate. ACMRandom* acm_; // Random number generator DISALLOW_COPY_AND_ASSIGN(StringGenerator); }; } // namespace re2 #endif // RE2_TESTING_STRING_GENERATOR_H__
bimage_lwt.ml
open Bimage module Filter = Filter.Make (struct type 'a io = 'a Lwt.t let bind = Lwt.bind let detach = Lwt_preemptive.detach let wrap = Lwt.wrap let wait (x : unit io) = Lwt_preemptive.run_in_main (fun () -> x) end)
record_field_attrs.ml
open! Base open! Ppxlib open Attrs module Generic = struct type 'specific t = | Omit_nil | Sexp_array of core_type | Sexp_bool | Sexp_list of core_type | Sexp_option of core_type | Specific of 'specific end open Generic let get_attribute attr ld ~f = Option.map (Attribute.get attr ld) ~f:(fun x -> f x, Attribute.name attr) ;; let create ~loc specific_getters ld ~if_no_attribute = let generic_getters = [ get_attribute omit_nil ~f:(fun () -> Omit_nil) ; (fun ld -> match ld.pld_type with | ty when Option.is_some (Attribute.get bool ld) -> (match ty with | [%type: bool] -> Some (Sexp_bool, "[@sexp.bool]") | _ -> invalid_attribute ~loc bool "bool") | ty when Option.is_some (Attribute.get option ld) -> (match ty with | [%type: [%t? ty] option] -> Some (Sexp_option ty, "[@sexp.option]") | _ -> invalid_attribute ~loc option "_ option") | ty when Option.is_some (Attribute.get list ld) -> (match ty with | [%type: [%t? ty] list] -> Some (Sexp_list ty, "[@sexp.list]") | _ -> invalid_attribute ~loc list "_ list") | ty when Option.is_some (Attribute.get array ld) -> (match ty with | [%type: [%t? ty] array] -> Some (Sexp_array ty, "[@sexp.array]") | _ -> invalid_attribute ~loc array "_ array") | _ -> None) ] in let getters = let wrapped_getters = List.map specific_getters ~f:(fun get ld -> Option.map (get ld) ~f:(fun (specific, string) -> Specific specific, string)) in List.concat [ wrapped_getters; generic_getters ] in match List.filter_map getters ~f:(fun f -> f ld) with | [] -> Specific if_no_attribute | [ (v, _) ] -> v | _ :: _ :: _ as attributes -> Location.raise_errorf ~loc "The following elements are mutually exclusive: %s" (String.concat ~sep:" " (List.map attributes ~f:snd)) ;; let strip_attributes = object inherit Ast_traverse.map method! attributes _ = [] end ;; let lift_default ~loc ld expr = let ty = strip_attributes#core_type ld.pld_type in Lifted.create ~loc ~prefix:"default" ~ty expr ;; let lift_drop_default ~loc ld expr = let ty = strip_attributes#core_type ld.pld_type in Lifted.create ~loc ~prefix:"drop_default" ~ty:[%type: [%t ty] -> [%t ty] -> Stdlib.Bool.t] expr ;; let lift_drop_if ~loc ld expr = let ty = strip_attributes#core_type ld.pld_type in Lifted.create ~loc ~prefix:"drop_if" ~ty:[%type: [%t ty] -> Stdlib.Bool.t] expr ;; module Of_sexp = struct type t = | Default of expression Lifted.t | Required let create ~loc ld = create ~loc [ get_attribute default ~f:(fun { to_lift = default } -> Default (lift_default ~loc ld default)) ] ld ~if_no_attribute:Required ;; end module Sexp_of = struct module Drop = struct type t = | No_arg | Compare | Equal | Sexp | Func of expression Lifted.t end type t = | Drop_default of Drop.t | Drop_if of expression Lifted.t | Keep let create ~loc ld = create ~loc [ get_attribute drop_default ~f:(function | None -> Drop_default No_arg | Some { to_lift = e } -> Drop_default (Func (lift_drop_default ~loc ld e))) ; get_attribute drop_default_equal ~f:(fun () -> Drop_default Equal) ; get_attribute drop_default_compare ~f:(fun () -> Drop_default Compare) ; get_attribute drop_default_sexp ~f:(fun () -> Drop_default Sexp) ; get_attribute drop_if ~f:(fun { to_lift = x } -> Drop_if (lift_drop_if ~loc ld x)) ] ld ~if_no_attribute:Keep ;; end
perms.ml
(** Types representing {i permissions} ['perms] for performing operations on a certain type ['perms t]. They are intended to be used as phantom parameters of the types that they control access to. As an example, consider the following type of references with permissions: {[ module Ref : sig type (+'a, -'perms) t val create : 'a -> ('a, read_write) t val get : ('a, [> read ]) t -> 'a val set : ('a, [> write ]) t -> 'a -> unit end ]} This type allows references to be created with arbitrary read-write access. One can then create weaker views onto the reference – with access to fewer operations – by upcasting: {[ let read_only t = (t :> (_, read) Ref.t) let write_only t = (t :> (_, write) Ref.t) ]} Note that the ['perms] phantom type parameter should be contravariant: it's safe to discard permissions, but not to gain new ones. *) module Read = struct type t = [ `Read ] end module Write = struct type t = [ `Write ] end module Read_write = struct type t = [ Read.t | Write.t ] end type read = Read.t (** The type parameter of a handle with [read] permissions. *) type write = Write.t (** The type parameter of a handle with [write] permissions. *) type read_write = Read_write.t (** The type parameter of a handle with both {!read} and {!write} permissions. *)
(* * Copyright (c) 2021 Craig Ferguson <craig@tarides.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
tztop.vanilla.ml
(* Vanilla toplevel needs -linkall flags. Dune doesn't provide a convenient * stanza to "select" compilation flags like it does with selecting dependencies * This could be worked around by using a configurator script *) let main () = failwith "tztop requires utop to be installed"
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021 Marigold <contact@marigold.dev> *) (* *) (* 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. *) (* *) (*****************************************************************************)
version.ml
let version = "11.0.8"
(* File: version.ml Copyright (C) 2012- Markus Mottl email: markus.mottl@gmail.com WWW: http://www.ocaml.info This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *)
dune
(executable (name example) (flags (:standard -w -9-27)) (ctypes (external_library_name libexample) (build_flags_resolver pkg_config) (headers (include "example.h")) (type_description (instance Types) (functor Type_description)) (function_description (concurrency unlocked) (instance Functions_unlocked) (functor Function_description_unlocked)) (function_description (concurrency sequential) (instance Functions_sequential) (functor Function_description_sequential)) (generated_entry_point C)))
test_ec_make.ml
let rec repeat n f = if n <= 0 then let f () = () in f else ( f () ; repeat (n - 1) f) (* copied from G_SIG to remove the dependency on bls12-381-gen *) module type G_SIG = sig exception Not_on_curve of Bytes.t (** The type of the element in the elliptic curve *) type t (** Contiguous C array containing points in affine coordinates *) type affine_array (** [to_affine_array pts] builds a contiguous C array and populate it with the points [pts] in affine coordinates. Use it with [pippenger_with_affine_array] to get better performance. *) val to_affine_array : t array -> affine_array (** Build a OCaml array of [t] values from the contiguous C array *) val of_affine_array : affine_array -> t array (** Return the number of elements in the array *) val size_of_affine_array : affine_array -> int (** Actual number of bytes allocated for a value of type t *) val size_in_memory : int (** The size of a point representation, in bytes *) val size_in_bytes : int module Scalar : Ff_sig.PRIME (** Create an empty value to store an element of the curve. DO NOT USE THIS TO DO COMPUTATIONS WITH, UNDEFINED BEHAVIORS MAY HAPPEN *) val empty : unit -> t (** Check if a point, represented as a byte array, is on the curve **) val check_bytes : Bytes.t -> bool (** Attempt to construct a point from a byte array of length [size_in_bytes]. *) val of_bytes_opt : Bytes.t -> t option (** Attempt to construct a point from a byte array of length [size_in_bytes]. Raise [Not_on_curve] if the point is not on the curve *) val of_bytes_exn : Bytes.t -> t (** Allocates a new point from a byte of length [size_in_bytes / 2] array representing a point in compressed form. *) val of_compressed_bytes_opt : Bytes.t -> t option (** Allocates a new point from a byte array of length [size_in_bytes / 2] representing a point in compressed form. Raise [Not_on_curve] if the point is not on the curve. *) val of_compressed_bytes_exn : Bytes.t -> t (** Return a representation in bytes *) val to_bytes : t -> Bytes.t (** Return a compressed bytes representation *) val to_compressed_bytes : t -> Bytes.t (** Zero of the elliptic curve *) val zero : t (** A fixed generator of the elliptic curve *) val one : t (** Return [true] if the given element is zero *) val is_zero : t -> bool (** [copy x] return a fresh copy of [x] *) val copy : t -> t (** Generate a random element. The element is on the curve and in the prime subgroup. *) val random : ?state:Random.State.t -> unit -> t (** Return the addition of two element *) val add : t -> t -> t val add_inplace : t -> t -> unit val add_bulk : t list -> t (** [double g] returns [2g] *) val double : t -> t (** Return the opposite of the element *) val negate : t -> t (** Return [true] if the two elements are algebraically the same *) val eq : t -> t -> bool (** Multiply an element by a scalar *) val mul : t -> Scalar.t -> t val mul_inplace : t -> Scalar.t -> unit (** [fft ~domain ~points] performs a Fourier transform on [points] using [domain] The domain should be of the form [w^{i}] where [w] is a principal root of unity. If the domain is of size [n], [w] must be a [n]-th principal root of unity. The number of points can be smaller than the domain size, but not larger. The complexity is in [O(n log(m))] where [n] is the domain size and [m] the number of points. A new array of size [n] is allocated and is returned. The parameters are not modified. *) val fft : domain:Scalar.t array -> points:t array -> t array (** [fft_inplace ~domain ~points] performs a Fourier transform on [points] using [domain] The domain should be of the form [w^{i}] where [w] is a principal root of unity. If the domain is of size [n], [w] must be a [n]-th principal root of unity. The number of points must be in the same size than the domain. It does not return anything but modified the points directly. It does only perform one allocation of a scalar for the FFT. It is recommended to use this function if side-effect is acceptable. *) val fft_inplace : domain:Scalar.t array -> points:t array -> unit (** [ifft ~domain ~points] performs an inverse Fourier transform on [points] using [domain]. The domain should be of the form [w^{-i}] (i.e the "inverse domain") where [w] is a principal root of unity. If the domain is of size [n], [w] must be a [n]-th principal root of unity. The domain size must be exactly the same than the number of points. The complexity is O(n log(n)) where [n] is the domain size. A new array of size [n] is allocated and is returned. The parameters are not modified. *) val ifft : domain:Scalar.t array -> points:t array -> t array val ifft_inplace : domain:Scalar.t array -> points:t array -> unit val hash_to_curve : Bytes.t -> Bytes.t -> t val pippenger : ?start:int -> ?len:int -> t array -> Scalar.t array -> t val pippenger_with_affine_array : ?start:int -> ?len:int -> affine_array -> Scalar.t array -> t end module MakeBulkOperations (G : G_SIG) = struct let test_bulk_add () = let n = 10 + Random.int 1_000 in let xs = List.init n (fun _ -> G.random ()) in assert (G.(eq (List.fold_left G.add G.zero xs) (G.add_bulk xs))) let test_pippenger () = let n = 1 + Random.int 5 in let start = Random.int n in let len = 1 + Random.int (n - start) in let ps = Array.init n (fun _ -> G.random ()) in let ss = Array.init n (fun _ -> G.Scalar.random ()) in let left = let ps = Array.sub ps start len in let ss = Array.sub ss start len in let xs = List.combine (Array.to_list ps) (Array.to_list ss) in List.fold_left (fun acc (g, n) -> G.add acc (G.mul g n)) G.zero xs in let right = G.pippenger ~start ~len ps ss in assert (G.(eq left right)) let test_pippenger_different_size () = let n_ps = 1 + Random.int 10 in let n_ss = 1 + Random.int 10 in let ps = Array.init n_ps (fun _ -> G.random ()) in let ss = Array.init n_ss (fun _ -> G.Scalar.random ()) in let left = let n = min n_ps n_ss in let ps = Array.sub ps 0 n in let ss = Array.sub ss 0 n in let xs = List.combine (Array.to_list ps) (Array.to_list ss) in List.fold_left (fun acc (g, n) -> G.add acc (G.mul g n)) G.zero xs in let right = G.pippenger ps ss in assert (G.(eq left right)) let test_to_affine_array () = let n = 1 + Random.int 1000 in let p = Array.init n (fun _ -> G.random ()) in let p' = G.of_affine_array (G.to_affine_array p) in let p = Array.to_list p in let p' = Array.to_list p' in assert (List.for_all2 G.eq p p') let test_size_of_affine_array () = let n = 1 + Random.int 1000 in let p = Array.init n (fun _ -> G.random ()) in let p = G.to_affine_array p in assert (G.size_of_affine_array p = n) let test_pippenger_contiguous () = let n = 1 + Random.int 10 in let ps = Array.init n (fun _ -> G.random ()) in let ps_contiguous = G.to_affine_array ps in let ss = Array.init n (fun _ -> G.Scalar.random ()) in let left = let xs = List.combine (Array.to_list ps) (Array.to_list ss) in List.fold_left (fun acc (g, n) -> G.add acc (G.mul g n)) G.zero xs in let right = G.pippenger_with_affine_array ps_contiguous ss in if not (G.eq left right) then Alcotest.failf "n = %d. Expected output is %s, computed %s" n (Hex.show (Hex.of_bytes (G.to_bytes left))) (Hex.show (Hex.of_bytes (G.to_bytes right))) let test_pippenger_contiguous_chunk () = let n = 10 + Random.int 1_000 in let nb_chunks = 1 + Random.int 10 in let chunk_size = n / nb_chunks in let rest = n mod nb_chunks in let ps = Array.init n (fun _ -> G.random ()) in let ps_contiguous = G.to_affine_array ps in let ss = Array.init n (fun _ -> G.Scalar.random ()) in let left = let xs = List.combine (Array.to_list ps) (Array.to_list ss) in List.fold_left (fun acc (g, n) -> G.add acc (G.mul g n)) G.zero xs in let right = let rec aux i acc = if i = nb_chunks then if rest <> 0 then let start = i * chunk_size in let len = rest in let res = G.pippenger_with_affine_array ~start ~len ps_contiguous ss in res :: acc else acc else let start = i * chunk_size in let len = chunk_size in let res = G.pippenger_with_affine_array ~start ~len ps_contiguous ss in let acc = res :: acc in aux (i + 1) acc in let l = aux 0 [] in List.fold_left G.add G.zero l in if not (G.eq left right) then Alcotest.failf "n = %d, chunk_size = %d, nb_chunks = %d. Expected output is %s, \ computed %s" n chunk_size nb_chunks (Hex.show (Hex.of_bytes (G.to_bytes left))) (Hex.show (Hex.of_bytes (G.to_bytes right))) let test_pippenger_contiguous_different_size () = let n_ps = 1 + Random.int 10 in let n_ss = 1 + Random.int 10 in let ps = Array.init n_ps (fun _ -> G.random ()) in let ps_contiguous = G.to_affine_array ps in let ss = Array.init n_ss (fun _ -> G.Scalar.random ()) in let left = let n = min n_ps n_ss in let ps = Array.sub ps 0 n in let ss = Array.sub ss 0 n in let xs = List.combine (Array.to_list ps) (Array.to_list ss) in List.fold_left (fun acc (g, n) -> G.add acc (G.mul g n)) G.zero xs in let right = G.pippenger_with_affine_array ps_contiguous ss in if not (G.eq left right) then Alcotest.failf "n_ss = %d, n_ps = %d. Expected output is %s, computed %s" n_ss n_ps (Hex.show (Hex.of_bytes (G.to_bytes left))) (Hex.show (Hex.of_bytes (G.to_bytes right))) let test_pippenger_contiguous_with_start_argument () = let n_ps = 1 + Random.int 10 in let n_ss = 1 + Random.int 10 in let ps = Array.init n_ps (fun _ -> G.random ()) in let ps_contiguous = G.to_affine_array ps in let ss = Array.init n_ss (fun _ -> G.Scalar.random ()) in let n = min n_ps n_ss in let start = Random.int n in let left = let ps = Array.sub ps start (n - start) in let ss = Array.sub ss start (n - start) in let xs = List.combine (Array.to_list ps) (Array.to_list ss) in List.fold_left (fun acc (g, n) -> G.add acc (G.mul g n)) G.zero xs in let right = G.pippenger_with_affine_array ~start ps_contiguous ss in if not (G.eq left right) then Alcotest.failf "n = %d, start = %d. Expected output is %s, computed %s" n start (Hex.show (Hex.of_bytes (G.to_bytes left))) (Hex.show (Hex.of_bytes (G.to_bytes right))) let test_pippenger_contiguous_with_len_argument () = let n_ps = 1 + Random.int 10 in let n_ss = 1 + Random.int 10 in let n = min n_ps n_ss in let len = 1 + Random.int n in let ps = Array.init n_ps (fun _ -> G.random ()) in let ps_contiguous = G.to_affine_array ps in let ss = Array.init n_ss (fun _ -> G.Scalar.random ()) in let left = let ps = Array.sub ps 0 len in let ss = Array.sub ss 0 len in let xs = List.combine (Array.to_list ps) (Array.to_list ss) in List.fold_left (fun acc (g, n) -> G.add acc (G.mul g n)) G.zero xs in let right = G.pippenger_with_affine_array ~len ps_contiguous ss in assert (G.(eq left right)) let test_pippenger_contiguous_with_start_and_len_argument () = let n_ps = 1 + Random.int 10 in let n_ss = 1 + Random.int 10 in let ps = Array.init n_ps (fun _ -> G.random ()) in let ps_contiguous = G.to_affine_array ps in let ss = Array.init n_ss (fun _ -> G.Scalar.random ()) in let n = min n_ps n_ss in let start = Random.int n in let len = 1 + Random.int (n - start) in let left = let ps = Array.sub ps start len in let ss = Array.sub ss start len in let xs = List.combine (Array.to_list ps) (Array.to_list ss) in List.fold_left (fun acc (g, n) -> G.add acc (G.mul g n)) G.zero xs in let right = G.pippenger_with_affine_array ~start ~len ps_contiguous ss in assert (G.(eq left right)) let get_tests () = let open Alcotest in ( "Bulk operations", [ test_case "bulk add" `Quick (repeat 10 test_bulk_add); test_case "to_affine_array" `Quick (repeat 10 test_to_affine_array); test_case "size_of_affine_array" `Quick (repeat 10 test_size_of_affine_array); test_case "pippenger" `Quick (repeat 10 test_pippenger); test_case "pippenger continuous chunk size" `Quick (repeat 10 test_pippenger_contiguous_chunk); test_case "pippenger different size" `Quick (repeat 10 test_pippenger_different_size); test_case "pippenger contiguous" `Quick (repeat 10 test_pippenger_contiguous); test_case "pippenger contiguous with different size" `Quick (repeat 10 test_pippenger_contiguous_different_size); test_case "pippenger contiguous with start argument" `Quick (repeat 10 test_pippenger_contiguous_with_start_argument); test_case "pippenger contiguous with start and len argument" `Quick (repeat 10 test_pippenger_contiguous_with_start_and_len_argument); test_case "pippenger contiguous with len argument" `Quick (repeat 10 test_pippenger_contiguous_with_len_argument) ] ) end module MakeInplaceOperations (G : G_SIG) = struct let test_mul_inplace () = let n = G.Scalar.random () in let g = G.random () in let res = G.mul g n in G.mul_inplace g n ; assert (G.eq g res) let test_add_inplace () = let x = G.random () in let y = G.random () in let res = G.add x y in G.add_inplace x y ; assert (G.eq x res) let get_tests () = let txt = "Inplace operations" in let open Alcotest in ( txt, [ test_case "mul inplace" `Quick (repeat 100 test_mul_inplace); test_case "add inplace" `Quick (repeat 100 test_add_inplace) ] ) end module MakeEquality (G : G_SIG) = struct (** Verify the equality is correct with the value zero *) let zero () = assert (G.eq G.zero G.zero) (** Verify the equality is correct with the value one *) let one () = assert (G.eq G.one G.one) (** Verify the equality of two random values created invidually *) let random_same_objects () = let random = G.random () in assert (G.eq random random) (** Returns the tests to be used with Alcotest *) let get_tests () = let open Alcotest in ( "equality", [ test_case "zero" `Quick (repeat 1 zero); test_case "one" `Quick (repeat 1 one); test_case "random_same_objects" `Quick (repeat 100 random_same_objects) ] ) end module MakeValueGeneration (G : G_SIG) = struct let random () = ignore @@ G.random () let negation_with_random () = let random = G.random () in ignore @@ G.negate random let negation_with_zero () = ignore @@ G.negate G.zero let negation_with_one () = ignore @@ G.negate G.one let double_with_zero () = ignore @@ G.double G.zero let double_with_one () = ignore @@ G.double G.one let double_with_random () = let g = G.random () in ignore @@ G.double g (** Returns the tests to be used with Alcotest *) let get_tests () = let open Alcotest in ( "value generation", [ test_case "random" `Quick (repeat 100 random); test_case "negate_with_one" `Quick (repeat 1 negation_with_one); test_case "negate_with_zero" `Quick (repeat 1 negation_with_zero); test_case "negate_with_random" `Quick (repeat 100 negation_with_random); test_case "double_with_random" `Quick (repeat 100 double_with_random); test_case "double_with_one" `Quick (repeat 1 double_with_one); test_case "double_with_zero" `Quick (repeat 100 double_with_zero) ] ) end module MakeIsZero (G : G_SIG) = struct let with_zero_value () = assert (G.is_zero G.zero = true) let with_one_value () = assert (G.is_zero G.one = false) let with_random_value () = assert (G.is_zero (G.random ()) = false) (** Returns the tests to be used with Alcotest *) let get_tests () = let open Alcotest in ( "is_zero", [ test_case "with zero value" `Quick (repeat 1 with_zero_value); test_case "with one value" `Quick (repeat 1 with_one_value); test_case "with random value" `Quick (repeat 100 with_random_value) ] ) end module MakeECProperties (G : G_SIG) = struct (** Verify that a random point is valid *) let check_bytes_random () = assert (G.(check_bytes @@ to_bytes @@ random ())) (** Verify that the zero point is valid *) let check_bytes_zero () = assert (G.(check_bytes @@ to_bytes @@ zero)) (** Verify that the fixed generator point is valid *) let check_bytes_one () = assert (G.(check_bytes @@ to_bytes @@ one)) (** Verify that doubling a random point gives a valid point *) let check_bytes_random_double () = assert (G.(check_bytes @@ to_bytes @@ double (random ()))) (** Verify that the sum of random points is valid *) let check_bytes_random_sum () = assert (G.(check_bytes @@ to_bytes @@ add (random ()) (random ()))) (** Verify that multiplying a random point by a scalar gives a valid point *) let check_bytes_random_multiplication () = assert (G.(check_bytes @@ to_bytes @@ mul (random ()) (Scalar.random ()))) (** Verify 0_S * g_EC = 0_EC where 0_S is the zero of the scalar field, 0_EC is the point at infinity and g_EC is an element of the EC *) let zero_scalar_nullifier_random () = let random = G.random () in assert (G.is_zero (G.mul random G.Scalar.zero)) (** Verify 0_S * 0_EC = 0_EC where 0_S is the zero of the scalar field and 0_EC is the point at infinity of the EC *) let zero_scalar_nullifier_zero () = assert (G.is_zero (G.mul G.zero G.Scalar.zero)) (** Verify 0_S * 1_EC = 0_EC where 0_S is the 0 of the scalar field, 1_EC is a fixed generator and 0_EC is the point at infinity of the EC *) let zero_scalar_nullifier_one () = assert (G.is_zero (G.mul G.one G.Scalar.zero)) let multiply_by_one_does_nothing () = let g = G.random () in assert (G.(eq (mul g Scalar.one) g)) (** Verify -(-g) = g where g is an element of the EC *) let opposite_of_opposite () = let random = G.random () in assert (G.eq (G.negate (G.negate random)) random) let opposite_of_opposite_using_scalar () = let r = G.random () in assert (G.(eq r (mul r (Scalar.negate (Scalar.negate Scalar.one))))) (** Verify -(-0_EC) = 0_EC where 0_EC is the point at infinity of the EC *) let opposite_of_zero_is_zero () = assert (G.eq (G.negate G.zero) G.zero) (** Verify -(-0_EC) = 0_EC where 0_EC is the point at infinity of the EC *) let opposite_of_opposite_of_zero_is_zero () = assert (G.eq (G.negate (G.negate G.zero)) G.zero) (** Verify -(-0_EC) = 0_EC where 0_EC is the point at infinity of the EC *) let opposite_of_opposite_of_one_is_one () = assert (G.eq (G.negate (G.negate G.one)) G.one) (** Verify g1 + (g2 + g3) = (g1 + g2) + g3 where g1, g2 and g3 are elements of the EC *) let additive_associativity () = let g1 = G.random () in let g2 = G.random () in let g3 = G.random () in assert (G.eq (G.add (G.add g1 g2) g3) (G.add (G.add g2 g3) g1)) (** Verify that g + (-g) = 0 *) let opposite_existential_property () = let g = G.random () in assert (G.(eq (add g (negate g)) zero)) (** Verify a (g1 + g2) = a * g1 + a * g2 where a is a scalar, g1, g2 two elements of the EC *) let distributivity () = let s = G.Scalar.random () in let g1 = G.random () in let g2 = G.random () in assert (G.eq (G.mul (G.add g1 g2) s) (G.add (G.mul g1 s) (G.mul g2 s))) (** Verify (a + -a) * g = a * g - a * g = 0 *) let opposite_equality () = let a = G.Scalar.random () in let g = G.random () in assert (G.(eq (mul g (Scalar.add a (Scalar.negate a))) zero)) ; assert (G.(eq zero (add (mul g a) (mul g (Scalar.negate a))))) ; assert ( G.( eq (mul g (Scalar.add a (Scalar.negate a))) (add (mul g a) (mul g (Scalar.negate a))))) (** a g + b + g = (a + b) g*) let additive_associativity_with_scalar () = let a = G.Scalar.random () in let b = G.Scalar.random () in let g = G.random () in let left = G.(add (mul g a) (mul g b)) in let right = G.(mul g (Scalar.add a b)) in assert (G.(eq left right)) (** (a * b) g = a (b g) = b (a g) *) let multiplication_properties_on_base_field_element () = let a = G.Scalar.random () in let b = G.Scalar.random () in let g = G.random () in assert (G.(eq (mul g (Scalar.mul a b)) (mul (mul g a) b))) ; assert (G.(eq (mul g (Scalar.mul a b)) (mul (mul g b) a))) let random_is_in_prime_subgroup () = let g = G.random () in (* [order] g = 0 *) assert (G.(eq (mul g Scalar.(of_z order)) zero)) ; (* [order - 1 ] g = [-1] g *) assert (G.(eq (mul g Scalar.(of_z (Z.pred order))) (G.negate g))) (** Verify (-s) * g = s * (-g) *) let opposite_of_scalar_is_opposite_of_ec () = let s = G.Scalar.random () in let g = G.random () in let left = G.mul g (G.Scalar.negate s) in let right = G.mul (G.negate g) s in assert (G.eq left right) (** Verify 2*g = g + g *) let double () = let s = G.random () in assert (G.(eq (double s) (add s s))) let test_bulk_add () = let n = 10 + Random.int 1_000 in let xs = List.init n (fun _ -> G.random ()) in assert (G.(eq (List.fold_left G.add G.zero xs) (G.add_bulk xs))) (** Returns the tests to be used with Alcotest *) let get_tests () = let open Alcotest in ( "Curve properties", [ test_case "check_bytes_random" `Quick (repeat 100 check_bytes_random); test_case "check_bytes_zero" `Quick (repeat 1 check_bytes_zero); test_case "check_bytes_one" `Quick (repeat 1 check_bytes_one); test_case "bulk add" `Quick (repeat 100 test_bulk_add); test_case "check_bytes_random_double" `Quick (repeat 100 check_bytes_random_double); test_case "check_bytes_random_sum" `Quick (repeat 100 check_bytes_random_sum); test_case "check_bytes_random_multiplication" `Quick (repeat 100 check_bytes_random_multiplication); test_case "zero_scalar_nullifier_one" `Quick (repeat 1 zero_scalar_nullifier_one); test_case "zero_scalar_nullifier_zero" `Quick (repeat 1 zero_scalar_nullifier_zero); test_case "zero_scalar_nullifier_random" `Quick (repeat 100 zero_scalar_nullifier_random); test_case "multiply_by_one_does_nothing" `Quick (repeat 100 multiply_by_one_does_nothing); test_case "opposite_of_opposite" `Quick (repeat 100 opposite_of_opposite); test_case "opposite_of_opposite_using_scalar" `Quick (repeat 100 opposite_of_opposite_using_scalar); test_case "opposite_of_zero_is_zero" `Quick (repeat 1 opposite_of_zero_is_zero); test_case "opposite_of_opposite_of_zero_is_zero" `Quick (repeat 1 opposite_of_opposite_of_zero_is_zero); test_case "opposite_of_opposite_of_one_is_one" `Quick (repeat 1 opposite_of_opposite_of_one_is_one); test_case "opposite_equality" `Quick (repeat 1 opposite_equality); test_case "distributivity" `Quick (repeat 100 distributivity); test_case "opposite_of_scalar_is_opposite_of_ec" `Quick (repeat 100 opposite_of_scalar_is_opposite_of_ec); test_case "opposite_existential_property" `Quick (repeat 100 opposite_existential_property); test_case "multiplication_properties_on_base_field_element" `Quick (repeat 100 multiplication_properties_on_base_field_element); test_case "double" `Quick (repeat 100 double); test_case "additive_associativity_with_scalar" `Quick (repeat 100 additive_associativity_with_scalar); test_case "random elements are generated in the prime subgroup" `Quick (repeat 100 random_is_in_prime_subgroup); test_case "additive_associativity" `Quick (repeat 100 additive_associativity) ] ) end module MakeCompressedRepresentation (G : G_SIG) = struct let test_recover_correct_point_uncompressed () = let g = G.random () in let compressed_bytes = G.to_compressed_bytes g in let uncompressed_g = G.of_compressed_bytes_exn compressed_bytes in assert (G.eq g uncompressed_g) (* it is correct to test this for BLS12-381 *) let test_compressed_version_is_half_the_size () = let g = G.random () in assert (Bytes.length (G.to_compressed_bytes g) = G.size_in_bytes / 2) let test_most_significant_bit_is_set_to_1 () = let g = G.random () in let compressed_g_bytes = G.to_compressed_bytes g in let first_byte = int_of_char @@ Bytes.get compressed_g_bytes 0 in assert (first_byte land 0b10000000 = 0b10000000) let test_check_second_most_significant_bit_is_set_to_1_for_zero () = let g = G.zero in let compressed_g_bytes = G.to_compressed_bytes g in let first_byte = int_of_char @@ Bytes.get compressed_g_bytes 0 in assert (first_byte land 0b01000000 = 0b01000000) let test_compressed_version_x_in_big_endian () = (* The compressed version fully carries the x coordinate. For G1, the compressed version is 384 bits with the 3 most significant bits being used to carry information to compute the y coordinate. For G2, as it is built on Fp2, the compressed version is (384 * 2) bits and the most significant 3 bits carries the same information. The bits 385, 386 and 387 (i.e. the last 3 bits of the constant coefficient of the x coordinate) are set to zero/unused. *) let g = G.random () in let g_bytes = G.to_bytes g in let x_bytes_be = Bytes.sub g_bytes 0 (G.size_in_bytes / 2) in let compressed_g_bytes = G.to_compressed_bytes g in let compressed_g_bytes_first_byte = Bytes.get compressed_g_bytes 0 in (* Get rid of the last 3 bits as it carries information unrelated to x *) let compressed_g_bytes_first_byte = int_of_char compressed_g_bytes_first_byte land 0b00011111 in Bytes.set compressed_g_bytes 0 (char_of_int compressed_g_bytes_first_byte) ; assert (Bytes.equal x_bytes_be compressed_g_bytes) let get_tests () = let open Alcotest in ( "Compressed representation", [ test_case "Recover correct point" `Quick test_recover_correct_point_uncompressed; test_case "Most significant bit is set to 1" `Quick (repeat 100 test_most_significant_bit_is_set_to_1); test_case "Second most significant bit is set to 1 for the identity element" `Quick test_check_second_most_significant_bit_is_set_to_1_for_zero; test_case "Verify x is fully in the compressed version and in big endian" `Quick (repeat 100 test_compressed_version_x_in_big_endian); test_case "Compressed version is half the size" `Quick test_compressed_version_is_half_the_size ] ) end
(*****************************************************************************) (* *) (* Copyright (c) 2020-2021 Danny Willems <be.danny.willems@gmail.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
private_key.ml
let ( let* ) = Result.bind type ecdsa = [ | `P224 of Mirage_crypto_ec.P224.Dsa.priv | `P256 of Mirage_crypto_ec.P256.Dsa.priv | `P384 of Mirage_crypto_ec.P384.Dsa.priv | `P521 of Mirage_crypto_ec.P521.Dsa.priv ] type t = [ ecdsa | `RSA of Mirage_crypto_pk.Rsa.priv | `ED25519 of Mirage_crypto_ec.Ed25519.priv ] let key_type = function | `RSA _ -> `RSA | `ED25519 _ -> `ED25519 | `P224 _ -> `P224 | `P256 _ -> `P256 | `P384 _ -> `P384 | `P521 _ -> `P521 let generate ?seed ?(bits = 4096) typ = let g = match seed with | None -> None | Some seed -> Some Mirage_crypto_rng.(create ~seed (module Fortuna)) in match typ with | `RSA -> `RSA (Mirage_crypto_pk.Rsa.generate ?g ~bits ()) | `ED25519 -> `ED25519 (fst (Mirage_crypto_ec.Ed25519.generate ?g ())) | `P224 -> `P224 (fst (Mirage_crypto_ec.P224.Dsa.generate ?g ())) | `P256 -> `P256 (fst (Mirage_crypto_ec.P256.Dsa.generate ?g ())) | `P384 -> `P384 (fst (Mirage_crypto_ec.P384.Dsa.generate ?g ())) | `P521 -> `P521 (fst (Mirage_crypto_ec.P521.Dsa.generate ?g ())) let of_cstruct data = let open Mirage_crypto_ec in let ec_err e = Result.map_error (fun e -> `Msg (Fmt.to_to_string Mirage_crypto_ec.pp_error e)) e in function | `RSA -> Error (`Msg "cannot decode an RSA key") | `ED25519 -> let* k = ec_err (Ed25519.priv_of_cstruct data) in Ok (`ED25519 k) | `P224 -> let* k = ec_err (P224.Dsa.priv_of_cstruct data) in Ok (`P224 k) | `P256 -> let* k = ec_err (P256.Dsa.priv_of_cstruct data) in Ok (`P256 k) | `P384 -> let* k = ec_err (P384.Dsa.priv_of_cstruct data) in Ok (`P384 k) | `P521 -> let* k = ec_err (P521.Dsa.priv_of_cstruct data) in Ok (`P521 k) let of_string ?seed_or_data ?bits typ data = match seed_or_data with | None -> begin match typ with | `RSA -> Ok (generate ~seed:(Cstruct.of_string data) ?bits `RSA) | _ -> let* data = Base64.decode data in of_cstruct (Cstruct.of_string data) typ end | Some `Seed -> Ok (generate ~seed:(Cstruct.of_string data) ?bits typ) | Some `Data -> let* data = Base64.decode data in of_cstruct (Cstruct.of_string data) typ let public = function | `RSA priv -> `RSA (Mirage_crypto_pk.Rsa.pub_of_priv priv) | `ED25519 priv -> `ED25519 (Mirage_crypto_ec.Ed25519.pub_of_priv priv) | `P224 priv -> `P224 (Mirage_crypto_ec.P224.Dsa.pub_of_priv priv) | `P256 priv -> `P256 (Mirage_crypto_ec.P256.Dsa.pub_of_priv priv) | `P384 priv -> `P384 (Mirage_crypto_ec.P384.Dsa.pub_of_priv priv) | `P521 priv -> `P521 (Mirage_crypto_ec.P521.Dsa.pub_of_priv priv) let sign hash ?scheme key data = let open Mirage_crypto_ec in let hashed () = Public_key.hashed hash data and ecdsa_to_cs s = Algorithm.ecdsa_sig_to_cstruct s in let scheme = Key_type.opt_signature_scheme ?scheme (key_type key) in try match key, scheme with | `RSA key, `RSA_PSS -> let module H = (val (Mirage_crypto.Hash.module_of hash)) in let module PSS = Mirage_crypto_pk.Rsa.PSS(H) in let* d = hashed () in Ok (PSS.sign ~key (`Digest d)) | `RSA key, `RSA_PKCS1 -> let* d = hashed () in Ok (Mirage_crypto_pk.Rsa.PKCS1.sign ~key ~hash (`Digest d)) | `ED25519 key, `ED25519 -> begin match data with | `Message m -> Ok (Ed25519.sign ~key m) | `Digest _ -> Error (`Msg "Ed25519 only suitable with raw message") end | #ecdsa as key, `ECDSA -> let* d = hashed () in Ok (ecdsa_to_cs (match key with | `P224 key -> P224.Dsa.(sign ~key (Public_key.trunc byte_length d)) | `P256 key -> P256.Dsa.(sign ~key (Public_key.trunc byte_length d)) | `P384 key -> P384.Dsa.(sign ~key (Public_key.trunc byte_length d)) | `P521 key -> P521.Dsa.(sign ~key (Public_key.trunc byte_length d)))) | _ -> Error (`Msg "invalid key and signature scheme combination") with | Mirage_crypto_pk.Rsa.Insufficient_key -> Error (`Msg "RSA key of insufficient length") | Message_too_long -> Error (`Msg "message too long") module Asn = struct open Asn.S open Mirage_crypto_pk (* RSA *) let other_prime_infos = sequence_of @@ (sequence3 (required ~label:"prime" integer) (required ~label:"exponent" integer) (required ~label:"coefficient" integer)) let rsa_private_key = let f (v, (n, (e, (d, (p, (q, (dp, (dq, (q', other))))))))) = match (v, other) with | (0, None) -> begin match Rsa.priv ~e ~d ~n ~p ~q ~dp ~dq ~q' with | Ok p -> p | Error (`Msg m) -> parse_error "bad RSA private key %s" m end | _ -> parse_error "multi-prime RSA keys not supported" and g { Rsa.e; d; n; p; q; dp; dq; q' } = (0, (n, (e, (d, (p, (q, (dp, (dq, (q', None))))))))) in map f g @@ sequence @@ (required ~label:"version" int) @ (required ~label:"modulus" integer) (* n *) @ (required ~label:"publicExponent" integer) (* e *) @ (required ~label:"privateExponent" integer) (* d *) @ (required ~label:"prime1" integer) (* p *) @ (required ~label:"prime2" integer) (* q *) @ (required ~label:"exponent1" integer) (* dp *) @ (required ~label:"exponent2" integer) (* dq *) @ (required ~label:"coefficient" integer) (* qinv *) -@ (optional ~label:"otherPrimeInfos" other_prime_infos) (* For outside uses. *) let (rsa_private_of_cstruct, rsa_private_to_cstruct) = Asn_grammars.projections_of Asn.der rsa_private_key (* PKCS8 *) let (rsa_priv_of_cs, rsa_priv_to_cs) = Asn_grammars.project_exn rsa_private_key let ec_to_err = function | Ok x -> x | Error e -> parse_error "%a" Mirage_crypto_ec.pp_error e let ed25519_of_cs, ed25519_to_cs = Asn_grammars.project_exn octet_string let ec_private_key = let f (v, pk, nc, pub) = if v <> 1 then parse_error "bad version for ec Private key" else let curve = match nc with | Some c -> Some (Algorithm.curve_of_oid c) | None -> None in pk, curve, pub and g (pk, curve, pub) = let nc = match curve with | None -> None | Some c -> Some (Algorithm.curve_to_oid c) in (1, pk, nc, pub) in Asn.S.map f g @@ sequence4 (required ~label:"version" int) (* ecPrivkeyVer1(1) *) (required ~label:"privateKey" octet_string) (* from rfc5480: choice3, but only namedCurve is allowed in PKIX *) (optional ~label:"namedCurve" (explicit 0 oid)) (optional ~label:"publicKey" (explicit 1 bit_string)) let ec_of_cs, ec_to_cs = Asn_grammars.project_exn ec_private_key let reparse_ec_private curve priv = let open Mirage_crypto_ec in match curve with | `SECP224R1 -> let* p = P224.Dsa.priv_of_cstruct priv in Ok (`P224 p) | `SECP256R1 -> let* p = P256.Dsa.priv_of_cstruct priv in Ok (`P256 p) | `SECP384R1 -> let* p = P384.Dsa.priv_of_cstruct priv in Ok (`P384 p) | `SECP521R1 -> let* p = P521.Dsa.priv_of_cstruct priv in Ok (`P521 p) (* external use (result) *) let ec_priv_of_cs = let dec, _ = Asn_grammars.projections_of Asn.der ec_private_key in fun cs -> let* priv, curve, _pub = dec cs in match curve with | None -> Error (`Parse "no curve provided") | Some c -> Result.map_error (fun e -> `Parse (Fmt.to_to_string Mirage_crypto_ec.pp_error e)) (reparse_ec_private c priv) let ec_of_cs ?curve cs = let (priv, named_curve, _pub) = ec_of_cs cs in let nc = match curve, named_curve with | Some c, None -> c | None, Some c -> c | Some c, Some c' -> if c = c' then c else parse_error "conflicting curve" | None, None -> parse_error "unknown curve" in ec_to_err (reparse_ec_private nc priv) let ec_to_cs ?curve ?pub key = ec_to_cs (key, curve, pub) let reparse_private pk = match pk with | (0, Algorithm.RSA, cs) -> `RSA (rsa_priv_of_cs cs) | (0, Algorithm.ED25519, cs) -> let data = ed25519_of_cs cs in `ED25519 (ec_to_err (Mirage_crypto_ec.Ed25519.priv_of_cstruct data)) | (0, Algorithm.EC_pub curve, cs) -> ec_of_cs ~curve cs | _ -> parse_error "unknown private key info" let unparse_private p = let open Mirage_crypto_ec in let open Algorithm in let alg, cs = match p with | `RSA pk -> RSA, rsa_priv_to_cs pk | `ED25519 pk -> ED25519, ed25519_to_cs (Ed25519.priv_to_cstruct pk) | `P224 pk -> EC_pub `SECP224R1, ec_to_cs (P224.Dsa.priv_to_cstruct pk) | `P256 pk -> EC_pub `SECP256R1, ec_to_cs (P256.Dsa.priv_to_cstruct pk) | `P384 pk -> EC_pub `SECP384R1, ec_to_cs (P384.Dsa.priv_to_cstruct pk) | `P521 pk -> EC_pub `SECP521R1, ec_to_cs (P521.Dsa.priv_to_cstruct pk) in (0, alg, cs) let private_key_info = map reparse_private unparse_private @@ sequence3 (required ~label:"version" int) (required ~label:"privateKeyAlgorithm" Algorithm.identifier) (required ~label:"privateKey" octet_string) (* TODO: there's an (optional ~label:"attributes" @@ implicit 0 (SET of Attributes) which are defined in X.501; but nobody seems to use them anyways *) let (private_of_cstruct, private_to_cstruct) = Asn_grammars.projections_of Asn.der private_key_info end let decode_der cs = Asn_grammars.err_to_msg (Asn.private_of_cstruct cs) let encode_der = Asn.private_to_cstruct let decode_pem cs = let* data = Pem.parse cs in let rsa_p (t, _) = String.equal "RSA PRIVATE KEY" t and ec_p (t, _) = String.equal "EC PRIVATE KEY" t and pk_p (t, _) = String.equal "PRIVATE KEY" t in let r, _ = List.partition rsa_p data and ec, _ = List.partition ec_p data and p, _ = List.partition pk_p data in let* k = Pem.foldM (fun (_, k) -> let* k = Asn_grammars.err_to_msg (Asn.rsa_private_of_cstruct k) in Ok (`RSA k)) r in let* k' = Pem.foldM (fun (_, k) -> Asn_grammars.err_to_msg (Asn.ec_priv_of_cs k)) ec in let* k'' = Pem.foldM (fun (_, k) -> Asn_grammars.err_to_msg (Asn.private_of_cstruct k)) p in Pem.exactly_one ~what:"private key" (k @ k' @ k'') let encode_pem p = Pem.unparse ~tag:"PRIVATE KEY" (Asn.private_to_cstruct p)
injector_functor.ml
open Protocol_client_context open Protocol open Alpha_context open Common open Injector_worker_types open Injector_sigs open Injector_errors (* This is the Tenderbake finality for blocks. *) (* TODO: https://gitlab.com/tezos/tezos/-/issues/2815 Centralize this and maybe make it configurable. *) let confirmations = 2 type injection_strategy = [`Each_block | `Delay_block] (* TODO/TORU: https://gitlab.com/tezos/tezos/-/issues/2755 Persist injector data on disk *) (** Builds a client context from another client context but uses logging instead of printing on stdout directly. This client context cannot make the injector exit. *) let injector_context (cctxt : #Protocol_client_context.full) = let log _channel msg = Logs_lwt.info (fun m -> m "%s" msg) in object inherit Protocol_client_context.wrap_full (new Client_context.proxy_context (cctxt :> Client_context.full)) inherit! Client_context.simple_printer log method! exit code = Format.ksprintf Stdlib.failwith "Injector client wants to exit %d" code end module Make (Rollup : PARAMETERS) = struct module Tags = Injector_tags.Make (Rollup.Tag) module Tags_table = Hashtbl.Make (Rollup.Tag) module Op_queue = Disk_persistence.Make_queue (struct let name = "operations_queue" end) (L1_operation.Hash) (L1_operation) (** Information stored about an L1 operation that was injected on a Tezos node. *) type injected_info = { op : L1_operation.t; (** The L1 manager operation. *) oph : Operation_hash.t; (** The hash of the operation which contains [op] (this can be an L1 batch of several manager operations). *) } module Injected_operations = Disk_persistence.Make_table (struct include L1_operation.Hash.Table type value = injected_info let name = "injected_operations" let string_of_key = L1_operation.Hash.to_b58check let key_of_string = L1_operation.Hash.of_b58check_opt let value_encoding = let open Data_encoding in conv (fun {op; oph} -> (oph, op)) (fun (oph, op) -> {op; oph}) @@ merge_objs (obj1 (req "oph" Operation_hash.encoding)) L1_operation.encoding end) module Injected_ophs = Disk_persistence.Make_table (struct include Operation_hash.Table type value = L1_operation.Hash.t list let name = "injected_ophs" let string_of_key = Operation_hash.to_b58check let key_of_string = Operation_hash.of_b58check_opt let value_encoding = Data_encoding.list L1_operation.Hash.encoding end) (** The part of the state which gathers information about injected operations (but not included). *) type injected_state = { injected_operations : Injected_operations.t; (** A table mapping L1 manager operation hashes to the injection info for that operation. *) injected_ophs : Injected_ophs.t; (** A mapping of all L1 manager operations contained in a L1 batch (i.e. an L1 operation). *) } (** Information stored about an L1 operation that was included in a Tezos block. *) type included_info = { op : L1_operation.t; (** The L1 manager operation. *) oph : Operation_hash.t; (** The hash of the operation which contains [op] (this can be an L1 batch of several manager operations). *) l1_block : Block_hash.t; (** The hash of the L1 block in which the operation was included. *) l1_level : int32; (** The level of [l1_block]. *) } module Included_operations = Disk_persistence.Make_table (struct include L1_operation.Hash.Table type value = included_info let name = "included_operations" let string_of_key = L1_operation.Hash.to_b58check let key_of_string = L1_operation.Hash.of_b58check_opt let value_encoding = let open Data_encoding in conv (fun {op; oph; l1_block; l1_level} -> (op, (oph, l1_block, l1_level))) (fun (op, (oph, l1_block, l1_level)) -> {op; oph; l1_block; l1_level}) @@ merge_objs L1_operation.encoding (obj3 (req "oph" Operation_hash.encoding) (req "l1_block" Block_hash.encoding) (req "l1_level" int32)) end) module Included_in_blocks = Disk_persistence.Make_table (struct include Block_hash.Table type value = int32 * L1_operation.Hash.t list let name = "included_in_blocks" let string_of_key = Block_hash.to_b58check let key_of_string = Block_hash.of_b58check_opt let value_encoding = let open Data_encoding in obj2 (req "level" int32) (req "l1_ops" (list L1_operation.Hash.encoding)) end) (** The part of the state which gathers information about operations which are included in the L1 chain (but not confirmed). *) type included_state = { included_operations : Included_operations.t; included_in_blocks : Included_in_blocks.t; } (** The internal state of each injector worker. *) type state = { cctxt : Protocol_client_context.full; (** The client context which is used to perform the injections. *) signer : signer; (** The signer for this worker. *) tags : Tags.t; (** The tags of this worker, for both informative and identification purposes. *) strategy : injection_strategy; (** The strategy of this worker for injecting the pending operations. *) save_dir : string; (** Path to where save persistent state *) queue : Op_queue.t; (** The queue of pending operations for this injector. *) injected : injected_state; (** The information about injected operations. *) included : included_state; (** The information about included operations. {b Note}: Operations which are confirmed are simply removed from the state and do not appear anymore. *) rollup_node_state : Rollup.rollup_node_state; (** The state of the rollup node. *) } module Event = struct include Injector_events.Make (Rollup) let emit1 e state x = emit e (state.signer.pkh, state.tags, x) let emit2 e state x y = emit e (state.signer.pkh, state.tags, x, y) let emit3 e state x y z = emit e (state.signer.pkh, state.tags, x, y, z) end let init_injector cctxt ~data_dir rollup_node_state ~signer strategy tags = let open Lwt_result_syntax in let* signer = get_signer cctxt signer in let data_dir = Filename.concat data_dir "injector" in let*! () = Lwt_utils_unix.create_dir data_dir in let filter op_proj op = let {L1_operation.manager_operation = Manager op; _} = op_proj op in match Rollup.operation_tag op with | None -> false | Some t -> Tags.mem t tags in let warn_unreadable = (* Warn of corrupted files but don't fail *) Some (fun file error -> Event.(emit corrupted_operation_on_disk) (signer.pkh, tags, file, error)) in let emit_event_loaded kind nb = Event.(emit loaded_from_disk) (signer.pkh, tags, nb, kind) in let* queue = Op_queue.load_from_disk ~warn_unreadable ~capacity:50_000 ~data_dir ~filter:(filter (fun op -> op)) in let*! () = emit_event_loaded "operations_queue" @@ Op_queue.length queue in (* Very coarse approximation for the number of operation we expect for each block *) let n = Tags.fold (fun t acc -> acc + Rollup.table_estimated_size t) tags 0 in let* injected_operations = Injected_operations.load_from_disk ~warn_unreadable ~initial_size:n ~data_dir ~filter:(filter (fun (i : injected_info) -> i.op)) in let*! () = emit_event_loaded "injected_operations" @@ Injected_operations.length injected_operations in let* included_operations = Included_operations.load_from_disk ~warn_unreadable ~initial_size:(confirmations * n) ~data_dir ~filter:(filter (fun (i : included_info) -> i.op)) in let*! () = emit_event_loaded "included_operations" @@ Included_operations.length included_operations in let* injected_ophs = Injected_ophs.load_from_disk ~warn_unreadable ~initial_size:n ~data_dir ~filter:(List.exists (Injected_operations.mem injected_operations)) in let*! () = emit_event_loaded "injected_ophs" @@ Injected_ophs.length injected_ophs in let* included_in_blocks = Included_in_blocks.load_from_disk ~warn_unreadable ~initial_size:(confirmations * n) ~data_dir ~filter:(fun (_, ops) -> List.exists (Included_operations.mem included_operations) ops) in let*! () = emit_event_loaded "included_in_blocks" @@ Included_in_blocks.length included_in_blocks in return { cctxt = injector_context (cctxt :> #Protocol_client_context.full); signer; tags; strategy; save_dir = data_dir; queue; injected = {injected_operations; injected_ophs}; included = {included_operations; included_in_blocks}; rollup_node_state; } (** Add an operation to the pending queue corresponding to the signer for this operation. *) let add_pending_operation state op = let open Lwt_result_syntax in let*! () = Event.(emit1 add_pending) state op in Op_queue.replace state.queue op.L1_operation.hash op (** Mark operations as injected (in [oph]). *) let add_injected_operations state oph operations = let open Lwt_result_syntax in let infos = List.map (fun op -> (op.L1_operation.hash, {op; oph})) operations in let* () = Injected_operations.replace_seq state.injected.injected_operations (List.to_seq infos) in Injected_ophs.replace state.injected.injected_ophs oph (List.map fst infos) (** [add_included_operations state oph l1_block l1_level operations] marks the [operations] as included (in the L1 batch [oph]) in the Tezos block [l1_block] of level [l1_level]. *) let add_included_operations state oph l1_block l1_level operations = let open Lwt_result_syntax in let*! () = Event.(emit3 included) state l1_block l1_level (List.map (fun o -> o.L1_operation.hash) operations) in let infos = List.map (fun op -> (op.L1_operation.hash, {op; oph; l1_block; l1_level})) operations in let* () = Included_operations.replace_seq state.included.included_operations (List.to_seq infos) in Included_in_blocks.replace state.included.included_in_blocks l1_block (l1_level, List.map fst infos) (** [remove state oph] removes the operations that correspond to the L1 batch [oph] from the injected operations in the injector state. This function is used to move operations from injected to included. *) let remove_injected_operation state oph = let open Lwt_result_syntax in match Injected_ophs.find state.injected.injected_ophs oph with | None -> (* Nothing removed *) return [] | Some mophs -> let* () = Injected_ophs.remove state.injected.injected_ophs oph in List.fold_left_es (fun removed moph -> match Injected_operations.find state.injected.injected_operations moph with | None -> return removed | Some info -> let+ () = Injected_operations.remove state.injected.injected_operations moph in info :: removed) [] mophs (** [remove state block] removes the included operations that correspond to all the L1 batches included in [block]. This function is used when [block] is on an alternative chain in the case of a reorganization. *) let remove_included_operation state block = let open Lwt_result_syntax in match Included_in_blocks.find state.included.included_in_blocks block with | None -> (* Nothing removed *) return [] | Some (_level, mophs) -> let* () = Included_in_blocks.remove state.included.included_in_blocks block in List.fold_left_es (fun removed moph -> match Included_operations.find state.included.included_operations moph with | None -> return removed | Some info -> let+ () = Included_operations.remove state.included.included_operations moph in info :: removed) [] mophs let fee_parameter_of_operations state ops = List.fold_left (fun acc {L1_operation.manager_operation = Manager op; _} -> let param = Rollup.fee_parameter state op in Injection. { minimal_fees = Tez.max acc.minimal_fees param.minimal_fees; minimal_nanotez_per_byte = Q.max acc.minimal_nanotez_per_byte param.minimal_nanotez_per_byte; minimal_nanotez_per_gas_unit = Q.max acc.minimal_nanotez_per_gas_unit param.minimal_nanotez_per_gas_unit; force_low_fee = acc.force_low_fee || param.force_low_fee; fee_cap = WithExceptions.Result.get_ok ~loc:__LOC__ Tez.(acc.fee_cap +? param.fee_cap); burn_cap = WithExceptions.Result.get_ok ~loc:__LOC__ Tez.(acc.burn_cap +? param.burn_cap); }) Injection. { minimal_fees = Tez.zero; minimal_nanotez_per_byte = Q.zero; minimal_nanotez_per_gas_unit = Q.zero; force_low_fee = false; fee_cap = Tez.zero; burn_cap = Tez.zero; } ops (** Simulate the injection of [operations]. See {!inject_operations} for the specification of [must_succeed]. *) let simulate_operations ~must_succeed state (operations : L1_operation.t list) = let open Lwt_result_syntax in let open Annotated_manager_operation in let force = match operations with | [] -> assert false | [_] -> (* If there is only one operation, fail when simulation fails *) false | _ -> ( (* We want to see which operation failed in the batch if not all must succeed *) match must_succeed with `All -> false | `At_least_one -> true) in let*! () = Event.(emit2 simulating_operations) state operations force in let fee_parameter = fee_parameter_of_operations state.rollup_node_state operations in let operations = List.map (fun {L1_operation.manager_operation = Manager operation; _} -> Annotated_manager_operation (Injection.prepare_manager_operation ~fee:Limit.unknown ~gas_limit:Limit.unknown ~storage_limit:Limit.unknown operation)) operations in let (Manager_list annot_op) = Annotated_manager_operation.manager_of_list operations in let* _, op, _, result = Injection.inject_manager_operation state.cctxt ~simulation:true (* Only simulation here *) ~force ~chain:state.cctxt#chain ~block:(`Head 0) ~source:state.signer.pkh ~src_pk:state.signer.pk ~src_sk:state.signer.sk ~successor_level:true (* Needed to simulate tx_rollup operations in the next block *) ~fee:Limit.unknown ~gas_limit:Limit.unknown ~storage_limit:Limit.unknown ~fee_parameter annot_op in return (op, Apply_results.Contents_result_list result) let inject_on_node state {shell; protocol_data = Operation_data {contents; _}} = let open Lwt_result_syntax in let unsigned_op = (shell, Contents_list contents) in let unsigned_op_bytes = Data_encoding.Binary.to_bytes_exn Operation.unsigned_encoding unsigned_op in let* signature = Client_keys_v0.sign state.cctxt ~watermark:Tezos_crypto.Signature.V0.Generic_operation state.signer.sk unsigned_op_bytes in let op : _ Operation.t = {shell; protocol_data = {contents; signature = Some signature}} in let op_bytes = Data_encoding.Binary.to_bytes_exn Operation.encoding (Operation.pack op) in Tezos_shell_services.Shell_services.Injection.operation state.cctxt ~chain:state.cctxt#chain op_bytes >>=? fun oph -> let*! () = Event.(emit1 injected) state oph in return oph (** Inject the given [operations] in an L1 batch. If [must_succeed] is [`All] then all the operations must succeed in the simulation of injection. If [must_succeed] is [`At_least_one] at least one operation in the list [operations] must be successful in the simulation. In any case, only operations which are known as successful will be included in the injected L1 batch. {b Note}: [must_succeed = `At_least_one] allows to incrementally build "or-batches" by iteratively removing operations that fail from the desired batch. *) let rec inject_operations ~must_succeed state (operations : L1_operation.t list) = let open Lwt_result_syntax in let* packed_op, result = simulate_operations ~must_succeed state operations in let results = Apply_results.to_list result in let failure = ref false in let* rev_non_failing_operations = List.fold_left2_s ~when_different_lengths: [ Exn (Failure "Unexpected error: length of operations and result differ in \ simulation"); ] (fun acc op (Apply_results.Contents_result result) -> match result with | Apply_results.Manager_operation_result { operation_result = Failed (_, error) | Backtracked (_, Some error); _; } -> let*! () = Event.(emit2 dropping_operation) state op error in failure := true ; Lwt.return acc | Apply_results.Manager_operation_result { operation_result = Applied _ | Backtracked (_, None) | Skipped _; _; } -> (* Not known to be failing *) Lwt.return (op :: acc) | _ -> (* Only manager operations *) assert false) [] operations results in if !failure then (* Invariant: must_succeed = `At_least_one, otherwise the simulation would have returned an error. We try to inject without the failing operation. *) let operations = List.rev rev_non_failing_operations in inject_operations ~must_succeed state operations else (* Inject on node for real *) let+ oph = inject_on_node state packed_op in (oph, operations) (** Returns the (upper bound on) the size of an L1 batch of operations composed of the manager operations [rev_ops]. *) let size_l1_batch state rev_ops = let contents_list = List.map (fun (op : L1_operation.t) -> let (Manager operation) = op.manager_operation in let {fee; counter; gas_limit; storage_limit} = Rollup.approximate_fee_bound state.rollup_node_state operation in let contents = Manager_operation { source = state.signer.pkh; operation; fee; counter; gas_limit; storage_limit; } in Contents contents) rev_ops in let (Contents_list contents) = match Operation.of_list contents_list with | Error _ -> (* Cannot happen: rev_ops is non empty and contains only manager operations *) assert false | Ok packed_contents_list -> packed_contents_list in let signature = Tezos_crypto.Signature.V0.zero in let branch = Block_hash.zero in let operation = { shell = {branch}; protocol_data = Operation_data {contents; signature = Some signature}; } in Data_encoding.Binary.length Operation.encoding operation (** Retrieve as many operations from the queue while remaining below the size limit. *) let get_operations_from_queue ~size_limit state = let exception Reached_limit of L1_operation.t list in let rev_ops = try Op_queue.fold (fun _oph op ops -> let new_ops = op :: ops in let new_size = size_l1_batch state new_ops in if new_size > size_limit then raise (Reached_limit ops) ; new_ops) state.queue [] with Reached_limit ops -> ops in List.rev rev_ops (* Ignore the failures of finalize and remove commitment operations. These operations fail when there are either no commitment to finalize or to remove (which can happen when there are no inbox for instance). *) let ignore_ignorable_failing_operations operations = function | Ok res -> Ok (`Injected res) | Error _ as res -> let open Result_syntax in let+ operations_to_drop = List.fold_left_e (fun to_drop op -> let (Manager operation) = op.L1_operation.manager_operation in match Rollup.ignore_failing_operation operation with | `Don't_ignore -> res | `Ignore_keep -> Ok to_drop | `Ignore_drop -> Ok (op :: to_drop)) [] operations in `Ignored operations_to_drop (** [inject_pending_operations_for ~size_limit state pending] injects operations from the pending queue [pending], whose total size does not exceed [size_limit]. Upon successful injection, the operations are removed from the queue and marked as injected. *) let inject_pending_operations ?(size_limit = Constants.max_operation_data_length) state = let open Lwt_result_syntax in (* Retrieve and remove operations from pending *) let operations_to_inject = get_operations_from_queue ~size_limit state in match operations_to_inject with | [] -> return_unit | _ -> ( let*! () = Event.(emit1 injecting_pending) state (List.length operations_to_inject) in let must_succeed = Rollup.batch_must_succeed @@ List.map (fun op -> op.L1_operation.manager_operation) operations_to_inject in let*! res = inject_operations ~must_succeed state operations_to_inject in let*? res = ignore_ignorable_failing_operations operations_to_inject res in match res with | `Injected (oph, injected_operations) -> (* Injection succeeded, remove from pending and add to injected *) let* () = List.iter_es (fun op -> Op_queue.remove state.queue op.L1_operation.hash) injected_operations in add_injected_operations state oph operations_to_inject | `Ignored operations_to_drop -> (* Injection failed but we ignore the failure. *) let* () = List.iter_es (fun op -> Op_queue.remove state.queue op.L1_operation.hash) operations_to_drop in return_unit) (** [register_included_operation state block level oph] marks the manager operations contained in the L1 batch [oph] as being included in the [block] of level [level], by moving them from the "injected" state to the "included" state. *) let register_included_operation state block level oph = let open Lwt_result_syntax in let* rmed = remove_injected_operation state oph in match rmed with | [] -> return_unit | injected_infos -> let included_mops = List.map (fun (i : injected_info) -> i.op) injected_infos in add_included_operations state oph block level included_mops (** [register_included_operations state block level oph] marks the known (by this injector) manager operations contained in [block] as being included. *) let register_included_operations state (block : Alpha_block_services.block_info) = List.iter_es (List.iter_es (fun (op : Alpha_block_services.operation) -> register_included_operation state block.hash block.header.shell.level op.hash (* TODO/TORU: Handle operations for rollup_id here with callback *))) block.Alpha_block_services.operations (** [revert_included_operations state block] marks the known (by this injector) manager operations contained in [block] as not being included any more, typically in the case of a reorganization where [block] is on an alternative chain. The operations are put back in the pending queue. *) let revert_included_operations state block = let open Lwt_result_syntax in let* included_infos = remove_included_operation state block in let*! () = Event.(emit1 revert_operations) state (List.map (fun o -> o.op.hash) included_infos) in (* TODO/TORU: https://gitlab.com/tezos/tezos/-/issues/2814 maybe put at the front of the queue for re-injection. *) List.iter_es (fun {op; _} -> let {L1_operation.manager_operation = Manager mop; _} = op in let*! requeue = Rollup.requeue_reverted_operation state.rollup_node_state mop in if requeue then add_pending_operation state op else return_unit) included_infos (** [register_confirmed_level state confirmed_level] is called when the level [confirmed_level] is known as confirmed. In this case, the operations of block which are below this level are also considered as confirmed and are removed from the "included" state. These operations cannot be part of a reorganization so there will be no need to re-inject them anymore. *) let register_confirmed_level state confirmed_level = let open Lwt_result_syntax in let*! () = Event.(emit confirmed_level) (state.signer.pkh, state.tags, confirmed_level) in Included_in_blocks.iter_es (fun block (level, _operations) -> if level <= confirmed_level then let* confirmed_ops = remove_included_operation state block in let*! () = Event.(emit2 confirmed_operations) state level (List.map (fun o -> o.op.hash) confirmed_ops) in return_unit else return_unit) state.included.included_in_blocks (** [on_new_tezos_head state head reorg] is called when there is a new Tezos head (with a potential reorganization [reorg]). It first reverts any blocks that are in the alternative branch of the reorganization and then registers the effect of the new branch (the newly included operation and confirmed operations). *) let on_new_tezos_head state (head : Alpha_block_services.block_info) (reorg : Alpha_block_services.block_info reorg) = let open Lwt_result_syntax in let*! () = Event.(emit1 new_tezos_head) state head.hash in let* () = List.iter_es (fun removed_block -> revert_included_operations state removed_block.Alpha_block_services.hash) (List.rev reorg.old_chain) in let* () = List.iter_es (fun added_block -> register_included_operations state added_block) reorg.new_chain in (* Head is already included in the reorganization, so no need to process it separately. *) let confirmed_level = Int32.sub head.Alpha_block_services.header.shell.level (Int32.of_int confirmations) in if confirmed_level >= 0l then register_confirmed_level state confirmed_level else return_unit (* The request {Request.Inject} triggers an injection of the operations the pending queue. *) let on_inject state = inject_pending_operations state module Types = struct type nonrec state = state type parameters = { cctxt : Protocol_client_context.full; data_dir : string; rollup_node_state : Rollup.rollup_node_state; strategy : injection_strategy; tags : Tags.t; } end (* The worker for the injector. *) module Worker = Worker.MakeSingle (Name) (Request) (Types) (* The queue for the requests to the injector worker is infinite. *) type worker = Worker.infinite Worker.queue Worker.t let table = Worker.create_table Queue let tags_table = Tags_table.create 7 module Handlers = struct type self = worker let on_request : type r request_error. worker -> (r, request_error) Request.t -> (r, request_error) result Lwt.t = fun w request -> let state = Worker.state w in match request with | Request.Add_pending op -> (* The execution of the request handler is protected to avoid stopping the worker in case of an exception. *) protect @@ fun () -> add_pending_operation state op | Request.New_tezos_head (head, reorg) -> protect @@ fun () -> on_new_tezos_head state head reorg | Request.Inject -> protect @@ fun () -> on_inject state type launch_error = error trace let on_launch _w signer Types.{cctxt; data_dir; rollup_node_state; strategy; tags} = init_injector cctxt ~data_dir rollup_node_state ~signer strategy tags let on_error (type a b) w st (r : (a, b) Request.t) (errs : b) : unit tzresult Lwt.t = let open Lwt_result_syntax in let state = Worker.state w in let request_view = Request.view r in let emit_and_return_errors errs = (* Errors do not stop the worker but emit an entry in the log. *) let*! () = Event.(emit3 request_failed) state request_view st errs in return_unit in match r with | Request.Add_pending _ -> emit_and_return_errors errs | Request.New_tezos_head _ -> emit_and_return_errors errs | Request.Inject -> emit_and_return_errors errs let on_completion w r _ st = let state = Worker.state w in match Request.view r with | Request.View (Add_pending _ | New_tezos_head _) -> Event.(emit2 request_completed_debug) state (Request.view r) st | View Inject -> Event.(emit2 request_completed_notice) state (Request.view r) st let on_no_request _ = Lwt.return_unit let on_close w = let state = Worker.state w in Tags.iter (Tags_table.remove tags_table) state.tags ; Lwt.return_unit end (* TODO/TORU: https://gitlab.com/tezos/tezos/-/issues/2754 Injector worker in a separate process *) let init (cctxt : #Protocol_client_context.full) ~data_dir rollup_node_state ~signers = let open Lwt_result_syntax in let signers_map = List.fold_left (fun acc (signer, strategy, tags) -> let tags = Tags.of_list tags in let strategy, tags = match Tezos_crypto.Signature.V0.Public_key_hash.Map.find_opt signer acc with | None -> (strategy, tags) | Some (other_strategy, other_tags) -> let strategy = match (strategy, other_strategy) with | `Each_block, `Each_block -> `Each_block | `Delay_block, _ | _, `Delay_block -> (* Delay_block strategy takes over because we can always wait a little bit more to inject operation which are to be injected "each block". *) `Delay_block in (strategy, Tags.union other_tags tags) in Tezos_crypto.Signature.V0.Public_key_hash.Map.add signer (strategy, tags) acc) Tezos_crypto.Signature.V0.Public_key_hash.Map.empty signers in Tezos_crypto.Signature.V0.Public_key_hash.Map.iter_es (fun signer (strategy, tags) -> let+ worker = Worker.launch table signer { cctxt = (cctxt :> Protocol_client_context.full); data_dir; rollup_node_state; strategy; tags; } (module Handlers) in ignore worker) signers_map let worker_of_signer signer_pkh = match Worker.find_opt table signer_pkh with | None -> (* TODO: https://gitlab.com/tezos/tezos/-/issues/2818 maybe lazily start worker here *) error (No_worker_for_source signer_pkh) | Some worker -> ok worker let worker_of_tag tag = match Tags_table.find_opt tags_table tag with | None -> Format.kasprintf (fun s -> error (No_worker_for_tag s)) "%a" Rollup.Tag.pp tag | Some worker -> ok worker let add_pending_operation ?source op = let open Lwt_result_syntax in let l1_operation = L1_operation.make op in let*? w = match source with | Some source -> worker_of_signer source | None -> ( match Rollup.operation_tag op with | None -> error (No_worker_for_operation l1_operation) | Some tag -> worker_of_tag tag) in let*! (_pushed : bool) = Worker.Queue.push_request w (Request.Add_pending l1_operation) in return_unit let new_tezos_head h reorg = let open Lwt_syntax in let workers = Worker.list table in List.iter_p (fun (_signer, w) -> let* (_pushed : bool) = Worker.Queue.push_request w (Request.New_tezos_head (h, reorg)) in return_unit) workers let has_tag_in ~tags state = match tags with | None -> (* Not filtering on tags *) true | Some tags -> not (Tags.disjoint state.tags tags) let has_strategy ~strategy state = match strategy with | None -> (* Not filtering on strategy *) true | Some strategy -> state.strategy = strategy let inject ?tags ?strategy () = let workers = Worker.list table in let tags = Option.map Tags.of_list tags in List.iter_p (fun (_signer, w) -> let open Lwt_syntax in let worker_state = Worker.state w in if has_tag_in ~tags worker_state && has_strategy ~strategy worker_state then let* _pushed = Worker.Queue.push_request w Request.Inject in return_unit else Lwt.return_unit) workers let shutdown () = let workers = Worker.list table in List.iter_p (fun (_signer, w) -> Worker.shutdown w) workers end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2022 Nomadic Labs, <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
errortrace.mli
open Types type position = First | Second val swap_position : position -> position val print_pos : Format.formatter -> position -> unit type expanded_type = { ty: type_expr; expanded: type_expr } (** [trivial_expansion ty] creates an [expanded_type] whose expansion is also [ty]. Usually, you want [Ctype.expand_type] instead, since the expansion carries useful information; however, in certain circumstances, the error is about the expansion of the type, meaning that actually performing the expansion produces more confusing or inaccurate output. *) val trivial_expansion : type_expr -> expanded_type type 'a diff = { got: 'a; expected: 'a } (** [map_diff f {expected;got}] is [{expected=f expected; got=f got}] *) val map_diff: ('a -> 'b) -> 'a diff -> 'b diff (** Scope escape related errors *) type 'a escape_kind = | Constructor of Path.t | Univ of type_expr (* The type_expr argument of [Univ] is always a [Tunivar _], we keep a [type_expr] to track renaming in {!Printtyp} *) | Self | Module_type of Path.t | Equation of 'a | Constraint type 'a escape = { kind : 'a escape_kind; context : type_expr option } val map_escape : ('a -> 'b) -> 'a escape -> 'b escape val explain: 'a list -> (prev:'a option -> 'a -> 'b option) -> 'b option (** Type indices *) type unification = private Unification type comparison = private Comparison type fixed_row_case = | Cannot_be_closed | Cannot_add_tags of string list type 'variety variant = (* Common *) | Incompatible_types_for : string -> _ variant | No_tags : position * (Asttypes.label * row_field) list -> _ variant (* Unification *) | No_intersection : unification variant | Fixed_row : position * fixed_row_case * fixed_explanation -> unification variant (* Equality & Moregen *) | Presence_not_guaranteed_for : position * string -> comparison variant | Openness : position (* Always [Second] for Moregen *) -> comparison variant type 'variety obj = (* Common *) | Missing_field : position * string -> _ obj | Abstract_row : position -> _ obj (* Unification *) | Self_cannot_be_closed : unification obj type ('a, 'variety) elt = (* Common *) | Diff : 'a diff -> ('a, _) elt | Variant : 'variety variant -> ('a, 'variety) elt | Obj : 'variety obj -> ('a, 'variety) elt | Escape : 'a escape -> ('a, _) elt | Incompatible_fields : { name:string; diff: type_expr diff } -> ('a, _) elt (* Unification & Moregen; included in Equality for simplicity *) | Rec_occur : type_expr * type_expr -> ('a, _) elt type ('a, 'variety) t = ('a, 'variety) elt list type 'variety trace = (type_expr, 'variety) t type 'variety error = (expanded_type, 'variety) t val map : ('a -> 'b) -> ('a, 'variety) t -> ('b, 'variety) t val incompatible_fields : name:string -> got:type_expr -> expected:type_expr -> (type_expr, _) elt val swap_trace : ('a, 'variety) t -> ('a, 'variety) t (** The traces (['variety t]) are the core error types. However, we bundle them up into three "top-level" error types, which are used elsewhere: [unification_error], [equality_error], and [moregen_error]. In the case of [equality_error], this has to bundle in extra information; in general, it distinguishes the three types of errors and allows us to distinguish traces that are being built (or processed) from those that are complete and have become the final error. These error types have the invariants that their traces are nonempty; we ensure that through three smart constructors with matching names. *) type unification_error = private { trace : unification error } [@@unboxed] type equality_error = private { trace : comparison error; subst : (type_expr * type_expr) list } type moregen_error = private { trace : comparison error } [@@unboxed] val unification_error : trace:unification error -> unification_error val equality_error : trace:comparison error -> subst:(type_expr * type_expr) list -> equality_error val moregen_error : trace:comparison error -> moregen_error (** Wraps up the two different kinds of [comparison] errors in one type *) type comparison_error = | Equality_error of equality_error | Moregen_error of moregen_error (** Lift [swap_trace] to [unification_error] *) val swap_unification_error : unification_error -> unification_error module Subtype : sig type 'a elt = | Diff of 'a diff type 'a t = 'a elt list (** Just as outside [Subtype], we split traces, completed traces, and complete errors. However, in a minor asymmetry, the name [Subtype.error_trace] corresponds to the outside [error] type, and [Subtype.error] corresponds to the outside [*_error] types (e.g., [unification_error]). This [error] type has the invariant that the subtype trace is nonempty; note that no such invariant is imposed on the unification trace. *) type trace = type_expr t type error_trace = expanded_type t type unification_error_trace = unification error (** To avoid shadowing *) type nonrec error = private { trace : error_trace ; unification_trace : unification error } val error : trace:error_trace -> unification_trace:unification_error_trace -> error val map : ('a -> 'b) -> 'a t -> 'b t end
(**************************************************************************) (* *) (* OCaml *) (* *) (* Florian Angeletti, projet Cambium, Inria Paris *) (* Antal Spector-Zabusky, Jane Street, New York *) (* *) (* Copyright 2018 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* Copyright 2021 Jane Street Group LLC *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************)
btree.ml
include Btree_intf module Make (InKey : Input.Key) (InValue : Input.Value) (Size : Input.Size) = Ext.Make_ext (InKey) (InValue) (Size)
(* * Copyright (c) 2021 Tarides <contact@tarides.com> * Copyright (c) 2021 Gabriel Belouze <gabriel.belouze@ens.psl.eu> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
Backtrackable_ref.mli
(** {1 Backtrackable ref} *) type 'a t val create : ?copy:('a -> 'a) -> 'a -> 'a t (** Create a backtrackable reference holding the given value initially. @param copy if provided, will be used to copy the value when [push_level] is called. *) val set : 'a t -> 'a -> unit (** Set the reference's current content *) val get : 'a t -> 'a (** Get the reference's current content *) val update : 'a t -> ('a -> 'a) -> unit (** Update the reference's current content *) val push_level : _ t -> unit (** Push a backtracking level, copying the current value on top of some stack. The [copy] function will be used if it was provided in {!create}. *) val n_levels : _ t -> int (** Number of saved values *) val pop_levels : _ t -> int -> unit (** Pop [n] levels, restoring to the value the reference was storing [n] calls to [push_level] earlier. @raise Invalid_argument if [n] is bigger than [n_levels]. *)
acl_unit_test.ml
open Acl let () = List.iter (fun (string, matcher) -> try if parse string <> matcher then Format.kasprintf failwith "Parsing returned unexpected value for path %S" string with Invalid_argument _ -> Format.kasprintf failwith "Parsing failed for path %S" string) [ ("/", {meth = Any; path = Exact []}); (" /", {meth = Any; path = Exact []}); (" /", {meth = Any; path = Exact []}); ("GET /", {meth = Exact `GET; path = Exact []}); ("GET/", {meth = Exact `GET; path = Exact []}); ("GET /", {meth = Exact `GET; path = Exact []}); ("POST /", {meth = Exact `POST; path = Exact []}); ("/**", {meth = Any; path = FollowedByAnySuffix []}); ("DELETE /**", {meth = Exact `DELETE; path = FollowedByAnySuffix []}); ("DELETE/**", {meth = Exact `DELETE; path = FollowedByAnySuffix []}); ( "/a/b/c/d/e", { meth = Any; path = Exact [Literal "a"; Literal "b"; Literal "c"; Literal "d"; Literal "e"]; } ); ( "/*/a/*/b", { meth = Any; path = Exact [Wildcard; Literal "a"; Wildcard; Literal "b"]; } ); ( "/*/a/*/b/**", { meth = Any; path = FollowedByAnySuffix [Wildcard; Literal "a"; Wildcard; Literal "b"]; } ); ( "PATCH /*/a/*/b/**", { meth = Exact `PATCH; path = FollowedByAnySuffix [Wildcard; Literal "a"; Wildcard; Literal "b"]; } ); ( "/%3F%3F%3F/**", {meth = Any; path = FollowedByAnySuffix [Literal "???"]} ); ("/%2A%2F%25", {meth = Any; path = Exact [Literal "*/%"]}) ] let () = List.iter (fun string -> try let _ = parse string in Format.kasprintf failwith "Parsing unexepectedly succeeded for invalid input %S" string with Invalid_argument _ -> ()) [ "NOTAMETH /a/b"; "GET /a*"; "GET /a&"; "GET /a?"; "GET /=a"; " GET /a"; " GET/"; "a"; " "; "GET "; "GET"; "G%45T/"; "GET%2F"; "GE/T"; "GET "; "FOOOOOOOO"; "\\"; ""; "GETGET/"; "GETGET/*"; "GETPUT/*"; "GETx/*"; "GET\n/*"; "PATCH-/*"; "PATCH#/*"; "PUT**"; "PUT*/"; "/a*"; "/**/*"; "/**/*/*/**"; "/**/**"; "/**/a"; "/**/a/b/*/c"; "/**/a/b*"; "/a/%25*%2524" ] let () = List.iter (fun (policy, meth, path, exp) -> if allowed policy ~meth ~path <> exp then Format.kasprintf failwith "\"%s %a\" Unexpectedly %s" (Resto.string_of_meth meth) Format.( pp_print_list ~pp_sep:(fun ppf () -> pp_print_char ppf '/') pp_print_string) path (if exp then "forbidden" else "allowed")) [ (Allow_all {except = []}, `GET, [], true); (Allow_all {except = []}, `GET, ["still"; "this"], true); (Deny_all {except = []}, `GET, [], false); (Deny_all {except = []}, `GET, ["still"; "this"], false); (Allow_all {except = [{meth = Any; path = Exact []}]}, `GET, [], false); (Allow_all {except = [{meth = Any; path = Exact []}]}, `GET, ["a"], true); (Deny_all {except = [{meth = Any; path = Exact []}]}, `GET, [], true); ( Deny_all {except = [{meth = Any; path = Exact []}]}, `GET, ["here"], false ); ( Deny_all {except = [{meth = Exact `GET; path = Exact []}]}, `GET, [], true ); ( Deny_all {except = [{meth = Exact `GET; path = Exact []}]}, `POST, [], false ); ( Deny_all {except = [{meth = Exact `GET; path = Exact []}]}, `PATCH, [], false ); ( Deny_all {except = [{meth = Exact `POST; path = Exact []}]}, `GET, [], false ); ( Deny_all {except = [{meth = Exact `POST; path = Exact []}]}, `POST, [], true ); ( Deny_all {except = [{meth = Exact `POST; path = Exact []}]}, `DELETE, [], false ); ( Deny_all {except = [{meth = Any; path = FollowedByAnySuffix []}]}, `GET, [], true ); ( Deny_all {except = [{meth = Any; path = FollowedByAnySuffix []}]}, `POST, [], true ); ( Deny_all {except = [{meth = Any; path = FollowedByAnySuffix []}]}, `GET, ["a"; "b"; "v"], true ); ( Deny_all {except = [{meth = Any; path = FollowedByAnySuffix []}]}, `POST, ["this"; "and"; "that"], true ); ( Deny_all {except = [{meth = Any; path = FollowedByAnySuffix []}]}, `DELETE, ["none"], true ); ( Deny_all { except = [ { meth = Any; path = Exact [Wildcard; Literal "a"; Wildcard; Literal "b"]; }; { meth = Any; path = Exact [Wildcard; Literal "0"; Wildcard; Literal "1"]; } ]; }, `GET, ["this"; "a"; "that"; "b"], true ); ( Deny_all { except = [ { meth = Any; path = Exact [Wildcard; Literal "a"; Wildcard; Literal "b"]; }; { meth = Any; path = Exact [Wildcard; Literal "0"; Wildcard; Literal "1"]; } ]; }, `GET, ["foo"; "a"; "barbarbar"; "b"], true ); ( Deny_all { except = [ { meth = Any; path = Exact [Wildcard; Literal "a"; Wildcard; Literal "b"]; }; { meth = Any; path = Exact [Wildcard; Literal "0"; Wildcard; Literal "1"]; } ]; }, `GET, ["foo"; "0"; "barbarbar"; "1"], true ); ( Deny_all { except = [ { meth = Any; path = Exact [Wildcard; Literal "a"; Wildcard; Literal "b"]; }; { meth = Any; path = Exact [Wildcard; Literal "0"; Wildcard; Literal "1"]; } ]; }, `GET, ["foo"; "1"; "barbarbar"; "0"], false ); ( Deny_all { except = [ { meth = Any; path = Exact [Wildcard; Literal "a"; Wildcard; Literal "b"]; }; { meth = Any; path = Exact [Wildcard; Literal "0"; Wildcard; Literal "1"]; } ]; }, `GET, ["foo"; "0"; "1"], false ); ( Deny_all { except = [ { meth = Any; path = Exact [Wildcard; Literal "a"; Wildcard; Literal "b"]; }; { meth = Any; path = Exact [Wildcard; Literal "0"; Wildcard; Literal "1"]; } ]; }, `GET, ["foo"; "a"; "barbarbar"; "1"], false ) ]
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *) (* *) (* 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. *) (* *) (*****************************************************************************)
mirage_impl_console.mli
type console val console : console Functoria.typ val default_console : console Functoria.impl val custom_console : string -> console Functoria.impl
clang__bindings.mli
(* This file is auto-generated by stubgen tool. It should not be modified by hand and it should not be versioned (except by continuous integration on the dedicated bootstrap branch). *) external get_build_session_timestamp : unit -> int = "clang_getBuildSessionTimestamp_wrapper"[@@ocaml.doc "Return the timestamp for use with Clang's -fbuild-session-timestamp= option."] type cxvirtualfileoverlay external virtual_file_overlay_create : int -> cxvirtualfileoverlay = "clang_VirtualFileOverlay_create_wrapper" [@@ocaml.doc "Create a CXVirtualFileOverlay object. Must be disposed with clang_VirtualFileOverlay_dispose()."] type cxerrorcode = | Failure [@ocaml.doc "A generic error code, no further details are available."] | Crashed [@ocaml.doc "libclang crashed while performing the requested operation."] | InvalidArguments [@ocaml.doc "The function detected that the arguments violate the function contract."] | ASTReadError [@ocaml.doc "An AST deserialization error has occurred."] [@@deriving refl][@@ocaml.doc "Error codes returned by libclang routines."] external virtual_file_overlay_add_file_mapping : cxvirtualfileoverlay -> virtual_path:string -> real_path:string -> (unit, cxerrorcode) result = "clang_VirtualFileOverlay_addFileMapping_wrapper"[@@ocaml.doc "Map an absolute virtual file path to an absolute real one. The virtual path must be canonicalized (not contain \".\"/\"..\")."] external virtual_file_overlay_set_case_sensitivity : cxvirtualfileoverlay -> int -> (unit, cxerrorcode) result = "clang_VirtualFileOverlay_setCaseSensitivity_wrapper"[@@ocaml.doc "Set the case sensitivity for the CXVirtualFileOverlay object. The CXVirtualFileOverlay object is case-sensitive by default, this option can be used to override the default."] external virtual_file_overlay_write_to_buffer : cxvirtualfileoverlay -> int -> (string, cxerrorcode) result = "clang_VirtualFileOverlay_writeToBuffer_wrapper"[@@ocaml.doc "Write out the CXVirtualFileOverlay object to a char buffer."] type cxmodulemapdescriptor external module_map_descriptor_create : int -> cxmodulemapdescriptor = "clang_ModuleMapDescriptor_create_wrapper" [@@ocaml.doc "Create a CXModuleMapDescriptor object. Must be disposed with clang_ModuleMapDescriptor_dispose()."] external module_map_descriptor_set_framework_module_name : cxmodulemapdescriptor -> string -> (unit, cxerrorcode) result = "clang_ModuleMapDescriptor_setFrameworkModuleName_wrapper"[@@ocaml.doc "Sets the framework module name that the module.map describes."] external module_map_descriptor_set_umbrella_header : cxmodulemapdescriptor -> string -> (unit, cxerrorcode) result = "clang_ModuleMapDescriptor_setUmbrellaHeader_wrapper"[@@ocaml.doc "Sets the umbrealla header name that the module.map describes."] external module_map_descriptor_write_to_buffer : cxmodulemapdescriptor -> int -> (string, cxerrorcode) result = "clang_ModuleMapDescriptor_writeToBuffer_wrapper"[@@ocaml.doc "Write out the CXModuleMapDescriptor object to a char buffer."] type cxindex external create_index : exclude_declarations_from_pch:bool -> display_diagnostics:bool -> cxindex = "clang_createIndex_wrapper"[@@ocaml.doc "Provides a shared context for creating translation units."] module Cxglobaloptflags : sig type t external (+) : t -> t -> t = "%orint" val (-) : t -> t -> t external (&) : t -> t -> t = "%andint" external ( * ) : t -> t -> t = "%xorint" val subset : t -> t -> bool val none : t val thread_background_priority_for_indexing : t val thread_background_priority_for_editing : t val thread_background_priority_for_all : t end external cxindex_set_global_options : cxindex -> Cxglobaloptflags.t -> unit = "clang_CXIndex_setGlobalOptions_wrapper"[@@ocaml.doc "Sets general options associated with a CXIndex."] external cxindex_get_global_options : cxindex -> Cxglobaloptflags.t = "clang_CXIndex_getGlobalOptions_wrapper" [@@ocaml.doc "Gets the general options associated with a CXIndex."] external cxindex_set_invocation_emission_path_option : cxindex -> string -> unit = "clang_CXIndex_setInvocationEmissionPathOption_wrapper"[@@ocaml.doc "Sets the invocation emission path option in a CXIndex."] type cxfile external get_file_name : cxfile -> string = "clang_getFileName_wrapper" [@@ocaml.doc "Retrieve the complete file and path name of the given file."] external get_file_time : cxfile -> int = "clang_getFileTime_wrapper"[@@ocaml.doc "Retrieve the last modification time of the given file."] type cxfileuniqueid = (int * int * int)[@@ocaml.doc "Uniquely identifies a CXFile, that refers to the same underlying file, across an indexing session."] external get_file_unique_id : cxfile -> cxfileuniqueid option = "clang_getFileUniqueID_wrapper"[@@ocaml.doc "Retrieve the unique ID for the given file."] type cxtranslationunit external is_file_multiple_include_guarded : cxtranslationunit -> cxfile -> bool = "clang_isFileMultipleIncludeGuarded_wrapper"[@@ocaml.doc "Determine whether the given header is guarded against multiple inclusions, either with the conventional #ifndef/#define/#endif macro guards or with #pragma once."] external get_file : cxtranslationunit -> string -> cxfile = "clang_getFile_wrapper"[@@ocaml.doc "Retrieve a file handle within the given translation unit."] external get_file_contents : cxtranslationunit -> cxfile -> string option = "clang_getFileContents_wrapper"[@@ocaml.doc "Retrieve the buffer associated with the given file."] external file_is_equal : cxfile -> cxfile -> bool = "clang_File_isEqual_wrapper"[@@ocaml.doc "Returns non-zero if the file1 and file2 point to the same file, or they are both NULL."] external file_try_get_real_path_name : cxfile -> string = "clang_File_tryGetRealPathName_wrapper"[@@ocaml.doc "Returns the real path name of file."] type cxsourcelocation[@@ocaml.doc "Identifies a specific source location within a translation unit."] external get_null_location : unit -> cxsourcelocation = "clang_getNullLocation_wrapper"[@@ocaml.doc "Retrieve a NULL (invalid) source location."] external equal_locations : cxsourcelocation -> cxsourcelocation -> bool = "clang_equalLocations_wrapper"[@@ocaml.doc "Determine whether two source locations, which must refer into the same translation unit, refer to exactly the same point in the source code."] external get_location : cxtranslationunit -> cxfile -> line:int -> column:int -> cxsourcelocation = "clang_getLocation_wrapper"[@@ocaml.doc "Retrieves the source location associated with a given file/line/column in a particular translation unit."] external get_location_for_offset : cxtranslationunit -> cxfile -> int -> cxsourcelocation = "clang_getLocationForOffset_wrapper"[@@ocaml.doc "Retrieves the source location associated with a given character offset in a particular translation unit."] external location_is_in_system_header : cxsourcelocation -> bool = "clang_Location_isInSystemHeader_wrapper" [@@ocaml.doc "Returns non-zero if the given source location is in a system header."] external location_is_from_main_file : cxsourcelocation -> bool = "clang_Location_isFromMainFile_wrapper"[@@ocaml.doc "Returns non-zero if the given source location is in the main file of the corresponding translation unit."] type cxsourcerange[@@ocaml.doc "Identifies a half-open character range in the source code."] external get_null_range : unit -> cxsourcerange = "clang_getNullRange_wrapper"[@@ocaml.doc "Retrieve a NULL (invalid) source range."] external get_range : cxsourcelocation -> cxsourcelocation -> cxsourcerange = "clang_getRange_wrapper"[@@ocaml.doc "Retrieve a source range given the beginning and ending source locations."] external equal_ranges : cxsourcerange -> cxsourcerange -> bool = "clang_equalRanges_wrapper" [@@ocaml.doc "Determine whether two ranges are equivalent."] external range_is_null : cxsourcerange -> bool = "clang_Range_isNull_wrapper" [@@ocaml.doc "Returns non-zero if range is null."] external get_expansion_location : cxsourcelocation -> (cxfile * int * int * int) = "clang_getExpansionLocation_wrapper"[@@ocaml.doc "Retrieve the file, line, column, and offset represented by the given source location."] external get_presumed_location : cxsourcelocation -> (string * int * int) = "clang_getPresumedLocation_wrapper"[@@ocaml.doc "Retrieve the file, line and column represented by the given source location, as specified in a # line directive."] external get_instantiation_location : cxsourcelocation -> (cxfile * int * int * int) = "clang_getInstantiationLocation_wrapper"[@@ocaml.doc "Legacy API to retrieve the file, line, column, and offset represented by the given source location."] external get_spelling_location : cxsourcelocation -> (cxfile * int * int * int) = "clang_getSpellingLocation_wrapper"[@@ocaml.doc "Retrieve the file, line, column, and offset represented by the given source location."] external get_file_location : cxsourcelocation -> (cxfile * int * int * int) = "clang_getFileLocation_wrapper"[@@ocaml.doc "Retrieve the file, line, column, and offset represented by the given source location."] external get_range_start : cxsourcerange -> cxsourcelocation = "clang_getRangeStart_wrapper"[@@ocaml.doc "Retrieve a source location representing the first character within a source range."] external get_range_end : cxsourcerange -> cxsourcelocation = "clang_getRangeEnd_wrapper"[@@ocaml.doc "Retrieve a source location representing the last character within a source range."] external get_skipped_ranges : cxtranslationunit -> cxfile -> cxsourcerange array = "clang_getSkippedRanges_wrapper"[@@ocaml.doc "Retrieve all ranges that were skipped by the preprocessor."] external get_all_skipped_ranges : cxtranslationunit -> cxsourcerange array = "clang_getAllSkippedRanges_wrapper"[@@ocaml.doc "Retrieve all ranges from all files that were skipped by the preprocessor."] type cxdiagnosticset external get_num_diagnostics_in_set : cxdiagnosticset -> int = "clang_getNumDiagnosticsInSet_wrapper"[@@ocaml.doc "Determine the number of diagnostics in a CXDiagnosticSet."] type cxdiagnostic external get_diagnostic_in_set : cxdiagnosticset -> int -> cxdiagnostic = "clang_getDiagnosticInSet_wrapper" [@@ocaml.doc "Retrieve a diagnostic associated with the given CXDiagnosticSet."] type cxloaddiag_error = | Unknown [@ocaml.doc "Indicates that an unknown error occurred while attempting to deserialize diagnostics."] | CannotLoad [@ocaml.doc "Indicates that the file containing the serialized diagnostics could not be opened."] | InvalidFile [@ocaml.doc "Indicates that the serialized diagnostics file is invalid or corrupt."] [@@deriving refl][@@ocaml.doc "Describes the kind of error that occurred (if any) in a call to clang_loadDiagnostics."] external load_diagnostics : string -> (cxdiagnosticset, (cxloaddiag_error * string)) result = "clang_loadDiagnostics_wrapper"[@@ocaml.doc "Deserialize a set of diagnostics from a Clang diagnostics bitcode file."] external get_child_diagnostics : cxdiagnostic -> cxdiagnosticset = "clang_getChildDiagnostics_wrapper" [@@ocaml.doc "Retrieve the child diagnostics of a CXDiagnostic."] external get_num_diagnostics : cxtranslationunit -> int = "clang_getNumDiagnostics_wrapper"[@@ocaml.doc "Determine the number of diagnostics produced for the given translation unit."] external get_diagnostic : cxtranslationunit -> int -> cxdiagnostic = "clang_getDiagnostic_wrapper" [@@ocaml.doc "Retrieve a diagnostic associated with the given translation unit."] external get_diagnostic_set_from_tu : cxtranslationunit -> cxdiagnosticset = "clang_getDiagnosticSetFromTU_wrapper"[@@ocaml.doc "Retrieve the complete set of diagnostics associated with a translation unit."] module Cxdiagnosticdisplayoptions : sig type t external (+) : t -> t -> t = "%orint" val (-) : t -> t -> t external (&) : t -> t -> t = "%andint" external ( * ) : t -> t -> t = "%xorint" val subset : t -> t -> bool val zero : t val display_source_location : t val display_column : t val display_source_ranges : t val display_option : t val display_category_id : t val display_category_name : t end external format_diagnostic : cxdiagnostic -> Cxdiagnosticdisplayoptions.t -> string = "clang_formatDiagnostic_wrapper"[@@ocaml.doc "Format the given diagnostic in a manner that is suitable for display."] external default_diagnostic_display_options : unit -> Cxdiagnosticdisplayoptions.t = "clang_defaultDiagnosticDisplayOptions_wrapper"[@@ocaml.doc "Retrieve the set of display options most similar to the default behavior of the clang compiler."] type cxdiagnosticseverity = | Ignored [@ocaml.doc "A diagnostic that has been suppressed, e.g., by a command-line option."] | Note [@ocaml.doc "This diagnostic is a note that should be attached to the previous (non-note) diagnostic."] | Warning [@ocaml.doc "This diagnostic indicates suspicious code that may not be wrong."] | Error [@ocaml.doc "This diagnostic indicates that the code is ill-formed."] | Fatal [@ocaml.doc "This diagnostic indicates that the code is ill-formed such that future parser recovery is unlikely to produce useful results."] [@@deriving refl][@@ocaml.doc "Describes the severity of a particular diagnostic."] external get_diagnostic_severity : cxdiagnostic -> cxdiagnosticseverity = "clang_getDiagnosticSeverity_wrapper"[@@ocaml.doc "Determine the severity of the given diagnostic."] external get_diagnostic_location : cxdiagnostic -> cxsourcelocation = "clang_getDiagnosticLocation_wrapper" [@@ocaml.doc "Retrieve the source location of the given diagnostic."] external get_diagnostic_spelling : cxdiagnostic -> string = "clang_getDiagnosticSpelling_wrapper"[@@ocaml.doc "Retrieve the text of the given diagnostic."] external get_diagnostic_option : cxdiagnostic -> (string * string) = "clang_getDiagnosticOption_wrapper" [@@ocaml.doc "Retrieve the name of the command-line option that enabled this diagnostic."] external get_diagnostic_category : cxdiagnostic -> int = "clang_getDiagnosticCategory_wrapper"[@@ocaml.doc "Retrieve the category number for this diagnostic."] external get_diagnostic_category_text : cxdiagnostic -> string = "clang_getDiagnosticCategoryText_wrapper"[@@ocaml.doc "Retrieve the diagnostic category text for a given diagnostic."] external get_diagnostic_num_ranges : cxdiagnostic -> int = "clang_getDiagnosticNumRanges_wrapper"[@@ocaml.doc "Determine the number of source ranges associated with the given diagnostic."] external get_diagnostic_range : cxdiagnostic -> int -> cxsourcerange = "clang_getDiagnosticRange_wrapper" [@@ocaml.doc "Retrieve a source range associated with the diagnostic."] external get_diagnostic_num_fix_its : cxdiagnostic -> int = "clang_getDiagnosticNumFixIts_wrapper"[@@ocaml.doc "Determine the number of fix-it hints associated with the given diagnostic."] external get_diagnostic_fix_it : cxdiagnostic -> int -> cxsourcerange -> (string * cxsourcerange) = "clang_getDiagnosticFixIt_wrapper"[@@ocaml.doc "Retrieve the replacement information for a given fix-it."] external get_translation_unit_spelling : cxtranslationunit -> string = "clang_getTranslationUnitSpelling_wrapper" [@@ocaml.doc "Get the original translation unit source file name."] type cxunsavedfile = { filename: string [@ocaml.doc "The file whose contents have not yet been saved."]; contents: string [@ocaml.doc "A buffer containing the unsaved contents of this file."]} [@@deriving refl][@@ocaml.doc "Provides the contents of a file that has not yet been saved to disk."] external create_translation_unit_from_source_file : cxindex -> string -> string array -> cxunsavedfile array -> cxtranslationunit = "clang_createTranslationUnitFromSourceFile_wrapper"[@@ocaml.doc "Return the CXTranslationUnit for a given source file and the provided command line arguments one would pass to the compiler."] external create_translation_unit : cxindex -> string -> cxtranslationunit = "clang_createTranslationUnit_wrapper"[@@ocaml.doc "Same as clang_createTranslationUnit2, but returns the CXTranslationUnit instead of an error code. In case of an error this routine returns a NULL CXTranslationUnit, without further detailed error codes."] external create_translation_unit2 : cxindex -> string -> (cxtranslationunit, cxerrorcode) result = "clang_createTranslationUnit2_wrapper"[@@ocaml.doc "Create a translation unit from an AST file ( -emit-ast)."] module Cxtranslationunit_flags : sig type t external (+) : t -> t -> t = "%orint" val (-) : t -> t -> t external (&) : t -> t -> t = "%andint" external ( * ) : t -> t -> t = "%xorint" val subset : t -> t -> bool val none : t val detailed_preprocessing_record : t val incomplete : t val precompiled_preamble : t val cache_completion_results : t val for_serialization : t val cxxchained_pch : t val skip_function_bodies : t val include_brief_comments_in_code_completion : t val create_preamble_on_first_parse : t val keep_going : t val single_file_parse : t val limit_skip_function_bodies_to_preamble : t end external default_editing_translation_unit_options : unit -> Cxtranslationunit_flags.t = "clang_defaultEditingTranslationUnitOptions_wrapper"[@@ocaml.doc "Returns the set of flags that is suitable for parsing a translation unit that is being edited."] external parse_translation_unit : cxindex -> string -> string array -> cxunsavedfile array -> Cxtranslationunit_flags.t -> cxtranslationunit option = "clang_parseTranslationUnit_wrapper"[@@ocaml.doc "Same as clang_parseTranslationUnit2, but returns the CXTranslationUnit instead of an error code. In case of an error this routine returns a NULL CXTranslationUnit, without further detailed error codes."] external parse_translation_unit2 : cxindex -> string -> string array -> cxunsavedfile array -> Cxtranslationunit_flags.t -> (cxtranslationunit, cxerrorcode) result = "clang_parseTranslationUnit2_wrapper"[@@ocaml.doc "Parse the given source file and the translation unit corresponding to that file."] external parse_translation_unit2_full_argv : cxindex -> string -> string array -> cxunsavedfile array -> Cxtranslationunit_flags.t -> (cxtranslationunit, cxerrorcode) result = "clang_parseTranslationUnit2FullArgv_wrapper"[@@ocaml.doc "Same as clang_parseTranslationUnit2 but requires a full command line for command_line_args including argv\\[0\\]. This is useful if the standard library paths are relative to the binary."] external default_save_options : cxtranslationunit -> int = "clang_defaultSaveOptions_wrapper"[@@ocaml.doc "Returns the set of flags that is suitable for saving a translation unit."] type cxsaveerror = | Unknown [@ocaml.doc "Indicates that an unknown error occurred while attempting to save the file."] | TranslationErrors [@ocaml.doc "Indicates that errors during translation prevented this attempt to save the translation unit."] | InvalidTU [@ocaml.doc "Indicates that the translation unit to be saved was somehow invalid (e.g., NULL)."] [@@deriving refl][@@ocaml.doc "Describes the kind of error that occurred (if any) in a call to clang_saveTranslationUnit()."] module Cxsavetranslationunit_flags : sig type t external (+) : t -> t -> t = "%orint" val (-) : t -> t -> t external (&) : t -> t -> t = "%andint" external ( * ) : t -> t -> t = "%xorint" val subset : t -> t -> bool val none : t end external save_translation_unit : cxtranslationunit -> string -> Cxsavetranslationunit_flags.t -> (unit, cxsaveerror) result = "clang_saveTranslationUnit_wrapper"[@@ocaml.doc "Saves a translation unit into a serialized representation of that translation unit on disk."] external suspend_translation_unit : cxtranslationunit -> int = "clang_suspendTranslationUnit_wrapper"[@@ocaml.doc "Suspend a translation unit in order to free memory associated with it."] module Cxreparse_flags : sig type t external (+) : t -> t -> t = "%orint" val (-) : t -> t -> t external (&) : t -> t -> t = "%andint" external ( * ) : t -> t -> t = "%xorint" val subset : t -> t -> bool val none : t end external default_reparse_options : cxtranslationunit -> Cxreparse_flags.t = "clang_defaultReparseOptions_wrapper"[@@ocaml.doc "Returns the set of flags that is suitable for reparsing a translation unit."] external reparse_translation_unit : cxtranslationunit -> cxunsavedfile array -> Cxreparse_flags.t -> (unit, cxerrorcode) result = "clang_reparseTranslationUnit_wrapper"[@@ocaml.doc "Reparse the source files that produced this translation unit."] type cxturesourceusagekind = | AST | Identifiers | Selectors | GlobalCompletionResults | SourceManagerContentCache | AST_SideTables | SourceManager_Membuffer_Malloc | SourceManager_Membuffer_MMap | ExternalASTSource_Membuffer_Malloc | ExternalASTSource_Membuffer_MMap | Preprocessor | PreprocessingRecord | SourceManager_DataStructures | Preprocessor_HeaderSearch [@@deriving refl][@@ocaml.doc "Categorizes how memory is being used by a translation unit."] external get_turesource_usage_name : cxturesourceusagekind -> string = "clang_getTUResourceUsageName_wrapper" [@@ocaml.doc "Returns the human-readable null-terminated C string that represents the name of the memory category. This string should never be freed."] type cxturesourceusage[@@ocaml.doc "The memory usage of a CXTranslationUnit, broken into categories."] external get_cxturesource_usage : cxtranslationunit -> cxturesourceusage = "clang_getCXTUResourceUsage_wrapper"[@@ocaml.doc "Return the memory usage of a translation unit. This object should be released with clang_disposeCXTUResourceUsage()."] type cxtargetinfo external get_translation_unit_target_info : cxtranslationunit -> cxtargetinfo = "clang_getTranslationUnitTargetInfo_wrapper"[@@ocaml.doc "Get target information for this translation unit."] external target_info_get_triple : cxtargetinfo -> string = "clang_TargetInfo_getTriple_wrapper"[@@ocaml.doc "Get the normalized target triple as a string."] external target_info_get_pointer_width : cxtargetinfo -> int = "clang_TargetInfo_getPointerWidth_wrapper"[@@ocaml.doc "Get the pointer width of the target in bits."] type cxcursorkind = | UnexposedDecl [@ocaml.doc "A declaration whose specific kind is not exposed via this interface."] | StructDecl [@ocaml.doc "A C or C++ struct."] | UnionDecl [@ocaml.doc "A C or C++ union."] | ClassDecl [@ocaml.doc "A C++ class."] | EnumDecl [@ocaml.doc "An enumeration."] | FieldDecl [@ocaml.doc "A field (in C) or non-static data member (in C++) in a struct, union, or C++ class."] | EnumConstantDecl [@ocaml.doc "An enumerator constant."] | FunctionDecl [@ocaml.doc "A function."] | VarDecl [@ocaml.doc "A variable."] | ParmDecl [@ocaml.doc "A function or method parameter."] | ObjCInterfaceDecl [@ocaml.doc "An Objective-C \\@interface."] | ObjCCategoryDecl [@ocaml.doc "An Objective-C \\@interface for a category."] | ObjCProtocolDecl [@ocaml.doc "An Objective-C \\@protocol declaration."] | ObjCPropertyDecl [@ocaml.doc "An Objective-C \\@property declaration."] | ObjCIvarDecl [@ocaml.doc "An Objective-C instance variable."] | ObjCInstanceMethodDecl [@ocaml.doc "An Objective-C instance method."] | ObjCClassMethodDecl [@ocaml.doc "An Objective-C class method."] | ObjCImplementationDecl [@ocaml.doc "An Objective-C \\@implementation."] | ObjCCategoryImplDecl [@ocaml.doc "An Objective-C \\@implementation for a category."] | TypedefDecl [@ocaml.doc "A typedef."] | CXXMethod [@ocaml.doc "A C++ class method."] | Namespace [@ocaml.doc "A C++ namespace."] | LinkageSpec [@ocaml.doc "A linkage specification, e.g. 'extern \"C\"'."] | Constructor [@ocaml.doc "A C++ constructor."] | Destructor [@ocaml.doc "A C++ destructor."] | ConversionFunction [@ocaml.doc "A C++ conversion function."] | TemplateTypeParameter [@ocaml.doc "A C++ template type parameter."] | NonTypeTemplateParameter [@ocaml.doc "A C++ non-type template parameter."] | TemplateTemplateParameter [@ocaml.doc "A C++ template template parameter."] | FunctionTemplate [@ocaml.doc "A C++ function template."] | ClassTemplate [@ocaml.doc "A C++ class template."] | ClassTemplatePartialSpecialization [@ocaml.doc "A C++ class template partial specialization."] | NamespaceAlias [@ocaml.doc "A C++ namespace alias declaration."] | UsingDirective [@ocaml.doc "A C++ using directive."] | UsingDeclaration [@ocaml.doc "A C++ using declaration."] | TypeAliasDecl [@ocaml.doc "A C++ alias declaration"] | ObjCSynthesizeDecl [@ocaml.doc "An Objective-C \\@synthesize definition."] | ObjCDynamicDecl [@ocaml.doc "An Objective-C \\@dynamic definition."] | CXXAccessSpecifier [@ocaml.doc "An access specifier."] | ObjCSuperClassRef [@ocaml.doc "An access specifier."] | ObjCProtocolRef [@ocaml.doc "An access specifier."] | ObjCClassRef [@ocaml.doc "An access specifier."] | TypeRef [@ocaml.doc "A reference to a type declaration."] | CXXBaseSpecifier [@ocaml.doc "A reference to a type declaration."] | TemplateRef [@ocaml.doc "A reference to a class template, function template, template template parameter, or class template partial specialization."] | NamespaceRef [@ocaml.doc "A reference to a namespace or namespace alias."] | MemberRef [@ocaml.doc "A reference to a member of a struct, union, or class that occurs in some non-expression context, e.g., a designated initializer."] | LabelRef [@ocaml.doc "A reference to a labeled statement."] | OverloadedDeclRef [@ocaml.doc "A reference to a set of overloaded functions or function templates that has not yet been resolved to a specific function or function template."] | VariableRef [@ocaml.doc "A reference to a variable that occurs in some non-expression context, e.g., a C++ lambda capture list."] | InvalidFile [@ocaml.doc "A reference to a variable that occurs in some non-expression context, e.g., a C++ lambda capture list."] | NoDeclFound [@ocaml.doc "A reference to a variable that occurs in some non-expression context, e.g., a C++ lambda capture list."] | NotImplemented [@ocaml.doc "A reference to a variable that occurs in some non-expression context, e.g., a C++ lambda capture list."] | InvalidCode [@ocaml.doc "A reference to a variable that occurs in some non-expression context, e.g., a C++ lambda capture list."] | UnexposedExpr [@ocaml.doc "An expression whose specific kind is not exposed via this interface."] | DeclRefExpr [@ocaml.doc "An expression that refers to some value declaration, such as a function, variable, or enumerator."] | MemberRefExpr [@ocaml.doc "An expression that refers to a member of a struct, union, class, Objective-C class, etc."] | CallExpr [@ocaml.doc "An expression that calls a function."] | ObjCMessageExpr [@ocaml.doc "An expression that sends a message to an Objective-C object or class."] | BlockExpr [@ocaml.doc "An expression that represents a block literal."] | IntegerLiteral [@ocaml.doc "An integer literal."] | FloatingLiteral [@ocaml.doc "A floating point number literal."] | ImaginaryLiteral [@ocaml.doc "An imaginary number literal."] | StringLiteral [@ocaml.doc "A string literal."] | CharacterLiteral [@ocaml.doc "A character literal."] | ParenExpr [@ocaml.doc "A parenthesized expression, e.g. \"(1)\"."] | UnaryOperator [@ocaml.doc "This represents the unary-expression's (except sizeof and alignof)."] | ArraySubscriptExpr [@ocaml.doc "\\[C99 6.5.2.1\\] Array Subscripting."] | BinaryOperator [@ocaml.doc "A builtin binary operation expression such as \"x + y\" or \"x <= y\"."] | CompoundAssignOperator [@ocaml.doc "Compound assignment such as \"+=\"."] | ConditionalOperator [@ocaml.doc "The ?: ternary operator."] | CStyleCastExpr [@ocaml.doc "An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ \\[expr.cast\\]), which uses the syntax (Type)expr."] | CompoundLiteralExpr [@ocaml.doc "\\[C99 6.5.2.5\\]"] | InitListExpr [@ocaml.doc "Describes an C or C++ initializer list."] | AddrLabelExpr [@ocaml.doc "The GNU address of label extension, representing &&label."] | StmtExpr [@ocaml.doc "This is the GNU Statement Expression extension: (\\{int X=4; X;\\})"] | GenericSelectionExpr [@ocaml.doc "Represents a C11 generic selection."] | GNUNullExpr [@ocaml.doc "Implements the GNU __null extension, which is a name for a null pointer constant that has integral type (e.g., int or long) and is the same size and alignment as a pointer."] | CXXStaticCastExpr [@ocaml.doc "C++'s static_cast<> expression."] | CXXDynamicCastExpr [@ocaml.doc "C++'s dynamic_cast<> expression."] | CXXReinterpretCastExpr [@ocaml.doc "C++'s reinterpret_cast<> expression."] | CXXConstCastExpr [@ocaml.doc "C++'s const_cast<> expression."] | CXXFunctionalCastExpr [@ocaml.doc "Represents an explicit C++ type conversion that uses \"functional\" notion (C++ \\[expr.type.conv\\])."] | CXXTypeidExpr [@ocaml.doc "A C++ typeid expression (C++ \\[expr.typeid\\])."] | CXXBoolLiteralExpr [@ocaml.doc "\\[C++ 2.13.5\\] C++ Boolean Literal."] | CXXNullPtrLiteralExpr [@ocaml.doc "\\[C++0x 2.14.7\\] C++ Pointer Literal."] | CXXThisExpr [@ocaml.doc "Represents the \"this\" expression in C++"] | CXXThrowExpr [@ocaml.doc "\\[C++ 15\\] C++ Throw Expression."] | CXXNewExpr [@ocaml.doc "A new expression for memory allocation and constructor calls, e.g: \"new CXXNewExpr(foo)\"."] | CXXDeleteExpr [@ocaml.doc "A delete expression for memory deallocation and destructor calls, e.g. \"delete\\[\\] pArray\"."] | UnaryExpr [@ocaml.doc "A unary expression. (noexcept, sizeof, or other traits)"] | ObjCStringLiteral [@ocaml.doc "An Objective-C string literal i.e. \"foo\"."] | ObjCEncodeExpr [@ocaml.doc "An Objective-C \\@encode expression."] | ObjCSelectorExpr [@ocaml.doc "An Objective-C \\@selector expression."] | ObjCProtocolExpr [@ocaml.doc "An Objective-C \\@protocol expression."] | ObjCBridgedCastExpr [@ocaml.doc "An Objective-C \"bridged\" cast expression, which casts between Objective-C pointers and C pointers, transferring ownership in the process."] | PackExpansionExpr [@ocaml.doc "Represents a C++0x pack expansion that produces a sequence of expressions."] | SizeOfPackExpr [@ocaml.doc "Represents an expression that computes the length of a parameter pack."] | LambdaExpr | ObjCBoolLiteralExpr [@ocaml.doc "Objective-c Boolean Literal."] | ObjCSelfExpr [@ocaml.doc "Represents the \"self\" expression in an Objective-C method."] | OMPArraySectionExpr [@ocaml.doc "OpenMP 4.0 \\[2.4, Array Section\\]."] | ObjCAvailabilityCheckExpr [@ocaml.doc "Represents an (...) check."] | FixedPointLiteral [@ocaml.doc "Fixed point literal"] | UnexposedStmt [@ocaml.doc "A statement whose specific kind is not exposed via this interface."] | LabelStmt [@ocaml.doc "A labelled statement in a function."] | CompoundStmt [@ocaml.doc "A group of statements like \\{ stmt stmt \\}."] | CaseStmt [@ocaml.doc "A case statement."] | DefaultStmt [@ocaml.doc "A default statement."] | IfStmt [@ocaml.doc "An if statement"] | SwitchStmt [@ocaml.doc "A switch statement."] | WhileStmt [@ocaml.doc "A while statement."] | DoStmt [@ocaml.doc "A do statement."] | ForStmt [@ocaml.doc "A for statement."] | GotoStmt [@ocaml.doc "A goto statement."] | IndirectGotoStmt [@ocaml.doc "An indirect goto statement."] | ContinueStmt [@ocaml.doc "A continue statement."] | BreakStmt [@ocaml.doc "A break statement."] | ReturnStmt [@ocaml.doc "A return statement."] | GCCAsmStmt [@ocaml.doc "A GCC inline assembly statement extension."] | ObjCAtTryStmt [@ocaml.doc "Objective-C's overall \\@try-\\@catch-\\@finally statement."] | ObjCAtCatchStmt [@ocaml.doc "Objective-C's \\@catch statement."] | ObjCAtFinallyStmt [@ocaml.doc "Objective-C's \\@finally statement."] | ObjCAtThrowStmt [@ocaml.doc "Objective-C's \\@throw statement."] | ObjCAtSynchronizedStmt [@ocaml.doc "Objective-C's \\@synchronized statement."] | ObjCAutoreleasePoolStmt [@ocaml.doc "Objective-C's autorelease pool statement."] | ObjCForCollectionStmt [@ocaml.doc "Objective-C's collection statement."] | CXXCatchStmt [@ocaml.doc "C++'s catch statement."] | CXXTryStmt [@ocaml.doc "C++'s try statement."] | CXXForRangeStmt [@ocaml.doc "C++'s for (* : *) statement."] | SEHTryStmt [@ocaml.doc "Windows Structured Exception Handling's try statement."] | SEHExceptStmt [@ocaml.doc "Windows Structured Exception Handling's except statement."] | SEHFinallyStmt [@ocaml.doc "Windows Structured Exception Handling's finally statement."] | MSAsmStmt [@ocaml.doc "A MS inline assembly statement extension."] | NullStmt [@ocaml.doc "The null statement \";\": C99 6.8.3p3."] | DeclStmt [@ocaml.doc "Adaptor class for mixing declarations with statements and expressions."] | OMPParallelDirective [@ocaml.doc "OpenMP parallel directive."] | OMPSimdDirective [@ocaml.doc "OpenMP SIMD directive."] | OMPForDirective [@ocaml.doc "OpenMP for directive."] | OMPSectionsDirective [@ocaml.doc "OpenMP sections directive."] | OMPSectionDirective [@ocaml.doc "OpenMP section directive."] | OMPSingleDirective [@ocaml.doc "OpenMP single directive."] | OMPParallelForDirective [@ocaml.doc "OpenMP parallel for directive."] | OMPParallelSectionsDirective [@ocaml.doc "OpenMP parallel sections directive."] | OMPTaskDirective [@ocaml.doc "OpenMP task directive."] | OMPMasterDirective [@ocaml.doc "OpenMP master directive."] | OMPCriticalDirective [@ocaml.doc "OpenMP critical directive."] | OMPTaskyieldDirective [@ocaml.doc "OpenMP taskyield directive."] | OMPBarrierDirective [@ocaml.doc "OpenMP barrier directive."] | OMPTaskwaitDirective [@ocaml.doc "OpenMP taskwait directive."] | OMPFlushDirective [@ocaml.doc "OpenMP flush directive."] | SEHLeaveStmt [@ocaml.doc "Windows Structured Exception Handling's leave statement."] | OMPOrderedDirective [@ocaml.doc "OpenMP ordered directive."] | OMPAtomicDirective [@ocaml.doc "OpenMP atomic directive."] | OMPForSimdDirective [@ocaml.doc "OpenMP for SIMD directive."] | OMPParallelForSimdDirective [@ocaml.doc "OpenMP parallel for SIMD directive."] | OMPTargetDirective [@ocaml.doc "OpenMP target directive."] | OMPTeamsDirective [@ocaml.doc "OpenMP teams directive."] | OMPTaskgroupDirective [@ocaml.doc "OpenMP taskgroup directive."] | OMPCancellationPointDirective [@ocaml.doc "OpenMP cancellation point directive."] | OMPCancelDirective [@ocaml.doc "OpenMP cancel directive."] | OMPTargetDataDirective [@ocaml.doc "OpenMP target data directive."] | OMPTaskLoopDirective [@ocaml.doc "OpenMP taskloop directive."] | OMPTaskLoopSimdDirective [@ocaml.doc "OpenMP taskloop simd directive."] | OMPDistributeDirective [@ocaml.doc "OpenMP distribute directive."] | OMPTargetEnterDataDirective [@ocaml.doc "OpenMP target enter data directive."] | OMPTargetExitDataDirective [@ocaml.doc "OpenMP target exit data directive."] | OMPTargetParallelDirective [@ocaml.doc "OpenMP target parallel directive."] | OMPTargetParallelForDirective [@ocaml.doc "OpenMP target parallel for directive."] | OMPTargetUpdateDirective [@ocaml.doc "OpenMP target update directive."] | OMPDistributeParallelForDirective [@ocaml.doc "OpenMP distribute parallel for directive."] | OMPDistributeParallelForSimdDirective [@ocaml.doc "OpenMP distribute parallel for simd directive."] | OMPDistributeSimdDirective [@ocaml.doc "OpenMP distribute simd directive."] | OMPTargetParallelForSimdDirective [@ocaml.doc "OpenMP target parallel for simd directive."] | OMPTargetSimdDirective [@ocaml.doc "OpenMP target simd directive."] | OMPTeamsDistributeDirective [@ocaml.doc "OpenMP teams distribute directive."] | OMPTeamsDistributeSimdDirective [@ocaml.doc "OpenMP teams distribute simd directive."] | OMPTeamsDistributeParallelForSimdDirective [@ocaml.doc "OpenMP teams distribute parallel for simd directive."] | OMPTeamsDistributeParallelForDirective [@ocaml.doc "OpenMP teams distribute parallel for directive."] | OMPTargetTeamsDirective [@ocaml.doc "OpenMP target teams directive."] | OMPTargetTeamsDistributeDirective [@ocaml.doc "OpenMP target teams distribute directive."] | OMPTargetTeamsDistributeParallelForDirective [@ocaml.doc "OpenMP target teams distribute parallel for directive."] | OMPTargetTeamsDistributeParallelForSimdDirective [@ocaml.doc "OpenMP target teams distribute parallel for simd directive."] | OMPTargetTeamsDistributeSimdDirective [@ocaml.doc "OpenMP target teams distribute simd directive."] | TranslationUnit [@ocaml.doc "Cursor that represents the translation unit itself."] | UnexposedAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | IBActionAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | IBOutletAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | IBOutletCollectionAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | CXXFinalAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | CXXOverrideAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | AnnotateAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | AsmLabelAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | PackedAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | PureAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | ConstAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | NoDuplicateAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | CUDAConstantAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | CUDADeviceAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | CUDAGlobalAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | CUDAHostAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | CUDASharedAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | VisibilityAttr [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | DLLExport [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | DLLImport [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | PreprocessingDirective [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | MacroDefinition [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | MacroExpansion [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | InclusionDirective [@ocaml.doc "An attribute whose specific kind is not exposed via this interface."] | ModuleImportDecl [@ocaml.doc "A module import declaration."] | TypeAliasTemplateDecl [@ocaml.doc "A module import declaration."] | StaticAssert [@ocaml.doc "A static_assert or _Static_assert node"] | FriendDecl [@ocaml.doc "a friend declaration."] | OverloadCandidate [@ocaml.doc "A code completion overload candidate."] [@@deriving refl][@@ocaml.doc "Describes the kind of entity that a cursor refers to."] type cxcursor[@@ocaml.doc "A cursor representing some element in the abstract syntax tree for a translation unit."] external get_null_cursor : unit -> cxcursor = "clang_getNullCursor_wrapper" [@@ocaml.doc "Retrieve the NULL cursor, which represents no entity."] external get_translation_unit_cursor : cxtranslationunit -> cxcursor = "clang_getTranslationUnitCursor_wrapper" [@@ocaml.doc "Retrieve the cursor that represents the given translation unit."] external equal_cursors : cxcursor -> cxcursor -> bool = "clang_equalCursors_wrapper"[@@ocaml.doc "Determine whether two cursors are equivalent."] external cursor_is_null : cxcursor -> bool = "clang_Cursor_isNull_wrapper" [@@ocaml.doc "Returns non-zero if cursor is null."] external hash_cursor : cxcursor -> int = "clang_hashCursor_wrapper"[@@ocaml.doc "Compute a hash value for the given cursor."] external get_cursor_kind : cxcursor -> cxcursorkind = "clang_getCursorKind_wrapper"[@@ocaml.doc "Retrieve the kind of the given cursor."] external is_declaration : cxcursorkind -> bool = "clang_isDeclaration_wrapper"[@@ocaml.doc "Determine whether the given cursor kind represents a declaration."] external is_invalid_declaration : cxcursor -> bool = "clang_isInvalidDeclaration_wrapper"[@@ocaml.doc "Determine whether the given declaration is invalid."] external is_reference : cxcursorkind -> bool = "clang_isReference_wrapper" [@@ocaml.doc "Determine whether the given cursor kind represents a simple reference."] external is_expression : cxcursorkind -> bool = "clang_isExpression_wrapper" [@@ocaml.doc "Determine whether the given cursor kind represents an expression."] external is_statement : cxcursorkind -> bool = "clang_isStatement_wrapper" [@@ocaml.doc "Determine whether the given cursor kind represents a statement."] external is_attribute : cxcursorkind -> bool = "clang_isAttribute_wrapper" [@@ocaml.doc "Determine whether the given cursor kind represents an attribute."] external cursor_has_attrs : cxcursor -> int = "clang_Cursor_hasAttrs_wrapper" [@@ocaml.doc "Determine whether the given cursor has any attributes."] external is_invalid : cxcursorkind -> bool = "clang_isInvalid_wrapper" [@@ocaml.doc "Determine whether the given cursor kind represents an invalid cursor."] external is_translation_unit : cxcursorkind -> bool = "clang_isTranslationUnit_wrapper"[@@ocaml.doc "Determine whether the given cursor kind represents a translation unit."] external is_preprocessing : cxcursorkind -> bool = "clang_isPreprocessing_wrapper"[@@ocaml.doc "* Determine whether the given cursor represents a preprocessing element, such as a preprocessor directive or macro instantiation."] external is_unexposed : cxcursorkind -> bool = "clang_isUnexposed_wrapper" [@@ocaml.doc "* Determine whether the given cursor represents a currently unexposed piece of the AST (e.g., CXCursor_UnexposedStmt)."] type cxlinkagekind = | Invalid [@ocaml.doc "This value indicates that no linkage information is available for a provided CXCursor."] | NoLinkage [@ocaml.doc "This is the linkage for variables, parameters, and so on that have automatic storage. This covers normal (non-extern) local variables."] | Internal [@ocaml.doc "This is the linkage for static variables and static functions."] | UniqueExternal [@ocaml.doc "This is the linkage for entities with external linkage that live in C++ anonymous namespaces."] | External [@ocaml.doc "This is the linkage for entities with true, external linkage."][@@deriving refl] [@@ocaml.doc "Describe the linkage of the entity referred to by a cursor."] external get_cursor_linkage : cxcursor -> cxlinkagekind = "clang_getCursorLinkage_wrapper"[@@ocaml.doc "Determine the linkage of the entity referred to by a given cursor."] type cxvisibilitykind = | Invalid [@ocaml.doc "This value indicates that no visibility information is available for a provided CXCursor."] | Hidden [@ocaml.doc "Symbol not seen by the linker."] | Protected [@ocaml.doc "Symbol seen by the linker but resolves to a symbol inside this object."] | Default [@ocaml.doc "Symbol seen by the linker and acts like a normal symbol."] [@@deriving refl] external get_cursor_visibility : cxcursor -> cxvisibilitykind = "clang_getCursorVisibility_wrapper"[@@ocaml.doc "Describe the visibility of the entity referred to by a cursor."] type cxavailabilitykind = | Available [@ocaml.doc "The entity is available."] | Deprecated [@ocaml.doc "The entity is available, but has been deprecated (and its use is not recommended)."] | NotAvailable [@ocaml.doc "The entity is not available; any use of it will be an error."] | NotAccessible [@ocaml.doc "The entity is available, but not accessible; any use of it will be an error."] [@@deriving refl][@@ocaml.doc "Describes the availability of a particular entity, which indicates whether the use of this entity will result in a warning or error due to it being deprecated or unavailable."] external get_cursor_availability : cxcursor -> cxavailabilitykind = "clang_getCursorAvailability_wrapper" [@@ocaml.doc "Determine the availability of the entity that this cursor refers to, taking the current target platform into account."] type cxlanguagekind = | Invalid | C | ObjC | CPlusPlus [@@deriving refl][@@ocaml.doc "Describe the \"language\" of the entity referred to by a cursor."] external get_cursor_language : cxcursor -> cxlanguagekind = "clang_getCursorLanguage_wrapper"[@@ocaml.doc "Determine the \"language\" of the entity referred to by a given cursor."] type cxtlskind = | None | Dynamic | Static [@@deriving refl][@@ocaml.doc "Describe the \"thread-local storage (TLS) kind\" of the declaration referred to by a cursor."] external get_cursor_tlskind : cxcursor -> cxtlskind = "clang_getCursorTLSKind_wrapper"[@@ocaml.doc "Determine the \"thread-local storage (TLS) kind\" of the declaration referred to by a cursor."] type cxcursorset external create_cxcursor_set : unit -> cxcursorset = "clang_createCXCursorSet_wrapper"[@@ocaml.doc "Creates an empty CXCursorSet."] external cxcursor_set_contains : cxcursorset -> cxcursor -> int = "clang_CXCursorSet_contains_wrapper" [@@ocaml.doc "Queries a CXCursorSet to see if it contains a specific CXCursor."] external cxcursor_set_insert : cxcursorset -> cxcursor -> int = "clang_CXCursorSet_insert_wrapper" [@@ocaml.doc "Inserts a CXCursor into a CXCursorSet."] external get_cursor_semantic_parent : cxcursor -> cxcursor = "clang_getCursorSemanticParent_wrapper"[@@ocaml.doc "Determine the semantic parent of the given cursor."] external get_cursor_lexical_parent : cxcursor -> cxcursor = "clang_getCursorLexicalParent_wrapper"[@@ocaml.doc "Determine the lexical parent of the given cursor."] external get_overridden_cursors : cxcursor -> cxcursor array = "clang_getOverriddenCursors_wrapper"[@@ocaml.doc "Determine the set of methods that are overridden by the given method."] external get_included_file : cxcursor -> cxfile = "clang_getIncludedFile_wrapper"[@@ocaml.doc "Retrieve the file that is included by the given inclusion directive cursor."] external get_cursor : cxtranslationunit -> cxsourcelocation -> cxcursor = "clang_getCursor_wrapper"[@@ocaml.doc "Map a source location to the cursor that describes the entity at that location in the source code."] external get_cursor_location : cxcursor -> cxsourcelocation = "clang_getCursorLocation_wrapper"[@@ocaml.doc "Retrieve the physical location of the source constructor referenced by the given cursor."] external get_cursor_extent : cxcursor -> cxsourcerange = "clang_getCursorExtent_wrapper"[@@ocaml.doc "Retrieve the physical extent of the source construct referenced by the given cursor."] type cxtypekind = | Invalid [@ocaml.doc "Represents an invalid type (e.g., where no type is available)."] | Unexposed [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Void [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Bool [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Char_U [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | UChar [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Char16 [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Char32 [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | UShort [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | UInt [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ULong [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ULongLong [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | UInt128 [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Char_S [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | SChar [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | WChar [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Short [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Int [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Long [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | LongLong [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Int128 [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Float [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Double [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | LongDouble [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | NullPtr [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Overload [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Dependent [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ObjCId [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ObjCClass [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ObjCSel [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Float128 [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Half [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Float16 [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ShortAccum [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Accum [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | LongAccum [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | UShortAccum [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | UAccum [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ULongAccum [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Complex [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Pointer [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | BlockPointer [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | LValueReference [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | RValueReference [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Record [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Enum [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Typedef [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ObjCInterface [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ObjCObjectPointer [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | FunctionNoProto [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | FunctionProto [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | ConstantArray [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Vector [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | IncompleteArray [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | VariableArray [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | DependentSizedArray [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | MemberPointer [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Auto [@ocaml.doc "A type whose specific kind is not exposed via this interface."] | Elaborated [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | Pipe [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dArrayRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dBufferRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dDepthRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayDepthRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dMSAARO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayMSAARO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dMSAADepthRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayMSAADepthRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage3dRO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dArrayWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dBufferWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dDepthWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayDepthWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dMSAAWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayMSAAWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dMSAADepthWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayMSAADepthWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage3dWO [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dArrayRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage1dBufferRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dDepthRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayDepthRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dMSAARW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayMSAARW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dMSAADepthRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage2dArrayMSAADepthRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLImage3dRW [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLSampler [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLEvent [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLQueue [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] | OCLReserveID [@ocaml.doc "Represents a type that was referred to using an elaborated type keyword."] [@@deriving refl][@@ocaml.doc "Describes the kind of type"] type cxtype[@@ocaml.doc "The type of an element in the abstract syntax tree."] external get_type_kind : cxtype -> cxtypekind = "clang_getTypeKind_wrapper" external get_cursor_type : cxcursor -> cxtype = "clang_getCursorType_wrapper" [@@ocaml.doc "Retrieve the type of a CXCursor (if any)."] external get_type_spelling : cxtype -> string = "clang_getTypeSpelling_wrapper"[@@ocaml.doc "Pretty-print the underlying type using the rules of the language of the translation unit from which it came."] external get_typedef_decl_underlying_type : cxcursor -> cxtype = "clang_getTypedefDeclUnderlyingType_wrapper"[@@ocaml.doc "Retrieve the underlying type of a typedef declaration."] external get_enum_decl_integer_type : cxcursor -> cxtype = "clang_getEnumDeclIntegerType_wrapper"[@@ocaml.doc "Retrieve the integer type of an enum declaration."] external get_enum_constant_decl_value : cxcursor -> int = "clang_getEnumConstantDeclValue_wrapper"[@@ocaml.doc "Retrieve the integer value of an enum constant declaration as a signed long long."] external get_enum_constant_decl_unsigned_value : cxcursor -> int = "clang_getEnumConstantDeclUnsignedValue_wrapper"[@@ocaml.doc "Retrieve the integer value of an enum constant declaration as an unsigned long long."] external get_field_decl_bit_width : cxcursor -> int = "clang_getFieldDeclBitWidth_wrapper"[@@ocaml.doc "Retrieve the bit width of a bit field declaration as an integer."] external cursor_get_num_arguments : cxcursor -> int = "clang_Cursor_getNumArguments_wrapper"[@@ocaml.doc "Retrieve the number of non-variadic arguments associated with a given cursor."] external cursor_get_argument : cxcursor -> int -> cxcursor = "clang_Cursor_getArgument_wrapper"[@@ocaml.doc "Retrieve the argument cursor of a function or method."] external cursor_get_num_template_arguments : cxcursor -> int = "clang_Cursor_getNumTemplateArguments_wrapper"[@@ocaml.doc "Returns the number of template args of a function decl representing a template specialization."] type cxtemplateargumentkind = | Null | Type | Declaration | NullPtr | Integral | Template | TemplateExpansion | Expression | Pack | Invalid [@@deriving refl][@@ocaml.doc "Describes the kind of a template argument."] external cursor_get_template_argument_kind : cxcursor -> int -> cxtemplateargumentkind = "clang_Cursor_getTemplateArgumentKind_wrapper"[@@ocaml.doc "Retrieve the kind of the I'th template argument of the CXCursor C."] external cursor_get_template_argument_type : cxcursor -> int -> cxtype = "clang_Cursor_getTemplateArgumentType_wrapper" [@@ocaml.doc "Retrieve a CXType representing the type of a TemplateArgument of a function decl representing a template specialization."] external cursor_get_template_argument_value : cxcursor -> int -> int = "clang_Cursor_getTemplateArgumentValue_wrapper" [@@ocaml.doc "Retrieve the value of an Integral TemplateArgument (of a function decl representing a template specialization) as a signed long long."] external cursor_get_template_argument_unsigned_value : cxcursor -> int -> int = "clang_Cursor_getTemplateArgumentUnsignedValue_wrapper"[@@ocaml.doc "Retrieve the value of an Integral TemplateArgument (of a function decl representing a template specialization) as an unsigned long long."] external equal_types : cxtype -> cxtype -> bool = "clang_equalTypes_wrapper" [@@ocaml.doc "Determine whether two CXTypes represent the same type."] external get_canonical_type : cxtype -> cxtype = "clang_getCanonicalType_wrapper"[@@ocaml.doc "Return the canonical type for a CXType."] external is_const_qualified_type : cxtype -> bool = "clang_isConstQualifiedType_wrapper"[@@ocaml.doc "Determine whether a CXType has the \"const\" qualifier set, without looking through typedefs that may have added \"const\" at a different level."] external cursor_is_macro_function_like : cxcursor -> bool = "clang_Cursor_isMacroFunctionLike_wrapper"[@@ocaml.doc "Determine whether a CXCursor that is a macro, is function like."] external cursor_is_macro_builtin : cxcursor -> bool = "clang_Cursor_isMacroBuiltin_wrapper"[@@ocaml.doc "Determine whether a CXCursor that is a macro, is a builtin one."] external cursor_is_function_inlined : cxcursor -> bool = "clang_Cursor_isFunctionInlined_wrapper"[@@ocaml.doc "Determine whether a CXCursor that is a function declaration, is an inline declaration."] external is_volatile_qualified_type : cxtype -> bool = "clang_isVolatileQualifiedType_wrapper"[@@ocaml.doc "Determine whether a CXType has the \"volatile\" qualifier set, without looking through typedefs that may have added \"volatile\" at a different level."] external is_restrict_qualified_type : cxtype -> bool = "clang_isRestrictQualifiedType_wrapper"[@@ocaml.doc "Determine whether a CXType has the \"restrict\" qualifier set, without looking through typedefs that may have added \"restrict\" at a different level."] external get_address_space : cxtype -> int = "clang_getAddressSpace_wrapper" [@@ocaml.doc "Returns the address space of the given type."] external get_typedef_name : cxtype -> string = "clang_getTypedefName_wrapper" [@@ocaml.doc "Returns the typedef name of the given type."] external get_pointee_type : cxtype -> cxtype = "clang_getPointeeType_wrapper" [@@ocaml.doc "For pointer types, returns the type of the pointee."] external get_type_declaration : cxtype -> cxcursor = "clang_getTypeDeclaration_wrapper"[@@ocaml.doc "Return the cursor for the declaration of the given type."] external get_decl_obj_ctype_encoding : cxcursor -> string = "clang_getDeclObjCTypeEncoding_wrapper"[@@ocaml.doc "Returns the Objective-C type encoding for the specified declaration."] external type_get_obj_cencoding : cxtype -> string = "clang_Type_getObjCEncoding_wrapper"[@@ocaml.doc "Returns the Objective-C type encoding for the specified CXType."] external get_type_kind_spelling : cxtypekind -> string = "clang_getTypeKindSpelling_wrapper"[@@ocaml.doc "Retrieve the spelling of a given CXTypeKind."] type cxcallingconv = | Default | C | X86StdCall | X86FastCall | X86ThisCall | X86Pascal | AAPCS | AAPCS_VFP | X86RegCall | IntelOclBicc | Win64 | X86_64SysV | X86VectorCall | Swift | PreserveMost | PreserveAll | Invalid | Unexposed [@@deriving refl][@@ocaml.doc "Describes the calling convention of a function type"] external get_function_type_calling_conv : cxtype -> cxcallingconv = "clang_getFunctionTypeCallingConv_wrapper" [@@ocaml.doc "Retrieve the calling convention associated with a function type."] external get_result_type : cxtype -> cxtype = "clang_getResultType_wrapper" [@@ocaml.doc "Retrieve the return type associated with a function type."] external get_exception_specification_type : cxtype -> int = "clang_getExceptionSpecificationType_wrapper"[@@ocaml.doc "Retrieve the exception specification type associated with a function type. This is a value of type CXCursor_ExceptionSpecificationKind."] external get_num_arg_types : cxtype -> int = "clang_getNumArgTypes_wrapper" [@@ocaml.doc "Retrieve the number of non-variadic parameters associated with a function type."] external get_arg_type : cxtype -> int -> cxtype = "clang_getArgType_wrapper" [@@ocaml.doc "Retrieve the type of a parameter of a function type."] external is_function_type_variadic : cxtype -> bool = "clang_isFunctionTypeVariadic_wrapper"[@@ocaml.doc "Return 1 if the CXType is a variadic function type, and 0 otherwise."] external get_cursor_result_type : cxcursor -> cxtype = "clang_getCursorResultType_wrapper"[@@ocaml.doc "Retrieve the return type associated with a given cursor."] external get_cursor_exception_specification_type : cxcursor -> int = "clang_getCursorExceptionSpecificationType_wrapper" [@@ocaml.doc "Retrieve the exception specification type associated with a given cursor. This is a value of type CXCursor_ExceptionSpecificationKind."] external is_podtype : cxtype -> bool = "clang_isPODType_wrapper"[@@ocaml.doc "Return 1 if the CXType is a POD (plain old data) type, and 0 otherwise."] external get_element_type : cxtype -> cxtype = "clang_getElementType_wrapper" [@@ocaml.doc "Return the element type of an array, complex, or vector type."] external get_num_elements : cxtype -> int = "clang_getNumElements_wrapper" [@@ocaml.doc "Return the number of elements of an array or vector type."] external get_array_element_type : cxtype -> cxtype = "clang_getArrayElementType_wrapper"[@@ocaml.doc "Return the element type of an array type."] external get_array_size : cxtype -> int = "clang_getArraySize_wrapper" [@@ocaml.doc "Return the array size of a constant array."] external type_get_named_type : cxtype -> cxtype = "clang_Type_getNamedType_wrapper"[@@ocaml.doc "Retrieve the type named by the qualified-id."] external type_is_transparent_tag_typedef : cxtype -> bool = "clang_Type_isTransparentTagTypedef_wrapper"[@@ocaml.doc "Determine if a typedef is 'transparent' tag."] external type_get_align_of : cxtype -> int = "clang_Type_getAlignOf_wrapper" [@@ocaml.doc "Return the alignment of a type in bytes as per C++\\[expr.alignof\\] standard."] external type_get_class_type : cxtype -> cxtype = "clang_Type_getClassType_wrapper"[@@ocaml.doc "Return the class type of an member pointer type."] external type_get_size_of : cxtype -> int = "clang_Type_getSizeOf_wrapper" [@@ocaml.doc "Return the size of a type in bytes as per C++\\[expr.sizeof\\] standard."] external type_get_offset_of : cxtype -> string -> int = "clang_Type_getOffsetOf_wrapper"[@@ocaml.doc "Return the offset of a field named S in a record of type T in bits as it would be returned by __offsetof__ as per C++11\\[18.2p4\\]"] external cursor_get_offset_of_field : cxcursor -> int = "clang_Cursor_getOffsetOfField_wrapper"[@@ocaml.doc "Return the offset of the field represented by the Cursor."] external cursor_is_anonymous : cxcursor -> bool = "clang_Cursor_isAnonymous_wrapper"[@@ocaml.doc "Determine whether the given cursor represents an anonymous record declaration."] external type_get_num_template_arguments : cxtype -> int = "clang_Type_getNumTemplateArguments_wrapper"[@@ocaml.doc "Returns the number of template arguments for given template specialization, or -1 if type T is not a template specialization."] external type_get_template_argument_as_type : cxtype -> int -> cxtype = "clang_Type_getTemplateArgumentAsType_wrapper" [@@ocaml.doc "Returns the type template argument of a template class specialization at given index."] type cxrefqualifierkind = | None [@ocaml.doc "No ref-qualifier was provided."] | LValue [@ocaml.doc "An lvalue ref-qualifier was provided ( &)."] | RValue [@ocaml.doc "An rvalue ref-qualifier was provided ( &&)."] [@@deriving refl] external type_get_cxxref_qualifier : cxtype -> cxrefqualifierkind = "clang_Type_getCXXRefQualifier_wrapper" [@@ocaml.doc "Retrieve the ref-qualifier kind of a function or method."] external cursor_is_bit_field : cxcursor -> bool = "clang_Cursor_isBitField_wrapper"[@@ocaml.doc "Returns non-zero if the cursor specifies a Record member that is a bitfield."] external is_virtual_base : cxcursor -> bool = "clang_isVirtualBase_wrapper" [@@ocaml.doc "Returns 1 if the base class specified by the cursor with kind CX_CXXBaseSpecifier is virtual."] type cx_cxxaccessspecifier = | CXXInvalidAccessSpecifier | CXXPublic | CXXProtected | CXXPrivate [@@deriving refl][@@ocaml.doc "Represents the C++ access control level to a base class for a cursor with kind CX_CXXBaseSpecifier."] external get_cxxaccess_specifier : cxcursor -> cx_cxxaccessspecifier = "clang_getCXXAccessSpecifier_wrapper" [@@ocaml.doc "Returns the access control level for the referenced object."] type cx_storageclass = | Invalid | None | Extern | Static | PrivateExtern | OpenCLWorkGroupLocal | Auto | Register [@@deriving refl][@@ocaml.doc "Represents the storage classes as declared in the source. CX_SC_Invalid was added for the case that the passed cursor in not a declaration."] external cursor_get_storage_class : cxcursor -> cx_storageclass = "clang_Cursor_getStorageClass_wrapper" [@@ocaml.doc "Returns the storage class for a function or variable declaration."] external get_num_overloaded_decls : cxcursor -> int = "clang_getNumOverloadedDecls_wrapper"[@@ocaml.doc "Determine the number of overloaded declarations referenced by a CXCursor_OverloadedDeclRef cursor."] external get_overloaded_decl : cxcursor -> int -> cxcursor = "clang_getOverloadedDecl_wrapper"[@@ocaml.doc "Retrieve a cursor for one of the overloaded declarations referenced by a CXCursor_OverloadedDeclRef cursor."] external get_iboutlet_collection_type : cxcursor -> cxtype = "clang_getIBOutletCollectionType_wrapper"[@@ocaml.doc "For cursors representing an iboutletcollection attribute, this function returns the collection element type."] type cxchildvisitresult = | Break [@ocaml.doc "Terminates the cursor traversal."] | Continue [@ocaml.doc "Continues the cursor traversal with the next sibling of the cursor just visited, without visiting its children."] | Recurse [@ocaml.doc "Recursively traverse the children of this cursor, using the same visitor and client data."] [@@deriving refl][@@ocaml.doc "Describes how the traversal of the children of a particular cursor should proceed after visiting a particular child cursor."] external visit_children : cxcursor -> (cxcursor -> cxcursor -> cxchildvisitresult) -> bool = "clang_visitChildren_wrapper"[@@ocaml.doc "Visit the children of a particular cursor."] external get_cursor_usr : cxcursor -> string = "clang_getCursorUSR_wrapper" [@@ocaml.doc "Retrieve a Unified Symbol Resolution (USR) for the entity referenced by the given cursor."] external get_cursor_spelling : cxcursor -> string = "clang_getCursorSpelling_wrapper"[@@ocaml.doc "Retrieve a name for the entity referenced by this cursor."] external cursor_get_spelling_name_range : cxcursor -> piece_index:int -> options:int -> cxsourcerange = "clang_Cursor_getSpellingNameRange_wrapper"[@@ocaml.doc "Retrieve a range for a piece that forms the cursors spelling name. Most of the times there is only one range for the complete spelling but for Objective-C methods and Objective-C message expressions, there are multiple pieces for each selector identifier."] type cxprintingpolicy type cxprintingpolicyproperty = | Indentation | SuppressSpecifiers | SuppressTagKeyword | IncludeTagDefinition | SuppressScope | SuppressUnwrittenScope | SuppressInitializers | ConstantArraySizeAsWritten | AnonymousTagLocations | SuppressStrongLifetime | SuppressLifetimeQualifiers | SuppressTemplateArgsInCXXConstructors | Bool | Restrict | Alignof | UnderscoreAlignof | UseVoidForZeroParams | TerseOutput | PolishForDeclaration | Half | MSWChar | IncludeNewlines | MSVCFormatting | ConstantsAsWritten | SuppressImplicitBase | FullyQualifiedName [@@deriving refl][@@ocaml.doc "Properties for the printing policy."] external printing_policy_get_property : cxprintingpolicy -> cxprintingpolicyproperty -> int = "clang_PrintingPolicy_getProperty_wrapper"[@@ocaml.doc "Get a property value for the given printing policy."] external printing_policy_set_property : cxprintingpolicy -> cxprintingpolicyproperty -> int -> unit = "clang_PrintingPolicy_setProperty_wrapper"[@@ocaml.doc "Set a property value for the given printing policy."] external get_cursor_printing_policy : cxcursor -> cxprintingpolicy = "clang_getCursorPrintingPolicy_wrapper" [@@ocaml.doc "Retrieve the default policy for the cursor."] external get_cursor_pretty_printed : cxcursor -> cxprintingpolicy -> string = "clang_getCursorPrettyPrinted_wrapper"[@@ocaml.doc "Pretty print declarations."] external get_cursor_display_name : cxcursor -> string = "clang_getCursorDisplayName_wrapper"[@@ocaml.doc "Retrieve the display name for the entity referenced by this cursor."] external get_cursor_referenced : cxcursor -> cxcursor = "clang_getCursorReferenced_wrapper"[@@ocaml.doc "For a cursor that is a reference, retrieve a cursor representing the entity that it references."] external get_cursor_definition : cxcursor -> cxcursor = "clang_getCursorDefinition_wrapper"[@@ocaml.doc "For a cursor that is either a reference to or a declaration of some entity, retrieve a cursor that describes the definition of that entity."] external is_cursor_definition : cxcursor -> bool = "clang_isCursorDefinition_wrapper"[@@ocaml.doc "Determine whether the declaration pointed to by this cursor is also a definition of that entity."] external get_canonical_cursor : cxcursor -> cxcursor = "clang_getCanonicalCursor_wrapper"[@@ocaml.doc "Retrieve the canonical cursor corresponding to the given cursor."] external cursor_get_obj_cselector_index : cxcursor -> int = "clang_Cursor_getObjCSelectorIndex_wrapper"[@@ocaml.doc "If the cursor points to a selector identifier in an Objective-C method or message expression, this returns the selector index."] external cursor_is_dynamic_call : cxcursor -> bool = "clang_Cursor_isDynamicCall_wrapper"[@@ocaml.doc "Given a cursor pointing to a C++ method call or an Objective-C message, returns non-zero if the method/message is \"dynamic\", meaning:"] external cursor_get_receiver_type : cxcursor -> cxtype = "clang_Cursor_getReceiverType_wrapper"[@@ocaml.doc "Given a cursor pointing to an Objective-C message or property reference, or C++ method call, returns the CXType of the receiver."] external cursor_get_obj_cproperty_attributes : cxcursor -> int -> int = "clang_Cursor_getObjCPropertyAttributes_wrapper" [@@ocaml.doc "Given a cursor that represents a property declaration, return the associated property attributes. The bits are formed from CXObjCPropertyAttrKind."] external cursor_get_obj_cdecl_qualifiers : cxcursor -> int = "clang_Cursor_getObjCDeclQualifiers_wrapper"[@@ocaml.doc "Given a cursor that represents an Objective-C method or parameter declaration, return the associated Objective-C qualifiers for the return type or the parameter respectively. The bits are formed from CXObjCDeclQualifierKind."] external cursor_is_obj_coptional : cxcursor -> bool = "clang_Cursor_isObjCOptional_wrapper"[@@ocaml.doc "\nGiven a cursor that represents an ObjC method or property declaration,\nreturn non-zero if the declaration was affected by \"\\@optional\".\nReturns zero if the cursor is not such a declaration or it is \"\\@required\". "] external cursor_is_variadic : cxcursor -> bool = "clang_Cursor_isVariadic_wrapper"[@@ocaml.doc "Returns non-zero if the given cursor is a variadic function or method."] external cursor_is_external_symbol : cxcursor -> (string * string * int) option = "clang_Cursor_isExternalSymbol_wrapper"[@@ocaml.doc "Returns non-zero if the given cursor points to a symbol marked with external_source_symbol attribute."] external cursor_get_comment_range : cxcursor -> cxsourcerange = "clang_Cursor_getCommentRange_wrapper"[@@ocaml.doc "Given a cursor that represents a declaration, return the associated comment's source range. The range may include multiple consecutive comments with whitespace in between."] external cursor_get_raw_comment_text : cxcursor -> string = "clang_Cursor_getRawCommentText_wrapper"[@@ocaml.doc "Given a cursor that represents a declaration, return the associated comment text, including comment markers."] external cursor_get_brief_comment_text : cxcursor -> string option = "clang_Cursor_getBriefCommentText_wrapper" [@@ocaml.doc "Given a cursor that represents a documentable entity (e.g., declaration), return the associated first paragraph."] external cursor_get_mangling : cxcursor -> string = "clang_Cursor_getMangling_wrapper"[@@ocaml.doc "Retrieve the CXString representing the mangled name of the cursor."] external cursor_get_cxxmanglings : cxcursor -> string array = "clang_Cursor_getCXXManglings_wrapper"[@@ocaml.doc "Retrieve the CXStrings representing the mangled symbols of the C++ constructor or destructor at the cursor."] external cursor_get_obj_cmanglings : cxcursor -> string array = "clang_Cursor_getObjCManglings_wrapper"[@@ocaml.doc "Retrieve the CXStrings representing the mangled symbols of the ObjC class interface or implementation at the cursor."] type cxmodule external cursor_get_module : cxcursor -> cxmodule = "clang_Cursor_getModule_wrapper"[@@ocaml.doc "Given a CXCursor_ModuleImportDecl cursor, return the associated module."] external get_module_for_file : cxtranslationunit -> cxfile -> cxmodule = "clang_getModuleForFile_wrapper" [@@ocaml.doc "Given a CXFile header file, return the module that contains it, if one exists."] external module_get_astfile : cxmodule -> cxfile = "clang_Module_getASTFile_wrapper"[@@ocaml.doc "Returns the module file where the provided module object came from."] external module_get_parent : cxmodule -> cxmodule = "clang_Module_getParent_wrapper"[@@ocaml.doc "Returns the parent of a sub-module or NULL if the given module is top-level, e.g. for 'std.vector' it will return the 'std' module."] external module_get_name : cxmodule -> string = "clang_Module_getName_wrapper"[@@ocaml.doc "Returns the name of the module, e.g. for the 'std.vector' sub-module it will return \"vector\"."] external module_get_full_name : cxmodule -> string = "clang_Module_getFullName_wrapper"[@@ocaml.doc "Returns the full name of the module, e.g. \"std.vector\"."] external module_is_system : cxmodule -> bool = "clang_Module_isSystem_wrapper"[@@ocaml.doc "Returns non-zero if the module is a system one."] external module_get_num_top_level_headers : cxtranslationunit -> cxmodule -> int = "clang_Module_getNumTopLevelHeaders_wrapper"[@@ocaml.doc "Returns the number of top level headers associated with this module."] external module_get_top_level_header : cxtranslationunit -> cxmodule -> int -> cxfile = "clang_Module_getTopLevelHeader_wrapper"[@@ocaml.doc "Returns the specified top level header associated with the module."] external cxxconstructor_is_converting_constructor : cxcursor -> bool = "clang_CXXConstructor_isConvertingConstructor_wrapper" [@@ocaml.doc "Determine if a C++ constructor is a converting constructor."] external cxxconstructor_is_copy_constructor : cxcursor -> bool = "clang_CXXConstructor_isCopyConstructor_wrapper" [@@ocaml.doc "Determine if a C++ constructor is a copy constructor."] external cxxconstructor_is_default_constructor : cxcursor -> bool = "clang_CXXConstructor_isDefaultConstructor_wrapper" [@@ocaml.doc "Determine if a C++ constructor is the default constructor."] external cxxconstructor_is_move_constructor : cxcursor -> bool = "clang_CXXConstructor_isMoveConstructor_wrapper" [@@ocaml.doc "Determine if a C++ constructor is a move constructor."] external cxxfield_is_mutable : cxcursor -> bool = "clang_CXXField_isMutable_wrapper"[@@ocaml.doc "Determine if a C++ field is declared 'mutable'."] external cxxmethod_is_defaulted : cxcursor -> bool = "clang_CXXMethod_isDefaulted_wrapper"[@@ocaml.doc "Determine if a C++ method is declared '= default'."] external cxxmethod_is_pure_virtual : cxcursor -> bool = "clang_CXXMethod_isPureVirtual_wrapper"[@@ocaml.doc "Determine if a C++ member function or member function template is pure virtual."] external cxxmethod_is_static : cxcursor -> bool = "clang_CXXMethod_isStatic_wrapper"[@@ocaml.doc "Determine if a C++ member function or member function template is declared 'static'."] external cxxmethod_is_virtual : cxcursor -> bool = "clang_CXXMethod_isVirtual_wrapper"[@@ocaml.doc "Determine if a C++ member function or member function template is explicitly declared 'virtual' or if it overrides a virtual method from one of the base classes."] external cxxrecord_is_abstract : cxcursor -> bool = "clang_CXXRecord_isAbstract_wrapper"[@@ocaml.doc "Determine if a C++ record is abstract, i.e. whether a class or struct has a pure virtual member function."] external enum_decl_is_scoped : cxcursor -> bool = "clang_EnumDecl_isScoped_wrapper"[@@ocaml.doc "Determine if an enum declaration refers to a scoped enum."] external cxxmethod_is_const : cxcursor -> bool = "clang_CXXMethod_isConst_wrapper"[@@ocaml.doc "Determine if a C++ member function or member function template is declared 'const'."] external get_template_cursor_kind : cxcursor -> cxcursorkind = "clang_getTemplateCursorKind_wrapper"[@@ocaml.doc "Given a cursor that represents a template, determine the cursor kind of the specializations would be generated by instantiating the template."] external get_specialized_cursor_template : cxcursor -> cxcursor = "clang_getSpecializedCursorTemplate_wrapper" [@@ocaml.doc "Given a cursor that may represent a specialization or instantiation of a template, retrieve the cursor that represents the template that it specializes or from which it was instantiated."] external get_cursor_reference_name_range : cxcursor -> name_flags:int -> piece_index:int -> cxsourcerange = "clang_getCursorReferenceNameRange_wrapper"[@@ocaml.doc "Given a cursor that references something else, return the source range covering that reference."] type cxtokenkind = | Punctuation [@ocaml.doc "A token that contains some kind of punctuation."] | Keyword [@ocaml.doc "A language keyword."] | Identifier [@ocaml.doc "An identifier (that is not a keyword)."] | Literal [@ocaml.doc "A numeric, string, or character literal."] | Comment [@ocaml.doc "A comment."][@@deriving refl][@@ocaml.doc "Describes a kind of token."] type cxtoken[@@ocaml.doc "Describes a single preprocessing token."] external get_token_kind : cxtoken -> cxtokenkind = "clang_getTokenKind_wrapper"[@@ocaml.doc "Determine the kind of the given token."] external get_token_spelling : cxtranslationunit -> cxtoken -> string = "clang_getTokenSpelling_wrapper" [@@ocaml.doc "Determine the spelling of the given token."] external get_token_location : cxtranslationunit -> cxtoken -> cxsourcelocation = "clang_getTokenLocation_wrapper"[@@ocaml.doc "Retrieve the source location of the given token."] external get_token_extent : cxtranslationunit -> cxtoken -> cxsourcerange = "clang_getTokenExtent_wrapper"[@@ocaml.doc "Retrieve a source range that covers the given token."] external get_cursor_kind_spelling : cxcursorkind -> string = "clang_getCursorKindSpelling_wrapper"[@@ocaml.doc "These routines are used for testing and debugging, only, and should not be relied upon."] external enable_stack_traces : unit -> unit = "clang_enableStackTraces_wrapper" type cxcompletionchunkkind = | Optional [@ocaml.doc "A code-completion string that describes \"optional\" text that could be a part of the template (but is not required)."] | TypedText [@ocaml.doc "Text that a user would be expected to type to get this code-completion result."] | Text [@ocaml.doc "Text that should be inserted as part of a code-completion result."] | Placeholder [@ocaml.doc "Placeholder text that should be replaced by the user."] | Informative [@ocaml.doc "Informative text that should be displayed but never inserted as part of the template."] | CurrentParameter [@ocaml.doc "Text that describes the current parameter when code-completion is referring to function call, message send, or template specialization."] | LeftParen [@ocaml.doc "A left parenthesis ('('), used to initiate a function call or signal the beginning of a function parameter list."] | RightParen [@ocaml.doc "A right parenthesis (')'), used to finish a function call or signal the end of a function parameter list."] | LeftBracket [@ocaml.doc "A left bracket ('\\[')."] | RightBracket [@ocaml.doc "A right bracket ('\\]')."] | LeftBrace [@ocaml.doc "A left brace ('\\{')."] | RightBrace [@ocaml.doc "A right brace ('\\}')."] | LeftAngle [@ocaml.doc "A left angle bracket ('<')."] | RightAngle [@ocaml.doc "A right angle bracket ('>')."] | Comma [@ocaml.doc "A comma separator (',')."] | ResultType [@ocaml.doc "Text that specifies the result type of a given result."] | Colon [@ocaml.doc "A colon (':')."] | SemiColon [@ocaml.doc "A semicolon (';')."] | Equal [@ocaml.doc "An '=' sign."] | HorizontalSpace [@ocaml.doc "Horizontal space (' ')."] | VerticalSpace [@ocaml.doc "Vertical space ('\\n'), after which it is generally a good idea to perform indentation."] [@@deriving refl][@@ocaml.doc "Describes a single piece of text within a code-completion string."] type cxcompletionstring external get_completion_chunk_kind : cxcompletionstring -> int -> cxcompletionchunkkind = "clang_getCompletionChunkKind_wrapper"[@@ocaml.doc "Determine the kind of a particular chunk within a completion string."] external get_completion_chunk_text : cxcompletionstring -> int -> string = "clang_getCompletionChunkText_wrapper"[@@ocaml.doc "Retrieve the text associated with a particular chunk within a completion string."] external get_completion_chunk_completion_string : cxcompletionstring -> int -> cxcompletionstring = "clang_getCompletionChunkCompletionString_wrapper"[@@ocaml.doc "Retrieve the completion string associated with a particular chunk within a completion string."] external get_num_completion_chunks : cxcompletionstring -> int = "clang_getNumCompletionChunks_wrapper"[@@ocaml.doc "Retrieve the number of chunks in the given code-completion string."] external get_completion_priority : cxcompletionstring -> int = "clang_getCompletionPriority_wrapper"[@@ocaml.doc "Determine the priority of this code completion."] external get_completion_availability : cxcompletionstring -> cxavailabilitykind = "clang_getCompletionAvailability_wrapper"[@@ocaml.doc "Determine the availability of the entity that this code-completion string refers to."] external get_completion_num_annotations : cxcompletionstring -> int = "clang_getCompletionNumAnnotations_wrapper" [@@ocaml.doc "Retrieve the number of annotations associated with the given completion string."] external get_completion_annotation : cxcompletionstring -> int -> string = "clang_getCompletionAnnotation_wrapper"[@@ocaml.doc "Retrieve the annotation associated with the given completion string."] external get_completion_parent : cxcompletionstring -> string = "clang_getCompletionParent_wrapper"[@@ocaml.doc "Retrieve the parent context of the given completion string."] external get_completion_brief_comment : cxcompletionstring -> string = "clang_getCompletionBriefComment_wrapper" [@@ocaml.doc "Retrieve the brief documentation comment attached to the declaration that corresponds to the given completion string."] external get_cursor_completion_string : cxcursor -> cxcompletionstring = "clang_getCursorCompletionString_wrapper" [@@ocaml.doc "Retrieve a completion string for an arbitrary declaration or macro definition cursor."] external default_code_complete_options : unit -> int = "clang_defaultCodeCompleteOptions_wrapper"[@@ocaml.doc "Returns a default set of code-completion options that can be passed to clang_codeCompleteAt()."] external get_clang_version : unit -> string = "clang_getClangVersion_wrapper" [@@ocaml.doc "Return a version string, suitable for showing to a user, but not intended to be parsed (the format is not guaranteed to be stable)."] external toggle_crash_recovery : int -> unit = "clang_toggleCrashRecovery_wrapper"[@@ocaml.doc "Enable/disable crash recovery."] type cxevalresult external cursor_evaluate : cxcursor -> cxevalresult = "clang_Cursor_Evaluate_wrapper"[@@ocaml.doc "If cursor is a statement declaration tries to evaluate the statement and if its variable, tries to evaluate its initializer, into its corresponding type."] type cxevalresultkind = | Int | Float | ObjCStrLiteral | StrLiteral | CFStr | Other | UnExposed [@@deriving refl] external eval_result_get_kind : cxevalresult -> cxevalresultkind = "clang_EvalResult_getKind_wrapper" [@@ocaml.doc "Returns the kind of the evaluated result."] external eval_result_get_as_int : cxevalresult -> int = "clang_EvalResult_getAsInt_wrapper"[@@ocaml.doc "Returns the evaluation result as integer if the kind is Int."] external eval_result_get_as_long_long : cxevalresult -> int = "clang_EvalResult_getAsLongLong_wrapper"[@@ocaml.doc "Returns the evaluation result as a long long integer if the kind is Int. This prevents overflows that may happen if the result is returned with clang_EvalResult_getAsInt."] external eval_result_is_unsigned_int : cxevalresult -> bool = "clang_EvalResult_isUnsignedInt_wrapper"[@@ocaml.doc "Returns a non-zero value if the kind is Int and the evaluation result resulted in an unsigned integer."] external eval_result_get_as_unsigned : cxevalresult -> int = "clang_EvalResult_getAsUnsigned_wrapper"[@@ocaml.doc "Returns the evaluation result as an unsigned integer if the kind is Int and clang_EvalResult_isUnsignedInt is non-zero."] external eval_result_get_as_double : cxevalresult -> float = "clang_EvalResult_getAsDouble_wrapper"[@@ocaml.doc "Returns the evaluation result as double if the kind is double."] external eval_result_get_as_str : cxevalresult -> string = "clang_EvalResult_getAsStr_wrapper"[@@ocaml.doc "Returns the evaluation result as a constant string if the kind is other than Int or float. User must not free this pointer, instead call clang_EvalResult_dispose on the CXEvalResult returned by clang_Cursor_Evaluate."] type cxremapping external get_remappings : string -> cxremapping = "clang_getRemappings_wrapper"[@@ocaml.doc "Retrieve a remapping."] external get_remappings_from_file_list : string array -> cxremapping = "clang_getRemappingsFromFileList_wrapper" [@@ocaml.doc "Retrieve a remapping."] external remap_get_num_files : cxremapping -> int = "clang_remap_getNumFiles_wrapper"[@@ocaml.doc "Determine the number of remappings."] type cxindexaction external index_action_create : cxindex -> cxindexaction = "clang_IndexAction_create_wrapper"[@@ocaml.doc "An indexing action/session, to be applied to one or multiple translation units."] type cxvisitorresult = | Break | Continue [@@deriving refl][@@ocaml.doc "\\@\\{"] external type_visit_fields : cxtype -> (cxcursor -> cxvisitorresult) -> bool = "clang_Type_visitFields_wrapper"[@@ocaml.doc "Visit the fields of a particular type."] type cxversion = { major: int [@ocaml.doc "The major version number, e.g., the '10' in '10.7.3'. A negative value indicates that there is no version number at all."]; minor: int [@ocaml.doc "The minor version number, e.g., the '7' in '10.7.3'. This value will be negative if no minor version number was provided, e.g., for version '10'."]; subminor: int [@ocaml.doc "The subminor version number, e.g., the '3' in '10.7.3'. This value will be negative if no minor or subminor version number was provided, e.g., in version '10' or '10.7'."]} [@@deriving refl][@@ocaml.doc "Describes a version number of the form major.minor.subminor."] external ext_get_version : unit -> cxversion = "clang_ext_getVersion_wrapper" type cxint external equal_cxint : cxint -> cxint -> bool = "clang_equal_cxint_wrapper" external compare_cxint : cxint -> cxint -> int = "clang_compare_cxint_wrapper" external ext_integer_literal_get_value : cxcursor -> cxint = "clang_ext_IntegerLiteral_getValue_wrapper" external ext_int_is_valid : cxint -> bool = "clang_ext_Int_isValid_wrapper" external ext_int_to_string : cxint -> int -> bool -> string = "clang_ext_Int_toString_wrapper" external ext_int_round_to_double : cxint -> bool -> float = "clang_ext_Int_roundToDouble_wrapper" external ext_int_bits_to_float : cxint -> float = "clang_ext_Int_bitsToFloat_wrapper" external ext_int_get_bit_width : cxint -> int = "clang_ext_Int_getBitWidth_wrapper" external ext_int_get_active_bits : cxint -> int = "clang_ext_Int_getActiveBits_wrapper" external ext_int_get_min_signed_bits : cxint -> int = "clang_ext_Int_getMinSignedBits_wrapper" external ext_int_get_bool_value : cxint -> bool = "clang_ext_Int_getBoolValue_wrapper" external ext_int_get_zext_value : cxint -> int = "clang_ext_Int_getZExtValue_wrapper" external ext_int_get_sext_value : cxint -> int = "clang_ext_Int_getSExtValue_wrapper" external ext_int_get_zext_value64 : cxint -> Int64.t = "clang_ext_Int_getZExtValue64_wrapper" external ext_int_get_sext_value64 : cxint -> Int64.t = "clang_ext_Int_getSExtValue64_wrapper" type cxfloat external equal_cxfloat : cxfloat -> cxfloat -> bool = "clang_equal_cxfloat_wrapper" external compare_cxfloat : cxfloat -> cxfloat -> int = "clang_compare_cxfloat_wrapper" external ext_floating_literal_get_value : cxcursor -> cxfloat = "clang_ext_FloatingLiteral_getValue_wrapper" external ext_float_is_valid : cxfloat -> bool = "clang_ext_Float_isValid_wrapper" external ext_float_to_string : cxfloat -> string = "clang_ext_Float_toString_wrapper" type clang_ext_fltsemantics = | IEEEhalf | IEEEsingle | IEEEdouble | IEEEquad | PPCDoubleDouble | X87DoubleExtended | Bogus | Invalid [@@deriving refl] external ext_float_get_semantics : cxfloat -> clang_ext_fltsemantics = "clang_ext_Float_getSemantics_wrapper" external ext_float_convert_to_float : cxfloat -> float = "clang_ext_Float_convertToFloat_wrapper" external ext_float_convert_to_double : cxfloat -> float = "clang_ext_Float_convertToDouble_wrapper" external ext_string_literal_get_string : cxcursor -> string = "clang_ext_StringLiteral_GetString_wrapper" external ext_string_literal_get_bytes : cxcursor -> string = "clang_ext_StringLiteral_getBytes_wrapper" external ext_string_literal_get_byte_length : cxcursor -> int = "clang_ext_StringLiteral_getByteLength_wrapper" external ext_string_literal_get_char_byte_width : cxcursor -> int = "clang_ext_StringLiteral_getCharByteWidth_wrapper" type clang_ext_stringkind = | Ordinary | Wide | UTF8 | UTF16 | UTF32 | InvalidStringKind [@@deriving refl] external ext_string_literal_get_kind : cxcursor -> clang_ext_stringkind = "clang_ext_StringLiteral_getKind_wrapper" type clang_ext_unaryoperatorkind = | PostInc | PostDec | PreInc | PreDec | AddrOf | Deref | Plus | Minus | Not | LNot | Real | Imag | Extension | Coawait | InvalidUnaryOperator [@@deriving refl] external ext_unary_operator_get_opcode : cxcursor -> clang_ext_unaryoperatorkind = "clang_ext_UnaryOperator_getOpcode_wrapper" external ext_unary_operator_get_opcode_spelling : clang_ext_unaryoperatorkind -> string = "clang_ext_UnaryOperator_getOpcodeSpelling_wrapper" type clang_ext_binaryoperatorkind = | PtrMemD | PtrMemI | Mul | Div | Rem | Add | Sub | Shl | Shr | Cmp | LT | GT | LE | GE | EQ | NE | And | Xor | Or | LAnd | LOr | Assign | MulAssign | DivAssign | RemAssign | AddAssign | SubAssign | ShlAssign | ShrAssign | AndAssign | XorAssign | OrAssign | Comma | InvalidBinaryOperator [@@deriving refl] external ext_binary_operator_get_opcode : cxcursor -> clang_ext_binaryoperatorkind = "clang_ext_BinaryOperator_getOpcode_wrapper" external ext_binary_operator_get_opcode_spelling : clang_ext_binaryoperatorkind -> string = "clang_ext_BinaryOperator_getOpcodeSpelling_wrapper" external ext_for_stmt_get_children_set : cxcursor -> int = "clang_ext_ForStmt_getChildrenSet_wrapper" external ext_if_stmt_get_children_set : cxcursor -> int = "clang_ext_IfStmt_getChildrenSet_wrapper" external ext_if_stmt_get_init : cxcursor -> cxcursor = "clang_ext_IfStmt_getInit_wrapper" external ext_if_stmt_get_condition_variable : cxcursor -> cxcursor = "clang_ext_IfStmt_getConditionVariable_wrapper" external ext_if_stmt_get_cond : cxcursor -> cxcursor = "clang_ext_IfStmt_getCond_wrapper" external ext_if_stmt_get_then : cxcursor -> cxcursor = "clang_ext_IfStmt_getThen_wrapper" external ext_if_stmt_get_else : cxcursor -> cxcursor = "clang_ext_IfStmt_getElse_wrapper" external ext_switch_stmt_get_children_set : cxcursor -> int = "clang_ext_SwitchStmt_getChildrenSet_wrapper" external ext_switch_stmt_get_init : cxcursor -> cxcursor = "clang_ext_SwitchStmt_getInit_wrapper" external ext_while_stmt_get_children_set : cxcursor -> int = "clang_ext_WhileStmt_getChildrenSet_wrapper" type clang_ext_elaboratedtypekeyword = | Struct | Interface | Union | Class | Enum | Typename | NoKeyword [@@deriving refl] external ext_elaborated_type_get_keyword : cxtype -> clang_ext_elaboratedtypekeyword = "clang_ext_ElaboratedType_getKeyword_wrapper" external ext_elaborated_type_get_keyword_spelling : clang_ext_elaboratedtypekeyword -> string = "clang_ext_ElaboratedType_getKeywordSpelling_wrapper" external ext_var_decl_has_init : cxcursor -> bool = "clang_ext_VarDecl_hasInit_wrapper" external ext_var_decl_is_constexpr : cxcursor -> bool = "clang_ext_VarDecl_isConstexpr_wrapper" external ext_member_ref_expr_is_arrow : cxcursor -> bool = "clang_ext_MemberRefExpr_isArrow_wrapper" external ext_stmt_get_class_name : cxcursor -> string = "clang_ext_Stmt_GetClassName_wrapper" external ext_stmt_get_class_kind : cxcursor -> int = "clang_ext_Stmt_GetClassKind_wrapper" type clang_ext_cursorkind = | ImplicitCastExpr | BinaryConditionalOperator | UnaryExprOrTypeTraitExpr | EmptyDecl | LinkageSpecDecl | Unknown [@@deriving refl] external ext_get_cursor_kind : cxcursor -> clang_ext_cursorkind = "clang_ext_GetCursorKind_wrapper" type clang_ext_declkind = | InvalidDecl | AccessSpec | Block | Captured | ClassScopeFunctionSpecialization | Empty | Export | ExternCContext | FileScopeAsm | Friend | FriendTemplate | Import | LinkageSpec | Label | Namespace | NamespaceAlias | ObjCCompatibleAlias | ObjCCategory | ObjCCategoryImpl | ObjCImplementation | ObjCInterface | ObjCProtocol | ObjCMethod | ObjCProperty | BuiltinTemplate | ClassTemplate | FunctionTemplate | TypeAliasTemplate | VarTemplate | TemplateTemplateParm | Enum | Record | CXXRecord | ClassTemplateSpecialization | ClassTemplatePartialSpecialization | TemplateTypeParm | ObjCTypeParam | TypeAlias | Typedef | UnresolvedUsingTypename | Using | UsingDirective | UsingPack | UsingShadow | ConstructorUsingShadow | Binding | Field | ObjCAtDefsField | ObjCIvar | Function | CXXDeductionGuide | CXXMethod | CXXConstructor | CXXConversion | CXXDestructor | MSProperty | NonTypeTemplateParm | Var | Decomposition | ImplicitParam | OMPCapturedExpr | ParmVar | VarTemplateSpecialization | VarTemplatePartialSpecialization | EnumConstant | IndirectField | OMPDeclareReduction | UnresolvedUsingValue | OMPThreadPrivate | ObjCPropertyImpl | PragmaComment | PragmaDetectMismatch | StaticAssert | TranslationUnit | UnknownDecl [@@deriving refl] external ext_decl_get_kind : cxcursor -> clang_ext_declkind = "clang_ext_Decl_GetKind_wrapper" external ext_decl_visit_attributes : cxcursor -> (cxcursor -> cxcursor -> cxchildvisitresult) -> bool = "clang_ext_Decl_visitAttributes_wrapper" external ext_decl_is_implicit : cxcursor -> bool = "clang_ext_Decl_isImplicit_wrapper" external ext_record_decl_is_injected_class_name : cxcursor -> bool = "clang_ext_RecordDecl_isInjectedClassName_wrapper" external ext_cxxrecord_decl_visit_bases : cxcursor -> (cxcursor -> cxcursor -> cxchildvisitresult) -> bool = "clang_ext_CXXRecordDecl_visitBases_wrapper" type clang_ext_stmtkind = | InvalidStmt | GCCAsmStmt | MSAsmStmt | AttributedStmt | BreakStmt | CXXCatchStmt | CXXForRangeStmt | CXXTryStmt | CapturedStmt | CompoundStmt | ContinueStmt | CoreturnStmt | CoroutineBodyStmt | DeclStmt | DoStmt | BinaryConditionalOperator | ConditionalOperator | AddrLabelExpr | ArrayInitIndexExpr | ArrayInitLoopExpr | ArraySubscriptExpr | ArrayTypeTraitExpr | AsTypeExpr | AtomicExpr | BinaryOperator | CompoundAssignOperator | BlockExpr | CXXBindTemporaryExpr | CXXBoolLiteralExpr | CXXConstructExpr | CXXTemporaryObjectExpr | CXXDefaultArgExpr | CXXDefaultInitExpr | CXXDeleteExpr | CXXDependentScopeMemberExpr | CXXFoldExpr | CXXInheritedCtorInitExpr | CXXNewExpr | CXXNoexceptExpr | CXXNullPtrLiteralExpr | CXXPseudoDestructorExpr | CXXScalarValueInitExpr | CXXStdInitializerListExpr | CXXThisExpr | CXXThrowExpr | CXXTypeidExpr | CXXUnresolvedConstructExpr | CXXUuidofExpr | CallExpr | CUDAKernelCallExpr | CXXMemberCallExpr | CXXOperatorCallExpr | UserDefinedLiteral | CStyleCastExpr | CXXFunctionalCastExpr | CXXConstCastExpr | CXXDynamicCastExpr | CXXReinterpretCastExpr | CXXStaticCastExpr | ObjCBridgedCastExpr | ImplicitCastExpr | CharacterLiteral | ChooseExpr | CompoundLiteralExpr | ConvertVectorExpr | CoawaitExpr | CoyieldExpr | DeclRefExpr | DependentCoawaitExpr | DependentScopeDeclRefExpr | DesignatedInitExpr | DesignatedInitUpdateExpr | ExprWithCleanups | ExpressionTraitExpr | ExtVectorElementExpr | FixedPointLiteral | FloatingLiteral | FunctionParmPackExpr | GNUNullExpr | GenericSelectionExpr | ImaginaryLiteral | ImplicitValueInitExpr | InitListExpr | IntegerLiteral | LambdaExpr | MSPropertyRefExpr | MSPropertySubscriptExpr | MaterializeTemporaryExpr | MemberExpr | NoInitExpr | OMPArraySectionExpr | ObjCArrayLiteral | ObjCAvailabilityCheckExpr | ObjCBoolLiteralExpr | ObjCBoxedExpr | ObjCDictionaryLiteral | ObjCEncodeExpr | ObjCIndirectCopyRestoreExpr | ObjCIsaExpr | ObjCIvarRefExpr | ObjCMessageExpr | ObjCPropertyRefExpr | ObjCProtocolExpr | ObjCSelectorExpr | ObjCStringLiteral | ObjCSubscriptRefExpr | OffsetOfExpr | OpaqueValueExpr | UnresolvedLookupExpr | UnresolvedMemberExpr | PackExpansionExpr | ParenExpr | ParenListExpr | PredefinedExpr | PseudoObjectExpr | ShuffleVectorExpr | SizeOfPackExpr | StmtExpr | StringLiteral | SubstNonTypeTemplateParmExpr | SubstNonTypeTemplateParmPackExpr | TypeTraitExpr | TypoExpr | UnaryExprOrTypeTraitExpr | UnaryOperator | VAArgExpr | ForStmt | GotoStmt | IfStmt | IndirectGotoStmt | LabelStmt | MSDependentExistsStmt | NullStmt | OMPAtomicDirective | OMPBarrierDirective | OMPCancelDirective | OMPCancellationPointDirective | OMPCriticalDirective | OMPFlushDirective | OMPDistributeDirective | OMPDistributeParallelForDirective | OMPDistributeParallelForSimdDirective | OMPDistributeSimdDirective | OMPForDirective | OMPForSimdDirective | OMPParallelForDirective | OMPParallelForSimdDirective | OMPSimdDirective | OMPTargetParallelForSimdDirective | OMPTargetSimdDirective | OMPTargetTeamsDistributeDirective | OMPTargetTeamsDistributeParallelForDirective | OMPTargetTeamsDistributeParallelForSimdDirective | OMPTargetTeamsDistributeSimdDirective | OMPTaskLoopDirective | OMPTaskLoopSimdDirective | OMPTeamsDistributeDirective | OMPTeamsDistributeParallelForDirective | OMPTeamsDistributeParallelForSimdDirective | OMPTeamsDistributeSimdDirective | OMPMasterDirective | OMPOrderedDirective | OMPParallelDirective | OMPParallelSectionsDirective | OMPSectionDirective | OMPSectionsDirective | OMPSingleDirective | OMPTargetDataDirective | OMPTargetDirective | OMPTargetEnterDataDirective | OMPTargetExitDataDirective | OMPTargetParallelDirective | OMPTargetParallelForDirective | OMPTargetTeamsDirective | OMPTargetUpdateDirective | OMPTaskDirective | OMPTaskgroupDirective | OMPTaskwaitDirective | OMPTaskyieldDirective | OMPTeamsDirective | ObjCAtCatchStmt | ObjCAtFinallyStmt | ObjCAtSynchronizedStmt | ObjCAtThrowStmt | ObjCAtTryStmt | ObjCAutoreleasePoolStmt | ObjCForCollectionStmt | ReturnStmt | SEHExceptStmt | SEHFinallyStmt | SEHLeaveStmt | SEHTryStmt | CaseStmt | DefaultStmt | SwitchStmt | WhileStmt | UnknownStmt [@@deriving refl] external ext_stmt_get_kind : cxcursor -> clang_ext_stmtkind = "clang_ext_Stmt_GetKind_wrapper" type clang_ext_typekind = | InvalidType | Builtin | Complex | Pointer | BlockPointer | LValueReference | RValueReference | MemberPointer | ConstantArray | IncompleteArray | VariableArray | DependentSizedArray | DependentSizedExtVector | DependentAddressSpace | Vector | DependentVector | ExtVector | FunctionProto | FunctionNoProto | UnresolvedUsing | Paren | Typedef | Adjusted | Decayed | TypeOfExpr | TypeOf | Decltype | UnaryTransform | Record | Enum | Elaborated | Attributed | TemplateTypeParm | SubstTemplateTypeParm | SubstTemplateTypeParmPack | TemplateSpecialization | Auto | DeducedTemplateSpecialization | InjectedClassName | DependentName | DependentTemplateSpecialization | PackExpansion | ObjCTypeParam | ObjCObject | ObjCInterface | ObjCObjectPointer | Pipe | Atomic | UnknownType [@@deriving refl] external ext_type_get_kind : cxtype -> clang_ext_typekind = "clang_ext_Type_GetKind_wrapper" external ext_get_type_kind : cxtype -> clang_ext_typekind = "clang_ext_GetTypeKind_wrapper" external ext_get_inner_type : cxtype -> cxtype = "clang_ext_GetInnerType_wrapper" external ext_declarator_decl_get_size_expr : cxcursor -> cxcursor = "clang_ext_DeclaratorDecl_GetSizeExpr_wrapper" external ext_variable_array_type_get_size_expr : cxtype -> cxcursor = "clang_ext_VariableArrayType_GetSizeExpr_wrapper" type clang_ext_characterkind = | Ascii | Wide | UTF8 | UTF16 | UTF32 | InvalidCharacterKind [@@deriving refl] external ext_character_literal_get_character_kind : cxcursor -> clang_ext_characterkind = "clang_ext_CharacterLiteral_GetCharacterKind_wrapper" external ext_character_literal_get_value : cxcursor -> int = "clang_ext_CharacterLiteral_GetValue_wrapper" type clang_ext_unaryexpr = | SizeOf | AlignOf | VecStep | OpenMPRequiredSimdAlign | PreferredAlignOf [@@deriving refl] external ext_unary_expr_get_kind : cxcursor -> clang_ext_unaryexpr = "clang_ext_UnaryExpr_GetKind_wrapper" external ext_unary_expr_is_argument_type : cxcursor -> bool = "clang_ext_UnaryExpr_isArgumentType_wrapper" type clang_ext_typeloc external ext_unary_expr_get_argument_type_loc : cxcursor -> clang_ext_typeloc = "clang_ext_UnaryExpr_getArgumentTypeLoc_wrapper" external ext_type_get_named_type : cxtype -> cxtype = "clang_ext_Type_getNamedType_wrapper" type clang_ext_attrkind = | NoAttr | FallThrough | Suppress | SwiftContext | SwiftErrorResult | SwiftIndirectResult | Annotate | CFConsumed | CarriesDependency | NSConsumed | NonNull | PassObjectSize | AMDGPUFlatWorkGroupSize | AMDGPUNumSGPR | AMDGPUNumVGPR | AMDGPUWavesPerEU | ARMInterrupt | AVRInterrupt | AVRSignal | AcquireCapability | AcquiredAfter | AcquiredBefore | AlignMac68k | Aligned | AllocAlign | AllocSize | AlwaysInline | AnalyzerNoReturn | AnyX86Interrupt | AnyX86NoCallerSavedRegisters | AnyX86NoCfCheck | ArcWeakrefUnavailable | ArgumentWithTypeTag | Artificial | AsmLabel | AssertCapability | AssertExclusiveLock | AssertSharedLock | AssumeAligned | Availability | Blocks | C11NoReturn | CDecl | CFAuditedTransfer | CFReturnsNotRetained | CFReturnsRetained | CFUnknownTransfer | CPUDispatch | CPUSpecific | CUDAConstant | CUDADevice | CUDAGlobal | CUDAHost | CUDAInvalidTarget | CUDALaunchBounds | CUDAShared | CXX11NoReturn | CallableWhen | Capability | CapturedRecord | Cleanup | CodeSeg | Cold | Common | Const | Constructor | Consumable | ConsumableAutoCast | ConsumableSetOnRead | Convergent | DLLExport | DLLImport | Deprecated | Destructor | DiagnoseIf | DisableTailCalls | EmptyBases | EnableIf | EnumExtensibility | ExclusiveTrylockFunction | ExternalSourceSymbol | FastCall | Final | FlagEnum | Flatten | Format | FormatArg | GNUInline | GuardedBy | GuardedVar | Hot | IBAction | IBOutlet | IBOutletCollection | InitPriority | IntelOclBicc | InternalLinkage | LTOVisibilityPublic | LayoutVersion | LifetimeBound | LockReturned | LocksExcluded | MSABI | MSInheritance | MSNoVTable | MSP430Interrupt | MSStruct | MSVtorDisp | MaxFieldAlignment | MayAlias | MicroMips | MinSize | MinVectorWidth | Mips16 | MipsInterrupt | MipsLongCall | MipsShortCall | NSConsumesSelf | NSReturnsAutoreleased | NSReturnsNotRetained | NSReturnsRetained | Naked | NoAlias | NoCommon | NoDebug | NoDuplicate | NoInline | NoInstrumentFunction | NoMicroMips | NoMips16 | NoReturn | NoSanitize | NoSplitStack | NoStackProtector | NoThreadSafetyAnalysis | NoThrow | NotTailCalled | OMPCaptureNoInit | OMPDeclareTargetDecl | OMPThreadPrivateDecl | ObjCBridge | ObjCBridgeMutable | ObjCBridgeRelated | ObjCException | ObjCExplicitProtocolImpl | ObjCIndependentClass | ObjCMethodFamily | ObjCNSObject | ObjCPreciseLifetime | ObjCRequiresPropertyDefs | ObjCRequiresSuper | ObjCReturnsInnerPointer | ObjCRootClass | ObjCSubclassingRestricted | OpenCLIntelReqdSubGroupSize | OpenCLKernel | OpenCLUnrollHint | OptimizeNone | Override | Ownership | Packed | ParamTypestate | Pascal | Pcs | PragmaClangBSSSection | PragmaClangDataSection | PragmaClangRodataSection | PragmaClangTextSection | PreserveAll | PreserveMost | PtGuardedBy | PtGuardedVar | Pure | RISCVInterrupt | RegCall | ReleaseCapability | ReqdWorkGroupSize | RequireConstantInit | RequiresCapability | Restrict | ReturnTypestate | ReturnsNonNull | ReturnsTwice | ScopedLockable | Section | SelectAny | Sentinel | SetTypestate | SharedTrylockFunction | StdCall | SwiftCall | SysVABI | TLSModel | Target | TestTypestate | ThisCall | TransparentUnion | TrivialABI | TryAcquireCapability | TypeTagForDatatype | TypeVisibility | Unavailable | Unused | Used | Uuid | VecReturn | VecTypeHint | VectorCall | Visibility | WarnUnused | WarnUnusedResult | Weak | WeakImport | WeakRef | WorkGroupSizeHint | X86ForceAlignArgPointer | XRayInstrument | XRayLogArgs | AbiTag | Alias | AlignValue | IFunc | InitSeg | LoopHint | Mode | NoEscape | OMPCaptureKind | OMPDeclareSimdDecl | OMPReferencedVar | ObjCBoxable | ObjCDesignatedInitializer | ObjCRuntimeName | ObjCRuntimeVisible | OpenCLAccess | Overloadable | RenderScriptKernel | Thread [@@deriving refl] external ext_attr_kind_get_spelling : clang_ext_attrkind -> string = "clang_ext_AttrKind_GetSpelling_wrapper" external ext_cxxmethod_is_defaulted : cxcursor -> bool = "clang_ext_CXXMethod_isDefaulted_wrapper" external ext_cxxmethod_is_const : cxcursor -> bool = "clang_ext_CXXMethod_isConst_wrapper" external ext_cxxconstructor_is_explicit : cxcursor -> bool = "clang_ext_CXXConstructor_isExplicit_wrapper" external ext_function_decl_is_deleted : cxcursor -> bool = "clang_ext_FunctionDecl_isDeleted_wrapper" external ext_function_decl_get_num_params : cxcursor -> int = "clang_ext_FunctionDecl_getNumParams_wrapper" external ext_function_decl_get_param_decl : cxcursor -> int -> cxcursor = "clang_ext_FunctionDecl_getParamDecl_wrapper" external ext_function_decl_is_constexpr : cxcursor -> bool = "clang_ext_FunctionDecl_isConstexpr_wrapper" external ext_function_decl_has_written_prototype : cxcursor -> bool = "clang_ext_FunctionDecl_hasWrittenPrototype_wrapper" external ext_function_decl_does_this_declaration_have_abody : cxcursor -> bool = "clang_ext_FunctionDecl_doesThisDeclarationHaveABody_wrapper" external ext_function_decl_get_body : cxcursor -> cxcursor = "clang_ext_FunctionDecl_getBody_wrapper" module Clang_ext_languageids : sig type t external (+) : t -> t -> t = "%orint" val (-) : t -> t -> t external (&) : t -> t -> t = "%andint" external ( * ) : t -> t -> t = "%xorint" val subset : t -> t -> bool val zero : t val c : t val cxx : t end external ext_linkage_spec_decl_get_language_ids : cxcursor -> Clang_ext_languageids.t = "clang_ext_LinkageSpecDecl_getLanguageIDs_wrapper" external ext_template_type_parm_decl_get_default_argument : cxcursor -> cxtype = "clang_ext_TemplateTypeParmDecl_getDefaultArgument_wrapper" external ext_non_type_template_parm_decl_get_default_argument : cxcursor -> cxcursor = "clang_ext_NonTypeTemplateParmDecl_getDefaultArgument_wrapper" type clang_ext_templatename_namekind = | Template | OverloadedTemplate | AssumedTemplate | QualifiedTemplate | DependentTemplate | SubstTemplateTemplateParm | SubstTemplateTemplateParmPack | InvalidNameKind [@@deriving refl] type clang_ext_templatename external ext_template_name_get_kind : clang_ext_templatename -> clang_ext_templatename_namekind = "clang_ext_TemplateName_getKind_wrapper" external ext_template_name_get_as_template_decl : clang_ext_templatename -> cxcursor = "clang_ext_TemplateName_getAsTemplateDecl_wrapper" type clang_ext_templateargument external ext_template_argument_get_kind : clang_ext_templateargument -> cxtemplateargumentkind = "clang_ext_TemplateArgument_getKind_wrapper" external ext_template_argument_get_as_type : clang_ext_templateargument -> cxtype = "clang_ext_TemplateArgument_getAsType_wrapper" external ext_template_argument_get_as_decl : clang_ext_templateargument -> cxcursor = "clang_ext_TemplateArgument_getAsDecl_wrapper" external ext_template_argument_get_null_ptr_type : clang_ext_templateargument -> cxtype = "clang_ext_TemplateArgument_getNullPtrType_wrapper" external ext_template_argument_get_as_template_or_template_pattern : clang_ext_templateargument -> clang_ext_templatename = "clang_ext_TemplateArgument_getAsTemplateOrTemplatePattern_wrapper" external ext_template_argument_get_as_integral : clang_ext_templateargument -> cxint = "clang_ext_TemplateArgument_getAsIntegral_wrapper" external ext_template_argument_get_integral_type : clang_ext_templateargument -> cxtype = "clang_ext_TemplateArgument_getIntegralType_wrapper" external ext_template_argument_get_as_expr : clang_ext_templateargument -> cxcursor = "clang_ext_TemplateArgument_getAsExpr_wrapper" external ext_template_argument_get_pack_size : clang_ext_templateargument -> int = "clang_ext_TemplateArgument_getPackSize_wrapper" external ext_template_argument_get_pack_argument : clang_ext_templateargument -> int -> clang_ext_templateargument = "clang_ext_TemplateArgument_getPackArgument_wrapper" external ext_template_argument_get_pack_expansion_pattern : clang_ext_templateargument -> clang_ext_templateargument = "clang_ext_TemplateArgument_getPackExpansionPattern_wrapper" external ext_template_specialization_type_get_template_name : cxtype -> clang_ext_templatename = "clang_ext_TemplateSpecializationType_getTemplateName_wrapper" external ext_template_specialization_type_get_num_args : cxtype -> int = "clang_ext_TemplateSpecializationType_getNumArgs_wrapper" external ext_template_specialization_type_get_argument : cxtype -> int -> clang_ext_templateargument = "clang_ext_TemplateSpecializationType_getArgument_wrapper" external ext_friend_decl_get_friend_decl : cxcursor -> cxcursor = "clang_ext_FriendDecl_getFriendDecl_wrapper" external ext_friend_decl_get_friend_type : cxcursor -> cxtype = "clang_ext_FriendDecl_getFriendType_wrapper" external ext_field_decl_get_in_class_initializer : cxcursor -> cxcursor = "clang_ext_FieldDecl_getInClassInitializer_wrapper" external ext_generic_selection_expr_get_assoc_type : cxcursor -> int -> cxtype = "clang_ext_GenericSelectionExpr_getAssocType_wrapper" external ext_template_parm_is_parameter_pack : cxcursor -> bool = "clang_ext_TemplateParm_isParameterPack_wrapper" external ext_template_decl_get_templated_decl : cxcursor -> cxcursor = "clang_ext_TemplateDecl_getTemplatedDecl_wrapper" type clang_ext_predefinedexpr_identkind = | Func | Function | LFunction | FuncDName | FuncSig | LFuncSig | PrettyFunction | PrettyFunctionNoVirtual | InvalidPredefinedExpr [@@deriving refl] external ext_predefined_expr_get_ident_kind : cxcursor -> clang_ext_predefinedexpr_identkind = "clang_ext_PredefinedExpr_getIdentKind_wrapper" external ext_predefined_expr_get_function_name : cxcursor -> string = "clang_ext_PredefinedExpr_getFunctionName_wrapper" external ext_predefined_expr_compute_name : clang_ext_predefinedexpr_identkind -> cxcursor -> string = "clang_ext_PredefinedExpr_ComputeName_wrapper" external ext_lambda_expr_is_mutable : cxcursor -> bool = "clang_ext_LambdaExpr_isMutable_wrapper" external ext_lambda_expr_has_explicit_parameters : cxcursor -> bool = "clang_ext_LambdaExpr_hasExplicitParameters_wrapper" external ext_lambda_expr_has_explicit_result_type : cxcursor -> bool = "clang_ext_LambdaExpr_hasExplicitResultType_wrapper" type clang_ext_lambdacapturedefault = | CaptureNone | ByCopy | ByRef [@@deriving refl] external ext_lambda_expr_get_capture_default : cxcursor -> clang_ext_lambdacapturedefault = "clang_ext_LambdaExpr_getCaptureDefault_wrapper" type clang_ext_lambdacapture external ext_lambda_expr_get_captures : cxcursor -> (clang_ext_lambdacapture -> unit) -> unit = "clang_ext_LambdaExpr_getCaptures_wrapper" external ext_lambda_expr_get_call_operator : cxcursor -> cxcursor = "clang_ext_LambdaExpr_getCallOperator_wrapper" type clang_ext_lambdacapturekind = | This | StarThis | ByCopy | ByRef | VLAType [@@deriving refl] external ext_lambda_capture_get_kind : clang_ext_lambdacapture -> clang_ext_lambdacapturekind = "clang_ext_LambdaCapture_getKind_wrapper" external ext_lambda_capture_get_captured_var : clang_ext_lambdacapture -> cxcursor = "clang_ext_LambdaCapture_getCapturedVar_wrapper" external ext_lambda_capture_is_implicit : clang_ext_lambdacapture -> bool = "clang_ext_LambdaCapture_isImplicit_wrapper" external ext_lambda_capture_is_pack_expansion : clang_ext_lambdacapture -> bool = "clang_ext_LambdaCapture_isPackExpansion_wrapper" external ext_cxxnew_expr_get_allocated_type_loc : cxcursor -> clang_ext_typeloc = "clang_ext_CXXNewExpr_getAllocatedTypeLoc_wrapper" external ext_cxxnew_expr_get_array_size : cxcursor -> cxcursor = "clang_ext_CXXNewExpr_getArraySize_wrapper" external ext_cxxnew_expr_get_num_placement_args : cxcursor -> int = "clang_ext_CXXNewExpr_getNumPlacementArgs_wrapper" external ext_cxxnew_expr_get_placement_arg : cxcursor -> int -> cxcursor = "clang_ext_CXXNewExpr_getPlacementArg_wrapper" external ext_cxxnew_expr_get_initializer : cxcursor -> cxcursor = "clang_ext_CXXNewExpr_getInitializer_wrapper" external ext_cxxdelete_expr_is_global_delete : cxcursor -> bool = "clang_ext_CXXDeleteExpr_isGlobalDelete_wrapper" external ext_cxxdelete_expr_is_array_form : cxcursor -> bool = "clang_ext_CXXDeleteExpr_isArrayForm_wrapper" external ext_cxxtypeid_expr_is_type_operand : cxcursor -> bool = "clang_ext_CXXTypeidExpr_isTypeOperand_wrapper" external ext_cxxtypeid_expr_get_type_operand : cxcursor -> clang_ext_typeloc = "clang_ext_CXXTypeidExpr_getTypeOperand_wrapper" external ext_cxxtypeid_expr_get_expr_operand : cxcursor -> cxcursor = "clang_ext_CXXTypeidExpr_getExprOperand_wrapper" type clang_ext_langstandards = | C89 | C94 | Gnu89 | C99 | Gnu99 | C11 | Gnu11 | C17 | Gnu17 | Cxx98 | Gnucxx98 | Cxx11 | Gnucxx11 | Cxx14 | Gnucxx14 | Cxx17 | Gnucxx17 | Cxx2a | Gnucxx2a | Opencl10 | Opencl11 | Opencl12 | Opencl20 | Openclcpp | Cuda | Hip | InvalidLang [@@deriving refl] external ext_lang_standard_get_name : clang_ext_langstandards -> string = "clang_ext_LangStandard_getName_wrapper" external ext_lang_standard_of_name : string -> clang_ext_langstandards = "clang_ext_LangStandard_ofName_wrapper" external ext_pack_expansion_get_pattern : cxtype -> cxtype = "clang_ext_PackExpansion_getPattern_wrapper" external ext_cxxfold_expr_is_right_fold : cxcursor -> bool = "clang_ext_CXXFoldExpr_isRightFold_wrapper" external ext_cxxfold_expr_get_operator : cxcursor -> clang_ext_binaryoperatorkind = "clang_ext_CXXFoldExpr_getOperator_wrapper" external ext_cxxbool_literal_expr_get_value : cxcursor -> bool = "clang_ext_CXXBoolLiteralExpr_getValue_wrapper" external ext_call_expr_get_callee : cxcursor -> cxcursor = "clang_ext_CallExpr_getCallee_wrapper" external ext_call_expr_get_num_args : cxcursor -> int = "clang_ext_CallExpr_getNumArgs_wrapper" external ext_call_expr_get_arg : cxcursor -> int -> cxcursor = "clang_ext_CallExpr_getArg_wrapper" external ext_size_of_pack_expr_get_pack : cxcursor -> cxcursor = "clang_ext_SizeOfPackExpr_getPack_wrapper" external ext_decltype_type_get_underlying_expr : cxtype -> cxcursor = "clang_ext_DecltypeType_getUnderlyingExpr_wrapper" external ext_namespace_decl_is_inline : cxcursor -> bool = "clang_ext_NamespaceDecl_isInline_wrapper" type clang_ext_overloadedoperatorkind = | InvalidOverloadedOperator | New | Delete | Array_New | Array_Delete | Plus | Minus | Star | Slash | Percent | Caret | Amp | Pipe | Tilde | Exclaim | Equal | Less | Greater | PlusEqual | MinusEqual | StarEqual | SlashEqual | PercentEqual | CaretEqual | AmpEqual | PipeEqual | LessLess | GreaterGreater | LessLessEqual | GreaterGreaterEqual | EqualEqual | ExclaimEqual | LessEqual | GreaterEqual | Spaceship | AmpAmp | PipePipe | PlusPlus | MinusMinus | Comma | ArrowStar | Arrow | Call | Subscript | Conditional | Coawait [@@deriving refl] external ext_overloaded_operator_get_spelling : clang_ext_overloadedoperatorkind -> string = "clang_ext_OverloadedOperator_getSpelling_wrapper" type clang_ext_declarationnamekind = | Identifier | ObjCZeroArgSelector | ObjCOneArgSelector | ObjCMultiArgSelector | CXXConstructorName | CXXDestructorName | CXXConversionFunctionName | CXXDeductionGuideName | CXXOperatorName | CXXLiteralOperatorName | CXXUsingDirective | InvalidDeclarationName [@@deriving refl] type clang_ext_declarationname external ext_declaration_name_get_kind : clang_ext_declarationname -> clang_ext_declarationnamekind = "clang_ext_DeclarationName_getKind_wrapper" external ext_declaration_name_get_cxxoverloaded_operator : clang_ext_declarationname -> clang_ext_overloadedoperatorkind = "clang_ext_DeclarationName_getCXXOverloadedOperator_wrapper" external ext_declaration_name_get_cxxname_type : clang_ext_declarationname -> cxtype = "clang_ext_DeclarationName_getCXXNameType_wrapper" external ext_declaration_name_get_as_identifier : clang_ext_declarationname -> string = "clang_ext_DeclarationName_getAsIdentifier_wrapper" external ext_declaration_name_get_cxxdeduction_guide_template : clang_ext_declarationname -> cxcursor = "clang_ext_DeclarationName_getCXXDeductionGuideTemplate_wrapper" external ext_declaration_name_get_cxxliteral_identifier : clang_ext_declarationname -> string = "clang_ext_DeclarationName_getCXXLiteralIdentifier_wrapper" external ext_decl_get_name : cxcursor -> clang_ext_declarationname = "clang_ext_Decl_getName_wrapper" external ext_using_directive_decl_get_nominated_namespace : cxcursor -> cxcursor = "clang_ext_UsingDirectiveDecl_getNominatedNamespace_wrapper" type clang_ext_nestednamespecifierkind = | InvalidNestedNameSpecifier | Identifier | Namespace | NamespaceAlias | TypeSpec | TypeSpecWithTemplate | Global | Super [@@deriving refl] type clang_ext_nestednamespecifier external ext_nested_name_specifier_get_kind : clang_ext_nestednamespecifier -> clang_ext_nestednamespecifierkind = "clang_ext_NestedNameSpecifier_getKind_wrapper" external ext_nested_name_specifier_get_prefix : clang_ext_nestednamespecifier -> clang_ext_nestednamespecifier = "clang_ext_NestedNameSpecifier_getPrefix_wrapper" external ext_nested_name_specifier_get_as_identifier : clang_ext_nestednamespecifier -> string = "clang_ext_NestedNameSpecifier_getAsIdentifier_wrapper" external ext_nested_name_specifier_get_as_namespace : clang_ext_nestednamespecifier -> cxcursor = "clang_ext_NestedNameSpecifier_getAsNamespace_wrapper" external ext_nested_name_specifier_get_as_type : clang_ext_nestednamespecifier -> cxtype = "clang_ext_NestedNameSpecifier_getAsType_wrapper" type clang_ext_nestednamespecifierloc external ext_nested_name_specifier_loc_get_nested_name_specifier : clang_ext_nestednamespecifierloc -> clang_ext_nestednamespecifier = "clang_ext_NestedNameSpecifierLoc_getNestedNameSpecifier_wrapper" external ext_nested_name_specifier_loc_get_prefix : clang_ext_nestednamespecifierloc -> clang_ext_nestednamespecifierloc = "clang_ext_NestedNameSpecifierLoc_getPrefix_wrapper" external ext_nested_name_specifier_loc_get_as_type_loc : clang_ext_nestednamespecifierloc -> clang_ext_typeloc = "clang_ext_NestedNameSpecifierLoc_getAsTypeLoc_wrapper" external ext_decl_get_nested_name_specifier_loc : cxcursor -> clang_ext_nestednamespecifierloc = "clang_ext_Decl_getNestedNameSpecifierLoc_wrapper" external ext_type_loc_get_qualifier_loc : clang_ext_typeloc -> clang_ext_nestednamespecifierloc = "clang_ext_TypeLoc_getQualifierLoc_wrapper" external ext_type_get_qualifier : cxtype -> clang_ext_nestednamespecifier = "clang_ext_Type_getQualifier_wrapper" external ext_tag_decl_is_complete_definition : cxcursor -> bool = "clang_ext_TagDecl_isCompleteDefinition_wrapper" external ext_cxxpseudo_destructor_expr_get_destroyed_type_loc : cxcursor -> clang_ext_typeloc = "clang_ext_CXXPseudoDestructorExpr_getDestroyedTypeLoc_wrapper" external ext_cursor_get_num_template_args : cxcursor -> int = "clang_ext_Cursor_getNumTemplateArgs_wrapper" external ext_cursor_get_template_arg : cxcursor -> int -> clang_ext_templateargument = "clang_ext_Cursor_getTemplateArg_wrapper" type clang_ext_templateparameterlist external ext_template_parameter_list_size : clang_ext_templateparameterlist -> int = "clang_ext_TemplateParameterList_size_wrapper" external ext_template_parameter_list_get_param : clang_ext_templateparameterlist -> int -> cxcursor = "clang_ext_TemplateParameterList_getParam_wrapper" external ext_template_parameter_list_get_requires_clause : clang_ext_templateparameterlist -> cxcursor = "clang_ext_TemplateParameterList_getRequiresClause_wrapper" external ext_template_decl_get_template_parameters : cxcursor -> clang_ext_templateparameterlist = "clang_ext_TemplateDecl_getTemplateParameters_wrapper" external ext_template_decl_get_parameter_count : cxcursor -> int = "clang_ext_TemplateDecl_getParameterCount_wrapper" external ext_template_decl_get_parameter : cxcursor -> int -> cxcursor = "clang_ext_TemplateDecl_getParameter_wrapper" external ext_subst_non_type_template_parm_expr_get_replacement : cxcursor -> cxcursor = "clang_ext_SubstNonTypeTemplateParmExpr_getReplacement_wrapper" external ext_attributed_stmt_get_attribute_count : cxcursor -> int = "clang_ext_AttributedStmt_GetAttributeCount_wrapper" external ext_attributed_stmt_get_attribute_kind : cxcursor -> int -> clang_ext_attrkind = "clang_ext_AttributedStmt_GetAttributeKind_wrapper" external ext_attributed_stmt_get_attrs : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_AttributedStmt_getAttrs_wrapper" external ext_decomposition_decl_get_bindings_count : cxcursor -> int = "clang_ext_DecompositionDecl_GetBindingsCount_wrapper" external ext_decomposition_decl_get_bindings : cxcursor -> int -> cxcursor = "clang_ext_DecompositionDecl_GetBindings_wrapper" external ext_attr_get_kind : cxcursor -> clang_ext_attrkind = "clang_ext_Attr_GetKind_wrapper" type clang_ext_exceptionspecificationtype = | NoExceptionSpecification | DynamicNone | Dynamic | MSAny | NoThrow | BasicNoexcept | DependentNoexcept | NoexceptFalse | NoexceptTrue | Unevaluated | Uninstantiated | Unparsed [@@deriving refl] external ext_function_proto_type_get_exception_spec_type : cxtype -> clang_ext_exceptionspecificationtype = "clang_ext_FunctionProtoType_getExceptionSpecType_wrapper" external ext_function_proto_type_get_num_exceptions : cxtype -> int = "clang_ext_FunctionProtoType_getNumExceptions_wrapper" external ext_function_proto_type_get_exception_type : cxtype -> int -> cxtype = "clang_ext_FunctionProtoType_getExceptionType_wrapper" external ext_function_proto_type_get_noexcept_expr : cxtype -> cxcursor = "clang_ext_FunctionProtoType_getNoexceptExpr_wrapper" external ext_asm_stmt_get_asm_string : cxcursor -> string = "clang_ext_AsmStmt_GetAsmString_wrapper" external ext_asm_stmt_get_num_outputs : cxcursor -> int = "clang_ext_AsmStmt_getNumOutputs_wrapper" external ext_asm_stmt_get_output_constraint : cxcursor -> int -> string = "clang_ext_AsmStmt_getOutputConstraint_wrapper" external ext_asm_stmt_get_output_expr : cxcursor -> int -> cxcursor = "clang_ext_AsmStmt_getOutputExpr_wrapper" external ext_asm_stmt_get_num_inputs : cxcursor -> int = "clang_ext_AsmStmt_getNumInputs_wrapper" external ext_asm_stmt_get_input_constraint : cxcursor -> int -> string = "clang_ext_AsmStmt_getInputConstraint_wrapper" external ext_asm_stmt_get_input_expr : cxcursor -> int -> cxcursor = "clang_ext_AsmStmt_getInputExpr_wrapper" external ext_declarator_decl_get_type_loc : cxcursor -> clang_ext_typeloc = "clang_ext_DeclaratorDecl_getTypeLoc_wrapper" type clang_ext_typeloc_class = | Qualified | Builtin | Complex | Pointer | BlockPointer | LValueReference | RValueReference | MemberPointer | ConstantArray | IncompleteArray | VariableArray | DependentSizedArray | DependentSizedExtVector | DependentAddressSpace | Vector | DependentVector | ExtVector | FunctionProto | FunctionNoProto | UnresolvedUsing | Paren | Typedef | Adjusted | Decayed | TypeOfExpr | TypeOf | Decltype | UnaryTransform | Record | Enum | Elaborated | Attributed | TemplateTypeParm | SubstTemplateTypeParm | SubstTemplateTypeParmPack | TemplateSpecialization | Auto | DeducedTemplateSpecialization | InjectedClassName | DependentName | DependentTemplateSpecialization | PackExpansion | ObjCTypeParam | ObjCObject | ObjCInterface | ObjCObjectPointer | Pipe | Atomic | InvalidTypeLoc [@@deriving refl] external ext_type_loc_get_class : clang_ext_typeloc -> clang_ext_typeloc_class = "clang_ext_TypeLoc_getClass_wrapper" external ext_type_loc_get_type : clang_ext_typeloc -> cxtype = "clang_ext_TypeLoc_getType_wrapper" external ext_array_type_loc_get_size_expr : clang_ext_typeloc -> cxcursor = "clang_ext_ArrayTypeLoc_getSizeExpr_wrapper" external ext_array_type_loc_get_element_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_ArrayTypeLoc_getElementLoc_wrapper" external ext_paren_type_loc_get_inner_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_ParenTypeLoc_getInnerLoc_wrapper" external ext_pointer_like_type_loc_get_pointee_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_PointerLikeTypeLoc_getPointeeLoc_wrapper" external ext_member_pointer_type_loc_get_class_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_MemberPointerTypeLoc_getClassLoc_wrapper" external ext_qualified_type_loc_get_unqualified_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_QualifiedTypeLoc_getUnqualifiedLoc_wrapper" external ext_function_type_loc_get_return_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_FunctionTypeLoc_getReturnLoc_wrapper" external ext_function_type_loc_get_num_params : clang_ext_typeloc -> int = "clang_ext_FunctionTypeLoc_getNumParams_wrapper" external ext_function_type_loc_get_param : clang_ext_typeloc -> int -> cxcursor = "clang_ext_FunctionTypeLoc_getParam_wrapper" external ext_init_list_expr_get_syntactic_form : cxcursor -> cxcursor = "clang_ext_InitListExpr_getSyntacticForm_wrapper" external ext_init_list_expr_get_semantic_form : cxcursor -> cxcursor = "clang_ext_InitListExpr_getSemanticForm_wrapper" external ext_init_list_expr_get_num_inits : cxcursor -> int = "clang_ext_InitListExpr_getNumInits_wrapper" external ext_init_list_expr_get_init : cxcursor -> int -> cxcursor = "clang_ext_InitListExpr_getInit_wrapper" external ext_designated_init_expr_size : cxcursor -> int = "clang_ext_DesignatedInitExpr_size_wrapper" type clang_ext_designatedinitexpr_designatorkind = | FieldDesignator | ArrayDesignator | ArrayRangeDesignator [@@deriving refl] external ext_designated_init_expr_get_kind : cxcursor -> int -> clang_ext_designatedinitexpr_designatorkind = "clang_ext_DesignatedInitExpr_getKind_wrapper" external ext_designated_init_expr_get_field : cxcursor -> int -> cxcursor = "clang_ext_DesignatedInitExpr_getField_wrapper" external ext_designated_init_expr_get_array_index : cxcursor -> int -> cxcursor = "clang_ext_DesignatedInitExpr_getArrayIndex_wrapper" external ext_designated_init_expr_get_array_range_start : cxcursor -> int -> cxcursor = "clang_ext_DesignatedInitExpr_getArrayRangeStart_wrapper" external ext_designated_init_expr_get_array_range_end : cxcursor -> int -> cxcursor = "clang_ext_DesignatedInitExpr_getArrayRangeEnd_wrapper" external ext_designated_init_expr_get_init : cxcursor -> cxcursor = "clang_ext_DesignatedInitExpr_getInit_wrapper" external ext_concept_decl_get_constraint_expr : cxcursor -> cxcursor = "clang_ext_ConceptDecl_getConstraintExpr_wrapper" type clang_ext_requirementkind = | Type | Simple | Compound | Nested [@@deriving refl] type clang_ext_requirement external ext_requirement_get_kind : clang_ext_requirement -> clang_ext_requirementkind = "clang_ext_Requirement_getKind_wrapper" external ext_type_requirement_get_type : clang_ext_requirement -> clang_ext_typeloc = "clang_ext_TypeRequirement_getType_wrapper" external ext_expr_requirement_get_expr : clang_ext_requirement -> cxcursor = "clang_ext_ExprRequirement_getExpr_wrapper" external ext_expr_requirement_return_type_get_type_constraint_template_parameter_list : clang_ext_requirement -> clang_ext_templateparameterlist = "clang_ext_ExprRequirement_ReturnType_getTypeConstraintTemplateParameterList_wrapper" external ext_expr_requirement_return_type_get_type_constraint : clang_ext_requirement -> cxcursor = "clang_ext_ExprRequirement_ReturnType_getTypeConstraint_wrapper" external ext_nested_requirement_get_constraint_expr : clang_ext_requirement -> cxcursor = "clang_ext_NestedRequirement_getConstraintExpr_wrapper" external ext_requires_expr_get_local_parameter_count : cxcursor -> int = "clang_ext_RequiresExpr_getLocalParameterCount_wrapper" external ext_requires_expr_get_local_parameter : cxcursor -> int -> cxcursor = "clang_ext_RequiresExpr_getLocalParameter_wrapper" external ext_requires_expr_get_requirement_count : cxcursor -> int = "clang_ext_RequiresExpr_getRequirementCount_wrapper" external ext_requires_expr_get_requirement : cxcursor -> int -> clang_ext_requirement = "clang_ext_RequiresExpr_getRequirement_wrapper" external ext_decl_context_visit_decls : cxcursor -> (cxcursor -> cxcursor -> cxchildvisitresult) -> bool = "clang_ext_DeclContext_visitDecls_wrapper" external ext_indirect_field_decl_visit_chain : cxcursor -> (cxcursor -> cxcursor -> cxchildvisitresult) -> bool = "clang_ext_IndirectFieldDecl_visitChain_wrapper" external ext_tag_decl_get_tag_kind : cxcursor -> clang_ext_elaboratedtypekeyword = "clang_ext_TagDecl_getTagKind_wrapper" external ext_decl_has_attrs : cxcursor -> bool = "clang_ext_Decl_hasAttrs_wrapper" external ext_decl_get_attr_count : cxcursor -> int = "clang_ext_Decl_getAttrCount_wrapper" external ext_decl_get_attr : cxcursor -> int -> cxcursor = "clang_ext_Decl_getAttr_wrapper" external ext_cursor_kind_is_attr : cxcursorkind -> bool = "clang_ext_CursorKind_isAttr_wrapper" external ext_function_decl_is_inline_specified : cxcursor -> bool = "clang_ext_FunctionDecl_isInlineSpecified_wrapper" external ext_function_decl_is_inlined : cxcursor -> bool = "clang_ext_FunctionDecl_isInlined_wrapper" external ext_cursor_get_type_loc : cxcursor -> clang_ext_typeloc = "clang_ext_Cursor_getTypeLoc_wrapper" external ext_cxxfor_range_stmt_get_loop_variable : cxcursor -> cxcursor = "clang_ext_CXXForRangeStmt_getLoopVariable_wrapper" external ext_cxxfor_range_stmt_get_range_init : cxcursor -> cxcursor = "clang_ext_CXXForRangeStmt_getRangeInit_wrapper" external ext_cxxfor_range_stmt_get_body : cxcursor -> cxcursor = "clang_ext_CXXForRangeStmt_getBody_wrapper" external ext_attributed_type_loc_get_modified_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_AttributedTypeLoc_getModifiedLoc_wrapper" external ext_attributed_type_loc_get_attr : clang_ext_typeloc -> cxcursor = "clang_ext_AttributedTypeLoc_getAttr_wrapper" external ext_attributed_type_get_modified_type : cxtype -> cxtype = "clang_ext_AttributedType_getModifiedType_wrapper" external ext_attributed_type_get_attr_kind : cxtype -> clang_ext_attrkind = "clang_ext_AttributedType_getAttrKind_wrapper" external ext_elaborated_type_loc_get_named_type_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_ElaboratedTypeLoc_getNamedTypeLoc_wrapper" external ext_pack_expansion_type_loc_get_pattern_loc : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_PackExpansionTypeLoc_getPatternLoc_wrapper" external ext_typedef_decl_get_underlying_type_loc : cxcursor -> clang_ext_typeloc = "clang_ext_TypedefDecl_getUnderlyingTypeLoc_wrapper" external ext_cxxmethod_decl_get_parent : cxcursor -> cxcursor = "clang_ext_CXXMethodDecl_getParent_wrapper" external ext_injected_class_name_type_get_injected_specialization_type : cxtype -> cxtype = "clang_ext_InjectedClassNameType_getInjectedSpecializationType_wrapper" external ext_type_get_unqualified_type : cxtype -> cxtype = "clang_ext_Type_getUnqualifiedType_wrapper" external ext_type_is_sugared : cxtype -> bool = "clang_ext_Type_isSugared_wrapper" external ext_type_desugar : cxtype -> cxtype = "clang_ext_Type_desugar_wrapper" type clang_ext_cxxctorinitializer external ext_cxxconstructor_decl_visit_initializers : cxcursor -> (clang_ext_cxxctorinitializer -> cxvisitorresult) -> bool = "clang_ext_CXXConstructorDecl_visitInitializers_wrapper" external ext_cxxctor_initializer_is_base_initializer : clang_ext_cxxctorinitializer -> bool = "clang_ext_CXXCtorInitializer_isBaseInitializer_wrapper" external ext_cxxctor_initializer_is_pack_expansion : clang_ext_cxxctorinitializer -> bool = "clang_ext_CXXCtorInitializer_isPackExpansion_wrapper" external ext_cxxctor_initializer_is_member_initializer : clang_ext_cxxctorinitializer -> bool = "clang_ext_CXXCtorInitializer_isMemberInitializer_wrapper" external ext_cxxctor_initializer_is_indirect_member_initializer : clang_ext_cxxctorinitializer -> bool = "clang_ext_CXXCtorInitializer_isIndirectMemberInitializer_wrapper" external ext_cxxctor_initializer_is_delegating_initializer : clang_ext_cxxctorinitializer -> bool = "clang_ext_CXXCtorInitializer_isDelegatingInitializer_wrapper" external ext_cxxctor_initializer_get_type_source_info : clang_ext_cxxctorinitializer -> clang_ext_typeloc = "clang_ext_CXXCtorInitializer_getTypeSourceInfo_wrapper" external ext_cxxctor_initializer_get_member : clang_ext_cxxctorinitializer -> cxcursor = "clang_ext_CXXCtorInitializer_getMember_wrapper" external ext_cxxctor_initializer_get_any_member : clang_ext_cxxctorinitializer -> cxcursor = "clang_ext_CXXCtorInitializer_getAnyMember_wrapper" external ext_cxxctor_initializer_get_init : clang_ext_cxxctorinitializer -> cxcursor = "clang_ext_CXXCtorInitializer_getInit_wrapper" external ext_function_decl_get_num_template_parameter_lists : cxcursor -> int = "clang_ext_FunctionDecl_getNumTemplateParameterLists_wrapper" external ext_function_decl_get_template_parameter_list : cxcursor -> int -> clang_ext_templateparameterlist = "clang_ext_FunctionDecl_getTemplateParameterList_wrapper" external ext_atomic_type_get_value_type : cxtype -> cxtype = "clang_ext_AtomicType_getValueType_wrapper" type clang_expr_atomicop = | Invalid | C11_atomic_init | C11_atomic_load | C11_atomic_store | C11_atomic_exchange | C11_atomic_compare_exchange_strong | C11_atomic_compare_exchange_weak | C11_atomic_fetch_add | C11_atomic_fetch_sub | C11_atomic_fetch_and | C11_atomic_fetch_or | C11_atomic_fetch_xor | Atomic_load | Atomic_load_n | Atomic_store | Atomic_store_n | Atomic_exchange | Atomic_exchange_n | Atomic_compare_exchange | Atomic_compare_exchange_n | Atomic_fetch_add | Atomic_fetch_sub | Atomic_fetch_and | Atomic_fetch_or | Atomic_fetch_xor | Atomic_fetch_nand | Atomic_add_fetch | Atomic_sub_fetch | Atomic_and_fetch | Atomic_or_fetch | Atomic_xor_fetch | Atomic_nand_fetch | Opencl_atomic_init | Opencl_atomic_load | Opencl_atomic_store | Opencl_atomic_exchange | Opencl_atomic_compare_exchange_strong | Opencl_atomic_compare_exchange_weak | Opencl_atomic_fetch_add | Opencl_atomic_fetch_sub | Opencl_atomic_fetch_and | Opencl_atomic_fetch_or | Opencl_atomic_fetch_xor | Opencl_atomic_fetch_min | Opencl_atomic_fetch_max | Atomic_fetch_min | Atomic_fetch_max [@@deriving refl] external ext_atomic_expr_get_op : cxcursor -> clang_expr_atomicop = "clang_ext_AtomicExpr_getOp_wrapper" external ext_type_of_expr_type_get_underlying_expr : cxtype -> cxcursor = "clang_ext_TypeOfExprType_getUnderlyingExpr_wrapper" external ext_type_of_type_get_underlying_type : cxtype -> cxtype = "clang_ext_TypeOfType_getUnderlyingType_wrapper" external ext_type_of_type_loc_get_underlying_type : clang_ext_typeloc -> clang_ext_typeloc = "clang_ext_TypeOfTypeLoc_getUnderlyingType_wrapper" type clang_ext_storageclass = | None | Extern | Static | PrivateExtern | OpenCLWorkGroupLocal | Auto | Register [@@deriving refl] external ext_decl_get_storage_class : cxcursor -> clang_ext_storageclass = "clang_ext_Decl_getStorageClass_wrapper" type clang_ext_aarch64svepcs_spelling = | GNU_aarch64_sve_pcs | CXX11_clang_aarch64_sve_pcs | C2x_clang_aarch64_sve_pcs | SpellingNotCalculated [@@deriving refl] external ext_aarch64_svepcs_get_spelling : cxcursor -> clang_ext_aarch64svepcs_spelling = "clang_ext_AArch64SVEPcs_getSpelling_wrapper" type clang_ext_aarch64vectorpcs_spelling = | GNU_aarch64_vector_pcs | CXX11_clang_aarch64_vector_pcs | C2x_clang_aarch64_vector_pcs | SpellingNotCalculated [@@deriving refl] external ext_aarch64_vector_pcs_get_spelling : cxcursor -> clang_ext_aarch64vectorpcs_spelling = "clang_ext_AArch64VectorPcs_getSpelling_wrapper" type clang_ext_amdgpuflatworkgroupsize_spelling = | GNU_amdgpu_flat_work_group_size | CXX11_clang_amdgpu_flat_work_group_size | SpellingNotCalculated [@@deriving refl] external ext_amdgpuflat_work_group_size_get_spelling : cxcursor -> clang_ext_amdgpuflatworkgroupsize_spelling = "clang_ext_AMDGPUFlatWorkGroupSize_getSpelling_wrapper" type clang_ext_amdgpukernelcall_spelling = | GNU_amdgpu_kernel | CXX11_clang_amdgpu_kernel | C2x_clang_amdgpu_kernel | SpellingNotCalculated [@@deriving refl] external ext_amdgpukernel_call_get_spelling : cxcursor -> clang_ext_amdgpukernelcall_spelling = "clang_ext_AMDGPUKernelCall_getSpelling_wrapper" type clang_ext_amdgpunumsgpr_spelling = | GNU_amdgpu_num_sgpr | CXX11_clang_amdgpu_num_sgpr | SpellingNotCalculated [@@deriving refl] external ext_amdgpunum_sgpr_get_spelling : cxcursor -> clang_ext_amdgpunumsgpr_spelling = "clang_ext_AMDGPUNumSGPR_getSpelling_wrapper" type clang_ext_amdgpunumvgpr_spelling = | GNU_amdgpu_num_vgpr | CXX11_clang_amdgpu_num_vgpr | SpellingNotCalculated [@@deriving refl] external ext_amdgpunum_vgpr_get_spelling : cxcursor -> clang_ext_amdgpunumvgpr_spelling = "clang_ext_AMDGPUNumVGPR_getSpelling_wrapper" type clang_ext_amdgpuwavespereu_spelling = | GNU_amdgpu_waves_per_eu | CXX11_clang_amdgpu_waves_per_eu | SpellingNotCalculated [@@deriving refl] external ext_amdgpuwaves_per_eu_get_spelling : cxcursor -> clang_ext_amdgpuwavespereu_spelling = "clang_ext_AMDGPUWavesPerEU_getSpelling_wrapper" type clang_ext_arminterrupt_spelling = | GNU_interrupt | CXX11_gnu_interrupt | C2x_gnu_interrupt | SpellingNotCalculated [@@deriving refl] external ext_arminterrupt_get_spelling : cxcursor -> clang_ext_arminterrupt_spelling = "clang_ext_ARMInterrupt_getSpelling_wrapper" type clang_ext_avrinterrupt_spelling = | GNU_interrupt | CXX11_gnu_interrupt | C2x_gnu_interrupt | SpellingNotCalculated [@@deriving refl] external ext_avrinterrupt_get_spelling : cxcursor -> clang_ext_avrinterrupt_spelling = "clang_ext_AVRInterrupt_getSpelling_wrapper" type clang_ext_avrsignal_spelling = | GNU_signal | CXX11_gnu_signal | C2x_gnu_signal | SpellingNotCalculated [@@deriving refl] external ext_avrsignal_get_spelling : cxcursor -> clang_ext_avrsignal_spelling = "clang_ext_AVRSignal_getSpelling_wrapper" type clang_ext_abitag_spelling = | GNU_abi_tag | CXX11_gnu_abi_tag | SpellingNotCalculated [@@deriving refl] external ext_abi_tag_get_spelling : cxcursor -> clang_ext_abitag_spelling = "clang_ext_AbiTag_getSpelling_wrapper" type clang_ext_acquirecapability_spelling = | GNU_acquire_capability | CXX11_clang_acquire_capability | GNU_acquire_shared_capability | CXX11_clang_acquire_shared_capability | GNU_exclusive_lock_function | GNU_shared_lock_function | SpellingNotCalculated [@@deriving refl] external ext_acquire_capability_get_spelling : cxcursor -> clang_ext_acquirecapability_spelling = "clang_ext_AcquireCapability_getSpelling_wrapper" type clang_ext_acquirehandle_spelling = | GNU_acquire_handle | CXX11_clang_acquire_handle | C2x_clang_acquire_handle | SpellingNotCalculated [@@deriving refl] external ext_acquire_handle_get_spelling : cxcursor -> clang_ext_acquirehandle_spelling = "clang_ext_AcquireHandle_getSpelling_wrapper" type clang_ext_addressspace_spelling = | GNU_address_space | CXX11_clang_address_space | C2x_clang_address_space | SpellingNotCalculated [@@deriving refl] external ext_address_space_get_spelling : cxcursor -> clang_ext_addressspace_spelling = "clang_ext_AddressSpace_getSpelling_wrapper" type clang_ext_alias_spelling = | GNU_alias | CXX11_gnu_alias | C2x_gnu_alias | SpellingNotCalculated [@@deriving refl] external ext_alias_get_spelling : cxcursor -> clang_ext_alias_spelling = "clang_ext_Alias_getSpelling_wrapper" type clang_ext_aligned_spelling = | GNU_aligned | CXX11_gnu_aligned | C2x_gnu_aligned | Declspec_align | Keyword_alignas | Keyword_Alignas | SpellingNotCalculated [@@deriving refl] external ext_aligned_get_spelling : cxcursor -> clang_ext_aligned_spelling = "clang_ext_Aligned_getSpelling_wrapper" type clang_ext_allocalign_spelling = | GNU_alloc_align | CXX11_gnu_alloc_align | C2x_gnu_alloc_align | SpellingNotCalculated [@@deriving refl] external ext_alloc_align_get_spelling : cxcursor -> clang_ext_allocalign_spelling = "clang_ext_AllocAlign_getSpelling_wrapper" type clang_ext_allocsize_spelling = | GNU_alloc_size | CXX11_gnu_alloc_size | C2x_gnu_alloc_size | SpellingNotCalculated [@@deriving refl] external ext_alloc_size_get_spelling : cxcursor -> clang_ext_allocsize_spelling = "clang_ext_AllocSize_getSpelling_wrapper" type clang_ext_alwaysdestroy_spelling = | GNU_always_destroy | CXX11_clang_always_destroy | SpellingNotCalculated [@@deriving refl] external ext_always_destroy_get_spelling : cxcursor -> clang_ext_alwaysdestroy_spelling = "clang_ext_AlwaysDestroy_getSpelling_wrapper" type clang_ext_alwaysinline_spelling = | GNU_always_inline | CXX11_gnu_always_inline | C2x_gnu_always_inline | CXX11_clang_always_inline | C2x_clang_always_inline | Keyword_forceinline | SpellingNotCalculated [@@deriving refl] external ext_always_inline_get_spelling : cxcursor -> clang_ext_alwaysinline_spelling = "clang_ext_AlwaysInline_getSpelling_wrapper" type clang_ext_annotate_spelling = | GNU_annotate | CXX11_clang_annotate | C2x_clang_annotate | SpellingNotCalculated [@@deriving refl] external ext_annotate_get_spelling : cxcursor -> clang_ext_annotate_spelling = "clang_ext_Annotate_getSpelling_wrapper" type clang_ext_annotatetype_spelling = | CXX11_clang_annotate_type | C2x_clang_annotate_type | SpellingNotCalculated [@@deriving refl] external ext_annotate_type_get_spelling : cxcursor -> clang_ext_annotatetype_spelling = "clang_ext_AnnotateType_getSpelling_wrapper" type clang_ext_anyx86interrupt_spelling = | GNU_interrupt | CXX11_gnu_interrupt | C2x_gnu_interrupt | SpellingNotCalculated [@@deriving refl] external ext_any_x86_interrupt_get_spelling : cxcursor -> clang_ext_anyx86interrupt_spelling = "clang_ext_AnyX86Interrupt_getSpelling_wrapper" type clang_ext_anyx86nocallersavedregisters_spelling = | GNU_no_caller_saved_registers | CXX11_gnu_no_caller_saved_registers | C2x_gnu_no_caller_saved_registers | SpellingNotCalculated [@@deriving refl] external ext_any_x86_no_caller_saved_registers_get_spelling : cxcursor -> clang_ext_anyx86nocallersavedregisters_spelling = "clang_ext_AnyX86NoCallerSavedRegisters_getSpelling_wrapper" type clang_ext_anyx86nocfcheck_spelling = | GNU_nocf_check | CXX11_gnu_nocf_check | C2x_gnu_nocf_check | SpellingNotCalculated [@@deriving refl] external ext_any_x86_no_cf_check_get_spelling : cxcursor -> clang_ext_anyx86nocfcheck_spelling = "clang_ext_AnyX86NoCfCheck_getSpelling_wrapper" type clang_ext_arcweakrefunavailable_spelling = | GNU_objc_arc_weak_reference_unavailable | CXX11_clang_objc_arc_weak_reference_unavailable | C2x_clang_objc_arc_weak_reference_unavailable | SpellingNotCalculated [@@deriving refl] external ext_arc_weakref_unavailable_get_spelling : cxcursor -> clang_ext_arcweakrefunavailable_spelling = "clang_ext_ArcWeakrefUnavailable_getSpelling_wrapper" type clang_ext_argumentwithtypetag_spelling = | GNU_argument_with_type_tag | CXX11_clang_argument_with_type_tag | C2x_clang_argument_with_type_tag | GNU_pointer_with_type_tag | CXX11_clang_pointer_with_type_tag | C2x_clang_pointer_with_type_tag | SpellingNotCalculated [@@deriving refl] external ext_argument_with_type_tag_get_spelling : cxcursor -> clang_ext_argumentwithtypetag_spelling = "clang_ext_ArgumentWithTypeTag_getSpelling_wrapper" type clang_ext_armbuiltinalias_spelling = | GNU_clang_arm_builtin_alias | CXX11_clang_clang_arm_builtin_alias | C2x_clang_clang_arm_builtin_alias | SpellingNotCalculated [@@deriving refl] external ext_arm_builtin_alias_get_spelling : cxcursor -> clang_ext_armbuiltinalias_spelling = "clang_ext_ArmBuiltinAlias_getSpelling_wrapper" type clang_ext_armmvestrictpolymorphism_spelling = | GNU_clang_arm_mve_strict_polymorphism | CXX11_clang_clang_arm_mve_strict_polymorphism | C2x_clang_clang_arm_mve_strict_polymorphism | SpellingNotCalculated [@@deriving refl] external ext_arm_mve_strict_polymorphism_get_spelling : cxcursor -> clang_ext_armmvestrictpolymorphism_spelling = "clang_ext_ArmMveStrictPolymorphism_getSpelling_wrapper" type clang_ext_artificial_spelling = | GNU_artificial | CXX11_gnu_artificial | C2x_gnu_artificial | SpellingNotCalculated [@@deriving refl] external ext_artificial_get_spelling : cxcursor -> clang_ext_artificial_spelling = "clang_ext_Artificial_getSpelling_wrapper" type clang_ext_asmlabel_spelling = | Keyword_asm | SpellingNotCalculated [@@deriving refl] external ext_asm_label_get_spelling : cxcursor -> clang_ext_asmlabel_spelling = "clang_ext_AsmLabel_getSpelling_wrapper" type clang_ext_assertcapability_spelling = | GNU_assert_capability | CXX11_clang_assert_capability | GNU_assert_shared_capability | CXX11_clang_assert_shared_capability | SpellingNotCalculated [@@deriving refl] external ext_assert_capability_get_spelling : cxcursor -> clang_ext_assertcapability_spelling = "clang_ext_AssertCapability_getSpelling_wrapper" type clang_ext_assumealigned_spelling = | GNU_assume_aligned | CXX11_gnu_assume_aligned | C2x_gnu_assume_aligned | SpellingNotCalculated [@@deriving refl] external ext_assume_aligned_get_spelling : cxcursor -> clang_ext_assumealigned_spelling = "clang_ext_AssumeAligned_getSpelling_wrapper" type clang_ext_assumption_spelling = | GNU_assume | CXX11_clang_assume | C2x_clang_assume | SpellingNotCalculated [@@deriving refl] external ext_assumption_get_spelling : cxcursor -> clang_ext_assumption_spelling = "clang_ext_Assumption_getSpelling_wrapper" type clang_ext_availability_spelling = | GNU_availability | CXX11_clang_availability | C2x_clang_availability | SpellingNotCalculated [@@deriving refl] external ext_availability_get_spelling : cxcursor -> clang_ext_availability_spelling = "clang_ext_Availability_getSpelling_wrapper" type clang_ext_bpfpreserveaccessindex_spelling = | GNU_preserve_access_index | CXX11_clang_preserve_access_index | C2x_clang_preserve_access_index | SpellingNotCalculated [@@deriving refl] external ext_bpfpreserve_access_index_get_spelling : cxcursor -> clang_ext_bpfpreserveaccessindex_spelling = "clang_ext_BPFPreserveAccessIndex_getSpelling_wrapper" type clang_ext_btfdecltag_spelling = | GNU_btf_decl_tag | CXX11_clang_btf_decl_tag | C2x_clang_btf_decl_tag | SpellingNotCalculated [@@deriving refl] external ext_btfdecl_tag_get_spelling : cxcursor -> clang_ext_btfdecltag_spelling = "clang_ext_BTFDeclTag_getSpelling_wrapper" type clang_ext_btftypetag_spelling = | GNU_btf_type_tag | CXX11_clang_btf_type_tag | C2x_clang_btf_type_tag | SpellingNotCalculated [@@deriving refl] external ext_btftype_tag_get_spelling : cxcursor -> clang_ext_btftypetag_spelling = "clang_ext_BTFTypeTag_getSpelling_wrapper" type clang_ext_blocks_spelling = | GNU_blocks | CXX11_clang_blocks | C2x_clang_blocks | SpellingNotCalculated [@@deriving refl] external ext_blocks_get_spelling : cxcursor -> clang_ext_blocks_spelling = "clang_ext_Blocks_getSpelling_wrapper" type clang_ext_builtinalias_spelling = | CXX11_clang_builtin_alias | C2x_clang_builtin_alias | GNU_clang_builtin_alias | SpellingNotCalculated [@@deriving refl] external ext_builtin_alias_get_spelling : cxcursor -> clang_ext_builtinalias_spelling = "clang_ext_BuiltinAlias_getSpelling_wrapper" type clang_ext_cdecl_spelling = | GNU_cdecl | CXX11_gnu_cdecl | C2x_gnu_cdecl | Keyword_cdecl | SpellingNotCalculated [@@deriving refl] external ext_cdecl_get_spelling : cxcursor -> clang_ext_cdecl_spelling = "clang_ext_CDecl_getSpelling_wrapper" type clang_ext_cfauditedtransfer_spelling = | GNU_cf_audited_transfer | CXX11_clang_cf_audited_transfer | C2x_clang_cf_audited_transfer | SpellingNotCalculated [@@deriving refl] external ext_cfaudited_transfer_get_spelling : cxcursor -> clang_ext_cfauditedtransfer_spelling = "clang_ext_CFAuditedTransfer_getSpelling_wrapper" type clang_ext_cfconsumed_spelling = | GNU_cf_consumed | CXX11_clang_cf_consumed | C2x_clang_cf_consumed | SpellingNotCalculated [@@deriving refl] external ext_cfconsumed_get_spelling : cxcursor -> clang_ext_cfconsumed_spelling = "clang_ext_CFConsumed_getSpelling_wrapper" type clang_ext_cficanonicaljumptable_spelling = | GNU_cfi_canonical_jump_table | CXX11_clang_cfi_canonical_jump_table | C2x_clang_cfi_canonical_jump_table | SpellingNotCalculated [@@deriving refl] external ext_cficanonical_jump_table_get_spelling : cxcursor -> clang_ext_cficanonicaljumptable_spelling = "clang_ext_CFICanonicalJumpTable_getSpelling_wrapper" type clang_ext_cfreturnsnotretained_spelling = | GNU_cf_returns_not_retained | CXX11_clang_cf_returns_not_retained | C2x_clang_cf_returns_not_retained | SpellingNotCalculated [@@deriving refl] external ext_cfreturns_not_retained_get_spelling : cxcursor -> clang_ext_cfreturnsnotretained_spelling = "clang_ext_CFReturnsNotRetained_getSpelling_wrapper" type clang_ext_cfreturnsretained_spelling = | GNU_cf_returns_retained | CXX11_clang_cf_returns_retained | C2x_clang_cf_returns_retained | SpellingNotCalculated [@@deriving refl] external ext_cfreturns_retained_get_spelling : cxcursor -> clang_ext_cfreturnsretained_spelling = "clang_ext_CFReturnsRetained_getSpelling_wrapper" type clang_ext_cfunknowntransfer_spelling = | GNU_cf_unknown_transfer | CXX11_clang_cf_unknown_transfer | C2x_clang_cf_unknown_transfer | SpellingNotCalculated [@@deriving refl] external ext_cfunknown_transfer_get_spelling : cxcursor -> clang_ext_cfunknowntransfer_spelling = "clang_ext_CFUnknownTransfer_getSpelling_wrapper" type clang_ext_cpudispatch_spelling = | GNU_cpu_dispatch | CXX11_clang_cpu_dispatch | C2x_clang_cpu_dispatch | Declspec_cpu_dispatch | SpellingNotCalculated [@@deriving refl] external ext_cpudispatch_get_spelling : cxcursor -> clang_ext_cpudispatch_spelling = "clang_ext_CPUDispatch_getSpelling_wrapper" type clang_ext_cpuspecific_spelling = | GNU_cpu_specific | CXX11_clang_cpu_specific | C2x_clang_cpu_specific | Declspec_cpu_specific | SpellingNotCalculated [@@deriving refl] external ext_cpuspecific_get_spelling : cxcursor -> clang_ext_cpuspecific_spelling = "clang_ext_CPUSpecific_getSpelling_wrapper" type clang_ext_cudaconstant_spelling = | GNU_constant | Declspec_constant | SpellingNotCalculated [@@deriving refl] external ext_cudaconstant_get_spelling : cxcursor -> clang_ext_cudaconstant_spelling = "clang_ext_CUDAConstant_getSpelling_wrapper" type clang_ext_cudadevice_spelling = | GNU_device | Declspec_device | SpellingNotCalculated [@@deriving refl] external ext_cudadevice_get_spelling : cxcursor -> clang_ext_cudadevice_spelling = "clang_ext_CUDADevice_getSpelling_wrapper" type clang_ext_cudadevicebuiltinsurfacetype_spelling = | GNU_device_builtin_surface_type | Declspec_device_builtin_surface_type | SpellingNotCalculated [@@deriving refl] external ext_cudadevice_builtin_surface_type_get_spelling : cxcursor -> clang_ext_cudadevicebuiltinsurfacetype_spelling = "clang_ext_CUDADeviceBuiltinSurfaceType_getSpelling_wrapper" type clang_ext_cudadevicebuiltintexturetype_spelling = | GNU_device_builtin_texture_type | Declspec_device_builtin_texture_type | SpellingNotCalculated [@@deriving refl] external ext_cudadevice_builtin_texture_type_get_spelling : cxcursor -> clang_ext_cudadevicebuiltintexturetype_spelling = "clang_ext_CUDADeviceBuiltinTextureType_getSpelling_wrapper" type clang_ext_cudaglobal_spelling = | GNU_global | Declspec_global | SpellingNotCalculated [@@deriving refl] external ext_cudaglobal_get_spelling : cxcursor -> clang_ext_cudaglobal_spelling = "clang_ext_CUDAGlobal_getSpelling_wrapper" type clang_ext_cudahost_spelling = | GNU_host | Declspec_host | SpellingNotCalculated [@@deriving refl] external ext_cudahost_get_spelling : cxcursor -> clang_ext_cudahost_spelling = "clang_ext_CUDAHost_getSpelling_wrapper" type clang_ext_cudalaunchbounds_spelling = | GNU_launch_bounds | Declspec_launch_bounds | SpellingNotCalculated [@@deriving refl] external ext_cudalaunch_bounds_get_spelling : cxcursor -> clang_ext_cudalaunchbounds_spelling = "clang_ext_CUDALaunchBounds_getSpelling_wrapper" type clang_ext_cudashared_spelling = | GNU_shared | Declspec_shared | SpellingNotCalculated [@@deriving refl] external ext_cudashared_get_spelling : cxcursor -> clang_ext_cudashared_spelling = "clang_ext_CUDAShared_getSpelling_wrapper" type clang_ext_cxx11noreturn_spelling = | CXX11_noreturn | C2x_noreturn | C2x_Noreturn | SpellingNotCalculated [@@deriving refl] external ext_cxx11_no_return_get_spelling : cxcursor -> clang_ext_cxx11noreturn_spelling = "clang_ext_CXX11NoReturn_getSpelling_wrapper" type clang_ext_callablewhen_spelling = | GNU_callable_when | CXX11_clang_callable_when | SpellingNotCalculated [@@deriving refl] external ext_callable_when_get_spelling : cxcursor -> clang_ext_callablewhen_spelling = "clang_ext_CallableWhen_getSpelling_wrapper" type clang_ext_callback_spelling = | GNU_callback | CXX11_clang_callback | C2x_clang_callback | SpellingNotCalculated [@@deriving refl] external ext_callback_get_spelling : cxcursor -> clang_ext_callback_spelling = "clang_ext_Callback_getSpelling_wrapper" type clang_ext_calledonce_spelling = | GNU_called_once | CXX11_clang_called_once | C2x_clang_called_once | SpellingNotCalculated [@@deriving refl] external ext_called_once_get_spelling : cxcursor -> clang_ext_calledonce_spelling = "clang_ext_CalledOnce_getSpelling_wrapper" type clang_ext_capability_spelling = | GNU_capability | CXX11_clang_capability | GNU_shared_capability | CXX11_clang_shared_capability | SpellingNotCalculated [@@deriving refl] external ext_capability_get_spelling : cxcursor -> clang_ext_capability_spelling = "clang_ext_Capability_getSpelling_wrapper" type clang_ext_carriesdependency_spelling = | GNU_carries_dependency | CXX11_carries_dependency | SpellingNotCalculated [@@deriving refl] external ext_carries_dependency_get_spelling : cxcursor -> clang_ext_carriesdependency_spelling = "clang_ext_CarriesDependency_getSpelling_wrapper" type clang_ext_cleanup_spelling = | GNU_cleanup | CXX11_gnu_cleanup | C2x_gnu_cleanup | SpellingNotCalculated [@@deriving refl] external ext_cleanup_get_spelling : cxcursor -> clang_ext_cleanup_spelling = "clang_ext_Cleanup_getSpelling_wrapper" type clang_ext_cold_spelling = | GNU_cold | CXX11_gnu_cold | C2x_gnu_cold | SpellingNotCalculated [@@deriving refl] external ext_cold_get_spelling : cxcursor -> clang_ext_cold_spelling = "clang_ext_Cold_getSpelling_wrapper" type clang_ext_common_spelling = | GNU_common | CXX11_gnu_common | C2x_gnu_common | SpellingNotCalculated [@@deriving refl] external ext_common_get_spelling : cxcursor -> clang_ext_common_spelling = "clang_ext_Common_getSpelling_wrapper" type clang_ext_const_spelling = | GNU_const | CXX11_gnu_const | C2x_gnu_const | SpellingNotCalculated [@@deriving refl] external ext_const_get_spelling : cxcursor -> clang_ext_const_spelling = "clang_ext_Const_getSpelling_wrapper" type clang_ext_constinit_spelling = | Keyword_constinit | GNU_require_constant_initialization | CXX11_clang_require_constant_initialization | SpellingNotCalculated [@@deriving refl] external ext_const_init_get_spelling : cxcursor -> clang_ext_constinit_spelling = "clang_ext_ConstInit_getSpelling_wrapper" type clang_ext_constructor_spelling = | GNU_constructor | CXX11_gnu_constructor | C2x_gnu_constructor | SpellingNotCalculated [@@deriving refl] external ext_constructor_get_spelling : cxcursor -> clang_ext_constructor_spelling = "clang_ext_Constructor_getSpelling_wrapper" type clang_ext_consumable_spelling = | GNU_consumable | CXX11_clang_consumable | SpellingNotCalculated [@@deriving refl] external ext_consumable_get_spelling : cxcursor -> clang_ext_consumable_spelling = "clang_ext_Consumable_getSpelling_wrapper" type clang_ext_consumableautocast_spelling = | GNU_consumable_auto_cast_state | CXX11_clang_consumable_auto_cast_state | SpellingNotCalculated [@@deriving refl] external ext_consumable_auto_cast_get_spelling : cxcursor -> clang_ext_consumableautocast_spelling = "clang_ext_ConsumableAutoCast_getSpelling_wrapper" type clang_ext_consumablesetonread_spelling = | GNU_consumable_set_state_on_read | CXX11_clang_consumable_set_state_on_read | SpellingNotCalculated [@@deriving refl] external ext_consumable_set_on_read_get_spelling : cxcursor -> clang_ext_consumablesetonread_spelling = "clang_ext_ConsumableSetOnRead_getSpelling_wrapper" type clang_ext_convergent_spelling = | GNU_convergent | CXX11_clang_convergent | C2x_clang_convergent | SpellingNotCalculated [@@deriving refl] external ext_convergent_get_spelling : cxcursor -> clang_ext_convergent_spelling = "clang_ext_Convergent_getSpelling_wrapper" type clang_ext_dllexport_spelling = | Declspec_dllexport | GNU_dllexport | CXX11_gnu_dllexport | C2x_gnu_dllexport | SpellingNotCalculated [@@deriving refl] external ext_dllexport_get_spelling : cxcursor -> clang_ext_dllexport_spelling = "clang_ext_DLLExport_getSpelling_wrapper" type clang_ext_dllimport_spelling = | Declspec_dllimport | GNU_dllimport | CXX11_gnu_dllimport | C2x_gnu_dllimport | SpellingNotCalculated [@@deriving refl] external ext_dllimport_get_spelling : cxcursor -> clang_ext_dllimport_spelling = "clang_ext_DLLImport_getSpelling_wrapper" type clang_ext_deprecated_spelling = | GNU_deprecated | CXX11_gnu_deprecated | C2x_gnu_deprecated | Declspec_deprecated | CXX11_deprecated | C2x_deprecated | SpellingNotCalculated [@@deriving refl] external ext_deprecated_get_spelling : cxcursor -> clang_ext_deprecated_spelling = "clang_ext_Deprecated_getSpelling_wrapper" type clang_ext_destructor_spelling = | GNU_destructor | CXX11_gnu_destructor | C2x_gnu_destructor | SpellingNotCalculated [@@deriving refl] external ext_destructor_get_spelling : cxcursor -> clang_ext_destructor_spelling = "clang_ext_Destructor_getSpelling_wrapper" type clang_ext_diagnoseasbuiltin_spelling = | GNU_diagnose_as_builtin | CXX11_clang_diagnose_as_builtin | C2x_clang_diagnose_as_builtin | SpellingNotCalculated [@@deriving refl] external ext_diagnose_as_builtin_get_spelling : cxcursor -> clang_ext_diagnoseasbuiltin_spelling = "clang_ext_DiagnoseAsBuiltin_getSpelling_wrapper" type clang_ext_disablesanitizerinstrumentation_spelling = | GNU_disable_sanitizer_instrumentation | CXX11_clang_disable_sanitizer_instrumentation | C2x_clang_disable_sanitizer_instrumentation | SpellingNotCalculated [@@deriving refl] external ext_disable_sanitizer_instrumentation_get_spelling : cxcursor -> clang_ext_disablesanitizerinstrumentation_spelling = "clang_ext_DisableSanitizerInstrumentation_getSpelling_wrapper" type clang_ext_disabletailcalls_spelling = | GNU_disable_tail_calls | CXX11_clang_disable_tail_calls | C2x_clang_disable_tail_calls | SpellingNotCalculated [@@deriving refl] external ext_disable_tail_calls_get_spelling : cxcursor -> clang_ext_disabletailcalls_spelling = "clang_ext_DisableTailCalls_getSpelling_wrapper" type clang_ext_enforcetcb_spelling = | GNU_enforce_tcb | CXX11_clang_enforce_tcb | C2x_clang_enforce_tcb | SpellingNotCalculated [@@deriving refl] external ext_enforce_tcb_get_spelling : cxcursor -> clang_ext_enforcetcb_spelling = "clang_ext_EnforceTCB_getSpelling_wrapper" type clang_ext_enforcetcbleaf_spelling = | GNU_enforce_tcb_leaf | CXX11_clang_enforce_tcb_leaf | C2x_clang_enforce_tcb_leaf | SpellingNotCalculated [@@deriving refl] external ext_enforce_tcbleaf_get_spelling : cxcursor -> clang_ext_enforcetcbleaf_spelling = "clang_ext_EnforceTCBLeaf_getSpelling_wrapper" type clang_ext_enumextensibility_spelling = | GNU_enum_extensibility | CXX11_clang_enum_extensibility | C2x_clang_enum_extensibility | SpellingNotCalculated [@@deriving refl] external ext_enum_extensibility_get_spelling : cxcursor -> clang_ext_enumextensibility_spelling = "clang_ext_EnumExtensibility_getSpelling_wrapper" type clang_ext_error_spelling = | GNU_error | CXX11_gnu_error | C2x_gnu_error | GNU_warning | CXX11_gnu_warning | C2x_gnu_warning | SpellingNotCalculated [@@deriving refl] external ext_error_get_spelling : cxcursor -> clang_ext_error_spelling = "clang_ext_Error_getSpelling_wrapper" type clang_ext_excludefromexplicitinstantiation_spelling = | GNU_exclude_from_explicit_instantiation | CXX11_clang_exclude_from_explicit_instantiation | C2x_clang_exclude_from_explicit_instantiation | SpellingNotCalculated [@@deriving refl] external ext_exclude_from_explicit_instantiation_get_spelling : cxcursor -> clang_ext_excludefromexplicitinstantiation_spelling = "clang_ext_ExcludeFromExplicitInstantiation_getSpelling_wrapper" type clang_ext_externalsourcesymbol_spelling = | GNU_external_source_symbol | CXX11_clang_external_source_symbol | C2x_clang_external_source_symbol | SpellingNotCalculated [@@deriving refl] external ext_external_source_symbol_get_spelling : cxcursor -> clang_ext_externalsourcesymbol_spelling = "clang_ext_ExternalSourceSymbol_getSpelling_wrapper" type clang_ext_fallthrough_spelling = | CXX11_fallthrough | C2x_fallthrough | CXX11_clang_fallthrough | GNU_fallthrough | CXX11_gnu_fallthrough | C2x_gnu_fallthrough | SpellingNotCalculated [@@deriving refl] external ext_fall_through_get_spelling : cxcursor -> clang_ext_fallthrough_spelling = "clang_ext_FallThrough_getSpelling_wrapper" type clang_ext_fastcall_spelling = | GNU_fastcall | CXX11_gnu_fastcall | C2x_gnu_fastcall | Keyword_fastcall | SpellingNotCalculated [@@deriving refl] external ext_fast_call_get_spelling : cxcursor -> clang_ext_fastcall_spelling = "clang_ext_FastCall_getSpelling_wrapper" type clang_ext_final_spelling = | Keyword_final | Keyword_sealed | SpellingNotCalculated [@@deriving refl] external ext_final_get_spelling : cxcursor -> clang_ext_final_spelling = "clang_ext_Final_getSpelling_wrapper" type clang_ext_flagenum_spelling = | GNU_flag_enum | CXX11_clang_flag_enum | C2x_clang_flag_enum | SpellingNotCalculated [@@deriving refl] external ext_flag_enum_get_spelling : cxcursor -> clang_ext_flagenum_spelling = "clang_ext_FlagEnum_getSpelling_wrapper" type clang_ext_flatten_spelling = | GNU_flatten | CXX11_gnu_flatten | C2x_gnu_flatten | SpellingNotCalculated [@@deriving refl] external ext_flatten_get_spelling : cxcursor -> clang_ext_flatten_spelling = "clang_ext_Flatten_getSpelling_wrapper" type clang_ext_format_spelling = | GNU_format | CXX11_gnu_format | C2x_gnu_format | SpellingNotCalculated [@@deriving refl] external ext_format_get_spelling : cxcursor -> clang_ext_format_spelling = "clang_ext_Format_getSpelling_wrapper" type clang_ext_formatarg_spelling = | GNU_format_arg | CXX11_gnu_format_arg | C2x_gnu_format_arg | SpellingNotCalculated [@@deriving refl] external ext_format_arg_get_spelling : cxcursor -> clang_ext_formatarg_spelling = "clang_ext_FormatArg_getSpelling_wrapper" type clang_ext_functionreturnthunks_spelling = | GNU_function_return | CXX11_gnu_function_return | C2x_gnu_function_return | SpellingNotCalculated [@@deriving refl] external ext_function_return_thunks_get_spelling : cxcursor -> clang_ext_functionreturnthunks_spelling = "clang_ext_FunctionReturnThunks_getSpelling_wrapper" type clang_ext_gnuinline_spelling = | GNU_gnu_inline | CXX11_gnu_gnu_inline | C2x_gnu_gnu_inline | SpellingNotCalculated [@@deriving refl] external ext_gnuinline_get_spelling : cxcursor -> clang_ext_gnuinline_spelling = "clang_ext_GNUInline_getSpelling_wrapper" type clang_ext_guardedvar_spelling = | GNU_guarded_var | CXX11_clang_guarded_var | SpellingNotCalculated [@@deriving refl] external ext_guarded_var_get_spelling : cxcursor -> clang_ext_guardedvar_spelling = "clang_ext_GuardedVar_getSpelling_wrapper" type clang_ext_hipmanaged_spelling = | GNU_managed | Declspec_managed | SpellingNotCalculated [@@deriving refl] external ext_hipmanaged_get_spelling : cxcursor -> clang_ext_hipmanaged_spelling = "clang_ext_HIPManaged_getSpelling_wrapper" type clang_ext_hot_spelling = | GNU_hot | CXX11_gnu_hot | C2x_gnu_hot | SpellingNotCalculated [@@deriving refl] external ext_hot_get_spelling : cxcursor -> clang_ext_hot_spelling = "clang_ext_Hot_getSpelling_wrapper" type clang_ext_ibaction_spelling = | GNU_ibaction | CXX11_clang_ibaction | C2x_clang_ibaction | SpellingNotCalculated [@@deriving refl] external ext_ibaction_get_spelling : cxcursor -> clang_ext_ibaction_spelling = "clang_ext_IBAction_getSpelling_wrapper" type clang_ext_iboutlet_spelling = | GNU_iboutlet | CXX11_clang_iboutlet | C2x_clang_iboutlet | SpellingNotCalculated [@@deriving refl] external ext_iboutlet_get_spelling : cxcursor -> clang_ext_iboutlet_spelling = "clang_ext_IBOutlet_getSpelling_wrapper" type clang_ext_iboutletcollection_spelling = | GNU_iboutletcollection | CXX11_clang_iboutletcollection | C2x_clang_iboutletcollection | SpellingNotCalculated [@@deriving refl] external ext_iboutlet_collection_get_spelling : cxcursor -> clang_ext_iboutletcollection_spelling = "clang_ext_IBOutletCollection_getSpelling_wrapper" type clang_ext_ifunc_spelling = | GNU_ifunc | CXX11_gnu_ifunc | C2x_gnu_ifunc | SpellingNotCalculated [@@deriving refl] external ext_ifunc_get_spelling : cxcursor -> clang_ext_ifunc_spelling = "clang_ext_IFunc_getSpelling_wrapper" type clang_ext_initpriority_spelling = | GNU_init_priority | CXX11_gnu_init_priority | SpellingNotCalculated [@@deriving refl] external ext_init_priority_get_spelling : cxcursor -> clang_ext_initpriority_spelling = "clang_ext_InitPriority_getSpelling_wrapper" type clang_ext_inteloclbicc_spelling = | GNU_intel_ocl_bicc | CXX11_clang_intel_ocl_bicc | SpellingNotCalculated [@@deriving refl] external ext_intel_ocl_bicc_get_spelling : cxcursor -> clang_ext_inteloclbicc_spelling = "clang_ext_IntelOclBicc_getSpelling_wrapper" type clang_ext_internallinkage_spelling = | GNU_internal_linkage | CXX11_clang_internal_linkage | C2x_clang_internal_linkage | SpellingNotCalculated [@@deriving refl] external ext_internal_linkage_get_spelling : cxcursor -> clang_ext_internallinkage_spelling = "clang_ext_InternalLinkage_getSpelling_wrapper" type clang_ext_ltovisibilitypublic_spelling = | GNU_lto_visibility_public | CXX11_clang_lto_visibility_public | C2x_clang_lto_visibility_public | SpellingNotCalculated [@@deriving refl] external ext_ltovisibility_public_get_spelling : cxcursor -> clang_ext_ltovisibilitypublic_spelling = "clang_ext_LTOVisibilityPublic_getSpelling_wrapper" type clang_ext_leaf_spelling = | GNU_leaf | CXX11_gnu_leaf | C2x_gnu_leaf | SpellingNotCalculated [@@deriving refl] external ext_leaf_get_spelling : cxcursor -> clang_ext_leaf_spelling = "clang_ext_Leaf_getSpelling_wrapper" type clang_ext_lifetimebound_spelling = | GNU_lifetimebound | CXX11_clang_lifetimebound | SpellingNotCalculated [@@deriving refl] external ext_lifetime_bound_get_spelling : cxcursor -> clang_ext_lifetimebound_spelling = "clang_ext_LifetimeBound_getSpelling_wrapper" type clang_ext_likely_spelling = | CXX11_likely | C2x_clang_likely | SpellingNotCalculated [@@deriving refl] external ext_likely_get_spelling : cxcursor -> clang_ext_likely_spelling = "clang_ext_Likely_getSpelling_wrapper" type clang_ext_loaderuninitialized_spelling = | GNU_loader_uninitialized | CXX11_clang_loader_uninitialized | C2x_clang_loader_uninitialized | SpellingNotCalculated [@@deriving refl] external ext_loader_uninitialized_get_spelling : cxcursor -> clang_ext_loaderuninitialized_spelling = "clang_ext_LoaderUninitialized_getSpelling_wrapper" type clang_ext_loophint_spelling = | Pragma_clang_loop | Pragma_unroll | Pragma_nounroll | Pragma_unroll_and_jam | Pragma_nounroll_and_jam | SpellingNotCalculated [@@deriving refl] external ext_loop_hint_get_spelling : cxcursor -> clang_ext_loophint_spelling = "clang_ext_LoopHint_getSpelling_wrapper" type clang_ext_migserverroutine_spelling = | GNU_mig_server_routine | CXX11_clang_mig_server_routine | C2x_clang_mig_server_routine | SpellingNotCalculated [@@deriving refl] external ext_migserver_routine_get_spelling : cxcursor -> clang_ext_migserverroutine_spelling = "clang_ext_MIGServerRoutine_getSpelling_wrapper" type clang_ext_msabi_spelling = | GNU_ms_abi | CXX11_gnu_ms_abi | C2x_gnu_ms_abi | SpellingNotCalculated [@@deriving refl] external ext_msabi_get_spelling : cxcursor -> clang_ext_msabi_spelling = "clang_ext_MSABI_getSpelling_wrapper" type clang_ext_msinheritance_spelling = | Keyword_single_inheritance | Keyword_multiple_inheritance | Keyword_virtual_inheritance | Keyword_unspecified_inheritance | SpellingNotCalculated [@@deriving refl] external ext_msinheritance_get_spelling : cxcursor -> clang_ext_msinheritance_spelling = "clang_ext_MSInheritance_getSpelling_wrapper" type clang_ext_msp430interrupt_spelling = | GNU_interrupt | CXX11_gnu_interrupt | C2x_gnu_interrupt | SpellingNotCalculated [@@deriving refl] external ext_msp430_interrupt_get_spelling : cxcursor -> clang_ext_msp430interrupt_spelling = "clang_ext_MSP430Interrupt_getSpelling_wrapper" type clang_ext_msstruct_spelling = | GNU_ms_struct | CXX11_gnu_ms_struct | C2x_gnu_ms_struct | SpellingNotCalculated [@@deriving refl] external ext_msstruct_get_spelling : cxcursor -> clang_ext_msstruct_spelling = "clang_ext_MSStruct_getSpelling_wrapper" type clang_ext_mayalias_spelling = | GNU_may_alias | CXX11_gnu_may_alias | C2x_gnu_may_alias | SpellingNotCalculated [@@deriving refl] external ext_may_alias_get_spelling : cxcursor -> clang_ext_mayalias_spelling = "clang_ext_MayAlias_getSpelling_wrapper" type clang_ext_micromips_spelling = | GNU_micromips | CXX11_gnu_micromips | C2x_gnu_micromips | SpellingNotCalculated [@@deriving refl] external ext_micro_mips_get_spelling : cxcursor -> clang_ext_micromips_spelling = "clang_ext_MicroMips_getSpelling_wrapper" type clang_ext_minsize_spelling = | GNU_minsize | CXX11_clang_minsize | C2x_clang_minsize | SpellingNotCalculated [@@deriving refl] external ext_min_size_get_spelling : cxcursor -> clang_ext_minsize_spelling = "clang_ext_MinSize_getSpelling_wrapper" type clang_ext_minvectorwidth_spelling = | GNU_min_vector_width | CXX11_clang_min_vector_width | C2x_clang_min_vector_width | SpellingNotCalculated [@@deriving refl] external ext_min_vector_width_get_spelling : cxcursor -> clang_ext_minvectorwidth_spelling = "clang_ext_MinVectorWidth_getSpelling_wrapper" type clang_ext_mips16_spelling = | GNU_mips16 | CXX11_gnu_mips16 | C2x_gnu_mips16 | SpellingNotCalculated [@@deriving refl] external ext_mips16_get_spelling : cxcursor -> clang_ext_mips16_spelling = "clang_ext_Mips16_getSpelling_wrapper" type clang_ext_mipsinterrupt_spelling = | GNU_interrupt | CXX11_gnu_interrupt | C2x_gnu_interrupt | SpellingNotCalculated [@@deriving refl] external ext_mips_interrupt_get_spelling : cxcursor -> clang_ext_mipsinterrupt_spelling = "clang_ext_MipsInterrupt_getSpelling_wrapper" type clang_ext_mipslongcall_spelling = | GNU_long_call | CXX11_gnu_long_call | C2x_gnu_long_call | GNU_far | CXX11_gnu_far | C2x_gnu_far | SpellingNotCalculated [@@deriving refl] external ext_mips_long_call_get_spelling : cxcursor -> clang_ext_mipslongcall_spelling = "clang_ext_MipsLongCall_getSpelling_wrapper" type clang_ext_mipsshortcall_spelling = | GNU_short_call | CXX11_gnu_short_call | C2x_gnu_short_call | GNU_near | CXX11_gnu_near | C2x_gnu_near | SpellingNotCalculated [@@deriving refl] external ext_mips_short_call_get_spelling : cxcursor -> clang_ext_mipsshortcall_spelling = "clang_ext_MipsShortCall_getSpelling_wrapper" type clang_ext_mode_spelling = | GNU_mode | CXX11_gnu_mode | C2x_gnu_mode | SpellingNotCalculated [@@deriving refl] external ext_mode_get_spelling : cxcursor -> clang_ext_mode_spelling = "clang_ext_Mode_getSpelling_wrapper" type clang_ext_musttail_spelling = | GNU_musttail | CXX11_clang_musttail | C2x_clang_musttail | SpellingNotCalculated [@@deriving refl] external ext_must_tail_get_spelling : cxcursor -> clang_ext_musttail_spelling = "clang_ext_MustTail_getSpelling_wrapper" type clang_ext_nsconsumed_spelling = | GNU_ns_consumed | CXX11_clang_ns_consumed | C2x_clang_ns_consumed | SpellingNotCalculated [@@deriving refl] external ext_nsconsumed_get_spelling : cxcursor -> clang_ext_nsconsumed_spelling = "clang_ext_NSConsumed_getSpelling_wrapper" type clang_ext_nsconsumesself_spelling = | GNU_ns_consumes_self | CXX11_clang_ns_consumes_self | C2x_clang_ns_consumes_self | SpellingNotCalculated [@@deriving refl] external ext_nsconsumes_self_get_spelling : cxcursor -> clang_ext_nsconsumesself_spelling = "clang_ext_NSConsumesSelf_getSpelling_wrapper" type clang_ext_nsreturnsautoreleased_spelling = | GNU_ns_returns_autoreleased | CXX11_clang_ns_returns_autoreleased | C2x_clang_ns_returns_autoreleased | SpellingNotCalculated [@@deriving refl] external ext_nsreturns_autoreleased_get_spelling : cxcursor -> clang_ext_nsreturnsautoreleased_spelling = "clang_ext_NSReturnsAutoreleased_getSpelling_wrapper" type clang_ext_nsreturnsnotretained_spelling = | GNU_ns_returns_not_retained | CXX11_clang_ns_returns_not_retained | C2x_clang_ns_returns_not_retained | SpellingNotCalculated [@@deriving refl] external ext_nsreturns_not_retained_get_spelling : cxcursor -> clang_ext_nsreturnsnotretained_spelling = "clang_ext_NSReturnsNotRetained_getSpelling_wrapper" type clang_ext_nsreturnsretained_spelling = | GNU_ns_returns_retained | CXX11_clang_ns_returns_retained | C2x_clang_ns_returns_retained | SpellingNotCalculated [@@deriving refl] external ext_nsreturns_retained_get_spelling : cxcursor -> clang_ext_nsreturnsretained_spelling = "clang_ext_NSReturnsRetained_getSpelling_wrapper" type clang_ext_naked_spelling = | GNU_naked | CXX11_gnu_naked | C2x_gnu_naked | Declspec_naked | SpellingNotCalculated [@@deriving refl] external ext_naked_get_spelling : cxcursor -> clang_ext_naked_spelling = "clang_ext_Naked_getSpelling_wrapper" type clang_ext_nobuiltin_spelling = | GNU_no_builtin | CXX11_clang_no_builtin | C2x_clang_no_builtin | SpellingNotCalculated [@@deriving refl] external ext_no_builtin_get_spelling : cxcursor -> clang_ext_nobuiltin_spelling = "clang_ext_NoBuiltin_getSpelling_wrapper" type clang_ext_nocommon_spelling = | GNU_nocommon | CXX11_gnu_nocommon | C2x_gnu_nocommon | SpellingNotCalculated [@@deriving refl] external ext_no_common_get_spelling : cxcursor -> clang_ext_nocommon_spelling = "clang_ext_NoCommon_getSpelling_wrapper" type clang_ext_nodebug_spelling = | GNU_nodebug | CXX11_gnu_nodebug | C2x_gnu_nodebug | SpellingNotCalculated [@@deriving refl] external ext_no_debug_get_spelling : cxcursor -> clang_ext_nodebug_spelling = "clang_ext_NoDebug_getSpelling_wrapper" type clang_ext_noderef_spelling = | GNU_noderef | CXX11_clang_noderef | C2x_clang_noderef | SpellingNotCalculated [@@deriving refl] external ext_no_deref_get_spelling : cxcursor -> clang_ext_noderef_spelling = "clang_ext_NoDeref_getSpelling_wrapper" type clang_ext_nodestroy_spelling = | GNU_no_destroy | CXX11_clang_no_destroy | SpellingNotCalculated [@@deriving refl] external ext_no_destroy_get_spelling : cxcursor -> clang_ext_nodestroy_spelling = "clang_ext_NoDestroy_getSpelling_wrapper" type clang_ext_noduplicate_spelling = | GNU_noduplicate | CXX11_clang_noduplicate | C2x_clang_noduplicate | SpellingNotCalculated [@@deriving refl] external ext_no_duplicate_get_spelling : cxcursor -> clang_ext_noduplicate_spelling = "clang_ext_NoDuplicate_getSpelling_wrapper" type clang_ext_noescape_spelling = | GNU_noescape | CXX11_clang_noescape | C2x_clang_noescape | SpellingNotCalculated [@@deriving refl] external ext_no_escape_get_spelling : cxcursor -> clang_ext_noescape_spelling = "clang_ext_NoEscape_getSpelling_wrapper" type clang_ext_noinline_spelling = | Keyword_noinline | GNU_noinline | CXX11_gnu_noinline | C2x_gnu_noinline | CXX11_clang_noinline | C2x_clang_noinline | Declspec_noinline | SpellingNotCalculated [@@deriving refl] external ext_no_inline_get_spelling : cxcursor -> clang_ext_noinline_spelling = "clang_ext_NoInline_getSpelling_wrapper" type clang_ext_noinstrumentfunction_spelling = | GNU_no_instrument_function | CXX11_gnu_no_instrument_function | C2x_gnu_no_instrument_function | SpellingNotCalculated [@@deriving refl] external ext_no_instrument_function_get_spelling : cxcursor -> clang_ext_noinstrumentfunction_spelling = "clang_ext_NoInstrumentFunction_getSpelling_wrapper" type clang_ext_nomerge_spelling = | GNU_nomerge | CXX11_clang_nomerge | C2x_clang_nomerge | SpellingNotCalculated [@@deriving refl] external ext_no_merge_get_spelling : cxcursor -> clang_ext_nomerge_spelling = "clang_ext_NoMerge_getSpelling_wrapper" type clang_ext_nomicromips_spelling = | GNU_nomicromips | CXX11_gnu_nomicromips | C2x_gnu_nomicromips | SpellingNotCalculated [@@deriving refl] external ext_no_micro_mips_get_spelling : cxcursor -> clang_ext_nomicromips_spelling = "clang_ext_NoMicroMips_getSpelling_wrapper" type clang_ext_nomips16_spelling = | GNU_nomips16 | CXX11_gnu_nomips16 | C2x_gnu_nomips16 | SpellingNotCalculated [@@deriving refl] external ext_no_mips16_get_spelling : cxcursor -> clang_ext_nomips16_spelling = "clang_ext_NoMips16_getSpelling_wrapper" type clang_ext_noprofilefunction_spelling = | GNU_no_profile_instrument_function | CXX11_gnu_no_profile_instrument_function | C2x_gnu_no_profile_instrument_function | SpellingNotCalculated [@@deriving refl] external ext_no_profile_function_get_spelling : cxcursor -> clang_ext_noprofilefunction_spelling = "clang_ext_NoProfileFunction_getSpelling_wrapper" type clang_ext_norandomizelayout_spelling = | GNU_no_randomize_layout | CXX11_gnu_no_randomize_layout | C2x_gnu_no_randomize_layout | SpellingNotCalculated [@@deriving refl] external ext_no_randomize_layout_get_spelling : cxcursor -> clang_ext_norandomizelayout_spelling = "clang_ext_NoRandomizeLayout_getSpelling_wrapper" type clang_ext_noreturn_spelling = | GNU_noreturn | CXX11_gnu_noreturn | C2x_gnu_noreturn | Declspec_noreturn | SpellingNotCalculated [@@deriving refl] external ext_no_return_get_spelling : cxcursor -> clang_ext_noreturn_spelling = "clang_ext_NoReturn_getSpelling_wrapper" type clang_ext_nosanitize_spelling = | GNU_no_sanitize | CXX11_clang_no_sanitize | C2x_clang_no_sanitize | SpellingNotCalculated [@@deriving refl] external ext_no_sanitize_get_spelling : cxcursor -> clang_ext_nosanitize_spelling = "clang_ext_NoSanitize_getSpelling_wrapper" type clang_ext_nospeculativeloadhardening_spelling = | GNU_no_speculative_load_hardening | CXX11_clang_no_speculative_load_hardening | C2x_clang_no_speculative_load_hardening | SpellingNotCalculated [@@deriving refl] external ext_no_speculative_load_hardening_get_spelling : cxcursor -> clang_ext_nospeculativeloadhardening_spelling = "clang_ext_NoSpeculativeLoadHardening_getSpelling_wrapper" type clang_ext_nosplitstack_spelling = | GNU_no_split_stack | CXX11_gnu_no_split_stack | C2x_gnu_no_split_stack | SpellingNotCalculated [@@deriving refl] external ext_no_split_stack_get_spelling : cxcursor -> clang_ext_nosplitstack_spelling = "clang_ext_NoSplitStack_getSpelling_wrapper" type clang_ext_nostackprotector_spelling = | GNU_no_stack_protector | CXX11_clang_no_stack_protector | C2x_clang_no_stack_protector | SpellingNotCalculated [@@deriving refl] external ext_no_stack_protector_get_spelling : cxcursor -> clang_ext_nostackprotector_spelling = "clang_ext_NoStackProtector_getSpelling_wrapper" type clang_ext_nothreadsafetyanalysis_spelling = | GNU_no_thread_safety_analysis | CXX11_clang_no_thread_safety_analysis | C2x_clang_no_thread_safety_analysis | SpellingNotCalculated [@@deriving refl] external ext_no_thread_safety_analysis_get_spelling : cxcursor -> clang_ext_nothreadsafetyanalysis_spelling = "clang_ext_NoThreadSafetyAnalysis_getSpelling_wrapper" type clang_ext_nothrow_spelling = | GNU_nothrow | CXX11_gnu_nothrow | C2x_gnu_nothrow | Declspec_nothrow | SpellingNotCalculated [@@deriving refl] external ext_no_throw_get_spelling : cxcursor -> clang_ext_nothrow_spelling = "clang_ext_NoThrow_getSpelling_wrapper" type clang_ext_nonnull_spelling = | GNU_nonnull | CXX11_gnu_nonnull | C2x_gnu_nonnull | SpellingNotCalculated [@@deriving refl] external ext_non_null_get_spelling : cxcursor -> clang_ext_nonnull_spelling = "clang_ext_NonNull_getSpelling_wrapper" type clang_ext_nottailcalled_spelling = | GNU_not_tail_called | CXX11_clang_not_tail_called | C2x_clang_not_tail_called | SpellingNotCalculated [@@deriving refl] external ext_not_tail_called_get_spelling : cxcursor -> clang_ext_nottailcalled_spelling = "clang_ext_NotTailCalled_getSpelling_wrapper" type clang_ext_osconsumed_spelling = | GNU_os_consumed | CXX11_clang_os_consumed | C2x_clang_os_consumed | SpellingNotCalculated [@@deriving refl] external ext_osconsumed_get_spelling : cxcursor -> clang_ext_osconsumed_spelling = "clang_ext_OSConsumed_getSpelling_wrapper" type clang_ext_osconsumesthis_spelling = | GNU_os_consumes_this | CXX11_clang_os_consumes_this | C2x_clang_os_consumes_this | SpellingNotCalculated [@@deriving refl] external ext_osconsumes_this_get_spelling : cxcursor -> clang_ext_osconsumesthis_spelling = "clang_ext_OSConsumesThis_getSpelling_wrapper" type clang_ext_osreturnsnotretained_spelling = | GNU_os_returns_not_retained | CXX11_clang_os_returns_not_retained | C2x_clang_os_returns_not_retained | SpellingNotCalculated [@@deriving refl] external ext_osreturns_not_retained_get_spelling : cxcursor -> clang_ext_osreturnsnotretained_spelling = "clang_ext_OSReturnsNotRetained_getSpelling_wrapper" type clang_ext_osreturnsretained_spelling = | GNU_os_returns_retained | CXX11_clang_os_returns_retained | C2x_clang_os_returns_retained | SpellingNotCalculated [@@deriving refl] external ext_osreturns_retained_get_spelling : cxcursor -> clang_ext_osreturnsretained_spelling = "clang_ext_OSReturnsRetained_getSpelling_wrapper" type clang_ext_osreturnsretainedonnonzero_spelling = | GNU_os_returns_retained_on_non_zero | CXX11_clang_os_returns_retained_on_non_zero | C2x_clang_os_returns_retained_on_non_zero | SpellingNotCalculated [@@deriving refl] external ext_osreturns_retained_on_non_zero_get_spelling : cxcursor -> clang_ext_osreturnsretainedonnonzero_spelling = "clang_ext_OSReturnsRetainedOnNonZero_getSpelling_wrapper" type clang_ext_osreturnsretainedonzero_spelling = | GNU_os_returns_retained_on_zero | CXX11_clang_os_returns_retained_on_zero | C2x_clang_os_returns_retained_on_zero | SpellingNotCalculated [@@deriving refl] external ext_osreturns_retained_on_zero_get_spelling : cxcursor -> clang_ext_osreturnsretainedonzero_spelling = "clang_ext_OSReturnsRetainedOnZero_getSpelling_wrapper" type clang_ext_objcboxable_spelling = | GNU_objc_boxable | CXX11_clang_objc_boxable | C2x_clang_objc_boxable | SpellingNotCalculated [@@deriving refl] external ext_obj_cboxable_get_spelling : cxcursor -> clang_ext_objcboxable_spelling = "clang_ext_ObjCBoxable_getSpelling_wrapper" type clang_ext_objcbridge_spelling = | GNU_objc_bridge | CXX11_clang_objc_bridge | C2x_clang_objc_bridge | SpellingNotCalculated [@@deriving refl] external ext_obj_cbridge_get_spelling : cxcursor -> clang_ext_objcbridge_spelling = "clang_ext_ObjCBridge_getSpelling_wrapper" type clang_ext_objcbridgemutable_spelling = | GNU_objc_bridge_mutable | CXX11_clang_objc_bridge_mutable | C2x_clang_objc_bridge_mutable | SpellingNotCalculated [@@deriving refl] external ext_obj_cbridge_mutable_get_spelling : cxcursor -> clang_ext_objcbridgemutable_spelling = "clang_ext_ObjCBridgeMutable_getSpelling_wrapper" type clang_ext_objcbridgerelated_spelling = | GNU_objc_bridge_related | CXX11_clang_objc_bridge_related | C2x_clang_objc_bridge_related | SpellingNotCalculated [@@deriving refl] external ext_obj_cbridge_related_get_spelling : cxcursor -> clang_ext_objcbridgerelated_spelling = "clang_ext_ObjCBridgeRelated_getSpelling_wrapper" type clang_ext_objcclassstub_spelling = | GNU_objc_class_stub | CXX11_clang_objc_class_stub | C2x_clang_objc_class_stub | SpellingNotCalculated [@@deriving refl] external ext_obj_cclass_stub_get_spelling : cxcursor -> clang_ext_objcclassstub_spelling = "clang_ext_ObjCClassStub_getSpelling_wrapper" type clang_ext_objcdesignatedinitializer_spelling = | GNU_objc_designated_initializer | CXX11_clang_objc_designated_initializer | C2x_clang_objc_designated_initializer | SpellingNotCalculated [@@deriving refl] external ext_obj_cdesignated_initializer_get_spelling : cxcursor -> clang_ext_objcdesignatedinitializer_spelling = "clang_ext_ObjCDesignatedInitializer_getSpelling_wrapper" type clang_ext_objcdirect_spelling = | GNU_objc_direct | CXX11_clang_objc_direct | C2x_clang_objc_direct | SpellingNotCalculated [@@deriving refl] external ext_obj_cdirect_get_spelling : cxcursor -> clang_ext_objcdirect_spelling = "clang_ext_ObjCDirect_getSpelling_wrapper" type clang_ext_objcdirectmembers_spelling = | GNU_objc_direct_members | CXX11_clang_objc_direct_members | C2x_clang_objc_direct_members | SpellingNotCalculated [@@deriving refl] external ext_obj_cdirect_members_get_spelling : cxcursor -> clang_ext_objcdirectmembers_spelling = "clang_ext_ObjCDirectMembers_getSpelling_wrapper" type clang_ext_objcexception_spelling = | GNU_objc_exception | CXX11_clang_objc_exception | C2x_clang_objc_exception | SpellingNotCalculated [@@deriving refl] external ext_obj_cexception_get_spelling : cxcursor -> clang_ext_objcexception_spelling = "clang_ext_ObjCException_getSpelling_wrapper" type clang_ext_objcexplicitprotocolimpl_spelling = | GNU_objc_protocol_requires_explicit_implementation | CXX11_clang_objc_protocol_requires_explicit_implementation | C2x_clang_objc_protocol_requires_explicit_implementation | SpellingNotCalculated [@@deriving refl] external ext_obj_cexplicit_protocol_impl_get_spelling : cxcursor -> clang_ext_objcexplicitprotocolimpl_spelling = "clang_ext_ObjCExplicitProtocolImpl_getSpelling_wrapper" type clang_ext_objcexternallyretained_spelling = | GNU_objc_externally_retained | CXX11_clang_objc_externally_retained | C2x_clang_objc_externally_retained | SpellingNotCalculated [@@deriving refl] external ext_obj_cexternally_retained_get_spelling : cxcursor -> clang_ext_objcexternallyretained_spelling = "clang_ext_ObjCExternallyRetained_getSpelling_wrapper" type clang_ext_objcgc_spelling = | GNU_objc_gc | CXX11_clang_objc_gc | C2x_clang_objc_gc | SpellingNotCalculated [@@deriving refl] external ext_obj_cgc_get_spelling : cxcursor -> clang_ext_objcgc_spelling = "clang_ext_ObjCGC_getSpelling_wrapper" type clang_ext_objcindependentclass_spelling = | GNU_objc_independent_class | CXX11_clang_objc_independent_class | C2x_clang_objc_independent_class | SpellingNotCalculated [@@deriving refl] external ext_obj_cindependent_class_get_spelling : cxcursor -> clang_ext_objcindependentclass_spelling = "clang_ext_ObjCIndependentClass_getSpelling_wrapper" type clang_ext_objcmethodfamily_spelling = | GNU_objc_method_family | CXX11_clang_objc_method_family | C2x_clang_objc_method_family | SpellingNotCalculated [@@deriving refl] external ext_obj_cmethod_family_get_spelling : cxcursor -> clang_ext_objcmethodfamily_spelling = "clang_ext_ObjCMethodFamily_getSpelling_wrapper" type clang_ext_objcnsobject_spelling = | GNU_NSObject | CXX11_clang_NSObject | C2x_clang_NSObject | SpellingNotCalculated [@@deriving refl] external ext_obj_cnsobject_get_spelling : cxcursor -> clang_ext_objcnsobject_spelling = "clang_ext_ObjCNSObject_getSpelling_wrapper" type clang_ext_objcnonlazyclass_spelling = | GNU_objc_nonlazy_class | CXX11_clang_objc_nonlazy_class | C2x_clang_objc_nonlazy_class | SpellingNotCalculated [@@deriving refl] external ext_obj_cnon_lazy_class_get_spelling : cxcursor -> clang_ext_objcnonlazyclass_spelling = "clang_ext_ObjCNonLazyClass_getSpelling_wrapper" type clang_ext_objcnonruntimeprotocol_spelling = | GNU_objc_non_runtime_protocol | CXX11_clang_objc_non_runtime_protocol | C2x_clang_objc_non_runtime_protocol | SpellingNotCalculated [@@deriving refl] external ext_obj_cnon_runtime_protocol_get_spelling : cxcursor -> clang_ext_objcnonruntimeprotocol_spelling = "clang_ext_ObjCNonRuntimeProtocol_getSpelling_wrapper" type clang_ext_objcownership_spelling = | GNU_objc_ownership | CXX11_clang_objc_ownership | C2x_clang_objc_ownership | SpellingNotCalculated [@@deriving refl] external ext_obj_cownership_get_spelling : cxcursor -> clang_ext_objcownership_spelling = "clang_ext_ObjCOwnership_getSpelling_wrapper" type clang_ext_objcpreciselifetime_spelling = | GNU_objc_precise_lifetime | CXX11_clang_objc_precise_lifetime | C2x_clang_objc_precise_lifetime | SpellingNotCalculated [@@deriving refl] external ext_obj_cprecise_lifetime_get_spelling : cxcursor -> clang_ext_objcpreciselifetime_spelling = "clang_ext_ObjCPreciseLifetime_getSpelling_wrapper" type clang_ext_objcrequirespropertydefs_spelling = | GNU_objc_requires_property_definitions | CXX11_clang_objc_requires_property_definitions | C2x_clang_objc_requires_property_definitions | SpellingNotCalculated [@@deriving refl] external ext_obj_crequires_property_defs_get_spelling : cxcursor -> clang_ext_objcrequirespropertydefs_spelling = "clang_ext_ObjCRequiresPropertyDefs_getSpelling_wrapper" type clang_ext_objcrequiressuper_spelling = | GNU_objc_requires_super | CXX11_clang_objc_requires_super | C2x_clang_objc_requires_super | SpellingNotCalculated [@@deriving refl] external ext_obj_crequires_super_get_spelling : cxcursor -> clang_ext_objcrequiressuper_spelling = "clang_ext_ObjCRequiresSuper_getSpelling_wrapper" type clang_ext_objcreturnsinnerpointer_spelling = | GNU_objc_returns_inner_pointer | CXX11_clang_objc_returns_inner_pointer | C2x_clang_objc_returns_inner_pointer | SpellingNotCalculated [@@deriving refl] external ext_obj_creturns_inner_pointer_get_spelling : cxcursor -> clang_ext_objcreturnsinnerpointer_spelling = "clang_ext_ObjCReturnsInnerPointer_getSpelling_wrapper" type clang_ext_objcrootclass_spelling = | GNU_objc_root_class | CXX11_clang_objc_root_class | C2x_clang_objc_root_class | SpellingNotCalculated [@@deriving refl] external ext_obj_croot_class_get_spelling : cxcursor -> clang_ext_objcrootclass_spelling = "clang_ext_ObjCRootClass_getSpelling_wrapper" type clang_ext_objcruntimename_spelling = | GNU_objc_runtime_name | CXX11_clang_objc_runtime_name | C2x_clang_objc_runtime_name | SpellingNotCalculated [@@deriving refl] external ext_obj_cruntime_name_get_spelling : cxcursor -> clang_ext_objcruntimename_spelling = "clang_ext_ObjCRuntimeName_getSpelling_wrapper" type clang_ext_objcruntimevisible_spelling = | GNU_objc_runtime_visible | CXX11_clang_objc_runtime_visible | C2x_clang_objc_runtime_visible | SpellingNotCalculated [@@deriving refl] external ext_obj_cruntime_visible_get_spelling : cxcursor -> clang_ext_objcruntimevisible_spelling = "clang_ext_ObjCRuntimeVisible_getSpelling_wrapper" type clang_ext_objcsubclassingrestricted_spelling = | GNU_objc_subclassing_restricted | CXX11_clang_objc_subclassing_restricted | C2x_clang_objc_subclassing_restricted | SpellingNotCalculated [@@deriving refl] external ext_obj_csubclassing_restricted_get_spelling : cxcursor -> clang_ext_objcsubclassingrestricted_spelling = "clang_ext_ObjCSubclassingRestricted_getSpelling_wrapper" type clang_ext_openclaccess_spelling = | Keyword_read_only | Keyword_write_only | Keyword_read_write | SpellingNotCalculated [@@deriving refl] external ext_open_claccess_get_spelling : cxcursor -> clang_ext_openclaccess_spelling = "clang_ext_OpenCLAccess_getSpelling_wrapper" type clang_ext_openclconstantaddressspace_spelling = | Keyword_constant | GNU_opencl_constant | CXX11_clang_opencl_constant | C2x_clang_opencl_constant | SpellingNotCalculated [@@deriving refl] external ext_open_clconstant_address_space_get_spelling : cxcursor -> clang_ext_openclconstantaddressspace_spelling = "clang_ext_OpenCLConstantAddressSpace_getSpelling_wrapper" type clang_ext_openclgenericaddressspace_spelling = | Keyword_generic | GNU_opencl_generic | CXX11_clang_opencl_generic | C2x_clang_opencl_generic | SpellingNotCalculated [@@deriving refl] external ext_open_clgeneric_address_space_get_spelling : cxcursor -> clang_ext_openclgenericaddressspace_spelling = "clang_ext_OpenCLGenericAddressSpace_getSpelling_wrapper" type clang_ext_openclglobaladdressspace_spelling = | Keyword_global | GNU_opencl_global | CXX11_clang_opencl_global | C2x_clang_opencl_global | SpellingNotCalculated [@@deriving refl] external ext_open_clglobal_address_space_get_spelling : cxcursor -> clang_ext_openclglobaladdressspace_spelling = "clang_ext_OpenCLGlobalAddressSpace_getSpelling_wrapper" type clang_ext_openclglobaldeviceaddressspace_spelling = | GNU_opencl_global_device | CXX11_clang_opencl_global_device | C2x_clang_opencl_global_device | SpellingNotCalculated [@@deriving refl] external ext_open_clglobal_device_address_space_get_spelling : cxcursor -> clang_ext_openclglobaldeviceaddressspace_spelling = "clang_ext_OpenCLGlobalDeviceAddressSpace_getSpelling_wrapper" type clang_ext_openclglobalhostaddressspace_spelling = | GNU_opencl_global_host | CXX11_clang_opencl_global_host | C2x_clang_opencl_global_host | SpellingNotCalculated [@@deriving refl] external ext_open_clglobal_host_address_space_get_spelling : cxcursor -> clang_ext_openclglobalhostaddressspace_spelling = "clang_ext_OpenCLGlobalHostAddressSpace_getSpelling_wrapper" type clang_ext_openclkernel_spelling = | Keyword_kernel | SpellingNotCalculated [@@deriving refl] external ext_open_clkernel_get_spelling : cxcursor -> clang_ext_openclkernel_spelling = "clang_ext_OpenCLKernel_getSpelling_wrapper" type clang_ext_opencllocaladdressspace_spelling = | Keyword_local | GNU_opencl_local | CXX11_clang_opencl_local | C2x_clang_opencl_local | SpellingNotCalculated [@@deriving refl] external ext_open_cllocal_address_space_get_spelling : cxcursor -> clang_ext_opencllocaladdressspace_spelling = "clang_ext_OpenCLLocalAddressSpace_getSpelling_wrapper" type clang_ext_openclprivateaddressspace_spelling = | Keyword_private | GNU_opencl_private | CXX11_clang_opencl_private | C2x_clang_opencl_private | SpellingNotCalculated [@@deriving refl] external ext_open_clprivate_address_space_get_spelling : cxcursor -> clang_ext_openclprivateaddressspace_spelling = "clang_ext_OpenCLPrivateAddressSpace_getSpelling_wrapper" type clang_ext_optimizenone_spelling = | GNU_optnone | CXX11_clang_optnone | C2x_clang_optnone | SpellingNotCalculated [@@deriving refl] external ext_optimize_none_get_spelling : cxcursor -> clang_ext_optimizenone_spelling = "clang_ext_OptimizeNone_getSpelling_wrapper" type clang_ext_overloadable_spelling = | GNU_overloadable | CXX11_clang_overloadable | C2x_clang_overloadable | SpellingNotCalculated [@@deriving refl] external ext_overloadable_get_spelling : cxcursor -> clang_ext_overloadable_spelling = "clang_ext_Overloadable_getSpelling_wrapper" type clang_ext_ownership_spelling = | GNU_ownership_holds | CXX11_clang_ownership_holds | C2x_clang_ownership_holds | GNU_ownership_returns | CXX11_clang_ownership_returns | C2x_clang_ownership_returns | GNU_ownership_takes | CXX11_clang_ownership_takes | C2x_clang_ownership_takes | SpellingNotCalculated [@@deriving refl] external ext_ownership_get_spelling : cxcursor -> clang_ext_ownership_spelling = "clang_ext_Ownership_getSpelling_wrapper" type clang_ext_packed_spelling = | GNU_packed | CXX11_gnu_packed | C2x_gnu_packed | SpellingNotCalculated [@@deriving refl] external ext_packed_get_spelling : cxcursor -> clang_ext_packed_spelling = "clang_ext_Packed_getSpelling_wrapper" type clang_ext_paramtypestate_spelling = | GNU_param_typestate | CXX11_clang_param_typestate | SpellingNotCalculated [@@deriving refl] external ext_param_typestate_get_spelling : cxcursor -> clang_ext_paramtypestate_spelling = "clang_ext_ParamTypestate_getSpelling_wrapper" type clang_ext_pascal_spelling = | GNU_pascal | CXX11_clang_pascal | C2x_clang_pascal | Keyword_pascal | SpellingNotCalculated [@@deriving refl] external ext_pascal_get_spelling : cxcursor -> clang_ext_pascal_spelling = "clang_ext_Pascal_getSpelling_wrapper" type clang_ext_passobjectsize_spelling = | GNU_pass_object_size | CXX11_clang_pass_object_size | C2x_clang_pass_object_size | GNU_pass_dynamic_object_size | CXX11_clang_pass_dynamic_object_size | C2x_clang_pass_dynamic_object_size | SpellingNotCalculated [@@deriving refl] external ext_pass_object_size_get_spelling : cxcursor -> clang_ext_passobjectsize_spelling = "clang_ext_PassObjectSize_getSpelling_wrapper" type clang_ext_patchablefunctionentry_spelling = | GNU_patchable_function_entry | CXX11_gnu_patchable_function_entry | C2x_gnu_patchable_function_entry | SpellingNotCalculated [@@deriving refl] external ext_patchable_function_entry_get_spelling : cxcursor -> clang_ext_patchablefunctionentry_spelling = "clang_ext_PatchableFunctionEntry_getSpelling_wrapper" type clang_ext_pcs_spelling = | GNU_pcs | CXX11_gnu_pcs | C2x_gnu_pcs | SpellingNotCalculated [@@deriving refl] external ext_pcs_get_spelling : cxcursor -> clang_ext_pcs_spelling = "clang_ext_Pcs_getSpelling_wrapper" type clang_ext_preferredname_spelling = | GNU_preferred_name | CXX11_clang_preferred_name | SpellingNotCalculated [@@deriving refl] external ext_preferred_name_get_spelling : cxcursor -> clang_ext_preferredname_spelling = "clang_ext_PreferredName_getSpelling_wrapper" type clang_ext_preserveall_spelling = | GNU_preserve_all | CXX11_clang_preserve_all | C2x_clang_preserve_all | SpellingNotCalculated [@@deriving refl] external ext_preserve_all_get_spelling : cxcursor -> clang_ext_preserveall_spelling = "clang_ext_PreserveAll_getSpelling_wrapper" type clang_ext_preservemost_spelling = | GNU_preserve_most | CXX11_clang_preserve_most | C2x_clang_preserve_most | SpellingNotCalculated [@@deriving refl] external ext_preserve_most_get_spelling : cxcursor -> clang_ext_preservemost_spelling = "clang_ext_PreserveMost_getSpelling_wrapper" type clang_ext_ptguardedvar_spelling = | GNU_pt_guarded_var | CXX11_clang_pt_guarded_var | SpellingNotCalculated [@@deriving refl] external ext_pt_guarded_var_get_spelling : cxcursor -> clang_ext_ptguardedvar_spelling = "clang_ext_PtGuardedVar_getSpelling_wrapper" type clang_ext_pure_spelling = | GNU_pure | CXX11_gnu_pure | C2x_gnu_pure | SpellingNotCalculated [@@deriving refl] external ext_pure_get_spelling : cxcursor -> clang_ext_pure_spelling = "clang_ext_Pure_getSpelling_wrapper" type clang_ext_riscvinterrupt_spelling = | GNU_interrupt | CXX11_gnu_interrupt | C2x_gnu_interrupt | SpellingNotCalculated [@@deriving refl] external ext_riscvinterrupt_get_spelling : cxcursor -> clang_ext_riscvinterrupt_spelling = "clang_ext_RISCVInterrupt_getSpelling_wrapper" type clang_ext_randomizelayout_spelling = | GNU_randomize_layout | CXX11_gnu_randomize_layout | C2x_gnu_randomize_layout | SpellingNotCalculated [@@deriving refl] external ext_randomize_layout_get_spelling : cxcursor -> clang_ext_randomizelayout_spelling = "clang_ext_RandomizeLayout_getSpelling_wrapper" type clang_ext_regcall_spelling = | GNU_regcall | CXX11_gnu_regcall | C2x_gnu_regcall | Keyword_regcall | SpellingNotCalculated [@@deriving refl] external ext_reg_call_get_spelling : cxcursor -> clang_ext_regcall_spelling = "clang_ext_RegCall_getSpelling_wrapper" type clang_ext_reinitializes_spelling = | GNU_reinitializes | CXX11_clang_reinitializes | SpellingNotCalculated [@@deriving refl] external ext_reinitializes_get_spelling : cxcursor -> clang_ext_reinitializes_spelling = "clang_ext_Reinitializes_getSpelling_wrapper" type clang_ext_releasecapability_spelling = | GNU_release_capability | CXX11_clang_release_capability | GNU_release_shared_capability | CXX11_clang_release_shared_capability | GNU_release_generic_capability | CXX11_clang_release_generic_capability | GNU_unlock_function | CXX11_clang_unlock_function | SpellingNotCalculated [@@deriving refl] external ext_release_capability_get_spelling : cxcursor -> clang_ext_releasecapability_spelling = "clang_ext_ReleaseCapability_getSpelling_wrapper" type clang_ext_releasehandle_spelling = | GNU_release_handle | CXX11_clang_release_handle | C2x_clang_release_handle | SpellingNotCalculated [@@deriving refl] external ext_release_handle_get_spelling : cxcursor -> clang_ext_releasehandle_spelling = "clang_ext_ReleaseHandle_getSpelling_wrapper" type clang_ext_requirescapability_spelling = | GNU_requires_capability | CXX11_clang_requires_capability | GNU_exclusive_locks_required | CXX11_clang_exclusive_locks_required | GNU_requires_shared_capability | CXX11_clang_requires_shared_capability | GNU_shared_locks_required | CXX11_clang_shared_locks_required | SpellingNotCalculated [@@deriving refl] external ext_requires_capability_get_spelling : cxcursor -> clang_ext_requirescapability_spelling = "clang_ext_RequiresCapability_getSpelling_wrapper" type clang_ext_restrict_spelling = | Declspec_restrict | GNU_malloc | CXX11_gnu_malloc | C2x_gnu_malloc | SpellingNotCalculated [@@deriving refl] external ext_restrict_get_spelling : cxcursor -> clang_ext_restrict_spelling = "clang_ext_Restrict_getSpelling_wrapper" type clang_ext_retain_spelling = | GNU_retain | CXX11_gnu_retain | C2x_gnu_retain | SpellingNotCalculated [@@deriving refl] external ext_retain_get_spelling : cxcursor -> clang_ext_retain_spelling = "clang_ext_Retain_getSpelling_wrapper" type clang_ext_returntypestate_spelling = | GNU_return_typestate | CXX11_clang_return_typestate | SpellingNotCalculated [@@deriving refl] external ext_return_typestate_get_spelling : cxcursor -> clang_ext_returntypestate_spelling = "clang_ext_ReturnTypestate_getSpelling_wrapper" type clang_ext_returnsnonnull_spelling = | GNU_returns_nonnull | CXX11_gnu_returns_nonnull | C2x_gnu_returns_nonnull | SpellingNotCalculated [@@deriving refl] external ext_returns_non_null_get_spelling : cxcursor -> clang_ext_returnsnonnull_spelling = "clang_ext_ReturnsNonNull_getSpelling_wrapper" type clang_ext_returnstwice_spelling = | GNU_returns_twice | CXX11_gnu_returns_twice | C2x_gnu_returns_twice | SpellingNotCalculated [@@deriving refl] external ext_returns_twice_get_spelling : cxcursor -> clang_ext_returnstwice_spelling = "clang_ext_ReturnsTwice_getSpelling_wrapper" type clang_ext_syclkernel_spelling = | GNU_sycl_kernel | CXX11_clang_sycl_kernel | C2x_clang_sycl_kernel | SpellingNotCalculated [@@deriving refl] external ext_syclkernel_get_spelling : cxcursor -> clang_ext_syclkernel_spelling = "clang_ext_SYCLKernel_getSpelling_wrapper" type clang_ext_syclspecialclass_spelling = | GNU_sycl_special_class | CXX11_clang_sycl_special_class | C2x_clang_sycl_special_class | SpellingNotCalculated [@@deriving refl] external ext_syclspecial_class_get_spelling : cxcursor -> clang_ext_syclspecialclass_spelling = "clang_ext_SYCLSpecialClass_getSpelling_wrapper" type clang_ext_scopedlockable_spelling = | GNU_scoped_lockable | CXX11_clang_scoped_lockable | SpellingNotCalculated [@@deriving refl] external ext_scoped_lockable_get_spelling : cxcursor -> clang_ext_scopedlockable_spelling = "clang_ext_ScopedLockable_getSpelling_wrapper" type clang_ext_section_spelling = | GNU_section | CXX11_gnu_section | C2x_gnu_section | Declspec_allocate | SpellingNotCalculated [@@deriving refl] external ext_section_get_spelling : cxcursor -> clang_ext_section_spelling = "clang_ext_Section_getSpelling_wrapper" type clang_ext_selectany_spelling = | Declspec_selectany | GNU_selectany | CXX11_gnu_selectany | C2x_gnu_selectany | SpellingNotCalculated [@@deriving refl] external ext_select_any_get_spelling : cxcursor -> clang_ext_selectany_spelling = "clang_ext_SelectAny_getSpelling_wrapper" type clang_ext_sentinel_spelling = | GNU_sentinel | CXX11_gnu_sentinel | C2x_gnu_sentinel | SpellingNotCalculated [@@deriving refl] external ext_sentinel_get_spelling : cxcursor -> clang_ext_sentinel_spelling = "clang_ext_Sentinel_getSpelling_wrapper" type clang_ext_settypestate_spelling = | GNU_set_typestate | CXX11_clang_set_typestate | SpellingNotCalculated [@@deriving refl] external ext_set_typestate_get_spelling : cxcursor -> clang_ext_settypestate_spelling = "clang_ext_SetTypestate_getSpelling_wrapper" type clang_ext_speculativeloadhardening_spelling = | GNU_speculative_load_hardening | CXX11_clang_speculative_load_hardening | C2x_clang_speculative_load_hardening | SpellingNotCalculated [@@deriving refl] external ext_speculative_load_hardening_get_spelling : cxcursor -> clang_ext_speculativeloadhardening_spelling = "clang_ext_SpeculativeLoadHardening_getSpelling_wrapper" type clang_ext_standalonedebug_spelling = | GNU_standalone_debug | CXX11_clang_standalone_debug | SpellingNotCalculated [@@deriving refl] external ext_standalone_debug_get_spelling : cxcursor -> clang_ext_standalonedebug_spelling = "clang_ext_StandaloneDebug_getSpelling_wrapper" type clang_ext_stdcall_spelling = | GNU_stdcall | CXX11_gnu_stdcall | C2x_gnu_stdcall | Keyword_stdcall | SpellingNotCalculated [@@deriving refl] external ext_std_call_get_spelling : cxcursor -> clang_ext_stdcall_spelling = "clang_ext_StdCall_getSpelling_wrapper" type clang_ext_swiftasync_spelling = | GNU_swift_async | CXX11_clang_swift_async | C2x_clang_swift_async | SpellingNotCalculated [@@deriving refl] external ext_swift_async_get_spelling : cxcursor -> clang_ext_swiftasync_spelling = "clang_ext_SwiftAsync_getSpelling_wrapper" type clang_ext_swiftasynccall_spelling = | GNU_swiftasynccall | CXX11_clang_swiftasynccall | C2x_clang_swiftasynccall | SpellingNotCalculated [@@deriving refl] external ext_swift_async_call_get_spelling : cxcursor -> clang_ext_swiftasynccall_spelling = "clang_ext_SwiftAsyncCall_getSpelling_wrapper" type clang_ext_swiftasynccontext_spelling = | GNU_swift_async_context | CXX11_clang_swift_async_context | C2x_clang_swift_async_context | SpellingNotCalculated [@@deriving refl] external ext_swift_async_context_get_spelling : cxcursor -> clang_ext_swiftasynccontext_spelling = "clang_ext_SwiftAsyncContext_getSpelling_wrapper" type clang_ext_swiftasyncerror_spelling = | GNU_swift_async_error | CXX11_clang_swift_async_error | C2x_clang_swift_async_error | SpellingNotCalculated [@@deriving refl] external ext_swift_async_error_get_spelling : cxcursor -> clang_ext_swiftasyncerror_spelling = "clang_ext_SwiftAsyncError_getSpelling_wrapper" type clang_ext_swiftcall_spelling = | GNU_swiftcall | CXX11_clang_swiftcall | C2x_clang_swiftcall | SpellingNotCalculated [@@deriving refl] external ext_swift_call_get_spelling : cxcursor -> clang_ext_swiftcall_spelling = "clang_ext_SwiftCall_getSpelling_wrapper" type clang_ext_swiftcontext_spelling = | GNU_swift_context | CXX11_clang_swift_context | C2x_clang_swift_context | SpellingNotCalculated [@@deriving refl] external ext_swift_context_get_spelling : cxcursor -> clang_ext_swiftcontext_spelling = "clang_ext_SwiftContext_getSpelling_wrapper" type clang_ext_swifterrorresult_spelling = | GNU_swift_error_result | CXX11_clang_swift_error_result | C2x_clang_swift_error_result | SpellingNotCalculated [@@deriving refl] external ext_swift_error_result_get_spelling : cxcursor -> clang_ext_swifterrorresult_spelling = "clang_ext_SwiftErrorResult_getSpelling_wrapper" type clang_ext_swiftindirectresult_spelling = | GNU_swift_indirect_result | CXX11_clang_swift_indirect_result | C2x_clang_swift_indirect_result | SpellingNotCalculated [@@deriving refl] external ext_swift_indirect_result_get_spelling : cxcursor -> clang_ext_swiftindirectresult_spelling = "clang_ext_SwiftIndirectResult_getSpelling_wrapper" type clang_ext_swiftnewtype_spelling = | GNU_swift_newtype | GNU_swift_wrapper | SpellingNotCalculated [@@deriving refl] external ext_swift_new_type_get_spelling : cxcursor -> clang_ext_swiftnewtype_spelling = "clang_ext_SwiftNewType_getSpelling_wrapper" type clang_ext_sysvabi_spelling = | GNU_sysv_abi | CXX11_gnu_sysv_abi | C2x_gnu_sysv_abi | SpellingNotCalculated [@@deriving refl] external ext_sys_vabi_get_spelling : cxcursor -> clang_ext_sysvabi_spelling = "clang_ext_SysVABI_getSpelling_wrapper" type clang_ext_tlsmodel_spelling = | GNU_tls_model | CXX11_gnu_tls_model | C2x_gnu_tls_model | SpellingNotCalculated [@@deriving refl] external ext_tlsmodel_get_spelling : cxcursor -> clang_ext_tlsmodel_spelling = "clang_ext_TLSModel_getSpelling_wrapper" type clang_ext_target_spelling = | GNU_target | CXX11_gnu_target | C2x_gnu_target | SpellingNotCalculated [@@deriving refl] external ext_target_get_spelling : cxcursor -> clang_ext_target_spelling = "clang_ext_Target_getSpelling_wrapper" type clang_ext_targetclones_spelling = | GNU_target_clones | CXX11_gnu_target_clones | C2x_gnu_target_clones | SpellingNotCalculated [@@deriving refl] external ext_target_clones_get_spelling : cxcursor -> clang_ext_targetclones_spelling = "clang_ext_TargetClones_getSpelling_wrapper" type clang_ext_testtypestate_spelling = | GNU_test_typestate | CXX11_clang_test_typestate | SpellingNotCalculated [@@deriving refl] external ext_test_typestate_get_spelling : cxcursor -> clang_ext_testtypestate_spelling = "clang_ext_TestTypestate_getSpelling_wrapper" type clang_ext_thiscall_spelling = | GNU_thiscall | CXX11_gnu_thiscall | C2x_gnu_thiscall | Keyword_thiscall | SpellingNotCalculated [@@deriving refl] external ext_this_call_get_spelling : cxcursor -> clang_ext_thiscall_spelling = "clang_ext_ThisCall_getSpelling_wrapper" type clang_ext_transparentunion_spelling = | GNU_transparent_union | CXX11_gnu_transparent_union | C2x_gnu_transparent_union | SpellingNotCalculated [@@deriving refl] external ext_transparent_union_get_spelling : cxcursor -> clang_ext_transparentunion_spelling = "clang_ext_TransparentUnion_getSpelling_wrapper" type clang_ext_trivialabi_spelling = | GNU_trivial_abi | CXX11_clang_trivial_abi | SpellingNotCalculated [@@deriving refl] external ext_trivial_abi_get_spelling : cxcursor -> clang_ext_trivialabi_spelling = "clang_ext_TrivialABI_getSpelling_wrapper" type clang_ext_tryacquirecapability_spelling = | GNU_try_acquire_capability | CXX11_clang_try_acquire_capability | GNU_try_acquire_shared_capability | CXX11_clang_try_acquire_shared_capability | SpellingNotCalculated [@@deriving refl] external ext_try_acquire_capability_get_spelling : cxcursor -> clang_ext_tryacquirecapability_spelling = "clang_ext_TryAcquireCapability_getSpelling_wrapper" type clang_ext_typetagfordatatype_spelling = | GNU_type_tag_for_datatype | CXX11_clang_type_tag_for_datatype | C2x_clang_type_tag_for_datatype | SpellingNotCalculated [@@deriving refl] external ext_type_tag_for_datatype_get_spelling : cxcursor -> clang_ext_typetagfordatatype_spelling = "clang_ext_TypeTagForDatatype_getSpelling_wrapper" type clang_ext_typevisibility_spelling = | GNU_type_visibility | CXX11_clang_type_visibility | C2x_clang_type_visibility | SpellingNotCalculated [@@deriving refl] external ext_type_visibility_get_spelling : cxcursor -> clang_ext_typevisibility_spelling = "clang_ext_TypeVisibility_getSpelling_wrapper" type clang_ext_unavailable_spelling = | GNU_unavailable | CXX11_clang_unavailable | C2x_clang_unavailable | SpellingNotCalculated [@@deriving refl] external ext_unavailable_get_spelling : cxcursor -> clang_ext_unavailable_spelling = "clang_ext_Unavailable_getSpelling_wrapper" type clang_ext_uninitialized_spelling = | GNU_uninitialized | CXX11_clang_uninitialized | SpellingNotCalculated [@@deriving refl] external ext_uninitialized_get_spelling : cxcursor -> clang_ext_uninitialized_spelling = "clang_ext_Uninitialized_getSpelling_wrapper" type clang_ext_unlikely_spelling = | CXX11_unlikely | C2x_clang_unlikely | SpellingNotCalculated [@@deriving refl] external ext_unlikely_get_spelling : cxcursor -> clang_ext_unlikely_spelling = "clang_ext_Unlikely_getSpelling_wrapper" type clang_ext_unused_spelling = | CXX11_maybe_unused | GNU_unused | CXX11_gnu_unused | C2x_gnu_unused | C2x_maybe_unused | SpellingNotCalculated [@@deriving refl] external ext_unused_get_spelling : cxcursor -> clang_ext_unused_spelling = "clang_ext_Unused_getSpelling_wrapper" type clang_ext_usehandle_spelling = | GNU_use_handle | CXX11_clang_use_handle | C2x_clang_use_handle | SpellingNotCalculated [@@deriving refl] external ext_use_handle_get_spelling : cxcursor -> clang_ext_usehandle_spelling = "clang_ext_UseHandle_getSpelling_wrapper" type clang_ext_used_spelling = | GNU_used | CXX11_gnu_used | C2x_gnu_used | SpellingNotCalculated [@@deriving refl] external ext_used_get_spelling : cxcursor -> clang_ext_used_spelling = "clang_ext_Used_getSpelling_wrapper" type clang_ext_usingifexists_spelling = | GNU_using_if_exists | CXX11_clang_using_if_exists | SpellingNotCalculated [@@deriving refl] external ext_using_if_exists_get_spelling : cxcursor -> clang_ext_usingifexists_spelling = "clang_ext_UsingIfExists_getSpelling_wrapper" type clang_ext_uuid_spelling = | Declspec_uuid | Microsoft_uuid | SpellingNotCalculated [@@deriving refl] external ext_uuid_get_spelling : cxcursor -> clang_ext_uuid_spelling = "clang_ext_Uuid_getSpelling_wrapper" type clang_ext_vecreturn_spelling = | GNU_vecreturn | CXX11_clang_vecreturn | SpellingNotCalculated [@@deriving refl] external ext_vec_return_get_spelling : cxcursor -> clang_ext_vecreturn_spelling = "clang_ext_VecReturn_getSpelling_wrapper" type clang_ext_vectorcall_spelling = | GNU_vectorcall | CXX11_clang_vectorcall | C2x_clang_vectorcall | Keyword_vectorcall | SpellingNotCalculated [@@deriving refl] external ext_vector_call_get_spelling : cxcursor -> clang_ext_vectorcall_spelling = "clang_ext_VectorCall_getSpelling_wrapper" type clang_ext_visibility_spelling = | GNU_visibility | CXX11_gnu_visibility | C2x_gnu_visibility | SpellingNotCalculated [@@deriving refl] external ext_visibility_get_spelling : cxcursor -> clang_ext_visibility_spelling = "clang_ext_Visibility_getSpelling_wrapper" type clang_ext_warnunused_spelling = | GNU_warn_unused | CXX11_gnu_warn_unused | C2x_gnu_warn_unused | SpellingNotCalculated [@@deriving refl] external ext_warn_unused_get_spelling : cxcursor -> clang_ext_warnunused_spelling = "clang_ext_WarnUnused_getSpelling_wrapper" type clang_ext_warnunusedresult_spelling = | CXX11_nodiscard | C2x_nodiscard | CXX11_clang_warn_unused_result | GNU_warn_unused_result | CXX11_gnu_warn_unused_result | C2x_gnu_warn_unused_result | SpellingNotCalculated [@@deriving refl] external ext_warn_unused_result_get_spelling : cxcursor -> clang_ext_warnunusedresult_spelling = "clang_ext_WarnUnusedResult_getSpelling_wrapper" type clang_ext_weak_spelling = | GNU_weak | CXX11_gnu_weak | C2x_gnu_weak | SpellingNotCalculated [@@deriving refl] external ext_weak_get_spelling : cxcursor -> clang_ext_weak_spelling = "clang_ext_Weak_getSpelling_wrapper" type clang_ext_weakimport_spelling = | GNU_weak_import | CXX11_clang_weak_import | C2x_clang_weak_import | SpellingNotCalculated [@@deriving refl] external ext_weak_import_get_spelling : cxcursor -> clang_ext_weakimport_spelling = "clang_ext_WeakImport_getSpelling_wrapper" type clang_ext_weakref_spelling = | GNU_weakref | CXX11_gnu_weakref | C2x_gnu_weakref | SpellingNotCalculated [@@deriving refl] external ext_weak_ref_get_spelling : cxcursor -> clang_ext_weakref_spelling = "clang_ext_WeakRef_getSpelling_wrapper" type clang_ext_webassemblyexportname_spelling = | GNU_export_name | CXX11_clang_export_name | C2x_clang_export_name | SpellingNotCalculated [@@deriving refl] external ext_web_assembly_export_name_get_spelling : cxcursor -> clang_ext_webassemblyexportname_spelling = "clang_ext_WebAssemblyExportName_getSpelling_wrapper" type clang_ext_webassemblyimportmodule_spelling = | GNU_import_module | CXX11_clang_import_module | C2x_clang_import_module | SpellingNotCalculated [@@deriving refl] external ext_web_assembly_import_module_get_spelling : cxcursor -> clang_ext_webassemblyimportmodule_spelling = "clang_ext_WebAssemblyImportModule_getSpelling_wrapper" type clang_ext_webassemblyimportname_spelling = | GNU_import_name | CXX11_clang_import_name | C2x_clang_import_name | SpellingNotCalculated [@@deriving refl] external ext_web_assembly_import_name_get_spelling : cxcursor -> clang_ext_webassemblyimportname_spelling = "clang_ext_WebAssemblyImportName_getSpelling_wrapper" type clang_ext_x86forcealignargpointer_spelling = | GNU_force_align_arg_pointer | CXX11_gnu_force_align_arg_pointer | C2x_gnu_force_align_arg_pointer | SpellingNotCalculated [@@deriving refl] external ext_x86_force_align_arg_pointer_get_spelling : cxcursor -> clang_ext_x86forcealignargpointer_spelling = "clang_ext_X86ForceAlignArgPointer_getSpelling_wrapper" type clang_ext_xrayinstrument_spelling = | GNU_xray_always_instrument | CXX11_clang_xray_always_instrument | C2x_clang_xray_always_instrument | GNU_xray_never_instrument | CXX11_clang_xray_never_instrument | C2x_clang_xray_never_instrument | SpellingNotCalculated [@@deriving refl] external ext_xray_instrument_get_spelling : cxcursor -> clang_ext_xrayinstrument_spelling = "clang_ext_XRayInstrument_getSpelling_wrapper" type clang_ext_xraylogargs_spelling = | GNU_xray_log_args | CXX11_clang_xray_log_args | C2x_clang_xray_log_args | SpellingNotCalculated [@@deriving refl] external ext_xray_log_args_get_spelling : cxcursor -> clang_ext_xraylogargs_spelling = "clang_ext_XRayLogArgs_getSpelling_wrapper" type clang_ext_zerocallusedregs_spelling = | GNU_zero_call_used_regs | CXX11_gnu_zero_call_used_regs | C2x_gnu_zero_call_used_regs | SpellingNotCalculated [@@deriving refl] external ext_zero_call_used_regs_get_spelling : cxcursor -> clang_ext_zerocallusedregs_spelling = "clang_ext_ZeroCallUsedRegs_getSpelling_wrapper" external ext_ompdeclare_simd_decl_attr_get_uniforms_size : cxcursor -> int = "clang_ext_OMPDeclareSimdDeclAttr_getUniforms_Size_wrapper" type clang_ext_returntypestateattr_consumedstate = | Unknown | Consumed | Unconsumed [@@deriving refl] external ext_return_typestate_attr_get_state : cxcursor -> clang_ext_returntypestateattr_consumedstate = "clang_ext_ReturnTypestateAttr_getState_wrapper" external ext_attrs_get_aliasee_length : cxcursor -> int = "clang_ext_Attrs_getAliaseeLength_wrapper" external ext_obj_cruntime_name_attr_get_metadata_name : cxcursor -> string = "clang_ext_ObjCRuntimeNameAttr_getMetadataName_wrapper" type clang_ext_swifterrorattr_conventionkind = | None | NonNullError | NullResult | ZeroResult | NonZeroResult [@@deriving refl] external ext_swift_error_attr_get_convention : cxcursor -> clang_ext_swifterrorattr_conventionkind = "clang_ext_SwiftErrorAttr_getConvention_wrapper" type clang_ext_swiftasyncerrorattr_conventionkind = | None | NonNullError | ZeroArgument | NonZeroArgument [@@deriving refl] external ext_swift_async_error_attr_get_convention : cxcursor -> clang_ext_swiftasyncerrorattr_conventionkind = "clang_ext_SwiftAsyncErrorAttr_getConvention_wrapper" external ext_attrs_get_delayed_args : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_Attrs_getDelayedArgs_wrapper" external ext_ifunc_attr_get_resolver : cxcursor -> string = "clang_ext_IFuncAttr_getResolver_wrapper" external ext_patchable_function_entry_attr_get_offset : cxcursor -> int = "clang_ext_PatchableFunctionEntryAttr_getOffset_wrapper" external ext_assume_aligned_attr_get_offset : cxcursor -> cxcursor = "clang_ext_AssumeAlignedAttr_getOffset_wrapper" external ext_btftype_tag_attr_get_btftype_tag_length : cxcursor -> int = "clang_ext_BTFTypeTagAttr_getBTFTypeTagLength_wrapper" external ext_web_assembly_import_name_attr_get_import_name_length : cxcursor -> int = "clang_ext_WebAssemblyImportNameAttr_getImportNameLength_wrapper" external ext_sentinel_attr_get_sentinel : cxcursor -> int = "clang_ext_SentinelAttr_getSentinel_wrapper" external ext_attrs_get_success_value : cxcursor -> cxcursor = "clang_ext_Attrs_getSuccessValue_wrapper" external ext_attrs_get_cpus_size : cxcursor -> int = "clang_ext_Attrs_getCpus_Size_wrapper" external ext_tlsmodel_attr_get_model_length : cxcursor -> int = "clang_ext_TLSModelAttr_getModelLength_wrapper" type clang_ext_paramtypestateattr_consumedstate = | Unknown | Consumed | Unconsumed [@@deriving refl] external ext_param_typestate_attr_get_param_state : cxcursor -> clang_ext_paramtypestateattr_consumedstate = "clang_ext_ParamTypestateAttr_getParamState_wrapper" external ext_external_source_symbol_attr_get_generated_declaration : cxcursor -> bool = "clang_ext_ExternalSourceSymbolAttr_getGeneratedDeclaration_wrapper" external ext_suppress_attr_get_diagnostic_identifiers : cxcursor -> (string -> unit) -> unit = "clang_ext_SuppressAttr_getDiagnosticIdentifiers_wrapper" external ext_attrs_get_deref_type : cxcursor -> clang_ext_typeloc = "clang_ext_Attrs_getDerefType_wrapper" type clang_ext_functionreturnthunksattr_kind = | Keep | Extern [@@deriving refl] external ext_function_return_thunks_attr_get_thunk_type : cxcursor -> clang_ext_functionreturnthunksattr_kind = "clang_ext_FunctionReturnThunksAttr_getThunkType_wrapper" external ext_ompdeclare_variant_attr_get_adjust_args_need_device_ptr_size : cxcursor -> int = "clang_ext_OMPDeclareVariantAttr_getAdjustArgsNeedDevicePtr_Size_wrapper" external ext_type_tag_for_datatype_attr_get_matching_ctype : cxcursor -> clang_ext_typeloc = "clang_ext_TypeTagForDatatypeAttr_getMatchingCType_wrapper" external ext_attrs_get_annotation_length : cxcursor -> int = "clang_ext_Attrs_getAnnotationLength_wrapper" external ext_layout_version_attr_get_version : cxcursor -> int = "clang_ext_LayoutVersionAttr_getVersion_wrapper" external ext_sentinel_attr_get_null_pos : cxcursor -> int = "clang_ext_SentinelAttr_getNullPos_wrapper" external ext_ompdeclare_simd_decl_attr_get_aligneds : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_OMPDeclareSimdDeclAttr_getAligneds_wrapper" external ext_swift_async_attr_get_completion_handler_index : cxcursor -> int = "clang_ext_SwiftAsyncAttr_getCompletionHandlerIndex_wrapper" external ext_attrs_get_args_size : cxcursor -> int = "clang_ext_Attrs_getArgs_Size_wrapper" external ext_cudalaunch_bounds_attr_get_min_blocks : cxcursor -> cxcursor = "clang_ext_CUDALaunchBoundsAttr_getMinBlocks_wrapper" external ext_btfdecl_tag_attr_get_btfdecl_tag_length : cxcursor -> int = "clang_ext_BTFDeclTagAttr_getBTFDeclTagLength_wrapper" external ext_swift_bridge_attr_get_swift_type_length : cxcursor -> int = "clang_ext_SwiftBridgeAttr_getSwiftTypeLength_wrapper" external ext_external_source_symbol_attr_get_defined_in_length : cxcursor -> int = "clang_ext_ExternalSourceSymbolAttr_getDefinedInLength_wrapper" type clang_ext_hlslshaderattr_shadertype = | Pixel | Vertex | Geometry | Hull | Domain | Compute | RayGeneration | Intersection | AnyHit | ClosestHit | Miss | Callable | Mesh | Amplification [@@deriving refl] external ext_hlslshader_attr_get_type : cxcursor -> clang_ext_hlslshaderattr_shadertype = "clang_ext_HLSLShaderAttr_getType_wrapper" external ext_format_attr_get_type : cxcursor -> string = "clang_ext_FormatAttr_getType_wrapper" external ext_pass_object_size_attr_get_type : cxcursor -> int = "clang_ext_PassObjectSizeAttr_getType_wrapper" type clang_ext_blocksattr_blocktype = | ByRef [@@deriving refl] external ext_blocks_attr_get_type : cxcursor -> clang_ext_blocksattr_blocktype = "clang_ext_BlocksAttr_getType_wrapper" external ext_assumption_attr_get_assumption_length : cxcursor -> int = "clang_ext_AssumptionAttr_getAssumptionLength_wrapper" external ext_asm_label_attr_get_label : cxcursor -> string = "clang_ext_AsmLabelAttr_getLabel_wrapper" external ext_swift_attr_attr_get_attribute : cxcursor -> string = "clang_ext_SwiftAttrAttr_getAttribute_wrapper" external ext_availability_attr_get_platform : cxcursor -> string = "clang_ext_AvailabilityAttr_getPlatform_wrapper" external ext_attrs_get_max : cxcursor -> cxcursor = "clang_ext_Attrs_getMax_wrapper" external ext_target_attr_get_features_str : cxcursor -> string = "clang_ext_TargetAttr_getFeaturesStr_wrapper" external ext_callable_when_attr_get_callable_states_size : cxcursor -> int = "clang_ext_CallableWhenAttr_getCallableStates_Size_wrapper" type clang_ext_testtypestateattr_consumedstate = | Consumed | Unconsumed [@@deriving refl] external ext_test_typestate_attr_get_test_state : cxcursor -> clang_ext_testtypestateattr_consumedstate = "clang_ext_TestTypestateAttr_getTestState_wrapper" external ext_ompcapture_kind_attr_get_capture_kind_val : cxcursor -> int = "clang_ext_OMPCaptureKindAttr_getCaptureKindVal_wrapper" external ext_init_priority_attr_get_priority : cxcursor -> int = "clang_ext_InitPriorityAttr_getPriority_wrapper" external ext_attrs_get_priority : cxcursor -> int = "clang_ext_Attrs_getPriority_wrapper" type clang_ext_ompdeclaretargetdeclattr_maptypety = | To | Link [@@deriving refl] external ext_ompdeclare_target_decl_attr_get_map_type : cxcursor -> clang_ext_ompdeclaretargetdeclattr_maptypety = "clang_ext_OMPDeclareTargetDeclAttr_getMapType_wrapper" external ext_attrs_get_ydim : cxcursor -> int = "clang_ext_Attrs_getYDim_wrapper" external ext_cleanup_attr_get_function_decl : cxcursor -> clang_ext_declarationname = "clang_ext_CleanupAttr_getFunctionDecl_wrapper" type clang_ext_versiontuple = { major: int ; minor: int ; subminor: int ; build: int }[@@deriving refl] external ext_availability_attr_get_obsoleted : cxcursor -> clang_ext_versiontuple = "clang_ext_AvailabilityAttr_getObsoleted_wrapper" external ext_init_seg_attr_get_section : cxcursor -> string = "clang_ext_InitSegAttr_getSection_wrapper" external ext_btfdecl_tag_attr_get_btfdecl_tag : cxcursor -> string = "clang_ext_BTFDeclTagAttr_getBTFDeclTag_wrapper" external ext_external_source_symbol_attr_get_defined_in : cxcursor -> string = "clang_ext_ExternalSourceSymbolAttr_getDefinedIn_wrapper" external ext_alloc_size_attr_get_num_elems_param : cxcursor -> int = "clang_ext_AllocSizeAttr_getNumElemsParam_wrapper" external ext_ifunc_attr_get_resolver_length : cxcursor -> int = "clang_ext_IFuncAttr_getResolverLength_wrapper" external ext_asm_label_attr_get_label_length : cxcursor -> int = "clang_ext_AsmLabelAttr_getLabelLength_wrapper" external ext_abi_tag_attr_get_tags_size : cxcursor -> int = "clang_ext_AbiTagAttr_getTags_Size_wrapper" external ext_cudalaunch_bounds_attr_get_max_threads : cxcursor -> cxcursor = "clang_ext_CUDALaunchBoundsAttr_getMaxThreads_wrapper" external ext_attrs_get_builtin_name : cxcursor -> string = "clang_ext_Attrs_getBuiltinName_wrapper" external ext_web_assembly_import_module_attr_get_import_module : cxcursor -> string = "clang_ext_WebAssemblyImportModuleAttr_getImportModule_wrapper" type clang_ext_swiftnewtypeattr_newtypekind = | Struct | Enum [@@deriving refl] external ext_swift_new_type_attr_get_newtype_kind : cxcursor -> clang_ext_swiftnewtypeattr_newtypekind = "clang_ext_SwiftNewTypeAttr_getNewtypeKind_wrapper" external ext_hlslnum_threads_attr_get_z : cxcursor -> int = "clang_ext_HLSLNumThreadsAttr_getZ_wrapper" external ext_no_sanitize_attr_get_sanitizers_size : cxcursor -> int = "clang_ext_NoSanitizeAttr_getSanitizers_Size_wrapper" external ext_callback_attr_get_encoding_size : cxcursor -> int = "clang_ext_CallbackAttr_getEncoding_Size_wrapper" external ext_attrs_get_xdim : cxcursor -> int = "clang_ext_Attrs_getXDim_wrapper" external ext_uuid_attr_get_guid_decl : cxcursor -> cxcursor = "clang_ext_UuidAttr_getGuidDecl_wrapper" external ext_attrs_get_aliasee : cxcursor -> string = "clang_ext_Attrs_getAliasee_wrapper" external ext_attrs_get_handle_type : cxcursor -> string = "clang_ext_Attrs_getHandleType_wrapper" external ext_web_assembly_import_module_attr_get_import_module_length : cxcursor -> int = "clang_ext_WebAssemblyImportModuleAttr_getImportModuleLength_wrapper" external ext_ompdeclare_simd_decl_attr_get_linears : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_OMPDeclareSimdDeclAttr_getLinears_wrapper" external ext_availability_attr_get_deprecated : cxcursor -> clang_ext_versiontuple = "clang_ext_AvailabilityAttr_getDeprecated_wrapper" external ext_preferred_name_attr_get_typedef_type : cxcursor -> clang_ext_typeloc = "clang_ext_PreferredNameAttr_getTypedefType_wrapper" external ext_diagnose_as_builtin_attr_get_arg_indices : cxcursor -> (int -> unit) -> unit = "clang_ext_DiagnoseAsBuiltinAttr_getArgIndices_wrapper" external ext_target_clones_attr_get_features_strs_size : cxcursor -> int = "clang_ext_TargetClonesAttr_getFeaturesStrs_Size_wrapper" external ext_error_attr_get_user_diagnostic_length : cxcursor -> int = "clang_ext_ErrorAttr_getUserDiagnosticLength_wrapper" external ext_web_assembly_export_name_attr_get_export_name : cxcursor -> string = "clang_ext_WebAssemblyExportNameAttr_getExportName_wrapper" external ext_argument_with_type_tag_attr_get_is_pointer : cxcursor -> bool = "clang_ext_ArgumentWithTypeTagAttr_getIsPointer_wrapper" external ext_uuid_attr_get_guid_length : cxcursor -> int = "clang_ext_UuidAttr_getGuidLength_wrapper" external ext_ompdeclare_simd_decl_attr_get_aligneds_size : cxcursor -> int = "clang_ext_OMPDeclareSimdDeclAttr_getAligneds_Size_wrapper" external ext_attrs_get_message_length : cxcursor -> int = "clang_ext_Attrs_getMessageLength_wrapper" type clang_ext_pcsattr_pcstype = | AAPCS | AAPCS_VFP [@@deriving refl] external ext_pcs_attr_get_pcs : cxcursor -> clang_ext_pcsattr_pcstype = "clang_ext_PcsAttr_getPCS_wrapper" external ext_callback_attr_get_encoding : cxcursor -> (int -> unit) -> unit = "clang_ext_CallbackAttr_getEncoding_wrapper" external ext_attrs_get_argument_kind : cxcursor -> string = "clang_ext_Attrs_getArgumentKind_wrapper" external ext_availability_attr_get_unavailable : cxcursor -> bool = "clang_ext_AvailabilityAttr_getUnavailable_wrapper" type clang_ext_omptraitinfo external ext_ompdeclare_variant_attr_get_trait_infos : cxcursor -> clang_ext_omptraitinfo = "clang_ext_OMPDeclareVariantAttr_getTraitInfos_wrapper" external ext_ompallocate_decl_attr_get_allocator : cxcursor -> cxcursor = "clang_ext_OMPAllocateDeclAttr_getAllocator_wrapper" external ext_hlslnum_threads_attr_get_y : cxcursor -> int = "clang_ext_HLSLNumThreadsAttr_getY_wrapper" external ext_attrs_get_annotation : cxcursor -> string = "clang_ext_Attrs_getAnnotation_wrapper" external ext_ompdeclare_variant_attr_get_variant_func_ref : cxcursor -> cxcursor = "clang_ext_OMPDeclareVariantAttr_getVariantFuncRef_wrapper" external ext_no_builtin_attr_get_builtin_names_size : cxcursor -> int = "clang_ext_NoBuiltinAttr_getBuiltinNames_Size_wrapper" external ext_target_clones_attr_get_features_strs : cxcursor -> (string -> unit) -> unit = "clang_ext_TargetClonesAttr_getFeaturesStrs_wrapper" external ext_attrs_get_replacement : cxcursor -> string = "clang_ext_Attrs_getReplacement_wrapper" external ext_amdgpunum_sgprattr_get_num_sgpr : cxcursor -> int = "clang_ext_AMDGPUNumSGPRAttr_getNumSGPR_wrapper" external ext_obj_cbridge_related_attr_get_instance_method : cxcursor -> string = "clang_ext_ObjCBridgeRelatedAttr_getInstanceMethod_wrapper" external ext_ompdeclare_variant_attr_get_adjust_args_need_device_ptr : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_OMPDeclareVariantAttr_getAdjustArgsNeedDevicePtr_wrapper" external ext_ompdeclare_simd_decl_attr_get_simdlen : cxcursor -> cxcursor = "clang_ext_OMPDeclareSimdDeclAttr_getSimdlen_wrapper" external ext_target_attr_get_features_str_length : cxcursor -> int = "clang_ext_TargetAttr_getFeaturesStrLength_wrapper" external ext_aligned_attr_get_alignment_expr : cxcursor -> cxcursor = "clang_ext_AlignedAttr_getAlignmentExpr_wrapper" type clang_ext_zerocallusedregsattr_zerocallusedregskind = | Skip | UsedGPRArg | UsedGPR | UsedArg | Used | AllGPRArg | AllGPR | AllArg | All [@@deriving refl] external ext_zero_call_used_regs_attr_get_zero_call_used_regs : cxcursor -> clang_ext_zerocallusedregsattr_zerocallusedregskind = "clang_ext_ZeroCallUsedRegsAttr_getZeroCallUsedRegs_wrapper" external ext_ompdeclare_simd_decl_attr_get_steps : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_OMPDeclareSimdDeclAttr_getSteps_wrapper" external ext_tlsmodel_attr_get_model : cxcursor -> string = "clang_ext_TLSModelAttr_getModel_wrapper" external ext_ompdeclare_simd_decl_attr_get_modifiers : cxcursor -> (int -> unit) -> unit = "clang_ext_OMPDeclareSimdDeclAttr_getModifiers_wrapper" external ext_format_attr_get_first_arg : cxcursor -> int = "clang_ext_FormatAttr_getFirstArg_wrapper" external ext_amdgpunum_vgprattr_get_num_vgpr : cxcursor -> int = "clang_ext_AMDGPUNumVGPRAttr_getNumVGPR_wrapper" type clang_ext_mipsinterruptattr_interrupttype = | Sw0 | Sw1 | Hw0 | Hw1 | Hw2 | Hw3 | Hw4 | Hw5 | Eic [@@deriving refl] external ext_mips_interrupt_attr_get_interrupt : cxcursor -> clang_ext_mipsinterruptattr_interrupttype = "clang_ext_MipsInterruptAttr_getInterrupt_wrapper" type clang_ext_arminterruptattr_interrupttype = | IRQ | FIQ | SWI | ABORT | UNDEF | Generic [@@deriving refl] external ext_arminterrupt_attr_get_interrupt : cxcursor -> clang_ext_arminterruptattr_interrupttype = "clang_ext_ARMInterruptAttr_getInterrupt_wrapper" type clang_ext_riscvinterruptattr_interrupttype = | User | Supervisor | Machine [@@deriving refl] external ext_riscvinterrupt_attr_get_interrupt : cxcursor -> clang_ext_riscvinterruptattr_interrupttype = "clang_ext_RISCVInterruptAttr_getInterrupt_wrapper" external ext_attrs_get_min : cxcursor -> cxcursor = "clang_ext_Attrs_getMin_wrapper" type clang_ext_enumextensibilityattr_kind = | Closed | Open [@@deriving refl] external ext_enum_extensibility_attr_get_extensibility : cxcursor -> clang_ext_enumextensibilityattr_kind = "clang_ext_EnumExtensibilityAttr_getExtensibility_wrapper" external ext_alloc_align_attr_get_param_index : cxcursor -> int = "clang_ext_AllocAlignAttr_getParamIndex_wrapper" external ext_diagnose_as_builtin_attr_get_arg_indices_size : cxcursor -> int = "clang_ext_DiagnoseAsBuiltinAttr_getArgIndices_Size_wrapper" external ext_availability_attr_get_introduced : cxcursor -> clang_ext_versiontuple = "clang_ext_AvailabilityAttr_getIntroduced_wrapper" external ext_max_field_alignment_attr_get_alignment : cxcursor -> int = "clang_ext_MaxFieldAlignmentAttr_getAlignment_wrapper" external ext_attrs_get_alignment : cxcursor -> cxcursor = "clang_ext_Attrs_getAlignment_wrapper" external ext_address_space_attr_get_address_space : cxcursor -> int = "clang_ext_AddressSpaceAttr_getAddressSpace_wrapper" external ext_mode_attr_get_mode : cxcursor -> string = "clang_ext_ModeAttr_getMode_wrapper" external ext_attrs_get_arg : cxcursor -> cxcursor = "clang_ext_Attrs_getArg_wrapper" external ext_attrs_get_cpus : cxcursor -> (string -> unit) -> unit = "clang_ext_Attrs_getCpus_wrapper" external ext_btftype_tag_attr_get_btftype_tag : cxcursor -> string = "clang_ext_BTFTypeTagAttr_getBTFTypeTag_wrapper" external ext_open_clintel_reqd_sub_group_size_attr_get_sub_group_size : cxcursor -> int = "clang_ext_OpenCLIntelReqdSubGroupSizeAttr_getSubGroupSize_wrapper" external ext_argument_with_type_tag_attr_get_argument_idx : cxcursor -> int = "clang_ext_ArgumentWithTypeTagAttr_getArgumentIdx_wrapper" external ext_availability_attr_get_strict : cxcursor -> bool = "clang_ext_AvailabilityAttr_getStrict_wrapper" type clang_ext_cfguardattr_guardarg = | Nocf [@@deriving refl] external ext_cfguard_attr_get_guard : cxcursor -> clang_ext_cfguardattr_guardarg = "clang_ext_CFGuardAttr_getGuard_wrapper" external ext_ownership_attr_get_module : cxcursor -> string = "clang_ext_OwnershipAttr_getModule_wrapper" external ext_min_vector_width_attr_get_vector_width : cxcursor -> int = "clang_ext_MinVectorWidthAttr_getVectorWidth_wrapper" external ext_type_tag_for_datatype_attr_get_layout_compatible : cxcursor -> bool = "clang_ext_TypeTagForDatatypeAttr_getLayoutCompatible_wrapper" external ext_ompdeclare_variant_attr_get_adjust_args_nothing : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_OMPDeclareVariantAttr_getAdjustArgsNothing_wrapper" external ext_init_seg_attr_get_section_length : cxcursor -> int = "clang_ext_InitSegAttr_getSectionLength_wrapper" external ext_vec_type_hint_attr_get_type_hint : cxcursor -> clang_ext_typeloc = "clang_ext_VecTypeHintAttr_getTypeHint_wrapper" external ext_attrs_get_tcbname_length : cxcursor -> int = "clang_ext_Attrs_getTCBNameLength_wrapper" external ext_ompdeclare_variant_attr_get_adjust_args_nothing_size : cxcursor -> int = "clang_ext_OMPDeclareVariantAttr_getAdjustArgsNothing_Size_wrapper" external ext_external_source_symbol_attr_get_language_length : cxcursor -> int = "clang_ext_ExternalSourceSymbolAttr_getLanguageLength_wrapper" external ext_obj_cruntime_name_attr_get_metadata_name_length : cxcursor -> int = "clang_ext_ObjCRuntimeNameAttr_getMetadataNameLength_wrapper" type clang_ext_consumableattr_consumedstate = | Unknown | Consumed | Unconsumed [@@deriving refl] external ext_consumable_attr_get_default_state : cxcursor -> clang_ext_consumableattr_consumedstate = "clang_ext_ConsumableAttr_getDefaultState_wrapper" external ext_builtin_attr_get_id : cxcursor -> int = "clang_ext_BuiltinAttr_getID_wrapper" external ext_assumption_attr_get_assumption : cxcursor -> string = "clang_ext_AssumptionAttr_getAssumption_wrapper" external ext_attrs_get_bridged_type : cxcursor -> string = "clang_ext_Attrs_getBridgedType_wrapper" external ext_ompdeclare_simd_decl_attr_get_modifiers_size : cxcursor -> int = "clang_ext_OMPDeclareSimdDeclAttr_getModifiers_Size_wrapper" external ext_swift_attr_attr_get_attribute_length : cxcursor -> int = "clang_ext_SwiftAttrAttr_getAttributeLength_wrapper" type clang_ext_settypestateattr_consumedstate = | Unknown | Consumed | Unconsumed [@@deriving refl] external ext_set_typestate_attr_get_new_state : cxcursor -> clang_ext_settypestateattr_consumedstate = "clang_ext_SetTypestateAttr_getNewState_wrapper" external ext_obj_cbridge_related_attr_get_class_method : cxcursor -> string = "clang_ext_ObjCBridgeRelatedAttr_getClassMethod_wrapper" external ext_ompreferenced_var_attr_get_ref : cxcursor -> cxcursor = "clang_ext_OMPReferencedVarAttr_getRef_wrapper" external ext_alloc_size_attr_get_elem_size_param : cxcursor -> int = "clang_ext_AllocSizeAttr_getElemSizeParam_wrapper" type clang_ext_visibilityattr_visibilitytype = | Default | Hidden | Protected [@@deriving refl] external ext_visibility_attr_get_visibility : cxcursor -> clang_ext_visibilityattr_visibilitytype = "clang_ext_VisibilityAttr_getVisibility_wrapper" type clang_ext_typevisibilityattr_visibilitytype = | Default | Hidden | Protected [@@deriving refl] external ext_type_visibility_attr_get_visibility : cxcursor -> clang_ext_typevisibilityattr_visibilitytype = "clang_ext_TypeVisibilityAttr_getVisibility_wrapper" external ext_external_source_symbol_attr_get_language : cxcursor -> string = "clang_ext_ExternalSourceSymbolAttr_getLanguage_wrapper" external ext_attrs_get_replacement_length : cxcursor -> int = "clang_ext_Attrs_getReplacementLength_wrapper" external ext_ompdeclare_simd_decl_attr_get_alignments_size : cxcursor -> int = "clang_ext_OMPDeclareSimdDeclAttr_getAlignments_Size_wrapper" external ext_ompdeclare_simd_decl_attr_get_linears_size : cxcursor -> int = "clang_ext_OMPDeclareSimdDeclAttr_getLinears_Size_wrapper" external ext_nserror_domain_attr_get_error_domain : cxcursor -> cxcursor = "clang_ext_NSErrorDomainAttr_getErrorDomain_wrapper" external ext_error_attr_get_user_diagnostic : cxcursor -> string = "clang_ext_ErrorAttr_getUserDiagnostic_wrapper" external ext_xray_log_args_attr_get_argument_count : cxcursor -> int = "clang_ext_XRayLogArgsAttr_getArgumentCount_wrapper" external ext_attrs_get_message : cxcursor -> string = "clang_ext_Attrs_getMessage_wrapper" external ext_argument_with_type_tag_attr_get_type_tag_idx : cxcursor -> int = "clang_ext_ArgumentWithTypeTagAttr_getTypeTagIdx_wrapper" external ext_uuid_attr_get_guid : cxcursor -> string = "clang_ext_UuidAttr_getGuid_wrapper" external ext_attrs_get_zdim : cxcursor -> int = "clang_ext_Attrs_getZDim_wrapper" external ext_attrs_get_handle_type_length : cxcursor -> int = "clang_ext_Attrs_getHandleTypeLength_wrapper" external ext_ompdeclare_simd_decl_attr_get_uniforms : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_OMPDeclareSimdDeclAttr_getUniforms_wrapper" type clang_ext_loophintattr_optiontype = | Vectorize | VectorizeWidth | Interleave | InterleaveCount | Unroll | UnrollCount | UnrollAndJam | UnrollAndJamCount | PipelineDisabled | PipelineInitiationInterval | Distribute | VectorizePredicate [@@deriving refl] external ext_loop_hint_attr_get_option : cxcursor -> clang_ext_loophintattr_optiontype = "clang_ext_LoopHintAttr_getOption_wrapper" external ext_obj_cbridge_related_attr_get_related_class : cxcursor -> string = "clang_ext_ObjCBridgeRelatedAttr_getRelatedClass_wrapper" external ext_web_assembly_import_name_attr_get_import_name : cxcursor -> string = "clang_ext_WebAssemblyImportNameAttr_getImportName_wrapper" external ext_no_sanitize_attr_get_sanitizers : cxcursor -> (string -> unit) -> unit = "clang_ext_NoSanitizeAttr_getSanitizers_wrapper" type clang_ext_callablewhenattr_consumedstate = | Unknown | Consumed | Unconsumed [@@deriving refl] external ext_callable_when_attr_get_callable_states : cxcursor -> (clang_ext_callablewhenattr_consumedstate -> unit) -> unit = "clang_ext_CallableWhenAttr_getCallableStates_wrapper" type clang_ext_ompdeclaresimddeclattr_branchstatety = | Undefined | Inbranch | Notinbranch [@@deriving refl] external ext_ompdeclare_simd_decl_attr_get_branch_state : cxcursor -> clang_ext_ompdeclaresimddeclattr_branchstatety = "clang_ext_OMPDeclareSimdDeclAttr_getBranchState_wrapper" external ext_asm_label_attr_get_is_literal_label : cxcursor -> bool = "clang_ext_AsmLabelAttr_getIsLiteralLabel_wrapper" external ext_swift_bridge_attr_get_swift_type : cxcursor -> string = "clang_ext_SwiftBridgeAttr_getSwiftType_wrapper" external ext_format_arg_attr_get_format_idx : cxcursor -> int = "clang_ext_FormatArgAttr_getFormatIdx_wrapper" external ext_format_attr_get_format_idx : cxcursor -> int = "clang_ext_FormatAttr_getFormatIdx_wrapper" external ext_type_tag_for_datatype_attr_get_must_be_null : cxcursor -> bool = "clang_ext_TypeTagForDatatypeAttr_getMustBeNull_wrapper" type clang_ext_ompallocatedeclattr_allocatortypety = | OMPNullMemAlloc | OMPDefaultMemAlloc | OMPLargeCapMemAlloc | OMPConstMemAlloc | OMPHighBWMemAlloc | OMPLowLatMemAlloc | OMPCGroupMemAlloc | OMPPTeamMemAlloc | OMPThreadMemAlloc | OMPUserDefinedMemAlloc [@@deriving refl] external ext_ompallocate_decl_attr_get_allocator_type : cxcursor -> clang_ext_ompallocatedeclattr_allocatortypety = "clang_ext_OMPAllocateDeclAttr_getAllocatorType_wrapper" external ext_attrs_get_name_length : cxcursor -> int = "clang_ext_Attrs_getNameLength_wrapper" external ext_attrs_get_name : cxcursor -> string = "clang_ext_Attrs_getName_wrapper" external ext_suppress_attr_get_diagnostic_identifiers_size : cxcursor -> int = "clang_ext_SuppressAttr_getDiagnosticIdentifiers_Size_wrapper" external ext_ompdeclare_simd_decl_attr_get_steps_size : cxcursor -> int = "clang_ext_OMPDeclareSimdDeclAttr_getSteps_Size_wrapper" external ext_web_assembly_export_name_attr_get_export_name_length : cxcursor -> int = "clang_ext_WebAssemblyExportNameAttr_getExportNameLength_wrapper" external ext_ompdeclare_simd_decl_attr_get_alignments : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_OMPDeclareSimdDeclAttr_getAlignments_wrapper" external ext_msvtor_disp_attr_get_vdm : cxcursor -> int = "clang_ext_MSVtorDispAttr_getVdm_wrapper" external ext_attrs_get_cond : cxcursor -> cxcursor = "clang_ext_Attrs_getCond_wrapper" external ext_iboutlet_collection_attr_get_interface : cxcursor -> clang_ext_typeloc = "clang_ext_IBOutletCollectionAttr_getInterface_wrapper" type clang_ext_objcmethodfamilyattr_familykind = | None | Alloc | Copy | Init | MutableCopy | New [@@deriving refl] external ext_obj_cmethod_family_attr_get_family : cxcursor -> clang_ext_objcmethodfamilyattr_familykind = "clang_ext_ObjCMethodFamilyAttr_getFamily_wrapper" external ext_swift_async_error_attr_get_handler_param_idx : cxcursor -> int = "clang_ext_SwiftAsyncErrorAttr_getHandlerParamIdx_wrapper" type clang_ext_swiftasyncattr_kind = | None | SwiftPrivate | NotSwiftPrivate [@@deriving refl] external ext_swift_async_attr_get_kind : cxcursor -> clang_ext_swiftasyncattr_kind = "clang_ext_SwiftAsyncAttr_getKind_wrapper" external ext_attrs_get_kind : cxcursor -> string = "clang_ext_Attrs_getKind_wrapper" external ext_hlslnum_threads_attr_get_x : cxcursor -> int = "clang_ext_HLSLNumThreadsAttr_getX_wrapper" external ext_patchable_function_entry_attr_get_count : cxcursor -> int = "clang_ext_PatchableFunctionEntryAttr_getCount_wrapper" external ext_diagnose_as_builtin_attr_get_function : cxcursor -> clang_ext_declarationname = "clang_ext_DiagnoseAsBuiltinAttr_getFunction_wrapper" external ext_attrs_get_delayed_args_size : cxcursor -> int = "clang_ext_Attrs_getDelayedArgs_Size_wrapper" external ext_abi_tag_attr_get_tags : cxcursor -> (string -> unit) -> unit = "clang_ext_AbiTagAttr_getTags_wrapper" external ext_attrs_get_number : cxcursor -> int = "clang_ext_Attrs_getNumber_wrapper" external ext_attrs_get_tcbname : cxcursor -> string = "clang_ext_Attrs_getTCBName_wrapper" external ext_open_clunroll_hint_attr_get_unroll_hint : cxcursor -> int = "clang_ext_OpenCLUnrollHintAttr_getUnrollHint_wrapper" external ext_no_builtin_attr_get_builtin_names : cxcursor -> (string -> unit) -> unit = "clang_ext_NoBuiltinAttr_getBuiltinNames_wrapper" external ext_msinheritance_attr_get_best_case : cxcursor -> bool = "clang_ext_MSInheritanceAttr_getBestCase_wrapper" external ext_non_null_attr_get_args : cxcursor -> (int -> unit) -> unit = "clang_ext_NonNullAttr_getArgs_wrapper" external ext_acquire_capability_attr_get_args : cxcursor -> (cxcursor -> unit) -> unit = "clang_ext_AcquireCapabilityAttr_getArgs_wrapper"
(* This file is auto-generated by stubgen tool. It should not be modified by hand and it should not be versioned (except by continuous integration on the dedicated bootstrap branch). *)
Tree_sitter_error.ml
(* Simple utilities to work on the types defined in Tree_sitter_output.atd. *) open Printf open Tree_sitter_bindings.Tree_sitter_output_t type error_class = { parent: node_kind; left_sibling: node_kind option; first_child: node_kind option; } type t = { kind: Tree_sitter_error_t.error_kind; msg: string; file: Src_file.info; start_pos: position; end_pos: position; substring: string; snippet: Snippet.t; error_class: error_class option; } exception Error of t let string_of_node_kind (x : node_kind) = match x with | Literal s -> sprintf "%S" s | Name s -> s | Error -> "ERROR" let string_of_node (x : node) = let node_kind = string_of_node_kind x.kind in match x.children with | None -> sprintf "node type: %s" node_kind | Some children -> sprintf "\ node type: %s children: [ %s]" node_kind (List.map (fun (x : node) -> sprintf " %s\n" (string_of_node_kind x.kind)) children |> String.concat "") let string_of_error_class (x : error_class) = let parent = sprintf "parent: %s" (string_of_node_kind x.parent) in let left_sibling = match x.left_sibling with | None -> ", no left sibling" | Some x -> sprintf ", left sibling: %s" (string_of_node_kind x) in let first_child = match x.first_child with | None -> ", no children" | Some x -> sprintf ", first child: %s" (string_of_node_kind x) in parent ^ left_sibling ^ first_child let rec find_left_sibling (children : node list) target_node = match children with | left :: node :: _ when node == target_node -> Some left.kind | node :: _ when node == target_node -> None | _ :: xs -> find_left_sibling xs target_node | [] -> assert false (* target_node must exist in 'children' list *) let error_class_of_node ~(parent : node option) node = match parent with | None -> None | Some { children = None; _ } -> assert false (* parent must have children *) | Some { kind; children = Some children; _ } -> let left_sibling = find_left_sibling children node in let first_child = match node.children with | None | Some [] -> None | Some (x :: _) -> Some x.kind in Some { parent = kind; left_sibling; first_child; } let create kind src ?parent node msg = let msg = sprintf "\ %s %s" (string_of_node node) msg in let start_pos = node.start_pos in let end_pos = node.end_pos in { kind; msg; file = Src_file.info src; start_pos; end_pos; substring = Src_file.get_region src start_pos end_pos; snippet = Snippet.extract src ~start_pos ~end_pos; error_class = error_class_of_node ~parent node; } let fail kind src node msg = raise (Error (create kind src node msg)) let external_error src node msg = fail External src node msg let internal_error src node msg = fail Internal src node msg let string_of_file_info (src_info : Src_file.info) = match src_info.path with | Some path -> sprintf "File %s" path | None -> src_info.name (* Take an error message and prepend the location information, in a human-readable and possibly computer-readable format (TODO check with emacs etc.) *) let to_string ?(color = false) (err : t) = let start = err.start_pos in let end_ = err.end_pos in let loc = let src_name = string_of_file_info err.file in if start.row = end_.row then sprintf "%s, line %i, characters %i-%i:" src_name (start.row + 1) start.column end_.column else sprintf "%s, line %i, character %i to line %i, character %i:" src_name (start.row + 1) start.column (end_.row + 1) end_.column in let error_class = match err.error_class with | None -> "" | Some x -> sprintf "%s\n" (string_of_error_class x) in sprintf "\ %s %s%s%s" loc (Snippet.format ~color err.snippet) error_class err.msg let to_json_error (x : t): Tree_sitter_error_t.json_error = { kind = x.kind; msg = x.msg; file = x.file.name; start_pos = x.start_pos; end_pos = x.end_pos; substring = x.substring; error_class = Option.map string_of_error_class x.error_class; } let log_json_errors out_file errors = let oc = open_out_gen [Open_creat; Open_text; Open_append] 0o666 out_file in Fun.protect ~finally:(fun () -> close_out_noerr oc) (fun () -> List.iter (fun err -> let simplified_err = to_json_error err in let json = Tree_sitter_error_j.string_of_json_error simplified_err in fprintf oc "%s\n" json ) errors )
(* Simple utilities to work on the types defined in Tree_sitter_output.atd. *)
filename.mli
val current_dir_name : string val parent_dir_name : string val concat : string -> string -> string val is_relative : string -> bool val is_implicit : string -> bool val check_suffix : string -> string -> bool val chop_suffix : string -> string -> string val chop_extension : string -> string val basename : string -> string val dirname : string -> string val temp_file : string -> string -> string val open_temp_file : ?mode:open_flag list -> string -> string -> (string * out_channel) val quote : string -> string
tezos_protocol.ml
open Internal_pervasives module Key = struct module Of_name = struct type t = { name: string ; pkh: Tezos_crypto.Ed25519.Public_key_hash.t ; pk: Tezos_crypto.Ed25519.Public_key.t ; sk: Tezos_crypto.Ed25519.Secret_key.t } let make name = let seed = Bytes.of_string (String.concat ~sep:"" (List.init 42 ~f:(fun _ -> name))) in let pkh, pk, sk = Tezos_crypto.Ed25519.generate_key ~seed () in {name; pkh; pk; sk} let pubkey n = Tezos_crypto.Ed25519.Public_key.to_b58check (make n).pk let pubkey_hash n = Tezos_crypto.Ed25519.Public_key_hash.to_b58check (make n).pkh let private_key n = "unencrypted:" ^ Tezos_crypto.Ed25519.Secret_key.to_b58check (make n).sk end end module Account = struct type t = | Of_name of string | Key_pair of {name: string; pubkey: string; pubkey_hash: string; private_key: string} let of_name s = Of_name s let of_namef fmt = ksprintf of_name fmt let name = function Of_name n -> n | Key_pair k -> k.name let key_pair name ~pubkey ~pubkey_hash ~private_key = Key_pair {name; pubkey; pubkey_hash; private_key} let pubkey = function | Of_name n -> Key.Of_name.pubkey n | Key_pair k -> k.pubkey let pubkey_hash = function | Of_name n -> Key.Of_name.pubkey_hash n | Key_pair k -> k.pubkey_hash let private_key = function | Of_name n -> Key.Of_name.private_key n | Key_pair k -> k.private_key end module Voting_period = struct type t = [`Proposal | `Exploration | `Cooldown | `Promotion | `Adoption] end module Protocol_kind = struct type t = [ `Athens | `Babylon | `Carthage | `Delphi | `Edo | `Florence | `Granada | `Hangzhou | `Ithaca | `Alpha ] let names = [ ("Athens", `Athens); ("Babylon", `Babylon); ("Carthage", `Carthage) ; ("Delphi", `Delphi); ("Edo", `Edo); ("Florence", `Florence) ; ("Granada", `Granada); ("Hangzhou", `Hangzhou); ("Ithaca", `Ithaca) ; ("Alpha", `Alpha) ] let ( < ) k1 k2 = let rec aux = function | [] -> assert false | (_, k) :: rest -> if Poly.equal k k2 then false else if Poly.equal k k1 then true else aux rest in aux names let default = `Alpha let cmdliner_term ~docs () : t Cmdliner.Term.t = let open Cmdliner in Arg.( value (opt (enum names) default (info ["protocol-kind"] ~docs ~doc:"Set the protocol family.") )) let pp ppf n = Fmt.string ppf (List.find_map_exn names ~f:(function | s, x when Poly.equal x n -> Some s | _ -> None ) ) end type t = { id: string ; kind: Protocol_kind.t ; bootstrap_accounts: (Account.t * Int64.t) list ; dictator: Account.t ; expected_pow: int ; name: string (* e.g. alpha *) ; hash: string ; time_between_blocks: int list ; minimal_block_delay: int ; baking_reward_per_endorsement: int list ; endorsement_reward: int list ; blocks_per_roll_snapshot: int ; blocks_per_voting_period: int ; blocks_per_cycle: int ; preserved_cycles: int ; proof_of_work_threshold: int ; timestamp_delay: int option ; custom_protocol_parameters: Ezjsonm.t option } let compare a b = String.compare a.id b.id let make_bootstrap_accounts ~balance n = List.init n ~f:(fun n -> (Account.of_namef "bootacc-%d" n, balance)) let default () = let dictator = Account.of_name "dictator-default" in { id= "default-bootstrap" ; kind= Protocol_kind.default ; bootstrap_accounts= make_bootstrap_accounts ~balance:4_000_000_000_000L 4 ; dictator ; expected_pow= 1 ; name= "alpha" ; hash= "ProtoALphaALphaALphaALphaALphaALphaALphaALphaDdp3zK" ; time_between_blocks= [2; 3] ; minimal_block_delay= 2 ; baking_reward_per_endorsement= [78_125; 11_719] ; endorsement_reward= [78_125; 52_083] ; blocks_per_roll_snapshot= 4 ; blocks_per_voting_period= 16 ; blocks_per_cycle= 8 ; preserved_cycles= 2 ; proof_of_work_threshold= -1 ; timestamp_delay= None ; custom_protocol_parameters= None } let protocol_parameters_json t : Ezjsonm.t = let open Ezjsonm in let make_account (account, amount) = strings [Account.pubkey account; sprintf "%Ld" amount] in let extra_post_babylon_stuff subkind = let alpha_specific_parameters = match subkind with | `Alpha -> [ ("tx_rollup_enable", bool false) ; (* TODO: https://gitlab.com/tezos/tezos/-/issues/2152 *) ("tx_rollup_origination_size", int 60_000) ; ("sc_rollup_enable", bool false) ; ("sc_rollup_origination_size", int 6_314) ] | `Hangzhou | `Ithaca -> [] | _ -> failwith "unsupported protocol" in let list_of_zs = list (fun i -> string (Int.to_string i)) in let pre_alpha_specific_parameters = match subkind with | `Ithaca | `Alpha -> [ ("max_operations_time_to_live", int 120) ; ("blocks_per_stake_snapshot", int t.blocks_per_roll_snapshot) ; ("baking_reward_fixed_portion", string "10000000") ; ("baking_reward_bonus_per_slot", string "4286") ; ("endorsing_reward_per_slot", string "2857") ; ("consensus_committee_size", int 67); ("consensus_threshold", int 6) ; ( "minimal_participation_ratio" , dict [("numerator", int 2); ("denominator", int 3)] ) ; ("minimal_block_delay", string (Int.to_string t.minimal_block_delay)) ; ("delay_increment_per_round", string "1") ; ("max_slashing_period", int 2) ; ("frozen_deposits_percentage", int 10) ; ( "ratio_of_frozen_deposits_slashed_per_double_endorsement" , dict [("numerator", int 1); ("denominator", int 2)] ) ; ("double_baking_punishment", string "640000000") ] | `Hangzhou -> [ ("blocks_per_roll_snapshot", int t.blocks_per_roll_snapshot) ; ("initial_endorsers", int 1) ; ("delay_per_missing_endorsement", string (Int.to_string 1)) ; ( "time_between_blocks" , list (ksprintf string "%d") t.time_between_blocks ) ; ("endorsers_per_block", int 56) ; ("block_security_deposit", string (Int.to_string 640_000_000)) ; ("endorsement_security_deposit", string (Int.to_string 250_000)) ; ( "baking_reward_per_endorsement" , list_of_zs t.baking_reward_per_endorsement ) ; ("endorsement_reward", list_of_zs t.endorsement_reward) ; ("minimal_block_delay", string (Int.to_string t.minimal_block_delay)) ] | _ -> failwith "unsupported protocol" in alpha_specific_parameters @ pre_alpha_specific_parameters in let common = [ ( "bootstrap_accounts" , list make_account (t.bootstrap_accounts @ [(t.dictator, 10_000_000L)]) ); ("blocks_per_voting_period", int t.blocks_per_voting_period) ; ("blocks_per_cycle", int t.blocks_per_cycle) ; ("preserved_cycles", int t.preserved_cycles) ; ("proof_of_work_threshold", ksprintf string "%d" t.proof_of_work_threshold) ; ("blocks_per_commitment", int 4) ; ("hard_gas_limit_per_operation", string (Int.to_string 1_040_000)) ; ("hard_gas_limit_per_block", string (Int.to_string 5_200_000)) ; ("tokens_per_roll", string (Int.to_string 8_000_000_000)) ; ("seed_nonce_revelation_tip", string (Int.to_string 125_000)) ; ("origination_size", int 257) ; ("hard_storage_limit_per_operation", string (Int.to_string 60_000)) ; ("cost_per_byte", string (Int.to_string 250)); ("quorum_min", int 3_000) ; ("quorum_max", int 7_000); ("min_proposal_quorum", int 500) ; ("liquidity_baking_subsidy", string "2500000") ; ("liquidity_baking_sunset_level", int 525600) ; ("liquidity_baking_escape_ema_threshold", int 1000000) ] in match t.custom_protocol_parameters with | Some s -> s | None -> dict (common @ extra_post_babylon_stuff t.kind) let voting_period_to_string t (p : Voting_period.t) = (* This has to mimic: src/proto_alpha/lib_protocol/voting_period_repr.ml *) match p with | `Promotion -> if Protocol_kind.(t.kind < `Florence) then "promotion_vote" else "promotion" | `Exploration -> if Protocol_kind.(t.kind < `Florence) then "testing_vote" else "exploration" | `Proposal -> "proposal" | `Cooldown -> if Protocol_kind.(t.kind < `Florence) then "testing" else "cooldown" | `Adoption -> "adoption" let sandbox {dictator; _} = let pk = Account.pubkey dictator in Ezjsonm.to_string (`O [("genesis_pubkey", `String pk)]) let protocol_parameters t = Ezjsonm.to_string ~minify:false (protocol_parameters_json t) let expected_pow t = t.expected_pow let id t = t.id let kind t = t.kind let bootstrap_accounts t = List.map ~f:fst t.bootstrap_accounts let dictator_name {dictator; _} = Account.name dictator let dictator_secret_key {dictator; _} = Account.private_key dictator let make_path config t = Paths.root config // sprintf "protocol-%s" (id t) let sandbox_path config t = make_path config t // "sandbox.json" let protocol_parameters_path config t = make_path config t // "protocol_parameters.json" let ensure_script state t = let open Genspio.EDSL in let file string p = let path = p state t in ( Caml.Filename.basename path , write_stdout ~path:(str path) (feed ~string:(str (string t)) (exec ["cat"])) ) in check_sequence ~verbosity:(`Announce (sprintf "Ensure-protocol-%s" (id t))) [ ("directory", exec ["mkdir"; "-p"; make_path state t]) ; file sandbox sandbox_path ; file protocol_parameters protocol_parameters_path ] let ensure state t = Running_processes.run_successful_cmdf state "sh -c %s" (Genspio.Compile.to_one_liner (ensure_script state t) |> Caml.Filename.quote) >>= fun _ -> return () let cli_term state = let open Cmdliner in let open Term in let def = default () in let docs = Manpage_builder.section state ~rank:2 ~name:"PROTOCOL OPTIONS" in pure (fun bootstrap_accounts (`Blocks_per_voting_period blocks_per_voting_period) (`Protocol_hash hash) (`Time_between_blocks time_between_blocks) (`Minimal_block_delay minimal_block_delay) (`Blocks_per_cycle blocks_per_cycle) (`Preserved_cycles preserved_cycles) (`Timestamp_delay timestamp_delay) (`Protocol_parameters custom_protocol_parameters) kind -> let id = "default-and-command-line" in { def with id ; kind ; custom_protocol_parameters ; blocks_per_cycle ; hash ; bootstrap_accounts ; time_between_blocks ; minimal_block_delay ; preserved_cycles ; timestamp_delay ; blocks_per_voting_period } ) $ Arg.( pure (fun remove_all nb balance add_bootstraps -> add_bootstraps @ make_bootstrap_accounts ~balance (if remove_all then 0 else nb) ) $ value (flag (info ~doc: "Do not create any of the default bootstrap accounts (this \ overrides `--number-of-bootstrap-accounts` with 0)." ~docs ["remove-default-bootstrap-accounts"] ) ) $ value (opt int 4 (info ["number-of-bootstrap-accounts"] ~docs ~doc:"Set the number of generated bootstrap accounts." ) ) $ ( pure (function | `Tez, f -> f *. 1_000_000. |> Int64.of_float | `Mutez, f -> f |> Int64.of_float ) $ value (opt (pair ~sep:':' (enum [("tz", `Tez); ("tez", `Tez); ("mutez", `Mutez)]) float ) (`Tez, 4_000_000.) (info ["balance-of-bootstrap-accounts"] ~docv:"UNIT:FLOAT" ~docs ~doc: "Set the initial balance of bootstrap accounts, for \ instance: `tz:2_000_000.42` or \ `mutez:42_000_000_000_000`." ) ) ) $ Arg.( pure (fun l -> List.map l ~f:(fun ((name, pubkey, pubkey_hash, private_key), tez) -> (Account.key_pair name ~pubkey ~pubkey_hash ~private_key, tez) ) ) $ value (opt_all (pair ~sep:'@' (t4 ~sep:',' string string string string) int64) [] (info ["add-bootstrap-account"] ~docs ~docv:"NAME,PUBKEY,PUBKEY-HASH,PRIVATE-URI@MUTEZ-AMOUNT" ~doc: "Add a custom bootstrap account, e.g. \ `LedgerBaker,edpku...,tz1YPS...,ledger://crouching-tiger.../ed25519/0'/0'@20_000_000_000`." ) ))) $ Arg.( pure (fun x -> `Blocks_per_voting_period x) $ value (opt int def.blocks_per_voting_period (info ~docs ["blocks-per-voting-period"] ~doc:"Set the length of voting periods." ) )) $ Arg.( pure (fun x -> `Protocol_hash x) $ value (opt string def.hash (info ["protocol-hash"] ~docs ~doc:"Set the (initial) protocol hash." ) )) $ Arg.( pure (fun x -> `Time_between_blocks x) $ value (opt (list ~sep:',' int) def.time_between_blocks (info ["time-between-blocks"] ~docv:"COMMA-SEPARATED-SECONDS" ~docs ~doc: "Set the time between blocks bootstrap-parameter, e.g. \ `2,3,2`." ) )) $ Arg.( pure (fun x -> `Minimal_block_delay x) $ value (opt int def.minimal_block_delay (info ["minimal-block-delay"] ~docv:"SECONDS" ~docs ~doc: "Set the minimal delay between blocks bootstrap-parameter, \ e.g. `2`." ) )) $ Arg.( pure (fun x -> `Blocks_per_cycle x) $ value (opt int def.blocks_per_cycle (info ["blocks-per-cycle"] ~docv:"NUMBER" ~docs ~doc:"Number of blocks per cycle." ) )) $ Arg.( pure (fun x -> `Preserved_cycles x) $ value (opt int def.preserved_cycles (info ["preserved-cycles"] ~docv:"NUMBER" ~docs ~doc: "Base constant for baking rights (search for \ `PRESERVED_CYCLES` in the white paper)." ) )) $ Arg.( pure (fun x -> `Timestamp_delay x) $ value (opt (some int) def.timestamp_delay (info ["timestamp-delay"] ~docv:"NUMBER" ~docs ~doc:"Protocol activation timestamp delay in seconds." ) )) $ Arg.( pure (fun f -> `Protocol_parameters (Option.map f ~f:(fun path -> let i = Caml.open_in path in Ezjsonm.from_channel i ) ) ) $ value (opt (some file) None (info ["override-protocol-parameters"] ~doc: "Use these protocol parameters instead of the generated ones \ (technically this invalidates most other options from a \ tezos-node point of view, use at your own risk)." ~docv:"JSON-FILE" ~docs ) )) $ Protocol_kind.cmdliner_term () ~docs module Pretty_print = struct open More_fmt let verbatim_protection f ppf json_blob = try f ppf json_blob with e -> json ppf json_blob ; cut ppf () ; exn ppf e let fail_expecting s = failwith "PP: Expecting %s" s let mempool_pending_operations_rpc ppf mempool_json = let pp_op_list_short ppf l = let kinds = List.map l ~f:(fun js -> Jqo.(field ~k:"kind" js |> get_string)) in pf ppf "%s" ( List.fold kinds ~init:[] ~f:(fun prev k -> match prev with | (kind, n) :: more when String.equal kind k -> (kind, n + 1) :: more | other -> (k, 1) :: other ) |> List.map ~f:(function k, 1 -> k | k, n -> str "%s×%d" k n) |> String.concat ~sep:"+" ) in let open Jqo in match mempool_json with | `O four_fields -> List.iter four_fields ~f:(fun (name, content) -> pf ppf "@,* `%s`: " (String.capitalize name) ; match content with | `A [] -> pf ppf "Empty." | `A l -> ( match name with | "applied" -> List.iter l ~f:(fun op -> let contents = field ~k:"contents" op |> get_list in let pp_op_long ppf js = match field ~k:"kind" js |> get_string with | "transaction" -> pf ppf "@, * Mutez:%s: `%s` -> `%s`%s" (field ~k:"amount" js |> get_string) (field ~k:"source" js |> get_string) (field ~k:"destination" js |> get_string) ( try let _ = field ~k:"parameters" js in "+parameters" with _ -> "" ) | "origination" -> pf ppf "@, * Mutez:%s, source: `%s`, fee: `%s`" (field ~k:"balance" js |> get_string) (field ~k:"source" js |> get_string) (field ~k:"fee" js |> get_string) | _ -> () in pf ppf "@, * [%a] %a" pp_op_list_short contents (long_string ~max:15) (field ~k:"hash" op |> get_string) ; List.iter contents ~f:(pp_op_long ppf) ) | _other -> List.iter l ~f:(function | `A [`String opid; op] -> let contents = field ~k:"contents" op |> get_list in pf ppf "@, * [%s]: %a" opid pp_op_list_short contents ; pf ppf "@, TODO: %a" json content | _ -> fail_expecting "a operation tuple" ) ) | _ -> fail_expecting "a list of operations" ) | _ -> fail_expecting "a JSON object" let block_head_rpc ppf block_json = let open Jqo in let proto = field ~k:"protocol" block_json |> get_string in let hash = field ~k:"hash" block_json |> get_string in let metadata = field ~k:"metadata" block_json in let next_protocol = metadata |> field ~k:"next_protocol" |> get_string in let header = field ~k:"header" block_json in let level = field ~k:"level" header |> get_int in let timestamp = field ~k:"timestamp" header |> get_string in let voting_kind = metadata |> field ~k:"voting_period_info" |> field ~k:"voting_period" |> field ~k:"kind" |> get_string in let voting_pos = metadata |> field ~k:"voting_period_info" |> field ~k:"position" |> get_int in let voting_nth = metadata |> field ~k:"level" |> field ~k:"voting_period" |> get_int in let baker = metadata |> field ~k:"baker" |> get_string in pf ppf "Level %d | `%s` | %s" level hash timestamp ; pf ppf "@,* Protocol: `%s`" proto ; if String.equal proto next_protocol then pf ppf " (also next)" else pf ppf "@,* Next-protocol: `%s`" next_protocol ; pf ppf "@,* Voting period %d: `%s` (level: %d)" voting_nth voting_kind voting_pos ; pf ppf "@,* Baker: `%s`" baker end
eqrel.ml
open Expr;; open Mlproof;; exception Wrong_shape;; type direction = L | R;; let symbol = ref None;; let leaves = ref [];; let typ = ref "";; let rec check_pattern env sym e = match e with | Eapp (s, [(Evar _ as x); (Evar _ as y)], _) | Enot (Eapp (s, [(Evar _ as x); (Evar _ as y)], _), _) when s = sym -> if List.mem_assoc x env && List.mem_assoc y env then () else raise Wrong_shape; | _ -> raise Wrong_shape; ;; let get_skeleton e = match e with | Enot (Eapp (s, _, _), _) -> s | Eapp (s, _, _) -> s | _ -> raise Wrong_shape ;; let get_type env e = match e with | Enot (Eapp (_, [Evar _ as x; _], _), _) -> List.assoc x env | Eapp (_, [Evar _ as x; _], _) -> List.assoc x env | _ -> assert false ;; let do_leaf env e = match !symbol with | Some s -> check_pattern env s e; leaves := e :: !leaves; | None -> let s = get_skeleton e in check_pattern env s e; symbol := Some s; leaves := e :: !leaves; typ := get_type env e; ;; let rec do_disj env e = match e with | Eor (e1, e2, _) -> do_disj env e1; do_disj env e2; | Eimply (e1, e2, _) -> do_disj env (enot e1); do_disj env e2; | Enot (Eand (e1, e2, _), _) -> do_disj env (enot e1); do_disj env (enot e2); | Enot (Enot (e1, _), _) -> do_disj env e1; | Enot (Etrue, _) | Efalse -> () | _ -> do_leaf env e; ;; let get_leaves path env e = symbol := None; leaves := []; typ := ""; try do_disj env e; (List.rev path, env, !leaves, !typ) with Wrong_shape -> (List.rev path, env, [], "") ;; let subexprs = ref [];; let rec do_conj path env e = match e with | Eand (e1, e2, _) -> do_conj (L::path) env e1; do_conj (R::path) env e2; | Eall (v, t, e1, _) -> do_conj path ((v,t)::env) e1; | Enot (Eor (e1, e2, _), _) -> do_conj (L::path) env (enot e1); do_conj (R::path) env (enot e2); | Enot (Eimply (e1, e2, _), _) -> do_conj (L::path) env e1; do_conj (R::path) env (enot e2); | Enot (Eex (v, t, e1, _), _) -> do_conj path ((v,t)::env) (enot e1); | Enot (Enot (e1, _), _) -> do_conj path env e1; | Eequiv (e1, e2, _) -> do_conj (L::path) env (eimply (e1, e2)); do_conj (R::path) env (eimply (e2, e1)); | Enot (Eequiv (e1, e2, _), _) -> do_conj (L::path) env (eor (e1, e2)); do_conj (R::path) env (eor (enot e1, enot e2)); | _ -> subexprs := (get_leaves path env e) :: !subexprs; ;; let get_subexprs e = subexprs := []; do_conj [] [] e; !subexprs ;; let get_symbol l = match l with | Enot (Eapp (s, _, _), _) :: _ -> s | Eapp (s, _, _) :: _ -> s | _ -> assert false ;; let rec partition pos neg l = match l with | [] -> (pos, neg) | (Enot _ as h) :: t -> partition pos (h::neg) t | h :: t -> partition (h::pos) neg t ;; let rec number_var env v = match env with | (Evar (x, _), t) :: rest -> if x = v then List.length rest else number_var rest v | _ -> assert false ;; let is_refl l e path env = match l with | [ Eapp (_, [Evar (x, _); Evar (y, _)], _) ] when x = y -> Some (e, path, [number_var env x]) | _ -> None ;; let is_sym l e path env = match partition [] [] l with | [ Eapp (_, [Evar (x1, _); Evar (y1, _)], _) ], [ Enot (Eapp (_, [Evar (x2, _); Evar (y2, _)], _), _) ] when x1 = y2 && y1 = x2 -> Some (e, path, List.map (number_var env) [x2; y2]) | _ -> None ;; let is_trans l e path env = match partition [] [] l with | [ Eapp (_, [Evar (x1, _); Evar (y1, _)], _) ], [ Enot (Eapp (_, [Evar (x2, _); Evar (y2, _)], _), _); Enot (Eapp (_, [Evar (x3, _); Evar (y3, _)], _), _)] when y2 = x3 && x1 = x2 && y1 = y3 -> Some (e, path, List.map (number_var env) [x1; y2; y1]) | [ Eapp (_, [Evar (x1, _); Evar (y1, _)], _) ], [ Enot (Eapp (_, [Evar (x2, _); Evar (y2, _)], _), _); Enot (Eapp (_, [Evar (x3, _); Evar (y3, _)], _), _)] when y3 = x2 && x1 = x3 && y1 = y2 -> Some (e, path, List.map (number_var env) [x1; x2; y1]) | _ -> None ;; let is_transsym l e path env = match partition [] [] l with | [ Eapp (_, [Evar (x1, _); Evar (y1, _)], _) ], [ Enot (Eapp (_, [Evar (x2, _); Evar (y2, _)], _), _); Enot (Eapp (_, [Evar (x3, _); Evar (y3, _)], _), _)] when y2 = x3 && y1 = x2 && x1 = y3 -> Some (e, path, List.map (number_var env) [y1; y2; x1]) | [ Eapp (_, [Evar (x1, _); Evar (y1, _)], _) ], [ Enot (Eapp (_, [Evar (x2, _); Evar (y2, _)], _), _); Enot (Eapp (_, [Evar (x3, _); Evar (y3, _)], _), _)] when y3 = x2 && y1 = x3 && x1 = y2 -> Some (e, path, List.map (number_var env) [y1; x2; x1]) | _ -> None ;; type info = { mutable refl : (Expr.expr * direction list * int list) option; mutable sym : (Expr.expr * direction list * int list) option; mutable trans : (Expr.expr * direction list * int list) option; mutable transsym : (Expr.expr * direction list * int list) option; mutable typ : string; mutable refl_hyp : Expr.expr option; mutable sym_hyp : Expr.expr option; mutable trans_hyp : Expr.expr option; };; let tbl = (Hashtbl.create 97 : (string, info) Hashtbl.t);; let get_record s = try Hashtbl.find tbl s with Not_found -> let result = {refl = None; sym = None; trans = None; transsym = None; typ = ""; refl_hyp = None; sym_hyp = None; trans_hyp = None} in Hashtbl.add tbl s result; result ;; let analyse_subexpr e (path, env, sb, typ) = let refl = is_refl sb e path env in let sym = is_sym sb e path env in let trans = is_trans sb e path env in let transsym = is_transsym sb e path env in match refl, sym, trans, transsym with | None, None, None, None -> () | _, _, _, _ -> let r = get_record (get_symbol sb) in if refl <> None then r.refl <- refl; if sym <> None then r.sym <- sym; if trans <> None then r.trans <- trans; if transsym <> None then r.transsym <- transsym; r.typ <- typ ;; let analyse e = List.iter (analyse_subexpr e) (get_subexprs e);; let subsumed_subexpr e (path, env, sb, typ) = if is_refl sb e path env <> None then (get_record (get_symbol sb)).refl <> None else if is_sym sb e path env <> None then (get_record (get_symbol sb)).sym <> None else if is_trans sb e path env <> None then (get_record (get_symbol sb)).trans <> None else if is_transsym sb e path env <> None then let r = get_record (get_symbol sb) in r.sym <> None && r.trans <> None else false ;; let subsumed e = List.for_all (subsumed_subexpr e) (get_subexprs e);; let eq_origin = Some (etrue, [], []);; Hashtbl.add tbl "=" { refl = eq_origin; sym = eq_origin; trans = eq_origin; transsym = eq_origin; typ = ""; refl_hyp = None; sym_hyp = None; trans_hyp = None; };; let refl s = try let r = Hashtbl.find tbl s in match r.refl with | None -> false | Some _ -> true with Not_found -> false ;; let sym s = try let r = Hashtbl.find tbl s in match r.sym, r.refl, r.transsym with | Some _, _, _ -> true | _, Some _, Some _ -> true | _, _, _ -> false with Not_found -> false ;; let trans s = try let r = Hashtbl.find tbl s in match r.trans, r.refl, r.transsym with | Some _, _, _ -> true | _, Some _, Some _ -> true | _, _, _ -> false with Not_found -> false ;; let any s = try let r = Hashtbl.find tbl s in match r.refl, r.sym, r.trans with | None, None, None -> false | _, _, _ -> true with Not_found -> false ;; type origin = Expr.expr * direction list * int list;; type hyp_kind = | Refl of origin | Sym of origin | Sym2 of string * origin * origin (* symbol, refl, transsym *) | Trans of origin | Trans2 of string * origin * origin (* symbol, refl, transsym *) ;; module HE = Hashtbl.Make (Expr);; let hyps_tbl = (HE.create 97 : hyp_kind HE.t) ;; let get_refl_hyp s = assert (s <> "="); let r = Hashtbl.find tbl s in match r.refl_hyp with | Some e -> e | None -> let vx = evar "x" in let result = eall (vx, r.typ, eapp (s, [vx; vx])) in r.refl_hyp <- Some result; begin match r.refl with | Some (e, dirs, vars) -> HE.add hyps_tbl result (Refl ((e, dirs, vars))) | None -> assert false end; result ;; let get_sym_hyp s = assert (s <> "="); let r = Hashtbl.find tbl s in match r.sym_hyp with | Some e -> e | None -> let vx = evar "x" and vy = evar "y" in let result = eall (vx, r.typ, eall (vy, r.typ, eimply (eapp (s, [vx; vy]), eapp (s, [vy; vx])))) in r.sym_hyp <- Some result; begin match r.refl, r.sym, r.transsym with | _, Some (e, dirs, vars), _ -> HE.add hyps_tbl result (Sym ((e, dirs, vars))) | Some (e1, dir1, var1), _, Some (e2, dir2, var2) -> HE.add hyps_tbl result (Sym2 (s, (e1, dir1, var1), (e2, dir2, var2))) | _, _, _ -> assert false end; result ;; let get_trans_hyp s = assert (s <> "="); let r = Hashtbl.find tbl s in match r.trans_hyp with | Some e -> e | None -> let vx = evar "x" and vy = evar "y" and vz = evar "z" in let result = eall (vx, r.typ, eall (vy, r.typ, eall (vz, r.typ, eimply (eapp (s, [vx; vy]), eimply (eapp (s, [vy; vz]), eapp (s, [vx; vz])))))) in r.trans_hyp <- Some result; begin match r.refl, r.trans, r.transsym with | _, Some (e, dirs, vars), _ -> HE.add hyps_tbl result (Trans ((e, dirs, vars))) | Some (e1, dir1, var1), _, Some (e2, dir2, var2) -> HE.add hyps_tbl result (Trans2 (s, (e1, dir1, var1), (e2, dir2, var2))) | _, _, _ -> assert false end; result ;; let inst_nall e = match e with | Enot (Eall (v, ty, f, _), _) -> let nf = enot f in let t = etau (v, ty, nf) in (Expr.substitute [(v, t)] nf, t) | _ -> assert false ;; let rec decompose_disj e forms = match e with | Eor (e1, e2, _) -> let n1 = decompose_disj e1 forms in let n2 = decompose_disj e2 forms in make_node [e] (Or (e1, e2)) [[e1]; [e2]] [n1; n2] | Eimply (e1, e2, _) -> let ne1 = enot e1 in let n1 = decompose_disj ne1 forms in let n2 = decompose_disj e2 forms in make_node [e] (Impl (e1, e2)) [[ne1]; [e2]] [n1; n2] | Enot (Eand (e1, e2, _), _) -> let ne1 = enot e1 in let ne2 = enot e2 in let n1 = decompose_disj ne1 forms in let n2 = decompose_disj ne2 forms in make_node [e] (NotAnd (e1, e2)) [[ne1]; [ne2]] [n1; n2] | Enot (Enot (e1, _), _) -> let n1 = decompose_disj e1 forms in make_node [e] (NotNot (e1)) [[e1]] [n1] | Efalse -> make_node [e] False [] [] | Enot (Etrue, _) -> make_node [e] NotTrue [] [] | Eapp (s, _, _) -> let ne = enot e in assert (List.exists (Expr.equal ne) forms); make_node [e; ne] (Close e) [] [] | Enot (Eapp (s, _, _) as e1, _) -> assert (List.exists (Expr.equal e1) forms); make_node [e1; e] (Close e1) [] [] | _ -> assert false ;; let rec decompose_conj n e dirs vars forms taus = match e, dirs, vars with | Eand (e1, e2, _), L::rest, _ -> let n1 = decompose_conj n e1 rest vars forms taus in make_node [e] (And (e1, e2)) [[e1]] [n1] | Eand (e1, e2, _), R::rest, _ -> let n1 = decompose_conj n e2 rest vars forms taus in make_node [e] (And (e1, e2)) [[e2]] [n1] | Eall (v, ty, e1, _), _, w::rest when n = w -> begin match taus with | [] -> assert false | x::t -> let f = Expr.substitute [(v, x)] e1 in let n1 = decompose_conj (n+1) f dirs rest forms t in make_node [e] (All (e, x)) [[f]] [n1] end | Eall (v, ty, e1, _), _, _ -> let x = emeta (e) in let f = Expr.substitute [(v, x)] e1 in let n1 = decompose_conj (n+1) f dirs vars forms taus in make_node [e] (All (e, x)) [[f]] [n1] | Enot (Eor (e1, e2, _), _), L::rest, _ -> let ne1 = enot e1 in let n1 = decompose_conj n ne1 rest vars forms taus in make_node [e] (NotOr (e1, e2)) [[ne1]] [n1] | Enot (Eor (e1, e2, _), _), R::rest, _ -> let ne2 = enot e2 in let n1 = decompose_conj n ne2 rest vars forms taus in make_node [e] (NotOr (e1, e2)) [[ne2]] [n1] | Enot (Eimply (e1, e2, _), _), L::rest, _ -> let n1 = decompose_conj n e1 rest vars forms taus in make_node [e] (NotImpl (e1, e2)) [[e1]] [n1] | Enot (Eimply (e1, e2, _), _), R::rest, _ -> let ne2 = enot e2 in let n1 = decompose_conj n ne2 rest vars forms taus in make_node [e] (NotOr (e1, e2)) [[ne2]] [n1] | Enot (Eex (v, ty, e1, _), _), _, w::rest when n = w -> begin match taus with | [] -> assert false | x::t -> let f = Expr.substitute [(v, x)] (enot e1) in let n1 = decompose_conj (n+1) f dirs rest forms t in make_node [e] (NotEx (e, x)) [[f]] [n1] end | Enot (Eex (v, ty, e1, _) as e2, _), _, _ -> let x = emeta (e2) in let f = Expr.substitute [(v, x)] (enot e1) in let n1 = decompose_conj (n+1) f dirs vars forms taus in make_node [e] (NotEx (e, x)) [[f]] [n1] | Enot (Enot (e1, _), _), _, _ -> let n1 = decompose_conj n e1 dirs vars forms taus in make_node [e] (NotNot e1) [[e1]] [n1] | Eequiv (e1, e2, _), L::rest, _ -> let ne1 = enot e1 in let n1 = decompose_disj ne1 forms in let n2 = decompose_disj e2 forms in make_node [e] (Equiv (e1, e2)) [[ne1]; [e2]] [n1; n2] | Eequiv (e1, e2, _), R::rest, _ -> let ne2 = enot e2 in let n1 = decompose_disj e1 forms in let n2 = decompose_disj ne2 forms in make_node [e] (Equiv (e1, e2)) [[ne2]; [e1]] [n2; n1] | Enot (Eequiv (e1, e2, _), _), L::rest, _ -> let n1 = decompose_disj e1 forms in let n2 = decompose_disj e2 forms in make_node [e] (NotEquiv (e1, e2)) [[e2]; [e1]] [n2; n1] | Enot (Eequiv (e1, e2, _), _), R::rest, _ -> let ne1 = enot e1 in let ne2 = enot e2 in let n1 = decompose_disj ne1 forms in let n2 = decompose_disj ne2 forms in make_node [e] (NotEquiv (e1, e2)) [[ne1]; [e2]] [n1; n2] | _, _, _ -> assert (dirs = []); assert (vars = []); assert (taus = []); decompose_disj e forms ;; let get_proof e = let ne = enot e in match HE.find hyps_tbl e with | Refl ((f, dirs, vars)) -> let (f1, tau) = inst_nall ne in let n1 = decompose_conj 0 f dirs vars [f1] [tau] in let n2 = make_node [ne] (NotAll ne) [[f1]] [n1] in (n2, [f]) | Sym ((f, dirs, vars)) -> let (f1, tau1) = inst_nall ne in let (f2, tau2) = inst_nall f1 in begin match f2 with | Enot (Eimply (f3, f4, _), _) -> let nf4 = enot f4 in let n1 = decompose_conj 0 f dirs vars [f3; nf4] [tau1; tau2] in let n2 = make_node [f2] (NotImpl (f3, f4)) [[f3; nf4]] [n1] in let n3 = make_node [f1] (NotAll f1) [[f2]] [n2] in let n4 = make_node [ne] (NotAll ne) [[f1]] [n3] in (n4, [f]) | _ -> assert false end | Sym2 (s, (fsy, dirsy, varsy), (ftx, dirtx, vartx)) -> let (f1, tau1) = inst_nall ne in let (f2, tau2) = inst_nall f1 in let rtt = eapp (s, [tau1; tau1]) in let nrtt = enot rtt in begin match f2 with | Enot (Eimply (f3, f4, _), _) -> let nf4 = enot f4 in let n1 = decompose_conj 0 fsy dirsy varsy [nrtt] [tau1] in let n2 = decompose_conj 0 ftx dirtx vartx [rtt; f3; nf4] [tau1; tau1; tau2] in let n3 = make_node [] (Cut rtt) [[rtt]; [nrtt]] [n2; n1] in let n4 = make_node [f2] (NotImpl (f3, f4)) [[f3; nf4]] [n3] in let n5 = make_node [f1] (NotAll f1) [[f2]] [n4] in let n6 = make_node [ne] (NotAll ne) [[f1]] [n5] in (n6, [fsy; ftx]) | _ -> assert false end | Trans ((f, dirs, vars)) -> let (f1, tau1) = inst_nall ne in let (f2, tau2) = inst_nall f1 in let (f3, tau3) = inst_nall f2 in begin match f3 with | Enot (Eimply (f4, (Eimply (f5, f6, _) as f56), _), _) -> let nf6 = enot f6 in let n1 = decompose_conj 0 f dirs vars [f4; f5; nf6] [tau1; tau2; tau3] in let n2 = make_node [f56] (NotImpl (f5, f6)) [[f5; nf6]] [n1] in let n3 = make_node [f3] (NotImpl (f4, f56)) [[f4; enot f56]] [n2] in let n4 = make_node [f2] (NotAll f2) [[f3]] [n3] in let n5 = make_node [f1] (NotAll f1) [[f2]] [n4] in let n6 = make_node [ne] (NotAll ne) [[f1]] [n5] in (n6, [f]) | _ -> assert false end | Trans2 (s, (fsy, dirsy, varsy), (ftx, dirtx, vartx)) -> let (f1, tau1) = inst_nall ne in let (f2, tau2) = inst_nall f1 in let (f3, tau3) = inst_nall f2 in let rt1t1 = eapp (s, [tau1; tau1]) in let nrt1t1 = enot rt1t1 in let rt3t1 = eapp (s, [tau3; tau1]) in let nrt3t1 = enot rt3t1 in begin match f3 with | Enot (Eimply (f4, (Eimply (f5, f6, _) as f56), _), _) -> let nf6 = enot f6 in let n1 = decompose_conj 0 ftx dirtx vartx [rt3t1; rt1t1; nf6] [tau3; tau1; tau1] in let n2 = decompose_conj 0 ftx dirtx vartx [f4; f5; nrt3t1] [tau1; tau2; tau3] in let n3 = make_node [] (Cut rt3t1) [[rt3t1]; [nrt3t1]] [n1; n2] in let n4 = decompose_conj 0 fsy dirsy varsy [nrt1t1] [tau1] in let n5 = make_node [] (Cut rt1t1) [[rt1t1]; [nrt1t1]] [n3; n4] in let n6 = make_node [f56] (NotImpl (f5, f6)) [[f5; nf6]] [n5] in let n7 = make_node [f3] (NotImpl (f4, f56)) [[f4; enot f56]] [n6] in let n8 = make_node [f2] (NotAll f2) [[f3]] [n7] in let n9 = make_node [f1] (NotAll f1) [[f2]] [n8] in let n10 = make_node [ne] (NotAll ne) [[f1]] [n9] in (n10, [fsy; ftx]) | _ -> assert false end ;; let print_rels oc = let f k r = Printf.fprintf oc " %s:%s%s%s%s" k (if r.refl = None then "" else "R") (if r.sym = None then "" else "S") (if r.trans = None then "" else "T") (if r.transsym = None then "" else "X") in Hashtbl.iter f tbl; ;;
(* Copyright 2004 INRIA *)
dune
(rule (targets binary-help.txt.gen) (action (with-stdout-to %{targets} (run binary --help=plain)))) (rule (alias runtest) (action (diff binary-help.txt binary-help.txt.gen)))