filename
stringlengths
3
67
data
stringlengths
0
58.3M
license
stringlengths
0
19.5k
web_trailing_slash.ml
let middleware () = let filter handler req = let root_uri = Core_configuration.read_string "PREFIX_PATH" |> CCOption.value ~default:"" |> Format.asprintf "%s/" |> Uri.of_string in let uri = req.Opium.Request.target |> Uri.of_string in let uri = uri |> Uri.path |> (fun path -> if Uri.equal root_uri uri then path (* don't drop root *) else path |> CCString.rdrop_while (Char.equal '/')) |> Uri.with_path uri in let req = Opium.Request.{ req with target = Uri.to_string uri } in handler req in Rock.Middleware.create ~name:"trailing_slash" ~filter ;;
platform.ml
module type IO = Io.S module type CLOCK = sig (** A monotonic time source. See {!Mtime_clock} for an OS-dependent implementation. *) type counter val counter : unit -> counter val count : counter -> Mtime.span end module type SEMAPHORE = sig (** Binary semaphores for mutual exclusion *) type t (** The type of binary semaphore. *) val make : bool -> t (** [make b] returns a new semaphore with the given initial state. If [b] is [true], the semaphore is initially available for acquisition; otherwise, the semaphore is initially unavailable. *) val acquire : string -> t -> unit (** Acquire the given semaphore. Acquisition is not re-entrant. *) val release : t -> unit (** Release the given semaphore. If any threads are attempting to acquire the semaphore, exactly one of them will gain access to the semaphore. *) val with_acquire : string -> t -> (unit -> 'a) -> 'a (** [with_acquire t f] first obtains [t], then computes [f ()], and finally release [t]. *) val is_held : t -> bool (** [is_held t] returns [true] if the semaphore is held, without acquiring [t]. *) end module type THREAD = sig (** Cooperative threads. *) type 'a t (** The type of thread handles. *) val async : (unit -> 'a) -> 'a t (** [async f] creates a new thread of control which executes [f ()] and returns the corresponding thread handle. The thread terminates whenever [f ()] returns a value or raises an exception. *) val await : 'a t -> ('a, [ `Async_exn of exn ]) result (** [await t] blocks on the termination of [t]. *) val return : 'a -> 'a t (** [return ()] is a pre-terminated thread handle. *) val yield : unit -> unit (** Re-schedule the calling thread without suspending it. *) end module type S = sig module IO : IO module Semaphore : SEMAPHORE module Thread : THREAD module Clock : CLOCK end
plplot_core.mli
(* File generated from plplot_core.idl *) type plplot3d_style_enum = | PL_DIFFUSE | PL_DRAW_LINEX | PL_DRAW_LINEY | PL_DRAW_LINEXY | PL_MAG_COLOR | PL_BASE_CONT | PL_TOP_CONT | PL_SURF_CONT | PL_DRAW_SIDES | PL_FACETED | PL_MESH and plplot3d_style = plplot3d_style_enum list and plplot_bin_enum = | PL_BIN_DEFAULT | PL_BIN_CENTRED | PL_BIN_NOEXPAND | PL_BIN_NOEMPTY and plplot_bin_style = plplot_bin_enum list and plplot_hist_enum = | PL_HIST_DEFAULT | PL_HIST_NOSCALING | PL_HIST_IGNORE_OUTLIERS | PL_HIST_NOEXPAND | PL_HIST_NOEMPTY and plplot_hist_style = plplot_hist_enum list and plplot_run_level_enum = | PL_UNINITIALIZED | PL_INITIALIZED | PL_VIEWPORT_DEFINED | PL_WORLD_COORDINATES_DEFINED and plplot_run_level = plplot_run_level_enum and plplot_position_enum = | PL_POSITION_LEFT | PL_POSITION_RIGHT | PL_POSITION_TOP | PL_POSITION_BOTTOM | PL_POSITION_INSIDE | PL_POSITION_OUTSIDE | PL_POSITION_VIEWPORT | PL_POSITION_SUBPAGE and plplot_position_opt = plplot_position_enum list and plplot_legend_enum = | PL_LEGEND_NONE | PL_LEGEND_COLOR_BOX | PL_LEGEND_LINE | PL_LEGEND_SYMBOL | PL_LEGEND_TEXT_LEFT | PL_LEGEND_BACKGROUND | PL_LEGEND_BOUNDING_BOX | PL_LEGEND_ROW_MAJOR and plplot_legend_opt = plplot_legend_enum list and plplot_colorbar_enum = | PL_COLORBAR_LABEL_LEFT | PL_COLORBAR_LABEL_RIGHT | PL_COLORBAR_LABEL_TOP | PL_COLORBAR_LABEL_BOTTOM | PL_COLORBAR_IMAGE | PL_COLORBAR_SHADE | PL_COLORBAR_GRADIENT | PL_COLORBAR_CAP_NONE | PL_COLORBAR_CAP_LOW | PL_COLORBAR_CAP_HIGH | PL_COLORBAR_SHADE_LABEL | PL_COLORBAR_ORIENT_RIGHT | PL_COLORBAR_ORIENT_TOP | PL_COLORBAR_ORIENT_LEFT | PL_COLORBAR_ORIENT_BOTTOM | PL_COLORBAR_BACKGROUND | PL_COLORBAR_BOUNDING_BOX and plplot_colorbar_opt = plplot_colorbar_enum list and plplot_fci_family_enum = | PL_FCI_FAMILY_UNCHANGED | PL_FCI_SANS | PL_FCI_SERIF | PL_FCI_MONO | PL_FCI_SCRIPT | PL_FCI_SYMBOL and plplot_fci_style_enum = | PL_FCI_STYLE_UNCHANGED | PL_FCI_UPRIGHT | PL_FCI_ITALIC | PL_FCI_OBLIQUE and plplot_fci_weight_enum = | PL_FCI_WEIGHT_UNCHANGED | PL_FCI_MEDIUM | PL_FCI_BOLD and plplot_draw_mode_enum = | PL_DRAWMODE_UNKNOWN | PL_DRAWMODE_DEFAULT | PL_DRAWMODE_REPLACE | PL_DRAWMODE_XOR and nonzero_error_int = int external pl_setcontlabelformat : int -> int -> unit = "camlidl_plplot_core_c_pl_setcontlabelformat" external pl_setcontlabelparam : float -> float -> float -> int -> unit = "camlidl_plplot_core_c_pl_setcontlabelparam" external pladv : int -> unit = "camlidl_plplot_core_c_pladv" external plarc : float -> float -> float -> float -> float -> float -> float -> bool -> unit = "camlidl_plplot_core_c_plarc_bytecode" "camlidl_plplot_core_c_plarc" external plaxes : float -> float -> string -> float -> int -> string -> float -> int -> unit = "camlidl_plplot_core_c_plaxes_bytecode" "camlidl_plplot_core_c_plaxes" external plbin : float array -> float array -> plplot_bin_style -> unit = "camlidl_plplot_core_c_plbin" external plbtime : float -> int * int * int * int * int * float = "camlidl_plplot_core_c_plbtime" external plbop : unit -> unit = "camlidl_plplot_core_c_plbop" external plbox : string -> float -> int -> string -> float -> int -> unit = "camlidl_plplot_core_c_plbox_bytecode" "camlidl_plplot_core_c_plbox" external plbox3 : string -> string -> float -> int -> string -> string -> float -> int -> string -> string -> float -> int -> unit = "camlidl_plplot_core_c_plbox3_bytecode" "camlidl_plplot_core_c_plbox3" external plcalc_world : float -> float -> float * float * int = "camlidl_plplot_core_c_plcalc_world" external plclear : unit -> unit = "camlidl_plplot_core_c_plclear" external plcol0 : int -> unit = "camlidl_plplot_core_c_plcol0" external plcol1 : float -> unit = "camlidl_plplot_core_c_plcol1" external plconfigtime : float -> float -> float -> int -> bool -> int -> int -> int -> int -> int -> float -> unit = "camlidl_plplot_core_c_plconfigtime_bytecode" "camlidl_plplot_core_c_plconfigtime" external plcpstrm : int -> bool -> unit = "camlidl_plplot_core_c_plcpstrm" external plctime : int -> int -> int -> int -> int -> float -> float = "camlidl_plplot_core_c_plctime_bytecode" "camlidl_plplot_core_c_plctime" external plend : unit -> unit = "camlidl_plplot_core_c_plend" external plend1 : unit -> unit = "camlidl_plplot_core_c_plend1" external plenv : float -> float -> float -> float -> int -> int -> unit = "camlidl_plplot_core_c_plenv_bytecode" "camlidl_plplot_core_c_plenv" external plenv0 : float -> float -> float -> float -> int -> int -> unit = "camlidl_plplot_core_c_plenv0_bytecode" "camlidl_plplot_core_c_plenv0" external pleop : unit -> unit = "camlidl_plplot_core_c_pleop" external plerrx : float array -> float array -> float array -> unit = "camlidl_plplot_core_c_plerrx" external plerry : float array -> float array -> float array -> unit = "camlidl_plplot_core_c_plerry" external plfamadv : unit -> unit = "camlidl_plplot_core_c_plfamadv" external plfill : float array -> float array -> unit = "camlidl_plplot_core_c_plfill" external plfill3 : float array -> float array -> float array -> unit = "camlidl_plplot_core_c_plfill3" external plflush : unit -> unit = "camlidl_plplot_core_c_plflush" external plfont : int -> unit = "camlidl_plplot_core_c_plfont" external plfontld : int -> unit = "camlidl_plplot_core_c_plfontld" external plgchr : unit -> float * float = "camlidl_plplot_core_c_plgchr" external plgcmap1_range : unit -> float * float = "camlidl_plplot_core_c_plgcmap1_range" external plgcol0 : int -> int * int * int = "camlidl_plplot_core_c_plgcol0" external plgcol0a : int -> int * int * int * float = "camlidl_plplot_core_c_plgcol0a" external plgcolbg : unit -> int * int * int = "camlidl_plplot_core_c_plgcolbg" external plgcolbga : unit -> int * int * int * float = "camlidl_plplot_core_c_plgcolbga" external plgcompression : unit -> int = "camlidl_plplot_core_c_plgcompression" external plgdev : unit -> string = "camlidl_plplot_core_c_plgdev" external plgdidev : unit -> float * float * float * float = "camlidl_plplot_core_c_plgdidev" external plgdiori : unit -> float = "camlidl_plplot_core_c_plgdiori" external plgdiplt : unit -> float * float * float * float = "camlidl_plplot_core_c_plgdiplt" external plgdrawmode : unit -> plplot_draw_mode_enum = "camlidl_plplot_core_c_plgdrawmode" external plgfci : unit -> int64 = "camlidl_plplot_core_c_plgfci" external plgfam : unit -> int * int * int = "camlidl_plplot_core_c_plgfam" external plgfnam : unit -> string = "camlidl_plplot_core_c_plgfnam" external plgfont : unit -> int * int * int = "camlidl_plplot_core_c_plgfont" external plglevel : unit -> plplot_run_level = "camlidl_plplot_core_c_plglevel" external plgpage : unit -> float * float * int * int * int * int = "camlidl_plplot_core_c_plgpage" external plgra : unit -> unit = "camlidl_plplot_core_c_plgra" external plgradient : float array -> float array -> float -> unit = "camlidl_plplot_core_c_plgradient" external plgspa : unit -> float * float * float * float = "camlidl_plplot_core_c_plgspa" external plgstrm : unit -> int = "camlidl_plplot_core_c_plgstrm" external plgver : unit -> string = "camlidl_plplot_core_c_plgver" external plgvpd : unit -> float * float * float * float = "camlidl_plplot_core_c_plgvpd" external plgvpw : unit -> float * float * float * float = "camlidl_plplot_core_c_plgvpw" external plgxax : unit -> int * int = "camlidl_plplot_core_c_plgxax" external plgyax : unit -> int * int = "camlidl_plplot_core_c_plgyax" external plgzax : unit -> int * int = "camlidl_plplot_core_c_plgzax" external plhist : float array -> float -> float -> int -> plplot_hist_style -> unit = "camlidl_plplot_core_c_plhist" external plhlsrgb : float -> float -> float -> float * float * float = "camlidl_plplot_core_c_plhlsrgb" external plinit : unit -> unit = "camlidl_plplot_core_c_plinit" external pljoin : float -> float -> float -> float -> unit = "camlidl_plplot_core_c_pljoin" external pllab : string -> string -> string -> unit = "camlidl_plplot_core_c_pllab" external pllightsource : float -> float -> float -> unit = "camlidl_plplot_core_c_pllightsource" external plline : float array -> float array -> unit = "camlidl_plplot_core_c_plline" external plline3 : float array -> float array -> float array -> unit = "camlidl_plplot_core_c_plline3" external pllsty : int -> unit = "camlidl_plplot_core_c_pllsty" external plmesh : float array -> float array -> float array array -> plplot3d_style -> unit = "camlidl_plplot_core_c_plmesh" external plmeshc : float array -> float array -> float array array -> plplot3d_style -> float array -> unit = "camlidl_plplot_core_c_plmeshc" external plmkstrm : unit -> int = "camlidl_plplot_core_c_plmkstrm" external plmtex : string -> float -> float -> float -> string -> unit = "camlidl_plplot_core_c_plmtex" external plmtex3 : string -> float -> float -> float -> string -> unit = "camlidl_plplot_core_c_plmtex3" external plot3d : float array -> float array -> float array array -> plplot3d_style -> bool -> unit = "camlidl_plplot_core_c_plot3d" external plot3dc : float array -> float array -> float array array -> plplot3d_style -> float array -> unit = "camlidl_plplot_core_c_plot3dc" external plpat : int array -> int array -> unit = "camlidl_plplot_core_c_plpat" external plpath : int -> float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plpath" external plpoin : float array -> float array -> int -> unit = "camlidl_plplot_core_c_plpoin" external plpoin3 : float array -> float array -> float array -> int -> unit = "camlidl_plplot_core_c_plpoin3" external plprec : int -> int -> unit = "camlidl_plplot_core_c_plprec" external plpsty : int -> unit = "camlidl_plplot_core_c_plpsty" external plptex : float -> float -> float -> float -> float -> string -> unit = "camlidl_plplot_core_c_plptex_bytecode" "camlidl_plplot_core_c_plptex" external plptex3 : float -> float -> float -> float -> float -> float -> float -> float -> float -> float -> string -> unit = "camlidl_plplot_core_c_plptex3_bytecode" "camlidl_plplot_core_c_plptex3" external plrandd : unit -> float = "camlidl_plplot_core_c_plrandd" external plreplot : unit -> unit = "camlidl_plplot_core_c_plreplot" external plrgbhls : float -> float -> float -> float * float * float = "camlidl_plplot_core_c_plrgbhls" external plschr : float -> float -> unit = "camlidl_plplot_core_c_plschr" external plscmap0 : int array -> int array -> int array -> unit = "camlidl_plplot_core_c_plscmap0" external plscmap0a : int array -> int array -> int array -> float array -> unit = "camlidl_plplot_core_c_plscmap0a" external plscmap0n : int -> unit = "camlidl_plplot_core_c_plscmap0n" external plscmap1 : int array -> int array -> int array -> unit = "camlidl_plplot_core_c_plscmap1" external plscmap1a : int array -> int array -> int array -> float array -> unit = "camlidl_plplot_core_c_plscmap1a" external plscmap1l : bool -> float array -> float array -> float array -> float array -> bool array option -> unit = "camlidl_plplot_core_c_plscmap1l_bytecode" "camlidl_plplot_core_c_plscmap1l" external plscmap1la : bool -> float array -> float array -> float array -> float array -> float array -> bool array option -> unit = "camlidl_plplot_core_c_plscmap1la_bytecode" "camlidl_plplot_core_c_plscmap1la" external plscmap1n : int -> unit = "camlidl_plplot_core_c_plscmap1n" external plscmap1_range : float -> float -> unit = "camlidl_plplot_core_c_plscmap1_range" external plscol0 : int -> int -> int -> int -> unit = "camlidl_plplot_core_c_plscol0" external plscol0a : int -> int -> int -> int -> float -> unit = "camlidl_plplot_core_c_plscol0a" external plscolbg : int -> int -> int -> unit = "camlidl_plplot_core_c_plscolbg" external plscolbga : int -> int -> int -> float -> unit = "camlidl_plplot_core_c_plscolbga" external plscolor : int -> unit = "camlidl_plplot_core_c_plscolor" external plscompression : int -> unit = "camlidl_plplot_core_c_plscompression" external plsdev : string -> unit = "camlidl_plplot_core_c_plsdev" external plsdidev : float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plsdidev" external plsdimap : int -> int -> int -> int -> float -> float -> unit = "camlidl_plplot_core_c_plsdimap_bytecode" "camlidl_plplot_core_c_plsdimap" external plsdiori : float -> unit = "camlidl_plplot_core_c_plsdiori" external plsdiplt : float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plsdiplt" external plsdiplz : float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plsdiplz" external plseed : int64 -> unit = "camlidl_plplot_core_c_plseed" external plsesc : char -> unit = "camlidl_plplot_core_c_plsesc" external plsfam : int -> int -> int -> unit = "camlidl_plplot_core_c_plsfam" external plsfci : int64 -> unit = "camlidl_plplot_core_c_plsfci" external plsfnam : string -> unit = "camlidl_plplot_core_c_plsfnam" external plsfont : plplot_fci_family_enum -> plplot_fci_style_enum -> plplot_fci_weight_enum -> unit = "camlidl_plplot_core_c_plsfont" external plsmaj : float -> float -> unit = "camlidl_plplot_core_c_plsmaj" external plsmin : float -> float -> unit = "camlidl_plplot_core_c_plsmin" external plsdrawmode : plplot_draw_mode_enum -> unit = "camlidl_plplot_core_c_plsdrawmode" external plsori : int -> unit = "camlidl_plplot_core_c_plsori" external plspage : float -> float -> int -> int -> int -> int -> unit = "camlidl_plplot_core_c_plspage_bytecode" "camlidl_plplot_core_c_plspage" external plspal0 : string -> unit = "camlidl_plplot_core_c_plspal0" external plspal1 : string -> bool -> unit = "camlidl_plplot_core_c_plspal1" external plspause : bool -> unit = "camlidl_plplot_core_c_plspause" external plsstrm : int -> unit = "camlidl_plplot_core_c_plsstrm" external plssub : int -> int -> unit = "camlidl_plplot_core_c_plssub" external plssym : float -> float -> unit = "camlidl_plplot_core_c_plssym" external plstar : int -> int -> unit = "camlidl_plplot_core_c_plstar" external plstart : string -> int -> int -> unit = "camlidl_plplot_core_c_plstart" external plstring : float array -> float array -> string -> unit = "camlidl_plplot_core_c_plstring" external plstring3 : float array -> float array -> float array -> string -> unit = "camlidl_plplot_core_c_plstring3" external plstripa : int -> int -> float -> float -> unit = "camlidl_plplot_core_c_plstripa" external plstripd : int -> unit = "camlidl_plplot_core_c_plstripd" external plimage : float array array -> float -> float -> float -> float -> float -> float -> float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plimage_bytecode" "camlidl_plplot_core_c_plimage" external plstyl : int array -> int array -> unit = "camlidl_plplot_core_c_plstyl" external plsurf3d : float array -> float array -> float array array -> plplot3d_style -> float array -> unit = "camlidl_plplot_core_c_plsurf3d" external plsvect : float array -> float array -> bool -> unit = "camlidl_plplot_core_c_plsvect" external plsvpa : float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plsvpa" external plsxax : int -> int -> unit = "camlidl_plplot_core_c_plsxax" external plsxwin : int -> unit = "camlidl_plplot_core_plsxwin" external plsyax : int -> int -> unit = "camlidl_plplot_core_c_plsyax" external plsym : float array -> float array -> int -> unit = "camlidl_plplot_core_c_plsym" external plszax : int -> int -> unit = "camlidl_plplot_core_c_plszax" external pltext : unit -> unit = "camlidl_plplot_core_c_pltext" external pltimefmt : string -> unit = "camlidl_plplot_core_c_pltimefmt" external plvasp : float -> unit = "camlidl_plplot_core_c_plvasp" external plvpas : float -> float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plvpas" external plvpor : float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plvpor" external plvsta : unit -> unit = "camlidl_plplot_core_c_plvsta" external plw3d : float -> float -> float -> float -> float -> float -> float -> float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plw3d_bytecode" "camlidl_plplot_core_c_plw3d" external plwidth : float -> unit = "camlidl_plplot_core_c_plwidth" external plwind : float -> float -> float -> float -> unit = "camlidl_plplot_core_c_plwind" external plxormod : bool -> bool = "camlidl_plplot_core_c_plxormod" external plsetopt : string -> string -> unit = "camlidl_plplot_core_c_plsetopt" external plMinMax2dGrid : float array array -> float * float = "camlidl_plplot_core_plMinMax2dGrid" external plcont : float array array -> int -> int -> int -> int -> float array -> unit = "camlidl_plplot_core_ml_plcont_bytecode" "camlidl_plplot_core_ml_plcont" external plshade : float array array -> float -> float -> float -> float -> float -> float -> int -> float -> float -> int -> float -> int -> float -> bool -> unit = "camlidl_plplot_core_ml_plshade_bytecode" "camlidl_plplot_core_ml_plshade" external plshades : float array array -> float -> float -> float -> float -> float array -> float -> int -> float -> bool -> unit = "camlidl_plplot_core_ml_plshades_bytecode" "camlidl_plplot_core_ml_plshades" external plimagefr : float array array -> float -> float -> float -> float -> float -> float -> float -> float -> unit = "camlidl_plplot_core_ml_plimagefr_bytecode" "camlidl_plplot_core_ml_plimagefr" external plvect : float array array -> float array array -> float -> unit = "camlidl_plplot_core_ml_plvect" external plmap : string -> float -> float -> float -> float -> unit = "camlidl_plplot_core_ml_plmap" external plmeridians : float -> float -> float -> float -> float -> float -> unit = "camlidl_plplot_core_ml_plmeridians_bytecode" "camlidl_plplot_core_ml_plmeridians" external plpoly3 : float array -> float array -> float array -> bool array -> bool -> unit = "camlidl_plplot_core_ml_plpoly3" external pltr0 : float -> float -> float * float = "camlidl_plplot_core_ml_pltr0" external plsvect_reset : unit -> unit = "camlidl_plplot_core_ml_plsvect_reset" external plg_current_col0 : unit -> int = "camlidl_plplot_core_plg_current_col0" external plg_current_col1 : unit -> float = "camlidl_plplot_core_plg_current_col1" external plgwidth : unit -> float = "camlidl_plplot_core_plgwidth" external plgchrht : unit -> float = "camlidl_plplot_core_plgchrht" external plstripc : string -> string -> float -> float -> float -> float -> float -> float -> float -> bool -> bool -> int -> int -> int array -> int array -> string array -> string -> string -> string -> int = "ml_plstripc_byte" "ml_plstripc" external pltr1 : float array -> float array -> float -> float -> float * float = "ml_pltr1" external pltr2 : float array array -> float array array -> float -> float -> float * float = "ml_pltr2" val plset_pltr : (float -> float -> (float * float)) -> unit val plunset_pltr : unit -> unit val plset_mapform : (float -> float -> (float * float)) -> unit val plunset_mapform : unit -> unit val plset_defined : (float -> float -> int) -> unit val plunset_defined : unit -> unit val plstransform : (float -> float -> (float * float)) -> unit val plunset_transform : unit -> unit type plplot_grid_method_type = PL_GRID_CSA | PL_GRID_DTLI | PL_GRID_NNI | PL_GRID_NNIDW | PL_GRID_NNLI | PL_GRID_NNAIDW type plplot_parse_method_type = PL_PARSE_PARTIAL | PL_PARSE_FULL | PL_PARSE_QUIET | PL_PARSE_NODELETE | PL_PARSE_SHOWALL | PL_PARSE_OVERRIDE | PL_PARSE_NOPROGRAM | PL_PARSE_NODASH | PL_PARSE_SKIP type plplot_axis_type = PL_X_AXIS | PL_Y_AXIS | PL_Z_AXIS val plslabelfunc : (plplot_axis_type -> float -> string) -> unit val plunset_labelfunc : unit -> unit val plsabort : (string -> unit) -> unit val plunset_abort : unit -> unit val plsexit : (string -> int) -> unit val plunset_exit : unit -> unit external plgriddata : float array -> float array -> float array -> float array -> float array -> plplot_grid_method_type -> float -> float array array = "ml_plgriddata_bytecode" "ml_plgriddata" external plparseopts : string array -> plplot_parse_method_type list -> unit = "ml_plparseopts" external pllegend : plplot_legend_opt -> plplot_position_opt -> float -> float -> float -> int -> int -> int -> int -> int -> plplot_legend_opt array -> float -> float -> float -> float -> int array -> string array -> int array -> int array -> float array -> float array -> int array -> int array -> float array -> int array -> float array -> int array -> string array -> float * float = "ml_pllegend_byte" "ml_pllegend" external plcolorbar : plplot_colorbar_opt -> plplot_position_opt -> float -> float -> float -> float -> int -> int -> int -> float -> float -> int -> float -> plplot_colorbar_opt array -> string array -> string array -> float array -> int array -> float array array -> float * float = "ml_plcolorbar_byte" "ml_plcolorbar"
(* File generated from plplot_core.idl *)
scriptable.ml
open Error_monad type output_format = Rows of {separator : string; escape : [`No | `OCaml]} let rows separator escape = Rows {separator; escape} let tsv = rows "\t" `No let csv = rows "," `OCaml let clic_arg () = let open Clic in arg ~doc:"Make the output script-friendly. Possible values are 'TSV' and 'CSV'." ~long:"for-script" ~placeholder:"FORMAT" (parameter (fun _ spec -> let open Lwt_result_syntax in match String.lowercase_ascii spec with | "tsv" -> return tsv | "csv" -> return csv | other -> failwith "Cannot recognize format %S, please try 'TSV' or 'CSV'" other)) let fprintf_lwt chan fmt = let open Lwt_syntax in Format.kasprintf (fun s -> protect (fun () -> let* () = Lwt_io.write chan s in return_ok_unit)) fmt let output ?(channel = Lwt_io.stdout) how_option ~for_human ~for_script = let open Lwt_result_syntax in match how_option with | None -> for_human () | Some (Rows {separator; escape}) -> let open Format in let* () = List.iter_es (fun row -> fprintf_lwt channel "%a@." (pp_print_list ~pp_sep:(fun fmt () -> pp_print_string fmt separator) (fun fmt cell -> match escape with | `OCaml -> fprintf fmt "%S" cell | `No -> pp_print_string fmt cell)) row) (for_script ()) in protect (fun () -> let*! () = Lwt_io.flush channel in return_unit) let output_for_human how_option for_human = output how_option ~for_human ~for_script:(fun () -> []) let output_row ?channel how_option ~for_human ~for_script = output ?channel how_option ~for_human ~for_script:(fun () -> [for_script ()])
TestML.ml
open Client (* A few manually constructed terms. *) let dummy_pos = ML.dummy_pos let hole = ML.Hole (dummy_pos, []) let x = ML.Var (dummy_pos, "x") let y = ML.Var (dummy_pos, "y") let id = ML.Abs (dummy_pos, "x", x) let delta = ML.Abs (dummy_pos, "x", ML.App (dummy_pos, x, x)) (* unused *) let _deltadelta = ML.App (dummy_pos, delta, delta) let idid = ML.App (dummy_pos, id, id) let k = ML.Abs (dummy_pos, "x", ML.Abs (dummy_pos, "y", x)) let genid = ML.Let (dummy_pos, "x", id, x) let genidid = ML.Let (dummy_pos, "x", id, ML.App (dummy_pos, x, x)) let genkidid = ML.Let (dummy_pos, "x", ML.App (dummy_pos, k, id), ML.App (dummy_pos, x, id)) let genkidid2 = ML.Let (dummy_pos, "x", ML.App (dummy_pos, ML.App (dummy_pos, k, id), id), x) (* unused *) let _app_pair = (* ill-typed *) ML.App (dummy_pos, ML.Tuple (dummy_pos, [id; id]), id) let unit = ML.Tuple (dummy_pos, []) (* "let x1 = (...[], ...[]) in ...[] x1" *) let regression1 = ML.Let (dummy_pos, "x1", ML.Tuple (dummy_pos, [ ML.Hole (dummy_pos, []) ; ML.Hole (dummy_pos, []) ]), ML.App (dummy_pos, ML.Hole (dummy_pos, []), ML.Var (dummy_pos, "x1"))) (* "let f = fun x -> let g = fun y -> (x, y) in g in fun x -> fun y -> f" *) let regression2 = ML.( Let (dummy_pos, "f", Abs (dummy_pos, "x", Let (dummy_pos, "g", Abs (dummy_pos, "y", Tuple (dummy_pos, [x; y]) ), Var (dummy_pos, "g") )), Abs(dummy_pos, "x", Abs(dummy_pos, "y", Var (dummy_pos, "f")))) ) let abs_match_with = ML.( Abs( dummy_pos, "x", Match( dummy_pos, Tuple (dummy_pos, []), [ (PTuple (dummy_pos, []), Tuple (dummy_pos, [])) ] ) ) ) (* option *) let option_env = (* type 'a option = None | Some of 'a *) let option_typedecl = let open Datatype in { name = Type "option"; type_params = [ "'a" ]; data_kind = Variant; labels_descr = [ { label_name = Label"None"; type_name = Type "option"; arg_type = None; } ; { label_name = Label "Some"; type_name = Type "option"; arg_type = Some (ML.TyVar (dummy_pos,"'a")); } ] } in Datatype.Env.add_decl Datatype.Env.empty option_typedecl let none = ML.Variant (dummy_pos, Datatype.Label "None" , None ) let some = ML.Variant ( dummy_pos, Datatype.Label "Some", Some id ) let match_none = ML.( Match (dummy_pos, none, [ PVariant (dummy_pos, Datatype.Label "None", None), none ; PVariant (dummy_pos, Datatype.Label "Some", Some (PVar (dummy_pos, "x"))), x ; ]) ) let match_some = ML.( Match (dummy_pos, some, [ PVariant (dummy_pos, Datatype.Label "None", None), none ; PVariant (dummy_pos, Datatype.Label "Some", Some (PWildcard dummy_pos)), none ]) ) let match_some_annotated = ML.( Match (dummy_pos, some, [ ( PVariant (dummy_pos, Datatype.Label "None", None), none ); ( PAnnot (dummy_pos, PVariant (dummy_pos, Datatype.Label "Some", Some (PWildcard dummy_pos)), (Flexible, ["'a"], TyConstr (dummy_pos, Datatype.Type "option", [ TyVar (dummy_pos, "'a") ]))), none ); ]) ) (* list *) let list_env = (* type 'a list = Nil | Cons of 'a * 'a list *) let list_typedecl = let open Datatype in { name = Type "list"; type_params = [ "'a" ]; data_kind = Variant; labels_descr = [ { label_name = Label "Nil"; type_name = Type "list"; arg_type = None; } ; { label_name = Label "Cons"; type_name = Type "list"; arg_type = Some (ML.(TyProduct (dummy_pos, [ TyVar (dummy_pos, "'a") ; TyConstr (dummy_pos, Type "list", [ TyVar (dummy_pos, "'a") ]) ] ))); } ] } in Datatype.Env.add_decl option_env list_typedecl let nil = ML.Variant (dummy_pos, Datatype.Label "Nil" , None ) let cons = ML.Variant ( dummy_pos, Datatype.Label "Cons", Some (ML.Tuple (dummy_pos, [ id ; nil ])) ) (* unused *) let _list_annotated = let open ML in Annot ( dummy_pos, Variant ( dummy_pos, Datatype.Label "Cons", Some (Tuple (dummy_pos, [ Annot (dummy_pos, id, (Flexible, ["'a"], TyArrow (dummy_pos, TyVar (dummy_pos, "'a"), TyVar (dummy_pos, "'a")))); nil ])) ), (Flexible, ["'a"; "'b"], TyConstr (dummy_pos, Datatype.Type "list", [TyArrow (dummy_pos, TyVar (dummy_pos, "'a"), TyVar (dummy_pos, "'b"))])) ) (* tree *) let tree_env = (* type 'a tree = Leaf | Node of 'a tree * 'a * 'a tree *) let tree_typedecl = let open Datatype in { name = Type "tree"; type_params = [ "'a" ]; data_kind = Variant; labels_descr = [ { label_name = Label "Leaf"; type_name = Type "tree"; arg_type = None } ; { label_name = Label "Node"; type_name = Type "tree"; arg_type = Some (ML.(TyProduct (dummy_pos, [ TyConstr (dummy_pos, Type "tree", [ TyVar (dummy_pos, "'a") ]); TyVar (dummy_pos, "'a"); TyConstr (dummy_pos, Type "tree", [ TyVar (dummy_pos, "'a") ]); ]))) } ]; } in Datatype.Env.add_decl list_env tree_typedecl let leaf = ML.Variant (dummy_pos, Datatype.Label "Leaf" , None ) let node = ML.Variant ( dummy_pos, Datatype.Label "Node", Some (ML.Tuple (dummy_pos, [ leaf ; id ; leaf ; ])) ) (* Families of terms of increasing size. *) let rec boom n = if n = 0 then "let f = fun x -> fun f -> f x x in " else boom (n - 1) ^ "let f = fun x -> f (f x) in " let boom n = boom n ^ "f" let parse (s : string) : ML.term = let lexbuf = Lexing.from_string s in MLParser.self_contained_term MLLexer.read lexbuf let boom n = parse (boom n) (* Infrastructure. *) let test_ok_from_ast datatype_env t () = Alcotest.(check bool) "type inference" (Test.CheckML.test ~rectypes:false datatype_env t) true let test_case msg datatype_env t = Alcotest.(test_case msg `Quick (test_ok_from_ast datatype_env t)) (* TODO: there is also a function named [test_case] in core.ml, this is confusing! *) let test_suite = let empty = Datatype.Env.empty in ( "test ML ast", [ test_case "hole" empty hole ; test_case "id" empty id ; test_case "id id" empty idid ; test_case "gen id" empty genid ; test_case "gen id id" empty genidid ; test_case "gen k id id" empty genkidid ; test_case "gen k id id 2" empty genkidid2 ; test_case "none" option_env none ; test_case "some" option_env some ; test_case "nil" list_env nil ; test_case "list" list_env cons ; test_case "leaf" tree_env leaf ; test_case "node" tree_env node ; test_case "abs match with" empty abs_match_with ; test_case "match none" option_env match_none ; test_case "match some" option_env match_some ; test_case "boom 0" empty (boom 0); test_case "boom 1" empty (boom 1); test_case "boom 2" empty (boom 2); test_case "boom 3" empty (boom 3); test_case "boom 4" empty (boom 4); (* boom 4 requires about 0.8 seconds *) (* boom 5 explodes, at over 25Gb and 60 seconds. *) ] ) (* -------------------------------------------------------------------------- *) let testable_term = let pprint fmt t = PPrint.ToFormatter.pretty 0.9 80 fmt (MLPrinter.print_term t) in Alcotest.testable pprint Test.CheckML.equal_term let test_ok ?(typedecl="") s expected = let (datatype_env, t) = Test.CheckML.from_string typedecl s in Alcotest.check' testable_term ~msg:"equal" ~expected ~actual:t; Alcotest.(check bool) "type inference" (Test.CheckML.test ~rectypes:false datatype_env t) true let test_error_parsing ?(typedecl="") s = let ok = match Test.CheckML.from_string typedecl s with | exception Test.CheckML.ParsingError _ -> false | _ -> true in Alcotest.(check bool "parsing" ok false) let test_id () = test_ok "fun x -> x" id let test_delta_delta_error () = test_error_parsing "(fun x -> x x (fun x -> x x)" let test_idid () = test_ok "(fun x -> x) (fun x -> x)" idid let test_idid_error () = test_error_parsing "fun x -> x fun x -> x" let test_unit () = test_ok "()" unit let test_abs_match_with () = test_ok "fun x -> match () with () -> () end" abs_match_with let test_let () = test_ok "let y = fun x -> x in ()" (ML.Let(dummy_pos, "y", id, unit)) let test_let_prod_singleton () = test_ok "let (y,) = (fun x -> x,) in ()" (ML.LetProd (dummy_pos, ["y"], ML.Tuple (dummy_pos, [id]), unit)) let test_let_prod () = test_ok "let (y,z) = (fun x -> x, ()) in ()" (ML.LetProd (dummy_pos, ["y";"z"], ML.Tuple (dummy_pos, [id;unit]), unit)) let test_singleton () = test_ok "(fun x -> x,)" (ML.Tuple (dummy_pos, [id])) let test_pair_tuple () = test_ok "(fun x -> x, fun x -> x)" (ML.Tuple (dummy_pos, [id; id])) let option_env_str = "type option 'a = None | Some of 'a" let test_none () = test_ok ~typedecl:option_env_str "None" none let test_some () = test_ok ~typedecl:option_env_str "Some (fun x -> x)" some let test_some_pair () = test_ok ~typedecl:option_env_str "Some (fun x -> x, fun x -> x)" (ML.Variant (dummy_pos, Datatype.Label "Some", Some (ML.Tuple (dummy_pos, [id;id])))) let list_env_str = "type list 'a = Nil | Cons of {'a * list 'a}" let test_list_nil () = test_ok ~typedecl:list_env_str "Nil" nil let test_list_cons () = test_ok ~typedecl:list_env_str "Cons (fun x -> x, Nil)" cons let test_arrow () = test_ok ~typedecl:"type func 'a 'b = Func of 'a -> 'b" "Func (fun x -> x)" (ML.Variant (dummy_pos, Datatype.Label "Func", Some id)) let test_match_tuple () = test_ok "match (fun x -> x, ()) with (f, ()) -> f end" (ML.Match (dummy_pos, ML.Tuple (dummy_pos, [id;unit]), [ (ML.PTuple (dummy_pos, [ML.PVar (dummy_pos, "f"); ML.PTuple (dummy_pos, [])]), ML.Var (dummy_pos, "f")) ] )) let test_match_none () = test_ok ~typedecl:option_env_str {|match None with | None -> None | Some x -> x end|} match_none let test_match_some () = test_ok ~typedecl:option_env_str {|match Some (fun x -> x) with | None -> None | Some _ -> None end|} match_some let test_match_some_annotated () = test_ok ~typedecl:option_env_str {|match Some (fun x -> x) with | None -> None | (Some _ : some 'a. option 'a) -> None end|} match_some_annotated (** Regressions *) let test_regression1 () = test_ok "let x1 = (...[], ...[]) in ...[] x1" regression1 let test_regression2 () = test_ok "let f = fun x -> let g = fun y -> (x, y) in g in fun x -> fun y -> f" regression2 let a = ML.TyVar (dummy_pos, "'a") let b = ML.TyVar (dummy_pos, "'b") let id_annot annot = ML.(Annot (dummy_pos, Abs(dummy_pos, "x", Var (dummy_pos, "x")), annot)) let test_id_rigid () = test_ok "(fun x -> x : for 'a. 'a -> 'a)" (id_annot (ML.Rigid, ["'a"], ML.TyArrow (dummy_pos, a, a))) let test_id_flexible () = test_ok "(fun x -> x : some 'a 'b. 'a -> 'b)" (id_annot (ML.Flexible, ["'a"; "'b"], ML.TyArrow (dummy_pos, a, b))) let test_suite = let open Alcotest in test_suite :: [ ( "basics", [ test_case "id" `Quick test_id; test_case "id id" `Quick test_idid; test_case "id id error" `Quick test_idid_error; test_case "delta delta error" `Quick test_delta_delta_error; test_case "unit" `Quick test_unit; test_case "regression1" `Quick test_regression1; test_case "regression2" `Quick test_regression2; test_case "abs match with" `Quick test_abs_match_with; test_case "let" `Quick test_let; test_case "let prod singleton" `Quick test_let_prod_singleton; test_case "let prod" `Quick test_let_prod; test_case "singleton" `Quick test_singleton; ] ) ; ( "data structures", [ test_case "pair tuple" `Quick test_pair_tuple; test_case "none" `Quick test_none; test_case "some" `Quick test_some; test_case "some pair" `Quick test_some_pair; test_case "list nil" `Quick test_list_nil; test_case "list cons" `Quick test_list_cons; test_case "arrow" `Quick test_arrow; ] ) ; ( "pattern matching", [ test_case "match tuple" `Quick test_match_tuple; test_case "match none" `Quick test_match_none; test_case "match some" `Quick test_match_some; test_case "match some annotated" `Quick test_match_some_annotated; ] ) ; ( "rigid", [ test_case "id rigid" `Quick test_id_rigid; test_case "id flexible" `Quick test_id_flexible; ] ) ] let () = Alcotest.run ~verbose:false "ML test suite" test_suite
css_jane.mli
open! Core type 'a with_loc = 'a * Location.t module rec Dimension : sig type t = | Length | Angle | Time | Frequency [@@deriving sexp_of] end and Component_value : sig type t = | Paren_block of t with_loc list | Bracket_block of t with_loc list | Percentage of string | Ident of string | String of string | Uri of string | Operator of string | Delim of string | Function of string with_loc * t with_loc list with_loc | Hash of string | Number of string | Unicode_range of string | Float_dimension of (string * string * Dimension.t) | Dimension of (string * string) [@@deriving sexp_of] end and Brace_block : sig type t = | Empty | Declaration_list of Declaration_list.t | Stylesheet of Stylesheet.t [@@deriving sexp_of] end and At_rule : sig type t = { name : string with_loc ; prelude : Component_value.t with_loc list with_loc ; block : Brace_block.t ; loc : Location.t } [@@deriving sexp_of] end and Declaration : sig type t = { name : string with_loc ; value : Component_value.t with_loc list with_loc ; important : bool with_loc ; loc : Location.t } [@@deriving sexp_of] end and Declaration_list : sig type kind = | Declaration of Declaration.t | At_rule of At_rule.t [@@deriving sexp_of] type t = kind list with_loc [@@deriving sexp_of] end and Style_rule : sig type t = { prelude : Component_value.t with_loc list with_loc ; block : Declaration_list.t ; loc : Location.t } [@@deriving sexp_of] end and Rule : sig type t = | Style_rule of Style_rule.t | At_rule of At_rule.t [@@deriving sexp_of] end and Stylesheet : sig type t = Rule.t list with_loc [@@deriving sexp_of] val to_string_hum : t -> string val to_string_minified : t -> string val of_string : ?pos:Source_code_position.t -> string -> t end
log.ml
(** Logging *) let log_src = Logs.Src.create ~doc:"Log for Css library" "css" module Log = (val Logs.src_log log_src) include Log
(*********************************************************************************) (* OCaml-CSS *) (* *) (* Copyright (C) 2023 INRIA All rights reserved. *) (* Author: Maxence Guesdon, INRIA Saclay *) (* *) (* This program is free software; you can redistribute it and/or modify *) (* it under the terms of the GNU General Public License as *) (* published by the Free Software Foundation, version 3 of the License. *) (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) (* You should have received a copy of the GNU General Public *) (* License along with this program; if not, write to the Free Software *) (* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA *) (* 02111-1307 USA *) (* *) (* As a special exception, you have permission to link this program *) (* with the OCaml compiler and distribute executables, as long as you *) (* follow the requirements of the GNU GPL in regard to all of the *) (* software in the executable aside from the OCaml compiler. *) (* *) (* Contact: Maxence.Guesdon@inria.fr *) (* *) (*********************************************************************************)
runner.mli
(** Runner specifications for processes spawned remotely using SSH. *) (** Connection information for a runner. See {!create}. *) type t = private { id : int; address : string; ssh_alias : string option; ssh_user : string option; ssh_port : int option; ssh_id : string option; } (** Create a runner. This function does not start any SSH connection, it only stores SSH connection information in a record. - [ssh_alias] is the alias in the ssh config file. - [ssh_user] is the username on the remote machine. - [ssh_port] is the port on the remote machine. - [ssh_id] is the path to the identity file. - [address] is the IP address of the remote machine. *) val create : ?ssh_alias:string -> ?ssh_user:string -> ?ssh_port:int -> ?ssh_id:string -> address:string -> unit -> t (** Get the IP address of the local machine as perceived by other runners. Use this if you need a runner to reach a process that is running on the local machine. This returns ["127.0.0.1"] by default, but you can set it with {!set_local_public_ip}. *) val get_local_public_ip : unit -> string (** Set the IP address of the local machine as perceived by other runners. *) val set_local_public_ip : string -> unit (** Get the IP / DNS address of a runner. Usage: [address ~from runner] Return the address at which a source node [from] can contact [runner]. If the source node [from] is not specified, return the [address] of [runner] as given to {!create}. If [runner] itself is [None], return ["127.0.0.1"] or ["localhost"] if the [hostname] variable is set to true (default false). If [from] is specified: - if [runner] is [None], return [get_local_public_ip ()]; - if [from] and [runner] are the same runner, return ["127.0.0.1"]; - else, return the [address] of [runner]. *) val address : ?hostname:bool -> ?from:t -> t option -> string module Shell : sig (** Shell command representation. This module is used for the subset of the shell language that is needed to operate remote runners through SSH. It makes sure that shell command are properly quoted. *) (** Commands. Commands execute a program (whose executable name is [name]), with some [arguments], possibly with some specific environment variables [local_env] to add to the current environment. *) type command = { local_env : (string * string) list; name : string; arguments : string list; } (** Shell programs. *) type t = | Cmd of command (** run a command *) | Seq of t * t (** run something, then something else ([;]) *) | Echo_pid (** echo the current process PID ([echo $$]) *) | Redirect_stdout of t * string (** redirect stdout to a file ([>]) *) | Redirect_stderr of t * string (** redirect stderr to a file ([2>]) *) | Or_echo_false of t (** run something, if it fails, print "false" ([|| echo false]) *) (** Convert a shell program into a string. The result is quoted using shell syntax. [context] specifies whether parentheses are needed: - [`top] means no parentheses are needed (default); - [`operator] means parentheses may be needed because this command is inside of an operator such as [;] or [||]. *) val to_string : ?context:[`operator | `top] -> t -> string (** Make a command to execute a program. Usage: [cmd local_env name arguments] Same as: [Cmd { local_env; name; arguments }] *) val cmd : (string * string) list -> string -> string list -> t (** Make a sequence. Usage: [seq command_1 command_2] Same as: [Seq (command_1, command_2)] *) val seq : t -> t -> t (** Make an stdout redirection. Usage: [redirect_stdout command path] Same as: [Redirect_stdout (command, path)] *) val redirect_stdout : t -> string -> t (** Make an stderr redirection. Usage: [redirect_stderr command path] Same as: [Redirect_stderr (command, path)] *) val redirect_stderr : t -> string -> t (** Make a shell program that prints "false" if another program fails. Usage: [or_echo_false command] Same as: [Or_echo_false command] *) val or_echo_false : t -> t end (** Wrap a shell command into an SSH call. Usage: [wrap_with_ssh runner shell] Return [(name, arguments)] where [name] is ["ssh"] and [arguments] are arguments to pass to SSH to execute [shell] on [runner]. *) val wrap_with_ssh : t -> Shell.t -> string * string list (** Same as {!wrap_with_ssh}, but print the PID on stdout first. The PID can be used later on to, for instance, kill the remote process. Indeed, killing the local SSH process will not necessarily kill the remote process. *) val wrap_with_ssh_pid : t -> Shell.command -> string * string list module Sys : sig (** Extension to [Stdlib.Sys] that can also execute on remote runners. Most functions from this module just call their [Stdlib.Sys] equivalent when [runner] is not specified. When [runner] is specified, they instead use SSH to execute a shell command remotely with a similar effect. *) (** Errors that can occur when executing a [Sys] command on a remote runner. *) type error (** Exception raised when failing to execute a [Sys] command remotely. This is not raised when running a command without a [runner]. Instead, [Sys_error] is raised. *) exception Remote_error of error (** Convert an error to an error message. *) val show_error : error -> string (** Check if a file exists on the system. For the local version, see {{: https://ocaml.org/api/Sys.html} Sys.file_exists}. *) val file_exists : ?runner:t -> string -> bool (** Create a new directory. For the local version, see {{: https://ocaml.org/api/Unix.html} Unix.mkdir}. *) val mkdir : ?runner:t -> ?perms:int -> string -> unit (** Check if a file exists and is a directory. For the local version, see {{: https://ocaml.org/api/Sys.html} Sys.is_directory}. *) val is_directory : ?runner:t -> string -> bool (** Return the contents of a directory. For the local version, see {{: https://ocaml.org/api/Sys.html} Sys.readdir}. *) val readdir : ?runner:t -> string -> string array (** Remove a file. For the local version, see {{: https://ocaml.org/api/Sys.html} Sys.remove}. *) val remove : ?runner:t -> string -> unit (** Remove recursively with [rm -rf]. Only implemented for remote runners. *) val rm_rf : t -> string -> unit (** Remove a directory. For the local version, see {{: https://ocaml.org/api/Unix.html} Unix.rmdir}. *) val rmdir : ?runner:t -> string -> unit (** Create a named pipe. For the local version, see {{: https://ocaml.org/api/Unix.html} Unix.mkfifo}. *) val mkfifo : ?runner:t -> ?perms:int -> string -> unit end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2021-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. *) (* *) (*****************************************************************************)
div.c
#include "fmpq_mpoly.h" void fmpq_mpoly_div(fmpq_mpoly_t Q, const fmpq_mpoly_t A, const fmpq_mpoly_t B, const fmpq_mpoly_ctx_t ctx) { fmpz_t scale; if (fmpq_mpoly_is_zero(B, ctx)) { flint_throw(FLINT_DIVZERO, "Divide by zero in fmpq_mpoly_div"); } if (fmpq_mpoly_is_zero(A, ctx)) { fmpq_mpoly_zero(Q, ctx); return; } fmpz_init(scale); fmpz_mpoly_quasidiv(scale, Q->zpoly, A->zpoly, B->zpoly, ctx->zctx); fmpq_div(Q->content, A->content, B->content); fmpq_div_fmpz(Q->content, Q->content, scale); fmpz_clear(scale); fmpq_mpoly_reduce(Q, ctx); }
/* Copyright (C) 2018 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/>. */
dune
(library (name file_path_test) (public_name file_path.file_path_test) (libraries async core_unix.command_test_helpers core expect_test_helpers_async expect_test_helpers_core file_path) (preprocess (pps ppx_jane)))
aim_with_mouse.ml
open OcamlCanvas.V1 let events = ref [] let retain_event e = events := e :: !events let clear_events () = events := [] let state = ref (0.0, 0.0, 0.0, 0.0) let () = Backend.init (); let c = Canvas.createOnscreen ~title:"Aim with mouse" ~pos:(300, 50) ~size:(800, 600) () in Canvas.show c; Canvas.setShadowBlur c 2.; Canvas.setShadowColor c (Color.of_argb 128 0 0 0); Canvas.setShadowOffset c (2., 2.); Canvas.setFillColor c Color.white; Canvas.fillRect c ~pos:(0.0, 0.0) ~size:(800.0, 600.0); let a = Array.create_float 2 in Array.set a 0 20.0; Array.set a 1 20.0; Canvas.setLineDash c (a); retain_event @@ React.E.map (fun _ -> Backend.stop () ) Event.close; retain_event @@ React.E.map (fun { Event.data = { Event.key; _ }; _ } -> if key = KeyEscape then Backend.stop () ) Event.key_down; retain_event @@ React.E.map (fun { Event.data = (x, y); _ } -> let _a, _b, _tan_alpha, old_t = !state in let a = float_of_int x in let b = float_of_int y in let g = 100. and v = 600. in let t = -. (g *. a *. a) /. (v *. v) in let tan_alpha = (-. a +. sqrt (a *. a -. 4.0 *. t *. (b +. t -. 600.0))) /. (2.0 *. t) in state := (a, b, tan_alpha, old_t) ) Event.mouse_move; retain_event @@ React.E.map (fun _ -> let a, b, tan_alpha, t = !state in let t = t -. 1. in Canvas.setLineDashOffset c t; Canvas.fillRect c ~pos:(0.0, 0.0) ~size:(800.0, 600.0); Canvas.clearPath c; Canvas.moveTo c (0.0, 600.0); let alpha = atan tan_alpha in let cos_a = cos alpha and sin_a = sin alpha in let n = 10 in for i = 1 to n do let x_1 = (float_of_int i) *. a /. (float_of_int n) and g = 100. and v = 600. in let y_1 = (-. sin_a) *. (x_1 /. cos_a) +. g *. (x_1 *. x_1) /. (cos_a *. cos_a *. v *. v) +. 600.0 in Canvas.lineTo c (x_1, y_1) done; Canvas.stroke c; Canvas.clearPath c; state := (a, b, tan_alpha, t) ) Event.frame; Backend.run (fun () -> clear_events (); Printf.printf "Goodbye !\n")
(**************************************************************************) (* *) (* Copyright 2022 OCamlPro *) (* *) (* 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. *) (* *) (**************************************************************************)
operation_result.ml
open Protocol open Alpha_context open Apply_results let pp_manager_operation_content (type kind) source internal pp_result ppf ((operation, result) : kind manager_operation * _) = Format.fprintf ppf "@[<v 0>" ; (match operation with | Transaction {destination; amount; parameters; entrypoint} -> Format.fprintf ppf "@[<v 2>%s:@,Amount: %s%a@,From: %a@,To: %a" (if internal then "Internal transaction" else "Transaction") Client_proto_args.tez_sym Tez.pp amount Contract.pp source Contract.pp destination ; (match entrypoint with | "default" -> () | _ -> Format.fprintf ppf "@,Entrypoint: %s" entrypoint) ; (if not (Script_repr.is_unit_parameter parameters) then let expr = WithExceptions.Option.to_exn ~none:(Failure "ill-serialized argument") (Data_encoding.force_decode parameters) in Format.fprintf ppf "@,Parameter: @[<v 0>%a@]" Michelson_v1_printer.print_expr expr) ; pp_result ppf result ; Format.fprintf ppf "@]" | Origination {delegate; credit; script = {code; storage}; preorigination = _} -> Format.fprintf ppf "@[<v 2>%s:@,From: %a@,Credit: %s%a" (if internal then "Internal origination" else "Origination") Contract.pp source Client_proto_args.tez_sym Tez.pp credit ; let code = WithExceptions.Option.to_exn ~none:(Failure "ill-serialized code") (Data_encoding.force_decode code) and storage = WithExceptions.Option.to_exn ~none:(Failure "ill-serialized storage") (Data_encoding.force_decode storage) in let {Michelson_v1_parser.source; _} = Michelson_v1_printer.unparse_toplevel code in Format.fprintf ppf "@,@[<hv 2>Script:@ @[<h>%a@]@,@[<hv 2>Initial storage:@ %a@]" Format.pp_print_text source Michelson_v1_printer.print_expr storage ; (match delegate with | None -> Format.fprintf ppf "@,No delegate for this contract" | Some delegate -> Format.fprintf ppf "@,Delegate: %a" Signature.Public_key_hash.pp delegate) ; pp_result ppf result ; Format.fprintf ppf "@]" | Reveal key -> Format.fprintf ppf "@[<v 2>%s of manager public key:@,Contract: %a@,Key: %a%a@]" (if internal then "Internal revelation" else "Revelation") Contract.pp source Signature.Public_key.pp key pp_result result | Delegation None -> Format.fprintf ppf "@[<v 2>%s:@,Contract: %a@,To: nobody%a@]" (if internal then "Internal Delegation" else "Delegation") Contract.pp source pp_result result | Delegation (Some delegate) -> Format.fprintf ppf "@[<v 2>%s:@,Contract: %a@,To: %a%a@]" (if internal then "Internal Delegation" else "Delegation") Contract.pp source Signature.Public_key_hash.pp delegate pp_result result) ; Format.fprintf ppf "@]" let pp_balance_updates ppf = function | [] -> () | balance_updates -> let open Delegate in let balance_updates = List.map (fun (balance, update) -> let balance = match balance with | Contract c -> Format.asprintf "%a" Contract.pp c | Rewards (pkh, l) -> Format.asprintf "rewards(%a,%a)" Signature.Public_key_hash.pp pkh Cycle.pp l | Fees (pkh, l) -> Format.asprintf "fees(%a,%a)" Signature.Public_key_hash.pp pkh Cycle.pp l | Deposits (pkh, l) -> Format.asprintf "deposits(%a,%a)" Signature.Public_key_hash.pp pkh Cycle.pp l in (balance, update)) balance_updates in let column_size = List.fold_left (fun acc (balance, _) -> Compare.Int.max acc (String.length balance)) 0 balance_updates in let pp_update ppf = function | Credited amount -> Format.fprintf ppf "+%s%a" Client_proto_args.tez_sym Tez.pp amount | Debited amount -> Format.fprintf ppf "-%s%a" Client_proto_args.tez_sym Tez.pp amount in let pp_one ppf (balance, update) = let to_fill = column_size + 3 - String.length balance in let filler = String.make to_fill '.' in Format.fprintf ppf "%s %s %a" balance filler pp_update update in Format.fprintf ppf "@[<v 0>%a@]" (Format.pp_print_list pp_one) balance_updates let pp_manager_operation_contents_and_result ppf ( Manager_operation {source; fee; operation; counter; gas_limit; storage_limit}, Manager_operation_result {balance_updates; operation_result; internal_operation_results} ) = let pp_transaction_result (Transaction_result { balance_updates; consumed_gas; storage; originated_contracts; storage_size; paid_storage_size_diff; big_map_diff; allocated_destination_contract = _; }) = (match originated_contracts with | [] -> () | contracts -> Format.fprintf ppf "@,@[<v 2>Originated contracts:@,%a@]" (Format.pp_print_list Contract.pp) contracts) ; (match storage with | None -> () | Some expr -> Format.fprintf ppf "@,@[<hv 2>Updated storage:@ %a@]" Michelson_v1_printer.print_expr expr) ; (match big_map_diff with | None | Some [] -> () | Some diff -> Format.fprintf ppf "@,@[<v 2>Updated big_maps:@ %a@]" Michelson_v1_printer.print_big_map_diff diff) ; if storage_size <> Z.zero then Format.fprintf ppf "@,Storage size: %s bytes" (Z.to_string storage_size) ; if paid_storage_size_diff <> Z.zero then Format.fprintf ppf "@,Paid storage size diff: %s bytes" (Z.to_string paid_storage_size_diff) ; Format.fprintf ppf "@,Consumed gas: %s" (Z.to_string consumed_gas) ; match balance_updates with | [] -> () | balance_updates -> Format.fprintf ppf "@,Balance updates:@, %a" pp_balance_updates balance_updates in let pp_origination_result (Origination_result { big_map_diff; balance_updates; consumed_gas; originated_contracts; storage_size; paid_storage_size_diff; }) = (match originated_contracts with | [] -> () | contracts -> Format.fprintf ppf "@,@[<v 2>Originated contracts:@,%a@]" (Format.pp_print_list Contract.pp) contracts) ; if storage_size <> Z.zero then Format.fprintf ppf "@,Storage size: %s bytes" (Z.to_string storage_size) ; (match big_map_diff with | None | Some [] -> () | Some diff -> Format.fprintf ppf "@,@[<v 2>Updated big_maps:@ %a@]" Michelson_v1_printer.print_big_map_diff diff) ; if paid_storage_size_diff <> Z.zero then Format.fprintf ppf "@,Paid storage size diff: %s bytes" (Z.to_string paid_storage_size_diff) ; Format.fprintf ppf "@,Consumed gas: %s" (Z.to_string consumed_gas) ; match balance_updates with | [] -> () | balance_updates -> Format.fprintf ppf "@,Balance updates:@, %a" pp_balance_updates balance_updates in let pp_result (type kind) ppf (result : kind manager_operation_result) = Format.fprintf ppf "@," ; match result with | Skipped _ -> Format.fprintf ppf "This operation was skipped" | Failed (_, _errs) -> Format.fprintf ppf "This operation FAILED." | Applied (Reveal_result {consumed_gas}) -> Format.fprintf ppf "This revelation was successfully applied" ; Format.fprintf ppf "@,Consumed gas: %s" (Z.to_string consumed_gas) | Backtracked (Reveal_result _, _) -> Format.fprintf ppf "@[<v 0>This revelation was BACKTRACKED, its expected effects were \ NOT applied.@]" | Applied (Delegation_result {consumed_gas}) -> Format.fprintf ppf "This delegation was successfully applied" ; Format.fprintf ppf "@,Consumed gas: %s" (Z.to_string consumed_gas) | Backtracked (Delegation_result _, _) -> Format.fprintf ppf "@[<v 0>This delegation was BACKTRACKED, its expected effects were \ NOT applied.@]" | Applied (Transaction_result _ as tx) -> Format.fprintf ppf "This transaction was successfully applied" ; pp_transaction_result tx | Backtracked ((Transaction_result _ as tx), _errs) -> Format.fprintf ppf "@[<v 0>This transaction was BACKTRACKED, its expected effects (as \ follow) were NOT applied.@]" ; pp_transaction_result tx | Applied (Origination_result _ as op) -> Format.fprintf ppf "This origination was successfully applied" ; pp_origination_result op | Backtracked ((Origination_result _ as op), _errs) -> Format.fprintf ppf "@[<v 0>This origination was BACKTRACKED, its expected effects (as \ follow) were NOT applied.@]" ; pp_origination_result op in Format.fprintf ppf "@[<v 0>@[<v 2>Manager signed operations:@,\ From: %a@,\ Fee to the baker: %s%a@,\ Expected counter: %s@,\ Gas limit: %s@,\ Storage limit: %s bytes" Signature.Public_key_hash.pp source Client_proto_args.tez_sym Tez.pp fee (Z.to_string counter) (Z.to_string gas_limit) (Z.to_string storage_limit) ; (match balance_updates with | [] -> () | balance_updates -> Format.fprintf ppf "@,Balance updates:@, %a" pp_balance_updates balance_updates) ; Format.fprintf ppf "@,%a" (pp_manager_operation_content (Contract.implicit_contract source) false pp_result) (operation, operation_result) ; (match internal_operation_results with | [] -> () | _ :: _ -> Format.fprintf ppf "@,@[<v 2>Internal operations:@ %a@]" (Format.pp_print_list (fun ppf (Internal_operation_result (op, res)) -> pp_manager_operation_content op.source false pp_result ppf (op.operation, res))) internal_operation_results) ; Format.fprintf ppf "@]" let rec pp_contents_and_result_list : type kind. Format.formatter -> kind contents_and_result_list -> unit = fun ppf -> function | Single_and_result (Seed_nonce_revelation {level; nonce}, Seed_nonce_revelation_result bus) -> Format.fprintf ppf "@[<v 2>Seed nonce revelation:@,\ Level: %a@,\ Nonce (hash): %a@,\ Balance updates:@,\ \ %a@]" Raw_level.pp level Nonce_hash.pp (Nonce.hash nonce) pp_balance_updates bus | Single_and_result (Double_baking_evidence {bh1; bh2}, Double_baking_evidence_result bus) -> Format.fprintf ppf "@[<v 2>Double baking evidence:@,\ Exhibit A: %a@,\ Exhibit B: %a@,\ Balance updates:@,\ \ %a@]" Block_hash.pp (Block_header.hash bh1) Block_hash.pp (Block_header.hash bh2) pp_balance_updates bus | Single_and_result ( Double_endorsement_evidence {op1; op2}, Double_endorsement_evidence_result bus ) -> Format.fprintf ppf "@[<v 2>Double endorsement evidence:@,\ Exhibit A: %a@,\ Exhibit B: %a@,\ Balance updates:@,\ \ %a@]" Operation_hash.pp (Operation.hash op1) Operation_hash.pp (Operation.hash op2) pp_balance_updates bus | Single_and_result (Activate_account {id; _}, Activate_account_result bus) -> Format.fprintf ppf "@[<v 2>Genesis account activation:@,\ Account: %a@,\ Balance updates:@,\ \ %a@]" Ed25519.Public_key_hash.pp id pp_balance_updates bus | Single_and_result ( Endorsement {level}, Endorsement_result {balance_updates; delegate; slots} ) -> Format.fprintf ppf "@[<v 2>Endorsement:@,\ Level: %a@,\ Balance updates:%a@,\ Delegate: %a@,\ Slots: %a@]" Raw_level.pp level pp_balance_updates balance_updates Signature.Public_key_hash.pp delegate (Format.pp_print_list ~pp_sep:Format.pp_print_space Format.pp_print_int) slots | Single_and_result (Proposals {source; period; proposals}, Proposals_result) -> Format.fprintf ppf "@[<v 2>Proposals:@,From: %a@,Period: %a@,Protocols:@, @[<v 0>%a@]@]" Signature.Public_key_hash.pp source Voting_period.pp period (Format.pp_print_list Protocol_hash.pp) proposals | Single_and_result (Ballot {source; period; proposal; ballot}, Ballot_result) -> Format.fprintf ppf "@[<v 2>Ballot:@,From: %a@,Period: %a@,Protocol: %a@,Vote: %a@]" Signature.Public_key_hash.pp source Voting_period.pp period Protocol_hash.pp proposal Data_encoding.Json.pp (Data_encoding.Json.construct Vote.ballot_encoding ballot) | Single_and_result ((Manager_operation _ as op), (Manager_operation_result _ as res)) -> Format.fprintf ppf "%a" pp_manager_operation_contents_and_result (op, res) | Cons_and_result ((Manager_operation _ as op), (Manager_operation_result _ as res), rest) -> Format.fprintf ppf "%a@\n%a" pp_manager_operation_contents_and_result (op, res) pp_contents_and_result_list rest let pp_operation_result ppf ((op, res) : 'kind contents_list * 'kind contents_result_list) = Format.fprintf ppf "@[<v 0>" ; let contents_and_result_list = Apply_results.pack_contents_list op res in pp_contents_and_result_list ppf contents_and_result_list ; Format.fprintf ppf "@]@." let pp_internal_operation ppf (Internal_operation {source; operation; nonce = _}) = pp_manager_operation_content source true (fun _ppf () -> ()) ppf (operation, ())
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
script_ir_annot.mli
open Alpha_context type var_annot = private Var_annot of Non_empty_string.t [@@ocaml.unboxed] type type_annot = private Type_annot of Non_empty_string.t [@@ocaml.unboxed] type field_annot = private Field_annot of Non_empty_string.t [@@ocaml.unboxed] module FOR_TESTS : sig val unsafe_var_annot_of_string : string -> var_annot val unsafe_type_annot_of_string : string -> type_annot val unsafe_field_annot_of_string : string -> field_annot end (** Default annotations *) val default_now_annot : var_annot option val default_amount_annot : var_annot option val default_balance_annot : var_annot option val default_level_annot : var_annot option val default_source_annot : var_annot option val default_sender_annot : var_annot option val default_self_annot : var_annot option val default_arg_annot : var_annot option val lambda_arg_annot : var_annot option val default_param_annot : var_annot option val default_storage_annot : var_annot option val default_sapling_state_annot : var_annot option val default_sapling_balance_annot : var_annot option val default_car_annot : field_annot option val default_cdr_annot : field_annot option val default_contract_annot : field_annot option val default_addr_annot : field_annot option val default_pack_annot : field_annot option val default_unpack_annot : field_annot option val default_slice_annot : field_annot option val default_elt_annot : field_annot option val default_key_annot : field_annot option val default_hd_annot : field_annot option val default_tl_annot : field_annot option val default_some_annot : field_annot option val default_left_annot : field_annot option val default_right_annot : field_annot option (** Unparse annotations to their string representation *) val unparse_type_annot : type_annot option -> string list val unparse_var_annot : var_annot option -> string list val unparse_field_annot : field_annot option -> string list (** Conversion functions between different annotation kinds *) val field_to_var_annot : field_annot option -> var_annot option val type_to_var_annot : type_annot option -> var_annot option val var_to_field_annot : var_annot option -> field_annot option (** Replace an annotation by its default value if it is [None] *) val default_annot : default:'a option -> 'a option -> 'a option (** Generate annotation for field accesses, of the form [var.field1.field2] *) val gen_access_annot : var_annot option -> ?default:field_annot option -> field_annot option -> var_annot option (** Merge type annotations. @return an error {!Inconsistent_type_annotations} if they are both present and different, unless [legacy] *) val merge_type_annot : legacy:bool -> type_annot option -> type_annot option -> type_annot option tzresult (** Merge field annotations. @return an error {!Inconsistent_type_annotations} if they are both present and different, unless [legacy] *) val merge_field_annot : legacy:bool -> field_annot option -> field_annot option -> field_annot option tzresult (** Merge variable annotations, does not fail ([None] if different). *) val merge_var_annot : var_annot option -> var_annot option -> var_annot option (** @return an error {!Unexpected_annotation} in the monad the list is not empty. *) val error_unexpected_annot : Script.location -> 'a list -> unit tzresult (** Parse a type annotation only. *) val parse_type_annot : Script.location -> string list -> type_annot option tzresult (** Parse a field annotation only. *) val parse_field_annot : Script.location -> string list -> field_annot option tzresult (** Parse an annotation for composed types, of the form [:ty_name %field1 %field2] in any order. *) val parse_composed_type_annot : Script.location -> string list -> (type_annot option * field_annot option * field_annot option) tzresult (** Extract and remove a field annotation from a node *) val extract_field_annot : Script.node -> (Script.node * field_annot option) tzresult (** Check that field annotations match, used for field accesses. *) val check_correct_field : field_annot option -> field_annot option -> unit tzresult (** Instruction annotations parsing *) (** Parse a variable annotation, replaced by a default value if [None]. *) val parse_var_annot : Script.location -> ?default:var_annot option -> string list -> var_annot option tzresult val is_allowed_char : char -> bool val parse_constr_annot : Script.location -> ?if_special_first:field_annot option -> ?if_special_second:field_annot option -> string list -> (var_annot option * type_annot option * field_annot option * field_annot option) tzresult val parse_two_var_annot : Script.location -> string list -> (var_annot option * var_annot option) tzresult val parse_destr_annot : Script.location -> string list -> default_accessor:field_annot option -> field_name:field_annot option -> pair_annot:var_annot option -> value_annot:var_annot option -> (var_annot option * field_annot option) tzresult val parse_unpair_annot : Script.location -> string list -> field_name_car:field_annot option -> field_name_cdr:field_annot option -> pair_annot:var_annot option -> value_annot_car:var_annot option -> value_annot_cdr:var_annot option -> (var_annot option * var_annot option * field_annot option * field_annot option) tzresult val parse_entrypoint_annot : Script.location -> ?default:var_annot option -> string list -> (var_annot option * field_annot option) tzresult val parse_var_type_annot : Script.location -> string list -> (var_annot option * type_annot option) tzresult
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
main.ml
(* To run as a standalone binary, run the registered drivers *) let () = Ppxlib.Driver.standalone ()
t-get_str.c
#include "fq_poly.h" #ifdef T #undef T #endif #define T fq #define CAP_T FQ #include "fq_poly_templates/test/t-get_str.c" #undef CAP_T #undef T
/* 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/>. */
test_standard1.ml
(* Tests Seqstd against Stdlib *) (* We test Seqstd by feeding it the Identity Monad: the resulting module should be indistinguishable from [Stdlib.Seq] (modulo the type being new) *) module SeqM = Seqes.Standard.Make1(Seqes.Identity1) module TestsSeqMTraversors = Helpers.MakeTestSuites(struct include Seq include SeqM (* overwrite traversors *) let of_seq s = s end) let () = Alcotest.run "Seqes.Standard.Make1" [("Identity", TestsSeqMTraversors.traversors)]
(**************************************************************************) (* *) (* OCaml *) (* *) (* Raphaël Proust *) (* *) (* Copyright 2022 Nomadic Labs *) (* *) (* 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
; File auto-generated by gentests.ml ; Auto-generated part begin ; Test for hanoi4.icnf ; Incremental test (rule (target hanoi4.incremental) (deps (:input hanoi4.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=incremental --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff hanoi4.expected hanoi4.incremental))) ; Full mode test (rule (target hanoi4.full) (deps (:input hanoi4.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=full --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff hanoi4.expected hanoi4.full))) ; Test for hanoi5.icnf ; Incremental test (rule (target hanoi5.incremental) (deps (:input hanoi5.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=incremental --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff hanoi5.expected hanoi5.incremental))) ; Full mode test (rule (target hanoi5.full) (deps (:input hanoi5.icnf)) (package dolmen_bin) (action (chdir %{workspace_root} (with-outputs-to %{target} (with-accepted-exit-codes (or 0 (not 0)) (run dolmen --mode=full --color=never %{input} %{read-lines:flags.dune})))))) (rule (alias runtest) (package dolmen_bin) (action (diff hanoi5.expected hanoi5.full))) ; Auto-generated part end
dune
(library (name caqti_driver_postgresql) (public_name caqti-driver-postgresql) (wrapped false) (modules Caqti_driver_postgresql) (library_flags (:standard -linkall)) (libraries caqti postgresql))
paf_mirage.ml
module type S = sig type stack type ipaddr module TCP : sig include Mirage_flow.S val dst : flow -> ipaddr * int val no_close : flow -> unit val to_close : flow -> unit end module TLS : sig type error = [ `Tls_alert of Tls.Packet.alert_type | `Tls_failure of Tls.Engine.failure | `Read of TCP.error | `Write of TCP.write_error ] type write_error = [ `Closed | error ] include Mirage_flow.S with type error := error and type write_error := write_error val no_close : flow -> unit val to_close : flow -> unit val epoch : flow -> (Tls.Core.epoch_data, unit) result val reneg : ?authenticator:X509.Authenticator.t -> ?acceptable_cas:X509.Distinguished_name.t list -> ?cert:Tls.Config.own_cert -> ?drop:bool -> flow -> (unit, write_error) result Lwt.t val server_of_flow : Tls.Config.server -> TCP.flow -> (flow, write_error) result Lwt.t val client_of_flow : Tls.Config.client -> ?host:[ `host ] Domain_name.t -> TCP.flow -> (flow, write_error) result Lwt.t end val tcp_protocol : (stack * ipaddr * int, TCP.flow) Mimic.protocol val tcp_edn : (stack * ipaddr * int) Mimic.value val tls_edn : ([ `host ] Domain_name.t option * Tls.Config.client * stack * ipaddr * int) Mimic.value val tls_protocol : ( [ `host ] Domain_name.t option * Tls.Config.client * stack * ipaddr * int, TLS.flow ) Mimic.protocol type t type dst = ipaddr * int val init : port:int -> stack -> t Lwt.t val accept : t -> (TCP.flow, [> `Closed ]) result Lwt.t val close : t -> unit Lwt.t val http_service : ?config:Httpaf.Config.t -> error_handler:(dst -> Httpaf.Server_connection.error_handler) -> (TCP.flow -> dst -> Httpaf.Server_connection.request_handler) -> t Paf.service val https_service : tls:Tls.Config.server -> ?config:Httpaf.Config.t -> error_handler:(dst -> Httpaf.Server_connection.error_handler) -> (TLS.flow -> dst -> Httpaf.Server_connection.request_handler) -> t Paf.service val alpn_service : tls:Tls.Config.server -> ?config:Httpaf.Config.t * H2.Config.t -> (TLS.flow, dst) Alpn.server_handler -> t Paf.service val serve : ?stop:Lwt_switch.t -> 't Paf.service -> 't -> [ `Initialized of unit Lwt.t ] end module Make (Stack : Tcpip.Tcp.S) : S with type stack = Stack.t and type ipaddr = Stack.ipaddr = struct open Lwt.Infix type ipaddr = Stack.ipaddr type dst = ipaddr * int module TCP = struct let src = Logs.Src.create "paf-tcp" module Log = (val Logs.src_log src : Logs.LOG) include Stack type nonrec flow = { flow : flow; mutable no_close : bool } type endpoint = Stack.t * Stack.ipaddr * int type nonrec write_error = [ `Write of write_error | `Connect of error | `Closed ] let pp_write_error ppf = function | `Write err | (`Closed as err) -> pp_write_error ppf err | `Connect err -> pp_error ppf err let read flow = read flow.flow let dst flow = dst flow.flow let write flow cs = write flow.flow cs >>= function | Ok _ as v -> Lwt.return v | Error err -> Lwt.return_error (`Write err) let writev flow css = writev flow.flow css >>= function | Ok _ as v -> Lwt.return v | Error err -> Lwt.return_error (`Write err) let connect (stack, ipaddr, port) = create_connection stack (ipaddr, port) >>= function | Ok flow -> Lwt.return_ok { flow; no_close = false } | Error err -> Lwt.return_error (`Connect err) let no_close flow = flow.no_close <- true let to_close flow = flow.no_close <- false let close flow = match flow.no_close with | true -> Log.debug (fun m -> m "Fakely close the connection.") ; Lwt.return_unit | false -> Log.debug (fun m -> m "Really close the connection.") ; close flow.flow end module TLS = struct let src = Logs.Src.create "paf-tls" module Log = (val Logs.src_log src : Logs.LOG) include Tls_mirage.Make (TCP) type endpoint = [ `host ] Domain_name.t option * Tls.Config.client * Stack.t * Stack.ipaddr * int type nonrec flow = TCP.flow * flow let connect (host, cfg, stack, ipaddr, port) = Stack.create_connection stack (ipaddr, port) >>= function | Error err -> Lwt.return_error (`Read err) | Ok flow -> let open Lwt_result.Infix in let tcp_flow = { TCP.flow; TCP.no_close = false } in client_of_flow cfg ?host tcp_flow >>= fun tls_flow -> Lwt.return_ok (tcp_flow, tls_flow) let no_close (tcp_flow, _) = TCP.no_close tcp_flow let to_close (tcp_flow, _) = TCP.to_close tcp_flow let read (_, tls_flow) = read tls_flow let write (_, tls_flow) = write tls_flow let writev (_, tls_flow) = writev tls_flow let epoch (_, tls_flow) = epoch tls_flow let reneg ?authenticator ?acceptable_cas ?cert ?drop (_, tls_flow) = reneg ?authenticator ?acceptable_cas ?cert ?drop tls_flow let server_of_flow config tcp_flow = Lwt_result.Infix.( server_of_flow config tcp_flow >>= fun tls_flow -> Lwt.return_ok (tcp_flow, tls_flow)) let client_of_flow config ?host tcp_flow = Lwt_result.Infix.( client_of_flow config ?host tcp_flow >>= fun tls_flow -> Lwt.return_ok (tcp_flow, tls_flow)) let close (tcp_flow, tls_flow) = match tcp_flow.TCP.no_close with | true -> Lwt.return_unit | false -> close tls_flow end let src = Logs.Src.create "paf-layer" module Log = (val Logs.src_log src : Logs.LOG) type stack = Stack.t let tcp_edn, tcp_protocol = Mimic.register ~name:"tcp" (module TCP) let tls_edn, tls_protocol = Mimic.register ~priority:10 ~name:"tls" (module TLS) type t = { stack : Stack.t; queue : Stack.flow Queue.t; condition : unit Lwt_condition.t; mutex : Lwt_mutex.t; mutable closed : bool; } let init ~port stack = let queue = Queue.create () in let condition = Lwt_condition.create () in let mutex = Lwt_mutex.create () in let listener flow = Lwt_mutex.lock mutex >>= fun () -> Queue.push flow queue ; Lwt_condition.signal condition () ; Lwt_mutex.unlock mutex ; Lwt.return () in Stack.listen ~port stack listener ; Lwt.return { stack; queue; condition; mutex; closed = false } let rec accept ({ queue; condition; mutex; _ } as t) = Lwt_mutex.lock mutex >>= fun () -> let rec await () = if Queue.is_empty queue && not t.closed then Lwt_condition.wait condition ~mutex >>= await else Lwt.return_unit in await () >>= fun () -> match Queue.pop queue with | flow -> Lwt_mutex.unlock mutex ; Lwt.return_ok { TCP.flow; TCP.no_close = false } | exception Queue.Empty -> if t.closed then ( Lwt_mutex.unlock mutex ; Lwt.return_error `Closed) else ( Lwt_mutex.unlock mutex ; accept t) let close ({ condition; _ } as t) = t.closed <- true ; (* Stack.disconnect stack >>= fun () -> *) Lwt_condition.signal condition () ; Lwt.return_unit let http_service ?config ~error_handler request_handler = let module R = (val Mimic.repr tcp_protocol) in let connection flow = let dst = TCP.dst flow in let error_handler = error_handler dst in let request_handler' reqd = request_handler flow dst reqd in let conn = Httpaf.Server_connection.create ?config ~error_handler request_handler' in Lwt.return_ok (R.T flow, Paf.Runtime ((module Httpaf.Server_connection), conn)) in Paf.service connection Lwt.return_ok accept close let https_service ~tls ?config ~error_handler request_handler = let module R = (val Mimic.repr tls_protocol) in let handshake tcp_flow = let dst = TCP.dst tcp_flow in TLS.server_of_flow tls tcp_flow >>= function | Ok flow -> Lwt.return_ok (dst, flow) | Error `Closed -> (* XXX(dinosaure): be care! [`Closed] at this stage does not mean * that the bound socket is closed but the socket with the peer is * closed. *) Log.err (fun m -> m "The connection was closed by peer.") ; TCP.close tcp_flow >>= fun () -> Lwt.return_error `Closed | Error err -> Log.err (fun m -> m "Got a TLS error: %a." TLS.pp_write_error err) ; TCP.close tcp_flow >>= fun () -> Lwt.return_error err in let connection (dst, flow) = let error_handler = error_handler dst in let request_handler' reqd = request_handler flow dst reqd in let conn = Httpaf.Server_connection.create ?config ~error_handler request_handler' in Lwt.return_ok (R.T flow, Paf.Runtime ((module Httpaf.Server_connection), conn)) in Paf.service connection handshake accept close let alpn = let module R = (val Mimic.repr tls_protocol) in let alpn_of_tls_connection (_edn, flow) = match TLS.epoch flow with | Ok { Tls.Core.alpn_protocol; _ } -> alpn_protocol | Error _ -> None in let peer_of_tls_connection (edn, _flow) = edn in (* XXX(dinosaure): [TLS]/[ocaml-tls] should let us to project the underlying * [flow] and apply [TCP.dst] on it. * Actually, we did it with the [TLS] module. *) let injection (_edn, flow) = R.T flow in { Alpn.alpn = alpn_of_tls_connection; Alpn.peer = peer_of_tls_connection; Alpn.injection; } let alpn_service ~tls ?config:(_ = (Httpaf.Config.default, H2.Config.default)) handler = let handshake tcp_flow = let dst = TCP.dst tcp_flow in TLS.server_of_flow tls tcp_flow >>= function | Ok flow -> Lwt.return_ok (dst, flow) | Error `Closed -> (* XXX(dinosaure): be care! [`Closed] at this stage does not mean * that the bound socket is closed but the socket with the peer is * closed. *) Log.err (fun m -> m "The connection was closed by peer.") ; Lwt.return_error (`Write `Closed) | Error err -> Log.err (fun m -> m "Got a TLS error: %a." TLS.pp_write_error err) ; TCP.close tcp_flow >>= fun () -> Lwt.return_error (err :> [ TLS.write_error | `Msg of string ]) in let module R = (val Mimic.repr tls_protocol) in let request flow edn reqd protocol = match flow with | R.T flow -> handler.Alpn.request flow edn reqd protocol | _ -> assert false (* XXX(dinosaure): this case should never occur. Indeed, the [injection] given to [Alpn.service] only create a [tls_protocol] flow. We just destruct it and give it to [request_handler]. *) in Alpn.service alpn { handler with request } handshake accept close let serve ?stop service t = Paf.serve ?stop service t end type transmission = [ `Clear | `TLS of string option ] let paf_transmission : transmission Mimic.value = Mimic.make ~name:"paf-transmission" let paf_endpoint : (Ipaddr.t * int) Mimic.value = Mimic.make ~name:"paf-endpoint" open Lwt.Infix let rec kind_of_flow : Mimic.edn list -> transmission option = function | Mimic.Edn (k, v) :: r -> ( match Mimic.equal k paf_transmission with | Some Mimic.Refl -> Some v | None -> kind_of_flow r) | [] -> None let rec endpoint_of_flow : Mimic.edn list -> (Ipaddr.t * int) option = function | Mimic.Edn (k, v) :: r -> ( match Mimic.equal k paf_endpoint with | Some Mimic.Refl -> Some v | None -> endpoint_of_flow r) | [] -> None let ( >>? ) = Lwt_result.bind let run ~ctx handler request = Mimic.unfold ctx >>? fun ress -> Mimic.connect ress >>= fun res -> match (res, kind_of_flow ress) with | (Error _ as err), _ -> Lwt.return err | Ok flow, (Some `Clear | None) -> let edn = endpoint_of_flow ress in let alpn = match request with `V1 _ -> "http/1.1" | `V2 _ -> "h2c" in Alpn.run ~alpn handler edn request flow | Ok flow, Some (`TLS alpn) -> let edn = endpoint_of_flow ress in Alpn.run ?alpn handler edn request flow
irmin_mirage_graphql.ml
module Server = struct module type S = sig module Pclock : Mirage_clock.PCLOCK module Http : Cohttp_lwt.S.Server module Store : Irmin.S with type Backend.Remote.endpoint = Smart_git.Endpoint.t val start : http:(Http.t -> unit Lwt.t) -> Store.repo -> unit Lwt.t end module Make (Http : Cohttp_lwt.S.Server) (Store : Irmin.S with type Backend.Remote.endpoint = Smart_git.Endpoint.t) (Pclock : Mirage_clock.PCLOCK) = struct module Store = Store module Pclock = Pclock module Http = Http let init () = let module Config = struct type info = Store.info let info ?(author = "irmin-graphql") fmt = let module I = Irmin_mirage.Info (Store.Info) (Pclock) in I.f ~author fmt let remote = Some (fun ?headers uri -> let ( ! ) f a b = f b a in let headers = Option.map Cohttp.Header.to_list headers in match Smart_git.Endpoint.of_string uri with | Ok ({ Smart_git.Endpoint.scheme = `HTTP _ | `HTTPS _; _ } as edn) -> let edn = Option.fold ~none:edn ~some:(!Smart_git.Endpoint.with_headers_if_http edn) headers in Lwt.return (Store.E edn) | Ok _ -> Fmt.invalid_arg "invalid remote: %s" uri | Error (`Msg err) -> Fmt.invalid_arg "invalid remote: %s" err) end in (module Irmin_graphql.Server.Make (Http) (Config) (Store) : Irmin_graphql.Server.S with type server = Http.t and type repo = Store.repo) let start ~http store = let (module G) = init () in let server = G.v store in http server end end
(* * Copyright (c) 2013-2021 Thomas Gazagnaire <thomas@gazagnaire.org> * * 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. *)
michelson_v1_gas.mli
open Alpha_context module Cost_of : sig val cycle : Gas.cost val loop_cycle : Gas.cost val list_size : Gas.cost val nop : Gas.cost val stack_op : Gas.cost val bool_binop : 'a -> 'b -> Gas.cost val bool_unop : 'a -> Gas.cost val pair : Gas.cost val pair_access : Gas.cost val cons : Gas.cost val variant_no_data : Gas.cost val branch : Gas.cost val concat_string : string list -> Gas.cost val concat_bytes : MBytes.t list -> Gas.cost val slice_string : int -> Gas.cost val slice_bytes : Gas.cost val map_mem : 'a -> ('b, 'c) Script_typed_ir.map -> Gas.cost val map_to_list : ('b, 'c) Script_typed_ir.map -> Gas.cost val map_get : 'a -> ('b, 'c) Script_typed_ir.map -> Gas.cost val map_update : 'a -> 'b -> ('c, 'd) Script_typed_ir.map -> Gas.cost val map_size : Gas.cost val big_map_mem : 'key -> ('key, 'value) Script_typed_ir.big_map -> Gas.cost val big_map_get : 'key -> ('key, 'value) Script_typed_ir.big_map -> Gas.cost val big_map_update : 'key -> 'value option -> ('key, 'value) Script_typed_ir.big_map -> Gas.cost val set_to_list : 'a Script_typed_ir.set -> Gas.cost val set_update : 'a -> bool -> 'a Script_typed_ir.set -> Gas.cost val set_mem : 'a -> 'a Script_typed_ir.set -> Gas.cost val mul : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val div : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val add : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val sub : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val abs : 'a Script_int.num -> Gas.cost val neg : 'a Script_int.num -> Gas.cost val int : 'a -> Gas.cost val add_timestamp : Script_timestamp.t -> 'a Script_int.num -> Gas.cost val sub_timestamp : Script_timestamp.t -> 'a Script_int.num -> Gas.cost val diff_timestamps : Script_timestamp.t -> Script_timestamp.t -> Gas.cost val empty_set : Gas.cost val set_size : Gas.cost val empty_map : Gas.cost val int64_op : Gas.cost val z_to_int64 : Gas.cost val int64_to_z : Gas.cost val bitwise_binop : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val logor : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val logand : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val logxor : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val lognot : 'a Script_int.num -> Gas.cost val shift_left : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val shift_right : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val exec : Gas.cost val push : Gas.cost val compare_res : Gas.cost val unpack_failed : MBytes.t -> Gas.cost val address : Gas.cost val contract : Gas.cost val transfer : Gas.cost val create_account : Gas.cost val create_contract : Gas.cost val implicit_account : Gas.cost val set_delegate : Gas.cost val balance : Gas.cost val now : Gas.cost val check_signature : Gas.cost val hash_key : Gas.cost val hash : MBytes.t -> int -> Gas.cost val steps_to_quota : Gas.cost val source : Gas.cost val self : Gas.cost val amount : Gas.cost val wrap : Gas.cost val compare_bool : 'a -> 'b -> Gas.cost val compare_string : string -> string -> Gas.cost val compare_bytes : MBytes.t -> MBytes.t -> Gas.cost val compare_tez : 'a -> 'b -> Gas.cost val compare_int : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val compare_nat : 'a Script_int.num -> 'b Script_int.num -> Gas.cost val compare_key_hash : 'a -> 'b -> Gas.cost val compare_timestamp : Script_timestamp.t -> Script_timestamp.t -> Gas.cost val compare_address : Contract.t -> Contract.t -> Gas.cost module Typechecking : sig val cycle : Gas.cost val unit : Gas.cost val bool : Gas.cost val tez : Gas.cost val z : Z.t -> Gas.cost val string : int -> Gas.cost val bytes : int -> Gas.cost val int_of_string : string -> Gas.cost val string_timestamp : Gas.cost val key : Gas.cost val key_hash : Gas.cost val signature : Gas.cost val contract : Gas.cost (** Gas.Cost of getting the code for a contract *) val get_script : Gas.cost val contract_exists : Gas.cost (** Additional Gas.cost of parsing a pair over the Gas.cost of parsing each type *) val pair : Gas.cost val union : Gas.cost val lambda : Gas.cost val some : Gas.cost val none : Gas.cost val list_element : Gas.cost val set_element : int -> Gas.cost val map_element : int -> Gas.cost val primitive_type : Gas.cost val one_arg_type : Gas.cost val two_arg_type : Gas.cost val operation : int -> Gas.cost (** Cost of parsing a type *) val type_ : int -> Gas.cost (** Cost of parsing an instruction *) val instr : ('a, 'b) Script_typed_ir.instr -> Gas.cost end module Unparse : sig val prim_cost : int -> Script.annot -> Gas.cost val seq_cost : int -> Gas.cost val cycle : Gas.cost val unit : Gas.cost val bool : Gas.cost val z : Z.t -> Gas.cost val int : 'a Script_int.num -> Gas.cost val tez : Gas.cost val string : string -> Gas.cost val bytes : MBytes.t -> Gas.cost val timestamp : Script_timestamp.t -> Gas.cost val key : Gas.cost val key_hash : Gas.cost val signature : Gas.cost val operation : MBytes.t -> Gas.cost val contract : Gas.cost (** Additional Gas.cost of parsing a pair over the Gas.cost of parsing each type *) val pair : Gas.cost val union : Gas.cost val some : Gas.cost val none : Gas.cost val list_element : Gas.cost val set_element : Gas.cost val map_element : Gas.cost val one_arg_type : Script.annot -> Gas.cost val two_arg_type : Script.annot -> Gas.cost val set_to_list : 'a Script_typed_ir.set -> Gas.cost val map_to_list : ('a, 'b) Script_typed_ir.map -> Gas.cost end end
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
js-pattern.ml
let f = function | _ -> 0 ;; let f x = match x with | _ -> 0 ;; let f = function | _ -> 0 ;; let f x = match x with | _ -> 0 ;; let f x = begin match x with | _ -> 0 end ;; let check_price t = function | { Exec. trade_at_settlement = (None | Some false); } -> () let check_price t = function | simpler -> () | other -> () (* Sometimes we like to write big alternations like this, in which case the comment should typically align with the following clause. *) let 0 = match x with | A (* a *) -> a let 0 = match x with A (* a *) -> a let _ = a || match a with | a -> true | b -> false
state_space.ml
(* The state of rewriting is a typed term *) type t = {typing : Inference.state lazy_t; term : Mikhailsky.node} let compare (term1 : t) (term2 : t) = let tag1 = Mikhailsky.tag term1.term in let tag2 = Mikhailsky.tag term2.term in if tag1 < tag2 then -1 else if tag1 > tag2 then 1 else 0 let equal (term1 : t) (term2 : t) = let tag1 = Mikhailsky.tag term1.term in let tag2 = Mikhailsky.tag term2.term in tag1 = tag2 let hash (t : t) = Mikhailsky.hash t.term type node_statistics = { mutable size : int; mutable bytes : int; mutable holes : int; mutable depth : int; } let pp_statistics fmtr stats = Format.fprintf fmtr "{ size = %d ; bytes = %d ; holes = %d }" stats.size stats.bytes stats.holes let rec statistics stats depth (n : Mikhailsky.node) = stats.size <- stats.size + 1 ; stats.depth <- max depth stats.depth ; match n with | Micheline.Int (_, z) -> stats.bytes <- stats.bytes + (Z.numbits z / 8) | Micheline.String (_, s) -> stats.bytes <- stats.bytes + String.length s | Micheline.Bytes (_, b) -> stats.bytes <- stats.bytes + Bytes.length b | Micheline.Prim (_, Mikhailsky_prim.I_Hole, _, _) | Micheline.Prim (_, Mikhailsky_prim.D_Hole, _, _) -> stats.holes <- stats.holes + 1 | Micheline.Prim (_, _, subterms, _) | Micheline.Seq (_, subterms) -> List.iter (statistics stats (depth + 1)) subterms let statistics {term; _} = let stats = {size = 0; bytes = 0; holes = 0; depth = 0} in statistics stats 0 term ; stats let pp fmtr (state : t) = Format.fprintf fmtr "current term:@." ; Format.fprintf fmtr "%a@." Mikhailsky.pp state.term ; Format.fprintf fmtr "stats:@." ; Format.fprintf fmtr "%a:@." pp_statistics (statistics state)
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
sub.c
#include "fmpr.h" static slong _fmpr_sub_special(fmpr_t z, const fmpr_t x, const fmpr_t y, slong prec, fmpr_rnd_t rnd) { if (fmpr_is_zero(x)) { return fmpr_neg_round(z, y, prec, rnd); } else if (fmpr_is_zero(y)) { return fmpr_set_round(z, x, prec, rnd); } else if (fmpr_is_nan(x) || fmpr_is_nan(y) || (fmpr_is_pos_inf(x) && fmpr_is_pos_inf(y)) || (fmpr_is_neg_inf(x) && fmpr_is_neg_inf(y))) { fmpr_nan(z); return FMPR_RESULT_EXACT; } else if (fmpr_is_special(x)) { fmpr_set(z, x); return FMPR_RESULT_EXACT; } else { fmpr_neg(z, y); return FMPR_RESULT_EXACT; } } slong fmpr_sub(fmpr_t z, const fmpr_t x, const fmpr_t y, slong prec, fmpr_rnd_t rnd) { slong shift, xn, yn; mp_limb_t xtmp, ytmp; mp_ptr xptr, yptr; fmpz xv, yv; const fmpz * xexp; const fmpz * yexp; int xsign, ysign; if (fmpr_is_special(x) || fmpr_is_special(y)) { return _fmpr_sub_special(z, x, y, prec, rnd); } shift = _fmpz_sub_small(fmpr_expref(y), fmpr_expref(x)); if (shift >= 0) { xexp = fmpr_expref(x); yexp = fmpr_expref(y); xv = *fmpr_manref(x); yv = *fmpr_manref(y); } else { xexp = fmpr_expref(y); yexp = fmpr_expref(x); xv = *fmpr_manref(y); yv = *fmpr_manref(x); } FMPZ_GET_MPN_READONLY(xsign, xn, xptr, xtmp, xv) FMPZ_GET_MPN_READONLY(ysign, yn, yptr, ytmp, yv) if (shift >= 0) { ysign = !ysign; } else { shift = -shift; xsign = !xsign; } if ((xn == 1) && (yn == 1) && (shift < FLINT_BITS)) return _fmpr_add_1x1(z, xptr[0], xsign, xexp, yptr[0], ysign, yexp, shift, prec, rnd); else return _fmpr_add_mpn(z, xptr, xn, xsign, xexp, yptr, yn, ysign, yexp, shift, prec, rnd); } slong fmpr_sub_ui(fmpr_t z, const fmpr_t x, ulong y, slong prec, fmpr_rnd_t rnd) { fmpr_t t; slong r; fmpr_init(t); fmpr_set_ui(t, y); r = fmpr_sub(z, x, t, prec, rnd); fmpr_clear(t); return r; } slong fmpr_sub_si(fmpr_t z, const fmpr_t x, slong y, slong prec, fmpr_rnd_t rnd) { fmpr_t t; slong r; fmpr_init(t); fmpr_set_si(t, y); r = fmpr_sub(z, x, t, prec, rnd); fmpr_clear(t); return r; } slong fmpr_sub_fmpz(fmpr_t z, const fmpr_t x, const fmpz_t y, slong prec, fmpr_rnd_t rnd) { fmpr_t t; slong r; fmpr_init(t); fmpr_set_fmpz(t, y); r = fmpr_sub(z, x, t, prec, rnd); fmpr_clear(t); return r; }
/* Copyright (C) 2012, 2013 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/>. */
dune
(install (section (site (camomile database))) (files acset.mar age.mar allkeys.mar Alphabetic.mar Alphabetic_set.mar ASCII_Hex_Digit.mar ASCII_Hex_Digit_set.mar Bidi_Control.mar Bidi_Control_set.mar case_folding.mar combined_class_map.mar combined_class.mar composition_exclusion.mar composition_exclusion_set.mar composition.mar d1.mar d2.mar decomposition.mar Deprecated.mar Deprecated_set.mar Diacritic.mar Diacritic_set.mar Extender.mar Extender_set.mar general_category_map.mar general_category.mar Grapheme_Base.mar Grapheme_Base_set.mar Grapheme_Extend.mar Grapheme_Extend_set.mar Grapheme_Link.mar Grapheme_Link_set.mar Hex_Digit.mar Hex_Digit_set.mar Hyphen.mar Hyphen_set.mar ID_Continue.mar ID_Continue_set.mar Ideographic.mar Ideographic_set.mar IDS_Binary_Operator.mar IDS_Binary_Operator_set.mar ID_Start.mar ID_Start_set.mar IDS_Trinary_Operator.mar IDS_Trinary_Operator_set.mar iscsi_prohibited.mar Join_Control.mar Join_Control_set.mar Logical_Order_Exception.mar Lowercase.mar Lowercase_set.mar map_b1b2.mar map_b1.mar Math.mar Math_set.mar mib_prohibited.mar nameprep_prohibited.mar nodeprep_prohibited.mar Noncharacter_Code_Point.mar Other_Alphabetic.mar Other_Alphabetic_set.mar Other_Grapheme_Extend.mar Other_Grapheme_Extend_set.mar Other_Lowercase.mar Other_Lowercase_set.mar Other_Math.mar Other_Math_set.mar Other_Uppercase.mar Other_Uppercase_set.mar Quotation_Mark.mar Quotation_Mark_set.mar Radical.mar Radical_set.mar resourceprep_prohibited.mar saslprep_map.mar saslprep_prohibited.mar scripts_map.mar scripts.mar Soft_Dotted.mar Soft_Dotted_set.mar special_casing.mar Terminal_Punctuation.mar Terminal_Punctuation_set.mar to_lower1.mar to_title1.mar to_upper1.mar trace_prohibited.mar Unified_Ideograph.mar Unified_Ideograph_set.mar Uppercase.mar Uppercase_set.mar White_Space.mar White_Space_set.mar XID_Continue.mar XID_Continue_set.mar XID_Start.mar XID_Start_set.mar)) ;; PROPS (rule (targets White_Space.mar White_Space_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . White_Space %{deps}))) (rule (targets Bidi_Control.mar Bidi_Control_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Bidi_Control %{deps}))) (rule (targets Join_Control.mar Join_Control_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Join_Control %{deps}))) (rule (targets Hyphen.mar Hyphen_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Hyphen %{deps}))) (rule (targets Quotation_Mark.mar Quotation_Mark_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Quotation_Mark %{deps}))) (rule (targets Terminal_Punctuation.mar Terminal_Punctuation_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Terminal_Punctuation %{deps}))) (rule (targets Other_Math.mar Other_Math_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Other_Math %{deps}))) (rule (targets Hex_Digit.mar Hex_Digit_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Hex_Digit %{deps}))) (rule (targets ASCII_Hex_Digit.mar ASCII_Hex_Digit_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . ASCII_Hex_Digit %{deps}))) (rule (targets Other_Alphabetic.mar Other_Alphabetic_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Other_Alphabetic %{deps}))) (rule (targets Ideographic.mar Ideographic_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Ideographic %{deps}))) (rule (targets Diacritic.mar Diacritic_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Diacritic %{deps}))) (rule (targets Extender.mar Extender_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Extender %{deps}))) (rule (targets Other_Lowercase.mar Other_Lowercase_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Other_Lowercase %{deps}))) (rule (targets Other_Uppercase.mar Other_Uppercase_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Other_Uppercase %{deps}))) (rule (targets Noncharacter_Code_Point.mar Noncharacter_Code_Point_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Noncharacter_Code_Point %{deps}))) (rule (targets Other_Grapheme_Extend.mar Other_Grapheme_Extend_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Other_Grapheme_Extend %{deps}))) (rule (targets Grapheme_Link.mar Grapheme_Link_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Grapheme_Link %{deps}))) (rule (targets IDS_Binary_Operator.mar IDS_Binary_Operator_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . IDS_Binary_Operator %{deps}))) (rule (targets IDS_Trinary_Operator.mar IDS_Trinary_Operator_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . IDS_Trinary_Operator %{deps}))) (rule (targets Radical.mar Radical_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Radical %{deps}))) (rule (targets Unified_Ideograph.mar Unified_Ideograph_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Unified_Ideograph %{deps}))) (rule (targets Other_Default_Ignorable_Code_Point.mar Other_Default_Ignorable_Code_Point_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Other_Default_Ignorable_Code_Point %{deps}))) (rule (targets Deprecated.mar Deprecated_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Deprecated %{deps}))) (rule (targets Soft_Dotted.mar Soft_Dotted_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Soft_Dotted %{deps}))) (rule (targets Logical_Order_Exception.mar Logical_Order_Exception_set.mar) (deps ../unidata/PropList.txt) (action (run ../tools/parse_uniset.exe -filter . Logical_Order_Exception %{deps}))) ;; CORE_DERIVED_PROPS (rule (targets Math.mar Math_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . Math %{deps}))) (rule (targets Alphabetic.mar Alphabetic_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . Alphabetic %{deps}))) (rule (targets Lowercase.mar Lowercase_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . Lowercase %{deps}))) (rule (targets Uppercase.mar Uppercase_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . Uppercase %{deps}))) (rule (targets ID_Start.mar ID_Start_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . ID_Start %{deps}))) (rule (targets ID_Continue.mar ID_Continue_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . ID_Continue %{deps}))) (rule (targets XID_Start.mar XID_Start_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . XID_Start %{deps}))) (rule (targets XID_Continue.mar XID_Continue_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . XID_Continue %{deps}))) (rule (targets Default_Ignorable_Code_Point.mar Default_Ignorable_Code_Point_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . Default_Ignorable_Code_Point %{deps}))) (rule (targets Grapheme_Extend.mar Grapheme_Extend_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . Grapheme_Extend %{deps}))) (rule (targets Grapheme_Base.mar Grapheme_Base_set.mar) (deps ../unidata/DerivedCoreProperties.txt) (action (run ../tools/parse_uniset.exe -filter . Grapheme_Base %{deps}))) ;; FROM_UNIDATA (rule (targets combined_class.mar combined_class_map.mar composition.mar decomposition.mar general_category.mar to_lower1.mar to_title1.mar to_upper1.mar general_category_map.mar) (deps ../unidata/UnicodeData.txt) (action (run ../tools/parse_unidata.exe . %{deps}))) ;; STRINGPREP_TABLES (rule (targets map_b1b2.mar map_b1.mar d1.mar d2.mar saslprep_map.mar nodeprep_prohibited.mar resourceprep_prohibited.mar nameprep_prohibited.mar saslprep_prohibited.mar trace_prohibited.mar iscsi_prohibited.mar mib_prohibited.mar) (deps (glob_files ../unidata/stringprep/*)) (action (run ../tools/camomilestringprep.exe -in ../unidata/stringprep -out .))) ;; other (alias (name database) (deps combined_class.mar composition.mar decomposition.mar general_category.mar to_lower1.mar to_title1.mar to_upper1.mar general_category_map.mar White_Space.mar Bidi_Control.mar Join_Control.mar Hyphen.mar Quotation_Mark.mar Terminal_Punctuation.mar Other_Math.mar Hex_Digit.mar ASCII_Hex_Digit.mar Other_Alphabetic.mar Ideographic.mar Diacritic.mar Extender.mar Other_Lowercase.mar Other_Uppercase.mar Noncharacter_Code_Point.mar Other_Grapheme_Extend.mar Grapheme_Link.mar IDS_Binary_Operator.mar IDS_Trinary_Operator.mar Radical.mar Unified_Ideograph.mar Other_Default_Ignorable_Code_Point.mar Deprecated.mar Soft_Dotted.mar Logical_Order_Exception.mar scripts.mar)) (rule (targets allkeys.mar acset.mar) (deps ../unidata/tr10/allkeys.txt (alias database)) (action (chdir .. (run tools/parse_allkeys.exe database %{deps})))) (rule (targets case_folding.mar) (deps ../unidata/CaseFolding.txt) (action (run ../tools/parse_casefolding.exe . %{deps}))) (rule (targets composition_exclusion.mar composition_exclusion_set.mar) (deps ../unidata/CompositionExclusions.txt) (action (run ../tools/parse_uniset.exe . composition_exclusion %{deps}))) (rule (targets special_casing.mar) (deps ../unidata/SpecialCasing.txt (alias database)) (action (chdir .. (run tools/parse_specialcasing.exe database %{deps})))) (rule (targets scripts.mar scripts_map.mar) (deps ../unidata/Scripts.txt) (action (run ../tools/parse_scripts.exe . %{deps}))) (rule (targets age.mar) (deps ../unidata/DerivedAge.txt) (action (run ../tools/parse_age.exe . %{deps})))
location.mli
(* $Id: location.mli,v 1.1 2007/09/24 23:04:50 so294 Exp $ *) (* Source code locations (ranges of positions), used in parsetree. *) open Format type t = { loc_start: Lexing.position; loc_end: Lexing.position; loc_ghost: bool; } (* Note on the use of Lexing.position in this module. If [pos_fname = ""], then use [!input_name] instead. If [pos_lnum = -1], then [pos_bol = 0]. Use [pos_cnum] and re-parse the file to get the line and character numbers. Else all fields are correct. *) val none : t (** An arbitrary value of type [t]; describes an empty ghost range. *) val in_file : string -> t;; (** Return an empty ghost range located in a given file. *) val init : Lexing.lexbuf -> string -> unit (** Set the file name and line number of the [lexbuf] to be the start of the named file. *) val curr : Lexing.lexbuf -> t (** Get the location of the current token from the [lexbuf]. *) val symbol_rloc: unit -> t val symbol_gloc: unit -> t val rhs_loc: int -> t val input_name: string ref val input_lexbuf: Lexing.lexbuf option ref val get_pos_info : Lexing.position -> string * int * int (* file, line, char *) val print: formatter -> t -> unit val print_warning: t -> formatter -> Warnings.t -> unit val prerr_warning: t -> Warnings.t -> unit val echo_eof: unit -> unit val reset: unit -> unit val highlight_locations: formatter -> t -> t -> bool
(***********************************************************************) (* *) (* Objective Caml *) (* *) (* 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 Q Public License version 1.0. *) (* *) (***********************************************************************)
zlib-test.c
/* compile using gcc -o zlib-test zlib-test.c -lz usage: zlib-test <compression-level> <string> where compression-level is from 0 to 9 */ #include <stdio.h> #include <zlib.h> #include <string.h> #include <stdlib.h> int main (int argc, char *argv[]) { unsigned char dest[32]; unsigned long destLen = 31; int retval, i; int level; char *endptr; if (argc != 3) { fprintf (stderr, "Usage: %s: <compression-level> <string>\n", argv[0]); return 1; } level = strtol (argv[1], &endptr, 10); if (endptr == argv[1] || level < 0 || level > 9) { fprintf (stderr, "Invalid compression level\n"); return 1; } retval = compress2 (dest, &destLen, (unsigned char *)argv[2], strlen (argv[2]), level); if (retval != Z_OK) { fprintf (stderr, "Error calling zlib compress2 function: %d\n", retval); return 1; } for (i = 0; i < destLen; i++) printf ("\\x%02hhx", dest[i]); printf ("\n"); return 0; }
/* compile using gcc -o zlib-test zlib-test.c -lz usage: zlib-test <compression-level> <string> where compression-level is from 0 to 9 */
xenstore.ml
open Lwt let src = Logs.Src.create "net-xen xenstore" ~doc:"mirage-net-xen's XenStore client" module Log = (val Logs.src_log src : Logs.LOG) let (/) a b = if a = "" then b else if b = "" then a else ( let b = if b.[0] = '/' then String.sub b 1 (String.length b - 1) else b in if a = "/" then a ^ b else if a.[String.length a - 1] = '/' then a ^ b else a ^ "/" ^ b ) module Make(Xs: Xs_client_lwt.S) = struct open S let read_int x = try return (int_of_string x) with _ -> fail (Failure (Printf.sprintf "Expected an integer: %s" x)) let read_int32 x = try return (Int32.of_string x) with _ -> fail (Failure (Printf.sprintf "Expected a 32-bit integer: %s" x)) (* Return the path of the frontend *) let frontend = function | `Client devid -> return (Printf.sprintf "device/vif/%d/" devid) | `Server (domid, devid) -> Xs.make () >>= fun xsc -> Xs.(immediate xsc (fun h -> read h (Printf.sprintf "backend/vif/%d/%d/frontend" domid devid))) let backend = function | `Client devid -> Xs.make () >>= fun xsc -> Xs.(immediate xsc (fun h -> read h (Printf.sprintf "device/vif/%d/backend" devid))) | `Server (domid, devid) -> return (Printf.sprintf "backend/vif/%d/%d" domid devid) let read_frontend_mac id = frontend id >>= fun frontend -> Xs.make () >>= fun xsc -> Xs.(immediate xsc (fun h -> read h (frontend / "mac"))) >|= Macaddr.of_string >>= function | Ok x -> return x | Error (`Msg msg) -> let m = Macaddr.make_local (fun _ -> Random.int 255) in Log.info (fun f -> f "%s: no configured MAC (error: %s), using %a" (Sexplib.Sexp.to_string (S.sexp_of_id id)) msg Macaddr.pp m); return m (* Curiously, libxl writes the frontend MAC to both the frontend and backend directories. The convention seems to be to use this as the backend MAC. See: https://github.com/QubesXen_os/qubes-issues/issues/5013 *) let backend_mac = Macaddr.of_string_exn "fe:ff:ff:ff:ff:ff" let read_backend_mac _ = return backend_mac let read_mtu _id = return 1500 (* TODO *) let read_features side path = Xs.make () >>= fun xsc -> Xs.(immediate xsc (fun h -> let read_feature key = Lwt.catch (fun () -> read h (path / key) >>= fun v -> return (v = "1")) (fun _ -> return false) in read_feature "feature-sg" >>= fun sg -> read_feature "feature-gso-tcpv4" >>= fun gso_tcpv4 -> begin match side with | `Client -> read_feature "request-rx-copy" | `Server -> read_feature "feature-rx-copy" end >>= fun rx_copy -> read_feature "feature-rx-flip" >>= fun rx_flip -> read_feature "feature-rx-notify" >>= fun rx_notify -> read_feature "feature-smart-poll" >>= fun smart_poll -> return { Features.sg; gso_tcpv4; rx_copy; rx_flip; rx_notify; smart_poll } ) ) let write_features h path side features = let open Features in let write_feature k v = Xs.write h (path / k) (if v then "1" else "0") in write_feature "feature-sg" features.sg >>= fun () -> write_feature "feature-gso-tcpv4" features.gso_tcpv4 >>= fun () -> begin match side with | `Client -> write_feature "request-rx-copy" features.rx_copy | `Server -> write_feature "feature-rx-copy" features.rx_copy end >>= fun () -> write_feature "feature-rx-flip" features.rx_flip >>= fun () -> write_feature "feature-rx-notify" features.rx_notify >>= fun () -> write_feature "feature-smart-poll" features.smart_poll let write_frontend_configuration id (f: frontend_configuration) = frontend id >>= fun frontend -> Xs.make () >>= fun xsc -> Xs.(transaction xsc (fun h -> let wrfn k v = write h (frontend / k) v in wrfn "tx-ring-ref" (Int32.to_string f.tx_ring_ref) >>= fun () -> wrfn "rx-ring-ref" (Int32.to_string f.rx_ring_ref) >>= fun () -> wrfn "event-channel" f.event_channel >>= fun () -> write_features h frontend `Client f.feature_requests )) let read_frontend_configuration id = frontend id >>= fun frontend -> Xs.make () >>= fun xsc -> Xs.wait xsc (fun h -> Lwt.catch (fun () -> Xs.read h (frontend / "state") >>= fun state -> let open Xen_os.Device_state in match of_string state with | Initialised | Connected -> return () | Unknown | Initialising | InitWait | Closing | Closed (* XXX: stop waiting? *) | Reconfigured (* XXX: stop waiting? *) | Reconfiguring -> fail Xs_protocol.Eagain ) (function | Xs_protocol.Enoent _ -> fail Xs_protocol.Eagain | e -> fail e) ) >>= fun () -> Xs.(immediate xsc (fun h -> read h (frontend / "tx-ring-ref") >>= fun tx_ring_ref -> read_int32 tx_ring_ref >>= fun tx_ring_ref -> read h (frontend / "rx-ring-ref") >>= fun rx_ring_ref -> read_int32 rx_ring_ref >>= fun rx_ring_ref -> read h (frontend / "event-channel") >>= fun event_channel -> read_features `Client frontend >>= fun feature_requests -> return { tx_ring_ref; rx_ring_ref; event_channel; feature_requests } ) ) let wait_until_backend_connected conf = Xs.make () >>= fun xsc -> Xs.wait xsc (fun h -> Lwt.catch (fun () -> Xs.read h (conf.backend / "state") >>= fun state -> let open Xen_os.Device_state in match of_string state with | Connected -> return () | Initialised | Unknown | Initialising | InitWait | Closing | Closed (* XXX: stop waiting? *) | Reconfigured (* XXX: stop waiting? *) | Reconfiguring -> fail Xs_protocol.Eagain ) (function | Xs_protocol.Enoent _ -> fail Xs_protocol.Eagain | ex -> fail ex ) ) let connect id = Xs.make () >>= fun xsc -> Xs.(immediate xsc (fun h -> ( match id with | `Client _ -> frontend id | `Server (_, _) -> backend id ) >>= fun path -> write h (path / "state") Xen_os.Device_state.(to_string Connected) )) let init_backend id features = backend id >>= fun backend -> Xs.make () >>= fun xsc -> Xs.(transaction xsc (fun h -> write_features h backend `Server features >>= fun () -> write h (backend / "state") Xen_os.Device_state.(to_string InitWait) )) >>= fun () -> Xs.(immediate xsc (fun h -> read h (backend / "frontend-id") >>= read_int >>= fun frontend_id -> frontend id >>= fun frontend -> read h (frontend / "backend-id") >>= fun backend_id -> read_int backend_id >>= fun backend_id -> read h (frontend / "backend") >>= fun backend -> return { frontend_id; backend; backend_id; features_available = features } )) let read_backend id = frontend id >>= fun frontend -> Xs.make () >>= fun xsc -> Xs.(immediate xsc (fun h -> begin match id with | `Client _ -> read h "domid" >>= read_int | `Server (frontend_id, _) -> return frontend_id end >>= fun frontend_id -> read h (frontend / "backend-id") >>= fun backend_id -> read_int backend_id >>= fun backend_id -> read h (frontend / "backend") >>= fun backend -> read_features `Server backend >>= fun features_available -> return { frontend_id; backend; backend_id; features_available } )) let enumerate () = Xs.make () >>= fun xsc -> Lwt.catch (fun () -> Xs.(immediate xsc (fun h -> directory h "device/vif"))) (function | Xs_protocol.Enoent _ -> return [] | e -> Log.warn (fun f -> f "enumerate caught exception: %s" (Printexc.to_string e)); return [] ) let description = "Configuration information will be shared via Xenstore keys" let closing path = Xs.make () >>= fun xsc -> Xs.wait xsc (fun h -> Lwt.try_bind (fun () -> Xs.read h (path / "state") ) (fun state -> match Xen_os.Device_state.of_string state with | Xen_os.Device_state.Closing | Closed -> return () | _ -> Lwt.fail Xs_protocol.Eagain ) (fun ex -> Log.warn (fun f -> f "Error reading device state at %S: %a" path Fmt.exn ex); Lwt.return () ) ) let wait_for_frontend_closing id = frontend id >>= closing let wait_for_backend_closing id = backend id >>= closing let disconnect_frontend id = Xs.make () >>= fun xsc -> frontend id >>= fun path -> Xs.(immediate xsc (fun h -> write h (path / "state") Xen_os.Device_state.(to_string Closed) )) (* See: https://github.com/mirage/xen/commit/546678c6a60f64fb186640460dfa69a837c8fba5 *) let disconnect_backend id = Xs.make () >>= fun xsc -> backend id >>= fun path -> Lwt.catch (fun () -> Xs.(immediate xsc (fun h -> write h (path / "state") Xen_os.Device_state.(to_string Closed))) >>= fun _ -> wait_for_frontend_closing id >>= fun () -> Xs.(immediate xsc (fun h -> rm h path)) ) (fun ex -> Log.warn (fun f -> f "XenStore error removing %S: %a" path Fmt.exn ex); Lwt.return_unit ) end
(* * Copyright (c) 2013,2014 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *)
graph_code_class_analysis.mli
(* It can actually be a DAG, as with interfaces and traits one can fake * multiple inheritance. * The direction of the graph is efficient to get the children * of a class: Parent -> Children. * *) type class_hierarchy = Graph_code.node Graphe.graph val class_hierarchy : Graph_code.t -> class_hierarchy (* Return the toplevel methods for each method name in the graph. * The returned hashtbl uses the Hashtbl.find_all property. *) val toplevel_methods : Graph_code.t -> class_hierarchy -> (string, Graph_code.node (*list*)) Hashtbl.t (* Return the possible dispatched methods. *) val dispatched_methods : Graph_code.t -> class_hierarchy -> Graph_code.node (* a method *) -> Graph_code.node list (* print optimization opportunities, also print dead fields *) val protected_to_private_candidates : Graph_code.t -> unit
(* It can actually be a DAG, as with interfaces and traits one can fake * multiple inheritance. * The direction of the graph is efficient to get the children * of a class: Parent -> Children. * *)
monitor_services.ml
type chain_status = | Active_main of Chain_id.t | Active_test of { chain : Chain_id.t; protocol : Protocol_hash.t; expiration_date : Time.Protocol.t; } | Stopping of Chain_id.t let chain_status_encoding = let open Data_encoding in union ~tag_size:`Uint8 [ case (Tag 0) ~title:"Main" (obj1 (req "chain_id" Chain_id.encoding)) (function Active_main chain_id -> Some chain_id | _ -> None) (fun chain_id -> Active_main chain_id); case (Tag 1) ~title:"Test" (obj3 (req "chain_id" Chain_id.encoding) (req "test_protocol" Protocol_hash.encoding) (req "expiration_date" Time.Protocol.encoding)) (function | Active_test {chain; protocol; expiration_date} -> Some (chain, protocol, expiration_date) | _ -> None) (fun (chain, protocol, expiration_date) -> Active_test {chain; protocol; expiration_date}); case (Tag 2) ~title:"Stopping" (obj1 (req "stopping" Chain_id.encoding)) (function Stopping chain_id -> Some chain_id | _ -> None) (fun chain_id -> Stopping chain_id); ] module S = struct open Data_encoding let path = Tezos_rpc.Path.(root / "monitor") let bootstrapped = Tezos_rpc.Service.get_service ~description: "Wait for the node to have synchronized its chain with a few peers \ (configured by the node's administrator), streaming head updates that \ happen during the bootstrapping process, and closing the stream at \ the end. If the node was already bootstrapped, returns the current \ head immediately." ~query:Tezos_rpc.Query.empty ~output: (obj2 (req "block" Block_hash.encoding) (req "timestamp" Time.Protocol.encoding)) Tezos_rpc.Path.(path / "bootstrapped") let validated_or_apply_blocks_query = let open Tezos_rpc.Query in query (fun protocols next_protocols chains -> object method protocols = protocols method next_protocols = next_protocols method chains = chains end) |+ multi_field "protocol" Protocol_hash.rpc_arg (fun t -> t#protocols) |+ multi_field "next_protocol" Protocol_hash.rpc_arg (fun t -> t#next_protocols) |+ multi_field "chain" Chain_services.chain_arg (fun t -> t#chains) |> seal let legacy_valid_blocks = Tezos_rpc.Service.get_service ~description: "(Deprecated) Monitor all blocks that are successfully applied by the \ node, disregarding whether they were selected as the new head or not." ~query:validated_or_apply_blocks_query ~output: (merge_objs (obj2 (req "chain_id" Chain_id.encoding) (req "hash" Block_hash.encoding)) Block_header.encoding) Tezos_rpc.Path.(path / "valid_blocks") let validated_blocks = Tezos_rpc.Service.get_service ~description: "Monitor all blocks that were successfully validated by the node but \ are not applied nor stored yet, disregarding whether they are going \ to be selected as the new head or not." ~query:validated_or_apply_blocks_query ~output: (obj4 (req "chain_id" Chain_id.encoding) (req "hash" Block_hash.encoding) (req "header" (dynamic_size Block_header.encoding)) (req "operations" (list (list (dynamic_size Operation.encoding))))) Tezos_rpc.Path.(path / "validated_blocks") let applied_blocks = Tezos_rpc.Service.get_service ~description: "Monitor all blocks that are successfully applied and stored by the \ node, disregarding whether they were selected as the new head or not." ~query:validated_or_apply_blocks_query ~output: (obj4 (req "chain_id" Chain_id.encoding) (req "hash" Block_hash.encoding) (req "header" (dynamic_size Block_header.encoding)) (req "operations" (list (list (dynamic_size Operation.encoding))))) Tezos_rpc.Path.(path / "applied_blocks") let heads_query = let open Tezos_rpc.Query in query (fun next_protocols -> object method next_protocols = next_protocols end) |+ multi_field "next_protocol" Protocol_hash.rpc_arg (fun t -> t#next_protocols) |> seal let heads = Tezos_rpc.Service.get_service ~description: "Monitor all blocks that are successfully validated and applied by the \ node and selected as the new head of the given chain." ~query:heads_query ~output: (merge_objs (obj1 (req "hash" Block_hash.encoding)) Block_header.encoding) Tezos_rpc.Path.(path / "heads" /: Chain_services.chain_arg) let protocols = Tezos_rpc.Service.get_service ~description: "Monitor all economic protocols that are retrieved and successfully \ loaded and compiled by the node." ~query:Tezos_rpc.Query.empty ~output:Protocol_hash.encoding Tezos_rpc.Path.(path / "protocols") (* DEPRECATED: use [version] from "version_services" instead. *) let commit_hash = Tezos_rpc.Service.get_service ~description:"DEPRECATED: use `version` instead." ~query:Tezos_rpc.Query.empty ~output:string Tezos_rpc.Path.(path / "commit_hash") let active_chains = Tezos_rpc.Service.get_service ~description: "Monitor every chain creation and destruction. Currently active chains \ will be given as first elements" ~query:Tezos_rpc.Query.empty ~output:(Data_encoding.list chain_status_encoding) Tezos_rpc.Path.(path / "active_chains") end open Tezos_rpc.Context let bootstrapped ctxt = make_streamed_call S.bootstrapped ctxt () () () let legacy_valid_blocks ctxt ?(chains = [`Main]) ?(protocols = []) ?(next_protocols = []) () = make_streamed_call S.legacy_valid_blocks ctxt () (object method chains = chains method protocols = protocols method next_protocols = next_protocols end) () let validated_blocks ctxt ?(chains = [`Main]) ?(protocols = []) ?(next_protocols = []) () = make_streamed_call S.validated_blocks ctxt () (object method chains = chains method protocols = protocols method next_protocols = next_protocols end) () let applied_blocks ctxt ?(chains = [`Main]) ?(protocols = []) ?(next_protocols = []) () = make_streamed_call S.applied_blocks ctxt () (object method chains = chains method protocols = protocols method next_protocols = next_protocols end) () let heads ctxt ?(next_protocols = []) chain = make_streamed_call S.heads ctxt ((), chain) (object method next_protocols = next_protocols end) () let protocols ctxt = make_streamed_call S.protocols ctxt () () () let commit_hash ctxt = make_call S.commit_hash ctxt () () () let active_chains ctxt = make_streamed_call S.active_chains ctxt () () ()
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
http.curl.ml
open Support open Support.Common let init = lazy ( Curl.(global_init CURLINIT_GLOBALALL); ) let is_redirect connection = let code = Curl.get_httpcode connection in code >= 300 && code < 400 (** Download the contents of [url] into [ch]. * This runs in a separate (either Lwt or native) thread. *) let download_no_follow ~cancelled ?size ?modification_time ?(start_offset=Int64.zero) ~progress connection ch url = let skip_bytes = ref (Int64.to_int start_offset) in let error_buffer = ref "" in Lwt.catch (fun () -> let redirect = ref None in let check_header header = if XString.starts_with (String.lowercase_ascii header) "location:" then ( redirect := Some (XString.tail header 9 |> String.trim) ); String.length header in if Support.Logging.will_log Support.Logging.Debug then Curl.set_verbose connection true; Curl.set_errorbuffer connection error_buffer; Curl.set_writefunction connection (fun data -> if !cancelled then 0 else ( try let l = String.length data in if !skip_bytes >= l then ( skip_bytes := !skip_bytes - l ) else ( output ch (Bytes.unsafe_of_string data) !skip_bytes (l - !skip_bytes); skip_bytes := 0 ); l with ex -> log_warning ~ex "Failed to write download data to temporary file"; error_buffer := !error_buffer ^ Printexc.to_string ex; 0 ) ); Curl.set_maxfilesizelarge connection (default Int64.zero size); begin match modification_time with | Some modification_time -> Curl.set_timecondition connection Curl.TIMECOND_IFMODSINCE; Curl.set_timevalue connection (Int32.of_float modification_time); (* Warning: 32-bit time *) | None -> (* ocurl won't let us unset timecondition, but at least we can make sure it never happens *) Curl.set_timevalue connection (Int32.zero) end; Curl.set_url connection url; Curl.set_useragent connection ("0install/" ^ About.version); Curl.set_headerfunction connection check_header; Curl.set_progressfunction connection (fun dltotal dlnow _ultotal _ulnow -> if !cancelled then true (* Don't override the finished=true signal *) else ( let dlnow = Int64.of_float dlnow in begin match size with | Some _ -> progress (dlnow, size, false) | None -> let total = if dltotal = 0.0 then None else Some (Int64.of_float dltotal) in progress (dlnow, total, false) end; false (* (continue download) *) ) ); Curl.set_noprogress connection false; (* progress = true *) Curl_lwt.perform connection >|= fun result -> (* Check for redirect header first because for large redirect bodies we may get a size-exceeded error rather than CURLE_OK. *) match !redirect with | Some target when is_redirect connection -> (* ocurl is missing CURLINFO_REDIRECT_URL, so we have to do this manually *) let target = Support.Urlparse.join_url url target in log_info "Redirect from '%s' to '%s'" url target; `Redirect target | _ -> match result with | Curl.CURLE_OK -> begin let actual_size = Curl.get_sizedownload connection in (* Curl.cleanup connection; - leave it open for the next request *) if modification_time <> None && actual_size = 0.0 then ( `Unmodified (* ocurl is missing CURLINFO_CONDITION_UNMET *) ) else ( size |> if_some (fun expected -> let expected = Int64.to_float expected in if expected <> actual_size then Safe_exn.failf "Downloaded archive has incorrect size.\n\ URL: %s\n\ Expected: %.0f bytes\n\ Received: %.0f bytes" url expected actual_size ); log_info "Download '%s' completed successfully (%.0f bytes)" url actual_size; `Success ) end | code -> raise Curl.(CurlException (code, errno code, strerror code)) ) (function | Curl.CurlException _ as ex -> if !cancelled then Lwt.return `Aborted_by_user else ( log_info ~ex "Curl error: %s" !error_buffer; let msg = Printf.sprintf "Error downloading '%s': %s" url !error_buffer in Lwt.return (`Network_failure msg) ) | ex -> raise ex ) let post ~data url = let error_buffer = ref "" in let connection = Curl.init () in Curl.set_nosignal connection true; (* Can't use DNS timeouts when multi-threaded *) Curl.set_failonerror connection true; if Support.Logging.will_log Support.Logging.Debug then Curl.set_verbose connection true; Curl.set_errorbuffer connection error_buffer; let output_buffer = Buffer.create 256 in Curl.set_writefunction connection (fun data -> Buffer.add_string output_buffer data; String.length data ); Curl.set_url connection url; Curl.set_post connection true; Curl.set_postfields connection data; Curl.set_postfieldsize connection (String.length data); Lwt.finalize (fun () -> Curl_lwt.perform connection) (fun () -> Curl.cleanup connection; Lwt.return ()) >|= function | Curl.CURLE_OK -> Ok (Buffer.contents output_buffer) | code -> let msg = Curl.strerror code in log_info "Curl error: %s\n%s" msg !error_buffer; Error (msg, !error_buffer) module Connection = struct type t = Curl.t let create () = Lazy.force init; let t = Curl.init () in Curl.set_nosignal t true; (* Can't use DNS timeouts when multi-threaded *) Curl.set_failonerror t true; Curl.set_followlocation t false; Curl.set_netrc t Curl.CURL_NETRC_OPTIONAL; t let release = Curl.cleanup let get = download_no_follow end let escape = Curl.escape let variant = "libcurl (C)"
l2_transaction.mli
open Protocol (** {2 Types for L2 transactions} *) type t = { transaction : (Indexable.unknown, Indexable.unknown) Tx_rollup_l2_batch.V1.transaction; signature : Tx_rollup_l2_batch.V1.signature; } (** Hash with b58check encoding txL2(54), for hashes of L2 transactions *) module Hash : S.HASH (** Alias for transaction hash *) type hash = Hash.t (** {2 Serialization} *) val encoding : t Data_encoding.encoding val hash : t -> Hash.t (** {2 Batching} *) (** Build a L2 batch of transactions by aggregating the BLS signatures of individual transactions *) val batch : t list -> (Indexable.unknown, Indexable.unknown) Tx_rollup_l2_batch.t tzresult
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
parser.mli
(** Parsing of the Dune language *) open Stdune module Mode : sig type 'a t = | Single : Ast.t t | Many : Ast.t list t | Many_as_one : Ast.t t | Cst : Cst.t list t end val parse : mode:'a Mode.t -> ?lexer:Lexer.t -> Lexing.lexbuf -> 'a val parse_string : fname:string -> mode:'a Mode.t -> ?lexer:Lexer.t -> string -> 'a val load : ?lexer:Lexer.t -> Path.t -> mode:'a Mode.t -> 'a (** Insert comments in a concrete syntax tree. Comments are inserted based on their location. *) val insert_comments : Cst.t list -> (Loc.t * string list) list -> Cst.t list
(** Parsing of the Dune language *)
unit_classes.ml
(** ocaml classes (http://caml.inria.fr/pub/docs/manual-ocaml/manual017.html) *) (* class types *) class type c = object end class type c = M.cl class type c = ['a, 'b] M.cl class type c = object ('ty) inherit cl val mutable virtual var : bool method private bar1 x ~y : bool method private virtual bar2 : 'a 'b.('a,'b) Hashtbl.t constraint 'a = 'b end (* class expressions *) class c = ['a, 'b] M.cl class c = fun a b -> object end class c = object val x = true end class c = object (_ : 'a) inherit Something.someclass as v val mutable var : bool = true val mutable virtual var2 : string method private bar1 x ~y : bool = false method private virtual bar2 : 'a 'b.('a,'b) Hashtbl.t constraint 'a = 'b initializer z end (* method specific expressions *) let e = var <- true let e = {< var = false; var2 = true; >} (* class definitions *) class cl = object val x = true end and virtual ['a, 'b] cl2 x y : object val x : bool end = fun x y -> object val x : bool = true end class cl : object end class type virtual ['a] clty = object method x : int end (* objects *) val a : < > let () = () val a : < .. > let () = () val a : < meth: int option; meth2: 'a. 'a option; meth3: 'a 'b. ('a,'b) Hashtbl.t > let () = () val a : < meth: int option; meth2: 'a. 'a option; meth3: 'a 'b. ('a,'b) Hashtbl.t; .. > let () = () (* #-types *) val a : #M.meth val a : 'a#M.meth val a : ('a,'b*'c) #M.meth (* object types *) type a = < > let () = () type a = < .. > let () = () type a = < meth: int option; meth2: 'a. 'a option; meth3: 'a 'b. ('a,'b) Hashtbl.t > let () = () type a = < meth: int option; meth2: 'a. 'a option; meth3: 'a 'b. ('a,'b) Hashtbl.t; .. > let () = () type t = < a : int; b: < a: int; b: < c:int > > > let () = () type t = < a : int; b: < a: int; b: < c: int -> int> >; c: int > let () = () type 'a t = | Bla : < x : int > t | Blo : < y : int > t
(** ocaml classes (http://caml.inria.fr/pub/docs/manual-ocaml/manual017.html) *)
dune
(executables (libraries angstrom core_bench threads RFC2616 RFC7159) (modules pure_benchmark) (names pure_benchmark)) (executables (libraries angstrom-async RFC2616 RFC7159) (modules async_benchmark) (names async_benchmark)) (executables (libraries angstrom-lwt-unix RFC2616 RFC7159) (modules lwt_benchmark) (names lwt_benchmark))
p256.mli
(** Tezos - P256 cryptography *) include S.SIGNATURE with type watermark := bytes
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
environment_V0.ml
open Environment_context open Environment_protocol_T module type V0 = sig include Tezos_protocol_environment_sigs.V0.T with type Format.formatter = Format.formatter and type 'a Data_encoding.t = 'a Data_encoding.t and type 'a Data_encoding.lazy_t = 'a Data_encoding.lazy_t and type 'a Lwt.t = 'a Lwt.t and type ('a, 'b) Pervasives.result = ('a, 'b) result and type Chain_id.t = Chain_id.t and type Block_hash.t = Block_hash.t and type Operation_hash.t = Operation_hash.t and type Operation_list_hash.t = Operation_list_hash.t and type Operation_list_list_hash.t = Operation_list_list_hash.t and type Context.t = Context.t and type Context_hash.t = Context_hash.t and type Protocol_hash.t = Protocol_hash.t and type Time.t = Time.Protocol.t and type MBytes.t = Tezos_protocol_environment_structs.V0.M.MBytes.t and type Operation.shell_header = Operation.shell_header and type Operation.t = Operation.t and type Block_header.shell_header = Block_header.shell_header and type Block_header.t = Block_header.t and type 'a RPC_directory.t = 'a RPC_directory.t and type Ed25519.Public_key_hash.t = Ed25519.Public_key_hash.t and type Ed25519.Public_key.t = Ed25519.Public_key.t and type Ed25519.t = Ed25519.t and type Secp256k1.Public_key_hash.t = Secp256k1.Public_key_hash.t and type Secp256k1.Public_key.t = Secp256k1.Public_key.t and type Secp256k1.t = Secp256k1.t and type P256.Public_key_hash.t = P256.Public_key_hash.t and type P256.Public_key.t = P256.Public_key.t and type P256.t = P256.t and type Signature.public_key_hash = Signature.public_key_hash and type Signature.public_key = Signature.public_key and type Signature.t = Signature.t and type Signature.watermark = Signature.watermark and type 'a Micheline.canonical = 'a Micheline.canonical and type Z.t = Z.t and type ('a, 'b) Micheline.node = ('a, 'b) Micheline.node and type Data_encoding.json_schema = Data_encoding.json_schema and type ('a, 'b) RPC_path.t = ('a, 'b) RPC_path.t and type RPC_service.meth = RPC_service.meth and type (+'m, 'pr, 'p, 'q, 'i, 'o) RPC_service.t = ('m, 'pr, 'p, 'q, 'i, 'o) RPC_service.t and type Error_monad.shell_error = Error_monad.error type error += Ecoproto_error of Error_monad.error val wrap_error : 'a Error_monad.tzresult -> 'a tzresult module Lift (P : Updater.PROTOCOL) : PROTOCOL with type block_header_data = P.block_header_data and type block_header_metadata = P.block_header_metadata and type block_header = P.block_header and type operation_data = P.operation_data and type operation_receipt = P.operation_receipt and type operation = P.operation and type validation_state = P.validation_state class ['chain, 'block] proto_rpc_context : Tezos_rpc.RPC_context.t -> (unit, (unit * 'chain) * 'block) RPC_path.t -> ['chain * 'block] RPC_context.simple class ['block] proto_rpc_context_of_directory : ('block -> RPC_context.t) -> RPC_context.t RPC_directory.t -> ['block] RPC_context.simple end module MakeV0 (Param : sig val name : string end) () = struct include Stdlib (* The modules provided in the [_struct.V0.M] pack are meant specifically to shadow modules from [Stdlib]/[Base]/etc. with backwards compatible versions. Thus we open the module, hiding the incompatible, newer modules. *) open Tezos_protocol_environment_structs.V0.M module Pervasives = Stdlib module Compare = Compare module List = List module Bytes = struct include Bytes include EndianBytes.BigEndian module LE = EndianBytes.LittleEndian end module String = struct include String include EndianString.BigEndian module LE = EndianString.LittleEndian end module Set = Stdlib.Set module Map = Stdlib.Map module Int32 = Int32 module Int64 = Int64 module Nativeint = Nativeint module Buffer = Buffer module Format = Format module Option = Option module MBytes = MBytes module Raw_hashes = struct let sha256 = Hacl.Hash.SHA256.digest let sha512 = Hacl.Hash.SHA512.digest let blake2b msg = Blake2B.to_bytes (Blake2B.hash_bytes [msg]) end module Z = struct include Z let to_bits ?(pad_to = 0) z = let bits = to_bits z in let len = Pervasives.((numbits z + 7) / 8) in let full_len = Tezos_stdlib.Compare.Int.max pad_to len in if full_len = 0 then MBytes.create 0 else let res = MBytes.create full_len in Bytes.fill res 0 full_len '\000' ; MBytes.blit_of_string bits 0 res 0 len ; res let of_bits bytes = of_bits (MBytes.to_string bytes) end module Lwt_sequence = Lwt_sequence module Lwt = Lwt module Lwt_list = Lwt_list module Uri = Uri module Data_encoding = struct include Data_encoding let def name ?title ?description encoding = def (Param.name ^ "." ^ name) ?title ?description encoding end module Time = Time.Protocol module Ed25519 = Ed25519 module Secp256k1 = Secp256k1 module P256 = P256 module Signature = Signature module S = struct module type T = Tezos_base.S.T module type HASHABLE = Tezos_base.S.HASHABLE module type MINIMAL_HASH = Tezos_crypto.S.MINIMAL_HASH module type B58_DATA = sig type t val to_b58check : t -> string val to_short_b58check : t -> string val of_b58check_exn : string -> t val of_b58check_opt : string -> t option type Base58.data += Data of t val b58check_encoding : t Base58.encoding end module type RAW_DATA = sig type t val size : int (* in bytes *) val to_bytes : t -> MBytes.t val of_bytes_opt : MBytes.t -> t option val of_bytes_exn : MBytes.t -> t end module type ENCODER = sig type t val encoding : t Data_encoding.t val rpc_arg : t RPC_arg.t end module type SET = S.SET module type MAP = S.MAP module type INDEXES = sig type t val to_path : t -> string list -> string list val of_path : string list -> t option val of_path_exn : string list -> t val prefix_path : string -> string list val path_length : int module Set : sig include SET with type elt = t val encoding : t Data_encoding.t end module Map : sig include MAP with type key = t val encoding : 'a Data_encoding.t -> 'a t Data_encoding.t end end module type HASH = sig include MINIMAL_HASH include RAW_DATA with type t := t include B58_DATA with type t := t include ENCODER with type t := t include INDEXES with type t := t end module type MERKLE_TREE = sig type elt include HASH val compute : elt list -> t val empty : t type path = Left of path * t | Right of t * path | Op val compute_path : elt list -> int -> path val check_path : path -> elt -> t * int val path_encoding : path Data_encoding.t end module type SIGNATURE = sig module Public_key_hash : sig type t val pp : Format.formatter -> t -> unit val pp_short : Format.formatter -> t -> unit include Compare.S with type t := t include RAW_DATA with type t := t include B58_DATA with type t := t include ENCODER with type t := t include INDEXES with type t := t val zero : t end module Public_key : sig type t val pp : Format.formatter -> t -> unit include Compare.S with type t := t include B58_DATA with type t := t include ENCODER with type t := t val hash : t -> Public_key_hash.t end type t val pp : Format.formatter -> t -> unit include RAW_DATA with type t := t include Compare.S with type t := t include B58_DATA with type t := t include ENCODER with type t := t val zero : t type watermark (** Check a signature *) val check : ?watermark:watermark -> Public_key.t -> t -> MBytes.t -> bool end end module Error_core = struct include Tezos_error_monad.Core_maker.Make (struct let id = Format.asprintf "proto.%s." Param.name end) (Tezos_protocol_environment_structs.V0.M.Error_monad_classification) let error_encoding = Data_encoding.dynamic_size error_encoding end type error_category = Error_core.error_category type error += Ecoproto_error of Error_core.error module Wrapped_error_monad = struct type unwrapped = Error_core.error = .. include ( Error_core : sig include Tezos_error_monad.Sig.CORE with type error := unwrapped and type error_category = error_category end) let unwrap = function Ecoproto_error ecoerror -> Some ecoerror | _ -> None let wrap ecoerror = Ecoproto_error ecoerror end module Error_monad = struct type 'a shell_tzresult = 'a Error_monad.tzresult type shell_error = Error_monad.error = .. include Error_core include Tezos_error_monad.TzLwtreslib.Monad include Tezos_error_monad.Monad_maker.Make (Error_core) (TzTrace) (Tezos_error_monad.TzLwtreslib.Monad) (* below is for backward compatibility *) include Error_monad_infix_globals include Error_monad_traversors include Error_monad_trace_eval let fail e = Lwt.return_error (TzTrace.make e) let error e = Error (TzTrace.make e) (* Shouldn't be used, only to keep the same environment interface *) let classify_errors = function | [] -> `Temporary | error :: _ -> (find_info_of_error error).category end let () = let id = Format.asprintf "proto.%s.wrapper" Param.name in register_wrapped_error_kind (module Wrapped_error_monad) ~id ~title:("Error returned by protocol " ^ Param.name) ~description:("Wrapped error for economic protocol " ^ Param.name ^ ".") let wrap_error = function | Ok _ as ok -> ok | Error errors -> Error (List.map (fun error -> Ecoproto_error error) errors) module Chain_id = Chain_id module Block_hash = Block_hash module Operation_hash = Operation_hash module Operation_list_hash = Operation_list_hash module Operation_list_list_hash = Operation_list_list_hash module Context_hash = Context_hash module Protocol_hash = Protocol_hash module Blake2B = Blake2B module Fitness = Fitness module Operation = Operation module Block_header = Block_header module Protocol = Protocol module RPC_arg = RPC_arg module RPC_path = RPC_path module RPC_query = RPC_query module RPC_service = RPC_service module RPC_answer = struct type 'o t = [ `Ok of 'o (* 200 *) | `OkStream of 'o stream (* 200 *) | `Created of string option (* 201 *) | `No_content (* 204 *) | `Unauthorized of Error_monad.error list option (* 401 *) | `Forbidden of Error_monad.error list option (* 403 *) | `Not_found of Error_monad.error list option (* 404 *) | `Conflict of Error_monad.error list option (* 409 *) | `Error of Error_monad.error list option (* 500 *) ] and 'a stream = 'a Resto_directory.Answer.stream = { next : unit -> 'a option Lwt.t; shutdown : unit -> unit; } let return x = Lwt.return (`Ok x) let return_chunked x = Lwt.return (`OkChunk x) let return_stream x = Lwt.return (`OkStream x) let not_found = Lwt.return (`Not_found None) let fail err = Lwt.return (`Error (Some err)) end module RPC_directory = struct include RPC_directory let gen_register dir service handler = let open Lwt_syntax in gen_register dir service (fun p q i -> let* r = handler p q i in match r with | `Ok o -> RPC_answer.return_chunked o | `OkStream s -> RPC_answer.return_stream s | `Created s -> Lwt.return (`Created s) | `No_content -> Lwt.return `No_content | `Unauthorized e -> let e = Option.map e ~f:(List.map (fun e -> Ecoproto_error e)) in Lwt.return (`Unauthorized e) | `Forbidden e -> let e = Option.map e ~f:(List.map (fun e -> Ecoproto_error e)) in Lwt.return (`Forbidden e) | `Not_found e -> let e = Option.map e ~f:(List.map (fun e -> Ecoproto_error e)) in Lwt.return (`Not_found e) | `Conflict e -> let e = Option.map e ~f:(List.map (fun e -> Ecoproto_error e)) in Lwt.return (`Conflict e) | `Error e -> let e = Option.map e ~f:(List.map (fun e -> Ecoproto_error e)) in Lwt.return (`Error e)) let register dir service handler = let open Lwt_syntax in gen_register dir service (fun p q i -> let* r = handler p q i in match r with | Ok o -> RPC_answer.return o | Error e -> RPC_answer.fail e) let opt_register dir service handler = let open Lwt_syntax in gen_register dir service (fun p q i -> let* r = handler p q i in match r with | Ok (Some o) -> RPC_answer.return o | Ok None -> RPC_answer.not_found | Error e -> RPC_answer.fail e) let lwt_register dir service handler = let open Lwt_syntax in gen_register dir service (fun p q i -> let* o = handler p q i in RPC_answer.return o) open Curry let register0 root s f = register root s (curry Z f) let register1 root s f = register root s (curry (S Z) f) let register2 root s f = register root s (curry (S (S Z)) f) let register3 root s f = register root s (curry (S (S (S Z))) f) let register4 root s f = register root s (curry (S (S (S (S Z)))) f) let register5 root s f = register root s (curry (S (S (S (S (S Z))))) f) let opt_register0 root s f = opt_register root s (curry Z f) let opt_register1 root s f = opt_register root s (curry (S Z) f) let opt_register2 root s f = opt_register root s (curry (S (S Z)) f) let opt_register3 root s f = opt_register root s (curry (S (S (S Z))) f) let opt_register4 root s f = opt_register root s (curry (S (S (S (S Z)))) f) let opt_register5 root s f = opt_register root s (curry (S (S (S (S (S Z))))) f) let gen_register0 root s f = gen_register root s (curry Z f) let gen_register1 root s f = gen_register root s (curry (S Z) f) let gen_register2 root s f = gen_register root s (curry (S (S Z)) f) let gen_register3 root s f = gen_register root s (curry (S (S (S Z))) f) let gen_register4 root s f = gen_register root s (curry (S (S (S (S Z)))) f) let gen_register5 root s f = gen_register root s (curry (S (S (S (S (S Z))))) f) let lwt_register0 root s f = lwt_register root s (curry Z f) let lwt_register1 root s f = lwt_register root s (curry (S Z) f) let lwt_register2 root s f = lwt_register root s (curry (S (S Z)) f) let lwt_register3 root s f = lwt_register root s (curry (S (S (S Z))) f) let lwt_register4 root s f = lwt_register root s (curry (S (S (S (S Z)))) f) let lwt_register5 root s f = lwt_register root s (curry (S (S (S (S (S Z))))) f) end module RPC_context = struct type t = rpc_context class type ['pr] simple = object method call_proto_service0 : 'm 'q 'i 'o. (([< RPC_service.meth] as 'm), t, t, 'q, 'i, 'o) RPC_service.t -> 'pr -> 'q -> 'i -> 'o Error_monad.shell_tzresult Lwt.t method call_proto_service1 : 'm 'a 'q 'i 'o. (([< RPC_service.meth] as 'm), t, t * 'a, 'q, 'i, 'o) RPC_service.t -> 'pr -> 'a -> 'q -> 'i -> 'o Error_monad.shell_tzresult Lwt.t method call_proto_service2 : 'm 'a 'b 'q 'i 'o. ( ([< RPC_service.meth] as 'm), t, (t * 'a) * 'b, 'q, 'i, 'o ) RPC_service.t -> 'pr -> 'a -> 'b -> 'q -> 'i -> 'o Error_monad.shell_tzresult Lwt.t method call_proto_service3 : 'm 'a 'b 'c 'q 'i 'o. ( ([< RPC_service.meth] as 'm), t, ((t * 'a) * 'b) * 'c, 'q, 'i, 'o ) RPC_service.t -> 'pr -> 'a -> 'b -> 'c -> 'q -> 'i -> 'o Error_monad.shell_tzresult Lwt.t end let make_call0 s (ctxt : _ simple) = ctxt#call_proto_service0 s let make_call0 = (make_call0 : _ -> _ simple -> _ :> _ -> _ #simple -> _) let make_call1 s (ctxt : _ simple) = ctxt#call_proto_service1 s let make_call1 = (make_call1 : _ -> _ simple -> _ :> _ -> _ #simple -> _) let make_call2 s (ctxt : _ simple) = ctxt#call_proto_service2 s let make_call2 = (make_call2 : _ -> _ simple -> _ :> _ -> _ #simple -> _) let make_call3 s (ctxt : _ simple) = ctxt#call_proto_service3 s let make_call3 = (make_call3 : _ -> _ simple -> _ :> _ -> _ #simple -> _) let make_opt_call0 s ctxt block q i = let open Lwt_syntax in let* r = make_call0 s ctxt block q i in match r with | Error [RPC_context.Not_found _] -> Lwt.return_ok None | Error _ as v -> Lwt.return v | Ok v -> Lwt.return_ok (Some v) let make_opt_call1 s ctxt block a1 q i = let open Lwt_syntax in let* r = make_call1 s ctxt block a1 q i in match r with | Error [RPC_context.Not_found _] -> Lwt.return_ok None | Error _ as v -> Lwt.return v | Ok v -> Lwt.return_ok (Some v) let make_opt_call2 s ctxt block a1 a2 q i = let open Lwt_syntax in let* r = make_call2 s ctxt block a1 a2 q i in match r with | Error [RPC_context.Not_found _] -> Lwt.return_ok None | Error _ as v -> Lwt.return v | Ok v -> Lwt.return_ok (Some v) let make_opt_call3 s ctxt block a1 a2 a3 q i = let open Lwt_syntax in let* r = make_call3 s ctxt block a1 a2 a3 q i in match r with | Error [RPC_context.Not_found _] -> Lwt.return_ok None | Error _ as v -> Lwt.return v | Ok v -> Lwt.return_ok (Some v) end module Micheline = struct include Micheline include Tezos_micheline.Micheline_encoding let canonical_encoding_v1 ~variant encoding = canonical_encoding_v1 ~variant:(Param.name ^ "." ^ variant) encoding let canonical_encoding ~variant encoding = canonical_encoding_v0 ~variant:(Param.name ^ "." ^ variant) encoding end module Logging = Internal_event.Legacy_logging.Make (Param) module Updater = struct type nonrec validation_result = validation_result = { context : Context.t; fitness : Fitness.t; message : string option; max_operations_ttl : int; last_allowed_fork_level : Int32.t; } type nonrec quota = quota = {max_size : int; max_op : int option} type nonrec rpc_context = rpc_context = { block_hash : Block_hash.t; block_header : Block_header.shell_header; context : Context.t; } let activate = Context.set_protocol let fork_test_chain = Context.fork_test_chain module type PROTOCOL = Environment_protocol_T_V0.T with type context := Context.t and type quota := quota and type validation_result := validation_result and type rpc_context := rpc_context and type 'a tzresult := 'a Error_monad.tzresult end module Base58 = struct include Tezos_crypto.Base58 let simple_encode enc s = simple_encode enc s let simple_decode enc s = simple_decode enc s include Make (struct type context = Context.t end) let decode s = decode s end module Context = struct include Context let set = add let get = find let dir_mem = mem_tree let remove_rec = remove let copy ctxt ~from ~to_ = let open Lwt_syntax in let* sub_tree = find_tree ctxt from in Tezos_error_monad.TzLwtreslib.Option.map_s (add_tree ctxt to_) sub_tree let fold_keys s root ~init ~f = Context.fold s root ~order:`Sorted ~init ~f:(fun k v acc -> let k = root @ k in match Tree.kind v with `Value -> f k acc | `Tree -> Lwt.return acc) let fold t root ~init ~f = Context.fold ~depth:(`Eq 1) t root ~order:`Sorted ~init ~f:(fun k v acc -> let k = root @ k in match Tree.kind v with | `Value -> f (`Key k) acc | `Tree -> f (`Dir k) acc) let keys t = fold_keys t ~init:[] ~f:(fun k acc -> Lwt.return (k :: acc)) let register_resolver = Base58.register_resolver let complete ctxt s = Base58.complete ctxt s let del = remove end module LiftV0 (P : Updater.PROTOCOL) = struct include P let begin_partial_application ~chain_id ~ancestor_context ~predecessor_timestamp ~predecessor_fitness raw_block = let open Lwt_syntax in let+ r = begin_partial_application ~chain_id ~ancestor_context ~predecessor_timestamp ~predecessor_fitness raw_block in wrap_error r let begin_application ~chain_id ~predecessor_context ~predecessor_timestamp ~predecessor_fitness raw_block = let open Lwt_syntax in let+ r = begin_application ~chain_id ~predecessor_context ~predecessor_timestamp ~predecessor_fitness raw_block in wrap_error r let begin_construction ~chain_id ~predecessor_context ~predecessor_timestamp ~predecessor_level ~predecessor_fitness ~predecessor ~timestamp ?protocol_data () = let open Lwt_syntax in let+ r = begin_construction ~chain_id ~predecessor_context ~predecessor_timestamp ~predecessor_level ~predecessor_fitness ~predecessor ~timestamp ?protocol_data () in wrap_error r let current_context c = let open Lwt_syntax in let+ r = current_context c in wrap_error r let apply_operation c o = let open Lwt_syntax in let+ r = apply_operation c o in wrap_error r let finalize_block c = let open Lwt_syntax in let+ r = finalize_block c in wrap_error r let init c bh = let open Lwt_syntax in let+ r = init c bh in wrap_error r end module Lift (P : Updater.PROTOCOL) = Environment_protocol_T.IgnoreCaches (struct let environment_version = Protocol.V0 let set_log_message_consumer _ = () include Environment_protocol_T.V0toV3 (LiftV0 (P)) end) class ['chain, 'block] proto_rpc_context (t : Tezos_rpc.RPC_context.t) (prefix : (unit, (unit * 'chain) * 'block) RPC_path.t) = object method call_proto_service0 : 'm 'q 'i 'o. ( ([< RPC_service.meth] as 'm), RPC_context.t, RPC_context.t, 'q, 'i, 'o ) RPC_service.t -> 'chain * 'block -> 'q -> 'i -> 'o tzresult Lwt.t = fun s (chain, block) q i -> let s = RPC_service.subst0 s in let s = RPC_service.prefix prefix s in t#call_service s (((), chain), block) q i method call_proto_service1 : 'm 'a 'q 'i 'o. ( ([< RPC_service.meth] as 'm), RPC_context.t, RPC_context.t * 'a, 'q, 'i, 'o ) RPC_service.t -> 'chain * 'block -> 'a -> 'q -> 'i -> 'o tzresult Lwt.t = fun s (chain, block) a1 q i -> let s = RPC_service.subst1 s in let s = RPC_service.prefix prefix s in t#call_service s ((((), chain), block), a1) q i method call_proto_service2 : 'm 'a 'b 'q 'i 'o. ( ([< RPC_service.meth] as 'm), RPC_context.t, (RPC_context.t * 'a) * 'b, 'q, 'i, 'o ) RPC_service.t -> 'chain * 'block -> 'a -> 'b -> 'q -> 'i -> 'o tzresult Lwt.t = fun s (chain, block) a1 a2 q i -> let s = RPC_service.subst2 s in let s = RPC_service.prefix prefix s in t#call_service s (((((), chain), block), a1), a2) q i method call_proto_service3 : 'm 'a 'b 'c 'q 'i 'o. ( ([< RPC_service.meth] as 'm), RPC_context.t, ((RPC_context.t * 'a) * 'b) * 'c, 'q, 'i, 'o ) RPC_service.t -> 'chain * 'block -> 'a -> 'b -> 'c -> 'q -> 'i -> 'o tzresult Lwt.t = fun s (chain, block) a1 a2 a3 q i -> let s = RPC_service.subst3 s in let s = RPC_service.prefix prefix s in t#call_service s ((((((), chain), block), a1), a2), a3) q i end class ['block] proto_rpc_context_of_directory conv dir : ['block] RPC_context.simple = let lookup = new Tezos_rpc.RPC_context.of_directory dir in object method call_proto_service0 : 'm 'q 'i 'o. ( ([< RPC_service.meth] as 'm), RPC_context.t, RPC_context.t, 'q, 'i, 'o ) RPC_service.t -> 'block -> 'q -> 'i -> 'o tzresult Lwt.t = fun s block q i -> let rpc_context = conv block in lookup#call_service s rpc_context q i method call_proto_service1 : 'm 'a 'q 'i 'o. ( ([< RPC_service.meth] as 'm), RPC_context.t, RPC_context.t * 'a, 'q, 'i, 'o ) RPC_service.t -> 'block -> 'a -> 'q -> 'i -> 'o tzresult Lwt.t = fun s block a1 q i -> let rpc_context = conv block in lookup#call_service s (rpc_context, a1) q i method call_proto_service2 : 'm 'a 'b 'q 'i 'o. ( ([< RPC_service.meth] as 'm), RPC_context.t, (RPC_context.t * 'a) * 'b, 'q, 'i, 'o ) RPC_service.t -> 'block -> 'a -> 'b -> 'q -> 'i -> 'o tzresult Lwt.t = fun s block a1 a2 q i -> let rpc_context = conv block in lookup#call_service s ((rpc_context, a1), a2) q i method call_proto_service3 : 'm 'a 'b 'c 'q 'i 'o. ( ([< RPC_service.meth] as 'm), RPC_context.t, ((RPC_context.t * 'a) * 'b) * 'c, 'q, 'i, 'o ) RPC_service.t -> 'block -> 'a -> 'b -> 'c -> 'q -> 'i -> 'o tzresult Lwt.t = fun s block a1 a2 a3 q i -> let rpc_context = conv block in lookup#call_service s (((rpc_context, a1), a2), a3) q i end end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* Copyright (c) 2018-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.ml
module B = Dolmen_type.Misc.Bitv let print s = Format.printf "%s@." s let () = Printexc.record_backtrace true; (* Testing binary parsing (not much chance of it being wrong) *) print @@ B.parse_binary "#b011010"; print @@ B.parse_binary "#b111001"; begin try ignore (B.parse_binary "#b10a0101"); print "fail !" with B.Invalid_char 'a' -> print "ok" end; (* Testing hexadecimal parsing *) print @@ B.parse_hexa "#x10"; print @@ B.parse_hexa "#x6B2D"; print @@ B.parse_hexa "#x123456789abcdef"; (* Testing decimal parsing (much more likely to have bugs, given the complexity of the code) *) print @@ B.parse_decimal "bv10" 2; print @@ B.parse_decimal "bv10" 5; print @@ B.parse_decimal "bv999" 5; print @@ B.parse_decimal "bv999" 10; print @@ B.parse_decimal "bv9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999" 334; (* end *) ()
bsd-proctitle.c
#include "uv.h" #include "internal.h" #include <sys/types.h> #include <unistd.h> static uv_mutex_t process_title_mutex; static uv_once_t process_title_mutex_once = UV_ONCE_INIT; static char* process_title; static void init_process_title_mutex_once(void) { if (uv_mutex_init(&process_title_mutex)) abort(); } void uv__process_title_cleanup(void) { uv_once(&process_title_mutex_once, init_process_title_mutex_once); uv_mutex_destroy(&process_title_mutex); } char** uv_setup_args(int argc, char** argv) { process_title = argc > 0 ? uv__strdup(argv[0]) : NULL; return argv; } int uv_set_process_title(const char* title) { char* new_title; new_title = uv__strdup(title); if (new_title == NULL) return UV_ENOMEM; uv_once(&process_title_mutex_once, init_process_title_mutex_once); uv_mutex_lock(&process_title_mutex); uv__free(process_title); process_title = new_title; setproctitle("%s", title); uv_mutex_unlock(&process_title_mutex); return 0; } int uv_get_process_title(char* buffer, size_t size) { size_t len; if (buffer == NULL || size == 0) return UV_EINVAL; uv_once(&process_title_mutex_once, init_process_title_mutex_once); uv_mutex_lock(&process_title_mutex); if (process_title != NULL) { len = strlen(process_title) + 1; if (size < len) { uv_mutex_unlock(&process_title_mutex); return UV_ENOBUFS; } memcpy(buffer, process_title, len); } else { len = 0; } uv_mutex_unlock(&process_title_mutex); buffer[len] = '\0'; return 0; }
/* Copyright libuv project contributors. All rights reserved. * * 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. */
raw_context.mli
(** {1 Errors} ****************************************************************) type error += Too_many_internal_operations (* `Permanent *) (** An internal storage error that should not happen *) type storage_error = | Incompatible_protocol_version of string | Missing_key of string list * [`Get | `Set | `Del | `Copy] | Existing_key of string list | Corrupted_data of string list type error += Storage_error of storage_error type error += Failed_to_parse_parameter of MBytes.t type error += Failed_to_decode_parameter of Data_encoding.json * string val storage_error: storage_error -> 'a tzresult Lwt.t (** {1 Abstract Context} **************************************************) (** Abstract view of the context. Includes a handle to the functional key-value database ({!Context.t}) along with some in-memory values (gas, etc.). *) type t type context = t type root_context = t (** Retrieves the state of the database and gives its abstract view. It also returns wether this is the first block validated with this version of the protocol. *) val prepare: level: Int32.t -> timestamp: Time.t -> fitness: Fitness.t -> Context.t -> context tzresult Lwt.t type previous_protocol = | Genesis of Parameters_repr.t | Alpha_003 val prepare_first_block: level:int32 -> timestamp:Time.t -> fitness:Fitness.t -> Context.t -> (previous_protocol * context) tzresult Lwt.t val activate: context -> Protocol_hash.t -> t Lwt.t val fork_test_chain: context -> Protocol_hash.t -> Time.t -> t Lwt.t val register_resolvers: 'a Base58.encoding -> (context -> string -> 'a list Lwt.t) -> unit (** Returns the state of the database resulting of operations on its abstract view *) val recover: context -> Context.t val current_level: context -> Level_repr.t val current_timestamp: context -> Time.t val current_fitness: context -> Int64.t val set_current_fitness: context -> Int64.t -> t val constants: context -> Constants_repr.parametric val patch_constants: context -> (Constants_repr.parametric -> Constants_repr.parametric) -> context Lwt.t val first_level: context -> Raw_level_repr.t (** Increment the current block fee stash that will be credited to baker's frozen_fees account at finalize_application *) val add_fees: context -> Tez_repr.t -> context tzresult Lwt.t (** Increment the current block reward stash that will be credited to baker's frozen_fees account at finalize_application *) val add_rewards: context -> Tez_repr.t -> context tzresult Lwt.t (** Increment the current block deposit stash for a specific delegate. All the delegates' frozen_deposit accounts are credited at finalize_application *) val add_deposit: context -> Signature.Public_key_hash.t -> Tez_repr.t -> context tzresult Lwt.t val get_fees: context -> Tez_repr.t val get_rewards: context -> Tez_repr.t val get_deposits: context -> Tez_repr.t Signature.Public_key_hash.Map.t type error += Gas_limit_too_high (* `Permanent *) val check_gas_limit: t -> Z.t -> unit tzresult val set_gas_limit: t -> Z.t -> t val set_gas_unlimited: t -> t val gas_level: t -> Gas_limit_repr.t val gas_consumed: since: t -> until: t -> Z.t val block_gas_level: t -> Z.t val init_storage_space_to_pay: t -> t val update_storage_space_to_pay: t -> Z.t -> t val update_allocated_contracts_count: t -> t val clear_storage_space_to_pay: t -> t * Z.t * int type error += Undefined_operation_nonce (* `Permanent *) val init_origination_nonce: t -> Operation_hash.t -> t val origination_nonce: t -> Contract_repr.origination_nonce tzresult val increment_origination_nonce: t -> (t * Contract_repr.origination_nonce) tzresult val unset_origination_nonce: t -> t (** {1 Generic accessors} *************************************************) type key = string list type value = MBytes.t (** All context manipulation functions. This signature is included as-is for direct context accesses, and used in {!Storage_functors} to provide restricted views to the context. *) module type T = sig type t type context = t (** Tells if the key is already defined as a value. *) val mem: context -> key -> bool Lwt.t (** Tells if the key is already defined as a directory. *) val dir_mem: context -> key -> bool Lwt.t (** Retrieve the value from the storage bucket ; returns a {!Storage_error Missing_key} if the key is not set. *) val get: context -> key -> value tzresult Lwt.t (** Retrieves the value from the storage bucket ; returns [None] if the data is not initialized. *) val get_option: context -> key -> value option Lwt.t (** Allocates the storage bucket and initializes it ; returns a {!Storage_error Existing_key} if the bucket exists. *) val init: context -> key -> value -> context tzresult Lwt.t (** Updates the content of the bucket ; returns a {!Storage_error Missing_key} if the value does not exists. *) val set: context -> key -> value -> context tzresult Lwt.t (** Allocates the data and initializes it with a value ; just updates it if the bucket exists. *) val init_set: context -> key -> value -> context Lwt.t (** When the value is [Some v], allocates the data and initializes it with [v] ; just updates it if the bucket exists. When the valus is [None], delete the storage bucket when the value ; does nothing if the bucket does not exists. *) val set_option: context -> key -> value option -> context Lwt.t (** Delete the storage bucket ; returns a {!Storage_error Missing_key} if the bucket does not exists. *) val delete: context -> key -> context tzresult Lwt.t (** Removes the storage bucket and its contents ; does nothing if the bucket does not exists. *) val remove: context -> key -> context Lwt.t (** Recursively removes all the storage buckets and contents ; does nothing if no bucket exists. *) val remove_rec: context -> key -> context Lwt.t val copy: context -> from:key -> to_:key -> context tzresult Lwt.t (** Iterator on all the items of a given directory. *) val fold: context -> key -> init:'a -> f:([ `Key of key | `Dir of key ] -> 'a -> 'a Lwt.t) -> 'a Lwt.t (** Recursively list all subkeys of a given key. *) val keys: context -> key -> key list Lwt.t (** Recursive iterator on all the subkeys of a given key. *) val fold_keys: context -> key -> init:'a -> f:(key -> 'a -> 'a Lwt.t) -> 'a Lwt.t (** Internally used in {!Storage_functors} to escape from a view. *) val project: context -> root_context (** Internally used in {!Storage_functors} to retrieve a full key from partial key relative a view. *) val absolute_key: context -> key -> key (** Internally used in {!Storage_functors} to consume gas from within a view. *) val consume_gas: context -> Gas_limit_repr.cost -> context tzresult (** Check if consume_gas will fail *) val check_enough_gas: context -> Gas_limit_repr.cost -> unit tzresult val description: context Storage_description.t end include T with type t := t and type context := context (** Initialize the local nonce used for preventing a script to duplicate an internal operation to replay it. *) val reset_internal_nonce: context -> context (** Increments the internal operation nonce. *) val fresh_internal_nonce: context -> (context * int) tzresult (** Mark an internal operation nonce as taken. *) val record_internal_nonce: context -> int -> context (** Check is the internal operation nonce has been taken. *) val internal_nonce_already_recorded: context -> int -> bool (** Returns a map where to each endorser's pkh is associated the list of its endorsing slots (in decreasing order) for a given level. *) val allowed_endorsements: context -> (Signature.Public_key.t * int list * bool) Signature.Public_key_hash.Map.t (** Initializes the map of allowed endorsements, this function must only be called once. *) val init_endorsements: context -> (Signature.Public_key.t * int list * bool) Signature.Public_key_hash.Map.t -> context (** Marks an endorsment in the map as used. *) val record_endorsement: context -> Signature.Public_key_hash.t -> context
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
file_name.mli
(** Used to determine which name to use for a file, depending on the operation. *) open! Core_kernel open! Import type t = | Real of { real_name : string ; alt_name : string option } (** A name corresponding to a real file on disk. [alt_name] is used to display the file name and for file extension heuristics. *) | Fake of string (** A name not necessarily corresponding to a real file. *) [@@deriving compare, equal] (** The name used to access the file system. May differ from the name used for display. *) val real_name_exn : t -> string (** The name used for display. Also used for file extension heuristics. If [t] has an [alt_name], then that is used. Otherwise, the real name is used. *) val display_name : t -> string (** Equivalent to {!display_name}. *) val to_string_hum : t -> string (** Append a path component to each of [real_name], [alt_name]. *) val append : t -> string -> t val dev_null : t
(** Used to determine which name to use for a file, depending on the operation. *)
solve_tril.c
#include "acb_mat.h" void acb_mat_solve_tril_classical(acb_mat_t X, const acb_mat_t L, const acb_mat_t B, int unit, slong prec) { slong i, j, n, m; acb_ptr tmp; acb_t s; n = L->r; m = B->c; acb_init(s); tmp = flint_malloc(sizeof(acb_struct) * n); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) tmp[j] = *acb_mat_entry(X, j, i); for (j = 0; j < n; j++) { acb_dot(s, acb_mat_entry(B, j, i), 1, L->rows[j], 1, tmp, 1, j, prec); if (!unit) acb_div(tmp + j, s, acb_mat_entry(L, j, j), prec); else acb_swap(tmp + j, s); } for (j = 0; j < n; j++) *acb_mat_entry(X, j, i) = tmp[j]; } flint_free(tmp); acb_clear(s); } void acb_mat_solve_tril_recursive(acb_mat_t X, const acb_mat_t L, const acb_mat_t B, int unit, slong prec) { acb_mat_t LA, LC, LD, XX, XY, BX, BY, T; slong r, n, m; n = L->r; m = B->c; r = n / 2; if (n == 0 || m == 0) return; /* Denoting inv(M) by M^, we have: [A 0]^ [X] == [A^ 0 ] [X] == [A^ X] [C D] [Y] == [-D^ C A^ D^] [Y] == [D^ (Y - C A^ X)] */ acb_mat_window_init(LA, L, 0, 0, r, r); acb_mat_window_init(LC, L, r, 0, n, r); acb_mat_window_init(LD, L, r, r, n, n); acb_mat_window_init(BX, B, 0, 0, r, m); acb_mat_window_init(BY, B, r, 0, n, m); acb_mat_window_init(XX, X, 0, 0, r, m); acb_mat_window_init(XY, X, r, 0, n, m); acb_mat_solve_tril(XX, LA, BX, unit, prec); /* acb_mat_submul(XY, BY, LC, XX); */ acb_mat_init(T, LC->r, BX->c); acb_mat_mul(T, LC, XX, prec); acb_mat_sub(XY, BY, T, prec); acb_mat_clear(T); acb_mat_solve_tril(XY, LD, XY, unit, prec); acb_mat_window_clear(LA); acb_mat_window_clear(LC); acb_mat_window_clear(LD); acb_mat_window_clear(BX); acb_mat_window_clear(BY); acb_mat_window_clear(XX); acb_mat_window_clear(XY); } void acb_mat_solve_tril(acb_mat_t X, const acb_mat_t L, const acb_mat_t B, int unit, slong prec) { if (B->r < 40 || B->c < 40) acb_mat_solve_tril_classical(X, L, B, unit, prec); else acb_mat_solve_tril_recursive(X, L, B, unit, prec); }
/* Copyright (C) 2018 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/>. */
test_cells.ml
let debug = false (* For each of [n_values], spawn one producer and one consumer. If the consumer has to wait, it will also try to cancel. The consumer increases the total if it gets a value; the producer increments it if the cancellation succeeds instead. *) let test_cells ~segment_order ~n_values () = let module Cqs = Simple_cqs.Make(struct let segment_order = segment_order end) in let expected_total = n_values in let t = Cqs.make () in let total = ref 0 in for i = 1 to n_values do Atomic.spawn (fun () -> if debug then Fmt.epr "%d: wrote value@." i; Cqs.resume t 1; ); Atomic.spawn (fun () -> match Cqs.suspend t (fun v -> if debug then Fmt.epr "%d: resumed@." i; total := !total + v ) with | None -> () (* Already resumed *) | Some request -> if Cqs.cancel request then ( if debug then Fmt.epr "%d: cancelled@." i; total := !total + 1 ) ); done; Atomic.final (fun () -> if debug then ( Format.eprintf "%a@." Cqs.dump t; Format.eprintf "total=%d, expected_total=%d\n%!" !total expected_total; ); Cqs.Cells.validate t; assert (!total = expected_total); (* Printf.printf "total = %d\n%!" !total *) ) (* An even simpler cell type with no payload. Just for testing removing whole cancelled segments. *) module Unit_cells(Config : sig val segment_order : int end) = struct module Cell = struct type _ t = | Empty (* A consumer is intending to collect a value in the future *) | Value (* A value is waiting for its consumer *) | Cancelled (* The consumer cancelled *) let init = Empty let segment_order = Config.segment_order let dump f = function | Empty -> Fmt.string f "Empty" | Value -> Fmt.string f "Value" | Cancelled -> Fmt.string f "Cancelled" end module Cells = Cells.Make(Cell) type request = unit Cells.segment * unit Cell.t Atomic.t let cancel (segment, cell) = if Atomic.compare_and_set cell Cell.Empty Cancelled then ( Cells.cancel_cell segment; true ) else false (* Already at [Value]; cancellation fails. *) (* Provide a value. Returns [false] if already [Cancelled]. *) let resume t = let cell = Cells.next_resume t in Atomic.compare_and_set cell Empty Value (* We reuse the [Empty] state to mean [Waiting]. *) let suspend t : request = Cells.next_suspend t let resume_all t = Cells.resume_all t let make = Cells.make let dump f t = Atomic.check (fun () -> Cells.dump f t; true) let validate t = Atomic.check (fun () -> Cells.validate t; true) end (* A producer writes [n_items] to the queue (retrying if the cell gets cancelled first). A consumer reads [n_items] from the queue (cancelling and retrying once if it can). At the end, the consumer and resumer are at the same position. This tests what happens if a whole segment gets cancelled and the producer therefore skips it. [test_cells] is too slow to test this. *) let test_skip_segments ~segment_order ~n_items () = let module Cells = Unit_cells(struct let segment_order = segment_order end) in if debug then print_endline "== start =="; let t = Cells.make () in Atomic.spawn (fun () -> for _ = 1 to n_items do let rec loop ~may_cancel = if debug then print_endline "suspend"; let request = Cells.suspend t in if may_cancel && Cells.cancel request then ( if debug then print_endline "cancelled"; loop ~may_cancel:false ) in loop ~may_cancel:true done ); Atomic.spawn (fun () -> for _ = 1 to n_items do if debug then print_endline "resume"; while not (Cells.resume t) do () done done ); Atomic.final (fun () -> if debug then Fmt.pr "%a@." Cells.dump t; Cells.Cells.validate t; assert (Cells.Cells.Position.index t.suspend = Cells.Cells.Position.index t.resume); ) (* Create a list of [n_internal + 2] segments and cancel all the internal ones. Ensure the list is valid afterwards. This is simpler than [test_skip_segments], so we can test longer sequences of cancellations. *) let test_cancel_only ~n_internal () = let module Cells = Unit_cells(struct let segment_order = 0 end) in let t = Cells.make () in ignore (Cells.suspend t : Cells.request); let internals = Array.init n_internal (fun _ -> Cells.suspend t) in ignore (Cells.suspend t : Cells.request); let in_progress = ref 0 in for i = 0 to n_internal - 1 do Atomic.spawn (fun () -> incr in_progress; assert (Cells.cancel internals.(i)); decr in_progress; if !in_progress = 0 then Cells.validate t ) done; Atomic.final (fun () -> assert (Cells.resume t); assert (Cells.resume t); if debug then Fmt.pr "%a@." Cells.dump t; Cells.validate t; assert (Cells.Cells.Position.index t.suspend = Cells.Cells.Position.index t.resume); ) (* Create [n] requests. Then try to cancel them in parallel with doing a resume_all. Check the number of resumed requests is plausible (at least as many as there were requests that hadn't started cancelling, and no more than those that hadn't finished cancelling. *) let test_broadcast ~segment_order ~n () = let messages = ref [] in let log fmt = (fmt ^^ "@.") |> Format.kasprintf @@ fun msg -> messages := msg :: !messages in if debug then log "== start =="; let module Cells = Unit_cells(struct let segment_order = segment_order end) in let t = Cells.make () in let requests = Array.init n (fun _ -> Cells.suspend t) in let min_requests = Atomic.make n in let max_requests = Atomic.make n in for i = 0 to n - 1 do Atomic.spawn (fun () -> Atomic.decr min_requests; if debug then log "Cancelling request"; if Cells.cancel requests.(i) then ( Atomic.decr max_requests; if debug then log "Cancelled request"; ) ) done; Atomic.spawn (fun () -> if debug then log "Broadcasting"; let max_expected = Atomic.get max_requests in let wakes = ref 0 in Cells.resume_all t (fun cell -> match Atomic.get cell with | Empty -> incr wakes | Cancelled -> () | Value -> assert false ); let min_expected = Atomic.get min_requests in let wakes = !wakes in if debug then log "Broadcast done: wakes=%d (expected=%d-%d)" wakes min_expected max_expected; assert (min_expected <= wakes && wakes <= max_expected) ); Atomic.final (fun () -> if debug then ( List.iter print_string (List.rev !messages) ) ) (* These tests take about 10s on my machine, with https://github.com/ocaml-multicore/dscheck/pull/3 However, that PR is not reliable at finding all interleavings. *) let () = print_endline "Test broadcast:"; Atomic.trace (test_broadcast ~segment_order:1 ~n:3); print_endline "Test cancelling segments:"; Atomic.trace (test_cancel_only ~n_internal:3); print_endline "Test cancelling segments while suspending and resuming:"; Atomic.trace (test_skip_segments ~segment_order:1 ~n_items:3); print_endline "Test with 1 cell per segment:"; Atomic.trace (test_cells ~segment_order:0 ~n_values:2); print_endline "Test with 2 cells per segment:"; Atomic.trace (test_cells ~segment_order:1 ~n_values:2)
check_basic.ml
(* Check that v of type [typ] matches with itself *) let id_case typ typ_str v1 v2 = Alcotest.test_case typ_str `Quick (fun () -> Alcotest.check typ typ_str v1 v2) let () = let open Alcotest in run ~verbose:true __FILE__ [ ( "different basic", [ id_case bool "bool" true false; id_case int "int" 1 2; id_case int32 "int32" Int32.max_int Int32.min_int; id_case int64 "int64" Int64.max_int Int64.min_int; id_case (float 0.0) "float" 1.0 2.0; id_case char "char" 'a' 'b'; id_case string "string" "Lorem ipsum" "dolor sit amet."; id_case bytes "bytes" (Bytes.of_string "\x01\x02\x03") (Bytes.of_string "\x01\x00\x03"); ] ); ( "different composite", [ id_case (list char) "list" [ 'a'; 'b' ] [ 'a'; 'c' ]; id_case (array int64) "array" Int64.[| zero; max_int |] Int64.[| zero; one; max_int |]; id_case (option int) "option some" (Some 1) (Some 2); id_case (result int unit) "result" (Ok 1) (Error ()); id_case (pair int char) "pair" (1, 'a') (1, 'b'); id_case (triple int bool string) "triple" (1, true, "a") (1, false, "a"); ] ); ]
(* Check that v of type [typ] matches with itself *) let id_case typ typ_str v1 v2 =
dune
(rule (alias extract-examples) (deps lib/version.sh lib/skdoc.sh lib/skdoc.py) (action (run bash lib/skdoc.sh examples))) ;; XXX Running once works, but running a second time does nothing and ;; erases the output of the first run in _build/default/html_doc. ;; (rule ;; (alias mkdocs) ;; (deps lib/version.sh lib/skdoc.sh lib/skdoc.py lib/ndarray.mli ;; lib/version.mli lib/PyList.mli mkdocs.yml README.md) ;; (action ;; (progn ;; (run bash lib/skdoc.sh doc) ;; (run lib/replace-variables.sh README.md doc/README.md) ;; (with-stdin-from lib/ndarray.mli (with-stdout-to ndarray.md (run lib/mli2md))) ;; (with-stdin-from lib/PyList.mli (with-stdout-to PyList.md (run lib/mli2md))) ;; (with-stdin-from lib/version.mli (with-stdout-to version.md (run lib/mli2md))) ;; (run cp ndarray.md version.md doc/) ;; (run mkdocs build)) ;; ))
frozen_deposits_storage.mli
val init : Raw_context.t -> Signature.Public_key_hash.t -> Raw_context.t tzresult Lwt.t val allocated : Raw_context.t -> Contract_repr.t -> bool Lwt.t val get : Raw_context.t -> Contract_repr.t -> Storage.deposits tzresult Lwt.t val find : Raw_context.t -> Contract_repr.t -> Storage.deposits option tzresult Lwt.t val credit_only_call_from_token : Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t val spend_only_call_from_token : Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t val update_deposits_cap : Raw_context.t -> Contract_repr.t -> Tez_repr.t -> (Raw_context.t * Tez_repr.t) tzresult Lwt.t
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
vote_storage.ml
let recorded_proposal_count_for_delegate ctxt proposer = Storage.Vote.Proposals_count.get_option ctxt proposer >>=? function | None -> return 0 | Some count -> return count let record_proposal ctxt proposal proposer = recorded_proposal_count_for_delegate ctxt proposer >>=? fun count -> Storage.Vote.Proposals_count.init_set ctxt proposer (count + 1) >>= fun ctxt -> Storage.Vote.Proposals.add ctxt (proposal, proposer) >>= fun ctxt -> return ctxt let get_proposals ctxt = Storage.Vote.Proposals.fold ctxt ~init:(ok Protocol_hash.Map.empty) ~f:(fun (proposal, delegate) acc -> (* Assuming the same listings is used at votings *) Storage.Vote.Listings.get ctxt delegate >>=? fun weight -> Lwt.return begin acc >>? fun acc -> let previous = match Protocol_hash.Map.find_opt proposal acc with | None -> 0l | Some x -> x in ok (Protocol_hash.Map.add proposal (Int32.add weight previous) acc) end) let clear_proposals ctxt = Storage.Vote.Proposals_count.clear ctxt >>= fun ctxt -> Storage.Vote.Proposals.clear ctxt type ballots = { yay: int32 ; nay: int32 ; pass: int32 ; } let ballots_encoding = let open Data_encoding in conv (fun { yay ; nay ; pass } -> ( yay , nay , pass )) (fun ( yay , nay , pass ) -> { yay ; nay ; pass }) @@ obj3 (req "yay" int32) (req "nay" int32) (req "pass" int32) let has_recorded_ballot = Storage.Vote.Ballots.mem let record_ballot = Storage.Vote.Ballots.init let get_ballots ctxt = Storage.Vote.Ballots.fold ctxt ~f:(fun delegate ballot (ballots: ballots tzresult) -> (* Assuming the same listings is used at votings *) Storage.Vote.Listings.get ctxt delegate >>=? fun weight -> let count = Int32.add weight in Lwt.return begin ballots >>? fun ballots -> match ballot with | Yay -> ok { ballots with yay = count ballots.yay } | Nay -> ok { ballots with nay = count ballots.nay } | Pass -> ok { ballots with pass = count ballots.pass } end) ~init:(ok { yay = 0l ; nay = 0l; pass = 0l }) let get_ballot_list = Storage.Vote.Ballots.bindings let clear_ballots = Storage.Vote.Ballots.clear let listings_encoding = Data_encoding.(list (obj2 (req "pkh" Signature.Public_key_hash.encoding) (req "rolls" int32))) let freeze_listings ctxt = Roll_storage.fold ctxt (ctxt, 0l) ~f:(fun _roll delegate (ctxt, total) -> (* TODO use snapshots *) let delegate = Signature.Public_key.hash delegate in begin Storage.Vote.Listings.get_option ctxt delegate >>=? function | None -> return 0l | Some count -> return count end >>=? fun count -> Storage.Vote.Listings.init_set ctxt delegate (Int32.succ count) >>= fun ctxt -> return (ctxt, Int32.succ total)) >>=? fun (ctxt, total) -> Storage.Vote.Listings_size.init ctxt total >>=? fun ctxt -> return ctxt let listing_size = Storage.Vote.Listings_size.get let in_listings = Storage.Vote.Listings.mem let get_listings = Storage.Vote.Listings.bindings let clear_listings ctxt = Storage.Vote.Listings.clear ctxt >>= fun ctxt -> Storage.Vote.Listings_size.remove ctxt >>= fun ctxt -> return ctxt let get_current_period_kind = Storage.Vote.Current_period_kind.get let set_current_period_kind = Storage.Vote.Current_period_kind.set let get_current_quorum = Storage.Vote.Current_quorum.get let set_current_quorum = Storage.Vote.Current_quorum.set let get_current_proposal = Storage.Vote.Current_proposal.get let init_current_proposal = Storage.Vote.Current_proposal.init let clear_current_proposal = Storage.Vote.Current_proposal.delete let init ctxt = Storage.Vote.Current_quorum.init ctxt 80_00l >>=? fun ctxt -> Storage.Vote.Current_period_kind.init ctxt Proposal >>=? fun ctxt -> return ctxt
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
clb_pdarrays.h
#ifndef CLB_PDARRAYS #define CLB_PDARRAYS #include <clb_memory.h> /*---------------------------------------------------------------------*/ /* Data type declarations */ /*---------------------------------------------------------------------*/ typedef struct pdarraycell { bool integer; long size; long grow; IntOrP *array; }PDArrayCell, *PDArray_p; #define GROW_EXPONENTIAL 0 /*---------------------------------------------------------------------*/ /* Exported Functions and Variables */ /*---------------------------------------------------------------------*/ #define PDArrayCellAlloc() (PDArrayCell*)SizeMalloc(sizeof(PDArrayCell)) #define PDArrayCellFree(junk) SizeFree(junk, sizeof(PDArrayCell)) #ifdef CONSTANT_MEM_ESTIMATE #define PDARRAYCELL_MEM 20 #else #define PDARRAYCELL_MEM MEMSIZE(PDArrayCell) #endif #define PDArrayStorage(arr) (PDARRAYCELL_MEM+INTORP_MEM+((arr)->size*INTORP_MEM)) PDArray_p PDArrayAlloc(long init_size, long grow); PDArray_p PDIntArrayAlloc(long init_size, long grow); void PDArrayFree(PDArray_p junk); #define PDArraySize(array) ((array)->size) PDArray_p PDArrayCopy(PDArray_p array); void PDArrayEnlarge(PDArray_p array, long idx); static inline IntOrP* PDArrayElementRef(PDArray_p array, long idx); void PDArrayElementDeleteP(PDArray_p array, long idx); void PDArrayElementDeleteInt(PDArray_p array, long idx); #define PDArrayElementClear(arr, idx) ((arr)->array[(idx)].p_val = NULL) #define PDArrayAssign(array, idx, value) \ *PDArrayElementRef((array), (idx)) = (value) #define PDArrayAssignP(array, idx, value) \ PDArrayElementRef((array), (idx))->p_val = (value) #define PDArrayAssignInt(array, idx, value) \ PDArrayElementRef((array), (idx))->i_val = (value) #define PDArrayElement(array, idx) \ *PDArrayElementRef((array), (idx)) #define PDArrayElementP(array, idx) \ (PDArrayElementRef((array), (idx))->p_val) #define PDArrayElementInt(array, idx) \ (PDArrayElementRef((array), (idx))->i_val) long PDArrayMembers(PDArray_p array); long PDArrayFirstUnused(PDArray_p array); long PDArrayStore(PDArray_p array, IntOrP value); long PDArrayStoreP(PDArray_p array, void* value); long PDArrayStoreInt(PDArray_p array, long value); void PDArrayAdd(PDArray_p collect, PDArray_p data, long limit); long PDArrayElementIncInt(PDArray_p array, long idx, long value); /*---------------------------------------------------------------------*/ /* Inline functions */ /*---------------------------------------------------------------------*/ /*----------------------------------------------------------------------- // // Function: PDArrayElementRef() // // Return a reference to an element in a dynamic array. This // reference is only good until the next call to this function! User // programs are expected to use this function only extremely rarely // and with special care. Use PDArrayElement()/PDArrayAssign() // instead. // // Global Variables: - // // Side Effects : May enlarge and move array. // /----------------------------------------------------------------------*/ static inline IntOrP* PDArrayElementRef(PDArray_p array, long idx) { assert(array); assert(idx >= 0); if(UNLIKELY(idx >= array->size)) { PDArrayEnlarge(array, idx); } return &(array->array[idx]); } #endif /*---------------------------------------------------------------------*/ /* End of File */ /*---------------------------------------------------------------------*/
/*----------------------------------------------------------------------- File : clb_pdarrays.h Author: Stephan Schulz Contents Dynamic arrays of pointers and long integers. You can define the growth behaviour by specifying a value. If it is GROW_EXPONENTIAL, arrays will always grow by a factor that is the lowest power of two that will make the array big enough. Otherwise it will grow by the smallest multiple of the value specified that creates the requested position. Copyright 1998, 1999, 2004 by the author. This code is released under the GNU General Public Licence and the GNU Lesser General Public License. See the file COPYING in the main E directory for details.. Run "eprover -h" for contact information. Changes Created: Wed Jul 22 21:34:41 MET DST 1998 -----------------------------------------------------------------------*/
fread_pretty.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <gmp.h> #include "flint.h" #include "fmpz.h" #include "fmpz_poly.h" static __inline__ int is_varsymbol0(char c) { return isalpha((unsigned char) c); } static __inline__ int is_varsymbol1(char c) { return isalnum((unsigned char) c) || (c == '_'); } #define next_event() \ do { \ c = fgetc(file); \ if (c == EOF && !feof(file)) \ goto s_ioe; \ ++r; \ if (i == N) \ { \ buf = flint_realloc(buf, N = 2*N); \ } \ buf[i++] = c; \ } while (0) #define add_coeff() \ do { \ fmpz_set_mpz(f_coeff, z_coeff); \ fmpz_poly_fit_length(poly, exp + 1); \ fmpz_add(poly->coeffs + exp, poly->coeffs + exp, f_coeff); \ if (poly->length < exp + 1) \ poly->length = exp + 1; \ } while (0) int fmpz_poly_fread_pretty(FILE *file, fmpz_poly_t poly, char **x) { /* var - variable name buf - buffer of size N, at write position i, with c == buf[i-1] z_coeff - mpz_t for the coefficient, f_coeff is the fmpz_t version z_exp - mpz_t for the exponent, exp is the slong version r - return value */ char *var = NULL; char c, *buf; int i, N; fmpz_t f_coeff; mpz_t z_coeff, z_exp; slong exp; int r = 0; fmpz_poly_zero(poly); if (poly->alloc) flint_mpn_zero((mp_ptr) poly->coeffs, poly->alloc); i = 0; N = 80; buf = flint_malloc(N); fmpz_init(f_coeff); mpz_init(z_coeff); mpz_init(z_exp); /* s_0 : */ next_event(); if (c == '-') goto s_1; if (isdigit((unsigned char) c)) goto s_2; if (is_varsymbol0(c)) { flint_mpz_set_si(z_coeff, 1); goto s_3; } goto s_parse_error; s_1 : next_event(); if (isdigit((unsigned char) c)) goto s_2; if (is_varsymbol0(c)) { if (i == 1) flint_mpz_set_si(z_coeff, 1); else /* i == 2 */ { flint_mpz_set_si(z_coeff, -1); buf[0] = c; i = 1; } goto s_3; } goto s_parse_error; s_2 : next_event(); if (isdigit((unsigned char) c)) goto s_2; if (c == '*') { buf[i-1] = '\0'; mpz_set_str(z_coeff, buf, 10); i = 0; goto s_4; } { buf[i-1] = '\0'; mpz_set_str(z_coeff, buf, 10); exp = 0; add_coeff(); if (c == '+' || c == '-') { i = 0; if (c == '-') buf[i++] = '-'; goto s_1; } else goto s_end; } s_3 : next_event(); if (is_varsymbol1(c)) goto s_3; { buf[i-1] = '\0'; if (var) { if (strcmp(buf, var)) /* Parse error */ goto s_parse_error; } else { var = flint_malloc(i); strcpy(var, buf); } if (c == '^') { i = 0; goto s_5; } else if (c == '+' || c == '-') { exp = 1; add_coeff(); i = 0; if (c == '-') buf[i++] = '-'; goto s_1; } else { exp = 1; add_coeff(); goto s_end; } } s_4 : next_event(); if (is_varsymbol0(c)) goto s_3; goto s_parse_error; s_5 : next_event(); if (isdigit((unsigned char) c)) goto s_6; goto s_parse_error; s_6 : next_event(); if (isdigit((unsigned char) c)) goto s_6; { buf[i-1] = '\0'; mpz_set_str(z_exp, buf, 10); if (!mpz_fits_slong_p(z_exp)) { goto s_parse_error; } exp = flint_mpz_get_si(z_exp); add_coeff(); if (c == '+' || c == '-') { i = 0; if (c == '-') buf[i++] = '-'; goto s_1; } else goto s_end; } s_parse_error : r = -2; goto s_end; s_ioe : r = -1; goto s_end; s_end : _fmpz_poly_normalise(poly); if (var) *x = var; else { *x = flint_malloc(1); **x = '\0'; } fmpz_clear(f_coeff); mpz_clear(z_coeff); mpz_clear(z_exp); flint_free(buf); return r; } #undef next_event #undef add_coeff
/* Copyright (C) 2010 Sebastian Pancratz 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/>. */
console_unix.ml
open Lwt.Infix (* TODO everything connects to the same console for now *) (* TODO management service for logging *) type t = { id: string; read_buffer: Cstruct.t; mutable closed: bool; } type 'a io = 'a Lwt.t type buffer = Cstruct.t type error let pp_error ppf _ = Fmt.string ppf "Console.error" type write_error = Mirage_flow.write_error let pp_write_error = Mirage_flow.pp_write_error let connect id = let read_buffer = Cstruct.create 1024 in let closed = false in let t = { id; read_buffer; closed } in Lwt.return t let disconnect _t = Lwt.return_unit let read t = Lwt_bytes.read Lwt_unix.stdin t.read_buffer.Cstruct.buffer 0 (Cstruct.len t.read_buffer) >|= fun n -> if n = 0 || t.closed then (Ok `Eof) else Ok (`Data (Cstruct.sub t.read_buffer 0 n)) let write_one buf = Lwt_cstruct.complete (fun frag -> let open Cstruct in Lwt_bytes.write Lwt_unix.stdout frag.buffer frag.off frag.len ) buf let write t buf = if t.closed then Lwt.return (Error `Closed) else write_one buf >|= fun () -> Ok () let writev t bufs = if t.closed then Lwt.return (Error `Closed) else Lwt_list.iter_s write_one bufs >|= fun () -> Ok () let close t = t.closed <- true; Lwt.return () let log t s = if t.closed then Lwt.return_unit else write_one (Cstruct.of_string (s ^ "\n"))
(* * Copyright (c) 2010-2013 Anil Madhavapeddy <anil@recoil.org> * * 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. *)
posix_types_stubs.c
#include "ctypes_primitives.h" #define _XOPEN_SOURCE 500 #include <caml/mlvalues.h> #include <assert.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> #if (!defined _WIN32 || defined __CYGWIN__) && !defined MINIOS #include <pthread.h> #endif #include <time.h> #include <stdint.h> #define EXPOSE_TYPEINFO_COMMON(TYPENAME,STYPENAME) \ value ctypes_typeof_ ## TYPENAME(value unit) \ { \ enum ctypes_arithmetic_type underlying = \ CTYPES_CLASSIFY_ARITHMETIC_TYPE(STYPENAME); \ return Val_int(underlying); \ } #define EXPOSE_ALIGNMENT_COMMON(TYPENAME,STYPENAME) \ value ctypes_alignmentof_ ## TYPENAME(value unit) \ { \ struct s { char c; STYPENAME t; }; \ return Val_int(offsetof(struct s, t)); \ } #define EXPOSE_TYPESIZE_COMMON(TYPENAME,STYPENAME) \ value ctypes_sizeof_ ## TYPENAME(value unit) \ { \ return Val_int(sizeof(STYPENAME)); \ } #if !defined _WIN32 || defined __CYGWIN__ #define UNDERSCORE(X) X #else #define UNDERSCORE(X) _## X #endif #define EXPOSE_TYPEINFO(X) EXPOSE_TYPEINFO_COMMON(X, X) #define EXPOSE_TYPEINFO_S(X) EXPOSE_TYPEINFO_COMMON(X, UNDERSCORE(X)) #define EXPOSE_TYPESIZE(X) EXPOSE_TYPESIZE_COMMON(X, X) #define EXPOSE_TYPESIZE_S(X) EXPOSE_TYPESIZE_COMMON(X, UNDERSCORE(X)) #define EXPOSE_ALIGNMENT(X) EXPOSE_ALIGNMENT_COMMON(X, X) #define EXPOSE_ALIGNMENT_S(X) EXPOSE_ALIGNMENT_COMMON(X, UNDERSCORE(X)) #ifdef __NetBSD__ /* NetBSD defines these types as macros, which expands to the wrong thing * in the EXPOSE_* macros above. I have no idea how to prevent cpp from * expanding macro arguments, so just hack around it for now. */ #undef off_t #undef mode_t #undef pid_t typedef __off_t off_t; typedef __mode_t mode_t; typedef __pid_t pid_t; #endif EXPOSE_TYPEINFO(clock_t) EXPOSE_TYPEINFO_S(dev_t) EXPOSE_TYPEINFO_S(ino_t) EXPOSE_TYPEINFO_S(mode_t) EXPOSE_TYPEINFO_S(off_t) EXPOSE_TYPEINFO_S(pid_t) EXPOSE_TYPEINFO(ssize_t) EXPOSE_TYPEINFO(time_t) EXPOSE_TYPEINFO(useconds_t) #if !defined _WIN32 || defined __CYGWIN__ EXPOSE_TYPEINFO(nlink_t) #else /* the mingw port of fts uses an int for nlink_t */ EXPOSE_TYPEINFO_COMMON(nlink_t, int) #endif EXPOSE_TYPESIZE_S(sigset_t) EXPOSE_ALIGNMENT_S(sigset_t)
/* * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. */
format.mli
val open_box : int -> unit val close_box : unit -> unit val print_string : string -> unit val print_as : int -> string -> unit val print_int : int -> unit val print_float : float -> unit val print_char : char -> unit val print_bool : bool -> unit val print_space : unit -> unit val print_cut : unit -> unit val print_break : int -> int -> unit val print_flush : unit -> unit val print_newline : unit -> unit val force_newline : unit -> unit val print_if_newline : unit -> unit val set_margin : int -> unit val get_margin : unit -> int val set_max_indent : int -> unit val get_max_indent : unit -> int val set_max_boxes : int -> unit val get_max_boxes : unit -> int val over_max_boxes : unit -> bool val open_hbox : unit -> unit val open_vbox : int -> unit val open_hvbox : int -> unit val open_hovbox : int -> unit val open_tbox : unit -> unit val close_tbox : unit -> unit val print_tbreak : int -> int -> unit val set_tab : unit -> unit val print_tab : unit -> unit val set_ellipsis_text : string -> unit val get_ellipsis_text : unit -> string type tag = string val open_tag : tag -> unit val close_tag : unit -> unit val set_tags : bool -> unit val set_print_tags : bool -> unit val set_mark_tags : bool -> unit val get_print_tags : unit -> bool val get_mark_tags : unit -> bool val set_formatter_out_channel : out_channel -> unit val set_formatter_output_functions : (string -> int -> int -> unit) -> (unit -> unit) -> unit val get_formatter_output_functions : unit -> ((string -> int -> int -> unit) * (unit -> unit)) type formatter_out_functions = { out_string: string -> int -> int -> unit ; out_flush: unit -> unit ; out_newline: unit -> unit ; out_spaces: int -> unit } val set_formatter_out_functions : formatter_out_functions -> unit val get_formatter_out_functions : unit -> formatter_out_functions type formatter_tag_functions = { mark_open_tag: tag -> string ; mark_close_tag: tag -> string ; print_open_tag: tag -> unit ; print_close_tag: tag -> unit } val set_formatter_tag_functions : formatter_tag_functions -> unit val get_formatter_tag_functions : unit -> formatter_tag_functions type formatter val formatter_of_out_channel : out_channel -> formatter val std_formatter : formatter val err_formatter : formatter val formatter_of_buffer : Buffer.t -> formatter val stdbuf : Buffer.t val str_formatter : formatter val flush_str_formatter : unit -> string val make_formatter : (string -> int -> int -> unit) -> (unit -> unit) -> formatter val pp_open_hbox : formatter -> unit -> unit val pp_open_vbox : formatter -> int -> unit val pp_open_hvbox : formatter -> int -> unit val pp_open_hovbox : formatter -> int -> unit val pp_open_box : formatter -> int -> unit val pp_close_box : formatter -> unit -> unit val pp_open_tag : formatter -> string -> unit val pp_close_tag : formatter -> unit -> unit val pp_print_string : formatter -> string -> unit val pp_print_as : formatter -> int -> string -> unit val pp_print_int : formatter -> int -> unit val pp_print_float : formatter -> float -> unit val pp_print_char : formatter -> char -> unit val pp_print_bool : formatter -> bool -> unit val pp_print_break : formatter -> int -> int -> unit val pp_print_cut : formatter -> unit -> unit val pp_print_space : formatter -> unit -> unit val pp_force_newline : formatter -> unit -> unit val pp_print_flush : formatter -> unit -> unit val pp_print_newline : formatter -> unit -> unit val pp_print_if_newline : formatter -> unit -> unit val pp_open_tbox : formatter -> unit -> unit val pp_close_tbox : formatter -> unit -> unit val pp_print_tbreak : formatter -> int -> int -> unit val pp_set_tab : formatter -> unit -> unit val pp_print_tab : formatter -> unit -> unit val pp_set_tags : formatter -> bool -> unit val pp_set_print_tags : formatter -> bool -> unit val pp_set_mark_tags : formatter -> bool -> unit val pp_get_print_tags : formatter -> unit -> bool val pp_get_mark_tags : formatter -> unit -> bool val pp_set_margin : formatter -> int -> unit val pp_get_margin : formatter -> unit -> int val pp_set_max_indent : formatter -> int -> unit val pp_get_max_indent : formatter -> unit -> int val pp_set_max_boxes : formatter -> int -> unit val pp_get_max_boxes : formatter -> unit -> int val pp_over_max_boxes : formatter -> unit -> bool val pp_set_ellipsis_text : formatter -> string -> unit val pp_get_ellipsis_text : formatter -> unit -> string val pp_set_formatter_out_channel : formatter -> out_channel -> unit val pp_set_formatter_output_functions : formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit val pp_get_formatter_output_functions : formatter -> unit -> ((string -> int -> int -> unit) * (unit -> unit)) val pp_set_formatter_tag_functions : formatter -> formatter_tag_functions -> unit val pp_get_formatter_tag_functions : formatter -> unit -> formatter_tag_functions val pp_set_formatter_out_functions : formatter -> formatter_out_functions -> unit val pp_get_formatter_out_functions : formatter -> unit -> formatter_out_functions val pp_print_list : ?pp_sep:(formatter -> unit -> unit) -> (formatter -> 'a -> unit) -> formatter -> 'a list -> unit val pp_print_text : formatter -> string -> unit val fprintf : formatter -> ('a, formatter, unit) format -> 'a val printf : ('a, formatter, unit) format -> 'a val eprintf : ('a, formatter, unit) format -> 'a val sprintf : ('a, unit, string) format -> 'a val asprintf : ('a, formatter, unit, string) format4 -> 'a val ifprintf : formatter -> ('a, formatter, unit) format -> 'a val kfprintf : (formatter -> 'a) -> formatter -> ('b, formatter, unit, 'a) format4 -> 'b val ikfprintf : (formatter -> 'a) -> formatter -> ('b, formatter, unit, 'a) format4 -> 'b val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a[@@ocaml.deprecated "- : Buffer.t -> ('a, Format.formatter, unit) format -> 'a = <fun>"] val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b[@@ocaml.deprecated "Use Format.ksprintf instead."] val set_all_formatter_output_functions : out:(string -> int -> int -> unit) -> flush:(unit -> unit) -> newline:(unit -> unit) -> spaces:(int -> unit) -> unit[@@ocaml.deprecated "Use Format.set_formatter_out_functions instead."] val get_all_formatter_output_functions : unit -> ((string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) * (int -> unit))[@@ocaml.deprecated "Use Format.get_formatter_out_functions instead."] val pp_set_all_formatter_output_functions : formatter -> out:(string -> int -> int -> unit) -> flush:(unit -> unit) -> newline:(unit -> unit) -> spaces:(int -> unit) -> unit[@@ocaml.deprecated "Use Format.pp_set_formatter_out_functions instead."] val pp_get_all_formatter_output_functions : formatter -> unit -> ((string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) * (int -> unit))[@@ocaml.deprecated "Use Format.pp_get_formatter_out_functions instead."]
wasm-binary.h
// // Parses and emits WebAssembly binary code // #ifndef wasm_wasm_binary_h #define wasm_wasm_binary_h #include <cassert> #include <ostream> #include <type_traits> #include "ir/import-utils.h" #include "ir/module-utils.h" #include "parsing.h" #include "support/debug.h" #include "wasm-builder.h" #include "wasm-traversal.h" #include "wasm-validator.h" #include "wasm.h" #define DEBUG_TYPE "binary" namespace wasm { enum { // the maximum amount of bytes we emit per LEB MaxLEB32Bytes = 5, }; // wasm VMs on the web have decided to impose some limits on what they // accept enum WebLimitations : uint32_t { MaxDataSegments = 100 * 1000, MaxFunctionBodySize = 128 * 1024, MaxFunctionLocals = 50 * 1000, MaxFunctionParams = 1000 }; template<typename T, typename MiniT> struct LEB { static_assert(sizeof(MiniT) == 1, "MiniT must be a byte"); T value; LEB() = default; LEB(T value) : value(value) {} bool hasMore(T temp, MiniT byte) { // for signed, we must ensure the last bit has the right sign, as it will // zero extend return std::is_signed<T>::value ? (temp != 0 && temp != T(-1)) || (value >= 0 && (byte & 64)) || (value < 0 && !(byte & 64)) : (temp != 0); } void write(std::vector<uint8_t>* out) { T temp = value; bool more; do { uint8_t byte = temp & 127; temp >>= 7; more = hasMore(temp, byte); if (more) { byte = byte | 128; } out->push_back(byte); } while (more); } // @minimum: a minimum number of bytes to write, padding as necessary // returns the number of bytes written size_t writeAt(std::vector<uint8_t>* out, size_t at, size_t minimum = 0) { T temp = value; size_t offset = 0; bool more; do { uint8_t byte = temp & 127; temp >>= 7; more = hasMore(temp, byte) || offset + 1 < minimum; if (more) { byte = byte | 128; } (*out)[at + offset] = byte; offset++; } while (more); return offset; } LEB<T, MiniT>& read(std::function<MiniT()> get) { value = 0; T shift = 0; MiniT byte; while (1) { byte = get(); bool last = !(byte & 128); T payload = byte & 127; using mask_type = typename std::make_unsigned<T>::type; auto shift_mask = 0 == shift ? ~mask_type(0) : ((mask_type(1) << (sizeof(T) * 8 - shift)) - 1u); T significant_payload = payload & shift_mask; if (significant_payload != payload) { if (!(std::is_signed<T>::value && last)) { throw ParseException("LEB dropped bits only valid for signed LEB"); } } value |= significant_payload << shift; if (last) { break; } shift += 7; if (size_t(shift) >= sizeof(T) * 8) { throw ParseException("LEB overflow"); } } // If signed LEB, then we might need to sign-extend. (compile should // optimize this out if not needed). if (std::is_signed<T>::value) { shift += 7; if ((byte & 64) && size_t(shift) < 8 * sizeof(T)) { size_t sext_bits = 8 * sizeof(T) - size_t(shift); value <<= sext_bits; value >>= sext_bits; if (value >= 0) { throw ParseException( " LEBsign-extend should produce a negative value"); } } } return *this; } }; using U32LEB = LEB<uint32_t, uint8_t>; using U64LEB = LEB<uint64_t, uint8_t>; using S32LEB = LEB<int32_t, int8_t>; using S64LEB = LEB<int64_t, int8_t>; // // We mostly stream into a buffer as we create the binary format, however, // sometimes we need to backtrack and write to a location behind us - wasm // is optimized for reading, not writing. // class BufferWithRandomAccess : public std::vector<uint8_t> { public: BufferWithRandomAccess() = default; BufferWithRandomAccess& operator<<(int8_t x) { BYN_TRACE("writeInt8: " << (int)(uint8_t)x << " (at " << size() << ")\n"); push_back(x); return *this; } BufferWithRandomAccess& operator<<(int16_t x) { BYN_TRACE("writeInt16: " << x << " (at " << size() << ")\n"); push_back(x & 0xff); push_back(x >> 8); return *this; } BufferWithRandomAccess& operator<<(int32_t x) { BYN_TRACE("writeInt32: " << x << " (at " << size() << ")\n"); push_back(x & 0xff); x >>= 8; push_back(x & 0xff); x >>= 8; push_back(x & 0xff); x >>= 8; push_back(x & 0xff); return *this; } BufferWithRandomAccess& operator<<(int64_t x) { BYN_TRACE("writeInt64: " << x << " (at " << size() << ")\n"); push_back(x & 0xff); x >>= 8; push_back(x & 0xff); x >>= 8; push_back(x & 0xff); x >>= 8; push_back(x & 0xff); x >>= 8; push_back(x & 0xff); x >>= 8; push_back(x & 0xff); x >>= 8; push_back(x & 0xff); x >>= 8; push_back(x & 0xff); return *this; } BufferWithRandomAccess& operator<<(U32LEB x) { size_t before = -1; WASM_UNUSED(before); BYN_DEBUG(before = size(); std::cerr << "writeU32LEB: " << x.value << " (at " << before << ")" << std::endl;); x.write(this); BYN_DEBUG(for (size_t i = before; i < size(); i++) { std::cerr << " " << (int)at(i) << " (at " << i << ")\n"; }); return *this; } BufferWithRandomAccess& operator<<(U64LEB x) { size_t before = -1; WASM_UNUSED(before); BYN_DEBUG(before = size(); std::cerr << "writeU64LEB: " << x.value << " (at " << before << ")" << std::endl;); x.write(this); BYN_DEBUG(for (size_t i = before; i < size(); i++) { std::cerr << " " << (int)at(i) << " (at " << i << ")\n"; }); return *this; } BufferWithRandomAccess& operator<<(S32LEB x) { size_t before = -1; WASM_UNUSED(before); BYN_DEBUG(before = size(); std::cerr << "writeS32LEB: " << x.value << " (at " << before << ")" << std::endl;); x.write(this); BYN_DEBUG(for (size_t i = before; i < size(); i++) { std::cerr << " " << (int)at(i) << " (at " << i << ")\n"; }); return *this; } BufferWithRandomAccess& operator<<(S64LEB x) { size_t before = -1; WASM_UNUSED(before); BYN_DEBUG(before = size(); std::cerr << "writeS64LEB: " << x.value << " (at " << before << ")" << std::endl;); x.write(this); BYN_DEBUG(for (size_t i = before; i < size(); i++) { std::cerr << " " << (int)at(i) << " (at " << i << ")\n"; }); return *this; } BufferWithRandomAccess& operator<<(uint8_t x) { return *this << (int8_t)x; } BufferWithRandomAccess& operator<<(uint16_t x) { return *this << (int16_t)x; } BufferWithRandomAccess& operator<<(uint32_t x) { return *this << (int32_t)x; } BufferWithRandomAccess& operator<<(uint64_t x) { return *this << (int64_t)x; } BufferWithRandomAccess& operator<<(float x) { BYN_TRACE("writeFloat32: " << x << " (at " << size() << ")\n"); return *this << Literal(x).reinterpreti32(); } BufferWithRandomAccess& operator<<(double x) { BYN_TRACE("writeFloat64: " << x << " (at " << size() << ")\n"); return *this << Literal(x).reinterpreti64(); } void writeAt(size_t i, uint16_t x) { BYN_TRACE("backpatchInt16: " << x << " (at " << i << ")\n"); (*this)[i] = x & 0xff; (*this)[i + 1] = x >> 8; } void writeAt(size_t i, uint32_t x) { BYN_TRACE("backpatchInt32: " << x << " (at " << i << ")\n"); (*this)[i] = x & 0xff; x >>= 8; (*this)[i + 1] = x & 0xff; x >>= 8; (*this)[i + 2] = x & 0xff; x >>= 8; (*this)[i + 3] = x & 0xff; } // writes out an LEB to an arbitrary location. this writes the LEB as a full // 5 bytes, the fixed amount that can easily be set aside ahead of time void writeAtFullFixedSize(size_t i, U32LEB x) { BYN_TRACE("backpatchU32LEB: " << x.value << " (at " << i << ")\n"); // fill all 5 bytes, we have to do this when backpatching x.writeAt(this, i, MaxLEB32Bytes); } // writes out an LEB of normal size // returns how many bytes were written size_t writeAt(size_t i, U32LEB x) { BYN_TRACE("writeAtU32LEB: " << x.value << " (at " << i << ")\n"); return x.writeAt(this, i); } template<typename T> void writeTo(T& o) { for (auto c : *this) { o << c; } } std::vector<char> getAsChars() { std::vector<char> ret; ret.resize(size()); std::copy(begin(), end(), ret.begin()); return ret; } }; namespace BinaryConsts { enum Meta { Magic = 0x6d736100, Version = 0x01 }; enum Section { User = 0, Type = 1, Import = 2, Function = 3, Table = 4, Memory = 5, Global = 6, Export = 7, Start = 8, Element = 9, Code = 10, Data = 11, DataCount = 12, Tag = 13, Strings = 14, }; // A passive segment is a segment that will not be automatically copied into a // memory or table on instantiation, and must instead be applied manually // using the instructions memory.init or table.init. // An active segment is equivalent to a passive segment, but with an implicit // memory.init followed by a data.drop (or table.init followed by a elem.drop) // that is prepended to the module's start function. // A declarative element segment is not available at runtime but merely serves // to forward-declare references that are formed in code with instructions // like ref.func. enum SegmentFlag { // Bit 0: 0 = active, 1 = passive IsPassive = 1 << 0, // Bit 1 if passive: 0 = passive, 1 = declarative IsDeclarative = 1 << 1, // Bit 1 if active: 0 = index 0, 1 = index given HasIndex = 1 << 1, // Table element segments only: // Bit 2: 0 = elemType is funcref and a vector of func indexes given // 1 = elemType is given and a vector of ref expressions is given UsesExpressions = 1 << 2 }; enum EncodedType { // value_type i32 = -0x1, // 0x7f i64 = -0x2, // 0x7e f32 = -0x3, // 0x7d f64 = -0x4, // 0x7c v128 = -0x5, // 0x7b i8 = -0x6, // 0x7a i16 = -0x7, // 0x79 // function reference type funcref = -0x10, // 0x70 // external (host) references externref = -0x11, // 0x6f // top type of references to non-function Wasm data. anyref = -0x12, // 0x6e // comparable reference type eqref = -0x13, // 0x6d // nullable typed function reference type, with parameter nullable = -0x14, // 0x6c // non-nullable typed function reference type, with parameter nonnullable = -0x15, // 0x6b // integer reference type i31ref = -0x16, // 0x6a // gc and string reference types dataref = -0x19, // 0x67 arrayref = -0x1a, // 0x66 stringref = -0x1c, // 0x64 stringview_wtf8 = -0x1d, // 0x63 stringview_wtf16 = -0x1e, // 0x62 stringview_iter = -0x1f, // 0x61 // bottom types nullexternref = -0x17, // 0x69 nullfuncref = -0x18, // 0x68 nullref = -0x1b, // 0x65 // type forms Func = -0x20, // 0x60 Struct = -0x21, // 0x5f Array = -0x22, // 0x5e Sub = -0x30, // 0x50 // prototype nominal forms we still parse FuncSubtype = -0x23, // 0x5d StructSubtype = -0x24, // 0x5c ArraySubtype = -0x25, // 0x5b // isorecursive recursion groups Rec = -0x31, // 0x4f // block_type Empty = -0x40 // 0x40 }; enum EncodedHeapType { func = -0x10, // 0x70 ext = -0x11, // 0x6f any = -0x12, // 0x6e eq = -0x13, // 0x6d i31 = -0x16, // 0x6a data = -0x19, // 0x67 array = -0x1a, // 0x66 string = -0x1c, // 0x64 // stringview/iter constants are identical to type, and cannot be duplicated // here as that would be a compiler error, so add _heap suffixes. See // https://github.com/WebAssembly/stringref/issues/12 stringview_wtf8_heap = -0x1d, // 0x63 stringview_wtf16_heap = -0x1e, // 0x62 stringview_iter_heap = -0x1f, // 0x61 // bottom types noext = -0x17, // 0x69 nofunc = -0x18, // 0x68 none = -0x1b, // 0x65 }; namespace UserSections { extern const char* Name; extern const char* SourceMapUrl; extern const char* Dylink; extern const char* Dylink0; extern const char* Linking; extern const char* Producers; extern const char* TargetFeatures; extern const char* AtomicsFeature; extern const char* BulkMemoryFeature; extern const char* ExceptionHandlingFeature; extern const char* MutableGlobalsFeature; extern const char* TruncSatFeature; extern const char* SignExtFeature; extern const char* SIMD128Feature; extern const char* ExceptionHandlingFeature; extern const char* TailCallFeature; extern const char* ReferenceTypesFeature; extern const char* MultivalueFeature; extern const char* GCFeature; extern const char* Memory64Feature; extern const char* RelaxedSIMDFeature; extern const char* ExtendedConstFeature; extern const char* StringsFeature; extern const char* MultiMemoriesFeature; enum Subsection { NameModule = 0, NameFunction = 1, NameLocal = 2, // see: https://github.com/WebAssembly/extended-name-section NameLabel = 3, NameType = 4, NameTable = 5, NameMemory = 6, NameGlobal = 7, NameElem = 8, NameData = 9, // see: https://github.com/WebAssembly/gc/issues/193 NameField = 10, NameTag = 11, DylinkMemInfo = 1, DylinkNeeded = 2, }; } // namespace UserSections enum ASTNodes { Unreachable = 0x00, Nop = 0x01, Block = 0x02, Loop = 0x03, If = 0x04, Else = 0x05, End = 0x0b, Br = 0x0c, BrIf = 0x0d, BrTable = 0x0e, Return = 0x0f, CallFunction = 0x10, CallIndirect = 0x11, RetCallFunction = 0x12, RetCallIndirect = 0x13, Drop = 0x1a, Select = 0x1b, SelectWithType = 0x1c, // added in reference types proposal LocalGet = 0x20, LocalSet = 0x21, LocalTee = 0x22, GlobalGet = 0x23, GlobalSet = 0x24, TableGet = 0x25, TableSet = 0x26, I32LoadMem = 0x28, I64LoadMem = 0x29, F32LoadMem = 0x2a, F64LoadMem = 0x2b, I32LoadMem8S = 0x2c, I32LoadMem8U = 0x2d, I32LoadMem16S = 0x2e, I32LoadMem16U = 0x2f, I64LoadMem8S = 0x30, I64LoadMem8U = 0x31, I64LoadMem16S = 0x32, I64LoadMem16U = 0x33, I64LoadMem32S = 0x34, I64LoadMem32U = 0x35, I32StoreMem = 0x36, I64StoreMem = 0x37, F32StoreMem = 0x38, F64StoreMem = 0x39, I32StoreMem8 = 0x3a, I32StoreMem16 = 0x3b, I64StoreMem8 = 0x3c, I64StoreMem16 = 0x3d, I64StoreMem32 = 0x3e, MemorySize = 0x3f, MemoryGrow = 0x40, I32Const = 0x41, I64Const = 0x42, F32Const = 0x43, F64Const = 0x44, I32EqZ = 0x45, I32Eq = 0x46, I32Ne = 0x47, I32LtS = 0x48, I32LtU = 0x49, I32GtS = 0x4a, I32GtU = 0x4b, I32LeS = 0x4c, I32LeU = 0x4d, I32GeS = 0x4e, I32GeU = 0x4f, I64EqZ = 0x50, I64Eq = 0x51, I64Ne = 0x52, I64LtS = 0x53, I64LtU = 0x54, I64GtS = 0x55, I64GtU = 0x56, I64LeS = 0x57, I64LeU = 0x58, I64GeS = 0x59, I64GeU = 0x5a, F32Eq = 0x5b, F32Ne = 0x5c, F32Lt = 0x5d, F32Gt = 0x5e, F32Le = 0x5f, F32Ge = 0x60, F64Eq = 0x61, F64Ne = 0x62, F64Lt = 0x63, F64Gt = 0x64, F64Le = 0x65, F64Ge = 0x66, I32Clz = 0x67, I32Ctz = 0x68, I32Popcnt = 0x69, I32Add = 0x6a, I32Sub = 0x6b, I32Mul = 0x6c, I32DivS = 0x6d, I32DivU = 0x6e, I32RemS = 0x6f, I32RemU = 0x70, I32And = 0x71, I32Or = 0x72, I32Xor = 0x73, I32Shl = 0x74, I32ShrS = 0x75, I32ShrU = 0x76, I32RotL = 0x77, I32RotR = 0x78, I64Clz = 0x79, I64Ctz = 0x7a, I64Popcnt = 0x7b, I64Add = 0x7c, I64Sub = 0x7d, I64Mul = 0x7e, I64DivS = 0x7f, I64DivU = 0x80, I64RemS = 0x81, I64RemU = 0x82, I64And = 0x83, I64Or = 0x84, I64Xor = 0x85, I64Shl = 0x86, I64ShrS = 0x87, I64ShrU = 0x88, I64RotL = 0x89, I64RotR = 0x8a, F32Abs = 0x8b, F32Neg = 0x8c, F32Ceil = 0x8d, F32Floor = 0x8e, F32Trunc = 0x8f, F32NearestInt = 0x90, F32Sqrt = 0x91, F32Add = 0x92, F32Sub = 0x93, F32Mul = 0x94, F32Div = 0x95, F32Min = 0x96, F32Max = 0x97, F32CopySign = 0x98, F64Abs = 0x99, F64Neg = 0x9a, F64Ceil = 0x9b, F64Floor = 0x9c, F64Trunc = 0x9d, F64NearestInt = 0x9e, F64Sqrt = 0x9f, F64Add = 0xa0, F64Sub = 0xa1, F64Mul = 0xa2, F64Div = 0xa3, F64Min = 0xa4, F64Max = 0xa5, F64CopySign = 0xa6, I32WrapI64 = 0xa7, I32STruncF32 = 0xa8, I32UTruncF32 = 0xa9, I32STruncF64 = 0xaa, I32UTruncF64 = 0xab, I64SExtendI32 = 0xac, I64UExtendI32 = 0xad, I64STruncF32 = 0xae, I64UTruncF32 = 0xaf, I64STruncF64 = 0xb0, I64UTruncF64 = 0xb1, F32SConvertI32 = 0xb2, F32UConvertI32 = 0xb3, F32SConvertI64 = 0xb4, F32UConvertI64 = 0xb5, F32DemoteI64 = 0xb6, F64SConvertI32 = 0xb7, F64UConvertI32 = 0xb8, F64SConvertI64 = 0xb9, F64UConvertI64 = 0xba, F64PromoteF32 = 0xbb, I32ReinterpretF32 = 0xbc, I64ReinterpretF64 = 0xbd, F32ReinterpretI32 = 0xbe, F64ReinterpretI64 = 0xbf, I32ExtendS8 = 0xc0, I32ExtendS16 = 0xc1, I64ExtendS8 = 0xc2, I64ExtendS16 = 0xc3, I64ExtendS32 = 0xc4, // prefixes GCPrefix = 0xfb, MiscPrefix = 0xfc, SIMDPrefix = 0xfd, AtomicPrefix = 0xfe, // atomic opcodes AtomicNotify = 0x00, I32AtomicWait = 0x01, I64AtomicWait = 0x02, AtomicFence = 0x03, I32AtomicLoad = 0x10, I64AtomicLoad = 0x11, I32AtomicLoad8U = 0x12, I32AtomicLoad16U = 0x13, I64AtomicLoad8U = 0x14, I64AtomicLoad16U = 0x15, I64AtomicLoad32U = 0x16, I32AtomicStore = 0x17, I64AtomicStore = 0x18, I32AtomicStore8 = 0x19, I32AtomicStore16 = 0x1a, I64AtomicStore8 = 0x1b, I64AtomicStore16 = 0x1c, I64AtomicStore32 = 0x1d, AtomicRMWOps_Begin = 0x1e, I32AtomicRMWAdd = 0x1e, I64AtomicRMWAdd = 0x1f, I32AtomicRMWAdd8U = 0x20, I32AtomicRMWAdd16U = 0x21, I64AtomicRMWAdd8U = 0x22, I64AtomicRMWAdd16U = 0x23, I64AtomicRMWAdd32U = 0x24, I32AtomicRMWSub = 0x25, I64AtomicRMWSub = 0x26, I32AtomicRMWSub8U = 0x27, I32AtomicRMWSub16U = 0x28, I64AtomicRMWSub8U = 0x29, I64AtomicRMWSub16U = 0x2a, I64AtomicRMWSub32U = 0x2b, I32AtomicRMWAnd = 0x2c, I64AtomicRMWAnd = 0x2d, I32AtomicRMWAnd8U = 0x2e, I32AtomicRMWAnd16U = 0x2f, I64AtomicRMWAnd8U = 0x30, I64AtomicRMWAnd16U = 0x31, I64AtomicRMWAnd32U = 0x32, I32AtomicRMWOr = 0x33, I64AtomicRMWOr = 0x34, I32AtomicRMWOr8U = 0x35, I32AtomicRMWOr16U = 0x36, I64AtomicRMWOr8U = 0x37, I64AtomicRMWOr16U = 0x38, I64AtomicRMWOr32U = 0x39, I32AtomicRMWXor = 0x3a, I64AtomicRMWXor = 0x3b, I32AtomicRMWXor8U = 0x3c, I32AtomicRMWXor16U = 0x3d, I64AtomicRMWXor8U = 0x3e, I64AtomicRMWXor16U = 0x3f, I64AtomicRMWXor32U = 0x40, I32AtomicRMWXchg = 0x41, I64AtomicRMWXchg = 0x42, I32AtomicRMWXchg8U = 0x43, I32AtomicRMWXchg16U = 0x44, I64AtomicRMWXchg8U = 0x45, I64AtomicRMWXchg16U = 0x46, I64AtomicRMWXchg32U = 0x47, AtomicRMWOps_End = 0x47, AtomicCmpxchgOps_Begin = 0x48, I32AtomicCmpxchg = 0x48, I64AtomicCmpxchg = 0x49, I32AtomicCmpxchg8U = 0x4a, I32AtomicCmpxchg16U = 0x4b, I64AtomicCmpxchg8U = 0x4c, I64AtomicCmpxchg16U = 0x4d, I64AtomicCmpxchg32U = 0x4e, AtomicCmpxchgOps_End = 0x4e, // truncsat opcodes I32STruncSatF32 = 0x00, I32UTruncSatF32 = 0x01, I32STruncSatF64 = 0x02, I32UTruncSatF64 = 0x03, I64STruncSatF32 = 0x04, I64UTruncSatF32 = 0x05, I64STruncSatF64 = 0x06, I64UTruncSatF64 = 0x07, // SIMD opcodes V128Load = 0x00, V128Load8x8S = 0x01, V128Load8x8U = 0x02, V128Load16x4S = 0x03, V128Load16x4U = 0x04, V128Load32x2S = 0x05, V128Load32x2U = 0x06, V128Load8Splat = 0x07, V128Load16Splat = 0x08, V128Load32Splat = 0x09, V128Load64Splat = 0x0a, V128Store = 0x0b, V128Const = 0x0c, I8x16Shuffle = 0x0d, I8x16Swizzle = 0x0e, I8x16Splat = 0x0f, I16x8Splat = 0x10, I32x4Splat = 0x11, I64x2Splat = 0x12, F32x4Splat = 0x13, F64x2Splat = 0x14, I8x16ExtractLaneS = 0x15, I8x16ExtractLaneU = 0x16, I8x16ReplaceLane = 0x17, I16x8ExtractLaneS = 0x18, I16x8ExtractLaneU = 0x19, I16x8ReplaceLane = 0x1a, I32x4ExtractLane = 0x1b, I32x4ReplaceLane = 0x1c, I64x2ExtractLane = 0x1d, I64x2ReplaceLane = 0x1e, F32x4ExtractLane = 0x1f, F32x4ReplaceLane = 0x20, F64x2ExtractLane = 0x21, F64x2ReplaceLane = 0x22, I8x16Eq = 0x23, I8x16Ne = 0x24, I8x16LtS = 0x25, I8x16LtU = 0x26, I8x16GtS = 0x27, I8x16GtU = 0x28, I8x16LeS = 0x29, I8x16LeU = 0x2a, I8x16GeS = 0x2b, I8x16GeU = 0x2c, I16x8Eq = 0x2d, I16x8Ne = 0x2e, I16x8LtS = 0x2f, I16x8LtU = 0x30, I16x8GtS = 0x31, I16x8GtU = 0x32, I16x8LeS = 0x33, I16x8LeU = 0x34, I16x8GeS = 0x35, I16x8GeU = 0x36, I32x4Eq = 0x37, I32x4Ne = 0x38, I32x4LtS = 0x39, I32x4LtU = 0x3a, I32x4GtS = 0x3b, I32x4GtU = 0x3c, I32x4LeS = 0x3d, I32x4LeU = 0x3e, I32x4GeS = 0x3f, I32x4GeU = 0x40, F32x4Eq = 0x41, F32x4Ne = 0x42, F32x4Lt = 0x43, F32x4Gt = 0x44, F32x4Le = 0x45, F32x4Ge = 0x46, F64x2Eq = 0x47, F64x2Ne = 0x48, F64x2Lt = 0x49, F64x2Gt = 0x4a, F64x2Le = 0x4b, F64x2Ge = 0x4c, V128Not = 0x4d, V128And = 0x4e, V128Andnot = 0x4f, V128Or = 0x50, V128Xor = 0x51, V128Bitselect = 0x52, V128AnyTrue = 0x53, V128Load8Lane = 0x54, V128Load16Lane = 0x55, V128Load32Lane = 0x56, V128Load64Lane = 0x57, V128Store8Lane = 0x58, V128Store16Lane = 0x59, V128Store32Lane = 0x5a, V128Store64Lane = 0x5b, V128Load32Zero = 0x5c, V128Load64Zero = 0x5d, F32x4DemoteF64x2Zero = 0x5e, F64x2PromoteLowF32x4 = 0x5f, I8x16Abs = 0x60, I8x16Neg = 0x61, I8x16Popcnt = 0x62, I8x16AllTrue = 0x63, I8x16Bitmask = 0x64, I8x16NarrowI16x8S = 0x65, I8x16NarrowI16x8U = 0x66, F32x4Ceil = 0x67, F32x4Floor = 0x68, F32x4Trunc = 0x69, F32x4Nearest = 0x6a, I8x16Shl = 0x6b, I8x16ShrS = 0x6c, I8x16ShrU = 0x6d, I8x16Add = 0x6e, I8x16AddSatS = 0x6f, I8x16AddSatU = 0x70, I8x16Sub = 0x71, I8x16SubSatS = 0x72, I8x16SubSatU = 0x73, F64x2Ceil = 0x74, F64x2Floor = 0x75, I8x16MinS = 0x76, I8x16MinU = 0x77, I8x16MaxS = 0x78, I8x16MaxU = 0x79, F64x2Trunc = 0x7a, I8x16AvgrU = 0x7b, I16x8ExtaddPairwiseI8x16S = 0x7c, I16x8ExtaddPairwiseI8x16U = 0x7d, I32x4ExtaddPairwiseI16x8S = 0x7e, I32x4ExtaddPairwiseI16x8U = 0x7f, I16x8Abs = 0x80, I16x8Neg = 0x81, I16x8Q15MulrSatS = 0x82, I16x8AllTrue = 0x83, I16x8Bitmask = 0x84, I16x8NarrowI32x4S = 0x85, I16x8NarrowI32x4U = 0x86, I16x8ExtendLowI8x16S = 0x87, I16x8ExtendHighI8x16S = 0x88, I16x8ExtendLowI8x16U = 0x89, I16x8ExtendHighI8x16U = 0x8a, I16x8Shl = 0x8b, I16x8ShrS = 0x8c, I16x8ShrU = 0x8d, I16x8Add = 0x8e, I16x8AddSatS = 0x8f, I16x8AddSatU = 0x90, I16x8Sub = 0x91, I16x8SubSatS = 0x92, I16x8SubSatU = 0x93, F64x2Nearest = 0x94, I16x8Mul = 0x95, I16x8MinS = 0x96, I16x8MinU = 0x97, I16x8MaxS = 0x98, I16x8MaxU = 0x99, // 0x9a unused I16x8AvgrU = 0x9b, I16x8ExtmulLowI8x16S = 0x9c, I16x8ExtmulHighI8x16S = 0x9d, I16x8ExtmulLowI8x16U = 0x9e, I16x8ExtmulHighI8x16U = 0x9f, I32x4Abs = 0xa0, I32x4Neg = 0xa1, // 0xa2 unused I32x4AllTrue = 0xa3, I32x4Bitmask = 0xa4, // 0xa5 unused // 0xa6 unused I32x4ExtendLowI16x8S = 0xa7, I32x4ExtendHighI16x8S = 0xa8, I32x4ExtendLowI16x8U = 0xa9, I32x4ExtendHighI16x8U = 0xaa, I32x4Shl = 0xab, I32x4ShrS = 0xac, I32x4ShrU = 0xad, I32x4Add = 0xae, // 0xaf unused // 0xb0 unused I32x4Sub = 0xb1, // 0xb2 unused // 0xb3 unused // 0xb4 unused I32x4Mul = 0xb5, I32x4MinS = 0xb6, I32x4MinU = 0xb7, I32x4MaxS = 0xb8, I32x4MaxU = 0xb9, I32x4DotI16x8S = 0xba, // 0xbb unused I32x4ExtmulLowI16x8S = 0xbc, I32x4ExtmulHighI16x8S = 0xbd, I32x4ExtmulLowI16x8U = 0xbe, I32x4ExtmulHighI16x8U = 0xbf, I64x2Abs = 0xc0, I64x2Neg = 0xc1, // 0xc2 unused I64x2AllTrue = 0xc3, I64x2Bitmask = 0xc4, // 0xc5 unused // 0xc6 unused I64x2ExtendLowI32x4S = 0xc7, I64x2ExtendHighI32x4S = 0xc8, I64x2ExtendLowI32x4U = 0xc9, I64x2ExtendHighI32x4U = 0xca, I64x2Shl = 0xcb, I64x2ShrS = 0xcc, I64x2ShrU = 0xcd, I64x2Add = 0xce, // 0xcf unused // 0xd0 unused I64x2Sub = 0xd1, // 0xd2 unused // 0xd3 unused // 0xd4 unused I64x2Mul = 0xd5, I64x2Eq = 0xd6, I64x2Ne = 0xd7, I64x2LtS = 0xd8, I64x2GtS = 0xd9, I64x2LeS = 0xda, I64x2GeS = 0xdb, I64x2ExtmulLowI32x4S = 0xdc, I64x2ExtmulHighI32x4S = 0xdd, I64x2ExtmulLowI32x4U = 0xde, I64x2ExtmulHighI32x4U = 0xdf, F32x4Abs = 0xe0, F32x4Neg = 0xe1, // 0xe2 unused F32x4Sqrt = 0xe3, F32x4Add = 0xe4, F32x4Sub = 0xe5, F32x4Mul = 0xe6, F32x4Div = 0xe7, F32x4Min = 0xe8, F32x4Max = 0xe9, F32x4Pmin = 0xea, F32x4Pmax = 0xeb, F64x2Abs = 0xec, F64x2Neg = 0xed, // 0xee unused F64x2Sqrt = 0xef, F64x2Add = 0xf0, F64x2Sub = 0xf1, F64x2Mul = 0xf2, F64x2Div = 0xf3, F64x2Min = 0xf4, F64x2Max = 0xf5, F64x2Pmin = 0xf6, F64x2Pmax = 0xf7, I32x4TruncSatF32x4S = 0xf8, I32x4TruncSatF32x4U = 0xf9, F32x4ConvertI32x4S = 0xfa, F32x4ConvertI32x4U = 0xfb, I32x4TruncSatF64x2SZero = 0xfc, I32x4TruncSatF64x2UZero = 0xfd, F64x2ConvertLowI32x4S = 0xfe, F64x2ConvertLowI32x4U = 0xff, // relaxed SIMD opcodes I8x16RelaxedSwizzle = 0x100, I32x4RelaxedTruncF32x4S = 0x101, I32x4RelaxedTruncF32x4U = 0x102, I32x4RelaxedTruncF64x2SZero = 0x103, I32x4RelaxedTruncF64x2UZero = 0x104, F32x4RelaxedFma = 0x105, F32x4RelaxedFms = 0x106, F64x2RelaxedFma = 0x107, F64x2RelaxedFms = 0x108, I8x16Laneselect = 0x109, I16x8Laneselect = 0x10a, I32x4Laneselect = 0x10b, I64x2Laneselect = 0x10c, F32x4RelaxedMin = 0x10d, F32x4RelaxedMax = 0x10e, F64x2RelaxedMin = 0x10f, F64x2RelaxedMax = 0x110, I16x8RelaxedQ15MulrS = 0x111, I16x8DotI8x16I7x16S = 0x112, I32x4DotI8x16I7x16AddS = 0x113, // bulk memory opcodes MemoryInit = 0x08, DataDrop = 0x09, MemoryCopy = 0x0a, MemoryFill = 0x0b, // reference types opcodes TableGrow = 0x0f, TableSize = 0x10, RefNull = 0xd0, RefIsNull = 0xd1, RefFunc = 0xd2, RefAsNonNull = 0xd3, BrOnNull = 0xd4, BrOnNonNull = 0xd6, // exception handling opcodes Try = 0x06, Catch = 0x07, CatchAll = 0x19, Delegate = 0x18, Throw = 0x08, Rethrow = 0x09, // typed function references opcodes CallRef = 0x14, RetCallRef = 0x15, // gc opcodes RefEq = 0xd5, StructGet = 0x03, StructGetS = 0x04, StructGetU = 0x05, StructSet = 0x06, StructNew = 0x07, StructNewDefault = 0x08, ArrayNewElem = 0x10, ArrayGet = 0x13, ArrayGetS = 0x14, ArrayGetU = 0x15, ArraySet = 0x16, ArrayLenAnnotated = 0x17, ArrayCopy = 0x18, ArrayLen = 0x19, ArrayInitStatic = 0x1a, ArrayNew = 0x1b, ArrayNewDefault = 0x1c, ArrayNewData = 0x1d, I31New = 0x20, I31GetS = 0x21, I31GetU = 0x22, RefTestStatic = 0x44, RefCastStatic = 0x45, BrOnCastStatic = 0x46, BrOnCastStaticFail = 0x47, RefCastNopStatic = 0x48, RefIsFunc = 0x50, RefIsData = 0x51, RefIsI31 = 0x52, RefAsFunc = 0x58, RefAsData = 0x59, RefAsI31 = 0x5a, BrOnFunc = 0x60, BrOnData = 0x61, BrOnI31 = 0x62, BrOnNonFunc = 0x63, BrOnNonData = 0x64, BrOnNonI31 = 0x65, ExternInternalize = 0x70, ExternExternalize = 0x71, StringNewWTF8 = 0x80, StringNewWTF16 = 0x81, StringConst = 0x82, StringMeasureWTF8 = 0x84, StringMeasureWTF16 = 0x85, StringEncodeWTF8 = 0x86, StringEncodeWTF16 = 0x87, StringConcat = 0x88, StringEq = 0x89, StringIsUSV = 0x8a, StringAsWTF8 = 0x90, StringViewWTF8Advance = 0x91, StringViewWTF8Slice = 0x93, StringAsWTF16 = 0x98, StringViewWTF16Length = 0x99, StringViewWTF16GetCodePoint = 0x9a, StringViewWTF16Slice = 0x9c, StringAsIter = 0xa0, StringViewIterNext = 0xa1, StringViewIterAdvance = 0xa2, StringViewIterRewind = 0xa3, StringViewIterSlice = 0xa4, StringNewWTF8Array = 0xb0, StringNewWTF16Array = 0xb1, StringEncodeWTF8Array = 0xb2, StringEncodeWTF16Array = 0xb3, }; enum MemoryAccess { Offset = 0x10, // bit 4 Alignment = 0x80, // bit 7 NaturalAlignment = 0 }; enum MemoryFlags { HasMaximum = 1 << 0, IsShared = 1 << 1, Is64 = 1 << 2 }; enum StringPolicy { UTF8 = 0x00, WTF8 = 0x01, Replace = 0x02, }; enum FeaturePrefix { FeatureUsed = '+', FeatureRequired = '=', FeatureDisallowed = '-' }; } // namespace BinaryConsts // (local index in IR, tuple index) => binary local index using MappedLocals = std::unordered_map<std::pair<Index, Index>, size_t>; // Writes out wasm to the binary format class WasmBinaryWriter { // Computes the indexes in a wasm binary, i.e., with function imports // and function implementations sharing a single index space, etc., // and with the imports first (the Module's functions and globals // arrays are not assumed to be in a particular order, so we can't // just use them directly). struct BinaryIndexes { std::unordered_map<Name, Index> functionIndexes; std::unordered_map<Name, Index> tagIndexes; std::unordered_map<Name, Index> globalIndexes; std::unordered_map<Name, Index> tableIndexes; std::unordered_map<Name, Index> elemIndexes; std::unordered_map<Name, Index> memoryIndexes; std::unordered_map<Name, Index> dataIndexes; BinaryIndexes(Module& wasm) { auto addIndexes = [&](auto& source, auto& indexes) { auto addIndex = [&](auto* curr) { auto index = indexes.size(); indexes[curr->name] = index; }; for (auto& curr : source) { if (curr->imported()) { addIndex(curr.get()); } } for (auto& curr : source) { if (!curr->imported()) { addIndex(curr.get()); } } }; addIndexes(wasm.functions, functionIndexes); addIndexes(wasm.tags, tagIndexes); addIndexes(wasm.tables, tableIndexes); addIndexes(wasm.memories, memoryIndexes); for (auto& curr : wasm.elementSegments) { auto index = elemIndexes.size(); elemIndexes[curr->name] = index; } for (auto& curr : wasm.dataSegments) { auto index = dataIndexes.size(); dataIndexes[curr->name] = index; } // Globals may have tuple types in the IR, in which case they lower to // multiple globals, one for each tuple element, in the binary. Tuple // globals therefore occupy multiple binary indices, and we have to take // that into account when calculating indices. Index globalCount = 0; auto addGlobal = [&](auto* curr) { globalIndexes[curr->name] = globalCount; globalCount += curr->type.size(); }; for (auto& curr : wasm.globals) { if (curr->imported()) { addGlobal(curr.get()); } } for (auto& curr : wasm.globals) { if (!curr->imported()) { addGlobal(curr.get()); } } } }; public: WasmBinaryWriter(Module* input, BufferWithRandomAccess& o) : wasm(input), o(o), indexes(*input) { prepare(); } // locations in the output binary for the various parts of the module struct TableOfContents { struct Entry { Name name; size_t offset; // where the entry starts size_t size; // the size of the entry Entry(Name name, size_t offset, size_t size) : name(name), offset(offset), size(size) {} }; std::vector<Entry> functionBodies; } tableOfContents; void setNamesSection(bool set) { debugInfo = set; emitModuleName = set; } void setEmitModuleName(bool set) { emitModuleName = set; } void setSourceMap(std::ostream* set, std::string url) { sourceMap = set; sourceMapUrl = url; } void setSymbolMap(std::string set) { symbolMap = set; } void write(); void writeHeader(); int32_t writeU32LEBPlaceholder(); void writeResizableLimits( Address initial, Address maximum, bool hasMaximum, bool shared, bool is64); template<typename T> int32_t startSection(T code); void finishSection(int32_t start); int32_t startSubsection(BinaryConsts::UserSections::Subsection code); void finishSubsection(int32_t start); void writeStart(); void writeMemories(); void writeTypes(); void writeImports(); void writeFunctionSignatures(); void writeExpression(Expression* curr); void writeFunctions(); void writeStrings(); void writeGlobals(); void writeExports(); void writeDataCount(); void writeDataSegments(); void writeTags(); uint32_t getFunctionIndex(Name name) const; uint32_t getTableIndex(Name name) const; uint32_t getMemoryIndex(Name name) const; uint32_t getGlobalIndex(Name name) const; uint32_t getTagIndex(Name name) const; uint32_t getTypeIndex(HeapType type) const; uint32_t getStringIndex(Name string) const; void writeTableDeclarations(); void writeElementSegments(); void writeNames(); void writeSourceMapUrl(); void writeSymbolMap(); void writeLateUserSections(); void writeUserSection(const UserSection& section); void writeFeaturesSection(); void writeDylinkSection(); void writeLegacyDylinkSection(); void initializeDebugInfo(); void writeSourceMapProlog(); void writeSourceMapEpilog(); void writeDebugLocation(const Function::DebugLocation& loc); void writeDebugLocation(Expression* curr, Function* func); void writeDebugLocationEnd(Expression* curr, Function* func); void writeExtraDebugLocation(Expression* curr, Function* func, size_t id); // helpers void writeInlineString(std::string_view name); void writeEscapedName(std::string_view name); void writeInlineBuffer(const char* data, size_t size); void writeData(const char* data, size_t size); struct Buffer { const char* data; size_t size; size_t pointerLocation; Buffer(const char* data, size_t size, size_t pointerLocation) : data(data), size(size), pointerLocation(pointerLocation) {} }; Module* getModule() { return wasm; } void writeType(Type type); // Writes an arbitrary heap type, which may be indexed or one of the // basic types like funcref. void writeHeapType(HeapType type); // Writes an indexed heap type. Note that this is encoded differently than a // general heap type because it does not allow negative values for basic heap // types. void writeIndexedHeapType(HeapType type); void writeField(const Field& field); private: Module* wasm; BufferWithRandomAccess& o; BinaryIndexes indexes; ModuleUtils::IndexedHeapTypes indexedTypes; bool debugInfo = true; // TODO: Remove `emitModuleName` in the future once there are better ways to // ensure modules have meaningful names in stack traces.For example, using // ObjectURLs works in FireFox, but not Chrome. See // https://bugs.chromium.org/p/v8/issues/detail?id=11808. bool emitModuleName = true; std::ostream* sourceMap = nullptr; std::string sourceMapUrl; std::string symbolMap; MixedArena allocator; // storage of source map locations until the section is placed at its final // location (shrinking LEBs may cause changes there) std::vector<std::pair<size_t, const Function::DebugLocation*>> sourceMapLocations; size_t sourceMapLocationsSizeAtSectionStart; Function::DebugLocation lastDebugLocation; std::unique_ptr<ImportInfo> importInfo; // General debugging info: track locations as we write. BinaryLocations binaryLocations; size_t binaryLocationsSizeAtSectionStart; // Track the expressions that we added for the current function being // written, so that we can update those specific binary locations when // the function is written out. std::vector<Expression*> binaryLocationTrackedExpressionsForFunc; // Maps function names to their mapped locals. This is used when we emit the // local names section: we map the locals when writing the function, save that // info here, and then use it when writing the names. std::unordered_map<Name, MappedLocals> funcMappedLocals; // Indexes in the string literal section of each StringConst in the wasm. std::unordered_map<Name, Index> stringIndexes; void prepare(); }; class WasmBinaryBuilder { Module& wasm; MixedArena& allocator; const std::vector<char>& input; std::istream* sourceMap; std::pair<uint32_t, Function::DebugLocation> nextDebugLocation; bool debugInfo = true; bool DWARF = false; bool skipFunctionBodies = false; size_t pos = 0; Index startIndex = -1; std::set<Function::DebugLocation> debugLocation; size_t codeSectionLocation; std::set<BinaryConsts::Section> seenSections; // All types defined in the type section std::vector<HeapType> types; public: WasmBinaryBuilder(Module& wasm, FeatureSet features, const std::vector<char>& input); void setDebugInfo(bool value) { debugInfo = value; } void setDWARF(bool value) { DWARF = value; } void setSkipFunctionBodies(bool skipFunctionBodies_) { skipFunctionBodies = skipFunctionBodies_; } void read(); void readUserSection(size_t payloadLen); bool more() { return pos < input.size(); } std::string_view getByteView(size_t size); uint8_t getInt8(); uint16_t getInt16(); uint32_t getInt32(); uint64_t getInt64(); uint8_t getLaneIndex(size_t lanes); // it is unsafe to return a float directly, due to ABI issues with the // signalling bit Literal getFloat32Literal(); Literal getFloat64Literal(); Literal getVec128Literal(); uint32_t getU32LEB(); uint64_t getU64LEB(); int32_t getS32LEB(); int64_t getS64LEB(); uint64_t getUPtrLEB(); bool getBasicType(int32_t code, Type& out); bool getBasicHeapType(int64_t code, HeapType& out); // Read a value and get a type for it. Type getType(); // Get a type given the initial S32LEB has already been read, and is provided. Type getType(int initial); HeapType getHeapType(); HeapType getIndexedHeapType(); Type getConcreteType(); Name getInlineString(); void verifyInt8(int8_t x); void verifyInt16(int16_t x); void verifyInt32(int32_t x); void verifyInt64(int64_t x); void readHeader(); void readStart(); void readMemories(); void readTypes(); // gets a name in the combined import+defined space Name getFunctionName(Index index); Name getTableName(Index index); Name getMemoryName(Index index); Name getGlobalName(Index index); Name getTagName(Index index); // gets a memory in the combined import+defined space Memory* getMemory(Index index); void getResizableLimits(Address& initial, Address& max, bool& shared, Type& indexType, Address defaultIfNoMax); void readImports(); // The signatures of each function, including imported functions, given in the // import and function sections. Store HeapTypes instead of Signatures because // reconstructing the HeapTypes from the Signatures is expensive. std::vector<HeapType> functionTypes; void readFunctionSignatures(); HeapType getTypeByIndex(Index index); HeapType getTypeByFunctionIndex(Index index); Signature getSignatureByTypeIndex(Index index); Signature getSignatureByFunctionIndex(Index index); size_t nextLabel; Name getNextLabel(); // We read functions and globals before we know their names, so we need to // backpatch the names later // at index i we have all refs to the function i std::map<Index, std::vector<Name*>> functionRefs; Function* currFunction = nullptr; // before we see a function (like global init expressions), there is no end of // function to check Index endOfFunction = -1; // at index i we have all references to the table i std::map<Index, std::vector<Name*>> tableRefs; std::map<Index, Name> elemTables; // at index i we have all references to the memory i std::map<Index, std::vector<wasm::Name*>> memoryRefs; // at index i we have all refs to the global i std::map<Index, std::vector<Name*>> globalRefs; // at index i we have all refs to the tag i std::map<Index, std::vector<Name*>> tagRefs; // Throws a parsing error if we are not in a function context void requireFunctionContext(const char* error); void readFunctions(); void readVars(); std::map<Export*, Index> exportIndices; std::vector<Export*> exportOrder; void readExports(); // The strings in the strings section (which are referred to by StringConst). std::vector<Name> strings; void readStrings(); Expression* readExpression(); void readGlobals(); struct BreakTarget { Name name; Type type; BreakTarget(Name name, Type type) : name(name), type(type) {} }; std::vector<BreakTarget> breakStack; // the names that breaks target. this lets us know if a block has breaks to it // or not. std::unordered_set<Name> breakTargetNames; // the names that delegates target. std::unordered_set<Name> exceptionTargetNames; std::vector<Expression*> expressionStack; // Control flow structure parsing: these have not just the normal binary // data for an instruction, but also some bytes later on like "end" or "else". // We must be aware of the connection between those things, for debug info. std::vector<Expression*> controlFlowStack; // Called when we parse the beginning of a control flow structure. void startControlFlow(Expression* curr); // set when we know code is unreachable in the sense of the wasm spec: we are // in a block and after an unreachable element. this helps parse stacky wasm // code, which can be unsuitable for our IR when unreachable. bool unreachableInTheWasmSense; // set when the current code being processed will not be emitted in the // output, which is the case when it is literally unreachable, for example, // (block $a // (unreachable) // (block $b // ;; code here is reachable in the wasm sense, even though $b as a whole // ;; is not // (unreachable) // ;; code here is unreachable in the wasm sense // ) // ) bool willBeIgnored; BinaryConsts::ASTNodes lastSeparator = BinaryConsts::End; // process a block-type scope, until an end or else marker, or the end of the // function void processExpressions(); void skipUnreachableCode(); void pushExpression(Expression* curr); Expression* popExpression(); Expression* popNonVoidExpression(); Expression* popTuple(size_t numElems); Expression* popTypedExpression(Type type); void validateBinary(); // validations that cannot be performed on the Module void processNames(); size_t dataCount = 0; bool hasDataCount = false; void readDataSegments(); void readDataSegmentCount(); void readTableDeclarations(); void readElementSegments(); void readTags(); static Name escape(Name name); void readNames(size_t); void readFeatures(size_t); void readDylink(size_t); void readDylink0(size_t); // Debug information reading helpers void setDebugLocations(std::istream* sourceMap_) { sourceMap = sourceMap_; } std::unordered_map<std::string, Index> debugInfoFileIndices; void readNextDebugLocation(); void readSourceMapHeader(); // AST reading int depth = 0; // only for debugging BinaryConsts::ASTNodes readExpression(Expression*& curr); void pushBlockElements(Block* curr, Type type, size_t start); void visitBlock(Block* curr); // Gets a block of expressions. If it's just one, return that singleton. Expression* getBlockOrSingleton(Type type); BreakTarget getBreakTarget(int32_t offset); Name getExceptionTargetName(int32_t offset); Index readMemoryAccess(Address& alignment, Address& offset); void visitIf(If* curr); void visitLoop(Loop* curr); void visitBreak(Break* curr, uint8_t code); void visitSwitch(Switch* curr); void visitCall(Call* curr); void visitCallIndirect(CallIndirect* curr); void visitLocalGet(LocalGet* curr); void visitLocalSet(LocalSet* curr, uint8_t code); void visitGlobalGet(GlobalGet* curr); void visitGlobalSet(GlobalSet* curr); bool maybeVisitLoad(Expression*& out, uint8_t code, bool isAtomic); bool maybeVisitStore(Expression*& out, uint8_t code, bool isAtomic); bool maybeVisitNontrappingTrunc(Expression*& out, uint32_t code); bool maybeVisitAtomicRMW(Expression*& out, uint8_t code); bool maybeVisitAtomicCmpxchg(Expression*& out, uint8_t code); bool maybeVisitAtomicWait(Expression*& out, uint8_t code); bool maybeVisitAtomicNotify(Expression*& out, uint8_t code); bool maybeVisitAtomicFence(Expression*& out, uint8_t code); bool maybeVisitConst(Expression*& out, uint8_t code); bool maybeVisitUnary(Expression*& out, uint8_t code); bool maybeVisitBinary(Expression*& out, uint8_t code); bool maybeVisitTruncSat(Expression*& out, uint32_t code); bool maybeVisitSIMDBinary(Expression*& out, uint32_t code); bool maybeVisitSIMDUnary(Expression*& out, uint32_t code); bool maybeVisitSIMDConst(Expression*& out, uint32_t code); bool maybeVisitSIMDStore(Expression*& out, uint32_t code); bool maybeVisitSIMDExtract(Expression*& out, uint32_t code); bool maybeVisitSIMDReplace(Expression*& out, uint32_t code); bool maybeVisitSIMDShuffle(Expression*& out, uint32_t code); bool maybeVisitSIMDTernary(Expression*& out, uint32_t code); bool maybeVisitSIMDShift(Expression*& out, uint32_t code); bool maybeVisitSIMDLoad(Expression*& out, uint32_t code); bool maybeVisitSIMDLoadStoreLane(Expression*& out, uint32_t code); bool maybeVisitMemoryInit(Expression*& out, uint32_t code); bool maybeVisitDataDrop(Expression*& out, uint32_t code); bool maybeVisitMemoryCopy(Expression*& out, uint32_t code); bool maybeVisitMemoryFill(Expression*& out, uint32_t code); bool maybeVisitTableSize(Expression*& out, uint32_t code); bool maybeVisitTableGrow(Expression*& out, uint32_t code); bool maybeVisitI31New(Expression*& out, uint32_t code); bool maybeVisitI31Get(Expression*& out, uint32_t code); bool maybeVisitRefTest(Expression*& out, uint32_t code); bool maybeVisitRefCast(Expression*& out, uint32_t code); bool maybeVisitBrOn(Expression*& out, uint32_t code); bool maybeVisitStructNew(Expression*& out, uint32_t code); bool maybeVisitStructGet(Expression*& out, uint32_t code); bool maybeVisitStructSet(Expression*& out, uint32_t code); bool maybeVisitArrayNew(Expression*& out, uint32_t code); bool maybeVisitArrayNewSeg(Expression*& out, uint32_t code); bool maybeVisitArrayInit(Expression*& out, uint32_t code); bool maybeVisitArrayGet(Expression*& out, uint32_t code); bool maybeVisitArraySet(Expression*& out, uint32_t code); bool maybeVisitArrayLen(Expression*& out, uint32_t code); bool maybeVisitArrayCopy(Expression*& out, uint32_t code); bool maybeVisitStringNew(Expression*& out, uint32_t code); bool maybeVisitStringConst(Expression*& out, uint32_t code); bool maybeVisitStringMeasure(Expression*& out, uint32_t code); bool maybeVisitStringEncode(Expression*& out, uint32_t code); bool maybeVisitStringConcat(Expression*& out, uint32_t code); bool maybeVisitStringEq(Expression*& out, uint32_t code); bool maybeVisitStringAs(Expression*& out, uint32_t code); bool maybeVisitStringWTF8Advance(Expression*& out, uint32_t code); bool maybeVisitStringWTF16Get(Expression*& out, uint32_t code); bool maybeVisitStringIterNext(Expression*& out, uint32_t code); bool maybeVisitStringIterMove(Expression*& out, uint32_t code); bool maybeVisitStringSliceWTF(Expression*& out, uint32_t code); bool maybeVisitStringSliceIter(Expression*& out, uint32_t code); void visitSelect(Select* curr, uint8_t code); void visitReturn(Return* curr); void visitMemorySize(MemorySize* curr); void visitMemoryGrow(MemoryGrow* curr); void visitNop(Nop* curr); void visitUnreachable(Unreachable* curr); void visitDrop(Drop* curr); void visitRefNull(RefNull* curr); void visitRefIs(RefIs* curr, uint8_t code); void visitRefFunc(RefFunc* curr); void visitRefEq(RefEq* curr); void visitTableGet(TableGet* curr); void visitTableSet(TableSet* curr); void visitTryOrTryInBlock(Expression*& out); void visitThrow(Throw* curr); void visitRethrow(Rethrow* curr); void visitCallRef(CallRef* curr); void visitRefAs(RefAs* curr, uint8_t code); [[noreturn]] void throwError(std::string text); // Struct/Array instructions have an unnecessary heap type that is just for // validation (except for the case of unreachability, but that's not a problem // anyhow, we can ignore it there). That is, we also have a reference typed // child from which we can infer the type anyhow, and we just need to check // that type is the same. void validateHeapTypeUsingChild(Expression* child, HeapType heapType); private: bool hasDWARFSections(); }; } // namespace wasm #undef DEBUG_TYPE #endif // wasm_wasm_binary_h
/* * Copyright 2015 WebAssembly Community Group participants * * 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. */
block_header.mli
type shell_header = { level : Int32.t; (** Height of the block, from the genesis block. *) proto_level : int; (** Number (uint8) of protocol changes since genesis modulo 256. *) predecessor : Block_hash.t; (** Hash of the preceding block. *) timestamp : Time.t; (** Timestamp at which the block is claimed to have been created. *) validation_passes : int; (** Number (uint8) of validation passes (also number of lists of operations). *) operations_hash : Operation_list_list_hash.t; (** Hash of the list of lists (actually root hashes of merkle trees) of operations included in the block. There is one list of operations per validation pass. *) fitness : Bytes.t list; (** A sequence of sequences of unsigned bytes, ordered by length and then lexicographically. It represents the claimed fitness of the chain ending in this block. *) context : Context_hash.t; (** Hash of the state of the context after application of this block. *) } val shell_header_encoding : shell_header Data_encoding.t type t = {shell : shell_header; protocol_data : bytes} include S.HASHABLE with type t := t and type hash := Block_hash.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. *) (* *) (*****************************************************************************)
dune
; This file was automatically generated, do not edit. ; Edit file manifest/main.ml instead. (library (name tezos_protocol_010_PtGRANAD_parameters) (public_name tezos-protocol-010-PtGRANAD-parameters) (instrumentation (backend bisect_ppx)) (libraries tezos-base tezos-protocol-environment tezos-protocol-010-PtGRANAD) (library_flags (:standard -linkall)) (flags (:standard -open Tezos_base.TzPervasives -open Tezos_protocol_010_PtGRANAD)) (modules (:standard \ gen))) (executable (name gen) (libraries tezos-base tezos-protocol-010-PtGRANAD-parameters) (link_flags (:standard -linkall)) (flags (:standard -open Tezos_base.TzPervasives -open Tezos_protocol_010_PtGRANAD_parameters)) (modules gen)) (rule (targets sandbox-parameters.json) (deps gen.exe) (action (run %{deps} --sandbox))) (rule (targets test-parameters.json) (deps gen.exe) (action (run %{deps} --test))) (rule (targets mainnet-parameters.json) (deps gen.exe) (action (run %{deps} --mainnet))) (install (section lib) (files sandbox-parameters.json test-parameters.json mainnet-parameters.json))
t-unity_zp_sqr3.c
#include <stdio.h> #include <stdlib.h> #include <gmp.h> #include "flint.h" #include "aprcl.h" int main(void) { int i, j; fmpz_t * t; FLINT_TEST_INIT(state); flint_printf("unity_zp_sqr3...."); fflush(stdout); t = (fmpz_t*) flint_malloc(sizeof(fmpz_t) * (SQUARING_SPACE)); for (i = 0; i < SQUARING_SPACE; i++) fmpz_init(t[i]); /* test squaring in Z[\zeta_3] */ for (i = 0; i < 10 * flint_test_multiplier(); i++) { ulong p; fmpz_t n; unity_zp f, g, temp; p = 3; fmpz_init(n); fmpz_randtest_unsigned(n, state, 200); while (fmpz_equal_ui(n, 0) != 0) fmpz_randtest_unsigned(n, state, 200); unity_zp_init(f, p, 1, n); unity_zp_init(g, p, 1, n); unity_zp_init(temp, p, 1, n); for (j = 0; j < 100; j++) { ulong ind; fmpz_t val; fmpz_init(val); ind = n_randint(state, p); fmpz_randtest_unsigned(val, state, 200); unity_zp_coeff_set_fmpz(temp, ind, val); fmpz_clear(val); } _unity_zp_reduce_cyclotomic(temp); unity_zp_sqr3(f, temp, t); unity_zp_sqr(g, temp); if (unity_zp_equal(f, g) == 0) { flint_printf("FAIL\n"); fflush(stdout); flint_abort(); } fmpz_clear(n); unity_zp_clear(f); unity_zp_clear(g); unity_zp_clear(temp); } /* test squaring in Z[\zeta_9] */ for (i = 0; i < 10 * flint_test_multiplier(); i++) { ulong p, k; fmpz_t n; unity_zp f, g, temp; p = 3; k = 2; fmpz_init(n); fmpz_randtest_unsigned(n, state, 200); while (fmpz_equal_ui(n, 0) != 0) fmpz_randtest_unsigned(n, state, 200); unity_zp_init(f, p, k, n); unity_zp_init(g, p, k, n); unity_zp_init(temp, p, k, n); for (j = 0; j < 100; j++) { ulong ind; fmpz_t val; fmpz_init(val); ind = n_randint(state, n_pow(p, k)); fmpz_randtest_unsigned(val, state, 200); unity_zp_coeff_set_fmpz(temp, ind, val); fmpz_clear(val); } _unity_zp_reduce_cyclotomic(temp); unity_zp_sqr9(f, temp, t); unity_zp_sqr(g, temp); if (unity_zp_equal(f, g) == 0) { flint_printf("FAIL\n"); fflush(stdout); flint_abort(); } fmpz_clear(n); unity_zp_clear(f); unity_zp_clear(g); unity_zp_clear(temp); } for (i = 0; i < SQUARING_SPACE; i++) fmpz_clear(t[i]); flint_free(t); FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
/* Copyright (C) 2015 Vladimir Glazachev 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/>. */
setup_oss.enabled.ml
let is_set = true
s.mli
(** Generic interface for a datatype with comparison, pretty-printer and serialization functions. *) module type T = sig type t include Compare.S with type t := t val pp : Format.formatter -> t -> unit val encoding : t Data_encoding.t val to_bytes : t -> bytes val of_bytes : bytes -> t option end (** Generic interface for a datatype with comparison, pretty-printer, serialization functions and a hashing function. *) module type HASHABLE = sig include T type hash val hash : t -> hash val hash_raw : bytes -> hash end (** {2 Hash Types} *) (** The signature of an abstract hash type, as produced by functor {!Make_SHA256}. The {!t} type is abstracted for separating the various kinds of hashes in the system at typing time. Each type is equipped with functions to use it as is of as keys in the database or in memory sets and maps. *) module type MINIMAL_HASH = sig type t val name : string val title : string val pp : Format.formatter -> t -> unit val pp_short : Format.formatter -> t -> unit include Compare.S with type t := t val hash_bytes : ?key:bytes -> bytes list -> t val hash_string : ?key:string -> string list -> t val zero : t end module type RAW_DATA = sig type t val size : int (* in bytes *) val to_bytes : t -> bytes val of_bytes_opt : bytes -> t option val of_bytes_exn : bytes -> t end module type B58_DATA = sig type t val to_b58check : t -> string val to_short_b58check : t -> string val of_b58check_exn : string -> t val of_b58check_opt : string -> t option type Base58.data += Data of t val b58check_encoding : t Base58.encoding end module type ENCODER = sig type t val encoding : t Data_encoding.t val rpc_arg : t RPC_arg.t end module type INDEXES_SET = sig include Set.S val random_elt : t -> elt val encoding : t Data_encoding.t end module type INDEXES_MAP = sig include Map.S val encoding : 'a Data_encoding.t -> 'a t Data_encoding.t end module type INDEXES = sig type t module Set : INDEXES_SET with type elt = t module Map : INDEXES_MAP with type key = t end module type HASH = sig include MINIMAL_HASH include RAW_DATA with type t := t include B58_DATA with type t := t include ENCODER with type t := t include INDEXES with type t := t end module type MERKLE_TREE = sig type elt include HASH val compute : elt list -> t val empty : t type path = Left of path * t | Right of t * path | Op val compute_path : elt list -> int -> path val check_path : path -> elt -> t * int val path_encoding : path Data_encoding.t end module type SIGNATURE_PUBLIC_KEY_HASH = sig type t val pp : Format.formatter -> t -> unit val pp_short : Format.formatter -> t -> unit include Compare.S with type t := t include RAW_DATA with type t := t include B58_DATA with type t := t include ENCODER with type t := t include INDEXES with type t := t val zero : t end module type SIGNATURE_PUBLIC_KEY = sig type t val pp : Format.formatter -> t -> unit include Compare.S with type t := t include B58_DATA with type t := t include ENCODER with type t := t type public_key_hash_t val hash : t -> public_key_hash_t val size : t -> int (* in bytes *) val of_bytes_without_validation : bytes -> t option end module type SIGNATURE = sig module Public_key_hash : SIGNATURE_PUBLIC_KEY_HASH module Public_key : SIGNATURE_PUBLIC_KEY with type public_key_hash_t := Public_key_hash.t type t val pp : Format.formatter -> t -> unit include RAW_DATA with type t := t include Compare.S with type t := t include B58_DATA with type t := t include ENCODER with type t := t val zero : t type watermark (** Check a signature *) val check : ?watermark:watermark -> Public_key.t -> t -> bytes -> bool end module type FIELD = sig type t (** The order of the finite field *) val order : Z.t (** minimal number of bytes required to encode a value of the field. *) val size_in_bytes : int (** [check_bytes bs] returns [true] if [bs] is a correct byte representation of a field element *) val check_bytes : Bytes.t -> bool (** The neutral element for the addition *) val zero : t (** The neutral element for the multiplication *) val one : t (** [add a b] returns [a + b mod order] *) val add : t -> t -> t (** [mul a b] returns [a * b mod order] *) val mul : t -> t -> t (** [eq a b] returns [true] if [a = b mod order], else [false] *) val eq : t -> t -> bool (** [negate x] returns [-x mod order]. Equivalently, [negate x] returns the unique [y] such that [x + y mod order = 0] *) val negate : t -> t (** [inverse_opt x] returns [x^-1] if [x] is not [0] as an option, else [None] *) val inverse_opt : t -> t option (** [pow x n] returns [x^n] *) val pow : t -> Z.t -> t (** From a predefined bytes representation, construct a value t. It is not required that to_bytes [(Option.get (of_bytes_opt t)) = t]. By default, little endian encoding is used and the given element is modulo the prime order *) val of_bytes_opt : Bytes.t -> t option (** Convert the value t to a bytes representation which can be used for hashing for instance. It is not required that [to_bytes (Option.get (of_bytes_opt t)) = t]. By default, little endian encoding is used, and length of the resulting bytes may vary depending on the order. *) val to_bytes : t -> Bytes.t end (** Module type for the prime fields GF(p) *) module type PRIME_FIELD = sig include FIELD (** [of_z x] builds an element t from the Zarith element [x]. [mod order] is applied if [x >= order] or [x < 0]. *) val of_z : Z.t -> t (** [to_z x] builds a Zarith element, using the decimal representation. Arithmetic on the result can be done using the modular functions on integers *) val to_z : t -> Z.t end module type CURVE = sig (** The type of the element in the elliptic curve *) type t (** The size of a point representation, in bytes *) val size_in_bytes : int module Scalar : FIELD (** 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 *) val of_bytes_opt : Bytes.t -> t option (** Return a representation in bytes *) val to_bytes : t -> Bytes.t (** Zero of the elliptic curve *) val zero : t (** A fixed generator of the elliptic curve *) val one : t (** Return the addition of two element *) val add : t -> t -> t (** Double the element *) 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 end module type PAIRING = sig module Gt : FIELD module G1 : CURVE module G2 : CURVE val miller_loop : (G1.t * G2.t) list -> Gt.t val final_exponentiation_opt : Gt.t -> Gt.t option val pairing : G1.t -> G2.t -> Gt.t end
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
test_priority.ml
open H2__ open Test_common module Scheduler = Server_connection.Scheduler let pp_priority fmt { Priority.weight; stream_dependency; exclusive } = Format.fprintf fmt "Weight: %d; Parent: %ld; Exclusive: %B" weight stream_dependency exclusive let priority = Alcotest.of_pp pp_priority let node = (module struct open Scheduler.PriorityTreeNode type t = parent let pp formatter (Parent t) = Format.pp_print_text formatter (Scheduler.stream_id t |> Int32.to_string) let equal (Parent h1) (Parent h2) = Stream_identifier.(Scheduler.(stream_id h1) === Scheduler.(stream_id h2)) end : Alcotest.TESTABLE with type t = Scheduler.PriorityTreeNode.parent) let default_error_handler ?request:_ _err _handle = () let new_p w = { Priority.exclusive = false; stream_dependency = 0l; weight = w } let test_reqd stream_id = Stream.create ~max_frame_size:Config.default.read_buffer_size stream_id Serialize.Writer.(create 0x400) default_error_handler (fun ~active:_ _ -> ()) let repeat (Scheduler.PriorityTreeNode.Connection root) queue num = let rec loop q n acc = if n = 0 then acc else match Scheduler.PriorityQueue.pop q with | None -> failwith "invalid queue" | Some ((k, (Scheduler.Stream p as p_node)), q') -> (* simulate writing 100 bytes *) root.t_last <- p.t; Scheduler.update_t p_node 100; loop (Scheduler.PriorityQueue.add k p_node q') (n - 1) (k :: acc) in loop queue num [] let add_stream root ?(priority = Priority.default_priority) reqd = ignore @@ Scheduler.add root ~priority ~initial_recv_window_size:Settings.WindowSize.default_initial_window_size ~initial_send_window_size:Settings.WindowSize.default_initial_window_size reqd let test_priority_queue () = let root = Scheduler.make_root ~capacity:1000 () in add_stream root ~priority:(new_p 201) (test_reqd 1l); add_stream root ~priority:(new_p 101) (test_reqd 3l); add_stream root ~priority:(new_p 1) (test_reqd 5l); let q = Scheduler.children root in Alcotest.(check bool) "Check if empty" false (Scheduler.PriorityQueue.is_empty q); let t = repeat root q 1000 in let count_1 = List.filter (fun x -> x = 1l) t |> List.length in let count_3 = List.filter (fun x -> x = 3l) t |> List.length in let count_5 = List.filter (fun x -> x = 5l) t |> List.length in (* After multiple repetitions, the frequency of 1, 3 and 5 is proportional to * their weight, e.g. 101 * 1000 / 303 *) Alcotest.(check int) "Number of items with weight 201" 663 count_1; Alcotest.(check int) "Number of items with weight 101" 333 count_3; Alcotest.(check int) "Number of items with weight 1" 4 count_5 let test_reprioritize () = let open Scheduler in let root = Scheduler.make_root ~capacity:5 () in add_stream root (test_reqd 1l); add_stream root (test_reqd 3l); add_stream root (test_reqd 5l); (* change the weight of stream 1 *) let new_priority = { Priority.default_priority with weight = 100 } in let (Stream stream1 as stream1_node) = Scheduler.get_node root 1l |> opt_exn in Scheduler.reprioritize_stream root ~priority:new_priority stream1_node; Alcotest.check priority "Stream 1 changed weight" new_priority stream1.priority; let (Stream stream3) = Scheduler.get_node root 3l |> opt_exn in Alcotest.check priority "Stream 3 still has default weight" Priority.default_priority stream3.priority; (* Add stream 7 that depends on 1 *) let stream7 = test_reqd 7l in let stream7_priority = { Priority.default_priority with stream_dependency = 1l } in add_stream root ~priority:stream7_priority stream7; let (Stream stream7) = Scheduler.get_node root 7l |> opt_exn in Alcotest.check priority "Stream 7 depends on stream 1" stream7_priority stream7.priority; Alcotest.check node "Stream 7 depends on stream 1" (Parent stream1_node) stream7.parent; let _, Stream stream1_first_child = stream1.children |> PriorityQueue.to_list |> List.hd in Alcotest.(check bool) "Stream 1 has stream 7 in its children" false (PriorityQueue.is_empty stream1.children); Alcotest.(check int32) "Stream 1 has stream 7 in its children" 7l stream1_first_child.descriptor.id; Alcotest.(check int) "Root still has 3 children" 3 (PriorityQueue.size (Scheduler.children root)) let test_reprioritize_exclusive () = let open Scheduler in let root = Scheduler.make_root ~capacity:5 () in add_stream root (test_reqd 1l); add_stream root (test_reqd 3l); add_stream root (test_reqd 5l); (* Add stream 7 that exclusively depends on 0 *) let stream7 = test_reqd 7l in let stream7_priority = { Priority.default_priority with stream_dependency = 0l; exclusive = true } in add_stream root ~priority:stream7_priority stream7; let (Stream stream7 as stream7_node) = Scheduler.get_node root 7l |> opt_exn in Alcotest.check priority "Stream 7 depends on stream 0" stream7_priority stream7.priority; Alcotest.check node "Stream 7 depends on stream 0" (Parent root) stream7.parent; let root_children = Scheduler.children root |> PriorityQueue.to_list in let _, Stream root_first_child = List.hd root_children in Alcotest.(check int32) "Stream 0 has a single child, stream 7" 7l root_first_child.descriptor.id; Alcotest.(check int) "Stream 0 has a single child, stream 7" 1 (List.length root_children); let (Stream stream1) = Scheduler.get_node root 1l |> opt_exn in Alcotest.check node "Stream 1's parent is now stream 7" (Parent stream7_node) stream1.parent; Alcotest.(check int) "Stream 7 has 3 children" 3 (PriorityQueue.size stream7.children) let depend_on stream_id = { Priority.default_priority with stream_dependency = stream_id } let set_up_dep_tree root = add_stream root (test_reqd 1l); add_stream root ~priority:(depend_on 1l) (test_reqd 3l); add_stream root ~priority:(depend_on 1l) (test_reqd 5l); add_stream root ~priority:(depend_on 5l) (test_reqd 7l); add_stream root ~priority:(depend_on 5l) (test_reqd 9l); add_stream root ~priority:(depend_on 7l) (test_reqd 11l) (* * This is the tree from: https://tools.ietf.org/html/rfc7540#section-5.3.3 * * 1 --> 7 * 0 0 * | | * 1 7 * / \ / \ * 3 5 ==> 11 1 * / \ / \ * 7 9 3 5 * | | * 11 9 * * (non-exclusive) *) let test_reprioritize_to_dependency () = let open Scheduler in let root = Scheduler.make_root ~capacity:6 () in set_up_dep_tree root; let (Stream stream1 as stream1_node) = Scheduler.get_node root 1l |> opt_exn in let stream5_node = Scheduler.get_node root 5l |> opt_exn in let (Stream stream7 as stream7_node) = Scheduler.get_node root 7l |> opt_exn in Alcotest.check node "Stream 7 depends on stream 5" (Parent stream5_node) stream7.parent; let root_children = Scheduler.children root |> PriorityQueue.to_list in let _, Stream root_first_child = List.hd root_children in Alcotest.(check int32) "Stream 0 has a single child, stream 1" 1l root_first_child.descriptor.id; Alcotest.(check int) "Stream 0 has a single child, stream 7" 1 (List.length root_children); (* reprioritize stream 1 to have 7 as the new parent *) reprioritize_stream root ~priority:(depend_on 7l) stream1_node; Alcotest.check node "Stream 1's parent is now stream 7" (Parent stream7_node) stream1.parent; Alcotest.check node "Stream 7's parent is now stream 0" (Parent root) stream7.parent; Alcotest.(check int) "Stream 7 has 2 children" 2 (PriorityQueue.size stream7.children); Alcotest.(check (list int32)) "Stream 7 has 2 children, 11 and 1" [ 1l; 11l ] (stream7.children |> PriorityQueue.to_list |> List.map fst) (* * This is the tree from: https://tools.ietf.org/html/rfc7540#section-5.3.3 * * 1 --> 7 * 0 0 * | | * 1 7 * / \ | * 3 5 ==> 1 * / \ /|\ * 7 9 3 5 11 * | | * 11 9 * * (exclusive) *) let test_reprioritize_to_dependency_exclusive () = let open Scheduler in let root = Scheduler.make_root ~capacity:6 () in set_up_dep_tree root; let stream5_node = Scheduler.get_node root 5l |> opt_exn in let (Stream stream7 as stream7_node) = Scheduler.get_node root 7l |> opt_exn in Alcotest.check node "Stream 7 depends on stream 5" (Parent stream5_node) stream7.parent; let root_children = Scheduler.children root |> PriorityQueue.to_list in let _, Stream root_first_child = List.hd root_children in Alcotest.(check int32) "Stream 0 has a single child, stream 1" 1l root_first_child.descriptor.id; Alcotest.(check int) "Stream 0 has a single child, stream 7" 1 (List.length root_children); (* reprioritize stream 1 to have 7 as the new parent with exclusive priority *) let (Stream stream1 as stream1_node) = Scheduler.get_node root 1l |> opt_exn in reprioritize_stream root ~priority: { Priority.default_priority with stream_dependency = 7l ; exclusive = true } stream1_node; Alcotest.check node "Stream 1's parent is now stream 7" (Parent stream7_node) stream1.parent; Alcotest.check node "Stream 7's parent is now stream 0" (Parent root) stream7.parent; Alcotest.(check int) "Stream 7 has a single child" 1 (PriorityQueue.size stream7.children); Alcotest.(check (list int32)) "Stream 7 has a single child 1" [ 1l ] (stream7.children |> PriorityQueue.to_list |> List.map fst); Alcotest.(check (list int32)) "Stream 11 is now a child of stream 1" [ 3l; 5l; 11l ] (stream1.children |> PriorityQueue.to_list |> List.map fst) let priority_queue_tests = [ "Priority queue tests", `Quick, test_priority_queue ] let reprioritization_tests = [ "Reprioritize simple", `Quick, test_reprioritize ; "Reprioritize simple exclusive", `Quick, test_reprioritize_exclusive ; "Reprioritize to dependency", `Quick, test_reprioritize_to_dependency ; ( "Reprioritize to dependency exclusive" , `Quick , test_reprioritize_to_dependency_exclusive ) ] let () = Alcotest.run "httpaf unit tests" [ "Reprioritization tests", reprioritization_tests ; "Priority_Queue_Tests", priority_queue_tests ]
contents.mli
(** Values. *) include Contents_intf.Sigs (** @inline *)
(* * Copyright (c) 2013-2022 Thomas Gazagnaire <thomas@gazagnaire.org> * * 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. *)
path.mli
(* $Id: path.mli 5640 2003-07-01 13:05:43Z xleroy $ *) (* Access paths *) type t = Pident of Ident.t | Pdot of t * string * int | Papply of t * t val same: t -> t -> bool val isfree: Ident.t -> t -> bool val binding_time: t -> int val nopos: int val name: t -> string val head: t -> Ident.t
(***********************************************************************) (* *) (* Objective Caml *) (* *) (* 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 Q Public License version 1.0. *) (* *) (***********************************************************************)
script_interpreter.mli
(** This is the Michelson interpreter. This module offers a way to execute either a Michelson script or a Michelson instruction. Implementation details are documented in the .ml file. *) open Alpha_context open Script_typed_ir type error += Reject of Script.location * Script.expr * execution_trace option type error += Overflow of Script.location * execution_trace option type error += Runtime_contract_error of Contract_hash.t type error += Bad_contract_parameter of Contract.t (* `Permanent *) type error += Cannot_serialize_failure type error += Cannot_serialize_storage type error += Michelson_too_many_recursive_calls (** The result from script interpretation. *) type execution_result = { script : Script_ir_translator.ex_script; code_size : int; storage : Script.expr; lazy_storage_diff : Lazy_storage.diffs option; operations : packed_internal_operation list; ticket_diffs : Z.t Ticket_token_map.t; } type step_constants = Script_typed_ir.step_constants = { source : Contract.t; payer : Contract.t; self : Contract_hash.t; amount : Tez.t; balance : Tez.t; chain_id : Chain_id.t; now : Script_timestamp.t; level : Script_int.n Script_int.num; } (** [execute ?logger ctxt ~cached_script mode step_constant ~script ~entrypoint ~parameter ~internal] interprets the [script]'s [entrypoint] for a given [parameter]. This will update the local storage of the contract [step_constants.self]. Other pieces of contextual information ([source], [payer], [amount], and [chaind_id]) are also passed in [step_constant]. [internal] is [true] if and only if the execution happens within an internal operation. [mode] is the unparsing mode, as declared by {!Script_ir_translator}. [cached_script] is the cached elaboration of [script], that is the well typed abstract syntax tree produced by the type elaboration of [script] during a previous execution and stored in the in-memory cache. *) val execute : ?logger:logger -> Alpha_context.t -> cached_script:Script_ir_translator.ex_script option -> Script_ir_translator.unparsing_mode -> step_constants -> script:Script.t -> entrypoint:Entrypoint.t -> parameter:Script.expr -> internal:bool -> (execution_result * context) tzresult Lwt.t (** [execute_with_typed_parameter ?logger ctxt ~cached_script mode step_constant ~script ~entrypoint loc ~parameter_ty ~parameter ~internal] interprets the [script]'s [entrypoint] for a given (typed) [parameter]. See {!execute} for more details about the function's arguments. *) val execute_with_typed_parameter : ?logger:logger -> Alpha_context.context -> cached_script:Script_ir_translator.ex_script option -> Script_ir_translator.unparsing_mode -> step_constants -> script:Script.t -> entrypoint:Entrypoint.t -> parameter_ty:('a, _) Script_typed_ir.ty -> location:Script.location -> parameter:'a -> internal:bool -> (execution_result * context) tzresult Lwt.t (** Internal interpretation loop ============================ The following types and the following functions are exposed in the interface to allow the inference of a gas model in snoop. Strictly speaking, they should not be considered as part of the interface since they expose implementation details that may change in the future. *) module Internals : sig (** Internally, the interpretation loop uses a local gas counter. *) (** [next logger (ctxt, step_constants) local_gas_counter ks accu stack] is an internal function which interprets the continuation [ks] to execute the interpreter on the current A-stack. *) val next : logger option -> Local_gas_counter.outdated_context * step_constants -> Local_gas_counter.local_gas_counter -> ('a, 's) stack_ty -> ('a, 's, 'r, 'f) continuation -> 'a -> 's -> ('r * 'f * Local_gas_counter.outdated_context * Local_gas_counter.local_gas_counter) tzresult Lwt.t val step : Local_gas_counter.outdated_context * step_constants -> Local_gas_counter.local_gas_counter -> ('a, 's, 'r, 'f) Script_typed_ir.kinstr -> 'a -> 's -> ('r * 'f * Local_gas_counter.outdated_context * Local_gas_counter.local_gas_counter) tzresult Lwt.t val step_descr : logger option -> context -> Script_typed_ir.step_constants -> ('a, 's, 'r, 'f) Script_typed_ir.kdescr -> 'a -> 's -> ('r * 'f * context) tzresult Lwt.t (** [kstep logger ctxt step_constants kinstr accu stack] interprets the script represented by [kinstr] under the context [ctxt]. This will turn a stack whose topmost element is [accu] and remaining elements [stack] into a new accumulator and a new stack. This function also returns an updated context. If [logger] is given, [kstep] calls back its functions at specific points of the execution. The execution is parameterized by some [step_constants]. *) val kstep : logger option -> context -> step_constants -> ('a, 's) stack_ty -> ('a, 's, 'r, 'f) Script_typed_ir.kinstr -> 'a -> 's -> ('r * 'f * context) tzresult Lwt.t end
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* 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. *) (* *) (*****************************************************************************)
pow_rmul.c
#include "fmpz_mod_mpoly.h" void fmpz_mod_mpoly_pow_rmul(fmpz_mod_mpoly_t A, const fmpz_mod_mpoly_t B, ulong k, const fmpz_mod_mpoly_ctx_t ctx) { fmpz_mod_mpoly_t T; fmpz_mod_mpoly_init(T, ctx); if (A == B) { fmpz_mod_mpoly_pow_rmul(T, A, k, ctx); fmpz_mod_mpoly_swap(T, A, ctx); goto cleanup; } fmpz_mod_mpoly_one(A, ctx); while (k >= 1) { fmpz_mod_mpoly_mul(T, A, B, ctx); fmpz_mod_mpoly_swap(A, T, ctx); k -= 1; } cleanup: fmpz_mod_mpoly_clear(T, ctx); }
/* Copyright (C) 2019 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/>. */
Tests.ml
open Cps_toolbox open Typeset open Spec open EDSL let _normal_form layout = let rec _spine layout = match layout with | Null | Text _ -> true | Seq layout1 | Grp layout1 | Fix layout1 | Nest layout1 | Pack (_, layout1) -> _term layout1 | Line (left, right) -> (_term left) && (_spine right) | Comp (left, right, _pad, _fix) -> (_term left) && (_term right) and _term layout = match layout with | Null | Text _ -> true | Seq layout1 | Grp layout1 | Nest layout1 | Fix layout1 | Pack (_, layout1) -> _term layout1 | Line _ -> false | Comp (left, right, _pad, _fix) -> (_term left) && (_term right) in _spine layout let _num_critical_comps tab marks layout return = let _fail () = assert false (* Invariant *) in let rec _visit head pos marks layout result return = let _insert = Map.insert Order.int in let _lookup = Map.lookup Order.int in match layout with | Null -> return result pos marks | Text data -> return result (pos + String.length data) marks | Fix layout1 -> _visit_fix head pos marks layout1 (return result) | Seq layout1 | Grp layout1 -> _visit head pos marks layout1 result return | Nest layout1 -> if head then _visit true (pos + tab) marks layout1 result return else _visit false pos marks layout1 result return | Pack (index, layout1) -> _lookup index marks (fun _ -> _insert index pos marks |> fun marks1 -> _visit head pos marks1 layout1 result return) (fun pos1 -> _visit head (max pos pos1) marks layout1 result return) | Line (left, right) -> _visit head pos marks left result @@ fun result1 _pos1 marks1 -> _visit true 0 marks1 right result1 return | Comp (left, right, pad, _fix) -> _visit head pos marks left result @@ fun result1 pos1 marks1 -> let pos2 = if pad then pos1 + 1 else pos1 in _visit false pos2 marks1 right result1 @@ fun result2 pos3 marks2 -> if 0 < pos2 then return result2 pos3 marks2 else if 0 < pos3 - pos2 then return result2 pos3 marks2 else return (result2 + 1) pos3 marks2 and _visit_fix head pos marks layout return = let _insert = Map.insert Order.int in let _lookup = Map.lookup Order.int in match layout with | Null -> return pos marks | Text data -> return (pos + (String.length data)) marks | Fix layout1 | Seq layout1 | Grp layout1 -> _visit_fix head pos marks layout1 return | Nest layout1 -> if head then _visit_fix true (pos + tab) marks layout1 return else _visit_fix false pos marks layout1 return | Pack (index, layout1) -> _lookup index marks (fun _ -> _insert index pos marks |> fun marks1 -> _visit_fix head pos marks1 layout1 return) (fun pos1 -> _visit_fix head (max pos pos1) marks layout1 return) | Line (left, _right) -> _visit_fix head pos marks left return | Comp (left, right, pad, _fix) -> _visit_fix head pos marks left @@ fun pos1 marks1 -> let pos2 = if pad then pos1 + 1 else pos1 in _visit_fix false pos2 marks1 right return in _visit true 0 marks layout 0 @@ fun result _pos _marks -> return result let _num_lines layout return = let rec _visit layout result return = match layout with | Null | Text _ -> return result | Fix layout1 | Seq layout1 | Grp layout1 | Nest layout1 | Pack (_, layout1) -> _visit layout1 result return | Line (left, right) -> _visit left result @@ fun result1 -> _visit right (result1 + 1) return | Comp (left, right, _pad, _fix) -> _visit left result @@ fun result1 -> _visit right result1 return in _visit layout 1 return let _solved_form tab width layout = let _fail () = assert false (* Invariant *) in let _cont k n m1 x m2 nxs = k m2 ((n, m1, x) :: nxs) in let rec _visit marks layout return = match layout with | Line (left, right) -> _measure true 0 marks left @@ fun marks1 length -> _visit marks1 right (_cont return length marks left) | _ -> _measure true 0 marks layout @@ fun marks1 length -> return marks1 [(length, marks, layout)] and _measure head pos marks layout return = let _insert = Map.insert Order.int in let _lookup = Map.lookup Order.int in match layout with | Null -> return marks 0 | Text data -> return marks (String.length data) | Fix layout1 | Seq layout1 | Grp layout1 -> _measure head pos marks layout1 return | Nest layout1 -> let pos1 = if head then pos + tab else pos in _measure head pos1 marks layout1 return | Pack (index, layout1) -> _lookup index marks (fun _ -> _insert index pos marks |> fun marks1 -> _measure head pos marks1 layout1 return) (fun pos1 -> let pos2 = max pos pos1 in _measure head pos2 marks layout1 return) | Line _ -> assert false (* Invariant *) | Comp (left, right, true, _fix) -> _measure head pos marks left @@ fun marks1 pos1 -> _measure false (pos1 + 1) marks1 right return | Comp (left, right, false, _fix) -> _measure head pos marks left @@ fun marks1 pos1 -> _measure false pos1 marks1 right return in let rec _check lines return = match lines with | [] -> return true | (length, marks, line) :: lines' -> if length <= width then _check lines' return else _num_critical_comps tab marks line @@ fun num_comps -> if 0 < num_comps then return false else _check lines' return in _visit Map.empty layout @@ fun _marks lines -> _check lines (fun result -> result) (* Define tests *) let spec_normalize_sound = QCheck.Test.make ~count:1024 ~name:"spec_normalize_sound" arbitrary_eDSL (fun eDSL -> Spec.convert eDSL |> fun layout -> Spec.pre_normalize layout |> fun layout1 -> _normal_form layout1) let spec_solve_sound = QCheck.Test.make ~count:1024 ~name:"spec_solve_sound" QCheck.(triple arbitrary_eDSL small_nat small_nat) (fun (eDSL, tab, width) -> Spec.convert eDSL |> fun layout -> Spec.solve layout tab width |> fun layout1 -> _solved_form tab width layout1) let _random_comp_tree x n = let open QCheck.Gen in let rec _visit n = if n <= 1 then return ~$x else int_bound (n - 2) >>= fun m -> let a = m + 1 in let b = n - a in map2 (fun l r -> l <&> r) (_visit a) (_visit b) in if n <= 0 then return Typeset.null else _visit n let spec_solve_box_reflow = QCheck.Test.make ~count:32 ~name:"spec_solve_box_reflow" QCheck.(pair small_nat small_nat) (fun (count, width) -> let eDSL = QCheck.Gen.generate1 (_random_comp_tree "x" count) in Spec.convert eDSL |> fun layout -> Spec.solve layout 0 width |> fun layout1 -> let expected_num_lines = let _count = max 1 count in if width <= 0 then _count else if 0 < (_count mod width) then (_count / width) + 1 else _count / width in _num_lines layout1 @@ fun actual_num_lines -> expected_num_lines = actual_num_lines) let impl_compile_normalizes = QCheck.Test.make ~count:2048 ~name:"impl_compile_normalizes" arbitrary_eDSL (fun eDSL -> Typeset.compile eDSL |> fun doc -> Spec.undoc doc |> fun layout -> Spec.pre_normalize layout |> fun layout1 -> if not (layout = layout1) then begin Spec.print_layout layout |> print_endline; print_endline "------------------------------------"; Spec.print_layout layout1 |> print_endline; print_endline "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"; false end else true) let impl_spec_normalize_identity = QCheck.Test.make ~count:1024 ~name:"impl_spec_normalize_identity" arbitrary_eDSL (fun eDSL -> Typeset.compile eDSL |> fun doc -> Spec.convert eDSL |> fun layout -> Spec.undoc doc |> fun impl_layout -> Spec.pre_normalize layout |> fun spec_layout -> if not (impl_layout = spec_layout) then begin Typeset.print doc |> print_endline; print_endline "------------------------------------"; Spec.print_layout spec_layout |> print_endline; print_endline "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"; false end else true) let impl_spec_render_identity = QCheck.Test.make ~count:1024 ~name:"impl_spec_render_identity" QCheck.(triple arbitrary_eDSL small_nat small_nat) (fun (eDSL, tab, width) -> Typeset.compile eDSL |> fun doc -> Typeset.render doc tab width |> fun output -> Spec.convert eDSL |> fun layout -> Spec.render layout tab width |> fun spec_output -> if not (output = spec_output) then begin Spec.undoc doc |> fun layout1 -> print_endline output; print_endline "------------------------------------"; print_endline spec_output; print_endline "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"; Spec.print_layout layout1 |> print_endline; false end else true) (* Run tests *) let _ = QCheck_runner.run_tests [ spec_normalize_sound ; spec_solve_sound ; spec_solve_box_reflow ; impl_compile_normalizes ; impl_spec_normalize_identity ; impl_spec_render_identity ]
parameters.h
#ifndef PARAMETERS_H #define PARAMETERS_H //have to pass one of these in as a macro //#define VDF_MODE 0 //used for the final submission and correctness testing //#define VDF_MODE 1 //used for performance or other testing //also have to pass in one of these //#define ENABLE_ALL_INSTRUCTIONS 1 //#define ENABLE_ALL_INSTRUCTIONS 0 // // //divide table const int divide_table_index_bits=11; const int gcd_num_quotient_bits=31; //excludes sign bit const int data_size=31; const int gcd_base_max_iter_divide_table=16; //continued fraction table const int gcd_table_num_exponent_bits=3; const int gcd_table_num_fraction_bits=7; const int gcd_base_max_iter=5; extern bool use_divide_table; extern int gcd_base_bits; extern int gcd_128_max_iter; extern std::string asmprefix; extern bool enable_all_instructions; bool bChecked=false; bool bAVX2=false; bool enable_avx512_ifma=false; #if defined(__i386) || defined(_M_IX86) #define ARCH_X86 #elif defined(__x86_64__) || defined(_M_X64) #define ARCH_X64 #elif (defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 5) || (defined(_M_ARM) && _M_ARM >= 5) || defined(__ARM_FEATURE_CLZ) /* ARM (Architecture Version 5) */ #define ARCH_ARM #endif #if defined(_WIN64) || defined(_LP64) || defined(__LP64__) #define ARCH_64BIT #else #define ARCH_32BIT #endif inline bool hasAVX2() { if(!bChecked) { bChecked=true; #if defined(ARCH_X86) || defined(ARCH_X64) int info[4] = {0}; #if defined(_MSC_VER) __cpuid(info, 0x7); #elif defined(__GNUC__) || defined(__clang__) #if defined(ARCH_X86) && defined(__PIC__) __asm__ __volatile__ ( "xchg{l} {%%}ebx, %k1;" "cpuid;" "xchg{l} {%%}ebx, %k1;" : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(0x7), "c"(0) ); #else __asm__ __volatile__ ( "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(0x7), "c"(0) ); #endif #endif const int AVX2 = 1<<5; const int ADX = 1<<19; bool avx2bit = ((info[1] & AVX2) == AVX2); bool adxbit = ((info[1] & ADX) == ADX); bAVX2 = avx2bit && adxbit; #elif defined(ARCH_ARM) bAVX2 = false; #else bAVX2 = false; #endif } return bAVX2; } /* divide_table_index bits 10 - 0m1.269s 11 - 0m1.261s 12 - 0m1.262s 13 - 0m1.341s **/ /* gcd_base_max_iter_divide_table 13 - 0m1.290s 14 - 0m1.275s 15 - 0m1.265s 16 - 0m1.261s 17 - 0m1.268s 18 - 0m1.278s 19 - 0m1.283s **/ /* 100k iterations; median of 3 runs. consistency between runs was very high effect of scheduler: taskset 0,1 : 0m1.352s (63% speedup single thread, 37% over 0,2) taskset 0,2 : 0m1.850s default : 0m1.348s (fastest) single threaded : 0m2.212s [this has gone down to 0m1.496s for some reason with the divide table] exponent fraction base_bits base_iter 128_iter seconds 3 7 50 5 3 0m1.350s [fastest with range checks enabled] 3 7 52 5 3 0m1.318s [range checks disabled; 2.4% faster] [this block with bmi and fma disabled] 3 7 46 5 3 0m1.426s 3 7 47 5 3 0m1.417s 3 7 48 5 3 0m1.421s 3 7 49 5 3 0m1.413s 3 7 50 5 3 0m1.401s [still fastest; bmi+fma is 3.8% faster] 3 7 51 5 3 0m1.406s 3 7 52 5 3 0m1.460s 3 7 50 6 3 0m1.416s 3 7 49 6 3 0m1.376s 2 8 45 6 3 0m1.590s 2 8 49 6 3 0m1.485s 2 8 51 6 3 0m1.479s 2 8 52 6 3 0m1.501s 2 8 53 6 3 0m1.531s 2 8 54 6 3 0m13.675s 2 8 55 6 3 0m13.648s 3 7 49 2 3 0m14.571s 3 7 49 3 3 0m1.597s 3 7 49 4 3 0m1.430s 3 7 49 5 3 0m1.348s 3 7 49 6 3 0m1.376s 3 7 49 10 3 0m1.485s 3 7 49 1 18 0m2.226s 3 7 49 2 10 0m1.756s 3 7 49 3 6 0m1.557s 3 7 49 4 4 0m1.388s 3 7 49 5 4 0m1.525s 3 7 49 6 3 0m1.377s 3 7 49 7 3 0m1.446s 3 7 49 8 2 0m1.503s 3 6 45 4 3 0m15.176s 3 7 45 4 3 0m1.443s 3 8 45 4 3 0m1.386s 3 9 45 4 3 0m1.355s 3 10 45 4 3 0m1.353s 3 11 45 4 3 0m1.419s 3 12 45 4 3 0m1.451s 3 13 45 4 3 0m1.584s 3 7 40 4 2 0m1.611s 3 8 40 4 2 0m1.570s 3 9 40 4 2 0m1.554s 3 10 40 4 2 0m1.594s 3 11 40 4 2 0m1.622s 3 12 40 4 2 0m1.674s 3 13 40 4 2 0m1.832s 3 7 48 5 3 0m1.358s 3 7 49 5 3 0m1.353s 3 7 50 5 3 0m1.350s 3 8 48 5 3 0m1.366s 3 8 49 5 3 0m1.349s 3 8 50 5 3 0m1.334s 3 9 48 5 3 0m1.370s 3 9 49 5 3 0m1.349s 3 9 50 5 3 0m1.346s 3 10 48 5 3 0m1.404s 3 10 49 5 3 0m1.382s 3 10 50 5 3 0m1.379s ***/ const uint64 max_spin_counter=10000000; //this value makes square_original not be called in 100k iterations. with every iteration reduced, minimum value is 1 const int num_extra_bits_ab=3; const bool calculate_k_repeated_mod=false; const bool calculate_k_repeated_mod_interval=1; const int validate_interval=1; //power of 2. will check the discriminant in the slave thread at this interval. -1 to disable. no effect on performance const int checkpoint_interval=10000; //at each checkpoint, the slave thread is restarted and the master thread calculates c //checkpoint_interval=100000: 39388 //checkpoint_interval=10000: 39249 cycles per fast iteration //checkpoint_interval=1000: 38939 //checkpoint_interval=100: 39988 //no effect on performance (with track cycles enabled) // ==== test ==== #if VDF_MODE==1 #define VDF_TEST const bool is_vdf_test=true; const bool enable_random_error_injection=false; const double random_error_injection_rate=0; //0 to 1 //#define GENERATE_ASM_TRACKING_DATA //#define ENABLE_TRACK_CYCLES const bool vdf_test_correctness=false; const bool enable_threads=true; #endif // ==== production ==== #if VDF_MODE==0 const bool is_vdf_test=false; const bool enable_random_error_injection=false; const double random_error_injection_rate=0; //0 to 1 const bool vdf_test_correctness=false; const bool enable_threads=true; //#define ENABLE_TRACK_CYCLES #endif // // //this doesn't do anything outside of test code //this doesn't work with the divide table currently #define TEST_ASM const int gcd_size=20; //multiple of 4. must be at least half the discriminant size in bits divided by 64 const int gcd_max_iterations=gcd_size*2; //typically 1 iteration per limb const int max_bits_base=1024; //half the discriminant number of bits, rounded up const int reduce_max_iterations=10000; const int num_asm_tracking_data=128; const int track_cycles_num_buckets=24; //each bucket is from 2^i to 2^(i+1) cycles const int track_cycles_max_num=128; void mark_vdf_test() { static bool did_warning=false; if (!is_vdf_test && !did_warning) { print( "test code enabled in production build" ); did_warning=true; } } // end Headerguard PARAMETERS_H #endif
int48_stubs.c
#include <stdint.h> #include <string.h> #include <caml/alloc.h> #include <caml/custom.h> #include <caml/fail.h> #include <caml/intext.h> #include <caml/memory.h> #include <caml/mlvalues.h> #include "int48.h" static const int64_t mask = 0xFFFFFFFFFFFF0000LL; CAMLprim value int48_mul(value v1, value v2) { CAMLparam2(v1, v2); CAMLreturn (copy_int48(Int48_val(v1) * Int64_val(v2))); } CAMLprim value int48_div(value v1, value v2) { CAMLparam2(v1, v2); int64_t divisor = Int64_val(v2); if (divisor == 0) caml_raise_zero_divide(); CAMLreturn (copy_int48((Int64_val(v1) / divisor) << 16)); } CAMLprim value int48_xor(value v1, value v2) { CAMLparam2(v1, v2); CAMLreturn (copy_int48((Int64_val(v1) ^ Int64_val(v2)) & mask)); } CAMLprim value int48_shift_right(value v1, value v2) { CAMLparam2(v1, v2); CAMLreturn (copy_int48((Int64_val(v1) >> Long_val(v2)) & mask)); } CAMLprim value int48_max_int(void) { CAMLparam0(); CAMLreturn (copy_int48(INT64_MAX & mask)); } CAMLprim value int48_min_int(void) { CAMLparam0(); CAMLreturn (copy_int48(INT64_MIN & mask)); }
micheline_parser.ml
open Error_monad open Micheline type 'a parsing_result = 'a * error list let compare compare (aa, ael) (ba, bel) = Compare.or_else (compare aa ba) (fun () -> (* FIXME: we need error comparison *) Stdlib.compare ael bel) type point = {point : int; byte : int; line : int; column : int} let point_zero = {point = 0; byte = 0; line = 0; column = 0} let point_encoding = let open Data_encoding in conv (fun {line; column; point; byte} -> (line, column, point, byte)) (fun (line, column, point, byte) -> {line; column; point; byte}) (obj4 (req "line" uint16) (req "column" uint16) (req "point" uint16) (req "byte" uint16)) type location = {start : point; stop : point} let location_zero = {start = point_zero; stop = point_zero} let location_encoding = let open Data_encoding in conv (fun {start; stop} -> (start, stop)) (fun (start, stop) -> {start; stop}) (obj2 (req "start" point_encoding) (req "stop" point_encoding)) type token_value = | String of string | Bytes of string | Int of string | Ident of string | Annot of string | Comment of string | Eol_comment of string | Semi | Open_paren | Close_paren | Open_brace | Close_brace let token_value_encoding = let open Data_encoding in union [ case (Tag 0) ~title:"String" (obj1 (req "string" string)) (function String s -> Some s | _ -> None) (fun s -> String s); case (Tag 1) ~title:"Int" (obj1 (req "int" string)) (function Int s -> Some s | _ -> None) (fun s -> Int s); case (Tag 2) ~title:"Annot" (obj1 (req "annot" string)) (function Annot s -> Some s | _ -> None) (fun s -> Annot s); case (Tag 3) ~title:"Comment" (obj2 (req "comment" string) (dft "end_of_line" bool false)) (function | Comment s -> Some (s, false) | Eol_comment s -> Some (s, true) | _ -> None) (function s, false -> Comment s | s, true -> Eol_comment s); case (Tag 4) ~title:"Punctuation" (obj1 (req "punctuation" (string_enum [ ("(", Open_paren); (")", Close_paren); ("{", Open_brace); ("}", Close_brace); (";", Semi); ]))) (fun t -> Some t) (fun t -> t); case (Tag 5) ~title:"Bytes" (obj1 (req "bytes" string)) (function Bytes s -> Some s | _ -> None) (fun s -> Bytes s); case (Tag 6) ~title:"Ident" (obj1 (req "ident" string)) (function Ident s -> Some s | _ -> None) (fun s -> Ident s); ] type token = {token : token_value; loc : location} let max_annot_length = 255 type error += Invalid_utf8_sequence of point * string type error += Unexpected_character of point * string type error += Undefined_escape_sequence of point * string type error += Missing_break_after_number of point type error += Unterminated_string of location type error += Unterminated_integer of location type error += Invalid_hex_bytes of location type error += Unterminated_comment of location type error += Annotation_length of location let tokenize source = let decoder = Uutf.decoder ~encoding:`UTF_8 (`String source) in let here () = { point = Uutf.decoder_count decoder; byte = Uutf.decoder_byte_count decoder; line = Uutf.decoder_line decoder; column = Uutf.decoder_col decoder; } in let tok start stop token = {loc = {start; stop}; token} in let stack = ref [] in let errors = ref [] in let rec next () = match !stack with | charloc :: charlocs -> stack := charlocs ; charloc | [] -> ( let loc = here () in match Uutf.decode decoder with | `Await -> assert false | `Malformed s -> errors := Invalid_utf8_sequence (loc, s) :: !errors ; next () | (`Uchar _ | `End) as other -> (other, loc)) in let back charloc = stack := charloc :: !stack in let uchar_to_char c = if Uchar.is_char c then Some (Uchar.to_char c) else None in let allowed_ident_char c = match uchar_to_char c with | Some ('a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9') -> true | Some _ | None -> false in let allowed_annot_char c = match uchar_to_char c with | Some ('a' .. 'z' | 'A' .. 'Z' | '_' | '.' | '%' | '@' | '0' .. '9') -> true | Some _ | None -> false in let rec skip acc = match next () with | `End, _ -> List.rev acc | `Uchar c, start -> ( match uchar_to_char c with | Some ('a' .. 'z' | 'A' .. 'Z') -> ident acc start (fun s _ -> Ident s) | Some ('@' | ':' | '$' | '&' | '%' | '!' | '?') -> annot acc start (fun str stop -> if String.length str > max_annot_length then errors := Annotation_length {start; stop} :: !errors ; Annot str) | Some '-' -> ( match next () with | `End, stop -> errors := Unterminated_integer {start; stop} :: !errors ; List.rev acc | (`Uchar c, stop) as first -> ( match uchar_to_char c with | Some '0' -> base acc start | Some '1' .. '9' -> integer acc start | Some _ | None -> errors := Unterminated_integer {start; stop} :: !errors ; back first ; skip acc)) | Some '0' -> base acc start | Some '1' .. '9' -> integer acc start | Some (' ' | '\n') -> skip acc | Some ';' -> skip (tok start (here ()) Semi :: acc) | Some '{' -> skip (tok start (here ()) Open_brace :: acc) | Some '}' -> skip (tok start (here ()) Close_brace :: acc) | Some '(' -> skip (tok start (here ()) Open_paren :: acc) | Some ')' -> skip (tok start (here ()) Close_paren :: acc) | Some '"' -> string acc [] start | Some '#' -> eol_comment acc start | Some '/' -> ( match next () with | `Uchar c, _ when Uchar.equal c (Uchar.of_char '*') -> comment acc start 0 | ((`Uchar _ | `End), _) as charloc -> errors := Unexpected_character (start, "/") :: !errors ; back charloc ; skip acc) | Some _ | None -> let byte = Uutf.decoder_byte_count decoder in let s = String.sub source start.byte (byte - start.byte) in errors := Unexpected_character (start, s) :: !errors ; skip acc) and base acc start = match next () with | (`Uchar c, stop) as charloc -> ( match uchar_to_char c with | Some '0' .. '9' -> integer acc start | Some 'x' -> bytes acc start | Some ('a' .. 'w' | 'y' | 'z' | 'A' .. 'Z') -> errors := Missing_break_after_number stop :: !errors ; back charloc ; skip (tok start stop (Int "0") :: acc) | Some _ | None -> back charloc ; skip (tok start stop (Int "0") :: acc)) | (_, stop) as other -> back other ; skip (tok start stop (Int "0") :: acc) and integer acc start = let tok stop = let value = String.sub source start.byte (stop.byte - start.byte) in tok start stop (Int value) in match next () with | (`Uchar c, stop) as charloc -> ( let missing_break () = errors := Missing_break_after_number stop :: !errors ; back charloc ; skip (tok stop :: acc) in match Uchar.to_char c with | '0' .. '9' -> integer acc start | 'a' .. 'z' | 'A' .. 'Z' -> missing_break () | _ -> back charloc ; skip (tok stop :: acc)) | (`End, stop) as other -> back other ; skip (tok stop :: acc) and bytes acc start = let tok stop = let value = String.sub source start.byte (stop.byte - start.byte) in tok start stop (Bytes value) in match next () with | (`Uchar c, stop) as charloc -> ( let missing_break () = errors := Missing_break_after_number stop :: !errors ; back charloc ; skip (tok stop :: acc) in match Uchar.to_char c with | '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> bytes acc start | 'g' .. 'z' | 'G' .. 'Z' -> missing_break () | _ -> back charloc ; skip (tok stop :: acc)) | (`End, stop) as other -> back other ; skip (tok stop :: acc) and string acc sacc start = let tok () = tok start (here ()) (String (String.concat "" (List.rev sacc))) in match next () with | `End, stop -> errors := Unterminated_string {start; stop} :: !errors ; skip (tok () :: acc) | `Uchar c, stop -> ( match uchar_to_char c with | Some '"' -> skip (tok () :: acc) | Some ('\n' | '\r') -> errors := Unterminated_string {start; stop} :: !errors ; skip (tok () :: acc) | Some '\\' -> ( match next () with | `End, stop -> errors := Unterminated_string {start; stop} :: !errors ; skip (tok () :: acc) | `Uchar c, loc -> ( match uchar_to_char c with | Some '"' -> string acc ("\"" :: sacc) start | Some 'r' -> string acc ("\r" :: sacc) start | Some 'n' -> string acc ("\n" :: sacc) start | Some 't' -> string acc ("\t" :: sacc) start | Some 'b' -> string acc ("\b" :: sacc) start | Some '\\' -> string acc ("\\" :: sacc) start | Some _ | None -> let byte = Uutf.decoder_byte_count decoder in let s = String.sub source loc.byte (byte - loc.byte) in errors := Undefined_escape_sequence (loc, s) :: !errors ; string acc sacc start)) | Some _ | None -> let byte = Uutf.decoder_byte_count decoder in let s = String.sub source stop.byte (byte - stop.byte) in string acc (s :: sacc) start) and generic_ident allow_char acc start (ret : string -> point -> token_value) = let tok stop = let name = String.sub source start.byte (stop.byte - start.byte) in tok start stop (ret name stop) in match next () with | (`Uchar c, stop) as charloc -> if allow_char c then generic_ident allow_char acc start ret else ( back charloc ; skip (tok stop :: acc)) | (_, stop) as other -> back other ; skip (tok stop :: acc) and ident acc start ret = generic_ident allowed_ident_char acc start ret and annot acc start ret = generic_ident allowed_annot_char acc start ret and comment acc start lvl = match next () with | `End, stop -> errors := Unterminated_comment {start; stop} :: !errors ; let text = String.sub source start.byte (stop.byte - start.byte) in skip (tok start stop (Comment text) :: acc) | `Uchar c, _ -> ( match uchar_to_char c with | Some '*' -> ( match next () with | `Uchar c, _ when Uchar.equal c (Uchar.of_char '/') -> if lvl = 0 then let stop = here () in let text = String.sub source start.byte (stop.byte - start.byte) in skip (tok start stop (Comment text) :: acc) else comment acc start (lvl - 1) | other -> back other ; comment acc start lvl) | Some '/' -> ( match next () with | `Uchar c, _ when Uchar.equal c (Uchar.of_char '*') -> comment acc start (lvl + 1) | other -> back other ; comment acc start lvl) | Some _ | None -> comment acc start lvl) and eol_comment acc start = let tok stop = let text = String.sub source start.byte (stop.byte - start.byte) in tok start stop (Eol_comment text) in match next () with | `Uchar c, stop -> ( match uchar_to_char c with | Some '\n' -> skip (tok stop :: acc) | Some _ | None -> eol_comment acc start) | (_, stop) as other -> back other ; skip (tok stop :: acc) in let tokens = skip [] in (tokens, List.rev !errors) type node = (location, string) Micheline.node (* Beginning of a sequence of consecutive primitives *) let min_point : node list -> point = function | [] -> point_zero | Int ({start; _}, _) :: _ | String ({start; _}, _) :: _ | Bytes ({start; _}, _) :: _ | Prim ({start; _}, _, _, _) :: _ | Seq ({start; _}, _) :: _ -> start (* End of a sequence of consecutive primitives *) let rec max_point : node list -> point = function | [] -> point_zero | _ :: (_ :: _ as rest) -> max_point rest | [Int ({stop; _}, _)] | [String ({stop; _}, _)] | [Bytes ({stop; _}, _)] | [Prim ({stop; _}, _, _, _)] | [Seq ({stop; _}, _)] -> stop (* An item in the parser's state stack. Not every value of type [mode list] is a valid parsing context. It must respect the following additional invariants. - a state stack always ends in [Toplevel _], - [Toplevel _] does not appear anywhere else, - [Unwrapped _] cannot appear directly on top of [Wrapped _], - [Wrapped _] cannot appear directly on top of [Sequence _], - [Wrapped _] cannot appear directly on top of [Sequence _]. *) type mode = | Toplevel of node list | Expression of node option | Sequence of token * node list | Unwrapped of location * string * node list * string list | Wrapped of token * string * node list * string list (* Enter a new parsing state. *) let push_mode mode stack = mode :: stack (* Leave a parsing state. *) let pop_mode = function [] -> assert false | _ :: rest -> rest (* Usually after a [pop_mode], jump back into the previous parsing state, injecting the current reduction (insert the just parsed item of a sequence or argument of a primitive application). *) let fill_mode result = function | [] -> assert false | Expression _ :: _ :: _ -> assert false | [Expression (Some _)] -> assert false | Toplevel _ :: _ :: _ -> assert false | [Expression None] -> [Expression (Some result)] | [Toplevel exprs] -> [Toplevel (result :: exprs)] | Sequence (token, exprs) :: rest -> Sequence (token, result :: exprs) :: rest | Wrapped (token, name, exprs, annot) :: rest -> Wrapped (token, name, result :: exprs, annot) :: rest | Unwrapped (start, name, exprs, annot) :: rest -> Unwrapped (start, name, result :: exprs, annot) :: rest type error += Unclosed of token type error += Unexpected of token type error += Extra of token type error += Misaligned of node type error += Empty let rec annots = function | {token = Annot annot; _} :: rest -> let annots, rest = annots rest in (annot :: annots, rest) | rest -> ([], rest) let rec parse ?(check = true) errors tokens stack = (* Two steps: - 1. parse without checking indentation [parse] - 2. check indentation [check] (inlined in 1) *) match (stack, tokens) with (* Start by preventing all absurd cases, so now the pattern matching exhaustivity can tell us that we treater all possible tokens for all possible valid states. *) | [], _ | [Wrapped _], _ | [Unwrapped _], _ | Unwrapped _ :: Unwrapped _ :: _, _ | Unwrapped _ :: Wrapped _ :: _, _ | Toplevel _ :: _ :: _, _ | Expression _ :: _ :: _, _ -> assert false (* Return *) | Expression (Some result) :: _, [] -> ([result], List.rev errors) | Expression (Some _) :: _, token :: rem -> let errors = Unexpected token :: errors in parse ~check errors rem (* skip *) stack | Expression None :: _, [] -> let errors = Empty :: errors in let ghost = {start = point_zero; stop = point_zero} in ([Seq (ghost, [])], List.rev errors) | [Toplevel [(Seq (_, exprs) as expr)]], [] -> let errors = if check then do_check ~toplevel:false errors expr else errors in (exprs, List.rev errors) | [Toplevel exprs], [] -> let exprs = List.rev exprs in let loc = {start = min_point exprs; stop = max_point exprs} in let expr = Seq (loc, exprs) in let errors = if check then do_check ~toplevel:true errors expr else errors in (exprs, List.rev errors) (* Ignore comments *) | _, {token = Eol_comment _ | Comment _; _} :: rest -> parse ~check errors rest stack | ( (Expression None | Sequence _ | Toplevel _) :: _, ({token = Int _ | String _ | Bytes _; _} as token) :: {token = Eol_comment _ | Comment _; _} :: rest ) | ( (Wrapped _ | Unwrapped _) :: _, ({token = Open_paren; _} as token) :: {token = Eol_comment _ | Comment _; _} :: rest ) -> parse ~check errors (token :: rest) stack (* Erroneous states *) | ( (Wrapped _ | Unwrapped _) :: _, ({token = Open_paren; _} as token) :: {token = Open_paren | Open_brace; _} :: rem ) | ( Unwrapped _ :: Expression _ :: _, ({token = Semi | Close_brace | Close_paren; _} as token) :: rem ) | ( Expression None :: _, ({token = Semi | Close_brace | Close_paren | Open_paren; _} as token) :: rem ) -> let errors = Unexpected token :: errors in parse ~check errors rem (* skip *) stack | ( (Sequence _ | Toplevel _) :: _, ({token = Semi; _} as valid) :: ({token = Semi; _} as token) :: rem ) -> let errors = Extra token :: errors in parse ~check errors (* skip *) (valid :: rem) stack | ( (Wrapped _ | Unwrapped _) :: _, {token = Open_paren; _} :: ({token = Int _ | String _ | Bytes _ | Annot _ | Close_paren; _} as token) :: rem ) | ( (Expression None | Sequence _ | Toplevel _) :: _, {token = Int _ | String _ | Bytes _; _} :: ({ token = ( Ident _ | Int _ | String _ | Bytes _ | Annot _ | Close_paren | Open_paren | Open_brace ); _; } as token) :: rem ) | ( Unwrapped (_, _, _, _) :: Toplevel _ :: _, ({token = Close_brace; _} as token) :: rem ) | Unwrapped (_, _, _, _) :: _, ({token = Close_paren; _} as token) :: rem | [Toplevel _], ({token = Close_paren; _} as token) :: rem | [Toplevel _], ({token = Open_paren; _} as token) :: rem | [Toplevel _], ({token = Close_brace; _} as token) :: rem | Sequence _ :: _, ({token = Open_paren; _} as token) :: rem | Sequence _ :: _, ({token = Close_paren; _} as token) :: rem | ( (Wrapped _ | Unwrapped _) :: _, ({token = Open_paren; _} as token) :: (({token = Close_brace | Semi; _} :: _ | []) as rem) ) | _, ({token = Annot _; _} as token) :: rem -> let errors = Unexpected token :: errors in parse ~check errors rem (* skip *) stack | Wrapped (token, _, _, _) :: _, ([] | {token = Close_brace | Semi; _} :: _) -> let errors = Unclosed token :: errors in let fake = {token with token = Close_paren} in let tokens = (* insert *) fake :: tokens in parse ~check errors tokens stack | (Sequence (token, _) :: _ | Unwrapped _ :: Sequence (token, _) :: _), [] -> let errors = Unclosed token :: errors in let fake = {token with token = Close_brace} in let tokens = (* insert *) fake :: tokens in parse ~check errors tokens stack (* Valid states *) | ( (Toplevel _ | Sequence (_, _)) :: _, {token = Ident name; loc} :: ({token = Annot _; _} :: _ as rest) ) -> let annots, rest = annots rest in let mode = Unwrapped (loc, name, [], annots) in parse ~check errors rest (push_mode mode stack) | ( (Expression None | Toplevel _ | Sequence (_, _)) :: _, {token = Ident name; loc} :: rest ) -> let mode = Unwrapped (loc, name, [], []) in parse ~check errors rest (push_mode mode stack) | (Unwrapped _ | Wrapped _) :: _, {token = Int value; loc} :: rest | ( (Expression None | Sequence _ | Toplevel _) :: _, {token = Int value; loc} :: (([] | {token = Semi | Close_brace; _} :: _) as rest) ) -> let expr : node = Int (loc, Z.of_string value) in let errors = if check then do_check ~toplevel:false errors expr else errors in parse ~check errors rest (fill_mode expr stack) | (Unwrapped _ | Wrapped _) :: _, {token = String contents; loc} :: rest | ( (Expression None | Sequence _ | Toplevel _) :: _, {token = String contents; loc} :: (([] | {token = Semi | Close_brace; _} :: _) as rest) ) -> let expr : node = String (loc, contents) in let errors = if check then do_check ~toplevel:false errors expr else errors in parse ~check errors rest (fill_mode expr stack) | (Unwrapped _ | Wrapped _) :: _, {token = Bytes contents; loc} :: rest | ( (Expression None | Sequence _ | Toplevel _) :: _, {token = Bytes contents; loc} :: (([] | {token = Semi | Close_brace; _} :: _) as rest) ) -> let errors, bytes = match Hex.to_bytes (`Hex (String.sub contents 2 (String.length contents - 2))) with | None -> (Invalid_hex_bytes loc :: errors, Bytes.empty) | Some bytes -> (errors, bytes) in let expr : node = Bytes (loc, bytes) in let errors = if check then do_check ~toplevel:false errors expr else errors in parse ~check errors rest (fill_mode expr stack) | ( Sequence ({loc = {start; _}; _}, exprs) :: _, {token = Close_brace; loc = {stop; _}} :: rest ) -> let exprs = List.rev exprs in let expr = Micheline.Seq ({start; stop}, exprs) in let errors = if check then do_check ~toplevel:false errors expr else errors in parse ~check errors rest (fill_mode expr (pop_mode stack)) | (Sequence _ | Toplevel _) :: _, {token = Semi; _} :: rest -> parse ~check errors rest stack | ( Unwrapped ({start; stop}, name, exprs, annot) :: Expression _ :: _, ([] as rest) ) | ( Unwrapped ({start; stop}, name, exprs, annot) :: Toplevel _ :: _, (({token = Semi; _} :: _ | []) as rest) ) | ( Unwrapped ({start; stop}, name, exprs, annot) :: Sequence _ :: _, ({token = Close_brace | Semi; _} :: _ as rest) ) | ( Wrapped ({loc = {start; stop}; _}, name, exprs, annot) :: _, {token = Close_paren; _} :: rest ) -> let exprs = List.rev exprs in let stop = if exprs = [] then stop else max_point exprs in let expr = Micheline.Prim ({start; stop}, name, exprs, annot) in let errors = if check then do_check ~toplevel:false errors expr else errors in parse ~check errors rest (fill_mode expr (pop_mode stack)) | ( (Wrapped _ | Unwrapped _) :: _, ({token = Open_paren; _} as token) :: {token = Ident name; _} :: ({token = Annot _; _} :: _ as rest) ) -> let annots, rest = annots rest in let mode = Wrapped (token, name, [], annots) in parse ~check errors rest (push_mode mode stack) | ( (Wrapped _ | Unwrapped _) :: _, ({token = Open_paren; _} as token) :: {token = Ident name; _} :: rest ) -> let mode = Wrapped (token, name, [], []) in parse ~check errors rest (push_mode mode stack) | (Wrapped _ | Unwrapped _) :: _, {token = Ident name; loc} :: rest -> let expr = Micheline.Prim (loc, name, [], []) in let errors = if check then do_check ~toplevel:false errors expr else errors in parse ~check errors rest (fill_mode expr stack) | ( (Wrapped _ | Unwrapped _ | Toplevel _ | Sequence _ | Expression None) :: _, ({token = Open_brace; _} as token) :: rest ) -> let mode = Sequence (token, []) in parse ~check errors rest (push_mode mode stack) (* indentation checker *) and do_check ?(toplevel = false) errors = function | Seq ({start; stop}, []) as expr -> if start.column >= stop.column then Misaligned expr :: errors else errors | ( Prim ({start; stop}, _, first :: rest, _) | Seq ({start; stop}, first :: rest) ) as expr -> let {column = first_column; line = first_line; _} = min_point [first] in if start.column >= stop.column then Misaligned expr :: errors else if (not toplevel) && start.column >= first_column then Misaligned expr :: errors else (* In a sequence or in the arguments of a primitive, we require all items to be aligned, but we relax the rule to allow consecutive items to be written on the same line. *) let rec in_line_or_aligned prev_start_line errors = function | [] -> errors | expr :: rest -> let {column; line = start_line; _} = min_point [expr] in let {line = stop_line; _} = max_point [expr] in let errors = if stop_line <> prev_start_line && column <> first_column then Misaligned expr :: errors else errors in in_line_or_aligned start_line errors rest in in_line_or_aligned first_line errors rest | Prim (_, _, [], _) | String _ | Int _ | Bytes _ -> errors let parse_expression ?check tokens = let result = match tokens with | ({token = Open_paren; _} as token) :: {token = Ident name; _} :: {token = Annot annot; _} :: rest -> let annots, rest = annots rest in let mode = Wrapped (token, name, [], annot :: annots) in parse ?check [] rest [mode; Expression None] | ({token = Open_paren; _} as token) :: {token = Ident name; _} :: rest -> let mode = Wrapped (token, name, [], []) in parse ?check [] rest [mode; Expression None] | _ -> parse ?check [] tokens [Expression None] in match result with [single], errors -> (single, errors) | _ -> assert false let parse_toplevel ?check tokens = parse ?check [] tokens [Toplevel []] let print_point ppf {line; column; _} = Format.fprintf ppf "At line %d character %d" line column let print_token_kind ppf = function | Open_paren | Close_paren -> Format.fprintf ppf "parenthesis" | Open_brace | Close_brace -> Format.fprintf ppf "curly brace" | String _ -> Format.fprintf ppf "string constant" | Bytes _ -> Format.fprintf ppf "bytes constant" | Int _ -> Format.fprintf ppf "integer constant" | Ident _ -> Format.fprintf ppf "identifier" | Annot _ -> Format.fprintf ppf "annotation" | Comment _ | Eol_comment _ -> Format.fprintf ppf "comment" | Semi -> Format.fprintf ppf "semi colon" let print_location ppf loc = if loc.start.line = loc.stop.line then if loc.start.column = loc.stop.column then Format.fprintf ppf "At line %d character %d" loc.start.line loc.start.column else Format.fprintf ppf "At line %d characters %d to %d" loc.start.line loc.start.column loc.stop.column else Format.fprintf ppf "From line %d character %d to line %d character %d" loc.start.line loc.start.column loc.stop.line loc.stop.column let no_parsing_error (ast, errors) = match errors with [] -> Ok ast | errors -> Error errors let () = register_error_kind `Permanent ~id:"micheline.parse_error.invalid_utf8_sequence" ~title:"Micheline parser error: invalid UTF-8 sequence" ~description: "While parsing a piece of Micheline source, a sequence of bytes that is \ not valid UTF-8 was encountered." ~pp:(fun ppf (point, str) -> Format.fprintf ppf "%a, invalid UTF-8 sequence %S" print_point point str) Data_encoding.(obj2 (req "point" point_encoding) (req "sequence" string)) (function | Invalid_utf8_sequence (point, str) -> Some (point, str) | _ -> None) (fun (point, str) -> Invalid_utf8_sequence (point, str)) ; register_error_kind `Permanent ~id:"micheline.parse_error.unexpected_character" ~title:"Micheline parser error: unexpected character" ~description: "While parsing a piece of Micheline source, an unexpected character was \ encountered." ~pp:(fun ppf (point, str) -> Format.fprintf ppf "%a, unexpected character %s" print_point point str) Data_encoding.(obj2 (req "point" point_encoding) (req "character" string)) (function | Unexpected_character (point, str) -> Some (point, str) | _ -> None) (fun (point, str) -> Unexpected_character (point, str)) ; register_error_kind `Permanent ~id:"micheline.parse_error.undefined_escape_sequence" ~title:"Micheline parser error: undefined escape sequence" ~description: "While parsing a piece of Micheline source, an unexpected escape \ sequence was encountered in a string." ~pp:(fun ppf (point, str) -> Format.fprintf ppf "%a, undefined escape sequence \"%s\"" print_point point str) Data_encoding.(obj2 (req "point" point_encoding) (req "sequence" string)) (function | Undefined_escape_sequence (point, str) -> Some (point, str) | _ -> None) (fun (point, str) -> Undefined_escape_sequence (point, str)) ; register_error_kind `Permanent ~id:"micheline.parse_error.missing_break_after_number" ~title:"Micheline parser error: missing break after number" ~description: "While parsing a piece of Micheline source, a number was not visually \ separated from its follower token, leading to misreadability." ~pp:(fun ppf point -> Format.fprintf ppf "%a, missing break after number" print_point point) Data_encoding.(obj1 (req "point" point_encoding)) (function Missing_break_after_number point -> Some point | _ -> None) (fun point -> Missing_break_after_number point) ; register_error_kind `Permanent ~id:"micheline.parse_error.unterminated_string" ~title:"Micheline parser error: unterminated string" ~description: "While parsing a piece of Micheline source, a string was not terminated." ~pp:(fun ppf loc -> Format.fprintf ppf "%a, unterminated string" print_location loc) Data_encoding.(obj1 (req "location" location_encoding)) (function Unterminated_string loc -> Some loc | _ -> None) (fun loc -> Unterminated_string loc) ; register_error_kind `Permanent ~id:"micheline.parse_error.unterminated_integer" ~title:"Micheline parser error: unterminated integer" ~description: "While parsing a piece of Micheline source, an integer was not \ terminated." ~pp:(fun ppf loc -> Format.fprintf ppf "%a, unterminated integer" print_location loc) Data_encoding.(obj1 (req "location" location_encoding)) (function Unterminated_integer loc -> Some loc | _ -> None) (fun loc -> Unterminated_integer loc) ; register_error_kind `Permanent ~id:"micheline.parse_error.invalid_hex_bytes" ~title:"Micheline parser error: invalid hex bytes" ~description: "While parsing a piece of Micheline source, a byte sequence (0x...) was \ not valid as a hex byte." ~pp:(fun ppf loc -> Format.fprintf ppf "%a, invalid hex bytes" print_location loc) Data_encoding.(obj1 (req "location" location_encoding)) (function Invalid_hex_bytes loc -> Some loc | _ -> None) (fun loc -> Invalid_hex_bytes loc) ; register_error_kind `Permanent ~id:"micheline.parse_error.unterminated_comment" ~title:"Micheline parser error: unterminated comment" ~description: "While parsing a piece of Micheline source, a commentX was not \ terminated." ~pp:(fun ppf loc -> Format.fprintf ppf "%a, unterminated comment" print_location loc) Data_encoding.(obj1 (req "location" location_encoding)) (function Unterminated_comment loc -> Some loc | _ -> None) (fun loc -> Unterminated_comment loc) ; register_error_kind `Permanent ~id:"micheline.parse_error.annotation_exceeds_max_length" ~title:"Micheline parser error: annotation exceeds max length" ~description: (Format.sprintf "While parsing a piece of Micheline source, an annotation exceeded \ the maximum length (%d)." max_annot_length) ~pp:(fun ppf loc -> Format.fprintf ppf "%a, annotation exceeded maximum length (%d chars)" print_location loc max_annot_length) Data_encoding.(obj1 (req "location" location_encoding)) (function Annotation_length loc -> Some loc | _ -> None) (fun loc -> Annotation_length loc) ; register_error_kind `Permanent ~id:"micheline.parse_error.unclosed_token" ~title:"Micheline parser error: unclosed token" ~description: "While parsing a piece of Micheline source, a parenthesis or a brace was \ unclosed." ~pp:(fun ppf (loc, token) -> Format.fprintf ppf "%a, unclosed %a" print_location loc print_token_kind token) Data_encoding.( obj2 (req "location" location_encoding) (req "token" token_value_encoding)) (function Unclosed {loc; token} -> Some (loc, token) | _ -> None) (fun (loc, token) -> Unclosed {loc; token}) ; register_error_kind `Permanent ~id:"micheline.parse_error.unexpected_token" ~title:"Micheline parser error: unexpected token" ~description: "While parsing a piece of Micheline source, an unexpected token was \ encountered." ~pp:(fun ppf (loc, token) -> Format.fprintf ppf "%a, unexpected %a" print_location loc print_token_kind token) Data_encoding.( obj2 (req "location" location_encoding) (req "token" token_value_encoding)) (function Unexpected {loc; token} -> Some (loc, token) | _ -> None) (fun (loc, token) -> Unexpected {loc; token}) ; register_error_kind `Permanent ~id:"micheline.parse_error.extra_token" ~title:"Micheline parser error: extra token" ~description: "While parsing a piece of Micheline source, an extra semi colon or \ parenthesis was encountered." ~pp:(fun ppf (loc, token) -> Format.fprintf ppf "%a, extra %a" print_location loc print_token_kind token) Data_encoding.( obj2 (req "location" location_encoding) (req "token" token_value_encoding)) (function Extra {loc; token} -> Some (loc, token) | _ -> None) (fun (loc, token) -> Extra {loc; token}) ; (* [Misaligned] is registered in the encoding module to break a dependency cycle *) register_error_kind `Permanent ~id:"micheline.parse_error.empty_expression" ~title:"Micheline parser error: empty_expression" ~description: "Tried to interpret an empty piece or Micheline source as a single \ expression." ~pp:(fun ppf () -> Format.fprintf ppf "empty expression") Data_encoding.empty (function Empty -> Some () | _ -> None) (fun () -> Empty) (* helper functions for the encoding *) let check_annot s = String.length s <= max_annot_length && match tokenize s with | [{token = Annot s'; _}], [] (* no errors *) -> String.equal s s' | _ -> false
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)
p2p_protocol.ml
module Events = P2p_events.P2p_protocol type ('msg, 'peer, 'conn) config = { swap_linger : Time.System.Span.t; pool : ('msg, 'peer, 'conn) P2p_pool.t; log : P2p_connection.P2p_event.t -> unit; connect : P2p_point.Id.t -> ('msg, 'peer, 'conn) P2p_conn.t tzresult Lwt.t; mutable latest_accepted_swap : Time.System.t; mutable latest_successful_swap : Time.System.t; } open P2p_answerer let message conn _request size msg = Lwt_pipe.Maybe_bounded.push conn.messages (size, msg) module Private_answerer = struct let advertise conn _request _points = Events.(emit private_node_new_peers) conn.peer_id let bootstrap conn _request = Events.(emit private_node_peers_request) conn.peer_id >>= fun () -> return_unit let swap_request conn _request _new_point _peer = Events.(emit private_node_swap_request) conn.peer_id let swap_ack conn _request _point _peer_id = Events.(emit private_node_swap_ack) conn.peer_id let create conn = P2p_answerer. { message = message conn; advertise = advertise conn; bootstrap = bootstrap conn; swap_request = swap_request conn; swap_ack = swap_ack conn; } end module Default_answerer = struct open P2p_connection.P2p_event let advertise config conn _request points = let log = config.log in let source_peer_id = conn.peer_id in log (Advertise_received {source = source_peer_id}) ; P2p_pool.register_list_of_new_points ~medium:"advertise" ~source:conn.peer_id config.pool points let bootstrap config conn _request_info = let log = config.log in let source_peer_id = conn.peer_id in log (Bootstrap_received {source = source_peer_id}) ; if conn.is_private then Events.(emit private_node_request) conn.peer_id >>= fun () -> return_unit else P2p_pool.list_known_points ~ignore_private:true config.pool >>= function | [] -> return_unit | points -> ( match conn.write_advertise points with | Ok true -> log (Advertise_sent {source = source_peer_id}) ; return_unit | Ok false -> (* if not sent then ?? TODO count dropped message ?? *) return_unit | Error err -> Events.(emit advertise_sending_failed) (source_peer_id, err) >>= fun () -> Lwt.return (Error err)) let swap t pool source_peer_id ~connect current_peer_id new_point = t.latest_accepted_swap <- Systime_os.now () ; connect new_point >>= function | Ok _new_conn -> ( t.latest_successful_swap <- Systime_os.now () ; t.log (Swap_success {source = source_peer_id}) ; Events.(emit swap_succeeded) new_point >>= fun () -> match P2p_pool.Connection.find_by_peer_id pool current_peer_id with | None -> Lwt.return_unit | Some conn -> P2p_conn.disconnect conn) | Error err -> ( t.latest_accepted_swap <- t.latest_successful_swap ; t.log (Swap_failure {source = source_peer_id}) ; match err with | [Timeout] -> Events.(emit swap_interrupted) (new_point, err) | _ -> Events.(emit swap_failed) (new_point, err)) let swap_ack config conn request new_point _peer = let source_peer_id = conn.peer_id in let pool = config.pool in let connect = config.connect in let log = config.log in log (Swap_ack_received {source = source_peer_id}) ; Events.(emit swap_ack_received) source_peer_id >>= fun () -> match request.last_sent_swap_request with | None -> Lwt.return_unit (* ignore *) | Some (_time, proposed_peer_id) -> ( match P2p_pool.Connection.find_by_peer_id pool proposed_peer_id with | None -> swap config pool source_peer_id ~connect proposed_peer_id new_point >>= fun () -> Lwt.return_unit | Some _ -> Lwt.return_unit) let swap_request config conn _request new_point _peer = let source_peer_id = conn.peer_id in let pool = config.pool in let swap_linger = config.swap_linger in let connect = config.connect in let log = config.log in log (Swap_request_received {source = source_peer_id}) ; Events.(emit swap_request_received) source_peer_id >>= fun () -> (* Ignore if already connected to peer or already swapped less than <swap_linger> ago. *) let span_since_last_swap = Ptime.diff (Systime_os.now ()) (Time.System.max config.latest_successful_swap config.latest_accepted_swap) in let new_point_info = P2p_pool.register_point pool new_point in if Ptime.Span.compare span_since_last_swap swap_linger < 0 || not (P2p_point_state.is_disconnected new_point_info) then ( log (Swap_request_ignored {source = source_peer_id}) ; Events.(emit swap_request_ignored) source_peer_id) else match P2p_pool.Connection.random_addr pool ~no_private:true with | None -> Events.(emit no_swap_candidate) source_peer_id | Some (proposed_point, proposed_peer_id) -> ( match conn.write_swap_ack proposed_point proposed_peer_id with | Ok true -> log (Swap_ack_sent {source = source_peer_id}) ; swap config pool source_peer_id ~connect proposed_peer_id new_point >>= fun () -> Lwt.return_unit | Ok false -> Lwt.return_unit | Error _ -> Lwt.return_unit) let create config conn = P2p_answerer. { message = message conn; advertise = advertise config conn; bootstrap = bootstrap config conn; swap_request = swap_request config conn; swap_ack = swap_ack config conn; } end let create_default = Default_answerer.create let create_private () = Private_answerer.create
(*****************************************************************************) (* *) (* Open Source License *) (* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *) (* 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. *) (* *) (*****************************************************************************)
michelson_v1_error_reporter.mli
val report_errors : details:bool -> show_source:bool -> ?parsed:Michelson_v1_parser.parsed -> Format.formatter -> Error_monad.error list -> unit
(*****************************************************************************) (* *) (* 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. *) (* *) (*****************************************************************************)